function restore($args)
 {
     global $wpdb, $wp_filesystem;
     if (empty($args)) {
         return false;
     }
     extract($args);
     $this->set_resource_limit();
     $unlink_file = true;
     //Delete file after restore
     include_once ABSPATH . 'wp-admin/includes/file.php';
     //Detect source
     if ($backup_url || isset($manualBackupFile) && !empty($manualBackupFile)) {
         //This is for clone (overwrite)
         $backup_file = array();
         if (!$backup_url) {
             $site_url = site_url();
             $backup_url = $site_url . "/" . $manualBackupFile;
         }
         $backup_url_array = $this->get_files_array_from_iwp_part($backup_url);
         if (!is_array($backup_url_array)) {
             echo "this backup backup_url - " . $backup_url_array;
             $temp_backup_url = $backup_url_array;
             $backup_url_array = array();
             $backup_url_array[] = $temp_backup_url;
         }
         foreach ($backup_url_array as $key => $single_backup_url) {
             $backup_file[] = download_url($single_backup_url);
             if (is_wp_error($backup_file[$key])) {
                 return array('error' => 'Unable to download backup file (' . $backup_file[$key]->get_error_message() . ')', 'error_code' => 'unable_to_download_backup_file');
             }
         }
         $what = 'full';
     } else {
         //manual restore darkPrince
         $tasks = array();
         $task = array();
         $tasks = $this->get_requested_task($result_id);
         $tasks['taskResults'] = unserialize($tasks['taskResults']);
         $backup = $tasks['taskResults']['task_results'][$result_id];
         //darkCode testing purpose
         $hashValues = $backup['hashValues'];
         //$backup = $tasks['taskResults'];
         $requestParams = unserialize($tasks['requestParams']);
         $args = $requestParams['account_info'];
         //$task = $tasks['Backup Now'];
         if (isset($backup['server'])) {
             $backup_file = $backup['server']['file_path'];
             $unlink_file = false;
             //Don't delete file if stored on server
         } elseif (isset($backup['ftp'])) {
             $ftp_file = $backup['ftp'];
             $args = $args['iwp_ftp'];
             if (!is_array($ftp_file)) {
                 $ftp_file = array();
                 $ftp_file[0] = $backup['ftp'];
                 $backup_file = array();
             }
             foreach ($ftp_file as $key => $value) {
                 $args['backup_file'] = $value;
                 iwp_mmb_print_flush('FTP download: Start ' . $key);
                 $backup_file[] = $this->get_ftp_backup($args);
                 iwp_mmb_print_flush('FTP download: End ' . $key);
                 if ($backup_file[$key] == false) {
                     return array('error' => 'Failed to download file from FTP.', 'error_code' => 'failed_to_download_file_from_ftp');
                 }
             }
         } elseif (isset($backup['amazons3'])) {
             $amazons3_file = $backup['amazons3'];
             $args = $args['iwp_amazon_s3'];
             if (!is_array($amazons3_file)) {
                 $amazons3_file = array();
                 $amazons3_file[0] = $backup['amazons3'];
                 $backup_file = array();
             }
             foreach ($amazons3_file as $key => $value) {
                 $args['backup_file'] = $value;
                 iwp_mmb_print_flush('Amazon S3 download: Start ' . $key);
                 if (is_new_s3_compatible()) {
                     require_once $GLOBALS['iwp_mmb_plugin_dir'] . '/lib/amazon/s3IWPBackup.php';
                     $new_s3_obj = new IWP_MMB_S3_MULTICALL();
                     $backup_file[] = $new_s3_obj->get_amazons3_backup($args);
                 } else {
                     $backup_file[] = $this->get_amazons3_backup_bwd_comp($args);
                 }
                 iwp_mmb_print_flush('Amazon S3 download: End ' . $key);
                 if ($backup_file[$key] == false) {
                     return array('error' => 'Failed to download file from Amazon S3.', 'error_code' => 'failed_to_download_file_from_s3');
                 } else {
                     if (is_array($backup_file[$key]) && isset($backup_file[$key]['error'])) {
                         return array('error' => 'Failed to download file from Amazon S3. Please enable curl first.', 'error_code' => 'failed_to_download_file_from_s3_enable_curl');
                     }
                 }
             }
         } elseif (isset($backup['dropbox'])) {
             $dropbox_file = $backup['dropbox'];
             $args = $args['iwp_dropbox'];
             if (!is_array($dropbox_file)) {
                 $dropbox_file = array();
                 $dropbox_file[0] = $backup['dropbox'];
                 $backup_file = array();
             }
             foreach ($dropbox_file as $key => $value) {
                 $args['backup_file'] = $value;
                 iwp_mmb_print_flush('Dropbox download: Start ' . $key);
                 $backup_file[] = $this->get_dropbox_backup($args);
                 iwp_mmb_print_flush('Dropbox download: End ' . $key);
                 if ($backup_file[$key] == false) {
                     return array('error' => 'Failed to download file from Dropbox.', 'error_code' => 'failed_to_download_file_from_dropbox');
                 } else {
                     if (is_array($backup_file[$key]) && isset($backup_file[$key]['error'])) {
                         return array('error' => 'Failed to download file from Dropbox. Please enable curl first.', 'error_code' => 'failed_to_download_file_from_dbox_enable_curl');
                     }
                 }
             }
         } elseif (isset($backup['gDrive'])) {
             $gdrive_file = $backup['gDrive'];
             $args = $args['iwp_gdrive'];
             if (!is_array($gdrive_file)) {
                 $gdrive_file = array();
                 $gdrive_file[0] = $backup['gDrive'];
                 $backup_file = array();
             }
             foreach ($gdrive_file as $key => $value) {
                 $args['backup_file'] = $value;
                 iwp_mmb_print_flush('gDrive download: Start');
                 $backup_file[] = $this->get_google_drive_backup($args);
                 iwp_mmb_print_flush('gDrive download: End');
                 if (is_array($backup_file[$key]) && array_key_exists('error', $backup_file[$key])) {
                     return $backup_file[$key];
                 }
                 if ($backup_file[$key] == false) {
                     return array('error' => 'Failed to download file from gDrive.');
                 }
             }
         }
         //$what = $tasks[$task_name]['task_args']['what'];
         $what = $requestParams['args']['what'];
     }
     $this->wpdb_reconnect();
     /////////////////// dev ////////////////////////
     if (!$this->is_server_writable()) {
         return array('error' => 'Failed, please add FTP details', 'error_code' => 'failed_please_add_ftp_details');
     }
     $url = wp_nonce_url('index.php?page=iwp_no_page', 'iwp_fs_cred');
     ob_start();
     if (false === ($creds = request_filesystem_credentials($url, '', false, ABSPATH, null))) {
         return array('error' => 'Unable to get file system credentials', 'error_code' => 'unable_to_get_file_system_credentials');
         // stop processing here
     }
     ob_end_clean();
     if (!WP_Filesystem($creds, ABSPATH)) {
         //request_filesystem_credentials($url, '', true, false, null);
         return array('error' => 'Unable to initiate file system. Please check you have entered valid FTP credentials.', 'error_code' => 'unable_to_initiate_file_system');
         // stop processing here
         //return;
     }
     require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
     //will be used to copy from temp directory
     // do process
     //$temp_dir = get_temp_dir();
     $temp_dir = IWP_PCLZIP_TEMPORARY_DIR;
     if (file_exists(IWP_PCLZIP_TEMPORARY_DIR) && is_dir(IWP_PCLZIP_TEMPORARY_DIR)) {
         //
     } else {
         if (file_exists(dirname(IWP_PCLZIP_TEMPORARY_DIR)) && is_dir(dirname(IWP_PCLZIP_TEMPORARY_DIR))) {
             @mkdir(IWP_PCLZIP_TEMPORARY_DIR, 0755, true);
         } else {
             @mkdir(dirname(IWP_PCLZIP_TEMPORARY_DIR), 0755, true);
             @mkdir(IWP_PCLZIP_TEMPORARY_DIR, 0755, true);
         }
     }
     if (is_writable(IWP_PCLZIP_TEMPORARY_DIR)) {
         @file_put_contents(IWP_PCLZIP_TEMPORARY_DIR . '/index.php', '');
         //safe
     } else {
         $chmod = chmod(IWP_PCLZIP_TEMPORARY_DIR, 777);
         if (is_writable(IWP_PCLZIP_TEMPORARY_DIR)) {
             @file_put_contents(IWP_PCLZIP_TEMPORARY_DIR . '/index.php', '');
             //safe
         }
     }
     if (is_writable(IWP_PCLZIP_TEMPORARY_DIR)) {
         $temp_dir = IWP_PCLZIP_TEMPORARY_DIR;
     } else {
         $temp_dir = get_temp_dir();
         if (!is_writable($temp_dir)) {
             return array('error' => 'Temporary directory is not writable. Please set 777 permission for ' . IWP_PCLZIP_TEMPORARY_DIR . ' and try again.', 'error_code' => 'pclzip_temp_dir_not_writable_please_set_777');
         }
     }
     $new_temp_folder = untrailingslashit($temp_dir);
     $temp_uniq = md5(microtime(1));
     //should be random
     while (is_dir($new_temp_folder . '/' . $temp_uniq)) {
         $temp_uniq = md5(microtime(1));
     }
     $new_temp_folder = trailingslashit($new_temp_folder . '/' . $temp_uniq);
     $is_dir_created = mkdir($new_temp_folder);
     // new folder should be empty
     if (!$is_dir_created) {
         return array('error' => 'Unable to create a temporary directory.', 'error_code' => 'unable_to_create_temporary_directory');
     }
     $remote_abspath = $wp_filesystem->abspath();
     if (!empty($remote_abspath)) {
         $remote_abspath = trailingslashit($remote_abspath);
     } else {
         return array('error' => 'Unable to locate WP root directory using file system.', 'error_code' => 'unable_to_locate_wp_root_directory_using_file_system');
     }
     //global $wp_filesystem;
     //		$wp_filesystem->put_contents(
     //		  '/tmp/example.txt',
     //		  'Example contents of a file',
     //		  FS_CHMOD_FILE // predefined mode settings for WP files
     //		);
     /////////////////// dev ////////////////////////
     //if ($backup_file && file_exists($backup_file)) {
     if ($backup_file) {
         if ($overwrite) {
             //clone only fresh or existing to existing
             //Keep old db credentials before overwrite
             if (!$wp_filesystem->copy($remote_abspath . 'wp-config.php', $remote_abspath . 'iwp-temp-wp-config.php', true)) {
                 if ($unlink_file) {
                     if (!is_array($backup_file)) {
                         $temp_backup_file = $backup_file;
                         $backup_file = array();
                         $backup_file = $temp_backup_file;
                     }
                     foreach ($backup_file as $k => $value) {
                         @unlink($value);
                     }
                 }
                 return array('error' => 'Error creating wp-config. Please check your write permissions.', 'error_code' => 'error_creating_wp_config');
             }
             $db_host = DB_HOST;
             $db_user = DB_USER;
             $db_password = DB_PASSWORD;
             $home = rtrim(get_option('home'), "/");
             $site_url = get_option('site_url');
             $clone_options = array();
             if (trim($clone_from_url) || trim($iwp_clone) || trim($maintain_old_key)) {
                 $clone_options['iwp_client_nossl_key'] = get_option('iwp_client_nossl_key');
                 $clone_options['iwp_client_public_key'] = get_option('iwp_client_public_key');
                 $clone_options['iwp_client_action_message_id'] = get_option('iwp_client_action_message_id');
             }
             //$clone_options['iwp_client_backup_tasks'] = serialize(get_option('iwp_client_multi_backup_temp_values'));
             $clone_options['iwp_client_notifications'] = serialize(get_option('iwp_client_notifications'));
             $clone_options['iwp_client_pageview_alerts'] = serialize(get_option('iwp_client_pageview_alerts'));
             $qry = "SELECT * FROM " . $wpdb->base_prefix . "iwp_backup_status";
             $clone_options['iwp_client_backup_tasks'] = $wpdb->get_results($qry, ARRAY_A);
             /*if(!$clone_options['iwp_client_backup_tasks'])
             		{
             			return array(
             			'error' => 'Unable to restore clone options.'
             			);
             		}*/
         } else {
             $restore_options = array();
             $restore_options['iwp_client_notifications'] = serialize(get_option('iwp_client_notifications'));
             $restore_options['iwp_client_pageview_alerts'] = serialize(get_option('iwp_client_pageview_alerts'));
             $restore_options['iwp_client_user_hit_count'] = serialize(get_option('iwp_client_user_hit_count'));
             //$restore_options['iwp_client_backup_tasks'] = serialize(get_option('iwp_client_multi_backup_temp_values'));
             $qry = "SELECT * FROM " . $wpdb->base_prefix . "iwp_backup_status";
             $restore_options['iwp_client_backup_tasks'] = $wpdb->get_results($qry, ARRAY_A);
             /*if(!$restore_options['iwp_client_backup_tasks'])
             		{
             			return array(
             			'error' => 'Unable to restore options.'
             			);
             		}*/
         }
         //Backup file will be extracted to a temporary path
         if (!is_array($backup_file)) {
             $temp_backup_file = $backup_file;
             $backup_file = array();
             $backup_file[0] = $temp_backup_file;
         }
         foreach ($backup_file as $single_backup_file) {
             echo "this backup file - " . $single_backup_file;
             //chdir(ABSPATH);
             $unzip = $this->get_unzip();
             $command = "{$unzip} -o {$single_backup_file} -d {$new_temp_folder}";
             iwp_mmb_print_flush('ZIP Extract CMD: Start');
             ob_start();
             $result = $this->iwp_mmb_exec($command);
             //$result = false;
             ob_get_clean();
             iwp_mmb_print_flush('ZIP Extract CMD: End');
             if (!$result) {
                 //fallback to pclzip
                 ////define('IWP_PCLZIP_TEMPORARY_DIR', IWP_BACKUP_DIR . '/');
                 //require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
                 //require_once $GLOBALS['iwp_mmb_plugin_dir'].'/pclzip.class.php';
                 iwp_mmb_print_flush('ZIP Extract PCL: Start');
                 $archive = new IWPPclZip($single_backup_file);
                 $result = $archive->extract(IWP_PCLZIP_OPT_PATH, $new_temp_folder, IWP_PCLZIP_OPT_REPLACE_NEWER);
                 iwp_mmb_print_flush('ZIP Extract PCL: End');
             }
             $this->wpdb_reconnect();
             if ($unlink_file) {
                 @unlink($single_backup_file);
             }
             if (!$result) {
                 if ($unlink_file) {
                     foreach ($backup_file as $single_file) {
                         @unlink($single_file);
                     }
                 }
                 return array('error' => 'Failed to unzip files. pclZip error (' . $archive->error_code . '): .' . $archive->error_string, 'error_code' => 'failed_to_unzip_files');
             }
         }
         //appending files if split is done
         $joinedFilesArray = $this->appendSplitFiles($new_temp_folder);
         //$compareHashValuesArray = $this -> compareHashValues($joinedFilesArray['orgHash'], $joinedFilesArray['afterSplitHash']);
         //do the restore db part only if the category is full or db .. else skip it for files alone concept
         if ($what == 'full' || $what == 'db') {
             $db_result = $this->restore_db($new_temp_folder);
             if (!$db_result) {
                 return array('error' => 'Error restoring database.', 'error_code' => 'error_restoring_database');
             } else {
                 if (is_array($db_result) && isset($db_result['error'])) {
                     return array('error' => $db_result['error']);
                 }
             }
         }
     } else {
         return array('error' => 'Backup file not found.', 'error_code' => 'backup_file_not_found');
     }
     $bError = error_get_last();
     //copy files from temp to ABSPATH
     $copy_result = $this->iwp_mmb_direct_to_any_copy_dir($new_temp_folder, $remote_abspath);
     if (is_wp_error($copy_result)) {
         $wp_temp_direct2 = new WP_Filesystem_Direct('');
         $wp_temp_direct2->delete($new_temp_folder, true);
         return $copy_result;
     }
     $this->wpdb_reconnect();
     //Replace options and content urls
     if ($overwrite) {
         //fresh WP package or existing to existing site
         //Get New Table prefix
         $new_table_prefix = trim($this->get_table_prefix());
         //Retrieve old wp_config
         //@unlink(ABSPATH . 'wp-config.php');
         $wp_filesystem->delete($remote_abspath . 'wp-config.php', false, 'f');
         //Replace table prefix
         //$lines = file(ABSPATH . 'iwp-temp-wp-config.php');
         $lines = $wp_filesystem->get_contents_array($remote_abspath . 'iwp-temp-wp-config.php');
         $new_lines = '';
         foreach ($lines as $line) {
             if (strstr($line, '$table_prefix')) {
                 $line = '$table_prefix = "' . $new_table_prefix . '";' . PHP_EOL;
             }
             $new_lines .= $line;
             //file_put_contents(ABSPATH . 'wp-config.php', $line, FILE_APPEND);
         }
         $wp_filesystem->put_contents($remote_abspath . 'wp-config.php', $new_lines);
         //@unlink(ABSPATH . 'iwp-temp-wp-config.php');
         $wp_filesystem->delete($remote_abspath . 'iwp-temp-wp-config.php', false, 'f');
         //Replace options
         $query = "SELECT option_value FROM " . $new_table_prefix . "options WHERE option_name = 'home'";
         $old = $wpdb->get_var($query);
         $old = rtrim($old, "/");
         $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'home'";
         $wpdb->query($wpdb->prepare($query, $home));
         $query = "UPDATE " . $new_table_prefix . "options  SET option_value = %s WHERE option_name = 'siteurl'";
         $wpdb->query($wpdb->prepare($query, $home));
         //Replace content urls
         $regexp1 = 'src="(.*)' . $old . '(.*)"';
         $regexp2 = 'href="(.*)' . $old . '(.*)"';
         $query = "UPDATE " . $new_table_prefix . "posts SET post_content = REPLACE (post_content, %s,%s) WHERE post_content REGEXP %s OR post_content REGEXP %s";
         $wpdb->query($wpdb->prepare($query, $old, $home, $regexp1, $regexp2));
         if (trim($new_password)) {
             $new_password = wp_hash_password($new_password);
         }
         if (!trim($clone_from_url) && !trim($iwp_clone)) {
             if ($new_user && $new_password) {
                 $query = "UPDATE " . $new_table_prefix . "users SET user_login = %s, user_pass = %s WHERE user_login = %s";
                 $wpdb->query($wpdb->prepare($query, $new_user, $new_password, $old_user));
             }
         } else {
             // if ($iwp_clone) {
             if ($admin_email) {
                 //Clean Install
                 $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'admin_email'";
                 $wpdb->query($wpdb->prepare($query, $admin_email));
                 $query = "SELECT * FROM " . $new_table_prefix . "users LIMIT 1";
                 $temp_user = $wpdb->get_row($query);
                 if (!empty($temp_user)) {
                     $query = "UPDATE " . $new_table_prefix . "users SET user_email=%s, user_login = %s, user_pass = %s WHERE user_login = %s";
                     $wpdb->query($wpdb->prepare($query, $admin_email, $new_user, $new_password, $temp_user->user_login));
                 }
             }
             // }
             //if ($clone_from_url) {
             if ($new_user && $new_password) {
                 $query = "UPDATE " . $new_table_prefix . "users SET user_pass = %s WHERE user_login = %s";
                 $wpdb->query($wpdb->prepare($query, $new_password, $new_user));
             }
             // }
         }
         if (is_array($clone_options) && !empty($clone_options)) {
             $GLOBALS['table_prefix'] = $new_table_prefix;
             $this->clone_restore_options($clone_options);
             if (!empty($clone_options['iwp_client_nossl_key'])) {
                 $query = "SELECT * FROM " . $new_table_prefix . "options WHERE option_name = 'iwp_client_nossl_key'";
                 $temp_row = $wpdb->get_row($query);
                 if (!empty($temp_row)) {
                     $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'iwp_client_nossl_key'";
                     $wpdb->query($wpdb->prepare($query, $clone_options['iwp_client_nossl_key']));
                 } else {
                     $insert = $wpdb->insert($new_table_prefix . "options", array('option_name' => 'iwp_client_nossl_key', 'option_value' => $clone_options['iwp_client_nossl_key'], 'autoload' => 'yes'), array('%s', '%s', '%s'));
                 }
             }
             if (!empty($clone_options['iwp_client_public_key'])) {
                 $query = "SELECT * FROM " . $new_table_prefix . "options WHERE option_name = 'iwp_client_public_key'";
                 $temp_row = $wpdb->get_row($query);
                 if (!empty($temp_row)) {
                     $query = "UPDATE " . $new_table_prefix . "options SET option_value = %s WHERE option_name = 'iwp_client_public_key'";
                     $wpdb->query($wpdb->prepare($query, $clone_options['iwp_client_public_key']));
                 } else {
                     $insert = $wpdb->insert($new_table_prefix . "options", array('option_name' => 'iwp_client_public_key', 'option_value' => $clone_options['iwp_client_public_key'], 'autoload' => 'yes'), array('%s', '%s', '%s'));
                 }
             }
         }
         $query = "SELECT * FROM " . $new_table_prefix . "users LIMIT 1";
         $temp_user = $wpdb->get_row($query);
         $new_user = $temp_user->user_login;
         //Remove hit count
         $query = "DELETE FROM " . $new_table_prefix . "options WHERE option_name = 'iwp_client_user_hit_count'";
         $wpdb->query($query);
         //Check for .htaccess permalinks update
         $this->replace_htaccess($home, $remote_abspath);
     } else {
         //restore client options
         if (is_array($restore_options) && !empty($restore_options)) {
             $GLOBALS['table_prefix'] = $wpdb->base_prefix;
             $this->clone_restore_options($restore_options);
         }
     }
     //clear the temp directory
     $wp_temp_direct2 = new WP_Filesystem_Direct('');
     $wp_temp_direct2->delete($new_temp_folder, true);
     return !empty($new_user) ? $new_user : true;
 }
