Current File : /home/lecoinf/www/iwp/includes/bridge/bridge.txt
<?php

$GLOBALS['IWP_MMB_PROFILING']['ACTION_START'] = microtime(1);
global $extract_start_time;
$extract_start_time = $GLOBALS['IWP_MMB_PROFILING']['ACTION_START'];
@ini_set('memory_limit', "-1"); // For big uploads
@ini_set("max_execution_time", 0);
@set_time_limit(0);
register_shutdown_function("bridge_shutdown");
error_reporting(E_ALL ^ E_NOTICE);
@ini_set("display_errors", 1);
@ignore_user_abort(true);

require_once 'fileSystem.php';
require_once 'db.php';

$HTTP_RAW_POST_DATA = file_get_contents('php://input');
if (strrpos($HTTP_RAW_POST_DATA, '_IWP_JSON_PREFIX_') !== false) {
	$request_data_array = explode('_IWP_JSON_PREFIX_', $HTTP_RAW_POST_DATA);
	$request_raw_data = $request_data_array[1];
	$data = trim(base64_decode($request_raw_data));
	$GLOBALS['IWP_JSON_COMMUNICATION'] = 1;
}else{
	$status = "Invalid request params";
	die(status($status, $success=false, $return=true));
}

$http_data = json_decode($data, true);
$_REQUEST = $http_data;
// ----- for multicall
$isMultiCall = false;
$prevMultiCallResponse = array();
$connectionFlag = false;
if(empty($_REQUEST['dbhost'])){
	if (!empty($_REQUEST['isExistingSite']) && $_REQUEST['iwp_action'] != 'bridgeExtractMulticall') {
		connfigFileProcessForExistingSite();
		$table_prefix = $GLOBALS['table_prefix'];
	}

	if (!empty($_REQUEST['isSameServerStaging']) && $_REQUEST['iwp_action'] != 'bridgeExtractMulticall') {
		connfigFileProcess();
	}
	if (!empty($_REQUEST['isStagingToLive']) && $_REQUEST['iwp_action'] != 'bridgeExtractMulticall') {
		connfigFileProcessForStagingToLive();
		$_REQUEST['db_table_prefix'] = $GLOBALS['table_prefix'];
	}
	if (empty($_REQUEST['isSameServerStaging']) && $_REQUEST['iwp_action'] != 'bridgeExtractMulticall' && !defined('DB_HOST') && empty($_REQUEST['dbHost'])) {
		if (file_exists('../wp-load.php')) {
			require_once '../wp-load.php';
		}
	}
}
$_REQUEST = $http_data;
$GLOBALS['is_new_backup'] = false;
$GLOBALS['connectionFlag'] = false;
$GLOBALS['isStagingToLive'] = false;
$GLOBALS['use_default_htaccess'] = false;
if(!empty($_REQUEST['iwp_action']) && $_REQUEST['iwp_action'] == 'bridgeExtractMulticall'){

	$oldValues = unserialize(base64_decode($_REQUEST['params']['param1']));
	$_REQUEST = array_merge($_REQUEST, $oldValues);
	if(!empty($_REQUEST['params']['responseData']['isLiteSpeed'])){
		IWP_LiteSpeed::$isLiteSpeedMultiCall = true;
	}
	if(!empty($_REQUEST['params']['responseData']['isLiteSpeedHtaccess'])){
		$GLOBALS['isLiteSpeedHtaccess'] = true;
		IWP_LiteSpeed::$isLiteSpeedHtaccess = true;
	}
	if (empty($_REQUEST['dbHost']) || !empty($_REQUEST['isStagingToLive'])) {
		$DBDetails = $_REQUEST['params']['responseData']['DBDetails'];
		$_REQUEST['dbHost'] = $DBDetails['DB_HOST'];
		$_REQUEST['dbUser'] = $DBDetails['DB_USER'];
		$_REQUEST['dbPassword'] = $DBDetails['DB_PASSWORD'];
		$_REQUEST['dbName'] = $DBDetails['DB_NAME'];
		$_REQUEST['db_table_prefix'] = $DBDetails['prefix'];
	}
	define('DB_HOST',$_REQUEST['dbHost']);
	define('DB_USER',$_REQUEST['dbUser']);
	define('DB_PASSWORD',$_REQUEST['dbPassword']);
	define('DB_NAME',$_REQUEST['dbName']);
	$connectionFlag = DB::connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, 3306);
	if(!$connectionFlag){
		$status = "DB verification Failed(".$connectionFlag.")";
		die(status($status, $success=false, $return=true));
	}
	$cloneStatus = DB::getField("iwp_clone_stats", "optionValue", "optionName = 'cloneStatus'");
	$cloneStatus = unserialize($cloneStatus);

	if (!empty($cloneStatus) && (!IWP_LiteSpeed::$isLiteSpeedMultiCall)) {
		$isMultiCall = true;
		$isDownloadMultiCall = $cloneStatus['isDownloadMultiCall'];
		$prevMultiCallResponse = $cloneStatus;
		$historyID = $_REQUEST['extractParentHID'];
	} else {
		//To run directly from iwp request not referring cloneStatus.php
		$isDownloadMultiCall = $_REQUEST['params']['responseData']['isDownloadMultiCall'];
		$prevMultiCallResponse = $_REQUEST['params']['responseData'];
		if (empty($prevMultiCallResponse)) {
			die(status('Retriving clone status' . DB::error(), $success=false, $return=true));
		}
	}
}

define('APP_FTP_HOST',$_REQUEST['ftpHost']);
define('APP_FTP_PORT',$_REQUEST['ftpPort']);
define('APP_FTP_USER',$_REQUEST['ftpUser']);
define('APP_FTP_PASS',$_REQUEST['ftpPass']);
define('APP_FTP_KEY',$_REQUEST['ftpKey']);
define('APP_FTP_BASE',$_REQUEST['ftpBase']);
define('APP_FTP_SSL',$_REQUEST['ftpSSL']);
define('APP_FTP_USE_SFTP',$_REQUEST['ftpUseSftp']);
define('APP_FTP_PASV',$_REQUEST['ftpPassive']);

if (!defined('DB_HOST')) {
	define('DB_HOST',$_REQUEST['dbHost']);
}
if (!defined('DB_USER')) {
	define('DB_USER',$_REQUEST['dbUser']);
}
if (!defined('DB_PASSWORD')) {
	define('DB_PASSWORD',$_REQUEST['dbPassword']);
}
if (!defined('DB_NAME')) {
	define('DB_NAME',$_REQUEST['dbName']);
}
if ($_REQUEST['isSameServerStaging']) {
	$IWP_ABSPATH = iwp_wp_normalize_path(dirname(dirname(dirname(__FILE__))));
	$IWP_STAGING_DIR = iwp_wp_normalize_path(dirname(dirname(__FILE__)));
	define('IWP_ABSPATH',$IWP_ABSPATH);
	define('IWP_STAGING_DIR',$IWP_STAGING_DIR);
}
$db_table_prefix = (!empty($_REQUEST['db_table_prefix'])) ? $_REQUEST['db_table_prefix'] : $table_prefix;
$GLOBALS['db_table_prefix'] = $db_table_prefix;
$GLOBALS['downloadPossibleError'] = '';
$GLOBALS['REPLACE_LIST'] = array();
//$old = $_REQUEST['oldSite'];
$old_url = removeTrailingSlash($_REQUEST['oldSite']);
$old_user = $_REQUEST['oldUser'];
$GLOBALS['old_user'] = $_REQUEST['oldUser'];
$newUser = $_REQUEST['newUser'];
$newPassword = $_REQUEST['newPassword'];
$new_url = removeTrailingSlash($_REQUEST['newSiteURL']);
$GLOBALS['new_url'] = $new_url;
$isTestConnection = $_REQUEST['isTestConnection'];
$GLOBALS['URLParseData'] = false;
$testConnectionResult = true;
$GLOBALS['LOG_FILE_HANDLE'] = false;
if (!empty($_REQUEST['actionID'])) {
	$GLOBALS['actionID'] = $_REQUEST['actionID'];
}
$GLOBALS['LOG_FILE_NAME'] = dirname(dirname(__FILE__))."/iwp-clone-".$GLOBALS['actionID']."-log.txt";
$GLOBALS['new_file_path'] = dirname(dirname(__FILE__));
$GLOBALS['needFileSystem'] = false;
if ($GLOBALS['new_file_path']) {
	initFileSystem();
}
//Check access
if (empty($connectionFlag)) {
	$connectionFlag = DB::connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME, '3306');
	$GLOBALS['connectionFlag'] = $connectionFlag; 
}
$GLOBALS['needFileSystem'] = checkFileSystemRequirement();
if ($GLOBALS['needFileSystem']) {
	$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder(dirname(dirname(__FILE__)));
	$GLOBALS['FileSystemObj']->touch($temp_unzip_dir_file.'/iwp-clone-log.txt');
	$GLOBALS['FileSystemObj']->chmod($temp_unzip_dir_file.'/iwp-clone-log.txt', 0777);
}
if ($isMultiCall) {
	$GLOBALS['LOG_FILE_HANDLE'] = @fopen($GLOBALS['LOG_FILE_NAME'], "a+");
}else{
	$GLOBALS['LOG_FILE_HANDLE'] = @fopen($GLOBALS['LOG_FILE_NAME'], "w+");
}

if ($isMultiCall==false) {
	if ($GLOBALS['needFileSystem']) {
		status("*********************************** Clone Will use File system method instead of PHP  *************************", $success=true, $return=false);
	}
	status("*********************************** Clone Test connection started  *************************", $success=true, $return=false);
}

//TestConnection
if($isTestConnection == 1){
	if($connectionFlag === true) {
		appUpdateMsg("test-connection : DB verification Success");
		return true;
	} else{
		appUpdateMsg("test-connection : DB verification Failed(".$connectionFlag.")", 1);
	}
	exit;
}

if ($connectionFlag !== true) {
	$status = "DB verification Failed(".$connectionFlag.")";
	die(status($status, $success=false, $return=true));
}elseif($isMultiCall == false){
	status("DB connected Successfully", $success=true, $return=false);
}

$query = DB::doQuery("CREATE TABLE IF NOT EXISTS `iwp_clone_stats` (
		  `optionName` varchar(255) NOT NULL,
		  `optionValue` longtext
		) ;");

$query = DB::doQuery("CREATE TABLE IF NOT EXISTS `IWP_processed_iterator` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` longtext  NOT NULL,
  `offset` text ,
  PRIMARY KEY (`id`)
);");
if($isMultiCall == false && !IWP_LiteSpeed::$isLiteSpeedMultiCall){
	$query = DB::doQuery("TRUNCATE TABLE `IWP_processed_iterator`");
}
if (!$query) {
	$status = 'Clone status table creation failed check your database credentials';
	die(status($status, $success=false, $return=true));
}elseif($isMultiCall == false){
	status("Clone status table created successfully", $success=true, $return=false);
}

if($connectionFlag !== true) {
    appUpdateMsg("Error establishing DB : ".$connectionFlag, 1);
    return true;
} else{
    appUpdateMsg("DB Connected");
    status("Database SQLMODE chose", $success=true, $return=false);
	DB::doQuery("SET SESSION sql_mode = ' '");
}

if (!empty($prevMultiCallResponse['URLParseData'])) {
	$GLOBALS['URLParseData'] = $prevMultiCallResponse['URLParseData'];
}

if (!empty($_REQUEST['isExistingSite'])) {
	$GLOBALS['isExistingSite'] = $_REQUEST['isExistingSite'];
}
if (!empty($prevMultiCallResponse['isExistingSite'])) {
	$GLOBALS['isExistingSite'] = $prevMultiCallResponse['isExistingSite'];
}

if (!empty($prevMultiCallResponse['WPVersionName'])) {
	$GLOBALS['WPVersionName'] = $prevMultiCallResponse['WPVersionName'];
}

if (!empty($_REQUEST['is_new_backup'])) {
	$GLOBALS['is_new_backup'] = $_REQUEST['is_new_backup'];
}
if (!empty($prevMultiCallResponse['is_new_backup'])) {
	$GLOBALS['is_new_backup'] = $prevMultiCallResponse['is_new_backup'];
}

if (!empty($_REQUEST['isStagingToLive'])) {
	$GLOBALS['isStagingToLive'] = $_REQUEST['isStagingToLive'];
}
if (!empty($prevMultiCallResponse['isStagingToLive'])) {
	$GLOBALS['isStagingToLive'] = $prevMultiCallResponse['isStagingToLive'];
}

if (!empty($_REQUEST['use_default_htaccess'])) {
	$GLOBALS['use_default_htaccess'] = $_REQUEST['use_default_htaccess'];
}
if (!empty($prevMultiCallResponse['use_default_htaccess'])) {
	$GLOBALS['use_default_htaccess'] = $prevMultiCallResponse['use_default_htaccess'];
}

if(!empty($GLOBALS['isStagingToLive']) && !empty($GLOBALS['use_default_htaccess'])){
	IWP_FolderProtection::$isStagingToLive  = true;
}
if ($isMultiCall == false && !IWP_LiteSpeed::$isLiteSpeedMultiCall && empty($_REQUEST['isExistingSite']) && ((isset($_REQUEST['emptyTargetDir']) && $_REQUEST['emptyTargetDir']) || isset($_REQUEST['isStaging']))) {
	status("Deleting root folders ", $success=true, $return=false);
	deleteOldFilesFromRootDir($_REQUEST['excludeFolder'], $_REQUEST['manualBackupFile']);
}
if ($isMultiCall == false) {
	status("*********************************** Clone Test connection Ended *************************", $success=true, $return=false);
}

if ($isMultiCall == false) {
	if(!empty(DB::getExists("SHOW TABLES LIKE '" . $db_table_prefix . "options'"))){
		$query =  "SELECT option_value FROM " . $db_table_prefix . "options  WHERE option_name = 'IWP_backup_history' LIMIT 1";
		$result = DB::doQuery($query);
		if ($result) {
			$_result = new DB::$DBResultClass($result);
			$info = $_result->nextRow($_result);
			$IWP_backup_history = $info['option_value'];
			DB::replace("iwp_clone_stats", array('optionName' => 'IWP_backup_history', 'optionValue' => $IWP_backup_history));
		}
	}
}

if($isMultiCall == false && empty($_REQUEST['isDeleteStagingSite']) && IWP_LiteSpeed::checkTimeOutRuleCompatibility()){
	// once write .htaccess again set as isMultiCall == false that case to avaid again wring .htaccess file empty($_REQUEST['params']['responseData']['isLiteSpeed']
	$temp_unzip_dir = dirname(dirname(__FILE__));
	$temp_unzip_dir = removeTrailingSlash($temp_unzip_dir);
	$data = IWP_LiteSpeed::writeTimeoutRule($new_url,$temp_unzip_dir);
	if($data){
		global $response_arr;
		$response_arr = array();
		$response_arr['isLiteSpeed'] = true;
		$GLOBALS['isLiteSpeedHtaccess'] = true;
		initialize_response_array($response_arr);
		die(status("multicall", $success=true, $return=false, $response_arr));
		return $response_arr;
	}
}

