Sync plugins from current page

Signed-off-by: Adrian Nöthlich <git@promasu.tech>
This commit is contained in:
2019-09-11 19:08:46 +02:00
parent 85d41e4216
commit 8515ff9587
1847 changed files with 505469 additions and 0 deletions

View File

@@ -0,0 +1,60 @@
# Redirection
[![Build Status](https://travis-ci.org/johngodley/redirection.svg?branch=master)](https://travis-ci.org/johngodley/redirection)
Redirection is a WordPress plugin to manage 301 redirections, keep track of 404 errors, and generally tidy up any loose ends your site may have. This is particularly useful if you are migrating pages from an old website, or are changing the directory of your WordPress installation.
Note: this is the current 'trunk' version of Redirection. It may be newer than what is in the WordPress.org plugin repository, and should be considered experimental.
## Installation
Redirection can be installed by visiting the WordPress.org plugin page:
https://wordpress.org/plugins/redirection/
## Customisation
### Request Information
The following WordPress filters are available for customisation of a server requests:
- `redirection_request_url` - The request URL
- `redirection_request_agent` - The request user agent
- `redirection_request_referrer` - The request referrer
- `redirection_request_ip` - The request IP address
### Logging
The following WordPress filters are available for customisation of logged data:
- `redirection_404_data` - Data to be inserted into the 404 table
- `redirection_log_data` - Data to be inserted into the redirect log table
### Redirect source and target
- `redirection_url_source` - The original URL used before matching a request. Return false to stop any redirection
- `redirection_url_target` - The target URL after a request has been matched (and after any regular expression captures have been replaced). Return false to stop any redirection
### Dynamic URL data
The following special words can be inserted into a target URL:
- `%userid%` - Insert user's ID
- `%userlogin%` - Insert user's login name
- `%userurl%` - Insert user's custom URL
### Management
- `redirection_permalink_changed` - return boolean if a post's permalink has changed
- `redirection_remove_existing` - fired when a post changes permalink and we need to clear existing redirects that might affect it
Additionally, if the target URL is a number without any slashes then Redirection will treat it as a post ID and redirect to the full URL for that post.
## Support
Please raise any bug reports or enhancement requests here. Pull requests are always welcome.
You can find a more detailed description of the plugin on the [Redirection home page](http://urbangiraffe.com/plugins/redirection/)
Translations can be added here:
https://translate.wordpress.org/projects/wp-plugins/redirection

View File

@@ -0,0 +1,43 @@
<?php
class Error_Action extends Red_Action {
function process_before( $code, $target ) {
$this->code = $code;
wp_reset_query();
set_query_var( 'is_404', true );
add_filter( 'template_include', [ $this, 'template_include' ] );
add_filter( 'pre_handle_404', [ $this, 'pre_handle_404' ] );
add_action( 'wp', [ $this, 'wp' ] );
return true;
}
public function wp() {
status_header( $this->code );
nocache_headers();
global $wp_version;
if ( version_compare( $wp_version, '5.1', '<' ) ) {
header( 'X-Redirect-Agent: redirection' );
}
}
public function pre_handle_404() {
global $wp_query;
// Page comments plugin interferes with this
$wp_query->posts = [];
return false;
}
public function template_include() {
return get_404_template();
}
public function needs_target() {
return false;
}
}

View File

@@ -0,0 +1,11 @@
<?php
class Nothing_Action extends Red_Action {
public function process_before( $code, $target ) {
return apply_filters( 'redirection_do_nothing', false, $target );
}
public function needs_target() {
return false;
}
}

View File

@@ -0,0 +1,63 @@
<?php
class Pass_Action extends Red_Action {
public function process_external( $url ) {
echo @wp_remote_fopen( $url );
}
/**
* This is deprecated and will be removed in a future version
*/
public function process_file( $url ) {
$parts = explode( '?', substr( $url, 7 ) );
if ( count( $parts ) > 1 ) {
// Put parameters into the environment
$args = explode( '&', $parts[1] );
if ( count( $args ) > 0 ) {
foreach ( $args as $arg ) {
$tmp = explode( '=', $arg );
if ( count( $tmp ) === 1 ) {
$_GET[ $arg ] = '';
} else {
$_GET[ $tmp[0] ] = $tmp[1];
}
}
}
}
@include $parts[0];
}
public function process_internal( $target ) {
// Another URL on the server
$_SERVER['REQUEST_URI'] = $target;
if ( strpos( $target, '?' ) ) {
$_SERVER['QUERY_STRING'] = substr( $target, strpos( $target, '?' ) + 1 );
parse_str( $_SERVER['QUERY_STRING'], $_GET );
}
return true;
}
public function is_external( $target ) {
return substr( $target, 0, 7 ) === 'http://' || substr( $target, 0, 8 ) === 'https://';
}
public function process_before( $code, $target ) {
// External target
if ( $this->is_external( $target ) ) {
$this->process_external( $target );
exit();
}
return $this->process_internal( $target );
}
public function needs_target() {
return true;
}
}

View File

@@ -0,0 +1,21 @@
<?php
include_once dirname( __FILE__ ) . '/url.php';
class Random_Action extends Url_Action {
public function process_before( $code, $target ) {
// Pick a random WordPress page
global $wpdb;
$id = $wpdb->get_var( "SELECT ID FROM {$wpdb->prefix}posts WHERE post_status='publish' AND post_password='' AND post_type='post' ORDER BY RAND() LIMIT 0,1" );
return str_replace( get_bloginfo( 'url' ), '', get_permalink( $id ) );
}
public function process_after( $code, $target ) {
$this->redirect_to( $code, $target );
}
public function needs_target() {
return true;
}
}

View File

@@ -0,0 +1,31 @@
<?php
class Url_Action extends Red_Action {
protected function redirect_to( $code, $target ) {
add_filter( 'x_redirect_by', [ $this, 'x_redirect_by' ] );
$redirect = wp_redirect( $target, $code );
if ( $redirect ) {
global $wp_version;
if ( version_compare( $wp_version, '5.1', '<' ) ) {
header( 'X-Redirect-Agent: redirection' );
}
die();
}
}
public function process_after( $code, $target ) {
$this->redirect_to( $code, $target );
}
public function needs_target() {
return true;
}
public function x_redirect_by() {
return 'redirection';
}
}

View File

@@ -0,0 +1,112 @@
<?php
/**
* @api {get} /redirection/v1/404 Get 404 logs
* @apiDescription Get 404 logs
* @apiGroup 404
*
* @apiParam {string} groupBy Group by 'ip' or 'url'
* @apiParam {string} orderby
* @apiParam {string} direction
* @apiParam {string} filter
* @apiParam {string} per_page
* @apiParam {string} page
*/
/**
* @api {post} /redirection/v1/404 Delete 404 logs
* @apiDescription Delete 404 logs either by ID or filter or group
* @apiGroup 404
*
* @apiParam {string} items Array of log IDs
* @apiParam {string} filter
* @apiParam {string} filterBy
* @apiParam {string} groupBy Group by 'ip' or 'url'
*/
/**
* @api {post} /redirection/v1/bulk/404/delete Bulk actions on 404s
* @apiDescription Delete 404 logs either by ID
* @apiGroup 404
*/
class Redirection_Api_404 extends Redirection_Api_Filter_Route {
public function __construct( $namespace ) {
$filters = array( 'ip', 'url', 'url-exact', 'total' );
register_rest_route( $namespace, '/404', array(
'args' => $this->get_filter_args( $filters, $filters ),
$this->get_route( WP_REST_Server::READABLE, 'route_404' ),
$this->get_route( WP_REST_Server::EDITABLE, 'route_delete_all' ),
) );
$this->register_bulk( $namespace, '/bulk/404/(?P<bulk>delete)', $filters, $filters, 'route_bulk' );
}
public function route_404( WP_REST_Request $request ) {
return $this->get_404( $request->get_params() );
}
public function route_bulk( WP_REST_Request $request ) {
$params = $request->get_params();
$items = explode( ',', $request['items'] );
if ( is_array( $items ) ) {
foreach ( $items as $item ) {
if ( is_numeric( $item ) ) {
RE_404::delete( intval( $item, 10 ) );
} else {
RE_404::delete_all( $this->get_delete_group( $params ), $item );
}
}
return $this->route_404( $request );
}
return $this->add_error_details( new WP_Error( 'redirect', 'Invalid array of items' ), __LINE__ );
}
private function get_delete_group( array $params ) {
if ( isset( $params['groupBy'] ) && $params['groupBy'] === 'ip' ) {
return 'ip';
}
return 'url-exact';
}
public function route_delete_all( WP_REST_Request $request ) {
$params = $request->get_params();
$filter = false;
$filter_by = false;
if ( isset( $params['items'] ) && is_array( $params['items'] ) ) {
foreach ( $params['items'] as $url ) {
RE_404::delete_all( $this->get_delete_group( $params ), $url );
}
} else {
if ( isset( $params['filter'] ) ) {
$filter = $params['filter'];
}
if ( isset( $params['filterBy'] ) ) {
$filter_by = $params['filterBy'];
}
RE_404::delete_all( $filter_by, $filter );
unset( $params['filterBy'] );
unset( $params['filter'] );
}
unset( $params['page'] );
return $this->get_404( $params );
}
private function get_404( array $params ) {
if ( isset( $params['groupBy'] ) && in_array( $params['groupBy'], array( 'ip', 'url' ), true ) ) {
return RE_Filter_Log::get_grouped( 'redirection_404', $params['groupBy'], $params );
}
return RE_Filter_Log::get( 'redirection_404', 'RE_404', $params );
}
}

View File

@@ -0,0 +1,41 @@
<?php
/**
* @api {get} /redirection/v1/export/:module/:format Export redirects for a module in a format
* @apiDescription Export redirects for a module in a format
* @apiGroup Export
*
* @apiParam {String} module The module to export - 1, 2, 3, or 'all'
* @apiParam {String} format The format of the export. Either 'csv', 'apache', 'nginx', or 'json'
*
* @apiSuccess {Array} ip Array of export data
* @apiSuccess {Integer} total Number of items exported
*
* @apiUse 400Error
*/
class Redirection_Api_Export extends Redirection_Api_Route {
public function __construct( $namespace ) {
register_rest_route( $namespace, '/export/(?P<module>1|2|3|all)/(?P<format>csv|apache|nginx|json)', array(
$this->get_route( WP_REST_Server::READABLE, 'route_export' ),
) );
}
public function route_export( WP_REST_Request $request ) {
$module = $request['module'];
$format = 'json';
if ( in_array( $request['format'], array( 'csv', 'apache', 'nginx', 'json' ) ) ) {
$format = $request['format'];
}
$export = Red_FileIO::export( $module, $format );
if ( $export === false ) {
return $this->add_error_details( new WP_Error( 'redirect', 'Invalid module' ), __LINE__ );
}
return array(
'data' => $export['data'],
'total' => $export['total'],
);
}
}

View File

@@ -0,0 +1,112 @@
<?php
/**
* @api {get} /redirection/v1/group Get list of groups
* @apiDescription Get list of groups
* @apiGroup Group
*
* @apiParam {string} orderby
* @apiParam {string} direction
* @apiParam {string} filter
* @apiParam {string} per_page
* @apiParam {string} page
*
* @apiSuccess {Array} ip Array of groups
* @apiSuccess {Integer} total Number of items
*
* @apiUse 400Error
*/
class Redirection_Api_Group extends Redirection_Api_Filter_Route {
public function __construct( $namespace ) {
$filters = array( 'name', 'module' );
$orders = array( 'name', 'id' );
register_rest_route( $namespace, '/group', array(
'args' => $this->get_filter_args( $filters, $orders ),
$this->get_route( WP_REST_Server::READABLE, 'route_list' ),
array_merge(
$this->get_route( WP_REST_Server::EDITABLE, 'route_create' ),
array( 'args' => $this->get_group_args() )
),
) );
register_rest_route( $namespace, '/group/(?P<id>[\d]+)', array(
'args' => $this->get_group_args(),
$this->get_route( WP_REST_Server::EDITABLE, 'route_update' ),
) );
$this->register_bulk( $namespace, '/bulk/group/(?P<bulk>delete|enable|disable)', $filters, $orders, 'route_bulk' );
}
private function get_group_args() {
return array(
'moduleId' => array(
'description' => 'Module ID',
'type' => 'integer',
'minimum' => 0,
'maximum' => 3,
'required' => true,
),
'name' => array(
'description' => 'Group name',
'type' => 'string',
'required' => true,
),
);
}
public function route_list( WP_REST_Request $request ) {
return Red_Group::get_filtered( $request->get_params() );
}
public function route_create( WP_REST_Request $request ) {
$params = $request->get_params( $request );
$group = Red_Group::create( isset( $params['name'] ) ? $params['name'] : '', isset( $params['moduleId'] ) ? $params['moduleId'] : 0 );
if ( $group ) {
return Red_Group::get_filtered( $params );
}
return $this->add_error_details( new WP_Error( 'redirect', 'Invalid group or parameters' ), __LINE__ );
}
public function route_update( WP_REST_Request $request ) {
$params = $request->get_params( $request );
$group = Red_Group::get( intval( $request['id'], 10 ) );
if ( $group ) {
$result = $group->update( $params );
if ( $result ) {
return array( 'item' => $group->to_json() );
}
}
return $this->add_error_details( new WP_Error( 'redirect', 'Invalid group details' ), __LINE__ );
}
public function route_bulk( WP_REST_Request $request ) {
$action = $request['bulk'];
$items = explode( ',', $request['items'] );
if ( is_array( $items ) ) {
foreach ( $items as $item ) {
$group = Red_Group::get( intval( $item, 10 ) );
if ( $group ) {
if ( $action === 'delete' ) {
$group->delete();
} elseif ( $action === 'disable' ) {
$group->disable();
} elseif ( $action === 'enable' ) {
$group->enable();
}
}
}
return $this->route_list( $request );
}
return $this->add_error_details( new WP_Error( 'redirect', 'Invalid array of items' ), __LINE__ );
}
}

View File

@@ -0,0 +1,52 @@
<?php
class Redirection_Api_Import extends Redirection_Api_Route {
public function __construct( $namespace ) {
register_rest_route( $namespace, '/import/file/(?P<group_id>\d+)', array(
$this->get_route( WP_REST_Server::EDITABLE, 'route_import_file' ),
) );
register_rest_route( $namespace, '/import/plugin', array(
$this->get_route( WP_REST_Server::READABLE, 'route_plugin_import_list' ),
) );
register_rest_route( $namespace, '/import/plugin/(?P<plugin>.*?)', array(
$this->get_route( WP_REST_Server::EDITABLE, 'route_plugin_import' ),
) );
}
public function route_plugin_import_list( WP_REST_Request $request ) {
include_once dirname( dirname( __FILE__ ) ) . '/models/importer.php';
return array( 'importers' => Red_Plugin_Importer::get_plugins() );
}
public function route_plugin_import( WP_REST_Request $request ) {
include_once dirname( dirname( __FILE__ ) ) . '/models/importer.php';
$groups = Red_Group::get_all();
return array( 'imported' => Red_Plugin_Importer::import( $request['plugin'], $groups[0]['id'] ) );
}
public function route_import_file( WP_REST_Request $request ) {
$upload = $request->get_file_params();
$upload = isset( $upload['file'] ) ? $upload['file'] : false;
$group_id = $request['group_id'];
if ( $upload && is_uploaded_file( $upload['tmp_name'] ) ) {
$count = Red_FileIO::import( $group_id, $upload );
if ( $count !== false ) {
return array(
'imported' => $count,
);
}
return $this->add_error_details( new WP_Error( 'redirect', 'Invalid group' ), __LINE__ );
}
return $this->add_error_details( new WP_Error( 'redirect', 'Invalid file' ), __LINE__ );
}
}

View File

@@ -0,0 +1,81 @@
<?php
/**
* @api {get} /redirection/v1/log Get log logs
* @apiDescription Get log logs
* @apiGroup Log
*
* @apiParam {string} groupBy Group by 'ip' or 'url'
* @apiParam {string} orderby
* @apiParam {string} direction
* @apiParam {string} filter
* @apiParam {string} per_page
* @apiParam {string} page
*/
/**
* @api {post} /redirection/v1/log Delete log logs
* @apiDescription Delete log logs either by ID or filter or group
* @apiGroup Log
*
* @apiParam {string} items Array of log IDs
* @apiParam {string} filter
* @apiParam {string} filterBy
* @apiParam {string} groupBy Group by 'ip' or 'url'
*/
/**
* @api {post} /redirection/v1/bulk/log/delete Bulk actions on logs
* @apiDescription Delete log logs either by ID
* @apiGroup Log
*/
class Redirection_Api_Log extends Redirection_Api_Filter_Route {
public function __construct( $namespace ) {
$filters = array( 'url', 'ip', 'url-exact' );
$orders = array( 'url', 'ip' );
register_rest_route( $namespace, '/log', array(
'args' => $this->get_filter_args( $filters, $orders ),
$this->get_route( WP_REST_Server::READABLE, 'route_log' ),
$this->get_route( WP_REST_Server::EDITABLE, 'route_delete_all' ),
) );
$this->register_bulk( $namespace, '/bulk/log/(?P<bulk>delete)', $filters, $filters, 'route_bulk' );
}
public function route_log( WP_REST_Request $request ) {
return $this->get_logs( $request->get_params() );
}
public function route_bulk( WP_REST_Request $request ) {
$items = explode( ',', $request['items'] );
if ( is_array( $items ) ) {
$items = array_map( 'intval', $items );
array_map( array( 'RE_Log', 'delete' ), $items );
return $this->route_log( $request );
}
return $this->add_error_details( new WP_Error( 'redirect', 'Invalid array of items' ), __LINE__ );
}
public function route_delete_all( WP_REST_Request $request ) {
$params = $request->get_params();
$filter = false;
$filter_by = false;
if ( isset( $params['filter'] ) ) {
$filter = $params['filter'];
}
if ( isset( $params['filterBy'] ) && in_array( $params['filterBy'], array( 'url', 'ip', 'url-exact' ), true ) ) {
$filter_by = $params['filterBy'];
}
RE_Log::delete_all( $filter_by, $filter );
return $this->route_log( $request );
}
private function get_logs( array $params ) {
return RE_Filter_Log::get( 'redirection_logs', 'RE_Log', $params );
}
}

View File

@@ -0,0 +1,165 @@
<?php
/**
* 'Plugin' functions for Redirection
*/
class Redirection_Api_Plugin extends Redirection_Api_Route {
public function __construct( $namespace ) {
register_rest_route( $namespace, '/plugin', array(
$this->get_route( WP_REST_Server::READABLE, 'route_status' ),
) );
register_rest_route( $namespace, '/plugin', array(
$this->get_route( WP_REST_Server::EDITABLE, 'route_fixit' ),
'args' => [
'name' => array(
'description' => 'Name',
'type' => 'string',
),
'value' => array(
'description' => 'Value',
'type' => 'string',
),
],
) );
register_rest_route( $namespace, '/plugin/delete', array(
$this->get_route( WP_REST_Server::EDITABLE, 'route_delete' ),
) );
register_rest_route( $namespace, '/plugin/test', array(
$this->get_route( WP_REST_Server::ALLMETHODS, 'route_test' ),
) );
register_rest_route( $namespace, '/plugin/post', array(
$this->get_route( WP_REST_Server::READABLE, 'route_match_post' ),
'args' => [
'text' => [
'description' => 'Text to match',
'type' => 'string',
],
],
) );
register_rest_route( $namespace, '/plugin/database', array(
$this->get_route( WP_REST_Server::EDITABLE, 'route_database' ),
'args' => array(
'description' => 'Upgrade parameter',
'type' => 'enum',
'enum' => array(
'stop',
'skip',
),
),
) );
}
public function route_match_post( WP_REST_Request $request ) {
$params = $request->get_params();
$search = isset( $params['text'] ) ? $params['text'] : false;
$results = [];
if ( $search ) {
global $wpdb;
$posts = $wpdb->get_results(
$wpdb->prepare(
"SELECT ID,post_title,post_name FROM $wpdb->posts WHERE post_status='publish' AND (post_title LIKE %s OR post_name LIKE %s) " .
"AND post_type NOT IN ('nav_menu_item','wp_block','oembed_cache')",
'%' . $wpdb->esc_like( $search ) . '%', '%' . $wpdb->esc_like( $search ) . '%'
)
);
foreach ( (array) $posts as $post ) {
$results[] = [
'title' => $post->post_title,
'slug' => $post->post_name,
'url' => get_permalink( $post->ID ),
];
}
}
return $results;
}
public function route_status( WP_REST_Request $request ) {
include_once dirname( REDIRECTION_FILE ) . '/models/fixer.php';
$fixer = new Red_Fixer();
return $fixer->get_json();
}
public function route_fixit( WP_REST_Request $request ) {
include_once dirname( REDIRECTION_FILE ) . '/models/fixer.php';
$params = $request->get_params();
$fixer = new Red_Fixer();
if ( isset( $params['name'] ) && isset( $params['value'] ) ) {
global $wpdb;
$fixer->save_debug( $params['name'], $params['value'] );
$groups = intval( $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}redirection_groups" ), 10 );
if ( $groups === 0 ) {
Red_Group::create( 'new group', 1 );
}
} else {
$fixer->fix( $fixer->get_status() );
}
return $fixer->get_json();
}
public function route_delete() {
if ( is_multisite() ) {
return $this->getError( 'Multisite installations must delete the plugin from the network admin', __LINE__ );
}
$plugin = Redirection_Admin::init();
$plugin->plugin_uninstall();
$current = get_option( 'active_plugins' );
array_splice( $current, array_search( basename( dirname( REDIRECTION_FILE ) ) . '/' . basename( REDIRECTION_FILE ), $current ), 1 );
update_option( 'active_plugins', $current );
return array( 'location' => admin_url() . 'plugins.php' );
}
public function route_test( WP_REST_Request $request ) {
return array(
'success' => true,
);
}
public function route_database( WP_REST_Request $request ) {
$params = $request->get_params();
$status = new Red_Database_Status();
$upgrade = false;
if ( isset( $params['upgrade'] ) && in_array( $params['upgrade'], [ 'stop', 'skip' ], true ) ) {
$upgrade = $params['upgrade'];
}
// Check upgrade
if ( ! $status->needs_updating() && ! $status->needs_installing() ) {
/* translators: version number */
$status->set_error( sprintf( __( 'Your database does not need updating to %s.', 'redirection' ), REDIRECTION_DB_VERSION ) );
return $status->get_json();
}
if ( $upgrade === 'stop' ) {
$status->stop_update();
} elseif ( $upgrade === 'skip' ) {
$status->set_next_stage();
}
if ( $upgrade === false || $status->get_current_stage() ) {
$database = new Red_Database();
$database->apply_upgrade( $status );
}
return $status->get_json();
}
}

View File

@@ -0,0 +1,109 @@
<?php
/**
* @api {get} /redirection/v1/redirect Get list of redirects
* @apiDescription Get list of redirects
* @apiGroup Redirect
*
* @apiParam {string} orderby
* @apiParam {string} direction
* @apiParam {string} filter
* @apiParam {string} per_page
* @apiParam {string} page
*
* @apiSuccess {Array} ip Array of redirects
* @apiSuccess {Integer} total Number of items
*
* @apiUse 400Error
*/
class Redirection_Api_Redirect extends Redirection_Api_Filter_Route {
public function __construct( $namespace ) {
$filters = array( 'url', 'group' );
$orders = array( 'url', 'last_count', 'last_access', 'position', 'id' );
register_rest_route( $namespace, '/redirect', array(
'args' => $this->get_filter_args( $filters, $orders ),
$this->get_route( WP_REST_Server::READABLE, 'route_list' ),
$this->get_route( WP_REST_Server::EDITABLE, 'route_create' ),
) );
register_rest_route( $namespace, '/redirect/(?P<id>[\d]+)', array(
$this->get_route( WP_REST_Server::EDITABLE, 'route_update' ),
) );
$this->register_bulk( $namespace, '/bulk/redirect/(?P<bulk>delete|enable|disable|reset)', $filters, $orders, 'route_bulk' );
}
public function route_list( WP_REST_Request $request ) {
return Red_Item::get_filtered( $request->get_params() );
}
public function route_create( WP_REST_Request $request ) {
$params = $request->get_params();
$urls = array();
if ( isset( $params['url'] ) ) {
$urls = array( $params['url'] );
if ( is_array( $params['url'] ) ) {
$urls = $params['url'];
}
foreach ( $urls as $url ) {
$params['url'] = $url;
$redirect = Red_Item::create( $params );
if ( is_wp_error( $redirect ) ) {
return $this->add_error_details( $redirect, __LINE__ );
}
}
}
return $this->route_list( $request );
}
public function route_update( WP_REST_Request $request ) {
$params = $request->get_params();
$redirect = Red_Item::get_by_id( intval( $params['id'], 10 ) );
if ( $redirect ) {
$result = $redirect->update( $params );
if ( is_wp_error( $result ) ) {
return $this->add_error_details( $result, __LINE__ );
}
return array( 'item' => $redirect->to_json() );
}
return $this->add_error_details( new WP_Error( 'redirect', 'Invalid redirect details' ), __LINE__ );
}
public function route_bulk( WP_REST_Request $request ) {
$action = $request['bulk'];
$items = explode( ',', $request['items'] );
if ( is_array( $items ) ) {
foreach ( $items as $item ) {
$redirect = Red_Item::get_by_id( intval( $item, 10 ) );
if ( $redirect ) {
if ( $action === 'delete' ) {
$redirect->delete();
} elseif ( $action === 'disable' ) {
$redirect->disable();
} elseif ( $action === 'enable' ) {
$redirect->enable();
} elseif ( $action === 'reset' ) {
$redirect->reset();
}
}
}
return $this->route_list( $request );
}
return $this->add_error_details( new WP_Error( 'redirect', 'Invalid array of items' ), __LINE__ );
}
}

View File

@@ -0,0 +1,63 @@
<?php
class Redirection_Api_Settings extends Redirection_Api_Route {
public function __construct( $namespace ) {
register_rest_route( $namespace, '/setting', array(
$this->get_route( WP_REST_Server::READABLE, 'route_settings' ),
$this->get_route( WP_REST_Server::EDITABLE, 'route_save_settings' ),
) );
}
public function route_settings( WP_REST_Request $request ) {
if ( ! function_exists( 'get_home_path' ) ) {
include_once ABSPATH . '/wp-admin/includes/file.php';
}
return [
'settings' => red_get_options(),
'groups' => $this->groups_to_json( Red_Group::get_for_select() ),
'installed' => get_home_path(),
'canDelete' => ! is_multisite(),
'post_types' => red_get_post_types(),
];
}
public function route_save_settings( WP_REST_Request $request ) {
$params = $request->get_params();
$result = true;
if ( isset( $params['location'] ) && strlen( $params['location'] ) > 0 ) {
$module = Red_Module::get( 2 );
$result = $module->can_save( $params['location'] );
}
red_set_options( $params );
$settings = $this->route_settings( $request );
if ( is_wp_error( $result ) ) {
$settings['warning'] = $result->get_error_message();
}
return $settings;
}
private function groups_to_json( $groups, $depth = 0 ) {
$items = array();
foreach ( $groups as $text => $value ) {
if ( is_array( $value ) && $depth === 0 ) {
$items[] = (object) array(
'text' => $text,
'value' => $this->groups_to_json( $value, 1 ),
);
} else {
$items[] = (object) array(
'text' => $value,
'value' => $text,
);
}
}
return $items;
}
}

View File

@@ -0,0 +1,371 @@
<?php
class Red_Database_Status {
// Used in < 3.7 versions of Redirection, but since migrated to general settings
const OLD_DB_VERSION = 'redirection_version';
const DB_UPGRADE_STAGE = 'redirection_database_stage';
const RESULT_OK = 'ok';
const RESULT_ERROR = 'error';
const STATUS_OK = 'ok';
const STATUS_NEED_INSTALL = 'need-install';
const STATUS_NEED_UPDATING = 'need-update';
const STATUS_FINISHED_INSTALL = 'finish-install';
const STATUS_FINISHED_UPDATING = 'finish-update';
private $stage = false;
private $stages = [];
private $status = false;
private $result = false;
private $reason = false;
private $debug = [];
public function __construct() {
$this->status = self::STATUS_OK;
if ( $this->needs_installing() ) {
$this->status = self::STATUS_NEED_INSTALL;
} elseif ( $this->needs_updating() ) {
$this->status = self::STATUS_NEED_UPDATING;
}
$info = get_option( self::DB_UPGRADE_STAGE );
if ( $info ) {
$this->stage = isset( $info['stage'] ) ? $info['stage'] : false;
$this->stages = isset( $info['stages'] ) ? $info['stages'] : [];
$this->status = isset( $info['status'] ) ? $info['status'] : false;
}
}
/**
* Does the database need install
*
* @return bool true if needs installing, false otherwise
*/
public function needs_installing() {
$settings = red_get_options();
if ( $settings['database'] === '' && $this->get_old_version() === false ) {
return true;
}
return false;
}
/**
* Does the current database need updating to the target
*
* @return bool true if needs updating, false otherwise
*/
public function needs_updating() {
// We need updating if we don't need to install, and the current version is less than target version
if ( $this->needs_installing() === false && version_compare( $this->get_current_version(), REDIRECTION_DB_VERSION, '<' ) ) {
return true;
}
// Also if we're still in the process of upgrading
if ( $this->get_current_stage() ) {
return true;
}
return false;
}
/**
* Get current database version
*
* @return string Current database version
*/
public function get_current_version() {
$settings = red_get_options();
if ( $settings['database'] !== '' ) {
return $settings['database'];
} elseif ( $this->get_old_version() !== false ) {
$version = $this->get_old_version();
// Upgrade the old value
red_set_options( array( 'database' => $version ) );
delete_option( self::OLD_DB_VERSION );
$this->clear_cache();
return $version;
}
return '';
}
private function get_old_version() {
return get_option( self::OLD_DB_VERSION );
}
public function check_tables_exist() {
$latest = Red_Database::get_latest_database();
$missing = $latest->get_missing_tables();
// No tables installed - do a fresh install
if ( count( $missing ) === count( $latest->get_all_tables() ) ) {
delete_option( Red_Database_Status::OLD_DB_VERSION );
red_set_options( [ 'database' => '' ] );
$this->clear_cache();
$this->status = self::STATUS_NEED_INSTALL;
$this->stop_update();
} elseif ( count( $missing ) > 0 && version_compare( $this->get_current_version(), '2.3.3', 'ge' ) ) {
// Some tables are missing - try and fill them in
$latest->install();
}
}
/**
* Does the current database support a particular version
*
* @param string $version Target version
* @return bool true if supported, false otherwise
*/
public function does_support( $version ) {
return version_compare( $this->get_current_version(), $version, 'ge' );
}
public function is_error() {
return $this->result === self::RESULT_ERROR;
}
public function set_error( $error ) {
global $wpdb;
$this->result = self::RESULT_ERROR;
$this->reason = str_replace( "\t", ' ', $error );
if ( $wpdb->last_error ) {
$this->debug[] = $wpdb->last_error;
if ( strpos( $wpdb->last_error, 'command denied to user' ) !== false ) {
$this->reason .= ' - ' . __( 'Insufficient database permissions detected. Please give your database user appropriate permissions.', 'redirection' );
}
}
$latest = Red_Database::get_latest_database();
$this->debug = array_merge( $this->debug, $latest->get_table_schema() );
$this->debug[] = 'Stage: ' . $this->get_current_stage();
}
public function set_ok( $reason ) {
$this->reason = $reason;
$this->result = self::RESULT_OK;
$this->debug = [];
}
/**
* Stop current upgrade
*/
public function stop_update() {
$this->stage = false;
$this->stages = [];
$this->debug = [];
delete_option( self::DB_UPGRADE_STAGE );
$this->clear_cache();
}
public function finish() {
$this->stop_update();
if ( $this->status === self::STATUS_NEED_INSTALL ) {
$this->status = self::STATUS_FINISHED_INSTALL;
} elseif ( $this->status === self::STATUS_NEED_UPDATING ) {
$this->status = self::STATUS_FINISHED_UPDATING;
}
}
/**
* Get current upgrade stage
* @return string|bool Current stage name, or false if not upgrading
*/
public function get_current_stage() {
return $this->stage;
}
/**
* Move current stage on to the next
*/
public function set_next_stage() {
$stage = $this->get_current_stage();
if ( $stage ) {
$stage = $this->get_next_stage( $stage );
// Save next position
if ( $stage ) {
$this->set_stage( $stage );
} else {
$this->finish();
}
}
}
/**
* Get current upgrade status
*
* @return array Database status array
*/
public function get_json() {
// Base information
$result = [
'status' => $this->status,
'inProgress' => $this->stage !== false,
];
// Add on version status
if ( $this->status === self::STATUS_NEED_INSTALL || $this->status === self::STATUS_NEED_UPDATING ) {
$result = array_merge(
$result,
$this->get_version_upgrade(),
[ 'manual' => $this->get_manual_upgrade() ]
);
}
// Add on upgrade status
if ( $this->is_error() ) {
$result = array_merge( $result, $this->get_version_upgrade(), $this->get_progress_status(), $this->get_error_status() );
} elseif ( $result['inProgress'] ) {
$result = array_merge( $result, $this->get_progress_status() );
} elseif ( $this->status === self::STATUS_FINISHED_INSTALL || $this->status === self::STATUS_FINISHED_UPDATING ) {
$result['complete'] = 100;
$result['reason'] = $this->reason;
}
return $result;
}
private function get_error_status() {
return [
'reason' => $this->reason,
'result' => self::RESULT_ERROR,
'debug' => $this->debug,
];
}
private function get_progress_status() {
$complete = 0;
if ( $this->stage ) {
$complete = round( ( array_search( $this->stage, $this->stages, true ) / count( $this->stages ) ) * 100, 1 );
}
return [
'complete' => $complete,
'result' => self::RESULT_OK,
'reason' => $this->reason,
];
}
private function get_version_upgrade() {
return [
'current' => $this->get_current_version() ? $this->get_current_version() : '-',
'next' => REDIRECTION_DB_VERSION,
'time' => microtime( true ),
];
}
/**
* Set the status information for a database upgrade
*/
public function start_install( array $upgrades ) {
$this->set_stages( $upgrades );
$this->status = self::STATUS_NEED_INSTALL;
}
public function start_upgrade( array $upgrades ) {
$this->set_stages( $upgrades );
$this->status = self::STATUS_NEED_UPDATING;
}
private function set_stages( array $upgrades ) {
$this->stages = [];
foreach ( $upgrades as $upgrade ) {
$upgrader = Red_Database_Upgrader::get( $upgrade );
$this->stages = array_merge( $this->stages, array_keys( $upgrader->get_stages() ) );
}
if ( count( $this->stages ) > 0 ) {
$this->set_stage( $this->stages[0] );
}
}
public function set_stage( $stage ) {
$this->stage = $stage;
$this->save_details();
}
private function save_details() {
update_option( self::DB_UPGRADE_STAGE, [
'stage' => $this->stage,
'stages' => $this->stages,
'status' => $this->status,
] );
$this->clear_cache();
}
private function get_manual_upgrade() {
$queries = [];
$database = new Red_Database();
$upgraders = $database->get_upgrades_for_version( $this->get_current_version(), false );
foreach ( $upgraders as $upgrade ) {
$upgrade = Red_Database_Upgrader::get( $upgrade );
$stages = $upgrade->get_stages();
foreach ( array_keys( $stages ) as $stage ) {
$queries = array_merge( $queries, $upgrade->get_queries_for_stage( $stage ) );
}
}
return $queries;
}
private function get_next_stage( $stage ) {
$database = new Red_Database();
$upgraders = $database->get_upgrades_for_version( $this->get_current_version(), $this->get_current_stage() );
if ( count( $upgraders ) === 0 ) {
$upgraders = $database->get_upgrades_for_version( $this->get_current_version(), false );
}
$upgrader = Red_Database_Upgrader::get( $upgraders[0] );
// Where are we in this?
$pos = array_search( $this->stage, $this->stages, true );
if ( $pos === count( $this->stages ) - 1 ) {
$this->save_db_version( REDIRECTION_DB_VERSION );
return false;
}
// Set current DB version
$current_stages = array_keys( $upgrader->get_stages() );
if ( array_search( $this->stage, $current_stages, true ) === count( $current_stages ) - 1 ) {
$this->save_db_version( $upgraders[1]['version'] );
}
// Move on to next in current version
return $this->stages[ $pos + 1 ];
}
public function save_db_version( $version ) {
red_set_options( array( 'database' => $version ) );
delete_option( self::OLD_DB_VERSION );
$this->clear_cache();
}
private function clear_cache() {
if ( file_exists( WP_CONTENT_DIR . '/object-cache.php' ) && function_exists( 'wp_cache_flush' ) ) {
wp_cache_flush();
}
}
}

View File

@@ -0,0 +1,124 @@
<?php
abstract class Red_Database_Upgrader {
private $queries = [];
private $live = true;
/**
* Return an array of all the stages for an upgrade
*
* @return array stage name => reason
*/
abstract public function get_stages();
public function get_reason( $stage ) {
$stages = $this->get_stages();
if ( isset( $stages[ $stage ] ) ) {
return $stages[ $stage ];
}
return 'Unknown';
}
/**
* Run a particular stage on the current upgrader
*
* @return Red_Database_Status
*/
public function perform_stage( Red_Database_Status $status ) {
global $wpdb;
$stage = $status->get_current_stage();
if ( $this->has_stage( $stage ) && method_exists( $this, $stage ) ) {
try {
$this->$stage( $wpdb );
$status->set_ok( $this->get_reason( $stage ) );
} catch ( Exception $e ) {
$status->set_error( $e->getMessage() );
}
} else {
$status->set_error( 'No stage found for upgrade ' . $stage );
}
}
public function get_queries_for_stage( $stage ) {
global $wpdb;
$this->queries = [];
$this->live = false;
$this->$stage( $wpdb );
$this->live = true;
return $this->queries;
}
/**
* Returns the current database charset
*
* @return string Database charset
*/
public function get_charset() {
global $wpdb;
$charset_collate = '';
if ( ! empty( $wpdb->charset ) ) {
// Fix some common invalid charset values
$fixes = [
'utf-8',
'utf',
];
$charset = $wpdb->charset;
if ( in_array( strtolower( $charset ), $fixes, true ) ) {
$charset = 'utf8';
}
$charset_collate = "DEFAULT CHARACTER SET $charset";
}
if ( ! empty( $wpdb->collate ) ) {
$charset_collate .= " COLLATE=$wpdb->collate";
}
return $charset_collate;
}
/**
* Performs a $wpdb->query, and throws an exception if an error occurs
*
* @return bool true if query is performed ok, otherwise an exception is thrown
*/
protected function do_query( $wpdb, $sql ) {
if ( ! $this->live ) {
$this->queries[] = $sql;
return true;
}
// These are known queries without user input
// phpcs:ignore
$result = $wpdb->query( $sql );
if ( $result === false ) {
/* translators: 1: SQL string */
throw new Exception( sprintf( __( 'Failed to perform query "%s"' ), $sql ) );
}
return true;
}
/**
* Load a database upgrader class
*
* @return object Database upgrader
*/
public static function get( $version ) {
include_once dirname( __FILE__ ) . '/schema/' . str_replace( [ '..', '/' ], '', $version['file'] );
return new $version['class'];
}
private function has_stage( $stage ) {
return in_array( $stage, array_keys( $this->get_stages() ), true );
}
}

View File

@@ -0,0 +1,165 @@
<?php
include_once dirname( __FILE__ ) . '/database-status.php';
include_once dirname( __FILE__ ) . '/database-upgrader.php';
class Red_Database {
/**
* Get all upgrades for a database version
*
* @return array Array of versions from self::get_upgrades()
*/
public function get_upgrades_for_version( $current_version, $current_stage ) {
if ( empty( $current_version ) ) {
return [
[
'version' => REDIRECTION_DB_VERSION,
'file' => 'latest.php',
'class' => 'Red_Latest_Database',
],
];
}
$upgraders = [];
$found = false;
foreach ( $this->get_upgrades() as $upgrade ) {
if ( ! $found ) {
$upgrader = Red_Database_Upgrader::get( $upgrade );
$stage_present = in_array( $current_stage, array_keys( $upgrader->get_stages() ), true );
$same_version = $current_stage === false && version_compare( $upgrade['version'], $current_version, 'g' );
if ( $stage_present || $same_version ) {
$found = true;
}
}
if ( $found ) {
$upgraders[] = $upgrade;
}
}
return $upgraders;
}
/**
* Apply a particular upgrade stage
*
* @return mixed Result for upgrade
*/
public function apply_upgrade( Red_Database_Status $status ) {
$upgraders = $this->get_upgrades_for_version( $status->get_current_version(), $status->get_current_stage() );
if ( count( $upgraders ) === 0 ) {
$status->set_error( 'No upgrades found for version ' . $status->get_current_version() );
return;
}
if ( $status->get_current_stage() === false ) {
if ( $status->needs_installing() ) {
$status->start_install( $upgraders );
} else {
$status->start_upgrade( $upgraders );
}
}
// Look at first upgrade
$upgrader = Red_Database_Upgrader::get( $upgraders[0] );
// Perform the upgrade
$upgrader->perform_stage( $status );
if ( ! $status->is_error() ) {
$status->set_next_stage();
}
}
public static function apply_to_sites( $callback ) {
if ( is_multisite() && ( is_network_admin() || defined( 'WP_CLI' ) && WP_CLI ) ) {
$total = get_sites( [ 'count' => true ] );
$per_page = 100;
// Paginate through all sites and apply the callback
for ( $offset = 0; $offset < $total; $offset += $per_page ) {
array_map( function( $site ) use ( $callback ) {
switch_to_blog( $site->blog_id );
$callback();
restore_current_blog();
}, get_sites( [ 'number' => $per_page, 'offset' => $offset ] ) );
}
return;
}
$callback();
}
/**
* Get latest database installer
*
* @return object Red_Latest_Database
*/
public static function get_latest_database() {
include_once dirname( __FILE__ ) . '/schema/latest.php';
return new Red_Latest_Database();
}
/**
* List of all upgrades and their associated file
*
* @return array Database upgrade array
*/
public function get_upgrades() {
return [
[
'version' => '2.0.1',
'file' => '201.php',
'class' => 'Red_Database_201',
],
[
'version' => '2.1.16',
'file' => '216.php',
'class' => 'Red_Database_216',
],
[
'version' => '2.2',
'file' => '220.php',
'class' => 'Red_Database_220',
],
[
'version' => '2.3.1',
'file' => '231.php',
'class' => 'Red_Database_231',
],
[
'version' => '2.3.2',
'file' => '232.php',
'class' => 'Red_Database_232',
],
[
'version' => '2.3.3',
'file' => '233.php',
'class' => 'Red_Database_233',
],
[
'version' => '2.4',
'file' => '240.php',
'class' => 'Red_Database_240',
],
[
'version' => '4.0',
'file' => '400.php',
'class' => 'Red_Database_400',
],
[
'version' => '4.1',
'file' => '410.php',
'class' => 'Red_Database_410',
],
];
}
}

View File

@@ -0,0 +1,14 @@
<?php
// Note: not localised as the messages aren't important enough
class Red_Database_201 extends Red_Database_Upgrader {
public function get_stages() {
return [
'add_title_201' => 'Add titles to redirects',
];
}
protected function add_title_201( $wpdb ) {
return $this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_items` ADD `title` varchar(50) NULL" );
}
}

View File

@@ -0,0 +1,26 @@
<?php
// Note: not localised as the messages aren't important enough
class Red_Database_216 extends Red_Database_Upgrader {
public function get_stages() {
return [
'add_group_indices_216' => 'Add indices to groups',
'add_redirect_indices_216' => 'Add indices to redirects',
];
}
protected function add_group_indices_216( $wpdb ) {
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_groups` ADD INDEX(module_id)" );
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_groups` ADD INDEX(status)" );
return true;
}
protected function add_redirect_indices_216( $wpdb ) {
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_items` ADD INDEX(url(191))" );
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_items` ADD INDEX(status)" );
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_items` ADD INDEX(regex)" );
return true;
}
}

View File

@@ -0,0 +1,26 @@
<?php
// Note: not localised as the messages aren't important enough
class Red_Database_220 extends Red_Database_Upgrader {
public function get_stages() {
return [
'add_group_indices_220' => 'Add group indices to redirects',
'add_log_indices_220' => 'Add indices to logs',
];
}
protected function add_group_indices_220( $wpdb ) {
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_items` ADD INDEX `group_idpos` (`group_id`,`position`)" );
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_items` ADD INDEX `group` (`group_id`)" );
return true;
}
protected function add_log_indices_220( $wpdb ) {
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_logs` ADD INDEX `created` (`created`)" );
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_logs` ADD INDEX `redirection_id` (`redirection_id`)" );
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_logs` ADD INDEX `ip` (`ip`)" );
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_logs` ADD INDEX `group_id` (`group_id`)" );
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_logs` ADD INDEX `module_id` (`module_id`)" );
return true;
}
}

View File

@@ -0,0 +1,37 @@
<?php
// Note: not localised as the messages aren't important enough
class Red_Database_231 extends Red_Database_Upgrader {
public function get_stages() {
return [
'remove_404_module_231' => 'Remove 404 module',
'create_404_table_231' => 'Create 404 table',
];
}
protected function remove_404_module_231( $wpdb ) {
return $this->do_query( $wpdb, "UPDATE {$wpdb->prefix}redirection_groups SET module_id=1 WHERE module_id=3" );
}
protected function create_404_table_231( $wpdb ) {
$this->do_query( $wpdb, $this->get_404_table( $wpdb ) );
}
private function get_404_table( $wpdb ) {
$charset_collate = $this->get_charset();
return "CREATE TABLE `{$wpdb->prefix}redirection_404` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`url` varchar(255) NOT NULL DEFAULT '',
`agent` varchar(255) DEFAULT NULL,
`referrer` varchar(255) DEFAULT NULL,
`ip` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `created` (`created`),
KEY `url` (`url`(191)),
KEY `ip` (`ip`),
KEY `referrer` (`referrer`(191))
) $charset_collate";
}
}

View File

@@ -0,0 +1,15 @@
<?php
// Note: not localised as the messages aren't important enough
class Red_Database_232 extends Red_Database_Upgrader {
public function get_stages() {
return [
'remove_modules_232' => 'Remove module table',
];
}
protected function remove_modules_232( $wpdb ) {
$this->do_query( $wpdb, "DROP TABLE IF EXISTS {$wpdb->prefix}redirection_modules" );
return true;
}
}

View File

@@ -0,0 +1,17 @@
<?php
// Note: not localised as the messages aren't important enough
class Red_Database_233 extends Red_Database_Upgrader {
public function get_stages() {
return [
'fix_invalid_groups_233' => 'Migrate any groups with invalid module ID',
];
}
protected function fix_invalid_groups_233( $wpdb ) {
$this->do_query( $wpdb, "UPDATE {$wpdb->prefix}redirection_groups SET module_id=1 WHERE module_id > 2" );
$latest = Red_Database::get_latest_database();
return $latest->create_groups( $wpdb );
}
}

View File

@@ -0,0 +1,88 @@
<?php
/**
* There are several problems with 2.3.3 => 2.4 that this attempts to cope with:
* - some sites have a misconfigured IP column
* - some sites don't have any IP column
*/
class Red_Database_240 extends Red_Database_Upgrader {
public function get_stages() {
return [
'convert_int_ip_to_varchar_240' => 'Convert integer IP values to support IPv6',
'expand_log_ip_column_240' => 'Expand IP size in logs to support IPv6',
'convert_title_to_text_240' => 'Expand size of redirect titles',
'add_missing_index_240' => 'Add missing IP index to 404 logs',
];
}
private function has_ip_index( $wpdb ) {
$wpdb->hide_errors();
$existing = $wpdb->get_row( "SHOW CREATE TABLE `{$wpdb->prefix}redirection_404`", ARRAY_N );
$wpdb->show_errors();
if ( isset( $existing[1] ) && strpos( strtolower( $existing[1] ), 'key `ip` (' ) !== false ) {
return true;
}
return false;
}
protected function has_varchar_ip( $wpdb ) {
$wpdb->hide_errors();
$existing = $wpdb->get_row( "SHOW CREATE TABLE `{$wpdb->prefix}redirection_404`", ARRAY_N );
$wpdb->show_errors();
if ( isset( $existing[1] ) && strpos( strtolower( $existing[1] ), '`ip` varchar(45)' ) !== false ) {
return true;
}
return false;
}
protected function has_int_ip( $wpdb ) {
$wpdb->hide_errors();
$existing = $wpdb->get_row( "SHOW CREATE TABLE `{$wpdb->prefix}redirection_404`", ARRAY_N );
$wpdb->show_errors();
if ( isset( $existing[1] ) && strpos( strtolower( $existing[1] ), '`ip` int' ) !== false ) {
return true;
}
return false;
}
protected function convert_int_ip_to_varchar_240( $wpdb ) {
if ( $this->has_int_ip( $wpdb ) ) {
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_404` ADD `ipaddress` VARCHAR(45) DEFAULT NULL AFTER `ip`" );
$this->do_query( $wpdb, "UPDATE {$wpdb->prefix}redirection_404 SET ipaddress=INET_NTOA(ip)" );
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_404` DROP `ip`" );
return $this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_404` CHANGE `ipaddress` `ip` VARCHAR(45) DEFAULT NULL" );
}
return true;
}
protected function expand_log_ip_column_240( $wpdb ) {
return $this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_logs` CHANGE `ip` `ip` VARCHAR(45) DEFAULT NULL" );
}
protected function add_missing_index_240( $wpdb ) {
if ( $this->has_ip_index( $wpdb ) ) {
// Remove index
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_404` DROP INDEX ip" );
}
// Ensure we have an IP column
$this->convert_int_ip_to_varchar_240( $wpdb );
if ( ! $this->has_varchar_ip( $wpdb ) ) {
$this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_404` ADD `ip` VARCHAR(45) DEFAULT NULL" );
}
// Finally add the index
return $this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_404` ADD INDEX `ip` (`ip`)" );
}
protected function convert_title_to_text_240( $wpdb ) {
return $this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_items` CHANGE `title` `title` text" );
}
}

View File

@@ -0,0 +1,68 @@
<?php
class Red_Database_400 extends Red_Database_Upgrader {
public function get_stages() {
return [
'add_match_url_400' => 'Add a matched URL column',
'add_match_url_index' => 'Add match URL index',
'add_redirect_data_400' => 'Add column to store new flags',
'convert_existing_urls_400' => 'Convert existing URLs to new format',
];
}
private function has_column( $wpdb, $column ) {
$existing = $wpdb->get_row( "SHOW CREATE TABLE `{$wpdb->prefix}redirection_items`", ARRAY_N );
if ( isset( $existing[1] ) && strpos( strtolower( $existing[1] ), strtolower( $column ) ) !== false ) {
return true;
}
return false;
}
private function has_match_index( $wpdb ) {
$existing = $wpdb->get_row( "SHOW CREATE TABLE `{$wpdb->prefix}redirection_items`", ARRAY_N );
if ( isset( $existing[1] ) && strpos( strtolower( $existing[1] ), 'key `match_url' ) !== false ) {
return true;
}
return false;
}
protected function add_match_url_400( $wpdb ) {
if ( ! $this->has_column( $wpdb, '`match_url` varchar(2000)' ) ) {
return $this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_items` ADD `match_url` VARCHAR(2000) NULL DEFAULT NULL AFTER `url`" );
}
return true;
}
protected function add_match_url_index( $wpdb ) {
if ( ! $this->has_match_index( $wpdb ) ) {
return $this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_items` ADD INDEX `match_url` (`match_url`(191))" );
}
}
protected function add_redirect_data_400( $wpdb ) {
if ( ! $this->has_column( $wpdb, '`match_data` TEXT' ) ) {
return $this->do_query( $wpdb, "ALTER TABLE `{$wpdb->prefix}redirection_items` ADD `match_data` TEXT NULL DEFAULT NULL AFTER `match_url`" );
}
return true;
}
protected function convert_existing_urls_400( $wpdb ) {
// All regex get match_url=regex
$this->do_query( $wpdb, "UPDATE `{$wpdb->prefix}redirection_items` SET match_url='regex' WHERE regex=1" );
// Remove query part from all URLs and lowercase
$this->do_query( $wpdb, "UPDATE `{$wpdb->prefix}redirection_items` SET match_url=SUBSTRING_INDEX(LOWER(url), '?', 1) WHERE regex=0" );
// Trim the last / from a URL
$this->do_query( $wpdb, "UPDATE `{$wpdb->prefix}redirection_items` SET match_url=LEFT(match_url,LENGTH(match_url)-1) WHERE regex=0 AND match_url != '/' AND RIGHT(match_url, 1) = '/'" );
// Any URL that is now empty becomes /
return $this->do_query( $wpdb, "UPDATE `{$wpdb->prefix}redirection_items` SET match_url='/' WHERE match_url=''" );
}
}

View File

@@ -0,0 +1,17 @@
<?php
class Red_Database_410 extends Red_Database_Upgrader {
public function get_stages() {
return [
'handle_double_slash' => 'Support double-slash URLs',
];
}
protected function handle_double_slash( $wpdb ) {
// Update any URL with a double slash at the end
$this->do_query( $wpdb, "UPDATE `{$wpdb->prefix}redirection_items` SET match_url=LOWER(LEFT(SUBSTRING_INDEX(url, '?', 1),LENGTH(SUBSTRING_INDEX(url, '?', 1)) - 1)) WHERE RIGHT(SUBSTRING_INDEX(url, '?', 1), 2) = '//' AND regex=0" );
// Any URL that is now empty becomes /
return $this->do_query( $wpdb, "UPDATE `{$wpdb->prefix}redirection_items` SET match_url='/' WHERE match_url=''" );
}
}

View File

@@ -0,0 +1,251 @@
<?php
/**
* Latest database schema
*/
class Red_Latest_Database extends Red_Database_Upgrader {
public function get_stages() {
return [
'create_tables' => __( 'Install Redirection tables', 'redirection' ),
'create_groups' => __( 'Create basic data', 'redirection' ),
];
}
/**
* Install the latest database
*
* @return bool|WP_Error true if installed, WP_Error otherwise
*/
public function install() {
global $wpdb;
foreach ( $this->get_stages() as $stage => $info ) {
$result = $this->$stage( $wpdb );
if ( is_wp_error( $result ) ) {
if ( $wpdb->last_error ) {
$result->add_data( $wpdb->last_error );
}
return $result;
}
}
red_set_options( array( 'database' => REDIRECTION_DB_VERSION ) );
return true;
}
/**
* Remove the database and any options (including unused ones)
*/
public function remove() {
global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}redirection_items" );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}redirection_logs" );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}redirection_groups" );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}redirection_modules" );
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}redirection_404" );
delete_option( 'redirection_lookup' );
delete_option( 'redirection_post' );
delete_option( 'redirection_root' );
delete_option( 'redirection_index' );
delete_option( 'redirection_options' );
delete_option( Red_Database_Status::OLD_DB_VERSION );
delete_option( Red_Database_Status::DB_UPGRADE_STAGE );
}
/**
* Return any tables that are missing from the database
*
* @return array Array of missing table names
*/
public function get_missing_tables() {
global $wpdb;
$tables = array_keys( $this->get_all_tables() );
$missing = [];
foreach ( $tables as $table ) {
$result = $wpdb->query( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
if ( intval( $result, 10 ) !== 1 ) {
$missing[] = $table;
}
}
return $missing;
}
/**
* Get table schema for latest database tables
*
* @return array Database schema array
*/
public function get_table_schema() {
global $wpdb;
$tables = array_keys( $this->get_all_tables() );
$show = array();
foreach ( $tables as $table ) {
// These are known queries without user input
// phpcs:ignore
$row = $wpdb->get_row( 'SHOW CREATE TABLE ' . $table, ARRAY_N );
if ( $row ) {
$show = array_merge( $show, explode( "\n", $row[1] ) );
$show[] = '';
} else {
/* translators: 1: table name */
$show[] = sprintf( __( 'Table "%s" is missing', 'redirection' ), $table );
}
}
return $show;
}
/**
* Return array of table names and table schema
*
* @return array
*/
public function get_all_tables() {
global $wpdb;
$charset_collate = $this->get_charset();
return array(
"{$wpdb->prefix}redirection_items" => $this->create_items_sql( $wpdb->prefix, $charset_collate ),
"{$wpdb->prefix}redirection_groups" => $this->create_groups_sql( $wpdb->prefix, $charset_collate ),
"{$wpdb->prefix}redirection_logs" => $this->create_log_sql( $wpdb->prefix, $charset_collate ),
"{$wpdb->prefix}redirection_404" => $this->create_404_sql( $wpdb->prefix, $charset_collate ),
);
}
/**
* Creates default group information
*/
public function create_groups( $wpdb ) {
$defaults = [
[
'name' => __( 'Redirections', 'redirection' ),
'module_id' => 1,
'position' => 0,
],
[
'name' => __( 'Modified Posts', 'redirection' ),
'module_id' => 1,
'position' => 1,
],
];
$existing_groups = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}redirection_groups" );
// Default groups
if ( intval( $existing_groups, 10 ) === 0 ) {
$wpdb->insert( $wpdb->prefix . 'redirection_groups', $defaults[0] );
$wpdb->insert( $wpdb->prefix . 'redirection_groups', $defaults[1] );
}
$group = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}redirection_groups LIMIT 1" );
if ( $group ) {
red_set_options( array( 'last_group_id' => $group->id ) );
}
return true;
}
/**
* Creates all the tables
*/
public function create_tables( $wpdb ) {
global $wpdb;
foreach ( $this->get_all_tables() as $table => $sql ) {
$sql = preg_replace( '/[ \t]{2,}/', '', $sql );
$this->do_query( $wpdb, $sql );
}
return true;
}
private function create_items_sql( $prefix, $charset_collate ) {
return "CREATE TABLE IF NOT EXISTS `{$prefix}redirection_items` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`url` mediumtext NOT NULL,
`match_url` varchar(2000) DEFAULT NULL,
`match_data` text,
`regex` int(11) unsigned NOT NULL DEFAULT '0',
`position` int(11) unsigned NOT NULL DEFAULT '0',
`last_count` int(10) unsigned NOT NULL DEFAULT '0',
`last_access` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`group_id` int(11) NOT NULL DEFAULT '0',
`status` enum('enabled','disabled') NOT NULL DEFAULT 'enabled',
`action_type` varchar(20) NOT NULL,
`action_code` int(11) unsigned NOT NULL,
`action_data` mediumtext,
`match_type` varchar(20) NOT NULL,
`title` text,
PRIMARY KEY (`id`),
KEY `url` (`url`(191)),
KEY `status` (`status`),
KEY `regex` (`regex`),
KEY `group_idpos` (`group_id`,`position`),
KEY `group` (`group_id`),
KEY `match_url` (`match_url`(191))
) $charset_collate";
}
private function create_groups_sql( $prefix, $charset_collate ) {
return "CREATE TABLE IF NOT EXISTS `{$prefix}redirection_groups` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`tracking` int(11) NOT NULL DEFAULT '1',
`module_id` int(11) unsigned NOT NULL DEFAULT '0',
`status` enum('enabled','disabled') NOT NULL DEFAULT 'enabled',
`position` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `module_id` (`module_id`),
KEY `status` (`status`)
) $charset_collate";
}
private function create_log_sql( $prefix, $charset_collate ) {
return "CREATE TABLE IF NOT EXISTS `{$prefix}redirection_logs` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`url` mediumtext NOT NULL,
`sent_to` mediumtext,
`agent` mediumtext NOT NULL,
`referrer` mediumtext,
`redirection_id` int(11) unsigned DEFAULT NULL,
`ip` varchar(45) DEFAULT NULL,
`module_id` int(11) unsigned NOT NULL,
`group_id` int(11) unsigned DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `created` (`created`),
KEY `redirection_id` (`redirection_id`),
KEY `ip` (`ip`),
KEY `group_id` (`group_id`),
KEY `module_id` (`module_id`)
) $charset_collate";
}
private function create_404_sql( $prefix, $charset_collate ) {
return "CREATE TABLE IF NOT EXISTS `{$prefix}redirection_404` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`created` datetime NOT NULL,
`url` varchar(255) NOT NULL DEFAULT '',
`agent` varchar(255) DEFAULT NULL,
`referrer` varchar(255) DEFAULT NULL,
`ip` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `created` (`created`),
KEY `url` (`url`(191)),
KEY `referrer` (`referrer`(191)),
KEY `ip` (`ip`)
) $charset_collate";
}
}