/**
 * Restores rtPanel Options
 *
 * @uses $rtp_general array
 * @uses $rtp_post_comments array
 * @uses $rtp_hooks array
 * @param string $file The
 * @return bool|array
 *
 * @since rtPanel 2.0
 */
function rtp_import($file)
{
    global $rtp_general, $rtp_post_comments;
    require_once ABSPATH . '/wp-admin/includes/class-wp-filesystem-base.php';
    require_once ABSPATH . '/wp-admin/includes/class-wp-filesystem-direct.php';
    require_once ABSPATH . '/wp-admin/includes/file.php';
    @($file_object = new WP_Filesystem_Direct());
    $overrides = array('test_form' => false, 'test_type' => false);
    $import_file = wp_handle_upload($file, $overrides);
    extract(wp_check_filetype($import_file['file'], array('rtp' => 'txt/rtp')));
    $data = wp_remote_get($import_file['url']);
    $file_object->delete($import_file['file']);
    if ($ext != 'rtp') {
        return 'ext';
    }
    if (is_wp_error($data)) {
        return false;
    } else {
        preg_match('/\\<rtp_general\\>(.*)<\\/rtp_general\\>/is', $data['body'], $general);
        preg_match('/\\<rtp_post_comments\\>(.*)<\\/rtp_post_comments\\>/is', $data['body'], $post_comments);
        if (!empty($post_comments[1])) {
            update_option('rtp_post_comments', maybe_unserialize($post_comments[1]));
        }
        return $general[1];
    }
}
/**
 * Used to download and create image from 'src' and attach to media library
 *
 * @param array $match Array in which [0]->whole img tag and [1]->the img src
 * @param object|array $post The global post variable or object from get_posts()
 * @param string $size The image size required
 * @param array $double_check_tag Used to take care of the misleading wp-image class
 * @return string
 *
 * @since rtPanel 2.0
 */