if ($_REQUEST['isSameServerStaging'] && $prevMultiCallResponse['file_iterator'] != true && empty($prevMultiCallResponse['db_clone']) && empty($prevMultiCallResponse['oldURLReplacement']) && empty($prevMultiCallResponse['dbModification']) && empty($_REQUEST['isDeleteStagingSite'])) {
	same_server_copy();
	renameServerConfig($GLOBALS['new_file_path']);
	same_server_clone_db();
	discourageSearchEngine($GLOBALS['new_file_path']);
	sameServerPostDBCloneProcess();
	exit();

}else if($prevMultiCallResponse['file_iterator']) {
	copy_selected_folders();
	renameServerConfig(dirname(dirname(__FILE__)));
	same_server_clone_db();
	discourageSearchEngine($GLOBALS['new_file_path']);
	sameServerPostDBCloneProcess();
	exit();
}else if(!empty($prevMultiCallResponse['db_clone'])){
	same_server_clone_db();
	discourageSearchEngine($GLOBALS['new_file_path']);
	sameServerPostDBCloneProcess();
	exit;
}else if(!empty($_REQUEST['isDeleteStagingSite'])){
	deleteStagingDB($db_table_prefix);
	deleteStagingSite();
	exit;
}  else if(!empty($prevMultiCallResponse['oldURLReplacement'])){
	oldURLReplacement($prevMultiCallResponse['dbModificationArray'], $prevMultiCallResponse['oldURLReplacement']);
	exit;
}else if(!empty($prevMultiCallResponse['dbModification'])){
	cloneDatabaseModification($prevMultiCallResponse['dbModificationArray']);
	exit;
}else if($isMultiCall && !($isDownloadMultiCall) && !$prevMultiCallResponse['is_file_copy']){
	if(empty($_REQUEST['temp_unzip_dir'])){
		$_REQUEST['temp_unzip_dir'] = $prevMultiCallResponse['temp_unzip_dir'];
		$_REQUEST['temp_pclzip'] = $prevMultiCallResponse['temp_pclzip'];
		$_REQUEST['bkfile'] = $prevMultiCallResponse['bkfile'];
	}
	
	if (!empty($prevMultiCallResponse['is_new_backup'])) {
		$GLOBALS['is_new_backup'] = true;
		$GLOBALS['dbBkFile'] = $prevMultiCallResponse['dbBkFile'];
		$GLOBALS['wp_content_url'] = $prevMultiCallResponse['wp_content_url'];
		$dbBkFile = $GLOBALS['dbBkFile'];
		$wpContentURL = $GLOBALS['wp_content_url'];
		$GLOBALS['backup_meta_files'] = $prevMultiCallResponse['backup_meta_files'];
	}
	$bkfile = $prevMultiCallResponse['bkfile'];
}else if($_REQUEST['backupURL'] == "localPackage"){
	$bkfile = "WPPackage.zip";
	
	if(!file_exists($bkfile)) {
   		die(status("Couldn't Find the backup file.", false ,true));
	}
	
	if(file_exists($bkfile)){
		status("Backup File Exist.", true, false);
	}

} else if(!empty($_REQUEST['manualBackupFile']) && $_REQUEST['manualBackupFile'] != 'undefined'){
	$bkfile = '../' . $_REQUEST['manualBackupFile'];
	if (!file_exists(dirname(__FILE__).'/clone_temp/')) {
			@mkdir(dirname(__FILE__).'/clone_temp/');
		}
	if (strpos($bkfile, '_backup_meta_')) {
		$backup_meta = $GLOBALS['new_file_path'].'/backup_meta.php';
		$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($GLOBALS['new_file_path']);
		$result = $GLOBALS['FileSystemObj']->move($temp_unzip_dir_file.'/'.basename($bkfile), $temp_unzip_dir_file.'/backup_meta.php');
		include $backup_meta;
		$GLOBALS['is_new_backup'] = true;
		global $backup_meta_files;
		$backup_meta_files = unserialize($backup_meta_files);
		$wpContentURL = $backup_meta_files['wp_content_url'];
		$dbBkFile = $GLOBALS['new_file_path'].'/'.$backup_meta_files['db'];
		$GLOBALS['dbBkFile'] = $dbBkFile;
		$GLOBALS['wp_content_url'] = $wpContentURL;
		$GLOBALS['backup_meta_files'] = $backup_meta_files;
		$this_backup_URL = getBackupFilesByTaskName($backup_meta_files, true);
		foreach ($this_backup_URL as $k => $v) {
			$this_backup_URL[$k] = $GLOBALS['new_file_path'].'/'.$v;
		}
		// if (empty($_REQUEST['isExistingSite'])) {
		$meta_pos = strpos($_REQUEST['manualBackupFile'], 'eta_');
		$php_pos = strpos($_REQUEST['manualBackupFile'], '.tmp');
		$sub = substr($_REQUEST['manualBackupFile'], $meta_pos-$php_pos);
		$WPVersion = str_replace('.tmp', '', $sub);
		$GLOBALS['WPVersionName'] = 'wordpress-'.$WPVersion.'.zip';
		$WPURL = 'https://wordpress.org/wordpress-'.$WPVersion.'.zip';
		$WPPath = dirname(__FILE__).'/WPPackage.zip';
		$this_backup_URL = array_merge(array($WPPath), $this_backup_URL);
		$download_result = multiCallDownloadUsingCURL($WPURL, $WPPath, $downloadResponseHeaders, $prevMultiCallResponse, $wpContentURL);
		checkdownloadResponseHeaders($downloadResponseHeaders);
		if($download_result['isDownloadMultiCall']){
			$download_result['backupURL'] = $WPURL;
			$download_result['bkfile'] = $this_backup_URL;
			send_multicall_response($download_result);
		}
		// }
		$bkfile = $this_backup_URL;
	}else{
		$bkfile =  get_files_array_from_iwp_part($bkfile, 'manual');
	}
} else{
	if ($prevMultiCallResponse['backupURL']) {
		$this_backup_URL = $prevMultiCallResponse['backupURL'];
		if (!empty($prevMultiCallResponse['is_new_backup'])) {
			$GLOBALS['dbBkFile'] = $prevMultiCallResponse['dbBkFile'];
			$GLOBALS['wp_content_url'] = $prevMultiCallResponse['wp_content_url'];
			$dbBkFile = $GLOBALS['dbBkFile'];
			$GLOBALS['is_new_backup'] = true;
			$wpContentURL = $GLOBALS['wp_content_url'];
		}

	}else {
		status("*********************************** Backup file download started *************************", $success=true, $return=false);
		$wpContentURL = false;
		if (!file_exists(dirname(__FILE__).'/clone_temp/')) {
			@mkdir(dirname(__FILE__).'/clone_temp/');
		}
		if (strpos($_REQUEST['backupURL'], '_backup_meta_')) {
			$URLParseData = parse_url($_REQUEST['backupURL']);
			$downloadResponseHeaders = array();
			$backup_meta = dirname(__FILE__).'/clone_temp/backup_meta.php';
			touch($backup_meta);
			$downloaded = multiCallDownloadUsingCURL($_REQUEST['backupURL'], $backup_meta, $downloadResponseHeaders);
			checkdownloadResponseHeaders($downloadResponseHeaders);
			include $backup_meta;
			$GLOBALS['is_new_backup'] = 1;
			global $backup_meta_files;
			$backup_meta_files = unserialize($backup_meta_files);
			$wpContentURL = $backup_meta_files['wp_content_url'];
			$dbBkFile = dirname(__FILE__).'/clone_temp/'.$backup_meta_files['db'];
			$GLOBALS['dbBkFile'] = $dbBkFile;
			$GLOBALS['backup_meta_files'] = $backup_meta_files;
			$this_backup_URL = getBackupFilesByTaskName($backup_meta_files);
			if(!empty($URLParseData['user']) && !empty($URLParseData['pass'])) {
				$GLOBALS['URLParseData'] = 	$URLParseData;
			}
			// if (empty($_REQUEST['isExistingSite'])) {
			$meta_pos = strpos($_REQUEST['backupURL'], 'eta_');
			$php_pos = strpos($_REQUEST['backupURL'], '.tmp');
			$sub = substr($_REQUEST['backupURL'], $meta_pos-$php_pos);
			$WPVersion = str_replace('.tmp', '', $sub);
			$GLOBALS['WPVersionName'] = 'wordpress-'.$WPVersion.'.zip';
			$WPURL[] = 'https://wordpress.org/wordpress-'.$WPVersion.'.zip';
			$this_backup_URL = array_merge($WPURL, $this_backup_URL);
			// }
			$GLOBALS['is_new_backup'] = 1;
			$GLOBALS['wp_content_url'] = $wpContentURL;
		}else{
			status("Multipart file checking... ", $success=true, $return=false);
			$this_backup_URL = get_files_array_from_iwp_part($_REQUEST['backupURL']);
		}
	}
	
	if(!is_array($this_backup_URL))
	{
		$this_temp_backup_URL = $this_backup_URL;
		$this_backup_URL = array();
		$this_backup_URL[] = $this_temp_backup_URL;
	}

	$tempBkFile= array();
	$tempBkFile=$this_backup_URL;
	$bkfile = array();
	if (!empty($prevMultiCallResponse['bkfile'])) {
		# code...
		$bkfile = $prevMultiCallResponse['bkfile'];
	}
	$download_result = array();
	$is_send_multicall_response = false;
	foreach($this_backup_URL as $key => $single_backup_URL)
	{
		iwp_mmb_auto_print('downloading_backup_file');
		$download_result = downloadURL($single_backup_URL, 'WPPackage.zip', $prevMultiCallResponse, $wpContentURL);
		if($download_result['isDownloadMultiCall']){
			$is_send_multicall_response = true;
			status("Backup file download will continue next call ", $success=true, $return=false);
			break;
		} else if(!empty($download_result['file'])){
			$bkfile[] = $download_result['file'];
		} else{
			$bkfile[] = $download_result;
		}
		if (!file_exists($bkfile[$key])) {
			 die(status("Couldn't Download the backup file.", false ,true));
		}
		if(file_exists($bkfile[$key])){
			status("Backup File Downloaded", true, false);
		}
		unset($tempBkFile[$key]);
		unset($prevMultiCallResponse['file']);
		unset($prevMultiCallResponse['startRange']);
		unset($prevMultiCallResponse['endRange']);
	}
	if($is_send_multicall_response){
		$download_result['backupURL'] = $tempBkFile;
		$download_result['bkfile'] = $bkfile;
		send_multicall_response($download_result);
	}
	if ($GLOBALS['is_new_backup']) {
		$dbkey= array_search($dbBkFile, $bkfile);
		unset($bkfile[$dbkey]);
	}
	//exit;
	}

iwp_mmb_auto_print('downloaded_all_backup_file');

transfer($bkfile, $new_url, $newUser, $newPassword, $old_user, $db_table_prefix, $prevMultiCallResponse, $dbBkFile);

function deleteStagingDB($table_prefix){

	$wp_tables = get_all_tables($table_prefix);
	foreach ($wp_tables as $table) {
		// status("DROP Table ".$table, $success=true, $return=false);
		// $table_skip_status = $this->exclude_class_obj->is_excluded_table($table)
		if (preg_match('#^'.$table_prefix.'#', $table) != 1) {
			continue;
		}
		DB::doQuery("DROP Table ". $table);

	}
	
	status("delete_db_completed", $success=true, $return=false);
}
//This making the issue if site has more number of the table 
function deleteStagingDBOldMethod($table_prefix){
	$tables_delete_query = "SELECT CONCAT( 'DROP TABLE ', GROUP_CONCAT(table_name) , ';' )
		AS statement FROM information_schema.tables
		WHERE table_schema = '".DB_NAME."' AND table_name LIKE '$table_prefix%';";
	
	$queryResult = DB::doQuery($tables_delete_query);
	if(!$queryResult){
		echo DB::error();
	}
	$_result = new DB::$DBResultClass($queryResult);
	$queriedRows = $_result->numRows($_result);
	if($queriedRows){
		$tablesArray = $_result->nextRow($_result);
		$queryResult = DB::doQuery($tablesArray['statement']);
		if(!$queryResult){
			echo DB::error();
		}
		DB::doQuery("DROP Table ". $table);

	}
	
	status("delete_db_completed", $success=true, $return=false);
}

function deleteStagingSite(){
	$site_parent_folder = dirname(dirname(__FILE__));
	initFileSystem(false, $site_parent_folder);
	$directFSObj = new filesystemDirect('');
	$delete_result = $directFSObj->delete($site_parent_folder, true);//dirname(__FILE__) => clone_controller folder
	if(!$delete_result){
		$delete_result = $GLOBALS['FileSystemObj']->delete(removeTrailingSlash(APP_FTP_BASE).'/clone_controller', true);//for those files and folders not delete with direct file system
	}
	if(!$delete_result){
		status("Delete through file system Error.", $success=false, $return=false);
	}
	status("delete_completed", $success=true, $return=false);
}

function deleteOldFilesFromRootDir($exclude = array(), $manualBackupFile){
	$defaultExclude = array('clone_controller','iwp-clone-log.txt');
	$bkfiles = array();
	if (!empty($manualBackupFile) && $manualBackupFile != 'undefined') {
		$bkfiles =  get_files_array_from_iwp_part($manualBackupFile, 'manual');
		$bkfiles = !is_array($bkfiles)?array($bkfiles):$bkfiles;
	}
	$exclude = array_merge($exclude, $defaultExclude);
	$tempWorkingDirFS = new filesystemDirect('');	
	$from = dirname(dirname(__FILE__));
	$dirList = $tempWorkingDirFS->dirList($from);
	initFileSystem();
	$from = addTrailingSlash($from);
	$from = $GLOBALS['FileSystemObj']->findFolder($from);	
	$from = addTrailingSlash($from);
	foreach ((array) $dirList as $filename => $fileinfo )  {
		if (!empty($exclude) && (in_array($filename, $exclude) || (!empty($bkfiles)&&in_array($filename, $bkfiles)) || strpos($filename, 'backup') !== false) || strpos($filename, 'WPPackage') !== false) {
			continue;
		}
		$GLOBALS['FileSystemObj']->delete($from. $filename, 1);
	}
}

function transfer($backup_file, $new_url, $newUser, $newPassword, $old_user, $db_table_prefix, $prevMultiCallResponse = array(), $dbBkFile = false){
	// ***************************************** Extract the ZIP  Starts {*************************

	if(empty($prevMultiCallResponse['is_extract_over'])){
		if(empty($prevMultiCallResponse) || empty($prevMultiCallResponse['next_extract_id'])){
			status("*********************************** Backup file extract process started *************************", $success=true, $return=false);
			if(!isset($_REQUEST['temp_unzip_dir'])){
				$temp_unzip_dir = dirname(dirname(__FILE__));
				$temp_unzip_dir = removeTrailingSlash($temp_unzip_dir);
				$temp_uniq = md5(microtime(1));
				while (is_dir($temp_unzip_dir .'/'. $temp_uniq )) {
					$temp_uniq = md5(microtime(1));
				}
				if (!file_exists(dirname(__FILE__).'/clone_temp/')) {
					mkdir(dirname(__FILE__).'/clone_temp/');
				}
				$temp_pclzip = dirname(__FILE__).'/clone_temp/'.$temp_uniq."_zip_tmp";
				mkdir($temp_pclzip);
				status("Temp folder created ", $success=true, $return=false);
			} else {
				$temp_unzip_dir = $_REQUEST['temp_unzip_dir'];
				$temp_pclzip 	= $_REQUEST['temp_pclzip'];
			}

	        if(@is_writable($temp_unzip_dir) && @is_writable($temp_pclzip) || $GLOBALS['new_file_path']) {
	            status("Using temp working dir:".$temp_unzip_dir, $success=true, $return=false);
				define( 'IWP_CLONE_PCLZIP_TEMPORARY_DIR',  $temp_pclzip."/");
				
				if(empty($_REQUEST['temp_unzip_dir'])){
					$_REQUEST['temp_unzip_dir'] = $temp_unzip_dir;
					$_REQUEST['temp_pclzip'] = $temp_pclzip;
					$_REQUEST['bkfile'] = $backup_file;
				}
	        } else {
	           die(status('Unable to write files to the random directory.', $success=false, $return=true));
	        }
		} else{
			//setting old values from response data
			$temp_unzip_dir = $_REQUEST['temp_unzip_dir'];
			$temp_pclzip = $_REQUEST['temp_pclzip'];
			define( 'IWP_CLONE_PCLZIP_TEMPORARY_DIR',  $temp_pclzip."/");
			logExtractResponse('', array('status' => 'startingBridgeExtract', 'extractParentHID' => $_REQUEST['extractParentHID']), $_REQUEST);
		}
		// For unzipping
		require_once 'class-pclzip.php';
		if(!is_array($backup_file)){
			$temp_backup_file = $backup_file;
			$backup_file = array();
			$backup_file[] = $temp_backup_file;
		}
		@ini_set('memory_limit', '-1');

		if (empty($prevMultiCallResponse['is_file_append'])) {
			$extract_result = extract_in_multicall($backup_file, $temp_unzip_dir);
		}
		
		if(is_array($extract_result) && $extract_result['status'] == 'partiallyCompleted' && empty($prevMultiCallResponse['is_file_append'])){
			global $response_arr;

			$response_arr = array();

			initialize_response_array($response_arr);
			$response_arr['next_extract_id'] = $extract_result['next_extract_id'];

			$response_arr['is_extract_over'] = false;

			$response_arr['status'] = 'partiallyCompleted';

			$response_arr['break'] = true;
			$response_arr['v_pos_entry'] = $extract_result['v_pos_entry'];

			$response_arr['bkfile'] = $extract_result['bkfile'];;

			$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);

			status("Extract will continue next call", $success=true, $return=false);
			die(status("multicall", $success=true, $return=false, $response_arr));

			return true;

			exit;
		}else{
			status("*********************************** Backup file extract process end *************************", $success=true, $return=false);
			status("*********************************** Renaming the htaccess  *************************", $success=true, $return=false);
			renameServerConfig($temp_unzip_dir);
		}

	}
	if(empty($temp_unzip_dir) && !isset($temp_unzip_dir)){
		$temp_unzip_dir = $_REQUEST['temp_unzip_dir'];
		$temp_pclzip 	= $_REQUEST['temp_pclzip'];
	}
	if (empty($prevMultiCallResponse['is_file_append']) && empty($prevMultiCallResponse['next_db_insert_id']) && $GLOBALS['is_new_backup'] == false) {

		// $directFSObj = new filesystemDirect('');
		$GLOBALS['FileSystemObj']->delete($temp_pclzip, true);
		foreach ($backup_file as $key => $file) {
			if (is_file($file)) {
				if ($GLOBALS['needFileSystem']) {
						$file_to_ulink_temp = $GLOBALS['FileSystemObj']->findFolder($file);
						$resultUnlink = $GLOBALS['FileSystemObj']->delete($file_to_ulink_temp);
				}else{
					unlink($file);
				}
			}
		}
		global $response_arr;
		$response_arr = array();
		status("*********************************** File appending process started *************************", $success=true, $return=false);
		initialize_response_array($response_arr);
		$response_arr['is_file_append'] = true;
		$response_arr['status'] = 'partiallyCompleted';
		$response_arr['break'] = true;
		$response_arr['is_extract_over'] = true;
		$response_arr['temp_pclzip'] = $temp_pclzip;
		$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);
		die(status("multicall", $success=true, $return=false, $response_arr));
		return $response_arr;
		
	}elseif(!empty($prevMultiCallResponse['is_extract_over']) && !empty($prevMultiCallResponse['is_file_append']) && $$GLOBALS['is_new_backup'] == false){
		
		if (empty($prevMultiCallResponse['appendFileLists'])) {
			$appendFileLists = $temp_unzip_dir;
		} else{
			$appendFileLists = $prevMultiCallResponse['appendFileLists'];
		}
		appendSplitFiles($appendFileLists);
		status("*********************************** File appending process Ended *************************", $success=true, $return=false);
		status("*********************************** Database dump started *************************", $success=true, $return=false);

	}
	
	// @chmod($temp_unzip_dir, 0755);
	discourageSearchEngine($temp_unzip_dir);
	if ($GLOBALS['is_new_backup'] == true ) {
		// include $dbBkFile;
		global $old_url, $old_file_path, $old_site_url, $backup_meta_files;
		$old_url = $GLOBALS['backup_meta_files']['old_url'];
		$old_file_path = $GLOBALS['backup_meta_files']['old_file_path'];
		status($old_file_path, $success=true, $return=false);


	}elseif(file_exists($temp_unzip_dir.'/iwp_db/index.php')){
		include	$temp_unzip_dir.'/iwp_db/index.php';//this will overwrite few global variables $old_url and $old_file_path
		global $old_url, $old_file_path, $old_site_url;
		if(isset($old_file_path)){
			$old_file_path = removeTrailingSlash($old_file_path);
		}
		if(isset($old_url)){
			$old_url = removeTrailingSlash($old_url);
		}
		if (isset($old_site_url)) {
			$old_site_url = removeTrailingSlash($old_site_url);
		}
	}
	
	// ***************************************** }Extract the ZIP  Ends ****************************
	
	// ***************************************** Replace DB Starts{*********************************
	global $old_url, $new_url, $old_table_prefix, $table_prefix;
	$do_db_clone_basic_requirements = false;
	if(empty($prevMultiCallResponse['old_table_prefix'])){
		$old_table_prefix = trim(get_table_prefix($temp_unzip_dir));
		$do_db_clone_basic_requirements = true;
	} else{
		$old_table_prefix = $prevMultiCallResponse['old_table_prefix'];
	}
	if ($db_table_prefix && ($old_table_prefix != $db_table_prefix)) {
		$has_new_prefix = true;
		$table_prefix = $db_table_prefix;
	} else {
		$has_new_prefix = false;
		$table_prefix = $old_table_prefix;
	}
	if (!empty($GLOBALS['isStagingToLive'])) {
		$table_prefix = $GLOBALS['db_table_prefix'];
		status("Table prefix". $table_prefix, $success=true, $return=false);

	}
	status("Table prefix $db_table_prefix .", $success=true, $return=false);
	if($do_db_clone_basic_requirements){
		$changed_prefix_config = change_table_prefix_config_file($temp_unzip_dir, $table_prefix);
		if ($changed_prefix_config) {
			status("Table prefix $table_prefix changed in Config file.", $success=true, $return=false);
		} else {
			die(status("Error: Couldn't change wp-config.php file.", $success=false, $return=true));
		}
	}

	$paths     = check_mysql_paths();
	if ($GLOBALS['is_new_backup'] == true){
		$db_file_path = dirname(__FILE__);
		$db_file = $dbBkFile;
	} else{
		@chmod($temp_unzip_dir.'/iwp_db',0755);
		$db_file_path = $temp_unzip_dir.'/iwp_db';
		$file_name = glob($db_file_path . '/*.sql');
		$db_file = $file_name[0];
    	$db_file = $db_file_path  . "/" . basename($db_file);
		
	}
	
	
	/*-----Replace URL--------*/
		
	/*if($do_db_clone_basic_requirements){
		if(modify_db_dump($db_file, $has_new_prefix)) {
			status("Database dump modified url and prefix.", $success=true, $return=false);
		} else {
			status("Error: Database dump cannot be modified.", $success=false, $return=true);
		}
	} /* No need to replace URL seperatly it can be done along with while query run */
	/*-----Replace URL-ends--------*/

	$brace     = (substr(PHP_OS, 0, 3) == 'WIN') ? '"' : '';
	$command   = $brace . $paths['mysql'] . $brace . ' --host="' . DB_HOST . '" --user="' . DB_USER . '" --password="' . DB_PASSWORD . '" --default-character-set="utf8" ' . DB_NAME . ' < ' . $brace . $db_file . $brace;
	
	$result = false;
	//$result = cmdExec($command);	
	
    iwp_mmb_auto_print('sql_import');
	
	if ($result){
		status("Database dump executed using command.", $success=true, $return=false);
	} else{
        //Else PHP db dump
        DB::doQuery("SET FOREIGN_KEY_CHECKS = 0");
        DB::doQuery("SET unique_checks=0");
        DB::doQuery("SET NAMES 'utf8'");
        // Read in entire file
        //$lines         = file($db_file);
   
        if ($GLOBALS['is_new_backup']) {
       		$handle = gzopen($db_file, "r");
   		}else{
        	$handle = fopen($db_file, "r");
   		}

		global $response_arr;
		$response_arr = array();
		initialize_response_array($response_arr);
		$next_db_insert_id = empty($prevMultiCallResponse['next_db_insert_id']) ? 0 : $prevMultiCallResponse['next_db_insert_id'];
		$change_collotion = empty($prevMultiCallResponse['change_collotion']) ? 0 : $prevMultiCallResponse['change_collotion'];
		$finalQueryCount = empty($prevMultiCallResponse['finalQueryCount']) ? 0 : $prevMultiCallResponse['finalQueryCount'];
		$failedQueryCount = empty($prevMultiCallResponse['failedQueryCount']) ? 0 : $prevMultiCallResponse['failedQueryCount'];
		$count = 0;
        // Loop through each line
        if($handle){
            while (!feof($handle)){
            	if ($GLOBALS['is_new_backup']) {
		       		$line = gzgets($handle);
		   		}else{
            		$line = fgets($handle);
            	}
                $count ++;
            	
				if($count < $next_db_insert_id){
					continue;
				}

                iwp_mmb_auto_print('php_sql_import');
                // Skip it if it's a comment
                if(substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 3) == '/*!'){
                    continue;
				}
                $line = preg_replace_callback("/(TABLE[S]?|INSERT\ INTO|DROP\ TABLE\ IF\ EXISTS) [`]?([^`\;\ ]+)[`]?/", 'search_and_replace_prefix', $line);// this will replace the old prefix to new one 

                $current_query .= $line;

                if (strlen($current_query) < 10 || $current_query == ";") {
                	continue;
                }
                if(!empty($GLOBALS['isStagingToLive'])){
                	if (substr(trim($line), -1, 1) == ';' && strrpos($current_query,$db_table_prefix.'iwp_backup_status')) {
                		status("iwp_backup_status table skipped", $success=true, $return=false);
                		$current_query = '';
                		continue;
                	}
                }
               	if ($change_collotion == true && strrpos($current_query,'utf8mb4_unicode_520_ci')) {
               		$current_query = str_replace('utf8mb4_unicode_520_ci','utf8mb4_unicode_ci',$current_query);
               	}
                // If it has a semicolon at the end, it's the end of the query
               
                if(substr(trim($line), -1, 1) == ';'){
                    // Perform the query
                	$finalQueryCount ++;
                    $result = DB::doQuery($current_query);
                    if (!$result) {
                    	$failedQueryCount++;
						//------------Due to big query, error msg is not getting saved in IWP Panel DB due to max packet length and other issues-- this is a fix for it------
						$temp_error_replace_text = '...[Big text removed for error]...';
						$max_error_query_length = 1500 + strlen($temp_error_replace_text);
						$temp_current_query = $current_query;
						if(strlen($current_query) > $max_error_query_length){
							$temp_current_query = substr_replace($temp_current_query, '...[Big text removed for error]...', 750, -750);
						}
						$temp_current_query = htmlentities($temp_current_query);
						//------------Due to big query, error msg is not getting saved in IWP Panel DB due to max packet length and other issues-- this is a fix for it------
						echo "line count".$count;
                        $db_error = 'Error performing query "<strong>' . $temp_current_query . '</strong>": ' . DB::error().' Error Number'.DB::errorNo();
                        status("Failed to restore: "  . $db_error, $success=true, $return=false);
                        if (DB::errorNo()==1273) {
                        	$current_query = str_replace('utf8mb4_unicode_520_ci','utf8mb4_unicode_ci',$current_query);
                        	$result = DB::doQuery($current_query);
                        	$change_collotion = true;
                        }
                        clone_error_status_log($db_error);
                        // break;
                    }
                    // Reset temp variable to empty
                    $current_query = '';
					
					$is_multicall_break = check_for_clone_break();
					//if($key == 10){
					if($is_multicall_break){
						global $response_arr;
						$response_arr['next_db_insert_id'] = $count + 1;
						$response_arr['old_table_prefix'] = $old_table_prefix;
						$response_arr['is_extract_over'] = true;
						$response_arr['is_db_insert_over'] = false;
						$response_arr['failedQueryCount'] = $failedQueryCount;
						$response_arr['finalQueryCount'] = $finalQueryCount;
						$response_arr['change_collotion'] = $change_collotion;
						$response_arr['status'] = 'partiallyCompleted';
						$response_arr['break'] = true;
						$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);
						break;
					}
                }
            }
        } else{
            $db_error = 'Cannot open database file.';
            if ($GLOBALS['is_new_backup']) {
        		gzclose($handle);
    		}else{
         		fclose($handle);
    		}
        }
        if ($GLOBALS['is_new_backup']) {
    		gzclose($handle);
		}else{
     		fclose($handle);
		}
		if($response_arr['break'] == true){
			//logExtractResponse($_REQUEST['extractParentHID'], array('status' => 'partiallyCompleted', 'sendResponse' => true, 'nextFunc' => 'backupFiles', 'responseParams' => $response_arr));
			storeCloningResponse();
			status("Query processed : ".$finalQueryCount, $success=true, $return=false);
			die(status("multicall", $success=true, $return=false, $response_arr));
			exit;
			return true;
			
		}
        
    	status("Total query executed : ".$finalQueryCount, $success=true, $return=false);
    	status("Total query failed : ".$failedQueryCount, $success=true, $return=false);
    	status("***********************************Database dump executed*********************************** ", $success=true, $return=false);

	}


	$dbModificationArray = array();
	$dbModificationArray['old_file_path'] = $old_file_path;
	$dbModificationArray['has_new_prefix'] = $has_new_prefix;
	$dbModificationArray['db_file'] = $db_file;
	$dbModificationArray['table_prefix'] = $table_prefix;
	$dbModificationArray['temp_unzip_dir'] = $temp_unzip_dir;
	$dbModificationArray['newUser'] = $newUser;
	$dbModificationArray['newPassword'] = $newPassword;
	$dbModificationArray['old_user'] = $old_user;
	$dbModificationArray['table_prefix'] = $table_prefix;
	$dbModificationArray['old_table_prefix'] = $old_table_prefix;
	$dbModificationArray['new_url'] = $new_url;
	$dbModificationArray['old_url'] = $old_url;
	if (empty($old_site_url)) {//$old_url - old site url
		$query =  "SELECT option_value FROM " . $table_prefix . "options  WHERE option_name = 'siteurl' LIMIT 1";
		$result = DB::doQuery($query) or die(status('Error getting old site URL' . DB::error(), $success=false, $return=true));
        $_result = new DB::$DBResultClass($result);
		$info = $_result->nextRow($_result);
		$old_site_url = removeTrailingSlash($info['option_value']);
	}
	$dbModificationArray['old_site_url'] = $old_site_url;
	$query =  "SELECT option_value FROM " . $table_prefix . "options  WHERE option_name = 'home' LIMIT 1";
	$result = DB::doQuery($query) or die(status('Error getting old site URL' . DB::error(), $success=false, $return=true));
    $_result = new DB::$DBResultClass($result);
	$info = $_result->nextRow($_result);
	$new_old_url = removeTrailingSlash($info['option_value']);
	if ($old_url != $new_old_url) {
		$old_url = $new_old_url;
		$dbModificationArray['old_url'] = $new_old_url;
		
	}
	$isBreak = check_for_clone_break();
	if ($isBreak) {
		global $response_arr;
		$response_arr = array();
		initialize_response_array($response_arr);
		$response_arr['status'] = 'partiallyCompleted';
		$response_arr['break'] = true;
		$response_arr['dbModificationArray'] = $dbModificationArray;
		$response_arr['dbModification'] = true;
		$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);
		die(status("multicall", $success=true, $return=false, $response_arr));
		return $response_arr;
	}

	cloneDatabaseModification($dbModificationArray);
	// $result = copyFilesAndRemoveCloneDir($temp_unzip_dir, dirname(dirname(__FILE__)));
	// if ($result) {
	// 	sendCompleteResponse($newUser, $new_url, $old_user, $table_prefix);
	// }
	
	//@unlink('class-pclzip.php');	
	//@unlink('bridge.php');
	//@unlink('fileSystem.php');
	//@unlink($backup_file);
	
	//if(file_exists('error_log')) @unlink('error_log');
	//@clearstatcache();
	//@rmdir('../clone_controller');
	return true;
}
function set_safe_path($path){
    return str_replace("\\", "/", $path);
}
function unset_safe_path($path) {
        return str_replace("/", "\\", $path);
 }