View File

@@ -0,0 +1,182 @@
<?php
class Red_Apache_File extends Red_FileIO {
public function force_download() {
parent::force_download();
header( 'Content-Type: application/octet-stream' );
header( 'Content-Disposition: attachment; filename="' . $this->export_filename( 'htaccess' ) . '"' );
}
public function get_data( array $items, array $groups ) {
include_once dirname( dirname( __FILE__ ) ) . '/models/htaccess.php';
$htaccess = new Red_Htaccess();
foreach ( $items as $item ) {
$htaccess->add( $item );
}
return $htaccess->get() . PHP_EOL;
}
public function load( $group, $filename, $data ) {
// Remove any comments
$data = str_replace( "\n", "\r", $data );
// Split it into lines
$lines = array_filter( explode( "\r", $data ) );
$count = 0;
foreach ( (array) $lines as $line ) {
$item = $this->get_as_item( $line );
if ( $item ) {
$item['group_id'] = $group;
$redirect = Red_Item::create( $item );
if ( ! is_wp_error( $redirect ) ) {
$count++;
}
}
}
return $count;
}
public function get_as_item( $line ) {
$item = false;
if ( preg_match( '@rewriterule\s+(.*?)\s+(.*?)\s+(\[.*\])*@i', $line, $matches ) > 0 ) {
$item = array(
'url' => $this->regex_url( $matches[1] ),
'match_type' => 'url',
'action_type' => 'url',
'action_data' => array( 'url' => $this->decode_url( $matches[2] ) ),
'action_code' => $this->get_code( $matches[3] ),
'regex' => $this->is_regex( $matches[1] ),
);
} elseif ( preg_match( '@Redirect\s+(.*?)\s+"(.*?)"\s+(.*)@i', $line, $matches ) > 0 || preg_match( '@Redirect\s+(.*?)\s+(.*?)\s+(.*)@i', $line, $matches ) > 0 ) {
$item = array(
'url' => $this->decode_url( $matches[2] ),
'match_type' => 'url',
'action_type' => 'url',
'action_data' => array( 'url' => $this->decode_url( $matches[3] ) ),
'action_code' => $this->get_code( $matches[1] ),
);
} elseif ( preg_match( '@Redirect\s+"(.*?)"\s+(.*)@i', $line, $matches ) > 0 || preg_match( '@Redirect\s+(.*?)\s+(.*)@i', $line, $matches ) > 0 ) {
$item = array(
'url' => $this->decode_url( $matches[1] ),
'match_type' => 'url',
'action_type' => 'url',
'action_data' => array( 'url' => $this->decode_url( $matches[2] ) ),
'action_code' => 302,
);
} elseif ( preg_match( '@Redirectmatch\s+(.*?)\s+(.*?)\s+(.*)@i', $line, $matches ) > 0 ) {
$item = array(
'url' => $this->decode_url( $matches[2] ),
'match_type' => 'url',
'action_type' => 'url',
'action_data' => array( 'url' => $this->decode_url( $matches[3] ) ),
'action_code' => $this->get_code( $matches[1] ),
'regex' => true,
);
} elseif ( preg_match( '@Redirectmatch\s+(.*?)\s+(.*)@i', $line, $matches ) > 0 ) {
$item = array(
'url' => $this->decode_url( $matches[1] ),
'match_type' => 'url',
'action_type' => 'url',
'action_data' => array( 'url' => $this->decode_url( $matches[2] ) ),
'action_code' => 302,
'regex' => true,
);
}
if ( $item ) {
$item['action_type'] = 'url';
$item['match_type'] = 'url';
if ( $item['action_code'] === 0 ) {
$item['action_type'] = 'pass';
}
return $item;
}
return false;
}
private function decode_url( $url ) {
$url = rawurldecode( $url );
// Replace quoted slashes
$url = preg_replace( '@\\\/@', '/', $url );
// Ensure escaped '.' is still escaped
$url = preg_replace( '@\\\\.@', '\\\\.', $url );
return $url;
}
private function is_str_regex( $url ) {
$regex = '()[]$^?+.';
$escape = false;
for ( $x = 0; $x < strlen( $url ); $x++ ) {
$escape = false;
if ( $url{$x} === '\\' ) {
$escape = true;
} elseif ( strpos( $regex, $url{$x} ) !== false && ! $escape ) {
return true;
}
}
return false;
}
private function is_regex( $url ) {
if ( $this->is_str_regex( $url ) ) {
$tmp = ltrim( $url, '^' );
$tmp = rtrim( $tmp, '$' );
if ( $this->is_str_regex( $tmp ) ) {
return true;
}
}
return false;
}
private function regex_url( $url ) {
$url = $this->decode_url( $url );
if ( $this->is_str_regex( $url ) ) {
$tmp = ltrim( $url, '^' );
$tmp = rtrim( $tmp, '$' );
if ( $this->is_str_regex( $tmp ) ) {
return '^/' . ltrim( $tmp, '/' );
}
return '/' . ltrim( $tmp, '/' );
}
return $this->decode_url( $url );
}
private function get_code( $code ) {
if ( strpos( $code, '301' ) !== false || stripos( $code, 'permanent' ) !== false ) {
return 301;
} elseif ( strpos( $code, '302' ) !== false ) {
return 302;
} elseif ( strpos( $code, '307' ) !== false || stripos( $code, 'seeother' ) !== false ) {
return 307;
} elseif ( strpos( $code, '404' ) !== false || stripos( $code, 'forbidden' ) !== false || strpos( $code, 'F' ) !== false ) {
return 404;
} elseif ( strpos( $code, '410' ) !== false || stripos( $code, 'gone' ) !== false || strpos( $code, 'G' ) !== false ) {
return 410;
}
return 302;
}
}