function rtp_create_external_thumb($match, $post, $size, $double_check_tag = '')
{
    require_once ABSPATH . '/wp-admin/includes/class-wp-filesystem-base.php';
    require_once ABSPATH . '/wp-admin/includes/class-wp-filesystem-direct.php';
    @($file_object = new WP_Filesystem_Direct());
    $img_path = urldecode($match[1]);
    // Need to do this else image fetching will fail
    $remote_get_path = str_replace(' ', '%20', $img_path);
    // Get the img name from url
    $img_name = basename($img_path);
    /* Set permissions if directory is not writable */
    $upload_path = wp_upload_dir();
    if (!is_writable($upload_path['basedir']) || !is_executable($upload_path['basedir'])) {
        $stat = @stat(dirname($upload_path['basedir']));
        // Get the permission bits
        $dir_perms = $stat['mode'] & 07777;
        @chmod($upload_path['basedir'], $dir_perms);
    }
    /* For sanitization of name (just a precaution, although wp_upload_bits will try to take care of this) */
    $img_name = str_replace('&', '-', $img_name);
    $img_name = str_replace('?', '-', $img_name);
    $allowed_image_types = array('jpg', 'jpeg', 'jpe', 'gif', 'png', 'bmp', 'ico', 'tif', 'tiff');
    $check_extension = pathinfo($img_name);
    // if not in the array assign a particular name
    if (!in_array($check_extension['extension'], $allowed_image_types)) {
        $img_name = 'query-image.jpg';
    }
    // get placeholder file in the upload dir with a unique, sanitized filename
    $file = wp_upload_bits($img_name, 0, '');
    // fetch the remote url and write it to the placeholder file
    $wp_remote_get = wp_get_http($remote_get_path, $file['file'], 5);
    if ($wp_remote_get == '' || $wp_remote_get == false) {
        $file_object->delete($file['file']);
        return 0;
    }
    /* if response id is 200 and it's type is image */
    if ($wp_remote_get['response'] == 200 && substr($wp_remote_get['content-type'], 0, 5) == 'image') {
        //created img path
        $img_path = $file['file'];
        //created img url
        $img_url = $file['url'];
        // Get the image type. Must to use it as a post thumbnail.
        $img_type = wp_check_filetype($img_path);
        extract($img_type);
        $img_info = apply_filters('wp_handle_upload', array('file' => $img_path, 'url' => $img_url, 'type' => $type), 'sideload');
        require_once ABSPATH . '/wp-admin/includes/image.php';
        /* use image exif/iptc data for title and caption defaults if possible */
        if ($img_meta = @wp_read_image_metadata($img_info['file'])) {
            if (trim($img_meta['title']) && !is_numeric(sanitize_title($img_meta['title']))) {
                $img_title = $img_meta['title'];
            }
            if (trim($img_meta['caption'])) {
                $img_content = $img_meta['caption'];
            }
        }
        $img_title = isset($img_title) ? $img_title : str_replace('.' . $ext, '', basename($img_url));
        $img_content = isset($img_content) ? $img_content : str_replace('.' . $ext, '', basename($img_url));
        // Construct the attachment array
        $attachment = array('post_mime_type' => $img_info['type'], 'guid' => $img_url, 'post_parent' => $post->ID, 'post_title' => $img_title, 'post_content' => $img_content);
        // Save the attachment metadata
        $new_image_id = wp_insert_attachment($attachment, $img_info['file'], $post->ID);
        if (!is_wp_error($new_image_id) && $new_image_id != 0 && $new_image_id != '') {
            wp_update_attachment_metadata($new_image_id, wp_generate_attachment_metadata($new_image_id, $img_info['file']));
            $updated_post = array();
            $updated_post['ID'] = $post->ID;
            if (is_int($new_image_id)) {
                $image_src = wp_get_attachment_image_src($new_image_id, $size);
                // get the img tag classes
                preg_match('/<img.*class\\s*=\\s*"([^"]*)[^>]+>/i', $match[0], $class);
                /* if the image tag has class attribute and it does not have wp-image in class */
                if (isset($class[1])) {
                    $updated_class = $class[1] . ' wp-image-' . $new_image_id;
                    $updated_image_tag = str_replace('class="' . $class[1] . '"', 'class="' . $updated_class . '"', $match[0]);
                    $updated_post['post_content'] = str_replace($match[0], $updated_image_tag, $post->post_content);
                    if ($double_check_tag != '') {
                        $updated_post['post_content'] = str_replace($double_check_tag, $updated_image_tag, $post->post_content);
                    }
                    // Update the post
                    wp_update_post($updated_post);
                } else {
                    $updated_image_tag = str_replace('<img', '<img role="img" class="wp-image-' . $new_image_id . '"', $match[0]);
                    $updated_post['post_content'] = str_replace($match[0], $updated_image_tag, $post->post_content);
                    // Update the post
                    wp_update_post($updated_post);
                }
                return $image_src[0];
            } else {
                $updated_post = array();
                $updated_post['ID'] = $post->ID;
                $new_image_id = rtp_get_attachment_id_from_src($new_image_id);
                $image_src = wp_get_attachment_image_src($new_image_id, $size);
                preg_match('/<img.*class\\s*=\\s*"([^"]*)[^>]+>/i', $match[0], $class);
                if (isset($class[1])) {
                    $updated_class = $class[1] . ' wp-image-' . $new_image_id;
                    $updated_image_tag = str_replace('class="' . $class[1] . '"', 'class="' . $updated_class . '"', $match[0]);
                    $updated_post['post_content'] = str_replace($match[0], $updated_image_tag, $post->post_content);
                    if ($double_check_tag != '') {
                        $updated_post['post_content'] = str_replace($double_check_tag, $updated_image_tag, $post->post_content);
                    }
                    // Update the post
                    wp_update_post($updated_post);
                } else {
                    $updated_image_tag = str_replace('<img', '<img role="img" class="wp-image-' . $new_image_id . '"', $match[0]);
                    $updated_post['post_content'] = str_replace($match[0], $updated_image_tag, $post->post_content);
                    // Update the post
                    wp_update_post($updated_post);
                }
                return $image_src[0];
            }
        }
    } else {
        $file_object->delete($file['file']);
        return 0;
    }
}
 /**
  * @param string $relative_path
  */
 public function remove($relative_path = '')
 {
     $main_directory_path = $this->get_main_directory_path();
     $absolute_path = trailingslashit($main_directory_path . ltrim($relative_path, '/\\'));
     $this->filesystem->delete($absolute_path, true);
 }