function _dupx_array_rtrim_iwp(&$value) {
    $value = rtrim($value, '\/');
}
function preg_replacement_Quote($str){
    return preg_replace('/(\$|\\\\)(?=\d)/', '\\\\\1', $str);
}

function cloneDatabaseModification($dbModificationArray){
	$old_file_path = $dbModificationArray['old_file_path'];
	$has_new_prefix = $dbModificationArray['has_new_prefix'];
	$db_file = $dbModificationArray['db_file'];
	$table_prefix = $dbModificationArray['table_prefix'];
	$temp_unzip_dir = $dbModificationArray['temp_unzip_dir'];
	$newUser = $dbModificationArray['newUser'];
	$newPassword = $dbModificationArray['newPassword'];
	$old_user = $dbModificationArray['old_user'];
	$table_prefix = $dbModificationArray['table_prefix'];
	$old_table_prefix = $dbModificationArray['old_table_prefix'];
	$new_url = $dbModificationArray['new_url'];
	$old_url = $dbModificationArray['old_url'];
	$old_site_url = $dbModificationArray['old_site_url'];
	if ($has_new_prefix) {
    	$query = "
			UPDATE {$table_prefix}options
    		SET option_name = '{$table_prefix}user_roles'
    		WHERE option_name = '{$old_table_prefix}user_roles'
    		LIMIT 1";
        DB::doQuery($query) or die(status('Error replacing options values - ' . DB::error(), $success=false, $return=true));
		
    	$query = "
			UPDATE {$table_prefix}usermeta
	    	SET meta_key = CONCAT('{$table_prefix}', SUBSTR(meta_key, CHAR_LENGTH('{$old_table_prefix}') + 1))
	    	WHERE meta_key LIKE '{$old_table_prefix}%'";
    	DB::doQuery($query) or die(status('Error replacing usermeta values - ' . DB::error(), $success=false, $return=true));
    }
	
	status("DB restored", $success=true, $return=false);
	status("DB user role modified", $success=true, $return=false);
	
	if ($GLOBALS['needFileSystem']) {
		$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder(dirname($db_file));
		if ($temp_unzip_dir_file != '/') {
			status("Delete iwp_db folder".$temp_unzip_dir_file, $success=true, $return=false);
			$GLOBALS['FileSystemObj']->delete($temp_unzip_dir_file, 1);
		}
	}else{
		@unlink($db_file);
		@unlink($temp_unzip_dir.'/iwp_db/index.php');
		@clearstatcache();
		@rmdir($temp_unzip_dir.'/iwp_db');
	}
	status("Database file deleted", $success=true, $return=false);
	//}***************************************** Replace DB Ends*********************************
	
	//*********************************** Write the Config File Starts { *************************
	status("*********************************** Write the Config File Starts { *************************", $success=true, $return=false);
	
	$lines = @file($temp_unzip_dir.'/wp-config.php');
    if(empty($lines)){
		$lines = @file($temp_unzip_dir.'/wp-config-sample.php');
	}
	if ($GLOBALS['needFileSystem']) {
		$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($temp_unzip_dir);
		$GLOBALS['FileSystemObj']->delete($temp_unzip_dir_file.'/wp-config.php');
		$GLOBALS['FileSystemObj']->touch($temp_unzip_dir_file.'/wp-config.php');
		$GLOBALS['FileSystemObj']->chmod($temp_unzip_dir_file.'/wp-config.php', 0777);
	}else{
		@unlink($temp_unzip_dir.'/wp-config.php'); // Unlink if a config already exists
	}
	if(empty($lines)){ die(status("Please replace wp-config.php. It seems missing", $success=false, $return=true)); }
	foreach ($lines as $line) {
		if (strstr($line, 'DB_NAME')){
			$line = "define('DB_NAME', '".DB_NAME."');\n";
		}
		if (strstr($line, 'DB_USER')){
			$line = "define('DB_USER', '".DB_USER."');\n";
		}
		if (strstr($line, 'DB_PASSWORD')){
			$line = "define('DB_PASSWORD', '".DB_PASSWORD."');\n";
		}
		if (strstr($line, 'DB_HOST')){
			$line = "define('DB_HOST', '".DB_HOST."');\n";
		}
		
		$result = @file_put_contents($temp_unzip_dir.'/wp-config.php', $line, FILE_APPEND);
		if($result === FALSE)
			die(status("Permission denied to write the config file.", $success=false, $return=true));
	}
	if ($GLOBALS['needFileSystem']) {
		$GLOBALS['FileSystemObj']->chmod($temp_unzip_dir_file.'/wp-config.php', 0644);
	}
	status("*********************************** Write the Config File Ends { *************************", $success=true, $return=false);			
	// }*********************************** Write the Config File Ends **********************************
			
	if (!$old_url) {//$old_url - old site url
		$query =  "SELECT option_value FROM " . $table_prefix . "options  WHERE option_name = 'siteurl' LIMIT 1";
		$result = DB::doQuery($query) or die(status('Error getting old site URL' . DB::error(), $success=false, $return=true));
        $_result = new DB::$DBResultClass($result);
		$info = $_result->nextRow($_result);
		$old_url = removeTrailingSlash($info['option_value']);
	}
				
	// Update the Home / Site URL
	/* This will happen next
	$query = "UPDATE " . $table_prefix . "options SET option_value = '".$new_url."' WHERE option_name = 'home'";
	DB::doQuery($query) or die(status("Error updating the home URL", $success=false, $return=true));
	status("Home URL updated", $success=true, $return=false);
	
	$query = "UPDATE " . $table_prefix . "options  SET option_value = '".$new_url."' WHERE option_name = 'siteurl'";
	DB::doQuery($query) or die(status("Error updating the site URL", $success=false, $return=true));
	status("Site URL updated", $success=true, $return=false);
	*/
	
	//Set the new admin password  
	if ($newUser && $newPassword && $old_user) {//$newPassword -> md5ed password
		$admin_email = trim($_REQUEST['admin_email']);
		$id = '';
		if($admin_email && $newUser){
			$query = "SELECT ID FROM " . $table_prefix ."users WHERE user_email = '".$admin_email."' AND user_login = '".$newUser."'  LIMIT 1";
			$result = DB::doQuery($query);
			$_result = new DB::$DBResultClass($result);
			$id = $_result->nextRow($_result);
		}
		if(empty($id)){
			if ($admin_email) {
				$query = "UPDATE " . $table_prefix . "options SET option_value = '".$admin_email."' WHERE option_name = 'admin_email'";
				DB::doQuery($query) or die(status('Error setting admin email - ' . DB::error(), $success=false, $return=true));
				$query        = "UPDATE " . $table_prefix . "users SET user_email='".$admin_email."' WHERE user_login = '".$old_user."'";
				DB::doQuery($query) or die(status('Error setting new user - ' . DB::error(), $success=false, $return=true));
				status("Admin Email Updated", $success=true, $return=false);
			}
			$query = "UPDATE " . $table_prefix . "users SET user_login = '".$newUser."', user_pass = '".$newPassword."' WHERE user_login = '".$old_user."'";
			DB::doQuery($query) or die(status("Error setting up credentials.", $success=false, $return=true));
			status("Credentials updated.", $success=true, $return=false);
		}else{
			status("We are found same username and email on database list.", $success=true, $return=false);
		}
	}
	if(!empty(DB::getExists("SHOW TABLES LIKE '" . $table_prefix . "options'"))){
		status("Saving html_type ", $success=true, $return=false);
		$query =  "SELECT option_value FROM " . $table_prefix . "options  WHERE option_name = 'html_type' LIMIT 1";
		$result = DB::doQuery($query);
		if ($result) {
			$_result = new DB::$DBResultClass($result);
			$info = $_result->nextRow($_result);
			$html_type = $info['option_value'];
			DB::replace("iwp_clone_stats", array('optionName' => 'html_type', 'optionValue' => $html_type));
		}
	}
	//Remove trailing slashes
	$isBreak = check_for_clone_break();
		if ($isBreak) {
			global $response_arr;
			$response_arr = array();
			initialize_response_array($response_arr);
			$response_arr['status'] = 'partiallyCompleted';
			$response_arr['break'] = true;
			$response_arr['dbModificationArray'] = $dbModificationArray;
			$response_arr['oldURLReplacement'] = true;
			$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);
			die(status("multicall", $success=true, $return=false, $response_arr));
			return $response_arr;
		}
	oldURLReplacement($dbModificationArray, false);
	
}
function oldURLReplacement_old_method($dbModificationArray, $is_fresh = false){
		$table_prefix = $dbModificationArray['table_prefix'];
		$temp_unzip_dir = $dbModificationArray['temp_unzip_dir'];
		$newUser = $dbModificationArray['newUser'];
		$newPassword = $dbModificationArray['newPassword'];
		$old_user = $dbModificationArray['old_user'];
		$old_table_prefix = $dbModificationArray['old_table_prefix'];
		$new_url = $dbModificationArray['new_url'];
		$old_url = $dbModificationArray['old_url'];
		$old_site_url = $dbModificationArray['old_site_url'];
		$old_file_path = $dbModificationArray['old_file_path'];

		$url_old_json = str_replace('"', "", json_encode($old_url));
		$url_new_json = str_replace('"', "", json_encode($new_url));
		$path_old_json = str_replace('"', "", json_encode($old_file_path));
		$path_new_json = str_replace('"', "", json_encode($GLOBALS['new_file_path']));
		$site_url_old_json = str_replace('"', "", json_encode($old_site_url));

		//DIRS PATHS
		array_push($GLOBALS['REPLACE_LIST'],
			array('search' => $old_file_path,			 'replace' => $GLOBALS['new_file_path']),
			array('search' => $path_old_json,				 'replace' => $path_new_json),
			array('search' => urlencode($old_file_path), 'replace' => urlencode($GLOBALS['new_file_path'])),
			array('search' => rtrim(unset_safe_path($old_file_path), '\\'), 'replace' => rtrim($GLOBALS['new_file_path'], '/'))
		);
		// $old_site_name = str_replace(array('http://www.', 'https://www.', 'http://', 'https://'), '', $old_url);
		// $new_site_name = str_replace(array('http://www.', 'https://www.', 'http://', 'https://'), '', $new_url);

		//SEARCH WITH NO PROTOCAL: RAW "//"
		$url_old_raw = str_ireplace(array('http://', 'https://'), '//', $old_url);
		$url_new_raw = str_ireplace(array('http://', 'https://'), '//', $new_url);
		$url_old_raw_json = str_replace('"',  "", json_encode($url_old_raw));
		$url_new_raw_json = str_replace('"',  "", json_encode($url_new_raw));

		array_push($GLOBALS['REPLACE_LIST'],
		    //RAW
		    array('search' => $url_old_raw,			 	'replace' => $url_new_raw),
		    array('search' => $url_old_raw_json,		'replace' => $url_new_raw_json),
		    array('search' => urlencode($url_old_raw), 	'replace' => urlencode($url_new_raw))
		);

		if (stristr($old_url, 'http:') && stristr($new_url, 'https:') ) {
		    $url_old_http = str_ireplace('https:', 'http:', $new_url);
		    $url_new_http = $new_url;
		    $url_old_http_json = str_replace('"',  "", json_encode($url_old_http));
		    $url_new_http_json = str_replace('"',  "", json_encode($url_new_http));

		} elseif(stristr($old_url, 'https:') && stristr($new_url, 'http:')) {
		    $url_old_http = str_ireplace('http:', 'https:', $new_url);
		    $url_new_http = $new_url;
		    $url_old_http_json = str_replace('"',  "", json_encode($url_old_http));
		    $url_new_http_json = str_replace('"',  "", json_encode($url_new_http));
		}

		if(isset($url_old_http)){
		    array_push($GLOBALS['REPLACE_LIST'],
		        array('search' => $url_old_http,			 	 'replace' => $url_new_http),
		        array('search' => $url_old_http_json,			 'replace' => $url_new_http_json),
		        array('search' => urlencode($url_old_http),  	 'replace' => urlencode($url_new_http))
		    );
		}
		/*array_push($GLOBALS['REPLACE_LIST'], 
				array('search' => $old_site_url,			 'replace' => $new_url), 
				array('search' => $old_url,			 'replace' => $new_url), 
				array('search' => $old_file_path,			 'replace' => $GLOBALS['new_file_path']), 
				array('search' => $site_url_old_json,				 'replace' => $url_new_json), 
				array('search' => $url_old_json,				 'replace' => $url_new_json), 
				array('search' => $path_old_json,				 'replace' => $path_new_json), 	
				array('search' => urlencode($old_file_path), 'replace' => urlencode($GLOBALS['new_file_path'])), 
				array('search' => urlencode($old_site_url),  'replace' => urlencode($new_url)),
				array('search' => urlencode($old_url),  'replace' => urlencode($new_url)),
				array('search' => rtrim(unset_safe_path($old_file_path), '\\'), 'replace' => rtrim($GLOBALS['new_file_path'], '/'))
		);*/// Old method

		array_walk_recursive($GLOBALS['REPLACE_LIST'], '_dupx_array_rtrim_iwp');
		if ($is_fresh == false && empty($dbModificationArray['replaceTableList'])) {
			$result = DB::getFields( 'SHOW TABLES LIKE "'.$table_prefix.'%"');
		}else{
			$result = $dbModificationArray['replaceTableList'];
		}
		foreach ($result as $key => $value) {
			DBUpdateEngine::load($GLOBALS['REPLACE_LIST'], array(0=>$value), true);
			status("Table ".$value." URL content updated.", $success=true, $return=false);
			unset($result[$key]);
			$isBreak = check_for_clone_break();
			if ($isBreak) {
				global $response_arr;
				$response_arr = array();
				initialize_response_array($response_arr);
				$response_arr['status'] = 'partiallyCompleted';
				$response_arr['break'] = true;
				$dbModificationArray['replaceTableList'] = $result;
				$response_arr['dbModificationArray'] = $dbModificationArray;
				$response_arr['oldURLReplacement'] = true;
				$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);
				die(status("multicall", $success=true, $return=false, $response_arr));
				return $response_arr;
			}
		}
		//Replace the post contents
		// $query = "UPDATE " . $table_prefix . "posts SET post_content = REPLACE (post_content, '$old_url','$new_url') WHERE post_content REGEXP 'src=\"(.*)$old_url(.*)\"' OR post_content REGEXP 'href=\"(.*)$old_url(.*)\"'";
		// DB::doQuery($query) or die(status("Error updating the post content", $success=false, $return=true));
		status("Post content updated.", $success=true, $return=false);
		 
		//$table = $GLOBALS['table_prefix'].'iwp_backup_status';
		 
		//mysql_num_rows(mysql_query("SHOW TABLES LIKE ".$table_prefix."iwp_backup_status"))
		$query = "
				UPDATE {$table_prefix}options
	    		SET option_value = '$new_url'
	    		WHERE option_name = 'siteurl'
	    		";
	    DB::doQuery($query) or die(status('Error replacing options values - ' . DB::error(), $success=false, $return=true));
	    $query = "
				UPDATE {$table_prefix}options
	    		SET option_value = '$new_url'
	    		WHERE option_name = 'home'
	    		";
	    DB::doQuery($query) or die(status('Error replacing options values - ' . DB::error(), $success=false, $return=true));
		$queryTestBS = DB::doQuery("SHOW TABLES LIKE '".$table_prefix."iwp_backup_status'");
		if(!$queryTestBS){
			echo DB::error();
		}
		$_result = new DB::$DBResultClass($queryTestBS);
		$queryTestBSRows = $_result->numRows($_result);
			
		if($queryTestBSRows){
			$delete = DB::doQuery("TRUNCATE TABLE ".$table_prefix."iwp_backup_status ")or die(status('Failed to clear old IWP backup status table.' . DB::error(), $success=false, $return=true));
			status("IWP backup status table cleared", $success=true, $return=false);
		}
		$query = "
			UPDATE ".$table_prefix."options
    		SET option_value = ''
    		WHERE option_name = 'IWP_backup_history' ";
        DB::doQuery($query);
		//clearing iwp-client plugin iwp_client_public_key, iwp_client_action_message_id, iwp_client_nossl_key
		$query = "DELETE FROM " . $table_prefix . "options WHERE option_name = 'iwp_client_public_key' OR option_name = 'iwp_client_action_message_id' OR option_name = 'iwp_client_nossl_key'";
		DB::doQuery($query) or die(status('Failed to clear old IWP Client Plugin details.' . DB::error(), $success=false, $return=true));
		status("Cleared old IWP Client Plugin details.", $success=true, $return=false);
		
		//Remove the iwp-client plugin old data // Need to change these
		$query = "DELETE FROM " . $table_prefix . "options WHERE option_name IN ('iwp_backup_tasks', 'iwp_notifications', 'iwp_client_brand', 'user_hit_count', 'iwp_pageview_alerts')";
		DB::doQuery($query) or die(status('Error deleting client settings' . DB::error(), $success=false, $return=true));
		status("IWP settings Deleted", $success=true, $return=false);  
		$query = "DELETE FROM " . $table_prefix . "options WHERE option_name LIKE '%IWP_jobdata_%'";
		DB::doQuery($query);
			   
	    if (!empty($_REQUEST['toIWP'])) {
			$iwp_client_activation_key = sha1( rand(1, 99999). uniqid('', true) .$new_url);
			$query = "REPLACE INTO " . $table_prefix . "options(option_name, option_value) VALUES('iwp_client_activate_key', '$iwp_client_activation_key')";
			DB::doQuery($query) or die(status("Failed to create Activation Key", $success=false, $return=true));
			status("Activation Key Created", $success=true, $return=false);
	    } else{
			//deactivate iwp-client plugin
			$query = "SELECT option_value FROM " . $table_prefix . "options WHERE option_name='active_plugins'";
			$result = DB::doQuery($query) or die(status("Failed to get active plugins", $success=false, $return=true));
	        $_result = new DB::$DBResultClass($result);
			$row = $_result->nextRow($_result);
			$active_plugins = @unserialize($row['option_value']);
			$key = array_search('iwp-client/init.php', $active_plugins);
			if($key !== false && $key !== NULL){
				unset($active_plugins[$key]);
			}
			$active_plugins = @serialize($active_plugins);
			$query = "UPDATE " . $table_prefix . "options SET option_value = '$active_plugins' WHERE option_name='active_plugins'";
			$result = DB::doQuery($query) or die(status("Failed to deactivate client plugin", $success=false, $return=true));
		}
			   
		$admin_email = trim($_REQUEST['admin_email']);
	    if(trim($old_user) == ''){
	    	if ($admin_email) {
				//Clean Install
				$query = "UPDATE " . $table_prefix . "options SET option_value = '$admin_email' WHERE option_name = 'admin_email'";
				DB::doQuery($query) or die(status('Error setting admin email - ' . DB::error(), $success=false, $return=true));
				status("Admin Email created", $success=true, $return=false);
				
				$query = "SELECT * FROM " . $table_prefix ."users LIMIT 1";
				$temp_user_result = DB::doQuery($query) or die(status('Error: user to replace not found - ' . DB::error(), $success=false, $return=true));
				$_result = new DB::$DBResultClass($temp_user_result);
				if($temp_user = $_result->nextRow($_result)){
					$query        = "UPDATE " . $table_prefix . "users SET user_email='$admin_email', user_login = '$newUser', user_pass = '$newPassword' WHERE user_login = '$temp_user[user_login]'";
					DB::doQuery($query) or die(status('Error setting new user - ' . DB::error(), $success=false, $return=true));
					status("New User Created", $success=true, $return=false);
				}
			} else {
	    		//Clone from url
	    		if($newUser && $newPassword){
					$query = "UPDATE " . $table_prefix . "users SET user_pass = '$newPassword' WHERE user_login = '$newUser'";
					DB::doQuery($query) or die(status('Error setting new password - ' . DB::error(), $success=false, $return=true));
					status("New Password Created", $success=true, $return=false);
				}
	    	}
	    }
		
		//Reset media upload settings
	    $query = "UPDATE " . $table_prefix . "options SET option_value = '' WHERE option_name = 'upload_path' OR option_name = 'upload_url_path'";
	    DB::doQuery($query) or die(status('Error setting media upload settings - ' . DB::error(), $success=false, $return=true));
		
		//@mysql_close($sqlConnect);
		status("DB Modifications done", $success=true, $return=false);

		//$result = copyFilesAndRemoveCloneDir($temp_unzip_dir, dirname(dirname(__FILE__)));
		//if ($result) {
		/** ==============================
		 * MU Updates*/
		status("*********************************** Multi user domain replacement start *************************", $success=true, $return=false);
		$mu_newDomain = parse_url($new_url);
		$mu_oldDomain = parse_url($old_url);
		$mu_newDomainHost = $mu_newDomain['host'];
		$mu_oldDomainHost = $mu_oldDomain['host'];
		$mu_newUrlPath = parse_url($new_url, PHP_URL_PATH);
		$mu_oldUrlPath = parse_url($old_url, PHP_URL_PATH);

		//Force a path for PATH_CURRENT_SITE
		$mu_newUrlPath = (empty($mu_newUrlPath) || ($mu_newUrlPath == '/')) ? '/'  : rtrim($mu_newUrlPath, '/') . '/';
		$mu_oldUrlPath = (empty($mu_oldUrlPath) || ($mu_oldUrlPath == '/')) ? '/'  : rtrim($mu_oldUrlPath, '/') . '/';
		$is_blogs_exits = DB::getField("SHOW TABLES LIKE '" . $table_prefix . "blogs'");
		if (!empty($is_blogs_exits)) {
			$query = "UPDATE " . $table_prefix . "blogs SET domain = '{$mu_newDomainHost}' WHERE domain = '{$mu_oldDomainHost}'";
			DB::doQuery($query);
			$query = "UPDATE " . $table_prefix . "blogs SET path = REPLACE(path, '{$mu_oldUrlPath}', '{$mu_newUrlPath}')";
			DB::doQuery($query);
		}
		status("*********************************** Multi user domain replacement end *************************", $success=true, $return=false);

		status("*********************************** Config file additional constants replace Started *************************", $success=true, $return=false);

		$iwp_config = new IWP_WPConfig($dbModificationArray);
		$iwp_config->updateStandard();
		$iwp_config->updateExtended();
		status("*********************************** Config file additional constants replace ended *************************", $success=true, $return=false);
		status("*********************************** Server config file reset process started*************************", $success=true, $return=false);
		replace_htaccess($new_url, $temp_unzip_dir, $old_file_path, $old_url);
		status("********** Wordfence configurations **********", $success=true, $return=false);
		resetWordfenceConfig($temp_unzip_dir, $old_file_path);
		status("*********************************** Server config file reset process ended *************************", $success=true, $return=false);
		replaceOldCachePath($temp_unzip_dir, $old_file_path, $old_url, $new_url);
		replaceCacheURLInHtaccess($temp_unzip_dir, $old_file_path);
		deleteCloneDir();
		// if ($result) {
			sendCompleteResponse($newUser, $new_url, $old_user, $table_prefix);
		// }
		//}
}