View File

@@ -0,0 +1,124 @@
<?php
class Red_Csv_File extends Red_FileIO {
const CSV_SOURCE = 0;
const CSV_TARGET = 1;
const CSV_REGEX = 2;
const CSV_CODE = 3;
public function force_download() {
parent::force_download();
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment; filename="' . $this->export_filename( 'csv' ) . '"' );
}
public function get_data( array $items, array $groups ) {
$lines[] = implode( ',', array( 'source', 'target', 'regex', 'type', 'code', 'match', 'hits', 'title' ) );
foreach ( $items as $line ) {
$lines[] = $this->item_as_csv( $line );
}
return implode( PHP_EOL, $lines ) . PHP_EOL;
}
public function item_as_csv( $item ) {
$data = $item->match->get_data();
$data = isset( $data['url'] ) ? $data = $data['url'] : '*';
$csv = array(
$item->get_url(),
$data,
$item->is_regex() ? 1 : 0,
$item->get_action_type(),
$item->get_action_code(),
$item->get_action_type(),
$item->get_hits(),
$item->get_title(),
);
$csv = array_map( array( $this, 'escape_csv' ), $csv );
return join( $csv, ',' );
}
public function escape_csv( $item ) {
return '"' . str_replace( '"', '""', $item ) . '"';
}
public function load( $group, $filename, $data ) {
ini_set( 'auto_detect_line_endings', true );
$file = fopen( $filename, 'r' );
ini_set( 'auto_detect_line_endings', false );
$count = 0;
if ( $file ) {
$count = $this->load_from_file( $group, $file, ',' );
// Try again with semicolons - Excel often exports CSV with semicolons
if ( $count === 0 ) {
$count = $this->load_from_file( $group, $file, ';' );
}
}
return $count;
}
public function load_from_file( $group_id, $file, $separator ) {
$count = 0;
while ( ( $csv = fgetcsv( $file, 5000, $separator ) ) ) {
$item = $this->csv_as_item( $csv, $group_id );
if ( $item ) {
$created = Red_Item::create( $item );
if ( ! is_wp_error( $created ) ) {
$count++;
}
}
}
return $count;
}
private function get_valid_code( $code ) {
if ( get_status_header_desc( $code ) !== '' ) {
return intval( $code, 10 );
}
return 301;
}
public function csv_as_item( $csv, $group ) {
if ( count( $csv ) > 1 && $csv[ self::CSV_SOURCE ] !== 'source' && $csv[ self::CSV_TARGET ] !== 'target' ) {
return array(
'url' => trim( $csv[ self::CSV_SOURCE ] ),
'action_data' => array( 'url' => trim( $csv[ self::CSV_TARGET ] ) ),
'regex' => isset( $csv[ self::CSV_REGEX ] ) ? $this->parse_regex( $csv[ self::CSV_REGEX ] ) : $this->is_regex( $csv[ self::CSV_SOURCE ] ),
'group_id' => $group,
'match_type' => 'url',
'action_type' => 'url',
'action_code' => isset( $csv[ self::CSV_CODE ] ) ? $this->get_valid_code( $csv[ self::CSV_CODE ] ) : 301,
);
}
return false;
}
private function parse_regex( $value ) {
return intval( $value, 10 ) === 1 ? true : false;
}
private function is_regex( $url ) {
$regex = '()[]$^*';
if ( strpbrk( $url, $regex ) === false ) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,82 @@
<?php
class Red_Json_File extends Red_FileIO {
public function force_download() {
parent::force_download();
header( 'Content-Type: application/json' );
header( 'Content-Disposition: attachment; filename="' . $this->export_filename( 'json' ) . '"' );
}
public function get_data( array $items, array $groups ) {
$version = red_get_plugin_data( dirname( dirname( __FILE__ ) ) . '/redirection.php' );
$items = array(
'plugin' => array(
'version' => trim( $version['Version'] ),
'date' => date( 'r' ),
),
'groups' => $groups,
'redirects' => array_map( function( $item ) {
return $item->to_json();
}, $items ),
);
return wp_json_encode( $items, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES ) . PHP_EOL;
}
public function load( $group, $filename, $data ) {
global $wpdb;
$count = 0;
$json = @json_decode( $data, true );
if ( $json === false ) {
return 0;
}
// Import groups
$groups = array();
$group_map = array();
if ( isset( $json['groups'] ) ) {
foreach ( $json['groups'] as $group ) {
$old_group_id = $group['id'];
unset( $group['id'] );
$group = Red_Group::create( $group['name'], $group['module_id'], $group['enabled'] ? true : false );
if ( $group ) {
$group_map[ $old_group_id ] = $group->get_id();
}
}
}
unset( $json['groups'] );
// Import redirects
if ( isset( $json['redirects'] ) ) {
foreach ( $json['redirects'] as $pos => $redirect ) {
unset( $redirect['id'] );
if ( ! isset( $group_map[ $redirect['group_id'] ] ) ) {
$new_group = Red_Group::create( 'Group', 1 );
$group_map[ $redirect['group_id'] ] = $new_group->get_id();
}
if ( $redirect['match_type'] === 'url' && isset( $redirect['action_data'] ) && ! is_array( $redirect['action_data'] ) ) {
$redirect['action_data'] = array( 'url' => $redirect['action_data'] );
}
$redirect['group_id'] = $group_map[ $redirect['group_id'] ];
Red_Item::create( $redirect );
$count++;
// Helps reduce memory usage
unset( $json['redirects'][ $pos ] );
$wpdb->queries = array();
$wpdb->num_queries = 0;
}
}
return $count;
}
}

View File

@@ -0,0 +1,112 @@
<?php
class Red_Nginx_File extends Red_FileIO {
public function force_download() {
parent::force_download();
header( 'Content-Type: application/octet-stream' );
header( 'Content-Disposition: attachment; filename="' . $this->export_filename( 'nginx' ) . '"' );
}
public function get_data( array $items, array $groups ) {
$lines = array();
$version = red_get_plugin_data( dirname( dirname( __FILE__ ) ) . '/redirection.php' );
$lines[] = '# Created by Redirection';
$lines[] = '# ' . date( 'r' );
$lines[] = '# Redirection ' . trim( $version['Version'] ) . ' - https://redirection.me';
$lines[] = '';
$lines[] = 'server {';
$parts = array();
foreach ( $items as $item ) {
if ( $item->is_enabled() ) {
$parts[] = $this->get_nginx_item( $item );
}
}
$lines = array_merge( $lines, array_filter( $parts ) );
$lines[] = '}';
$lines[] = '';
$lines[] = '# End of Redirection';
return implode( PHP_EOL, $lines ) . PHP_EOL;
}
private function get_redirect_code( Red_Item $item ) {
if ( $item->get_action_code() === 301 ) {
return 'permanent';
}
return 'redirect';
}
function load( $group, $data, $filename = '' ) {
return 0;
}
private function get_nginx_item( Red_Item $item ) {
$target = 'add_' . $item->get_match_type();
if ( method_exists( $this, $target ) ) {
return ' ' . $this->$target( $item, $item->get_match_data() );
}
return false;
}
private function add_url( Red_Item $item, array $match_data ) {
return $this->get_redirect( $item->get_url(), $item->get_action_data(), $this->get_redirect_code( $item ), $match_data['source'] );
}
private function add_agent( Red_Item $item, array $match_data ) {
if ( $item->match->url_from ) {
$lines[] = 'if ( $http_user_agent ~* ^' . $item->match->user_agent . '$ ) {';
$lines[] = ' ' . $this->get_redirect( $item->get_url(), $item->match->url_from, $this->get_redirect_code( $item ), $match_data['source'] );
$lines[] = ' }';
}
if ( $item->match->url_notfrom ) {
$lines[] = 'if ( $http_user_agent !~* ^' . $item->match->user_agent . '$ ) {';
$lines[] = ' ' . $this->get_redirect( $item->get_url(), $item->match->url_notfrom, $this->get_redirect_code( $item ), $match_data['source'] );
$lines[] = ' }';
}
return implode( "\n", $lines );
}
private function add_referrer( Red_Item $item, array $match_data ) {
if ( $item->match->url_from ) {
$lines[] = 'if ( $http_referer ~* ^' . $item->match->referrer . '$ ) {';
$lines[] = ' ' . $this->get_redirect( $item->get_url(), $item->match->url_from, $this->get_redirect_code( $item ), $match_data['source'] );
$lines[] = ' }';
}
if ( $item->match->url_notfrom ) {
$lines[] = 'if ( $http_referer !~* ^' . $item->match->referrer . '$ ) {';
$lines[] = ' ' . $this->get_redirect( $item->get_url(), $item->match->url_notfrom, $this->get_redirect_code( $item ), $match_data['source'] );
$lines[] = ' }';
}
return implode( "\n", $lines );
}
private function get_redirect( $line, $target, $code, $source ) {
// Remove any existing start/end from a regex
$line = ltrim( $line, '^' );
$line = rtrim( $line, '$' );
if ( isset( $source['flag_case'] ) && $source['flag_case'] ) {
$line = '(?i)^' . $line;
} else {
$line = '^' . $line;
}
$line = preg_replace( "/[\r\n\t].*?$/s", '', $line );
$line = preg_replace( '/[^\PC\s]/u', '', $line );
$target = preg_replace( "/[\r\n\t].*?$/s", '', $target );
$target = preg_replace( '/[^\PC\s]/u', '', $target );
return 'rewrite ' . $line . '$ ' . $target . ' ' . $code . ';';
}
}

View File

@@ -0,0 +1,47 @@
<?php
class Red_Rss_File extends Red_FileIO {
public function force_download() {
header( 'Content-type: text/xml; charset=' . get_option( 'blog_charset' ), true );
}
public function get_data( array $items, array $groups ) {
$xml = '<?xml version="1.0" encoding="' . get_option( 'blog_charset' ) . '"?' . ">\r\n";
ob_start();
?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
<title>Redirection - <?php bloginfo_rss( 'name' ); ?></title>
<link><?php esc_url( bloginfo_rss( 'url' ) ); ?></link>
<description><?php esc_html( bloginfo_rss( 'description' ) ); ?></description>
<pubDate><?php echo esc_html( mysql2date( 'D, d M Y H:i:s +0000', get_lastpostmodified( 'GMT' ), false ) ); ?></pubDate>
<generator>
<?php echo esc_html( 'http://wordpress.org/?v=' ); ?>
<?php bloginfo_rss( 'version' ); ?>
</generator>
<language><?php echo esc_html( get_option( 'rss_language' ) ); ?></language>
<?php foreach ( $items as $log ) : ?>
<item>
<title><?php echo esc_html( $log->get_url() ); ?></title>
<link><![CDATA[<?php echo esc_url( home_url() ) . esc_url( $log->get_url() ); ?>]]></link>
<pubDate><?php echo esc_html( date( 'D, d M Y H:i:s +0000', intval( $log->get_last_hit(), 10 ) ) ); ?></pubDate>
<guid isPermaLink="false"><?php echo esc_html( $log->get_id() ); ?></guid>
<description><?php echo esc_html( $log->get_url() ); ?></description>
</item>
<?php endforeach; ?>
</channel>
</rss>
<?php
$xml .= ob_get_contents();
ob_end_clean();
return $xml;
}
function load( $group, $data, $filename = '' ) {
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,18 @@
<?php
include_once dirname( __FILE__ ) . '/http-header.php';
class Cookie_Match extends Header_Match {
public function name() {
return __( 'URL and cookie', 'redirection' );
}
public function is_match( $url ) {
if ( $this->regex ) {
$regex = new Red_Regex( $this->value, true );
return $regex->is_match( Redirection_Request::get_cookie( $this->name ) );
}
return Redirection_Request::get_cookie( $this->name ) === $this->value;
}
}

View File

@@ -0,0 +1,40 @@
<?php
class Custom_Match extends Red_Match {
use FromNotFrom_Match;
public $filter = '';
public function name() {
return __( 'URL and custom filter', 'redirection' );
}
public function save( array $details, $no_target_url = false ) {
$data = array(
'filter' => isset( $details['filter'] ) ? $this->sanitize_filter( $details['filter'] ) : '',
);
return $this->save_data( $details, $no_target_url, $data );
}
public function sanitize_filter( $name ) {
$name = preg_replace( '/[^A-Za-z0-9\-_]/', '', $name );
return trim( $name );
}
public function is_match( $url ) {
return apply_filters( $this->filter, false, $url );
}
public function get_data() {
return array_merge( array(
'filter' => $this->filter,
), $this->get_from_data() );
}
public function load( $values ) {
$values = $this->load_data( $values );
$this->filter = isset( $values['filter'] ) ? $values['filter'] : '';
}
}

View File

@@ -0,0 +1,59 @@
<?php
class Header_Match extends Red_Match {
use FromNotFrom_Match;
public $name;
public $value;
public $regex;
public function name() {
return __( 'URL and HTTP header', 'redirection' );
}
public function save( array $details, $no_target_url = false ) {
$data = array(
'regex' => isset( $details['regex'] ) && $details['regex'] ? true : false,
'name' => isset( $details['name'] ) ? $this->sanitize_name( $details['name'] ) : '',
'value' => isset( $details['value'] ) ? $this->sanitize_value( $details['value'] ) : '',
);
return $this->save_data( $details, $no_target_url, $data );
}
public function sanitize_name( $name ) {
$name = $this->sanitize_url( $name );
$name = str_replace( ' ', '', $name );
$name = preg_replace( '/[^A-Za-z0-9\-_]/', '', $name );
return trim( trim( $name, ':' ) );
}
public function sanitize_value( $value ) {
return $this->sanitize_url( $value );
}
public function is_match( $url ) {
if ( $this->regex ) {
$regex = new Red_Regex( $this->value, true );
return $regex->is_match( Redirection_Request::get_header( $this->name ) );
}
return Redirection_Request::get_header( $this->name ) === $this->value;
}
public function get_data() {
return array_merge( array(
'regex' => $this->regex,
'name' => $this->name,
'value' => $this->value,
), $this->get_from_data() );
}
public function load( $values ) {
$values = $this->load_data( $values );
$this->regex = isset( $values['regex'] ) ? $values['regex'] : false;
$this->name = isset( $values['name'] ) ? $values['name'] : '';
$this->value = isset( $values['value'] ) ? $values['value'] : '';
}
}

View File

@@ -0,0 +1,60 @@
<?php
class IP_Match extends Red_Match {
use FromNotFrom_Match;
public $ip = [];
public function name() {
return __( 'URL and IP', 'redirection' );
}
public function save( array $details, $no_target_url = false ) {
$data = array( 'ip' => isset( $details['ip'] ) && is_array( $details['ip'] ) ? $this->sanitize_ips( $details['ip'] ) : [] );
return $this->save_data( $details, $no_target_url, $data );
}
private function sanitize_single_ip( $ip ) {
$ip = @inet_pton( trim( $ip ) );
if ( $ip !== false ) {
return @inet_ntop( $ip ); // Convert back to string
}
return false;
}
private function sanitize_ips( $ips ) {
if ( is_array( $ips ) ) {
$ips = array_map( array( $this, 'sanitize_single_ip' ), $ips );
return array_values( array_filter( array_unique( $ips ) ) );
}
return array();
}
private function get_matching_ips( $match_ip ) {
$current_ip = @inet_pton( $match_ip );
return array_filter( $this->ip, function( $ip ) use ( $current_ip ) {
return @inet_pton( $ip ) === $current_ip;
} );
}
public function is_match( $url ) {
$matched = $this->get_matching_ips( Redirection_Request::get_ip() );
return count( $matched ) > 0;
}
public function get_data() {
return array_merge( array(
'ip' => $this->ip,
), $this->get_from_data() );
}
public function load( $values ) {
$values = $this->load_data( $values );
$this->ip = isset( $values['ip'] ) ? $values['ip'] : [];
}
}

View File

@@ -0,0 +1,54 @@
<?php
class Login_Match extends Red_Match {
public $logged_in;
public $logged_out;
public function name() {
return __( 'URL and login status', 'redirection' );
}
public function save( array $details, $no_target_url = false ) {
if ( $no_target_url ) {
return null;
}
return array(
'logged_in' => isset( $details['logged_in'] ) ? $this->sanitize_url( $details['logged_in'] ) : '',
'logged_out' => isset( $details['logged_out'] ) ? $this->sanitize_url( $details['logged_out'] ) : '',
);
}
public function is_match( $url ) {
return is_user_logged_in();
}
public function get_target_url( $requested_url, $source_url, Red_Source_Flags $flags, $match ) {
$target = false;
if ( $match && $this->logged_in !== '' ) {
$target = $this->logged_in;
} elseif ( ! $match && $this->logged_out !== '' ) {
$target = $this->logged_out;
}
if ( $flags->is_regex() && $target ) {
$target = $this->get_target_regex_url( $source_url, $target, $requested_url, $flags );
}
return $target;
}
public function get_data() {
return array(
'logged_in' => $this->logged_in,
'logged_out' => $this->logged_out,
);
}
public function load( $values ) {
$values = unserialize( $values );
$this->logged_in = isset( $values['logged_in'] ) ? $values['logged_in'] : '';
$this->logged_out = isset( $values['logged_out'] ) ? $values['logged_out'] : '';
}
}

View File

@@ -0,0 +1,36 @@
<?php
class Page_Match extends Red_Match {
use FromUrl_Match;
public $page;
public function name() {
return __( 'URL and WordPress page type', 'redirection' );
}
public function save( array $details, $no_target_url = false ) {
$data = array( 'page' => isset( $details['page'] ) ? $this->sanitize_page( $details['page'] ) : '404' );
return $this->save_data( $details, $no_target_url, $data );
}
private function sanitize_page( $page ) {
return '404';
}
public function is_match( $url ) {
return is_404();
}
public function get_data() {
return array_merge( array(
'page' => $this->page,
), $this->get_from_data() );
}
public function load( $values ) {
$values = $this->load_data( $values );
$this->page = isset( $values['page'] ) ? $values['page'] : '404';
}
}

View File

@@ -0,0 +1,47 @@
<?php
class Referrer_Match extends Red_Match {
use FromNotFrom_Match;
public $referrer;
public $regex;
public function name() {
return __( 'URL and referrer', 'redirection' );
}
public function save( array $details, $no_target_url = false ) {
$data = array(
'regex' => isset( $details['regex'] ) && $details['regex'] ? true : false,
'referrer' => isset( $details['referrer'] ) ? $this->sanitize_referrer( $details['referrer'] ) : '',
);
return $this->save_data( $details, $no_target_url, $data );
}
public function sanitize_referrer( $agent ) {
return $this->sanitize_url( $agent );
}
public function is_match( $url ) {
if ( $this->regex ) {
$regex = new Red_Regex( $this->referrer, true );
return $regex->is_match( Redirection_Request::get_referrer() );
}
return Redirection_Request::get_referrer() === $this->referrer;
}
public function get_data() {
return array_merge( array(
'regex' => $this->regex,
'referrer' => $this->referrer,
), $this->get_from_data() );
}
public function load( $values ) {
$values = $this->load_data( $values );
$this->regex = isset( $values['regex'] ) ? $values['regex'] : false;
$this->referrer = isset( $values['referrer'] ) ? $values['referrer'] : '';
}
}

View File

@@ -0,0 +1,48 @@
<?php
class Server_Match extends Red_Match {
use FromNotFrom_Match;
public $server;
public function name() {
return __( 'URL and server', 'redirection' );
}
public function save( array $details, $no_target_url = false ) {
$data = array( 'server' => isset( $details['server'] ) ? $this->sanitize_server( $details['server'] ) : '' );
return $this->save_data( $details, $no_target_url, $data );
}
private function sanitize_server( $server ) {
if ( strpos( $server, 'http' ) === false ) {
$server = ( is_ssl() ? 'https://' : 'http://' ) . $server;
}
$parts = wp_parse_url( $server );
if ( isset( $parts['host'] ) ) {
return $parts['scheme'] . '://' . $parts['host'];
}
return '';
}
public function is_match( $url ) {
$server = wp_parse_url( $this->server, PHP_URL_HOST );
return $server === Redirection_Request::get_server_name();
}
public function get_data() {
return array_merge( array(
'server' => $this->server,
), $this->get_from_data() );
}
public function load( $values ) {
$values = $this->load_data( $values );
$this->server = isset( $values['server'] ) ? $values['server'] : '';
}
}

View File

@@ -0,0 +1,50 @@
<?php
class URL_Match extends Red_Match {
public $url = false;
public function name() {
return __( 'URL only', 'redirection' );
}
public function save( array $details, $no_target_url = false ) {
$data = isset( $details['url'] ) ? $details['url'] : '';
if ( strlen( $data ) === 0 ) {
$data = '/';
}
if ( $no_target_url ) {
return null;
}
return $this->sanitize_url( $data );
}
public function is_match( $url ) {
return true;
}
public function get_target_url( $requested_url, $source_url, Red_Source_Flags $flags, $matched ) {
$target = $this->url;
if ( $flags->is_regex() ) {
$target = $this->get_target_regex_url( $source_url, $target, $requested_url, $flags );
}
return $target;
}
public function get_data() {
if ( $this->url ) {
return array(
'url' => $this->url,
);
}
return '';
}
public function load( $values ) {
$this->url = $values;
}
}

View File

@@ -0,0 +1,47 @@
<?php
class Agent_Match extends Red_Match {
use FromNotFrom_Match;
public $agent;
public $regex;
public function name() {
return __( 'URL and user agent', 'redirection' );
}
public function save( array $details, $no_target_url = false ) {
$data = array(
'regex' => isset( $details['regex'] ) && $details['regex'] ? true : false,
'agent' => isset( $details['agent'] ) ? $this->sanitize_agent( $details['agent'] ) : '',
);
return $this->save_data( $details, $no_target_url, $data );
}
private function sanitize_agent( $agent ) {
return $this->sanitize_url( $agent );
}
public function is_match( $url ) {
if ( $this->regex ) {
$regex = new Red_Regex( $this->agent, true );
return $regex->is_match( Redirection_Request::get_user_agent() );
}
return $this->agent === Redirection_Request::get_user_agent();
}
public function get_data() {
return array_merge( array(
'regex' => $this->regex,
'agent' => $this->agent,
), $this->get_from_data() );
}
public function load( $values ) {
$values = $this->load_data( $values );
$this->regex = isset( $values['regex'] ) ? $values['regex'] : false;
$this->agent = isset( $values['agent'] ) ? $values['agent'] : '';
}
}

View File

@@ -0,0 +1,32 @@
<?php
class Role_Match extends Red_Match {
use FromNotFrom_Match;
public $role;
public function name() {
return __( 'URL and role/capability', 'redirection' );
}
public function save( array $details, $no_target_url = false ) {
$data = array( 'role' => isset( $details['role'] ) ? $details['role'] : '' );
return $this->save_data( $details, $no_target_url, $data );
}
public function is_match( $url ) {
return current_user_can( $this->role );
}
public function get_data() {
return array_merge( array(
'role' => $this->role,
), $this->get_from_data() );
}
public function load( $values ) {
$values = $this->load_data( $values );
$this->role = isset( $values['role'] ) ? $values['role'] : '';
}
}

View File

@@ -0,0 +1,58 @@
<?php
abstract class Red_Action {
protected $code;
protected $type;
function __construct( $values ) {
if ( is_array( $values ) ) {
foreach ( $values as $key => $value ) {
$this->$key = $value;
}
}
}
static function create( $name, $code ) {
$avail = self::available();
if ( isset( $avail[ $name ] ) ) {
if ( ! class_exists( strtolower( $avail[ $name ][1] ) ) ) {
include_once dirname( __FILE__ ) . '/../actions/' . $avail[ $name ][0];
}
$obj = new $avail[ $name ][1]( array( 'code' => $code ) );
$obj->type = $name;
return $obj;
}
return false;
}
static function available() {
return array(
'url' => array( 'url.php', 'Url_Action' ),
'error' => array( 'error.php', 'Error_Action' ),
'nothing' => array( 'nothing.php', 'Nothing_Action' ),
'random' => array( 'random.php', 'Random_Action' ),
'pass' => array( 'pass.php', 'Pass_Action' ),
);
}
public function process_before( $code, $target ) {
return $target;
}
public function process_after( $code, $target ) {
return true;
}
public function get_code() {
return $this->code;
}
public function get_type() {
return $this->type;
}
abstract public function needs_target();
}

View File

@@ -0,0 +1,101 @@
<?php
abstract class Red_FileIO {
public static function create( $type ) {
$exporter = false;
if ( $type === 'rss' ) {
include_once dirname( dirname( __FILE__ ) ) . '/fileio/rss.php';
$exporter = new Red_Rss_File();
} elseif ( $type === 'csv' ) {
include_once dirname( dirname( __FILE__ ) ) . '/fileio/csv.php';
$exporter = new Red_Csv_File();
} elseif ( $type === 'apache' ) {
include_once dirname( dirname( __FILE__ ) ) . '/fileio/apache.php';
$exporter = new Red_Apache_File();
} elseif ( $type === 'nginx' ) {
include_once dirname( dirname( __FILE__ ) ) . '/fileio/nginx.php';
$exporter = new Red_Nginx_File();
} elseif ( $type === 'json' ) {
include_once dirname( dirname( __FILE__ ) ) . '/fileio/json.php';
$exporter = new Red_Json_File();
}
return $exporter;
}
public static function import( $group_id, $file ) {
$parts = pathinfo( $file['name'] );
$extension = isset( $parts['extension'] ) ? $parts['extension'] : '';
$extension = strtolower( $extension );
if ( $extension === 'csv' ) {
include_once dirname( dirname( __FILE__ ) ) . '/fileio/csv.php';
$importer = new Red_Csv_File();
$data = '';
} elseif ( $extension === 'json' ) {
include_once dirname( dirname( __FILE__ ) ) . '/fileio/json.php';
$importer = new Red_Json_File();
$data = @file_get_contents( $file['tmp_name'] );
} else {
include_once dirname( dirname( __FILE__ ) ) . '/fileio/apache.php';
$importer = new Red_Apache_File();
$data = @file_get_contents( $file['tmp_name'] );
}
if ( $extension !== 'json' ) {
$group = Red_Group::get( $group_id );
if ( ! $group ) {
return false;
}
}
return $importer->load( $group_id, $file['tmp_name'], $data );
}
public function force_download() {
header( 'Cache-Control: no-cache, must-revalidate' );
header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
}
protected function export_filename( $extension ) {
$name = wp_parse_url( home_url(), PHP_URL_HOST );
$name = str_replace( '.', '-', $name );
$date = strtolower( date_i18n( get_option( 'date_format' ) ) );
$date = str_replace( [ ',', ' ', '--' ], '-', $date );
return 'redirection-' . $name . '-' . $date . '.' . $extension;
}
public static function export( $module_name_or_id, $format ) {
$groups = false;
$items = false;
if ( $module_name_or_id === 'all' || $module_name_or_id === 0 ) {
$groups = Red_Group::get_all();
$items = Red_Item::get_all();
} else {
$module_name_or_id = is_numeric( $module_name_or_id ) ? $module_name_or_id : Red_Module::get_id_for_name( $module_name_or_id );
$module = Red_Module::get( intval( $module_name_or_id, 10 ) );
if ( $module ) {
$groups = Red_Group::get_all_for_module( $module->get_id() );
$items = Red_Item::get_all_for_module( $module->get_id() );
}
}
$exporter = self::create( $format );
if ( $exporter && $items !== false && $groups !== false ) {
return array(
'data' => $exporter->get_data( $items, $groups ),
'total' => count( $items ),
'exporter' => $exporter,
);
}
return false;
}
abstract function get_data( array $items, array $groups );
abstract function load( $group, $filename, $data );
}

View File

@@ -0,0 +1,164 @@
<?php
include_once dirname( REDIRECTION_FILE ) . '/database/database.php';
class Red_Fixer {
public function get_json() {
return [
'status' => $this->get_status(),
'debug' => $this->get_debug(),
];
}
public function get_debug() {
$status = new Red_Database_Status();
return [
'database' => [
'current' => $status->get_current_version(),
'latest' => REDIRECTION_DB_VERSION,
],
'ip_header' => [
'HTTP_CF_CONNECTING_IP' => isset( $_SERVER['HTTP_CF_CONNECTING_IP'] ) ? $_SERVER['HTTP_CF_CONNECTING_IP'] : false,
'HTTP_X_FORWARDED_FOR' => isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : false,
'REMOTE_ADDR' => isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : false,
],
];
}
public function save_debug( $name, $value ) {
if ( $name === 'database' ) {
$database = new Red_Database();
$status = new Red_Database_Status();
foreach ( $database->get_upgrades() as $upgrade ) {
if ( $value === $upgrade['version'] ) {
$status->finish();
$status->save_db_version( $value );
break;
}
}
}
}
public function get_status() {
global $wpdb;
$options = red_get_options();
$groups = intval( $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}redirection_groups" ), 10 );
$bad_group = $this->get_missing();
$monitor_group = $options['monitor_post'];
$valid_monitor = Red_Group::get( $monitor_group ) || $monitor_group === 0;
return [
array_merge( [
'id' => 'db',
'name' => __( 'Database tables', 'redirection' ),
], $this->get_database_status( Red_Database::get_latest_database() ) ),
[
'name' => __( 'Valid groups', 'redirection' ),
'id' => 'groups',
'message' => $groups === 0 ? __( 'No valid groups, so you will not be able to create any redirects', 'redirection' ) : __( 'Valid groups detected', 'redirection' ),
'status' => $groups === 0 ? 'problem' : 'good',
],
[
'name' => __( 'Valid redirect group', 'redirection' ),
'id' => 'redirect_groups',
'message' => count( $bad_group ) > 0 ? __( 'Redirects with invalid groups detected', 'redirection' ) : __( 'All redirects have a valid group', 'redirection' ),
'status' => count( $bad_group ) > 0 ? 'problem' : 'good',
],
[
'name' => __( 'Post monitor group', 'redirection' ),
'id' => 'monitor',
'message' => $valid_monitor === false ? __( 'Post monitor group is invalid', 'redirection' ) : __( 'Post monitor group is valid', 'redirection' ),
'status' => $valid_monitor === false ? 'problem' : 'good',
],
$this->get_http_settings(),
];
}
private function get_database_status( $database ) {
$missing = $database->get_missing_tables();
return array(
'status' => count( $missing ) === 0 ? 'good' : 'error',
'message' => count( $missing ) === 0 ? __( 'All tables present', 'redirection' ) : __( 'The following tables are missing:', 'redirection' ) . ' ' . join( ',', $missing ),
);
}
private function get_http_settings() {
$site = wp_parse_url( get_site_url(), PHP_URL_SCHEME );
$home = wp_parse_url( get_home_url(), PHP_URL_SCHEME );
$message = __( 'Site and home are consistent', 'redirection' );
if ( $site !== $home ) {
/* translators: 1: Site URL, 2: Home URL */
$message = sprintf( __( 'Site and home URL are inconsistent. Please correct from your Settings > General page: %1$1s is not %2$2s', 'redirection' ), get_site_url(), get_home_url() );
}
return array(
'name' => __( 'Site and home protocol', 'redirection' ),
'id' => 'redirect_url',
'message' => $message,
'status' => $site === $home ? 'good' : 'problem',
);
}
public function fix( $status ) {
foreach ( $status as $item ) {
if ( $item['status'] !== 'good' ) {
$fixer = 'fix_' . $item['id'];
if ( method_exists( $this, $fixer ) ) {
$result = $this->$fixer();
}
if ( is_wp_error( $result ) ) {
return $result;
}
}
}
return $this->get_status();
}
private function get_missing() {
global $wpdb;
return $wpdb->get_results( "SELECT {$wpdb->prefix}redirection_items.id FROM {$wpdb->prefix}redirection_items LEFT JOIN {$wpdb->prefix}redirection_groups ON {$wpdb->prefix}redirection_items.group_id = {$wpdb->prefix}redirection_groups.id WHERE {$wpdb->prefix}redirection_groups.id IS NULL" );
}
private function fix_db() {
$database = Red_Database::get_latest_database();
return $database->install();
}
private function fix_groups() {
if ( Red_Group::create( 'new group', 1 ) === false ) {
return new WP_Error( __( 'Unable to create group', 'redirection' ) );
}
return true;
}
private function fix_redirect_groups() {
global $wpdb;
$missing = $this->get_missing();
foreach ( $missing as $row ) {
$wpdb->update( $wpdb->prefix . 'redirection_items', array( 'group_id' => $this->get_valid_group() ), array( 'id' => $row->id ) );
}
}
private function fix_monitor() {
red_set_options( array( 'monitor_post' => $this->get_valid_group() ) );
}
private function get_valid_group() {
$groups = Red_Group::get_all();
return $groups[0]['id'];
}
}

View File

@@ -0,0 +1,69 @@
<?php
class Red_Flusher {
const DELETE_HOOK = 'redirection_log_delete';
const DELETE_FREQ = 'daily';
const DELETE_MAX = 3000;
const DELETE_KEEP_ON = 10; // 10 minutes
public function flush() {
$options = red_get_options();
$total = $this->expire_logs( 'redirection_logs', $options['expire_redirect'] );
$total += $this->expire_logs( 'redirection_404', $options['expire_404'] );
if ( $total >= self::DELETE_MAX ) {
$next = time() + ( self::DELETE_KEEP_ON * 60 );
// There are still more logs to clear - keep on doing until we're clean or until the next normal event
if ( $next < wp_next_scheduled( self::DELETE_HOOK ) ) {
wp_schedule_single_event( $next, self::DELETE_HOOK );
}
}
$this->optimize_logs();
}
private function optimize_logs() {
global $wpdb;
$rand = wp_rand( 1, 5000 );
if ( $rand === 11 ) {
$wpdb->query( "OPTIMIZE TABLE {$wpdb->prefix}redirection_logs" );
} elseif ( $rand === 12 ) {
$wpdb->query( "OPTIMIZE TABLE {$wpdb->prefix}redirection_404" );
}
}
private function expire_logs( $table, $expiry_time ) {
global $wpdb;
if ( $expiry_time > 0 ) {
$logs = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}{$table} WHERE created < DATE_SUB(NOW(), INTERVAL %d DAY)", $expiry_time ) );
if ( $logs > 0 ) {
$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}{$table} WHERE created < DATE_SUB(NOW(), INTERVAL %d DAY) LIMIT %d", $expiry_time, self::DELETE_MAX ) );
return min( self::DELETE_MAX, $logs );
}
}
return 0;
}
public static function schedule() {
$options = red_get_options();
if ( $options['expire_redirect'] > 0 || $options['expire_404'] > 0 ) {
if ( ! wp_next_scheduled( self::DELETE_HOOK ) ) {
wp_schedule_event( time(), self::DELETE_FREQ, self::DELETE_HOOK );
}
} else {
Red_Flusher::clear();
}
}
public static function clear() {
wp_clear_scheduled_hook( self::DELETE_HOOK );
}
}

View File

@@ -0,0 +1,255 @@
<?php
class Red_Group {
private $items = 0;
private $name;
private $module_id;
private $status;
private $position;
public function __construct( $values = '' ) {
if ( is_object( $values ) ) {
$this->name = $values->name;
$this->module_id = intval( $values->module_id, 10 );
$this->status = $values->status;
$this->id = intval( $values->id, 10 );
$this->position = intval( $values->position, 10 );
}
}
public function get_name() {
return $this->name;
}
public function get_id() {
return $this->id;
}
public function is_enabled() {
return $this->status === 'enabled' ? true : false;
}
static function get( $id ) {
global $wpdb;
$row = $wpdb->get_row( $wpdb->prepare( "SELECT {$wpdb->prefix}redirection_groups.*,COUNT( {$wpdb->prefix}redirection_items.id ) AS items,SUM( {$wpdb->prefix}redirection_items.last_count ) AS redirects FROM {$wpdb->prefix}redirection_groups LEFT JOIN {$wpdb->prefix}redirection_items ON {$wpdb->prefix}redirection_items.group_id={$wpdb->prefix}redirection_groups.id WHERE {$wpdb->prefix}redirection_groups.id=%d GROUP BY {$wpdb->prefix}redirection_groups.id", $id ) );
if ( $row ) {
return new Red_Group( $row );
}
return false;
}
static function get_all() {
global $wpdb;
$data = array();
$rows = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}redirection_groups" );
if ( $rows ) {
foreach ( $rows as $row ) {
$group = new Red_Group( $row );
$data[] = $group->to_json();
}
}
return $data;
}
static function get_all_for_module( $module_id ) {
global $wpdb;
$data = array();
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}redirection_groups WHERE module_id=%d", $module_id ) );
if ( $rows ) {
foreach ( $rows as $row ) {
$group = new Red_Group( $row );
$data[] = $group->to_json();
}
}
return $data;
}
static function get_for_select() {
global $wpdb;
$data = array();
$rows = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}redirection_groups" );
if ( $rows ) {
foreach ( $rows as $row ) {
$module = Red_Module::get( $row->module_id );
if ( $module ) {
$data[ $module->get_name() ][ intval( $row->id, 10 ) ] = $row->name;
}
}
}
return $data;
}
static function create( $name, $module_id, $enabled = true ) {
global $wpdb;
$name = trim( substr( $name, 0, 50 ) );
$module_id = intval( $module_id, 10 );
if ( $name !== '' && Red_Module::is_valid_id( $module_id ) ) {
$position = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( * ) FROM {$wpdb->prefix}redirection_groups WHERE module_id=%d", $module_id ) );
$data = array(
'name' => trim( $name ),
'module_id' => intval( $module_id ),
'position' => intval( $position ),
'status' => $enabled ? 'enabled' : 'disabled',
);
$wpdb->insert( $wpdb->prefix . 'redirection_groups', $data );
return Red_Group::get( $wpdb->insert_id );
}
return false;
}
public function update( $data ) {
global $wpdb;
$old_id = $this->module_id;
$this->name = trim( wp_kses( $data['name'], array() ) );
if ( Red_Module::is_valid_id( intval( $data['moduleId'], 10 ) ) ) {
$this->module_id = intval( $data['moduleId'], 10 );
}
$wpdb->update( $wpdb->prefix . 'redirection_groups', array( 'name' => $this->name, 'module_id' => $this->module_id ), array( 'id' => intval( $this->id ) ) );
if ( $old_id !== $this->module_id ) {
Red_Module::flush_by_module( $old_id );
Red_Module::flush_by_module( $this->module_id );
}
return true;
}
public function delete() {
global $wpdb;
// Delete all items in this group
$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}redirection_items WHERE group_id=%d", $this->id ) );
Red_Module::flush( $this->id );
// Delete the group
$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->prefix}redirection_groups WHERE id=%d", $this->id ) );
if ( $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}redirection_groups" ) === 0 ) {
$wpdb->insert( $wpdb->prefix . 'redirection_groups', array( 'name' => __( 'Redirections' ), 'module_id' => 1, 'position' => 0 ) );
}
}
public function get_total_redirects() {
global $wpdb;
return intval( $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->prefix}redirection_items WHERE group_id=%d", $this->id ) ), 10 );
}
public function enable() {
global $wpdb;
$wpdb->update( $wpdb->prefix . 'redirection_groups', array( 'status' => 'enabled' ), array( 'id' => $this->id ) );
$wpdb->update( $wpdb->prefix . 'redirection_items', array( 'status' => 'enabled' ), array( 'group_id' => $this->id ) );
Red_Module::flush( $this->id );
}
public function disable() {
global $wpdb;
$wpdb->update( $wpdb->prefix . 'redirection_groups', array( 'status' => 'disabled' ), array( 'id' => $this->id ) );
$wpdb->update( $wpdb->prefix . 'redirection_items', array( 'status' => 'disabled' ), array( 'group_id' => $this->id ) );
Red_Module::flush( $this->id );
}
public function get_module_id() {
return $this->module_id;
}
public static function get_filtered( array $params ) {
global $wpdb;
$orderby = 'id';
$direction = 'DESC';
$limit = RED_DEFAULT_PER_PAGE;
$offset = 0;
$where = '';
if ( isset( $params['orderby'] ) && in_array( $params['orderby'], array( 'name' ), true ) ) {
$orderby = $params['orderby'];
}
if ( isset( $params['direction'] ) && in_array( $params['direction'], array( 'asc', 'desc' ), true ) ) {
$direction = strtoupper( $params['direction'] );
}
if ( isset( $params['filter'] ) && strlen( $params['filter'] ) > 0 ) {
if ( isset( $params['filterBy'] ) && $params['filterBy'] === 'module' ) {
$where = $wpdb->prepare( 'WHERE module_id=%d', intval( $params['filter'], 10 ) );
} else {
$where = $wpdb->prepare( 'WHERE name LIKE %s', '%' . $wpdb->esc_like( trim( $params['filter'] ) ) . '%' );
}
}
if ( isset( $params['per_page'] ) ) {
$limit = intval( $params['per_page'], 10 );
$limit = min( RED_MAX_PER_PAGE, $limit );
$limit = max( 5, $limit );
}
if ( isset( $params['page'] ) ) {
$offset = intval( $params['page'], 10 );
$offset = max( 0, $offset );
$offset *= $limit;
}
$rows = $wpdb->get_results(
"SELECT * FROM {$wpdb->prefix}redirection_groups $where " . $wpdb->prepare( "ORDER BY $orderby $direction LIMIT %d,%d", $offset, $limit )
);
$total_items = intval( $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->prefix}redirection_groups " . $where ) );
$items = array();
$options = red_get_options();
foreach ( $rows as $row ) {
$group = new Red_Group( $row );
$group_json = $group->to_json();
if ( $group->get_id() === $options['last_group_id'] ) {
$group_json['default'] = true;
}
$items[] = $group_json;
}
return array(
'items' => $items,
'total' => intval( $total_items, 10 ),
);
}
public function to_json() {
$module = Red_Module::get( $this->get_module_id() );
return array(
'id' => $this->get_id(),
'name' => $this->get_name(),
'redirects' => $this->get_total_redirects(),
'module_id' => $this->get_module_id(),
'moduleName' => $module ? $module->get_name() : '',
'enabled' => $this->is_enabled(),
);
}
}

Some files were not shown because too many files have changed in this diff Show More