Exemple #5
0
 function file_editor_upload($params)
 {
     global $wpdb, $wp_filesystem;
     include_once ABSPATH . 'wp-admin/includes/file.php';
     extract($params);
     if (!function_exists('gzinflate')) {
         return array('error' => 'Gzip library functions are not available.', 'error_code' => 'gzip_library_functions_are_not_available');
     } else {
         $fileContent = gzinflate($fileContent);
     }
     if (!$this->is_server_writable()) {
         return array('error' => 'Failed, please add FTP details', 'error_code' => 'failed_please_add_FTP_details_file_editor_upload');
     }
     $url = wp_nonce_url('index.php?page=iwp_no_page', 'iwp_fs_cred');
     ob_start();
     if (false === ($creds = request_filesystem_credentials($url, '', false, ABSPATH, null))) {
         return array('error' => 'Unable to get file system credentials', 'error_code' => 'unable_to_get_file_system_credentials_file_editor_upload');
         // stop processing here
     }
     ob_end_clean();
     if (!WP_Filesystem($creds, ABSPATH)) {
         return array('error' => 'Unable to initiate file system. Please check you have entered valid FTP credentials.', 'error_code' => 'unable_to_initiate_file_system_check_ftp_credentials_file_editor_upload');
         // stop processing here
     }
     require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php';
     //will be used to copy from temp directory
     $temp_folder = untrailingslashit(get_temp_dir());
     $temp_uniq = 'iwp_' . md5(microtime(1));
     //should be random
     while (is_dir($temp_folder . '/' . $temp_uniq)) {
         $temp_uniq = 'iwp_' . md5(microtime(1));
     }
     $new_temp_folder = trailingslashit($temp_folder . '/' . $temp_uniq);
     $is_dir_created = mkdir($new_temp_folder);
     // new folder should be empty
     if (!$is_dir_created) {
         return array('error' => 'Unable to create a temporary directory.', 'error_code' => 'unable_to_create_temporary_directory_file_editor_upload');
     }
     $remote_abspath = $wp_filesystem->abspath();
     if (!empty($remote_abspath)) {
         $remote_abspath = trailingslashit($remote_abspath);
     } else {
         return array('error' => 'Unable to locate WP root directory using file system.', 'error_code' => 'unable_to_locate_root_directory_remote_abspath_file_editor_upload');
     }
     if ($folderPath == 'root' && ($filePath == 'wp-config' || $filePath == 'wp-config.php')) {
         return array('error' => 'wp-config file is not allowed.', 'error_code' => 'config_file_is_not_allowed_file_editor_upload');
     }
     $file = $this->get_file_editor_vars($remote_abspath, $folderPath, $filePath, $ext);
     if ($file === false) {
         return array('error' => 'File path given is invalid.', 'error_code' => 'file_path_given_is_invalid_file_editor_upload');
     }
     $new_temp_subfolders = $new_temp_folder;
     for ($i = 0; $i < count($file['toCreate']); $i++) {
         $new_temp_subfolders .= trailingslashit($file['toCreate'][$i]);
         $is_subdir_created = mkdir($new_temp_subfolders);
         // new folder should be empty
         if (!$is_subdir_created) {
             return array('error' => 'Unable to create a temporary directory.', 'error_code' => 'unable_to_locate_wp_root_directory_using_file_system_file_editor_upload');
         }
     }
     $fileHandler = fopen($new_temp_subfolders . $file['name'], w);
     fwrite($fileHandler, $fileContent);
     fclose($fileHandler);
     $copy_result = $this->iwp_mmb_direct_to_any_copy_dir($new_temp_folder, $file['toPath']);
     if (is_wp_error($copy_result)) {
         $wp_temp_direct2 = new WP_Filesystem_Direct('');
         $wp_temp_direct2->delete($new_temp_folder, true);
         return $copy_result;
     }
     return 'success';
 }
 /**
  * @access public
  *
  * @param string $file
  * @param bool $recursive
  * @param string $type
  * @return bool
  */
 public function delete($file, $recursive = false, $type = false)
 {
     if ($this->authorized()) {
         return parent::delete($file, $recursive, $type);
     } else {
         return false;
     }
 }