function oldURLReplacement($dbModificationArray, $is_fresh = false){
		$table_prefix = $dbModificationArray['table_prefix'];
		$temp_unzip_dir = $dbModificationArray['temp_unzip_dir'];
		$newUser = $dbModificationArray['newUser'];
		$newPassword = $dbModificationArray['newPassword'];
		$old_user = $dbModificationArray['old_user'];
		$old_table_prefix = $dbModificationArray['old_table_prefix'];
		$new_url = $dbModificationArray['new_url'];
		$old_url = $dbModificationArray['old_url'];
		$old_site_url = $dbModificationArray['old_site_url'];
		$old_file_path = $dbModificationArray['old_file_path'];

		$old_site_url = iwp_untrailingslashit(trim($old_site_url));
		$old_url = iwp_untrailingslashit(trim($old_url));
		$new_url = iwp_untrailingslashit(trim($new_url));

		$old_file_path = iwp_untrailingslashit(trim($old_file_path));
		$new_file_path = iwp_untrailingslashit(trim($GLOBALS['new_file_path']));

		$old_url = iwp_check_and_protocol($old_url);
		$new_url = iwp_check_and_protocol($new_url);

		/*

		http://example.com to https://example.com/staging

		(1) with and without www search and replace with placeholder

		//example.com					|		
		//www.example.com				|	to	|	//|---NEW----URL---|

		urlencode(//example.com)		|	
		urlencode(//www.example.com)	|	to |	urlencode(//|---NEW----URL---|)

		json_encode(//example.com)		|	
		json_encode(//www.example.com)	|	to |	json_encode(//|---NEW----URL---|)

		(2) If new url is https, then http to https or if new url is http then https to http

		http://|---NEW----URL---|				|	to	|	https://|---NEW----URL---|

		urlencode(http://|---NEW----URL---|)	|	to |	urlencode(https://|---NEW----URL---|)

		json_encode(http://|---NEW----URL---|)	|	to |	json_encode(https://|---NEW----URL---|)

		(3) with out protocol, change the placeholder to new url

		//|---NEW----URL---|		|	to	|	//example.com/staging

		urlencode(//|---NEW----URL---|)		|	to	|	urlencode
			(//example.com/staging)

		json_encode(//|---NEW----URL---|)		|	to	|	json_encode(//example.com/staging)

		*/
		
		//old urls
		$site_relative_url_without_www = iwp_add_protocal_to_url($old_site_url, $protocal = '//', $add_www = false);
		$site_relative_url_with_www = iwp_add_protocal_to_url($old_site_url, $protocal = '//', $add_www = true);
		$old_relative_url_without_www = iwp_add_protocal_to_url($old_url, $protocal = '//', $add_www = false);
		$old_relative_url_with_www = iwp_add_protocal_to_url($old_url, $protocal = '//', $add_www = true);

		$site_relative_url_without_www_urlencoded = urlencode($site_relative_url_without_www);
		$old_relative_url_without_www_urlencoded = urlencode($old_relative_url_without_www);
		$old_relative_url_with_www_urlencoded  = urlencode($old_relative_url_with_www);

		$site_relative_url_without_www_json = str_replace('"', "", json_encode($site_relative_url_without_www));
		$old_relative_url_without_www_json = str_replace('"', "", json_encode($old_relative_url_without_www));
		$old_relative_url_with_www_json = str_replace('"', "", json_encode($old_relative_url_with_www));

		//placeholder urls
		$placeholder_relative_url = '//|---NEW----URL---|';//there is advantage of using '//' in front of this placeholder. Which get converted to '\/\/' in json so it will avoid double replace

		$placeholder_relative_url_urlencoded = urlencode($placeholder_relative_url);

		$placeholder_relative_url_json  = str_replace('"', "", json_encode($placeholder_relative_url));


		//new url s
		$new_relative_url = str_ireplace(array('http://', 'https://'), '//', $new_url);

		$new_relative_url_urlencoded = urlencode($new_relative_url);

		$new_relative_url_json  = str_replace('"', "", json_encode($new_relative_url));

		//____ need to come multisite code _____ //

		//protocols

		if(stristr($new_url, 'https:')){
			$from_protocol = 'http:';//even old url is https, it better to clean away http protocols
			$to_protocol = 'https:';			
		}
		else{
			$from_protocol = 'https:';//read above comment - similar
			$to_protocol = 'http:';
		}

		$from_protocol_urlencode = urlencode($from_protocol);
		$to_protocol_urlencode = urlencode($to_protocol);

		//no need to encode http: and https: but still ;)
		$from_protocol_json  = str_replace('"', "", json_encode($from_protocol));
		$to_protocol_json  = str_replace('"', "", json_encode($to_protocol));

		//placeholders for path
		$placeholder_path = '|---NEW----PATH---|';
		$placeholder_path_urlencode = '|--URLENCODE--NEW----PATH---|';
		$placeholder_path_json = '|--JSON--NEW----PATH---|';


		array_push($GLOBALS['REPLACE_LIST'],
			//old url to placeholder url
		    array(
		        'search'  => $site_relative_url_without_www,
		        'replace' => $placeholder_relative_url
		    ),
		    array(
                'search'  => $site_relative_url_with_www,
                'replace' => $placeholder_relative_url
			),
		    array(
		        'search'  => $site_relative_url_without_www_urlencoded,
		        'replace' => $placeholder_relative_url
		    ),
		    array(
		        'search'  => $site_relative_url_without_www_json,
		        'replace' => $placeholder_relative_url
		    ),
            array(
                'search'  => $old_relative_url_without_www,
                'replace' => $placeholder_relative_url
            ),
            array(
                'search'  => $old_relative_url_with_www,
                'replace' => $placeholder_relative_url
			),
			array(
                'search'  => $old_relative_url_without_www_urlencoded,
                'replace' => $placeholder_relative_url_urlencoded
            ),
            array(
                'search'  => $old_relative_url_with_www_urlencoded,
                'replace' => $placeholder_relative_url_urlencoded
			),
			array(
                'search'  => $old_relative_url_without_www_json,
                'replace' => $placeholder_relative_url_json
            ),
            array(
                'search'  => $old_relative_url_with_www_json,
                'replace' => $placeholder_relative_url_json
			)
		);

		//____ need to come multisite code _____ //

		array_push($GLOBALS['REPLACE_LIST'],
			//file paths
			array(//json replace should fist happen before plain path replace to avoid subset issue('/public_html' is subset of its json version '\/public_html' it happen when it is single folder)
                'search'  => str_replace('"', "", json_encode($old_file_path)),
                'replace' => str_replace('"', "", json_encode($placeholder_path_json))
			),
					
            array(
                'search'  => $old_file_path,
                'replace' => $placeholder_path
			),
			
			array(
                'search'  => urlencode($old_file_path),
                'replace' => urlencode($placeholder_path_urlencode)
            ),

			//---------------------Start replacing placeholers----------------
			array(
                'search'  => str_replace('"', "", json_encode($placeholder_path_json)),
                'replace' => str_replace('"', "", json_encode($new_file_path))
			),
			array(
                'search'  => $placeholder_path,
                'replace' => $new_file_path
			),
			
			array(
                'search'  => urlencode($placeholder_path_urlencode),
                'replace' => urlencode($new_file_path)
            ),

            array(//exceptional case
                'search'  => rtrim(iwp_unset_safe_path($old_file_path), '\\'),
				'replace' => rtrim($new_file_path, '/')
			),

			//from protocol placeholder url (to) to protocol placeholder url 
			array(
                'search'  => $from_protocol . $placeholder_relative_url,
                'replace' => $to_protocol . $placeholder_relative_url
			),
			array(
                'search'  => $from_protocol_urlencode . $placeholder_relative_url_urlencoded,
                'replace' => $to_protocol_urlencode . $placeholder_relative_url_urlencoded
            ),
            array(
                'search'  => $from_protocol_json. $placeholder_relative_url_json,
                'replace' => $to_protocol_json . $placeholder_relative_url_json
			)
		);

		//____ need to come multisite code _____ //

		array_push($GLOBALS['REPLACE_LIST'],
			array(
                'search'  => $placeholder_relative_url,
                'replace' => $new_relative_url
			),
			array(
                'search'  => $placeholder_relative_url_urlencoded,
                'replace' => $new_relative_url_urlencoded
            ),
            array(
                'search'  => $placeholder_relative_url_json,
				'replace' => $new_relative_url_json
			)
		);


		array_walk_recursive($GLOBALS['REPLACE_LIST'], '_dupx_array_rtrim_iwp');
		if ($is_fresh == false && empty($dbModificationArray['replaceTableList'])) {
			// SHOW TABLES LIKE 'wp_%'
			// This quoted LIKE operand seldom holds a full table name.(wp1_,wp2_)
			// eg : $new_table_prefix = wp\_  
			$new_table_prefix = addcslashes($table_prefix, '_%\\' );
			$result = DB::getFields( 'SHOW TABLES LIKE "'.$new_table_prefix.'%"');
		}else{
			$result = $dbModificationArray['replaceTableList'];
		}
		if (!empty($dbModificationArray['offset'])) {
			$GLOBALS['offset'] = $dbModificationArray['offset'];
		}
		foreach ($result as $key => $value) {
			$replaceResult = DBUpdateEngine::load($GLOBALS['REPLACE_LIST'], array(0=>$value), true);
			$offset = false;
			if (!empty($replaceResult['offset'])) {
				$offset = $replaceResult['offset'];
				status("Table ".$value." URL content updated with current offset ".$offset, $success=true, $return=false);
			}else{
				status("Table ".$value." URL content updated.", $success=true, $return=false);
				unset($result[$key]);
			}
			$isBreak = check_for_clone_break();
			if ($isBreak) {
				global $response_arr;
				$response_arr = array();
				initialize_response_array($response_arr);
				$response_arr['status'] = 'partiallyCompleted';
				$response_arr['break'] = true;
				$dbModificationArray['replaceTableList'] = $result;
				if (!empty($offset)) {
					$dbModificationArray['offset'] = $offset;
				}else{
					$dbModificationArray['offset'] = 0;
				}
				$response_arr['dbModificationArray'] = $dbModificationArray;
				$response_arr['oldURLReplacement'] = true;
				$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);
				die(status("multicall", $success=true, $return=false, $response_arr));
				return $response_arr;
			}
		}
		//Replace the post contents
		// $query = "UPDATE " . $table_prefix . "posts SET post_content = REPLACE (post_content, '$old_url','$new_url') WHERE post_content REGEXP 'src=\"(.*)$old_url(.*)\"' OR post_content REGEXP 'href=\"(.*)$old_url(.*)\"'";
		// DB::doQuery($query) or die(status("Error updating the post content", $success=false, $return=true));
		status("Post content updated.", $success=true, $return=false);
		 
		//$table = $GLOBALS['table_prefix'].'iwp_backup_status';
		 
		//mysql_num_rows(mysql_query("SHOW TABLES LIKE ".$table_prefix."iwp_backup_status"))
		$query = "
				UPDATE {$table_prefix}options
	    		SET option_value = '$new_url'
	    		WHERE option_name = 'siteurl'
	    		";
	    DB::doQuery($query) or die(status('Error replacing options values - ' . DB::error(), $success=false, $return=true));
	    $query = "
				UPDATE {$table_prefix}options
	    		SET option_value = '$new_url'
	    		WHERE option_name = 'home'
	    		";
	    DB::doQuery($query) or die(status('Error replacing options values - ' . DB::error(), $success=false, $return=true));
	    if(empty($GLOBALS['isStagingToLive'])){
		$queryTestBS = DB::doQuery("SHOW TABLES LIKE '".$table_prefix."iwp_backup_status'");
		if(!$queryTestBS){
			echo DB::error();
		}
		$_result = new DB::$DBResultClass($queryTestBS);
		$queryTestBSRows = $_result->numRows($_result);
			
		if($queryTestBSRows){
			$delete = DB::doQuery("TRUNCATE TABLE ".$table_prefix."iwp_backup_status ")or die(status('Failed to clear old IWP backup status table.' . DB::error(), $success=false, $return=true));
			status("IWP backup status table cleared", $success=true, $return=false);
		}
		$query = "
			UPDATE ".$table_prefix."options
    		SET option_value = ''
    		WHERE option_name = 'IWP_backup_history' ";
        DB::doQuery($query);
	    }
		//clearing iwp-client plugin iwp_client_public_key, iwp_client_action_message_id, iwp_client_nossl_key
		$query = "DELETE FROM " . $table_prefix . "options WHERE option_name = 'iwp_client_public_key' OR option_name = 'iwp_client_action_message_id' OR option_name = 'iwp_client_nossl_key'";
		DB::doQuery($query) or die(status('Failed to clear old IWP Client Plugin details.' . DB::error(), $success=false, $return=true));
		status("Cleared old IWP Client Plugin details.", $success=true, $return=false);
		
		//Remove the iwp-client plugin old data // Need to change these
		$query = "DELETE FROM " . $table_prefix . "options WHERE option_name IN ('iwp_backup_tasks', 'iwp_notifications', 'iwp_client_brand', 'user_hit_count', 'iwp_pageview_alerts')";
		DB::doQuery($query) or die(status('Error deleting client settings' . DB::error(), $success=false, $return=true));
		status("IWP settings Deleted", $success=true, $return=false);  
		$query = "DELETE FROM " . $table_prefix . "options WHERE option_name LIKE '%IWP_jobdata_%'";
		DB::doQuery($query);
			   
	    if (!empty($_REQUEST['toIWP'])) {
			$iwp_client_activation_key = sha1( rand(1, 99999). uniqid('', true) .$new_url);
			$query = "REPLACE INTO " . $table_prefix . "options(option_name, option_value) VALUES('iwp_client_activate_key', '$iwp_client_activation_key')";
			DB::doQuery($query) or die(status("Failed to create Activation Key", $success=false, $return=true));
			status("Activation Key Created", $success=true, $return=false);
	    } else{
			//deactivate iwp-client plugin
			$query = "SELECT option_value FROM " . $table_prefix . "options WHERE option_name='active_plugins'";
			$result = DB::doQuery($query) or die(status("Failed to get active plugins", $success=false, $return=true));
	        $_result = new DB::$DBResultClass($result);
			$row = $_result->nextRow($_result);
			$active_plugins = @unserialize($row['option_value']);
			$key = array_search('iwp-client/init.php', $active_plugins);
			if($key !== false && $key !== NULL){
				unset($active_plugins[$key]);
			}
			$active_plugins = @serialize($active_plugins);
			$query = "UPDATE " . $table_prefix . "options SET option_value = '$active_plugins' WHERE option_name='active_plugins'";
			$result = DB::doQuery($query) or die(status("Failed to deactivate client plugin", $success=false, $return=true));
		}
			   
		$admin_email = trim($_REQUEST['admin_email']);
	    if(trim($old_user) == ''){
	    	if ($admin_email) {
				if($admin_email && $newUser){
					$query = "SELECT ID FROM " . $table_prefix ."users WHERE user_email = '".$admin_email."' AND user_login = '".$newUser."'  LIMIT 1";
					$result = DB::doQuery($query);
					$_result = new DB::$DBResultClass($result);
					$id = $_result->nextRow($_result);
				}
				if(empty($id)){
					$query = "UPDATE " . $table_prefix . "options SET option_value = '$admin_email' WHERE option_name = 'admin_email'";
					DB::doQuery($query) or die(status('Error setting admin email - ' . DB::error(), $success=false, $return=true));
					status("Admin Email created", $success=true, $return=false);
					
					$query = "SELECT * FROM " . $table_prefix ."users LIMIT 1";
					$temp_user_result = DB::doQuery($query) or die(status('Error: user to replace not found - ' . DB::error(), $success=false, $return=true));
					$_result = new DB::$DBResultClass($temp_user_result);
					if($temp_user = $_result->nextRow($_result)){
						$query        = "UPDATE " . $table_prefix . "users SET user_email='$admin_email', user_login = '$newUser', user_pass = '$newPassword' WHERE user_login = '$temp_user[user_login]'";
						DB::doQuery($query) or die(status('Error setting new user - ' . DB::error(), $success=false, $return=true));
						status("New User Created", $success=true, $return=false);
					}
				}else{
					status("We are found same username and email on database list.", $success=true, $return=false);
				}
				//Clean Install
			} else {
	    		//Clone from url
	    		if($newUser && $newPassword){
					$query = "UPDATE " . $table_prefix . "users SET user_pass = '$newPassword' WHERE user_login = '$newUser'";
					DB::doQuery($query) or die(status('Error setting new password - ' . DB::error(), $success=false, $return=true));
					status("New Password Created", $success=true, $return=false);
				}
	    	}
	    }
		
		//Reset media upload settings
	    $query = "UPDATE " . $table_prefix . "options SET option_value = '' WHERE option_name = 'upload_path' OR option_name = 'upload_url_path'";
	    DB::doQuery($query) or die(status('Error setting media upload settings - ' . DB::error(), $success=false, $return=true));
		
		//@mysql_close($sqlConnect);
		status("DB Modifications done", $success=true, $return=false);

		//$result = copyFilesAndRemoveCloneDir($temp_unzip_dir, dirname(dirname(__FILE__)));
		//if ($result) {
		/** ==============================
		 * MU Updates*/
		status("*********************************** Multi user domain replacement start *************************", $success=true, $return=false);
		$mu_newDomain = parse_url($new_url);
		$mu_oldDomain = parse_url($old_url);
		$mu_newDomainHost = $mu_newDomain['host'];
		$mu_oldDomainHost = $mu_oldDomain['host'];
		$mu_newUrlPath = parse_url($new_url, PHP_URL_PATH);
		$mu_oldUrlPath = parse_url($old_url, PHP_URL_PATH);

		//Force a path for PATH_CURRENT_SITE
		$mu_newUrlPath = (empty($mu_newUrlPath) || ($mu_newUrlPath == '/')) ? '/'  : rtrim($mu_newUrlPath, '/') . '/';
		$mu_oldUrlPath = (empty($mu_oldUrlPath) || ($mu_oldUrlPath == '/')) ? '/'  : rtrim($mu_oldUrlPath, '/') . '/';
		$is_blogs_exits = DB::getField("SHOW TABLES LIKE '" . $table_prefix . "blogs'");
		if (!empty($is_blogs_exits)) {
			$query = "UPDATE " . $table_prefix . "blogs SET domain = '{$mu_newDomainHost}' WHERE domain = '{$mu_oldDomainHost}'";
			DB::doQuery($query);
			$query = "UPDATE " . $table_prefix . "blogs SET path = REPLACE(path, '{$mu_oldUrlPath}', '{$mu_newUrlPath}')";
			DB::doQuery($query);
		}
		status("*********************************** Multi user domain replacement end *************************", $success=true, $return=false);

		status("*********************************** Config file additional constants replace Started *************************", $success=true, $return=false);

		$iwp_config = new IWP_WPConfig($dbModificationArray);
		$iwp_config->updateStandard();
		$iwp_config->updateExtended();
		status("*********************************** Config file additional constants replace ended *************************", $success=true, $return=false);
		status("*********************************** Server config file reset process started*************************", $success=true, $return=false);
		if(!empty($_REQUEST['isStaging']) && !empty($GLOBALS['use_default_htaccess'])){
			status("Staging site on folder protection setup ", $success=true, $return=false);
			replaceDefaultHtaccess($new_url, $temp_unzip_dir);
		}else{
			replace_htaccess($new_url, $temp_unzip_dir, $old_file_path, $old_url);
		}
		/*1.While performing staging to live, if staging site is folder protection, we are not processing the staging htaccess to live well kept old live site htaccess avoid folder protection path conflict in htaccess
		2. while performing staging, if source site (parent site) is folder protection, we are put the default htaccess refer  replaceDefaultHtaccess function
		*/

		if(!empty($_REQUEST['isStaging'])){
			status("********** Setting IWP staging site flag **********", $success=true, $return=false);

			$query = "INSERT INTO `" . $table_prefix . "options` (`option_name`, `option_value`) VALUES( 'iwp_staged_site', 1) ON DUPLICATE KEY UPDATE `option_value` = 1";
			DB::doQuery($query);
		}

		if (!empty($_REQUEST['isStagingToLive'])){
			status("********** Removing setting IWP staging site flag **********", $success=true, $return=false);
			$query = "DELETE FROM `" . $table_prefix . "options` WHERE (`option_name` = 'iwp_staged_site') ";
			DB::doQuery($query);
		}

		status("********** Wordfence configurations **********", $success=true, $return=false);
		resetWordfenceConfig($temp_unzip_dir, $old_file_path);
		status("*********************************** Server config file reset process ended *************************", $success=true, $return=false);
		replaceOldCachePath($temp_unzip_dir, $old_file_path, $old_url, $new_url);
		replaceCacheURLInHtaccess($temp_unzip_dir, $old_file_path);
		deleteCloneDir();
		// if ($result) {
			sendCompleteResponse($newUser, $new_url, $old_user, $table_prefix);
		// }
		//}
}
function iwp_untrailingslashit($string) {
		return rtrim($string, '/\\');
}

