/**
* Copyright (C) 2014-2020 ServMask Inc.
*
* 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 .
*
* ███████╗███████╗██████╗ ██╗ ██╗███╗ ███╗ █████╗ ███████╗██╗ ██╗
* ██╔════╝██╔════╝██╔══██╗██║ ██║████╗ ████║██╔══██╗██╔════╝██║ ██╔╝
* ███████╗█████╗ ██████╔╝██║ ██║██╔████╔██║███████║███████╗█████╔╝
* ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██║╚██╔╝██║██╔══██║╚════██║██╔═██╗
* ███████║███████╗██║ ██║ ╚████╔╝ ██║ ╚═╝ ██║██║ ██║███████║██║ ██╗
* ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
*/
if ( ! defined( 'ABSPATH' ) ) {
die( 'Kangaroos cannot jump here' );
}
/**
* Get retention.json absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wmue_retention_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WMUE_RETENTION_NAME;
}
/**
* Check whether export/import is running
*
* @return boolean
*/
function ai1wmue_is_running() {
if ( isset( $_GET['file'] ) || isset( $_POST['file'] ) ) {
return true;
}
return false;
}
/**
* Check if the base plugin is installed
*
* @return boolean
*/
function ai1wmue_is_base_plugin_installed() {
return file_exists( WP_PLUGIN_DIR . '/all-in-one-wp-migration/all-in-one-wp-migration.php' );
}
/**
* Check if the base plugin is activated
*
* @return boolean
*/
function ai1wmue_is_base_plugin_active() {
return is_plugin_active( 'all-in-one-wp-migration/all-in-one-wp-migration.php' );
}
/**
* Install the base plugin from WordPress repository
*
* @return boolean|WP_Error
*/
function ai1wmue_install_base_plugin() {
if ( ! function_exists( 'plugins_api' ) ) {
require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
}
if ( ! class_exists( 'WP_Upgrader', false ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
}
$api = plugins_api(
'plugin_information',
array(
'slug' => 'all-in-one-wp-migration',
'fields' => array(
'short_description' => false,
'sections' => false,
'requires' => false,
'rating' => false,
'ratings' => false,
'downloaded' => false,
'last_updated' => false,
'added' => false,
'tags' => false,
'compatibility' => false,
'homepage' => false,
'donate_link' => false,
),
)
);
if ( is_wp_error( $api ) ) {
return $api;
}
$upgrader = new Plugin_Upgrader( new WP_Ajax_Upgrader_Skin() );
$result = $upgrader->install( $api->download_link );
return $result;
}/**
* Copyright (C) 2014-2023 ServMask Inc.
*
* 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 .
*
* ███████╗███████╗██████╗ ██╗ ██╗███╗ ███╗ █████╗ ███████╗██╗ ██╗
* ██╔════╝██╔════╝██╔══██╗██║ ██║████╗ ████║██╔══██╗██╔════╝██║ ██╔╝
* ███████╗█████╗ ██████╔╝██║ ██║██╔████╔██║███████║███████╗█████╔╝
* ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██║╚██╔╝██║██╔══██║╚════██║██╔═██╗
* ███████║███████╗██║ ██║ ╚████╔╝ ██║ ╚═╝ ██║██║ ██║███████║██║ ██╗
* ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
*/
if ( ! defined( 'ABSPATH' ) ) {
die( 'Kangaroos cannot jump here' );
}
if ( ! class_exists( 'Ai1wmve_Schedule_Event_Log' ) ) {
class Ai1wmve_Schedule_Event_Log {
const MAX_RECORDS = 30;
protected $event_id;
protected $records = array();
public function __construct( $event_id ) {
$this->event_id = $event_id;
$this->load();
}
public function load() {
$this->records = get_option( Ai1wmve_Schedule_Event::option_key( 'log', $this->event_id ), array() );
}
public function save() {
if ( count( $this->records ) > self::MAX_RECORDS ) {
array_pop( $this->records );
}
update_option( Ai1wmve_Schedule_Event::option_key( 'log', $this->event_id ), $this->records );
}
public function add( $status, $message = null ) {
$data = array(
'time' => (int) get_date_from_gmt( 'now', 'U' ),
'status' => $status,
'message' => $message,
);
array_unshift( $this->records, $data );
$this->save();
}
public function records() {
return $this->records;
}
}
}/**
* Copyright (C) 2014-2020 ServMask Inc.
*
* 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 .
*
* ███████╗███████╗██████╗ ██╗ ██╗███╗ ███╗ █████╗ ███████╗██╗ ██╗
* ██╔════╝██╔════╝██╔══██╗██║ ██║████╗ ████║██╔══██╗██╔════╝██║ ██╔╝
* ███████╗█████╗ ██████╔╝██║ ██║██╔████╔██║███████║███████╗█████╔╝
* ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██║╚██╔╝██║██╔══██║╚════██║██╔═██╗
* ███████║███████╗██║ ██║ ╚████╔╝ ██║ ╚═╝ ██║██║ ██║███████║██║ ██╗
* ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
*/
if ( ! defined( 'ABSPATH' ) ) {
die( 'Kangaroos cannot jump here' );
}
class Ai1wmue_Eula_Controller {
/**
* Check if EULA needs to be displayed
*
* @return boolean
*/
public static function should_display_eula() {
// Only show on admin pages
if ( ! is_admin() ) {
return false;
}
// Check if user has capability to manage plugins
if ( ! current_user_can( 'activate_plugins' ) ) {
return false;
}
// Additional check: verify the plugin is actually active
if ( ! is_plugin_active( AI1WMUE_PLUGIN_BASENAME ) ) {
return false;
}
// Check if EULA has been accepted for current version
$accepted_version = get_option( 'ai1wmue_eula_accepted_version', '' );
// Show EULA if not accepted or if version has changed
return ( $accepted_version !== AI1WMUE_EULA_VERSION );
}
/**
* Display EULA modal
*
* @return void
*/
public static function display_eula_modal() {
if ( ! self::should_display_eula() ) {
return;
}
// Read EULA content securely
$eula_path = AI1WMUE_PATH . DIRECTORY_SEPARATOR . 'End-User-License-Agreement.txt';
$eula_content = '';
// Validate file path is within plugin directory
$real_path = realpath( $eula_path );
$plugin_path = realpath( AI1WMUE_PATH );
if ( $real_path && $plugin_path && strpos( $real_path, $plugin_path ) === 0 && file_exists( $eula_path ) ) {
$eula_content = file_get_contents( $eula_path );
}
// Enqueue styles
if ( is_rtl() ) {
wp_enqueue_style(
'ai1wmue_eula_modal',
Ai1wm_Template::asset_link( 'css/eula-modal.min.rtl.css', 'AI1WMUE' ),
array( 'ai1wm_servmask' )
);
} else {
wp_enqueue_style(
'ai1wmue_eula_modal',
Ai1wm_Template::asset_link( 'css/eula-modal.min.css', 'AI1WMUE' ),
array( 'ai1wm_servmask' )
);
}
// Enqueue scripts
wp_enqueue_script(
'ai1wmue_eula_modal',
Ai1wm_Template::asset_link( 'javascript/eula-modal.min.js', 'AI1WMUE' ),
array( 'jquery' )
);
// Check if this is an update scenario (only for versions after 1.0)
$is_update = get_option( 'ai1wmue_eula_accepted', false ) && get_option( 'ai1wmue_eula_accepted_version', '' ) !== AI1WMUE_EULA_VERSION && AI1WMUE_EULA_VERSION !== '1.0';
// Localize script
wp_localize_script(
'ai1wmue_eula_modal',
'ai1wmue_eula',
array(
'ajax' => array(
'url' => wp_make_link_relative( admin_url( 'admin-ajax.php?action=ai1wmue_eula_response' ) ),
),
'secret_key' => get_option( AI1WM_SECRET_KEY ),
'nonce' => wp_create_nonce( 'ai1wmue_eula_action' ),
'show_eula' => true,
'is_update' => $is_update,
'confirm_decline' => __( 'Are you sure you want to decline the EULA? The Unlimited Extension plugin will be deactivated.', AI1WMUE_PLUGIN_NAME ),
'plugins_url' => network_admin_url( 'plugins.php' ),
)
);
// Render modal
Ai1wm_Template::render(
'eula/eula-modal',
array(
'eula_content' => $eula_content,
'is_update' => $is_update,
),
AI1WMUE_TEMPLATES_PATH
);
}
/**
* Handle EULA response
*
* @return void
*/
public static function eula_response() {
// Verify request
ai1wm_setup_environment();
// Params
$params = stripslashes_deep( $_POST );
// Verify nonce
if ( ! isset( $params['nonce'] ) || ! wp_verify_nonce( $params['nonce'], 'ai1wmue_eula_action' ) ) {
wp_send_json_error( array( 'message' => __( 'Security check failed. Please refresh the page and try again.', AI1WMUE_PLUGIN_NAME ) ) );
}
// Verify secret key
$secret_key = isset( $params['secret_key'] ) ? trim( $params['secret_key'] ) : null;
try {
ai1wm_verify_secret_key( $secret_key );
} catch ( Ai1wm_Not_Valid_Secret_Key_Exception $e ) {
wp_send_json_error( array( 'message' => $e->getMessage() ) );
}
// Check capability
if ( ! current_user_can( 'activate_plugins' ) ) {
wp_send_json_error( array( 'message' => __( 'Insufficient permissions.', AI1WMUE_PLUGIN_NAME ) ) );
}
// Sanitize and validate action
$user_action = isset( $params['eula_action'] ) ? sanitize_text_field( $params['eula_action'] ) : '';
// Whitelist allowed actions
$allowed_actions = array( 'accept', 'decline' );
if ( ! in_array( $user_action, $allowed_actions, true ) ) {
wp_send_json_error( array( 'message' => __( 'Invalid action.', AI1WMUE_PLUGIN_NAME ) ) );
}
if ( $user_action === 'accept' ) {
// Store acceptance with version
update_option( 'ai1wmue_eula_accepted', true );
update_option( 'ai1wmue_eula_accepted_version', AI1WMUE_EULA_VERSION );
update_option( 'ai1wmue_eula_accepted_date', current_time( 'mysql' ) );
update_option( 'ai1wmue_eula_accepted_by', get_current_user_id() );
wp_send_json_success();
} elseif ( $user_action === 'decline' ) {
// Deactivate plugin
deactivate_plugins( AI1WMUE_PLUGIN_BASENAME );
wp_send_json_success();
}
}
}/**
* Copyright (C) 2014-2025 ServMask Inc.
*
* 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 .
*
* Attribution: This code is part of the All-in-One WP Migration plugin, developed by
*
* ███████╗███████╗██████╗ ██╗ ██╗███╗ ███╗ █████╗ ███████╗██╗ ██╗
* ██╔════╝██╔════╝██╔══██╗██║ ██║████╗ ████║██╔══██╗██╔════╝██║ ██╔╝
* ███████╗█████╗ ██████╔╝██║ ██║██╔████╔██║███████║███████╗█████╔╝
* ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██║╚██╔╝██║██╔══██║╚════██║██╔═██╗
* ███████║███████╗██║ ██║ ╚████╔╝ ██║ ╚═╝ ██║██║ ██║███████║██║ ██╗
* ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
*/
if ( ! defined( 'ABSPATH' ) ) {
die( 'Kangaroos cannot jump here' );
}
/**
* Get storage absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_storage_path( $params ) {
if ( empty( $params['storage'] ) ) {
throw new Ai1wm_Storage_Exception(
wp_kses(
__( 'Could not locate the storage path. The process cannot continue. Technical details', 'all-in-one-wp-migration' ),
ai1wm_allowed_html_tags()
)
);
}
// Validate storage path
if ( ai1wm_validate_file( $params['storage'] ) !== 0 ) {
throw new Ai1wm_Storage_Exception(
wp_kses(
__( 'Your storage directory name contains invalid characters: < > : " | ? * \0. It must not include these characters. The process cannot continue. Technical details', 'all-in-one-wp-migration' ),
ai1wm_allowed_html_tags()
)
);
}
// Get storage path
$storage = AI1WM_STORAGE_PATH . DIRECTORY_SEPARATOR . basename( $params['storage'] );
if ( ! is_dir( $storage ) ) {
mkdir( $storage, 0777, true );
}
return $storage;
}
/**
* Get backup absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_backup_path( $params ) {
if ( empty( $params['archive'] ) ) {
throw new Ai1wm_Archive_Exception(
wp_kses(
__( 'Could not locate the archive path. The process cannot continue. Technical details', 'all-in-one-wp-migration' ),
ai1wm_allowed_html_tags()
)
);
}
// Validate archive path
if ( ai1wm_validate_file( $params['archive'] ) !== 0 ) {
throw new Ai1wm_Archive_Exception(
wp_kses(
__( 'Your archive file name contains invalid characters: < > : " | ? * \0. It must not include these characters. The process cannot continue. Technical details', 'all-in-one-wp-migration' ),
ai1wm_allowed_html_tags()
)
);
}
// Validate file extension
if ( ! ai1wm_is_filename_supported( $params['archive'] ) ) {
throw new Ai1wm_Archive_Exception(
wp_kses(
__( 'Invalid archive file type. Only .wpress files are allowed. The process cannot continue. Technical details', 'all-in-one-wp-migration' ),
ai1wm_allowed_html_tags()
)
);
}
return AI1WM_BACKUPS_PATH . DIRECTORY_SEPARATOR . $params['archive'];
}
/**
* Validates a file name and path against an allowed set of rules
*
* @param string $file File path
* @param array $allowed_files Array of allowed files
* @return integer
*/
function ai1wm_validate_file( $file, $allowed_files = array() ) {
$file = str_replace( '\\', '/', $file );
// Validates special characters that are illegal in filenames on certain
// operating systems and special characters requiring special escaping
// to manipulate at the command line
$invalid_chars = array( '<', '>', ':', '"', '|', '?', '*', chr( 0 ) );
foreach ( $invalid_chars as $char ) {
if ( strpos( $file, $char ) !== false ) {
return 1;
}
}
return validate_file( $file, $allowed_files );
}
/**
* Get archive absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_archive_path( $params ) {
if ( empty( $params['archive'] ) ) {
throw new Ai1wm_Archive_Exception(
wp_kses(
__( 'Could not locate the archive path. The process cannot continue. Technical details', 'all-in-one-wp-migration' ),
ai1wm_allowed_html_tags()
)
);
}
// Validate archive path
if ( ai1wm_validate_file( $params['archive'] ) !== 0 ) {
throw new Ai1wm_Archive_Exception(
wp_kses(
__( 'Your archive file name contains invalid characters: < > : " | ? * \0. It must not include these characters. The process cannot continue. Technical details', 'all-in-one-wp-migration' ),
ai1wm_allowed_html_tags()
)
);
}
// Validate file extension
if ( ! ai1wm_is_filename_supported( $params['archive'] ) ) {
throw new Ai1wm_Archive_Exception(
wp_kses(
__( 'Invalid archive file type. Only .wpress files are allowed. The process cannot continue. Technical details', 'all-in-one-wp-migration' ),
ai1wm_allowed_html_tags()
)
);
}
// Get archive path
if ( empty( $params['ai1wm_manual_restore'] ) ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . $params['archive'];
}
return ai1wm_backup_path( $params );
}
/**
* Get multipart.list absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_multipart_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_MULTIPART_NAME;
}
/**
* Get content.list absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_content_list_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_CONTENT_LIST_NAME;
}
/**
* Get media.list absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_media_list_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_MEDIA_LIST_NAME;
}
/**
* Get plugins.list absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_plugins_list_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_PLUGINS_LIST_NAME;
}
/**
* Get themes.list absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_themes_list_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_THEMES_LIST_NAME;
}
/**
* Get tables.list absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_tables_list_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_TABLES_LIST_NAME;
}
/**
* Get incremental.content.list absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_incremental_content_list_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_INCREMENTAL_CONTENT_LIST_NAME;
}
/**
* Get incremental.media.list absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_incremental_media_list_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_INCREMENTAL_MEDIA_LIST_NAME;
}
/**
* Get incremental.plugins.list absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_incremental_plugins_list_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_INCREMENTAL_PLUGINS_LIST_NAME;
}
/**
* Get incremental.themes.list absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_incremental_themes_list_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_INCREMENTAL_THEMES_LIST_NAME;
}
/**
* Get incremental.backups.list absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_incremental_backups_list_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_INCREMENTAL_BACKUPS_LIST_NAME;
}
/**
* Get package.json absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_package_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_PACKAGE_NAME;
}
/**
* Get multisite.json absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_multisite_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_MULTISITE_NAME;
}
/**
* Get blogs.json absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_blogs_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_BLOGS_NAME;
}
/**
* Get settings.json absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_settings_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_SETTINGS_NAME;
}
/**
* Get database.sql absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_database_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_DATABASE_NAME;
}
/**
* Get cookies.txt absolute path
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_cookies_path( $params ) {
return ai1wm_storage_path( $params ) . DIRECTORY_SEPARATOR . AI1WM_COOKIES_NAME;
}
/**
* Get error log absolute path
*
* @param string $nonce Log nonce
* @return string
*/
function ai1wm_error_path( $nonce ) {
return AI1WM_STORAGE_PATH . DIRECTORY_SEPARATOR . sprintf( AI1WM_ERROR_NAME, $nonce );
}
/**
* Get archive name
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_archive_name( $params ) {
return basename( $params['archive'] );
}
/**
* Get backup URL address
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_backup_url( $params ) {
static $backups_base_url = '';
if ( empty( $backups_base_url ) ) {
if ( Ai1wm_Backups::are_in_wp_content_folder() ) {
$backups_base_url = str_replace( untrailingslashit( WP_CONTENT_DIR ), '', AI1WM_BACKUPS_PATH );
$backups_base_url = content_url(
ai1wm_replace_directory_separator_with_forward_slash( $backups_base_url )
);
} else {
$backups_base_url = str_replace( untrailingslashit( ABSPATH ), '', AI1WM_BACKUPS_PATH );
$backups_base_url = site_url(
ai1wm_replace_directory_separator_with_forward_slash( $backups_base_url )
);
}
}
return $backups_base_url . '/' . ai1wm_replace_directory_separator_with_forward_slash( $params['archive'] );
}
/**
* Get archive size in bytes
*
* @param array $params Request parameters
* @return integer
*/
function ai1wm_archive_bytes( $params ) {
return filesize( ai1wm_archive_path( $params ) );
}
/**
* Get archive modified time in seconds
*
* @param array $params Request parameters
* @return integer
*/
function ai1wm_archive_mtime( $params ) {
return filemtime( ai1wm_archive_path( $params ) );
}
/**
* Get backup size in bytes
*
* @param array $params Request parameters
* @return integer
*/
function ai1wm_backup_bytes( $params ) {
return filesize( ai1wm_backup_path( $params ) );
}
/**
* Get database size in bytes
*
* @param array $params Request parameters
* @return integer
*/
function ai1wm_database_bytes( $params ) {
return filesize( ai1wm_database_path( $params ) );
}
/**
* Get package size in bytes
*
* @param array $params Request parameters
* @return integer
*/
function ai1wm_package_bytes( $params ) {
return filesize( ai1wm_package_path( $params ) );
}
/**
* Get multisite size in bytes
*
* @param array $params Request parameters
* @return integer
*/
function ai1wm_multisite_bytes( $params ) {
return filesize( ai1wm_multisite_path( $params ) );
}
/**
* Get archive size as text
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_archive_size( $params ) {
return ai1wm_size_format( filesize( ai1wm_archive_path( $params ) ) );
}
/**
* Get backup size as text
*
* @param array $params Request parameters
* @return string
*/
function ai1wm_backup_size( $params ) {
return ai1wm_size_format( filesize( ai1wm_backup_path( $params ) ) );
}
/**
* Parse file size
*
* @param string $size File size
* @param string $default Default size
* @return string
*/
function ai1wm_parse_size( $size, $default = null ) {
$suffixes = array(
'' => 1,
'k' => 1000,
'm' => 1000000,
'g' => 1000000000,
);
// Parse size format
if ( preg_match( '/([0-9]+)\s*(k|m|g)?(b?(ytes?)?)/i', $size, $matches ) ) {
return $matches[1] * $suffixes[ strtolower( $matches[2] ) ];
}
return $default;
}
/**
* Format file size into human-readable string
*
* Fixes the WP size_format bug: size_format( '0' ) => false
*
* @param int|string $bytes Number of bytes. Note max integer size for integers.
* @param int $decimals Optional. Precision of number of decimal places. Default 0.
* @return string|false False on failure. Number string on success.
*/
function ai1wm_size_format( $bytes, $decimals = 0 ) {
if ( strval( $bytes ) === '0' ) {
return size_format( 0, $decimals );
}
return size_format( $bytes, $decimals );
}
/**
* Get current site name
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_site_name( $blog_id = null ) {
return parse_url( get_site_url( $blog_id ), PHP_URL_HOST );
}
/**
* Get archive file name
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_archive_file( $blog_id = null ) {
$name = array();
// Add domain
if ( defined( 'AI1WM_KEEP_DOMAIN_NAME' ) ) {
$name[] = parse_url( get_site_url( $blog_id ), PHP_URL_HOST );
} elseif ( ( $domain = explode( '.', parse_url( get_site_url( $blog_id ), PHP_URL_HOST ) ) ) ) {
foreach ( $domain as $subdomain ) {
if ( ( $subdomain = strtolower( $subdomain ) ) ) {
$name[] = $subdomain;
}
}
}
// Add path
if ( ( $path = parse_url( get_site_url( $blog_id ), PHP_URL_PATH ) ) ) {
foreach ( explode( '/', $path ) as $directory ) {
if ( ( $directory = strtolower( preg_replace( '/[^A-Za-z0-9\-]/', '', $directory ) ) ) ) {
$name[] = $directory;
}
}
}
// Add year, month and day
$name[] = current_time( 'Ymd' );
// Add hours, minutes and seconds
$name[] = current_time( 'His' );
// Add unique identifier
$name[] = ai1wm_generate_random_string( 12, false );
return sprintf( '%s.wpress', strtolower( implode( '-', $name ) ) );
}
/**
* Get archive folder name
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_archive_folder( $blog_id = null ) {
$name = array();
// Add domain
if ( defined( 'AI1WM_KEEP_DOMAIN_NAME' ) ) {
$name[] = parse_url( get_site_url( $blog_id ), PHP_URL_HOST );
} elseif ( ( $domain = explode( '.', parse_url( get_site_url( $blog_id ), PHP_URL_HOST ) ) ) ) {
foreach ( $domain as $subdomain ) {
if ( ( $subdomain = strtolower( $subdomain ) ) ) {
$name[] = $subdomain;
}
}
}
// Add path
if ( ( $path = parse_url( get_site_url( $blog_id ), PHP_URL_PATH ) ) ) {
foreach ( explode( '/', $path ) as $directory ) {
if ( ( $directory = strtolower( preg_replace( '/[^A-Za-z0-9\-]/', '', $directory ) ) ) ) {
$name[] = $directory;
}
}
}
return strtolower( implode( '-', $name ) );
}
/**
* Get archive bucket name
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_archive_bucket( $blog_id = null ) {
$name = array();
// Add domain
if ( ( $domain = explode( '.', parse_url( get_site_url( $blog_id ), PHP_URL_HOST ) ) ) ) {
foreach ( $domain as $subdomain ) {
if ( ( $subdomain = strtolower( $subdomain ) ) ) {
$name[] = $subdomain;
}
}
}
// Add path
if ( ( $path = parse_url( get_site_url( $blog_id ), PHP_URL_PATH ) ) ) {
foreach ( explode( '/', $path ) as $directory ) {
if ( ( $directory = strtolower( preg_replace( '/[^A-Za-z0-9\-]/', '', $directory ) ) ) ) {
$name[] = $directory;
}
}
}
return strtolower( implode( '-', $name ) );
}
/**
* Get archive vault name
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_archive_vault( $blog_id = null ) {
$name = array();
// Add domain
if ( ( $domain = explode( '.', parse_url( get_site_url( $blog_id ), PHP_URL_HOST ) ) ) ) {
foreach ( $domain as $subdomain ) {
if ( ( $subdomain = strtolower( $subdomain ) ) ) {
$name[] = $subdomain;
}
}
}
// Add path
if ( ( $path = parse_url( get_site_url( $blog_id ), PHP_URL_PATH ) ) ) {
foreach ( explode( '/', $path ) as $directory ) {
if ( ( $directory = strtolower( preg_replace( '/[^A-Za-z0-9\-]/', '', $directory ) ) ) ) {
$name[] = $directory;
}
}
}
return strtolower( implode( '-', $name ) );
}
/**
* Get archive project name
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_archive_project( $blog_id = null ) {
$name = array();
// Add domain
if ( ( $domain = explode( '.', parse_url( get_site_url( $blog_id ), PHP_URL_HOST ) ) ) ) {
foreach ( $domain as $subdomain ) {
if ( ( $subdomain = strtolower( $subdomain ) ) ) {
$name[] = $subdomain;
}
}
}
// Add path
if ( ( $path = parse_url( get_site_url( $blog_id ), PHP_URL_PATH ) ) ) {
foreach ( explode( '/', $path ) as $directory ) {
if ( ( $directory = strtolower( preg_replace( '/[^A-Za-z0-9\-]/', '', $directory ) ) ) ) {
$name[] = $directory;
}
}
}
return strtolower( implode( '-', $name ) );
}
/**
* Get archive share name
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_archive_share( $blog_id = null ) {
$name = array();
// Add domain
if ( ( $domain = explode( '.', parse_url( get_site_url( $blog_id ), PHP_URL_HOST ) ) ) ) {
foreach ( $domain as $subdomain ) {
if ( ( $subdomain = strtolower( $subdomain ) ) ) {
$name[] = $subdomain;
}
}
}
// Add path
if ( ( $path = parse_url( get_site_url( $blog_id ), PHP_URL_PATH ) ) ) {
foreach ( explode( '/', $path ) as $directory ) {
if ( ( $directory = strtolower( preg_replace( '/[^A-Za-z0-9\-]/', '', $directory ) ) ) ) {
$name[] = $directory;
}
}
}
return strtolower( implode( '-', $name ) );
}
/**
* Generate random string
*
* @param integer $length String length
* @param boolean $mixed_chars Whether to include mixed characters
* @param boolean $special_chars Whether to include special characters
* @param boolean $extra_special_chars Whether to include extra special characters
* @return string
*/
function ai1wm_generate_random_string( $length = 12, $mixed_chars = true, $special_chars = false, $extra_special_chars = false ) {
$chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
if ( $mixed_chars ) {
$chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
}
if ( $special_chars ) {
$chars .= '!@#$%^&*()';
}
if ( $extra_special_chars ) {
$chars .= '-_ []{}<>~`+=,.;:/?|';
}
$str = '';
for ( $i = 0; $i < $length; $i++ ) {
$str .= substr( $chars, wp_rand( 0, strlen( $chars ) - 1 ), 1 );
}
return $str;
}
/**
* Get storage folder name
*
* @return string
*/
function ai1wm_storage_folder() {
return uniqid();
}
/**
* Check whether blog ID is main site
*
* @param integer $blog_id Blog ID
* @return boolean
*/
function ai1wm_is_mainsite( $blog_id = null ) {
return $blog_id === null || $blog_id === 0 || $blog_id === 1;
}
/**
* Get files absolute path by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_blog_files_abspath( $blog_id = null ) {
if ( ai1wm_is_mainsite( $blog_id ) ) {
return ai1wm_get_uploads_dir();
}
return WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'blogs.dir' . DIRECTORY_SEPARATOR . $blog_id . DIRECTORY_SEPARATOR . 'files';
}
/**
* Get blogs.dir absolute path by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_blog_blogsdir_abspath( $blog_id = null ) {
if ( ai1wm_is_mainsite( $blog_id ) ) {
return ai1wm_get_uploads_dir();
}
return WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'blogs.dir' . DIRECTORY_SEPARATOR . $blog_id;
}
/**
* Get sites absolute path by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_blog_sites_abspath( $blog_id = null ) {
if ( ai1wm_is_mainsite( $blog_id ) ) {
return ai1wm_get_uploads_dir();
}
return ai1wm_get_uploads_dir() . DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR . $blog_id;
}
/**
* Get files relative path by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_blog_files_relpath( $blog_id = null ) {
if ( ai1wm_is_mainsite( $blog_id ) ) {
return 'uploads';
}
return 'blogs.dir' . DIRECTORY_SEPARATOR . $blog_id . DIRECTORY_SEPARATOR . 'files';
}
/**
* Get blogs.dir relative path by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_blog_blogsdir_relpath( $blog_id = null ) {
if ( ai1wm_is_mainsite( $blog_id ) ) {
return 'uploads';
}
return 'blogs.dir' . DIRECTORY_SEPARATOR . $blog_id;
}
/**
* Get sites relative path by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_blog_sites_relpath( $blog_id = null ) {
if ( ai1wm_is_mainsite( $blog_id ) ) {
return 'uploads';
}
return 'uploads' . DIRECTORY_SEPARATOR . 'sites' . DIRECTORY_SEPARATOR . $blog_id;
}
/**
* Get files URL by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_blog_files_url( $blog_id = null ) {
if ( ai1wm_is_mainsite( $blog_id ) ) {
return '/wp-content/uploads/';
}
return sprintf( '/wp-content/blogs.dir/%d/files/', $blog_id );
}
/**
* Get blogs.dir URL by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_blog_blogsdir_url( $blog_id = null ) {
if ( ai1wm_is_mainsite( $blog_id ) ) {
return '/wp-content/uploads/';
}
return sprintf( '/wp-content/blogs.dir/%d/', $blog_id );
}
/**
* Get sites URL by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_blog_sites_url( $blog_id = null ) {
if ( ai1wm_is_mainsite( $blog_id ) ) {
return '/wp-content/uploads/';
}
return sprintf( '/wp-content/uploads/sites/%d/', $blog_id );
}
/**
* Get uploads URL by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_blog_uploads_url( $blog_id = null ) {
if ( ai1wm_is_mainsite( $blog_id ) ) {
return sprintf( '/%s/', ai1wm_get_uploads_path() );
}
return sprintf( '/%s/sites/%d/', ai1wm_get_uploads_path(), $blog_id );
}
/**
* Get ServMask table prefix by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_servmask_prefix( $blog_id = null ) {
if ( ai1wm_is_mainsite( $blog_id ) ) {
return AI1WM_TABLE_PREFIX;
}
return AI1WM_TABLE_PREFIX . $blog_id . '_';
}
/**
* Get WordPress table prefix by blog ID
*
* @param integer $blog_id Blog ID
* @return string
*/
function ai1wm_table_prefix( $blog_id = null ) {
global $wpdb;
// Set base table prefix
if ( ai1wm_is_mainsite( $blog_id ) ) {
return $wpdb->base_prefix;
}
return $wpdb->base_prefix . $blog_id . '_';
}
/**
* Get default content filters
*
* @param array $filters List of files and directories
* @return array
*/
function ai1wm_content_filters( $filters = array() ) {
return array_merge(
$filters,
array(
AI1WM_BACKUPS_PATH,
AI1WM_BACKUPS_NAME,
AI1WM_PACKAGE_NAME,
AI1WM_MULTISITE_NAME,
AI1WM_DATABASE_NAME,
AI1WM_W3TC_CONFIG_FILE,
)
);
}
/**
* Get default media filters
*
* @param array $filters List of files and directories
* @return array
*/
function ai1wm_media_filters( $filters = array() ) {
return array_merge(
$filters,
array(
AI1WM_BACKUPS_PATH,
)
);
}
/**
* Get default plugin filters
*
* @param array $filters List of plugins
* @return array
*/
function ai1wm_plugin_filters( $filters = array() ) {
return array_merge(
$filters,
array(
AI1WM_BACKUPS_PATH,
AI1WM_PLUGIN_BASEDIR,
AI1WMZE_PLUGIN_BASEDIR,
AI1WMAE_PLUGIN_BASEDIR,
AI1WMVE_PLUGIN_BASEDIR,
AI1WMBE_PLUGIN_BASEDIR,
AI1WMIE_PLUGIN_BASEDIR,
AI1WMXE_PLUGIN_BASEDIR,
AI1WMDE_PLUGIN_BASEDIR,
AI1WMTE_PLUGIN_BASEDIR,
AI1WMFE_PLUGIN_BASEDIR,
AI1WMCE_PLUGIN_BASEDIR,
AI1WMGE_PLUGIN_BASEDIR,
AI1WMRE_PLUGIN_BASEDIR,
AI1WMEE_PLUGIN_BASEDIR,
AI1WMME_PLUGIN_BASEDIR,
AI1WMOE_PLUGIN_BASEDIR,
AI1WMPE_PLUGIN_BASEDIR,
AI1WMKE_PLUGIN_BASEDIR,
AI1WMNE_PLUGIN_BASEDIR,
AI1WMSE_PLUGIN_BASEDIR,
AI1WMUE_PLUGIN_BASEDIR,
AI1WMLE_PLUGIN_BASEDIR,
AI1WMWE_PLUGIN_BASEDIR,
)
);
}
/**
* Get default theme filters
*
* @param array $filters List of files and directories
* @return array
*/
function ai1wm_theme_filters( $filters = array() ) {
return array_merge(
$filters,
array(
AI1WM_BACKUPS_PATH,
)
);
}
/**
* Get active ServMask plugins
*
* @return array
*/
function ai1wm_active_servmask_plugins( $plugins = array() ) {
// WP Migration Plugin
if ( defined( 'AI1WM_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WM_PLUGIN_BASENAME;
}
// Microsoft Azure Extension
if ( defined( 'AI1WMZE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMZE_PLUGIN_BASENAME;
}
// Backblaze B2 Extension
if ( defined( 'AI1WMAE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMAE_PLUGIN_BASENAME;
}
// Backup Plugin
if ( defined( 'AI1WMVE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMVE_PLUGIN_BASENAME;
}
// Box Extension
if ( defined( 'AI1WMBE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMBE_PLUGIN_BASENAME;
}
// DigitalOcean Spaces Extension
if ( defined( 'AI1WMIE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMIE_PLUGIN_BASENAME;
}
// Direct Extension
if ( defined( 'AI1WMXE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMXE_PLUGIN_BASENAME;
}
// Dropbox Extension
if ( defined( 'AI1WMDE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMDE_PLUGIN_BASENAME;
}
// File Extension
if ( defined( 'AI1WMTE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMTE_PLUGIN_BASENAME;
}
// FTP Extension
if ( defined( 'AI1WMFE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMFE_PLUGIN_BASENAME;
}
// Google Cloud Storage Extension
if ( defined( 'AI1WMCE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMCE_PLUGIN_BASENAME;
}
// Google Drive Extension
if ( defined( 'AI1WMGE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMGE_PLUGIN_BASENAME;
}
// Amazon Glacier Extension
if ( defined( 'AI1WMRE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMRE_PLUGIN_BASENAME;
}
// Mega Extension
if ( defined( 'AI1WMEE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMEE_PLUGIN_BASENAME;
}
// Multisite Extension
if ( defined( 'AI1WMME_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMME_PLUGIN_BASENAME;
}
// OneDrive Extension
if ( defined( 'AI1WMOE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMOE_PLUGIN_BASENAME;
}
// pCloud Extension
if ( defined( 'AI1WMPE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMPE_PLUGIN_BASENAME;
}
// Pro Plugin
if ( defined( 'AI1WMKE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMKE_PLUGIN_BASENAME;
}
// S3 Client Extension
if ( defined( 'AI1WMNE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMNE_PLUGIN_BASENAME;
}
// Amazon S3 Extension
if ( defined( 'AI1WMSE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMSE_PLUGIN_BASENAME;
}
// Unlimited Extension
if ( defined( 'AI1WMUE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMUE_PLUGIN_BASENAME;
}
// URL Extension
if ( defined( 'AI1WMLE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMLE_PLUGIN_BASENAME;
}
// WebDAV Extension
if ( defined( 'AI1WMWE_PLUGIN_BASENAME' ) ) {
$plugins[] = AI1WMWE_PLUGIN_BASENAME;
}
return $plugins;
}
/**
* Get active sitewide plugins
*
* @return array
*/
function ai1wm_active_sitewide_plugins() {
return array_keys( get_site_option( AI1WM_ACTIVE_SITEWIDE_PLUGINS, array() ) );
}
/**
* Get active plugins
*
* @return array
*/
function ai1wm_active_plugins() {
return array_values( get_option( AI1WM_ACTIVE_PLUGINS, array() ) );
}
/**
* Set active sitewide plugins (inspired by WordPress activate_plugins() function)
*
* @param array $plugins List of plugins
* @return boolean
*/
function ai1wm_activate_sitewide_plugins( $plugins ) {
$current = get_site_option( AI1WM_ACTIVE_SITEWIDE_PLUGINS, array() );
// Add plugins
foreach ( $plugins as $plugin ) {
if ( ! isset( $current[ $plugin ] ) && ! is_wp_error( validate_plugin( $plugin ) ) ) {
$current[ $plugin ] = time();
}
}
return update_site_option( AI1WM_ACTIVE_SITEWIDE_PLUGINS, $current );
}
/**
* Set active plugins (inspired by WordPress activate_plugins() function)
*
* @param array $plugins List of plugins
* @return boolean
*/
function ai1wm_activate_plugins( $plugins ) {
$current = get_option( AI1WM_ACTIVE_PLUGINS, array() );
// Add plugins
foreach ( $plugins as $plugin ) {
if ( ! in_array( $plugin, $current ) && ! is_wp_error( validate_plugin( $plugin ) ) ) {
$current[] = $plugin;
}
}
return update_option( AI1WM_ACTIVE_PLUGINS, $current );
}
/**
* Get active template
*
* @return string
*/
function ai1wm_active_template() {
return get_option( AI1WM_ACTIVE_TEMPLATE );
}
/**
* Get active stylesheet
*
* @return string
*/
function ai1wm_active_stylesheet() {
return get_option( AI1WM_ACTIVE_STYLESHEET );
}
/**
* Set active template
*
* @param string $template Template name
* @return boolean
*/
function ai1wm_activate_template( $template ) {
return update_option( AI1WM_ACTIVE_TEMPLATE, $template );
}
/**
* Set active stylesheet
*
* @param string $stylesheet Stylesheet name
* @return boolean
*/
function ai1wm_activate_stylesheet( $stylesheet ) {
return update_option( AI1WM_ACTIVE_STYLESHEET, $stylesheet );
}
/**
* Set inactive sitewide plugins (inspired by WordPress deactivate_plugins() function)
*
* @param array $plugins List of plugins
* @return boolean
*/
function ai1wm_deactivate_sitewide_plugins( $plugins ) {
$current = get_site_option( AI1WM_ACTIVE_SITEWIDE_PLUGINS, array() );
// Add plugins
foreach ( $plugins as $plugin ) {
if ( isset( $current[ $plugin ] ) ) {
unset( $current[ $plugin ] );
}
}
return update_site_option( AI1WM_ACTIVE_SITEWIDE_PLUGINS, $current );
}
/**
* Set inactive plugins (inspired by WordPress deactivate_plugins() function)
*
* @param array $plugins List of plugins
* @return boolean
*/
function ai1wm_deactivate_plugins( $plugins ) {
$current = get_option( AI1WM_ACTIVE_PLUGINS, array() );
// Remove plugins
foreach ( $plugins as $plugin ) {
if ( ( $key = array_search( $plugin, $current ) ) !== false ) {
unset( $current[ $key ] );
}
}
return update_option( AI1WM_ACTIVE_PLUGINS, $current );
}
/**
* Deactivate Jetpack modules
*
* @param array $modules List of modules
* @return boolean
*/
function ai1wm_deactivate_jetpack_modules( $modules ) {
$current = get_option( AI1WM_JETPACK_ACTIVE_MODULES, array() );
// Remove modules
foreach ( $modules as $module ) {
if ( ( $key = array_search( $module, $current ) ) !== false ) {
unset( $current[ $key ] );
}
}
return update_option( AI1WM_JETPACK_ACTIVE_MODULES, $current );
}
/**
* Deactivate Swift Optimizer rules
*
* @param array $rules List of rules
* @return boolean
*/
function ai1wm_deactivate_swift_optimizer_rules( $rules ) {
$current = get_option( AI1WM_SWIFT_OPTIMIZER_PLUGIN_ORGANIZER, array() );
// Remove rules
foreach ( $rules as $rule ) {
unset( $current['rules'][ $rule ] );
}
return update_option( AI1WM_SWIFT_OPTIMIZER_PLUGIN_ORGANIZER, $current );
}
/**
* Deactivate sitewide Revolution Slider
*
* @param string $basename Plugin basename
* @return boolean
*/
function ai1wm_deactivate_sitewide_revolution_slider( $basename ) {
if ( ( $plugins = get_plugins() ) ) {
if ( isset( $plugins[ $basename ]['Version'] ) && ( $version = $plugins[ $basename ]['Version'] ) ) {
if ( version_compare( PHP_VERSION, '7.3', '>=' ) && version_compare( $version, '5.4.8.3', '<' ) ) {
return ai1wm_deactivate_sitewide_plugins( array( $basename ) );
}
if ( version_compare( PHP_VERSION, '7.2', '>=' ) && version_compare( $version, '5.4.6', '<' ) ) {
return ai1wm_deactivate_sitewide_plugins( array( $basename ) );
}
if ( version_compare( PHP_VERSION, '7.1', '>=' ) && version_compare( $version, '5.4.1', '<' ) ) {
return ai1wm_deactivate_sitewide_plugins( array( $basename ) );
}
if ( version_compare( PHP_VERSION, '7.0', '>=' ) && version_compare( $version, '4.6.5', '<' ) ) {
return ai1wm_deactivate_sitewide_plugins( array( $basename ) );
}
}
}
return false;
}
/**
* Deactivate Revolution Slider
*
* @param string $basename Plugin basename
* @return boolean
*/
function ai1wm_deactivate_revolution_slider( $basename ) {
if ( ( $plugins = get_plugins() ) ) {
if ( isset( $plugins[ $basename ]['Version'] ) && ( $version = $plugins[ $basename ]['Version'] ) ) {
if ( version_compare( PHP_VERSION, '7.3', '>=' ) && version_compare( $version, '5.4.8.3', '<' ) ) {
return ai1wm_deactivate_plugins( array( $basename ) );
}
if ( version_compare( PHP_VERSION, '7.2', '>=' ) && version_compare( $version, '5.4.6', '<' ) ) {
return ai1wm_deactivate_plugins( array( $basename ) );
}
if ( version_compare( PHP_VERSION, '7.1', '>=' ) && version_compare( $version, '5.4.1', '<' ) ) {
return ai1wm_deactivate_plugins( array( $basename ) );
}
if ( version_compare( PHP_VERSION, '7.0', '>=' ) && version_compare( $version, '4.6.5', '<' ) ) {
return ai1wm_deactivate_plugins( array( $basename ) );
}
}
}
return false;
}
/**
* Initial DB version
*
* @return boolean
*/
function ai1wm_initial_db_version() {
if ( ! get_option( AI1WM_DB_VERSION ) ) {
return update_option( AI1WM_DB_VERSION, get_option( AI1WM_INITIAL_DB_VERSION ) );
}
return false;
}
/**
* Discover plugin basename
*
* @param string $basename Plugin basename
* @return string
*/
function ai1wm_discover_plugin_basename( $basename ) {
if ( ( $plugins = get_plugins() ) ) {
foreach ( $plugins as $plugin => $info ) {
if ( strpos( dirname( $plugin ), dirname( $basename ) ) !== false ) {
if ( basename( $plugin ) === basename( $basename ) ) {
return $plugin;
}
}
}
}
return $basename;
}
/**
* Validate plugin basename
*
* @param string $basename Plugin basename
* @return boolean
*/
function ai1wm_validate_plugin_basename( $basename ) {
if ( ( $plugins = get_plugins() ) ) {
foreach ( $plugins as $plugin => $info ) {
if ( $plugin === $basename ) {
return true;
}
}
}
return false;
}
/**
* Validate theme basename
*
* @param string $basename Theme basename
* @return boolean
*/
function ai1wm_validate_theme_basename( $basename ) {
if ( ( $themes = search_theme_directories() ) ) {
foreach ( $themes as $theme => $info ) {
if ( $info['theme_file'] === $basename ) {
return true;
}
}
}
return false;
}
/**
* Flush WP options cache
*
* @return void
*/
function ai1wm_cache_flush() {
wp_cache_init();
wp_cache_flush();
// Reset WP options cache
wp_cache_set( 'alloptions', array(), 'options' );
wp_cache_set( 'notoptions', array(), 'options' );
// Reset WP sitemeta cache
wp_cache_set( '1:notoptions', array(), 'site-options' );
wp_cache_set( '1:ms_files_rewriting', false, 'site-options' );
wp_cache_set( '1:active_sitewide_plugins', false, 'site-options' );
// Delete WP options cache
wp_cache_delete( 'alloptions', 'options' );
wp_cache_delete( 'notoptions', 'options' );
// Delete WP sitemeta cache
wp_cache_delete( '1:notoptions', 'site-options' );
wp_cache_delete( '1:ms_files_rewriting', 'site-options' );
wp_cache_delete( '1:active_sitewide_plugins', 'site-options' );
// Remove WP options filter
remove_all_filters( 'sanitize_option_home' );
remove_all_filters( 'sanitize_option_siteurl' );
remove_all_filters( 'default_site_option_ms_files_rewriting' );
}
/**
* Flush Elementor cache
*
* @return void
*/
function ai1wm_elementor_cache_flush() {
delete_post_meta_by_key( '_elementor_css' );
delete_post_meta_by_key( '_elementor_element_cache' );
delete_post_meta_by_key( '_elementor_page_assets' );
delete_option( '_elementor_global_css' );
delete_option( '_elementor_assets_data' );
delete_option( 'elementor-custom-breakpoints-files' );
}
/**
* Set WooCommerce Force SSL checkout
*
* @param boolean $yes Force SSL checkout
* @return void
*/
function ai1wm_woocommerce_force_ssl( $yes = true ) {
if ( get_option( 'woocommerce_force_ssl_checkout' ) ) {
if ( $yes ) {
update_option( 'woocommerce_force_ssl_checkout', 'yes' );
} else {
update_option( 'woocommerce_force_ssl_checkout', 'no' );
}
}
}
/**
* Set URL scheme
*
* @param string $url URL value
* @param string $scheme URL scheme
* @return string
*/
function ai1wm_url_scheme( $url, $scheme = '' ) {
if ( empty( $scheme ) ) {
return preg_replace( '#^\w+://#', '//', $url );
}
return preg_replace( '#^\w+://#', $scheme . '://', $url );
}
/**
* Opens a file in specified mode
*
* @param string $file Path to the file to open
* @param string $mode Mode in which to open the file
* @return resource
* @throws Ai1wm_Not_Accessible_Exception
*/
function ai1wm_open( $file, $mode ) {
$file_handle = @fopen( $file, $mode );
if ( false === $file_handle ) {
throw new Ai1wm_Not_Accessible_Exception(
wp_kses(
/* translators: 1: File path, 2: mode */
sprintf( __( 'Could not open %1$s with mode %2$s. The process cannot continue. Technical details', 'all-in-one-wp-migration' ), $file, $mode ),
ai1wm_allowed_html_tags()
)
);
}
return $file_handle;
}
/**
* Write contents to a file
*
* @param resource $handle File handle to write to
* @param string $content Contents to write to the file
* @return integer
* @throws Ai1wm_Not_Writable_Exception
* @throws Ai1wm_Quota_Exceeded_Exception
*/
function ai1wm_write( $handle, $content ) {
$write_result = @fwrite( $handle, $content );
if ( false === $write_result ) {
if ( ( $meta = stream_get_meta_data( $handle ) ) ) {
throw new Ai1wm_Not_Writable_Exception(
wp_kses(
/* translators: 1: Meta data stream URI. */
sprintf( __( 'Could not write to: %s. The process cannot continue. Technical details', 'all-in-one-wp-migration' ), $meta['uri'] ),
ai1wm_allowed_html_tags()
)
);
}
} elseif ( null === $write_result ) {
return strlen( $content );
} elseif ( strlen( $content ) !== $write_result ) {
if ( ( $meta = stream_get_meta_data( $handle ) ) ) {
throw new Ai1wm_Quota_Exceeded_Exception(
wp_kses(
/* translators: 1: Meta data stream URI. */
sprintf( __( 'Out of disk space. Could not write to: %s. The process cannot continue. Technical details', 'all-in-one-wp-migration' ), $meta['uri'] ),
ai1wm_allowed_html_tags()
)
);
}
}
return $write_result;
}
/**
* Read contents from a file
*
* @param resource $handle File handle to read from
* @param integer $length Up to length number of bytes read
* @return string
* @throws Ai1wm_Not_Readable_Exception
*/
function ai1wm_read( $handle, $length ) {
if ( $length > 0 ) {
$read_result = @fread( $handle, $length );
if ( false === $read_result ) {
if ( ( $meta = stream_get_meta_data( $handle ) ) ) {
throw new Ai1wm_Not_Readable_Exception(
wp_kses(
/* translators: 1: Meta data stream URI. */
sprintf( __( 'Could not read file: %s. The process cannot continue. Technical details', 'all-in-one-wp-migration' ), $meta['uri'] ),
ai1wm_allowed_html_tags()
)
);
}
}
return $read_result;
}
return false;
}
/**
* Seeks on a file pointer
*
* @param resource $handle File handle
* @param integer $offset File offset
* @param integer $mode Offset mode
* @return integer
*/
function ai1wm_seek( $handle, $offset, $mode = SEEK_SET ) {
$seek_result = @fseek( $handle, $offset, $mode );
if ( -1 === $seek_result ) {
if ( ( $meta = stream_get_meta_data( $handle ) ) ) {
throw new Ai1wm_Not_Seekable_Exception(
wp_kses(
/* translators: 1: File offset, 2: Meta data stream URI. */
sprintf( __( 'Could not seek to offset %1$d on %2$s. The process cannot continue. Technical details', 'all-in-one-wp-migration' ), $offset, $meta['uri'] ),
ai1wm_allowed_html_tags()
)
);
}
}
return $seek_result;
}
/**
* Returns the current position of the file read/write pointer
*
* @param resource $handle File handle
* @return integer
*/
function ai1wm_tell( $handle ) {
$tell_result = @ftell( $handle );
if ( false === $tell_result ) {
if ( ( $meta = stream_get_meta_data( $handle ) ) ) {
throw new Ai1wm_Not_Tellable_Exception(
wp_kses(
/* translators: 1: Meta data stream URI. */
sprintf( __( 'Could not get current pointer position of %s. The process cannot continue. Technical details', 'all-in-one-wp-migration' ), $meta['uri'] ),
ai1wm_allowed_html_tags()
)
);
}
}
return $tell_result;
}
/**
* Write fields to a file
*
* @param resource $handle File handle to write to
* @param array $fields Fields to write to the file
* @param string $separator
* @param string $enclosure
* @param string $escape
*
* @return integer
* @throws Ai1wm_Not_Writable_Exception
*/
function ai1wm_putcsv( $handle, $fields, $separator = ',', $enclosure = '"', $escape = '\\' ) {
if ( PHP_MAJOR_VERSION >= 7 ) {
$write_result = @fputcsv( $handle, $fields, $separator, $enclosure, $escape );
} else {
$write_result = @fputcsv( $handle, $fields, $separator, $enclosure );
}
if ( false === $write_result ) {
if ( ( $meta = stream_get_meta_data( $handle ) ) ) {
throw new Ai1wm_Not_Writable_Exception(
wp_kses(
/* translators: 1: Meta data stream URI. */
sprintf( __( 'Could not write to: %s. The process cannot continue. Technical details', 'all-in-one-wp-migration' ), $meta['uri'] ),
ai1wm_allowed_html_tags()
)
);
}
}
return $write_result;
}
/**
* Read fields from a file
*
* @param resource $handle File handle to read from
* @param int $length
* @param string $separator
* @param string $enclosure
* @param string $escape
*
* @return array|false|null
*/
function ai1wm_getcsv( $handle, $length = null, $separator = ',', $enclosure = '"', $escape = '\\' ) {
return fgetcsv( $handle, $length, $separator, $enclosure, $escape );
}
/**
* Closes a file handle
*
* @param resource $handle File handle to close
* @return boolean
*/
function ai1wm_close( $handle ) {
return @fclose( $handle );
}
/**
* Deletes a file
*
* @param string $file Path to file to delete
* @return boolean
*/
function ai1wm_unlink( $file ) {
return @unlink( $file );
}
/**
* Sets modification time of a file
*
* @param string $file Path to file to change modification time
* @param integer $time File modification time
* @return boolean
*/
function ai1wm_touch( $file, $mtime ) {
return @touch( $file, $mtime );
}
/**
* Changes file mode
*
* @param string $file Path to file to change mode
* @param integer $time File mode
* @return boolean
*/
function ai1wm_chmod( $file, $mode ) {
return @chmod( $file, $mode );
}
/**
* Copies one file's contents to another
*
* @param string $target_file File to copy the contents from
* @param string $output_file File to copy the contents to
* @param integer $output_file_offset Output file offset bytes
* @return void
*/
function ai1wm_copy( $target_file, $output_file, $output_file_offset = 0 ) {
$target_handle = ai1wm_open( $target_file, 'rb' );
$output_handle = ai1wm_open( $output_file, 'cb' );
if ( ai1wm_seek( $output_handle, $output_file_offset, SEEK_SET ) !== -1 ) {
while ( ( $file_buffer = ai1wm_read( $target_handle, 4096 ) ) ) {
ai1wm_write( $output_handle, $file_buffer );
}
}
ai1wm_close( $target_handle );
ai1wm_close( $output_handle );
}
/**
* Check whether file size is supported by current PHP version
*
* @param string $file Path to file
* @param integer $php_int_size Size of PHP integer
* @return boolean $php_int_max Max value of PHP integer
*/
function ai1wm_is_filesize_supported( $file, $php_int_size = PHP_INT_SIZE, $php_int_max = PHP_INT_MAX ) {
$size_result = true;
// Check whether file size is less than 2GB in PHP 32bits
if ( $php_int_size === 4 ) {
if ( ( $file_handle = @fopen( $file, 'rb' ) ) ) {
if ( @fseek( $file_handle, $php_int_max, SEEK_SET ) !== -1 ) {
if ( @fgetc( $file_handle ) !== false ) {
$size_result = false;
}
}
@fclose( $file_handle );
}
}
return $size_result;
}
/**
* Check whether file name is supported by All-in-One WP Migration
*
* @param string $file Path to file
* @param array $extensions File extensions
* @return boolean
*/
function ai1wm_is_filename_supported( $file, $extensions = array( 'wpress' ) ) {
if ( in_array( pathinfo( $file, PATHINFO_EXTENSION ), $extensions ) ) {
return true;
}
return false;
}
/**
* Check whether file data is supported by All-in-One WP Migration
*
* @param string $file Path to file
* @return boolean
*/
function ai1wm_is_filedata_supported( $file ) {
if ( ( $file_handle = @fopen( $file, 'rb' ) ) ) {
if ( ( $file_buffer = @fread( $file_handle, 4377 ) ) ) {
if ( ( $file_data = @unpack( 'a255filename/a14size/a12mtime/a4096path', $file_buffer ) ) !== false ) {
if ( AI1WM_PACKAGE_NAME === trim( $file_data['filename'] ) ) {
return true;
}
}
}
@fclose( $file_handle );
}
return false;
}
/**
* Verify secret key
*
* @param string $secret_key Secret key
* @return boolean
* @throws Ai1wm_Not_Valid_Secret_Key_Exception
*/
function ai1wm_verify_secret_key( $secret_key ) {
if ( $secret_key !== get_option( AI1WM_SECRET_KEY ) ) {
throw new Ai1wm_Not_Valid_Secret_Key_Exception(
wp_kses(
__( 'Could not authenticate the secret key. The process cannot continue. Technical details', 'all-in-one-wp-migration' ),
ai1wm_allowed_html_tags()
)
);
}
return true;
}
/**
* Is scheduled backup?
*
* @return boolean
*/
function ai1wm_is_scheduled_backup() {
if ( isset( $_GET['ai1wm_manual_export'] ) || isset( $_POST['ai1wm_manual_export'] ) ) {
return false;
}
if ( isset( $_GET['ai1wm_manual_import'] ) || isset( $_POST['ai1wm_manual_import'] ) ) {
return false;
}
if ( isset( $_GET['ai1wm_manual_restore'] ) || isset( $_POST['ai1wm_manual_restore'] ) ) {
return false;
}
if ( isset( $_GET['ai1wm_manual_reset'] ) || isset( $_POST['ai1wm_manual_reset'] ) ) {
return false;
}
return true;
}
/**
* PHP setup environment
*
* @return void
*/
function ai1wm_setup_environment() {
// Set whether a client disconnect should abort script execution
@ignore_user_abort( true );
// Set maximum execution time
@set_time_limit( 0 );
// Set maximum time in seconds a script is allowed to parse input data
@ini_set( 'max_input_time', '-1' );
// Set maximum backtracking steps
@ini_set( 'pcre.backtrack_limit', PHP_INT_MAX );
// Set binary safe encoding
if ( @function_exists( 'mb_internal_encoding' ) && ( @ini_get( 'mbstring.func_overload' ) & 2 ) ) {
@mb_internal_encoding( 'ISO-8859-1' );
}
// Clean (erase) the output buffer and turn off output buffering
if ( @ob_get_length() ) {
@ob_end_clean();
}
}
/**
* PHP register error handlers
*
* @return void
*/
function ai1wm_setup_errors() {
@set_error_handler( 'Ai1wm_Handler::error' );
@register_shutdown_function( 'Ai1wm_Handler::shutdown' );
}
/**
* Get WordPress time zone string
*
* @return string
*/
function ai1wm_get_timezone_string() {
if ( ( $timezone_string = get_option( 'timezone_string' ) ) ) {
return $timezone_string;
}
if ( ( $gmt_offset = get_option( 'gmt_offset' ) ) ) {
if ( $gmt_offset > 0 ) {
return sprintf( 'UTC+%s', abs( $gmt_offset ) );
} elseif ( $gmt_offset < 0 ) {
return sprintf( 'UTC-%s', abs( $gmt_offset ) );
}
}
return 'UTC';
}
/**
* Get WordPress filter hooks
*
* @param string $tag The name of the filter hook
* @return array
*/
function ai1wm_get_filters( $tag ) {
global $wp_filter;
// Get WordPress filter hooks
$filters = array();
if ( isset( $wp_filter[ $tag ] ) ) {
if ( ( $filters = $wp_filter[ $tag ] ) ) {
// WordPress 4.7 introduces new class for working with filters/actions called WP_Hook
// which adds another level of abstraction and we need to address it.
if ( isset( $filters->callbacks ) ) {
$filters = $filters->callbacks;
}
}
ksort( $filters );
}
return $filters;
}
/**
* Get WordPress plugins directories
*
* @return array
*/
function ai1wm_get_themes_dirs() {
$theme_dirs = array();
foreach ( search_theme_directories() as $theme_name => $theme_info ) {
if ( isset( $theme_info['theme_root'] ) ) {
if ( ! in_array( $theme_info['theme_root'], $theme_dirs ) ) {
$theme_dirs[] = untrailingslashit( $theme_info['theme_root'] );
}
}
}
return $theme_dirs;
}
/**
* Get WordPress plugins directory
*
* @return string
*/
function ai1wm_get_plugins_dir() {
return untrailingslashit( WP_PLUGIN_DIR );
}
/**
* Get WordPress uploads directory
*
* @return string
*/
function ai1wm_get_uploads_dir() {
if ( ( $upload_dir = wp_upload_dir() ) ) {
if ( isset( $upload_dir['basedir'] ) ) {
return untrailingslashit( $upload_dir['basedir'] );
}
}
}
/**
* Get WordPress uploads URL
*
* @return string
*/
function ai1wm_get_uploads_url() {
if ( ( $upload_dir = wp_upload_dir() ) ) {
if ( isset( $upload_dir['baseurl'] ) ) {
return trailingslashit( $upload_dir['baseurl'] );
}
}
}
/**
* Get WordPress uploads path
*
* @return string
*/
function ai1wm_get_uploads_path() {
if ( ( $upload_dir = wp_upload_dir() ) ) {
if ( isset( $upload_dir['basedir'] ) ) {
return str_replace( ABSPATH, '', $upload_dir['basedir'] );
}
}
}
/**
* i18n friendly version of basename()
*
* @param string $path File path
* @param string $suffix If the filename ends in suffix this will also be cut off
* @return string
*/
function ai1wm_basename( $path, $suffix = '' ) {
return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
}
/**
* i18n friendly version of dirname()
*
* @param string $path File path
* @return string
*/
function ai1wm_dirname( $path ) {
return urldecode( dirname( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ) ) );
}
/**
* Replace forward slash with current directory separator
*
* @param string $path Path
* @return string
*/
function ai1wm_replace_forward_slash_with_directory_separator( $path ) {
return str_replace( '/', DIRECTORY_SEPARATOR, $path );
}
/**
* Replace current directory separator with forward slash
*
* @param string $path Path
* @return string
*/
function ai1wm_replace_directory_separator_with_forward_slash( $path ) {
return str_replace( DIRECTORY_SEPARATOR, '/', $path );
}
/**
* Escape Windows directory separator
*
* @param string $path Path
* @return string
*/
function ai1wm_escape_windows_directory_separator( $path ) {
return preg_replace( '/[\\\\]+/', '\\\\\\\\', $path );
}
/**
* Should reset WordPress permalinks?
*
* @param array $params Request parameters
* @return boolean
*/
function ai1wm_should_reset_permalinks( $params ) {
global $wp_rewrite, $is_apache;
// Permalinks are not supported
if ( empty( $params['using_permalinks'] ) ) {
if ( $wp_rewrite->using_permalinks() ) {
if ( $is_apache ) {
if ( ! apache_mod_loaded( 'mod_rewrite', false ) ) {
return true;
}
}
}
}
return false;
}
/**
* Get .htaccess file content
*
* @return string
*/
function ai1wm_get_htaccess() {
if ( is_file( AI1WM_WORDPRESS_HTACCESS ) ) {
return @file_get_contents( AI1WM_WORDPRESS_HTACCESS );
}
return '';
}
/**
* Get web.config file content
*
* @return string
*/
function ai1wm_get_webconfig() {
if ( is_file( AI1WM_WORDPRESS_WEBCONFIG ) ) {
return @file_get_contents( AI1WM_WORDPRESS_WEBCONFIG );
}
return '';
}
/**
* Get available space on filesystem or disk partition
*
* @param string $path Directory of the filesystem or disk partition
* @return mixed
*/
function ai1wm_disk_free_space( $path ) {
if ( function_exists( 'disk_free_space' ) ) {
return @disk_free_space( $path );
}
}
/**
* Set response header to json end echo data
*
* @param array $data
* @param int $options
* @param int $depth
* @return void
*/
function ai1wm_json_response( $data, $options = 0 ) {
if ( ! headers_sent() ) {
header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset', 'utf-8' ) );
}
echo json_encode( $data, $options );
}
/**
* Determines if the server can encrypt backups
*
* @return boolean
*/
function ai1wm_can_encrypt() {
if ( ! function_exists( 'openssl_encrypt' ) ) {
return false;
}
if ( ! function_exists( 'openssl_random_pseudo_bytes' ) ) {
return false;
}
if ( ! function_exists( 'openssl_cipher_iv_length' ) ) {
return false;
}
if ( ! function_exists( 'sha1' ) ) {
return false;
}
if ( ! in_array( AI1WM_CIPHER_NAME, array_map( 'strtoupper', openssl_get_cipher_methods() ) ) ) {
return false;
}
return true;
}
/**
* Determines if the server can decrypt backups
*
* @return boolean
*/
function ai1wm_can_decrypt() {
if ( ! function_exists( 'openssl_decrypt' ) ) {
return false;
}
if ( ! function_exists( 'openssl_random_pseudo_bytes' ) ) {
return false;
}
if ( ! function_exists( 'openssl_cipher_iv_length' ) ) {
return false;
}
if ( ! function_exists( 'sha1' ) ) {
return false;
}
if ( ! in_array( AI1WM_CIPHER_NAME, array_map( 'strtoupper', openssl_get_cipher_methods() ) ) ) {
return false;
}
return true;
}
/**
* Encrypts a string with a key
*
* @param string $string String to encrypt
* @param string $key Key to encrypt the string with
* @return string
* @throws Ai1wm_Not_Encryptable_Exception
*/
function ai1wm_encrypt_string( $string, $key ) {
$iv_length = ai1wm_crypt_iv_length();
$key = substr( sha1( $key, true ), 0, $iv_length );
$iv = openssl_random_pseudo_bytes( $iv_length );
if ( $iv === false ) {
throw new Ai1wm_Not_Encryptable_Exception( esc_html__( 'Could not generate random bytes. The process cannot continue.', 'all-in-one-wp-migration' ) );
}
$encrypted_string = openssl_encrypt( $string, AI1WM_CIPHER_NAME, $key, OPENSSL_RAW_DATA, $iv );
if ( $encrypted_string === false ) {
throw new Ai1wm_Not_Encryptable_Exception( esc_html__( 'Could not encrypt data. The process cannot continue.', 'all-in-one-wp-migration' ) );
}
return sprintf( '%s%s', $iv, $encrypted_string );
}
/**
* Returns encrypt/decrypt iv length
*
* @return int
* @throws Ai1wm_Not_Encryptable_Exception
*/
function ai1wm_crypt_iv_length() {
$iv_length = openssl_cipher_iv_length( AI1WM_CIPHER_NAME );
if ( $iv_length === false ) {
throw new Ai1wm_Not_Encryptable_Exception( esc_html__( 'Could not obtain cipher length. The process cannot continue.', 'all-in-one-wp-migration' ) );
}
return $iv_length;
}
/**
* Decrypts a string with a eky
*
* @param string $encrypted_string String to decrypt
* @param string $key Key to decrypt the string with
* @return string
* @throws Ai1wm_Not_Encryptable_Exception
* @throws Ai1wm_Not_Decryptable_Exception
*/
function ai1wm_decrypt_string( $encrypted_string, $key ) {
$iv_length = ai1wm_crypt_iv_length();
$key = substr( sha1( $key, true ), 0, $iv_length );
$iv = substr( $encrypted_string, 0, $iv_length );
$decrypted_string = openssl_decrypt( substr( $encrypted_string, $iv_length ), AI1WM_CIPHER_NAME, $key, OPENSSL_RAW_DATA, $iv );
if ( $decrypted_string === false ) {
throw new Ai1wm_Not_Decryptable_Exception( esc_html__( 'Could not decrypt data. The process cannot continue.', 'all-in-one-wp-migration' ) );
}
return $decrypted_string;
}
/**
* Checks if decryption password is valid
*
* @param string $encrypted_signature
* @param string $password
* @return bool
*/
function ai1wm_is_decryption_password_valid( $encrypted_signature, $password ) {
try {
$encrypted_signature = base64_decode( $encrypted_signature );
return ai1wm_decrypt_string( $encrypted_signature, $password ) === AI1WM_SIGN_TEXT;
} catch ( Ai1wm_Not_Decryptable_Exception $exception ) {
return false;
}
}
function ai1wm_populate_roles() {
if ( ! function_exists( 'populate_roles' ) && ! function_exists( 'populate_options' ) && ! function_exists( 'populate_network' ) ) {
require_once( ABSPATH . 'wp-admin/includes/schema.php' );
}
if ( function_exists( 'populate_roles' ) ) {
populate_roles();
}
}
/**
* Set basic auth header to request
*
* @param array $headers
*
* @return array
*/
function ai1wm_auth_headers( $headers = array() ) {
if ( $hash = get_option( AI1WM_AUTH_HEADER ) ) {
$headers['Authorization'] = sprintf( 'Basic %s', $hash );
}
if ( ( $user = get_option( AI1WM_AUTH_USER ) ) && ( $password = get_option( AI1WM_AUTH_PASSWORD ) ) ) {
if ( ! isset( $headers['Authorization'] ) && ( $hash = base64_encode( sprintf( '%s:%s', $user, $password ) ) ) ) {
update_option( AI1WM_AUTH_HEADER, $hash );
$headers['Authorization'] = sprintf( 'Basic %s', $hash );
}
delete_option( AI1WM_AUTH_USER );
delete_option( AI1WM_AUTH_PASSWORD );
}
return $headers;
}
/**
* Check if direct download of backup supported
*
* @return bool
*/
function ai1wm_direct_download_supported() {
return ! ( $_SERVER['SERVER_NAME'] === 'playground.wordpress.net' || $_SERVER['SERVER_SOFTWARE'] === 'PHP.wasm' );
}
/**
* Get allowed HTML tags when output with `wp_kses()`
*
* @return array
*/
function ai1wm_allowed_html_tags() {
return array(
'a' => array(
'href' => array(),
'title' => array(),
'target' => array(),
'id' => array(),
'name' => array(),
'aria-label' => array(),
'class' => array(),
'style' => array(),
'disabled' => array(),
'download' => array(),
),
'p' => array(
'class' => array(),
'style' => array(),
),
'br' => array(),
'em' => array(),
'strong' => array(),
'input' => array(
'type' => array(),
'name' => array(),
'aria-label' => array(),
'style' => array(),
'id' => array(),
'value' => array(),
'class' => array(),
'disabled' => array(),
),
);
}
/**
* Wrapper for wp_register_style function
*
* @param string $handle Name of the stylesheet
* @param string $src Path of the stylesheet
* @param array $deps An array of registered stylesheet handles this stylesheet depends on
* @param mixed $ver String specifying stylesheet version number
* @param string $media The media for which this stylesheet has been defined
*
* @return bool
*/
function ai1wm_register_style( $handle, $src, $deps = array(), $ver = false, $media = 'all' ) {
if ( is_rtl() ) {
$src = str_replace( '.min.css', '.min.rtl.css', $src );
}
return wp_register_style( $handle, $src, $deps, $ver, $media );
}
/**
* Wrapper for wp_enqueue_style function
*
* @param string $handle Name of the stylesheet
* @param string $src Path of the stylesheet
* @param array $deps An array of registered stylesheet handles this stylesheet depends on
* @param mixed $ver String specifying stylesheet version number
* @param string $media The media for which this stylesheet has been defined
*
* @return void
*/
function ai1wm_enqueue_style( $handle, $src = '', $deps = array(), $ver = false, $media = 'all' ) {
if ( is_rtl() ) {
$src = str_replace( '.min.css', '.min.rtl.css', $src );
}
wp_enqueue_style( $handle, $src, $deps, $ver, $media );
}
/**
* Wrapper for wp_register_script function
*
* @param string $handle Name of the script
* @param string $src Path of the script
* @param array $deps An array of registered script handles this script depends on
* @param mixed $ver String specifying script version number
* @param mixed $args An array of additional script loading strategies
*
* @return bool
*/
function ai1wm_register_script( $handle, $src, $deps = array(), $ver = false, $args = array() ) {
return wp_register_script( $handle, $src, $deps, $ver, $args );
}
/**
* Wrapper for wp_enqueue_script function
*
* @param string $handle Name of the script
* @param string $src Path of the script
* @param array $deps An array of registered script handles this script depends on
* @param mixed $ver String specifying script version number
* @param mixed $args An array of additional script loading strategies
*
* @return void
*/
function ai1wm_enqueue_script( $handle, $src = '', $deps = array(), $ver = false, $args = array() ) {
wp_enqueue_script( $handle, $src, $deps, $ver, $args );
}/**
* Copyright (C) 2014-2025 ServMask Inc.
*
* 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 .
*
* Attribution: This code is part of the All-in-One WP Migration plugin, developed by
*
* ███████╗███████╗██████╗ ██╗ ██╗███╗ ███╗ █████╗ ███████╗██╗ ██╗
* ██╔════╝██╔════╝██╔══██╗██║ ██║████╗ ████║██╔══██╗██╔════╝██║ ██╔╝
* ███████╗█████╗ ██████╔╝██║ ██║██╔████╔██║███████║███████╗█████╔╝
* ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██║╚██╔╝██║██╔══██║╚════██║██╔═██╗
* ███████║███████╗██║ ██║ ╚████╔╝ ██║ ╚═╝ ██║██║ ██║███████║██║ ██╗
* ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
*/
if ( ! defined( 'ABSPATH' ) ) {
die( 'Kangaroos cannot jump here' );
}
class Ai1wm_File {
/**
* Create a file with content
*
* @param string $path Path to the file
* @param string $content Content of the file
* @return boolean
*/
public static function create( $path, $content ) {
if ( ! @file_exists( $path ) ) {
if ( ! @is_writable( dirname( $path ) ) ) {
return false;
}
if ( ! @touch( $path ) ) {
return false;
}
} elseif ( ! @is_writable( $path ) ) {
return false;
}
// No changes were added
if ( function_exists( 'md5_file' ) ) {
if ( @md5_file( $path ) === md5( $content ) ) {
return true;
}
}
$is_written = false;
if ( ( $handle = @fopen( $path, 'w' ) ) !== false ) {
if ( @fwrite( $handle, $content ) !== false ) {
$is_written = true;
}
@fclose( $handle );
}
return $is_written;
}
/**
* Create a file with marker and content
*
* @param string $path Path to the file
* @param string $marker Name of the marker
* @param string $content Content of the file
* @return boolean
*/
public static function insert_with_markers( $path, $marker, $content ) {
return @insert_with_markers( $path, $marker, $content );
}
/**
* Delete a file by path
*
* @param string $path Path to the file
* @return boolean
*/
public static function delete( $path ) {
if ( ! @file_exists( $path ) ) {
return false;
}
return @unlink( $path );
}
}/**
* Copyright (C) 2014-2025 ServMask Inc.
*
* 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 .
*
* Attribution: This code is part of the All-in-One WP Migration plugin, developed by
*
* ███████╗███████╗██████╗ ██╗ ██╗███╗ ███╗ █████╗ ███████╗██╗ ██╗
* ██╔════╝██╔════╝██╔══██╗██║ ██║████╗ ████║██╔══██╗██╔════╝██║ ██╔╝
* ███████╗█████╗ ██████╔╝██║ ██║██╔████╔██║███████║███████╗█████╔╝
* ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██║╚██╔╝██║██╔══██║╚════██║██╔═██╗
* ███████║███████╗██║ ██║ ╚████╔╝ ██║ ╚═╝ ██║██║ ██║███████║██║ ██╗
* ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
*/
if ( ! defined( 'ABSPATH' ) ) {
die( 'Kangaroos cannot jump here' );
}
abstract class Ai1wm_Database {
/**
* WordPress database handler
*
* @var object
*/
protected $wpdb = null;
/**
* WordPress database base tables
*
* @var array
*/
protected $base_tables = null;
/**
* WordPress database views
*
* @var array
*/
protected $views = null;
/**
* WordPress database tables
*
* @var array
*/
protected $tables = null;
/**
* Old table prefixes
*
* @var array
*/
protected $old_table_prefixes = array();
/**
* New table prefixes
*
* @var array
*/
protected $new_table_prefixes = array();
/**
* Old column prefixes
*
* @var array
*/
protected $old_column_prefixes = array();
/**
* New column prefixes
*
* @var array
*/
protected $new_column_prefixes = array();
/**
* Reserved column prefixes
*
* @var array
*/
protected $reserved_column_prefixes = array();
/**
* Old replace values
*
* @var array
*/
protected $old_replace_values = array();
/**
* New replace values
*
* @var array
*/
protected $new_replace_values = array();
/**
* Old raw replace values
*
* @var array
*/
protected $old_replace_raw_values = array();
/**
* New raw replace values
*
* @var array
*/
protected $new_replace_raw_values = array();
/**
* Table where query
*
* @var array
*/
protected $table_where_query = array();
/**
* Table select columns
*
* @var array
*/
protected $table_select_columns = array();
/**
* Table prefix columns
*
* @var array
*/
protected $table_prefix_columns = array();
/**
* Table prefix filters
*
* @var array
*/
protected $table_prefix_filters = array();
/**
* List all tables that should not be affected by the timeout of the current request
*
* @var array
*/
protected $atomic_tables = array();
/**
* List all tables that should not be populated on import
*
* @var array
*/
protected $empty_tables = array();
/**
* Visual Composer
*
* @var boolean
*/
protected $visual_composer = false;
/**
* Oxygen Builder
*
* @var boolean
*/
protected $oxygen_builder = false;
/**
* BeTheme Responsive
*
* @var boolean
*/
protected $betheme_responsive = false;
/**
* Optimize Press
*
* @var boolean
*/
protected $optimize_press = false;
/**
* Avada Fusion Builder
*
* @var boolean
*/
protected $avada_fusion_builder = false;
/**
* Constructor
*
* @param object $wpdb WPDB instance
*/
public function __construct( $wpdb ) {
$this->wpdb = $wpdb;
// Check Microsoft SQL Server support
if ( is_resource( $this->wpdb->dbh ) ) {
if ( get_resource_type( $this->wpdb->dbh ) === 'SQL Server Connection' ) {
throw new Ai1wm_Database_Exception(
__(
'Your WordPress installation uses Microsoft SQL Server. ' .
'To use All-in-One WP Migration, please change your installation to MySQL and try again. ' .
'Technical details',
'all-in-one-wp-migration'
),
501
);
}
}
// Set database host (HyberDB)
if ( empty( $this->wpdb->dbhost ) ) {
if ( isset( $this->wpdb->last_used_server['host'] ) ) {
$this->wpdb->dbhost = $this->wpdb->last_used_server['host'];
}
}
// Set database name (HyperDB)
if ( empty( $this->wpdb->dbname ) ) {
if ( isset( $this->wpdb->last_used_server['name'] ) ) {
$this->wpdb->dbname = $this->wpdb->last_used_server['name'];
}
}
}
/**
* Set old table prefixes
*
* @param array $prefixes List of table prefixes
* @return object
*/
public function set_old_table_prefixes( $prefixes ) {
$this->old_table_prefixes = $prefixes;
return $this;
}
/**
* Get old table prefixes
*
* @return array
*/
public function get_old_table_prefixes() {
return $this->old_table_prefixes;
}
/**
* Set new table prefixes
*
* @param array $prefixes List of table prefixes
* @return object
*/
public function set_new_table_prefixes( $prefixes ) {
$this->new_table_prefixes = $prefixes;
return $this;
}
/**
* Get new table prefixes
*
* @return array
*/
public function get_new_table_prefixes() {
return $this->new_table_prefixes;
}
/**
* Set old column prefixes
*
* @param array $prefixes List of column prefixes
* @return object
*/
public function set_old_column_prefixes( $prefixes ) {
$this->old_column_prefixes = $prefixes;
return $this;
}
/**
* Get old column prefixes
*
* @return array
*/
public function get_old_column_prefixes() {
return $this->old_column_prefixes;
}
/**
* Set new column prefixes
*
* @param array $prefixes List of column prefixes
* @return object
*/
public function set_new_column_prefixes( $prefixes ) {
$this->new_column_prefixes = $prefixes;
return $this;
}
/**
* Get new column prefixes
*
* @return array
*/
public function get_new_column_prefixes() {
return $this->new_column_prefixes;
}
/**
* Set reserved column prefixes
*
* @param array $prefixes List of column prefixes
* @return object
*/
public function set_reserved_column_prefixes( $prefixes ) {
$this->reserved_column_prefixes = $prefixes;
return $this;
}
/**
* Get reserved column prefixes
*
* @return array
*/
public function get_reserved_column_prefixes() {
return $this->reserved_column_prefixes;
}
/**
* Set old replace values
*
* @param array $values List of values
* @return object
*/
public function set_old_replace_values( $values ) {
$this->old_replace_values = $values;
return $this;
}
/**
* Get old replace values
*
* @return array
*/
public function get_old_replace_values() {
return $this->old_replace_values;
}
/**
* Get old replace values min length
*
* @return integer
*/
protected function get_old_replace_values_min_length() {
static $cached_result = null;
if ( $cached_result === null ) {
$cached_result = min( array_map( 'strlen', $this->get_old_replace_values() ) );
}
return $cached_result;
}
/**
* Set new replace values
*
* @param array $values List of values
* @return object
*/
public function set_new_replace_values( $values ) {
$this->new_replace_values = $values;
return $this;
}
/**
* Get new replace values
*
* @return array
*/
public function get_new_replace_values() {
return $this->new_replace_values;
}
/**
* Set old replace raw values
*
* @param array $values List of values
* @return object
*/
public function set_old_replace_raw_values( $values ) {
$this->old_replace_raw_values = $values;
return $this;
}
/**
* Get old replace raw values
*
* @return array
*/
public function get_old_replace_raw_values() {
return $this->old_replace_raw_values;
}
/**
* Set new replace raw values
*
* @param array $values List of values
* @return object
*/
public function set_new_replace_raw_values( $values ) {
$this->new_replace_raw_values = $values;
return $this;
}
/**
* Get new replace raw values
*
* @return array
*/
public function get_new_replace_raw_values() {
return $this->new_replace_raw_values;
}
/**
* Set table where query
*
* @param string $table_name Table name
* @param array $where_$query Table query
* @return object
*/
public function set_table_where_query( $table_name, $where_query ) {
$this->table_where_query[ strtolower( $table_name ) ] = $where_query;
return $this;
}
/**
* Get table where query
*
* @param string $table_name Table name
* @return string
*/
public function get_table_where_query( $table_name ) {
if ( isset( $this->table_where_query[ strtolower( $table_name ) ] ) ) {
return $this->table_where_query[ strtolower( $table_name ) ];
}
}
/**
* Set table select columns
*
* @param string $table_name Table name
* @param array $column_names Column names
* @return object
*/
public function set_table_select_columns( $table_name, $column_names ) {
foreach ( $column_names as $column_name => $column_expression ) {
$this->table_select_columns[ strtolower( $table_name ) ][ strtolower( $column_name ) ] = $column_expression;
}
return $this;
}
/**
* Get table select columns
*
* @param string $table_name Table name
* @return array
*/
public function get_table_select_columns( $table_name ) {
if ( isset( $this->table_select_columns[ strtolower( $table_name ) ] ) ) {
return $this->table_select_columns[ strtolower( $table_name ) ];
}
}
/**
* Set table prefix columns
*
* @param string $table_name Table name
* @param array $column_names Column names
* @return object
*/
public function set_table_prefix_columns( $table_name, $column_names ) {
foreach ( $column_names as $column_name ) {
$this->table_prefix_columns[ strtolower( $table_name ) ][ strtolower( $column_name ) ] = true;
}
return $this;
}
/**
* Get table prefix columns
*
* @param string $table_name Table name
* @return array
*/
public function get_table_prefix_columns( $table_name ) {
if ( isset( $this->table_prefix_columns[ strtolower( $table_name ) ] ) ) {
return $this->table_prefix_columns[ strtolower( $table_name ) ];
}
}
/**
* Add table prefix filter
*
* @param string $table_prefix Table prefix
* @param string $exclude_prefix Exclude prefix
* @return object
*/
public function add_table_prefix_filter( $table_prefix, $exclude_prefix = null ) {
$this->table_prefix_filters[] = array( $table_prefix, $exclude_prefix );
return $this;
}
/**
* Get table prefix filter
*
* @return array
*/
public function get_table_prefix_filters() {
return $this->table_prefix_filters;
}
/**
* Set atomic tables
*
* @param array $tables List of tables
* @return object
*/
public function set_atomic_tables( $tables ) {
$this->atomic_tables = $tables;
return $this;
}
/**
* Get atomic tables
*
* @return array
*/
public function get_atomic_tables() {
return $this->atomic_tables;
}
/**
* Set empty tables
*
* @param array $tables List of tables
* @return object
*/
public function set_empty_tables( $tables ) {
$this->empty_tables = $tables;
return $this;
}
/**
* Get empty tables
*
* @return array
*/
public function get_empty_tables() {
return $this->empty_tables;
}
/**
* Set Visual Composer
*
* @param boolean $active Is Visual Composer Active?
* @return object
*/
public function set_visual_composer( $active ) {
$this->visual_composer = $active;
return $this;
}
/**
* Get Visual Composer
*
* @return boolean
*/
public function get_visual_composer() {
return $this->visual_composer;
}
/**
* Set Oxygen Builder
*
* @param boolean $active Is Oxygen Builder Active?
* @return object
*/
public function set_oxygen_builder( $active ) {
$this->oxygen_builder = $active;
return $this;
}
/**
* Get Oxygen Builder
*
* @return boolean
*/
public function get_oxygen_builder() {
return $this->oxygen_builder;
}
/**
* Set BeTheme Responsive
*
* @param boolean $active Is BeTheme Responsive Active?
* @return object
*/
public function set_betheme_responsive( $active ) {
$this->betheme_responsive = $active;
return $this;
}
/**
* Get BeTheme Responsive
*
* @return boolean
*/
public function get_betheme_responsive() {
return $this->betheme_responsive;
}
/**
* Set Optimize Press
*
* @param boolean $active Is Optimize Press Active?
* @return object
*/
public function set_optimize_press( $active ) {
$this->optimize_press = $active;
return $this;
}
/**
* Get Optimize Press
*
* @return boolean
*/
public function get_optimize_press() {
return $this->optimize_press;
}
/**
* Set Avada Fusion Builder
*
* @param boolean $active Is Avada Fusion Builder Active?
* @return object
*/
public function set_avada_fusion_builder( $active ) {
$this->avada_fusion_builder = $active;
return $this;
}
/**
* Get Avada Fusion Builder
*
* @return boolean
*/
public function get_avada_fusion_builder() {
return $this->avada_fusion_builder;
}
/**
* Get views
*
* @return array
*/
protected function get_views() {
if ( is_null( $this->views ) ) {
$where_query = array();
// Get lower case table names
$lower_case_table_names = $this->get_lower_case_table_names();
// Loop over table prefixes
if ( $this->get_table_prefix_filters() ) {
foreach ( $this->get_table_prefix_filters() as $prefix_filter ) {
if ( isset( $prefix_filter[0], $prefix_filter[1] ) ) {
if ( $lower_case_table_names ) {
$where_query[] = sprintf( "(`Tables_in_%s` REGEXP '^%s' AND `Tables_in_%s` NOT REGEXP '^%s')", $this->wpdb->dbname, $prefix_filter[0], $this->wpdb->dbname, $prefix_filter[1] );
} else {
$where_query[] = sprintf( "(CAST(`Tables_in_%s` AS BINARY) REGEXP BINARY '^%s' AND CAST(`Tables_in_%s` AS BINARY) NOT REGEXP BINARY '^%s')", $this->wpdb->dbname, $prefix_filter[0], $this->wpdb->dbname, $prefix_filter[1] );
}
} else {
if ( $lower_case_table_names ) {
$where_query[] = sprintf( "`Tables_in_%s` REGEXP '^%s'", $this->wpdb->dbname, $prefix_filter[0] );
} else {
$where_query[] = sprintf( "CAST(`Tables_in_%s` AS BINARY) REGEXP BINARY '^%s'", $this->wpdb->dbname, $prefix_filter[0] );
}
}
}
} else {
$where_query[] = 1;
}
$this->views = array();
// Loop over views
$result = $this->query( sprintf( "SHOW FULL TABLES FROM `%s` WHERE `Table_type` = 'VIEW' AND (%s)", $this->wpdb->dbname, implode( ' OR ', $where_query ) ) );
while ( $row = $this->fetch_row( $result ) ) {
if ( isset( $row[0] ) ) {
$this->views[] = $row[0];
}
}
$this->free_result( $result );
}
return $this->views;
}
/**
* Get base tables
*
* @return array
*/
protected function get_base_tables() {
if ( is_null( $this->base_tables ) ) {
$where_query = array();
// Get lower case table names
$lower_case_table_names = $this->get_lower_case_table_names();
// Loop over table prefixes
if ( $this->get_table_prefix_filters() ) {
foreach ( $this->get_table_prefix_filters() as $prefix_filter ) {
if ( isset( $prefix_filter[0], $prefix_filter[1] ) ) {
if ( $lower_case_table_names ) {
$where_query[] = sprintf( "(`Tables_in_%s` REGEXP '^%s' AND `Tables_in_%s` NOT REGEXP '^%s')", $this->wpdb->dbname, $prefix_filter[0], $this->wpdb->dbname, $prefix_filter[1] );
} else {
$where_query[] = sprintf( "(CAST(`Tables_in_%s` AS BINARY) REGEXP BINARY '^%s' AND CAST(`Tables_in_%s` AS BINARY) NOT REGEXP BINARY '^%s')", $this->wpdb->dbname, $prefix_filter[0], $this->wpdb->dbname, $prefix_filter[1] );
}
} else {
if ( $lower_case_table_names ) {
$where_query[] = sprintf( "`Tables_in_%s` REGEXP '^%s'", $this->wpdb->dbname, $prefix_filter[0] );
} else {
$where_query[] = sprintf( "CAST(`Tables_in_%s` AS BINARY) REGEXP BINARY '^%s'", $this->wpdb->dbname, $prefix_filter[0] );
}
}
}
} else {
$where_query[] = 1;
}
$this->base_tables = array();
// Loop over base tables
$result = $this->query( sprintf( "SHOW FULL TABLES FROM `%s` WHERE `Table_type` = 'BASE TABLE' AND (%s)", $this->wpdb->dbname, implode( ' OR ', $where_query ) ) );
while ( $row = $this->fetch_row( $result ) ) {
if ( isset( $row[0] ) ) {
$this->base_tables[] = $row[0];
}
}
$this->free_result( $result );
}
return $this->base_tables;
}
/**
* Set tables
*
* @param array $tables List of tables
* @return object
*/
public function set_tables( $tables ) {
$this->tables = $tables;
return $this;
}
/**
* Get tables
*
* @return array
*/
public function get_tables() {
if ( is_null( $this->tables ) ) {
return array_merge( $this->get_base_tables(), $this->get_views() );
}
return $this->tables;
}
/**
* Export database into a file
*
* @param string $file_name File name
* @param integer $query_offset Query offset
* @param integer $table_index Table index
* @param integer $table_offset Table offset
* @param integer $table_rows Table rows
* @return boolean
*/
public function export( $file_name, &$query_offset = 0, &$table_index = 0, &$table_offset = 0, &$table_rows = 0 ) {
// Set file handler
$file_handler = ai1wm_open( $file_name, 'cb' );
// Start time
$start = microtime( true );
// Flag to hold if all tables have been processed
$completed = true;
// Set SQL mode
$this->query( "SET SESSION sql_mode = ''" );
// Get tables
$tables = $this->get_tables();
// Get views
$views = $this->get_views();
// Set file pointer at the query offset
if ( fseek( $file_handler, $query_offset ) !== -1 ) {
// Write headers
if ( $query_offset === 0 ) {
ai1wm_write( $file_handler, $this->get_header() );
}
// Export tables
for ( ; $table_index < count( $tables ); ) {
// Get table name
$table_name = $tables[ $table_index ];
// Replace table name prefixes
$new_table_name = $this->replace_table_prefixes( $table_name, 0 );
// Loop over tables and views
if ( in_array( $table_name, $views ) ) {
// Get create view statement
if ( $table_offset === 0 ) {
// Write view drop statement
$drop_view = "\nDROP VIEW IF EXISTS `{$new_table_name}`;\n";
// Write drop view statement
ai1wm_write( $file_handler, $drop_view );
// Get create view statement
$create_view = $this->get_create_view( $table_name );
// Replace create view quotes
$create_view = $this->replace_view_quotes( $create_view );
// Replace create view name
$create_view = $this->replace_view_name( $create_view, $table_name, $new_table_name );
// Replace create view identifiers
$create_view = $this->replace_view_identifiers( $create_view );
// Replace create view options
$create_view = $this->replace_view_options( $create_view );
// Write create view statement
ai1wm_write( $file_handler, $create_view );
// Write end of statement
ai1wm_write( $file_handler, ";\n\n" );
}
// Set curent table index
$table_index++;
// Set current table offset
$table_offset = 0;
} else {
// Get create table statement
if ( $table_offset === 0 ) {
// Write table drop statement
$drop_table = "\nDROP TABLE IF EXISTS `{$new_table_name}`;\n";
// Write table statement
ai1wm_write( $file_handler, $drop_table );
// Get create table statement
$create_table = $this->get_create_table( $table_name );
// Replace create table quotes
$create_table = $this->replace_table_quotes( $create_table );
// Replace create table name
$create_table = $this->replace_table_name( $create_table, $table_name, $new_table_name );
// Replace create table comments
$create_table = $this->replace_table_comments( $create_table );
// Replace create table constraints
$create_table = $this->replace_table_constraints( $create_table );
// Replace create table options
$create_table = $this->replace_table_options( $create_table );
// Replace create table defaults
$create_table = $this->replace_table_defaults( $create_table );
// Write create table statement
ai1wm_write( $file_handler, $create_table );
// Write end of statement
ai1wm_write( $file_handler, ";\n\n" );
}
// Get primary keys
$primary_keys = $this->get_primary_keys( $table_name );
// Get column types
$column_types = $this->get_column_types( $table_name );
// Get prefix columns
$prefix_columns = $this->get_table_prefix_columns( $table_name );
do {
// Set query
if ( $primary_keys ) {
// Set table keys
$table_keys = array();
foreach ( $primary_keys as $key ) {
$table_keys[] = sprintf( '`%s`', $key );
}
$table_keys = implode( ', ', $table_keys );
// Set table where query
if ( ! ( $table_where = $this->get_table_where_query( $table_name ) ) ) {
$table_where = 1;
}
// Set table select columns
if ( ! ( $select_columns = $this->get_table_select_columns( $table_name ) ) ) {
$select_columns = array( 't1.*' );
}
$select_columns = implode( ', ', $select_columns );
// Set query with offset and rows count
if ( defined( 'AI1WM_DISABLE_LATE_ROW_LOOKUPS' ) ) {
$query = sprintf( 'SELECT %s FROM `%s` AS t1 WHERE %s ORDER BY %s LIMIT %d, %d', $select_columns, $table_name, $table_where, $table_keys, $table_offset, AI1WM_MAX_SELECT_RECORDS );
} else {
$query = sprintf( 'SELECT %s FROM `%s` AS t1 JOIN (SELECT %s FROM `%s` WHERE %s ORDER BY %s LIMIT %d, %d) AS t2 USING (%s)', $select_columns, $table_name, $table_keys, $table_name, $table_where, $table_keys, $table_offset, AI1WM_MAX_SELECT_RECORDS, $table_keys );
}
} else {
$table_keys = 1;
// Set table where query
if ( ! ( $table_where = $this->get_table_where_query( $table_name ) ) ) {
$table_where = 1;
}
// Set table select columns
if ( ! ( $select_columns = $this->get_table_select_columns( $table_name ) ) ) {
$select_columns = array( '*' );
}
$select_columns = implode( ', ', $select_columns );
// Set query with offset and rows count
$query = sprintf( 'SELECT %s FROM `%s` WHERE %s ORDER BY %s LIMIT %d, %d', $select_columns, $table_name, $table_where, $table_keys, $table_offset, AI1WM_MAX_SELECT_RECORDS );
}
// Run SQL query
$result = $this->query( $query );
// Repair table data
if ( $this->errno() === 1194 ) {
// Current table is marked as crashed and should be repaired
$this->repair_table( $table_name );
// Run SQL query
$result = $this->query( $query );
}
// Generate insert statements
if ( $num_rows = $this->num_rows( $result ) ) {
// Loop over table rows
while ( $row = $this->fetch_assoc( $result ) ) {
// Write start transaction
if ( $table_offset % AI1WM_MAX_TRANSACTION_QUERIES === 0 ) {
ai1wm_write( $file_handler, "START TRANSACTION;\n" );
}
$items = array();
foreach ( $row as $key => $value ) {
// Replace table prefix columns
if ( isset( $prefix_columns[ strtolower( $key ) ] ) ) {
$value = $this->replace_column_prefixes( $value, 0 );
}
$items[] = $this->prepare_table_values( $value, $column_types[ strtolower( $key ) ] );
}
// Set table values
$table_values = implode( ',', $items );
// Set insert statement
$table_insert = "INSERT INTO `{$new_table_name}` VALUES ({$table_values});\n";
// Write insert statement
ai1wm_write( $file_handler, $table_insert );
// Set current table offset
$table_offset++;
// Set current table rows
$table_rows++;
// Write end of transaction
if ( $table_offset % AI1WM_MAX_TRANSACTION_QUERIES === 0 ) {
ai1wm_write( $file_handler, "COMMIT;\n" );
}
}
} else {
// Write end of transaction
if ( $table_offset % AI1WM_MAX_TRANSACTION_QUERIES !== 0 ) {
ai1wm_write( $file_handler, "COMMIT;\n" );
}
// Set curent table index
$table_index++;
// Set current table offset
$table_offset = 0;
}
// Close result cursor
$this->free_result( $result );
// Time elapsed
if ( ( $timeout = apply_filters( 'ai1wm_completed_timeout', 10 ) ) ) {
if ( ( microtime( true ) - $start ) > $timeout ) {
$completed = false;
break 2;
}
}
} while ( $num_rows > 0 );
}
}
}
// Set query offset
$query_offset = ftell( $file_handler );
// Close file handler
ai1wm_close( $file_handler );
return $completed;
}
/**
* Import database from a file
*
* @param string $file_name File name
* @param integer $query_offset Query offset
* @return boolean
*/
public function import( $file_name, &$query_offset = 0 ) {
// Set max allowed packet
$max_allowed_packet = $this->get_max_allowed_packet();
// Set file handler
$file_handler = ai1wm_open( $file_name, 'rb' );
// Start time
$start = microtime( true );
// Flag to hold if all tables have been processed
$completed = true;
// Set SQL Mode
$this->query( "SET SESSION sql_mode = ''" );
// Set file pointer at the query offset
if ( fseek( $file_handler, $query_offset ) !== -1 ) {
$query = null;
// Start transaction
if ( $this->use_transactions() ) {
$this->query( 'START TRANSACTION' );
}
// Read database file line by line
while ( ( $line = fgets( $file_handler ) ) !== false ) {
$query .= $line;
// End of query
if ( preg_match( '/;\s*$/S', $query ) ) {
$query = trim( $query );
// Check max allowed packet
if ( strlen( $query ) <= $max_allowed_packet ) {
// Replace table prefixes
$query = $this->replace_table_prefixes( $query );
// Skip table query
if ( $this->should_ignore_query( $query ) === false ) {
// Replace table collations
$query = $this->replace_table_collations( $query );
// Replace table values
$query = $this->replace_table_values( $query );
// Replace raw values
$query = $this->replace_raw_values( $query );
// Run SQL query
$this->query( $query );
// Replace table engines (Azure)
if ( $this->errno() === 1030 ) {
// Replace table engines
$query = $this->replace_table_engines( $query );
// Run SQL query
$this->query( $query );
}
// Replace table row format (MyISAM and InnoDB)
if ( $this->errno() === 1071 || $this->errno() === 1709 ) {
// Replace table row format
$query = $this->replace_table_row_format( $query );
// Run SQL query
$this->query( $query );
}
// Replace table full-text indexes (MySQL <= 5.5)
if ( $this->errno() === 1214 ) {
// Full-text searches are supported for MyISAM tables only.
// In MySQL 5.6 and up, they can also be used with InnoDB tables
$query = $this->replace_table_fulltext_indexes( $query );
// Run SQL query
$this->query( $query );
}
// Check tablespace exists
if ( $this->errno() === 1813 ) {
throw new Ai1wm_Database_Exception( __( 'Error importing database table. Technical details', 'all-in-one-wp-migration' ), 503 );
}
// Check max queries per hour
if ( $this->errno() === 1226 ) {
if ( stripos( $this->error(), 'max_queries_per_hour' ) !== false ) {
throw new Ai1wm_Database_Exception(
__(
'Your WordPress installation has reached the maximum allowed queries per hour set by your server admin or hosting provider. ' .
'To use All-in-One WP Migration, please increase MySQL max_queries_per_hour limit. ' .
'Technical details',
'all-in-one-wp-migration'
),
503
);
} elseif ( stripos( $this->error(), 'max_updates_per_hour' ) !== false ) {
throw new Ai1wm_Database_Exception(
__(
'Your WordPress installation has reached the maximum allowed updates per hour set by your server admin or hosting provider. ' .
'To use All-in-One WP Migration, please increase MySQL max_updates_per_hour limit. ' .
'Technical details',
'all-in-one-wp-migration'
),
503
);
} elseif ( stripos( $this->error(), 'max_connections_per_hour' ) !== false ) {
throw new Ai1wm_Database_Exception(
__(
'Your WordPress installation has reached the maximum allowed connections per hour set by your server admin or hosting provider. ' .
'To use All-in-One WP Migration, please increase MySQL max_connections_per_hour limit. ' .
'Technical details',
'all-in-one-wp-migration'
),
503
);
} elseif ( stripos( $this->error(), 'max_user_connections' ) !== false ) {
throw new Ai1wm_Database_Exception(
__(
'Your WordPress installation has reached the maximum allowed user connections set by your server admin or hosting provider. ' .
'To use All-in-One WP Migration, please increase MySQL max_user_connections limit. ' .
'Technical details',
'all-in-one-wp-migration'
),
503
);
}
}
}
// Time elapsed
if ( ( $timeout = apply_filters( 'ai1wm_completed_timeout', 10 ) ) ) {
if ( ! $this->is_atomic_query( $query ) ) {
if ( ( microtime( true ) - $start ) > $timeout ) {
$completed = false;
break;
}
}
}
}
$query = null;
}
}
// End transaction
if ( $this->use_transactions() ) {
$this->query( 'COMMIT' );
}
}
// Set query offset
$query_offset = ftell( $file_handler );
// Close file handler
ai1wm_close( $file_handler );
return $completed;
}
/**
* Flush database
*
* @return void
*/
public function flush() {
$views = $this->get_views();
foreach ( $this->get_tables() as $table_name ) {
if ( in_array( $table_name, $views ) ) {
$this->query( "DROP VIEW IF EXISTS `{$table_name}`" );
} else {
$this->query( "DROP TABLE IF EXISTS `{$table_name}`" );
}
}
}
/**
* Get MySQL max allowed packet
*
* @return integer
*/
protected function get_max_allowed_packet() {
$result = $this->query( "SHOW VARIABLES LIKE 'max_allowed_packet'" );
$row = $this->fetch_assoc( $result );
// Close result cursor
$this->free_result( $result );
// Get max allowed packet
if ( isset( $row['Value'] ) ) {
return $row['Value'];
}
}
/**
* Get MySQL lower case table names
*
* @return integer
*/
protected function get_lower_case_table_names() {
$result = $this->query( "SHOW VARIABLES LIKE 'lower_case_table_names'" );
$row = $this->fetch_assoc( $result );
// Close result cursor
$this->free_result( $result );
// Get lower case table names
if ( isset( $row['Value'] ) ) {
return $row['Value'];
}
}
/**
* Get MySQL collation name
*
* @param string $collation_name Collation name
* @return string
*/
protected function get_collation( $collation_name ) {
$result = $this->query( "SHOW COLLATION LIKE '{$collation_name}'" );
$row = $this->fetch_assoc( $result );
// Close result cursor
$this->free_result( $result );
// Get collation name
if ( isset( $row['Collation'] ) ) {
return $row['Collation'];
}
}
/**
* Get MySQL create view
*
* @param string $view_name View name
* @return string
*/
protected function get_create_view( $view_name ) {
$result = $this->query( "SHOW CREATE VIEW `{$view_name}`" );
$row = $this->fetch_assoc( $result );
// Close result cursor
$this->free_result( $result );
// Get create view
if ( isset( $row['Create View'] ) ) {
return $row['Create View'];
}
}
/**
* Get MySQL create table
*
* @param string $table_name Table name
* @return string
*/
protected function get_create_table( $table_name ) {
$result = $this->query( "SHOW CREATE TABLE `{$table_name}`" );
$row = $this->fetch_assoc( $result );
// Close result cursor
$this->free_result( $result );
// Get create table
if ( isset( $row['Create Table'] ) ) {
return $row['Create Table'];
}
}
/**
* Repair MySQL table
*
* @param string $table_name Table name
* @return void
*/
protected function repair_table( $table_name ) {
$this->query( "REPAIR TABLE `{$table_name}`" );
}
/**
* Get MySQL primary keys
*
* @param string $table_name Table name
* @return array
*/
protected function get_primary_keys( $table_name ) {
$primary_keys = array();
// Get primary keys
$result = $this->query( "SHOW KEYS FROM `{$table_name}` WHERE `Key_name` = 'PRIMARY'" );
while ( $row = $this->fetch_assoc( $result ) ) {
if ( isset( $row['Column_name'] ) ) {
$primary_keys[] = $row['Column_name'];
}
}
// Close result cursor
$this->free_result( $result );
return $primary_keys;
}
/**
* Get MySQL unique keys
*
* @param string $table_name Table name
* @return array
*/
protected function get_unique_keys( $table_name ) {
$unique_keys = array();
// Get unique keys
$result = $this->query( "SHOW KEYS FROM `{$table_name}` WHERE `Non_unique` = 0" );
while ( $row = $this->fetch_assoc( $result ) ) {
if ( isset( $row['Column_name'] ) ) {
$unique_keys[] = $row['Column_name'];
}
}
// Close result cursor
$this->free_result( $result );
return $unique_keys;
}
/**
* Get MySQL column types
*
* @param string $table_name Table name
* @return array
*/
protected function get_column_types( $table_name ) {
$column_types = array();
// Get column types
$result = $this->query( "SHOW COLUMNS FROM `{$table_name}`" );
while ( $row = $this->fetch_assoc( $result ) ) {
if ( isset( $row['Field'] ) ) {
$column_types[ strtolower( $row['Field'] ) ] = $row['Type'];
}
}
// Close result cursor
$this->free_result( $result );
return $column_types;
}
/**
* Get MySQL column names
*
* @param string $table_name Table name
* @return array
*/
public function get_column_names( $table_name ) {
$column_names = array();
// Get column names
$result = $this->query( "SHOW COLUMNS FROM `{$table_name}`" );
while ( $row = $this->fetch_assoc( $result ) ) {
if ( isset( $row['Field'] ) ) {
$column_names[ strtolower( $row['Field'] ) ] = $row['Field'];
}
}
// Close result cursor
$this->free_result( $result );
return $column_names;
}
/**
* Replace table quotes
*
* @param string $input Table value
* @return string
*/
protected function replace_table_quotes( $input ) {
return $input;
}
/**
* Replace table name
*
* @param string $input Table value
* @param string $old_table_name Old table name
* @param string $new_table_name New table name
* @return string
*/
protected function replace_table_name( $input, $old_table_name, $new_table_name ) {
$position = stripos( $input, "`$old_table_name`" );
if ( $position !== false ) {
$input = substr_replace( $input, "`$new_table_name`", $position, strlen( "`$old_table_name`" ) );
}
return $input;
}
/**
* Replace view quotes
*
* @param string $input View value
* @return string
*/
protected function replace_view_quotes( $input ) {
return $input;
}
/**
* Replace view name
*
* @param string $input View value
* @param string $old_view_name Old view name
* @param string $new_view_name New view name
* @return string
*/
protected function replace_view_name( $input, $old_view_name, $new_view_name ) {
$position = stripos( $input, "`$old_view_name`" );
if ( $position !== false ) {
$input = substr_replace( $input, "`$new_view_name`", $position, strlen( "`$old_view_name`" ) );
}
return $input;
}
/**
* Replace view identifiers
*
* @param string $input Table value
* @return string
*/
protected function replace_view_identifiers( $input ) {
$base_tables = $this->get_base_tables();
foreach ( $base_tables as $table_name ) {
if ( ( $new_table_name = $this->replace_table_prefixes( $table_name, 0 ) ) ) {
$input = str_ireplace( "`$table_name`", "`$new_table_name`", $input );
}
}
return $input;
}
/**
* Replace view options
*
* @param string $input Table value
* @return string
*/
protected function replace_view_options( $input ) {
return preg_replace( '/CREATE(.+?)VIEW/i', 'CREATE VIEW', $input );
}
/**
* Replace table prefixes
*
* @param string $input Table value
* @param mixed $position Replace first occurrence at a specified position
* @return string
*/
protected function replace_table_prefixes( $input, $position = false ) {
$search = $this->get_old_table_prefixes();
$replace = $this->get_new_table_prefixes();
// Replace first occurrence at a specified position
if ( $position !== false ) {
for ( $i = 0; $i < count( $search ); $i++ ) {
$current = stripos( $input, $search[ $i ], $position );
if ( $current === $position ) {
$input = substr_replace( $input, $replace[ $i ], $current, strlen( $search[ $i ] ) );
}
}
return $input;
}
return str_ireplace( $search, $replace, $input );
}
/**
* Replace column prefixes
*
* @param string $input Column value
* @param mixed $position Replace first occurrence at a specified position
* @return string
*/
protected function replace_column_prefixes( $input, $position = false ) {
$search = $this->get_old_column_prefixes();
$replace = $this->get_new_column_prefixes();
$reserved = $this->get_reserved_column_prefixes();
// Replace first occurrence at a specified position
if ( $position !== false ) {
for ( $i = 0; $i < count( $reserved ); $i++ ) {
$current = stripos( $input, $reserved[ $i ], $position );
if ( $current === $position ) {
return $input;
}
}
for ( $i = 0; $i < count( $search ); $i++ ) {
$current = stripos( $input, $search[ $i ], $position );
if ( $current === $position ) {
$input = substr_replace( $input, $replace[ $i ], $current, strlen( $search[ $i ] ) );
}
}
return $input;
}
return str_ireplace( $search, $replace, $input );
}
/**
* Replace table values
*
* @param string $input Table value
* @return string
*/
protected function replace_table_values( $input ) {
// Replace base64 encoded values (Visual Composer)
if ( $this->get_visual_composer() ) {
$input = preg_replace_callback( '/\[vc_raw_html\]([a-zA-Z0-9\/+]+={0,2})\[\/vc_raw_html\]/S', array( $this, 'replace_visual_composer_values_callback' ), $input );
}
// Replace base64 encoded values (Oxygen Builder)
if ( $this->get_oxygen_builder() ) {
$input = preg_replace_callback( '/\\\\"(code-php|code-css|code-js)\\\\":\\\\"([a-zA-Z0-9\/+]+={0,2})\\\\"/S', array( $this, 'replace_oxygen_builder_values_callback' ), $input );
}
// Replace base64 encoded values (BeTheme Responsive, Optimize Press and Avada Fusion Builder)
if ( $this->get_betheme_responsive() || $this->get_optimize_press() || $this->get_avada_fusion_builder() ) {
$input = preg_replace_callback( "/'([a-zA-Z0-9\/+]+={0,2})'/S", array( $this, 'replace_base64_values_callback' ), $input );
}
// Replace serialized values
foreach ( $this->get_old_replace_values() as $old_value ) {
if ( strpos( $input, $this->escape( $old_value ) ) !== false ) {
$input = preg_replace_callback( "/'(.*?)(?= $this->get_old_replace_values_min_length() ) {
$matches[1] = Ai1wm_Database_Utility::replace_values( $matches[1], $this->get_old_replace_values(), $this->get_new_replace_values() );
}
// Encode base64 characters
$matches[1] = Ai1wm_Database_Utility::base64_encode( $matches[1] );
}
return '[vc_raw_html]' . $matches[1] . '[/vc_raw_html]';
}
/**
* Replace base64 values callback (Oxygen Builder)
*
* @param array $matches List of matches
* @return string
*/
protected function replace_oxygen_builder_values_callback( $matches ) {
// Validate base64 data
if ( Ai1wm_Database_Utility::base64_validate( $matches[2] ) ) {
// Decode base64 characters
$matches[2] = Ai1wm_Database_Utility::base64_decode( $matches[2] );
// Replace values
if ( strlen( $matches[2] ) >= $this->get_old_replace_values_min_length() ) {
$matches[2] = Ai1wm_Database_Utility::replace_values( $matches[2], $this->get_old_replace_values(), $this->get_new_replace_values() );
}
// Encode base64 characters
$matches[2] = Ai1wm_Database_Utility::base64_encode( $matches[2] );
}
return '\"' . $matches[1] . '\":\"' . $matches[2] . '\"';
}
/**
* Replace base64 values callback (BeTheme Responsive and Optimize Press)
*
* @param array $matches List of matches
* @return string
*/
protected function replace_base64_values_callback( $matches ) {
// Validate base64 data
if ( Ai1wm_Database_Utility::base64_validate( $matches[1] ) ) {
// Decode base64 characters
$matches[1] = Ai1wm_Database_Utility::base64_decode( $matches[1] );
// Replace serialized values
if ( strlen( $matches[1] ) >= $this->get_old_replace_values_min_length() ) {
$matches[1] = Ai1wm_Database_Utility::replace_serialized_values( $matches[1], $this->get_old_replace_values(), $this->get_new_replace_values() );
}
// Encode base64 characters
$matches[1] = Ai1wm_Database_Utility::base64_encode( $matches[1] );
}
return "'" . $matches[1] . "'";
}
/**
* Replace table values callback
*
* @param array $matches List of matches
* @return string
*/
protected function replace_table_values_callback( $matches ) {
// Unescape MySQL special characters
$matches[1] = Ai1wm_Database_Utility::unescape_mysql( $matches[1] );
// Replace serialized values
if ( strlen( $matches[1] ) >= $this->get_old_replace_values_min_length() ) {
$matches[1] = Ai1wm_Database_Utility::replace_serialized_values( $matches[1], $this->get_old_replace_values(), $this->get_new_replace_values() );
}
// Escape MySQL special characters
$matches[1] = Ai1wm_Database_Utility::escape_mysql( $matches[1] );
return "'" . $matches[1] . "'";
}
/**
* Replace table collations
*
* @param string $input SQL statement
* @return string
*/
protected function replace_table_collations( $input ) {
static $search = array();
static $replace = array();
// Replace table collations
if ( empty( $search ) || empty( $replace ) ) {
if ( ! $this->wpdb->has_cap( 'utf8mb4_520' ) ) {
if ( ! $this->wpdb->has_cap( 'utf8mb4' ) ) {
$search = array( 'utf8mb4_0900_ai_ci', 'utf8mb4_unicode_520_ci', 'utf8mb4' );
$replace = array( 'utf8_unicode_ci', 'utf8_unicode_ci', 'utf8' );
} else {
$search = array( 'utf8mb4_0900_ai_ci', 'utf8mb4_unicode_520_ci' );
$replace = array( 'utf8mb4_unicode_ci', 'utf8mb4_unicode_ci' );
}
} else {
$search = array( 'utf8mb4_0900_ai_ci' );
$replace = array( 'utf8mb4_unicode_520_ci' );
}
}
return str_replace( $search, $replace, $input );
}
/**
* Replace raw values
*
* @param string $input SQL statement
* @return string
*/
protected function replace_raw_values( $input ) {
return Ai1wm_Database_Utility::replace_values( $input, $this->get_old_replace_raw_values(), $this->get_new_replace_raw_values() );
}
/**
* Replace table comments
*
* @param string $input SQL statement
* @return string
*/
protected function replace_table_comments( $input ) {
return preg_replace( '/\/\*(.+?)\*\//s', '', $input );
}
/**
* Replace table constraints
*
* @param string $input SQL statement
* @return string
*/
protected function replace_table_constraints( $input ) {
$pattern = array(
'/\s+CONSTRAINT(.+)REFERENCES(.+),/i',
'/,\s+CONSTRAINT(.+)REFERENCES(.+)/i',
'/\s+ON(.+)CONFLICT(.+)(ROLLBACK|ABORT|FAIL|IGNORE|REPLACE)/i',
'/\s+COLLATE(.+)(BINARY|NOCASE|RTRIM)/i',
);
return preg_replace( $pattern, '', $input );
}
/**
* Check whether input is transient query
*
* @param string $input SQL statement
* @return boolean
*/
protected function is_transient_query( $input ) {
return strpos( $input, "'_transient_" ) !== false;
}
/**
* Check whether input is site transient query
*
* @param string $input SQL statement
* @return boolean
*/
protected function is_site_transient_query( $input ) {
return strpos( $input, "'_site_transient_" ) !== false;
}
/**
* Check whether input is WooCommerce session query
*
* @param string $input SQL statement
* @return boolean
*/
protected function is_wc_session_query( $input ) {
return strpos( $input, "'_wc_session_" ) !== false;
}
/**
* Check whether input is WP All Import session query
*
* @param string $input SQL statement
* @return boolean
*/
protected function is_wpallimport_session_query( $input ) {
return strpos( $input, "'_wpallimport_session_" ) !== false;
}
/**
* Check whether input is START TRANSACTION query
*
* @param string $input SQL statement
* @return boolean
*/
protected function is_start_transaction_query( $input ) {
return strpos( $input, 'START TRANSACTION' ) === 0;
}
/**
* Check whether input is COMMIT query
*
* @param string $input SQL statement
* @return boolean
*/
protected function is_commit_query( $input ) {
return strpos( $input, 'COMMIT' ) === 0;
}
/**
* Check whether input is DROP TABLE query
*
* @param string $input SQL statement
* @return boolean
*/
protected function is_drop_table_query( $input ) {
return strpos( $input, 'DROP TABLE' ) === 0;
}
/**
* Check whether input is CREATE TABLE query
*
* @param string $input SQL statement
* @return boolean
*/
protected function is_create_table_query( $input ) {
return strpos( $input, 'CREATE TABLE' ) === 0;
}
/**
* Check whether input is INSERT INTO query
*
* @param string $input SQL statement
* @param string $table_name Table name (case insensitive)
* @return boolean
*/
protected function is_insert_into_query( $input, $table_name ) {
return stripos( $input, sprintf( 'INSERT INTO `%s`', $table_name ) ) === 0;
}
/**
* Should ignore query on import?
*
* @param string $input SQL statement
* @return boolean
*/
public function should_ignore_query( $input ) {
$ignore = false;
// Ignore query based on table query
switch ( true ) {
case $this->is_transient_query( $input ):
case $this->is_site_transient_query( $input ):
case $this->is_wc_session_query( $input ):
case $this->is_wpallimport_session_query( $input ):
$ignore = true;
break;
default:
foreach ( $this->get_empty_tables() as $table_name ) {
if ( $this->is_insert_into_query( $input, $table_name ) ) {
$ignore = true;
break;
}
}
}
return $ignore;
}
/**
* Check whether input is atomic query
*
* @param string $input SQL statement
* @return boolean
*/
protected function is_atomic_query( $input ) {
$atomic = false;
// Skip timeout based on table query
switch ( true ) {
case $this->is_drop_table_query( $input ):
case $this->is_create_table_query( $input ):
case $this->is_start_transaction_query( $input ):
case $this->is_commit_query( $input ):
$atomic = true;
break;
default:
// Skip timeout based on table query and table name
foreach ( $this->get_atomic_tables() as $table_name ) {
if ( $this->is_insert_into_query( $input, $table_name ) ) {
$atomic = true;
break;
}
}
}
return $atomic;
}
/**
* Replace table definitions
*
* @param string $input SQL statement
* @return string
*/
protected function replace_table_defaults( $input ) {
return $input;
}
/**
* Replace table options
*
* @param string $input SQL statement
* @return string
*/
protected function replace_table_options( $input ) {
$search = array(
'TYPE=InnoDB',
'TYPE=MyISAM',
'ENGINE=Aria',
'TRANSACTIONAL=0',
'TRANSACTIONAL=1',
'PAGE_CHECKSUM=0',
'PAGE_CHECKSUM=1',
'TABLE_CHECKSUM=0',
'TABLE_CHECKSUM=1',
'ROW_FORMAT=PAGE',
'ROW_FORMAT=FIXED',
'ROW_FORMAT=DYNAMIC',
'AUTOINCREMENT',
);
$replace = array(
'ENGINE=InnoDB',
'ENGINE=MyISAM',
'ENGINE=MyISAM',
'',
'',
'',
'',
'',
'',
'',
'',
'',
'AUTO_INCREMENT',
);
return str_ireplace( $search, $replace, $input );
}
/**
* Replace table engines
*
* @param string $input SQL statement
* @return string
*/
protected function replace_table_engines( $input ) {
$search = array(
'ENGINE=MyISAM',
'ENGINE=Aria',
);
$replace = array(
'ENGINE=InnoDB',
'ENGINE=InnoDB',
);
return str_ireplace( $search, $replace, $input );
}
/**
* Replace table row format
*
* @param string $input SQL statement
* @return string
*/
protected function replace_table_row_format( $input ) {
$search = array(
'ENGINE=InnoDB',
'ENGINE=MyISAM',
);
$replace = array(
'ENGINE=InnoDB ROW_FORMAT=DYNAMIC',
'ENGINE=MyISAM ROW_FORMAT=DYNAMIC',
);
return str_ireplace( $search, $replace, $input );
}
/**
* Replace table full-text indexes (MySQL <= 5.5)
*
* @param string $input SQL statement
* @return string
*/
protected function replace_table_fulltext_indexes( $input ) {
$pattern = array(
'/\s+FULLTEXT KEY(.+),/i',
'/,\s+FULLTEXT KEY(.+)/i',
);
return preg_replace( $pattern, '', $input );
}
/**
* Returns header for dump file
*
* @return string
*/
protected function get_header() {
// Some info about software, source and time
$header = sprintf(
"-- All-in-One WP Migration SQL Dump\n" .
"-- https://servmask.com/\n" .
"--\n" .
"-- Host: %s\n" .
"-- Database: %s\n" .
"-- Class: %s\n" .
"--\n",
$this->wpdb->dbhost,
$this->wpdb->dbname,
get_class( $this )
);
return $header;
}
/**
* Prepare table values
*
* @param string $input Table value
* @param integer $column_type Column type
* @return string
*/
protected function prepare_table_values( $input, $column_type ) {
switch ( true ) {
case is_null( $input ):
return 'NULL';
case stripos( $column_type, 'tinyint' ) === 0:
case stripos( $column_type, 'smallint' ) === 0:
case stripos( $column_type, 'mediumint' ) === 0:
case stripos( $column_type, 'int' ) === 0:
case stripos( $column_type, 'bigint' ) === 0:
case stripos( $column_type, 'float' ) === 0:
case stripos( $column_type, 'double' ) === 0:
case stripos( $column_type, 'decimal' ) === 0:
case stripos( $column_type, 'bit' ) === 0:
return $input;
case stripos( $column_type, 'binary' ) === 0:
case stripos( $column_type, 'varbinary' ) === 0:
case stripos( $column_type, 'tinyblob' ) === 0:
case stripos( $column_type, 'mediumblob' ) === 0:
case stripos( $column_type, 'longblob' ) === 0:
case stripos( $column_type, 'blob' ) === 0:
return '0x' . bin2hex( $input );
default:
return "'" . $this->escape( $input ) . "'";
}
}
/**
* Use MySQL transactions
*
* @return boolean
*/
protected function use_transactions() {
return true;
}
/**
* Check whether table has auto increment attribute
*
* @param string $table_name Table name
* @return boolean
*/
abstract public function has_auto_increment( $table_name );
/**
* Run MySQL query
*
* @param string $input SQL query
* @return resource
*/
abstract public function query( $input );
/**
* Escape string input for MySQL query
*
* @param string $input String to escape
* @return string
*/
abstract public function escape( $input );
/**
* Return the error code for the most recent function call
*
* @return integer
*/
abstract public function errno();
/**
* Return a string description of the last error
*
* @return string
*/
abstract public function error();
/**
* Return server info
*
* @return string
*/
abstract public function server_info();
/**
* Return the result from MySQL query as associative array
*
* @param mixed $result MySQL resource
* @return array
*/
abstract public function fetch_assoc( &$result );
/**
* Return the result from MySQL query as row
*
* @param mixed $result MySQL resource
* @return array
*/
abstract public function fetch_row( &$result );
/**
* Return the number for rows from MySQL results
*
* @param mixed $result MySQL resource
* @return integer
*/
abstract public function num_rows( &$result );
/**
* Free MySQL result memory
*
* @param mixed $result MySQL resource
* @return boolean
*/
abstract public function free_result( &$result );
}/**
* Copyright (C) 2014-2025 ServMask Inc.
*
* 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 .
*
* Attribution: This code is part of the All-in-One WP Migration plugin, developed by
*
* ███████╗███████╗██████╗ ██╗ ██╗███╗ ███╗ █████╗ ███████╗██╗ ██╗
* ██╔════╝██╔════╝██╔══██╗██║ ██║████╗ ████║██╔══██╗██╔════╝██║ ██╔╝
* ███████╗█████╗ ██████╔╝██║ ██║██╔████╔██║███████║███████╗█████╔╝
* ╚════██║██╔══╝ ██╔══██╗╚██╗ ██╔╝██║╚██╔╝██║██╔══██║╚════██║██╔═██╗
* ███████║███████╗██║ ██║ ╚████╔╝ ██║ ╚═╝ ██║██║ ██║███████║██║ ██╗
* ╚══════╝╚══════╝╚═╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
*/
if ( ! defined( 'ABSPATH' ) ) {
die( 'Kangaroos cannot jump here' );
}
class Ai1wm_Database_Mysql extends Ai1wm_Database {
/**
* Check whether table has auto increment attribute
*
* @param string $table_name Table name
* @return boolean
*/
public function has_auto_increment( $table_name ) {
return stripos( $this->get_create_table( $table_name ), 'AUTO_INCREMENT' ) !== false;
}
/**
* Run MySQL query
*
* @param string $input SQL query
* @return mixed
*/
public function query( $input ) {
if ( ! ( $result = mysql_query( $input, $this->wpdb->dbh ) ) ) {
$mysql_errno = 0;
// Get MySQL error code
if ( ! empty( $this->wpdb->dbh ) ) {
if ( is_resource( $this->wpdb->dbh ) ) {
$mysql_errno = mysql_errno( $this->wpdb->dbh );
} else {
$mysql_errno = 2006;
}
}
// MySQL server has gone away, try to reconnect
if ( empty( $this->wpdb->dbh ) || 2006 === $mysql_errno ) {
if ( ! $this->wpdb->check_connection( false ) ) {
throw new Ai1wm_Database_Exception( __( 'Error reconnecting to the database. Technical details', 'all-in-one-wp-migration' ), 503 );
}
$result = mysql_query( $input, $this->wpdb->dbh );
}
}
return $result;
}
/**
* Escape string input for MySQL query
*
* @param string $input String to escape
* @return string
*/
public function escape( $input ) {
return mysql_real_escape_string( $input, $this->wpdb->dbh );
}
/**
* Return the error code for the most recent function call
*
* @return integer
*/
public function errno() {
return mysql_errno( $this->wpdb->dbh );
}
/**
* Return a string description of the last error
*
* @return string
*/
public function error() {
return mysql_error( $this->wpdb->dbh );
}
/**
* Return server info
*
* @return string
*/
public function server_info() {
return mysql_get_server_info( $this->wpdb->dbh );
}
/**
* Return the result from MySQL query as associative array
*
* @param mixed $result MySQL resource
* @return array
*/
public function fetch_assoc( &$result ) {
return mysql_fetch_assoc( $result );
}
/**
* Return the result from MySQL query as row
*
* @param mixed $result MySQL resource
* @return array
*/
public function fetch_row( &$result ) {
return mysql_fetch_row( $result );
}
/**
* Return the number for rows from MySQL results
*
* @param mixed $result MySQL resource
* @return integer
*/
public function num_rows( &$result ) {
return mysql_num_rows( $result );
}
/**
* Free MySQL result memory
*
* @param mixed $result MySQL resource
* @return boolean
*/
public function free_result( &$result ) {
return mysql_free_result( $result );
}
}