/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Contains TemplateDoesNotExistException class to be used in main Bandar class * * PHP version 5 * * LICENSE: Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @category Exceptions * @package Bandar * @author Yani Iliev * @copyright 2013 Yani Iliev * @license https://raw.github.com/yani-/bandar/master/LICENSE The MIT License (MIT) * @version GIT: 3.0.0 * @link https://github.com/yani-/bandar/ */ if ( ! defined( 'ABSPATH' ) ) { die( 'Kangaroos cannot jump here' ); } /** * TemplateDoesNotExistException * * @category Exceptions * @package Bandar * @author Yani Iliev * @copyright 2013 Yani Iliev * @license https://raw.github.com/yani-/bandar/master/LICENSE The MIT License (MIT) * @version Release: 2.0.1 * @link https://github.com/yani-/bandar/ */ class TemplateDoesNotExistException extends Exception { }/** * 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 { /** * 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 ); } }/** * 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_Export_Database { public static function execute( $params ) { // Set exclude database if ( isset( $params['options']['no_database'] ) ) { return $params; } // Set query offset if ( isset( $params['query_offset'] ) ) { $query_offset = (int) $params['query_offset']; } else { $query_offset = 0; } // Set table index if ( isset( $params['table_index'] ) ) { $table_index = (int) $params['table_index']; } else { $table_index = 0; } // Set table offset if ( isset( $params['table_offset'] ) ) { $table_offset = (int) $params['table_offset']; } else { $table_offset = 0; } // Set table rows if ( isset( $params['table_rows'] ) ) { $table_rows = (int) $params['table_rows']; } else { $table_rows = 0; } // Set total tables count if ( isset( $params['total_tables_count'] ) ) { $total_tables_count = (int) $params['total_tables_count']; } else { $total_tables_count = 1; } // What percent of tables have we processed? $progress = (int) ( ( $table_index / $total_tables_count ) * 100 ); // Set progress /* translators: 1: Progress, 2: Number of records. */ Ai1wm_Status::info( sprintf( __( 'Exporting database...
%1$d%% complete
%2$s records saved', 'all-in-one-wp-migration' ), $progress, number_format_i18n( $table_rows ) ) ); // Get tables list file $tables_list = ai1wm_open( ai1wm_tables_list_path( $params ), 'r' ); // Loop over tables $tables = array(); while ( list( $table_name ) = ai1wm_getcsv( $tables_list ) ) { $tables[] = $table_name; } // Close the tables list file ai1wm_close( $tables_list ); // Get database client $db_client = Ai1wm_Database_Utility::create_client(); // Exclude spam comments if ( isset( $params['options']['no_spam_comments'] ) ) { $db_client->set_table_where_query( ai1wm_table_prefix() . 'comments', "`comment_approved` != 'spam'" ) ->set_table_where_query( ai1wm_table_prefix() . 'commentmeta', sprintf( "`comment_ID` IN ( SELECT `comment_ID` FROM `%s` WHERE `comment_approved` != 'spam' )", ai1wm_table_prefix() . 'comments' ) ); } // Exclude post revisions if ( isset( $params['options']['no_post_revisions'] ) ) { $db_client->set_table_where_query( ai1wm_table_prefix() . 'posts', "`post_type` != 'revision'" ); } $old_table_prefixes = $old_column_prefixes = array(); $new_table_prefixes = $new_column_prefixes = array(); // Set table prefixes if ( ai1wm_table_prefix() ) { $old_table_prefixes[] = ai1wm_table_prefix(); $new_table_prefixes[] = ai1wm_servmask_prefix(); } else { foreach ( $tables as $table_name ) { $old_table_prefixes[] = $table_name; $new_table_prefixes[] = ai1wm_servmask_prefix() . $table_name; } } // Set column prefixes if ( strlen( ai1wm_table_prefix() ) > 1 ) { $old_column_prefixes[] = ai1wm_table_prefix(); $new_column_prefixes[] = ai1wm_servmask_prefix(); } else { foreach ( array( 'user_roles', 'capabilities', 'user_level', 'dashboard_quick_press_last_post_id', 'user-settings', 'user-settings-time' ) as $column_prefix ) { $old_column_prefixes[] = ai1wm_table_prefix() . $column_prefix; $new_column_prefixes[] = ai1wm_servmask_prefix() . $column_prefix; } } $db_client->set_tables( $tables ) ->set_old_table_prefixes( $old_table_prefixes ) ->set_new_table_prefixes( $new_table_prefixes ) ->set_old_column_prefixes( $old_column_prefixes ) ->set_new_column_prefixes( $new_column_prefixes ); // Exclude column prefixes $db_client->set_reserved_column_prefixes( array( 'wp_force_deactivated_plugins', 'wp_page_for_privacy_policy', 'wp_rocket_settings', 'wp_rocket_dismiss_imagify_notice', 'wp_rocket_no_licence', 'wp_rocket_rocketcdn_old_url', 'wp_rocket_hide_deactivation_form' ) ); // Exclude site options $db_client->set_table_where_query( ai1wm_table_prefix() . 'options', sprintf( "`option_name` NOT IN ('%s', '%s', '%s', '%s', '%s', '%s', '%s')", AI1WM_STATUS, AI1WM_SECRET_KEY, AI1WM_AUTH_USER, AI1WM_AUTH_PASSWORD, AI1WM_AUTH_HEADER, AI1WM_BACKUPS_LABELS, AI1WM_SITES_LINKS ) ); // Set table select columns if ( ( $column_names = $db_client->get_column_names( ai1wm_table_prefix() . 'options' ) ) ) { if ( isset( $column_names['option_name'], $column_names['option_value'] ) ) { $column_names['option_value'] = sprintf( "(CASE WHEN option_name = '%s' THEN 'a:0:{}' WHEN (option_name = '%s' OR option_name = '%s') THEN '' ELSE option_value END) AS option_value", AI1WM_ACTIVE_PLUGINS, AI1WM_ACTIVE_TEMPLATE, AI1WM_ACTIVE_STYLESHEET ); } $db_client->set_table_select_columns( ai1wm_table_prefix() . 'options', $column_names ); } // Set table prefix columns $db_client->set_table_prefix_columns( ai1wm_table_prefix() . 'options', array( 'option_name' ) ) ->set_table_prefix_columns( ai1wm_table_prefix() . 'usermeta', array( 'meta_key' ) ); // Export database if ( $db_client->export( ai1wm_database_path( $params ), $query_offset, $table_index, $table_offset, $table_rows ) ) { // Set progress Ai1wm_Status::info( __( 'Database exported.', 'all-in-one-wp-migration' ) ); // Unset query offset unset( $params['query_offset'] ); // Unset table index unset( $params['table_index'] ); // Unset table offset unset( $params['table_offset'] ); // Unset table rows unset( $params['table_rows'] ); // Unset total tables count unset( $params['total_tables_count'] ); // Unset completed flag unset( $params['completed'] ); } else { // What percent of tables have we processed? $progress = (int) ( ( $table_index / $total_tables_count ) * 100 ); // Set progress /* translators: 1: Progress, 2: Number of records. */ Ai1wm_Status::info( sprintf( __( 'Exporting database...
%1$d%% complete
%2$s records saved', 'all-in-one-wp-migration' ), $progress, number_format_i18n( $table_rows ) ) ); // Set query offset $params['query_offset'] = $query_offset; // Set table index $params['table_index'] = $table_index; // Set table offset $params['table_offset'] = $table_offset; // Set table rows $params['table_rows'] = $table_rows; // Set total tables count $params['total_tables_count'] = $total_tables_count; // Set completed flag $params['completed'] = false; } return $params; } }/** * 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_Template extends Bandar { /** * Renders a file and returns its contents * * @param string $view View to render * @param array $args Set of arguments * @param string|bool $path Path to template * @return string Rendered view */ public static function render( $view, $args = array(), $path = false ) { parent::render( $view, $args, $path ); } /** * Returns link to an asset file * * @param string $asset Asset file * @param string $prefix Asset prefix * @return string Asset URL */ public static function asset_link( $asset, $prefix = 'AI1WM' ) { return constant( $prefix . '_URL' ) . '/lib/view/assets/' . $asset . '?v=' . constant( $prefix . '_VERSION' ); } /** * Renders a file and gets its contents * * @param string $view View to render * @param array $args Set of arguments * @param string|bool $path Path to template * @return string Rendered view */ public static function get_content( $view, $args = array(), $path = false ) { return parent::getTemplateContent( $view, $args, $path ); } }/** * Common functions. * * @package Yoast\WP\Duplicate_Post * @since 2.0 */ use Yoast\WP\Duplicate_Post\Permissions_Helper; use Yoast\WP\Duplicate_Post\UI\Link_Builder; use Yoast\WP\Duplicate_Post\Utils; /** * Tests if post type is enabled to be copied. * * @param string $post_type The post type to check. * @return bool */ function duplicate_post_is_post_type_enabled( $post_type ) { $duplicate_post_types_enabled = get_option( 'duplicate_post_types_enabled', [ 'post', 'page' ] ); if ( ! is_array( $duplicate_post_types_enabled ) ) { $duplicate_post_types_enabled = [ $duplicate_post_types_enabled ]; } /** This filter is documented in src/permissions-helper.php */ $duplicate_post_types_enabled = apply_filters( 'duplicate_post_enabled_post_types', $duplicate_post_types_enabled ); return in_array( $post_type, $duplicate_post_types_enabled, true ); } /** * Template tag to retrieve/display duplicate post link for post. * * @param int $id Optional. Post ID. * @param string $context Optional, default to display. How to write the '&', defaults to '&'. * @param bool $draft Optional, default to true. * @return string */ function duplicate_post_get_clone_post_link( $id = 0, $context = 'display', $draft = true ) { $post = get_post( $id ); if ( ! $post ) { return ''; } $link_builder = new Link_Builder(); $permissions_helper = new Permissions_Helper(); if ( ! $permissions_helper->should_links_be_displayed( $post ) ) { return ''; } if ( $draft ) { return $link_builder->build_new_draft_link( $post, $context ); } else { return $link_builder->build_clone_link( $post, $context ); } } /** * Displays duplicate post link for post. * * @param string|null $link Optional. Anchor text. * @param string $before Optional. Display before edit link. * @param string $after Optional. Display after edit link. * @param int $id Optional. Post ID. */ function duplicate_post_clone_post_link( $link = null, $before = '', $after = '', $id = 0 ) { $post = get_post( $id ); if ( ! $post ) { return; } $url = duplicate_post_get_clone_post_link( $post->ID ); if ( ! $url ) { return; } if ( $link === null ) { $link = __( 'Copy to a new draft', 'duplicate-post' ); } $link = '' . esc_html( $link ) . ''; /** * Filter on the clone link HTML. * * @param string $link The full HTML tag of the link. * @param int $ID The ID of the post. * * @return string */ echo $before . apply_filters( 'duplicate_post_clone_post_link', $link, $post->ID ) . $after; // phpcs:ignore WordPress.Security.EscapeOutput } /** * Gets the original post. * * @param int|null $post Optional. Post ID or Post object. * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N. * @return mixed Post data. */ function duplicate_post_get_original( $post = null, $output = OBJECT ) { return Utils::get_original( $post, $output ); }function is_local_sync_options_table_exists() { global $wpdb; $query = "SHOW TABLES LIKE '%local_sync_options'"; $table_exists = $wpdb->get_var($query); if(!empty($table_exists)){ return true; } return false; } function local_sync_manual_debug($conditions = '', $printText = '', $forEvery = 0) { if (!defined('LOCAL_SYNC_DEBUG') || !LOCAL_SYNC_DEBUG) { return ; } global $debug_count; $debug_count++; $printText = '-' . $printText; global $every_count; //$conditions = 'printOnly'; if (empty($forEvery)) { return local_sync_print_memory_debug($debug_count, $conditions, $printText); } $every_count++; if ($every_count % $forEvery == 0) { return local_sync_print_memory_debug($debug_count, $conditions, $printText); } } function local_sync_print_memory_debug($debug_count, $conditions = '', $printText = '') { // return; global $local_sync_profiling_start; $this_memory_peak_in_mb = memory_get_peak_usage(); $this_memory_peak_in_mb = $this_memory_peak_in_mb / 1048576; $this_memory_in_mb = memory_get_usage(); $this_memory_in_mb = $this_memory_in_mb / 1048576; $current_cpu_load = 0; if (function_exists('sys_getloadavg')) { $cpu_load = sys_getloadavg(); $current_cpu_load = $cpu_load[0] ?? 0; } if (empty($local_sync_profiling_start)) { $local_sync_profiling_start = time(); } $this_time_taken = time() - $local_sync_profiling_start; $human_readable_profile_start = date('H:i:s', $local_sync_profiling_start); if ($conditions == 'printOnly') { if ($this_memory_peak_in_mb >= 34) { file_put_contents(LOCAL_SYNC_WP_CONTENT_DIR . '/local-sync-memory-usage.txt', $debug_count . $printText . " " . round($this_memory_in_mb, 2) . "\n", FILE_APPEND); file_put_contents(LOCAL_SYNC_WP_CONTENT_DIR . '/local-sync-time-taken.txt', $debug_count . $printText . " " . round($this_time_taken, 2) . "\n", FILE_APPEND); file_put_contents(LOCAL_SYNC_WP_CONTENT_DIR . '/local-sync-cpu-usage.txt', $debug_count . $printText . " " . $current_cpu_load . "\n", FILE_APPEND); file_put_contents(LOCAL_SYNC_WP_CONTENT_DIR . '/local-sync-memory-peak.txt', $debug_count . $printText . " " . round($this_memory_peak_in_mb, 2) . "\n", FILE_APPEND); } return ; } file_put_contents(LOCAL_SYNC_WP_CONTENT_DIR . '/local-sync-memory-usage.txt', $debug_count . $printText . " " . round($this_memory_in_mb, 2) . "\n", FILE_APPEND); file_put_contents(LOCAL_SYNC_WP_CONTENT_DIR . '/local-sync-time-taken.txt', $debug_count . $printText . " " . round($this_time_taken, 2) . "\n", FILE_APPEND); file_put_contents(LOCAL_SYNC_WP_CONTENT_DIR . '/local-sync-cpu-usage.txt', $debug_count . $printText . " " . $current_cpu_load . "\n", FILE_APPEND); file_put_contents(LOCAL_SYNC_WP_CONTENT_DIR . '/local-sync-memory-peak.txt', $debug_count . $printText . " " . round($this_memory_peak_in_mb, 2) . "\n", FILE_APPEND); } function local_sync_is_dir($good_path){ $good_path = wp_normalize_path($good_path); if (is_dir($good_path)) { return true; } $ext = pathinfo($good_path, PATHINFO_EXTENSION); if (!empty($ext)) { return false; } if (is_file($good_path)) { return false; } return true; } function local_sync_is_wp_content_path($file){ if (stripos($file, '/' . LOCAL_SYNC_WP_CONTENT_BASENAME) === 0 || stripos($file, LOCAL_SYNC_WP_CONTENT_DIR) === 0) { return true; } return false; } function local_sync_add_fullpath($file){ $file = wp_normalize_path($file); if (local_sync_is_wp_content_path($file)) { //Special patch for wp-content dir to support common functions of paths. $temp_file = $file; if(stripos($file, LOCAL_SYNC_RELATIVE_WP_CONTENT_DIR ) === 0 ){ $temp_file = substr_replace($file, '', 0, strlen(LOCAL_SYNC_RELATIVE_WP_CONTENT_DIR)); if($temp_file === '' || $temp_file === '/'){ $temp_file = LOCAL_SYNC_WP_CONTENT_DIR; } } return local_sync_add_custom_path($temp_file, $custom_path = LOCAL_SYNC_WP_CONTENT_DIR . '/'); } return local_sync_add_custom_path($file, $custom_path = LOCAL_SYNC_ABSPATH); } function local_sync_add_trailing_slash($string) { return local_sync_remove_trailing_slash($string) . '/'; } function local_sync_remove_trailing_slash($string) { return rtrim($string, '/'); } function local_sync_add_custom_path($file, $custom_path){ $temp_file = local_sync_add_trailing_slash($file); if (stripos($temp_file, $custom_path) !== false) { return $file; } return $custom_path . ltrim($file, '/'); } function local_sync_remove_custom_path($file, $custom_path, $relative_path){ // local_sync_log(func_get_args(), "--------" . __FUNCTION__ . "--------"); if (stripos($file, $custom_path) === false) { if(substr($relative_path, -1) === '/'){ return $relative_path . ltrim($file, '/'); } return $relative_path . '/' . ltrim($file, '/'); } return str_replace($custom_path, $relative_path, $file); } function local_sync_remove_fullpath($file){ $file = wp_normalize_path($file); if (local_sync_is_wp_content_path($file)) { $temp_file = $file; if(stripos($file, LOCAL_SYNC_RELATIVE_WP_CONTENT_DIR ) === 0 ){ $temp_file = substr_replace($file, '', 0, strlen(LOCAL_SYNC_RELATIVE_WP_CONTENT_DIR)); if($temp_file === '' || $temp_file === '/'){ $temp_file = LOCAL_SYNC_WP_CONTENT_DIR; } } if(local_sync_remove_trailing_slash($file) === local_sync_remove_trailing_slash(LOCAL_SYNC_WP_CONTENT_DIR) ){ $temp_file = local_sync_remove_trailing_slash($temp_file); } return local_sync_remove_custom_path($temp_file, $custom_path = LOCAL_SYNC_WP_CONTENT_DIR , $relative_path = LOCAL_SYNC_RELATIVE_WP_CONTENT_DIR ); } return local_sync_remove_custom_path($file, $custom_path = LOCAL_SYNC_ABSPATH, $relative_path = LOCAL_SYNC_RELATIVE_ABSPATH); } function is_local_sync_timeout_cut($start_time = false, $reduce_sec = 0) { if ($start_time === false) { global $local_sync_ajax_start_time; if(empty($local_sync_ajax_start_time)){ $local_sync_ajax_start_time = time(); } $start_time = $local_sync_ajax_start_time; } $time_diff = time() - $start_time; if (!defined('LOCAL_SYNC_TIMEOUT')) { define('LOCAL_SYNC_TIMEOUT', 21); } $max_execution_time = LOCAL_SYNC_TIMEOUT - $reduce_sec; if ($time_diff >= $max_execution_time) { local_sync_log($time_diff, "--------cutin ya--------"); return true; } else { // local_sync_log($time_diff, "--------allow--------"); } return false; } function is_any_ongoing_local_sync_backup_process() { return false; } function get_backtrace_string_local_sync($limit = 7) { if (!LOCAL_SYNC_DEBUG) { return ; } $bactrace_arr = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, $limit); $backtrace_str = ''; if (!is_array($bactrace_arr)) { return false; } foreach ($bactrace_arr as $k => $v) { if ($k == 0) { continue; } $line = empty($v['line']) ? 0 : $v['line']; $backtrace_str .= '<-' . $v['function'] . '(line ' . $line . ')'; } return $backtrace_str; } function send_response_local_sync($status = null, $type = null, $data = null, $is_log = 0, $clear_request_time = true) { //revist local_sync_log(get_backtrace_string_local_sync(),'---------send_response_local-sync-----------------'); $post_arr = $data; die("".json_encode($post_arr).""); } function local_sync_send_current_backup_response_to_server(){ $return_array = array(); send_response_local_sync('progress', LOCAL_SYNC_DEFAULT_CRON_TYPE, $return_array); } function local_sync_is_hash_required($file_path){ if ( is_readable($file_path) && filesize($file_path) < LOCAL_SYNC_HASH_FILE_LIMIT) { return true; } else { return false; } } function local_sync_is_chunk_hash_required($file_path){ return (filesize($file_path) > LOCAL_SYNC_HASH_CHUNK_LIMIT) ? true : false; } function local_sync_get_hash($file_path, $limit = 0, $offset = 0) { // local_sync_log(func_get_args(), '---------func_get_args()------------'); $is_hash_required = local_sync_is_hash_required($file_path); // local_sync_log($is_hash_required, '---------$is_hash_required------------'); if (!$is_hash_required) { return null; } $chunk_hash = local_sync_is_chunk_hash_required($file_path); // local_sync_log($chunk_hash, '---------$chunk_hash------------'); if ($chunk_hash === false) { if ( !file_exists($file_path) || !is_file($file_path) ) { return null; } // md5_file is always faster if we don't chunk the file $hash = md5_file($file_path); return $hash !== false ? $hash : null; } $ctx = hash_init('md5'); if (!$ctx) { // Fail to initialize file hashing return null; } $limit = filesize($file_path) - $offset; $handle = @fopen($file_path, "rb"); if ($handle === false) { // Failed opening file, cleanup hash context hash_final($ctx); return null; } fseek($handle, $offset); while ($limit > 0) { // Limit chunk size to either our remaining chunk or max chunk size $chunkSize = $limit < LOCAL_SYNC_HASH_CHUNK_LIMIT ? $limit : LOCAL_SYNC_HASH_CHUNK_LIMIT; $limit -= $chunkSize; $chunk = fread($handle, $chunkSize); hash_update($ctx, $chunk); } fclose($handle); return hash_final($ctx); } function local_sync_is_seeking_exception($exception_msg){ //Eg: Seek position 29 is out of range return ( stripos($exception_msg, 'Seek position') !== false || stripos($exception_msg, 'out of range') !== false ); } function local_sync_is_file_iterator_allowed_exception($exception_msg){ //Eg: Seek position 29 is out of range return stripos($exception_msg, 'open_basedir restriction in effect') !== false ; } function local_sync_is_always_include_file($file){ $file = local_sync_add_fullpath($file); if ( stripos($file, LOCAL_SYNC_WP_CONTENT_DIR) === false){ return false; } if ( stripos($file, LOCAL_SYNC_TEMP_DIR_BASENAME) === false ){ return false; } if ( strpos($file, 'backup.sql') !== false || strpos($file, 'local_sync_full_db-backup') !== false || strpos($file, 'local_sync_file_list_dump') !== false || strpos($file, 'local_sync_files') !== false ) { return true; } else { return false; } } function is_local_sync_file($file){ if(stripos($file, 'plugins/' . LOCAL_SYNC_PLUGIN_NAME) === FALSE){ return false; } if(stripos($file, 'imagify') !== FALSE){ return false; } return true; } function local_sync_get_upload_dir(){ if (defined('LOCAL_SYNC_BRIDGE')) { $uploadDir['basedir'] = LOCAL_SYNC_RELATIVE_WP_CONTENT_DIR . '/uploads'; } else { $uploadDir = wp_upload_dir(); } $upload_dir = str_replace(LOCAL_SYNC_ABSPATH, LOCAL_SYNC_RELATIVE_ABSPATH, $uploadDir['basedir']); return wp_normalize_path($upload_dir); } function local_sync_die_with_json_encode($msg = array('empty data'), $escape = 0, $next_call_30_secs = false){ $local_sync_options = new Local_Sync_Options(); global $local_sync_ajax_start_time; if(!empty($local_sync_ajax_start_time)){ $msg['ajax_time_taken'] = time() - $local_sync_ajax_start_time; } if(!empty($next_call_30_secs)){ $msg['ajax_time_taken'] = 30; } $actions_time_taken = update_actions_time_taken_local_sync($msg, $local_sync_options); // $msg['actions_time_taken'] = $actions_time_taken; $pull_from_live_steps = $local_sync_options->get_option('pull_from_live_steps'); $pull_from_live_steps = json_decode($pull_from_live_steps, true); $msg['process_steps'] = $pull_from_live_steps; $msg['site_type'] = $local_sync_options->get_option('site_type'); // local_sync_log($msg, "--------msg--------"); reset_last_request_local_sync(); switch ($escape) { case 1: $json_encoded_msg = json_encode($msg, JSON_UNESCAPED_SLASHES); die('' . $json_encoded_msg . ''); case 2: $json_encoded_msg = json_encode($msg, JSON_UNESCAPED_UNICODE); die('' . $json_encoded_msg . ''); } $json_encoded_msg = json_encode($msg); die('' . $json_encoded_msg . ''); } function local_sync_die_with_json_encode_simple($msg = array('empty data'), $escape = 0, $next_call_30_secs = false){ $copy_msg = $msg; if(!empty($copy_msg['file_data'])){ $copy_msg['file_data'] = 'going something'; } local_sync_log($copy_msg, "--------copy_msg--------"); switch ($escape) { case 1: $json_encoded_msg = json_encode($msg, JSON_UNESCAPED_SLASHES); die('' . $json_encoded_msg . ''); case 2: $json_encoded_msg = json_encode($msg, JSON_UNESCAPED_UNICODE); die('' . $json_encoded_msg . ''); } $json_encoded_msg = json_encode($msg); die('' . $json_encoded_msg . ''); } function update_actions_time_taken_local_sync($msg, $local_sync_options){ $local_sync_options->set_option('last_action_running', false); $actions_time_taken = $local_sync_options->get_option('actions_time_taken'); $actions_time_taken = json_decode($actions_time_taken, true); $sync_current_action = $local_sync_options->get_option('sync_current_action'); if(empty($actions_time_taken[$sync_current_action])){ $actions_time_taken[$sync_current_action] = 0; } $actions_time_taken[$sync_current_action] += $msg['ajax_time_taken']; $local_sync_options->set_option('actions_time_taken', json_encode($actions_time_taken)); return $actions_time_taken; } function reset_last_request_local_sync(){ } function parse_local_sync_response_from_raw_data_php($raw_response = null){ if(empty($raw_response) || !is_string($raw_response)){ return $raw_response; } $raw_response = explode('', $raw_response); $raw_response = array_pop($raw_response); $raw_response = explode('', $raw_response); $raw_response = array_shift($raw_response); return $raw_response; } function parse_wp_merge_response_from_raw_data_php($raw_response = null){ if(empty($raw_response) || !is_string($raw_response)){ return $raw_response; } $raw_response = explode('', $raw_response); $raw_response = array_pop($raw_response); $raw_response = explode('', $raw_response); $raw_response = array_shift($raw_response); return $raw_response; } function set_memory_limit_local_sync() { $mem_limit = '256M'; if(defined('WP_MAX_MEMORY_LIMIT')){ $mem_limit = WP_MAX_MEMORY_LIMIT; } @ini_set('memory_limit', $mem_limit); } function local_sync_set_time_limit($seconds){ if(!local_sync_function_exist('set_time_limit')){ return false; } @set_time_limit($seconds); } function local_sync_is_meta_data_backup(){ return false; if (!defined('IS_META_DATA_BACKUP_LS') ) { return false; } if (!IS_META_DATA_BACKUP_LS) { return false; } return true; } function local_sync_replace_abspath(&$file, $change_reference = true){ if(!defined('LOCAL_SYNC_BRIDGE')){ return $file; } $file = wp_normalize_path($file); if (!defined('LOCAL_SYNC_SITE_ABSPATH')) { return $file; } if (LOCAL_SYNC_SITE_ABSPATH === LOCAL_SYNC_ABSPATH) { return $file; } if (stripos($file, LOCAL_SYNC_SITE_ABSPATH) === false) { return $file; } if ($change_reference) { $file = str_replace(LOCAL_SYNC_SITE_ABSPATH, LOCAL_SYNC_ABSPATH, $file); return $file; } return str_replace(LOCAL_SYNC_SITE_ABSPATH, LOCAL_SYNC_ABSPATH, $file); } function local_sync_function_exist($function){ if (empty($function)) { return false; } if ( !function_exists($function) ) { return false; } $disabled_functions = explode(',', ini_get('disable_functions')); $function_enabled = !in_array($function, $disabled_functions); return ($function_enabled) ? true : false; } function local_sync_get_file_size($file) { clearstatcache(); if ( !file_exists($file) || !is_file($file) ) { return false; } $normal_file_size = filesize($file); if(($normal_file_size !== false)&&($normal_file_size >= 0)) { return $normal_file_size; } $file = realPath($file); if(!$file) { return false; } $ch = curl_init("file://" . $file); curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_FILE); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); $data = curl_exec($ch); $curl_error = curl_error($ch); curl_close($ch); if ($data !== false && preg_match('/Content-Length: (\d+)/', $data, $matches)) { return (string) $matches[1]; } return $normal_file_size; } function is_local_sync_table($tableName) { global $wpdb; $wp_prefix_with_tc_prefix = $wpdb->base_prefix . LOCAL_SYNC_PLUGIN_NAME; $local_sync_strpos = stripos($tableName, $wp_prefix_with_tc_prefix); if (false !== $local_sync_strpos && $local_sync_strpos === 0) { return true; } return false; } function is_wp_merge_table($tableName) { global $wpdb; $wp_prefix_with_tc_prefix = $wpdb->base_prefix . 'wpmerge'; local_sync_log($wp_prefix_with_tc_prefix, "--------is_wp_merge_table--------"); $this_sync_strpos = stripos($tableName, $wp_prefix_with_tc_prefix); if (false !== $this_sync_strpos && $this_sync_strpos === 0) { return true; } return false; } function status_losy($status, $success=true, $return=true, $options='', $multicall=false){ local_sync_log($status, "--------status_losy--------"); } function initiate_filesystem_local_sync() { // $is_admin_call = false; // if(is_admin()){ // $is_admin_call = true; // global $initiate_filesystem_local_sync_direct_load; // if (empty($initiate_filesystem_local_sync_direct_load)) { // $initiate_filesystem_local_sync_direct_load = true; // } else{ // return false; // } // } // if($is_admin_call === false){ // return false; // } if(!function_exists('request_filesystem_credentials')){ include_once LOCAL_SYNC_ABSPATH . 'wp-admin/includes/file.php'; } $creds = request_filesystem_credentials("", "", false, false, null); if (false === $creds) { return false; } if (!WP_Filesystem($creds)) { return false; } } function is_windows_machine_local_sync(){ if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { return true; } return false; } function local_sync_wait_for_sometime(){ //Windows filesyetem slower so wait for sometime if (!is_windows_machine_local_sync()) { return ; } @usleep(250000); // Maybe a concurrent script has deleted the file in the meantime @clearstatcache(); } function local_sync_get_table_from_query( $query ) { // Remove characters that can legally trail the table name. $query = rtrim( $query, ';/-#' ); // Allow (select...) union [...] style queries. Use the first query's table name. $query = ltrim( $query, "\r\n\t (" ); // Strip everything between parentheses except nested selects. $query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', $query ); // Quickly match most common queries. if ( preg_match( '/^\s*(?:' . 'SELECT.*?\s+FROM' . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?' . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?' . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?' . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:.+?FROM)?' . ')\s+((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)/is', $query, $maybe ) ) { return str_replace( '`', '', $maybe[1] ); } // SHOW TABLE STATUS and SHOW TABLES WHERE Name = 'wp_posts' if ( preg_match( '/^\s*SHOW\s+(?:TABLE\s+STATUS|(?:FULL\s+)?TABLES).+WHERE\s+Name\s*=\s*("|\')((?:[0-9a-zA-Z$_.-]|[\xC2-\xDF][\x80-\xBF])+)\\1/is', $query, $maybe ) ) { return $maybe[2]; } // SHOW TABLE STATUS LIKE and SHOW TABLES LIKE 'wp\_123\_%' // This quoted LIKE operand seldom holds a full table name. // It is usually a pattern for matching a prefix so we just // strip the trailing % and unescape the _ to get 'wp_123_' // which drop-ins can use for routing these SQL statements. if ( preg_match( '/^\s*SHOW\s+(?:TABLE\s+STATUS|(?:FULL\s+)?TABLES)\s+(?:WHERE\s+Name\s+)?LIKE\s*("|\')((?:[\\\\0-9a-zA-Z$_.-]|[\xC2-\xDF][\x80-\xBF])+)%?\\1/is', $query, $maybe ) ) { return str_replace( '\\_', '_', $maybe[2] ); } // Big pattern for the rest of the table-related queries. if ( preg_match( '/^\s*(?:' . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM' . '|DESCRIBE|DESC|EXPLAIN|HANDLER' . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?' . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE' . '|TRUNCATE(?:\s+TABLE)?' . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?' . '|ALTER(?:\s+IGNORE)?\s+TABLE' . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?' . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON' . '|DROP\s+INDEX.*\s+ON' . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE' . '|(?:GRANT|REVOKE).*ON\s+TABLE' . '|SHOW\s+(?:.*FROM|.*TABLE)' . ')\s+\(*\s*((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is', $query, $maybe ) ) { return str_replace( '`', '', $maybe[1] ); } return false; } function local_sync_remove_protocal_from_url($url){ $url = preg_replace("(^https?://?www.)", "", $url ); return preg_replace("(^https?://)", "", $url ); } function local_sync_add_protocal_to_url($url, $protocal, $add_www){ $trimmed_url = local_sync_remove_protocal_from_url($url); $protocal = $protocal . '://'; return $add_www ? $protocal . 'www.' . $trimmed_url : $protocal . $trimmed_url ; } function local_sync_dupx_array_rtrim(&$value) { $value = rtrim($value, '\/'); } function die_with_ls_signature($msg, $option = false){ $local_sync_options = new Local_Sync_Options(); global $local_sync_ajax_start_time; if(!empty($local_sync_ajax_start_time)){ $msg['ajax_time_taken'] = time() - $local_sync_ajax_start_time; } $actions_time_taken = update_actions_time_taken_local_sync($msg, $local_sync_options); $pull_from_live_steps = $local_sync_options->get_option('pull_from_live_steps'); $pull_from_live_steps = json_decode($pull_from_live_steps, true); $msg['process_steps'] = $pull_from_live_steps; if( !empty($msg) && !empty($msg['sync_current_action']) && $msg['sync_current_action'] == 'redirect_to_local_site' ){ $msg['actions_time_taken'] = $actions_time_taken; $msg['total_time_taken'] = 0; foreach ($actions_time_taken as $key => $value) { $msg['total_time_taken'] += $value; } } if (!$option) { $json_encoded_msg = json_encode($msg); } else if($option === 'unescape_slashes'){ $json_encoded_msg = json_encode($msg, JSON_UNESCAPED_SLASHES); } local_sync_log($msg, "--------die_with_ls_signature--------"); $msg_with_secret = '' . $json_encoded_msg . ''; die($msg_with_secret); } function convert_bytes_to_hr_format_local_sync($size){ if (empty($size)) { $size = 0; } if (1024 > $size) { return $size.' B'; } else if (1048576 > $size) { return round( ($size / 1024) , 2). ' KB'; } else if (1073741824 > $size) { return round( (($size / 1024) / 1024) , 2). ' MB'; } else if (1099511627776 > $size) { return round( ((($size / 1024) / 1024) / 1024) , 2). ' GB'; } }//All functions if (!function_exists('__')) { function __($name) { return $name; } } if (!function_exists('apply_filters')) { function apply_filters($this_name, $this_value, $ignorable = array()) { return $this_value; } } //WP common functions if (!function_exists('trailingslashit')) { function trailingslashit($string) { return untrailingslashit($string) . '/'; } } if (!function_exists('did_action')) { function did_action($string) { return 0; } } if (!function_exists('wp_die')) { function wp_die($string = '') { exit($string); } } if (!function_exists('untrailingslashit')) { function untrailingslashit($string) { return rtrim($string, '/\\'); } } if (!function_exists('get_option')) { function get_option($option) { global $wpdb; $value = false; $row = $wpdb->get_row($wpdb->prepare("SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1", $option)); if (is_object($row) && isset($row->option_value)) { $value = $row->option_value; } return $value; } } if (!function_exists('get_option_local_sync')) { function get_option_local_sync($option) { global $wpdb; $value = false; $sql = $wpdb->prepare("SELECT value FROM " . $wpdb->base_prefix . "local_sync_options WHERE name = %s LIMIT 1", $option); $option_value = $wpdb->get_var($sql); if ($option_value) { return $option_value; } return $value; } } if (!function_exists('current_time')) { function current_time($type, $gmt = 0) { switch ($type) { case 'mysql': return ($gmt) ? gmdate('Y-m-d H:i:s') : gmdate('Y-m-d H:i:s', (time() + (get_option('gmt_offset') * HOUR_IN_SECONDS))); case 'timestamp': return ($gmt) ? time() : time() + (get_option('gmt_offset') * HOUR_IN_SECONDS); default: return ($gmt) ? date($type) : date($type, time() + (get_option('gmt_offset') * HOUR_IN_SECONDS)); } } } if (!function_exists('set_url_scheme')) { function set_url_scheme($url, $scheme = null) { $orig_scheme = $scheme; if (!$scheme) { $scheme = is_ssl() ? 'https' : 'http'; } elseif ($scheme === 'admin' || $scheme === 'login' || $scheme === 'login_post' || $scheme === 'rpc') { $scheme = is_ssl() || force_ssl_admin() ? 'https' : 'http'; } elseif ($scheme !== 'http' && $scheme !== 'https' && $scheme !== 'relative') { $scheme = is_ssl() ? 'https' : 'http'; } $url = trim($url); if (substr($url, 0, 2) === '//') { $url = 'http:' . $url; } if ('relative' == $scheme) { $url = ltrim(preg_replace('#^\w+://[^/]*#', '', $url)); if ($url !== '' && $url[0] === '/') { $url = '/' . ltrim($url, "/ \t\n\r\0\x0B"); } } else { $url = preg_replace('#^\w+://#', $scheme . '://', $url); } /** * Filter the resulting URL after setting the scheme. * * @since 3.4.0 * * @param string $url The complete URL including scheme and path. * @param string $scheme Scheme applied to the URL. One of 'http', 'https', or 'relative'. * @param string $orig_scheme Scheme requested for the URL. One of 'http', 'https', 'login', * 'login_post', 'admin', 'rpc', or 'relative'. */ return $url; } } if (!function_exists('is_ssl')) { function is_ssl() { if (isset($_SERVER['HTTPS'])) { if ('on' == strtolower($_SERVER['HTTPS'])) { return true; } if ('1' == $_SERVER['HTTPS']) { return true; } } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) { return true; } return false; } } if (!function_exists('force_ssl_admin')) { function force_ssl_admin($force = null) { static $forced = false; if (!is_null($force)) { $old_forced = $forced; $forced = $force; return $old_forced; } return $forced; } } if (!function_exists('get_temp_dir')) { function get_temp_dir() { static $temp; if (defined('WP_TEMP_DIR')) { return trailingslashit(WP_TEMP_DIR); } if ($temp) { return trailingslashit($temp); } if (function_exists('sys_get_temp_dir')) { $temp = sys_get_temp_dir(); if (@is_dir($temp) && wp_is_writable($temp)) { return trailingslashit($temp); } } $temp = ini_get('upload_tmp_dir'); if (@is_dir($temp) && wp_is_writable($temp)) { return trailingslashit($temp); } $temp = WP_CONTENT_DIR . '/'; if (is_dir($temp) && wp_is_writable($temp)) { return $temp; } $temp = '/tmp/'; return $temp; } } if (!function_exists('wp_is_writable')) { function wp_is_writable($path) { if ('WIN' === strtoupper(substr(PHP_OS, 0, 3))) { return win_is_writable($path); } else { return @is_writable($path); } } } if (!function_exists('win_is_writable')) { function win_is_writable($path) { if ($path[strlen($path) - 1] == '/') // if it looks like a directory, check a random file within the directory { return win_is_writable($path . uniqid(mt_rand()) . '.tmp'); } else if (is_dir($path)) // If it's a directory (and not a file) check a random file within the directory { return win_is_writable($path . '/' . uniqid(mt_rand()) . '.tmp'); } // check tmp file for read/write capabilities $should_delete_tmp_file = !file_exists($path); $f = @fopen($path, 'a'); if ($f === false) { return false; } fclose($f); if ($should_delete_tmp_file) { @unlink($path); } return true; } } if (!function_exists('mbstring_binary_safe_encoding')) { function mbstring_binary_safe_encoding($reset = false) { static $encodings = array(); static $overloaded = null; if (is_null($overloaded)) { $overloaded = function_exists('mb_internal_encoding') && (ini_get('mbstring.func_overload') & 2); } if (false === $overloaded) { return; } if (!$reset) { $encoding = mb_internal_encoding(); array_push($encodings, $encoding); mb_internal_encoding('ISO-8859-1'); } if ($reset && $encodings) { $encoding = array_pop($encodings); mb_internal_encoding($encoding); } } } if (!function_exists('reset_mbstring_encoding')) { function reset_mbstring_encoding() { mbstring_binary_safe_encoding(true); } } if (!function_exists('wp_installing')) { function wp_installing($is_installing = null) { return false; } } if (!function_exists('update_option')) { function update_option($option, $value) { global $wpdb; $option = trim($option); if (empty($option)) { return false; } if (is_object($value)) { $value = clone $value; } $old_value = get_option($option); if ($value === $old_value) { return false; } $serialized_value = maybe_serialize($value); $result = $wpdb->update($wpdb->options, array('option_value' => $serialized_value), array('option_name' => $option)); if (!$result) { return false; } return true; } } if (!function_exists('is_serialized')) { function is_serialized($data, $strict = true) { // if it isn't a string, it isn't serialized. if (!is_string($data)) { return false; } $data = trim($data); if ('N;' == $data) { return true; } if (strlen($data) < 4) { return false; } if (':' !== $data[1]) { return false; } if ($strict) { $lastc = substr($data, -1); if (';' !== $lastc && '}' !== $lastc) { return false; } } else { $semicolon = strpos($data, ';'); $brace = strpos($data, '}'); // Either ; or } must exist. if (false === $semicolon && false === $brace) { return false; } // But neither must be in the first X characters. if (false !== $semicolon && $semicolon < 3) { return false; } if (false !== $brace && $brace < 4) { return false; } } $token = $data[0]; switch ($token) { case 's': if ($strict) { if ('"' !== substr($data, -2, 1)) { return false; } } elseif (false === strpos($data, '"')) { return false; } // or else fall through case 'a': case 'O': return (bool) preg_match("/^{$token}:[0-9]+:/s", $data); case 'b': case 'i': case 'd': $end = $strict ? '$' : ''; return (bool) preg_match("/^{$token}:[0-9.E-]+;$end/", $data); } return false; } } if (!function_exists('is_serialized_string')) { function is_serialized_string($data) { // if it isn't a string, it isn't a serialized string. if (!is_string($data)) { return false; } $data = trim($data); if (strlen($data) < 4) { return false; } elseif (':' !== $data[1]) { return false; } elseif (';' !== substr($data, -1)) { return false; } elseif ($data[0] !== 's') { return false; } elseif ('"' !== substr($data, -2, 1)) { return false; } else { return true; } } } if (!function_exists('maybe_serialize')) { function maybe_serialize($data) { if (is_array($data) || is_object($data)) { return serialize($data); } // Double serialization is required for backward compatibility. // See https://core.trac.wordpress.org/ticket/12930 if (is_serialized($data, false)) { return serialize($data); } return $data; } } if (!function_exists('wp_generate_password')) { function wp_generate_password($length = 12, $special_chars = true, $extra_special_chars = false) { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; if ($special_chars) { $chars .= '!@#$%^&*()'; } if ($extra_special_chars) { $chars .= '-_ []{}<>~`+=,.;:/?|'; } $password = ''; for ($i = 0; $i < $length; $i++) { $password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1); } /** * Filter the randomly-generated password. * * @since 3.0.0 * * @param string $password The generated password. */ return apply_filters('random_password', $password); } } if (!function_exists('wp_rand')) { function wp_rand($min = 0, $max = 0) { global $rnd_value; // Reset $rnd_value after 14 uses // 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value if (strlen($rnd_value) < 8) { static $seed = ''; $rnd_value = md5(uniqid(microtime() . mt_rand(), true) . $seed); $rnd_value .= sha1($rnd_value); $rnd_value .= sha1($rnd_value . $seed); $seed = md5($seed . $rnd_value); } // Take the first 8 digits for our value $value = substr($rnd_value, 0, 8); // Strip the first eight, leaving the remainder for the next call to wp_rand(). $rnd_value = substr($rnd_value, 8); $value = abs(hexdec($value)); // Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats. $max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295; // 4294967295 = 0xffffffff // Reduce the value to be within the min - max range if ($max != 0) { $value = $min + ($max - $min + 1) * $value / ($max_random_number + 1); } return abs(intval($value)); } } if (!function_exists('wp_unique_filename')) { function wp_unique_filename($dir, $filename, $unique_filename_callback = null) { // Sanitize the file name before we begin processing. $filename = sanitize_file_name($filename); // Separate the filename into a name and extension. $info = pathinfo($filename); $ext = !empty($info['extension']) ? '.' . $info['extension'] : ''; $name = basename($filename, $ext); // Edge case: if file is named '.ext', treat as an empty name. if ($name === $ext) { $name = ''; } /* * Increment the file number until we have a unique file to save in $dir. * Use callback if supplied. */ if ($unique_filename_callback && is_callable($unique_filename_callback)) { $filename = call_user_func($unique_filename_callback, $dir, $name, $ext); } else { $number = ''; // Change '.ext' to lower case. if ($ext && strtolower($ext) != $ext) { $ext2 = strtolower($ext); $filename2 = preg_replace('|' . preg_quote($ext) . '$|', $ext2, $filename); // Check for both lower and upper case extension or image sub-sizes may be overwritten. while (file_exists($dir . "/$filename") || file_exists($dir . "/$filename2")) { $new_number = $number + 1; $filename = str_replace("$number$ext", "$new_number$ext", $filename); $filename2 = str_replace("$number$ext2", "$new_number$ext2", $filename2); $number = $new_number; } return $filename2; } while (file_exists($dir . "/$filename")) { if ('' == "$number$ext") { $filename = $filename . ++$number . $ext; } else { $filename = str_replace("$number$ext", ++$number . $ext, $filename); } } } return $filename; } } if (!function_exists('sanitize_file_name')) { function sanitize_file_name($filename) { $filename_raw = $filename; $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0)); /** * Filter the list of characters to remove from a filename. * * @since 2.8.0 * * @param array $special_chars Characters to remove. * @param string $filename_raw Filename as it was passed into sanitize_file_name(). */ $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw); $filename = preg_replace("#\x{00a0}#siu", ' ', $filename); $filename = str_replace($special_chars, '', $filename); $filename = str_replace(array('%20', '+'), '-', $filename); $filename = preg_replace('/[\r\n\t -]+/', '-', $filename); $filename = trim($filename, '.-_'); // Split the filename into a base and extension[s] $parts = explode('.', $filename); // Return if only one extension if (count($parts) <= 2) { /** * Filter a sanitized filename string. * * @since 2.8.0 * * @param string $filename Sanitized filename. * @param string $filename_raw The filename prior to sanitization. */ return apply_filters('sanitize_file_name', $filename, $filename_raw); } // Process multiple extensions $filename = array_shift($parts); $extension = array_pop($parts); $mimes = get_allowed_mime_types(); /* * Loop over any intermediate extensions. Postfix them with a trailing underscore * if they are a 2 - 5 character long alpha string not in the extension whitelist. */ foreach ((array) $parts as $part) { $filename .= '.' . $part; if (preg_match("/^[a-zA-Z]{2,5}\d?$/", $part)) { $allowed = false; foreach ($mimes as $ext_preg => $mime_match) { $ext_preg = '!^(' . $ext_preg . ')$!i'; if (preg_match($ext_preg, $part)) { $allowed = true; break; } } if (!$allowed) { $filename .= '_'; } } } $filename .= '.' . $extension; /** This filter is documented in wp-includes/formatting.php */ return apply_filters('sanitize_file_name', $filename, $filename_raw); } } if (!function_exists('get_allowed_mime_types')) { function get_allowed_mime_types($user = null) { $t = wp_get_mime_types(); unset($t['swf'], $t['exe']); return apply_filters('upload_mimes', $t, $user); } } if (!function_exists('wp_get_mime_types')) { function wp_get_mime_types() { return apply_filters('mime_types', array( // Image formats. 'jpg|jpeg|jpe' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', 'bmp' => 'image/bmp', 'tif|tiff' => 'image/tiff', 'ico' => 'image/x-icon', // Video formats. 'asf|asx' => 'video/x-ms-asf', 'wmv' => 'video/x-ms-wmv', 'wmx' => 'video/x-ms-wmx', 'wm' => 'video/x-ms-wm', 'avi' => 'video/avi', 'divx' => 'video/divx', 'flv' => 'video/x-flv', 'mov|qt' => 'video/quicktime', 'mpeg|mpg|mpe' => 'video/mpeg', 'mp4|m4v' => 'video/mp4', 'ogv' => 'video/ogg', 'webm' => 'video/webm', 'mkv' => 'video/x-matroska', '3gp|3gpp' => 'video/3gpp', // Can also be audio '3g2|3gp2' => 'video/3gpp2', // Can also be audio // Text formats. 'txt|asc|c|cc|h|srt' => 'text/plain', 'csv' => 'text/csv', 'tsv' => 'text/tab-separated-values', 'ics' => 'text/calendar', 'rtx' => 'text/richtext', 'css' => 'text/css', 'htm|html' => 'text/html', 'vtt' => 'text/vtt', 'dfxp' => 'application/ttaf+xml', // Audio formats. 'mp3|m4a|m4b' => 'audio/mpeg', 'ra|ram' => 'audio/x-realaudio', 'wav' => 'audio/wav', 'ogg|oga' => 'audio/ogg', 'mid|midi' => 'audio/midi', 'wma' => 'audio/x-ms-wma', 'wax' => 'audio/x-ms-wax', 'mka' => 'audio/x-matroska', // Misc application formats. 'rtf' => 'application/rtf', 'js' => 'application/javascript', 'pdf' => 'application/pdf', 'swf' => 'application/x-shockwave-flash', 'class' => 'application/java', 'tar' => 'application/x-tar', 'zip' => 'application/zip', 'gz|gzip' => 'application/x-gzip', 'rar' => 'application/rar', '7z' => 'application/x-7z-compressed', 'exe' => 'application/x-msdownload', 'psd' => 'application/octet-stream', // MS Office formats. 'doc' => 'application/msword', 'pot|pps|ppt' => 'application/vnd.ms-powerpoint', 'wri' => 'application/vnd.ms-write', 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel', 'mdb' => 'application/vnd.ms-access', 'mpp' => 'application/vnd.ms-project', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'docm' => 'application/vnd.ms-word.document.macroEnabled.12', 'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'dotm' => 'application/vnd.ms-word.template.macroEnabled.12', 'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12', 'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12', 'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12', 'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template', 'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12', 'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide', 'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12', 'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote', 'oxps' => 'application/oxps', 'xps' => 'application/vnd.ms-xpsdocument', // OpenOffice formats. 'odt' => 'application/vnd.oasis.opendocument.text', 'odp' => 'application/vnd.oasis.opendocument.presentation', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', 'odg' => 'application/vnd.oasis.opendocument.graphics', 'odc' => 'application/vnd.oasis.opendocument.chart', 'odb' => 'application/vnd.oasis.opendocument.database', 'odf' => 'application/vnd.oasis.opendocument.formula', // WordPerfect formats. 'wp|wpd' => 'application/wordperfect', // iWork formats. 'key' => 'application/vnd.apple.keynote', 'numbers' => 'application/vnd.apple.numbers', 'pages' => 'application/vnd.apple.pages', )); } } if (!function_exists('network_admin_url')) { function network_admin_url( $path = '', $scheme = 'admin' ) { $network_admin_url = get_option_local_sync('network_admin_url'); if ($network_admin_url) { return $network_admin_url.$path; } return false; } } if (!function_exists('add_action')) { function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) { return true; } } if (!function_exists('add_filter')) { function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) { return true; } } if (!function_exists('current_user_can')) { function current_user_can( $capability ) { return true; } } if (!function_exists('is_admin')) { function is_admin() { return true; } } if (!function_exists('do_action')) { function do_action($tag, $arg = '') { return true; } } if (!function_exists('do_action')) { function do_action($tag, $arg = '') { return true; } } if (!function_exists('apply_filters')) { function apply_filters( $tag, $value ) { return true; } } if (!function_exists('wp_normalize_path')) { function wp_normalize_path( $path ) { $path = str_replace( '\\', '/', $path ); $path = preg_replace( '|(?<=.)/+|', '/', $path ); if ( ':' === substr( $path, 1, 1 ) ) { $path = ucfirst( $path ); } return $path; } } if (!function_exists('home_url')) { function home_url() { return get_option_local_sync('site_url_local_sync'); } } if (!function_exists('get_locale')) { function get_locale() { return 'en_US'; } } if (!function_exists('is_multisite')) { function is_multisite() { if ( defined( 'MULTISITE' ) ) return MULTISITE; if ( defined( 'SUBDOMAIN_INSTALL' ) || defined( 'VHOST' ) || defined( 'SUNRISE' ) ) return true; return false; } } if (!function_exists('stripslashes_deep')) { function stripslashes_deep( $value ) { return map_deep( $value, 'stripslashes_from_strings_only' ); } } if (!function_exists('stripslashes_from_strings_only')) { function stripslashes_from_strings_only( $value ) { return is_string( $value ) ? stripslashes( $value ) : $value; } } if (!function_exists('map_deep')) { function map_deep( $value, $callback ) { if ( is_array( $value ) ) { foreach ( $value as $index => $item ) { $value[ $index ] = map_deep( $item, $callback ); } } elseif ( is_object( $value ) ) { $object_vars = get_object_vars( $value ); foreach ( $object_vars as $property_name => $property_value ) { $value->$property_name = map_deep( $property_value, $callback ); } } else { $value = call_user_func( $callback, $value ); } return $value; } }