function iwp_add_protocal_to_url($url, $protocal, $add_www){
	$trimmed_url = iwp_remove_protocal_from_url($url);
	if($protocal !== '//'){
		$protocal = $protocal . '://';
	}
	return $add_www ? $protocal . 'www.' . $trimmed_url : $protocal . $trimmed_url ;
}
function iwp_remove_protocal_from_url($url){
	$url = preg_replace("(^https?://?www.)", "", $url );
	return preg_replace("(^https?://)", "", $url );
}
function iwp_unset_safe_path($path){
    return str_replace("/", "\\", $path);
}
function iwp_check_and_protocol($url) {
    $url = trim($url);
    if(substr($url, 0, 2) == '//'){
        return 'http:'.$url;
    }
    return (substr($url, 0, 7) == 'http://' || substr($url, 0, 8) == 'https://')
        ? $url
        : 'http://'.$url;
}
function extract_in_multicall($backup_file, $temp_unzip_dir){
	$backup_file_temp = $backup_file;
	foreach($backup_file as $key => $single_backup_file)
	{
		status("Extracting backup file ", $success=true, $return=false);
		status("Extracting backup file key".$key, $success=true, $return=false);
		if ($GLOBALS['is_new_backup'] && ($key != 0) && !strpos($single_backup_file, 'more.zip')) {
			$unzip_dir = $temp_unzip_dir.'/wp-content';
		}else{
			$unzip_dir = $temp_unzip_dir;
		}
		status("Extracting location ".$unzip_dir, $success=true, $return=false);
		
		$result = false;
		if (!$result) {
			initFileSystem(false, $unzip_dir);
			$archive   = new IWPPclZip($single_backup_file);
			$extracted = $archive->extract(IWP_PCLZIP_OPT_PATH, $unzip_dir, IWP_PCLZIP_OPT_TEMP_FILE_THRESHOLD, 1);
			if ($extracted['break']) {
				$extracted['bkfile'] = $backup_file_temp;
				return $extracted;
			}

			if (!$extracted || $archive->error_code) {
				die(status('Error: Failed to extract backup file (' . $archive->error_string . ').'.$GLOBALS['downloadPossibleError'], $success=false, $return=true));
			}
			unset($backup_file_temp[$key]);
			unlink($single_backup_file);
			unset($_REQUEST['params']['responseData']['next_extract_id']);
			unset($_REQUEST['params']['responseData']['v_pos_entry']);
		} else{
			status('Native zip is used to unzip.', $success=true, $return=false);
		}
	}
}

function copyFilesAndRemoveCloneDir($fromFile, $toFile, $skipList = array(), $prevMultiCallResponse = array() ){
	
	if (empty($fromFile)) {
		return false;
	}
	initFileSystem(false, dirname(dirname(__FILE__)));
	$isBreak = check_for_clone_break();
	if ($isBreak) {
		global $response_arr;
		initialize_response_array($response_arr);
		$response_arr['from_dir'] = $fromFile;
		$response_arr['to_dir'] = $toFile;
		$response_arr['is_file_copy'] = true;
		$response_arr['status'] = 'partiallyCompleted';
		$response_arr['break'] = true;
		$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);
		die(status("multicall", $success=true, $return=false, $response_arr));
		return $response_arr;
	}
		$FSCopyResult = array();
		$FSCopyResult = multicallFSCopyDirNew($fromFile, $toFile);
		if($FSCopyResult['break']){
			global $response_arr;
			echo "file copy break";
			$response_arr = array();
			initialize_response_array($response_arr);
			$response_arr['is_file_copy'] = true;
			$response_arr['status'] = 'partiallyCompleted';
			$response_arr['break'] = true;
			$response_arr['from_dir'] = $fromFile;
			$response_arr['to_dir'] = $toFile;
			$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);
			die(status("multicall", $success=true, $return=false, $response_arr));
			return $response_arr;
		}
	
		if($FSCopyResult !== true){
			die(status("Error in file system copy.", $success=false, $return=true));
		}

		deleteCloneDir();
		return true;
		
}

function deleteCloneDir(){
		$site_parent_folder = dirname(__FILE__);
		initFileSystem(false, $site_parent_folder);
		$directFSObj = new filesystemDirect('');
		$delete_result = $directFSObj->delete($site_parent_folder, true);//dirname(__FILE__) => clone_controller folder
		if(!$delete_result){
			$delete_result = $GLOBALS['FileSystemObj']->delete(removeTrailingSlash(APP_FTP_BASE).'/clone_controller', true);//for those files and folders not delete with direct file system
		}
		if(!$delete_result){
			status("Delete through file system Error.", $success=false, $return=false);
		}
		echo "<h1>Clone Completed</h1>";
		$mem_peak = (memory_get_peak_usage(true)/1024/1024);
		status("clone_completed", $success=true, $return=false);//changing success or status will affect result processing in addon controller
		return true;
}

function deleteCloneDirWhileError(){
	$directFSObj = new filesystemDirect('');
	$directFSObj->delete(dirname(__FILE__), true);
	echo "Clone folder deleted during error";
}

function discourageSearchEngine($temp_unzip_dir){
	if (isset($_REQUEST['isStaging'])) {
		$data = "User-agent: *\nDisallow: /\n";
		@file_put_contents($temp_unzip_dir.'/robots.txt', $data);
	}
}

function sendCompleteResponse($newUser, $new_url, $old_user, $db_table_prefix){
	status("clone_completed", $success=true, $return=false);
	if(!empty($GLOBALS['isStagingToLive'])){
		$query =  "SELECT optionValue FROM iwp_clone_stats  WHERE optionName = 'IWP_backup_history'";
		$result = DB::doQuery($query);
	    $_result = new DB::$DBResultClass($result);
		$info = $_result->nextRow($_result);
		$IWP_backup_history = $info['optionValue'];
		if (!empty($IWP_backup_history)) {
			DB::replace($db_table_prefix."options", array('option_name' => 'IWP_backup_history', 'option_value' => $IWP_backup_history));
		}
		status("blog_public option saved as 1 ", $success=true, $return=false);
		DB::replace($db_table_prefix."options", array('option_name' => 'blog_public', 'option_value' => 1));
	}

	$query =  "SELECT optionValue FROM iwp_clone_stats  WHERE optionName = 'html_type'";
	$result = DB::doQuery($query);
	$_result = new DB::$DBResultClass($result);
	$info = $_result->nextRow($_result);
	$html_type = $info['optionValue'];
	if (!empty($html_type)) {
		status("Re Saving html_type ", $success=true, $return=false);
		DB::replace($db_table_prefix."options", array('option_name' => 'html_type', 'option_value' => $html_type));
	}

	if(!empty($_REQUEST['isStaging'])){
		status("blog_public option saved as 0 ", $success=true, $return=false);
		DB::replace($db_table_prefix."options", array('option_name' => 'blog_public', 'option_value' => 0));
	}

	if (!empty($_REQUEST['toIWP'])) {
		$query = "SELECT option_value FROM " . $db_table_prefix . "options WHERE option_name='iwp_client_activate_key'";
			$temp_user_result = DB::doQuery($query) or die(status('Error: user to replace not found - ' . DB::error(), $success=false, $return=true));
			$_result = new DB::$DBResultClass($temp_user_result);
			$row = $_result->nextRow($_result);
			$iwp_client_activation_key = $row['option_value'];
			if(empty($newUser) && empty($old_user)){
				$adminQuery = "SELECT user_id FROM ".$db_table_prefix."usermeta where meta_key = '".$db_table_prefix."capabilities' AND meta_value LIKE '%Administrator%' LIMIT 1";
				$temp_user_result = DB::doQuery($adminQuery);
				$_result = new DB::$DBResultClass($temp_user_result);
				$row = $_result->nextRow($_result);
				$user_id = $row['user_id'];

				$userQuery = "SELECT user_login FROM ".$db_table_prefix."users where ID = '".$user_id."'";
				$temp_user_result = DB::doQuery($userQuery);
				$_result = new DB::$DBResultClass($temp_user_result);
				$row = $_result->nextRow($_result);
				$newUser = $row['user_login'];

				status("Datas", $success=true, $return=false, array('URL' => $new_url, 'userName' => $newUser, 'activationKey' => $iwp_client_activation_key));
			}elseif(!empty($newUser)){
				status("Datas", $success=true, $return=false, array('URL' => $new_url, 'userName' => $newUser, 'activationKey' => $iwp_client_activation_key));
			} else{
				status("Datas", $success=true, $return=false, array('URL' => $new_url, 'userName' => $old_user, 'activationKey' => $iwp_client_activation_key));
			}
		}
}

function initialize_response_array(&$response_arr){
	$response_arr['db_table_prefix'] = $GLOBALS['db_table_prefix'];
	$response_arr['temp_unzip_dir'] = $_REQUEST['temp_unzip_dir'];
	$response_arr['temp_pclzip'] = $_REQUEST['temp_pclzip'];
	$response_arr['bkfile'] = $_REQUEST['bkfile'];
	$response_arr['extractParentHID'] = $_REQUEST['extractParentHID'];
	$response_arr['isDownloadMultiCall'] = false;
	$response_arr['is_file_append'] = false;
	$response_arr['DBDetails']['DB_HOST'] = DB_HOST;
	$response_arr['DBDetails']['DB_NAME'] = DB_NAME;
	$response_arr['DBDetails']['DB_USER'] = DB_USER;
	$response_arr['DBDetails']['DB_PASSWORD'] = DB_PASSWORD;
	$response_arr['DBDetails']['prefix'] = $GLOBALS['db_table_prefix'];
	$response_arr['dbModification'] = false;
	$response_arr['URLParseData'] = $GLOBALS['URLParseData'];
	$response_arr['wp_content_url'] = $GLOBALS['wp_content_url'];
	$response_arr['is_new_backup'] = $GLOBALS['is_new_backup'];
	$response_arr['isStagingToLive'] = $GLOBALS['isStagingToLive'];
	$response_arr['isExistingSite'] = $GLOBALS['isExistingSite'];
	$response_arr['dbBkFile'] = $GLOBALS['dbBkFile'];
	$response_arr['backup_meta_files'] = $GLOBALS['backup_meta_files'];
	$response_arr['WPVersionName'] = $GLOBALS['WPVersionName'];
	$response_arr['oldURLReplacement'] = false;
	$response_arr['next_extract_id'] = 0;
	$response_arr['file_iterator'] = false;
	$response_arr['isStaging'] = $_REQUEST['isStaging'];
	$response_arr['oneShotdownlaod'] = $_REQUEST['oneShotdownlaod'];
	$response_arr['status'] = 'completed';
	$response_arr['break'] = false;
	$response_arr['isLiteSpeedHtaccess'] = $GLOBALS['isLiteSpeedHtaccess'];
	$response_arr['use_default_htaccess'] = $GLOBALS['use_default_htaccess'];
	$response_arr['actionID'] = $GLOBALS['actionID'];
}

function get_files_array_from_iwp_part($backup_file, $manual = ''){
	$backup_files_array = array();
	if(!is_array(($backup_file)) && strpos($backup_file, '_iwp_part') !== false)
	{
		$orgName = substr($backup_file, 0, strpos($backup_file, '_iwp_part_'));
		if (!empty($manual)) {
			$orgName = $orgName;
		}
		$totalParts = substr($backup_file, strpos($backup_file, '_iwp_part_')+10);
		$totalParts = substr($totalParts, 0, strlen($totalParts)-4);
		for($i=0; $i<=$totalParts; $i++)
		{
			iwp_mmb_auto_print('get_files_array_from_iwp_part');
			if($i == 0)
			{
				$backup_files_array[] = $orgName.'.zip';
			} else {
				$backup_files_array[] = $orgName.'_iwp_part_'.$i.'.zip';
			}
		}
		return $backup_files_array;
	} else {
		if (!empty($manual)) {
			$backup_file = $backup_file;
		}
		$backup_files_array[] = $backup_file;
		return $backup_file;
	}
}

function appendSplitFiles($fileToAppend){
	 // function to join the split files during multicall backup
	
	if (!is_array($fileToAppend)) {
		$directory_tree = get_all_files_from_dir($fileToAppend);
		$isBreak = check_for_clone_break();
		if ($isBreak) {
			global $response_arr;
			$response_arr = array();
			initialize_response_array($response_arr);
			$response_arr['is_file_append'] = true;
			$response_arr['status'] = 'partiallyCompleted';
			$response_arr['break'] = true;
			$response_arr['kuppu'] = true;
			$response_arr['is_extract_over'] = true;
			$response_arr['appendFileLists'] = $directory_tree;
			$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);
			die(status("multicall", $success=true, $return=false, $response_arr));
			return $response_arr;
		}
	} else{
		$directory_tree = $fileToAppend;
	}
	usort($directory_tree, "sortString");
	$joinedFilesArray = array();
	$orgHashValues = array();
	$hashValue = '';
		
	foreach($directory_tree as $k => $v)
	{
		$contents = '';
			$orgFileCount = 0;
			$count = 0;
		/* $subject = $v;
		$pattern = '/iwp_part/i';
		preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE);
		print_r($matches); */
		$backup_folder_pos = strpos($v, 'infinitewp/backups/');
		// While copying the Staging site to live the live site backups list were not cleared now
		// Avoid merging multipart file to single zip file after perform staging to live - live site backups
		$pos = strpos($v, 'iwp_part');
		if($pos !== false && $backup_folder_pos === false)
		{
			$count ++;
			$currentFile = explode(".",$v);
				$currentFileSize = count($currentFile);
			 foreach($currentFile as $key => $val)
				{
					iwp_mmb_auto_print('appendSplitFiles');
					if(($key == ($currentFileSize-2))||($currentFileSize == 1))
					{
						$insPos = strpos($val, '_iwp_part');
						$rest = substr_replace($val, '', $insPos);
						$currentFile[$key] = $rest;
						
						$insPos2 = strpos($rest, '_iwp_hash');
						if($insPos2 != false)
						{
							$hashValue = substr($rest, -32);
							$rest = substr_replace($rest, '', $insPos2);
							$currentFile[$key] = $rest;
						}
					}
				}
				$orgFileCount++;	
			$orgFileName = implode(".", $currentFile);
			$handle = fopen($v,"r");
			$size = filesize($v);
			if ($size <= 0) {
				continue;
			}
			$contents = fread($handle, $size);
			fclose($handle);
				if($orgFileCount == 1)
				{
					//clearing contents of file intially to prevent appending to already existing file
				}
			if ($GLOBALS['needFileSystem']) {
			   $p_entry_file = $GLOBALS['FileSystemObj']->findFolder($orgFileName);
			   $GLOBALS['FileSystemObj']->touch($p_entry_file);
			   $GLOBALS['FileSystemObj']->chmod($p_entry_file, 0777);
			 }
			file_put_contents($orgFileName,$contents,FILE_APPEND);
			$joinedFilesArray[$orgFileName] = 'hash';
			$orgHashValues[$orgFileName] = $hashValue;
			echo " orgFileName - ".$orgFileName;
			$file_to_ulink = realpath($v);
			if ($GLOBALS['needFileSystem']) {
				$file_to_ulink_temp = $GLOBALS['FileSystemObj']->findFolder($file_to_ulink);
				$resultUnlink = $GLOBALS['FileSystemObj']->delete($file_to_ulink_temp);
			}else{
				$resultUnlink = unlink($file_to_ulink);
			}
			$resultUnlink = error_get_last();
			if(!$resultUnlink)
			{
				if(is_file($v))
				{	
					if ($GLOBALS['needFileSystem']) {
						$file_to_ulink_temp = $GLOBALS['FileSystemObj']->findFolder($file_to_ulink);
						$resultUnlink = $GLOBALS['FileSystemObj']->delete($file_to_ulink_temp);
					}else{
						unlink($file_to_ulink);
					}
				}
			}
			if (!is_file($v)) {
				unset($directory_tree[$k]);
			}
		}

		$isBreak = check_for_clone_break();
		if ($isBreak) {
			global $response_arr;
			$response_arr = array();
			initialize_response_array($response_arr);
			$response_arr['is_file_append'] = true;
			$response_arr['status'] = 'partiallyCompleted';
			$response_arr['break'] = true;
			$response_arr['kuppu'] = true;
			$response_arr['is_extract_over'] = true;
			$response_arr['appendFileLists'] = $directory_tree;
			$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);
			die(status("multicall", $success=true, $return=false, $response_arr));
			return $response_arr;
		}
	}
	// md5 hash check currently not in use 
	// $hashValues = array();
	// foreach($joinedFilesArray as $key => $value)
	// {
	// 	$hashValues[$key] = md5_file($key);
	// }
	// 	$totalHashValues = array();
	// 	$totalHashValues['orgHash'] = $orgHashValues;
	// 	$totalHashValues['afterSplitHash'] = $hashValues;
	// 	return $totalHashValues;
}

function sortString($a, $b){
	// the uSort CallBack Function used in the appendSplitFiles function
	$stringArr = array();
	$stringArr[0] = $a;
	$stringArr[1] = $b;
	$strA = '';
	$strB = '';
	foreach($stringArr as $strKey => $strVal)
	{
		$mystring = $strVal;
		$findme = '_iwp_part';																		//fileNameSplit logic
		$pos = strpos($mystring, $findme);
		$rest = substr($mystring, $pos);
		$pos2 = strrpos($rest, $findme);
		$len = strlen($rest);
		$actLen = $pos2+strlen($findme);
		$actPos = $len - $actLen -1;
		$actPartNum = substr($rest, -($actPos));
			$actPartNumArray = explode(".",$actPartNum);
			foreach($actPartNumArray as $key => $val)
			{
				if($key == 0)
				$actPartNum = $val;
			}
		if($strKey == 0){
			$strA = intval($actPartNum);
		}
		else{
			$strB = intval($actPartNum);
		}
	}
	if ($strA == $strB){return 0;}
	return ($strA < $strB) ? -1 : 1;	
}

function get_all_files_from_dir($path, $exclude = array()){
	if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
	global $directory_tree, $ignore_array;
	$directory_tree = array();
	foreach ($exclude as $file) {
		if (!in_array($file, array('.', '..'))) {
			if ($file[0] === "/") $path = substr($file, 1);
			$ignore_array[] = "$path/$file";
		}
	}
	get_all_files_from_dir_recursive($path);
	return $directory_tree;
}

function get_all_files_from_dir_recursive($path, $ignore_array=array()){
	if ($path[strlen($path) - 1] === "/") $path = substr($path, 0, -1);
	global $directory_tree, $ignore_array;
	$directory_tree_temp = array();
	$dh = @opendir($path);
	if(empty($ignore_array))
	{
		$ignore_array = array();
	}
	while (false !== ($file = @readdir($dh))) {
		if (!in_array($file, array('.', '..'))) {
			if (!in_array("$path/$file", $ignore_array)) {
				if (!is_dir("$path/$file")) {
						$pos = strpos("$path/$file", 'iwp_part');
						if($pos !== false) {
							$directory_tree[] = "$path/$file";
						}
				} else {
					iwp_mmb_auto_print('appendSplitFiles');
					get_all_files_from_dir_recursive("$path/$file");
				}
			}
		}
	}
	@closedir($dh);
}

function change_table_prefix_config_file($file_path, $db_table_prefix){
	//select wp-config-sample.php
	$wp_config_file = glob($file_path . '/wp-config.php');
	if ($GLOBALS['needFileSystem']) {
	  $temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($file_path);
	  $result = $GLOBALS['FileSystemObj']->move($temp_unzip_dir_file.'wp-config.php', $temp_unzip_dir_file.'wp-config-temp.php');
	  $GLOBALS['FileSystemObj']->chmod($temp_unzip_dir_file.'/wp-config.php', 0777);

	}else{
		$result = @rename($wp_config_file[0], $file_path.'/wp-config-temp.php');
	}
	if ($result) {
		$lines = file($file_path.'/wp-config-temp.php');
		@unlink($file_path.'/wp-config-temp.php');
	} else {
		$lines = @file($file_path.'/wp-config-sample.php');
	}
	if ($GLOBALS['needFileSystem']) {
		$GLOBALS['FileSystemObj']->delete($temp_unzip_dir_file.'/wp-config.php');
		$GLOBALS['FileSystemObj']->touch($temp_unzip_dir_file.'/wp-config.php');
		$GLOBALS['FileSystemObj']->chmod($temp_unzip_dir_file.'/wp-config.php', 0777);
	}else{
		@unlink($file_path.'/wp-config.php');
	}

	if (empty($lines))
		die(status('Error: Cannot recreate wp-config.php file.', $success=false, $return=true));

	$file_success = false;

	foreach ($lines as $line) {
		if ($db_table_prefix && strstr($line, '$table_prefix')) {
			$line         = "\$table_prefix = '$db_table_prefix';\n";
			$file_success = true;
		}
	
		$result = file_put_contents($file_path.'/wp-config.php', $line, FILE_APPEND);

		if ($result === true)
			die(status('Error: Cannot write wp-config.php file.', $success=false, $return=true));
	}
	return $file_success;
}

function cmdExec(){
	if ($command == ''){
		return false;
	}
    if (checkFunctionExists('exec')) {
        $log = @exec($command, $output, $return);
        if ($string)
            return $log;
        return $return ? false : true;
    } else if (checkFunctionExists('system')) {
        $log = @system($command, $return);
        if ($string){
			return $log;
        }
        return $return ? false : true;
    } else if (checkFunctionExists('passthru') && !$string) {
        $log = passthru($command, $return);
        return $return ? false : true;
    } else {
        return false;
    }
}

function checkFunctionExists($function_callback){
	
	if(!function_exists($function_callback)){
		return false;
	}
		
	$disabled = explode(', ', @ini_get('disable_functions'));
	if (in_array($function_callback, $disabled)){
		return false;
	}
		
	if (extension_loaded('suhosin')) {
		$suhosin = @ini_get("suhosin.executor.func.blacklist");
		if (empty($suhosin) == false) {
			$suhosin = explode(',', $suhosin);
			$blacklist = array_map('trim', $suhosin);
			$blacklist = array_map('strtolower', $blacklist);
			if(in_array($function_callback, $blacklist)){
				return false;
			}
		}
	}
	return true;
}

function get_table_prefix($temp_unzip_dir){
	$lines = file($temp_unzip_dir.'/wp-config.php');
	foreach ($lines as $line) {
		if (strstr($line, '$table_prefix')) {
			$pattern = "/(\'|\")[^(\'|\")]*/";
			preg_match($pattern, $line, $matches);
			$prefix = substr($matches[0], 1);
			return $prefix;
			break;
		}
	}
	return 'wp_'; //default
}

if (!function_exists('file_put_contents')){
	function file_put_contents($filename, $data){
		$f = @fopen($filename, 'w');
		if (!$f) {
		  die(status("Error - Fopen needs to be enabled in your server", $success=false, $return=true));
		} else {
			$bytes = fwrite($f, $data);
			fclose($f);
			return $bytes;
		}
	}
}

function check_mysql_paths(){
	 $paths = array(
		'mysql' => '',
		'mysqldump' => ''
	);
	if (substr(PHP_OS, 0, 3) == 'WIN') {
		$mysql_install = DB::doQuery("SHOW VARIABLES LIKE 'basedir'");
		$_result = new DB::$DBResultClass($mysql_install);
		$mysql_install = $_result->nextRow($_result);
		appUpdateMsg("inside-check-mysql-path : ".$mysql_install->Value);
		if ($mysql_install) {
			$install_path       = str_replace('\\', '/', $mysql_install->Value);
			$paths['mysql']     = $install_path . 'bin/mysql.exe';
			$paths['mysqldump'] = $install_path . 'bin/mysqldump.exe';
		} else {
			$paths['mysql']     = 'mysql.exe';
			$paths['mysqldump'] = 'mysqldump.exe';
		}
	} else {
		$paths['mysql'] = cmdExec('which mysql', true);
		if (empty($paths['mysql']))
			$paths['mysql'] = 'mysql'; // try anyway
		
		$paths['mysqldump'] = cmdExec('which mysqldump', true);
		if (empty($paths['mysqldump']))
			$paths['mysqldump'] = 'mysqldump'; // try anyway         
		
	}
	
	return $paths;
}


function replace_htaccess($url, $temp_unzip_dir, $old_file_path, $old_url){
    $defaultHtaccess = ".htaccess";
	if(IWP_FolderProtection::$isStagingToLive && IWP_FolderProtection::commonFileExist($temp_unzip_dir)){
		$file = @file_get_contents($temp_unzip_dir.'/'.IWP_FolderProtection::$htaccessFileName);
		$defaultHtaccess = IWP_FolderProtection::$htaccessFileName;
		status("Staging to live (Staging site enabled folder protection. replace_htaccess by  .htaccess.folderprotection file not .htaccess file. will keep the old .htaccess on live site)", $success=true, $return=false);
	}else{
		if(IWP_LiteSpeed::commonFileExist($temp_unzip_dir)){
			$file = @file_get_contents($temp_unzip_dir.'/'.IWP_LiteSpeed::$htaccessFileName);
		}else{
			$file = @file_get_contents($temp_unzip_dir.'/.htaccess.orgi');
		}
	}
    if ($file && strlen($file)) {
        $args    = parse_url($url);        
        $string  = rtrim($args['path'], "/");
        $regex   = "/BEGIN WordPress(.*?)RewriteBase(.*?)\n(.*?)RewriteRule \.(.*?)index\.php(.*?)END WordPress/sm";
        $replace = "BEGIN WordPress$1RewriteBase " . $string . "/ \n$3RewriteRule . " . $string . "/index.php$5END WordPress";
        $file    = preg_replace($regex, $replace, $file);
        $regex   = "/RewriteBase(.*?)\n(.*?)/sm";
        $replace = "RewriteBase " . $string . "/\n";
        $file    = preg_replace($regex, $replace, $file);
        status(".htaccess content modified", $success=true, $return=false);
        status($old_file_path, $success=true, $return=false);
        status($GLOBALS['new_file_path'], $success=true, $return=false);
        if (!empty($old_file_path)) {
        	$old_file_path = removeTrailingSlash($old_file_path).'/';
	        $file    = str_replace($old_file_path.'/', $GLOBALS['new_file_path'], $file);
        }
        // $args    = parse_url($old_url);        
        // $old_string  = rtrim($args['path'], "/");
        // $file    = str_replace($old_string, $string, $file);

        status(".htaccess content modified", $success=true, $return=false);
        
        if ($GLOBALS['needFileSystem']) {
        	$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($temp_unzip_dir);
        	$GLOBALS['FileSystemObj']->putContents($temp_unzip_dir_file.'/'.$defaultHtaccess, $file);
        }else{
        	@file_put_contents($temp_unzip_dir.'/'.$defaultHtaccess, $file);
        }
    }
	// if (isset($_REQUEST['isStaging'])) {
	// 	replaceDefaultHtaccess($url, $temp_unzip_dir);
	// }
	status(".htaccess file changed", $success=true, $return=false);

}

function renameServerConfig($temp_unzip_dir){
	$file = @file_get_contents($temp_unzip_dir.'/.htaccess');
	if(IWP_FolderProtection::$isStagingToLive && IWP_FolderProtection::commonFileExist($temp_unzip_dir)){
		$file = @file_get_contents($temp_unzip_dir.'/'.IWP_FolderProtection::$htaccessFileName);
		// if staging site is folder protected .htaccess name changed  to IWP_FolderProtection::$htaccessFileName on pclzip.class so .htaccess not exisit
	}

	if ($GLOBALS['needFileSystem']) {
		$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($temp_unzip_dir);
	}

    if ($file && strlen($file) && !IWP_LiteSpeed::commonFileExist($temp_unzip_dir)) {
    	if ($GLOBALS['needFileSystem']) {
    	    $GLOBALS['FileSystemObj']->putContents($temp_unzip_dir_file.'/.htaccess.orgi', $file);
    	    if(!IWP_FolderProtection::$isStagingToLive){
	    	    $GLOBALS['FileSystemObj']->delete($temp_file);
    	    }
    	}else{
			@file_put_contents($temp_unzip_dir.'/.htaccess.orgi', $file);
    	    if(!IWP_FolderProtection::$isStagingToLive){
				@unlink($temp_unzip_dir.'/.htaccess');
    	    }
    	}
		status(".htaccess rename", $success=true, $return=false);
	}
	if ($GLOBALS['needFileSystem']) {
		$isUseriniCopied = $GLOBALS['FileSystemObj']->copy( $temp_unzip_dir_file.'/.user.ini',  $temp_unzip_dir_file.'/.user.ini.orgi');
		$isWebConfigCopied = $GLOBALS['FileSystemObj']->copy( $temp_unzip_dir_file.'/web.config',  $temp_unzip_dir_file.'/web.config.orgi');
		if ($isUseriniCopied) {
			$GLOBALS['FileSystemObj']->delete($temp_unzip_dir_file.'/.user.ini');
			status(".user.ini renamed for wordfence", $success=true, $return=false);
		}
		if ($isWebConfigCopied) {
			$GLOBALS['FileSystemObj']->delete($temp_unzip_dir_file.'/web.config');
			status(".user.ini renamed for wordfence", $success=true, $return=false);
		}
	}else{
		$isUseriniCopied = @copy($temp_unzip_dir.'/.user.ini', $temp_unzip_dir.'/.user.ini.orgi');
		if ($isUseriniCopied) {
			@unlink($temp_unzip_dir.'/.user.ini');
			status(".user.ini renamed for wordfence", $success=true, $return=false);
		}
		$isWebConfigCopied = @copy($temp_unzip_dir.'/web.config', $temp_unzip_dir.'/web.config.orgi');
		if ($isWebConfigCopied) {
			@unlink($temp_unzip_dir.'/web.config');
			status("web.config file renamed", $success=true, $return=false);
		}
	}
	

}

function replaceDefaultHtaccess($url,$temp_unzip_dir){
	$args    = parse_url($url);        
	$string  = rtrim($args['path'], "/");
	$data = "# BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /".$string."/\nRewriteRule ^index\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /".$string."/index.php [L]\n</IfModule>\n# END WordPress";
	if ($GLOBALS['needFileSystem']) {
		$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($temp_unzip_dir);
		$GLOBALS['FileSystemObj']->putContents($temp_unzip_dir_file.'/.htaccess', $data);
	}else{
		@file_put_contents($temp_unzip_dir.'/.htaccess', $data);
	}
    status("Default .htaccess replaced", $success=true, $return=false);

}
function resetWordfenceConfig($temp_unzip_dir, $old_file_path){
	$file = @file_get_contents($temp_unzip_dir.'/.user.ini.orgi');
	if ($file && strlen($file)) {
		$file    = str_replace($old_file_path, $GLOBALS['new_file_path'], $file);
		if ($GLOBALS['needFileSystem']) {
			$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($temp_unzip_dir);
			$GLOBALS['FileSystemObj']->putContents($temp_unzip_dir_file.'/.user.ini', $file);
		}else{
			@file_put_contents($temp_unzip_dir.'/.user.ini', $file);
		}
		status(".user.ini old path replaced", $success=true, $return=false);
	}
	$file = @file_get_contents($temp_unzip_dir.'/wordfence-waf.php');
	if ($file && strlen($file)) {
		$file    = str_replace($old_file_path, $GLOBALS['new_file_path'], $file);
		if ($GLOBALS['needFileSystem']) {
			$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($temp_unzip_dir);
			$GLOBALS['FileSystemObj']->putContents($temp_unzip_dir_file.'/wordfence-waf.php', $file);
		}else{
			@file_put_contents($temp_unzip_dir.'/wordfence-waf.php', $file);
		}
		status("wordfence-waf.php old path replaced", $success=true, $return=false);
	}
}

function replaceOldCachePath($temp_unzip_dir, $old_file_path, $old_url, $new_url){
	$defaultHtaccess = ".htaccess";
	$file = @file_get_contents($temp_unzip_dir.'/.htaccess');
	if(IWP_FolderProtection::$isStagingToLive && IWP_FolderProtection::commonFileExist($temp_unzip_dir)){
		$file = @file_get_contents($temp_unzip_dir.'/'.IWP_FolderProtection::$htaccessFileName);
		$defaultHtaccess = IWP_FolderProtection::$htaccessFileName;
	}
	if ($file && strlen($file)) {
		$file    = str_replace($old_file_path, $GLOBALS['new_file_path'], $file);

		$p_quote_old_url = preg_quote($old_url, '/');
		$p_quote_new_url = preg_quote($new_url, '/');

		$file    = str_replace($p_quote_old_url, $p_quote_new_url, $file);

		$mu_oldUrlPath = parse_url($old_url, PHP_URL_PATH);
		$mu_oldUrlPath = ltrim($mu_oldUrlPath, '/');
		$mu_newUrlPath = parse_url($new_url, PHP_URL_PATH);
		$mu_newUrlPath = ltrim($mu_newUrlPath, '/');

		if(!empty($mu_newUrlPath) && $mu_newUrlPath != '/'){
			$file    = str_replace('/' . $mu_oldUrlPath . '/wp-content', '/' .$mu_newUrlPath . '/wp-content', $file);
			$file    = str_replace('/' . $mu_oldUrlPath . '/$1', '/' .$mu_newUrlPath . '/$1', $file);
		}

		if ($GLOBALS['needFileSystem']) {
			$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($temp_unzip_dir);
        	$GLOBALS['FileSystemObj']->putContents($temp_unzip_dir_file.'/'.$defaultHtaccess, $file);
		}else{
        	@file_put_contents($temp_unzip_dir.'/'.$defaultHtaccess, $file);
		}
		status("old cache path replaced in $defaultHtaccess", $success=true, $return=false);
	}
}

function replaceCacheURLInHtaccess($temp_unzip_dir, $old_file_path){
	$file = @file_get_contents($temp_unzip_dir.'/wp-config.php');
	if ($file && strlen($file)) {
		$file    = str_replace($old_file_path, $GLOBALS['new_file_path'], $file);
		if ($GLOBALS['needFileSystem']) {
			$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($temp_unzip_dir);
			$GLOBALS['FileSystemObj']->putContents($temp_unzip_dir_file.'/wp-config.php', $file);
		}else{
			@file_put_contents($temp_unzip_dir.'/wp-config.php', $file);
		}
		status("old cache path replaced in wp-config.php", $success=true, $return=false);
	}
}

function modify_db_dump($db_file, $has_new_prefix){
	copy($db_file,$db_file.'tmp');
	$handle = fopen($db_file.'tmp', "r");
	@unlink($db_file);
	// Loop through each line
	
	if ($handle) {
		while (($line = fgets($handle)) !== false) {
                        iwp_mmb_auto_print('modify_db_dump');
			// Skip it if it's a comment
                        if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 3) == '/*!')
				continue;
			
			
			
			//$line = preg_replace_callback('/\\\'(.*?[^\\\\])\\\'[\\,\\)]/', 'search_and_replace_url', $line);//old - /\'([^\']+)\'[\,\)]/ new - /\'(.*?[^\\])\'[\,\)]/
			if ($has_new_prefix) {
				$line = preg_replace_callback("/(TABLE[S]?|INSERT\ INTO|DROP\ TABLE\ IF\ EXISTS) [`]?([^`\;\ ]+)[`]?/", 'search_and_replace_prefix', $line);				
			}
			// Add this line to the current segment
			if (file_put_contents($db_file, $line, FILE_APPEND) === FALSE)
            	die(status('Error: Cannot write wp-config.php file.', $success=false, $return=true));
		}
		fclose($handle);
		@unlink($db_file.'tmp');
		return true;
	} else {
		fclose($handle);
		@unlink($db_file.'tmp');
		return false;
	}
}

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':
			case 'E':
				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;
	}
}
function apply_replaces($subject, $is_serialized = false){
	global $old_url, $new_url, $old_file_path;
	
	$search = array();
	$replace = array();
	
	//all these values with untrailed slashes will be good
	
	$search[0] = $old_url;
	$replace[0] = $new_url;
	
	if(!empty($old_file_path)){
		$search[1] = $old_file_path;
		$replace[1] = $GLOBALS['new_file_path'];
	}

	return str_replace($search, $replace, $subject);
}

function replace_array_values(&$value, $key){
	if (!is_string($value)) return;
	$value = apply_replaces($value, true);
}

function search_and_replace_url($matches){

	global $old_url, $old_file_path;
	$replace = $search = $matches[1];
	$subject = $matches[0];
	
	if (($old_url && strpos($replace, $old_url) !== false) || ($old_file_path && strpos($replace, $old_file_path) !== false)) {//URL and file path IWP improvement
		if (is_serialized(stripcslashes($replace)) && false !== ($data = @unserialize(stripcslashes($replace)))) {
			if ( is_array( $data ) ) {
				array_walk_recursive($data, 'replace_array_values');
			} else if (is_string($data)) {
				$data = apply_replaces($data, true);
			}
			$replace = addslashes(serialize($data));
			$replace = str_replace("\r", '\r', $replace);
			$replace = str_replace("\n", '\n', $replace);
		} else {
			$replace = apply_replaces($replace);
		}
	}
	return str_replace($search, $replace, $subject);
}

function search_and_replace_prefix($matches){
	global $old_table_prefix, $table_prefix;
	$subject = $matches[0];
	$old_table_name = $matches[2];

	//$new_table_name = str_replace($old_table_prefix, $table_prefix, $old_table_name);
	
	$new_table_name = preg_replace("/$old_table_prefix/", $table_prefix, $old_table_name, 1);
	
	return str_replace($old_table_name, $new_table_name, $subject);
}

function status($status, $success=true, $return=true, $options='', $multicall=false){
	
	if($success && !empty($options)){  
		echo '#Status('.base64_encode(serialize(array('success' => $status, 'options' => $options))).')#'; echo "\n".serialize(array('success' => $status, 'options' => $options));
		if ($GLOBALS["LOG_FILE_HANDLE"]) {
			@fwrite($GLOBALS["LOG_FILE_HANDLE"], 'success : '.$status."\n");
		} 
	} else if($success){ 
		echo '#Status('.base64_encode(serialize(array('success' => $status))).')#';  echo "\n".serialize(array('success' => $status)); 
		if ($GLOBALS["LOG_FILE_HANDLE"])
		@fwrite($GLOBALS["LOG_FILE_HANDLE"], 'success : '.$status."\n");
	} else if(!$success && $return){  
		echo '#Status('.base64_encode(serialize(array('error' => $status))).')#';  echo "\n".serialize(array('error' => $status));
		if ($GLOBALS["LOG_FILE_HANDLE"]) 
		@fwrite($GLOBALS["LOG_FILE_HANDLE"], 'error : '.$status."\n"); 
		// deleteCloneDirWhileError(); //write now it is no need because we cant get log
	} else if($return){ 
		echo '#Status('.base64_encode(serialize(array('error' => $status))).')#';  echo "\n".serialize(array('error' => $status)); 
		if ($GLOBALS["LOG_FILE_HANDLE"])
		@fwrite($GLOBALS["LOG_FILE_HANDLE"], 'error : '.$status."\n"); 
	}

	//if($multicall)){  echo '#Status('.base64_encode(serialize(array('success' => $status, 'options' => $options))).')#'; echo "\n".serialize(array('success' => $status, 'options' => $options)); }
	
	ob_flush(); flush();
	
		global $current_time;
        $GLOBALS['IWP_MMB_PROFILING']['LAST_PRINT'] = $current_time;
}

function bridge_shutdown(){
	$isError = false;
	$isWarning = false;

	if ($error = error_get_last()){
		switch($error['type']){
			/*case E_PARSE:*/
			case E_ERROR:
			case E_CORE_ERROR:
			case E_COMPILE_ERROR:
			case E_PARSE:
			case E_USER_ERROR:
			case E_RECOVERABLE_ERROR:
				$isError = true;
				break;
			case E_WARNING:
			case E_CORE_WARNING:
			case E_USER_WARNING:
			case E_NOTICE:
			case E_USER_NOTICE:
			case E_STRICT:
				$isWarning = true;
			}
	}

	if ($isError){
		$status = 'PHP Fatal error occured: '.$error['message'].' in '.$error['file'].' on line '.$error['line'].'.';
		status($status, $success=false, $return=true);
	}elseif($isWarning){
		$status = 'PHP Fatal error occured: '.$error['message'].' in '.$error['file'].' on line '.$error['line'].'.';
		status($status, $success=false, $return=false);
	}
	if ($GLOBALS['connectionFlag']) {
		storeCloningResponse();
	}
}

function storeCloningResponse(){
	global $response_arr, $download_result;
	if (!empty($response_arr)) {
		DB::doQuery("UNLOCK TABLES");
		$exit = DB::getExists("iwp_clone_stats", "optionValue", "optionName = 'cloneStatus'");
		if ($exit) {
			!DB::update("iwp_clone_stats", array('optionName' => 'cloneStatus', 'optionValue' => serialize($response_arr)), "optionName = 'cloneStatus'");
		}else{
			DB::insert("iwp_clone_stats", array('optionName' => 'cloneStatus', 'optionValue' => serialize($response_arr))) or die(status('Error storing clone status' . DB::error(), $success=false, $return=false));
		}
	}else{
		$exit = DB::getExists("iwp_clone_stats", "optionValue", "optionName = 'cloneStatus'");
		if ($exit) {
			!DB::update("iwp_clone_stats", array('optionName' => 'cloneStatus', 'optionValue' => serialize($download_result)), "optionName = 'cloneStatus'");
		}else{
			DB::insert("iwp_clone_stats", array('optionName' => 'cloneStatus', 'optionValue' => serialize($download_result))) or die(status('Error storing clone status' . DB::error(), $success=false, $return=false));
		}
	} 
}

function appUpdateMsg($msg, $isError=0){
	if($isError){
		die(status($msg, $success=false, $return=true, $options=''));
	}
	else{
		status($msg, $success=true, $return=false, $options='');
	}
}

function iwp_mmb_auto_print($unique_task, $task_desc=''){// this will help responding web server, will keep alive the script execution
    $print_every_x_secs = 5;
    global $current_time;
    $current_time = microtime(1);
    if(!$GLOBALS['IWP_MMB_PROFILING']['TASKS'][$unique_task]['START']){
            $GLOBALS['IWP_MMB_PROFILING']['TASKS'][$unique_task]['START'] = $current_time;	
    }

    if(!$GLOBALS['IWP_MMB_PROFILING']['LAST_PRINT'] || ($current_time - $GLOBALS['IWP_MMB_PROFILING']['LAST_PRINT']) > $print_every_x_secs){

            //$print_string = "TT:".($current_time - $GLOBALS['IWP_MMB_PROFILING']['ACTION_START'])."\n";
            if(!empty($task_desc)){
                $print_string = $unique_task."  Task Desc :".$task_desc." TT:".($current_time - $GLOBALS['IWP_MMB_PROFILING']['TASKS'][$unique_task]['START']);
            }else {
                $print_string = $unique_task." TT:".($current_time - $GLOBALS['IWP_MMB_PROFILING']['TASKS'][$unique_task]['START']);
            }
            iwp_mmb_print_flush($print_string);            		
            $GLOBALS['IWP_MMB_PROFILING']['LAST_PRINT'] = $current_time;
    }
}

function iwp_mmb_print_flush($print_string){// this will help responding web server, will keep alive the script execution
    echo $print_string." ||| ";
    echo "TT:".(microtime(1) - $GLOBALS['IWP_MMB_PROFILING']['ACTION_START'])."\n";
    ob_flush();
    flush();
}

function logExtractResponse($historyID = '', $statusArray = array(), $params=array()){
	return true;
	$insertID = '';
	if(empty($historyID))
	{
		$insert  = DB::insert($_REQUEST['db_table_prefix'].'iwp_extract_status', array( 'stage' => 'installClone', 'status' => $statusArray['status'],  'action' => 'installClone', 'type' => 'bridge','category' => 'installClone','historyID' => $statusArray['extractParentHID'],'finalStatus' => 'pending','startTime' => microtime(true),'endTime' => '','statusMsg' => 'blah','requestParams' => serialize($params),'taskName' => 'installCloneBridge'));
		if($insert)
		{
			$insertID = $insert; 
		}
	} else if((isset($statusArray['responseParams']))||(isset($statusArray['task_result']))) {
		$update = DB::update($_REQUEST['db_table_prefix'].'iwp_extract_status', array( 'responseParams' => serialize($statusArray['responseParams']),'stage' => 'installClone', 'status' => $statusArray['status'],'statusMsg' => 'blah','taskResults' =>  isset($statusArray['task_result']) ? serialize($statusArray['task_result']) : serialize(array())), "historyID=".$historyID);
	} else {
		//$responseParams = $this -> getRequiredData($historyID,"responseParams");
		$update = DB::update($_REQUEST['db_table_prefix'].'iwp_extract_status', array('stage' => 'installClone', 'status' => $statusArray['status'],'statusMsg' => 'blah' ),"historyID=". $historyID);
	}
	if( (isset($update)&&($update === false)) || (isset($insert)&&($insert === false)) )
	{
		 die(status("Error: Insert or Update", $success=false, $return=true));
	}
	if((isset($statusArray['sendResponse']) && $statusArray['sendResponse'] == true) || $statusArray['status'] == 'completed')
	{
		$returnParams = array();
		$returnParams['parentHID'] = $historyID;
		$returnParams['backupRowID'] = $insertID;
		$returnParams['stage'] = $statusArray['stage'] ;
		$returnParams['status'] = $statusArray['status'];
		$returnParams['nextFunc'] = isset($statusArray['nextFunc']) ? $statusArray['nextFunc'] : '';
		return array('success' => $returnParams);
	} else {
		if($statusArray['status'] == 'error') {
			$returnParams = array();
			$returnParams['parentHID'] = $historyID;
			$returnParams['backupRowID'] = $insertID;
			$returnParams['stage'] = $statusArray['stage'] ;
			$returnParams['status'] = $statusArray['status'];
			$returnParams['statusMsg'] = $statusArray['statusMsg'];
			
			die(status("Error: Insert or Update status", $success=false, $return=true));
		}
	}
}

function send_multicall_response($multicall_response){
	die(status("multicall", $success=true, $return=false, $multicall_response));
}

function check_for_clone_break(){
	global $extract_start_time;
	$extract_time_taken = microtime(1) - $extract_start_time;
	
	if($extract_time_taken >= 22){
		return true;
	}
}

function clone_error_status_log($error){
	$data = DB::getField("iwp_clone_stats", "optionValue", "optionName = 'cloneErrorStatus'");
	if (!empty($data)) {
		!DB::update("iwp_clone_stats", array('optionName' => 'cloneErrorStatus', 'optionValue' => $data.'<br>'.$error), "optionName = 'cloneErrorStatus'") ;
	}else{
		DB::insert("iwp_clone_stats", array('optionName' => 'cloneErrorStatus', 'optionValue' => $error));
	}
}

function memory_check($memory, $check_using = false) {
	$memory_limit = memory_check_current($check_using);
	return ($memory_limit >= $memory)?true:false;
}

function memory_check_current($memory_limit = false) {
	# Returns in megabytes
	if ($memory_limit == false) $memory_limit = ini_get('memory_limit');
	$memory_limit = rtrim($memory_limit);
	$memory_unit = $memory_limit[strlen($memory_limit)-1];
	if ((int)$memory_unit == 0 && $memory_unit !== '0') {
		$memory_limit = substr($memory_limit,0,strlen($memory_limit)-1);
	} else {
		$memory_unit = '';
	}
	switch($memory_unit) {
		case '':
			$memory_limit = floor($memory_limit/1048576);
		break;
		case 'K':
		case 'k':
			$memory_limit = floor($memory_limit/1024);
		break;
		case 'G':
			$memory_limit = $memory_limit*1024;
		break;
		case 'M':
			//assumed size, no change needed
		break;
	}
	return $memory_limit;
}

function checkFileSystemRequirement(){
	$tempDirName = dirname(dirname(__FILE__))."/".time().'_IWP';
	if (!@mkdir($tempDirName)) {
		$GLOBALS['needFileSystem'] = true;
		initFileSystem(false, true);
		$tempDirName = $GLOBALS['FileSystemObj']->findFolder($tempDirName);
		$return = $GLOBALS['FileSystemObj']->mkdir($tempDirName);
		if (!$return || !$GLOBALS['FileSystemObj']->chmod($tempDirName, 777)) {
			die(status("Could not change the File/Directory permission. Please give access to change permissions for your FTP/SFTP user", false ,true));
		}
		$return = $GLOBALS['FileSystemObj']->rmdir($tempDirName);
		return true;
	}
	@rmdir($tempDirName);
	return false;

}

function getBackupFilesByTaskName($backupDetails, $skipDB = false){
		$backupFiles = array();
		if (!empty($backupDetails['plugins'])) {
			$backupFiles = array_merge($backupFiles, $backupDetails['plugins']);
		}
		if (!empty($backupDetails['themes'])) {
			$backupFiles = array_merge($backupFiles, $backupDetails['themes']);
		}
		if (!empty($backupDetails['others'])) {
			$backupFiles = array_merge($backupFiles, $backupDetails['others']);
		}
		if (!empty($backupDetails['uploads'])) {
			$backupFiles = array_merge($backupFiles, $backupDetails['uploads']);
		}
		if (!empty($backupDetails['more'])) {
			$backupFiles = array_merge($backupFiles,$backupDetails['more']);
		}
		if ($skipDB == false) {
			$backupFiles[] = $backupDetails['db'];
		}

		return $backupFiles;
}

function buildFolderAuthURL($URLParseData, $bkURL){
	if (!empty($URLParseData['user']) && !empty($URLParseData['pass'])) {
		$URLParts = parse_url($bkURL);
		$URLParts['user'] = $URLParseData['user'];
		$URLParts['pass'] = $URLParseData['pass'];
		$bkURL = httpBuildURLCustom($URLParts);
		return $bkURL;
	}else{
		return $bkURL;
	}
}

function httpBuildURLCustom($parts){
	
	if(is_array($parts['query'])){
		$parts['query'] = http_build_query($parts['query'], NULL, '&');
	}
	$URL = $parts['scheme'].'://'
		.($parts['user'] ? $parts['user'].':'.$parts['pass'].'@' : '')
		.$parts['host']
		.((!empty($parts['port']) && $parts['port'] != 80) ? ':'.$parts['port'] : '')
		.($parts['path'] ? $parts['path'] : '')
		.($parts['query'] ? '?'.$parts['query'] : '')
		.($parts['fragment'] ? '#'.$parts['fragment'] : '');
	return $URL;
}

function sameServerPostDBCloneProcess(){
	$old_table_prefix = get_table_prefix(dirname(dirname(__FILE__)));
	$changed_prefix_config = change_table_prefix_config_file(dirname(dirname(__FILE__)), $GLOBALS['db_table_prefix']);
	$dbModificationArray = array();
	$dbModificationArray['old_file_path'] = dirname(dirname(dirname(__FILE__)));
	$dbModificationArray['has_new_prefix'] = true;
	$dbModificationArray['db_file'] = $db_file;
	$dbModificationArray['table_prefix'] = $GLOBALS['db_table_prefix'];
	$dbModificationArray['temp_unzip_dir'] = dirname(dirname(__FILE__));
	$dbModificationArray['newUser'] = $newUser;
	$dbModificationArray['newPassword'] = $newPassword;
	$dbModificationArray['old_user'] = $GLOBALS['old_user'];
	$dbModificationArray['old_table_prefix'] = $old_table_prefix;
	$dbModificationArray['new_url'] = $GLOBALS['new_url'];
	$dbModificationArray['old_url'] = $old_url;
	if (empty($old_site_url)) {//$old_url - old site url
		$query =  "SELECT option_value FROM " . $GLOBALS['db_table_prefix'] . "options  WHERE option_name = 'siteurl' LIMIT 1";
		$result = DB::doQuery($query) or die(status('Error getting old site URL' . DB::error(), $success=false, $return=true));
        $_result = new DB::$DBResultClass($result);
		$info = $_result->nextRow($_result);
		$old_site_url = removeTrailingSlash($info['option_value']);
	}
	$dbModificationArray['old_site_url'] = $old_site_url;
	$query =  "SELECT option_value FROM " . $GLOBALS['db_table_prefix'] . "options  WHERE option_name = 'home' LIMIT 1";
	$result = DB::doQuery($query) or die(status('Error getting old site URL' . DB::error(), $success=false, $return=true));
    $_result = new DB::$DBResultClass($result);
	$info = $_result->nextRow($_result);
	$new_old_url = removeTrailingSlash($info['option_value']);
	if ($old_url != $new_old_url) {
		$old_url = $new_old_url;
		$dbModificationArray['old_url'] = $new_old_url;
		
	}
	$isBreak = check_for_clone_break();
	if ($isBreak) {
		global $response_arr;
		$response_arr = array();
		initialize_response_array($response_arr);
		$response_arr['status'] = 'partiallyCompleted';
		$response_arr['break'] = true;
		$response_arr['dbModificationArray'] = $dbModificationArray;
		$response_arr['dbModification'] = true;
		$response_arr['peak_mem_usage'] = (memory_get_peak_usage(true)/1024/1024);
		die(status("multicall", $success=true, $return=false, $response_arr));
		return $response_arr;
	}

	cloneDatabaseModification($dbModificationArray);
}

function connfigFileProcess(){
	if (file_exists(dirname(dirname(dirname(__FILE__))).'/wp-config.php')) {
		$configContent = IWP_WPConfig::tokenParser(dirname(dirname(dirname(__FILE__))).'/wp-config.php');
		iwp_define_constants($configContent);
		$GLOBALS['table_prefix'] = get_table_prefix(dirname(dirname(dirname(__FILE__))));
	}
	if(empty($configContent['DB_NAME'])){
		if (file_exists( dirname(dirname(dirname(__FILE__))).'/wp-load.php')) {
			require dirname(dirname(dirname(__FILE__))).'/wp-load.php';
			global $wpdb;
			$GLOBALS['table_prefix'] = $wpdb->base_prefix;
		}else{
			if($_REQUEST['isTestConnection'] == 1){
				$status = 'test-connection : Please create staging inside your WordPress installed folder';
				appUpdateMsg($status, 1);
				exit;
			}else{
				$status = 'Please create staging inside your WordPress installed folder';
				die(status($status, $success=false, $return=true));			
			}
		}
	}
}

function connfigFileProcessForExistingSite(){
	if (file_exists(dirname(dirname(__FILE__)).'/wp-config.php')) {
		$configContent = IWP_WPConfig::tokenParser(dirname(dirname(__FILE__)).'/wp-config.php');
		iwp_define_constants($configContent);
		$GLOBALS['table_prefix'] = get_table_prefix(dirname(dirname(__FILE__)));
	}
	if(empty($configContent['DB_NAME'])){
		if (file_exists( dirname(dirname(__FILE__)).'/wp-load.php')) {
			require dirname(dirname(__FILE__)).'/wp-load.php';
			global $wpdb;
			$GLOBALS['table_prefix'] = $wpdb->base_prefix;
		}else{
			if($_REQUEST['isTestConnection'] == 1){
				$status = 'test-connection : Please create staging inside your WordPress installed folder';
				appUpdateMsg($status, 1);
				exit;
			}else{
				$status = 'Please create staging inside your WordPress installed folder';
				die(status($status, $success=false, $return=true));			
			}		
		}
	}
}
function connfigFileProcessForStagingToLive(){
	if (file_exists(dirname(dirname(__FILE__)).'/wp-config.php')) {
		$configContent = IWP_WPConfig::tokenParser(dirname(dirname(__FILE__)).'/wp-config.php');
		iwp_define_constants($configContent);
		$GLOBALS['table_prefix'] = get_table_prefix(dirname(dirname(__FILE__)));
	}
	if(empty($configContent['DB_NAME'])){
		if (file_exists( dirname(dirname(__FILE__)).'/wp-load.php')) {
			require dirname(dirname(__FILE__)).'/wp-load.php';
			global $wpdb;
			$GLOBALS['table_prefix'] = $wpdb->base_prefix;
		}else{
			if($_REQUEST['isTestConnection'] == 1){
				$status = 'test-connection : Please create staging inside your WordPress installed folder';
				appUpdateMsg($status, 1);
				exit;
			}else{
				$status = 'Please create staging inside your WordPress installed folder';
				die(status($status, $success=false, $return=true));			
			}			
		}
	}
}
function iwp_define_constants($configContent){
	if (isset($configContent['DB_NAME'])) {
		define('DB_NAME', $configContent['DB_NAME'] );
	}
	if (isset($configContent['DB_USER'])) {
		define('DB_USER', $configContent['DB_USER'] );
	}
	if (isset($configContent['DB_PASSWORD'])) {
		define('DB_PASSWORD', $configContent['DB_PASSWORD'] );
	}
	if (isset($configContent['DB_HOST'])) {
		define('DB_HOST', $configContent['DB_HOST'] );
	}
}

class IWP_WPConfig
{
	public $new_url;
	public $old_url;
	public $old_site_url;
	public $old_file_path;

	public function __construct($params){
		$this->new_url = $params['new_url'];
		$this->old_url = $params['old_url'];
		$this->old_site_url = $params['old_site_url'];
		$this->old_file_path = $params['old_file_path'];
	}
	public function updateStandard()
	{
		if (!file_exists($GLOBALS['new_file_path'].'/wp-config.php')) return;
		if ($GLOBALS['needFileSystem']) {
			$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($GLOBALS['new_file_path']);
			// $GLOBALS['FileSystemObj']->delete($temp_unzip_dir_file.'/wp-config.php');
			// $GLOBALS['FileSystemObj']->touch($temp_unzip_dir_file.'/wp-config.php');
			$GLOBALS['FileSystemObj']->chmod($temp_unzip_dir_file.'/wp-config.php', 0777);
		}

		$root_path	 = set_safe_path($GLOBALS['new_file_path']);
		$wpconfig_path	= "{$root_path}/wp-config.php";
		$wpconfig	 = @file_get_contents('wp-config.php', true);

		$patterns = array();
		$replace  = array();

		//SSL CHECKS
		if (stristr($this->new_url, 'https:')) {
			if (!strstr($wpconfig, 'FORCE_SSL_ADMIN')) {
				$wpconfig = $wpconfig.PHP_EOL."define('FORCE_SSL_ADMIN', true);";
			}
		} else {
			array_push($patterns, "/'FORCE_SSL_ADMIN',\s*true/");
			array_push($replace, "'FORCE_SSL_ADMIN', false");
		}

		// //CACHE CHECKS
		// if ($_POST['cache_wp']) {
		// 	if (!strstr($wpconfig, 'WP_CACHE')) {
		// 		$wpconfig = $wpconfig.PHP_EOL."define('WP_CACHE', true);";
		// 	}
		// } else {
		// 	array_push($patterns, "/'WP_CACHE',\s*true/");
		// 	array_push($replace, "'WP_CACHE', false");
		// }
		// if (!$_POST['cache_path']) {
		// 	array_push($patterns, "/'WPCACHEHOME',\s*'.*?'/");
		// 	array_push($replace, "'WPCACHEHOME', ''");
		// }

		if (!is_writable("{$root_path}/wp-config.php")) {
			if (file_exists("{$root_path}/wp-config.php")) {
				die(status("Permission denied to write the config file.", $success=false, $return=true));
			} else {
				die(status("wp config file does not exits.", $success=false, $return=true));
			}
		}

		$wpconfig	 = preg_replace($patterns, $replace, $wpconfig);
		file_put_contents('wp-config.php', $wpconfig);
		if ($GLOBALS['needFileSystem']) {
			$GLOBALS['FileSystemObj']->chmod($temp_unzip_dir_file.'/wp-config.php', 0644);
		}
		$wpconfig	 = null;
	}

	/**
	 *  Updates the web server config files in Step 1
	 *
	 *  @return null
	 */
	public function updateExtended()
	{
		$config_file = '';
		if (!file_exists($GLOBALS['new_file_path'].'/wp-config.php')) {
			return $config_file;
		}

		if ($GLOBALS['needFileSystem']) {
			$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($GLOBALS['new_file_path']);
			// $GLOBALS['FileSystemObj']->delete($temp_unzip_dir_file.'/wp-config.php');
			// $GLOBALS['FileSystemObj']->touch($temp_unzip_dir_file.'/wp-config.php');
			$GLOBALS['FileSystemObj']->chmod($temp_unzip_dir_file.'/wp-config.php', 0777);
		}

		$root_path		= set_safe_path($GLOBALS['new_file_path']);
		$wpconfig_path	= "{$root_path}/wp-config.php";
		$config_file	= @file_get_contents($wpconfig_path, true);

		$patterns	 = array(
			"/('|\")WP_HOME.*?\)\s*;/",
			"/('|\")WP_SITEURL.*?\)\s*;/");
		$replace	 = array(
			"'WP_HOME', '{$this->new_url}');",
			"'WP_SITEURL', '{$this->new_url}');");

		//Not sure how well tokenParser works on all servers so only using for not critical constants at this point.
		//$count checks for dynamic variable types such as:  define('WP_TEMP_DIR',	'D:/' . $var . 'somepath/');
		//which should not be updated.
		$defines = self::tokenParser($wpconfig_path);

		//WP_CONTENT_DIR
		if (isset($defines['WP_CONTENT_DIR'])) {
			$val = str_replace($this->old_file_path, $GLOBALS['new_file_path'], set_safe_path($defines['WP_CONTENT_DIR']), $count);
			if ($count > 0) {
				array_push($patterns, "/('|\")WP_CONTENT_DIR.*?\)\s*;/");
				array_push($replace, "'WP_CONTENT_DIR', '{$val}');");
			}
		}

		//WP_CONTENT_URL
		if (isset($defines['WP_CONTENT_URL'])) {
			$val = str_replace($this->old_url . '/', $this->new_url . '/', $defines['WP_CONTENT_URL'], $count);
			if ($count > 0) {
				array_push($patterns, "/('|\")WP_CONTENT_URL.*?\)\s*;/");
				array_push($replace, "'WP_CONTENT_URL', '{$val}');");
			}
		}

		//WP_TEMP_DIR
		if (isset($defines['WP_TEMP_DIR'])) {
			$val = str_replace($_POST['path_old'], $GLOBALS['new_file_path'], set_safe_path($defines['WP_TEMP_DIR']) , $count);
			if ($count > 0) {
				array_push($patterns, "/('|\")WP_TEMP_DIR.*?\)\s*;/");
				array_push($replace, "'WP_TEMP_DIR', '{$val}');");
			}
		}
		
		//DOMAIN_CURRENT_SITE
		if (isset($defines['DOMAIN_CURRENT_SITE'])) {
			$mu_newDomainHost = parse_url($this->new_url, PHP_URL_HOST);
			array_push($patterns, "/('|\")DOMAIN_CURRENT_SITE.*?\)\s*;/");
			array_push($replace, "'DOMAIN_CURRENT_SITE', '{$mu_newDomainHost}');");
		}

		//PATH_CURRENT_SITE
		if (isset($defines['PATH_CURRENT_SITE'])) {
			$mu_newUrlPath = parse_url($this->new_url, PHP_URL_PATH);
			$mu_newUrlPath = $mu_newUrlPath.'/';
			array_push($patterns, "/('|\")PATH_CURRENT_SITE.*?\)\s*;/");
			array_push($replace, "'PATH_CURRENT_SITE', '{$mu_newUrlPath}');");
		}
		
		$config_file = preg_replace($patterns, $replace, $config_file);
		file_put_contents($wpconfig_path, $config_file);
		if ($GLOBALS['needFileSystem']) {
			$GLOBALS['FileSystemObj']->chmod($temp_unzip_dir_file.'/wp-config.php', 0644);
		}
		$config_file = file_get_contents($wpconfig_path, true);

		return $config_file;
	}


	public static function tokenParser($wpconfig_path) {

		$defines = array();
		$wpconfig_file = @file_get_contents($wpconfig_path);

		if (!function_exists('token_get_all')) {
			status("PHP function 'token_get_all' does not exist so skipping WP_CONTENT_DIR and WP_CONTENT_URL processing.", $success=false, $return=false);
			return $defines;
		}

		if ($wpconfig_file === false) {
			return $defines;
		}

		$defines = array();
		$tokens	 = token_get_all($wpconfig_file);
		$token	 = reset($tokens);
		while ($token) {
			if (is_array($token)) {
				if ($token[0] == T_WHITESPACE || $token[0] == T_COMMENT || $token[0] == T_DOC_COMMENT) {
					// do nothing
				} else if ($token[0] == T_STRING && strtolower($token[1]) == 'define') {
					$state = 1;
				} else if ($state == 2 && self::isConstant($token[0])) {
					$key	 = $token[1];
					$state	 = 3;
				} else if ($state == 4 && self::isConstant($token[0])) {
					$value	 = $token[1];
					$state	 = 5;
				}
			} else {
				$symbol = trim($token);
				if ($symbol == '(' && $state == 1) {
					$state = 2;
				} else if ($symbol == ',' && $state == 3) {
					$state = 4;
				} else if ($symbol == ')' && $state == 5) {
					$defines[self::tokenStrip($key)] = self::tokenStrip($value);
					$state = 0;
				}
			}
			$token = next($tokens);
		}

		return $defines;

	}

	private static function tokenStrip($value)
	{
		return preg_replace('!^([\'"])(.*)\1$!', '$2', $value);
	}

	private static function isConstant($token)
	{
		return $token == T_CONSTANT_ENCAPSED_STRING || $token == T_STRING || $token == T_LNUMBER || $token == T_DNUMBER;
	}


}

class IWP_LiteSpeed {
	public static $isLiteSpeedMultiCall = false;
	public static $isLiteSpeedHtaccess = false;
	public static $htaccessFileName = '.htaccess.litespeed';
	public static function isLiteSpeedServer(){
		$server_software = strtolower($_SERVER['SERVER_SOFTWARE']);
		$server = 'litespeed';
		if(strpos($server_software, $server) !== false){
			return true;
		}
		return false; 

	}
	public static function checkTimeOutRuleCompatibility(){
		if(self::$isLiteSpeedMultiCall == false && self::isLiteSpeedServer()){
			return true;
		}
		return false;

	}
	public static function writeTimeoutRule($url,$temp_unzip_dir){
			status("*********************************** Start creating litespeed server timeout rule in .htaccess file  *************************", $success=true, $return=false);
			$timeout_rule_added = false;
			$args    = parse_url($url);        
			$string  = rtrim($args['path'], "/");
			$data = "<IfModule Litespeed>\nRewriteEngine On\nRewriteRule .* - [E=noabort:1]\nRewriteRule .* - [E=noconntimeout:1]\n</IfModule>\n# BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /".$string."/\nRewriteRule ^index\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /".$string."/index.php [L]\n</IfModule>\n# END WordPress";
			if ($GLOBALS['needFileSystem']) {
				$temp_unzip_dir_file = $GLOBALS['FileSystemObj']->findFolder($temp_unzip_dir);
				if($GLOBALS['FileSystemObj']->putContents($temp_unzip_dir_file.'/.htaccess', $data)){
					$timeout_rule_added = true;
				}
			}else{
				if(@file_put_contents($temp_unzip_dir.'/.htaccess', $data)){
					$timeout_rule_added = true;
				}
			}
			if($timeout_rule_added){
				status("*********************************** LiteSpeed server timeout rule created  *************************", $success=true, $return=false);
				return true;
			}else{
				status("*********************************** We are not able to create LiteSpeed rule. Please give write access to php or FTP/SFTP  *************************", $success=true, $return=false);
				return false;
			}

	}

	public static function commonFileExist($temp_unzip_dir){
		if(self::$isLiteSpeedHtaccess && file_exists($temp_unzip_dir.'/'.self::$htaccessFileName)){
			return true;
		}
		return false;
	}

}

class IWP_FolderProtection {
	public static $htaccessFileName = '.htaccess.folderprotection';
	public static $isStagingToLive  = false;
	public static function commonFileExist($temp_unzip_dir){
		if(file_exists($temp_unzip_dir.'/'.self::$htaccessFileName)){
			return true;
		}
		return false;
	}
}
Le coin du marchand VO vente véhicule entre professionnels

Accès réservé aux professionnels

Site regroupant des annonces de véhicules marchands en vente entre professionnels. Vendez, achetez vos V.O entre pros en toute simplicité et sans intermédiaires.

Déposez gratuitement vos annonces*

*Offre de lancement

Marques
Nous avons trouvé annonces pour vous.

Slide Slide Slide Slide Slide En savoir plus

A propos de nous

Le Coin du Marchand
VO

Le Coin du Marchand
VO

Parce que le métier de marchand V.O. est en perpétuelle évolution
Le coin du marchand V.O. a décidé de vous accompagner à travers cette plateforme qui vous propose un service de petites annonces pour la vente et l’achat de véhicules entre professionnels revendeurs.

Pour l’approvisionnement de votre parc, pour une recherche personnalisée ou vendre des véhicules stockés , assurez-vous des transactions uniquement entre pros.
L’accès à la plateforme est sécurisé et exclusivement réservé aux professionnels.

Soigneusement sélectionnées

Annonces Récentes

Pourquoi Nous Choisir

Professionnalisme

Plateforme regroupant les professionnels qui proposent des véhicules de divers modèles à la vente

Sur toute la France

Les ventes se font uniquement entre professionnels

Meilleurs Tarifs

Vous trouverez de très bonnes occasions de véhicules à des tarifs marchands

Partenaires

  • Développement
  • Bénéfices Mutuelles
  • Collaborations
  • Visibilité
  • Soutenir d’autres Projets

Newsletter

Abonnez-vous à notre newsletter et restez informé de nos offres

Copyright © 2023 Le Coin du Marchand VO | All Rights Reserved | Yanacom