| Server IP : 146.59.209.152 / Your IP : 216.73.216.46 Web Server : Apache System : Linux webm005.cluster131.gra.hosting.ovh.net 5.15.167-ovh-vps-grsec-zfs-classid #1 SMP Tue Sep 17 08:14:20 UTC 2024 x86_64 User : infrafs ( 43850) PHP Version : 8.2.29 Disable Function : _dyuweyrj4,_dyuweyrj4r,dl MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : ON | Sudo : OFF | Pkexec : OFF Directory : /home/i/n/f/infrafs/INFRABIKEIT/wp-content/plugins/ |
Upload File : |
uninstall.php 0000644 00000010226 15132770567 0007304 0 ustar 00 <?php
// If uninstall not called from WordPress, then exit.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
function wpvivid_clear_free_dir($directory){
if(file_exists($directory)){
if($dir_handle=@opendir($directory)){
while($filename=readdir($dir_handle)){
if($filename!='.' && $filename!='..'){
$subFile=$directory."/".$filename;
if(is_dir($subFile)){
wpvivid_clear_free_dir($subFile);
}
if(is_file($subFile)){
wp_delete_file($subFile);
}
}
}
closedir($dir_handle);
rmdir($directory);
}
}
}
$wpvivid_common_setting = get_option('wpvivid_common_setting', array());
if(!empty($wpvivid_common_setting))
{
if(isset($wpvivid_common_setting['uninstall_clear_folder']) && $wpvivid_common_setting['uninstall_clear_folder'])
{
$wpvivid_local_setting = get_option('wpvivid_local_setting', array());
if(isset($wpvivid_local_setting['path']))
{
if($wpvivid_local_setting['path'] !== 'wpvividbackups')
{
wpvivid_clear_free_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'wpvividbackups');
}
$wpvivid_local_setting['path']=basename($wpvivid_local_setting['path']);
$source_array=array('.', '..', 'plugins', 'themes', 'uploads');
if(!empty($wpvivid_local_setting['path']) && !in_array($wpvivid_local_setting['path'], $source_array))
{
if(is_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$wpvivid_local_setting['path']))
{
wpvivid_clear_free_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$wpvivid_local_setting['path']);
}
}
}
else
{
wpvivid_clear_free_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'wpvividbackups');
}
}
}
delete_option('wpvivid_schedule_setting');
delete_option('wpvivid_email_setting');
delete_option('wpvivid_compress_setting');
delete_option('wpvivid_local_setting');
delete_option('wpvivid_upload_setting');
delete_option('wpvivid_common_setting');
delete_option('wpvivid_backup_list');
delete_option('wpvivid_task_list');
delete_option('wpvivid_init');
delete_option('wpvivid_remote_init');
delete_option('wpvivid_last_msg');
delete_option('wpvivid_download_cache');
delete_option('wpvivid_download_task');
delete_option('wpvivid_user_history');
delete_option('wpvivid_saved_api_token');
delete_option('wpvivid_import_list_cache');
delete_option('wpvivid_importer_task_list');
delete_option('wpvivid_list_cache');
delete_option('wpvivid_exporter_task_list');
delete_option('wpvivid_need_review');
delete_option('wpvivid_review_msg');
delete_option('wpvivid_review_time');
delete_option('wpvivid_review_type');
delete_option('wpvivid_migrate_status');
delete_option('clean_task');
delete_option('cron_backup_count');
delete_option('wpvivid_backup_success_count');
delete_option('wpvivid_backup_error_array');
delete_option('wpvivid_amazons3_notice');
delete_option('wpvivid_hide_mwp_tab_page_v1');
delete_option('wpvivid_hide_wp_cron_notice');
delete_option('wpvivid_transfer_error_array');
delete_option('wpvivid_transfer_success_count');
delete_option('wpvivid_api_token');
delete_option('wpvivid_download_task_v2');
delete_option('wpvivid_export_list');
delete_option('wpvivid_backup_report');
$options=get_option('wpvivid_staging_options',array());
$staging_keep_setting=isset($options['staging_keep_setting']) ? $options['staging_keep_setting'] : true;
if($staging_keep_setting)
{
}
else
{
delete_option('wpvivid_staging_task_list');
delete_option('wpvivid_staging_task_cancel');
delete_option('wpvivid_staging_options');
delete_option('wpvivid_staging_history');
delete_option('wpvivid_staging_list');
}
define('WPVIVID_MAIN_SCHEDULE_EVENT','wpvivid_main_schedule_event');
if(wp_get_schedule(WPVIVID_MAIN_SCHEDULE_EVENT))
{
wp_clear_scheduled_hook(WPVIVID_MAIN_SCHEDULE_EVENT);
$timestamp = wp_next_scheduled(WPVIVID_MAIN_SCHEDULE_EVENT);
wp_unschedule_event($timestamp,WPVIVID_MAIN_SCHEDULE_EVENT);
}
includes/class-wpvivid-i18n.php 0000644 00000001603 15132770567 0012450 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
/**
* Define the internationalization functionality
*
* Loads and defines the internationalization files for this plugin
* so that it is ready for translation.
*
* @link https://wpvivid.com
* @since 0.9.1
*
* @package wpvivid
* @subpackage wpvivid/includes
*/
/**
* Define the internationalization functionality.
*
* Loads and defines the internationalization files for this plugin
* so that it is ready for translation.
*
* @since 0.9.1
* @package wpvivid
* @subpackage wpvivid/includes
* @author wpvivid team
*/
class WPvivid_i18n {
/**
* Load the plugin text domain for translation.
*
*
*/
public function load_plugin_textdomain() {
load_plugin_textdomain(
'wpvivid-backuprestore',
false,
dirname( dirname( plugin_basename( __FILE__ ) ) ) . '/languages/'
);
}
}
includes/class-wpvivid-zipclass.php 0000644 00000152531 15132770567 0013530 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
require_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-compress-default.php';
$wpvivid_extract_option = array();
class WPvivid_ZipClass extends Wpvivid_Compress_Default
{
public $last_error = '';
public $path_filter=array();
public function __construct()
{
if (!class_exists('PclZip'))
include_once(ABSPATH.'/wp-admin/includes/class-pclzip.php');
if (!class_exists('PclZip'))
{
$this->last_error = array('result'=>WPVIVID_FAILED,'error'=>"Class PclZip is not detected. Please update or reinstall your WordPress.");
}
}
public function get_packages($data,$write_child_files_json=false)
{
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
$files = $this -> filesplit($data['compress']['max_file_size'],$data['files']);
$temp_dir = $data['path'].'temp-'.$data['prefix'].DIRECTORY_SEPARATOR;
if(!file_exists($temp_dir))
@mkdir($temp_dir);
$packages = array();
if(sizeof($files) > 1)
{
for($i =0;$i <sizeof($files);$i ++)
{
$package = array();
$path = $data['path'].$data['prefix'].'.part'.sprintf('%03d',($i +1)).'.zip';
if(isset($data['json_info']))
{
$package['json']=$data['json_info'];
}
/*
$remove_path_size = strlen( $this -> transfer_path(get_home_path()));
$package['json']['root'] = substr($data['root_path'], $remove_path_size);
*/
if($write_child_files_json)
{
foreach ($files[$i] as $file)
{
$ret_file=$this->get_json_data($file);
if($ret_file['result']==WPVIVID_SUCCESS)
{
$json=$ret_file['json_data'];
$json = json_decode($json, 1);
$package['json']['child_file'][basename($file)]=$json;
}
}
}
if(isset($data['root_flag']))
$package['json']['root_flag'] = $data['root_flag'];
if(isset($data['root_path']))
$package['json']['root_path'] = $data['root_path'];
$package['json']['file']=basename($path);
$package['path'] = $path;
$package['files'] = $files[$i];
$packages[] = $package;
}
}else {
$package = array();
$path = $data['path'].$data['prefix'].'.zip';
if(isset($data['json_info']))
{
$package['json']=$data['json_info'];
}
if($write_child_files_json)
{
foreach ($files[0] as $file)
{
$ret_file=$this->get_json_data($file);
if($ret_file['result']==WPVIVID_SUCCESS)
{
$json=$ret_file['json_data'];
$json = json_decode($json, 1);
$package['json']['child_file'][basename($file)]=$json;
}
}
}
/*
$remove_path_size = strlen( $this -> transfer_path(get_home_path()));
$package['json']['root'] = substr($data['root_path'], $remove_path_size);
*/
if(isset($data['root_flag']))
$package['json']['root_flag'] = $data['root_flag'];
if(isset($data['root_path']))
$package['json']['root_path'] = $data['root_path'];
$package['json']['file']=basename($path);
$package['path'] = $path;
$package['files'] = $files[0];
$packages[] = $package;
}
$ret['packages']=$packages;
$ret['temp_dir']=$temp_dir;
return $ret;
}
public function get_plugin_packages($data)
{
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
$max_size= $data['compress']['max_file_size'];
$max_size = str_replace('M', '', $max_size);
if($max_size==0)
$max_size=200;
$size = intval($max_size) * 1024 * 1024;
$files = $this -> filesplit_plugin($size,$data['files'],false);
$temp_dir = $data['path'].'temp-'.$data['prefix'].DIRECTORY_SEPARATOR;
if(!file_exists($temp_dir))
@mkdir($temp_dir);
$packages = array();
if(sizeof($files) > 1)
{
for($i =0;$i <sizeof($files);$i ++)
{
$package = array();
$path = $data['path'].$data['prefix'].'.part'.sprintf('%03d',($i +1)).'.zip';
if(isset($data['json_info']))
{
$package['json']=$data['json_info'];
}
/*
$remove_path_size = strlen( $this -> transfer_path(get_home_path()));
$package['json']['root'] = substr($data['root_path'], $remove_path_size);
*/
if(isset($data['root_flag']))
$package['json']['root_flag'] = $data['root_flag'];
if(isset($data['root_path']))
$package['json']['root_path'] = $data['root_path'];
$package['json']['file']=basename($path);
$package['path'] = $path;
$package['files'] = $files[$i];
$packages[] = $package;
}
}else {
$package = array();
$path = $data['path'].$data['prefix'].'.zip';
if(isset($data['json_info']))
{
$package['json']=$data['json_info'];
}
/*
$remove_path_size = strlen( $this -> transfer_path(get_home_path()));
$package['json']['root'] = substr($data['root_path'], $remove_path_size);
*/
if(isset($data['root_flag']))
$package['json']['root_flag'] = $data['root_flag'];
if(isset($data['root_path']))
$package['json']['root_path'] = $data['root_path'];
$package['json']['file']=basename($path);
$package['path'] = $path;
$package['files'] = $files[0];
$packages[] = $package;
}
$ret['packages']=$packages;
$ret['temp_dir']=$temp_dir;
return $ret;
}
public function get_upload_packages($data)
{
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
$max_size= $data['compress']['max_file_size'];
$max_size = str_replace('M', '', $max_size);
if($max_size==0)
$max_size=200;
$size = intval($max_size) * 1024 * 1024;
$files = $this -> get_files_cache($size,$data);
$temp_dir = $data['path'].'temp-'.$data['prefix'].DIRECTORY_SEPARATOR;
if(!file_exists($temp_dir))
@mkdir($temp_dir);
$packages = array();
if(sizeof($files) > 1)
{
$i=0;
foreach ($files as $file)
{
$package = array();
$path = $data['path'].$data['prefix'].'.part'.sprintf('%03d',($i +1)).'.zip';
if(isset($data['json_info']))
{
$package['json']=$data['json_info'];
}
/*
$remove_path_size = strlen( $this -> transfer_path(get_home_path()));
$package['json']['root'] = substr($data['root_path'], $remove_path_size);
*/
if(isset($data['root_flag']))
$package['json']['root_flag'] = $data['root_flag'];
if(isset($data['root_path']))
$package['json']['root_path'] = $data['root_path'];
$package['json']['file']=basename($path);
$package['path'] = $path;
$package['files'] = $file;
$packages[] = $package;
$i++;
}
}else {
$package = array();
$path = $data['path'].$data['prefix'].'.zip';
if(isset($data['json_info']))
{
$package['json']=$data['json_info'];
}
/*
$remove_path_size = strlen( $this -> transfer_path(get_home_path()));
$package['json']['root'] = substr($data['root_path'], $remove_path_size);
*/
if(isset($data['root_flag']))
$package['json']['root_flag'] = $data['root_flag'];
if(isset($data['root_path']))
$package['json']['root_path'] = $data['root_path'];
$package['json']['file']=basename($path);
$package['path'] = $path;
$package['files'] = $files[0];
$packages[] = $package;
}
$ret['packages']=$packages;
return $ret;
}
public function compress_additional_database($data){
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Start compressing '.$data['key'],'notice');
$files = $data['files'];
$temp_dir = $data['path'].'temp-'.$data['prefix'].DIRECTORY_SEPARATOR;
if(!file_exists($temp_dir))
@mkdir($temp_dir);
$package_file = array();
$ret['result']=WPVIVID_SUCCESS;
$ret['files']=array();
foreach ($files as $file){
$file_name = $file;
$file_name = str_replace($data['path'], '', $file_name);
$file_name = str_replace('.sql', '', $file_name);
$path = $data['path'].$file_name.'.zip';
if(isset($data['json_info']))
{
$package_file['json']=$data['json_info'];
foreach ($data['sql_file_name'] as $sql_info){
if($file === $sql_info['file_name']){
$package_file['json']['database'] = $sql_info['database'];
}
}
}
if(isset($data['root_path']))
$package['json']['root_path'] = $data['root_path'];
if(isset($data['root_flag']))
$package_file['json']['root_flag'] = $data['root_flag'];
$package_file['json']['file']=basename($path);
$package_file['path'] = $path;
$package_file['files'] = $file;
$wpvivid_plugin->set_time_limit($wpvivid_plugin->current_task['id']);
$zip_ret=$this -> _zip($package_file['path'],$package_file['files'], $data, $package_file['json']);
if($zip_ret['result']==WPVIVID_SUCCESS)
{
$ret['files'][] = $zip_ret['file_data'];
}
else
{
$ret=$zip_ret;
break;
}
}
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing '.$data['key'].' completed','notice');
return $ret;
}
public function compress($data,$write_child_files_json=false)
{
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Start compressing '.$data['key'],'notice');
$files = $this -> filesplit($data['compress']['max_file_size'],$data['files']);
$temp_dir = $data['path'].'temp-'.$data['prefix'].DIRECTORY_SEPARATOR;
if(!file_exists($temp_dir))
@mkdir($temp_dir);
$packages = array();
if(sizeof($files) > 1)
{
for($i =0;$i <sizeof($files);$i ++)
{
$package = array();
$path = $data['path'].$data['prefix'].'.part'.sprintf('%03d',($i +1)).'.zip';
if(isset($data['json_info']))
{
$package['json']=$data['json_info'];
}
/*
$remove_path_size = strlen( $this -> transfer_path(get_home_path()));
$package['json']['root'] = substr($data['root_path'], $remove_path_size);
*/
if(isset($data['root_flag']))
$package['json']['root_flag'] = $data['root_flag'];
if(isset($options['root_path']))
$package['json']['root_path'] = $data['root_path'];
$package['json']['file']=basename($path);
$package['path'] = $path;
$package['files'] = $files[$i];
$packages[] = $package;
}
}else {
$package = array();
$path = $data['path'].$data['prefix'].'.zip';
if(isset($data['json_info']))
{
$package['json']=$data['json_info'];
}
/*
$remove_path_size = strlen( $this -> transfer_path(get_home_path()));
$package['json']['root'] = substr($data['root_path'], $remove_path_size);
*/
if(isset($data['root_flag']))
$package['json']['root_flag'] = $data['root_flag'];
if(isset($options['root_path']))
$package['json']['root_path'] = $data['root_path'];
$package['json']['file']=basename($path);
$package['path'] = $path;
$package['files'] = $files[0];
$packages[] = $package;
}
$ret['result']=WPVIVID_SUCCESS;
$ret['files']=array();
foreach ($packages as $package)
{
if(!empty($package['files']))
{
$wpvivid_plugin->set_time_limit($wpvivid_plugin->current_task['id']);
$zip_ret=$this -> _zip($package['path'],$package['files'], $data,$package['json']);
if($zip_ret['result']==WPVIVID_SUCCESS)
{
$ret['files'][] = $zip_ret['file_data'];
}
else
{
$ret=$zip_ret;
break;
}
}else {
continue;
}
}
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing '.$data['key'].' completed','notice');
return $ret;
}
public function extract($files, $path = '', $option = array())
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
if(!empty($option)){
$GLOBALS['wpvivid_extract_option'] = $option;
}
global $wpvivid_plugin;
//$wpvivid_plugin->restore_data->write_log('start prepare extract','notice');
define(PCLZIP_TEMPORARY_DIR,dirname($path));
$ret['result']=WPVIVID_SUCCESS;
foreach ($files as $file)
{
$wpvivid_plugin->restore_data->write_log('start extracting file:'.$file,'notice');
$archive = new WPvivid_PclZip($file);
$zip_ret = $archive->extract(WPVIVID_PCLZIP_OPT_PATH, $path,WPVIVID_PCLZIP_OPT_REPLACE_NEWER,WPVIVID_PCLZIP_CB_PRE_EXTRACT,'wpvivid_function_pre_extract_callback',WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,16);
if(!$zip_ret)
{
$ret['result']=WPVIVID_FAILED;
$ret['error'] = $archive->errorInfo(true);
$wpvivid_plugin->restore_data->write_log('extract finished:'.wp_json_encode($ret),'notice');
break;
}
else
{
$wpvivid_plugin->restore_data->write_log('extract finished file:'.$file,'notice');
}
}
//$this->restore_data->write_log('extract finished files:'.wp_json_encode($all_files),'notice');
return $ret;
}
public function extract_ex($files,$path = '',$extract_files=array())
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
global $wpvivid_plugin;
//$wpvivid_plugin->restore_data->write_log('start prepare extract','notice');
define(PCLZIP_TEMPORARY_DIR,dirname($path));
$ret['result']=WPVIVID_SUCCESS;
foreach ($files as $file)
{
$wpvivid_plugin->restore_data->write_log('start extracting file:'.$file,'notice');
$wpvivid_plugin->restore_data->write_log('extract child file:'.wp_json_encode($extract_files),'notice');
$archive = new WPvivid_PclZip($file);
$zip_ret = $archive->extract(WPVIVID_PCLZIP_OPT_BY_NAME,$extract_files,WPVIVID_PCLZIP_OPT_PATH, $path,WPVIVID_PCLZIP_OPT_REPLACE_NEWER,WPVIVID_PCLZIP_CB_PRE_EXTRACT,'wpvivid_function_pre_extract_callback',WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,16);
if(!$zip_ret)
{
$ret['result']=WPVIVID_FAILED;
$ret['error'] = $archive->errorInfo(true);
$wpvivid_plugin->restore_data->write_log('extract finished:'.wp_json_encode($ret),'notice');
break;
}
else
{
$wpvivid_plugin->restore_data->write_log('extract finished file:'.$file,'notice');
}
}
//$this->restore_data->write_log('extract finished files:'.wp_json_encode($all_files),'notice');
return $ret;
}
public function extract_by_files($files,$zip,$path = '')
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
define(PCLZIP_TEMPORARY_DIR,$path);
$flag = true;
$table = array();
$archive = new WPvivid_PclZip($zip);
$list = $archive -> listContent();
foreach ($list as $item)
{
if(strstr($item['filename'],WPVIVID_ZIPCLASS_JSONFILE_NAME))
{
$result = $archive->extract(WPVIVID_PCLZIP_OPT_BY_NAME, WPVIVID_ZIPCLASS_JSONFILE_NAME);
if($result)
{
$json = json_decode(file_get_contents(dirname($zip).WPVIVID_ZIPCLASS_JSONFILE_NAME),true);
$path = $json['root_path'];
}
}
}
$str = $archive->extract(WPVIVID_PCLZIP_OPT_PATH, $path, WPVIVID_PCLZIP_OPT_BY_NAME, $files, WPVIVID_PCLZIP_OPT_REPLACE_NEWER,WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,16);
if(!$str){
$flag = false;
$error = $archive->errorInfo(true);
}else{
$success_num = 0;
$error_num = 0;
$last_error = '';
foreach ($str as $item){
if($item['status'] === 'ok'){
$success_num ++;
}else{
$error_num ++;
$last_error = 'restore '.$item['filename'].' failed status:'.$item['status'];
}
}
$table['succeed'] = $success_num;
$table['failed'] = $error_num;
$error = $last_error;
}
if($flag){
return array('result'=>WPVIVID_SUCCESS,'table'=>$table,'error' => $error);
}else{
return array('result'=>'failed','error'=>$error);
}
}
public function get_include_zip($files,$allpackages){
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$i = sizeof($files);
$zips = array();
foreach ( $allpackages as $item){
$archive = new WPvivid_PclZip($item);
$lists = $archive -> listContent();
foreach ($lists as $file){
if($this -> _in_array($file['filename'],$files)){
$zips[$item][] = $file['filename'];
if($i -- === 0)
break 2;
}
}
}
return $zips;
}
public function _zip($name,$files,$options,$json_info=false)
{
$zip_object_class=apply_filters('wpvivid_get_zip_object_class_ex','WPvivid_PclZip_Class',$options);
$zip=new $zip_object_class();
return $zip->zip($name,$files,$options,$json_info);
}
public function listcontent($path){
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$zip = new WPvivid_PclZip($path);
$list = $zip->listContent();
return $list;
}
public function listnum($path , $includeFolder = false){
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$zip = new WPvivid_PclZip($path);
$list = $zip->listContent();
$index = 0;
foreach ($list as $item){
if(!$includeFolder && $item['folder'])
continue;
$index ++;
}
return $index;
}
private function transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode(DIRECTORY_SEPARATOR,$values);
}
public function get_json_data($path, $json_type = 'backup')
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$json_file_name = $json_type === 'backup' ? 'wpvivid_package_info.json' : 'wpvivid_export_package_info.json';
$archive = new WPvivid_PclZip($path);
$list = $archive->listContent();
if($list == false){
return array('result'=>WPVIVID_FAILED,'error'=>$archive->errorInfo(true));
}
else {
$b_exist = false;
foreach ($list as $item) {
if (basename($item['filename']) === $json_file_name) {
$b_exist = true;
$result = $archive->extract(WPVIVID_PCLZIP_OPT_BY_NAME, $json_file_name, WPVIVID_PCLZIP_OPT_EXTRACT_AS_STRING);
if ($result != 0) {
return array('result'=>WPVIVID_SUCCESS,'json_data'=>$result[0]['content']);
} else {
return array('result'=>WPVIVID_FAILED,'error'=>$archive->errorInfo(true));
}
}
}
if(!$b_exist){
return array('result'=>WPVIVID_FAILED,'error'=>'Failed to get json, this may be a old version backup.');
}
}
return array('result'=>WPVIVID_FAILED,'error'=>'Unknown error');
}
public function list_file($path)
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$archive = new WPvivid_PclZip($path);
$list = $archive->listContent();
$files=array();
foreach ($list as $item)
{
if(basename($item['filename'])==='wpvivid_package_info.json')
{
continue;
}
$file['file_name']=$item['filename'];
$files[]=$file;
}
return $files;
}
public function filesplit_plugin($max_file_size,$files,$is_num=true)
{
$packages=array();
if($max_file_size == 0 || empty($max_file_size))
{
$packages[] = $files;
}else{
$folder_num_sum = 0;
$package = array();
if($is_num)
{
foreach ($files as $file)
{
$folder_num=0;
if(is_dir($file))
{
$folder_num=$this->get_folder_file_count($file);
}
else
{
$folder_num_sum+=filesize($file);
}
if($folder_num > $max_file_size)
{
$temp_package[] = $file;
$packages[] = $temp_package;
$temp_package = array();
continue;
}
else
{
$folder_num_sum+=$folder_num;
}
if($folder_num_sum > $max_file_size)
{
$package[] = $file;
$packages[] = $package;
$package = array();
$folder_num_sum=0;
}
else{
$package[] = $file;
}
}
}
else
{
foreach ($files as $file)
{
$folder_num=0;
if(is_dir($file))
{
$folder_num=$this->get_folder_file_size($file);
}
else
{
$folder_num_sum+=filesize($file);
}
if($folder_num > $max_file_size)
{
$temp_package[] = $file;
$packages[] = $temp_package;
$temp_package = array();
continue;
}
else
{
$folder_num_sum+=$folder_num;
}
if($folder_num_sum > $max_file_size)
{
$package[] = $file;
$packages[] = $package;
$package = array();
$folder_num_sum=0;
}
else{
$package[] = $file;
}
}
}
if(!empty($package))
$packages[] = $package;
}
return $packages;
}
public function get_folder_file_count($file)
{
$count=0;
$this->get_folder_file_count_loop($file,$count);
return $count;
}
function get_folder_file_count_loop($path,&$count)
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
$count++;
if(is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
$this->get_folder_file_count_loop($path . DIRECTORY_SEPARATOR . $filename,$count);
}
}
}
if($handler)
@closedir($handler);
}
}
function get_folder_file_size($file)
{
$count=0;
$this->get_folder_file_size_loop($file,$count);
return $count;
}
function get_folder_file_size_loop($path,&$count)
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if(is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
$this->get_folder_file_size_loop($path . DIRECTORY_SEPARATOR . $filename,$count);
}
else
{
$count+=filesize($path . DIRECTORY_SEPARATOR . $filename);
}
}
}
if($handler)
@closedir($handler);
}
}
public function get_root_flag_path($flag)
{
$path='';
if($flag==WPVIVID_BACKUP_ROOT_WP_CONTENT)
{
$path=WP_CONTENT_DIR;
}
else if($flag==WPVIVID_BACKUP_ROOT_CUSTOM)
{
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
}
else if($flag==WPVIVID_BACKUP_ROOT_WP_ROOT)
{
$path=ABSPATH;
}
return $path;
}
public function get_files_cache($size,$data)
{
$number=1;
$cache_perfix = $data['path'].$data['prefix'].'_file_cache_';
$cache_file_handle=false;
$sumsize=0;
if(isset($data['exclude_files_regex']))
$exclude_files_regex=$data['exclude_files_regex'];
else
$exclude_files_regex=array();
if(isset($data['exclude_regex']))
$exclude_regex=$data['exclude_regex'];
else
$exclude_regex=array();
if(isset($data['compress'])&&$data['compress']['exclude_file_size'])
$exclude_file_size=$data['compress']['exclude_file_size'];
else
$exclude_file_size=0;
if(isset($data['skip_files_time']))
{
$skip_files_time=$data['skip_files_time'];
}
else
{
$skip_files_time=0;
}
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('exclude_files_regex:'.wp_json_encode($exclude_files_regex),'notice');
foreach ($data['files'] as $file)
{
$this->get_file_cache($size,$file,$cache_perfix,$cache_file_handle,$number,$sumsize,$exclude_regex,$exclude_files_regex,$exclude_file_size,$skip_files_time);
}
$file_cache=array();
for($i=1;$i<$number+1;$i++)
{
$file_cache[]=$cache_perfix.$i.'.txt';
}
return $file_cache;
}
public function get_file_cache($size,$path,$cache_perfix,&$cache_file_handle,&$number,&$sumsize,$exclude_regex,$exclude_files_regex,$exclude_file_size,$skip_files_time)
{
if(!$cache_file_handle)
{
$cache_file=$cache_perfix.$number.'.txt';
$cache_file_handle=fopen($cache_file,'a');
}
$handler = opendir($path);
if($handler===false)
return;
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if (is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
if ($this->regex_match($exclude_regex, $path . DIRECTORY_SEPARATOR . $filename, 0))
{
$this->get_file_cache($size,$path . DIRECTORY_SEPARATOR . $filename,$cache_perfix,$cache_file_handle,$number,$sumsize,$exclude_regex,$exclude_files_regex,$exclude_file_size,$skip_files_time);
}
}
/*if(is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
$this->get_file_cache($size,$path . DIRECTORY_SEPARATOR . $filename,$cache_perfix,$cache_file_handle,$number,$sumsize,$exclude_regex,$exclude_files_regex,$exclude_file_size,$skip_files_time);
}*/
else
{
if($this->regex_match($exclude_files_regex, $filename, 0))
{
if ($exclude_file_size == 0||(filesize($path . DIRECTORY_SEPARATOR . $filename) < $exclude_file_size * 1024 * 1024))
{
if(is_readable($path . DIRECTORY_SEPARATOR . $filename))
{
if($skip_files_time>0)
{
$file_time=filemtime($path . DIRECTORY_SEPARATOR . $filename);
if($file_time>0&&$file_time>$skip_files_time)
{
$sumsize+=filesize($path . DIRECTORY_SEPARATOR . $filename);
if($sumsize>$size)
{
$number++;
fclose($cache_file_handle);
$cache_file=$cache_perfix.$number.'.txt';
$cache_file_handle=fopen($cache_file,'a');
$line = $path . DIRECTORY_SEPARATOR . $filename.PHP_EOL;
fwrite($cache_file_handle, $line);
$sumsize=filesize($path . DIRECTORY_SEPARATOR . $filename);
}
else
{
$line = $path . DIRECTORY_SEPARATOR . $filename.PHP_EOL;
fwrite($cache_file_handle, $line);
}
}
}
else
{
$sumsize+=filesize($path . DIRECTORY_SEPARATOR . $filename);
if($sumsize>$size)
{
$number++;
fclose($cache_file_handle);
$cache_file=$cache_perfix.$number.'.txt';
$cache_file_handle=fopen($cache_file,'a');
$line = $path . DIRECTORY_SEPARATOR . $filename.PHP_EOL;
fwrite($cache_file_handle, $line);
$sumsize=filesize($path . DIRECTORY_SEPARATOR . $filename);
}
else
{
$line = $path . DIRECTORY_SEPARATOR . $filename.PHP_EOL;
fwrite($cache_file_handle, $line);
}
$files[] = $path . DIRECTORY_SEPARATOR . $filename;
}
}
}
}
}
}
}
if($handler)
@closedir($handler);
}
private function regex_match($regex_array,$string,$mode)
{
if(empty($regex_array))
{
return true;
}
if($mode==0)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return false;
}
}
return true;
}
if($mode==1)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return true;
}
}
return false;
}
return true;
}
public function get_upload_files_from_cache($file)
{
$files=array();
$file = new SplFileObject($file);
$file->seek(0);
$file->setFlags( \SplFileObject::SKIP_EMPTY | \SplFileObject::READ_AHEAD );
while(!$file->eof())
{
$src = $file->fgets();
$src=trim($src,PHP_EOL);
if(empty($src))
continue;
if(!file_exists($src))
{
continue;
}
$files[]=$src;
}
return $files;
}
}
class WPvivid_PclZip_Class
{
public function zip($name,$files,$options,$json_info=false)
{
global $wpvivid_plugin;
if(file_exists($name))
@wp_delete_file($name);
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$archive = new WPvivid_PclZip($name);
if(isset($options['compress']['no_compress']))
{
$no_compress=$options['compress']['no_compress'];
}
else
{
$no_compress=1;
}
if(isset($options['compress']['use_temp_file']))
{
$use_temp_file=1;
}
else
{
$use_temp_file=0;
}
if(isset($options['compress']['use_temp_size']))
{
$use_temp_size=$options['compress']['use_temp_size'];
}
else
{
$use_temp_size=16;
}
if(isset($options['root_path']))
{
$replace_path=$options['root_path'];
}
else if(isset($options['root_flag']))
{
$replace_path=$this->get_root_flag_path($options['root_flag']);
}
else
{
$replace_path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
}
if($json_info!==false)
{
$temp_path = dirname($name).DIRECTORY_SEPARATOR.'wpvivid_package_info.json';
if(file_exists($temp_path))
{
@wp_delete_file($temp_path);
}
$json_info['php_version'] = phpversion();
global $wpdb;
$json_info['mysql_version'] = $wpdb->db_version();
file_put_contents($temp_path,print_r(wp_json_encode($json_info),true));
$archive -> add($temp_path,WPVIVID_PCLZIP_OPT_REMOVE_PATH,dirname($temp_path));
@wp_delete_file($temp_path);
}
$wpvivid_plugin->wpvivid_log->WriteLog('Prepare to zip files. file: '.basename($name),'notice');
/*foreach ($files as $index => $file){
if(!is_dir($file) && filesize($file) === 0){
$wpvivid_plugin->wpvivid_log->WriteLog('Ignore files with size 0. file: '.$file,'notice');
unset($files[$index]);
}
}*/
if($no_compress)
{
if($use_temp_file==1)
{
if($use_temp_size!=0)
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_NO_COMPRESSION,WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,$use_temp_size);
}
else
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_NO_COMPRESSION,WPVIVID_PCLZIP_OPT_TEMP_FILE_ON);
}
}
else
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_NO_COMPRESSION,WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF);
}
}
else
{
if($use_temp_file==1)
{
if($use_temp_size!=0)
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,$use_temp_size);
}
else
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_TEMP_FILE_ON);
}
}
else
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF);
}
}
if(!$ret)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Failed to add zip files, error: '.$archive->errorInfo(true),'notice');
$size=size_format(disk_free_space(dirname($name)),2);
$wpvivid_plugin->wpvivid_log->WriteLog('disk_free_space : '.$size,'notice');
return array('result'=>WPVIVID_FAILED,'error'=>$archive->errorInfo(true));
}
$size=filesize($name);
if($size===false)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Failed to add zip files, error: file not found after backup success','error');
$size=size_format(disk_free_space(dirname($name)),2);
$wpvivid_plugin->wpvivid_log->WriteLog('disk_free_space : '.$size,'notice');
return array('result'=>WPVIVID_FAILED,'error'=>'The file compression failed while backing up becuase of '.$name.' file not found. Please try again. The available disk space: '.$size.'.');
}
else if($size==0)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Failed to add zip files, error: file size 0B after backup success','error');
$size=size_format(disk_free_space(dirname($name)),2);
$wpvivid_plugin->wpvivid_log->WriteLog('disk_free_space : '.$size,'notice');
return array('result'=>WPVIVID_FAILED,'error'=>'The file compression failed while backing up. The size of '.$name.' file is 0. Please make sure there is an enough disk space to backup. Then try again. The available disk space: '.$size.'.');
}
$wpvivid_plugin->wpvivid_log->WriteLog('Adding zip files completed.'.basename($name).', filesize: '.size_format(filesize($name),2),'notice');
$file_data = array();
$file_data['file_name'] = basename($name);
$file_data['size'] = filesize($name);
return array('result'=>WPVIVID_SUCCESS,'file_data'=>$file_data);
}
public function get_root_flag_path($flag)
{
$path='';
if($flag==WPVIVID_BACKUP_ROOT_WP_CONTENT)
{
$path=WP_CONTENT_DIR;
}
else if($flag==WPVIVID_BACKUP_ROOT_CUSTOM)
{
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
}
else if($flag==WPVIVID_BACKUP_ROOT_WP_ROOT)
{
$path=ABSPATH;
}
return $path;
}
}
class WPvivid_PclZip_Class_Ex
{
public function zip($name,$files,$options,$json_info=false)
{
global $wpvivid_plugin;
if(file_exists($name))
@wp_delete_file($name);
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$archive = new WPvivid_PclZip($name);
if(isset($options['compress']['no_compress']))
{
$no_compress=$options['compress']['no_compress'];
}
else
{
$no_compress=1;
}
if(isset($options['compress']['use_temp_file']))
{
$use_temp_file=1;
}
else
{
$use_temp_file=0;
}
if(isset($options['compress']['use_temp_size']))
{
$use_temp_size=$options['compress']['use_temp_size'];
}
else
{
$use_temp_size=16;
}
if(isset($options['root_path']))
{
$replace_path=$options['root_path'];
}
else if(isset($options['root_flag']))
{
$replace_path=$this->get_root_flag_path($options['root_flag']);
}
else
{
$replace_path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
}
if($json_info!==false)
{
$temp_path = dirname($name).DIRECTORY_SEPARATOR.'wpvivid_package_info.json';
if(file_exists($temp_path))
{
@wp_delete_file($temp_path);
}
$json_info['php_version'] = phpversion();
global $wpdb;
$json_info['mysql_version'] = $wpdb->db_version();
file_put_contents($temp_path,print_r(wp_json_encode($json_info),true));
$archive -> add($temp_path,WPVIVID_PCLZIP_OPT_REMOVE_PATH,dirname($temp_path));
@wp_delete_file($temp_path);
}
$wpvivid_plugin->wpvivid_log->WriteLog('Prepare to zip files. file: '.basename($name),'notice');
if($no_compress)
{
if($use_temp_file==1)
{
if($use_temp_size!=0)
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_NO_COMPRESSION,WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,$use_temp_size);
}
else
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_NO_COMPRESSION,WPVIVID_PCLZIP_OPT_TEMP_FILE_ON);
}
}
else
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_NO_COMPRESSION,WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF);
}
}
else
{
if($use_temp_file==1)
{
if($use_temp_size!=0)
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,$use_temp_size);
}
else
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_TEMP_FILE_ON);
}
}
else
{
$ret = $archive -> add($files,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF);
}
}
if(!$ret)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Failed to add zip files, error: '.$archive->errorInfo(true),'notice');
$size=size_format(disk_free_space(dirname($name)),2);
$wpvivid_plugin->wpvivid_log->WriteLog('disk_free_space : '.$size,'notice');
return array('result'=>WPVIVID_FAILED,'error'=>$archive->errorInfo(true));
}
$size=filesize($name);
if($size===false)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Failed to add zip files, error: file not found after backup success','error');
$size=size_format(disk_free_space(dirname($name)),2);
$wpvivid_plugin->wpvivid_log->WriteLog('disk_free_space : '.$size,'notice');
return array('result'=>WPVIVID_FAILED,'error'=>'The file compression failed while backing up becuase of '.$name.' file not found. Please try again. The available disk space: '.$size.'.');
}
else if($size==0)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Failed to add zip files, error: file size 0B after backup success','error');
$size=size_format(disk_free_space(dirname($name)),2);
$wpvivid_plugin->wpvivid_log->WriteLog('disk_free_space : '.$size,'notice');
return array('result'=>WPVIVID_FAILED,'error'=>'The file compression failed while backing up. The size of '.$name.' file is 0. Please make sure there is an enough disk space to backup. Then try again. The available disk space: '.$size.'.');
}
$wpvivid_plugin->wpvivid_log->WriteLog('Adding zip files completed.'.basename($name).', filesize: '.size_format(filesize($name),2),'notice');
$file_data = array();
$file_data['file_name'] = basename($name);
$file_data['size'] = filesize($name);
return array('result'=>WPVIVID_SUCCESS,'file_data'=>$file_data);
}
public function get_root_flag_path($flag)
{
$path='';
if($flag==WPVIVID_BACKUP_ROOT_WP_CONTENT)
{
$path=WP_CONTENT_DIR;
}
else if($flag==WPVIVID_BACKUP_ROOT_CUSTOM)
{
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
}
else if($flag==WPVIVID_BACKUP_ROOT_WP_ROOT)
{
$path=ABSPATH;
}
return $path;
}
}
$wpvivid_old_time=0;
function wpvivid_function_per_add_callback($p_event, &$p_header)
{
if(!file_exists($p_header['filename'])){
return 0;
}
/*if($p_header['size'] === 0){
return 0;
}*/
$path = str_replace('\\','/',WP_CONTENT_DIR);
$content_path = $path.'/';
if(strpos($p_header['filename'], $content_path.'mu-plugins/endurance-browser-cache.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'mu-plugins/endurance-page-cache.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'mu-plugins/endurance-php-edge.php')!==false)
{
return 0;
}
$plugins = substr(WP_PLUGIN_DIR, strpos(WP_PLUGIN_DIR, 'wp-content/'));
if(strpos($p_header['filename'],$plugins.'/wpvivid-backuprestore')!==false)
{
return 0;
}
if(strpos($p_header['filename'],$plugins.'/wpvivid-backup-pro')!==false)
{
return 0;
}
global $wpvivid_old_time;
if(time()-$wpvivid_old_time>30)
{
$wpvivid_old_time=time();
global $wpvivid_plugin;
if(isset($wpvivid_plugin->current_task['id']))
{
$wpvivid_plugin->check_cancel_backup($wpvivid_plugin->current_task['id']);
WPvivid_taskmanager::update_backup_task_status($wpvivid_plugin->current_task['id']);
}
}
return 1;
}
function wpvivid_function_pre_extract_callback($p_event, &$p_header)
{
$plugins = substr(WP_PLUGIN_DIR, strpos(WP_PLUGIN_DIR, 'wp-content/'));
if ( isset( $GLOBALS['wpvivid_extract_option'] ) )
{
$option = $GLOBALS['wpvivid_extract_option'];
if (isset($option['file_type']))
{
if ($option['file_type'] == 'themes')
{
if (isset($option['remove_themes']))
{
foreach ($option['remove_themes'] as $slug => $themes)
{
if (empty($slug))
continue;
if(strpos($p_header['filename'],$plugins.DIRECTORY_SEPARATOR.$slug)!==false)
{
return 0;
}
}
}
}
else if ($option['file_type'] == 'plugin')
{
if (isset($option['remove_plugin']))
{
foreach ($option['remove_plugin'] as $slug => $plugin)
{
if (empty($slug))
continue;
if(strpos($p_header['filename'],$plugins.'/'.$slug)!==false)
{
return 0;
}
}
}
}
}
}
$path = str_replace('\\','/',WP_CONTENT_DIR);
$content_path = $path.'/';
if(strpos($p_header['filename'], $content_path.'advanced-cache.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'db.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'object-cache.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'],$plugins.'/wpvivid-backuprestore')!==false)
{
return 0;
}
if(strpos($p_header['filename'],'wp-config.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'],'wpvivid_package_info.json')!==false)
{
return 0;
}
if(strpos($p_header['filename'],'.htaccess')!==false)
{
return 0;
}
if(strpos($p_header['filename'],'.user.ini')!==false)
{
return 0;
}
if(strpos($p_header['filename'],'wordfence-waf.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'mu-plugins/endurance-browser-cache.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'mu-plugins/endurance-page-cache.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'mu-plugins/endurance-php-edge.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'mu-plugins/wp-stack-cache.php')!==false)
{
return 0;
}
return 1;
} includes/class-wpvivid-tab-page-container.php 0000644 00000023303 15132770567 0015332 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Tab_Page_Container
{
public $tabs;
public $container_id;
public $is_parent_tab=1;
public function __construct( $args = array() )
{
$this->tabs=array();
$this->container_id=uniqid('tab-');
}
public function add_tab($title,$slug,$callback,$args=array())
{
$new_tab['title']=$title;
$new_tab['slug']=$slug;
$new_tab['page']=$callback;
foreach ($args as $key=>$arg)
{
$new_tab[$key]=$arg;
if($key === 'is_parent_tab') {
$this->is_parent_tab = $arg;
}
}
$this->tabs[]=$new_tab;
}
public function set_tab($tabs)
{
foreach ($tabs as $tab)
{
$new_tab['title']=$tab['title'];
$new_tab['slug']=$tab['slug'];
$new_tab['page']=$tab['page'];
$this->tabs[]=$new_tab;
}
}
public function display()
{
$class = '';
?>
<div id="<?php echo esc_attr($this->container_id)?>">
<h2 class="nav-tab-wrapper <?php echo esc_attr($class); ?>" style="padding-bottom:0!important;">
<?php
$this->display_tabs();
?>
</h2>
<?php
if($this->is_parent_tab){
?>
<div style="margin: 10px 0 0 2px;">
<div id="poststuff" style="padding-top: 0;">
<div id="post-body" class="metabox-holder columns-2">
<div id="post-body-content">
<div class="inside" style="margin-top:0;">
<div>
<?php
$this->display_page();
?>
</div>
</div>
</div>
<div id="postbox-container-1" class="postbox-container">
<div class="meta-box-sortables">
<?php
if(has_filter('wpvivid_add_side_bar')){
$side_bar = '1';
}
else{
$side_bar = '0';
}
//$side_bar = '';
if(get_current_screen()->id=='wpvivid-backup_page_wpvivid-staging')
{
do_action('wpvivid_add_staging_side_bar_ex' ,$side_bar, false);
}
else if(get_current_screen()->id=='wpvivid-backup_page_wpvivid-snapshot-ex')
{
do_action('wpvivid_snapshot_add_sidebar_free');
}
else
{
do_action('wpvivid_add_side_bar' ,$side_bar, false);
}
//$side_bar = apply_filters('wpvivid_add_side_bar', $side_bar, false);
//echo $side_bar;
?>
</div>
</div>
</div>
<br class="clear">
</div>
</div>
<?php
}
else{
?>
<div>
<?php
$this->display_page();
?>
</div>
<?php
}
?>
</div>
<script>
jQuery('#<?php echo esc_attr($this->container_id)?>').on("click",".<?php echo esc_attr($this->container_id)?>-tab",function()
{
jQuery('#<?php echo esc_attr($this->container_id)?>').find( '.<?php echo esc_attr($this->container_id)?>-tab' ).each(function()
{
jQuery(this).removeClass( "nav-tab-active" );
});
jQuery('#<?php echo esc_attr($this->container_id)?>').find( '.<?php echo esc_attr($this->container_id)?>-content' ).each(function()
{
jQuery(this).hide();
});
var id=jQuery(this).attr('id');
id= id.substr(12);
jQuery("#wpvivid_page_"+id).show();
jQuery(this).addClass( "nav-tab-active" );
});
jQuery('#<?php echo esc_attr($this->container_id)?>').on("click",".nav-tab-delete-img",function(event)
{
event.stopPropagation();
var redirect=jQuery(this).attr('redirect');
jQuery(this).parent().hide();
jQuery('#<?php echo esc_attr($this->container_id)?>').find( '.<?php echo esc_attr($this->container_id)?>-tab' ).each(function()
{
jQuery(this).removeClass( "nav-tab-active" );
});
jQuery('#<?php echo esc_attr($this->container_id)?>').find( '.<?php echo esc_attr($this->container_id)?>-content' ).each(function()
{
jQuery(this).hide();
});
jQuery("#wpvivid_page_"+redirect).show();
jQuery("#wpvivid_tab_"+redirect).addClass( "nav-tab-active" );
//jQuery(this).addClass( "nav-tab-active" );
});
jQuery(document).ready(function($)
{
jQuery(document).on('<?php echo esc_attr($this->container_id)?>-show', function(event,id,redirect)
{
jQuery('#<?php echo esc_attr($this->container_id)?>').find( '.<?php echo esc_attr($this->container_id)?>-tab' ).each(function()
{
jQuery(this).removeClass( "nav-tab-active" );
});
jQuery('#<?php echo esc_attr($this->container_id)?>').find( '.<?php echo esc_attr($this->container_id)?>-content' ).each(function()
{
jQuery(this).hide();
});
jQuery("#wpvivid_page_"+id).show();
jQuery("#wpvivid_tab_"+id).show();
jQuery("#wpvivid_tab_"+id).find( '.nav-tab-delete-img' ).each(function()
{
jQuery(this).attr('redirect',redirect);
});
jQuery("#wpvivid_tab_"+id).addClass( "nav-tab-active" );
var top = jQuery("#wpvivid_tab_"+id).offset().top-jQuery("#wpvivid_tab_"+id).height();
jQuery('html, body').animate({scrollTop:top}, 'slow');
});
});
</script>
<?php
}
public function display_tabs()
{
$first=true;
foreach ($this->tabs as $tab)
{
$class='nav-tab '.$this->container_id.'-tab';
if($first)
{
$class.=' nav-tab-active';
$first=false;
}
$style='cursor:pointer;';
if(isset($tab['hide']))
{
$style.=' display: none';
}
if(isset($tab['can_delete']))
{
$class.=' delete';
}
if(isset($tab['transparency']))
{
$class.=' wpvivid-transparency-tab';
}
echo '<a id="wpvivid_tab_'.esc_attr($tab['slug']).'" class="'.esc_attr($class).'" style="'.esc_attr($style).'">';
if(isset($tab['can_delete']))
{
echo '<div style="margin-right: 15px;">'.esc_html($tab['title']).'</div>';
if(isset($tab['redirect']))
{
echo '<div class="nav-tab-delete-img" redirect="'.esc_url($tab['redirect']).'">
<img src="'.esc_url( WPVIVID_PLUGIN_URL.'/admin/partials/images/delete-tab.png' ).'" style="vertical-align:middle; cursor:pointer;">
</div>';
}
else
{
echo '<div class="nav-tab-delete-img">
<img src="'.esc_url( WPVIVID_PLUGIN_URL.'/admin/partials/images/delete-tab.png' ).'" style="vertical-align:middle; cursor:pointer;">
</div>';
}
}
else
{
echo esc_html($tab['title']);
}
echo '</a>';
}
}
public function display_page()
{
$first=true;
foreach ($this->tabs as $tab)
{
//delete
$style='display: none;';
if($first)
{
if(isset($tab['hide']))
{
}
else
{
$style='';
$first=false;
}
}
$class=$this->container_id.'-content';
echo '<div id="wpvivid_page_'.esc_attr($tab['slug']).'" class="'.esc_attr($class).'" style="'.esc_attr($style).'">';
call_user_func($tab['page']);
echo '</div>';
}
}
} includes/class-wpvivid.php 0000644 00001175761 15132770567 0011715 0 ustar 00 <?php
/**
* The file that defines the core plugin class
*
* A class definition that includes attributes and functions used across both the
* public-facing side of the site and the admin area.
*
* @link https://wpvivid.com
* @since 0.9.1
*
* @package wpvivid
* @subpackage wpvivid/includes
*/
/**
* The core plugin class.
*
* This is used to define internationalization, admin-specific hooks, and
* public-facing site hooks.
*
* Also maintains the unique identifier of this plugin as well as the current
* version of the plugin.
*
* @since 0.9.1
* @package wpvivid
* @subpackage wpvivid/includes
* @author wpvivid team
*/
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid
{
protected $plugin_name;
protected $version;
public $wpvivid_log;
public $wpvivid_download_log;
public $current_task;
public $updater;
public $remote_collection;
public $function_realize;
public $end_shutdown_function;
public $restore_data;
public $migrate;
public $backup_uploader;
public $admin;
public $interface_mainwp;
public $staging;
public $backup2;
public function __construct()
{
$this->version = WPVIVID_PLUGIN_VERSION;
$this->plugin_name = WPVIVID_PLUGIN_SLUG;
$this->end_shutdown_function = false;
$this->restore_data=false;
$this->remote_collection=false;
add_action('plugins_loaded', array($this, 'load_remote_storage'),10);
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-setting.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-tools.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-schedule.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-taskmanager.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-backuplist.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-public-interface.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-crypt.php';
if(!$this->wpvivid_check_staging_pro_active())
{
$this->staging=new WPvivid_Staging_Free();
}
$this->init_cron();
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-backup2.php';
$this->backup2=new WPvivid_Backup_2();
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-restore2.php';
new WPvivid_Restore_2();
include_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-send-to-site.php';
new WPvivid_Send_to_site();
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-log.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-error-log.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-backup.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-upload.php';
$this->wpvivid_log=new WPvivid_Log();
$this->wpvivid_download_log=new WPvivid_Log();
add_action('init', array($this, 'init_pclzip_tmp_folder'));
if(is_admin())
{
$this->load_admin();
$this->set_locale();
}
add_filter('wpvivid_get_oldest_backup_ids', array($this, 'get_oldest_backup_ids'), 10, 2);
add_filter('wpvivid_check_backup_completeness', array($this, 'check_backup_completeness'), 10, 2);
/*
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-log.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-error-log.php';
$this->load_dependencies();
$this->wpvivid_log=new WPvivid_Log();
$this->wpvivid_download_log=new WPvivid_Log();
//Load dependent files
//A flag to determine whether plugin had been initialized
$init=get_option('wpvivid_init', 'not init');
if($init=='not init')
{
//Initialization settings
WPvivid_Setting::init_option();
WPvivid_Setting::update_option('wpvivid_init','init');
}
$wpvivid_remote_init=get_option('wpvivid_remote_init', 'not init');
if($wpvivid_remote_init=='not init'){
$this->init_remote_option();
WPvivid_Setting::update_option('wpvivid_remote_init','init');
}
*/
}
public function load_admin()
{
require_once WPVIVID_PLUGIN_DIR . '/admin/class-wpvivid-admin.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-tab-page-container.php' ;
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-downloader.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-mail-report.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-function-realize.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-backup-uploader.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-migrate.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-db-method.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-additional-db-method.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-export-import.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-exporter.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-importer.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-interface-mainwp.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/upload-cleaner/class-wpvivid-uploads-cleaner.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/snapshot/class-wpvivid-snapshot.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-restore-data.php';
$this->function_realize=new WPvivid_Function_Realize();
$this->migrate=new WPvivid_Migrate();
$this->backup_uploader=new Wpvivid_BackupUploader();
$this->interface_mainwp = new WPvivid_Interface_MainWP();
$export_import = new WPvivid_Export_Import();
$cleaner=new WPvivid_Uploads_Cleaner();
new WPvivid_Snapshot_Ex();
$this->admin = new WPvivid_Admin($this->get_plugin_name(), $this->get_version());
add_filter('wpvivid_pre_add_remote',array($this, 'pre_add_remote'),10,2);
add_filter('wpvivid_get_log_list', array( $this, 'wpvivid_get_log_list' ), 10);
add_action('wpvivid_get_log_list_output', array( $this, 'wpvivid_get_log_list_output' ));
//add_action('plugins_loaded', array($this, 'load_remote_storage'),10);
$this->load_ajax_hook_for_admin();
add_filter('wpvivid_add_backup_list', array( $this, 'wpvivid_add_backup_list' ), 10, 3);
add_action('wpvivid_add_backup_list_output', array( $this, 'wpvivid_add_backup_list_output' ), 10);
add_filter('wpvivid_add_remote_storage_list', array( $this, 'wpvivid_add_remote_storage_list' ), 10);
add_filter('wpvivid_schedule_add_remote_pic', array( $this, 'wpvivid_schedule_add_remote_pic' ), 10);
add_filter('wpvivid_get_remote_directory', array( $this, 'wpvivid_get_remote_directory' ), 10);
add_filter('wpvivid_get_last_backup_message', array( $this, 'wpvivid_get_last_backup_message' ), 10);
add_action('wpvivid_get_last_backup_message_output', array( $this, 'wpvivid_get_last_backup_message_output' ), 10);
add_filter('wpvivid_schedule_local_remote', array( $this, 'wpvivid_schedule_local_remote' ), 10);
add_filter('wpvivid_remote_storage', array( $this, 'wpvivid_remote_storage'), 10);
add_filter('wpvivid_add_remote_notice', array($this, 'wpvivid_add_remote_notice'), 10, 2);
add_filter('wpvivid_set_general_setting', array($this, 'wpvivid_set_general_setting'), 10, 3);
add_action('wpvivid_handle_backup_succeed',array($this,'wpvivid_handle_backup_succeed'),10);
add_action('wpvivid_handle_upload_succeed',array($this,'wpvivid_handle_backup_succeed'),10);
add_action('wpvivid_handle_upload_succeed',array($this,'wpvivid_mark_task'),20);
add_action('wpvivid_handle_backup_succeed',array($this,'wpvivid_mark_task'),20);
add_action('wpvivid_handle_backup_failed',array($this,'wpvivid_handle_backup_failed'),9, 2);
add_action('wpvivid_handle_upload_succeed',array($this,'wpvivid_deal_upload_succeed'),9);
add_action('wpvivid_handle_backup_failed',array($this,'wpvivid_mark_task'),20);
add_action('wpvivid_before_setup_page',array($this,'clean_cache'));
add_filter('wpvivid_check_type_database', array($this, 'wpvivid_check_type_database'), 10, 2);
add_filter('wpvivid_set_mail_subject', array($this, 'set_mail_subject'), 10, 2);
add_filter('wpvivid_set_mail_body', array($this, 'set_mail_body'), 10, 2);
add_filter('wpvivid_get_mainwp_sync_data', array($this, 'get_mainwp_sync_data'), 10);
//
add_filter('wpvivid_get_zip_object_class_ex',array($this, 'get_zip_object_class'));
}
public function init_cron()
{
$schedule=new WPvivid_Schedule();
//add_action(WPVIVID_MAIN_SCHEDULE_EVENT,array( $this,'main_schedule'));
add_action(WPVIVID_RESUME_SCHEDULE_EVENT,array( $this,'resume_schedule'));
add_action(WPVIVID_CLEAN_BACKING_UP_DATA_EVENT,array($this,'clean_backing_up_data_event'));
add_action(WPVIVID_CLEAN_BACKUP_RECORD_EVENT,array($this,'clean_backup_record_event'));
//add_clean_event
add_action(WPVIVID_TASK_MONITOR_EVENT,array( $this,'task_monitor'));
add_filter('cron_schedules',array( $schedule,'wpvivid_cron_schedules'),99);
add_filter('wpvivid_schedule_time', array($schedule, 'output'));
}
private function load_dependencies()
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-taskmanager.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-downloader.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-mail-report.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-function-realize.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-upload.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-backup-uploader.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-crypt.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-migrate.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-db-method.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-public-interface.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-additional-db-method.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-export-import.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-exporter.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-importer.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-interface-mainwp.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/upload-cleaner/class-wpvivid-uploads-cleaner.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/snapshot/class-wpvivid-snapshot.php';
$this->function_realize=new WPvivid_Function_Realize();
$this->migrate=new WPvivid_Migrate();
$this->backup_uploader=new Wpvivid_BackupUploader();
$this->interface_mainwp = new WPvivid_Interface_MainWP();
$send_to_site=new WPvivid_Send_to_site();
$export_import = new WPvivid_Export_Import();
$cleaner=new WPvivid_Uploads_Cleaner();
if(!$this->wpvivid_check_staging_pro_active())
{
$this->staging=new WPvivid_Staging_Free();
}
new WPvivid_Snapshot_Ex();
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-backup2.php';
$this->backup2=new WPvivid_Backup_2();
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-restore2.php';
new WPvivid_Restore_2();
}
public function wpvivid_check_staging_pro_active()
{
if ( ! function_exists( 'is_plugin_active' ) )
{
include_once(ABSPATH.'wp-admin/includes/plugin.php');
}
if(is_plugin_active('wpvivid-staging/wpvivid-staging.php'))
{
return true;
}
else
{
return false;
}
}
public function init_pclzip_tmp_folder()
{
if (!defined('PCLZIP_TEMPORARY_DIR')) {
$backupdir=WPvivid_Setting::get_backupdir();
define( 'PCLZIP_TEMPORARY_DIR', WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backupdir.DIRECTORY_SEPARATOR );
}
}
public function load_remote_storage()
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-remote-collection.php';
$this->remote_collection=new WPvivid_Remote_collection();
}
private function set_locale()
{
require_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-i18n.php';
$plugin_i18n = new WPvivid_i18n();
add_action('init',array( $plugin_i18n,'load_plugin_textdomain'));
}
public function pre_add_remote($remote,$id)
{
unset($remote['default']);
return $remote;
}
public function wpjam_pre_update_option_cache($value, $option)
{
wp_cache_delete('notoptions', 'options');
wp_cache_delete('alloptions', 'options');
wp_cache_delete($option, 'options');
return $value;
}
public function load_ajax_hook_for_admin()
{
//Add remote storage
add_action('wp_ajax_wpvivid_add_remote',array( $this,'add_remote'));
//Delete remote storage
add_action('wp_ajax_wpvivid_delete_remote',array( $this,'delete_remote'));
//Retrieve remote storage
add_action('wp_ajax_wpvivid_retrieve_remote',array( $this,'retrieve_remote'));
//Edit remote storage
add_action('wp_ajax_wpvivid_edit_remote',array( $this,'edit_remote'));
//List exist remote
add_action('wp_ajax_wpvivid_list_remote',array( $this,'list_remote'));
//Test remote connection
add_action('wp_ajax_wpvivid_test_remote_connection',array( $this,'test_remote_connection'));
//Start backup
add_action('wp_ajax_wpvivid_prepare_backup',array( $this,'prepare_backup'));
add_action('wp_ajax_wpvivid_delete_ready_task',array($this,'delete_ready_task'));
add_action('wp_ajax_wpvivid_backup_now',array( $this,'backup_now'));
//Cancel backup
add_action('wp_ajax_wpvivid_backup_cancel',array( $this,'backup_cancel'));
//List backup record
add_action('wp_ajax_wpvivid_get_backup_list',array( $this,'get_backup_list'));
//View backup record log file
add_action('wp_ajax_wpvivid_view_backup_log',array( $this,'view_backup_log'));
//View log file of the backup task
add_action('wp_ajax_wpvivid_view_backup_task_log',array( $this,'view_backup_task_log'));
//List all logs
add_action('wp_ajax_wpvivid_get_log_list',array( $this,'get_log_list'));
//View logs
add_action('wp_ajax_wpvivid_view_log',array( $this,'view_log'));
//Prepare download backup files
add_action('wp_ajax_wpvivid_prepare_download_backup',array( $this,'prepare_download_backup'));
//Get download progress
add_action('wp_ajax_wpvivid_get_download_progress',array($this,'get_download_progress'));
//Download backup from site
add_action('wp_ajax_wpvivid_download_backup',array( $this,'download_backup'));
//Delete backup record
add_action('wp_ajax_wpvivid_delete_backup',array( $this,'delete_backup'));
//Delete backup records
add_action('wp_ajax_wpvivid_delete_backup_array',array( $this,'delete_backup_array'));
//
add_action('wp_ajax_wpvivid_init_download_page',array( $this,'init_download_page'));
//Download backuplist change page
add_action('wp_ajax_wpvivid_get_download_page_ex',array($this,'get_download_page_ex'));
//Set security lock for backup record
add_action('wp_ajax_wpvivid_set_security_lock',array( $this,'set_security_lock'));
//Delete task
add_action('wp_ajax_wpvivid_delete_task',array( $this,'delete_task'));
//Get backup schedule data
add_action('wp_ajax_wpvivid_get_schedule',array( $this,'get_schedule'));
//Get last backup information
add_action('wp_ajax_wpvivid_get_last_backup',array( $this,'get_last_backup'));
//Get settings
add_action('wp_ajax_wpvivid_get_setting',array( $this,'get_setting'));
add_action('wp_ajax_wpvivid_get_general_setting',array( $this,'get_general_setting'));
//Update settings
add_action('wp_ajax_wpvivid_update_setting',array( $this,'update_setting'));
add_action('wp_ajax_wpvivid_set_general_setting',array( $this,'set_general_setting'));
add_action('wp_ajax_wpvivid_set_schedule',array( $this,'set_schedule' ));
//Export settings
add_action('wp_ajax_wpvivid_export_setting',array( $this,'export_setting'));
//Import settings
add_action('wp_ajax_wpvivid_import_setting',array( $this,'import_setting'));
//Send test mail
add_action('wp_ajax_wpvivid_test_send_mail',array( $this,'test_send_mail'));
//Send debug mail
add_action('wp_ajax_wpvivid_create_debug_package',array( $this,'create_debug_package'));
//Get backup local storage path
add_action('wp_ajax_wpvivid_get_dir',array( $this,'get_dir'));
//Get Web-server disk space in use
add_action('wp_ajax_wpvivid_junk_files_info',array( $this,'junk_files_info'));
add_action('wp_ajax_wpvivid_clean_local_storage',array( $this,'clean_local_storage'));
add_action('wp_ajax_wpvivid_get_out_of_date_info',array($this,'get_out_of_date_info'));
add_action('wp_ajax_wpvivid_clean_out_of_date_backup',array($this,'clean_out_of_date_backup'));
//Prepare backup files for restore
add_action('wp_ajax_wpvivid_prepare_restore',array( $this,'prepare_restore'));
//Download backup files for restore
add_action('wp_ajax_wpvivid_download_restore',array( $this,'download_restore_file'));
//
add_action('wp_ajax_wpvivid_init_restore_page',array( $this,'init_restore_page'));
//
add_action('wp_ajax_wpvivid_delete_last_restore_data',array( $this,'delete_last_restore_data'));
//
//start restore
add_action('wp_ajax_wpvivid_restore',array( $this,'restore'));
add_action('wp_ajax_wpvivid_get_restore_progress',array( $this,'get_restore_progress'));
add_action('wp_ajax_wpvivid_get_download_restore_progress',array( $this,'download_restore_progress'));
add_action('wp_ajax_wpvivid_check_download_has_zero_date', array( $this, 'download_check_has_zero_date' ));
//When restoring the database use wp_ajax_nopriv_
add_action('wp_ajax_nopriv_wpvivid_restore',array( $this,'restore'));
add_action('wp_ajax_nopriv_wpvivid_get_restore_progress',array( $this,'get_restore_progress'));
add_action('wp_ajax_wpvivid_list_tasks',array( $this,'list_tasks'));
//View last backup record log
add_action('wp_ajax_wpvivid_read_last_backup_log',array( $this,'read_last_backup_log'));
//Set default remote storage when backing up
add_action('wp_ajax_wpvivid_set_default_remote_storage',array( $this,'set_default_remote_storage'));
//Get default remote storage when backing up
add_action('wp_ajax_wpvivid_get_default_remote_storage',array( $this,'get_default_remote_storage'));
add_action('wp_ajax_wpvivid_need_review',array( $this,'need_review'));
add_action('wp_ajax_wpvivid_send_debug_info',array($this,'wpvivid_send_debug_info'));
add_action('wp_ajax_wpvivid_get_ini_memory_limit',array($this,'get_ini_memory_limit'));
add_action('wp_ajax_wpvivid_get_restore_file_is_migrate', array($this, 'get_restore_file_is_migrate'));
add_action('wp_ajax_wpvivid_check_remote_alias_exist', array($this, 'check_remote_alias_exist'));
add_action('wp_ajax_wpvivid_task_monitor', array($this, 'task_monitor_ex'));
add_action('wp_ajax_wpvivid_amazons3_notice', array($this, 'amazons3_notice'));
add_action('wp_ajax_wpvivid_hide_mainwp_tab_page', array($this, 'hide_mainwp_tab_page'));
add_action('wp_ajax_wpvivid_hide_wp_cron_notice', array($this, 'hide_wp_cron_notice'));
//wpvivid_task_monitor
//download backup by mainwp
add_action('wp_ajax_wpvivid_download_backup_mainwp', array($this, 'download_backup_mainwp'));
}
public function get_plugin_name()
{
return $this->plugin_name;
}
public function get_version()
{
return $this->version;
}
/**
* Prepare backup include what you want to backup,where you want to store.
*
*When prepare backup finished,you can use backup_now start a backup task.
*
* @since 0.9.1
*/
public function prepare_backup()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$this->end_shutdown_function=false;
register_shutdown_function(array($this,'deal_prepare_shutdown_error'));
try
{
if(isset($_POST['backup'])&&!empty($_POST['backup']))
{
$json = sanitize_text_field($_POST['backup']);
$json = stripslashes($json);
$backup_options = json_decode($json, true);
if (is_null($backup_options))
{
$this->end_shutdown_function=true;
die();
}
$backup_options = apply_filters('wpvivid_custom_backup_options', $backup_options);
if(!isset($backup_options['type']))
{
$backup_options['type']='Manual';
$backup_options['action']='backup';
}
$ret = $this->check_backup_option($backup_options, $backup_options['type']);
if($ret['result']!=WPVIVID_SUCCESS)
{
$this->end_shutdown_function=true;
echo wp_json_encode($ret);
die();
}
$ret=$this->pre_backup($backup_options);
if($ret['result']=='success')
{
//Check the website data to be backed up
/*
$ret['check']=$this->check_backup($ret['task_id'],$backup_options);
if(isset($ret['check']['result']) && $ret['check']['result'] == WPVIVID_FAILED)
{
$this->end_shutdown_function=true;
echo wp_json_encode(array('result' => WPVIVID_FAILED,'error' => $ret['check']['error']));
die();
}*/
$html = '';
$html = apply_filters('wpvivid_add_backup_list', $html);
$ret['html'] = $html;
}
$this->end_shutdown_function=true;
echo wp_json_encode($ret);
die();
}
}
catch (Exception $error)
{
$this->end_shutdown_function=true;
$ret['result']='failed';
$message = 'An exception has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
$ret['error'] = $message;
$id=uniqid('wpvivid-');
$log_file_name=$id.'_backup';
if(!class_exists('WPvivid_Log'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-log.php';
}
$log=new WPvivid_Log();
$log->CreateLogFile($log_file_name,'no_folder','backup');
$log->WriteLog($message,'notice');
$log->CloseFile();
WPvivid_error_log::create_error_log($log->log_file);
error_log($message);
echo wp_json_encode($ret);
die();
}
}
public function deal_prepare_shutdown_error()
{
if($this->end_shutdown_function==false)
{
$last_error = error_get_last();
if (!empty($last_error) && !in_array($last_error['type'], array(E_NOTICE,E_WARNING,E_USER_NOTICE,E_USER_WARNING,E_DEPRECATED), true)) {
$error = $last_error;
} else {
$error = false;
}
$ret['result'] = 'failed';
if ($error === false) {
$ret['error'] = 'unknown Error';
} else {
$ret['error'] = 'type: '. $error['type'] . ', ' . $error['message'] . ' file:' . $error['file'] . ' line:' . $error['line'];
error_log($ret['error']);
}
$id = uniqid('wpvivid-');
$log_file_name = $id . '_backup';
if(!class_exists('WPvivid_Log'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-log.php';
}
$log = new WPvivid_Log();
$log->CreateLogFile($log_file_name, 'no_folder', 'backup');
$log->WriteLog($ret['error'], 'notice');
$log->CloseFile();
WPvivid_error_log::create_error_log($log->log_file);
echo wp_json_encode($ret);
die();
}
}
public function check_backup_option($data, $backup_method = 'Manual')
{
$ret['result']=WPVIVID_SUCCESS;
add_filter('wpvivid_check_backup_options_valid',array($this, 'check_backup_options_valid'),10,3);
$ret=apply_filters('wpvivid_check_backup_options_valid',$ret,$data,$backup_method);
return $ret;
}
public function check_backup_options_valid($ret,$data,$backup_method)
{
$ret['result']=WPVIVID_FAILED;
if(!isset($data['backup_files']))
{
$ret['error']=__('A backup type is required.', 'wpvivid-backuprestore');
return $ret;
}
$data['backup_files']=sanitize_text_field($data['backup_files']);
if(empty($data['backup_files']))
{
$ret['error']=__('A backup type is required.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['local']) && !isset($data['remote']))
{
$ret['error']=__('Choose at least one storage location for backups.', 'wpvivid-backuprestore');
return $ret;
}
$data['local']=sanitize_text_field($data['local']);
$data['remote']=sanitize_text_field($data['remote']);
if(empty($data['local']) && empty($data['remote']))
{
$ret['error']=__('Choose at least one storage location for backups.', 'wpvivid-backuprestore');
return $ret;
}
if($backup_method == 'Manual')
{
if ($data['remote'] === '1')
{
$remote_storage = WPvivid_Setting::get_remote_options();
if ($remote_storage == false)
{
$ret['error'] = __('There is no default remote storage configured. Please set it up first.', 'wpvivid-backuprestore');
return $ret;
}
}
}
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
/**
* Delete tasks had [ready] status.
*
*When prepare backup go wrong,may retain some task we don't need.Delete them.
*
* @since 0.9.3
*/
public function delete_ready_task()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
WPvivid_taskmanager::delete_ready_task();
$ret['result'] = 'success';
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
/**
* Start a backup task init by prepare_backup.
*
* @since 0.9.1
*/
public function backup_now()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (!isset($_POST['task_id']) || empty($_POST['task_id']) || !is_string($_POST['task_id'])) {
$ret['result'] = 'failed';
$ret['error'] = __('Error occurred while parsing the request data. Please try to run backup again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$task_id = sanitize_key($_POST['task_id']);
//Start backup site
if (WPvivid_taskmanager::is_tasks_backup_running()) {
$ret['result'] = 'failed';
$ret['error'] = __('A task is already running. Please wait until the running task is complete, and try again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
//flush buffer
$this->flush($task_id);
$task_msg = WPvivid_taskmanager::get_task($task_id);
$this->update_last_backup_time($task_msg);
$this->backup($task_id);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
/**
* View backup record logs.
*
* @since 0.9.1
*/
public function view_backup_log()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
if (isset($_POST['id']) && !empty($_POST['id']) && is_string($_POST['id']))
{
$backup_id = sanitize_key($_POST['id']);
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
if (!$backup)
{
$json['result'] = 'failed';
$json['error'] = __('Retrieving the backup information failed while showing log. Please try again later.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
if (!file_exists($backup['log']))
{
$json['result'] = 'failed';
$json['error'] = __('The log not found.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$file = fopen($backup['log'], 'r');
if (!$file)
{
$json['result'] = 'failed';
$json['error'] = __('Unable to open the log file.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$buffer = '';
while (!feof($file))
{
$buffer .= fread($file, 1024);
}
fclose($file);
$json['result'] = 'success';
$json['data'] = $buffer;
echo wp_json_encode($json);
} else {
$json['result'] = 'failed';
$json['error'] = __('Reading the log failed. Please try again.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
}
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
/**
* View last backup record logs.
*
* @since 0.9.1
*/
public function read_last_backup_log()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (!isset($_POST['log_file_name']) || empty($_POST['log_file_name']) || !is_string($_POST['log_file_name'])) {
$json['result'] = 'failed';
$json['error'] = __('Reading the log failed. Please try again.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$option = sanitize_text_field($_POST['log_file_name']);
$log_file_name = $this->wpvivid_log->GetSaveLogFolder() . $option . '_log.txt';
if (!file_exists($log_file_name)) {
$json['result'] = 'failed';
$json['error'] = __('The log not found.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$file = fopen($log_file_name, 'r');
if (!$file) {
$json['result'] = 'failed';
$json['error'] = __('Unable to open the log file.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$buffer = '';
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
$json['result'] = 'success';
$json['data'] = $buffer;
echo wp_json_encode($json);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
/**
* View logs of the backup task.
*
* @since 0.9.1
*/
public function view_backup_task_log()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_POST['id']) && !empty($_POST['id']) && is_string($_POST['id'])) {
$backup_task_id = sanitize_key($_POST['id']);
$option = WPvivid_taskmanager::get_task_options($backup_task_id, 'log_file_name');
if (!$option) {
$json['result'] = 'failed';
$json['error'] = __('Retrieving the backup information failed while showing log. Please try again later.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$log_file_name = $this->wpvivid_log->GetSaveLogFolder() . $option . '_log.txt';
if (!file_exists($log_file_name)) {
$json['result'] = 'failed';
$json['error'] = __('The log not found.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$file = fopen($log_file_name, 'r');
if (!$file) {
$json['result'] = 'failed';
$json['error'] = __('Unable to open the log file.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$buffer = '';
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
$json['result'] = 'success';
$json['data'] = $buffer;
echo wp_json_encode($json);
} else {
$json['result'] = 'failed';
$json['error'] = __('Reading the log failed. Please try again.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
/**
* Cancel a backup task.
*
* @since 0.9.1
*/
public function backup_cancel()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
/*if (isset($_POST['task_id']) && !empty($_POST['task_id']) && is_string($_POST['task_id'])) {
$task_id = sanitize_key($_POST['task_id']);
$json = $this->function_realize->_backup_cancel($task_id);
echo wp_json_encode($json);
}*/
$json = $this->function_realize->_backup_cancel();
echo wp_json_encode($json);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function main_schedule($schedule_id='')
{
//get backup options
do_action('wpvivid_set_current_schedule_id', $schedule_id);
$this->end_shutdown_function=false;
register_shutdown_function(array($this,'deal_prepare_shutdown_error'));
$schedule_options=WPvivid_Schedule::get_schedule($schedule_id);
if(empty($schedule_options))
{
$this->end_shutdown_function=true;
die();
}
try
{
$schedule_options['backup']['local'] = strval($schedule_options['backup']['local']);
$schedule_options['backup']['remote'] = strval($schedule_options['backup']['remote']);
$schedule_options['backup']['ismerge'] = strval($schedule_options['backup']['ismerge']);
$schedule_options['backup']['lock'] = strval($schedule_options['backup']['lock']);
$ret = $this->check_backup_option($schedule_options['backup'], 'Cron');
if ($ret['result'] != WPVIVID_SUCCESS)
{
$this->end_shutdown_function=true;
//echo wp_json_encode($ret);
die();
}
if(!isset($schedule_options['backup']['type']))
{
$schedule_options['backup']['type']='Cron';
$schedule_options['backup']['action']='backup';
}
$ret = $this->pre_backup($schedule_options['backup']);
if ($ret['result'] == 'success') {
//Check the website data to be backed up.
//$this->check_backup($ret['task_id'], $schedule_options['backup']);
//flush buffer
$this->flush($ret['task_id']);
//start backup task.
$task_msg = WPvivid_taskmanager::get_task($ret['task_id']);
$this->update_last_backup_time($task_msg);
$this->backup($ret['task_id']);
}
$this->end_shutdown_function=true;
die();
}
catch (Exception $error)
{
$this->end_shutdown_function=true;
$ret['result']='failed';
$message = 'An exception has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
$ret['error'] = $message;
$id=uniqid('wpvivid-');
$log_file_name=$id.'_backup';
if(!class_exists('WPvivid_Log'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-log.php';
}
$log=new WPvivid_Log();
$log->CreateLogFile($log_file_name,'no_folder','backup');
$log->WriteLog($message,'notice');
$log->CloseFile();
WPvivid_error_log::create_error_log($log->log_file);
error_log($message);
//echo wp_json_encode($ret);
die();
}
}
/**
* Resume backup schedule.
*
* Resume a backup task.
*
* @var string $task_id backup task id
*
* @since 0.9.1
*/
public function resume_schedule($task_id='0')
{
if($task_id=='0')
{
die();
}
$task=WPvivid_taskmanager::get_task($task_id);
if(!$task)
{
die();
}
if (WPvivid_taskmanager::is_tasks_backup_running())
{
$ret['result'] = 'failed';
$ret['error'] = __('A task is already running. Please wait until the running task is complete, and try again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$doing=WPvivid_taskmanager::get_backup_main_task_progress($task_id);
if($doing=='backup')
{
//flush buffer
$this->flush($task_id);
$this->backup($task_id);
}
else if($doing=='upload')
{
//flush buffer
$this->flush($task_id);
$this->upload($task_id);
}
//resume backup
die();
}
/**
* Clean backing up data schedule.
*
* @var string $task_id backup task id
*
* @since 0.9.1
*/
public function clean_backing_up_data_event($task_id)
{
$tasks=WPvivid_Setting::get_option('clean_task');
if(isset($tasks[$task_id])){
$task=$tasks[$task_id];
unset($tasks[$task_id]);
}
WPvivid_Setting::update_option('clean_task',$tasks);
if(!empty($task))
{
$backup=new WPvivid_Backup(false,$task);
$backup->clean_backup();
$files=array();
if($task['options']['remote_options']!==false)
{
$backup_files=$backup->task->get_need_cleanup_files(true);
foreach ($backup_files as $file)
{
$files[]=basename($file);
}
if(!empty($files))
{
$upload=new WPvivid_Upload();
$upload->clean_remote_backup($task['options']['remote_options'],$files);
}
}
//clean upload
}
}
/**
* Clean backup record schedule.
*
* @var string $task_id backup task id
*
* @since 0.9.1
*/
public function clean_backup_record_event($backup_id)
{
$tasks=WPvivid_Setting::get_option('clean_task');
$backup=$tasks[$backup_id];
unset($tasks[$backup_id]);
WPvivid_Setting::update_option('clean_task',$tasks);
if(!empty($backup))
{
$backup_item=new WPvivid_Backup_Item($backup);
$backup_item->cleanup_local_backup();
$backup_item->cleanup_remote_backup();
}
}
/**
* Clean oldest backup record.
*
* @var string $task_id backup task id
*
* @since 0.9.1
*/
public function clean_oldest_backup()
{
$oldest_ids=array();
$oldest_ids=apply_filters('wpvivid_get_oldest_backup_ids',$oldest_ids,false);
if($oldest_ids!==false)
{
foreach ($oldest_ids as $oldest_id)
{
$this->add_clean_backup_record_event($oldest_id);
WPvivid_Backuplist::delete_backup($oldest_id);
}
}
}
public function get_oldest_backup_ids($oldest_ids,$multiple)
{
if($multiple)
{
$count=WPvivid_Setting::get_max_backup_count();
$oldest_ids = WPvivid_Backuplist::get_out_of_date_backuplist($count);
return $oldest_ids;
}
else
{
$count=WPvivid_Setting::get_max_backup_count();
$oldest_id=WPvivid_Backuplist::check_backuplist_limit($count);
$oldest_ids=array();
$oldest_ids[]=$oldest_id;
return $oldest_ids;
}
}
public function check_backup_completeness($check_res, $task_id){
$task=WPvivid_taskmanager::get_task($task_id);
if(isset($task['setting']['is_merge']) && $task['setting']['is_merge'] == '1')
{
if(isset($task['jobs']))
{
foreach ($task['jobs'] as $job_info)
{
if($job_info['backup_type'] === 'backup_merge')
{
if(isset($job_info['zip_file']) && !empty($job_info['zip_file']))
{
foreach ($job_info['zip_file'] as $zip_file_name => $zip_file_info)
{
if(!$this->check_backup_file_json($zip_file_name)){
$check_res = false;
}
}
}
}
}
}
}
else
{
if(isset($task['jobs']))
{
foreach ($task['jobs'] as $job_info)
{
if(isset($job_info['zip_file']) && !empty($job_info['zip_file']))
{
foreach ($job_info['zip_file'] as $zip_file_name => $zip_file_info)
{
if(!$this->check_backup_file_json($zip_file_name)){
$check_res = false;
}
}
}
}
}
}
return $check_res;
}
public function get_mainwp_sync_data($information)
{
$data['setting']['wpvivid_compress_setting']=get_option('wpvivid_compress_setting');
$data['setting']['wpvivid_local_setting']=get_option('wpvivid_local_setting');
$data['setting']['wpvivid_common_setting']=get_option('wpvivid_common_setting');
$data['setting']['wpvivid_email_setting']=get_option('wpvivid_email_setting');
$data['setting']['cron_backup_count']=get_option('cron_backup_count');
$data['schedule']=get_option('wpvivid_schedule_setting');
$data['remote']['upload']=get_option('wpvivid_upload_setting');
$data['remote']['history']=get_option('wpvivid_user_history');
$data['setting_addon'] = $data['setting'];
$data['setting_addon']['wpvivid_staging_options']=array();
$data['backup_custom_setting']=array();
$data['menu_capability']=array();
$data['white_label_setting']=array();
$data['incremental_backup_setting']=array();
$data['last_backup_report']=array();
$data['schedule_addon']=array();
$data['time_zone']=false;
$data['is_pro']=false;
$data['is_install']=false;
$data['is_login']=false;
$data['latest_version']='';
$data['current_version']='';
$data['dashboard_version'] = '';
$data['addons_info'] = array();
$data=apply_filters('wpvivid_get_wpvivid_info_addon_mainwp', $data);
$information['syncWPvividSetting']=$data;
return $information;
}
public function check_backup_file_json($file_name){
$setting=get_option('wpvivid_common_setting',array());
$zip_method=isset($setting['zip_method'])?$setting['zip_method']:'ziparchive';
if($zip_method=='ziparchive'||empty($zip_method))
{
if(class_exists('ZipArchive'))
{
if(method_exists('ZipArchive', 'addFile'))
{
$zip_method='ziparchive';
}
else
{
$zip_method='pclzip';
}
}
else
{
$zip_method='pclzip';
}
}
else
{
$zip_method='pclzip';
}
if($zip_method=='ziparchive')
{
$general_setting=WPvivid_Setting::get_setting(true, "");
$backup_folder = $general_setting['options']['wpvivid_local_setting']['path'];
$backup_path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_folder.DIRECTORY_SEPARATOR;
$file_path=$backup_path.$file_name;
$zip_object=new ZipArchive();
$zip_object->open($file_path);
$json=$zip_object->getFromName('wpvivid_package_info.json');
if($json !== false)
{
$json = json_decode($json, 1);
if (is_null($json))
{
return false;
}
else
{
return $json;
}
}
else
{
return false;
}
}
else
{
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
$general_setting=WPvivid_Setting::get_setting(true, "");
$backup_folder = $general_setting['options']['wpvivid_local_setting']['path'];
$backup_path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_folder.DIRECTORY_SEPARATOR;
$file_path=$backup_path.$file_name;
$ret=$zip->get_json_data($file_path);
if($ret['result'] === WPVIVID_SUCCESS) {
$json=$ret['json_data'];
$json = json_decode($json, 1);
if (is_null($json)) {
return false;
} else {
return $json;
}
}
elseif($ret['result'] === WPVIVID_FAILED){
return false;
}
}
}
/**
* Initialization backup task.
*
* @var array $backup_options
* @var string $type
* @var int $lock
*
* @return array
*
* @since 0.9.1
*/
public function pre_backup($backup_options)
{
if(apply_filters('wpvivid_need_clean_oldest_backup',true,$backup_options))
{
$this->clean_oldest_backup();
}
do_action('wpvivid_clean_oldest_backup',$backup_options);
if(WPvivid_taskmanager::is_tasks_backup_running())
{
$ret['result']='failed';
$ret['error']=__('A task is already running. Please wait until the running task is complete, and try again.', 'wpvivid-backuprestore');
return $ret;
}
$backup=new WPvivid_Backup_Task();
$ret=$backup->new_backup_task($backup_options,$backup_options['type'],$backup_options['action']);
return $ret;
}
/**
* start or resume a backup task.
*
* @var string $task_id
*
* @since 0.9.1
*/
public function backup($task_id)
{
//register shutdown function to catch php fatal error such as script time out and memory limit
$common_setting = WPvivid_Setting::get_option('wpvivid_common_setting');
if(isset($common_setting['memory_limit']) && !empty($common_setting['memory_limit'])){
$memory_limit = $common_setting['memory_limit'];
}
else{
$memory_limit = WPVIVID_MEMORY_LIMIT;
}
@ini_set('memory_limit', $memory_limit);
$this->end_shutdown_function=false;
register_shutdown_function(array($this,'deal_shutdown_error'),$task_id);
@ignore_user_abort(true);
WPvivid_taskmanager::update_backup_task_status($task_id,true,'running');
$this->current_task=WPvivid_taskmanager::get_task($task_id);
//start a watch task event
$this->add_monitor_event($task_id);
//flush buffer
//$this->flush($task_id);
$this->wpvivid_log->OpenLogFile(WPvivid_taskmanager::get_task_options($task_id,'log_file_name'));
$this->wpvivid_log->WriteLog('Start backing up.','notice');
$this->wpvivid_log->WriteLogHander();
//start backup
try
{
$this->wpvivid_check_add_litespeed_server($task_id);
$backup=new WPvivid_Backup();
//$backup->clearcache();
$backup_ret=$backup->backup($task_id);
$backup->clearcache();
if($backup_ret['result'] != WPVIVID_SUCCESS)
{
$this->wpvivid_log->WriteLog('Backup ends with an error '. $backup_ret['error'], 'error');
}
else {
$this->wpvivid_log->WriteLog('Backup completed.','notice');
}
if(!$this->finish_backup_task($task_id))
{
$this->end_shutdown_function=true;
die();
}
if(WPvivid_taskmanager::get_task_options($task_id,'remote_options')!=false)
{
$this->upload($task_id,false);
}
}
catch (Exception $e)
{
//catch error and stop task recording history
$this->deal_task_error($task_id,'exception',$e);
$this->wpvivid_log->CloseFile();
$this->end_shutdown_function=true;
die();
}
$this->end_shutdown_function=true;
die();
}
/**
* recording finished backup task.
*
* @var string $task_id
*
* @var array $backup_ret return data of backup
*
* @return boolean
*
* @since 0.9.1
*/
private function finish_backup_task($task_id)
{
$status=WPvivid_taskmanager::get_backup_task_status($task_id);
if($status['str']=='running')
{
$this->wpvivid_log->WriteLog('Backup succeeded.','notice');
$check_res = apply_filters('wpvivid_check_backup_completeness', true, $task_id);
if(!$check_res){
$task=WPvivid_taskmanager::get_task($task_id);
$task['status']['error'] = 'We have detected that this backup is either corrupted or incomplete. Please make sure your server disk space is sufficient then create a new backup. In order to successfully back up/restore a website, the amount of free server disk space needs to be at least twice the size of the website';
do_action('wpvivid_handle_backup_failed',$task, false);
return false;
}
$remote_options=WPvivid_taskmanager::get_task_options($task_id,'remote_options');
if($remote_options===false)
{
$task=WPvivid_taskmanager::update_backup_task_status($task_id,false,'completed');
do_action('wpvivid_handle_backup_succeed',$task);
}
return true;
}
else
{
$task=WPvivid_taskmanager::get_task($task_id);
do_action('wpvivid_handle_backup_failed',$task, false);
return false;
}
}
public function wpvivid_analysis_backup($task)
{
if($task['type'] == 'Manual')
{
$need_review=WPvivid_Setting::get_option('wpvivid_need_review');
if($need_review=='not')
{
$review_time=WPvivid_Setting::get_option('wpvivid_review_time', false);
if($review_time === false || time() >= $review_time)
{
WPvivid_Setting::update_option('wpvivid_need_review','show');
$msg = 'Backup successful! If you\'re happy with WPvivid Backup Plugin, a 5-star rating would mean the world to us and help us make it even better.';
WPvivid_Setting::update_option('wpvivid_review_msg',$msg);
WPvivid_Setting::update_option('wpvivid_review_type', 'manual');
}
}
}
else if($task['type'] == 'Cron')
{
$cron_backup_count = WPvivid_Setting::get_option('cron_backup_count');
if(empty($cron_backup_count)){
$cron_backup_count = 0;
}
$cron_backup_count++;
WPvivid_Setting::update_option('cron_backup_count', $cron_backup_count);
$common_setting = WPvivid_Setting::get_option('wpvivid_common_setting');
$max_backup_count = $common_setting['max_backup_count'];
if($cron_backup_count >= $max_backup_count){
$need_review=WPvivid_Setting::get_option('wpvivid_need_review');
if($need_review=='not')
{
WPvivid_Setting::update_option('wpvivid_need_review','show');
$msg = 'Cheers, scheduled backups are running smoothly. If you find WPvivid Backup plugin helpful, a 5-star rating would help us continue improving.';
WPvivid_Setting::update_option('wpvivid_review_msg',$msg);
WPvivid_Setting::update_option('wpvivid_review_type', 'cron');
}
}
}
}
/**
* start upload files to remote.
*
* @var string $task_id
* @var bool $restart
* @since 0.9.10
*/
public function upload($task_id,$restart=true)
{
$this->end_shutdown_function=false;
register_shutdown_function(array($this,'deal_shutdown_error'),$task_id);
@ignore_user_abort(true);
WPvivid_taskmanager::update_backup_task_status($task_id,$restart,'running',false,0);
$this->current_task=WPvivid_taskmanager::get_task($task_id);
//start a watch task event
$this->add_monitor_event($task_id);
//flush buffer
//$this->flush($task_id);
$this->wpvivid_log->OpenLogFile(WPvivid_taskmanager::get_task_options($task_id,'log_file_name'));
$this->wpvivid_log->WriteLog('Start upload.','notice');
$this->set_time_limit($task_id);
$upload=new WPvivid_Upload();
$ret=$upload->upload($task_id);
if($ret['result'] == WPVIVID_SUCCESS)
{
$task=WPvivid_taskmanager::update_backup_task_status($task_id,false,'completed');
do_action('wpvivid_handle_upload_succeed',$task);
}
else
{
$backup = WPvivid_Backuplist::get_backup_by_id($task_id);
if($backup!==false)
{
$backup['save_local']=1;
WPvivid_Backuplist::update_backup_option($task_id, $backup);
}
$this->wpvivid_log->WriteLog('Uploading the file ends with an error '. $ret['error'], 'error');
$task=WPvivid_taskmanager::get_task($task_id);
do_action('wpvivid_handle_backup_failed',$task, false);
}
$this->end_shutdown_function=true;
die();
}
function wpvivid_deal_upload_succeed($task)
{
$save_local=$task['options']['save_local'];
if($save_local==0)
{
$retain_local = WPvivid_Setting::get_retain_local_status();
if(!$retain_local) {
$this->wpvivid_log->WriteLog('Cleaned up local files after uploading to remote storages.', 'notice');
$backup = new WPvivid_Backup($task['id']);
$backup->clean_backup();
}
}
$this->wpvivid_log->WriteLog('Upload succeeded.','notice');
$remote_options=$task['options']['remote_options'];
$remote_options=apply_filters('wpvivid_set_backup_remote_options',$remote_options,$task['id']);
WPvivid_Backuplist::update_backup($task['id'],'remote',$remote_options);
}
function wpvivid_handle_backup_succeed($task)
{
if($task['action'] === 'backup')
{
$backup_task=new WPvivid_Backup_Task($task['id']);
$backup_task->add_new_backup();
$remote_options = WPvivid_taskmanager::get_task_options($task['id'], 'remote_options');
if($remote_options != false){
WPvivid_Backuplist::update_backup($task['id'],'remote', $remote_options);
}
$backup_success_count = WPvivid_Setting::get_option('wpvivid_backup_success_count');
if (empty($backup_success_count))
{
$backup_success_count = 0;
}
$backup_success_count++;
WPvivid_Setting::update_option('wpvivid_backup_success_count', $backup_success_count);
$this->wpvivid_analysis_backup($task);
$task_msg = WPvivid_taskmanager::get_task($task['id']);
$this->update_last_backup_task($task_msg);
}
WPvivid_Schedule::clear_monitor_schedule($task['id']);
$backup_task=new WPvivid_Backup_Task($task['id']);
$res=$backup_task->get_backup_result();
if(!empty($res['files']))
{
if(!class_exists('WPvivid_mail_report'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-mail-report.php';
WPvivid_mail_report::send_report_mail($task);
}
$this->wpvivid_check_clear_litespeed_rule($task['id']);
}
function wpvivid_mark_task($task)
{
WPvivid_taskmanager::mark_task($task['id']);
}
function wpvivid_handle_backup_failed($task, $need_set_low_resource_mode)
{
if($task['action'] === 'backup')
{
$backup_error_array = WPvivid_Setting::get_option('wpvivid_backup_error_array');
if (!isset($backup_error_array) || empty($backup_error_array))
{
$backup_error_array = array();
$backup_error_array['bu_error']['task_id'] = '';
$backup_error_array['bu_error']['error_msg'] = '';
}
if (!array_key_exists($task['id'], $backup_error_array['bu_error']))
{
$backup_error_array['bu_error']['task_id'] = $task['id'];
$backup_error_array['bu_error']['error_msg'] = 'Unknown error.';
$general_setting=WPvivid_Setting::get_setting(true, "");
$need_notice = false;
if(!isset($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload'])){
$need_notice = true;
}
else{
if($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload']){
$need_notice = false;
}
else{
$need_notice = true;
}
}
if($need_notice) {
if($need_set_low_resource_mode) {
$notice_msg1 = 'Backup failed, it seems due to insufficient server resource or hitting server limit. Please navigate to Settings > Advanced > ';
$notice_msg2 = 'optimization mode for web hosting/shared hosting';
$notice_msg3 = ' to enable it and try again';
$backup_error_array['bu_error']['error_msg']='<div class="notice notice-error inline"><p>'.$notice_msg1.'<strong>'.$notice_msg2.'</strong>'.$notice_msg3.'</p></div>';
}
else{
$notice_msg = 'Backup error: '.$task['status']['error'].', task id: '.$task['id'];
$backup_error_array['bu_error']['error_msg']='<div class="notice notice-error inline"><p>'.$notice_msg.', Please switch to <a href="#" onclick="wpvivid_click_switch_page(\'wrap\', \'wpvivid_tab_debug\', true);">Website Info</a> page to send us the debug information. </p></div>';
}
}
else{
if($need_set_low_resource_mode) {
$notice_msg = 'Backup failed, it seems due to insufficient server resource or hitting server limit.';
$backup_error_array['bu_error']['error_msg'] = '<div class="notice notice-error inline"><p>' . $notice_msg . ', Please switch to <a href="#" onclick="wpvivid_click_switch_page(\'wrap\', \'wpvivid_tab_debug\', true);">Website Info</a> page to send us the debug information. </p></div>';
}
else {
$notice_msg = 'Backup error: ' . $task['status']['error'] . ', task id: ' . $task['id'];
$backup_error_array['bu_error']['error_msg'] = '<div class="notice notice-error inline"><p>' . $notice_msg . ', Please switch to <a href="#" onclick="wpvivid_click_switch_page(\'wrap\', \'wpvivid_tab_debug\', true);">Website Info</a> page to send us the debug information. </p></div>';
}
}
}
WPvivid_Setting::update_option('wpvivid_backup_error_array', $backup_error_array);
$task_msg = WPvivid_taskmanager::get_task($task['id']);
$this->update_last_backup_task($task_msg);
}
$this->wpvivid_log->WriteLog($task['status']['error'],'error');
$this->wpvivid_log->CloseFile();
WPvivid_error_log::create_error_log($this->wpvivid_log->log_file);
WPvivid_Schedule::clear_monitor_schedule($task['id']);
$this->add_clean_backing_up_data_event($task['id']);
if(!class_exists('WPvivid_mail_report'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-mail-report.php';
WPvivid_mail_report::send_report_mail($task);
$this->wpvivid_check_clear_litespeed_rule($task['id']);
}
public function deal_shutdown_error($task_id)
{
if($this->end_shutdown_function===false)
{
$last_error = error_get_last();
if (!empty($last_error) && !in_array($last_error['type'], array(E_NOTICE,E_WARNING,E_USER_NOTICE,E_USER_WARNING,E_DEPRECATED), true))
{
$error = $last_error;
} else {
$error = false;
}
//$this->task_monitor($task_id,$error);
if (WPvivid_taskmanager::get_task($task_id) !== false)
{
if ($this->wpvivid_log->log_file_handle == false)
{
$this->wpvivid_log->OpenLogFile(WPvivid_taskmanager::get_task_options($task_id, 'log_file_name'));
}
$status = WPvivid_taskmanager::get_backup_task_status($task_id);
if ($status['str'] == 'running' || $status['str'] == 'error' || $status['str'] == 'no_responds')
{
$options=WPvivid_Setting::get_option('wpvivid_common_setting');
if(isset($options['max_execution_time']))
{
$limit=$options['max_execution_time'];
}
else
{
$limit=WPVIVID_MAX_EXECUTION_TIME;
}
if(isset($options['max_resume_count']))
{
$max_resume_count=$options['max_resume_count'];
}
else
{
$max_resume_count=WPVIVID_RESUME_RETRY_TIMES;
}
$time_spend = time() - $status['timeout'];
$time_start = time() - $status['start_time'];
$time_min=min($limit, 120);
if ($time_spend >= $limit)
{
//time out
$status['resume_count']++;
if ($status['resume_count'] > $max_resume_count)
{
$message = __('Too many resumption attempts.', 'wpvivid-backuprestore');
$task = WPvivid_taskmanager::update_backup_task_status($task_id, false, 'error', false, $status['resume_count'], $message);
do_action('wpvivid_handle_backup_failed', $task, true);
} else {
$this->check_cancel_backup($task_id);
$message = 'Task timed out.';
if ($this->add_resume_event($task_id))
{
WPvivid_taskmanager::update_backup_task_status($task_id, false, 'wait_resume', false, $status['resume_count']);
} else {
$task = WPvivid_taskmanager::update_backup_task_status($task_id, false, 'error', false, $status['resume_count'], $message);
do_action('wpvivid_handle_backup_failed', $task, true);
}
}
if ($this->wpvivid_log)
$this->wpvivid_log->WriteLog($message, 'error');
}
else if($time_start>=$time_min)
{
$status['resume_count']++;
if ($status['resume_count'] > $max_resume_count)
{
$message = __('Too many resumption attempts.', 'wpvivid-backuprestore');
if ($error !== false)
{
$message.= 'type: '. $error['type'] . ', ' . $error['message'] . ' file:' . $error['file'] . ' line:' . $error['line'];
}
$task = WPvivid_taskmanager::update_backup_task_status($task_id, false, 'error', false, $status['resume_count'], $message);
do_action('wpvivid_handle_backup_failed', $task ,true);
} else {
$this->check_cancel_backup($task_id);
$message = 'Task timed out (WebHosting).';
if ($this->add_resume_event($task_id))
{
WPvivid_taskmanager::update_backup_task_status($task_id, false, 'wait_resume', false, $status['resume_count']);
} else {
$task = WPvivid_taskmanager::update_backup_task_status($task_id, false, 'error', false, $status['resume_count'], $message);
do_action('wpvivid_handle_backup_failed', $task, true);
}
}
if ($this->wpvivid_log)
$this->wpvivid_log->WriteLog($message, 'error');
}
else
{
$status['resume_count']++;
if ($status['resume_count'] > $max_resume_count)
{
$message = __('Too many resumption attempts.', 'wpvivid-backuprestore');
if ($error !== false)
{
$message.= 'type: '. $error['type'] . ', ' . $error['message'] . ' file:' . $error['file'] . ' line:' . $error['line'];
}
$task = WPvivid_taskmanager::update_backup_task_status($task_id, false, 'error', false, $status['resume_count'], $message);
do_action('wpvivid_handle_backup_failed', $task ,true);
} else {
$this->check_cancel_backup($task_id);
$message = 'Task timed out (WebHosting).';
if ($this->add_resume_event($task_id))
{
WPvivid_taskmanager::update_backup_task_status($task_id, false, 'wait_resume', false, $status['resume_count']);
} else {
$task = WPvivid_taskmanager::update_backup_task_status($task_id, false, 'error', false, $status['resume_count'], $message);
do_action('wpvivid_handle_backup_failed', $task, true);
}
}
if ($this->wpvivid_log)
$this->wpvivid_log->WriteLog($message, 'error');
}
/*
else
{
if ($status['str'] != 'error')
{
if ($error !== false)
{
$message = 'type: '. $error['type'] . ', ' . $error['message'] . ' file:' . $error['file'] . ' line:' . $error['line'];
} else {
$message = __('Backup timed out. Please set the value of PHP script execution timeout to '.$time_start.' in plugin settings.', 'wpvivid-backuprestore');
}
WPvivid_taskmanager::update_backup_task_status($task_id, false, 'error', false, $status['resume_count'], $message);
}
$task = WPvivid_taskmanager::get_task($task_id);
do_action('wpvivid_handle_backup_failed', $task, false);
}
*/
}
}
die();
}
}
public function deal_task_error($task_id,$error_type,$error)
{
$message = 'An '.$error_type.' has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
error_log($message);
$task=WPvivid_taskmanager::update_backup_task_status($task_id,false,'error',false,false,$message);
$this->wpvivid_log->WriteLog($message,'error');
do_action('wpvivid_handle_backup_failed',$task, false);
}
/**
* update time limit.
*
* @var string $task_id
*
* @var int $second
*
* @since 0.9.1
*/
public function set_time_limit($task_id,$second=0)
{
if($second==0)
{
$options=WPvivid_Setting::get_option('wpvivid_common_setting');
if(isset($options['max_execution_time']))
{
$second=$options['max_execution_time'];
}
else
{
$second=WPVIVID_MAX_EXECUTION_TIME;
}
}
WPvivid_taskmanager::update_backup_task_status($task_id,false,'',true);
@set_time_limit($second);
}
/**
* Watch task status.
*
* @var string $task_id
*
* @var array|false $error
*
* @since 0.9.1
*/
public function task_monitor($task_id)
{
if(WPvivid_taskmanager::get_task($task_id)!==false)
{
if($this->wpvivid_log->log_file_handle==false)
{
$this->wpvivid_log->OpenLogFile(WPvivid_taskmanager::get_task_options($task_id,'log_file_name'));
}
$status=WPvivid_taskmanager::get_backup_task_status($task_id);
if($status['str']=='running'||$status['str']=='error'||$status['str']=='no_responds')
{
$options=WPvivid_Setting::get_option('wpvivid_common_setting');
if(isset($options['max_execution_time']))
{
$limit=$options['max_execution_time'];
}
else
{
$limit=WPVIVID_MAX_EXECUTION_TIME;
}
$time_spend=time()-$status['timeout'];
$last_active_time=time()-$status['run_time'];
if($time_spend>=$limit&&$last_active_time>min(180,$limit))
{
//time out
if(isset($options['max_resume_count']))
{
$max_resume_count=$options['max_resume_count'];
}
else
{
$max_resume_count=WPVIVID_RESUME_RETRY_TIMES;
}
$status['resume_count']++;
if($status['resume_count']>$max_resume_count)
{
$message=__('Too many resumption attempts.', 'wpvivid-backuprestore');
$task=WPvivid_taskmanager::update_backup_task_status($task_id,false,'error',false,$status['resume_count'],$message);
//WPvivid_error_log::create_error_log($this->wpvivid_log->log_file);
do_action('wpvivid_handle_backup_failed',$task, true);
}
else
{
$this->check_cancel_backup($task_id);
$message=__('Task timed out.', 'wpvivid-backuprestore');
if($this->add_resume_event($task_id))
{
WPvivid_taskmanager::update_backup_task_status($task_id,false,'wait_resume',false,$status['resume_count']);
}
else
{
$task=WPvivid_taskmanager::update_backup_task_status($task_id,false,'error',false,$status['resume_count'],$message);
do_action('wpvivid_handle_backup_failed',$task, true);
}
}
if($this->wpvivid_log)
$this->wpvivid_log->WriteLog($message,'error');
}
else {
$time_spend=time()-$status['run_time'];
if($time_spend>180)
{
$this->check_cancel_backup($task_id);
$this->wpvivid_log->WriteLog('Not responding for a long time.','notice');
WPvivid_taskmanager::update_backup_task_status($task_id,false,'no_responds',false,$status['resume_count']);
$this->add_monitor_event($task_id);
}
else {
$this->add_monitor_event($task_id);
}
}
}
else if($status['str']=='wait_resume')
{
$timestamp = wp_next_scheduled(WPVIVID_RESUME_SCHEDULE_EVENT,array($task_id));
if($timestamp===false)
{
if($this->wpvivid_log)
$this->wpvivid_log->WriteLog('Missing resume task,so we create new one.','error');
$message = 'Task timed out (WebHosting).';
if ($this->add_resume_event($task_id))
{
WPvivid_taskmanager::update_backup_task_status($task_id, false, 'wait_resume', false, $status['resume_count']);
} else {
$task = WPvivid_taskmanager::update_backup_task_status($task_id, false, 'error', false, $status['resume_count'], $message);
do_action('wpvivid_handle_backup_failed', $task, true);
}
}
}
}
}
public function task_monitor_ex()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$tasks=WPvivid_Setting::get_tasks();
$task_id='';
foreach ($tasks as $task)
{
if($task['action']=='backup')
{
$status=WPvivid_taskmanager::get_backup_tasks_status($task['id']);
if($status['str']=='completed'||$status['str']=='error')
{
continue;
}
else
{
$task_id=$task['id'];
break;
}
}
}
if(empty($task_id))
{
die();
}
if(WPvivid_taskmanager::get_task($task_id)!==false)
{
if($this->wpvivid_log->log_file_handle==false)
{
$this->wpvivid_log->OpenLogFile(WPvivid_taskmanager::get_task_options($task_id,'log_file_name'));
}
$status=WPvivid_taskmanager::get_backup_task_status($task_id);
if($status['str']=='running'||$status['str']=='error'||$status['str']=='no_responds')
{
$options=WPvivid_Setting::get_option('wpvivid_common_setting');
if(isset($options['max_execution_time']))
{
$limit=$options['max_execution_time'];
}
else
{
$limit=WPVIVID_MAX_EXECUTION_TIME;
}
$time_spend=time()-$status['timeout'];
$last_active_time=time()-$status['run_time'];
if($time_spend>=$limit&&$last_active_time>min(180,$limit))
{
//time out
if(isset($options['max_resume_count']))
{
$max_resume_count=$options['max_resume_count'];
}
else
{
$max_resume_count=WPVIVID_RESUME_RETRY_TIMES;
}
$status['resume_count']++;
if($status['resume_count']>$max_resume_count)
{
$message=__('Too many resumption attempts.', 'wpvivid-backuprestore');
$task=WPvivid_taskmanager::update_backup_task_status($task_id,false,'error',false,$status['resume_count'],$message);
//WPvivid_error_log::create_error_log($this->wpvivid_log->log_file);
do_action('wpvivid_handle_backup_failed',$task, true);
}
else
{
$this->check_cancel_backup($task_id);
$message=__('Task timed out.', 'wpvivid-backuprestore');
if($this->add_resume_event($task_id))
{
WPvivid_taskmanager::update_backup_task_status($task_id,false,'wait_resume',false,$status['resume_count']);
}
else
{
$task=WPvivid_taskmanager::update_backup_task_status($task_id,false,'error',false,$status['resume_count'],$message);
do_action('wpvivid_handle_backup_failed',$task, true);
}
}
if($this->wpvivid_log)
$this->wpvivid_log->WriteLog($message,'error');
}
else {
$time_spend=time()-$status['run_time'];
if($time_spend>180)
{
$this->check_cancel_backup($task_id);
$this->wpvivid_log->WriteLog('Not responding for a long time.','notice');
WPvivid_taskmanager::update_backup_task_status($task_id,false,'no_responds',false,$status['resume_count']);
$this->add_monitor_event($task_id);
}
else{
$this->add_monitor_event($task_id);
}
}
}
else if($status['str']=='wait_resume')
{
$timestamp = wp_next_scheduled(WPVIVID_RESUME_SCHEDULE_EVENT,array($task_id));
if($timestamp===false)
{
if($this->wpvivid_log)
$this->wpvivid_log->WriteLog('Missing resume task,so we create new one.','error');
$message = 'Task timed out (WebHosting).';
if ($this->add_resume_event($task_id))
{
WPvivid_taskmanager::update_backup_task_status($task_id, false, 'wait_resume', false, $status['resume_count']);
} else {
$task = WPvivid_taskmanager::update_backup_task_status($task_id, false, 'error', false, $status['resume_count'], $message);
do_action('wpvivid_handle_backup_failed', $task, true);
}
}
}
}
}
/**
* Estimate the size of files, folder, database and backup time before backing up.
*
* @var string $task_id
*
* @var string $backup_files
*
* @var array $backup_option
*
* @return array
*
* @since 0.9.1
*/
public function check_backup($task_id,$backup_option)
{
@set_time_limit(180);
$options=WPvivid_Setting::get_option('wpvivid_common_setting');
if(isset($options['estimate_backup']))
{
if($options['estimate_backup'] == false)
{
$ret['alert_db']=false;
$ret['alter_files']=false;
$ret['alter_fcgi']=false;
$ret['alter_big_file']=false;
return $ret;
}
}
$file_size=false;
$check['check_file']=false;
$check['check_db']=false;
add_filter('wpvivid_check_backup_size',array($this, 'check_backup_size'),10,2);
$check = apply_filters('wpvivid_check_backup_size', $check,$backup_option);
$check_file=$check['check_file'];
$check_db=$check['check_db'];
$sapi_type=php_sapi_name();
if($sapi_type=='cgi-fcgi'||$sapi_type=='fpm-fcgi')
{
$alter_fcgi=true;
}
else
{
$alter_fcgi=false;
}
if($check_db)
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-db-method.php';
$db_method=new WPvivid_DB_Method();
$ret=$db_method->check_db($alter_fcgi);
if($ret['result']==WPVIVID_FAILED)
{
return $ret;
}
}
else
{
$ret['alert_db']=false;
$ret['db_size']=false;
}
$ret['alter_files']=false;
$ret['alter_big_file']=false;
$ret['alter_fcgi']=false;
if($check_file)
{
include_once WPVIVID_PLUGIN_DIR .'/includes/class-wpvivid-backup.php';
$task=new WPvivid_Backup_Task($task_id);
$file_size=$task->get_file_info();
$sum_size=$file_size['sum_size'];
$sum_count=$file_size['sum_count'];
if($alter_fcgi)
{
$alter_sum_size=1024*1024*1024;
$alter_sum_count=20000;
}
else
{
$alter_sum_size=4*1024*1024*1024;
$alter_sum_count=8*10000;
}
if($sum_size>$alter_sum_size||$sum_count>$alter_sum_count)
{
$ret['alter_files']=true;
$ret['sum_size']=$this->formatBytes($sum_size);
$ret['sum_count']=$sum_count;
$ret['file_size']=$file_size;
if($alter_fcgi)
$ret['alter_fcgi']=true;
}
else{
$ret['sum_count']=$sum_count;
}
$file_size['sum']=$this->formatBytes($sum_size);
}
$ret['file_size']=$file_size;
if($task_id!==false)
{
$task=new WPvivid_Backup_Task($task_id);
$task->set_file_and_db_info($ret['db_size'],$file_size);
}
return $ret;
}
public function check_backup_size($check,$backup_option)
{
if(isset($backup_option['backup_files']))
{
if($backup_option['backup_files']=='files+db')
{
$check['check_file']=true;
$check['check_db']=true;
}
else if($backup_option['backup_files']=='files')
{
$check['check_file']=true;
}
else if($backup_option['backup_files']=='db')
{
$check['check_db']=true;
}
}
return $check;
}
/**
* Add a backup task resume schedule.
*
* @var string $task_id
*
* @return boolean
*
* @since 0.9.1
*/
private function add_resume_event($task_id)
{
$resume_time=time()+WPVIVID_RESUME_INTERVAL;
$b=wp_schedule_single_event($resume_time,WPVIVID_RESUME_SCHEDULE_EVENT,array($task_id));
if($b===false)
{
$timestamp = wp_next_scheduled(WPVIVID_RESUME_SCHEDULE_EVENT,array($task_id));
if($timestamp!==false)
{
$resume_time=max($resume_time,$timestamp+10*60+10);
$b=wp_schedule_single_event($resume_time,WPVIVID_RESUME_SCHEDULE_EVENT,array($task_id));
if($b===false)
{
$this->wpvivid_log->WriteLog('Add and retry resume event failed.','notice');
return false;
}
$this->wpvivid_log->WriteLog('Retry resume event succeeded.','notice');
}
else
{
$this->wpvivid_log->WriteLog('Add resume event failed.','notice');
return false;
}
}
$this->wpvivid_log->WriteLog('Add resume event succeeded.. arg1:'.$resume_time.' arg2:'.WPVIVID_RESUME_SCHEDULE_EVENT.' arg3:'.$task_id,'notice');
return true;
}
/**
* Add a scheduled task to clear backup data.
*
* @var string $task_id
*
* @return boolean
*
* @since 0.9.1
*/
public function add_clean_backing_up_data_event($task_id)
{
$task=WPvivid_taskmanager::get_task($task_id);
$tasks=WPvivid_Setting::get_option('clean_task');
$tasks[$task_id]=$task;
WPvivid_Setting::update_option('clean_task',$tasks);
$resume_time=time()+60;
$b=wp_schedule_single_event($resume_time,WPVIVID_CLEAN_BACKING_UP_DATA_EVENT,array($task_id));
if($b===false)
{
$timestamp = wp_next_scheduled(WPVIVID_CLEAN_BACKING_UP_DATA_EVENT,array($task_id));
if($timestamp!==false)
{
$resume_time=max($resume_time,$timestamp+10*60+10);
$b=wp_schedule_single_event($resume_time,WPVIVID_CLEAN_BACKING_UP_DATA_EVENT,array($task_id));
if($b===false)
{
return false;
}
}
else
{
return false;
}
}
return true;
}
/**
* Add a scheduled task to clear backup record.
*
* @var string $task_id
*
* @return boolean
*
* @since 0.9.1
*/
private function add_clean_backup_record_event($backup_id)
{
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
$tasks=WPvivid_Setting::get_option('clean_task');
$tasks[$backup_id]=$backup;
WPvivid_Setting::update_option('clean_task',$tasks);
$resume_time=time()+60;
$b=wp_schedule_single_event($resume_time,WPVIVID_CLEAN_BACKUP_RECORD_EVENT,array($backup_id));
if($b===false)
{
$timestamp = wp_next_scheduled(WPVIVID_CLEAN_BACKUP_RECORD_EVENT,array($backup_id));
if($timestamp!==false)
{
$resume_time=max($resume_time,$timestamp+10*60+10);
$b=wp_schedule_single_event($resume_time,WPVIVID_CLEAN_BACKUP_RECORD_EVENT,array($backup_id));
if($b===false)
{
return false;
}
}
else
{
return false;
}
}
return true;
}
/**
* Add a watch task scheduled event.
*
* @var string $task_id
*
* @var int $next_time
*
* @return boolean
*
* @since 0.9.1
*/
public function add_monitor_event($task_id,$next_time=120)
{
$resume_time=time()+$next_time;
$timestamp = wp_next_scheduled(WPVIVID_TASK_MONITOR_EVENT,array($task_id));
if($timestamp===false)
{
$b = wp_schedule_single_event($resume_time, WPVIVID_TASK_MONITOR_EVENT, array($task_id));
if ($b === false)
{
return false;
} else {
return true;
}
}
return true;
}
public function formatBytes($bytes, $precision = 2)
{
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
// Uncomment one of the following alternatives
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . '' . $units[$pow];
}
/**
* check backup task canceled or not
*
* @var string $task_id
*
* @since 0.9.1
*/
public function check_cancel_backup($task_id)
{
if(WPvivid_taskmanager::get_task($task_id)!==false)
{
$task=new WPvivid_Backup_Task($task_id);
if($task->is_cancel_file_exist())
{
if($this->wpvivid_log->log_file_handle==false)
{
$this->wpvivid_log->OpenLogFile(WPvivid_taskmanager::get_task_options($task_id,'log_file_name'));
}
$this->wpvivid_log->WriteLog('Backup cancelled.','notice');
$task->update_status('cancel');
//WPvivid_taskmanager::update_backup_task_status($task_id,false,'cancel',false);
$this->add_clean_backing_up_data_event($task_id);
WPvivid_Schedule::clear_monitor_schedule($task_id);
WPvivid_taskmanager::delete_task($task_id);
die();
}
}
}
public function flush($txt, $from_mainwp=false) {
if(!$from_mainwp) {
$ret['result'] = 'success';
$ret['task_id'] = $txt;
$txt = wp_json_encode($ret);
}
else{
$ret['result']='success';
$txt = '<mainwp>' . base64_encode( serialize( $ret ) ) . '</mainwp>';
}
if(!headers_sent()){
header('Content-Length: '.( ( ! empty( $txt ) ) ? strlen( $txt ) : '0' ));
header('Connection: close');
header('Content-Encoding: none');
}
if (session_id())
session_write_close();
echo wp_json_encode($ret);
if(function_exists('fastcgi_finish_request'))
{
fastcgi_finish_request();
}
else
{
if(ob_get_level()>0)
ob_flush();
flush();
}
}
/**
* return initialization download page data
*
* @var string $task_id
*
* @since 0.9.48
*/
public function init_download_page()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_POST['backup_id']) && !empty($_POST['backup_id']) && is_string($_POST['backup_id'])) {
$backup_id = sanitize_key($_POST['backup_id']);
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
if ($backup === false) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'backup id not found';
echo wp_json_encode($ret);
die();
}
$backup_item = new WPvivid_Backup_Item($backup);
$backup_files = $backup_item->get_download_backup_files($backup_id);
if ($backup_files['result'] == WPVIVID_SUCCESS) {
$ret['result'] = WPVIVID_SUCCESS;
$remote = $backup_item->get_remote();
foreach ($backup_files['files'] as $file) {
$path = $this->get_backup_path($backup_item, $file['file_name']);
//$path = $backup_item->get_local_path() . $file['file_name'];
if (file_exists($path)) {
if (filesize($path) == $file['size']) {
if (WPvivid_taskmanager::get_download_task_v2($file['file_name']))
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
$ret['files'][$file['file_name']]['status'] = 'completed';
$ret['files'][$file['file_name']]['size'] = size_format(filesize($path), 2);
$ret['files'][$file['file_name']]['download_path'] = $path;
$download_url = $this->get_backup_url($backup_item, $file['file_name']);
$ret['files'][$file['file_name']]['download_url'] = $download_url;
continue;
}
}
$ret['files'][$file['file_name']]['size'] = size_format($file['size'], 2);
if (empty($remote)) {
$ret['files'][$file['file_name']]['status'] = 'file_not_found';
} else {
$task = WPvivid_taskmanager::get_download_task_v2($file['file_name']);
if ($task === false) {
$ret['files'][$file['file_name']]['status'] = 'need_download';
} else {
$ret['result'] = WPVIVID_SUCCESS;
if ($task['status'] === 'running') {
$ret['files'][$file['file_name']]['status'] = 'running';
$ret['files'][$file['file_name']]['progress_text'] = $task['progress_text'];
if (file_exists($path)) {
$ret['files'][$file['file_name']]['downloaded_size'] = size_format(filesize($path), 2);
} else {
$ret['files'][$file['file_name']]['downloaded_size'] = '0';
}
} elseif ($task['status'] === 'timeout') {
$ret['files'][$file['file_name']]['status'] = 'timeout';
$ret['files'][$file['file_name']]['progress_text'] = $task['progress_text'];
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
} elseif ($task['status'] === 'completed') {
$ret['files'][$file['file_name']]['status'] = 'completed';
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
} elseif ($task['status'] === 'error') {
$ret['files'][$file['file_name']]['status'] = 'error';
$ret['files'][$file['file_name']]['error'] = $task['error'];
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
}
}
}
}
} else {
$ret = $backup_files;
}
if (!class_exists('WPvivid_Files_List'))
include_once WPVIVID_PLUGIN_DIR .'/admin/partials/wpvivid-backup-restore-page-display.php';
$files_list = new WPvivid_Files_List();
$files_list->set_files_list($ret['files'], $backup_id);
$files_list->prepare_items();
ob_start();
$files_list->display();
$ret['html'] = ob_get_clean();
echo wp_json_encode($ret);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function get_download_page_ex()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_POST['backup_id']) && !empty($_POST['backup_id']) && is_string($_POST['backup_id'])) {
if (isset($_POST['page'])) {
$page = sanitize_key($_POST['page']);
} else {
$page = 1;
}
$backup_id = sanitize_key($_POST['backup_id']);
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
if ($backup === false) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'backup id not found';
echo wp_json_encode($ret);
die();
}
$backup_item = new WPvivid_Backup_Item($backup);
$backup_files = $backup_item->get_download_backup_files($backup_id);
if ($backup_files['result'] == WPVIVID_SUCCESS) {
$ret['result'] = WPVIVID_SUCCESS;
$remote = $backup_item->get_remote();
foreach ($backup_files['files'] as $file) {
$path = $this->get_backup_path($backup_item, $file['file_name']);
//$path = $backup_item->get_local_path() . $file['file_name'];
if (file_exists($path)) {
if (filesize($path) == $file['size']) {
if (WPvivid_taskmanager::get_download_task_v2($file['file_name']))
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
$ret['files'][$file['file_name']]['status'] = 'completed';
$ret['files'][$file['file_name']]['size'] = size_format(filesize($path), 2);
$ret['files'][$file['file_name']]['download_path'] = $path;
$download_url = $this->get_backup_url($backup_item, $file['file_name']);
$ret['files'][$file['file_name']]['download_url'] = $download_url;
continue;
}
}
$ret['files'][$file['file_name']]['size'] = size_format($file['size'], 2);
if (empty($remote)) {
$ret['files'][$file['file_name']]['status'] = 'file_not_found';
} else {
$task = WPvivid_taskmanager::get_download_task_v2($file['file_name']);
if ($task === false) {
$ret['files'][$file['file_name']]['status'] = 'need_download';
} else {
$ret['result'] = WPVIVID_SUCCESS;
if ($task['status'] === 'running') {
$ret['files'][$file['file_name']]['status'] = 'running';
$ret['files'][$file['file_name']]['progress_text'] = $task['progress_text'];
if (file_exists($path)) {
$ret['files'][$file['file_name']]['downloaded_size'] = size_format(filesize($path), 2);
} else {
$ret['files'][$file['file_name']]['downloaded_size'] = '0';
}
} elseif ($task['status'] === 'timeout') {
$ret['files'][$file['file_name']]['status'] = 'timeout';
$ret['files'][$file['file_name']]['progress_text'] = $task['progress_text'];
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
} elseif ($task['status'] === 'completed') {
$ret['files'][$file['file_name']]['status'] = 'completed';
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
} elseif ($task['status'] === 'error') {
$ret['files'][$file['file_name']]['status'] = 'error';
$ret['files'][$file['file_name']]['error'] = $task['error'];
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
}
}
}
}
} else {
$ret = $backup_files;
}
if (!class_exists('WPvivid_Files_List'))
include_once WPVIVID_PLUGIN_DIR .'/admin/partials/wpvivid-backup-restore-page-display.php';
$files_list = new WPvivid_Files_List();
$files_list->set_files_list($ret['files'], $backup_id, $page);
$files_list->prepare_items();
ob_start();
$files_list->display();
$ret['html'] = ob_get_clean();
echo wp_json_encode($ret);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
/**
* prepare download backup
*
* Retrieve files from the server
*
* @var string $task_id
*
* @since 0.9.1
*/
public function prepare_download_backup()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$this->end_shutdown_function=false;
register_shutdown_function(array($this,'deal_prepare_download_shutdown_error'));
$id=uniqid('wpvivid-');
$log_file_name=$id.'_download';
$this->wpvivid_download_log->OpenLogFile($log_file_name);
$this->wpvivid_download_log->WriteLog('Prepare download backup.','notice');
$this->wpvivid_download_log->WriteLogHander();
try {
if (!isset($_POST['backup_id']) || empty($_POST['backup_id']) || !is_string($_POST['backup_id']) || !isset($_POST['file_name']) || empty($_POST['file_name']) || !is_string($_POST['file_name'])) {
$this->end_shutdown_function=true;
die();
}
$download_info = array();
$download_info['backup_id'] = sanitize_key($_POST['backup_id']);
$download_info['file_name'] = sanitize_text_field($_POST['file_name']);
@set_time_limit(600);
if (session_id())
session_write_close();
$downloader = new WPvivid_downloader();
$downloader->ready_download($download_info);
$ret['result'] = 'success';
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
if($this->wpvivid_download_log){
$this->wpvivid_download_log->WriteLog($message ,'error');
$this->wpvivid_download_log->CloseFile();
WPvivid_error_log::create_error_log($this->wpvivid_download_log->log_file);
}
else {
$id = uniqid('wpvivid-');
$log_file_name = $id . '_download';
if(!class_exists('WPvivid_Log'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-log.php';
}
$log = new WPvivid_Log();
$log->CreateLogFile($log_file_name, 'no_folder', 'download');
$log->WriteLog($message, 'error');
$log->CloseFile();
WPvivid_error_log::create_error_log($log->log_file);
}
error_log($message);
$this->end_shutdown_function=true;
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
$this->wpvivid_download_log->CloseFile();
$this->end_shutdown_function=true;
die();
}
public function get_download_progress()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_POST['backup_id'])) {
$backup_id = sanitize_key($_POST['backup_id']);
$ret['result'] = WPVIVID_SUCCESS;
$ret['files'] = array();
$ret['need_update'] = false;
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
if ($backup === false) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'backup id not found';
return $ret;
}
$backup_item = new WPvivid_Backup_Item($backup);
$backup_files = $backup_item->get_download_backup_files($backup_id);
foreach ($backup_files['files'] as $file) {
$path = $this->get_backup_path($backup_item, $file['file_name']);
//$path = $backup_item->get_local_path() . $file['file_name'];
if (file_exists($path)) {
$downloaded_size = size_format(filesize($path), 2);
} else {
$downloaded_size = '0';
}
$file['size'] = size_format($file['size'], 2);
$task = WPvivid_taskmanager::get_download_task_v2($file['file_name']);
if ($task === false) {
$ret['files'][$file['file_name']]['status'] = 'need_download';
$ret['files'][$file['file_name']]['html'] = '<div class="wpvivid-element-space-bottom">
<span class="wpvivid-element-space-right">Retriving (remote storage to web server)</span><span class="wpvivid-element-space-right">|</span><span>File Size: </span><span class="wpvivid-element-space-right">' . $file['size'] . '</span><span class="wpvivid-element-space-right">|</span><span>Downloaded Size: </span><span>0</span>
</div>
<div style="width:100%;height:10px; background-color:#dcdcdc;">
<div style="background-color:#0085ba; float:left;width:0%;height:10px;"></div>
</div>';
$ret['need_update'] = true;
} else {
if ($task['status'] === 'running') {
$ret['files'][$file['file_name']]['status'] = 'running';
$ret['files'][$file['file_name']]['progress_text'] = $task['progress_text'];
$ret['files'][$file['file_name']]['html'] = '<div class="wpvivid-element-space-bottom">
<span class="wpvivid-element-space-right">Retriving (remote storage to web server)</span><span class="wpvivid-element-space-right">|</span><span>File Size: </span><span class="wpvivid-element-space-right">' . $file['size'] . '</span><span class="wpvivid-element-space-right">|</span><span>Downloaded Size: </span><span>' . $downloaded_size . '</span>
</div>
<div style="width:100%;height:10px; background-color:#dcdcdc;">
<div style="background-color:#0085ba; float:left;width:' . $task['progress_text'] . '%;height:10px;"></div>
</div>';
$ret['need_update'] = true;
} elseif ($task['status'] === 'timeout') {
$ret['files'][$file['file_name']]['status'] = 'timeout';
$ret['files'][$file['file_name']]['progress_text'] = $task['progress_text'];
$ret['files'][$file['file_name']]['html'] = '<div class="wpvivid-element-space-bottom">
<span>Download timeout, please retry.</span>
</div>
<div>
<span>' . __('File Size: ', 'wpvivid-backuprestore') . '</span><span class="wpvivid-element-space-right">' . $file['size'] . '</span><span class="wpvivid-element-space-right">|</span><span class="wpvivid-element-space-right"><a class="wpvivid-download" style="cursor: pointer;">'. __('Prepare to Download', 'wpvivid-backuprestore').'</a></span>
</div>';
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
} elseif ($task['status'] === 'completed') {
$ret['files'][$file['file_name']]['status'] = 'completed';
$ret['files'][$file['file_name']]['html'] = '<span>' . __('File Size: ', 'wpvivid-backuprestore') . '</span><span class="wpvivid-element-space-right">' . $file['size'] . '</span><span class="wpvivid-element-space-right">|</span><span class="wpvivid-element-space-right wpvivid-ready-download"><a style="cursor: pointer;">'. __('Download', 'wpvivid-backuprestore').'</a></span>';
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
} elseif ($task['status'] === 'error') {
$ret['files'][$file['file_name']]['status'] = 'error';
$ret['files'][$file['file_name']]['error'] = $task['error'];
$ret['files'][$file['file_name']]['html'] = '<div class="wpvivid-element-space-bottom">
<span>' . $task['error'] . '</span>
</div>
<div>
<span>' . __('File Size: ', 'wpvivid-backuprestore') . '</span><span class="wpvivid-element-space-right">' . $file['size'] . '</span><span class="wpvivid-element-space-right">|</span><span class="wpvivid-element-space-right"><a class="wpvivid-download" style="cursor: pointer;">'. __('Prepare to Download', 'wpvivid-backuprestore').'</a></span>
</div>';
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
}
}
}
echo wp_json_encode($ret);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function deal_prepare_download_shutdown_error()
{
if($this->end_shutdown_function==false) {
$last_error = error_get_last();
if (!empty($last_error) && !in_array($last_error['type'], array(E_NOTICE,E_WARNING,E_USER_NOTICE,E_USER_WARNING,E_DEPRECATED), true)) {
$error = $last_error;
} else {
$error = false;
}
$ret['result'] = 'failed';
if ($error === false) {
$ret['error'] = 'unknown Error';
} else {
$ret['error'] = 'type: '. $error['type'] . ', ' . $error['message'] . ' file:' . $error['file'] . ' line:' . $error['line'];
error_log($ret['error']);
}
if($this->wpvivid_download_log){
$this->wpvivid_download_log->WriteLog($ret['error'] ,'error');
$this->wpvivid_download_log->CloseFile();
WPvivid_error_log::create_error_log($this->wpvivid_download_log->log_file);
}
else {
$id = uniqid('wpvivid-');
$log_file_name = $id . '_download';
if(!class_exists('WPvivid_Log'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-log.php';
}
$log = new WPvivid_Log();
$log->CreateLogFile($log_file_name, 'no_folder', 'download');
$log->WriteLog($ret['error'], 'notice');
$log->CloseFile();
WPvivid_error_log::create_error_log($log->log_file);
}
echo wp_json_encode($ret);
die();
}
}
public function init_download($backup_id)
{
if(empty($backup_id))
{
$ret['result']=WPVIVID_SUCCESS;
$ret['data']=array();
return $ret;
}
$ret['result']=WPVIVID_SUCCESS;
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
if($backup===false)
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='backup id not found';
return $ret;
}
$backup_item=new WPvivid_Backup_Item($backup);
$ret=$backup_item->get_download_backup_files($backup_id);
if($ret['result']==WPVIVID_SUCCESS){
$ret=$backup_item->get_download_progress($backup_id, $ret['files']);
WPvivid_taskmanager::update_download_cache($backup_id,$ret);
}
return $ret;
}
/**
* download backup file
*
* @since 0.9.1
*/
public function download_backup()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_REQUEST['backup_id']) && isset($_REQUEST['file_name'])) {
if (!empty($_REQUEST['backup_id']) && is_string($_REQUEST['backup_id'])) {
$backup_id = sanitize_key($_REQUEST['backup_id']);
} else {
die();
}
if (!empty($_REQUEST['file_name']) && is_string($_REQUEST['file_name'])) {
//$file_name=sanitize_file_name($_REQUEST['file_name']);
$file_name = sanitize_text_field($_REQUEST['file_name']);
} else {
die();
}
$cache = WPvivid_taskmanager::get_download_cache($backup_id);
if ($cache === false) {
$this->init_download($backup_id);
$cache = WPvivid_taskmanager::get_download_cache($backup_id);
}
$path = false;
if (array_key_exists($file_name, $cache['files'])) {
if ($cache['files'][$file_name]['status'] == 'completed') {
$path = $cache['files'][$file_name]['download_path'];
}
}
if ($path !== false) {
if (file_exists($path)) {
if (session_id())
session_write_close();
@ini_set( 'memory_limit', '1024M' );
$size = filesize($path);
if (!headers_sent()) {
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . $size);
header('Content-Transfer-Encoding: binary');
}
if ($size < 1024 * 1024 * 60) {
ob_end_clean();
readfile($path);
exit;
} else {
ob_end_clean();
$download_rate = 1024 * 10;
$file = fopen($path, "r");
while (!feof($file)) {
@set_time_limit(20);
// send the current file part to the browser
print fread($file, round($download_rate * 1024));
// flush the content to the browser
ob_flush();
flush();
// sleep one second
sleep(1);
}
fclose($file);
exit;
}
}
}
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
$admin_url = admin_url();
echo '<a href="'.esc_url($admin_url).'admin.php?page=WPvivid">file not found. please retry again.</a>';
die();
}
/**
* List backup record
*
* @since 0.9.1
*/
public function get_backup_list()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try
{
$json['result'] = 'success';
$html = '';
$html = apply_filters('wpvivid_add_backup_list', $html);
$json['html'] = $html;
echo wp_json_encode($json);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
/**
* Delete backup record
*
* @since 0.9.1
*/
public function delete_backup()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
if (isset($_POST['backup_id']) && !empty($_POST['backup_id']) && is_string($_POST['backup_id']) && isset($_POST['force']))
{
if ($_POST['force'] == 0 || $_POST['force'] == 1)
{
$force_del = sanitize_key($_POST['force']);
} else {
$force_del = 0;
}
$backup_id = sanitize_key($_POST['backup_id']);
$ret = $this->delete_backup_by_id($backup_id, $force_del);
echo wp_json_encode($ret);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
/**
* Delete backup records
*
* @since 0.9.1
*/
public function delete_backup_array()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
if (isset($_POST['backup_id']) && !empty($_POST['backup_id']) && is_array($_POST['backup_id']))
{
$backup_ids = $_POST['backup_id'];
$ret = array();
foreach ($backup_ids as $backup_id)
{
$backup_id = sanitize_key($backup_id);
$ret = $this->delete_backup_by_id($backup_id);
}
$html = '';
$html = apply_filters('wpvivid_add_backup_list', $html);
$ret['html'] = $html;
echo wp_json_encode($ret);
}
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function delete_backup_by_id($backup_id,$force=0)
{
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
if(!$backup)
{
$ret['result']='failed';
$ret['error']=__('Retrieving the backup(s) information failed while deleting the selected backup(s). Please try again later.', 'wpvivid-backuprestore');
return $ret;
}
$backup_item=new WPvivid_Backup_Item($backup);
if($backup_item->is_lock())
{
if($force==0)
{
$ret['result']='failed';
$ret['error']=__('Unable to delete the locked backup. Please unlock it first and try again.', 'wpvivid-backuprestore');
return $ret;
}
}
WPvivid_Backuplist::delete_backup($backup_id);
$backup_item->cleanup_local_backup();
$backup_item->cleanup_remote_backup();
$html = '';
$html = apply_filters('wpvivid_add_backup_list', $html);
$ret['html'] = $html;
$ret['result']='success';
return $ret;
}
public function delete_local_backup($backup_ids)
{
foreach ($backup_ids as $backup_id)
{
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
if(!$backup)
{
continue;
}
if(array_key_exists('lock',$backup))
{
continue;
}
$backup_item = new WPvivid_Backup_Item($backup);
$backup_item->cleanup_local_backup();
}
}
public function delete_task()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
if (isset($_POST['task_id']) && !empty($_POST['task_id']) && is_string($_POST['task_id'])) {
$task_id = sanitize_key($_POST['task_id']);
WPvivid_taskmanager::delete_task($task_id);
$json['result'] = 'success';
echo wp_json_encode($json);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
/**
* Add remote storage
*
* @since 0.9.1
*/
public function add_remote()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (empty($_POST) || !isset($_POST['remote']) || !is_string($_POST['remote']) || !isset($_POST['type']) || !is_string($_POST['type'])) {
die();
}
$json = $_POST['remote'];
$json = stripslashes($json);
$remote_options = json_decode($json, true);
if (is_null($remote_options)) {
die();
}
$remote_options['type'] = sanitize_text_field($_POST['type']);
if ($remote_options['type'] == 'amazons3')
{
if(isset($remote_options['s3Path']))
$remote_options['s3Path'] = rtrim($remote_options['s3Path'], "/");
}
$ret = $this->remote_collection->add_remote($remote_options);
if ($ret['result'] == 'success') {
$html = '';
$html = apply_filters('wpvivid_add_remote_storage_list', $html);
$ret['html'] = $html;
$pic = '';
$pic = apply_filters('wpvivid_schedule_add_remote_pic', $pic);
$ret['pic'] = $pic;
$dir = '';
$dir = apply_filters('wpvivid_get_remote_directory', $dir);
$ret['dir'] = $dir;
$schedule_local_remote = '';
$schedule_local_remote = apply_filters('wpvivid_schedule_local_remote', $schedule_local_remote);
$ret['local_remote'] = $schedule_local_remote;
$remote_storage = '';
$remote_storage = apply_filters('wpvivid_remote_storage', $remote_storage);
$ret['remote_storage'] = $remote_storage;
$remote_select_part = '';
$remote_select_part = apply_filters('wpvivid_remote_storage_select_part', $remote_select_part);
$ret['remote_select_part'] = $remote_select_part;
$default = array();
$remote_array = apply_filters('wpvivid_archieve_remote_array', $default);
$ret['remote_array'] = $remote_array;
$success_msg = __('You have successfully added a remote storage.', 'wpvivid-backuprestore');
$ret['notice'] = apply_filters('wpvivid_add_remote_notice', true, $success_msg);
}
else{
$ret['notice'] = apply_filters('wpvivid_add_remote_notice', false, $ret['error']);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
/**
* Delete remote storage
*
* @since 0.9.1
*/
public function delete_remote()
{
try {
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
if (empty($_POST) || !isset($_POST['remote_id']) || !is_string($_POST['remote_id'])) {
die();
}
$id = sanitize_key($_POST['remote_id']);
if (WPvivid_Setting::delete_remote_option($id)) {
$remote_selected = WPvivid_Setting::get_user_history('remote_selected');
if (in_array($id, $remote_selected)) {
WPvivid_Setting::update_user_history('remote_selected', array());
}
$ret['result'] = 'success';
$html = '';
$html = apply_filters('wpvivid_add_remote_storage_list', $html);
$ret['html'] = $html;
$pic = '';
$pic = apply_filters('wpvivid_schedule_add_remote_pic', $pic);
$ret['pic'] = $pic;
$dir = '';
$dir = apply_filters('wpvivid_get_remote_directory', $dir);
$ret['dir'] = $dir;
$schedule_local_remote = '';
$schedule_local_remote = apply_filters('wpvivid_schedule_local_remote', $schedule_local_remote);
$ret['local_remote'] = $schedule_local_remote;
$remote_storage = '';
$remote_storage = apply_filters('wpvivid_remote_storage', $remote_storage);
$ret['remote_storage'] = $remote_storage;
} else {
$ret['result'] = 'failed';
$ret['error'] = __('Failed to delete the remote storage, can not retrieve the storage infomation. Please try again.', 'wpvivid-backuprestore');
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
/**
* Retrieve remote storage
*
* @since 0.9.8
*/
public function retrieve_remote()
{
try {
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if (empty($_POST) || !isset($_POST['remote_id']) || !is_string($_POST['remote_id'])) {
die();
}
$id = sanitize_key($_POST['remote_id']);
$remoteslist = WPvivid_Setting::get_all_remote_options();
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = __('Failed to get the remote storage information. Please try again later.', 'wpvivid-backuprestore');
foreach ($remoteslist as $key => $value) {
if ($key == $id) {
if ($key === 'remote_selected') {
continue;
}
$value = apply_filters('wpvivid_encrypt_remote_password', $value);
$ret = $value;
$ret['result'] = WPVIVID_SUCCESS;
break;
}
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
/**
* Edit remote storage
*
* @since 0.9.8
*/
public function edit_remote()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (empty($_POST) || !isset($_POST['remote']) || !is_string($_POST['remote']) || !isset($_POST['id']) || !is_string($_POST['id']) || !isset($_POST['type']) || !is_string($_POST['type'])) {
die();
}
$json = sanitize_text_field($_POST['remote']);
$json = stripslashes($json);
$remote_options = json_decode($json, true);
if (is_null($remote_options)) {
die();
}
$remote_options['type'] = sanitize_text_field($_POST['type']);
if ($remote_options['type'] == 'amazons3')
{
if(isset($remote_options['s3Path']))
$remote_options['s3Path'] = rtrim($remote_options['s3Path'], "/");
}
$id=sanitize_key($_POST['id']);
$old_remote=WPvivid_Setting::get_remote_option($id);
foreach ($old_remote as $key=>$value)
{
if(isset($remote_options[$key]))
$old_remote[$key]=$remote_options[$key];
}
$ret = $this->remote_collection->update_remote($id, $old_remote);
if ($ret['result'] == 'success') {
$ret['result'] = WPVIVID_SUCCESS;
$html = '';
$html = apply_filters('wpvivid_add_remote_storage_list', $html);
$ret['html'] = $html;
$pic = '';
$pic = apply_filters('wpvivid_schedule_add_remote_pic', $pic);
$ret['pic'] = $pic;
$dir = '';
$dir = apply_filters('wpvivid_get_remote_directory', $dir);
$ret['dir'] = $dir;
$schedule_local_remote = '';
$schedule_local_remote = apply_filters('wpvivid_schedule_local_remote', $schedule_local_remote);
$ret['local_remote'] = $schedule_local_remote;
$remote_storage = '';
$remote_storage = apply_filters('wpvivid_remote_storage', $remote_storage);
$ret['remote_storage'] = $remote_storage;
$remote_select_part = '';
$remote_select_part = apply_filters('wpvivid_remote_storage_select_part', $remote_select_part);
$ret['remote_select_part'] = $remote_select_part;
$default = array();
$remote_array = apply_filters('wpvivid_archieve_remote_array', $default);
$ret['remote_array'] = $remote_array;
$success_msg = 'You have successfully updated the account information of your remote storage.';
$ret['notice'] = apply_filters('wpvivid_add_remote_notice', true, $success_msg);
}
else{
$ret['notice'] = apply_filters('wpvivid_add_remote_notice', false, $ret['error']);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
/**
* List exist remote
*
* @since 0.9.1
*/
public function list_remote()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
$ret['result'] = 'success';
$html = '';
$html = apply_filters('wpvivid_add_remote_storage_list', $html);
$ret['html'] = $html;
$pic = '';
$pic = apply_filters('wpvivid_schedule_add_remote_pic', $pic);
$ret['pic'] = $pic;
$dir = '';
$dir = apply_filters('wpvivid_get_remote_directory', $dir);
$ret['dir'] = $dir;
$schedule_local_remote = '';
$schedule_local_remote = apply_filters('wpvivid_schedule_local_remote', $schedule_local_remote);
$ret['local_remote'] = $schedule_local_remote;
$remote_storage = '';
$remote_storage = apply_filters('wpvivid_remote_storage', $remote_storage);
$ret['remote_storage'] = $remote_storage;
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
/**
* Test remote connection
*
* @since 0.9.1
*/
public function test_remote_connection()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (empty($_POST) || !isset($_POST['remote']) || !is_string($_POST['remote']) || !isset($_POST['type']) || !is_string($_POST['type'])) {
die();
}
$json = sanitize_text_field($_POST['remote']);
$json = stripslashes($json);
$remote_options = json_decode($json, true);
if (is_null($remote_options)) {
die();
}
$remote_options['type'] = sanitize_text_field($_POST['type']);
$remote = $this->remote_collection->get_remote($remote_options);
$ret = $remote->test_connect();
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
/**
* Get backup schedule data
*
* @since 0.9.1
*/
public function get_schedule()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
$schedule = WPvivid_Schedule::get_schedule();
$schedule['next_start'] = gmdate("l, F d, Y H:i", $schedule['next_start']);
$ret['result'] = 'success';
$ret['data'] = $schedule;
$ret['user_history'] = WPvivid_Setting::get_user_history('remote_selected');
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function scan_last_restore()
{
try
{
$dir=WPvivid_Setting::get_backupdir();
$restore_data_file=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.'wpvivid_restoredata';
if(file_exists($restore_data_file))
{
$ret['has_exist_restore']=1;
}
else
{
$ret['has_exist_restore']=0;
}
$ret['has_old_files']=0;
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
$ret['has_exist_restore']=1;
$ret['restore_error']=$message;
}
return $ret;
}
public function check_max_allow_packet_ex()
{
$max_all_packet_warning=false;
global $wpdb;
$wpdb->get_results('SET NAMES utf8mb4', ARRAY_A);
$max_allowed_packet = $wpdb->get_results('SELECT @@session.max_allowed_packet;',ARRAY_N);
if($max_allowed_packet)
{
if(is_array($max_allowed_packet)&&isset($max_allowed_packet[0])&&isset($max_allowed_packet[0][0]))
{
if($max_allowed_packet[0][0]<16777216){
$max_all_packet_warning = 'max_allowed_packet = '.size_format($max_allowed_packet[0][0]).' is too small. The recommended value is 16M or higher. Too small value could lead to a failure when importing a larger database.';
}
}
}
return $max_all_packet_warning;
}
public function init_restore_page()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
if (!isset($_POST['backup_id']) || empty($_POST['backup_id']) || !is_string($_POST['backup_id']))
{
die();
}
//$this->restore_data = new WPvivid_restore_data();
$ret_scan_last_restore = $this->scan_last_restore();
$backup_id = sanitize_key($_POST['backup_id']);
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
$backup_item = new WPvivid_Backup_Item($backup);
$ret = $backup_item->check_backup_files();
$ret['is_migrate'] = $backup_item->check_migrate_file();
if ($backup_item->get_backup_type() == 'Upload' || $backup_item->get_backup_type() == 'Migration')
{
$is_display = $backup_item->is_display_migrate_option();
if($is_display === true)
{
$ret['is_migrate_ui'] = 1;
}
else {
$ret['is_migrate_ui'] = 0;
}
} else {
$ret['is_migrate_ui'] = 0;
}
$ret['skip_backup_old_site'] = 1;
$ret['skip_backup_old_database'] = 1;
$ret = array_merge($ret, $ret_scan_last_restore);
$ret['max_allow_packet_warning'] = $this->check_max_allow_packet_ex();
$common_setting = WPvivid_Setting::get_option('wpvivid_common_setting');
if(isset($common_setting['restore_memory_limit']) && !empty($common_setting['restore_memory_limit'])){
$memory_limit = $common_setting['restore_memory_limit'];
}
else{
$memory_limit = WPVIVID_RESTORE_MEMORY_LIMIT;
}
@ini_set('memory_limit', $memory_limit);
$memory_limit = ini_get('memory_limit');
$unit = strtoupper(substr($memory_limit, -1));
if ($unit == 'K')
{
$memory_limit_tmp = intval($memory_limit) * 1024;
}
else if ($unit == 'M')
{
$memory_limit_tmp = intval($memory_limit) * 1024 * 1024;
}
else if ($unit == 'G')
{
$memory_limit_tmp = intval($memory_limit) * 1024 * 1024 * 1024;
}
else{
$memory_limit_tmp = intval($memory_limit);
}
if ($memory_limit_tmp < 256 * 1024 * 1024)
{
$ret['memory_limit_warning'] = 'memory_limit = ' . $memory_limit . ' is too small. The recommended value is 256M or higher. Too small value could result in a failure of website restore.';
} else {
$ret['memory_limit_warning'] = false;
}
if ($ret['result'] == WPVIVID_FAILED)
{
//$this->wpvivid_handle_restore_error($ret['error'], 'Init restore page');
}
$has_zero_date=$backup_item->check_has_zero_date();
if($has_zero_date)
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-db-method.php';
$db_method = new WPvivid_DB_Method();
$ret_sql_mode = $db_method->get_sql_mode();
if(preg_match('/NO_ZERO_DATE/', $ret_sql_mode['mysql_mode']))
{
$ret['has_zero_date']=1;
}
}
$wp_version_check=$backup_item->check_wp_version();
if($wp_version_check)
{
$ret['wp_version_check']=true;
}
else
{
$ret['wp_version_check']=false;
}
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function get_restore_file_is_migrate()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (!isset($_POST['backup_id']) || empty($_POST['backup_id']) || !is_string($_POST['backup_id'])) {
die();
}
$backup_id = sanitize_key($_POST['backup_id']);
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
$backup_item = new WPvivid_Backup_Item($backup);
$ret = $backup_item->check_backup_files();
$ret['is_migrate'] = $backup_item->check_migrate_file();
if ($backup_item->get_backup_type() == 'Upload' || $backup_item->get_backup_type() == 'Migration')
{
$is_display = $backup_item->is_display_migrate_option();
if($is_display === true){
$ret['is_migrate_ui'] = 1;
}
else{
$ret['is_migrate_ui'] = 0;
}
/*if( $ret['is_migrate']==0)
$ret['is_migrate_ui'] = 1;
else
$ret['is_migrate_ui'] = 0;*/
} else {
$ret['is_migrate_ui'] = 0;
}
if ($ret['result'] == WPVIVID_FAILED) {
//$this->wpvivid_handle_restore_error($ret['error'], 'Init restore page');
}
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function delete_last_restore_data()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
$this->restore_data = new WPvivid_restore_data();
$this->restore_data->clean_restore_data();
$ret['result'] = 'success';
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
/**
* Prepare backup files for restore
*
* @since 0.9.1
*/
public function prepare_restore()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (!isset($_POST['backup_id']) || empty($_POST['backup_id']) || !is_string($_POST['backup_id'])) {
die();
}
$backup_id = sanitize_key($_POST['backup_id']);
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
$backup_item = new WPvivid_Backup_Item($backup);
$ret = $backup_item->check_backup_files();
if ($backup_item->get_backup_type() == 'Upload')
{
$ret['is_migrate'] = 1;
} else {
$ret['is_migrate'] = 0;
}
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
/**
* Download backup files from remote server for restore
*
* @since 0.9.1
*/
public function download_restore_file()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (!isset($_POST['backup_id']) || empty($_POST['backup_id']) || !is_string($_POST['backup_id'])
|| !isset($_POST['file_name']) || empty($_POST['file_name']) || !is_string($_POST['file_name'])) {
die();
}
@set_time_limit(600);
$backup_id = sanitize_key($_POST['backup_id']);
//$file_name=sanitize_file_name($_POST['file_name']);
$file_name = sanitize_text_field($_POST['file_name']);
$file['file_name'] = $file_name;
$file['size'] = sanitize_key($_POST['size']);
if(isset($_POST['md5']))
{
$file['md5'] = sanitize_key($_POST['md5']);
}
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
if (!$backup) {
echo wp_json_encode(array('result' => WPVIVID_FAILED, 'error' => 'backup not found'));
die();
}
$backup_item = new WPvivid_Backup_Item($backup);
$remote_option = $backup_item->get_remote();
if ($remote_option === false) {
echo wp_json_encode(array('result' => WPVIVID_FAILED, 'error' => 'Retrieving the cloud storage information failed while downloading backups. Please try again later.'));
die();
}
//$downloader = new WPvivid_downloader();
//$ret = $downloader->download($file, $local_path, $remote_option);
$download_info = array();
$download_info['backup_id'] = sanitize_key($_POST['backup_id']);
//$download_info['file_name']=sanitize_file_name($_POST['file_name']);
$download_info['file_name'] = sanitize_text_field($_POST['file_name']);
//set_time_limit(600);
if (session_id())
session_write_close();
$downloader = new WPvivid_downloader();
$downloader->ready_download($download_info);
$ret['result'] = 'success';
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function download_restore_progress()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
if (!isset($_POST['file_name'])) {
die();
}
$file_name=sanitize_text_field($_POST['file_name']);
$file_size = sanitize_key($_POST['size']);
$task = WPvivid_taskmanager::get_download_task_v2($file_name);
if ($task === false)
{
$check_status = false;
$backupdir=WPvivid_Setting::get_backupdir();
$local_storage_dir = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backupdir;
$local_file=$local_storage_dir.DIRECTORY_SEPARATOR.$file_name;
if(file_exists($local_file))
{
if(filesize($local_file)==$file_size)
{
$check_status = true;
}
}
if($check_status){
$ret['result'] = WPVIVID_SUCCESS;
$ret['status'] = 'completed';
}
else {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'not found download file';
//$this->wpvivid_handle_restore_error($ret['error'], 'Downloading backup file');
}
echo wp_json_encode($ret);
} else {
$ret['result'] = WPVIVID_SUCCESS;
$ret['status'] = $task['status'];
if(isset($task['download_descript']))
{
$ret['log'] = $task['download_descript'];
}
else
{
$ret['log'] = '';
}
$ret['error'] = $task['error'];
echo wp_json_encode($ret);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function download_check_has_zero_date()
{
try
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if (!isset($_POST['backup_id'])) {
die();
}
$backup_id = sanitize_key($_POST['backup_id']);
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
$backup_item = new WPvivid_Backup_Item($backup);
$has_zero_date=$backup_item->check_has_zero_date();
if($has_zero_date)
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-db-method.php';
$db_method = new WPvivid_DB_Method();
$ret_sql_mode = $db_method->get_sql_mode();
if(preg_match('/NO_ZERO_DATE/', $ret_sql_mode['mysql_mode']))
{
$ret['has_zero_date']=1;
}
}
$wp_version_check=$backup_item->check_wp_version();
if($wp_version_check)
{
$ret['wp_version_check']=true;
}
else
{
$ret['wp_version_check']=false;
}
$ret['result']=WPVIVID_SUCCESS;
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function wpvivid_handle_restore_error($error_message, $error_type)
{
$this->restore_data=new WPvivid_restore_data();
$this->restore_data->delete_restore_log();
$this->restore_data->write_log($error_type, 'error');
$this->restore_data->write_log($error_message, 'error');
$this->restore_data->save_error_log_to_debug();
}
public function wpvivid_handle_remote_storage_error($error_message, $error_type)
{
$id = uniqid('wpvivid-');
$log_file_name = $id . '_add_remote';
$log = new WPvivid_Log();
$log->CreateLogFile($log_file_name, 'no_folder', 'Add Remote Test Connection');
$log->WriteLog('Remote Type: '.$error_type, 'notice');
if(isset($ret['error'])) {
$log->WriteLog($error_message, 'notice');
}
$log->CloseFile();
WPvivid_error_log::create_error_log($log->log_file);
}
/**
* Start restore
*
* @since 0.9.1
*/
public function restore()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
if(!$check)
{
die();
}
$this->end_shutdown_function=false;
register_shutdown_function(array($this,'deal_restore_shutdown_error'));
if(!isset($_POST['backup_id'])||empty($_POST['backup_id'])||!is_string($_POST['backup_id']))
{
$this->end_shutdown_function=true;
die();
}
$backup_id=sanitize_key($_POST['backup_id']);
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
if($backup===false)
{
die();
}
$this->restore_data=new WPvivid_restore_data();
$restore_options=array();
if(isset($_POST['restore_options']))
{
$json=sanitize_text_field($_POST['restore_options']);
$json = stripslashes($json);
$restore_options = json_decode($json, 1);
if(is_null($restore_options))
{
$restore_options=array();
}
}
try
{
if ($this->restore_data->has_restore())
{
$status = $this->restore_data->get_restore_status();
if ($status === WPVIVID_RESTORE_ERROR)
{
$ret['result'] =WPVIVID_FAILED;
$ret['error'] = $this->restore_data->get_restore_error();
$this->restore_data->save_error_log_to_debug();
$this->restore_data->delete_temp_files();
$this->_disable_maintenance_mode();
echo wp_json_encode($ret);
$this->end_shutdown_function=true;
die();
}
else if ($status === WPVIVID_RESTORE_COMPLETED)
{
$this->write_litespeed_rule(false);
$this->restore_data->write_log('disable maintenance mode', 'notice');
$this->restore_data->delete_temp_files();
$this->_disable_maintenance_mode();
echo wp_json_encode(array('result' => 'finished'));
$this->end_shutdown_function=true;
die();
}
}
else {
$this->restore_data->init_restore_data($backup_id,$restore_options);
$this->restore_data->write_log('init restore data', 'notice');
}
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
echo esc_html($message);
$this->end_shutdown_function=true;
die();
}
try
{
$this->_enable_maintenance_mode();
$this->write_litespeed_rule();
$restore=new WPvivid_Restore();
$common_setting = WPvivid_Setting::get_option('wpvivid_common_setting');
if(isset($common_setting['restore_memory_limit']) && !empty($common_setting['restore_memory_limit'])){
$memory_limit = $common_setting['restore_memory_limit'];
}
else{
$memory_limit = WPVIVID_RESTORE_MEMORY_LIMIT;
}
@ini_set('memory_limit', $memory_limit);
$ret=$restore->restore();
if($ret['result']==WPVIVID_FAILED&&$ret['error']=='A restore task is already running.')
{
echo wp_json_encode(array('result'=> WPVIVID_SUCCESS));
$this->end_shutdown_function=true;
die();
}
$this->_disable_maintenance_mode();
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
$this->restore_data->delete_temp_files();
$this->restore_data->update_error($message);
$this->restore_data->write_log($message,'error');
$this->restore_data->save_error_log_to_debug();
$this->_disable_maintenance_mode();
echo wp_json_encode(array('result'=>WPVIVID_FAILED,'error'=>$message));
$this->end_shutdown_function=true;
die();
}
if($ret['result']==WPVIVID_FAILED)
{
$this->restore_data->delete_temp_files();
$this->_disable_maintenance_mode();
}
echo wp_json_encode($ret);
$this->end_shutdown_function=true;
die();
}
public function write_litespeed_rule($open=true)
{
$litespeed=false;
if ( isset( $_SERVER['HTTP_X_LSCACHE'] ) && $_SERVER['HTTP_X_LSCACHE'] )
{
$litespeed=true;
}
elseif ( isset( $_SERVER['LSWS_EDITION'] ) && strpos( $_SERVER['LSWS_EDITION'], 'Openlitespeed' ) === 0 ) {
$litespeed=true;
}
elseif ( isset( $_SERVER['SERVER_SOFTWARE'] ) && $_SERVER['SERVER_SOFTWARE'] == 'LiteSpeed' ) {
$litespeed=true;
}
if($litespeed)
{
if (function_exists('insert_with_markers'))
{
$home_path = get_home_path();
$htaccess_file = $home_path . '.htaccess';
if ( ( ! file_exists( $htaccess_file ) && is_writable( $home_path ) ) || is_writable( $htaccess_file ) )
{
if ( got_mod_rewrite() )
{
if($open)
{
$line=array();
$line[]='<IfModule Litespeed>';
$line[]='RewriteEngine On';
$line[]='RewriteRule .* - [E=noabort:1, E=noconntimeout:1]';
$line[]='</IfModule>';
insert_with_markers($htaccess_file,'WPvivid_Restore',$line);
}
else
{
insert_with_markers($htaccess_file,'WPvivid_Restore','');
}
}
}
}
}
}
public function deal_restore_shutdown_error()
{
if($this->end_shutdown_function===false)
{
$last_error = error_get_last();
if (!empty($last_error) && !in_array($last_error['type'], array(E_NOTICE,E_WARNING,E_USER_NOTICE,E_USER_WARNING,E_DEPRECATED), true))
{
$error = $last_error;
} else {
$error = false;
}
//$this->task_monitor($task_id,$error);
if ($error !== false)
{
$message = 'type: '. $error['type'] . ', ' . $error['message'] . ' file:' . $error['file'] . ' line:' . $error['line'];
$this->restore_data->delete_temp_files();
$this->restore_data->update_error($message);
$this->restore_data->write_log($message,'error');
$this->restore_data->save_error_log_to_debug();
//save_error_log_to_debug
$this->_disable_maintenance_mode();
echo wp_json_encode(array('result'=>WPVIVID_FAILED,'error'=>$message));
}
else {
$message = __('restore failed error unknown', 'wpvivid-backuprestore');
$this->restore_data->delete_temp_files();
$this->restore_data->update_error($message);
$this->restore_data->write_log($message,'error');
$this->restore_data->save_error_log_to_debug();
$this->_disable_maintenance_mode();
echo wp_json_encode(array('result'=>WPVIVID_FAILED,'error'=>$message));
}
die();
}
}
/**
* Get restore progress
*
* @since 0.9.1
*/
public function get_restore_progress()
{
try
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
if(!$check)
{
die();
}
if(!isset($_POST['backup_id'])||empty($_POST['backup_id'])||!is_string($_POST['backup_id']))
{
$this->end_shutdown_function=true;
die();
}
$backup_id=sanitize_key($_POST['backup_id']);
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
if($backup===false)
{
die();
}
$this->restore_data = new WPvivid_restore_data();
if ($this->restore_data->has_restore())
{
$ret['result'] = 'success';
$ret['status'] = $this->restore_data->get_restore_status();
if ($ret['status'] == WPVIVID_RESTORE_ERROR) {
$this->restore_data->save_error_log_to_debug();
}
$ret['log'] = $this->restore_data->get_log_content();
echo wp_json_encode($ret);
die();
} else {
$ret['result'] = 'failed';
$ret['error'] = __('The restore file not found. Please verify the file exists.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
}
public function init_filesystem()
{
$credentials = request_filesystem_credentials(wp_nonce_url(admin_url('admin.php')."?page=WPvivid", 'wpvivid-nonce'));
if ( ! WP_Filesystem($credentials) )
{
return false;
}
return true;
}
public function _enable_maintenance_mode()
{
//enable maintenance mode by create the .maintenance file.
//If your wordpress version is greater than 4.6, use the enable_maintenance_mode filter to make our ajax request pass
$this->init_filesystem();
global $wp_filesystem;
$file = $wp_filesystem->abspath() . '.maintenance';
$maintenance_string = '<?php $upgrading = ' . (time()+1200) . ';';
$maintenance_string.='global $wp_version;';
$maintenance_string.='$version_check=version_compare($wp_version,4.6,\'>\' );';
$maintenance_string.='if($version_check)';
$maintenance_string.='{';
$maintenance_string.='if(!function_exists(\'enable_maintenance_mode_filter\'))';
$maintenance_string.='{';
$maintenance_string.='function enable_maintenance_mode_filter($enable_checks,$upgrading)';
$maintenance_string.='{';
$maintenance_string.='if(is_admin()&&isset($_POST[\'wpvivid_restore\']))';
$maintenance_string.='{';
$maintenance_string.='return false;';
$maintenance_string.='}';
$maintenance_string.='return $enable_checks;';
$maintenance_string.='}';
$maintenance_string.='}';
$maintenance_string.='add_filter( \'enable_maintenance_mode\',\'enable_maintenance_mode_filter\',10, 2 );';
$maintenance_string.='}';
$maintenance_string.='else';
$maintenance_string.='{';
$maintenance_string.='if(is_admin()&&isset($_POST[\'wpvivid_restore\']))';
$maintenance_string.='{';
$maintenance_string.='global $upgrading;';
$maintenance_string.='$upgrading=0;';
$maintenance_string.='return 1;';
$maintenance_string.='}';
$maintenance_string.='}';
if ($wp_filesystem->exists( $file ) )
{
$wp_filesystem->delete($file);
}
$wp_filesystem->put_contents($file, $maintenance_string, FS_CHMOD_FILE);
}
public function _disable_maintenance_mode()
{
$this->init_filesystem();
global $wp_filesystem;
$file = $wp_filesystem->abspath() . '.maintenance';
if ($wp_filesystem->exists( $file ))
{
$wp_filesystem->delete($file);
}
}
public function deal_restore_error($error_type,$error)
{
$message = 'A '.$error_type.' has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
error_log($message);
echo esc_html($message);
}
public function update_last_backup_time($task)
{
WPvivid_Setting::update_option('wpvivid_last_msg',$task);
}
public function update_last_backup_task($task)
{
apply_filters('wpvivid_set_backup_report_addon_mainwp', $task);
}
/**
* Get last backup information
*
* @since 0.9.1
*/
public function get_last_backup()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
$html = '';
$html = apply_filters('wpvivid_get_last_backup_message', $html);
$ret['data'] = $html;
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function wpvivid_get_last_backup_message($html)
{
$html='';
$message=WPvivid_Setting::get_last_backup_message('wpvivid_last_msg');
if(empty($message)){
$last_message=__('The last backup message not found.', 'wpvivid-backuprestore');
}
else{
if(isset($message['status']['start_time']))
{
$message['status']['start_time'] = gmdate("l, F-d-Y H:i", strtotime($message['status']['start_time']));
$last_message=$message['status']['start_time'];
}
else
{
$last_message=__('The last backup message not found.', 'wpvivid-backuprestore');
}
}
$html .= '<strong>'.__('Last Backup: ', 'wpvivid-backuprestore').'</strong>'.$last_message;
return $html;
}
public function wpvivid_get_last_backup_message_output()
{
$message=WPvivid_Setting::get_last_backup_message('wpvivid_last_msg');
if(empty($message)){
?>
<strong><?php esc_html_e('Last Backup: ', 'wpvivid-backuprestore'); ?></strong><?php esc_html_e('The last backup message not found.', 'wpvivid-backuprestore'); ?>
<?php
}
else{
if(isset($message['status']['start_time']))
{
if($message['status']['str'] == 'completed'){
$last_backup_status='Succeeded';
$span_style='color: #81d742;';
}
elseif($message['status']['str'] == 'error'){
$last_backup_status='Failed';
$span_style='color: #ff0000;';
}
elseif($message['status']['str'] == 'cancel'){
$last_backup_status='Failed';
$span_style='color: #ff0000;';
}
else{
$last_backup_status='Succeeded';
$span_style='color: #81d742;';
}
?>
<strong><?php esc_html_e('Last Backup: ', 'wpvivid-backuprestore'); ?></strong>
<span style="<?php echo esc_attr($span_style); ?>">
<?php
echo esc_html(gmdate("F-d-Y H:i", strtotime($message['status']['start_time'])).' ('.$last_backup_status.')');
?>
</span>
<?php
}
else
{
?>
<strong><?php esc_html_e('Last Backup: ', 'wpvivid-backuprestore'); ?></strong><?php esc_html_e('The last backup message not found.', 'wpvivid-backuprestore'); ?>
<?php
}
}
}
public function list_tasks()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try
{
if (isset($_POST['backup_id']))
{
$backup_id=sanitize_key($_POST['backup_id']);
}
else{
$backup_id=false;
}
$ret = $this->_list_tasks($backup_id);
$backup_success_count=WPvivid_Setting::get_option('wpvivid_backup_success_count');
if(!empty($backup_success_count)){
WPvivid_Setting::delete_option('wpvivid_backup_success_count');
}
$backup_error_array=WPvivid_Setting::get_option('wpvivid_backup_error_array');
if(!empty($backup_error_array)){
WPvivid_Setting::delete_option('wpvivid_backup_error_array');
}
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function _list_tasks($backup_id)
{
$tasks=WPvivid_Setting::get_tasks();
$ret=array();
$list_tasks=array();
foreach ($tasks as $task)
{
if($task['action']=='backup')
{
$backup=new WPvivid_Backup_Task($task['id']);
$list_tasks[$task['id']]=$backup->get_backup_task_info($task['id']);
if($list_tasks[$task['id']]['task_info']['need_next_schedule']===true){
$timestamp = wp_next_scheduled(WPVIVID_TASK_MONITOR_EVENT,array($task['id']));
if($timestamp===false)
{
$this->add_monitor_event($task['id'],20);
}
}
/*if($list_tasks[$task['id']]['task_info']['need_update_last_task']===true){
$task_msg = WPvivid_taskmanager::get_task($task['id']);
$this->update_last_backup_task($task_msg);
if($task['type'] === 'Cron') {
//update last backup time
//do_action('wpvivid_update_schedule_last_time_addon');
}
}*/
//<div id="wpvivid_estimate_backup_info" style="float:left; ' . $list_tasks[$task['id']]['task_info']['display_estimate_backup'] . '">
// <div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Database Size:', 'wpvivid-backuprestore') . '</span><span id="wpvivid_backup_database_size">' . $list_tasks[$task['id']]['task_info']['db_size'] . '</span></div>
// <div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('File Size:', 'wpvivid-backuprestore') . '</span><span id="wpvivid_backup_file_size">' . $list_tasks[$task['id']]['task_info']['file_size'] . '</span></div>
// </div>
$list_tasks[$task['id']]['progress_html'] = '<div class="action-progress-bar" id="wpvivid_action_progress_bar">
<div class="action-progress-bar-percent" id="wpvivid_action_progress_bar_percent" style="height:24px;width:' . $list_tasks[$task['id']]['task_info']['backup_percent'] . '"></div>
</div>
<div id="wpvivid_estimate_upload_info" style="float: left;">
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Total Size:', 'wpvivid-backuprestore') . '</span><span>' . $list_tasks[$task['id']]['task_info']['total'] . '</span></div>
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Uploaded:', 'wpvivid-backuprestore') . '</span><span>' . $list_tasks[$task['id']]['task_info']['upload'] . '</span></div>
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Speed:', 'wpvivid-backuprestore') . '</span><span>' . $list_tasks[$task['id']]['task_info']['speed'] . '</span></div>
</div>
<div style="float: left;">
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Network Connection:', 'wpvivid-backuprestore') . '</span><span>' . $list_tasks[$task['id']]['task_info']['network_connection'] . '</span></div>
</div>
<div style="clear:both;"></div>
<div style="margin-left:10px; float: left; width:100%;"><p id="wpvivid_current_doing">' . $list_tasks[$task['id']]['task_info']['descript'] . '</p></div>
<div style="clear: both;"></div>
<div>
<div id="wpvivid_backup_cancel" class="backup-log-btn"><input class="button-primary" id="wpvivid_backup_cancel_btn" type="submit" value="' . esc_attr('Cancel', 'wpvivid-backuprestore') . '" style="' . $list_tasks[$task['id']]['task_info']['css_btn_cancel'] . '" /></div>
<div id="wpvivid_backup_log" class="backup-log-btn"><input class="button-primary" id="wpvivid_backup_log_btn" type="submit" value="' . esc_attr('Log', 'wpvivid-backuprestore') . '" style="' . $list_tasks[$task['id']]['task_info']['css_btn_log'] . '" /></div>
</div>
<div style="clear: both;"></div>';
}
}
WPvivid_taskmanager::delete_marked_task();
$ret['backuplist_html'] = false;
$backup_success_count=WPvivid_Setting::get_option('wpvivid_backup_success_count');
if(!empty($backup_success_count)){
//$notice_msg = $backup_success_count.' backup tasks have been completed. Please switch to <a href="#" onclick="wpvivid_click_switch_page(\'wrap\', \'wpvivid_tab_log\', true);">Log</a> page to check the details.';
$notice_msg = sprintf('%d backup tasks have been completed. Please switch to <a href="#" onclick="wpvivid_click_switch_page(\'wrap\', \'wpvivid_tab_log\', true);">Log</a> page to check the details.', $backup_success_count);
$success_notice_html='<div class="notice notice-success is-dismissible inline"><p>'.$notice_msg.'</p>
<button type="button" class="notice-dismiss" onclick="click_dismiss_notice(this);">
<span class="screen-reader-text">Dismiss this notice.</span>
</button>
</div>';
//WPvivid_Setting::delete_option('wpvivid_backup_success_count');
$html = '';
$html = apply_filters('wpvivid_add_backup_list', $html);
$ret['backuplist_html'] = $html;
}
else {
$success_notice_html = false;
}
$ret['success_notice_html'] = $success_notice_html;
$backup_error_array=WPvivid_Setting::get_option('wpvivid_backup_error_array');
if(!empty($backup_error_array)){
$error_notice_html = array();
foreach ($backup_error_array as $key => $value){
$error_notice_html['bu_error']['task_id']=$value['task_id'];
$error_notice_html['bu_error']['error_msg']=$value['error_msg'];
}
//WPvivid_Setting::delete_option('wpvivid_backup_error_array');
$html = '';
$html = apply_filters('wpvivid_add_backup_list', $html);
$ret['backuplist_html'] = $html;
}
else{
$error_notice_html = false;
}
$ret['error_notice_html'] = $error_notice_html;
$ret['backup']['result']='success';
$ret['backup']['data']=$list_tasks;
$ret['download']=array();
if($backup_id !== false && !empty($backup_id)) {
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
if($backup===false)
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='backup id not found';
return $ret;
}
$backup_item=new WPvivid_Backup_Item($backup);
$ret['download']=$backup_item->update_download_page($backup_id);
}
$html='';
$html=apply_filters('wpvivid_get_last_backup_message', $html);
$ret['last_msg_html']=$html;
$html='';
$html=apply_filters('wpvivid_get_log_list', $html);
$ret['log_html'] = $html['html'];
$ret['log_count'] = $html['log_count'];
return $ret;
}
public function clean_cache()
{
delete_option('wpvivid_download_cache');
delete_option('wpvivid_download_task');
WPvivid_taskmanager::delete_out_of_date_finished_task();
WPvivid_taskmanager::delete_ready_task();
}
/**
* Get backup local storage path
*
* @since 0.9.1
*/
public function get_dir()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
$dir = WPvivid_Setting::get_option('wpvivid_local_setting');
if (!isset($dir['path'])) {
$dir = WPvivid_Setting::set_default_local_option();
}
if (!is_dir(WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $dir['path'])) {
@mkdir(WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $dir['path'], 0777, true);
@fopen(WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $dir['path'] . '/index.html', 'x');
$tempfile = @fopen(WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $dir['path'] . '/.htaccess', 'x');
if ($tempfile) {
//$text = "deny from all";
$text="<IfModule mod_rewrite.c>\r\nRewriteEngine On\r\nRewriteRule .* - [F,L]\r\n</IfModule>";
fwrite($tempfile, $text);
fclose($tempfile);
} else {
$ret['result'] = 'failed';
$ret['error'] = __('Getting backup directory failed. Please try again later.', 'wpvivid-backuprestore');
}
}
$ret['result'] = 'success';
$ret['path'] = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $dir['path'];
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
/**
* Set security lock for backup record
*
* @since 0.9.1
*/
public function set_security_lock()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
if (isset($_POST['backup_id']) && !empty($_POST['backup_id']) && is_string($_POST['backup_id']) && isset($_POST['lock'])) {
$backup_id = sanitize_key($_POST['backup_id']);
if ($_POST['lock'] == 0 || $_POST['lock'] == 1) {
$lock = sanitize_key($_POST['lock']);
} else {
$lock = 0;
}
$ret = WPvivid_Backuplist::set_security_lock($backup_id, $lock);
echo wp_json_encode($ret);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
/**
* Get Web-server disk space in use
*
* @since 0.9.1
*/
public function junk_files_info()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
$ret['result'] = 'success';
$ret['data'] = $this->_junk_files_info_ex();
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function check_is_a_wpvivid_backup($file_name)
{
$ret=WPvivid_Backup_Item::get_backup_file_info($file_name);
if($ret['result'] === WPVIVID_SUCCESS){
return true;
}
elseif($ret['result'] === WPVIVID_FAILED){
return $ret['error'];
}
}
public function check_file_is_a_wpvivid_backup($file_name,&$backup_id)
{
if(preg_match('/wpvivid-.*_.*_.*\.zip$/',$file_name))
{
if(preg_match('/wpvivid-(.*?)_/',$file_name,$matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
$backup_id_list=WPvivid_Backuplist::get_has_remote_backuplist();
if(in_array($id, $backup_id_list))
{
return false;
}
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public function get_wpvivid_backup_size()
{
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR;
$backups=array();
$count = 0;
$ret_size = 0;
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
$count++;
if (is_dir($path . $filename))
{
continue;
} else {
if($this->check_file_is_a_wpvivid_backup($filename,$backup_id))
{
if($this->check_is_a_wpvivid_backup($path.$filename) === true)
{
$backups[$backup_id]['files'][] = $filename;
}
}
}
}
}
if($handler)
@closedir($handler);
}
if(!empty($backups))
{
foreach ($backups as $backup_id =>$backup)
{
$backup_data['result']='success';
$backup_data['files']=array();
if(empty($backup['files']))
continue;
foreach ($backup['files'] as $file)
{
$ret_size += filesize($path.$file);
}
}
}
}
else{
$ret_size = 0;
}
return $ret_size;
}
public function _junk_files_info_ex()
{
try
{
$log_dir = WPvivid_tools::GetSaveLogFolder();
$log_dir_byte = $this->GetDirectorySize($log_dir);
$ret['log_dir_size'] = $this->formatBytes($log_dir_byte);
$ret['backup_cache_size'] = 0;
$path = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
$handler=opendir($path);
if($handler===false)
{
$ret['backup_cache_size'] = 0;
}
while(($filename=readdir($handler))!==false)
{
if(preg_match('#pclzip-.*\.tmp#', $filename)){
$ret['backup_cache_size'] += filesize($path.DIRECTORY_SEPARATOR.$filename);
}
if(preg_match('#pclzip-.*\.gz#', $filename)){
$ret['backup_cache_size'] += filesize($path.DIRECTORY_SEPARATOR.$filename);
}
}
@closedir($handler);
$backup_id_list=WPvivid_Backuplist::get_has_remote_backuplist();
foreach ($backup_id_list as $backup_id)
{
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
if(!$backup)
{
continue;
}
if(array_key_exists('lock',$backup))
{
continue;
}
$backup_item = new WPvivid_Backup_Item($backup);
$file=$backup_item->get_files(false);
foreach ($file as $filename)
{
if(file_exists($path.DIRECTORY_SEPARATOR.$filename))
{
$ret['backup_cache_size'] += filesize($path.DIRECTORY_SEPARATOR.$filename);
}
}
}
$ret['backup_cache_size'] = $this->formatBytes($ret['backup_cache_size']);
$ret['junk_size'] = 0;
$delete_files = array();
$delete_folder = array();
$list=WPvivid_Backuplist::get_backuplist();
$files=array();
foreach ($list as $backup_id => $backup_value)
{
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
if($backup===false)
{
continue;
}
$backup_item = new WPvivid_Backup_Item($backup);
$file=$backup_item->get_files(false);
foreach ($file as $filename){
$files[]=$filename;
}
}
$dir=WPvivid_Setting::get_backupdir();
$dir=WP_CONTENT_DIR.DIRECTORY_SEPARATOR. $dir;
$path=str_replace('/',DIRECTORY_SEPARATOR,WPvivid_tools::GetSaveLogFolder());
if(substr($path, -1) == DIRECTORY_SEPARATOR)
{
$path = substr($path, 0, -1);
}
$folder[]= $path;
$except_regex['file'][]='&wpvivid-&';
$except_regex['file'][]='&wpvivid_temp-&';
//$except_regex['file'][]='&'.apply_filters('wpvivid_white_label_file_prefix', 'wpvivid').'-&';
//$except_regex['file'][]='&'.apply_filters('wpvivid_white_label_file_prefix', 'wpvivid').'_temp-&';
$this -> get_dir_files($delete_files,$delete_folder,$dir,$except_regex,$files,$folder,0,false);
foreach ($delete_files as $file)
{
if(file_exists($file))
{
$ret['junk_size'] += filesize($file);
}
}
foreach ($delete_folder as $folder)
{
if(file_exists($folder))
{
$ret['junk_size'] += $this->GetDirectorySize($folder);
}
}
$ret['junk_size'] = $this->formatBytes($ret['junk_size']);
$backup_dir_byte = $this->GetDirectorySize($dir);
$ret['backup_size'] = $this->get_wpvivid_backup_size();
$ret['backup_size'] = $this->formatBytes($ret['backup_size']);
$ret['sum_size'] = $this->formatBytes($backup_dir_byte + $log_dir_byte);
}
catch (Exception $e)
{
$ret['log_path'] = $log_dir = WPvivid_tools::GetSaveLogFolder();
$dir = WPvivid_Setting::get_backupdir();
$ret['old_files_path'] = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . WPVIVID_DEFAULT_ROLLBACK_DIR;
$dir = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $dir;
$ret['junk_path'] = $dir;
$ret['sum_size'] = '0';
$ret['log_dir_size'] = '0';
$ret['backup_cache_size'] = '0';
$ret['junk_size'] = '0';
$ret['backup_size'] = '0';
}
return $ret;
}
public function get_out_of_date_info()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
$dir = WPvivid_Setting::get_backupdir();
$dir = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $dir;
$ret['web_server'] = $dir;
$ret['remote_options'] = WPvivid_Setting::get_remote_options();
$info = WPvivid_Backuplist::get_out_of_date_backuplist_info(WPvivid_Setting::get_max_backup_count());
$ret['info'] = $info;
$ret['info']['size'] = $this->formatBytes($info['size']);
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function _get_out_of_date_info()
{
$dir=WPvivid_Setting::get_backupdir();
$dir=WP_CONTENT_DIR.DIRECTORY_SEPARATOR. $dir;
$ret['web_server']=$dir;
$ret['remote_options']=WPvivid_Setting::get_remote_options();
$info=WPvivid_Backuplist::get_out_of_date_backuplist_info(WPvivid_Setting::get_max_backup_count());
$ret['info']=$info;
$ret['info']['size']=$this->formatBytes($info['size']);
return $ret;
}
public function clean_out_of_date_backup()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$backup_ids=array();
$backup_ids=apply_filters('wpvivid_get_oldest_backup_ids',$backup_ids,true);
foreach ($backup_ids as $backup_id)
{
$this->delete_backup_by_id($backup_id);
}
$ret['result'] = 'success';
$html = '';
$html = apply_filters('wpvivid_add_backup_list', $html);
$ret['html'] = $html;
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
private function GetDirectorySize($path){
$bytes_total = 0;
$path = realpath($path);
if($path!==false && $path!='' && file_exists($path))
{
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
$bytes_total += $object->getSize();
}
}
return $bytes_total;
}
public function clean_local_storage()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
if(!isset($_POST['options'])||empty($_POST['options'])||!is_string($_POST['options']))
{
die();
}
$options=sanitize_text_field($_POST['options']);
$options =stripslashes($options);
$options=json_decode($options,true);
if(is_null($options))
{
die();
}
if($options['log']=='0' && $options['backup_cache']=='0' && $options['junk_files']=='0' && $options['old_files']=='0')
{
$ret['result']=WPVIVID_FAILED;
$ret['msg']=__('Choose at least one type of junk files for deleting.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$delete_files = array();
$delete_folder=array();
if($options['log']=='1')
{
$log_dir=$this->wpvivid_log->GetSaveLogFolder();
$log_files=array();
$temp=array();
$this -> get_dir_files($log_files,$temp,$log_dir,array('file' => '&wpvivid-&'),array(),array(),0,false);
foreach ($log_files as $file)
{
$file_name=basename($file);
$id=substr ($file_name,0,21);
if(WPvivid_Backuplist::get_backup_by_id($id)===false)
{
$delete_files[]=$file;
}
}
}
if($options['backup_cache']=='1')
{
$backup_id_list=WPvivid_Backuplist::get_has_remote_backuplist();
$this->delete_local_backup($backup_id_list);
WPvivid_tools::clean_junk_cache();
}
if($options['junk_files']=='1')
{
$list=WPvivid_Backuplist::get_backuplist();
$files=array();
foreach ($list as $backup_id => $backup_value)
{
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
if($backup===false)
{
continue;
}
$backup_item = new WPvivid_Backup_Item($backup);
$file=$backup_item->get_files(false);
foreach ($file as $filename){
$files[]=$filename;
}
}
$dir=WPvivid_Setting::get_backupdir();
$dir=WP_CONTENT_DIR.DIRECTORY_SEPARATOR. $dir;
$path=str_replace('/',DIRECTORY_SEPARATOR,$this->wpvivid_log->GetSaveLogFolder());
if(substr($path, -1) == DIRECTORY_SEPARATOR) {
$path = substr($path, 0, -1);
}
$folder[]= $path;
$except_regex['file'][]='&wpvivid-&';
$except_regex['file'][]='&wpvivid_temp-&';
$this -> get_dir_files($delete_files,$delete_folder,$dir,$except_regex,$files,$folder,0,false);
}
foreach ($delete_files as $file)
{
if(file_exists($file))
@wp_delete_file($file);
}
foreach ($delete_folder as $folder)
{
if(file_exists($folder))
WPvivid_tools::deldir($folder,'',true);
}
$ret['result']='success';
$ret['msg']=__('The selected junk files have been deleted.', 'wpvivid-backuprestore');
$ret['data']=$this->_junk_files_info_ex();
$html = '';
$html = apply_filters('wpvivid_get_log_list', $html);
$ret['html'] = $html['html'];
$ret['log_count'] = $html['log_count'];
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function get_dir_files(&$files,&$folder,$path,$except_regex,$exclude_files=array(),$exclude_folder=array(),$exclude_file_size=0,$flag = true)
{
$handler=opendir($path);
if($handler===false)
return;
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
$dir=str_replace('/',DIRECTORY_SEPARATOR,$path.DIRECTORY_SEPARATOR.$filename);
if(in_array($dir,$exclude_folder))
{
continue;
}
else if(is_dir($path.DIRECTORY_SEPARATOR.$filename))
{
if($except_regex!==false)
{
if($this -> regex_match($except_regex['file'],$path.DIRECTORY_SEPARATOR.$filename,$flag)){
continue;
}
$folder[]=$path.DIRECTORY_SEPARATOR.$filename;
}else
{
$folder[]=$path.DIRECTORY_SEPARATOR.$filename;
}
$this->get_dir_files($files ,$folder, $path.DIRECTORY_SEPARATOR.$filename,$except_regex,$exclude_folder);
}else {
if($except_regex===false||!$this -> regex_match($except_regex['file'] ,$path.DIRECTORY_SEPARATOR.$filename,$flag))
{
if(in_array($filename,$exclude_files))
{
continue;
}
if($exclude_file_size==0)
{
$files[] = $path.DIRECTORY_SEPARATOR.$filename;
}
else if(filesize($path.DIRECTORY_SEPARATOR.$filename)<$exclude_file_size*1024*1024)
{
$files[] = $path.DIRECTORY_SEPARATOR.$filename;
}
}
}
}
}
if($handler)
@closedir($handler);
}
private function regex_match($regex_array,$filename,$flag){
if($flag){
if(empty($regex_array)){
return false;
}
if(is_array($regex_array)){
foreach ($regex_array as $regex)
{
if(preg_match($regex,$filename))
{
return true;
}
}
}else{
if(preg_match($regex_array,$filename))
{
return true;
}
}
return false;
}else{
if(empty($regex_array)){
return true;
}
if(is_array($regex_array)){
foreach ($regex_array as $regex)
{
if(preg_match($regex,$filename))
{
return false;
}
}
}else{
if(preg_match($regex_array,$filename))
{
return false;
}
}
return true;
}
}
public function get_setting()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
if (isset($_POST['all']) && is_bool($_POST['all'])) {
$all = sanitize_key($_POST['all']);
if (!$all) {
if (isset($_POST['options_name']) && is_array($_POST['options_name'])) {
$options_name = $_POST['options_name'];
$options_name_array=array();
foreach ($options_name as $option_name)
{
$options_name_array[]=sanitize_text_field($option_name);
}
$ret = WPvivid_Setting::get_setting($all, $options_name_array);
echo wp_json_encode($ret);
}
} else {
$options_name = array();
$ret = WPvivid_Setting::get_setting($all, $options_name);
echo wp_json_encode($ret);
}
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function update_setting()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
if (isset($_POST['options']) && !empty($_POST['options']) && is_string($_POST['options'])) {
$json = sanitize_text_field($_POST['options']);
$json = stripslashes($json);
$options = json_decode($json, true);
if (is_null($options)) {
die();
}
$ret = WPvivid_Setting::update_setting($options);
echo wp_json_encode($ret);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
function set_default_remote_storage()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
if (!isset($_POST['remote_storage']) || empty($_POST['remote_storage']) || !is_array($_POST['remote_storage'])) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = __('Choose one storage from the list to be the default storage.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$remote_storage = $_POST['remote_storage'];
$remote_storage = array_map( 'sanitize_text_field', $remote_storage );
WPvivid_Setting::update_user_history('remote_selected', $remote_storage);
$ret['result'] = 'success';
$html = '';
$html = apply_filters('wpvivid_add_remote_storage_list', $html);
$ret['html'] = $html;
$pic = '';
$pic = apply_filters('wpvivid_schedule_add_remote_pic', $pic);
$ret['pic'] = $pic;
$dir = '';
$dir = apply_filters('wpvivid_get_remote_directory', $dir);
$ret['dir'] = $dir;
$schedule_local_remote = '';
$schedule_local_remote = apply_filters('wpvivid_schedule_local_remote', $schedule_local_remote);
$ret['local_remote'] = $schedule_local_remote;
$remote_storage = '';
$remote_storage = apply_filters('wpvivid_remote_storage', $remote_storage);
$ret['remote_storage'] = $remote_storage;
$remote_select_part = '';
$remote_select_part = apply_filters('wpvivid_remote_storage_select_part', $remote_select_part);
$ret['remote_select_part'] = $remote_select_part;
$default = array();
$remote_array = apply_filters('wpvivid_archieve_remote_array', $default);
$ret['remote_array'] = $remote_array;
$success_msg = __('You have successfully changed your default remote storage.', 'wpvivid-backuprestore');
$ret['notice'] = apply_filters('wpvivid_add_remote_notice', true, $success_msg);
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function check_remote_alias_exist()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
if (!isset($_POST['remote_alias']))
{
$remote_alias=sanitize_text_field($_POST['remote_alias']);
$remoteslist=WPvivid_Setting::get_all_remote_options();
foreach ($remoteslist as $key=>$value)
{
if(isset($value['name'])&&$value['name'] == $remote_alias)
{
$ret['result']=WPVIVID_FAILED;
$ret['error']="Warning: The alias already exists in storage list.";
echo wp_json_encode($ret);
die();
}
}
$ret['result']=WPVIVID_SUCCESS;
echo wp_json_encode($ret);
die();
}
die();
}
function get_default_remote_storage(){
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
$ret['result'] = 'success';
$ret['remote_storage'] = WPvivid_Setting::get_user_history('remote_selected');
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
function get_default_remote_storage_ex(){
$ret['result']='success';
$ret['remote_storage']=WPvivid_Setting::get_user_history('remote_selected');
return $ret;
}
public function get_general_setting()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
if (isset($_POST['all']) && is_bool($_POST['all'])) {
$all = sanitize_key($_POST['all']);
if (!$all) {
if (isset($_POST['options_name']) && is_array($_POST['options_name'])) {
$options_name = $_POST['options_name'];
$options_name_array=array();
foreach ($options_name as $option_name)
{
$options_name_array[]=sanitize_text_field($option_name);
}
$ret['data']['setting'] = WPvivid_Setting::get_setting($all, $options_name_array);
$schedule = WPvivid_Schedule::get_schedule();
$schedule['next_start'] = gmdate("l, F d, Y H:i", $schedule['next_start']);
$ret['result'] = 'success';
$ret['data']['schedule'] = $schedule;
$ret['user_history'] = WPvivid_Setting::get_user_history('remote_selected');
echo wp_json_encode($ret);
}
} else {
$options_name = array();
$ret['data']['setting'] = WPvivid_Setting::get_setting($all, $options_name);
$schedule = WPvivid_Schedule::get_schedule();
$schedule['next_start'] = gmdate("l, F d, Y H:i", $schedule['next_start']);
$ret['result'] = 'success';
$ret['data']['schedule'] = $schedule;
$ret['user_history'] = WPvivid_Setting::get_user_history('remote_selected');
echo wp_json_encode($ret);
}
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function wpvivid_set_general_setting($setting_data, $setting, $options)
{
$setting_data['wpvivid_common_setting']['backup_params'] = $setting['backup_params'];
if($setting_data['wpvivid_common_setting']['backup_params'] === 'low')
{
$setting_data['wpvivid_common_setting']['compress_file_count'] = 500;
$setting_data['wpvivid_common_setting']['max_file_size'] = '200';
$setting_data['wpvivid_common_setting']['max_sql_file_size'] = 400;
$setting_data['wpvivid_common_setting']['exclude_file_size'] = 0;
$setting_data['wpvivid_common_setting']['max_execution_time'] = 300;
$setting_data['wpvivid_common_setting']['memory_limit'] = '512M';
$setting_data['wpvivid_common_setting']['migrate_size'] = '2048';
$setting_data['wpvivid_common_setting']['max_resume_count'] = 6;
}
else if($setting_data['wpvivid_common_setting']['backup_params'] === 'mid')
{
$setting_data['wpvivid_common_setting']['compress_file_count'] = 2000;
$setting_data['wpvivid_common_setting']['max_file_size'] = '1024';
$setting_data['wpvivid_common_setting']['max_sql_file_size'] = 1024;
$setting_data['wpvivid_common_setting']['exclude_file_size'] = 0;
$setting_data['wpvivid_common_setting']['max_execution_time'] = 500;
$setting_data['wpvivid_common_setting']['memory_limit'] = '512M';
$setting_data['wpvivid_common_setting']['migrate_size'] = '2048';
$setting_data['wpvivid_common_setting']['max_resume_count'] = 6;
}
else if($setting_data['wpvivid_common_setting']['backup_params'] === 'high')
{
$setting_data['wpvivid_common_setting']['compress_file_count'] = 10000;
$setting_data['wpvivid_common_setting']['max_file_size'] = '4080';
$setting_data['wpvivid_common_setting']['max_sql_file_size'] = 4080;
$setting_data['wpvivid_common_setting']['exclude_file_size'] = 0;
$setting_data['wpvivid_common_setting']['max_execution_time'] = 900;
$setting_data['wpvivid_common_setting']['memory_limit'] = '512M';
$setting_data['wpvivid_common_setting']['migrate_size'] = '2048';
$setting_data['wpvivid_common_setting']['max_resume_count'] = 6;
}
else if($setting_data['wpvivid_common_setting']['backup_params'] === 'custom')
{
$setting_data['wpvivid_common_setting']['compress_file_count'] = intval($setting['compress_file_count']);
$setting_data['wpvivid_common_setting']['max_file_size'] = $setting['max_file_size'];
$setting_data['wpvivid_common_setting']['max_sql_file_size'] = intval($setting['max_sql_file_size']);
$setting_data['wpvivid_common_setting']['exclude_file_size'] = intval($setting['exclude_file_size']);
$setting_data['wpvivid_common_setting']['max_execution_time'] = intval($setting['max_execution_time']);
$setting_data['wpvivid_common_setting']['memory_limit'] = $setting['memory_limit'].'M';
$setting_data['wpvivid_common_setting']['migrate_size'] = $setting['migrate_size'];
$setting_data['wpvivid_common_setting']['max_resume_count'] = $setting['max_resume_count'];
}
$setting['restore_max_execution_time'] = intval($setting['restore_max_execution_time']);
$setting['max_backup_count'] = intval($setting['max_backup_count']);
$setting_data['wpvivid_email_setting']['send_to'][] = $setting['send_to'];
$setting_data['wpvivid_email_setting']['always'] = $setting['always'];
if(isset($setting['email_enable'])) {
$setting_data['wpvivid_email_setting']['email_enable'] = $setting['email_enable'];
}
$setting['path']=esc_attr($setting['path']);
$setting_data['wpvivid_local_setting']['path'] = $setting['path'];
if($options['options']['wpvivid_local_setting']['path'] !== $setting['path'])
{
if(file_exists(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['options']['wpvivid_local_setting']['path']))
{
@rename(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['options']['wpvivid_local_setting']['path'], WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$setting['path']);
}
}
$setting_data['wpvivid_local_setting']['save_local'] = $options['options']['wpvivid_local_setting']['save_local'];
$setting_data['wpvivid_common_setting']['restore_max_execution_time'] = $setting['restore_max_execution_time'];
$setting_data['wpvivid_common_setting']['log_save_location'] = $setting['path'].'/wpvivid_log';
$setting_data['wpvivid_common_setting']['max_backup_count'] = $setting['max_backup_count'];
$setting_data['wpvivid_common_setting']['show_admin_bar'] = $setting['show_admin_bar'];
$setting_data['wpvivid_common_setting']['domain_include'] = $setting['domain_include'];
$setting_data['wpvivid_common_setting']['estimate_backup'] = $setting['estimate_backup'];
$setting_data['wpvivid_common_setting']['restore_memory_limit'] = $setting['restore_memory_limit'].'M';
$setting_data['wpvivid_common_setting']['ismerge'] = $setting['ismerge'];
$setting_data['wpvivid_common_setting']['db_connect_method'] = $setting['db_connect_method'];
$setting_data['wpvivid_common_setting']['retain_local'] = $setting['retain_local'];
$setting_data['wpvivid_common_setting']['uninstall_clear_folder'] = $setting['uninstall_clear_folder'];
$setting_data['wpvivid_common_setting']['backup_symlink_folder'] = $setting['backup_symlink_folder'];
//new
$setting_data['wpvivid_common_setting']['replace_rows_pre_request'] = intval($setting['replace_rows_pre_request']);
$setting_data['wpvivid_common_setting']['sql_file_buffer_pre_request'] = intval($setting['sql_file_buffer_pre_request']);
$setting_data['wpvivid_common_setting']['use_index'] = intval($setting['use_index']);
$setting_data['wpvivid_common_setting']['unzip_files_pre_request'] = intval($setting['unzip_files_pre_request']);
$setting_data['wpvivid_common_setting']['zip_method'] = $setting['zip_method'];
return $setting_data;
}
public function set_general_setting()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
$ret=array();
try
{
if(isset($_POST['setting'])&&!empty($_POST['setting']))
{
$json_setting = sanitize_text_field($_POST['setting']);
$json_setting = stripslashes($json_setting);
$setting = json_decode($json_setting, true);
if (is_null($setting)){
die();
}
$ret = $this->check_setting_option($setting);
if($ret['result']!=WPVIVID_SUCCESS)
{
echo wp_json_encode($ret);
die();
}
$options=WPvivid_Setting::get_setting(true, "");
$setting_data = array();
$setting_data= apply_filters('wpvivid_set_general_setting',$setting_data, $setting, $options);
$ret['setting']=WPvivid_Setting::update_setting($setting_data);
}
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
public function set_schedule(){
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
$ret=array();
try{
if(isset($_POST['schedule'])&&!empty($_POST['schedule']))
{
$json = sanitize_text_field($_POST['schedule']);
$json = stripslashes($json);
$schedule = json_decode($json, true);
if (is_null($schedule))
{
die();
}
$ret = $this->check_schedule_option($schedule);
if($ret['result']!=WPVIVID_SUCCESS)
{
echo wp_json_encode($ret);
die();
}
//set_schedule_ex
$ret=WPvivid_Schedule::set_schedule_ex($schedule);
if($ret['result']!='success')
{
echo wp_json_encode($ret);
die();
}
}
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
public function check_setting_option($data)
{
$ret['result']=WPVIVID_FAILED;
if(!isset($data['max_file_size']))
{
$ret['error']=__('The value of \'Compress file every\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
$data['max_file_size']=sanitize_text_field($data['max_file_size']);
if(empty($data['max_file_size']) && $data['max_file_size'] != '0')
{
$ret['error']=__('The value of \'Compress file every\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['exclude_file_size']))
{
$ret['error']=__('The value of \'Exclude files which are larger than\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['exclude_file_size']=sanitize_text_field($data['exclude_file_size']);
if(empty($data['exclude_file_size']) && $data['exclude_file_size'] != '0')
{
$ret['error']=__('The value of \'Exclude files which are larger than\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['max_execution_time']))
{
$ret['error']=__('The value of \'PHP scripts execution timeout for backup\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['max_execution_time']=sanitize_text_field($data['max_execution_time']);
if(empty($data['max_execution_time']) && $data['max_execution_time'] != '0')
{
$ret['error']=__('The value of \'PHP scripts execution timeout for backup\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
//
if(!isset($data['restore_max_execution_time']))
{
$ret['error']=__('The value of \'PHP scripts execution timeout for restore\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['restore_max_execution_time']=sanitize_text_field($data['restore_max_execution_time']);
if(empty($data['restore_max_execution_time']) && $data['restore_max_execution_time'] != '0')
{
$ret['error']=__('The value of \'PHP scripts execution timeout for restore\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['memory_limit']))
{
$ret['error']=__('The value of \'PHP memory limit for backup\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['memory_limit']=sanitize_text_field($data['memory_limit']);
if(empty($data['memory_limit']) && $data['memory_limit'] != '0')
{
$ret['error']=__('The value of \'PHP memory limit for backup\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['restore_memory_limit']))
{
$ret['error']=__('The value of \'PHP memory limit for restoration\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['restore_memory_limit']=sanitize_text_field($data['restore_memory_limit']);
if(empty($data['restore_memory_limit']) && $data['restore_memory_limit'] != '0')
{
$ret['error']=__('The value of \'PHP memory limit for restoration\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['migrate_size']))
{
$ret['error']=__('The value of \'Chunk Size\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['migrate_size']=sanitize_text_field($data['migrate_size']);
if(empty($data['migrate_size']) && $data['migrate_size'] != '0')
{
$ret['error']=__('The value of \'Chunk Size\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
$data['compress_file_count']=sanitize_text_field($data['compress_file_count']);
if(!isset($data['compress_file_count']) || empty($data['compress_file_count']))
{
$ret['error']=__('The value of \'The number of files compressed to the backup zip each time\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
$data['max_sql_file_size']=sanitize_text_field($data['max_sql_file_size']);
if(!isset($data['max_sql_file_size']) || empty($data['max_sql_file_size']))
{
$ret['error']=__('The value of \'Split a sql file every this size\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
$data['replace_rows_pre_request']=sanitize_text_field($data['replace_rows_pre_request']);
if(!isset($data['replace_rows_pre_request']) || empty($data['replace_rows_pre_request']))
{
$ret['error']=__('The value of \'Maximum rows of data to be processed per request for restoration\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
$data['sql_file_buffer_pre_request']=sanitize_text_field($data['sql_file_buffer_pre_request']);
if(!isset($data['sql_file_buffer_pre_request']) || empty($data['sql_file_buffer_pre_request']))
{
$ret['error']=__('The value of \'Maximum size of sql file to be imported per request for restoration\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['wpvivid_uc_scan_limit']))
{
$ret['error']=__('The value of \'Posts Quantity Processed Per Request\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['wpvivid_uc_scan_limit']=sanitize_text_field($data['wpvivid_uc_scan_limit']);
if(empty($data['wpvivid_uc_scan_limit']) && $data['wpvivid_uc_scan_limit'] != '0')
{
$ret['error']=__('The value of \'Posts Quantity Processed Per Request\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['wpvivid_uc_files_limit']))
{
$ret['error']=__('The value of \'Media Files Quantity Processed Per Request\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['wpvivid_uc_files_limit']=sanitize_text_field($data['wpvivid_uc_files_limit']);
if(empty($data['wpvivid_uc_files_limit']) && $data['wpvivid_uc_files_limit'] != '0')
{
$ret['error']=__('The value of \'Media Files Quantity Processed Per Request\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!$this->wpvivid_check_staging_pro_active())
{
if(!isset($data['staging_db_insert_count']))
{
$ret['error']=__('The value of \'DB Copy Count\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['staging_db_insert_count']=sanitize_text_field($data['staging_db_insert_count']);
if(empty($data['staging_db_insert_count']) && $data['staging_db_insert_count'] != '0')
{
$ret['error']=__('The value of \'DB Copy Count\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['staging_db_replace_count']))
{
$ret['error']=__('The value of \'DB Replace Count\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['staging_db_replace_count']=sanitize_text_field($data['staging_db_replace_count']);
if(empty($data['staging_db_replace_count']) && $data['staging_db_replace_count'] != '0')
{
$ret['error']=__('The value of \'DB Replace Count\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['staging_file_copy_count']))
{
$ret['error']=__('The value of \'File Copy Count\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['staging_file_copy_count']=sanitize_text_field($data['staging_file_copy_count']);
if(empty($data['staging_file_copy_count']) && $data['staging_file_copy_count'] != '0')
{
$ret['error']=__('The value of \'File Copy Count\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['staging_exclude_file_size']))
{
$ret['error']=__('The value of \'Max File Size\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['staging_exclude_file_size']=sanitize_text_field($data['staging_exclude_file_size']);
if(empty($data['staging_exclude_file_size']) && $data['staging_exclude_file_size'] != '0')
{
$ret['error']=__('The value of \'Max File Size\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['staging_memory_limit']))
{
$ret['error']=__('The value of \'Staging Memory Limit\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['staging_memory_limit']=sanitize_text_field($data['staging_memory_limit']);
if(empty($data['staging_memory_limit']) && $data['staging_memory_limit'] != '0')
{
$ret['error']=__('The value of \'Staging Memory Limit\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['staging_max_execution_time']))
{
$ret['error']=__('The value of \'PHP Scripts Execution Timeout\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['staging_max_execution_time']=sanitize_text_field($data['staging_max_execution_time']);
if(empty($data['staging_max_execution_time']) && $data['staging_max_execution_time'] != '0')
{
$ret['error']=__('The value of \'PHP Scripts Execution Timeout\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($data['staging_request_timeout']))
{
$ret['error']=__('The value of \'Delay Between Requests\' can\'t be empty.', 'wpvivid-backuprestore');
}
$data['staging_request_timeout']=sanitize_text_field($data['staging_request_timeout']);
if(empty($data['staging_request_timeout']) && $data['staging_request_timeout'] != '0')
{
$ret['error']=__('The value of \'Delay Between Requests\' can\'t be empty.', 'wpvivid-backuprestore');
return $ret;
}
}
//
if(!isset($data['path']))
{
$ret['error']=__('The local storage path is required.', 'wpvivid-backuprestore');
}
$data['path']=sanitize_text_field($data['path']);
if(empty($data['path']))
{
$ret['error']=__('The local storage path is required.', 'wpvivid-backuprestore');
return $ret;
}
$data['email_enable']=sanitize_text_field($data['email_enable']);
$data['send_to']=sanitize_text_field($data['send_to']);
if($data['email_enable'] == '1')
{
if(empty($data['send_to']))
{
$ret['error']=__('An email address is required.', 'wpvivid-backuprestore');
return $ret;
}
}
if(isset($data['db_connect_method']) && $data['db_connect_method'] === 'pdo') {
if (class_exists('PDO')) {
$extensions = get_loaded_extensions();
if (!array_search('pdo_mysql', $extensions)) {
$ret['error'] = __('The pdo_mysql extension is not detected. Please install the extension first or choose wpdb option for Database connection method.', 'wpvivid-backuprestore');
return $ret;
}
} else {
$ret['error'] = __('The pdo_mysql extension is not detected. Please install the extension first or choose wpdb option for Database connection method.', 'wpvivid-backuprestore');
return $ret;
}
}
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
public function check_schedule_option($data)
{
$ret['result']=WPVIVID_FAILED;
$data['enable']=sanitize_text_field($data['enable']);
$data['save_local_remote']=sanitize_text_field($data['save_local_remote']);
if(!empty($data['enable'])){
if($data['enable'] == '1'){
if(!empty($data['save_local_remote'])){
if($data['save_local_remote'] == 'remote'){
$remote_storage=WPvivid_Setting::get_remote_options();
if($remote_storage == false) {
$ret['error']=__('There is no default remote storage configured. Please set it up first.', 'wpvivid-backuprestore');
return $ret;
}
}
}
}
}
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
public function export_setting()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
if (isset($_REQUEST['setting']) && !empty($_REQUEST['setting']) && isset($_REQUEST['history']) && !empty($_REQUEST['history']) && isset($_REQUEST['review'])) {
$setting = sanitize_text_field($_REQUEST['setting']);
$history = sanitize_text_field($_REQUEST['history']);
$review = sanitize_text_field($_REQUEST['review']);
if ($setting == '1') {
$setting = true;
} else {
$setting = false;
}
if ($history == '1') {
$history = true;
} else {
$history = false;
}
if ($review == '1') {
$review = true;
} else {
$review = false;
}
$backup_list = false;
$json = WPvivid_Setting::export_setting_to_json($setting, $history, $review, $backup_list);
$parse = wp_parse_url(home_url());
$path = '';
if(isset($parse['path'])) {
$parse['path'] = str_replace('/', '_', $parse['path']);
$parse['path'] = str_replace('.', '_', $parse['path']);
$path = $parse['path'];
}
$parse['host'] = str_replace('/', '_', $parse['host']);
$parse['host'] = str_replace('.', '_', $parse['host']);
$domain_tran = $parse['host'].$path;
$offset=get_option('gmt_offset');
$date_format = gmdate("Ymd",time()+$offset*60*60);
$time_format = gmdate("His",time()+$offset*60*60);
$export_file_name = apply_filters('wpvivid_white_label_slug', 'wpvivid').'_setting-'.$domain_tran.'-'.$date_format.'-'.$time_format.'.json';
if (!headers_sent()) {
header('Content-Disposition: attachment; filename='.$export_file_name);
//header('Content-type: application/json');
header('Content-Type: application/force-download');
header('Content-Description: File Transfer');
header('Cache-Control: must-revalidate');
header('Content-Transfer-Encoding: binary');
}
echo wp_json_encode($json);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
exit;
}
public function import_setting()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
};
try {
if (isset($_POST['data']) && !empty($_POST['data']) && is_string($_POST['data'])) {
$data = sanitize_text_field($_POST['data']);
$data = stripslashes($data);
$json = json_decode($data, true);
if (is_null($json)) {
die();
}
if (json_last_error() === JSON_ERROR_NONE && is_array($json) && array_key_exists('plugin', $json) && $json['plugin'] == 'WPvivid') {
$json = apply_filters('wpvivid_trim_import_info', $json);
WPvivid_Setting::import_json_to_setting($json);
//WPvivid_Schedule::reset_schedule();
do_action('wpvivid_reset_schedule');
$ret['result'] = 'success';
$ret['slug'] = apply_filters('wpvivid_white_label_slug', 'WPvivid');
echo wp_json_encode($ret);
} else {
$ret['result'] = 'failed';
$ret['error'] = __('The selected file is not the setting file for WPvivid. Please upload the right file.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
}
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function test_send_mail()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_POST['send_to']) && !empty($_POST['send_to']) && is_string($_POST['send_to'])) {
$send_to = sanitize_email($_POST['send_to']);
if (empty($send_to)) {
$ret['result'] = 'failed';
$ret['error'] = __('Invalid email address', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
} else {
$subject = 'WPvivid Test Mail';
$body = 'This is a test mail from WPvivid backup plugin';
$headers = array('Content-Type: text/html; charset=UTF-8');
if (wp_mail($send_to, $subject, $body, $headers) === false) {
$ret['result'] = 'failed';
$ret['error'] = __('Unable to send email. Please check the configuration of email server.', 'wpvivid-backuprestore');
} else {
$ret['result'] = 'success';
}
echo wp_json_encode($ret);
}
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function create_debug_package()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
$files = WPvivid_error_log::get_error_log();
$staging_files = WPvivid_error_log::get_staging_error_log();
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$backup_path = WPvivid_Setting::get_backupdir();
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $backup_path . DIRECTORY_SEPARATOR . 'wpvivid_debug.zip';
if (file_exists($path)) {
@wp_delete_file($path);
}
$archive = new WPvivid_PclZip($path);
if (!empty($files)) {
if (!$archive->add($files, WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH)) {
echo esc_html($archive->errorInfo(true)) . ' <a href="' . esc_url(admin_url()) . 'admin.php?page=WPvivid">retry</a>.';
exit;
}
}
if (!empty($staging_files)) {
if (!$archive->add($staging_files, WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH)) {
echo esc_html($archive->errorInfo(true)) . ' <a href="' . esc_url(admin_url()) . 'admin.php?page=WPvivid">retry</a>.';
exit;
}
}
$server_info = wp_json_encode($this->get_website_info());
$server_file_path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $backup_path . DIRECTORY_SEPARATOR . 'wpvivid_server_info.json';
if (file_exists($server_file_path)) {
@wp_delete_file($server_file_path);
}
$server_file = fopen($server_file_path, 'x');
fclose($server_file);
file_put_contents($server_file_path, $server_info);
if (!$archive->add($server_file_path, WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH)) {
echo esc_html($archive->errorInfo(true)) . ' <a href="' . esc_url(admin_url()) . 'admin.php?page=WPvivid">retry</a>.';
exit;
}
@wp_delete_file($server_file_path);
if (session_id())
session_write_close();
$size = filesize($path);
if (!headers_sent()) {
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . $size);
header('Content-Transfer-Encoding: binary');
}
ob_end_clean();
readfile($path);
@wp_delete_file($path);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
exit;
}
public function get_log_list()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
$ret['result'] = 'success';
$html = '';
$html = apply_filters('wpvivid_get_log_list', $html);
$ret['html'] = $html['html'];
$ret['log_count'] = $html['log_count'];
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function wpvivid_get_log_list($html)
{
$loglist=$this->get_log_list_ex();
$current_num=1;
$max_log_diaplay=20;
$log_index=0;
$pic_log='/admin/partials/images/Log.png';
if(!empty($loglist['log_list']['file'])) {
foreach ($loglist['log_list']['file'] as $value) {
if ($current_num <= $max_log_diaplay) {
$log_tr_display = '';
} else {
$log_tr_display = 'display: none;';
}
if (empty($value['time'])) {
$value['time'] = 'N/A';
}
else{
$offset=get_option('gmt_offset');
$localtime = strtotime($value['time'])/* + $offset * 60 * 60*/;
$value['time'] = gmdate('F-d-Y H:i:s',$localtime);
}
if (empty($value['des'])) {
$value['des'] = 'N/A';
}
$value['path'] = str_replace('\\', '/', $value['path']);
$html .= '<tr style="'.esc_attr($log_tr_display, 'wpvivid-backuprestore').'">
<td class="row-title"><label for="tablecell">'.$value['time'].'</label>
</td>
<td>'.$value['des'].'</td>
<td>'.$value['file_name'].'</td>
<td>
<a onclick="wpvivid_read_log(\''.'wpvivid_view_log'.'\', \''.$value['id'].'\', \''.'backup'.'\')" style="cursor:pointer;">
<img src="'.esc_url(WPVIVID_PLUGIN_URL.$pic_log).'" style="vertical-align:middle;">Log
</a>
</td>
</tr>';
$log_index++;
$current_num++;
}
}
$ret['log_count']=$log_index;
$ret['html']=$html;
return $ret;
}
public function wpvivid_get_log_list_output()
{
$loglist=$this->get_log_list_ex();
$current_num=1;
$max_log_diaplay=20;
$pic_log='/admin/partials/images/Log.png';
if(!empty($loglist['log_list']['file'])) {
foreach ($loglist['log_list']['file'] as $value) {
if ($current_num <= $max_log_diaplay) {
$log_tr_display = '';
} else {
$log_tr_display = 'display: none;';
}
if (empty($value['time'])) {
$value['time'] = 'N/A';
}
else{
$localtime = strtotime($value['time']);
$value['time'] = gmdate('F-d-Y H:i:s',$localtime);
}
if (empty($value['des'])) {
$value['des'] = 'N/A';
}
$value['path'] = str_replace('\\', '/', $value['path']);
?>
<tr style="<?php echo esc_attr($log_tr_display); ?>">
<td class="row-title"><label for="tablecell"><?php echo esc_html($value['time']); ?></label>
</td>
<td><?php echo esc_html($value['des']); ?></td>
<td><?php echo esc_html($value['file_name']); ?></td>
<td>
<a onclick="wpvivid_read_log('wpvivid_view_log', '<?php echo esc_js($value['id']); ?>', 'backup');" style="cursor:pointer;">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL.$pic_log); ?>" style="vertical-align:middle;">Log
</a>
</td>
</tr>
<?php
$current_num++;
}
}
}
public function get_log_list_ex()
{
$ret['log_list']['file']=array();
if(!class_exists('WPvivid_Log'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-log.php';
}
$log=new WPvivid_Log();
$dir=$log->GetSaveLogFolder();
$files=array();
$handler=opendir($dir);
$regex='#^wpvivid.*_log.txt#';
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.$filename))
{
continue;
}else{
if(preg_match($regex,$filename))
{
$files[$filename] = $dir.$filename;
}
}
}
}
if($handler)
@closedir($handler);
}
$dir.='error'.DIRECTORY_SEPARATOR;
if(file_exists($dir))
{
$handler=opendir($dir);
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.$filename))
{
continue;
}else {
if(preg_match($regex,$filename))
{
$files[$filename] = $dir.$filename;
}
}
}
}
if($handler)
@closedir($handler);
}
}
foreach ($files as $file)
{
$handle = @fopen($file, "r");
if ($handle)
{
$log_file['file_name']=basename($file);
$log_file['id']='';
if(preg_match('/wpvivid-(.*?)_/', basename($file), $matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
$log_file['id']=$id;
}
$log_file['path']=$file;
$log_file['des']='';
$log_file['time']='';
if(preg_match('/error/', $file))
{
$log_file['result']='failed';
}
else
{
$log_file['result']='success';
}
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Log created: ');
if($pos!==false)
{
$log_file['time']=substr ($line,$pos+strlen('Log created: '));
}
}
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Type: ');
if($pos!==false)
{
$log_file['des']=substr ($line,$pos+strlen('Type: '));
}
}
fclose($handle);
$ret['log_list']['file'][basename($file)]=$log_file;
}
}
$ret['log_list']['file'] =$this->sort_list($ret['log_list']['file']);
return $ret;
}
public function sort_list($list)
{
uasort ($list,function($a, $b)
{
if($a['time']>$b['time'])
{
return -1;
}
else if($a['time']===$b['time'])
{
return 0;
}
else
{
return 1;
}
});
return $list;
}
public function view_log()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_POST['id']) && !empty($_POST['id']) && is_string($_POST['id'])) {
$id = sanitize_text_field($_POST['id']);
$path = '';
if(isset($_POST['log_type']))
{
$log_type = sanitize_text_field($_POST['log_type']);
}
else
{
$log_type = 'backup';
}
if($log_type === 'backup')
{
$loglist=$this->get_log_list_ex();
}
else
{
$log_page=new WPvivid_Staging_Log_Page_Free();
$loglist=$log_page->get_log_list('staging');
}
if(!empty($loglist['log_list']['file']))
{
foreach ($loglist['log_list']['file'] as $value)
{
if($value['id'] === $id)
{
$path = str_replace('\\', '/', $value['path']);
break;
}
}
}
if (!file_exists($path)) {
$json['result'] = 'failed';
$json['error'] = __('The log not found.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$file = fopen($path, 'r');
if (!$file) {
$json['result'] = 'failed';
$json['error'] = __('Unable to open the log file.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$buffer = '';
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
$json['result'] = 'success';
$json['data'] = $buffer;
echo wp_json_encode($json);
} else {
$json['result'] = 'failed';
$json['error'] = __('Reading the log failed. Please try again.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function get_website_info()
{
try {
$version = $this->version;
$version = apply_filters('wpvivid_display_pro_version', $version);
$ret['result'] = 'success';
$ret['data']['version'] = $version;
$ret['data']['home_url'] = get_home_url();
$ret['data']['abspath'] = ABSPATH;
$ret['data']['wp_content_path'] = WP_CONTENT_DIR;
$ret['data']['wp_plugin_path'] = WP_PLUGIN_DIR;
$ret['data']['active_plugins'] = get_option('active_plugins');
global $wp_version;
$ret['wp_version'] = $wp_version;
if (is_multisite()) {
$ret['data']['multisite'] = 'enable';
} else {
$ret['data']['multisite'] = 'disable';
}
$ret['data']['web_server'] = $_SERVER["SERVER_SOFTWARE"];
$ret['data']['php_version'] = phpversion();
global $wpdb;
$ret['data']['mysql_version'] = $wpdb->db_version();
if (defined('WP_DEBUG')) {
$ret['data']['wp_debug'] = WP_DEBUG;
} else {
$ret['wp_debug'] = false;
}
$ret['data']['language'] = get_bloginfo('language');
$ret['data']['upload_max_filesize'] = ini_get("upload_max_filesize");
$options = WPvivid_Setting::get_option('wpvivid_common_setting');
if (isset($options['max_execution_time'])) {
$limit = $options['max_execution_time'];
} else {
$limit = WPVIVID_MAX_EXECUTION_TIME;
}
ini_set('max_execution_time', $limit);
$current_offset = get_option( 'gmt_offset' );
$timezone = get_option( 'timezone_string' );
if ( false !== strpos( $timezone, 'Etc/GMT' ) ) {
$timezone = '';
}
if ( empty( $timezone ) ) {
if ( 0 == $current_offset ) {
$timezone = 'UTC+0';
} elseif ( $current_offset < 0 ) {
$timezone = 'UTC' . $current_offset;
} else {
$timezone = 'UTC+' . $current_offset;
}
}
$ret['data']['max_execution_time'] = ini_get("max_execution_time");
$ret['data']['max_input_vars'] = ini_get("max_input_vars");
$ret['data']['max_input_vars'] = ini_get("max_input_vars");
$ret['data']['timezone'] = $timezone;//date_default_timezone_get();
if(function_exists('php_uname'))
{
$ret['data']['OS'] = php_uname();
}
$ret['data']['memory_current'] = $this->formatBytes(memory_get_usage());
$ret['data']['memory_peak'] = $this->formatBytes(memory_get_peak_usage());
$ret['data']['memory_limit'] = ini_get('memory_limit');
$ret['data']['post_max_size'] = ini_get('post_max_size');
$ret['data']['allow_url_fopen'] = ini_get('allow_url_fopen');
$ret['data']['safe_mode'] = ini_get('safe_mode');
$ret['data']['pcre.backtrack_limit'] = ini_get('pcre.backtrack_limit');
$extensions = get_loaded_extensions();
if (array_search('exif', $extensions)) {
$ret['data']['exif'] = 'support';
} else {
$ret['data']['exif'] = 'not support';
}
if (array_search('xml', $extensions)) {
$ret['data']['xml'] = 'support';
} else {
$ret['data']['xml'] = 'not support';
}
if (array_search('suhosin', $extensions)) {
$ret['data']['suhosin'] = 'support';
} else {
$ret['data']['suhosin'] = 'not support';
}
if (array_search('gd', $extensions)) {
$ret['data']['IPTC'] = 'support';
} else {
$ret['data']['IPTC'] = 'not support';
}
$ret['data']['extensions'] = $extensions;
if (function_exists('apache_get_modules')) {
$ret['data']['apache_modules'] = apache_get_modules();
} else {
$ret['data']['apache_modules'] = array();
}
if (array_search('pdo_mysql', $extensions)) {
$ret['data']['pdo_mysql'] = 'support';
} else {
$ret['data']['pdo_mysql'] = 'not support';
}
if ($ret['data']['pdo_mysql'] == 'support') {
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-db-method.php';
$db_method = new WPvivid_DB_Method();
$ret_sql_mode = $db_method->get_sql_mode();
if ($ret_sql_mode['result'] == WPVIVID_FAILED) {
$ret['data']['mysql_mode'] = '';
} else {
$ret['data']['mysql_mode'] = $ret_sql_mode['mysql_mode'];
$ret['mysql_mode'] = $ret_sql_mode['mysql_mode'];
}
} else {
$ret['data']['mysql_mode'] = '';
}
if (!class_exists('PclZip')) include_once(ABSPATH . '/wp-admin/includes/class-pclzip.php');
if (!class_exists('PclZip')) {
$ret['data']['PclZip'] = 'not support';
} else {
$ret['data']['PclZip'] = 'support';
}
if (is_multisite() && !defined('MULTISITE')) {
$prefix = $wpdb->base_prefix;
} else {
$prefix = $wpdb->get_blog_prefix(0);
}
$ret['data']['wp_prefix'] = $prefix;
$sapi_type = php_sapi_name();
if ($sapi_type == 'cgi-fcgi' || $sapi_type == ' fpm-fcgi') {
$ret['data']['fast_cgi'] = 'On';
} else {
$ret['data']['fast_cgi'] = 'Off';
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('result'=>'failed','error'=>$message);
}
return $ret;
}
public function wpvivid_add_backup_list($html, $list_name = 'wpvivid_backup_list', $tour = false)
{
$html = '';
$backuplist=WPvivid_Backuplist::get_backuplist($list_name);
$remote=array();
$remote=apply_filters('wpvivid_remote_pic', $remote);
$upload_title = '';
foreach ($backuplist as $key=>$value) {
if($value['type'] !== 'Rollback') {
$row_style = '';
if ($value['type'] == 'Migration' || $value['type'] == 'Upload') {
if ($value['type'] == 'Migration') {
$upload_title = 'Received Backup: ';
} else if ($value['type'] == 'Upload') {
$upload_title = __('Uploaded Backup: ', 'wpvivid-backuprestore');
}
$row_style = 'border: 2px solid #006799; box-sizing:border-box; -moz-box-sizing:border-box; -webkit-box-sizing:border-box;';
} else if ($value['type'] == 'Manual' || $value['type'] == 'Cron') {
$row_style = '';
$upload_title = '';
} else {
$upload_title = '';
}
if (empty($value['lock'])) {
$backup_lock = '/admin/partials/images/unlocked.png';
$lock_status = 'unlock';
} else {
if ($value['lock'] == 0) {
$backup_lock = '/admin/partials/images/unlocked.png';
$lock_status = 'unlock';
} else {
$backup_lock = '/admin/partials/images/locked.png';
$lock_status = 'lock';
}
}
$backup_size=0;
$backup_time=$value['create_time'];
if(isset($value['backup']['files'])){
foreach ($value['backup']['files'] as $file_info){
$backup_size+=$file_info['size'];
if(preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}/',$file_info['file_name'],$matches))
{
$backup_date=$matches[0];
}
else
{
$backup_date=$value['create_time'];
}
$time_array=explode('-',$backup_date);
if(sizeof($time_array)>4){
$time=$time_array[0].'-'.$time_array[1].'-'.$time_array[2].' '.$time_array[3].':'.$time_array[4];
$backup_time=strtotime($time);
}
//break;
}
}
$remote_pic_html = '';
$save_local_pic_y = '/admin/partials/images/storage-local.png';
$save_local_pic_n = '/admin/partials/images/storage-local(gray).png';
$local_title = 'Localhost';
if ($value['save_local'] == 1 || $value['type'] == 'Migration') {
$remote_pic_html .= '<img src="' . esc_url(WPVIVID_PLUGIN_URL . $save_local_pic_y) . '" style="vertical-align:middle; " title="' . $local_title . '"/>';
} else {
$remote_pic_html .= '<img src="' . esc_url(WPVIVID_PLUGIN_URL . $save_local_pic_n) . '" style="vertical-align:middle; " title="' . $local_title . '"/>';
}
$b_has_remote = false;
if (is_array($remote)) {
foreach ($remote as $key1 => $value1) {
foreach ($value['remote'] as $storage_type) {
$b_has_remote = true;
if ($key1 === $storage_type['type']) {
$pic = $value1['selected_pic'];
} else {
$pic = $value1['default_pic'];
}
}
if (!$b_has_remote) {
$pic = $value1['default_pic'];
}
$title = $value1['title'];
$remote_pic_html .= '<img src="' . esc_url(WPVIVID_PLUGIN_URL . $pic) . '" style="vertical-align:middle; " title="' . $title . '"/>';
}
}
if ($tour) {
$tour = false;
$tour_message = '<div class="wpvivid-popuptext" id="wpvivid_popup_tour">' . esc_html__('Click the button to complete website restore or migration', 'wpvivid-backuprestore') . '</div>';
$tour_class = 'wpvivid-popup';
} else {
$tour_message = '';
$tour_class = '';
}
$hide = 'hide';
$html .= '<tr style="' . $row_style . '">
<th class="check-column"><input name="check_backup" type="checkbox" id="' . esc_attr($key, 'wpvivid-backuprestore') . '" value="' . esc_attr($key, 'wpvivid-backuprestore') . '" onclick="wpvivid_click_check_backup(\'' . $key . '\', \'' . $list_name . '\');" /></th>
<td class="tablelistcolumn">
<div style="float:left;padding:0 10px 10px 0;">
<div class="backuptime"><strong>' . $upload_title . '</strong>' . gmdate('M-d-Y H:i', $backup_time) . '</div>
<div class="common-table">
<span title="To lock the backup, the backup can only be deleted manually" id="wpvivid_lock_' . $key . '">
<img src="' . esc_url(WPVIVID_PLUGIN_URL . $backup_lock) . '" name="' . esc_attr($lock_status, 'wpvivid-backuprestore') . '" onclick="wpvivid_set_backup_lock(\'' . $key . '\', \'' . $lock_status . '\');" style="vertical-align:middle; cursor:pointer;"/>
</span>
<span style="margin:0;">|</span> <span>' . __('Type:', 'wpvivid-backuprestore') . '</span><span>' . $value['type'] . '</span>
<span style="margin:0;">|</span> <span title="Backup log"><a href="#" onclick="wpvivid_read_log(\'' . 'wpvivid_view_backup_log' . '\', \'' . $key . '\');"><img src="' . esc_url(WPVIVID_PLUGIN_URL . '/admin/partials/images/Log.png') . '" style="vertical-align:middle;cursor:pointer;"/><span style="margin:0;">' . __('Log', 'wpvivid-backuprestore') . '</span></a></span>
</div>
</div>
</td>
<td class="tablelistcolumn">
<div style="float:left;padding:10px 10px 10px 0;">' . $remote_pic_html . '</div>
</td>
<td class="tablelistcolumn" style="min-width:100px;">
<div id="wpvivid_file_part_' .$key . '" style="float:left;padding:10px 10px 10px 0;">
<div style="cursor:pointer;" onclick="wpvivid_initialize_download(\'' . $key . '\', \'' . $list_name . '\');" title="'. esc_html__('Prepare to download the backup', 'wpvivid-backuprestore') .'">
<img id="wpvivid_download_btn_' . $key . '" src="' . esc_url(WPVIVID_PLUGIN_URL . '/admin/partials/images/download.png') . '" style="vertical-align:middle;" /><span>' . __('Download', 'wpvivid-backuprestore') . ' (' . esc_html(size_format($backup_size, 2)) . ')' .'</span>
<div class="spinner" id="wpvivid_download_loading_' . $key . '" style="float:right;width:auto;height:auto;padding:10px 180px 10px 0;background-position:0 0;"></div>
</div>
</div>
</td>
<td class="tablelistcolumn" style="min-width:100px;">
<div class="' . $tour_class . '" onclick="wpvivid_popup_tour(\'' . $hide . '\');">
' . $tour_message . '<div style="cursor:pointer;padding:10px 0 10px 0;" onclick="wpvivid_initialize_restore(\'' . $key . '\',\'' . gmdate('M-d-Y H:i', $backup_time) . '\',\'' . $value['type'] . '\');" style="float:left;padding:10px 10px 10px 0;">
<img src="' . esc_url(WPVIVID_PLUGIN_URL . '/admin/partials/images/Restore.png') . '" style="vertical-align:middle;" /><span>' . __('Restore', 'wpvivid-backuprestore') . '</span>
</div>
</div>
</td>
<td class="tablelistcolumn">
<div class="backuplist-delete-backup" style="padding:10px 0 10px 0;">
<img src="' . esc_url(WPVIVID_PLUGIN_URL . '/admin/partials/images/Delete.png') . '" style="vertical-align:middle; cursor:pointer;" title="'. __('Delete the backup', 'wpvivid-backuprestore') .'" onclick="wpvivid_delete_selected_backup(\'' . $key . '\', \'' . $list_name . '\');"/>
</div>
</td>
</tr>';
}
}
return $html;
}
public function wpvivid_add_backup_list_output()
{
$list_name = 'wpvivid_backup_list';
$backuplist=WPvivid_Backuplist::get_backuplist($list_name);
$remote=array();
$remote=apply_filters('wpvivid_remote_pic', $remote);
$upload_title = '';
foreach ($backuplist as $key=>$value) {
if($value['type'] !== 'Rollback') {
$row_style = '';
if ($value['type'] == 'Migration' || $value['type'] == 'Upload') {
if ($value['type'] == 'Migration') {
$upload_title = 'Received Backup: ';
} else if ($value['type'] == 'Upload') {
$upload_title = __('Uploaded Backup: ', 'wpvivid-backuprestore');
}
$row_style = 'border: 2px solid #006799; box-sizing:border-box; -moz-box-sizing:border-box; -webkit-box-sizing:border-box;';
} else if ($value['type'] == 'Manual' || $value['type'] == 'Cron') {
$row_style = '';
$upload_title = '';
} else {
$upload_title = '';
}
if (empty($value['lock'])) {
$backup_lock = '/admin/partials/images/unlocked.png';
$lock_status = 'unlock';
} else {
if ($value['lock'] == 0) {
$backup_lock = '/admin/partials/images/unlocked.png';
$lock_status = 'unlock';
} else {
$backup_lock = '/admin/partials/images/locked.png';
$lock_status = 'lock';
}
}
$backup_size=0;
$backup_time=$value['create_time'];
if(isset($value['backup']['files'])){
foreach ($value['backup']['files'] as $file_info){
$backup_size+=$file_info['size'];
if(preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}/',$file_info['file_name'],$matches))
{
$backup_date=$matches[0];
}
else
{
$backup_date=$value['create_time'];
}
$time_array=explode('-',$backup_date);
if(sizeof($time_array)>4){
$time=$time_array[0].'-'.$time_array[1].'-'.$time_array[2].' '.$time_array[3].':'.$time_array[4];
$backup_time=strtotime($time);
}
//break;
}
}
$hide = 'hide';
?>
<tr style="<?php echo esc_attr($row_style); ?>">
<th class="check-column"><input name="check_backup" type="checkbox" id="<?php echo esc_attr($key); ?>" value="<?php echo esc_attr($key); ?>" onclick="wpvivid_click_check_backup('<?php echo esc_js($key); ?>', '<?php echo esc_js($list_name); ?>');" /></th>
<td class="tablelistcolumn">
<div style="float:left;padding:0 10px 10px 0;">
<div class="backuptime"><strong><?php echo esc_html($upload_title); ?></strong><?php echo esc_html(gmdate('M-d-Y H:i', $backup_time)); ?></div>
<div class="common-table">
<span title="To lock the backup, the backup can only be deleted manually" id="wpvivid_lock_<?php echo esc_attr($key); ?>">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL . $backup_lock); ?>" name="<?php echo esc_attr($lock_status); ?>" onclick="wpvivid_set_backup_lock('<?php echo esc_js($key); ?>', '<?php echo esc_js($lock_status); ?>');" style="vertical-align:middle; cursor:pointer;"/>
</span>
<span style="margin:0;">|</span> <span><?php esc_html_e('Type: ', 'wpvivid-backuprestore'); ?></span><span><?php echo esc_html($value['type']); ?></span>
<span style="margin:0;">|</span> <span title="Backup log"><a href="#" onclick="wpvivid_read_log('wpvivid_view_backup_log', '<?php echo esc_js($key); ?>');"><img src="<?php echo esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/Log.png'); ?>" style="vertical-align:middle;cursor:pointer;"/><span style="margin:0;"><?php esc_html_e('Log', 'wpvivid-backuprestore'); ?></span></a></span>
</div>
</div>
</td>
<td class="tablelistcolumn">
<div style="float:left;padding:10px 10px 10px 0;">
<?php
$remote_pic_html = '';
$save_local_pic_y = '/admin/partials/images/storage-local.png';
$save_local_pic_n = '/admin/partials/images/storage-local(gray).png';
$local_title = 'Localhost';
if ($value['save_local'] == 1 || $value['type'] == 'Migration') {
echo '<img src="'.esc_url(WPVIVID_PLUGIN_URL . $save_local_pic_y).'" style="vertical-align:middle; " title="'.esc_attr($local_title).'"/>';
} else {
echo '<img src="'.esc_url(WPVIVID_PLUGIN_URL . $save_local_pic_n).'" style="vertical-align:middle; " title="'.esc_attr($local_title).'"/>';
}
$b_has_remote = false;
if (is_array($remote)) {
foreach ($remote as $key1 => $value1) {
$pic = $value1['default_pic'];
foreach ($value['remote'] as $storage_type) {
$b_has_remote = true;
if ($key1 === $storage_type['type']) {
$pic = $value1['selected_pic'];
} else {
$pic = $value1['default_pic'];
}
}
if (!$b_has_remote) {
$pic = $value1['default_pic'];
}
$title = $value1['title'];
echo '<img src="'.esc_url(WPVIVID_PLUGIN_URL . $pic).'" style="vertical-align:middle; " title="'.esc_attr($title).'"/>';
}
}
?>
</div>
</td>
<td class="tablelistcolumn" style="min-width:100px;">
<div id="wpvivid_file_part_<?php echo esc_attr($key); ?>" style="float:left;padding:10px 10px 10px 0;">
<div style="cursor:pointer;" onclick="wpvivid_initialize_download('<?php echo esc_js($key); ?>', '<?php echo esc_js($list_name); ?>');" title="<?php esc_attr_e('Prepare to download the backup', 'wpvivid-backuprestore'); ?>">
<img id="wpvivid_download_btn_<?php echo esc_attr($key); ?>" src="<?php echo esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/download.png'); ?>" style="vertical-align:middle;" /><span><?php esc_html_e('Download', 'wpvivid-backuprestore'); echo ' ('.esc_html(size_format($backup_size, 2)).')'; ?></span>
<div class="spinner" id="wpvivid_download_loading_<?php esc_attr($key); ?>" style="float:right;width:auto;height:auto;padding:10px 180px 10px 0;background-position:0 0;"></div>
</div>
</div>
</td>
<td class="tablelistcolumn" style="min-width:100px;">
<div onclick="wpvivid_popup_tour('<?php echo esc_js($hide); ?>');">
<div style="cursor:pointer;padding:10px 0 10px 0;" onclick="wpvivid_initialize_restore('<?php echo esc_js($key); ?>','<?php echo esc_js(gmdate('M-d-Y H:i', $backup_time)); ?>','<?php echo esc_js($value['type']); ?>');" style="float:left;padding:10px 10px 10px 0;">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL . '/admin/partials/images/Restore.png'); ?>" style="vertical-align:middle;" /><span><?php esc_html_e('Restore', 'wpvivid-backuprestore'); ?></span>
</div>
</div>
</td>
<td class="tablelistcolumn">
<div class="backuplist-delete-backup" style="padding:10px 0 10px 0;">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL . '/admin/partials/images/Delete.png'); ?>" style="vertical-align:middle; cursor:pointer;" title="<?php esc_attr_e('Delete the backup', 'wpvivid-backuprestore'); ?>" onclick="wpvivid_delete_selected_backup('<?php echo esc_js($key); ?>', '<?php echo esc_js($list_name); ?>');"/>
</div>
</td>
</tr>
<?php
}
}
}
public function wpvivid_add_remote_storage_list($html)
{
$html = '';
$remoteslist=WPvivid_Setting::get_all_remote_options();
$default_remote_storage='';
foreach ($remoteslist['remote_selected'] as $value) {
$default_remote_storage=$value;
}
$i=1;
foreach ($remoteslist as $key=>$value)
{
if($key === 'remote_selected')
{
continue;
}
if ($key === $default_remote_storage)
{
$check_status = 'checked';
}
else
{
$check_status='';
}
$storage_type = $value['type'];
$storage_type=apply_filters('wpvivid_storage_provider_tran', $storage_type);
$html .= '<tr>
<td>'.$i++.'</td>
<td><input type="checkbox" name="remote_storage" value="'.esc_attr($key).'" '.esc_attr($check_status).' /></td>
<td>'.$storage_type.'</td>
<td class="row-title"><label for="tablecell">'.$value['name'].'</label></td>
<td>
<div style="float: left;"><img src="'.esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/Edit.png').'" onclick="click_retrieve_remote_storage(\''.esc_attr($key).'\',\''.esc_attr($value['type']).'\',\''.esc_attr($value['name']).'\'
);" style="vertical-align:middle; cursor:pointer;" title="'. esc_html__('Edit the remote storage', 'wpvivid-backuprestore') .'"/></div>
<div><img src="'.esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/Delete.png').'" onclick="wpvivid_delete_remote_storage(\''.esc_attr($key).'\'
);" style="vertical-align:middle; cursor:pointer;" title="'. esc_html__('Remove the remote storage', 'wpvivid-backuprestore') .'"/></div>
</td>
</tr>';
}
return $html;
}
public function wpvivid_remote_storage($remote_storage){
$remote_id_array = WPvivid_Setting::get_user_history('remote_selected');
$remote_storage = false;
foreach ($remote_id_array as $value){
$remote_storage = true;
}
return $remote_storage;
}
public function wpvivid_add_remote_notice($notice_type, $message){
$html = '';
if($notice_type) {
$html .= '<div class="notice notice-success is-dismissible inline"><p>'.$message.'</p>
<button type="button" class="notice-dismiss" onclick="click_dismiss_notice(this);">
<span class="screen-reader-text">Dismiss this notice.</span>
</button>
</div>';
}
else{
$html .= '<div class="notice notice-error"><p>' . $message . '</p></div>';
}
return $html;
}
public function wpvivid_schedule_add_remote_pic($html){
$html = '';
$remoteslist=WPvivid_Setting::get_all_remote_options();
$default_remote_storage=array();
foreach ($remoteslist['remote_selected'] as $value) {
$default_remote_storage[]=$value;
}
$remote_storage_type=array();
foreach ($remoteslist as $key=>$value)
{
if(in_array($key, $default_remote_storage))
{
$remote_storage_type[]=$value['type'];
}
}
$remote=array();
$remote=apply_filters('wpvivid_remote_pic', $remote);
if(is_array($remote)) {
foreach ($remote as $key => $value) {
$title = $value['title'];
if (in_array($key, $remote_storage_type)) {
$pic = $value['selected_pic'];
} else {
$pic = $value['default_pic'];
}
$url = apply_filters('wpvivid_get_wpvivid_pro_url', WPVIVID_PLUGIN_URL, $key);
$html .= '<img src="' . esc_url($url . $pic) . '" style="vertical-align:middle; " title="' . $title . '"/>';
}
$html.='<img onclick="wpvivid_click_switch_page(\'wrap\', \'wpvivid_tab_remote_storage\', true);" src="'.esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/add-storages.png').'" style="vertical-align:middle;" title="'.esc_attr__('Add a storage', 'wpvivid-backuprestore').'"/>';
}
return $html;
}
public function wpvivid_schedule_local_remote($html){
$html = '';
$schedule=WPvivid_Schedule::get_schedule();
$backup_local = 'checked';
$backup_remote = '';
if($schedule['enable'] == true)
{
if($schedule['backup']['remote'] === 1)
{
$backup_local = '';
$backup_remote = 'checked';
}
else{
$backup_local = 'checked';
$backup_remote = '';
}
}
$html .= '<fieldset>
<label title="">
<input type="radio" option="schedule" name="save_local_remote" value="local" '.$backup_local.' />
<span>'.__( 'Save backups on localhost (web server)', 'wpvivid-backuprestore' ).'</span>
</label><br>
<label title="">
<input type="radio" option="schedule" name="save_local_remote" value="remote" '.$backup_remote.' />
<span>'.__( 'Send backups to remote storage (You can choose whether to keep the backup in localhost after it is uploaded to cloud storage in Settings.)', 'wpvivid-backuprestore' ).'</span>
</label>
<label style="display: none;">
<input type="checkbox" option="schedule" name="lock" value="0" />
</label>
</fieldset>';
return $html;
}
public function wpvivid_get_remote_directory($out_of_date_remote){
$out_of_date=$this->_get_out_of_date_info();
$out_of_date_remote='There is no path for remote storage, please set it up first.';
if($out_of_date['remote_options'] !== false)
{
$out_of_date_remote_temp = array();
foreach ($out_of_date['remote_options'] as $value)
{
$out_of_date_remote=apply_filters('wpvivid_get_out_of_date_remote',$out_of_date_remote, $value);
$value['type']=apply_filters('wpvivid_storage_provider_tran', $value['type']);
$out_of_date_remote_temp[] = $value['type'].': '.$out_of_date_remote;
}
$out_of_date_remote = implode(',', $out_of_date_remote_temp);
}
return $out_of_date_remote;
}
public function init_remote_option()
{
$remoteslist=WPvivid_Setting::get_all_remote_options();
foreach ($remoteslist as $key=>$value)
{
if(!array_key_exists('options',$value))
{
continue;
}
$remote = array();
if($value['type'] === 'ftp')
{
$remote['host']=$value['options']['host'];
$remote['username']=$value['options']['username'];
$remote['password']=$value['options']['password'];
$remote['path']=$value['options']['path'];
$remote['name']=$value['options']['name'];
$remote['passive']=$value['options']['passive'];
$value['type'] = strtolower($value['type']);
$remote['type']=$value['type'];
$remoteslist[$key]=$remote;
}
elseif ($value['type'] === 'sftp')
{
$remote['host']=$value['options']['host'];
$remote['username']=$value['options']['username'];
$remote['password']=$value['options']['password'];
$remote['path']=$value['options']['path'];
$remote['name']=$value['options']['name'];
$remote['port']=$value['options']['port'];
$value['type'] = strtolower($value['type']);
$remote['type']=$value['type'];
$remoteslist[$key]=$remote;
}
elseif ($value['type'] === 'amazonS3')
{
$remote['classMode']='0';
$remote['sse']='0';
$remote['name']=$value['options']['name'];
$remote['access']=$value['options']['access'];
$remote['secret']=$value['options']['secret'];
$remote['s3Path']=$value['options']['s3Path'];
$value['type'] = strtolower($value['type']);
$remote['type']=$value['type'];
$remoteslist[$key]=$remote;
}
}
WPvivid_Setting::update_option('wpvivid_upload_setting',$remoteslist);
$backuplist=WPvivid_Backuplist::get_backuplist();
foreach ($backuplist as $key=>$value)
{
if(is_array($value['remote']))
{
foreach ($value['remote'] as $remote_key=>$storage_type)
{
if(!array_key_exists('options',$storage_type))
{
continue;
}
$remote = array();
if($storage_type['type'] === 'ftp')
{
$remote['host']=$storage_type['options']['host'];
$remote['username']=$storage_type['options']['username'];
$remote['password']=$storage_type['options']['password'];
$remote['path']=$storage_type['options']['path'];
$remote['name']=$storage_type['options']['name'];
$remote['passive']=$storage_type['options']['passive'];
$storage_type['type'] = strtolower($storage_type['type']);
$remote['type']=$storage_type['type'];
}
elseif ($storage_type['type'] === 'sftp')
{
$remote['host']=$storage_type['options']['host'];
$remote['username']=$storage_type['options']['username'];
$remote['password']=$storage_type['options']['password'];
$remote['path']=$storage_type['options']['path'];
$remote['name']=$storage_type['options']['name'];
$remote['port']=$storage_type['options']['port'];
$storage_type['type'] = strtolower($storage_type['type']);
$remote['type']=$storage_type['type'];
}
elseif ($storage_type['type'] === 'amazonS3')
{
$remote['classMode']='0';
$remote['sse']='0';
$remote['name']=$storage_type['options']['name'];
$remote['access']=$storage_type['options']['access'];
$remote['secret']=$storage_type['options']['secret'];
$remote['s3Path']=$storage_type['options']['s3Path'];
$storage_type['type'] = strtolower($storage_type['type']);
$remote['type']=$storage_type['type'];
}
$backuplist[$key]['remote'][$remote_key]=$remote;
}
}
}
WPvivid_Setting::update_option('wpvivid_backup_list',$backuplist);
}
public function need_review()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_POST['review']) && !empty($_POST['review']) && is_string($_POST['review'])) {
$review = sanitize_text_field($_POST['review']);
if ($review == 'rate-now') {
$review_option = 'do_not_ask';
echo 'https://wordpress.org/support/plugin/wpvivid-backuprestore/reviews/?filter=5';
} elseif ($review == 'never-ask') {
$review_option = 'do_not_ask';
echo '';
} elseif ($review == 'already-done'){
$review_option = 'do_not_ask';
echo '';
} elseif ($review == 'ask-later') {
$review_option = 'not';
$review_type = WPvivid_Setting::get_option('wpvivid_review_type', false);
if($review_type === 'manual' || $review_type === 'migration')
{
WPvivid_Setting::update_option('wpvivid_review_time', time()+ 7*24*60*60);
}
WPvivid_Setting::update_option('cron_backup_count', 0);
echo '';
} elseif ($review == 'dismiss') {
$review_option = 'not';
$review_type = WPvivid_Setting::get_option('wpvivid_review_type', false);
if($review_type === 'manual' || $review_type === 'migration')
{
WPvivid_Setting::update_option('wpvivid_review_time', time()+ 14*24*60*60);
WPvivid_Setting::update_option('cron_backup_count', 0);
}
echo '';
} else {
$review_option = 'not';
echo '';
}
WPvivid_Setting::update_option('wpvivid_need_review', $review_option);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function wpvivid_send_debug_info(){
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (!isset($_POST['user_mail']) || empty($_POST['user_mail'])) {
$ret['result'] = 'failed';
$ret['error'] = __('User\'s email address is required.', 'wpvivid-backuprestore');
} else {
$pattern = '/^[a-z0-9]+([._-][a-z0-9]+)*@([0-9a-z-]+\.[a-z]{2,14}(\.[a-z]{2})?)$/i';
if (!preg_match($pattern, $_POST['user_mail'])) {
$ret['result'] = 'failed';
$ret['error'] = __('Please enter a valid email address.', 'wpvivid-backuprestore');
} else {
$user_mail=sanitize_email($_POST['user_mail']);
$server_type=sanitize_text_field($_POST['server_type']);
$host_provider=sanitize_text_field($_POST['host_provider']);
$comment=sanitize_text_field($_POST['comment']);
if(!class_exists('WPvivid_mail_report'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-mail-report.php';
$ret = WPvivid_mail_report::wpvivid_send_debug_info($user_mail,$server_type,$host_provider,$comment);
}
}
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function get_ini_memory_limit(){
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
$memory_limit = @ini_get('memory_limit');
echo esc_html($memory_limit);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function wpvivid_switch_domain_to_folder($domain){
$parse = wp_parse_url($domain);
$path = '';
if(isset($parse['path'])) {
$parse['path'] = str_replace('/', '_', $parse['path']);
$parse['path'] = str_replace('.', '_', $parse['path']);
$path = $parse['path'];
}
$parse['host'] = str_replace('/', '_', $parse['host']);
$parse['host'] = str_replace('.', '_', $parse['host']);
return $parse['host'].$path;
}
public function wpvivid_check_zip_valid()
{
return true;
}
public function amazons3_notice()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
$notice_message = 'init';
WPvivid_Setting::update_option('wpvivid_amazons3_notice', $notice_message);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function wpvivid_check_type_database($is_type_db, $data){
if(isset($data['dump_db'])){
$is_type_db = true;
}
return $is_type_db;
}
public function hide_mainwp_tab_page(){
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
WPvivid_Setting::update_option('wpvivid_hide_mwp_tab_page_v1', true);
$ret['result']=WPVIVID_SUCCESS;
echo wp_json_encode($ret);
die();
}
public function hide_wp_cron_notice(){
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
WPvivid_Setting::update_option('wpvivid_hide_wp_cron_notice', true);
$ret['result']=WPVIVID_SUCCESS;
echo wp_json_encode($ret);
die();
}
public function download_backup_mainwp()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_REQUEST['backup_id']) && isset($_REQUEST['file_name'])) {
if (!empty($_REQUEST['backup_id']) && is_string($_REQUEST['backup_id'])) {
$backup_id = sanitize_key($_REQUEST['backup_id']);
} else {
die();
}
if (!empty($_REQUEST['file_name']) && is_string($_REQUEST['file_name'])) {
//$file_name=sanitize_file_name($_REQUEST['file_name']);
$file_name = sanitize_text_field($_REQUEST['file_name']);
} else {
die();
}
$cache = WPvivid_taskmanager::get_download_cache($backup_id);
if ($cache === false) {
$this->init_download($backup_id);
$cache = WPvivid_taskmanager::get_download_cache($backup_id);
}
$path = false;
if (array_key_exists($file_name, $cache['files'])) {
if ($cache['files'][$file_name]['status'] == 'completed') {
$path = $cache['files'][$file_name]['download_path'];
}
}
if ($path !== false) {
if (file_exists($path)) {
if (session_id())
session_write_close();
$size = filesize($path);
if (!headers_sent()) {
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . $size);
header('Content-Transfer-Encoding: binary');
}
if ($size < 1024 * 1024 * 60) {
ob_end_clean();
readfile($path);
exit;
} else {
ob_end_clean();
$download_rate = 1024 * 10;
$file = fopen($path, "r");
while (!feof($file)) {
@set_time_limit(20);
// send the current file part to the browser
print fread($file, round($download_rate * 1024));
// flush the content to the browser
ob_flush();
flush();
// sleep one second
sleep(1);
}
fclose($file);
exit;
}
}
}
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
$admin_url = admin_url();
echo '<a href="'.esc_url($admin_url).'admin.php?page=WPvivid">file not found. please retry again.</a>';
die();
}
public function set_mail_subject($subject, $task){
if(!class_exists('WPvivid_mail_report'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-mail-report.php';
$subject=WPvivid_mail_report::create_subject($task);
return $subject;
}
public function set_mail_body($body, $task){
if(!class_exists('WPvivid_mail_report'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-mail-report.php';
$body=WPvivid_mail_report::create_body($task);
return $body;
}
public function wpvivid_handle_mainwp_action($data){
$public_interface = new WPvivid_Public_Interface();
$ret = $public_interface->mainwp_data($data);
return $ret;
}
public function get_zip_object_class($class)
{
/*if(version_compare(phpversion(),'8.0.0','>='))
{
return 'WPvivid_PclZip_Class_Ex';
}
return $class;*/
return 'WPvivid_PclZip_Class_Ex';
}
public function get_backup_path($backup_item, $file_name)
{
$path = $backup_item->get_local_path() . $file_name;
if (file_exists($path)) {
return $path;
}
else{
$local_setting = get_option('wpvivid_local_setting', array());
if(!empty($local_setting))
{
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $local_setting['path'] . DIRECTORY_SEPARATOR . $file_name;
}
else {
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'wpvividbackups' . DIRECTORY_SEPARATOR . $file_name;
}
}
return $path;
}
public function get_backup_folder()
{
$local_setting = get_option('wpvivid_local_setting', array());
if(!empty($local_setting))
{
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $local_setting['path'] . DIRECTORY_SEPARATOR;
}
else {
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'wpvividbackups' . DIRECTORY_SEPARATOR;
}
return $path;
}
public function get_backup_url($backup_item, $file_name)
{
$path = $backup_item->get_local_path() . $file_name;
if (file_exists($path)) {
return $backup_item->get_local_url() . $file_name;
}
else{
$local_setting = get_option('wpvivid_local_setting', array());
if(!empty($local_setting))
{
$url = content_url().DIRECTORY_SEPARATOR.$local_setting['path'].DIRECTORY_SEPARATOR.$file_name;
}
else {
$url = content_url().DIRECTORY_SEPARATOR.'wpvividbackups'.DIRECTORY_SEPARATOR.$file_name;
}
}
return $url;
}
public function wpvivid_check_add_litespeed_server($task_id)
{
$litespeed=false;
if ( isset( $_SERVER['HTTP_X_LSCACHE'] ) && $_SERVER['HTTP_X_LSCACHE'] )
{
$litespeed=true;
}
elseif ( isset( $_SERVER['LSWS_EDITION'] ) && strpos( $_SERVER['LSWS_EDITION'], 'Openlitespeed' ) === 0 ) {
$litespeed=true;
}
elseif ( isset( $_SERVER['SERVER_SOFTWARE'] ) && $_SERVER['SERVER_SOFTWARE'] == 'LiteSpeed' ) {
$litespeed=true;
}
if($litespeed)
{
if($this->wpvivid_log->log_file_handle==false)
{
$this->wpvivid_log->OpenLogFile(WPvivid_taskmanager::get_task_options($task_id,'log_file_name'));
}
$this->wpvivid_log->WriteLog('LiteSpeed Server.','notice');
if ( ! function_exists( 'got_mod_rewrite' ) )
{
require_once ABSPATH . 'wp-admin/includes/misc.php';
}
if(function_exists('insert_with_markers'))
{
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
$home_path = get_home_path();
$htaccess_file = $home_path . '.htaccess';
if ( ( ! file_exists( $htaccess_file ) && is_writable( $home_path ) ) || is_writable( $htaccess_file ) )
{
if ( got_mod_rewrite() )
{
$line[]='<IfModule Litespeed>';
$line[]='RewriteEngine On';
$line[]='RewriteRule .* - [E=noabort:1, E=noconntimeout:1]';
$line[]='</IfModule>';
insert_with_markers($htaccess_file,'WPvivid Rewrite Rule for LiteSpeed',$line);
$this->wpvivid_log->WriteLog('Add LiteSpeed Rule','notice');
}
else
{
$this->wpvivid_log->WriteLog('mod_rewrite not found.','notice');
}
}
else
{
$this->wpvivid_log->WriteLog('.htaccess file not exists or not writable.','notice');
}
}
else
{
$this->wpvivid_log->WriteLog('insert_with_markers function not exists.','notice');
}
}
}
public function wpvivid_check_clear_litespeed_rule($task_id)
{
$litespeed=false;
if ( isset( $_SERVER['HTTP_X_LSCACHE'] ) && $_SERVER['HTTP_X_LSCACHE'] )
{
$litespeed=true;
}
elseif ( isset( $_SERVER['LSWS_EDITION'] ) && strpos( $_SERVER['LSWS_EDITION'], 'Openlitespeed' ) === 0 ) {
$litespeed=true;
}
elseif ( isset( $_SERVER['SERVER_SOFTWARE'] ) && $_SERVER['SERVER_SOFTWARE'] == 'LiteSpeed' ) {
$litespeed=true;
}
if($litespeed)
{
if($this->wpvivid_log->log_file_handle==false)
{
$this->wpvivid_log->OpenLogFile(WPvivid_taskmanager::get_task_options($task_id,'log_file_name'));
}
$this->wpvivid_log->WriteLog('LiteSpeed Server.','notice');
if ( ! function_exists( 'got_mod_rewrite' ) )
{
require_once ABSPATH . 'wp-admin/includes/misc.php';
}
if(function_exists('insert_with_markers'))
{
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
$home_path = get_home_path();
$htaccess_file = $home_path . '.htaccess';
if ( ( ! file_exists( $htaccess_file ) && is_writable( $home_path ) ) || is_writable( $htaccess_file ) )
{
if ( got_mod_rewrite() )
{
insert_with_markers($htaccess_file,'WPvivid Rewrite Rule for LiteSpeed','');
$this->wpvivid_log->WriteLog('Clear LiteSpeed Rule','notice');
}
else
{
$this->wpvivid_log->WriteLog('mod_rewrite not found.','notice');
}
}
else
{
$this->wpvivid_log->WriteLog('.htaccess file not exists or not writable.','notice');
}
}
else
{
$this->wpvivid_log->WriteLog('insert_with_markers function not exists.','notice');
}
}
}
}
includes/class-wpvivid-schedule.php 0000644 00000032441 15132770567 0013471 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_Schedule
{
protected $schedule_type = array(
'wpvivid_12hours' => '12Hours',
'twicedaily' => '12Hours',
'wpvivid_daily' => 'Daily',
'daily' => 'Daily',
'onceday' => 'Daily',
'wpvivid_weekly' => 'Weekly',
'weekly' => 'Weekly',
'wpvivid_fortnightly' => 'Fortnightly',
'fortnightly' => 'Fortnightly',
'wpvivid_monthly' => 'Monthly',
'monthly' => 'Monthly',
'montly' => 'Monthly'
);
public function __construct()
{
add_action('wpvivid_reset_schedule', array($this, 'wpvivid_reset_schedule'), 10);
}
public function wpvivid_cron_schedules($schedules)
{
if(!isset($schedules["wpvivid_12hours"])){
$schedules["wpvivid_12hours"] = array(
'interval' => 3600*12,
'display' => __('12 Hours', 'wpvivid-backuprestore'));
}
if(!isset($schedules["wpvivid_daily"])){
$schedules["wpvivid_daily"] = array(
'interval' => 86400 ,
'display' => __('Daily', 'wpvivid-backuprestore'));
}
if(!isset($schedules["wpvivid_weekly"])){
$schedules["wpvivid_weekly"] = array(
'interval' => 604800 ,
'display' => __('Weekly', 'wpvivid-backuprestore'));
}
if(!isset($schedules["wpvivid_fortnightly"])){
$schedules["wpvivid_fortnightly"] = array(
'interval' => 604800*2 ,
'display' => __('Fortnightly', 'wpvivid-backuprestore'));
}
if(!isset($schedules["wpvivid_monthly"])){
$schedules["wpvivid_monthly"] = array(
'interval' => 2592000 ,
'display' => __('Monthly', 'wpvivid-backuprestore'));
}
return $schedules;
}
public function check_schedule_type($display){
$schedules = wp_get_schedules();
$check_res = false;
$ret = array();
foreach ($this->schedule_type as $key => $value){
if($value == $display){
if(isset($schedules[$key])){
$check_res = true;
$ret['type']=$key;
break;
}
}
}
$ret['result']=$check_res;
return $ret;
}
public function output($html)
{
$html='';
$display_array = array("12Hours", "Daily", "Weekly", "Fortnightly", "Monthly");
foreach($display_array as $display){
$schedule_check = $this->check_schedule_type($display);
if($schedule_check['result']){
$html.=' <label><input type="radio" option="schedule" name="recurrence" value="'.$schedule_check['type'].'" />';
if($display === '12Hours'){
$html.='<span>'.__('12Hours', 'wpvivid-backuprestore').'</span></label><br>';
}
if($display === 'Daily'){
$html.='<span>'.__('Daily', 'wpvivid-backuprestore').'</span></label><br>';
}
if($display === 'Weekly'){
$html.='<span>'.__('Weekly', 'wpvivid-backuprestore').'</span></label><br>';
}
if($display === 'Fortnightly'){
$html.='<span>'.__('Fortnightly', 'wpvivid-backuprestore').'</span></label><br>';
}
if($display === 'Monthly'){
$html.='<span>'.__('Monthly', 'wpvivid-backuprestore').'</span></label><br>';
}
}
else{
$html.='<p>Warning: Unable to set '.$display.' backup schedule</p>';
}
}
$html.='<label>';
$html.='<div style="float: left;">';
$html.='<input type="radio" disabled />';
$html.='<span class="wpvivid-element-space-right" style="color: #ddd;">'.__('Custom', 'wpvivid-backuprestore').'</span>';
$html.='</div>';
$html.='<div style="float: left; height: 32px; line-height: 32px;">';
$html.='<span class="wpvivid-feature-pro">';
$html.='<a href="https://docs.wpvivid.com/wpvivid-backup-pro-customize-start-time.html" style="text-decoration: none; margin-top: 10px;">'.__('Pro feature: learn more', 'wpvivid-backuprestore').'</a>';
$html.='</span>';
$html.='</div>';
$html.='</label><br>';
return $html;
}
public static function get_start_time($time)
{
if(!is_array( $time ) )
{
return false;
}
if(!isset($time['type']))
{
return false;
}
$week=$time['start_time']['week'];
$day=$time['start_time']['day'];
$current_day=$time['start_time']['current_day'];
if(strtotime('now')>strtotime($current_day)){
$daily_start_time = $current_day.' +1 day';
}
else{
$daily_start_time = $current_day;
}
$weekly_tmp = $week.' '.$current_day;
if(strtotime('now')>strtotime($weekly_tmp)) {
$weekly_start_time = $week.' '.$weekly_tmp.' next week';
}
else{
$weekly_start_time = $weekly_tmp;
}
$date_now = gmdate("Y-m-",time());
$monthly_tmp = $date_now.$day.' '.$current_day;
if(strtotime('now')>strtotime($monthly_tmp)){
$date_now = gmdate("Y-m-",strtotime('+1 month'));
$monthly_start_time = $date_now.$day.' '.$current_day;
}
else{
$monthly_start_time = $monthly_tmp;
}
$schedule_type_ex = array(
'wpvivid_12hours' => '12Hours',
'twicedaily' => '12Hours',
'wpvivid_daily' => 'Daily',
'daily' => 'Daily',
'onceday' => 'Daily',
'wpvivid_weekly' => 'Weekly',
'weekly' => 'Weekly',
'wpvivid_fortnightly' => 'Fortnightly',
'fortnightly' => 'Fortnightly',
'wpvivid_monthly' => 'Monthly',
'monthly' => 'Monthly',
'montly' => 'Monthly'
);
$display_array = array(
"12Hours" => $daily_start_time,
"Daily" => $daily_start_time,
"Weekly" => $weekly_start_time,
"Fortnightly" => $weekly_start_time,
"Monthly" => $monthly_start_time
);
foreach ($schedule_type_ex as $key => $value){
if($key == $time['type']){
foreach ($display_array as $display_key => $display_value){
if($value == $display_key){
return strtotime($display_value);
}
}
}
}
return false;
}
public static function get_schedule($schedule_id = '')
{
add_filter('wpvivid_get_schedule', array('WPvivid_Schedule', 'get_schedule_ex'),10,2);
$schedule=array();
$schedule=apply_filters('wpvivid_get_schedule',$schedule,$schedule_id);
return $schedule;
}
public static function get_schedule_ex($schedule,$schedule_id)
{
$schedule=WPvivid_Setting::get_option('wpvivid_schedule_setting');
if(empty($schedule['backup']))
{
$schedule['backup']['backup_files']='files+db';
$schedule['backup']['local']=1;
$schedule['backup']['remote']=0;
$schedule['backup']['ismerge']=1;
$schedule['backup']['lock']=0;
}
$recurrence = wp_get_schedule(WPVIVID_MAIN_SCHEDULE_EVENT);
if(!wp_get_schedule(WPVIVID_MAIN_SCHEDULE_EVENT))
{
$schedule['enable']=false;
return $schedule;
}
$schedule['enable']=true;
$schedule['recurrence']=$recurrence;
$timestamp=wp_next_scheduled(WPVIVID_MAIN_SCHEDULE_EVENT);
$schedule['next_start']=$timestamp;
return $schedule;
}
public static function set_schedule($schedule_data,$schedule)
{
if($schedule['enable']==1)
{
$schedule_data['enable']=$schedule['enable'];
$schedule_data['type']=$schedule['recurrence'];
$schedule_data['event']=WPVIVID_MAIN_SCHEDULE_EVENT;
$time['type']=$schedule['recurrence'];
$time['start_time']['week']='mon';
$time['start_time']['day']='01';
$time['start_time']['current_day']="00:00";
$timestamp=WPvivid_Schedule::get_start_time($time);
$schedule_data['start_time']=$timestamp;
$schedule_data['backup']['backup_files']=$schedule['backup_type'];
if($schedule['save_local_remote']=='remote')
{
$schedule_data['backup']['local']=0;
$schedule_data['backup']['remote']=1;
}
else
{
$schedule_data['backup']['local']=1;
$schedule_data['backup']['remote']=0;
}
$schedule_data['backup']['ismerge']=1;
$schedule_data['backup']['lock']=$schedule['lock'];
}
else
{
$schedule_data['enable']=$schedule['enable'];
}
return $schedule_data;
}
public static function set_schedule_ex($schedule)
{
add_filter('wpvivid_set_schedule', array('WPvivid_Schedule', 'set_schedule'),10,2);
$schedule_data=array();
$schedule_data= apply_filters('wpvivid_set_schedule',$schedule_data, $schedule);
WPvivid_Setting::update_option('wpvivid_schedule_setting',$schedule_data);
if($schedule_data===false)
{
$ret['result']='failed';
$ret['error']=__('Creating scheduled tasks failed. Please try again later.', 'wpvivid-backuprestore');
return $ret;
}
if($schedule_data['enable']==1)
{
if(wp_get_schedule($schedule_data['event']))
{
$timestamp = wp_next_scheduled($schedule_data['event']);
wp_unschedule_event($timestamp,$schedule_data['event']);
}
if(wp_schedule_event($schedule_data['start_time'], $schedule_data['type'], $schedule_data['event'])===false)
{
$ret['result']='failed';
$ret['error']=__('Creating scheduled tasks failed. Please try again later.', 'wpvivid-backuprestore');
$ret['data']=$schedule_data;
return $ret;
}
else
{
$ret['result']='success';
$ret['data']=$schedule_data;
return $ret;
}
}
else
{
if(wp_get_schedule(WPVIVID_MAIN_SCHEDULE_EVENT))
{
wp_clear_scheduled_hook(WPVIVID_MAIN_SCHEDULE_EVENT);
$timestamp = wp_next_scheduled(WPVIVID_MAIN_SCHEDULE_EVENT);
wp_unschedule_event($timestamp,WPVIVID_MAIN_SCHEDULE_EVENT);
}
$ret['result']='success';
$ret['data']=$schedule_data;
return $ret;
}
}
public function wpvivid_reset_schedule()
{
self::reset_schedule();
return true;
}
public static function reset_schedule()
{
$schedule=WPvivid_Setting::get_option('wpvivid_schedule_setting');
if(!empty($schedule))
{
if($schedule['enable'])
{
self::set_schedule_ex($schedule);
}
else
{
self::disable_schedule();
}
}
else
{
self::disable_schedule();
}
return true;
}
public static function disable_schedule()
{
$schedule=WPvivid_Setting::get_option('wpvivid_schedule_setting');
$schedule['enable']=false;
WPvivid_Setting::update_option('wpvivid_schedule_setting',$schedule);
if(wp_get_schedule(WPVIVID_MAIN_SCHEDULE_EVENT))
{
wp_clear_scheduled_hook(WPVIVID_MAIN_SCHEDULE_EVENT);
$timestamp = wp_next_scheduled(WPVIVID_MAIN_SCHEDULE_EVENT);
wp_unschedule_event($timestamp,WPVIVID_MAIN_SCHEDULE_EVENT);
}
}
public static function clear_monitor_schedule($id)
{
$timestamp =wp_next_scheduled(WPVIVID_TASK_MONITOR_EVENT,array($id));
if($timestamp!==false)
{
wp_unschedule_event($timestamp,WPVIVID_TASK_MONITOR_EVENT,array($id));
}
}
public static function get_next_resume_time($id)
{
$timestamp=wp_next_scheduled(WPVIVID_RESUME_SCHEDULE_EVENT,array($id));
if($timestamp!==false)
{
return $timestamp-time();
}
else
{
return false;
}
}
}
includes/class-wpvivid-remote-collection.php 0000644 00000012157 15132770567 0015323 0 ustar 00 <?php
/**
* Created by PhpStorm.
* User: alienware`x
* Date: 2019/1/22
* Time: 9:19
*/
require_once WPVIVID_PLUGIN_DIR .'/includes/customclass/class-wpvivid-remote-default.php';
require_once WPVIVID_PLUGIN_DIR .'/includes/customclass/class-wpvivid-ftpclass.php';
require_once WPVIVID_PLUGIN_DIR. '/includes/customclass/class-wpvivid-sftpclass.php';
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-amazons3-plus.php';
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-google-drive.php';
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-dropbox.php';
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-one-drive.php';
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-s3compat.php';
class WPvivid_Remote_collection
{
private $remote_collection=array();
public function __construct()
{
add_filter('wpvivid_remote_register', array($this, 'init_remotes'),10);
$this->remote_collection=apply_filters('wpvivid_remote_register',$this->remote_collection);
$this->load_hooks();
}
public function get_remote($remote)
{
if(is_array($remote)&&array_key_exists('type',$remote)&&array_key_exists($remote['type'],$this->remote_collection))
{
$class_name =$this->remote_collection[$remote['type']];
if(class_exists($class_name))
{
$object = new $class_name($remote);
return $object;
}
}
$object = new $this ->remote_collection['default']();
return $object;
}
public function add_remote($remote_option)
{
$remote=$this->get_remote($remote_option);
$ret=$remote->sanitize_options();
if($ret['result']=='success')
{
$remote_option=$ret['options'];
$ret=$remote->test_connect();
if($ret['result']=='success')
{
$ret=array();
$default=$remote_option['default'];
$id=WPvivid_Setting::add_remote_options($remote_option);
if($default==1)
{
$remote_ids[]=$id;
$remote_ids=apply_filters('wpvivid_before_add_user_history',$remote_ids);
WPvivid_Setting::update_user_history('remote_selected',$remote_ids);
$schedule_data = WPvivid_Setting::get_option('wpvivid_schedule_setting');
if(!empty($schedule_data['enable'])) {
if ($schedule_data['enable'] == 1) {
$schedule_data['backup']['local'] = 0;
$schedule_data['backup']['remote'] = 1;
}
WPvivid_Setting::update_option('wpvivid_schedule_setting', $schedule_data);
}
}
$ret['result']=WPVIVID_SUCCESS;
}
else {
$id = uniqid('wpvivid-');
$log_file_name = $id . '_add_remote';
$log = new WPvivid_Log();
$log->CreateLogFile($log_file_name, 'no_folder', 'Add Remote Test Connection');
$log->WriteLog('Remote Type: '.$remote_option['type'], 'notice');
if(isset($ret['error'])) {
$log->WriteLog($ret['error'], 'notice');
}
$log->CloseFile();
WPvivid_error_log::create_error_log($log->log_file);
}
}
return $ret;
}
public function update_remote($id,$remote_option)
{
$remote=$this->get_remote($remote_option);
$old_remote=WPvivid_Setting::get_remote_option($id);
$ret=$remote->sanitize_options($old_remote['name']);
if($ret['result']=='success')
{
$remote_option=$ret['options'];
$ret=$remote->test_connect();
if($ret['result']=='success')
{
$ret=array();
WPvivid_Setting::update_remote_option($id,$remote_option);
$ret['result']=WPVIVID_SUCCESS;
}
}
return $ret;
}
public function init_remotes($remote_collection)
{
$remote_collection['default'] = 'WPvivid_Remote_Defult';
$remote_collection['sftp']='WPvivid_SFTPClass';
$remote_collection['ftp']='WPvivid_FTPClass';
$remote_collection['amazons3']='WPvivid_AMAZONS3Class';
$remote_collection[WPVIVID_REMOTE_GOOGLEDRIVE] = 'Wpvivid_Google_drive';
$remote_collection['dropbox']='WPvivid_Dropbox';
$remote_collection[WPVIVID_REMOTE_ONEDRIVE] = 'Wpvivid_one_drive';
$remote_collection[WPVIVID_REMOTE_S3COMPAT] = 'Wpvivid_S3Compat';
$remote_collection[WPVIVID_REMOTE_SEND_TO_SITE] = 'WPvivid_Send_to_site';
return $remote_collection;
}
public function load_hooks()
{
foreach ($this->remote_collection as $class_name)
{
$object = new $class_name();
}
}
} includes/class-wpvivid-mysqldump-method.php 0000644 00000311513 15132770567 0015206 0 ustar 00 <?php
use PDO as PDO;
use PDOException as PDOException;
/**
* Enum with all available compression methods
*
*/
abstract class WPvividCompressMethod
{
public static $enums = array(
"None",
"Gzip",
"Bzip2"
);
/**
* @param string $c
* @return boolean
*/
public static function isValid($c)
{
return in_array($c, self::$enums);
}
}
abstract class WPvividCompressManagerFactory
{
/**
* @param string $c
* @return WPvividCompressBzip2|WPvividCompressGzip|WPvividCompressNone
*/
public static function create($c)
{
$c = ucfirst(strtolower($c));
if (! WPvividCompressMethod::isValid($c)) {
throw new Exception("Compression method (".esc_html($c).") is not defined yet");
}
$method = __NAMESPACE__ . "\\" . "WPvividCompress" . $c;
return new $method;
}
}
class WPvividCompressBzip2 extends WPvividCompressManagerFactory
{
private $fileHandler = null;
public function __construct()
{
if (! function_exists("bzopen")) {
throw new Exception("Compression is enabled, but bzip2 lib is not installed or configured properly");
}
}
/**
* @param string $filename
*/
public function open($filename)
{
$this->fileHandler = bzopen($filename, "w");
if (false === $this->fileHandler) {
throw new Exception("Output file is not writable");
}
return true;
}
public function write($str)
{
if (false === ($bytesWritten = bzwrite($this->fileHandler, $str))) {
throw new Exception("Writting to file failed! Probably, there is no more free space left?");
}
return $bytesWritten;
}
public function close()
{
return bzclose($this->fileHandler);
}
}
class WPvividCompressGzip extends WPvividCompressManagerFactory
{
private $fileHandler = null;
public function __construct()
{
if (! function_exists("gzopen")) {
throw new Exception("Compression is enabled, but gzip lib is not installed or configured properly");
}
}
/**
* @param string $filename
*/
public function open($filename)
{
$this->fileHandler = gzopen($filename, "wb");
if (false === $this->fileHandler) {
throw new Exception("Output file is not writable");
}
return true;
}
public function write($str)
{
if (false === ($bytesWritten = gzwrite($this->fileHandler, $str))) {
throw new Exception("Writting to file failed! Probably, there is no more free space left?");
}
return $bytesWritten;
}
public function close()
{
return gzclose($this->fileHandler);
}
}
class WPvividCompressNone extends WPvividCompressManagerFactory
{
private $fileHandler = null;
/**
* @param string $filename
*/
public function open($filename)
{
$this->fileHandler = fopen($filename, "wb");
if (false === $this->fileHandler) {
throw new Exception("Output file is not writable");
}
return true;
}
public function write($str)
{
if (false === ($bytesWritten = fwrite($this->fileHandler, $str))) {
throw new Exception("Writting to file failed! Probably, there is no more free space left?");
}
return $bytesWritten;
}
public function close()
{
return fclose($this->fileHandler);
}
}
/**
* Enum with all available TypeAdapter implementations
*
*/
abstract class WPvividTypeAdapter
{
public static $enums = array(
"Sqlite",
"Mysql",
"Wpdb"
);
/**
* @param string $c
* @return boolean
*/
public static function isValid($c)
{
return in_array($c, self::$enums);
}
}
if(!class_exists('TypeAdapterFactory'))
{
abstract class TypeAdapterFactory
{
/**
* @param string $c Type of database factory to create (Mysql, Sqlite,...)
* @param PDO $dbHandler
*/
public static function create($c, $dbHandler = null)
{
$c = ucfirst(strtolower($c));
if (! WPvividTypeAdapter::isValid($c)) {
if($c === 'Mysql'){
$c = 'PDO_MySQL';
}
throw new Exception("Database type support for (".esc_html($c).") not yet available");
}
$method = __NAMESPACE__ . "\\" . "WPvividTypeAdapter" . $c;
return new $method($dbHandler);
}
/**
* function databases Add sql to create and use database
* @todo make it do something with sqlite
*/
public function databases()
{
return "";
}
public function show_create_table($tableName)
{
return "SELECT tbl_name as 'Table', sql as 'Create Table' " .
"FROM sqlite_master " .
"WHERE type='table' AND tbl_name='$tableName'";
}
/**
* function create_table Get table creation code from database
* @todo make it do something with sqlite
*/
public function create_table($row, $dumpSettings)
{
return "";
}
public function show_create_view($viewName)
{
return "SELECT tbl_name as 'View', sql as 'Create View' " .
"FROM sqlite_master " .
"WHERE type='view' AND tbl_name='$viewName'";
}
/**
* function create_view Get view creation code from database
* @todo make it do something with sqlite
*/
public function create_view($row)
{
return "";
}
/**
* function show_create_trigger Get trigger creation code from database
* @todo make it do something with sqlite
*/
public function show_create_trigger($triggerName)
{
return "";
}
/**
* function create_trigger Modify trigger code, add delimiters, etc
* @todo make it do something with sqlite
*/
public function create_trigger($triggerName)
{
return "";
}
/**
* function create_procedure Modify procedure code, add delimiters, etc
* @todo make it do something with sqlite
*/
public function create_procedure($procedureName, $dumpSettings)
{
return "";
}
public function show_tables()
{
return "SELECT tbl_name FROM sqlite_master WHERE type='table'";
}
public function show_views()
{
return "SELECT tbl_name FROM sqlite_master WHERE type='view'";
}
public function show_triggers()
{
return "SELECT name FROM sqlite_master WHERE type='trigger'";
}
public function show_columns()
{
if (func_num_args() != 1) {
return "";
}
$args = func_get_args();
return "pragma table_info({$args[0]})";
}
public function show_procedures()
{
return "";
}
public function show_events()
{
return "";
}
public function setup_transaction()
{
return "";
}
public function start_transaction()
{
return "BEGIN EXCLUSIVE";
}
public function commit_transaction()
{
return "COMMIT";
}
public function lock_table()
{
return "";
}
public function unlock_table()
{
return "";
}
public function start_add_lock_table()
{
return PHP_EOL;
}
public function end_add_lock_table()
{
return PHP_EOL;
}
public function start_add_disable_keys()
{
return PHP_EOL;
}
public function end_add_disable_keys()
{
return PHP_EOL;
}
public function start_disable_foreign_keys_check()
{
return PHP_EOL;
}
public function end_disable_foreign_keys_check()
{
return PHP_EOL;
}
public function add_drop_database()
{
return PHP_EOL;
}
public function add_drop_trigger()
{
return PHP_EOL;
}
public function drop_table()
{
return PHP_EOL;
}
public function drop_view()
{
return PHP_EOL;
}
/**
* Decode column metadata and fill info structure.
* type, is_numeric and is_blob will always be available.
*
* @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
* @return array
*/
public function parseColumnType($colType)
{
return array();
}
public function backup_parameters()
{
return PHP_EOL;
}
public function restore_parameters()
{
return PHP_EOL;
}
}
class TypeAdapterPgsql extends TypeAdapterFactory
{
}
class TypeAdapterDblib extends TypeAdapterFactory
{
}
class TypeAdapterSqlite extends TypeAdapterFactory
{
}
class TypeAdapterMysql extends TypeAdapterFactory
{
private $dbHandler = null;
private $dsn;
private $user;
private $pass;
private $pdoSettings;
private $reconnect_count;
// Numerical Mysql types
public $mysqlTypes = array(
'numerical' => array(
'bit',
'tinyint',
'smallint',
'mediumint',
'int',
'integer',
'bigint',
'real',
'double',
'float',
'decimal',
'numeric'
),
'blob' => array(
'tinyblob',
'blob',
'mediumblob',
'longblob',
'binary',
'varbinary',
'bit',
'geometry', /* http://bugs.mysql.com/bug.php?id=43544 */
'point',
'linestring',
'polygon',
'multipoint',
'multilinestring',
'multipolygon',
'geometrycollection',
)
);
public function __construct ($dbHandler)
{
$pdoSettingsDefault = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false
);
$this->dbHandler = $dbHandler;
$this->dsn='';
$this->user='';
$this->pass='';
$this->pdoSettings=$pdoSettingsDefault;
$this->reconnect_count=0;
}
public function set_connect_info($dsn,$user,$pass,$pdoSetting)
{
$this->dsn=$dsn;
$this->user=$user;
$this->pass=$pass;
$this->pdoSettings=$pdoSetting;
}
public function connect($host,$dbname,$user,$pass,$init_commands=array())
{
if(empty($host))
{
$host=DB_HOST;
}
$res = explode(':',$host);
$db_host = $res[0];
$db_port = empty($res[1])?'':$res[1];
if(!empty($db_port)) {
$this->dsn='mysql:host=' . $db_host . ';port=' . $db_port . ';dbname=' . $dbname;
}
else{
$this->dsn='mysql:host=' . $db_host . ';dbname=' . $dbname;
}
$this->user=$user;
$this->pass=$pass;
$this->dbHandler = @new PDO(
$this->dsn,
$this->user,
$this->pass,
$this->pdoSettings
);
// Execute init commands once connected
foreach($init_commands as $stmt)
{
$this->dbHandler->exec($stmt);
}
$this->dbHandler->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
}
public function errorInfo()
{
$error=$this->dbHandler->errorInfo();
return $error;
}
public function quote($colValue)
{
return $this->dbHandler->quote($colValue);
}
public function databases()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$databaseName = $args[0];
$resultSet = $this->query("SHOW VARIABLES LIKE 'character_set_database';");
$characterSet = $resultSet->fetchColumn(1);
$resultSet->closeCursor();
$resultSet = $this->query("SHOW VARIABLES LIKE 'collation_database';");
$collationDb = $resultSet->fetchColumn(1);
$resultSet->closeCursor();
$ret = "";
$ret .= "CREATE DATABASE /*!32312 IF NOT EXISTS*/ `{$databaseName}`".
" /*!40100 DEFAULT CHARACTER SET {$characterSet} " .
" COLLATE {$collationDb} */;" . PHP_EOL . PHP_EOL .
"USE `{$databaseName}`;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function show_create_table($tableName)
{
return "SHOW CREATE TABLE `$tableName`";
}
public function show_create_view($viewName)
{
return "SHOW CREATE VIEW `$viewName`";
}
public function show_create_trigger($triggerName)
{
return "SHOW CREATE TRIGGER `$triggerName`";
}
public function show_create_procedure($procedureName)
{
return "SHOW CREATE PROCEDURE `$procedureName`";
}
public function show_create_event($eventName)
{
return "SHOW CREATE EVENT `$eventName`";
}
public function create_table( $row, $dumpSettings )
{
if ( !isset($row['Create Table']) ) {
throw new Exception("Error getting table code, unknown output");
}
//$createTable = str_replace('\'0000-00-00 00:00:00\'','\'1999-01-01 00:00:00\'',$row['Create Table']);
$createTable = $row['Create Table'];
if ( $dumpSettings['reset-auto-increment'] ) {
$match = "/AUTO_INCREMENT=[0-9]+/s";
$replace = "";
$createTable = preg_replace($match, $replace, $createTable);
}
$ret = "/*!40101 SET @saved_cs_client = @@character_set_client */;" . PHP_EOL .
"/*!40101 SET character_set_client = " . $dumpSettings['default-character-set'] . " */;" . PHP_EOL .
$createTable . ";" . PHP_EOL .
"/*!40101 SET character_set_client = @saved_cs_client */;" . PHP_EOL .
PHP_EOL;
return $ret;
}
public function create_view($row)
{
$ret = "";
if (!isset($row['Create View'])) {
throw new Exception("Error getting view structure, unknown output");
}
$triggerStmt = $row['Create View'];
$triggerStmtReplaced1 = str_replace(
"CREATE ALGORITHM",
"/*!50001 CREATE ALGORITHM",
$triggerStmt
);
$triggerStmtReplaced2 = str_replace(
" DEFINER=",
" */" . PHP_EOL . "/*!50013 DEFINER=",
$triggerStmtReplaced1
);
$triggerStmtReplaced3 = str_replace(
" VIEW ",
" */" . PHP_EOL . "/*!50001 VIEW ",
$triggerStmtReplaced2
);
if (false === $triggerStmtReplaced1 ||
false === $triggerStmtReplaced2 ||
false === $triggerStmtReplaced3) {
$triggerStmtReplaced = $triggerStmt;
} else {
$triggerStmtReplaced = $triggerStmtReplaced3 . " */;";
}
$ret .= $triggerStmtReplaced . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_trigger($row)
{
$ret = "";
if (!isset($row['SQL Original Statement'])) {
throw new Exception("Error getting trigger code, unknown output");
}
$triggerStmt = $row['SQL Original Statement'];
$triggerStmtReplaced = str_replace(
"CREATE DEFINER",
"/*!50003 CREATE*/ /*!50017 DEFINER",
$triggerStmt
);
$triggerStmtReplaced = str_replace(
" TRIGGER",
"*/ /*!50003 TRIGGER",
$triggerStmtReplaced
);
if ( false === $triggerStmtReplaced ) {
$triggerStmtReplaced = $triggerStmt . " /* ";
}
$ret .= "DELIMITER ;;" . PHP_EOL .
$triggerStmtReplaced . " */ ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_procedure($row, $dumpSettings)
{
$ret = "";
if (!isset($row['Create Procedure'])) {
throw new Exception("Error getting procedure code, unknown output. " .
"Please check 'https://bugs.mysql.com/bug.php?id=14564'");
}
$procedureStmt = $row['Create Procedure'];
$ret .= "/*!50003 DROP PROCEDURE IF EXISTS `" .
$row['Procedure'] . "` */;" . PHP_EOL .
"/*!40101 SET @saved_cs_client = @@character_set_client */;" . PHP_EOL .
"/*!40101 SET character_set_client = " . $dumpSettings['default-character-set'] . " */;" . PHP_EOL .
"DELIMITER ;;" . PHP_EOL .
$procedureStmt . " ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL .
"/*!40101 SET character_set_client = @saved_cs_client */;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_event($row)
{
$ret = "";
if ( !isset($row['Create Event']) ) {
throw new Exception("Error getting event code, unknown output. " .
"Please check 'http://stackoverflow.com/questions/10853826/mysql-5-5-create-event-gives-syntax-error'");
}
$eventName = $row['Event'];
$eventStmt = $row['Create Event'];
$sqlMode = $row['sql_mode'];
$eventStmtReplaced = str_replace(
"CREATE DEFINER",
"/*!50106 CREATE*/ /*!50117 DEFINER",
$eventStmt
);
$eventStmtReplaced = str_replace(
" EVENT ",
"*/ /*!50106 EVENT ",
$eventStmtReplaced
);
if ( false === $eventStmtReplaced ) {
$eventStmtReplaced = $eventStmt . " /* ";
}
$ret .= "/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;" . PHP_EOL .
"/*!50106 DROP EVENT IF EXISTS `" . $eventName . "` */;" . PHP_EOL .
"DELIMITER ;;" . PHP_EOL .
"/*!50003 SET @saved_cs_client = @@character_set_client */ ;;" . PHP_EOL .
"/*!50003 SET @saved_cs_results = @@character_set_results */ ;;" . PHP_EOL .
"/*!50003 SET @saved_col_connection = @@collation_connection */ ;;" . PHP_EOL .
"/*!50003 SET character_set_client = utf8 */ ;;" . PHP_EOL .
"/*!50003 SET character_set_results = utf8 */ ;;" . PHP_EOL .
"/*!50003 SET collation_connection = utf8_general_ci */ ;;" . PHP_EOL .
"/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;" . PHP_EOL .
"/*!50003 SET sql_mode = '" . $sqlMode . "' */ ;;" . PHP_EOL .
"/*!50003 SET @saved_time_zone = @@time_zone */ ;;" . PHP_EOL .
"/*!50003 SET time_zone = 'SYSTEM' */ ;;" . PHP_EOL .
$eventStmtReplaced . " */ ;;" . PHP_EOL .
"/*!50003 SET time_zone = @saved_time_zone */ ;;" . PHP_EOL .
"/*!50003 SET sql_mode = @saved_sql_mode */ ;;" . PHP_EOL .
"/*!50003 SET character_set_client = @saved_cs_client */ ;;" . PHP_EOL .
"/*!50003 SET character_set_results = @saved_cs_results */ ;;" . PHP_EOL .
"/*!50003 SET collation_connection = @saved_col_connection */ ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL .
"/*!50106 SET TIME_ZONE= @save_time_zone */ ;" . PHP_EOL . PHP_EOL;
// Commented because we are doing this in restore_parameters()
// "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function show_tables()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT TABLE_NAME AS tbl_name " .
"FROM INFORMATION_SCHEMA.TABLES " .
"WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='{$args[0]}'";
}
public function show_views()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT TABLE_NAME AS tbl_name " .
"FROM INFORMATION_SCHEMA.TABLES " .
"WHERE TABLE_TYPE='VIEW' AND TABLE_SCHEMA='{$args[0]}'";
}
public function show_triggers()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SHOW TRIGGERS FROM `{$args[0]}`;";
}
public function show_columns()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SHOW COLUMNS FROM `{$args[0]}`;";
}
public function show_procedures()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT SPECIFIC_NAME AS procedure_name " .
"FROM INFORMATION_SCHEMA.ROUTINES " .
"WHERE ROUTINE_TYPE='PROCEDURE' AND ROUTINE_SCHEMA='{$args[0]}'";
}
/**
* Get query string to ask for names of events from current database.
*
* @param string Name of database
* @return string
*/
public function show_events()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT EVENT_NAME AS event_name " .
"FROM INFORMATION_SCHEMA.EVENTS " .
"WHERE EVENT_SCHEMA='{$args[0]}'";
}
public function setup_transaction()
{
return "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
}
public function start_transaction()
{
return "START TRANSACTION";
}
public function commit_transaction()
{
return "COMMIT";
}
public function lock_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return $this->dbHandler->exec("LOCK TABLES `{$args[0]}` READ LOCAL");
}
public function unlock_table()
{
return $this->dbHandler->exec("UNLOCK TABLES");
}
public function start_add_lock_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "LOCK TABLES `{$args[0]}` WRITE;" . PHP_EOL;
}
public function end_add_lock_table()
{
return "UNLOCK TABLES;" . PHP_EOL;
}
public function start_add_disable_keys()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 ALTER TABLE `{$args[0]}` DISABLE KEYS */;" .
PHP_EOL;
}
public function end_add_disable_keys()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 ALTER TABLE `{$args[0]}` ENABLE KEYS */;" .
PHP_EOL;
}
public function start_disable_autocommit()
{
return "SET autocommit=0;" . PHP_EOL;
}
public function end_disable_autocommit()
{
return "COMMIT;" . PHP_EOL;
}
public function add_drop_database()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 DROP DATABASE IF EXISTS `{$args[0]}`*/;" .
PHP_EOL . PHP_EOL;
}
public function add_drop_trigger()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TRIGGER IF EXISTS `{$args[0]}`;" . PHP_EOL;
}
public function drop_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TABLE IF EXISTS `{$args[0]}`;" . PHP_EOL;
}
public function drop_view()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TABLE IF EXISTS `{$args[0]}`;" . PHP_EOL .
"/*!50001 DROP VIEW IF EXISTS `{$args[0]}`*/;" . PHP_EOL;
}
public function getDatabaseHeader()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "--" . PHP_EOL .
"-- Current Database: `{$args[0]}`" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL;
}
/**
* Decode column metadata and fill info structure.
* type, is_numeric and is_blob will always be available.
*
* @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
* @return array
*/
public function parseColumnType($colType)
{
$colInfo = array();
$colParts = explode(" ", $colType['Type']);
if($fparen = strpos($colParts[0], "("))
{
$colInfo['type'] = substr($colParts[0], 0, $fparen);
$colInfo['length'] = str_replace(")", "", substr($colParts[0], $fparen+1));
$colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : NULL;
}
else
{
$colInfo['type'] = $colParts[0];
}
$colInfo['is_numeric'] = in_array($colInfo['type'], $this->mysqlTypes['numerical']);
$colInfo['is_blob'] = in_array($colInfo['type'], $this->mysqlTypes['blob']);
// for virtual 'Extra' -> "STORED GENERATED"
$colInfo['is_virtual'] = strpos($colType['Extra'], "STORED GENERATED") === false ? false : true;
return $colInfo;
}
public function get_connection_charset($wpdb = null) {
if (null === $wpdb) {
global $wpdb;
}
$charset = (defined('DB_CHARSET') && DB_CHARSET) ? DB_CHARSET : 'utf8mb4';
if (method_exists($wpdb, 'determine_charset')) {
$charset_collate = $wpdb->determine_charset($charset, '');
if (!empty($charset_collate['charset'])) $charset = $charset_collate['charset'];
}
return $charset;
}
public function backup_parameters()
{
global $wpdb;
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$dumpSettings = $args[0];
$ret = "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;" . PHP_EOL .
"/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;" . PHP_EOL .
"/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;" . PHP_EOL .
"/*!40101 SET NAMES " . $this->get_connection_charset($wpdb) . " */;" . PHP_EOL;
if (false === $dumpSettings['skip-tz-utc']) {
$ret .= "/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;" . PHP_EOL .
"/*!40103 SET TIME_ZONE='+00:00' */;" . PHP_EOL;
}
$ret .= "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;" . PHP_EOL .
"/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;" . PHP_EOL .
"/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;" . PHP_EOL .
"/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;" . PHP_EOL .PHP_EOL;
return $ret;
}
public function restore_parameters()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$dumpSettings = $args[0];
$ret = "";
if (false === $dumpSettings['skip-tz-utc']) {
$ret .= "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;" . PHP_EOL;
}
$ret .= "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;" . PHP_EOL .
"/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;" . PHP_EOL .
"/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;" . PHP_EOL .
"/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;" . PHP_EOL .
"/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;" . PHP_EOL .
"/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;" . PHP_EOL .
"/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;" . PHP_EOL . PHP_EOL;
return $ret;
}
/**
* Check number of parameters passed to function, useful when inheriting.
* Raise exception if unexpected.
*
* @param integer $num_args
* @param integer $expected_num_args
* @param string $method_name
*/
private function check_parameters($num_args, $expected_num_args, $method_name)
{
if ( $num_args != $expected_num_args ) {
throw new Exception("Unexpected parameter passed to ".esc_html($method_name));
}
return;
}
public function query($string)
{
$ret= $this->dbHandler->query($string);
if($ret===false)
{
$info=$this->dbHandler->errorInfo();
if($info[1] == 2006)
{
if($this->reconnect_count>3)
{
throw new Exception("MySQL server has gone away. Too many reconnect.");
}
$this->reconnect();
$this->reconnect_count++;
$ret= $this->dbHandler->query($string);
if($ret!==false)
{
$ret->setFetchMode(PDO::FETCH_ASSOC);
}
}
}
else
{
$ret->setFetchMode(PDO::FETCH_ASSOC);
}
return $ret;
}
public function exec($string)
{
$ret=$this->dbHandler->exec($string);
if($ret===false)
{
$info=$this->dbHandler->errorInfo();
if($info[1] == 2006)
{
if($this->reconnect_count>3)
{
throw new Exception("MySQL server has gone away. Too many reconnect.");
}
$this->reconnect();
$this->reconnect_count++;
$ret= $this->dbHandler->exec($string);
}
}
return $ret;
}
public function reconnect()
{
$this->dbHandler = @new PDO(
$this->dsn,
$this->user,
$this->pass,
$this->pdoSettings
);
}
public function closeCursor($resultSet)
{
$resultSet->closeCursor();
}
}
class TypeAdapterWpdb extends TypeAdapterFactory
{
private $dbHandler = null;
// Numerical Mysql types
public $mysqlTypes = array(
'numerical' => array(
'bit',
'tinyint',
'smallint',
'mediumint',
'int',
'integer',
'bigint',
'real',
'double',
'float',
'decimal',
'numeric'
),
'blob' => array(
'tinyblob',
'blob',
'mediumblob',
'longblob',
'binary',
'varbinary',
'bit',
'geometry', /* http://bugs.mysql.com/bug.php?id=43544 */
'point',
'linestring',
'polygon',
'multipoint',
'multilinestring',
'multipolygon',
'geometrycollection',
)
);
public function __construct ($dbHandler)
{
$this->dbHandler = $dbHandler;
}
public function connect($host,$dbname,$user,$pass,$init_commands=array())
{
global $wpdb;
$this->dbHandler=$wpdb;
}
public function databases()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$databaseName = $args[0];
$resultSet = $this->query("SHOW VARIABLES LIKE 'character_set_database';");
$characterSet = $resultSet->fetchColumn(1);
$resultSet->closeCursor();
$resultSet = $this->query("SHOW VARIABLES LIKE 'collation_database';");
$collationDb = $resultSet->fetchColumn(1);
$resultSet->closeCursor();
$ret = "";
$ret .= "CREATE DATABASE /*!32312 IF NOT EXISTS*/ `{$databaseName}`".
" /*!40100 DEFAULT CHARACTER SET {$characterSet} " .
" COLLATE {$collationDb} */;" . PHP_EOL . PHP_EOL .
"USE `{$databaseName}`;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function show_create_table($tableName)
{
return "SHOW CREATE TABLE `$tableName`";
}
public function show_create_view($viewName)
{
return "SHOW CREATE VIEW `$viewName`";
}
public function show_create_trigger($triggerName)
{
return "SHOW CREATE TRIGGER `$triggerName`";
}
public function show_create_procedure($procedureName)
{
return "SHOW CREATE PROCEDURE `$procedureName`";
}
public function show_create_event($eventName)
{
return "SHOW CREATE EVENT `$eventName`";
}
public function create_table( $row, $dumpSettings )
{
if ( !isset($row['Create Table']) ) {
throw new Exception("Error getting table code, unknown output");
}
//$createTable = str_replace('\'0000-00-00 00:00:00\'','\'1999-01-01 00:00:00\'',$row['Create Table']);
$createTable = $row['Create Table'];
if ( $dumpSettings['reset-auto-increment'] ) {
$match = "/AUTO_INCREMENT=[0-9]+/s";
$replace = "";
$createTable = preg_replace($match, $replace, $createTable);
}
$ret = "/*!40101 SET @saved_cs_client = @@character_set_client */;" . PHP_EOL .
"/*!40101 SET character_set_client = " . $dumpSettings['default-character-set'] . " */;" . PHP_EOL .
$createTable . ";" . PHP_EOL .
"/*!40101 SET character_set_client = @saved_cs_client */;" . PHP_EOL .
PHP_EOL;
return $ret;
}
public function create_view($row)
{
$ret = "";
if (!isset($row['Create View'])) {
throw new Exception("Error getting view structure, unknown output");
}
$triggerStmt = $row['Create View'];
$triggerStmtReplaced1 = str_replace(
"CREATE ALGORITHM",
"/*!50001 CREATE ALGORITHM",
$triggerStmt
);
$triggerStmtReplaced2 = str_replace(
" DEFINER=",
" */" . PHP_EOL . "/*!50013 DEFINER=",
$triggerStmtReplaced1
);
$triggerStmtReplaced3 = str_replace(
" VIEW ",
" */" . PHP_EOL . "/*!50001 VIEW ",
$triggerStmtReplaced2
);
if (false === $triggerStmtReplaced1 ||
false === $triggerStmtReplaced2 ||
false === $triggerStmtReplaced3) {
$triggerStmtReplaced = $triggerStmt;
} else {
$triggerStmtReplaced = $triggerStmtReplaced3 . " */;";
}
$ret .= $triggerStmtReplaced . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_trigger($row)
{
$ret = "";
if (!isset($row['SQL Original Statement'])) {
throw new Exception("Error getting trigger code, unknown output");
}
$triggerStmt = $row['SQL Original Statement'];
$triggerStmtReplaced = str_replace(
"CREATE DEFINER",
"/*!50003 CREATE*/ /*!50017 DEFINER",
$triggerStmt
);
$triggerStmtReplaced = str_replace(
" TRIGGER",
"*/ /*!50003 TRIGGER",
$triggerStmtReplaced
);
if ( false === $triggerStmtReplaced ) {
$triggerStmtReplaced = $triggerStmt . " /* ";
}
$ret .= "DELIMITER ;;" . PHP_EOL .
$triggerStmtReplaced . " */ ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_procedure($row, $dumpSettings)
{
$ret = "";
if (!isset($row['Create Procedure'])) {
throw new Exception("Error getting procedure code, unknown output. " .
"Please check 'https://bugs.mysql.com/bug.php?id=14564'");
}
$procedureStmt = $row['Create Procedure'];
$ret .= "/*!50003 DROP PROCEDURE IF EXISTS `" .
$row['Procedure'] . "` */;" . PHP_EOL .
"/*!40101 SET @saved_cs_client = @@character_set_client */;" . PHP_EOL .
"/*!40101 SET character_set_client = " . $dumpSettings['default-character-set'] . " */;" . PHP_EOL .
"DELIMITER ;;" . PHP_EOL .
$procedureStmt . " ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL .
"/*!40101 SET character_set_client = @saved_cs_client */;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_event($row)
{
$ret = "";
if ( !isset($row['Create Event']) ) {
throw new Exception("Error getting event code, unknown output. " .
"Please check 'http://stackoverflow.com/questions/10853826/mysql-5-5-create-event-gives-syntax-error'");
}
$eventName = $row['Event'];
$eventStmt = $row['Create Event'];
$sqlMode = $row['sql_mode'];
$eventStmtReplaced = str_replace(
"CREATE DEFINER",
"/*!50106 CREATE*/ /*!50117 DEFINER",
$eventStmt
);
$eventStmtReplaced = str_replace(
" EVENT ",
"*/ /*!50106 EVENT ",
$eventStmtReplaced
);
if ( false === $eventStmtReplaced ) {
$eventStmtReplaced = $eventStmt . " /* ";
}
$ret .= "/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;" . PHP_EOL .
"/*!50106 DROP EVENT IF EXISTS `" . $eventName . "` */;" . PHP_EOL .
"DELIMITER ;;" . PHP_EOL .
"/*!50003 SET @saved_cs_client = @@character_set_client */ ;;" . PHP_EOL .
"/*!50003 SET @saved_cs_results = @@character_set_results */ ;;" . PHP_EOL .
"/*!50003 SET @saved_col_connection = @@collation_connection */ ;;" . PHP_EOL .
"/*!50003 SET character_set_client = utf8 */ ;;" . PHP_EOL .
"/*!50003 SET character_set_results = utf8 */ ;;" . PHP_EOL .
"/*!50003 SET collation_connection = utf8_general_ci */ ;;" . PHP_EOL .
"/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;" . PHP_EOL .
"/*!50003 SET sql_mode = '" . $sqlMode . "' */ ;;" . PHP_EOL .
"/*!50003 SET @saved_time_zone = @@time_zone */ ;;" . PHP_EOL .
"/*!50003 SET time_zone = 'SYSTEM' */ ;;" . PHP_EOL .
$eventStmtReplaced . " */ ;;" . PHP_EOL .
"/*!50003 SET time_zone = @saved_time_zone */ ;;" . PHP_EOL .
"/*!50003 SET sql_mode = @saved_sql_mode */ ;;" . PHP_EOL .
"/*!50003 SET character_set_client = @saved_cs_client */ ;;" . PHP_EOL .
"/*!50003 SET character_set_results = @saved_cs_results */ ;;" . PHP_EOL .
"/*!50003 SET collation_connection = @saved_col_connection */ ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL .
"/*!50106 SET TIME_ZONE= @save_time_zone */ ;" . PHP_EOL . PHP_EOL;
// Commented because we are doing this in restore_parameters()
// "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function show_tables()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT TABLE_NAME AS tbl_name " .
"FROM INFORMATION_SCHEMA.TABLES " .
"WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='{$args[0]}'";
}
public function show_views()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT TABLE_NAME AS tbl_name " .
"FROM INFORMATION_SCHEMA.TABLES " .
"WHERE TABLE_TYPE='VIEW' AND TABLE_SCHEMA='{$args[0]}'";
}
public function show_triggers()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SHOW TRIGGERS FROM `{$args[0]}`;";
}
public function show_columns()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SHOW COLUMNS FROM `{$args[0]}`;";
}
public function show_procedures()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT SPECIFIC_NAME AS procedure_name " .
"FROM INFORMATION_SCHEMA.ROUTINES " .
"WHERE ROUTINE_TYPE='PROCEDURE' AND ROUTINE_SCHEMA='{$args[0]}'";
}
/**
* Get query string to ask for names of events from current database.
*
* @param string Name of database
* @return string
*/
public function show_events()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT EVENT_NAME AS event_name " .
"FROM INFORMATION_SCHEMA.EVENTS " .
"WHERE EVENT_SCHEMA='{$args[0]}'";
}
public function setup_transaction()
{
return "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
}
public function start_transaction()
{
return "START TRANSACTION";
}
public function commit_transaction()
{
return "COMMIT";
}
public function lock_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return $this->dbHandler->get_results("LOCK TABLES `{$args[0]}` READ LOCAL",ARRAY_A);
}
public function unlock_table()
{
return $this->dbHandler->get_results("UNLOCK TABLES",ARRAY_A);
}
public function start_add_lock_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "LOCK TABLES `{$args[0]}` WRITE;" . PHP_EOL;
}
public function end_add_lock_table()
{
return "UNLOCK TABLES;" . PHP_EOL;
}
public function start_add_disable_keys()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 ALTER TABLE `{$args[0]}` DISABLE KEYS */;" .
PHP_EOL;
}
public function end_add_disable_keys()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 ALTER TABLE `{$args[0]}` ENABLE KEYS */;" .
PHP_EOL;
}
public function start_disable_autocommit()
{
return "SET autocommit=0;" . PHP_EOL;
}
public function end_disable_autocommit()
{
return "COMMIT;" . PHP_EOL;
}
public function add_drop_database()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 DROP DATABASE IF EXISTS `{$args[0]}`*/;" .
PHP_EOL . PHP_EOL;
}
public function add_drop_trigger()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TRIGGER IF EXISTS `{$args[0]}`;" . PHP_EOL;
}
public function drop_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TABLE IF EXISTS `{$args[0]}`;" . PHP_EOL;
}
public function drop_view()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TABLE IF EXISTS `{$args[0]}`;" . PHP_EOL .
"/*!50001 DROP VIEW IF EXISTS `{$args[0]}`*/;" . PHP_EOL;
}
public function getDatabaseHeader()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "--" . PHP_EOL .
"-- Current Database: `{$args[0]}`" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL;
}
/**
* Decode column metadata and fill info structure.
* type, is_numeric and is_blob will always be available.
*
* @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
* @return array
*/
public function parseColumnType($colType)
{
$colInfo = array();
$colParts = explode(" ", $colType['Type']);
if($fparen = strpos($colParts[0], "("))
{
$colInfo['type'] = substr($colParts[0], 0, $fparen);
$colInfo['length'] = str_replace(")", "", substr($colParts[0], $fparen+1));
$colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : NULL;
}
else
{
$colInfo['type'] = $colParts[0];
}
$colInfo['is_numeric'] = in_array($colInfo['type'], $this->mysqlTypes['numerical']);
$colInfo['is_blob'] = in_array($colInfo['type'], $this->mysqlTypes['blob']);
// for virtual 'Extra' -> "STORED GENERATED"
$colInfo['is_virtual'] = strpos($colType['Extra'], "STORED GENERATED") === false ? false : true;
return $colInfo;
}
public function get_connection_charset($wpdb = null) {
if (null === $wpdb) {
global $wpdb;
}
$charset = (defined('DB_CHARSET') && DB_CHARSET) ? DB_CHARSET : 'utf8mb4';
if (method_exists($wpdb, 'determine_charset')) {
$charset_collate = $wpdb->determine_charset($charset, '');
if (!empty($charset_collate['charset'])) $charset = $charset_collate['charset'];
}
return $charset;
}
public function backup_parameters()
{
global $wpdb;
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$dumpSettings = $args[0];
$ret = "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;" . PHP_EOL .
"/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;" . PHP_EOL .
"/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;" . PHP_EOL .
"/*!40101 SET NAMES " . $this->get_connection_charset($wpdb) . " */;" . PHP_EOL;
if (false === $dumpSettings['skip-tz-utc']) {
$ret .= "/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;" . PHP_EOL .
"/*!40103 SET TIME_ZONE='+00:00' */;" . PHP_EOL;
}
$ret .= "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;" . PHP_EOL .
"/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;" . PHP_EOL .
"/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;" . PHP_EOL .
"/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;" . PHP_EOL .PHP_EOL;
return $ret;
}
public function restore_parameters()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$dumpSettings = $args[0];
$ret = "";
if (false === $dumpSettings['skip-tz-utc']) {
$ret .= "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;" . PHP_EOL;
}
$ret .= "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;" . PHP_EOL .
"/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;" . PHP_EOL .
"/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;" . PHP_EOL .
"/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;" . PHP_EOL .
"/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;" . PHP_EOL .
"/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;" . PHP_EOL .
"/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;" . PHP_EOL . PHP_EOL;
return $ret;
}
/**
* Check number of parameters passed to function, useful when inheriting.
* Raise exception if unexpected.
*
* @param integer $num_args
* @param integer $expected_num_args
* @param string $method_name
*/
private function check_parameters($num_args, $expected_num_args, $method_name)
{
if ( $num_args != $expected_num_args ) {
throw new Exception("Unexpected parameter passed to ".esc_html($method_name));
}
return;
}
public function query($string)
{
return $this->dbHandler->get_results($string, ARRAY_A);
}
public function exec($string)
{
return $this->dbHandler->get_results($string, ARRAY_A);
}
public function quote($value)
{
$search = array("\x00", "\x0a", "\x0d", "\x1a");
$replace = array('\0', '\n', '\r', '\Z');
$value=str_replace('\\', '\\\\', $value);
$value=str_replace('\'', '\\\'', $value);
$value= "'" . str_replace($search, $replace, $value) . "'";
return $value;
}
public function closeCursor($resultSet)
{
$this->dbHandler->flush();
}
}
}
/**
* TypeAdapter Factory
*
*/
abstract class WPvividTypeAdapterFactory
{
/**
* @param string $c Type of database factory to create (Mysql, Sqlite,...)
* @param PDO $dbHandler
*/
public static function create($c, $dbHandler = null)
{
$c = ucfirst(strtolower($c));
if (! WPvividTypeAdapter::isValid($c)) {
if($c === 'Mysql'){
$c = 'PDO_MySQL';
}
throw new Exception("Database type support for (".esc_html($c).") not yet available");
}
$method = __NAMESPACE__ . "\\" . "WPvividTypeAdapter" . $c;
return new $method($dbHandler);
}
/**
* function databases Add sql to create and use database
* @todo make it do something with sqlite
*/
public function databases()
{
return "";
}
public function show_create_table($tableName)
{
return "SELECT tbl_name as 'Table', sql as 'Create Table' " .
"FROM sqlite_master " .
"WHERE type='table' AND tbl_name='$tableName'";
}
/**
* function create_table Get table creation code from database
* @todo make it do something with sqlite
*/
public function create_table($row, $dumpSettings)
{
return "";
}
public function show_create_view($viewName)
{
return "SELECT tbl_name as 'View', sql as 'Create View' " .
"FROM sqlite_master " .
"WHERE type='view' AND tbl_name='$viewName'";
}
/**
* function create_view Get view creation code from database
* @todo make it do something with sqlite
*/
public function create_view($row)
{
return "";
}
/**
* function show_create_trigger Get trigger creation code from database
* @todo make it do something with sqlite
*/
public function show_create_trigger($triggerName)
{
return "";
}
/**
* function create_trigger Modify trigger code, add delimiters, etc
* @todo make it do something with sqlite
*/
public function create_trigger($triggerName)
{
return "";
}
/**
* function create_procedure Modify procedure code, add delimiters, etc
* @todo make it do something with sqlite
*/
public function create_procedure($procedureName, $dumpSettings)
{
return "";
}
public function show_tables()
{
return "SELECT tbl_name FROM sqlite_master WHERE type='table'";
}
public function show_views()
{
return "SELECT tbl_name FROM sqlite_master WHERE type='view'";
}
public function show_triggers()
{
return "SELECT name FROM sqlite_master WHERE type='trigger'";
}
public function show_columns()
{
if (func_num_args() != 1) {
return "";
}
$args = func_get_args();
return "pragma table_info({$args[0]})";
}
public function show_procedures()
{
return "";
}
public function show_events()
{
return "";
}
public function setup_transaction()
{
return "";
}
public function start_transaction()
{
return "BEGIN EXCLUSIVE";
}
public function commit_transaction()
{
return "COMMIT";
}
public function lock_table()
{
return "";
}
public function unlock_table()
{
return "";
}
public function start_add_lock_table()
{
return PHP_EOL;
}
public function end_add_lock_table()
{
return PHP_EOL;
}
public function start_add_disable_keys()
{
return PHP_EOL;
}
public function end_add_disable_keys()
{
return PHP_EOL;
}
public function start_disable_foreign_keys_check()
{
return PHP_EOL;
}
public function end_disable_foreign_keys_check()
{
return PHP_EOL;
}
public function add_drop_database()
{
return PHP_EOL;
}
public function add_drop_trigger()
{
return PHP_EOL;
}
public function drop_table()
{
return PHP_EOL;
}
public function drop_view()
{
return PHP_EOL;
}
/**
* Decode column metadata and fill info structure.
* type, is_numeric and is_blob will always be available.
*
* @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
* @return array
*/
public function parseColumnType($colType)
{
return array();
}
public function backup_parameters()
{
return PHP_EOL;
}
public function restore_parameters()
{
return PHP_EOL;
}
}
class WPvividTypeAdapterPgsql extends WPvividTypeAdapterFactory
{
}
class WPvividTypeAdapterDblib extends WPvividTypeAdapterFactory
{
}
class WPvividTypeAdapterSqlite extends WPvividTypeAdapterFactory
{
}
class WPvividTypeAdapterMysql extends WPvividTypeAdapterFactory
{
private $dbHandler = null;
private $dsn;
private $user;
private $pass;
private $pdoSettings;
private $reconnect_count;
// Numerical Mysql types
public $mysqlTypes = array(
'numerical' => array(
'bit',
'tinyint',
'smallint',
'mediumint',
'int',
'integer',
'bigint',
'real',
'double',
'float',
'decimal',
'numeric'
),
'blob' => array(
'tinyblob',
'blob',
'mediumblob',
'longblob',
'binary',
'varbinary',
'bit',
'geometry', /* http://bugs.mysql.com/bug.php?id=43544 */
'point',
'linestring',
'polygon',
'multipoint',
'multilinestring',
'multipolygon',
'geometrycollection',
)
);
public function __construct ($dbHandler)
{
$pdoSettingsDefault = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING,
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false
);
$this->dbHandler = $dbHandler;
$this->dsn='';
$this->user='';
$this->pass='';
$this->pdoSettings=$pdoSettingsDefault;
$this->reconnect_count=0;
}
public function set_connect_info($dsn,$user,$pass,$pdoSetting)
{
$this->dsn=$dsn;
$this->user=$user;
$this->pass=$pass;
$this->pdoSettings=$pdoSetting;
}
public function connect($host,$dbname,$user,$pass,$init_commands=array())
{
if(empty($host))
{
$host=DB_HOST;
}
$res = explode(':',$host);
$db_host = $res[0];
$db_port = empty($res[1])?'':$res[1];
if(!empty($db_port)) {
$this->dsn='mysql:host=' . $db_host . ';port=' . $db_port . ';dbname=' . $dbname;
}
else{
$this->dsn='mysql:host=' . $db_host . ';dbname=' . $dbname;
}
$this->user=$user;
$this->pass=$pass;
$this->dbHandler = @new PDO(
$this->dsn,
$this->user,
$this->pass,
$this->pdoSettings
);
// Execute init commands once connected
foreach($init_commands as $stmt)
{
$this->dbHandler->exec($stmt);
}
$this->dbHandler->setAttribute(PDO::ATTR_ORACLE_NULLS, PDO::NULL_NATURAL);
}
public function errorInfo()
{
$error=$this->dbHandler->errorInfo();
return $error;
}
public function quote($colValue)
{
return $this->dbHandler->quote($colValue);
}
public function databases()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$databaseName = $args[0];
$resultSet = $this->query("SHOW VARIABLES LIKE 'character_set_database';");
$characterSet = $resultSet->fetchColumn(1);
$resultSet->closeCursor();
$resultSet = $this->query("SHOW VARIABLES LIKE 'collation_database';");
$collationDb = $resultSet->fetchColumn(1);
$resultSet->closeCursor();
$ret = "";
$ret .= "CREATE DATABASE /*!32312 IF NOT EXISTS*/ `{$databaseName}`".
" /*!40100 DEFAULT CHARACTER SET {$characterSet} " .
" COLLATE {$collationDb} */;" . PHP_EOL . PHP_EOL .
"USE `{$databaseName}`;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function show_create_table($tableName)
{
return "SHOW CREATE TABLE `$tableName`";
}
public function show_create_view($viewName)
{
return "SHOW CREATE VIEW `$viewName`";
}
public function show_create_trigger($triggerName)
{
return "SHOW CREATE TRIGGER `$triggerName`";
}
public function show_create_procedure($procedureName)
{
return "SHOW CREATE PROCEDURE `$procedureName`";
}
public function show_create_event($eventName)
{
return "SHOW CREATE EVENT `$eventName`";
}
public function create_table( $row, $dumpSettings )
{
if ( !isset($row['Create Table']) ) {
throw new Exception("Error getting table code, unknown output");
}
//$createTable = str_replace('\'0000-00-00 00:00:00\'','\'1999-01-01 00:00:00\'',$row['Create Table']);
$createTable = $row['Create Table'];
if ( $dumpSettings['reset-auto-increment'] ) {
$match = "/AUTO_INCREMENT=[0-9]+/s";
$replace = "";
$createTable = preg_replace($match, $replace, $createTable);
}
$ret = "/*!40101 SET @saved_cs_client = @@character_set_client */;" . PHP_EOL .
"/*!40101 SET character_set_client = " . $dumpSettings['default-character-set'] . " */;" . PHP_EOL .
$createTable . ";" . PHP_EOL .
"/*!40101 SET character_set_client = @saved_cs_client */;" . PHP_EOL .
PHP_EOL;
return $ret;
}
public function create_view($row)
{
$ret = "";
if (!isset($row['Create View'])) {
throw new Exception("Error getting view structure, unknown output");
}
$triggerStmt = $row['Create View'];
$triggerStmtReplaced1 = str_replace(
"CREATE ALGORITHM",
"/*!50001 CREATE ALGORITHM",
$triggerStmt
);
$triggerStmtReplaced2 = str_replace(
" DEFINER=",
" */" . PHP_EOL . "/*!50013 DEFINER=",
$triggerStmtReplaced1
);
$triggerStmtReplaced3 = str_replace(
" VIEW ",
" */" . PHP_EOL . "/*!50001 VIEW ",
$triggerStmtReplaced2
);
if (false === $triggerStmtReplaced1 ||
false === $triggerStmtReplaced2 ||
false === $triggerStmtReplaced3) {
$triggerStmtReplaced = $triggerStmt;
} else {
$triggerStmtReplaced = $triggerStmtReplaced3 . " */;";
}
$ret .= $triggerStmtReplaced . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_trigger($row)
{
$ret = "";
if (!isset($row['SQL Original Statement'])) {
throw new Exception("Error getting trigger code, unknown output");
}
$triggerStmt = $row['SQL Original Statement'];
$triggerStmtReplaced = str_replace(
"CREATE DEFINER",
"/*!50003 CREATE*/ /*!50017 DEFINER",
$triggerStmt
);
$triggerStmtReplaced = str_replace(
" TRIGGER",
"*/ /*!50003 TRIGGER",
$triggerStmtReplaced
);
if ( false === $triggerStmtReplaced ) {
$triggerStmtReplaced = $triggerStmt . " /* ";
}
$ret .= "DELIMITER ;;" . PHP_EOL .
$triggerStmtReplaced . " */ ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_procedure($row, $dumpSettings)
{
$ret = "";
if (!isset($row['Create Procedure'])) {
throw new Exception("Error getting procedure code, unknown output. " .
"Please check 'https://bugs.mysql.com/bug.php?id=14564'");
}
$procedureStmt = $row['Create Procedure'];
$ret .= "/*!50003 DROP PROCEDURE IF EXISTS `" .
$row['Procedure'] . "` */;" . PHP_EOL .
"/*!40101 SET @saved_cs_client = @@character_set_client */;" . PHP_EOL .
"/*!40101 SET character_set_client = " . $dumpSettings['default-character-set'] . " */;" . PHP_EOL .
"DELIMITER ;;" . PHP_EOL .
$procedureStmt . " ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL .
"/*!40101 SET character_set_client = @saved_cs_client */;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_event($row)
{
$ret = "";
if ( !isset($row['Create Event']) ) {
throw new Exception("Error getting event code, unknown output. " .
"Please check 'http://stackoverflow.com/questions/10853826/mysql-5-5-create-event-gives-syntax-error'");
}
$eventName = $row['Event'];
$eventStmt = $row['Create Event'];
$sqlMode = $row['sql_mode'];
$eventStmtReplaced = str_replace(
"CREATE DEFINER",
"/*!50106 CREATE*/ /*!50117 DEFINER",
$eventStmt
);
$eventStmtReplaced = str_replace(
" EVENT ",
"*/ /*!50106 EVENT ",
$eventStmtReplaced
);
if ( false === $eventStmtReplaced ) {
$eventStmtReplaced = $eventStmt . " /* ";
}
$ret .= "/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;" . PHP_EOL .
"/*!50106 DROP EVENT IF EXISTS `" . $eventName . "` */;" . PHP_EOL .
"DELIMITER ;;" . PHP_EOL .
"/*!50003 SET @saved_cs_client = @@character_set_client */ ;;" . PHP_EOL .
"/*!50003 SET @saved_cs_results = @@character_set_results */ ;;" . PHP_EOL .
"/*!50003 SET @saved_col_connection = @@collation_connection */ ;;" . PHP_EOL .
"/*!50003 SET character_set_client = utf8 */ ;;" . PHP_EOL .
"/*!50003 SET character_set_results = utf8 */ ;;" . PHP_EOL .
"/*!50003 SET collation_connection = utf8_general_ci */ ;;" . PHP_EOL .
"/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;" . PHP_EOL .
"/*!50003 SET sql_mode = '" . $sqlMode . "' */ ;;" . PHP_EOL .
"/*!50003 SET @saved_time_zone = @@time_zone */ ;;" . PHP_EOL .
"/*!50003 SET time_zone = 'SYSTEM' */ ;;" . PHP_EOL .
$eventStmtReplaced . " */ ;;" . PHP_EOL .
"/*!50003 SET time_zone = @saved_time_zone */ ;;" . PHP_EOL .
"/*!50003 SET sql_mode = @saved_sql_mode */ ;;" . PHP_EOL .
"/*!50003 SET character_set_client = @saved_cs_client */ ;;" . PHP_EOL .
"/*!50003 SET character_set_results = @saved_cs_results */ ;;" . PHP_EOL .
"/*!50003 SET collation_connection = @saved_col_connection */ ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL .
"/*!50106 SET TIME_ZONE= @save_time_zone */ ;" . PHP_EOL . PHP_EOL;
// Commented because we are doing this in restore_parameters()
// "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function show_tables()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT TABLE_NAME AS tbl_name " .
"FROM INFORMATION_SCHEMA.TABLES " .
"WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='{$args[0]}'";
}
public function show_views()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT TABLE_NAME AS tbl_name " .
"FROM INFORMATION_SCHEMA.TABLES " .
"WHERE TABLE_TYPE='VIEW' AND TABLE_SCHEMA='{$args[0]}'";
}
public function show_triggers()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SHOW TRIGGERS FROM `{$args[0]}`;";
}
public function show_columns()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SHOW COLUMNS FROM `{$args[0]}`;";
}
public function show_procedures()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT SPECIFIC_NAME AS procedure_name " .
"FROM INFORMATION_SCHEMA.ROUTINES " .
"WHERE ROUTINE_TYPE='PROCEDURE' AND ROUTINE_SCHEMA='{$args[0]}'";
}
/**
* Get query string to ask for names of events from current database.
*
* @param string Name of database
* @return string
*/
public function show_events()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT EVENT_NAME AS event_name " .
"FROM INFORMATION_SCHEMA.EVENTS " .
"WHERE EVENT_SCHEMA='{$args[0]}'";
}
public function setup_transaction()
{
return "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
}
public function start_transaction()
{
return "START TRANSACTION";
}
public function commit_transaction()
{
return "COMMIT";
}
public function lock_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return $this->dbHandler->exec("LOCK TABLES `{$args[0]}` READ LOCAL");
}
public function unlock_table()
{
return $this->dbHandler->exec("UNLOCK TABLES");
}
public function start_add_lock_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "LOCK TABLES `{$args[0]}` WRITE;" . PHP_EOL;
}
public function end_add_lock_table()
{
return "UNLOCK TABLES;" . PHP_EOL;
}
public function start_add_disable_keys()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 ALTER TABLE `{$args[0]}` DISABLE KEYS */;" .
PHP_EOL;
}
public function end_add_disable_keys()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 ALTER TABLE `{$args[0]}` ENABLE KEYS */;" .
PHP_EOL;
}
public function start_disable_autocommit()
{
return "SET autocommit=0;" . PHP_EOL;
}
public function end_disable_autocommit()
{
return "COMMIT;" . PHP_EOL;
}
public function add_drop_database()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 DROP DATABASE IF EXISTS `{$args[0]}`*/;" .
PHP_EOL . PHP_EOL;
}
public function add_drop_trigger()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TRIGGER IF EXISTS `{$args[0]}`;" . PHP_EOL;
}
public function drop_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TABLE IF EXISTS `{$args[0]}`;" . PHP_EOL;
}
public function drop_view()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TABLE IF EXISTS `{$args[0]}`;" . PHP_EOL .
"/*!50001 DROP VIEW IF EXISTS `{$args[0]}`*/;" . PHP_EOL;
}
public function getDatabaseHeader()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "--" . PHP_EOL .
"-- Current Database: `{$args[0]}`" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL;
}
/**
* Decode column metadata and fill info structure.
* type, is_numeric and is_blob will always be available.
*
* @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
* @return array
*/
public function parseColumnType($colType)
{
$colInfo = array();
$colParts = explode(" ", $colType['Type']);
if($fparen = strpos($colParts[0], "("))
{
$colInfo['type'] = substr($colParts[0], 0, $fparen);
$colInfo['length'] = str_replace(")", "", substr($colParts[0], $fparen+1));
$colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : NULL;
}
else
{
$colInfo['type'] = $colParts[0];
}
$colInfo['is_numeric'] = in_array($colInfo['type'], $this->mysqlTypes['numerical']);
$colInfo['is_blob'] = in_array($colInfo['type'], $this->mysqlTypes['blob']);
// for virtual 'Extra' -> "STORED GENERATED"
$colInfo['is_virtual'] = strpos($colType['Extra'], "STORED GENERATED") === false ? false : true;
return $colInfo;
}
public function get_connection_charset($wpdb = null) {
if (null === $wpdb) {
global $wpdb;
}
$charset = (defined('DB_CHARSET') && DB_CHARSET) ? DB_CHARSET : 'utf8mb4';
if (method_exists($wpdb, 'determine_charset')) {
$charset_collate = $wpdb->determine_charset($charset, '');
if (!empty($charset_collate['charset'])) $charset = $charset_collate['charset'];
}
return $charset;
}
public function backup_parameters()
{
global $wpdb;
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$dumpSettings = $args[0];
$ret = "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;" . PHP_EOL .
"/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;" . PHP_EOL .
"/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;" . PHP_EOL .
"/*!40101 SET NAMES " . $this->get_connection_charset($wpdb) . " */;" . PHP_EOL;
if (false === $dumpSettings['skip-tz-utc']) {
$ret .= "/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;" . PHP_EOL .
"/*!40103 SET TIME_ZONE='+00:00' */;" . PHP_EOL;
}
$ret .= "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;" . PHP_EOL .
"/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;" . PHP_EOL .
"/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;" . PHP_EOL .
"/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;" . PHP_EOL .PHP_EOL;
return $ret;
}
public function restore_parameters()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$dumpSettings = $args[0];
$ret = "";
if (false === $dumpSettings['skip-tz-utc']) {
$ret .= "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;" . PHP_EOL;
}
$ret .= "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;" . PHP_EOL .
"/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;" . PHP_EOL .
"/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;" . PHP_EOL .
"/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;" . PHP_EOL .
"/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;" . PHP_EOL .
"/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;" . PHP_EOL .
"/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;" . PHP_EOL . PHP_EOL;
return $ret;
}
/**
* Check number of parameters passed to function, useful when inheriting.
* Raise exception if unexpected.
*
* @param integer $num_args
* @param integer $expected_num_args
* @param string $method_name
*/
private function check_parameters($num_args, $expected_num_args, $method_name)
{
if ( $num_args != $expected_num_args ) {
throw new Exception("Unexpected parameter passed to ".esc_html($method_name));
}
return;
}
public function query($string)
{
$ret= $this->dbHandler->query($string);
if($ret===false)
{
$info=$this->dbHandler->errorInfo();
if($info[1] == 2006)
{
if($this->reconnect_count>3)
{
throw new Exception("MySQL server has gone away. Too many reconnect.");
}
$this->reconnect();
$this->reconnect_count++;
$ret= $this->dbHandler->query($string);
if($ret!==false)
{
$ret->setFetchMode(PDO::FETCH_ASSOC);
}
}
}
else
{
$ret->setFetchMode(PDO::FETCH_ASSOC);
}
return $ret;
}
public function exec($string)
{
$ret=$this->dbHandler->exec($string);
if($ret===false)
{
$info=$this->dbHandler->errorInfo();
if($info[1] == 2006)
{
if($this->reconnect_count>3)
{
throw new Exception("MySQL server has gone away. Too many reconnect.");
}
$this->reconnect();
$this->reconnect_count++;
$ret= $this->dbHandler->exec($string);
}
}
return $ret;
}
public function reconnect()
{
$this->dbHandler = @new PDO(
$this->dsn,
$this->user,
$this->pass,
$this->pdoSettings
);
}
public function closeCursor($resultSet)
{
$resultSet->closeCursor();
}
}
class WPvividTypeAdapterWpdb extends WPvividTypeAdapterFactory
{
private $dbHandler = null;
// Numerical Mysql types
public $mysqlTypes = array(
'numerical' => array(
'bit',
'tinyint',
'smallint',
'mediumint',
'int',
'integer',
'bigint',
'real',
'double',
'float',
'decimal',
'numeric'
),
'blob' => array(
'tinyblob',
'blob',
'mediumblob',
'longblob',
'binary',
'varbinary',
'bit',
'geometry', /* http://bugs.mysql.com/bug.php?id=43544 */
'point',
'linestring',
'polygon',
'multipoint',
'multilinestring',
'multipolygon',
'geometrycollection',
)
);
public function __construct ($dbHandler)
{
$this->dbHandler = $dbHandler;
}
public function connect($host,$dbname,$user,$pass,$init_commands=array())
{
global $wpdb;
$this->dbHandler=$wpdb;
}
public function databases()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$databaseName = $args[0];
$resultSet = $this->query("SHOW VARIABLES LIKE 'character_set_database';");
$characterSet = $resultSet->fetchColumn(1);
$resultSet->closeCursor();
$resultSet = $this->query("SHOW VARIABLES LIKE 'collation_database';");
$collationDb = $resultSet->fetchColumn(1);
$resultSet->closeCursor();
$ret = "";
$ret .= "CREATE DATABASE /*!32312 IF NOT EXISTS*/ `{$databaseName}`".
" /*!40100 DEFAULT CHARACTER SET {$characterSet} " .
" COLLATE {$collationDb} */;" . PHP_EOL . PHP_EOL .
"USE `{$databaseName}`;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function show_create_table($tableName)
{
return "SHOW CREATE TABLE `$tableName`";
}
public function show_create_view($viewName)
{
return "SHOW CREATE VIEW `$viewName`";
}
public function show_create_trigger($triggerName)
{
return "SHOW CREATE TRIGGER `$triggerName`";
}
public function show_create_procedure($procedureName)
{
return "SHOW CREATE PROCEDURE `$procedureName`";
}
public function show_create_event($eventName)
{
return "SHOW CREATE EVENT `$eventName`";
}
public function create_table( $row, $dumpSettings )
{
if ( !isset($row['Create Table']) ) {
throw new Exception("Error getting table code, unknown output");
}
//$createTable = str_replace('\'0000-00-00 00:00:00\'','\'1999-01-01 00:00:00\'',$row['Create Table']);
$createTable = $row['Create Table'];
if ( $dumpSettings['reset-auto-increment'] ) {
$match = "/AUTO_INCREMENT=[0-9]+/s";
$replace = "";
$createTable = preg_replace($match, $replace, $createTable);
}
$ret = "/*!40101 SET @saved_cs_client = @@character_set_client */;" . PHP_EOL .
"/*!40101 SET character_set_client = " . $dumpSettings['default-character-set'] . " */;" . PHP_EOL .
$createTable . ";" . PHP_EOL .
"/*!40101 SET character_set_client = @saved_cs_client */;" . PHP_EOL .
PHP_EOL;
return $ret;
}
public function create_view($row)
{
$ret = "";
if (!isset($row['Create View'])) {
throw new Exception("Error getting view structure, unknown output");
}
$triggerStmt = $row['Create View'];
$triggerStmtReplaced1 = str_replace(
"CREATE ALGORITHM",
"/*!50001 CREATE ALGORITHM",
$triggerStmt
);
$triggerStmtReplaced2 = str_replace(
" DEFINER=",
" */" . PHP_EOL . "/*!50013 DEFINER=",
$triggerStmtReplaced1
);
$triggerStmtReplaced3 = str_replace(
" VIEW ",
" */" . PHP_EOL . "/*!50001 VIEW ",
$triggerStmtReplaced2
);
if (false === $triggerStmtReplaced1 ||
false === $triggerStmtReplaced2 ||
false === $triggerStmtReplaced3) {
$triggerStmtReplaced = $triggerStmt;
} else {
$triggerStmtReplaced = $triggerStmtReplaced3 . " */;";
}
$ret .= $triggerStmtReplaced . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_trigger($row)
{
$ret = "";
if (!isset($row['SQL Original Statement'])) {
throw new Exception("Error getting trigger code, unknown output");
}
$triggerStmt = $row['SQL Original Statement'];
$triggerStmtReplaced = str_replace(
"CREATE DEFINER",
"/*!50003 CREATE*/ /*!50017 DEFINER",
$triggerStmt
);
$triggerStmtReplaced = str_replace(
" TRIGGER",
"*/ /*!50003 TRIGGER",
$triggerStmtReplaced
);
if ( false === $triggerStmtReplaced ) {
$triggerStmtReplaced = $triggerStmt . " /* ";
}
$ret .= "DELIMITER ;;" . PHP_EOL .
$triggerStmtReplaced . " */ ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_procedure($row, $dumpSettings)
{
$ret = "";
if (!isset($row['Create Procedure'])) {
throw new Exception("Error getting procedure code, unknown output. " .
"Please check 'https://bugs.mysql.com/bug.php?id=14564'");
}
$procedureStmt = $row['Create Procedure'];
$ret .= "/*!50003 DROP PROCEDURE IF EXISTS `" .
$row['Procedure'] . "` */;" . PHP_EOL .
"/*!40101 SET @saved_cs_client = @@character_set_client */;" . PHP_EOL .
"/*!40101 SET character_set_client = " . $dumpSettings['default-character-set'] . " */;" . PHP_EOL .
"DELIMITER ;;" . PHP_EOL .
$procedureStmt . " ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL .
"/*!40101 SET character_set_client = @saved_cs_client */;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function create_event($row)
{
$ret = "";
if ( !isset($row['Create Event']) ) {
throw new Exception("Error getting event code, unknown output. " .
"Please check 'http://stackoverflow.com/questions/10853826/mysql-5-5-create-event-gives-syntax-error'");
}
$eventName = $row['Event'];
$eventStmt = $row['Create Event'];
$sqlMode = $row['sql_mode'];
$eventStmtReplaced = str_replace(
"CREATE DEFINER",
"/*!50106 CREATE*/ /*!50117 DEFINER",
$eventStmt
);
$eventStmtReplaced = str_replace(
" EVENT ",
"*/ /*!50106 EVENT ",
$eventStmtReplaced
);
if ( false === $eventStmtReplaced ) {
$eventStmtReplaced = $eventStmt . " /* ";
}
$ret .= "/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;" . PHP_EOL .
"/*!50106 DROP EVENT IF EXISTS `" . $eventName . "` */;" . PHP_EOL .
"DELIMITER ;;" . PHP_EOL .
"/*!50003 SET @saved_cs_client = @@character_set_client */ ;;" . PHP_EOL .
"/*!50003 SET @saved_cs_results = @@character_set_results */ ;;" . PHP_EOL .
"/*!50003 SET @saved_col_connection = @@collation_connection */ ;;" . PHP_EOL .
"/*!50003 SET character_set_client = utf8 */ ;;" . PHP_EOL .
"/*!50003 SET character_set_results = utf8 */ ;;" . PHP_EOL .
"/*!50003 SET collation_connection = utf8_general_ci */ ;;" . PHP_EOL .
"/*!50003 SET @saved_sql_mode = @@sql_mode */ ;;" . PHP_EOL .
"/*!50003 SET sql_mode = '" . $sqlMode . "' */ ;;" . PHP_EOL .
"/*!50003 SET @saved_time_zone = @@time_zone */ ;;" . PHP_EOL .
"/*!50003 SET time_zone = 'SYSTEM' */ ;;" . PHP_EOL .
$eventStmtReplaced . " */ ;;" . PHP_EOL .
"/*!50003 SET time_zone = @saved_time_zone */ ;;" . PHP_EOL .
"/*!50003 SET sql_mode = @saved_sql_mode */ ;;" . PHP_EOL .
"/*!50003 SET character_set_client = @saved_cs_client */ ;;" . PHP_EOL .
"/*!50003 SET character_set_results = @saved_cs_results */ ;;" . PHP_EOL .
"/*!50003 SET collation_connection = @saved_col_connection */ ;;" . PHP_EOL .
"DELIMITER ;" . PHP_EOL .
"/*!50106 SET TIME_ZONE= @save_time_zone */ ;" . PHP_EOL . PHP_EOL;
// Commented because we are doing this in restore_parameters()
// "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;" . PHP_EOL . PHP_EOL;
return $ret;
}
public function show_tables()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT TABLE_NAME AS tbl_name " .
"FROM INFORMATION_SCHEMA.TABLES " .
"WHERE TABLE_TYPE='BASE TABLE' AND TABLE_SCHEMA='{$args[0]}'";
}
public function show_views()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT TABLE_NAME AS tbl_name " .
"FROM INFORMATION_SCHEMA.TABLES " .
"WHERE TABLE_TYPE='VIEW' AND TABLE_SCHEMA='{$args[0]}'";
}
public function show_triggers()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SHOW TRIGGERS FROM `{$args[0]}`;";
}
public function show_columns()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SHOW COLUMNS FROM `{$args[0]}`;";
}
public function show_procedures()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT SPECIFIC_NAME AS procedure_name " .
"FROM INFORMATION_SCHEMA.ROUTINES " .
"WHERE ROUTINE_TYPE='PROCEDURE' AND ROUTINE_SCHEMA='{$args[0]}'";
}
/**
* Get query string to ask for names of events from current database.
*
* @param string Name of database
* @return string
*/
public function show_events()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "SELECT EVENT_NAME AS event_name " .
"FROM INFORMATION_SCHEMA.EVENTS " .
"WHERE EVENT_SCHEMA='{$args[0]}'";
}
public function setup_transaction()
{
return "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ";
}
public function start_transaction()
{
return "START TRANSACTION";
}
public function commit_transaction()
{
return "COMMIT";
}
public function lock_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return $this->dbHandler->get_results("LOCK TABLES `{$args[0]}` READ LOCAL",ARRAY_A);
}
public function unlock_table()
{
return $this->dbHandler->get_results("UNLOCK TABLES",ARRAY_A);
}
public function start_add_lock_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "LOCK TABLES `{$args[0]}` WRITE;" . PHP_EOL;
}
public function end_add_lock_table()
{
return "UNLOCK TABLES;" . PHP_EOL;
}
public function start_add_disable_keys()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 ALTER TABLE `{$args[0]}` DISABLE KEYS */;" .
PHP_EOL;
}
public function end_add_disable_keys()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 ALTER TABLE `{$args[0]}` ENABLE KEYS */;" .
PHP_EOL;
}
public function start_disable_autocommit()
{
return "SET autocommit=0;" . PHP_EOL;
}
public function end_disable_autocommit()
{
return "COMMIT;" . PHP_EOL;
}
public function add_drop_database()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "/*!40000 DROP DATABASE IF EXISTS `{$args[0]}`*/;" .
PHP_EOL . PHP_EOL;
}
public function add_drop_trigger()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TRIGGER IF EXISTS `{$args[0]}`;" . PHP_EOL;
}
public function drop_table()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TABLE IF EXISTS `{$args[0]}`;" . PHP_EOL;
}
public function drop_view()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "DROP TABLE IF EXISTS `{$args[0]}`;" . PHP_EOL .
"/*!50001 DROP VIEW IF EXISTS `{$args[0]}`*/;" . PHP_EOL;
}
public function getDatabaseHeader()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
return "--" . PHP_EOL .
"-- Current Database: `{$args[0]}`" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL;
}
/**
* Decode column metadata and fill info structure.
* type, is_numeric and is_blob will always be available.
*
* @param array $colType Array returned from "SHOW COLUMNS FROM tableName"
* @return array
*/
public function parseColumnType($colType)
{
$colInfo = array();
$colParts = explode(" ", $colType['Type']);
if($fparen = strpos($colParts[0], "("))
{
$colInfo['type'] = substr($colParts[0], 0, $fparen);
$colInfo['length'] = str_replace(")", "", substr($colParts[0], $fparen+1));
$colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : NULL;
}
else
{
$colInfo['type'] = $colParts[0];
}
$colInfo['is_numeric'] = in_array($colInfo['type'], $this->mysqlTypes['numerical']);
$colInfo['is_blob'] = in_array($colInfo['type'], $this->mysqlTypes['blob']);
// for virtual 'Extra' -> "STORED GENERATED"
$colInfo['is_virtual'] = strpos($colType['Extra'], "STORED GENERATED") === false ? false : true;
return $colInfo;
}
public function get_connection_charset($wpdb = null) {
if (null === $wpdb) {
global $wpdb;
}
$charset = (defined('DB_CHARSET') && DB_CHARSET) ? DB_CHARSET : 'utf8mb4';
if (method_exists($wpdb, 'determine_charset')) {
$charset_collate = $wpdb->determine_charset($charset, '');
if (!empty($charset_collate['charset'])) $charset = $charset_collate['charset'];
}
return $charset;
}
public function backup_parameters()
{
global $wpdb;
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$dumpSettings = $args[0];
$ret = "/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;" . PHP_EOL .
"/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;" . PHP_EOL .
"/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;" . PHP_EOL .
"/*!40101 SET NAMES " . $this->get_connection_charset($wpdb) . " */;" . PHP_EOL;
if (false === $dumpSettings['skip-tz-utc']) {
$ret .= "/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;" . PHP_EOL .
"/*!40103 SET TIME_ZONE='+00:00' */;" . PHP_EOL;
}
$ret .= "/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;" . PHP_EOL .
"/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;" . PHP_EOL .
"/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;" . PHP_EOL .
"/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;" . PHP_EOL .PHP_EOL;
return $ret;
}
public function restore_parameters()
{
$this->check_parameters(func_num_args(), $expected_num_args = 1, __METHOD__);
$args = func_get_args();
$dumpSettings = $args[0];
$ret = "";
if (false === $dumpSettings['skip-tz-utc']) {
$ret .= "/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;" . PHP_EOL;
}
$ret .= "/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;" . PHP_EOL .
"/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;" . PHP_EOL .
"/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;" . PHP_EOL .
"/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;" . PHP_EOL .
"/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;" . PHP_EOL .
"/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;" . PHP_EOL .
"/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;" . PHP_EOL . PHP_EOL;
return $ret;
}
/**
* Check number of parameters passed to function, useful when inheriting.
* Raise exception if unexpected.
*
* @param integer $num_args
* @param integer $expected_num_args
* @param string $method_name
*/
private function check_parameters($num_args, $expected_num_args, $method_name)
{
if ( $num_args != $expected_num_args ) {
throw new Exception("Unexpected parameter passed to ".esc_html($method_name));
}
return;
}
public function query($string)
{
return $this->dbHandler->get_results($string, ARRAY_A);
}
public function exec($string)
{
return $this->dbHandler->get_results($string, ARRAY_A);
}
public function quote($value)
{
$search = array("\x00", "\x0a", "\x0d", "\x1a");
$replace = array('\0', '\n', '\r', '\Z');
$value=str_replace('\\', '\\\\', $value);
$value=str_replace('\'', '\\\'', $value);
$value= "'" . str_replace($search, $replace, $value) . "'";
return $value;
}
public function closeCursor($resultSet)
{
$this->dbHandler->flush();
}
} includes/class-wpvivid-backuplist.php 0000644 00000032036 15132770567 0014036 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_Backuplist
{
public static function get_backup_by_id($id)
{
$lists[]='wpvivid_backup_list';
$lists=apply_filters('wpvivid_get_backuplist_name',$lists);
foreach ($lists as $list_name)
{
$list = WPvivid_Setting::get_option($list_name);
if(!empty($list))
{
foreach ($list as $k=>$backup)
{
if ($id == $k)
{
return $backup;
}
}
}
}
return false;
}
public static function update_backup_option($backup_id,$backup_new)
{
$lists[]='wpvivid_backup_list';
$lists=apply_filters('wpvivid_get_backuplist_name',$lists);
foreach ($lists as $list_name)
{
$list = WPvivid_Setting::get_option($list_name);
if(!empty($list))
{
foreach ($list as $k=>$backup)
{
if ($backup_id == $k)
{
$list[$backup_id]=$backup_new;
WPvivid_Setting::update_option($list_name,$list);
return ;
}
}
}
}
}
public static function get_backuplist($list_name='')
{
$list=array();
add_filter('wpvivid_get_backuplist',array('WPvivid_Backuplist','get_backup_list'),10,2);
$list=apply_filters('wpvivid_get_backuplist',$list,$list_name);
return $list;
}
public static function get_backup_list($list,$list_name)
{
$list = WPvivid_Setting::get_option('wpvivid_backup_list');
$list =self::sort_list($list);
return $list;
}
public static function get_backuplist_by_id($id){
$list = array();
add_filter('wpvivid_get_backuplist_by_id',array('WPvivid_Backuplist','get_backup_list_by_id'), 10 , 2);
$ret=apply_filters('wpvivid_get_backuplist_by_id',$list,$id);
return $ret;
}
public static function get_backup_list_by_id($list, $id)
{
$list = WPvivid_Setting::get_option('wpvivid_backup_list');
foreach ($list as $k=>$backup)
{
if ($id == $k)
{
$ret['list_name'] = 'wpvivid_backup_list';
$ret['list_data'] = $list;
return $ret;
}
}
return false;
}
public static function get_backuplist_by_key($key)
{
add_filter('wpvivid_get_backuplist_item',array('WPvivid_Backuplist','get_backuplist_item'),10,2);
$backup=false;
$backup=apply_filters('wpvivid_get_backuplist_item',$backup,$key);
return $backup;
}
public static function get_backuplist_item($backup,$key)
{
$list = WPvivid_Setting::get_option('wpvivid_backup_list');
foreach ($list as $k=>$backup)
{
if ($key == $k)
{
return $backup;
}
}
return false;
}
public static function update_backup($id,$key,$data)
{
add_action('wpvivid_update_backup',array('WPvivid_Backuplist', 'update_backup_item'),10,3);
do_action('wpvivid_update_backup',$id,$key,$data);
}
public static function update_backup_item($id,$key,$data)
{
$list = WPvivid_Setting::get_option('wpvivid_backup_list');
if(array_key_exists($id,$list))
{
$list[$id][$key]=$data;
WPvivid_Setting::update_option('wpvivid_backup_list',$list);
}
}
public static function add_new_upload_backup($task_id,$backup,$time,$log='')
{
$backup_data=array();
$backup_data['type']='Upload';
$backup_data['create_time']=$time;
$backup_data['manual_delete']=0;
$backup_data['local']['path']=WPvivid_Setting::get_backupdir();
$backup_data['compress']['compress_type']='zip';
$backup_data['save_local']=1;
$backup_data['log']=$log;
$backup_data['backup']=$backup;
$backup_data['remote']=array();
$backup_data['lock']=0;
$backup_list='wpvivid_backup_list';
$backup_list=apply_filters('get_wpvivid_backup_list_name',$backup_list,$task_id,$backup_data);
$list = WPvivid_Setting::get_option($backup_list);
$list[$task_id]=$backup_data;
WPvivid_Setting::update_option($backup_list,$list);
}
public static function delete_backup($key)
{
$lists[]='wpvivid_backup_list';
$lists=apply_filters('wpvivid_get_backuplist_name',$lists);
foreach ($lists as $list_name)
{
$list = WPvivid_Setting::get_option($list_name);
foreach ($list as $k=>$backup)
{
if ($key == $k)
{
unset($list[$key]);
WPvivid_Setting::update_option($list_name, $list);
return;
}
}
}
}
public static function sort_list($list)
{
if($list !== false)
{
uasort ($list,function($a, $b)
{
if($a['create_time']>$b['create_time'])
{
return -1;
}
else if($a['create_time']===$b['create_time'])
{
return 0;
}
else
{
return 1;
}
});
}
return $list;
}
public static function get_oldest_backup_id($list)
{
$oldest_id='';
$oldest=0;
foreach ($list as $k=>$backup)
{
if(!array_key_exists('lock',$backup) || (isset($backup['lock']) && $backup['lock'] == '0'))
{
if ($oldest == 0)
{
$oldest = $backup['create_time'];
$oldest_id = $k;
} else {
if ($oldest > $backup['create_time'])
{
$oldest_id = $k;
}
}
}
}
return $oldest_id;
}
public static function check_backuplist_limit($max_count)
{
$list = WPvivid_Setting::get_option('wpvivid_backup_list');
foreach ($list as $key=>$value)
{
if(isset($value['lock']) && $value['lock'] == 1)
{
unset($list[$key]);
}
}
if($list !== false)
{
$size=sizeof($list);
}
else
{
$size = 0;
}
if($size>=$max_count)
{
$oldest_id=self::get_oldest_backup_id($list);
if(empty($oldest_id))
{
return false;
}
else
{
return $oldest_id;
}
}
else
{
return false;
}
}
public static function get_out_of_date_backuplist($max_count)
{
$list = WPvivid_Setting::get_option('wpvivid_backup_list');
foreach ($list as $key=>$value)
{
if(isset($value['lock']) && $value['lock'] == 1)
{
unset($list[$key]);
}
}
if($list !== false)
{
$size=sizeof($list);
}
else
{
$size = 0;
}
$out_of_date_list=array();
if($max_count==0)
return $out_of_date_list;
while($size>$max_count)
{
$oldest_id=self::get_oldest_backup_id($list);
if(!empty($oldest_id))
{
$out_of_date_list[]=$oldest_id;
unset($list[$oldest_id]);
}
$new_size=sizeof($list);
if($new_size==$size)
{
break;
}
else
{
$size=$new_size;
}
}
return $out_of_date_list;
}
public static function get_out_of_date_backuplist_info($max_count)
{
$list = WPvivid_Setting::get_option('wpvivid_backup_list');
if($list !== false)
{
$size=sizeof($list);
}
else
{
$size = 0;
}
$out_of_date_list['size']=0;
$out_of_date_list['count']=0;
if($max_count==0)
return $out_of_date_list;
while($size>$max_count)
{
$oldest_id=self::get_oldest_backup_id($list);
if(!empty($oldest_id))
{
$out_of_date_list['size']+=self::get_size($oldest_id);
$out_of_date_list['count']++;
unset($list[$oldest_id]);
}
$new_size=sizeof($list);
if($new_size==$size)
{
break;
}
else
{
$size=$new_size;
}
}
return $out_of_date_list;
}
public static function get_size($backup_id)
{
$size=0;
$list = WPvivid_Setting::get_option('wpvivid_backup_list');
$backup=$list[$backup_id];
if(isset($backup['backup']['files'])){
foreach ($backup['backup']['files'] as $file) {
$size+=$file['size'];
}
}
else{
if(isset($backup['backup']['data']['type'])){
foreach ($backup['backup']['data']['type'] as $type) {
foreach ($type['files'] as $file) {
$size+=$file['size'];
}
}
}
}
return $size;
}
public static function set_security_lock($backup_id,$lock)
{
//$list = WPvivid_Setting::get_option('wpvivid_backup_list');
$ret = self::get_backuplist_by_id($backup_id);
if($ret !== false) {
$list = $ret['list_data'];
if (array_key_exists($backup_id, $list)) {
if ($lock == 1) {
$list[$backup_id]['lock'] = 1;
}
else {
if (array_key_exists('lock', $list[$backup_id])) {
unset($list[$backup_id]['lock']);
}
}
}
WPvivid_Setting::update_option($ret['list_name'], $list);
}
$ret['result'] = 'success';
$list = WPvivid_Setting::get_option($ret['list_name']);
if (array_key_exists($backup_id, $list)) {
if (isset($list[$backup_id]['lock'])) {
if ($list[$backup_id]['lock'] == 1) {
$backup_lock = '/admin/partials/images/locked.png';
$lock_status = 'lock';
$ret['html'] = '<img src="' . esc_url(WPVIVID_PLUGIN_URL . $backup_lock) . '" name="' . esc_attr($lock_status, 'wpvivid-backuprestore') . '" onclick="wpvivid_set_backup_lock(\''.$backup_id.'\', \''.$lock_status.'\');" style="vertical-align:middle; cursor:pointer;"/>';
} else {
$backup_lock = '/admin/partials/images/unlocked.png';
$lock_status = 'unlock';
$ret['html'] = '<img src="' . esc_url(WPVIVID_PLUGIN_URL . $backup_lock) . '" name="' . esc_attr($lock_status, 'wpvivid-backuprestore') . '" onclick="wpvivid_set_backup_lock(\''.$backup_id.'\', \''.$lock_status.'\');" style="vertical-align:middle; cursor:pointer;"/>';
}
} else {
$backup_lock = '/admin/partials/images/unlocked.png';
$lock_status = 'unlock';
$ret['html'] = '<img src="' . esc_url(WPVIVID_PLUGIN_URL . $backup_lock) . '" name="' . esc_attr($lock_status, 'wpvivid-backuprestore') . '" onclick="wpvivid_set_backup_lock(\''.$backup_id.'\', \''.$lock_status.'\');" style="vertical-align:middle; cursor:pointer;"/>';
}
} else {
$backup_lock = '/admin/partials/images/unlocked.png';
$lock_status = 'unlock';
$ret['html'] = '<img src="' . esc_url(WPVIVID_PLUGIN_URL . $backup_lock) . '" name="' . esc_attr($lock_status, 'wpvivid-backuprestore') . '" onclick="wpvivid_set_backup_lock(\''.$backup_id.'\', \''.$lock_status.'\');" style="vertical-align:middle; cursor:pointer;"/>';
}
return $ret;
}
public static function get_has_remote_backuplist()
{
$backup_id_list=array();
$list = WPvivid_Setting::get_option('wpvivid_backup_list');
foreach ($list as $k=>$backup)
{
if(!empty($backup['remote']))
{
$backup_id_list[]=$k;
}
}
return $backup_id_list;
}
} includes/lib2/google-api-php-client/src/WPvivid/Google/Exception.php 0000644 00000001217 15132770567 0021346 0 ustar 00 <?php
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class WPvivid_Google_Exception extends Exception
{
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Resource.php 0000644 00000024014 15132770567 0022577 0 ustar 00 <?php
/**
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGuzzleHttp\Psr7\Request;
/**
* Implements the actual methods/resources of the discovered Google API using magic function
* calling overloading (__call()), which on call will see if the method name (plus.activities.list)
* is available in this service, and if so construct an apiHttpRequest representing it.
*
*/
class WPvivid_Google_Service_Resource
{
// Valid query parameters that work, but don't appear in discovery.
private $stackParameters = array(
'alt' => array('type' => 'string', 'location' => 'query'),
'fields' => array('type' => 'string', 'location' => 'query'),
'trace' => array('type' => 'string', 'location' => 'query'),
'userIp' => array('type' => 'string', 'location' => 'query'),
'quotaUser' => array('type' => 'string', 'location' => 'query'),
'data' => array('type' => 'string', 'location' => 'body'),
'mimeType' => array('type' => 'string', 'location' => 'header'),
'uploadType' => array('type' => 'string', 'location' => 'query'),
'mediaUpload' => array('type' => 'complex', 'location' => 'query'),
'prettyPrint' => array('type' => 'string', 'location' => 'query'),
);
/** @var string $rootUrl */
private $rootUrl;
/** @var Google_Client $client */
private $client;
/** @var string $serviceName */
private $serviceName;
/** @var string $servicePath */
private $servicePath;
/** @var string $resourceName */
private $resourceName;
/** @var array $methods */
private $methods;
public function __construct($service, $serviceName, $resourceName, $resource)
{
$this->rootUrl = $service->rootUrl;
$this->client = $service->getClient();
$this->servicePath = $service->servicePath;
$this->serviceName = $serviceName;
$this->resourceName = $resourceName;
$this->methods = is_array($resource) && isset($resource['methods']) ?
$resource['methods'] :
array($resourceName => $resource);
}
/**
* TODO: This function needs simplifying.
* @param $name
* @param $arguments
* @param $expectedClass - optional, the expected class name
* @return WPvivid_Google_Http_Request|expectedClass
* @throws WPvivid_Google_Exception
*/
public function call($name, $arguments, $expectedClass = null)
{
if (! isset($this->methods[$name])) {
$this->client->getLogger()->error(
'Service method unknown',
array(
'service' => $this->serviceName,
'resource' => $this->resourceName,
'method' => $name
)
);
throw new WPvivid_Google_Exception(
"Unknown function: " .
esc_html("{$this->serviceName}->{$this->resourceName}->{$name}()")
);
}
$method = $this->methods[$name];
$parameters = $arguments[0];
// postBody is a special case since it's not defined in the discovery
// document as parameter, but we abuse the param entry for storing it.
$postBody = null;
if (isset($parameters['postBody'])) {
if ($parameters['postBody'] instanceof WPvivid_Google_Model) {
// In the cases the post body is an existing object, we want
// to use the smart method to create a simple object for
// for JSONification.
$parameters['postBody'] = $parameters['postBody']->toSimpleObject();
} else if (is_object($parameters['postBody'])) {
// If the post body is another kind of object, we will try and
// wrangle it into a sensible format.
$parameters['postBody'] =
$this->convertToArrayAndStripNulls($parameters['postBody']);
}
$postBody = (array) $parameters['postBody'];
unset($parameters['postBody']);
}
// TODO: optParams here probably should have been
// handled already - this may well be redundant code.
if (isset($parameters['optParams'])) {
$optParams = $parameters['optParams'];
unset($parameters['optParams']);
$parameters = array_merge($parameters, $optParams);
}
if (!isset($method['parameters'])) {
$method['parameters'] = array();
}
$method['parameters'] = array_merge(
$this->stackParameters,
$method['parameters']
);
foreach ($parameters as $key => $val) {
if ($key != 'postBody' && ! isset($method['parameters'][$key])) {
$this->client->getLogger()->error(
'Service parameter unknown',
array(
'service' => $this->serviceName,
'resource' => $this->resourceName,
'method' => $name,
'parameter' => $key
)
);
throw new WPvivid_Google_Exception(esc_html("($name) unknown parameter: '$key'"));
}
}
foreach ($method['parameters'] as $paramName => $paramSpec) {
if (isset($paramSpec['required']) &&
$paramSpec['required'] &&
! isset($parameters[$paramName])
) {
$this->client->getLogger()->error(
'Service parameter missing',
array(
'service' => $this->serviceName,
'resource' => $this->resourceName,
'method' => $name,
'parameter' => $paramName
)
);
throw new WPvivid_Google_Exception(esc_html("($name) missing required param: '$paramName'"));
}
if (isset($parameters[$paramName])) {
$value = $parameters[$paramName];
$parameters[$paramName] = $paramSpec;
$parameters[$paramName]['value'] = $value;
unset($parameters[$paramName]['required']);
} else {
// Ensure we don't pass nulls.
unset($parameters[$paramName]);
}
}
$this->client->getLogger()->info(
'Service Call',
array(
'service' => $this->serviceName,
'resource' => $this->resourceName,
'method' => $name,
'arguments' => $parameters,
)
);
// build the service uri
$url = $this->createRequestUri(
$method['path'],
$parameters
);
// NOTE: because we're creating the request by hand,
// and because the service has a rootUrl property
// the "base_uri" of the Http Client is not accounted for
$request = new Request(
$method['httpMethod'],
$url,
['content-type' => 'application/json'],
$postBody ? json_encode($postBody) : ''
);
// support uploads
if (isset($parameters['data'])) {
$mimeType = isset($parameters['mimeType'])
? $parameters['mimeType']['value']
: 'application/octet-stream';
$data = $parameters['data']['value'];
$upload = new WPvivid_Google_Http_MediaFileUpload($this->client, $request, $mimeType, $data);
// pull down the modified request
$request = $upload->getRequest();
}
// if this is a media type, we will return the raw response
// rather than using an expected class
if (isset($parameters['alt']) && $parameters['alt']['value'] == 'media') {
$expectedClass = null;
}
// if the client is marked for deferring, rather than
// execute the request, return the response
if ($this->client->shouldDefer()) {
// @TODO find a better way to do this
$request = $request
->withHeader('X-Php-Expected-Class', $expectedClass);
return $request;
}
return $this->client->execute($request, $expectedClass);
}
protected function convertToArrayAndStripNulls($o)
{
$o = (array) $o;
foreach ($o as $k => $v) {
if ($v === null) {
unset($o[$k]);
} elseif (is_object($v) || is_array($v)) {
$o[$k] = $this->convertToArrayAndStripNulls($o[$k]);
}
}
return $o;
}
/**
* Parse/expand request parameters and create a fully qualified
* request uri.
* @static
* @param string $restPath
* @param array $params
* @return string $requestUrl
*/
public function createRequestUri($restPath, $params)
{
// Override the default servicePath address if the $restPath use a /
if ('/' == substr($restPath, 0, 1)) {
$requestUrl = substr($restPath, 1);
} else {
$requestUrl = $this->servicePath . $restPath;
}
// code for leading slash
if ($this->rootUrl) {
if ('/' !== substr($this->rootUrl, -1) && '/' !== substr($requestUrl, 0, 1)) {
$requestUrl = '/' . $requestUrl;
}
$requestUrl = $this->rootUrl . $requestUrl;
}
$uriTemplateVars = array();
$queryVars = array();
foreach ($params as $paramName => $paramSpec) {
if ($paramSpec['type'] == 'boolean') {
$paramSpec['value'] = $paramSpec['value'] ? 'true' : 'false';
}
if ($paramSpec['location'] == 'path') {
$uriTemplateVars[$paramName] = $paramSpec['value'];
} else if ($paramSpec['location'] == 'query') {
if (is_array($paramSpec['value'])) {
foreach ($paramSpec['value'] as $value) {
$queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($value));
}
} else {
$queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($paramSpec['value']));
}
}
}
if (count($uriTemplateVars)) {
$uriTemplateParser = new WPvivid_Google_Utils_UriTemplate();
$requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
}
if (count($queryVars)) {
if (version_compare(PHP_VERSION, '7.4', '>=')) {
$requestUrl .= '?' . implode('&', $queryVars);
}
else{
$requestUrl .= '?' . implode($queryVars, '&');
}
}
return $requestUrl;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Exception.php 0000644 00000003553 15132770567 0022753 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class WPvivid_Google_Service_Exception extends WPvivid_Google_Exception
{
/**
* Optional list of errors returned in a JSON body of an HTTP error response.
*/
protected $errors = array();
/**
* Override default constructor to add the ability to set $errors and a retry
* map.
*
* @param string $message
* @param int $code
* @param Exception|null $previous
* @param [{string, string}] errors List of errors returned in an HTTP
* response. Defaults to [].
* @param array|null $retryMap Map of errors with retry counts.
*/
public function __construct(
$message,
$code = 0,
Exception $previous = null,
$errors = array()
) {
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
parent::__construct($message, $code, $previous);
} else {
parent::__construct($message, $code);
}
$this->errors = $errors;
}
/**
* An example of the possible errors returned.
*
* {
* "domain": "global",
* "reason": "authError",
* "message": "Invalid Credentials",
* "locationType": "header",
* "location": "Authorization",
* }
*
* @return [{string, string}] List of errors return in an HTTP response or [].
*/
public function getErrors()
{
return $this->errors;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/README.md 0000644 00000000301 15132770567 0021547 0 ustar 00 # Google API Client Services
Google API Client Service classes have been moved to the
[google-api-php-client-services](https://github.com/google/google-api-php-client-services)
repository.
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/DriveFileVideoMediaMetadata.php0000644 00000002274 15132770567 0027326 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_DriveFileVideoMediaMetadata extends WPvivid_Google_Model
{
public $durationMillis;
public $height;
public $width;
public function setDurationMillis($durationMillis)
{
$this->durationMillis = $durationMillis;
}
public function getDurationMillis()
{
return $this->durationMillis;
}
public function setHeight($height)
{
$this->height = $height;
}
public function getHeight()
{
return $this->height;
}
public function setWidth($width)
{
$this->width = $width;
}
public function getWidth()
{
return $this->width;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/DriveFile.php 0000644 00000033030 15132770567 0023730 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_DriveFile extends WPvivid_Google_Collection
{
protected $collection_key = 'spaces';
public $appProperties;
protected $capabilitiesType = 'WPvivid_Google_Service_Drive_DriveFileCapabilities';
protected $capabilitiesDataType = '';
protected $contentHintsType = 'WPvivid_Google_Service_Drive_DriveFileContentHints';
protected $contentHintsDataType = '';
public $copyRequiresWriterPermission;
public $createdTime;
public $description;
public $explicitlyTrashed;
public $exportLinks;
public $fileExtension;
public $folderColorRgb;
public $fullFileExtension;
public $hasAugmentedPermissions;
public $hasThumbnail;
public $headRevisionId;
public $iconLink;
public $id;
protected $imageMediaMetadataType = 'WPvivid_Google_Service_Drive_DriveFileImageMediaMetadata';
protected $imageMediaMetadataDataType = '';
public $isAppAuthorized;
public $kind;
protected $lastModifyingUserType = 'WPvivid_Google_Service_Drive_User';
protected $lastModifyingUserDataType = '';
public $md5Checksum;
public $mimeType;
public $modifiedByMe;
public $modifiedByMeTime;
public $modifiedTime;
public $name;
public $originalFilename;
public $ownedByMe;
protected $ownersType = 'WPvivid_Google_Service_Drive_User';
protected $ownersDataType = 'array';
public $parents;
public $permissionIds;
protected $permissionsType = 'WPvivid_Google_Service_Drive_Permission';
protected $permissionsDataType = 'array';
public $properties;
public $quotaBytesUsed;
public $shared;
public $sharedWithMeTime;
protected $sharingUserType = 'WPvivid_Google_Service_Drive_User';
protected $sharingUserDataType = '';
public $size;
public $spaces;
public $starred;
public $teamDriveId;
public $thumbnailLink;
public $thumbnailVersion;
public $trashed;
public $trashedTime;
protected $trashingUserType = 'WPvivid_Google_Service_Drive_User';
protected $trashingUserDataType = '';
public $version;
protected $videoMediaMetadataType = 'WPvivid_Google_Service_Drive_DriveFileVideoMediaMetadata';
protected $videoMediaMetadataDataType = '';
public $viewedByMe;
public $viewedByMeTime;
public $viewersCanCopyContent;
public $webContentLink;
public $webViewLink;
public $writersCanShare;
public function setAppProperties($appProperties)
{
$this->appProperties = $appProperties;
}
public function getAppProperties()
{
return $this->appProperties;
}
/**
* @param WPvivid_Google_Service_Drive_DriveFileCapabilities
*/
public function setCapabilities(WPvivid_Google_Service_Drive_DriveFileCapabilities $capabilities)
{
$this->capabilities = $capabilities;
}
/**
* @return WPvivid_Google_Service_Drive_DriveFileCapabilities
*/
public function getCapabilities()
{
return $this->capabilities;
}
/**
* @param WPvivid_Google_Service_Drive_DriveFileContentHints
*/
public function setContentHints(WPvivid_Google_Service_Drive_DriveFileContentHints $contentHints)
{
$this->contentHints = $contentHints;
}
/**
* @return WPvivid_Google_Service_Drive_DriveFileContentHints
*/
public function getContentHints()
{
return $this->contentHints;
}
public function setCopyRequiresWriterPermission($copyRequiresWriterPermission)
{
$this->copyRequiresWriterPermission = $copyRequiresWriterPermission;
}
public function getCopyRequiresWriterPermission()
{
return $this->copyRequiresWriterPermission;
}
public function setCreatedTime($createdTime)
{
$this->createdTime = $createdTime;
}
public function getCreatedTime()
{
return $this->createdTime;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setExplicitlyTrashed($explicitlyTrashed)
{
$this->explicitlyTrashed = $explicitlyTrashed;
}
public function getExplicitlyTrashed()
{
return $this->explicitlyTrashed;
}
public function setExportLinks($exportLinks)
{
$this->exportLinks = $exportLinks;
}
public function getExportLinks()
{
return $this->exportLinks;
}
public function setFileExtension($fileExtension)
{
$this->fileExtension = $fileExtension;
}
public function getFileExtension()
{
return $this->fileExtension;
}
public function setFolderColorRgb($folderColorRgb)
{
$this->folderColorRgb = $folderColorRgb;
}
public function getFolderColorRgb()
{
return $this->folderColorRgb;
}
public function setFullFileExtension($fullFileExtension)
{
$this->fullFileExtension = $fullFileExtension;
}
public function getFullFileExtension()
{
return $this->fullFileExtension;
}
public function setHasAugmentedPermissions($hasAugmentedPermissions)
{
$this->hasAugmentedPermissions = $hasAugmentedPermissions;
}
public function getHasAugmentedPermissions()
{
return $this->hasAugmentedPermissions;
}
public function setHasThumbnail($hasThumbnail)
{
$this->hasThumbnail = $hasThumbnail;
}
public function getHasThumbnail()
{
return $this->hasThumbnail;
}
public function setHeadRevisionId($headRevisionId)
{
$this->headRevisionId = $headRevisionId;
}
public function getHeadRevisionId()
{
return $this->headRevisionId;
}
public function setIconLink($iconLink)
{
$this->iconLink = $iconLink;
}
public function getIconLink()
{
return $this->iconLink;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
/**
* @param WPvivid_Google_Service_Drive_DriveFileImageMediaMetadata
*/
public function setImageMediaMetadata(WPvivid_Google_Service_Drive_DriveFileImageMediaMetadata $imageMediaMetadata)
{
$this->imageMediaMetadata = $imageMediaMetadata;
}
/**
* @return WPvivid_Google_Service_Drive_DriveFileImageMediaMetadata
*/
public function getImageMediaMetadata()
{
return $this->imageMediaMetadata;
}
public function setIsAppAuthorized($isAppAuthorized)
{
$this->isAppAuthorized = $isAppAuthorized;
}
public function getIsAppAuthorized()
{
return $this->isAppAuthorized;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
/**
* @param WPvivid_Google_Service_Drive_User
*/
public function setLastModifyingUser(WPvivid_Google_Service_Drive_User $lastModifyingUser)
{
$this->lastModifyingUser = $lastModifyingUser;
}
/**
* @return WPvivid_Google_Service_Drive_User
*/
public function getLastModifyingUser()
{
return $this->lastModifyingUser;
}
public function setMd5Checksum($md5Checksum)
{
$this->md5Checksum = $md5Checksum;
}
public function getMd5Checksum()
{
return $this->md5Checksum;
}
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
}
public function getMimeType()
{
return $this->mimeType;
}
public function setModifiedByMe($modifiedByMe)
{
$this->modifiedByMe = $modifiedByMe;
}
public function getModifiedByMe()
{
return $this->modifiedByMe;
}
public function setModifiedByMeTime($modifiedByMeTime)
{
$this->modifiedByMeTime = $modifiedByMeTime;
}
public function getModifiedByMeTime()
{
return $this->modifiedByMeTime;
}
public function setModifiedTime($modifiedTime)
{
$this->modifiedTime = $modifiedTime;
}
public function getModifiedTime()
{
return $this->modifiedTime;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setOriginalFilename($originalFilename)
{
$this->originalFilename = $originalFilename;
}
public function getOriginalFilename()
{
return $this->originalFilename;
}
public function setOwnedByMe($ownedByMe)
{
$this->ownedByMe = $ownedByMe;
}
public function getOwnedByMe()
{
return $this->ownedByMe;
}
/**
* @param WPvivid_Google_Service_Drive_User
*/
public function setOwners($owners)
{
$this->owners = $owners;
}
/**
* @return WPvivid_Google_Service_Drive_User
*/
public function getOwners()
{
return $this->owners;
}
public function setParents($parents)
{
$this->parents = $parents;
}
public function getParents()
{
return $this->parents;
}
public function setPermissionIds($permissionIds)
{
$this->permissionIds = $permissionIds;
}
public function getPermissionIds()
{
return $this->permissionIds;
}
/**
* @param WPvivid_Google_Service_Drive_Permission
*/
public function setPermissions($permissions)
{
$this->permissions = $permissions;
}
/**
* @return WPvivid_Google_Service_Drive_Permission
*/
public function getPermissions()
{
return $this->permissions;
}
public function setProperties($properties)
{
$this->properties = $properties;
}
public function getProperties()
{
return $this->properties;
}
public function setQuotaBytesUsed($quotaBytesUsed)
{
$this->quotaBytesUsed = $quotaBytesUsed;
}
public function getQuotaBytesUsed()
{
return $this->quotaBytesUsed;
}
public function setShared($shared)
{
$this->shared = $shared;
}
public function getShared()
{
return $this->shared;
}
public function setSharedWithMeTime($sharedWithMeTime)
{
$this->sharedWithMeTime = $sharedWithMeTime;
}
public function getSharedWithMeTime()
{
return $this->sharedWithMeTime;
}
/**
* @param WPvivid_Google_Service_Drive_User
*/
public function setSharingUser(WPvivid_Google_Service_Drive_User $sharingUser)
{
$this->sharingUser = $sharingUser;
}
/**
* @return WPvivid_Google_Service_Drive_User
*/
public function getSharingUser()
{
return $this->sharingUser;
}
public function setSize($size)
{
$this->size = $size;
}
public function getSize()
{
return $this->size;
}
public function setSpaces($spaces)
{
$this->spaces = $spaces;
}
public function getSpaces()
{
return $this->spaces;
}
public function setStarred($starred)
{
$this->starred = $starred;
}
public function getStarred()
{
return $this->starred;
}
public function setTeamDriveId($teamDriveId)
{
$this->teamDriveId = $teamDriveId;
}
public function getTeamDriveId()
{
return $this->teamDriveId;
}
public function setThumbnailLink($thumbnailLink)
{
$this->thumbnailLink = $thumbnailLink;
}
public function getThumbnailLink()
{
return $this->thumbnailLink;
}
public function setThumbnailVersion($thumbnailVersion)
{
$this->thumbnailVersion = $thumbnailVersion;
}
public function getThumbnailVersion()
{
return $this->thumbnailVersion;
}
public function setTrashed($trashed)
{
$this->trashed = $trashed;
}
public function getTrashed()
{
return $this->trashed;
}
public function setTrashedTime($trashedTime)
{
$this->trashedTime = $trashedTime;
}
public function getTrashedTime()
{
return $this->trashedTime;
}
/**
* @param WPvivid_Google_Service_Drive_User
*/
public function setTrashingUser(WPvivid_Google_Service_Drive_User $trashingUser)
{
$this->trashingUser = $trashingUser;
}
/**
* @return WPvivid_Google_Service_Drive_User
*/
public function getTrashingUser()
{
return $this->trashingUser;
}
public function setVersion($version)
{
$this->version = $version;
}
public function getVersion()
{
return $this->version;
}
/**
* @param WPvivid_Google_Service_Drive_DriveFileVideoMediaMetadata
*/
public function setVideoMediaMetadata(WPvivid_Google_Service_Drive_DriveFileVideoMediaMetadata $videoMediaMetadata)
{
$this->videoMediaMetadata = $videoMediaMetadata;
}
/**
* @return WPvivid_Google_Service_Drive_DriveFileVideoMediaMetadata
*/
public function getVideoMediaMetadata()
{
return $this->videoMediaMetadata;
}
public function setViewedByMe($viewedByMe)
{
$this->viewedByMe = $viewedByMe;
}
public function getViewedByMe()
{
return $this->viewedByMe;
}
public function setViewedByMeTime($viewedByMeTime)
{
$this->viewedByMeTime = $viewedByMeTime;
}
public function getViewedByMeTime()
{
return $this->viewedByMeTime;
}
public function setViewersCanCopyContent($viewersCanCopyContent)
{
$this->viewersCanCopyContent = $viewersCanCopyContent;
}
public function getViewersCanCopyContent()
{
return $this->viewersCanCopyContent;
}
public function setWebContentLink($webContentLink)
{
$this->webContentLink = $webContentLink;
}
public function getWebContentLink()
{
return $this->webContentLink;
}
public function setWebViewLink($webViewLink)
{
$this->webViewLink = $webViewLink;
}
public function getWebViewLink()
{
return $this->webViewLink;
}
public function setWritersCanShare($writersCanShare)
{
$this->writersCanShare = $writersCanShare;
}
public function getWritersCanShare()
{
return $this->writersCanShare;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/CommentList.php 0000644 00000002657 15132770567 0024330 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_CommentList extends WPvivid_Google_Collection
{
protected $collection_key = 'comments';
protected $commentsType = 'WPvivid_Google_Service_Drive_Comment';
protected $commentsDataType = 'array';
public $kind;
public $nextPageToken;
/**
* @param WPvivid_Google_Service_Drive_Comment
*/
public function setComments($comments)
{
$this->comments = $comments;
}
/**
* @return WPvivid_Google_Service_Drive_Comment
*/
public function getComments()
{
return $this->comments;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/TeamDriveList.php 0000644 00000002711 15132770567 0024575 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_TeamDriveList extends WPvivid_Google_Collection
{
protected $collection_key = 'teamDrives';
public $kind;
public $nextPageToken;
protected $teamDrivesType = 'WPvivid_Google_Service_Drive_TeamDrive';
protected $teamDrivesDataType = 'array';
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
/**
* @param WPvivid_Google_Service_Drive_TeamDrive
*/
public function setTeamDrives($teamDrives)
{
$this->teamDrives = $teamDrives;
}
/**
* @return WPvivid_Google_Service_Drive_TeamDrive
*/
public function getTeamDrives()
{
return $this->teamDrives;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/AboutTeamDriveThemes.php 0000644 00000002321 15132770567 0026077 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_AboutTeamDriveThemes extends WPvivid_Google_Model
{
public $backgroundImageLink;
public $colorRgb;
public $id;
public function setBackgroundImageLink($backgroundImageLink)
{
$this->backgroundImageLink = $backgroundImageLink;
}
public function getBackgroundImageLink()
{
return $this->backgroundImageLink;
}
public function setColorRgb($colorRgb)
{
$this->colorRgb = $colorRgb;
}
public function getColorRgb()
{
return $this->colorRgb;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/ChangeList.php 0000644 00000003203 15132770567 0024077 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_ChangeList extends Google_Collection
{
protected $collection_key = 'changes';
protected $changesType = 'WPvivid_Google_Service_Drive_Change';
protected $changesDataType = 'array';
public $kind;
public $newStartPageToken;
public $nextPageToken;
/**
* @param WPvivid_Google_Service_Drive_Change
*/
public function setChanges($changes)
{
$this->changes = $changes;
}
/**
* @return WPvivid_Google_Service_Drive_Change
*/
public function getChanges()
{
return $this->changes;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNewStartPageToken($newStartPageToken)
{
$this->newStartPageToken = $newStartPageToken;
}
public function getNewStartPageToken()
{
return $this->newStartPageToken;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/DriveFileContentHints.php 0000644 00000002600 15132770567 0026270 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_DriveFileContentHints extends WPvivid_Google_Model
{
public $indexableText;
protected $thumbnailType = 'WPvivid_Google_Service_Drive_DriveFileContentHintsThumbnail';
protected $thumbnailDataType = '';
public function setIndexableText($indexableText)
{
$this->indexableText = $indexableText;
}
public function getIndexableText()
{
return $this->indexableText;
}
/**
* @param WPvivid_Google_Service_Drive_DriveFileContentHintsThumbnail
*/
public function setThumbnail(WPvivid_Google_Service_Drive_DriveFileContentHintsThumbnail $thumbnail)
{
$this->thumbnail = $thumbnail;
}
/**
* @return WPvivid_Google_Service_Drive_DriveFileContentHintsThumbnail
*/
public function getThumbnail()
{
return $this->thumbnail;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/TeamDrive.php 0000644 00000006572 15132770567 0023752 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_TeamDrive extends WPvivid_Google_Model
{
protected $backgroundImageFileType = 'WPvivid_Google_Service_Drive_TeamDriveBackgroundImageFile';
protected $backgroundImageFileDataType = '';
public $backgroundImageLink;
protected $capabilitiesType = 'WPvivid_Google_Service_Drive_TeamDriveCapabilities';
protected $capabilitiesDataType = '';
public $colorRgb;
public $createdTime;
public $id;
public $kind;
public $name;
protected $restrictionsType = 'WPvivid_Google_Service_Drive_TeamDriveRestrictions';
protected $restrictionsDataType = '';
public $themeId;
/**
* @param WPvivid_Google_Service_Drive_TeamDriveBackgroundImageFile
*/
public function setBackgroundImageFile(WPvivid_Google_Service_Drive_TeamDriveBackgroundImageFile $backgroundImageFile)
{
$this->backgroundImageFile = $backgroundImageFile;
}
/**
* @return WPvivid_Google_Service_Drive_TeamDriveBackgroundImageFile
*/
public function getBackgroundImageFile()
{
return $this->backgroundImageFile;
}
public function setBackgroundImageLink($backgroundImageLink)
{
$this->backgroundImageLink = $backgroundImageLink;
}
public function getBackgroundImageLink()
{
return $this->backgroundImageLink;
}
/**
* @param WPvivid_Google_Service_Drive_TeamDriveCapabilities
*/
public function setCapabilities(WPvivid_Google_Service_Drive_TeamDriveCapabilities $capabilities)
{
$this->capabilities = $capabilities;
}
/**
* @return WPvivid_Google_Service_Drive_TeamDriveCapabilities
*/
public function getCapabilities()
{
return $this->capabilities;
}
public function setColorRgb($colorRgb)
{
$this->colorRgb = $colorRgb;
}
public function getColorRgb()
{
return $this->colorRgb;
}
public function setCreatedTime($createdTime)
{
$this->createdTime = $createdTime;
}
public function getCreatedTime()
{
return $this->createdTime;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
/**
* @param WPvivid_Google_Service_Drive_TeamDriveRestrictions
*/
public function setRestrictions(WPvivid_Google_Service_Drive_TeamDriveRestrictions $restrictions)
{
$this->restrictions = $restrictions;
}
/**
* @return WPvivid_Google_Service_Drive_TeamDriveRestrictions
*/
public function getRestrictions()
{
return $this->restrictions;
}
public function setThemeId($themeId)
{
$this->themeId = $themeId;
}
public function getThemeId()
{
return $this->themeId;
}
}
lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/TeamDriveBackgroundImageFile.php 0000644 00000002513 15132770567 0027425 0 ustar 00 includes <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_TeamDriveBackgroundImageFile extends WPvivid_Google_Model
{
public $id;
public $width;
public $xCoordinate;
public $yCoordinate;
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setWidth($width)
{
$this->width = $width;
}
public function getWidth()
{
return $this->width;
}
public function setXCoordinate($xCoordinate)
{
$this->xCoordinate = $xCoordinate;
}
public function getXCoordinate()
{
return $this->xCoordinate;
}
public function setYCoordinate($yCoordinate)
{
$this->yCoordinate = $yCoordinate;
}
public function getYCoordinate()
{
return $this->yCoordinate;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Change.php 0000644 00000004576 15132770567 0023261 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_Change extends WPvivid_Google_Model
{
protected $fileType = 'WPvivid_Google_Service_Drive_DriveFile';
protected $fileDataType = '';
public $fileId;
public $kind;
public $removed;
protected $teamDriveType = 'WPvivid_Google_Service_Drive_TeamDrive';
protected $teamDriveDataType = '';
public $teamDriveId;
public $time;
public $type;
/**
* @param WPvivid_Google_Service_Drive_DriveFile
*/
public function setFile(WPvivid_Google_Service_Drive_DriveFile $file)
{
$this->file = $file;
}
/**
* @return WPvivid_Google_Service_Drive_DriveFile
*/
public function getFile()
{
return $this->file;
}
public function setFileId($fileId)
{
$this->fileId = $fileId;
}
public function getFileId()
{
return $this->fileId;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setRemoved($removed)
{
$this->removed = $removed;
}
public function getRemoved()
{
return $this->removed;
}
/**
* @param WPvivid_Google_Service_Drive_TeamDrive
*/
public function setTeamDrive(WPvivid_Google_Service_Drive_TeamDrive $teamDrive)
{
$this->teamDrive = $teamDrive;
}
/**
* @return WPvivid_Google_Service_Drive_TeamDrive
*/
public function getTeamDrive()
{
return $this->teamDrive;
}
public function setTeamDriveId($teamDriveId)
{
$this->teamDriveId = $teamDriveId;
}
public function getTeamDriveId()
{
return $this->teamDriveId;
}
public function setTime($time)
{
$this->time = $time;
}
public function getTime()
{
return $this->time;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/DriveFileCapabilities.php 0000644 00000014236 15132770567 0026251 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_DriveFileCapabilities extends WPvivid_Google_Model
{
public $canAddChildren;
public $canChangeCopyRequiresWriterPermission;
public $canChangeViewersCanCopyContent;
public $canComment;
public $canCopy;
public $canDelete;
public $canDeleteChildren;
public $canDownload;
public $canEdit;
public $canListChildren;
public $canMoveChildrenOutOfTeamDrive;
public $canMoveChildrenWithinTeamDrive;
public $canMoveItemIntoTeamDrive;
public $canMoveItemOutOfTeamDrive;
public $canMoveItemWithinTeamDrive;
public $canMoveTeamDriveItem;
public $canReadRevisions;
public $canReadTeamDrive;
public $canRemoveChildren;
public $canRename;
public $canShare;
public $canTrash;
public $canTrashChildren;
public $canUntrash;
public function setCanAddChildren($canAddChildren)
{
$this->canAddChildren = $canAddChildren;
}
public function getCanAddChildren()
{
return $this->canAddChildren;
}
public function setCanChangeCopyRequiresWriterPermission($canChangeCopyRequiresWriterPermission)
{
$this->canChangeCopyRequiresWriterPermission = $canChangeCopyRequiresWriterPermission;
}
public function getCanChangeCopyRequiresWriterPermission()
{
return $this->canChangeCopyRequiresWriterPermission;
}
public function setCanChangeViewersCanCopyContent($canChangeViewersCanCopyContent)
{
$this->canChangeViewersCanCopyContent = $canChangeViewersCanCopyContent;
}
public function getCanChangeViewersCanCopyContent()
{
return $this->canChangeViewersCanCopyContent;
}
public function setCanComment($canComment)
{
$this->canComment = $canComment;
}
public function getCanComment()
{
return $this->canComment;
}
public function setCanCopy($canCopy)
{
$this->canCopy = $canCopy;
}
public function getCanCopy()
{
return $this->canCopy;
}
public function setCanDelete($canDelete)
{
$this->canDelete = $canDelete;
}
public function getCanDelete()
{
return $this->canDelete;
}
public function setCanDeleteChildren($canDeleteChildren)
{
$this->canDeleteChildren = $canDeleteChildren;
}
public function getCanDeleteChildren()
{
return $this->canDeleteChildren;
}
public function setCanDownload($canDownload)
{
$this->canDownload = $canDownload;
}
public function getCanDownload()
{
return $this->canDownload;
}
public function setCanEdit($canEdit)
{
$this->canEdit = $canEdit;
}
public function getCanEdit()
{
return $this->canEdit;
}
public function setCanListChildren($canListChildren)
{
$this->canListChildren = $canListChildren;
}
public function getCanListChildren()
{
return $this->canListChildren;
}
public function setCanMoveChildrenOutOfTeamDrive($canMoveChildrenOutOfTeamDrive)
{
$this->canMoveChildrenOutOfTeamDrive = $canMoveChildrenOutOfTeamDrive;
}
public function getCanMoveChildrenOutOfTeamDrive()
{
return $this->canMoveChildrenOutOfTeamDrive;
}
public function setCanMoveChildrenWithinTeamDrive($canMoveChildrenWithinTeamDrive)
{
$this->canMoveChildrenWithinTeamDrive = $canMoveChildrenWithinTeamDrive;
}
public function getCanMoveChildrenWithinTeamDrive()
{
return $this->canMoveChildrenWithinTeamDrive;
}
public function setCanMoveItemIntoTeamDrive($canMoveItemIntoTeamDrive)
{
$this->canMoveItemIntoTeamDrive = $canMoveItemIntoTeamDrive;
}
public function getCanMoveItemIntoTeamDrive()
{
return $this->canMoveItemIntoTeamDrive;
}
public function setCanMoveItemOutOfTeamDrive($canMoveItemOutOfTeamDrive)
{
$this->canMoveItemOutOfTeamDrive = $canMoveItemOutOfTeamDrive;
}
public function getCanMoveItemOutOfTeamDrive()
{
return $this->canMoveItemOutOfTeamDrive;
}
public function setCanMoveItemWithinTeamDrive($canMoveItemWithinTeamDrive)
{
$this->canMoveItemWithinTeamDrive = $canMoveItemWithinTeamDrive;
}
public function getCanMoveItemWithinTeamDrive()
{
return $this->canMoveItemWithinTeamDrive;
}
public function setCanMoveTeamDriveItem($canMoveTeamDriveItem)
{
$this->canMoveTeamDriveItem = $canMoveTeamDriveItem;
}
public function getCanMoveTeamDriveItem()
{
return $this->canMoveTeamDriveItem;
}
public function setCanReadRevisions($canReadRevisions)
{
$this->canReadRevisions = $canReadRevisions;
}
public function getCanReadRevisions()
{
return $this->canReadRevisions;
}
public function setCanReadTeamDrive($canReadTeamDrive)
{
$this->canReadTeamDrive = $canReadTeamDrive;
}
public function getCanReadTeamDrive()
{
return $this->canReadTeamDrive;
}
public function setCanRemoveChildren($canRemoveChildren)
{
$this->canRemoveChildren = $canRemoveChildren;
}
public function getCanRemoveChildren()
{
return $this->canRemoveChildren;
}
public function setCanRename($canRename)
{
$this->canRename = $canRename;
}
public function getCanRename()
{
return $this->canRename;
}
public function setCanShare($canShare)
{
$this->canShare = $canShare;
}
public function getCanShare()
{
return $this->canShare;
}
public function setCanTrash($canTrash)
{
$this->canTrash = $canTrash;
}
public function getCanTrash()
{
return $this->canTrash;
}
public function setCanTrashChildren($canTrashChildren)
{
$this->canTrashChildren = $canTrashChildren;
}
public function getCanTrashChildren()
{
return $this->canTrashChildren;
}
public function setCanUntrash($canUntrash)
{
$this->canUntrash = $canUntrash;
}
public function getCanUntrash()
{
return $this->canUntrash;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Permission.php 0000644 00000006257 15132770567 0024222 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_Permission extends WPvivid_Google_Collection
{
protected $collection_key = 'teamDrivePermissionDetails';
public $allowFileDiscovery;
public $deleted;
public $displayName;
public $domain;
public $emailAddress;
public $expirationTime;
public $id;
public $kind;
public $photoLink;
public $role;
protected $teamDrivePermissionDetailsType = 'WPvivid_Google_Service_Drive_PermissionTeamDrivePermissionDetails';
protected $teamDrivePermissionDetailsDataType = 'array';
public $type;
public function setAllowFileDiscovery($allowFileDiscovery)
{
$this->allowFileDiscovery = $allowFileDiscovery;
}
public function getAllowFileDiscovery()
{
return $this->allowFileDiscovery;
}
public function setDeleted($deleted)
{
$this->deleted = $deleted;
}
public function getDeleted()
{
return $this->deleted;
}
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
}
public function getDisplayName()
{
return $this->displayName;
}
public function setDomain($domain)
{
$this->domain = $domain;
}
public function getDomain()
{
return $this->domain;
}
public function setEmailAddress($emailAddress)
{
$this->emailAddress = $emailAddress;
}
public function getEmailAddress()
{
return $this->emailAddress;
}
public function setExpirationTime($expirationTime)
{
$this->expirationTime = $expirationTime;
}
public function getExpirationTime()
{
return $this->expirationTime;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setPhotoLink($photoLink)
{
$this->photoLink = $photoLink;
}
public function getPhotoLink()
{
return $this->photoLink;
}
public function setRole($role)
{
$this->role = $role;
}
public function getRole()
{
return $this->role;
}
/**
* @param WPvivid_Google_Service_Drive_PermissionTeamDrivePermissionDetails
*/
public function setTeamDrivePermissionDetails($teamDrivePermissionDetails)
{
$this->teamDrivePermissionDetails = $teamDrivePermissionDetails;
}
/**
* @return WPvivid_Google_Service_Drive_PermissionTeamDrivePermissionDetails
*/
public function getTeamDrivePermissionDetails()
{
return $this->teamDrivePermissionDetails;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Revision.php 0000644 00000006445 15132770567 0023667 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_Revision extends WPvivid_Google_Model
{
public $exportLinks;
public $id;
public $keepForever;
public $kind;
protected $lastModifyingUserType = 'WPvivid_Google_Service_Drive_User';
protected $lastModifyingUserDataType = '';
public $md5Checksum;
public $mimeType;
public $modifiedTime;
public $originalFilename;
public $publishAuto;
public $published;
public $publishedOutsideDomain;
public $size;
public function setExportLinks($exportLinks)
{
$this->exportLinks = $exportLinks;
}
public function getExportLinks()
{
return $this->exportLinks;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKeepForever($keepForever)
{
$this->keepForever = $keepForever;
}
public function getKeepForever()
{
return $this->keepForever;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
/**
* @param WPvivid_Google_Service_Drive_User
*/
public function setLastModifyingUser(WPvivid_Google_Service_Drive_User $lastModifyingUser)
{
$this->lastModifyingUser = $lastModifyingUser;
}
/**
* @return WPvivid_Google_Service_Drive_User
*/
public function getLastModifyingUser()
{
return $this->lastModifyingUser;
}
public function setMd5Checksum($md5Checksum)
{
$this->md5Checksum = $md5Checksum;
}
public function getMd5Checksum()
{
return $this->md5Checksum;
}
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
}
public function getMimeType()
{
return $this->mimeType;
}
public function setModifiedTime($modifiedTime)
{
$this->modifiedTime = $modifiedTime;
}
public function getModifiedTime()
{
return $this->modifiedTime;
}
public function setOriginalFilename($originalFilename)
{
$this->originalFilename = $originalFilename;
}
public function getOriginalFilename()
{
return $this->originalFilename;
}
public function setPublishAuto($publishAuto)
{
$this->publishAuto = $publishAuto;
}
public function getPublishAuto()
{
return $this->publishAuto;
}
public function setPublished($published)
{
$this->published = $published;
}
public function getPublished()
{
return $this->published;
}
public function setPublishedOutsideDomain($publishedOutsideDomain)
{
$this->publishedOutsideDomain = $publishedOutsideDomain;
}
public function getPublishedOutsideDomain()
{
return $this->publishedOutsideDomain;
}
public function setSize($size)
{
$this->size = $size;
}
public function getSize()
{
return $this->size;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/CommentQuotedFileContent.php 0000644 00000001763 15132770567 0027006 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_CommentQuotedFileContent extends WPvivid_Google_Model
{
public $mimeType;
public $value;
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
}
public function getMimeType()
{
return $this->mimeType;
}
public function setValue($value)
{
$this->value = $value;
}
public function getValue()
{
return $this->value;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/GeneratedIds.php 0000644 00000002174 15132770567 0024422 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_GeneratedIds extends WPvivid_Google_Collection
{
protected $collection_key = 'ids';
public $ids;
public $kind;
public $space;
public function setIds($ids)
{
$this->ids = $ids;
}
public function getIds()
{
return $this->ids;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setSpace($space)
{
$this->space = $space;
}
public function getSpace()
{
return $this->space;
}
}
lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/DriveFileImageMediaMetadataLocation.php 0000644 00000002304 15132770567 0030706 0 ustar 00 includes <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_DriveFileImageMediaMetadataLocation extends WPvivid_Google_Model
{
public $altitude;
public $latitude;
public $longitude;
public function setAltitude($altitude)
{
$this->altitude = $altitude;
}
public function getAltitude()
{
return $this->altitude;
}
public function setLatitude($latitude)
{
$this->latitude = $latitude;
}
public function getLatitude()
{
return $this->latitude;
}
public function setLongitude($longitude)
{
$this->longitude = $longitude;
}
public function getLongitude()
{
return $this->longitude;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/PermissionList.php 0000644 00000002726 15132770567 0025053 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_PermissionList extends WPvivid_Google_Collection
{
protected $collection_key = 'permissions';
public $kind;
public $nextPageToken;
protected $permissionsType = 'WPvivid_Google_Service_Drive_Permission';
protected $permissionsDataType = 'array';
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
/**
* @param WPvivid_Google_Service_Drive_Permission
*/
public function setPermissions($permissions)
{
$this->permissions = $permissions;
}
/**
* @return WPvivid_Google_Service_Drive_Permission
*/
public function getPermissions()
{
return $this->permissions;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/StartPageToken.php 0000644 00000002014 15132770567 0024750 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_StartPageToken extends WPvivid_Google_Model
{
public $kind;
public $startPageToken;
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setStartPageToken($startPageToken)
{
$this->startPageToken = $startPageToken;
}
public function getStartPageToken()
{
return $this->startPageToken;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/TeamDriveCapabilities.php 0000644 00000012226 15132770567 0026255 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_TeamDriveCapabilities extends WPvivid_Google_Model
{
public $canAddChildren;
public $canChangeCopyRequiresWriterPermissionRestriction;
public $canChangeDomainUsersOnlyRestriction;
public $canChangeTeamDriveBackground;
public $canChangeTeamMembersOnlyRestriction;
public $canComment;
public $canCopy;
public $canDeleteChildren;
public $canDeleteTeamDrive;
public $canDownload;
public $canEdit;
public $canListChildren;
public $canManageMembers;
public $canReadRevisions;
public $canRemoveChildren;
public $canRename;
public $canRenameTeamDrive;
public $canShare;
public $canTrashChildren;
public function setCanAddChildren($canAddChildren)
{
$this->canAddChildren = $canAddChildren;
}
public function getCanAddChildren()
{
return $this->canAddChildren;
}
public function setCanChangeCopyRequiresWriterPermissionRestriction($canChangeCopyRequiresWriterPermissionRestriction)
{
$this->canChangeCopyRequiresWriterPermissionRestriction = $canChangeCopyRequiresWriterPermissionRestriction;
}
public function getCanChangeCopyRequiresWriterPermissionRestriction()
{
return $this->canChangeCopyRequiresWriterPermissionRestriction;
}
public function setCanChangeDomainUsersOnlyRestriction($canChangeDomainUsersOnlyRestriction)
{
$this->canChangeDomainUsersOnlyRestriction = $canChangeDomainUsersOnlyRestriction;
}
public function getCanChangeDomainUsersOnlyRestriction()
{
return $this->canChangeDomainUsersOnlyRestriction;
}
public function setCanChangeTeamDriveBackground($canChangeTeamDriveBackground)
{
$this->canChangeTeamDriveBackground = $canChangeTeamDriveBackground;
}
public function getCanChangeTeamDriveBackground()
{
return $this->canChangeTeamDriveBackground;
}
public function setCanChangeTeamMembersOnlyRestriction($canChangeTeamMembersOnlyRestriction)
{
$this->canChangeTeamMembersOnlyRestriction = $canChangeTeamMembersOnlyRestriction;
}
public function getCanChangeTeamMembersOnlyRestriction()
{
return $this->canChangeTeamMembersOnlyRestriction;
}
public function setCanComment($canComment)
{
$this->canComment = $canComment;
}
public function getCanComment()
{
return $this->canComment;
}
public function setCanCopy($canCopy)
{
$this->canCopy = $canCopy;
}
public function getCanCopy()
{
return $this->canCopy;
}
public function setCanDeleteChildren($canDeleteChildren)
{
$this->canDeleteChildren = $canDeleteChildren;
}
public function getCanDeleteChildren()
{
return $this->canDeleteChildren;
}
public function setCanDeleteTeamDrive($canDeleteTeamDrive)
{
$this->canDeleteTeamDrive = $canDeleteTeamDrive;
}
public function getCanDeleteTeamDrive()
{
return $this->canDeleteTeamDrive;
}
public function setCanDownload($canDownload)
{
$this->canDownload = $canDownload;
}
public function getCanDownload()
{
return $this->canDownload;
}
public function setCanEdit($canEdit)
{
$this->canEdit = $canEdit;
}
public function getCanEdit()
{
return $this->canEdit;
}
public function setCanListChildren($canListChildren)
{
$this->canListChildren = $canListChildren;
}
public function getCanListChildren()
{
return $this->canListChildren;
}
public function setCanManageMembers($canManageMembers)
{
$this->canManageMembers = $canManageMembers;
}
public function getCanManageMembers()
{
return $this->canManageMembers;
}
public function setCanReadRevisions($canReadRevisions)
{
$this->canReadRevisions = $canReadRevisions;
}
public function getCanReadRevisions()
{
return $this->canReadRevisions;
}
public function setCanRemoveChildren($canRemoveChildren)
{
$this->canRemoveChildren = $canRemoveChildren;
}
public function getCanRemoveChildren()
{
return $this->canRemoveChildren;
}
public function setCanRename($canRename)
{
$this->canRename = $canRename;
}
public function getCanRename()
{
return $this->canRename;
}
public function setCanRenameTeamDrive($canRenameTeamDrive)
{
$this->canRenameTeamDrive = $canRenameTeamDrive;
}
public function getCanRenameTeamDrive()
{
return $this->canRenameTeamDrive;
}
public function setCanShare($canShare)
{
$this->canShare = $canShare;
}
public function getCanShare()
{
return $this->canShare;
}
public function setCanTrashChildren($canTrashChildren)
{
$this->canTrashChildren = $canTrashChildren;
}
public function getCanTrashChildren()
{
return $this->canTrashChildren;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/User.php 0000644 00000003252 15132770567 0023000 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_User extends WPvivid_Google_Model
{
public $displayName;
public $emailAddress;
public $kind;
public $me;
public $permissionId;
public $photoLink;
public function setDisplayName($displayName)
{
$this->displayName = $displayName;
}
public function getDisplayName()
{
return $this->displayName;
}
public function setEmailAddress($emailAddress)
{
$this->emailAddress = $emailAddress;
}
public function getEmailAddress()
{
return $this->emailAddress;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setMe($me)
{
$this->me = $me;
}
public function getMe()
{
return $this->me;
}
public function setPermissionId($permissionId)
{
$this->permissionId = $permissionId;
}
public function getPermissionId()
{
return $this->permissionId;
}
public function setPhotoLink($photoLink)
{
$this->photoLink = $photoLink;
}
public function getPhotoLink()
{
return $this->photoLink;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/TeamDriveRestrictions.php 0000644 00000003267 15132770567 0026361 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_TeamDriveRestrictions extends WPvivid_Google_Model
{
public $adminManagedRestrictions;
public $copyRequiresWriterPermission;
public $domainUsersOnly;
public $teamMembersOnly;
public function setAdminManagedRestrictions($adminManagedRestrictions)
{
$this->adminManagedRestrictions = $adminManagedRestrictions;
}
public function getAdminManagedRestrictions()
{
return $this->adminManagedRestrictions;
}
public function setCopyRequiresWriterPermission($copyRequiresWriterPermission)
{
$this->copyRequiresWriterPermission = $copyRequiresWriterPermission;
}
public function getCopyRequiresWriterPermission()
{
return $this->copyRequiresWriterPermission;
}
public function setDomainUsersOnly($domainUsersOnly)
{
$this->domainUsersOnly = $domainUsersOnly;
}
public function getDomainUsersOnly()
{
return $this->domainUsersOnly;
}
public function setTeamMembersOnly($teamMembersOnly)
{
$this->teamMembersOnly = $teamMembersOnly;
}
public function getTeamMembersOnly()
{
return $this->teamMembersOnly;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Channel.php 0000644 00000004345 15132770567 0023436 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_Channel extends WPvivid_Google_Model
{
public $address;
public $expiration;
public $id;
public $kind;
public $params;
public $payload;
public $resourceId;
public $resourceUri;
public $token;
public $type;
public function setAddress($address)
{
$this->address = $address;
}
public function getAddress()
{
return $this->address;
}
public function setExpiration($expiration)
{
$this->expiration = $expiration;
}
public function getExpiration()
{
return $this->expiration;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setParams($params)
{
$this->params = $params;
}
public function getParams()
{
return $this->params;
}
public function setPayload($payload)
{
$this->payload = $payload;
}
public function getPayload()
{
return $this->payload;
}
public function setResourceId($resourceId)
{
$this->resourceId = $resourceId;
}
public function getResourceId()
{
return $this->resourceId;
}
public function setResourceUri($resourceUri)
{
$this->resourceUri = $resourceUri;
}
public function getResourceUri()
{
return $this->resourceUri;
}
public function setToken($token)
{
$this->token = $token;
}
public function getToken()
{
return $this->token;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Resource/Changes.php 0000644 00000013453 15132770567 0025225 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "changes" collection of methods.
* Typical usage is:
* <code>
* $driveService = new Google_Service_Drive(...);
* $changes = $driveService->changes;
* </code>
*/
class WPvivid_Google_Service_Drive_Resource_Changes extends WPvivid_Google_Service_Resource
{
/**
* Gets the starting pageToken for listing future changes.
* (changes.getStartPageToken)
*
* @param array $optParams Optional parameters.
*
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @opt_param string teamDriveId The ID of the Team Drive for which the starting
* pageToken for listing future changes from that Team Drive will be returned.
* @return WPvivid_Google_Service_Drive_StartPageToken
*/
public function getStartPageToken($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('getStartPageToken', array($params), "WPvivid_Google_Service_Drive_StartPageToken");
}
/**
* Lists the changes for a user or Team Drive. (changes.listChanges)
*
* @param string $pageToken The token for continuing a previous list request on
* the next page. This should be set to the value of 'nextPageToken' from the
* previous response or to the response from the getStartPageToken method.
* @param array $optParams Optional parameters.
*
* @opt_param bool includeCorpusRemovals Whether changes should include the file
* resource if the file is still accessible by the user at the time of the
* request, even when a file was removed from the list of changes and there will
* be no further change entries for this file.
* @opt_param bool includeRemoved Whether to include changes indicating that
* items have been removed from the list of changes, for example by deletion or
* loss of access.
* @opt_param bool includeTeamDriveItems Whether Team Drive files or changes
* should be included in results.
* @opt_param int pageSize The maximum number of changes to return per page.
* @opt_param bool restrictToMyDrive Whether to restrict the results to changes
* inside the My Drive hierarchy. This omits changes to files such as those in
* the Application Data folder or shared files which have not been added to My
* Drive.
* @opt_param string spaces A comma-separated list of spaces to query within the
* user corpus. Supported values are 'drive', 'appDataFolder' and 'photos'.
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @opt_param string teamDriveId The Team Drive from which changes will be
* returned. If specified the change IDs will be reflective of the Team Drive;
* use the combined Team Drive ID and change ID as an identifier.
* @return WPvivid_Google_Service_Drive_ChangeList
*/
public function listChanges($pageToken, $optParams = array())
{
$params = array('pageToken' => $pageToken);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "WPvivid_Google_Service_Drive_ChangeList");
}
/**
* Subscribes to changes for a user. (changes.watch)
*
* @param string $pageToken The token for continuing a previous list request on
* the next page. This should be set to the value of 'nextPageToken' from the
* previous response or to the response from the getStartPageToken method.
* @param WPvivid_Google_Service_Drive_Channel $postBody
* @param array $optParams Optional parameters.
*
* @opt_param bool includeCorpusRemovals Whether changes should include the file
* resource if the file is still accessible by the user at the time of the
* request, even when a file was removed from the list of changes and there will
* be no further change entries for this file.
* @opt_param bool includeRemoved Whether to include changes indicating that
* items have been removed from the list of changes, for example by deletion or
* loss of access.
* @opt_param bool includeTeamDriveItems Whether Team Drive files or changes
* should be included in results.
* @opt_param int pageSize The maximum number of changes to return per page.
* @opt_param bool restrictToMyDrive Whether to restrict the results to changes
* inside the My Drive hierarchy. This omits changes to files such as those in
* the Application Data folder or shared files which have not been added to My
* Drive.
* @opt_param string spaces A comma-separated list of spaces to query within the
* user corpus. Supported values are 'drive', 'appDataFolder' and 'photos'.
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @opt_param string teamDriveId The Team Drive from which changes will be
* returned. If specified the change IDs will be reflective of the Team Drive;
* use the combined Team Drive ID and change ID as an identifier.
* @return WPvivid_Google_Service_Drive_Channel
*/
public function watch($pageToken, WPvivid_Google_Service_Drive_Channel $postBody, $optParams = array())
{
$params = array('pageToken' => $pageToken, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('watch', array($params), "WPvivid_Google_Service_Drive_Channel");
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Resource/Replies.php 0000644 00000010744 15132770567 0025260 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "replies" collection of methods.
* Typical usage is:
* <code>
* $driveService = new WPvivid_Google_Service_Drive(...);
* $replies = $driveService->replies;
* </code>
*/
class WPvivid_Google_Service_Drive_Resource_Replies extends WPvivid_Google_Service_Resource
{
/**
* Creates a new reply to a comment. (replies.create)
*
* @param string $fileId The ID of the file.
* @param string $commentId The ID of the comment.
* @param WPvivid_Google_Service_Drive_Reply $postBody
* @param array $optParams Optional parameters.
* @return WPvivid_Google_Service_Drive_Reply
*/
public function create($fileId, $commentId, WPvivid_Google_Service_Drive_Reply $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'commentId' => $commentId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "WPvivid_Google_Service_Drive_Reply");
}
/**
* Deletes a reply. (replies.delete)
*
* @param string $fileId The ID of the file.
* @param string $commentId The ID of the comment.
* @param string $replyId The ID of the reply.
* @param array $optParams Optional parameters.
*/
public function delete($fileId, $commentId, $replyId, $optParams = array())
{
$params = array('fileId' => $fileId, 'commentId' => $commentId, 'replyId' => $replyId);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Gets a reply by ID. (replies.get)
*
* @param string $fileId The ID of the file.
* @param string $commentId The ID of the comment.
* @param string $replyId The ID of the reply.
* @param array $optParams Optional parameters.
*
* @opt_param bool includeDeleted Whether to return deleted replies. Deleted
* replies will not include their original content.
* @return WPvivid_Google_Service_Drive_Reply
*/
public function get($fileId, $commentId, $replyId, $optParams = array())
{
$params = array('fileId' => $fileId, 'commentId' => $commentId, 'replyId' => $replyId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "WPvivid_Google_Service_Drive_Reply");
}
/**
* Lists a comment's replies. (replies.listReplies)
*
* @param string $fileId The ID of the file.
* @param string $commentId The ID of the comment.
* @param array $optParams Optional parameters.
*
* @opt_param bool includeDeleted Whether to include deleted replies. Deleted
* replies will not include their original content.
* @opt_param int pageSize The maximum number of replies to return per page.
* @opt_param string pageToken The token for continuing a previous list request
* on the next page. This should be set to the value of 'nextPageToken' from the
* previous response.
* @return WPvivid_Google_Service_Drive_ReplyList
*/
public function listReplies($fileId, $commentId, $optParams = array())
{
$params = array('fileId' => $fileId, 'commentId' => $commentId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "WPvivid_Google_Service_Drive_ReplyList");
}
/**
* Updates a reply with patch semantics. (replies.update)
*
* @param string $fileId The ID of the file.
* @param string $commentId The ID of the comment.
* @param string $replyId The ID of the reply.
* @param WPvivid_Google_Service_Drive_Reply $postBody
* @param array $optParams Optional parameters.
* @return WPvivid_Google_Service_Drive_Reply
*/
public function update($fileId, $commentId, $replyId, WPvivid_Google_Service_Drive_Reply $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'commentId' => $commentId, 'replyId' => $replyId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "WPvivid_Google_Service_Drive_Reply");
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Resource/Permissions.php 0000644 00000015261 15132770567 0026167 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "permissions" collection of methods.
* Typical usage is:
* <code>
* $driveService = new Google_Service_Drive(...);
* $permissions = $driveService->permissions;
* </code>
*/
class WPvivid_Google_Service_Drive_Resource_Permissions extends WPvivid_Google_Service_Resource
{
/**
* Creates a permission for a file or Team Drive. (permissions.create)
*
* @param string $fileId The ID of the file or Team Drive.
* @param WPvivid_Google_Service_Drive_Permission $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string emailMessage A plain text custom message to include in the
* notification email.
* @opt_param bool sendNotificationEmail Whether to send a notification email
* when sharing to users or groups. This defaults to true for users and groups,
* and is not allowed for other requests. It must not be disabled for ownership
* transfers.
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @opt_param bool transferOwnership Whether to transfer ownership to the
* specified user and downgrade the current owner to a writer. This parameter is
* required as an acknowledgement of the side effect.
* @opt_param bool useDomainAdminAccess Issue the request as a domain
* administrator; if set to true, then the requester will be granted access if
* they are an administrator of the domain to which the item belongs.
* @return WPvivid_Google_Service_Drive_Permission
*/
public function create($fileId, WPvivid_Google_Service_Drive_Permission $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "WPvivid_Google_Service_Drive_Permission");
}
/**
* Deletes a permission. (permissions.delete)
*
* @param string $fileId The ID of the file or Team Drive.
* @param string $permissionId The ID of the permission.
* @param array $optParams Optional parameters.
*
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @opt_param bool useDomainAdminAccess Issue the request as a domain
* administrator; if set to true, then the requester will be granted access if
* they are an administrator of the domain to which the item belongs.
*/
public function delete($fileId, $permissionId, $optParams = array())
{
$params = array('fileId' => $fileId, 'permissionId' => $permissionId);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Gets a permission by ID. (permissions.get)
*
* @param string $fileId The ID of the file.
* @param string $permissionId The ID of the permission.
* @param array $optParams Optional parameters.
*
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @opt_param bool useDomainAdminAccess Issue the request as a domain
* administrator; if set to true, then the requester will be granted access if
* they are an administrator of the domain to which the item belongs.
* @return WPvivid_Google_Service_Drive_Permission
*/
public function get($fileId, $permissionId, $optParams = array())
{
$params = array('fileId' => $fileId, 'permissionId' => $permissionId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "WPvivid_Google_Service_Drive_Permission");
}
/**
* Lists a file's or Team Drive's permissions. (permissions.listPermissions)
*
* @param string $fileId The ID of the file or Team Drive.
* @param array $optParams Optional parameters.
*
* @opt_param int pageSize The maximum number of permissions to return per page.
* When not set for files in a Team Drive, at most 100 results will be returned.
* When not set for files that are not in a Team Drive, the entire list will be
* returned.
* @opt_param string pageToken The token for continuing a previous list request
* on the next page. This should be set to the value of 'nextPageToken' from the
* previous response.
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @opt_param bool useDomainAdminAccess Issue the request as a domain
* administrator; if set to true, then the requester will be granted access if
* they are an administrator of the domain to which the item belongs.
* @return WPvivid_Google_Service_Drive_PermissionList
*/
public function listPermissions($fileId, $optParams = array())
{
$params = array('fileId' => $fileId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "WPvivid_Google_Service_Drive_PermissionList");
}
/**
* Updates a permission with patch semantics. (permissions.update)
*
* @param string $fileId The ID of the file or Team Drive.
* @param string $permissionId The ID of the permission.
* @param WPvivid_Google_Service_Drive_Permission $postBody
* @param array $optParams Optional parameters.
*
* @opt_param bool removeExpiration Whether to remove the expiration date.
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @opt_param bool transferOwnership Whether to transfer ownership to the
* specified user and downgrade the current owner to a writer. This parameter is
* required as an acknowledgement of the side effect.
* @opt_param bool useDomainAdminAccess Issue the request as a domain
* administrator; if set to true, then the requester will be granted access if
* they are an administrator of the domain to which the item belongs.
* @return WPvivid_Google_Service_Drive_Permission
*/
public function update($fileId, $permissionId, WPvivid_Google_Service_Drive_Permission $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'permissionId' => $permissionId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "WPvivid_Google_Service_Drive_Permission");
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Resource/Revisions.php 0000644 00000007111 15132770567 0025630 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "revisions" collection of methods.
* Typical usage is:
* <code>
* $driveService = new WPvivid_Google_Service_Drive(...);
* $revisions = $driveService->revisions;
* </code>
*/
class WPvivid_Google_Service_Drive_Resource_Revisions extends WPvivid_Google_Service_Resource
{
/**
* Permanently deletes a revision. This method is only applicable to files with
* binary content in Drive. (revisions.delete)
*
* @param string $fileId The ID of the file.
* @param string $revisionId The ID of the revision.
* @param array $optParams Optional parameters.
*/
public function delete($fileId, $revisionId, $optParams = array())
{
$params = array('fileId' => $fileId, 'revisionId' => $revisionId);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Gets a revision's metadata or content by ID. (revisions.get)
*
* @param string $fileId The ID of the file.
* @param string $revisionId The ID of the revision.
* @param array $optParams Optional parameters.
*
* @opt_param bool acknowledgeAbuse Whether the user is acknowledging the risk
* of downloading known malware or other abusive files. This is only applicable
* when alt=media.
* @return WPvivid_Google_Service_Drive_Revision
*/
public function get($fileId, $revisionId, $optParams = array())
{
$params = array('fileId' => $fileId, 'revisionId' => $revisionId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "WPvivid_Google_Service_Drive_Revision");
}
/**
* Lists a file's revisions. (revisions.listRevisions)
*
* @param string $fileId The ID of the file.
* @param array $optParams Optional parameters.
*
* @opt_param int pageSize The maximum number of revisions to return per page.
* @opt_param string pageToken The token for continuing a previous list request
* on the next page. This should be set to the value of 'nextPageToken' from the
* previous response.
* @return WPvivid_Google_Service_Drive_RevisionList
*/
public function listRevisions($fileId, $optParams = array())
{
$params = array('fileId' => $fileId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "WPvivid_Google_Service_Drive_RevisionList");
}
/**
* Updates a revision with patch semantics. (revisions.update)
*
* @param string $fileId The ID of the file.
* @param string $revisionId The ID of the revision.
* @param WPvivid_Google_Service_Drive_Revision $postBody
* @param array $optParams Optional parameters.
* @return WPvivid_Google_Service_Drive_Revision
*/
public function update($fileId, $revisionId, WPvivid_Google_Service_Drive_Revision $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'revisionId' => $revisionId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "WPvivid_Google_Service_Drive_Revision");
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Resource/Files.php 0000644 00000025715 15132770567 0024723 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "files" collection of methods.
* Typical usage is:
* <code>
* $driveService = new WPvivid_Google_Service_Drive(...);
* $files = $driveService->files;
* </code>
*/
class WPvivid_Google_Service_Drive_Resource_Files extends WPvivid_Google_Service_Resource
{
/**
* Creates a copy of a file and applies any requested updates with patch
* semantics. (files.copy)
*
* @param string $fileId The ID of the file.
* @param WPvivid_Google_Service_Drive_DriveFile $postBody
* @param array $optParams Optional parameters.
*
* @opt_param bool ignoreDefaultVisibility Whether to ignore the domain's
* default visibility settings for the created file. Domain administrators can
* choose to make all uploaded files visible to the domain by default; this
* parameter bypasses that behavior for the request. Permissions are still
* inherited from parent folders.
* @opt_param bool keepRevisionForever Whether to set the 'keepForever' field in
* the new head revision. This is only applicable to files with binary content
* in Drive.
* @opt_param string ocrLanguage A language hint for OCR processing during image
* import (ISO 639-1 code).
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @return WPvivid_Google_Service_Drive_DriveFile
*/
public function copy($fileId, WPvivid_Google_Service_Drive_DriveFile $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('copy', array($params), "WPvivid_Google_Service_Drive_DriveFile");
}
/**
* Creates a new file. (files.create)
*
* @param WPvivid_Google_Service_Drive_DriveFile $postBody
* @param array $optParams Optional parameters.
*
* @opt_param bool ignoreDefaultVisibility Whether to ignore the domain's
* default visibility settings for the created file. Domain administrators can
* choose to make all uploaded files visible to the domain by default; this
* parameter bypasses that behavior for the request. Permissions are still
* inherited from parent folders.
* @opt_param bool keepRevisionForever Whether to set the 'keepForever' field in
* the new head revision. This is only applicable to files with binary content
* in Drive.
* @opt_param string ocrLanguage A language hint for OCR processing during image
* import (ISO 639-1 code).
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @opt_param bool useContentAsIndexableText Whether to use the uploaded content
* as indexable text.
* @return WPvivid_Google_Service_Drive_DriveFile
*/
public function create(WPvivid_Google_Service_Drive_DriveFile $postBody, $optParams = array())
{
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "WPvivid_Google_Service_Drive_DriveFile");
}
/**
* Permanently deletes a file owned by the user without moving it to the trash.
* If the file belongs to a Team Drive the user must be an organizer on the
* parent. If the target is a folder, all descendants owned by the user are also
* deleted. (files.delete)
*
* @param string $fileId The ID of the file.
* @param array $optParams Optional parameters.
*
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
*/
public function delete($fileId, $optParams = array())
{
$params = array('fileId' => $fileId);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Permanently deletes all of the user's trashed files. (files.emptyTrash)
*
* @param array $optParams Optional parameters.
*/
public function emptyTrash($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('emptyTrash', array($params));
}
/**
* Exports a Google Doc to the requested MIME type and returns the exported
* content. Please note that the exported content is limited to 10MB.
* (files.export)
*
* @param string $fileId The ID of the file.
* @param string $mimeType The MIME type of the format requested for this
* export.
* @param array $optParams Optional parameters.
*/
public function export($fileId, $mimeType, $optParams = array())
{
$params = array('fileId' => $fileId, 'mimeType' => $mimeType);
$params = array_merge($params, $optParams);
return $this->call('export', array($params));
}
/**
* Generates a set of file IDs which can be provided in create requests.
* (files.generateIds)
*
* @param array $optParams Optional parameters.
*
* @opt_param int count The number of IDs to return.
* @opt_param string space The space in which the IDs can be used to create new
* files. Supported values are 'drive' and 'appDataFolder'.
* @return WPvivid_Google_Service_Drive_GeneratedIds
*/
public function generateIds($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('generateIds', array($params), "WPvivid_Google_Service_Drive_GeneratedIds");
}
/**
* Gets a file's metadata or content by ID. (files.get)
*
* @param string $fileId The ID of the file.
* @param array $optParams Optional parameters.
*
* @opt_param bool acknowledgeAbuse Whether the user is acknowledging the risk
* of downloading known malware or other abusive files. This is only applicable
* when alt=media.
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @return WPvivid_Google_Service_Drive_DriveFile
*/
public function get($fileId, $optParams = array())
{
$params = array('fileId' => $fileId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "WPvivid_Google_Service_Drive_DriveFile");
}
/**
* Lists or searches files. (files.listFiles)
*
* @param array $optParams Optional parameters.
*
* @opt_param string corpora Comma-separated list of bodies of items
* (files/documents) to which the query applies. Supported bodies are 'user',
* 'domain', 'teamDrive' and 'allTeamDrives'. 'allTeamDrives' must be combined
* with 'user'; all other values must be used in isolation. Prefer 'user' or
* 'teamDrive' to 'allTeamDrives' for efficiency.
* @opt_param string corpus The source of files to list. Deprecated: use
* 'corpora' instead.
* @opt_param bool includeTeamDriveItems Whether Team Drive items should be
* included in results.
* @opt_param string orderBy A comma-separated list of sort keys. Valid keys are
* 'createdTime', 'folder', 'modifiedByMeTime', 'modifiedTime', 'name',
* 'name_natural', 'quotaBytesUsed', 'recency', 'sharedWithMeTime', 'starred',
* and 'viewedByMeTime'. Each key sorts ascending by default, but may be
* reversed with the 'desc' modifier. Example usage:
* ?orderBy=folder,modifiedTime desc,name. Please note that there is a current
* limitation for users with approximately one million files in which the
* requested sort order is ignored.
* @opt_param int pageSize The maximum number of files to return per page.
* Partial or empty result pages are possible even before the end of the files
* list has been reached.
* @opt_param string pageToken The token for continuing a previous list request
* on the next page. This should be set to the value of 'nextPageToken' from the
* previous response.
* @opt_param string q A query for filtering the file results. See the "Search
* for Files" guide for supported syntax.
* @opt_param string spaces A comma-separated list of spaces to query within the
* corpus. Supported values are 'drive', 'appDataFolder' and 'photos'.
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @opt_param string teamDriveId ID of Team Drive to search.
* @return WPvivid_Google_Service_Drive_FileList
*/
public function listFiles($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "WPvivid_Google_Service_Drive_FileList");
}
/**
* Updates a file's metadata and/or content with patch semantics. (files.update)
*
* @param string $fileId The ID of the file.
* @param WPvivid_Google_Service_Drive_DriveFile $postBody
* @param array $optParams Optional parameters.
*
* @opt_param string addParents A comma-separated list of parent IDs to add.
* @opt_param bool keepRevisionForever Whether to set the 'keepForever' field in
* the new head revision. This is only applicable to files with binary content
* in Drive.
* @opt_param string ocrLanguage A language hint for OCR processing during image
* import (ISO 639-1 code).
* @opt_param string removeParents A comma-separated list of parent IDs to
* remove.
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @opt_param bool useContentAsIndexableText Whether to use the uploaded content
* as indexable text.
* @return WPvivid_Google_Service_Drive_DriveFile
*/
public function update($fileId, WPvivid_Google_Service_Drive_DriveFile $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "WPvivid_Google_Service_Drive_DriveFile");
}
/**
* Subscribes to changes to a file (files.watch)
*
* @param string $fileId The ID of the file.
* @param WPvivid_Google_Service_Drive_Channel $postBody
* @param array $optParams Optional parameters.
*
* @opt_param bool acknowledgeAbuse Whether the user is acknowledging the risk
* of downloading known malware or other abusive files. This is only applicable
* when alt=media.
* @opt_param bool supportsTeamDrives Whether the requesting application
* supports Team Drives.
* @return WPvivid_Google_Service_Drive_Channel
*/
public function watch($fileId, WPvivid_Google_Service_Drive_Channel $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('watch', array($params), "WPvivid_Google_Service_Drive_Channel");
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Resource/Comments.php 0000644 00000010341 15132770567 0025433 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "comments" collection of methods.
* Typical usage is:
* <code>
* $driveService = new WPvivid_Google_Service_Drive(...);
* $comments = $driveService->comments;
* </code>
*/
class WPvivid_Google_Service_Drive_Resource_Comments extends WPvivid_Google_Service_Resource
{
/**
* Creates a new comment on a file. (comments.create)
*
* @param string $fileId The ID of the file.
* @param WPvivid_Google_Service_Drive_Comment $postBody
* @param array $optParams Optional parameters.
* @return WPvivid_Google_Service_Drive_Comment
*/
public function create($fileId, WPvivid_Google_Service_Drive_Comment $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "WPvivid_Google_Service_Drive_Comment");
}
/**
* Deletes a comment. (comments.delete)
*
* @param string $fileId The ID of the file.
* @param string $commentId The ID of the comment.
* @param array $optParams Optional parameters.
*/
public function delete($fileId, $commentId, $optParams = array())
{
$params = array('fileId' => $fileId, 'commentId' => $commentId);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Gets a comment by ID. (comments.get)
*
* @param string $fileId The ID of the file.
* @param string $commentId The ID of the comment.
* @param array $optParams Optional parameters.
*
* @opt_param bool includeDeleted Whether to return deleted comments. Deleted
* comments will not include their original content.
* @return WPvivid_Google_Service_Drive_Comment
*/
public function get($fileId, $commentId, $optParams = array())
{
$params = array('fileId' => $fileId, 'commentId' => $commentId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "WPvivid_Google_Service_Drive_Comment");
}
/**
* Lists a file's comments. (comments.listComments)
*
* @param string $fileId The ID of the file.
* @param array $optParams Optional parameters.
*
* @opt_param bool includeDeleted Whether to include deleted comments. Deleted
* comments will not include their original content.
* @opt_param int pageSize The maximum number of comments to return per page.
* @opt_param string pageToken The token for continuing a previous list request
* on the next page. This should be set to the value of 'nextPageToken' from the
* previous response.
* @opt_param string startModifiedTime The minimum value of 'modifiedTime' for
* the result comments (RFC 3339 date-time).
* @return WPvivid_Google_Service_Drive_CommentList
*/
public function listComments($fileId, $optParams = array())
{
$params = array('fileId' => $fileId);
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "WPvivid_Google_Service_Drive_CommentList");
}
/**
* Updates a comment with patch semantics. (comments.update)
*
* @param string $fileId The ID of the file.
* @param string $commentId The ID of the comment.
* @param WPvivid_Google_Service_Drive_Comment $postBody
* @param array $optParams Optional parameters.
* @return WPvivid_Google_Service_Drive_Comment
*/
public function update($fileId, $commentId, WPvivid_Google_Service_Drive_Comment $postBody, $optParams = array())
{
$params = array('fileId' => $fileId, 'commentId' => $commentId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "WPvivid_Google_Service_Drive_Comment");
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Resource/About.php 0000644 00000002413 15132770567 0024721 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "about" collection of methods.
* Typical usage is:
* <code>
* $driveService = new Google_Service_Drive(...);
* $about = $driveService->about;
* </code>
*/
class WPvivid_Google_Service_Drive_Resource_About extends WPvivid_Google_Service_Resource
{
/**
* Gets information about the user, the user's Drive, and system capabilities.
* (about.get)
*
* @param array $optParams Optional parameters.
* @return WPvivid_Google_Service_Drive_About
*/
public function get($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "WPvivid_Google_Service_Drive_About");
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Resource/Teamdrives.php 0000644 00000011176 15132770567 0025760 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "teamdrives" collection of methods.
* Typical usage is:
* <code>
* $driveService = new WPvivid_Google_Service_Drive(...);
* $teamdrives = $driveService->teamdrives;
* </code>
*/
class WPvivid_Google_Service_Drive_Resource_Teamdrives extends WPvivid_Google_Service_Resource
{
/**
* Creates a new Team Drive. (teamdrives.create)
*
* @param string $requestId An ID, such as a random UUID, which uniquely
* identifies this user's request for idempotent creation of a Team Drive. A
* repeated request by the same user and with the same request ID will avoid
* creating duplicates by attempting to create the same Team Drive. If the Team
* Drive already exists a 409 error will be returned.
* @param WPvivid_Google_Service_Drive_TeamDrive $postBody
* @param array $optParams Optional parameters.
* @return WPvivid_Google_Service_Drive_TeamDrive
*/
public function create($requestId, WPvivid_Google_Service_Drive_TeamDrive $postBody, $optParams = array())
{
$params = array('requestId' => $requestId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('create', array($params), "WPvivid_Google_Service_Drive_TeamDrive");
}
/**
* Permanently deletes a Team Drive for which the user is an organizer. The Team
* Drive cannot contain any untrashed items. (teamdrives.delete)
*
* @param string $teamDriveId The ID of the Team Drive
* @param array $optParams Optional parameters.
*/
public function delete($teamDriveId, $optParams = array())
{
$params = array('teamDriveId' => $teamDriveId);
$params = array_merge($params, $optParams);
return $this->call('delete', array($params));
}
/**
* Gets a Team Drive's metadata by ID. (teamdrives.get)
*
* @param string $teamDriveId The ID of the Team Drive
* @param array $optParams Optional parameters.
*
* @opt_param bool useDomainAdminAccess Issue the request as a domain
* administrator; if set to true, then the requester will be granted access if
* they are an administrator of the domain to which the Team Drive belongs.
* @return WPvivid_Google_Service_Drive_TeamDrive
*/
public function get($teamDriveId, $optParams = array())
{
$params = array('teamDriveId' => $teamDriveId);
$params = array_merge($params, $optParams);
return $this->call('get', array($params), "WPvivid_Google_Service_Drive_TeamDrive");
}
/**
* Lists the user's Team Drives. (teamdrives.listTeamdrives)
*
* @param array $optParams Optional parameters.
*
* @opt_param int pageSize Maximum number of Team Drives to return.
* @opt_param string pageToken Page token for Team Drives.
* @opt_param string q Query string for searching Team Drives.
* @opt_param bool useDomainAdminAccess Issue the request as a domain
* administrator; if set to true, then all Team Drives of the domain in which
* the requester is an administrator are returned.
* @return WPvivid_Google_Service_Drive_TeamDriveList
*/
public function listTeamdrives($optParams = array())
{
$params = array();
$params = array_merge($params, $optParams);
return $this->call('list', array($params), "WPvivid_Google_Service_Drive_TeamDriveList");
}
/**
* Updates a Team Drive's metadata (teamdrives.update)
*
* @param string $teamDriveId The ID of the Team Drive
* @param WPvivid_Google_Service_Drive_TeamDrive $postBody
* @param array $optParams Optional parameters.
*
* @opt_param bool useDomainAdminAccess Issue the request as a domain
* administrator; if set to true, then the requester will be granted access if
* they are an administrator of the domain to which the Team Drive belongs.
* @return WPvivid_Google_Service_Drive_TeamDrive
*/
public function update($teamDriveId, WPvivid_Google_Service_Drive_TeamDrive $postBody, $optParams = array())
{
$params = array('teamDriveId' => $teamDriveId, 'postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('update', array($params), "WPvivid_Google_Service_Drive_TeamDrive");
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Resource/Channels.php 0000644 00000002455 15132770567 0025410 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* The "channels" collection of methods.
* Typical usage is:
* <code>
* $driveService = new WPvivid_Google_Service_Drive(...);
* $channels = $driveService->channels;
* </code>
*/
class WPvivid_Google_Service_Drive_Resource_Channels extends WPvivid_Google_Service_Resource
{
/**
* Stop watching resources through this channel (channels.stop)
*
* @param WPvivid_Google_Service_Drive_Channel $postBody
* @param array $optParams Optional parameters.
*/
public function stop(WPvivid_Google_Service_Drive_Channel $postBody, $optParams = array())
{
$params = array('postBody' => $postBody);
$params = array_merge($params, $optParams);
return $this->call('stop', array($params));
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/AboutStorageQuota.php 0000644 00000002606 15132770567 0025475 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_AboutStorageQuota extends WPvivid_Google_Model
{
public $limit;
public $usage;
public $usageInDrive;
public $usageInDriveTrash;
public function setLimit($limit)
{
$this->limit = $limit;
}
public function getLimit()
{
return $this->limit;
}
public function setUsage($usage)
{
$this->usage = $usage;
}
public function getUsage()
{
return $this->usage;
}
public function setUsageInDrive($usageInDrive)
{
$this->usageInDrive = $usageInDrive;
}
public function getUsageInDrive()
{
return $this->usageInDrive;
}
public function setUsageInDriveTrash($usageInDriveTrash)
{
$this->usageInDriveTrash = $usageInDriveTrash;
}
public function getUsageInDriveTrash()
{
return $this->usageInDriveTrash;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/DriveFileImageMediaMetadata.php0000644 00000011346 15132770567 0027302 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_DriveFileImageMediaMetadata extends WPvivid_Google_Model
{
public $aperture;
public $cameraMake;
public $cameraModel;
public $colorSpace;
public $exposureBias;
public $exposureMode;
public $exposureTime;
public $flashUsed;
public $focalLength;
public $height;
public $isoSpeed;
public $lens;
protected $locationType = 'WPvivid_Google_Service_Drive_DriveFileImageMediaMetadataLocation';
protected $locationDataType = '';
public $maxApertureValue;
public $meteringMode;
public $rotation;
public $sensor;
public $subjectDistance;
public $time;
public $whiteBalance;
public $width;
public function setAperture($aperture)
{
$this->aperture = $aperture;
}
public function getAperture()
{
return $this->aperture;
}
public function setCameraMake($cameraMake)
{
$this->cameraMake = $cameraMake;
}
public function getCameraMake()
{
return $this->cameraMake;
}
public function setCameraModel($cameraModel)
{
$this->cameraModel = $cameraModel;
}
public function getCameraModel()
{
return $this->cameraModel;
}
public function setColorSpace($colorSpace)
{
$this->colorSpace = $colorSpace;
}
public function getColorSpace()
{
return $this->colorSpace;
}
public function setExposureBias($exposureBias)
{
$this->exposureBias = $exposureBias;
}
public function getExposureBias()
{
return $this->exposureBias;
}
public function setExposureMode($exposureMode)
{
$this->exposureMode = $exposureMode;
}
public function getExposureMode()
{
return $this->exposureMode;
}
public function setExposureTime($exposureTime)
{
$this->exposureTime = $exposureTime;
}
public function getExposureTime()
{
return $this->exposureTime;
}
public function setFlashUsed($flashUsed)
{
$this->flashUsed = $flashUsed;
}
public function getFlashUsed()
{
return $this->flashUsed;
}
public function setFocalLength($focalLength)
{
$this->focalLength = $focalLength;
}
public function getFocalLength()
{
return $this->focalLength;
}
public function setHeight($height)
{
$this->height = $height;
}
public function getHeight()
{
return $this->height;
}
public function setIsoSpeed($isoSpeed)
{
$this->isoSpeed = $isoSpeed;
}
public function getIsoSpeed()
{
return $this->isoSpeed;
}
public function setLens($lens)
{
$this->lens = $lens;
}
public function getLens()
{
return $this->lens;
}
/**
* @param WPvivid_Google_Service_Drive_DriveFileImageMediaMetadataLocation
*/
public function setLocation(WPvivid_Google_Service_Drive_DriveFileImageMediaMetadataLocation $location)
{
$this->location = $location;
}
/**
* @return WPvivid_Google_Service_Drive_DriveFileImageMediaMetadataLocation
*/
public function getLocation()
{
return $this->location;
}
public function setMaxApertureValue($maxApertureValue)
{
$this->maxApertureValue = $maxApertureValue;
}
public function getMaxApertureValue()
{
return $this->maxApertureValue;
}
public function setMeteringMode($meteringMode)
{
$this->meteringMode = $meteringMode;
}
public function getMeteringMode()
{
return $this->meteringMode;
}
public function setRotation($rotation)
{
$this->rotation = $rotation;
}
public function getRotation()
{
return $this->rotation;
}
public function setSensor($sensor)
{
$this->sensor = $sensor;
}
public function getSensor()
{
return $this->sensor;
}
public function setSubjectDistance($subjectDistance)
{
$this->subjectDistance = $subjectDistance;
}
public function getSubjectDistance()
{
return $this->subjectDistance;
}
public function setTime($time)
{
$this->time = $time;
}
public function getTime()
{
return $this->time;
}
public function setWhiteBalance($whiteBalance)
{
$this->whiteBalance = $whiteBalance;
}
public function getWhiteBalance()
{
return $this->whiteBalance;
}
public function setWidth($width)
{
$this->width = $width;
}
public function getWidth()
{
return $this->width;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/RevisionList.php 0000644 00000002674 15132770567 0024523 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_RevisionList extends WPvivid_Google_Collection
{
protected $collection_key = 'revisions';
public $kind;
public $nextPageToken;
protected $revisionsType = 'WPvivid_Google_Service_Drive_Revision';
protected $revisionsDataType = 'array';
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
/**
* @param WPvivid_Google_Service_Drive_Revision
*/
public function setRevisions($revisions)
{
$this->revisions = $revisions;
}
/**
* @return WPvivid_Google_Service_Drive_Revision
*/
public function getRevisions()
{
return $this->revisions;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Comment.php 0000644 00000006713 15132770567 0023471 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_Comment extends WPvivid_Google_Collection
{
protected $collection_key = 'replies';
public $anchor;
protected $authorType = 'WPvivid_Google_Service_Drive_User';
protected $authorDataType = '';
public $content;
public $createdTime;
public $deleted;
public $htmlContent;
public $id;
public $kind;
public $modifiedTime;
protected $quotedFileContentType = 'WPvivid_Google_Service_Drive_CommentQuotedFileContent';
protected $quotedFileContentDataType = '';
protected $repliesType = 'WPvivid_Google_Service_Drive_Reply';
protected $repliesDataType = 'array';
public $resolved;
public function setAnchor($anchor)
{
$this->anchor = $anchor;
}
public function getAnchor()
{
return $this->anchor;
}
/**
* @param WPvivid_Google_Service_Drive_User
*/
public function setAuthor(WPvivid_Google_Service_Drive_User $author)
{
$this->author = $author;
}
/**
* @return WPvivid_Google_Service_Drive_User
*/
public function getAuthor()
{
return $this->author;
}
public function setContent($content)
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function setCreatedTime($createdTime)
{
$this->createdTime = $createdTime;
}
public function getCreatedTime()
{
return $this->createdTime;
}
public function setDeleted($deleted)
{
$this->deleted = $deleted;
}
public function getDeleted()
{
return $this->deleted;
}
public function setHtmlContent($htmlContent)
{
$this->htmlContent = $htmlContent;
}
public function getHtmlContent()
{
return $this->htmlContent;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setModifiedTime($modifiedTime)
{
$this->modifiedTime = $modifiedTime;
}
public function getModifiedTime()
{
return $this->modifiedTime;
}
/**
* @param WPvivid_Google_Service_Drive_CommentQuotedFileContent
*/
public function setQuotedFileContent(WPvivid_Google_Service_Drive_CommentQuotedFileContent $quotedFileContent)
{
$this->quotedFileContent = $quotedFileContent;
}
/**
* @return WPvivid_Google_Service_Drive_CommentQuotedFileContent
*/
public function getQuotedFileContent()
{
return $this->quotedFileContent;
}
/**
* @param WPvivid_Google_Service_Drive_Reply
*/
public function setReplies($replies)
{
$this->replies = $replies;
}
/**
* @return WPvivid_Google_Service_Drive_Reply
*/
public function getReplies()
{
return $this->replies;
}
public function setResolved($resolved)
{
$this->resolved = $resolved;
}
public function getResolved()
{
return $this->resolved;
}
}
lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/PermissionTeamDrivePermissionDetails.php0000644 00000002737 15132770567 0031322 0 ustar 00 includes <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_PermissionTeamDrivePermissionDetails extends WPvivid_Google_Model
{
public $inherited;
public $inheritedFrom;
public $role;
public $teamDrivePermissionType;
public function setInherited($inherited)
{
$this->inherited = $inherited;
}
public function getInherited()
{
return $this->inherited;
}
public function setInheritedFrom($inheritedFrom)
{
$this->inheritedFrom = $inheritedFrom;
}
public function getInheritedFrom()
{
return $this->inheritedFrom;
}
public function setRole($role)
{
$this->role = $role;
}
public function getRole()
{
return $this->role;
}
public function setTeamDrivePermissionType($teamDrivePermissionType)
{
$this->teamDrivePermissionType = $teamDrivePermissionType;
}
public function getTeamDrivePermissionType()
{
return $this->teamDrivePermissionType;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/About.php 0000644 00000007173 15132770567 0023142 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_About extends WPvivid_Google_Collection
{
protected $collection_key = 'teamDriveThemes';
public $appInstalled;
public $canCreateTeamDrives;
public $exportFormats;
public $folderColorPalette;
public $importFormats;
public $kind;
public $maxImportSizes;
public $maxUploadSize;
protected $storageQuotaType = 'WPvivid_Google_Service_Drive_AboutStorageQuota';
protected $storageQuotaDataType = '';
protected $teamDriveThemesType = 'WPvivid_Google_Service_Drive_AboutTeamDriveThemes';
protected $teamDriveThemesDataType = 'array';
protected $userType = 'WPvivid_Google_Service_Drive_User';
protected $userDataType = '';
public function setAppInstalled($appInstalled)
{
$this->appInstalled = $appInstalled;
}
public function getAppInstalled()
{
return $this->appInstalled;
}
public function setCanCreateTeamDrives($canCreateTeamDrives)
{
$this->canCreateTeamDrives = $canCreateTeamDrives;
}
public function getCanCreateTeamDrives()
{
return $this->canCreateTeamDrives;
}
public function setExportFormats($exportFormats)
{
$this->exportFormats = $exportFormats;
}
public function getExportFormats()
{
return $this->exportFormats;
}
public function setFolderColorPalette($folderColorPalette)
{
$this->folderColorPalette = $folderColorPalette;
}
public function getFolderColorPalette()
{
return $this->folderColorPalette;
}
public function setImportFormats($importFormats)
{
$this->importFormats = $importFormats;
}
public function getImportFormats()
{
return $this->importFormats;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setMaxImportSizes($maxImportSizes)
{
$this->maxImportSizes = $maxImportSizes;
}
public function getMaxImportSizes()
{
return $this->maxImportSizes;
}
public function setMaxUploadSize($maxUploadSize)
{
$this->maxUploadSize = $maxUploadSize;
}
public function getMaxUploadSize()
{
return $this->maxUploadSize;
}
/**
* @param WPvivid_Google_Service_Drive_AboutStorageQuota
*/
public function setStorageQuota(WPvivid_Google_Service_Drive_AboutStorageQuota $storageQuota)
{
$this->storageQuota = $storageQuota;
}
/**
* @return WPvivid_Google_Service_Drive_AboutStorageQuota
*/
public function getStorageQuota()
{
return $this->storageQuota;
}
/**
* @param WPvivid_Google_Service_Drive_AboutTeamDriveThemes
*/
public function setTeamDriveThemes($teamDriveThemes)
{
$this->teamDriveThemes = $teamDriveThemes;
}
/**
* @return WPvivid_Google_Service_Drive_AboutTeamDriveThemes
*/
public function getTeamDriveThemes()
{
return $this->teamDriveThemes;
}
/**
* @param WPvivid_Service_Drive_User
*/
public function setUser(WPvivid_Google_Service_Drive_User $user)
{
$this->user = $user;
}
/**
* @return WPvivid_Google_Service_Drive_User
*/
public function getUser()
{
return $this->user;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/ReplyList.php 0000644 00000002636 15132770567 0024016 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_ReplyList extends WPvivid_Google_Collection
{
protected $collection_key = 'replies';
public $kind;
public $nextPageToken;
protected $repliesType = 'WPvivid_Google_Service_Drive_Reply';
protected $repliesDataType = 'array';
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
/**
* @param WPvivid_Google_Service_Drive_Reply
*/
public function setReplies($replies)
{
$this->replies = $replies;
}
/**
* @return WPvivid_Google_Service_Drive_Reply
*/
public function getReplies()
{
return $this->replies;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/Reply.php 0000644 00000004527 15132770567 0023163 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_Reply extends WPvivid_Google_Model
{
public $action;
protected $authorType = 'WPvivid_Google_Service_Drive_User';
protected $authorDataType = '';
public $content;
public $createdTime;
public $deleted;
public $htmlContent;
public $id;
public $kind;
public $modifiedTime;
public function setAction($action)
{
$this->action = $action;
}
public function getAction()
{
return $this->action;
}
/**
* @param WPvivid_Google_Service_Drive_User
*/
public function setAuthor(WPvivid_Google_Service_Drive_User $author)
{
$this->author = $author;
}
/**
* @return WPvivid_Google_Service_Drive_User
*/
public function getAuthor()
{
return $this->author;
}
public function setContent($content)
{
$this->content = $content;
}
public function getContent()
{
return $this->content;
}
public function setCreatedTime($createdTime)
{
$this->createdTime = $createdTime;
}
public function getCreatedTime()
{
return $this->createdTime;
}
public function setDeleted($deleted)
{
$this->deleted = $deleted;
}
public function getDeleted()
{
return $this->deleted;
}
public function setHtmlContent($htmlContent)
{
$this->htmlContent = $htmlContent;
}
public function getHtmlContent()
{
return $this->htmlContent;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setModifiedTime($modifiedTime)
{
$this->modifiedTime = $modifiedTime;
}
public function getModifiedTime()
{
return $this->modifiedTime;
}
}
lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/DriveFileContentHintsThumbnail.php 0000644 00000001771 15132770567 0030065 0 ustar 00 includes <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_DriveFileContentHintsThumbnail extends WPvivid_Google_Model
{
public $image;
public $mimeType;
public function setImage($image)
{
$this->image = $image;
}
public function getImage()
{
return $this->image;
}
public function setMimeType($mimeType)
{
$this->mimeType = $mimeType;
}
public function getMimeType()
{
return $this->mimeType;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive/FileList.php 0000644 00000003212 15132770567 0023571 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class WPvivid_Google_Service_Drive_FileList extends WPvivid_Google_Collection
{
protected $collection_key = 'files';
protected $filesType = 'WPvivid_Google_Service_Drive_DriveFile';
protected $filesDataType = 'array';
public $incompleteSearch;
public $kind;
public $nextPageToken;
public $files;
/**
* @param WPvivid_Google_Service_Drive_DriveFile
*/
public function setFiles($files)
{
$this->files = $files;
}
/**
* @return WPvivid_Google_Service_Drive_DriveFile
*/
public function getFiles()
{
return $this->files;
}
public function setIncompleteSearch($incompleteSearch)
{
$this->incompleteSearch = $incompleteSearch;
}
public function getIncompleteSearch()
{
return $this->incompleteSearch;
}
public function setKind($kind)
{
$this->kind = $kind;
}
public function getKind()
{
return $this->kind;
}
public function setNextPageToken($nextPageToken)
{
$this->nextPageToken = $nextPageToken;
}
public function getNextPageToken()
{
return $this->nextPageToken;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service/Drive.php 0000644 00000076743 15132770567 0022101 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
/**
* Service definition for Drive (v3).
*
* <p>
* Manages files in Drive including uploading, downloading, searching, detecting
* changes, and updating sharing permissions.</p>
*
* <p>
* For more information about this service, see the API
* <a href="https://developers.google.com/drive/" target="_blank">Documentation</a>
* </p>
*
* @author Google, Inc.
*/
class WPvivid_Google_Service_Drive extends WPvivid_Google_Service
{
/** See, edit, create, and delete all of your Google Drive files. */
const DRIVE =
"https://www.googleapis.com/auth/drive";
/** View and manage its own configuration data in your Google Drive. */
const DRIVE_APPDATA =
"https://www.googleapis.com/auth/drive.appdata";
/** View and manage Google Drive files and folders that you have opened or created with this app. */
const DRIVE_FILE =
"https://www.googleapis.com/auth/drive.file";
/** View and manage metadata of files in your Google Drive. */
const DRIVE_METADATA =
"https://www.googleapis.com/auth/drive.metadata";
/** View metadata for files in your Google Drive. */
const DRIVE_METADATA_READONLY =
"https://www.googleapis.com/auth/drive.metadata.readonly";
/** View the photos, videos and albums in your Google Photos. */
const DRIVE_PHOTOS_READONLY =
"https://www.googleapis.com/auth/drive.photos.readonly";
/** See and download all your Google Drive files. */
const DRIVE_READONLY =
"https://www.googleapis.com/auth/drive.readonly";
/** Modify your Google Apps Script scripts' behavior. */
const DRIVE_SCRIPTS =
"https://www.googleapis.com/auth/drive.scripts";
public $about;
public $changes;
public $channels;
public $comments;
public $files;
public $permissions;
public $replies;
public $revisions;
public $teamdrives;
public $serviceName;
/**
* Constructs the internal representation of the Drive service.
*
* @param WPvivid_Google_Client $client
*/
public function __construct(WPvivid_Google_Client $client)
{
parent::__construct($client);
$this->rootUrl = 'https://www.googleapis.com/';
$this->servicePath = 'drive/v3/';
$this->version = 'v3';
$this->serviceName = 'drive';
$this->about = new WPvivid_Google_Service_Drive_Resource_About(
$this,
$this->serviceName,
'about',
array(
'methods' => array(
'get' => array(
'path' => 'about',
'httpMethod' => 'GET',
'parameters' => array(),
),
)
)
);
$this->changes = new WPvivid_Google_Service_Drive_Resource_Changes(
$this,
$this->serviceName,
'changes',
array(
'methods' => array(
'getStartPageToken' => array(
'path' => 'changes/startPageToken',
'httpMethod' => 'GET',
'parameters' => array(
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
'teamDriveId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'list' => array(
'path' => 'changes',
'httpMethod' => 'GET',
'parameters' => array(
'pageToken' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'includeCorpusRemovals' => array(
'location' => 'query',
'type' => 'boolean',
),
'includeRemoved' => array(
'location' => 'query',
'type' => 'boolean',
),
'includeTeamDriveItems' => array(
'location' => 'query',
'type' => 'boolean',
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'restrictToMyDrive' => array(
'location' => 'query',
'type' => 'boolean',
),
'spaces' => array(
'location' => 'query',
'type' => 'string',
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
'teamDriveId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'watch' => array(
'path' => 'changes/watch',
'httpMethod' => 'POST',
'parameters' => array(
'pageToken' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
'includeCorpusRemovals' => array(
'location' => 'query',
'type' => 'boolean',
),
'includeRemoved' => array(
'location' => 'query',
'type' => 'boolean',
),
'includeTeamDriveItems' => array(
'location' => 'query',
'type' => 'boolean',
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'restrictToMyDrive' => array(
'location' => 'query',
'type' => 'boolean',
),
'spaces' => array(
'location' => 'query',
'type' => 'string',
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
'teamDriveId' => array(
'location' => 'query',
'type' => 'string',
),
),
),
)
)
);
$this->channels = new WPvivid_Google_Service_Drive_Resource_Channels(
$this,
$this->serviceName,
'channels',
array(
'methods' => array(
'stop' => array(
'path' => 'channels/stop',
'httpMethod' => 'POST',
'parameters' => array(),
),
)
)
);
$this->comments = new WPvivid_Google_Service_Drive_Resource_Comments(
$this,
$this->serviceName,
'comments',
array(
'methods' => array(
'create' => array(
'path' => 'files/{fileId}/comments',
'httpMethod' => 'POST',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'delete' => array(
'path' => 'files/{fileId}/comments/{commentId}',
'httpMethod' => 'DELETE',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'commentId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'get' => array(
'path' => 'files/{fileId}/comments/{commentId}',
'httpMethod' => 'GET',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'commentId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'includeDeleted' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'files/{fileId}/comments',
'httpMethod' => 'GET',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'includeDeleted' => array(
'location' => 'query',
'type' => 'boolean',
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'startModifiedTime' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'files/{fileId}/comments/{commentId}',
'httpMethod' => 'PATCH',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'commentId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
$this->files = new WPvivid_Google_Service_Drive_Resource_Files(
$this,
$this->serviceName,
'files',
array(
'methods' => array(
'copy' => array(
'path' => 'files/{fileId}/copy',
'httpMethod' => 'POST',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'ignoreDefaultVisibility' => array(
'location' => 'query',
'type' => 'boolean',
),
'keepRevisionForever' => array(
'location' => 'query',
'type' => 'boolean',
),
'ocrLanguage' => array(
'location' => 'query',
'type' => 'string',
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'create' => array(
'path' => 'files',
'httpMethod' => 'POST',
'parameters' => array(
'ignoreDefaultVisibility' => array(
'location' => 'query',
'type' => 'boolean',
),
'keepRevisionForever' => array(
'location' => 'query',
'type' => 'boolean',
),
'ocrLanguage' => array(
'location' => 'query',
'type' => 'string',
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
'useContentAsIndexableText' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'delete' => array(
'path' => 'files/{fileId}',
'httpMethod' => 'DELETE',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'emptyTrash' => array(
'path' => 'files/trash',
'httpMethod' => 'DELETE',
'parameters' => array(),
),'export' => array(
'path' => 'files/{fileId}/export',
'httpMethod' => 'GET',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'mimeType' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'generateIds' => array(
'path' => 'files/generateIds',
'httpMethod' => 'GET',
'parameters' => array(
'count' => array(
'location' => 'query',
'type' => 'integer',
),
'space' => array(
'location' => 'query',
'type' => 'string',
),
),
),'get' => array(
'path' => 'files/{fileId}',
'httpMethod' => 'GET',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'acknowledgeAbuse' => array(
'location' => 'query',
'type' => 'boolean',
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'files',
'httpMethod' => 'GET',
'parameters' => array(
'corpora' => array(
'location' => 'query',
'type' => 'string',
),
'corpus' => array(
'location' => 'query',
'type' => 'string',
),
'includeTeamDriveItems' => array(
'location' => 'query',
'type' => 'boolean',
),
'orderBy' => array(
'location' => 'query',
'type' => 'string',
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'q' => array(
'location' => 'query',
'type' => 'string',
),
'spaces' => array(
'location' => 'query',
'type' => 'string',
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
'teamDriveId' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'files/{fileId}',
'httpMethod' => 'PATCH',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'addParents' => array(
'location' => 'query',
'type' => 'string',
),
'keepRevisionForever' => array(
'location' => 'query',
'type' => 'boolean',
),
'ocrLanguage' => array(
'location' => 'query',
'type' => 'string',
),
'removeParents' => array(
'location' => 'query',
'type' => 'string',
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
'useContentAsIndexableText' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'watch' => array(
'path' => 'files/{fileId}/watch',
'httpMethod' => 'POST',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'acknowledgeAbuse' => array(
'location' => 'query',
'type' => 'boolean',
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->permissions = new WPvivid_Google_Service_Drive_Resource_Permissions(
$this,
$this->serviceName,
'permissions',
array(
'methods' => array(
'create' => array(
'path' => 'files/{fileId}/permissions',
'httpMethod' => 'POST',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'emailMessage' => array(
'location' => 'query',
'type' => 'string',
),
'sendNotificationEmail' => array(
'location' => 'query',
'type' => 'boolean',
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
'transferOwnership' => array(
'location' => 'query',
'type' => 'boolean',
),
'useDomainAdminAccess' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'delete' => array(
'path' => 'files/{fileId}/permissions/{permissionId}',
'httpMethod' => 'DELETE',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'permissionId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
'useDomainAdminAccess' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'get' => array(
'path' => 'files/{fileId}/permissions/{permissionId}',
'httpMethod' => 'GET',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'permissionId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
'useDomainAdminAccess' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'files/{fileId}/permissions',
'httpMethod' => 'GET',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
'useDomainAdminAccess' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'update' => array(
'path' => 'files/{fileId}/permissions/{permissionId}',
'httpMethod' => 'PATCH',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'permissionId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'removeExpiration' => array(
'location' => 'query',
'type' => 'boolean',
),
'supportsTeamDrives' => array(
'location' => 'query',
'type' => 'boolean',
),
'transferOwnership' => array(
'location' => 'query',
'type' => 'boolean',
),
'useDomainAdminAccess' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
$this->replies = new WPvivid_Google_Service_Drive_Resource_Replies(
$this,
$this->serviceName,
'replies',
array(
'methods' => array(
'create' => array(
'path' => 'files/{fileId}/comments/{commentId}/replies',
'httpMethod' => 'POST',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'commentId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'delete' => array(
'path' => 'files/{fileId}/comments/{commentId}/replies/{replyId}',
'httpMethod' => 'DELETE',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'commentId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'replyId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'get' => array(
'path' => 'files/{fileId}/comments/{commentId}/replies/{replyId}',
'httpMethod' => 'GET',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'commentId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'replyId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'includeDeleted' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'files/{fileId}/comments/{commentId}/replies',
'httpMethod' => 'GET',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'commentId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'includeDeleted' => array(
'location' => 'query',
'type' => 'boolean',
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'files/{fileId}/comments/{commentId}/replies/{replyId}',
'httpMethod' => 'PATCH',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'commentId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'replyId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
$this->revisions = new WPvivid_Google_Service_Drive_Resource_Revisions(
$this,
$this->serviceName,
'revisions',
array(
'methods' => array(
'delete' => array(
'path' => 'files/{fileId}/revisions/{revisionId}',
'httpMethod' => 'DELETE',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'revisionId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'get' => array(
'path' => 'files/{fileId}/revisions/{revisionId}',
'httpMethod' => 'GET',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'revisionId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'acknowledgeAbuse' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'files/{fileId}/revisions',
'httpMethod' => 'GET',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
),
),'update' => array(
'path' => 'files/{fileId}/revisions/{revisionId}',
'httpMethod' => 'PATCH',
'parameters' => array(
'fileId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'revisionId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),
)
)
);
$this->teamdrives = new WPvivid_Google_Service_Drive_Resource_Teamdrives(
$this,
$this->serviceName,
'teamdrives',
array(
'methods' => array(
'create' => array(
'path' => 'teamdrives',
'httpMethod' => 'POST',
'parameters' => array(
'requestId' => array(
'location' => 'query',
'type' => 'string',
'required' => true,
),
),
),'delete' => array(
'path' => 'teamdrives/{teamDriveId}',
'httpMethod' => 'DELETE',
'parameters' => array(
'teamDriveId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
),
),'get' => array(
'path' => 'teamdrives/{teamDriveId}',
'httpMethod' => 'GET',
'parameters' => array(
'teamDriveId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'useDomainAdminAccess' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'list' => array(
'path' => 'teamdrives',
'httpMethod' => 'GET',
'parameters' => array(
'pageSize' => array(
'location' => 'query',
'type' => 'integer',
),
'pageToken' => array(
'location' => 'query',
'type' => 'string',
),
'q' => array(
'location' => 'query',
'type' => 'string',
),
'useDomainAdminAccess' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),'update' => array(
'path' => 'teamdrives/{teamDriveId}',
'httpMethod' => 'PATCH',
'parameters' => array(
'teamDriveId' => array(
'location' => 'path',
'type' => 'string',
'required' => true,
),
'useDomainAdminAccess' => array(
'location' => 'query',
'type' => 'boolean',
),
),
),
)
)
);
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Client.php 0000644 00000077164 15132770567 0020644 0 ustar 00 <?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGoogle\Auth\ApplicationDefaultCredentials;
use WPvividGoogle\Auth\Cache\MemoryCacheItemPool;
use WPvividGoogle\Auth\CredentialsLoader;
use WPvividGoogle\Auth\HttpHandler\HttpHandlerFactory;
use WPvividGoogle\Auth\OAuth2;
use WPvividGoogle\Auth\Credentials\ServiceAccountCredentials;
use WPvividGoogle\Auth\Credentials\UserRefreshCredentials;
use WPvividGuzzleHttp\Client;
use WPvividGuzzleHttp\ClientInterface;
use WPvividGuzzleHttp\Ring\Client\StreamHandler;
use WPvividPsr\Cache\CacheItemPoolInterface;
use WPvividPsr\Http\Message\RequestInterface;
use WPvividPsr\Log\LoggerInterface;
use WPvividMonolog\Logger;
use WPvividMonolog\Handler\StreamHandler as MonologStreamHandler;
use WPvividMonolog\Handler\SyslogHandler as MonologSyslogHandler;
/**
* The Google API Client
* https://github.com/google/google-api-php-client
*/
class WPvivid_Google_Client
{
const LIBVER = "2.2.2";
const USER_AGENT_SUFFIX = "google-api-php-client/";
const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
const OAUTH2_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token';
const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
const API_BASE_PATH = 'https://www.googleapis.com';
/**
* @var WPvividGoogle\Auth\OAuth2 $auth
*/
private $auth;
/**
* @var WPvividGuzzleHttp\ClientInterface $http
*/
private $http;
/**
* @var WPvividPsr\Cache\CacheItemPoolInterface $cache
*/
private $cache;
/**
* @var array access token
*/
private $token;
/**
* @var array $config
*/
private $config;
/**
* @var WPvividPsr\Log\LoggerInterface $logger
*/
private $logger;
/**
* @var boolean $deferExecution
*/
private $deferExecution = false;
/** @var array $scopes */
// Scopes requested by the client
protected $requestedScopes = [];
/**
* Construct the Google Client.
*
* @param array $config
*/
public function __construct(array $config = array())
{
$this->config = array_merge(
[
'application_name' => '',
// Don't change these unless you're working against a special development
// or testing environment.
'base_path' => self::API_BASE_PATH,
// https://developers.google.com/console
'client_id' => '',
'client_secret' => '',
'redirect_uri' => null,
'state' => null,
// Simple API access key, also from the API console. Ensure you get
// a Server key, and not a Browser key.
'developer_key' => '',
// For use with Google Cloud Platform
// fetch the ApplicationDefaultCredentials, if applicable
// @see https://developers.google.com/identity/protocols/application-default-credentials
'use_application_default_credentials' => false,
'signing_key' => null,
'signing_algorithm' => null,
'subject' => null,
// Other OAuth2 parameters.
'hd' => '',
'prompt' => '',
'openid.realm' => '',
'include_granted_scopes' => null,
'login_hint' => '',
'request_visible_actions' => '',
'access_type' => 'online',
'approval_prompt' => 'auto',
// Task Runner retry configuration
// @see WPvivid_Google_Task_Runner
'retry' => array(),
// cache config for downstream auth caching
'cache_config' => [],
// function to be called when an access token is fetched
// follows the signature function ($cacheKey, $accessToken)
'token_callback' => null,
// Service class used in WPvivid_Google_Client::verifyIdToken.
// Explicitly pass this in to avoid setting JWT::$leeway
'jwt' => null,
],
$config
);
}
/**
* Get a string containing the version of the library.
*
* @return string
*/
public function getLibraryVersion()
{
return self::LIBVER;
}
/**
* For backwards compatibility
* alias for fetchAccessTokenWithAuthCode
*
* @param $code string code from accounts.google.com
* @return array access token
* @deprecated
*/
public function authenticate($code)
{
return $this->fetchAccessTokenWithAuthCode($code);
}
/**
* Attempt to exchange a code for an valid authentication token.
* Helper wrapped around the OAuth 2.0 implementation.
*
* @param $code string code from accounts.google.com
* @return array access token
*/
public function fetchAccessTokenWithAuthCode($code)
{
if (strlen($code) == 0) {
throw new InvalidArgumentException("Invalid code");
}
$auth = $this->getOAuth2Service();
$auth->setCode($code);
$auth->setRedirectUri($this->getRedirectUri());
$httpHandler = HttpHandlerFactory::build($this->getHttpClient());
$creds = $auth->fetchAuthToken($httpHandler);
if ($creds && isset($creds['access_token'])) {
$creds['created'] = time();
$this->setAccessToken($creds);
}
return $creds;
}
/**
* For backwards compatibility
* alias for fetchAccessTokenWithAssertion
*
* @return array access token
* @deprecated
*/
public function refreshTokenWithAssertion()
{
return $this->fetchAccessTokenWithAssertion();
}
/**
* Fetches a fresh access token with a given assertion token.
* @param ClientInterface $authHttp optional.
* @return array access token
*/
public function fetchAccessTokenWithAssertion(ClientInterface $authHttp = null)
{
if (!$this->isUsingApplicationDefaultCredentials()) {
throw new DomainException(
'set the JSON service account credentials using'
. ' WPvivid_Client::setAuthConfig or set the path to your JSON file'
. ' with the "GOOGLE_APPLICATION_CREDENTIALS" environment variable'
. ' and call WPvivid_Google_Client::useApplicationDefaultCredentials to'
. ' refresh a token with assertion.'
);
}
$this->getLogger()->log(
'info',
'OAuth2 access token refresh with Signed JWT assertion grants.'
);
$credentials = $this->createApplicationDefaultCredentials();
$httpHandler = HttpHandlerFactory::build($authHttp);
$creds = $credentials->fetchAuthToken($httpHandler);
if ($creds && isset($creds['access_token'])) {
$creds['created'] = time();
$this->setAccessToken($creds);
}
return $creds;
}
/**
* For backwards compatibility
* alias for fetchAccessTokenWithRefreshToken
*
* @param string $refreshToken
* @return array access token
*/
public function refreshToken($refreshToken)
{
return $this->fetchAccessTokenWithRefreshToken($refreshToken);
}
/**
* Fetches a fresh OAuth 2.0 access token with the given refresh token.
* @param string $refreshToken
* @return array access token
*/
public function fetchAccessTokenWithRefreshToken($refreshToken = null)
{
if (null === $refreshToken) {
if (!isset($this->token['refresh_token'])) {
throw new LogicException(
'refresh token must be passed in or set as part of setAccessToken'
);
}
$refreshToken = $this->token['refresh_token'];
}
$this->getLogger()->info('OAuth2 access token refresh');
$auth = $this->getOAuth2Service();
$auth->setRefreshToken($refreshToken);
$httpHandler = HttpHandlerFactory::build($this->getHttpClient());
$creds = $auth->fetchAuthToken($httpHandler);
if ($creds && isset($creds['access_token'])) {
$creds['created'] = time();
if (!isset($creds['refresh_token'])) {
$creds['refresh_token'] = $refreshToken;
}
$this->setAccessToken($creds);
}
return $creds;
}
/**
* Create a URL to obtain user authorization.
* The authorization endpoint allows the user to first
* authenticate, and then grant/deny the access request.
* @param string|array $scope The scope is expressed as an array or list of space-delimited strings.
* @return string
*/
public function createAuthUrl($scope = null)
{
if (empty($scope)) {
$scope = $this->prepareScopes();
}
if (is_array($scope)) {
$scope = implode(' ', $scope);
}
// only accept one of prompt or approval_prompt
$approvalPrompt = $this->config['prompt']
? null
: $this->config['approval_prompt'];
// include_granted_scopes should be string "true", string "false", or null
$includeGrantedScopes = $this->config['include_granted_scopes'] === null
? null
: var_export($this->config['include_granted_scopes'], true);
$params = array_filter(
[
'access_type' => $this->config['access_type'],
'approval_prompt' => $approvalPrompt,
'hd' => $this->config['hd'],
'include_granted_scopes' => $includeGrantedScopes,
'login_hint' => $this->config['login_hint'],
'openid.realm' => $this->config['openid.realm'],
'prompt' => $this->config['prompt'],
'response_type' => 'code',
'scope' => $scope,
'state' => $this->config['state'],
]
);
// If the list of scopes contains plus.login, add request_visible_actions
// to auth URL.
$rva = $this->config['request_visible_actions'];
if (strlen($rva) > 0 && false !== strpos($scope, 'plus.login')) {
$params['request_visible_actions'] = $rva;
}
$auth = $this->getOAuth2Service();
return (string) $auth->buildFullAuthorizationUri($params);
}
/**
* Adds auth listeners to the HTTP client based on the credentials
* set in the Google API Client object
*
* @param WPvividGuzzleHttp\ClientInterface $http the http client object.
* @return WPvividGuzzleHttp\ClientInterface the http client object
*/
public function authorize(ClientInterface $http = null)
{
$credentials = null;
$token = null;
$scopes = null;
if (null === $http) {
$http = $this->getHttpClient();
}
// These conditionals represent the decision tree for authentication
// 1. Check for Application Default Credentials
// 2. Check for API Key
// 3a. Check for an Access Token
// 3b. If access token exists but is expired, try to refresh it
if ($this->isUsingApplicationDefaultCredentials()) {
$credentials = $this->createApplicationDefaultCredentials();
} elseif ($token = $this->getAccessToken()) {
$scopes = $this->prepareScopes();
// add refresh subscriber to request a new token
if (isset($token['refresh_token']) && $this->isAccessTokenExpired()) {
$credentials = $this->createUserRefreshCredentials(
$scopes,
$token['refresh_token']
);
}
}
$authHandler = $this->getAuthHandler();
if ($credentials) {
$callback = $this->config['token_callback'];
$http = $authHandler->attachCredentials($http, $credentials, $callback);
} elseif ($token) {
$http = $authHandler->attachToken($http, $token, (array) $scopes);
} elseif ($key = $this->config['developer_key']) {
$http = $authHandler->attachKey($http, $key);
}
return $http;
}
/**
* Set the configuration to use application default credentials for
* authentication
*
* @see https://developers.google.com/identity/protocols/application-default-credentials
* @param boolean $useAppCreds
*/
public function useApplicationDefaultCredentials($useAppCreds = true)
{
$this->config['use_application_default_credentials'] = $useAppCreds;
}
/**
* To prevent useApplicationDefaultCredentials from inappropriately being
* called in a conditional
*
* @see https://developers.google.com/identity/protocols/application-default-credentials
*/
public function isUsingApplicationDefaultCredentials()
{
return $this->config['use_application_default_credentials'];
}
/**
* @param string|array $token
* @throws InvalidArgumentException
*/
public function setAccessToken($token)
{
if (is_string($token)) {
if ($json = json_decode($token, true)) {
$token = $json;
} else {
// assume $token is just the token string
$token = array(
'access_token' => $token,
);
}
}
if ($token == null) {
throw new InvalidArgumentException('invalid json token');
}
if (!isset($token['access_token'])) {
throw new InvalidArgumentException("Invalid token format");
}
$this->token = $token;
}
public function getAccessToken()
{
return $this->token;
}
/**
* @return string|null
*/
public function getRefreshToken()
{
if (isset($this->token['refresh_token'])) {
return $this->token['refresh_token'];
}
return null;
}
/**
* Returns if the access_token is expired.
* @return bool Returns True if the access_token is expired.
*/
public function isAccessTokenExpired()
{
if (!$this->token) {
return true;
}
$created = 0;
if (isset($this->token['created'])) {
$created = $this->token['created'];
} elseif (isset($this->token['id_token'])) {
// check the ID token for "iat"
// signature verification is not required here, as we are just
// using this for convenience to save a round trip request
// to the Google API server
$idToken = $this->token['id_token'];
if (substr_count($idToken, '.') == 2) {
$parts = explode('.', $idToken);
$payload = json_decode(base64_decode($parts[1]), true);
if ($payload && isset($payload['iat'])) {
$created = $payload['iat'];
}
}
}
// If the token is set to expire in the next 30 seconds.
return ($created + ($this->token['expires_in'] - 30)) < time();
}
/**
* @deprecated See UPGRADING.md for more information
*/
public function getAuth()
{
throw new BadMethodCallException(
'This function no longer exists. See UPGRADING.md for more information'
);
}
/**
* @deprecated See UPGRADING.md for more information
*/
public function setAuth($auth)
{
throw new BadMethodCallException(
'This function no longer exists. See UPGRADING.md for more information'
);
}
/**
* Set the OAuth 2.0 Client ID.
* @param string $clientId
*/
public function setClientId($clientId)
{
$this->config['client_id'] = $clientId;
}
public function getClientId()
{
return $this->config['client_id'];
}
/**
* Set the OAuth 2.0 Client Secret.
* @param string $clientSecret
*/
public function setClientSecret($clientSecret)
{
$this->config['client_secret'] = $clientSecret;
}
public function getClientSecret()
{
return $this->config['client_secret'];
}
/**
* Set the OAuth 2.0 Redirect URI.
* @param string $redirectUri
*/
public function setRedirectUri($redirectUri)
{
$this->config['redirect_uri'] = $redirectUri;
}
public function getRedirectUri()
{
return $this->config['redirect_uri'];
}
/**
* Set OAuth 2.0 "state" parameter to achieve per-request customization.
* @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2
* @param string $state
*/
public function setState($state)
{
$this->config['state'] = $state;
}
/**
* @param string $accessType Possible values for access_type include:
* {@code "offline"} to request offline access from the user.
* {@code "online"} to request online access from the user.
*/
public function setAccessType($accessType)
{
$this->config['access_type'] = $accessType;
}
/**
* @param string $approvalPrompt Possible values for approval_prompt include:
* {@code "force"} to force the approval UI to appear.
* {@code "auto"} to request auto-approval when possible. (This is the default value)
*/
public function setApprovalPrompt($approvalPrompt)
{
$this->config['approval_prompt'] = $approvalPrompt;
}
/**
* Set the login hint, email address or sub id.
* @param string $loginHint
*/
public function setLoginHint($loginHint)
{
$this->config['login_hint'] = $loginHint;
}
/**
* Set the application name, this is included in the User-Agent HTTP header.
* @param string $applicationName
*/
public function setApplicationName($applicationName)
{
$this->config['application_name'] = $applicationName;
}
/**
* If 'plus.login' is included in the list of requested scopes, you can use
* this method to define types of app activities that your app will write.
* You can find a list of available types here:
* @link https://developers.google.com/+/api/moment-types
*
* @param array $requestVisibleActions Array of app activity types
*/
public function setRequestVisibleActions($requestVisibleActions)
{
if (is_array($requestVisibleActions)) {
$requestVisibleActions = implode(" ", $requestVisibleActions);
}
$this->config['request_visible_actions'] = $requestVisibleActions;
}
/**
* Set the developer key to use, these are obtained through the API Console.
* @see http://code.google.com/apis/console-help/#generatingdevkeys
* @param string $developerKey
*/
public function setDeveloperKey($developerKey)
{
$this->config['developer_key'] = $developerKey;
}
/**
* Set the hd (hosted domain) parameter streamlines the login process for
* Google Apps hosted accounts. By including the domain of the user, you
* restrict sign-in to accounts at that domain.
* @param $hd string - the domain to use.
*/
public function setHostedDomain($hd)
{
$this->config['hd'] = $hd;
}
/**
* Set the prompt hint. Valid values are none, consent and select_account.
* If no value is specified and the user has not previously authorized
* access, then the user is shown a consent screen.
* @param $prompt string
*/
public function setPrompt($prompt)
{
$this->config['prompt'] = $prompt;
}
/**
* openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth
* 2.0. It is used in OpenID 2.0 requests to signify the URL-space for which
* an authentication request is valid.
* @param $realm string - the URL-space to use.
*/
public function setOpenidRealm($realm)
{
$this->config['openid.realm'] = $realm;
}
/**
* If this is provided with the value true, and the authorization request is
* granted, the authorization will include any previous authorizations
* granted to this user/application combination for other scopes.
* @param $include boolean - the URL-space to use.
*/
public function setIncludeGrantedScopes($include)
{
$this->config['include_granted_scopes'] = $include;
}
/**
* sets function to be called when an access token is fetched
* @param callable $tokenCallback - function ($cacheKey, $accessToken)
*/
public function setTokenCallback(callable $tokenCallback)
{
$this->config['token_callback'] = $tokenCallback;
}
/**
* Revoke an OAuth2 access token or refresh token. This method will revoke the current access
* token, if a token isn't provided.
*
* @param string|null $token The token (access token or a refresh token) that should be revoked.
* @return boolean Returns True if the revocation was successful, otherwise False.
*/
public function revokeToken($token = null)
{
$tokenRevoker = new WPvivid_Google_AccessToken_Revoke(
$this->getHttpClient()
);
return $tokenRevoker->revokeToken($token ?: $this->getAccessToken());
}
/**
* Verify an id_token. This method will verify the current id_token, if one
* isn't provided.
*
* @throws LogicException
* @param string|null $idToken The token (id_token) that should be verified.
* @return array|false Returns the token payload as an array if the verification was
* successful, false otherwise.
*/
public function verifyIdToken($idToken = null)
{
$tokenVerifier = new WPvivid_Google_AccessToken_Verify(
$this->getHttpClient(),
$this->getCache(),
$this->config['jwt']
);
if (null === $idToken) {
$token = $this->getAccessToken();
if (!isset($token['id_token'])) {
throw new LogicException(
'id_token must be passed in or set as part of setAccessToken'
);
}
$idToken = $token['id_token'];
}
return $tokenVerifier->verifyIdToken(
$idToken,
$this->getClientId()
);
}
/**
* Set the scopes to be requested. Must be called before createAuthUrl().
* Will remove any previously configured scopes.
* @param array $scopes, ie: array('https://www.googleapis.com/auth/plus.login',
* 'https://www.googleapis.com/auth/moderator')
*/
public function setScopes($scopes)
{
$this->requestedScopes = array();
$this->addScope($scopes);
}
/**
* This functions adds a scope to be requested as part of the OAuth2.0 flow.
* Will append any scopes not previously requested to the scope parameter.
* A single string will be treated as a scope to request. An array of strings
* will each be appended.
* @param $scope_or_scopes string|array e.g. "profile"
*/
public function addScope($scope_or_scopes)
{
if (is_string($scope_or_scopes) && !in_array($scope_or_scopes, $this->requestedScopes)) {
$this->requestedScopes[] = $scope_or_scopes;
} else if (is_array($scope_or_scopes)) {
foreach ($scope_or_scopes as $scope) {
$this->addScope($scope);
}
}
}
/**
* Returns the list of scopes requested by the client
* @return array the list of scopes
*
*/
public function getScopes()
{
return $this->requestedScopes;
}
/**
* @return string|null
* @visible For Testing
*/
public function prepareScopes()
{
if (empty($this->requestedScopes)) {
return null;
}
return implode(' ', $this->requestedScopes);
}
/**
* Helper method to execute deferred HTTP requests.
*
* @param $request WPvividPsr\Http\Message\RequestInterface|WPvivid_Google_Http_Batch
* @throws WPvivid_Google_Exception
* @return array of the type of the expected class or Psr\Http\Message\ResponseInterface.
*/
public function execute(RequestInterface $request, $expectedClass = null)
{
$request = $request->withHeader(
'User-Agent',
$this->config['application_name']
. " " . self::USER_AGENT_SUFFIX
. $this->getLibraryVersion()
);
// call the authorize method
// this is where most of the grunt work is done
$http = $this->authorize();
return WPvivid_Google_Http_REST::execute($http, $request, $expectedClass, $this->config['retry']);
}
/**
* Declare whether batch calls should be used. This may increase throughput
* by making multiple requests in one connection.
*
* @param boolean $useBatch True if the batch support should
* be enabled. Defaults to False.
*/
public function setUseBatch($useBatch)
{
// This is actually an alias for setDefer.
$this->setDefer($useBatch);
}
/**
* Are we running in Google AppEngine?
* return bool
*/
public function isAppEngine()
{
return (isset($_SERVER['SERVER_SOFTWARE']) &&
strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== false);
}
public function setConfig($name, $value)
{
$this->config[$name] = $value;
}
public function getConfig($name, $default = null)
{
return isset($this->config[$name]) ? $this->config[$name] : $default;
}
/**
* For backwards compatibility
* alias for setAuthConfig
*
* @param string $file the configuration file
* @throws WPvivid_Google_Exception
* @deprecated
*/
public function setAuthConfigFile($file)
{
$this->setAuthConfig($file);
}
/**
* Set the auth config from new or deprecated JSON config.
* This structure should match the file downloaded from
* the "Download JSON" button on in the Google Developer
* Console.
* @param string|array $config the configuration json
* @throws WPvivid_Google_Exception
*/
public function setAuthConfig($config)
{
if (is_string($config)) {
if (!file_exists($config)) {
throw new InvalidArgumentException('file does not exist');
}
$json = file_get_contents($config);
if (!$config = json_decode($json, true)) {
throw new LogicException('invalid json for auth config');
}
}
$key = isset($config['installed']) ? 'installed' : 'web';
if (isset($config['type']) && $config['type'] == 'service_account') {
// application default credentials
$this->useApplicationDefaultCredentials();
// set the information from the config
$this->setClientId($config['client_id']);
$this->config['client_email'] = $config['client_email'];
$this->config['signing_key'] = $config['private_key'];
$this->config['signing_algorithm'] = 'HS256';
} elseif (isset($config[$key])) {
// old-style
$this->setClientId($config[$key]['client_id']);
$this->setClientSecret($config[$key]['client_secret']);
if (isset($config[$key]['redirect_uris'])) {
$this->setRedirectUri($config[$key]['redirect_uris'][0]);
}
} else {
// new-style
$this->setClientId($config['client_id']);
$this->setClientSecret($config['client_secret']);
if (isset($config['redirect_uris'])) {
$this->setRedirectUri($config['redirect_uris'][0]);
}
}
}
/**
* Use when the service account has been delegated domain wide access.
*
* @param string $subject an email address account to impersonate
*/
public function setSubject($subject)
{
$this->config['subject'] = $subject;
}
/**
* Declare whether making API calls should make the call immediately, or
* return a request which can be called with ->execute();
*
* @param boolean $defer True if calls should not be executed right away.
*/
public function setDefer($defer)
{
$this->deferExecution = $defer;
}
/**
* Whether or not to return raw requests
* @return boolean
*/
public function shouldDefer()
{
return $this->deferExecution;
}
/**
* @return WPvividGoogle\Auth\OAuth2 implementation
*/
public function getOAuth2Service()
{
if (!isset($this->auth)) {
$this->auth = $this->createOAuth2Service();
}
return $this->auth;
}
/**
* create a default google auth object
*/
protected function createOAuth2Service()
{
$auth = new OAuth2(
[
'clientId' => $this->getClientId(),
'clientSecret' => $this->getClientSecret(),
'authorizationUri' => self::OAUTH2_AUTH_URL,
'tokenCredentialUri' => self::OAUTH2_TOKEN_URI,
'redirectUri' => $this->getRedirectUri(),
'issuer' => $this->config['client_id'],
'signingKey' => $this->config['signing_key'],
'signingAlgorithm' => $this->config['signing_algorithm'],
]
);
return $auth;
}
/**
* Set the Cache object
* @param WPvividPsr\Cache\CacheItemPoolInterface $cache
*/
public function setCache(CacheItemPoolInterface $cache)
{
$this->cache = $cache;
}
/**
* @return WPvividPsr\Cache\CacheItemPoolInterface Cache implementation
*/
public function getCache()
{
if (!$this->cache) {
$this->cache = $this->createDefaultCache();
}
return $this->cache;
}
/**
* @param array $cacheConfig
*/
public function setCacheConfig(array $cacheConfig)
{
$this->config['cache_config'] = $cacheConfig;
}
/**
* Set the Logger object
* @param WPvividPsr\Log\LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* @return WPvividPsr\Log\LoggerInterface implementation
*/
public function getLogger()
{
if (!isset($this->logger)) {
$this->logger = $this->createDefaultLogger();
}
return $this->logger;
}
protected function createDefaultLogger()
{
$logger = new Logger('google-api-php-client');
if ($this->isAppEngine()) {
$handler = new MonologSyslogHandler('app', LOG_USER, Logger::NOTICE);
} else {
$handler = new MonologStreamHandler('php://stderr', Logger::NOTICE);
}
$logger->pushHandler($handler);
return $logger;
}
protected function createDefaultCache()
{
return new MemoryCacheItemPool;
}
/**
* Set the Http Client object
* @param WPvividGuzzleHttp\ClientInterface $http
*/
public function setHttpClient(ClientInterface $http)
{
$this->http = $http;
}
/**
* @return WPvividGuzzleHttp\ClientInterface implementation
*/
public function getHttpClient()
{
if (null === $this->http) {
$this->http = $this->createDefaultHttpClient();
}
return $this->http;
}
protected function createDefaultHttpClient()
{
$options = ['exceptions' => false];
$version = ClientInterface::VERSION;
if ('5' === $version[0]) {
$options = [
'base_url' => $this->config['base_path'],
'defaults' => $options,
];
if ($this->isAppEngine()) {
// set StreamHandler on AppEngine by default
$options['handler'] = new StreamHandler();
$options['defaults']['verify'] = '/etc/ca-certificates.crt';
}
} else {
// guzzle 6
$options['base_uri'] = $this->config['base_path'];
$options['verify'] = WPVIVID_PLUGIN_DIR.'/vendor/guzzle/guzzle/src/Guzzle/Http/Resources/cacert.pem';
}
return new WPvividGuzzleHttp\Client($options);
}
private function createApplicationDefaultCredentials()
{
$scopes = $this->prepareScopes();
$sub = $this->config['subject'];
$signingKey = $this->config['signing_key'];
// create credentials using values supplied in setAuthConfig
if ($signingKey) {
$serviceAccountCredentials = array(
'client_id' => $this->config['client_id'],
'client_email' => $this->config['client_email'],
'private_key' => $signingKey,
'type' => 'service_account',
);
$credentials = CredentialsLoader::makeCredentials($scopes, $serviceAccountCredentials);
} else {
$credentials = ApplicationDefaultCredentials::getCredentials($scopes);
}
// for service account domain-wide authority (impersonating a user)
// @see https://developers.google.com/identity/protocols/OAuth2ServiceAccount
if ($sub) {
if (!$credentials instanceof ServiceAccountCredentials) {
throw new DomainException('domain-wide authority requires service account credentials');
}
$credentials->setSub($sub);
}
return $credentials;
}
protected function getAuthHandler()
{
// Be very careful using the cache, as the underlying auth library's cache
// implementation is naive, and the cache keys do not account for user
// sessions.
//
// @see https://github.com/google/google-api-php-client/issues/821
return WPvivid_Google_AuthHandler_AuthHandlerFactory::build(
$this->getCache(),
$this->config['cache_config']
);
}
private function createUserRefreshCredentials($scope, $refreshToken)
{
$creds = array_filter(
array(
'client_id' => $this->getClientId(),
'client_secret' => $this->getClientSecret(),
'refresh_token' => $refreshToken,
)
);
return new UserRefreshCredentials($scope, $creds);
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Service.php 0000644 00000002471 15132770567 0021013 0 ustar 00 <?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class WPvivid_Google_Service
{
public $batchPath;
public $rootUrl;
public $version;
public $servicePath;
public $availableScopes;
public $resource;
private $client;
public function __construct(WPvivid_Google_Client $client)
{
$this->client = $client;
}
/**
* Return the associated WPvivid_Google_Client class.
* @return WPvivid_Google_Client
*/
public function getClient()
{
return $this->client;
}
/**
* Create a new HTTP Batch handler for this service
*
* @return WPvivid_Google_Http_Batch
*/
public function createBatch()
{
return new WPvivid_Google_Http_Batch(
$this->client,
false,
$this->rootUrl,
$this->batchPath
);
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Utils/UriTemplate.php 0000644 00000022357 15132770567 0022753 0 ustar 00 <?php
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Implementation of levels 1-3 of the URI Template spec.
* @see http://tools.ietf.org/html/rfc6570
*/
class WPvivid_Google_Utils_UriTemplate
{
const TYPE_MAP = "1";
const TYPE_LIST = "2";
const TYPE_SCALAR = "4";
/**
* @var $operators array
* These are valid at the start of a template block to
* modify the way in which the variables inside are
* processed.
*/
private $operators = array(
"+" => "reserved",
"/" => "segments",
"." => "dotprefix",
"#" => "fragment",
";" => "semicolon",
"?" => "form",
"&" => "continuation"
);
/**
* @var $reserved array
* These are the characters which should not be URL encoded in reserved
* strings.
*/
private $reserved = array(
"=", ",", "!", "@", "|", ":", "/", "?", "#",
"[", "]",'$', "&", "'", "(", ")", "*", "+", ";"
);
private $reservedEncoded = array(
"%3D", "%2C", "%21", "%40", "%7C", "%3A", "%2F", "%3F",
"%23", "%5B", "%5D", "%24", "%26", "%27", "%28", "%29",
"%2A", "%2B", "%3B"
);
public function parse($string, array $parameters)
{
return $this->resolveNextSection($string, $parameters);
}
/**
* This function finds the first matching {...} block and
* executes the replacement. It then calls itself to find
* subsequent blocks, if any.
*/
private function resolveNextSection($string, $parameters)
{
$start = strpos($string, "{");
if ($start === false) {
return $string;
}
$end = strpos($string, "}");
if ($end === false) {
return $string;
}
$string = $this->replace($string, $start, $end, $parameters);
return $this->resolveNextSection($string, $parameters);
}
private function replace($string, $start, $end, $parameters)
{
// We know a data block will have {} round it, so we can strip that.
$data = substr($string, $start + 1, $end - $start - 1);
// If the first character is one of the reserved operators, it effects
// the processing of the stream.
if (isset($this->operators[$data[0]])) {
$op = $this->operators[$data[0]];
$data = substr($data, 1);
$prefix = "";
$prefix_on_missing = false;
switch ($op) {
case "reserved":
// Reserved means certain characters should not be URL encoded
$data = $this->replaceVars($data, $parameters, ",", null, true);
break;
case "fragment":
// Comma separated with fragment prefix. Bare values only.
$prefix = "#";
$prefix_on_missing = true;
$data = $this->replaceVars($data, $parameters, ",", null, true);
break;
case "segments":
// Slash separated data. Bare values only.
$prefix = "/";
$data =$this->replaceVars($data, $parameters, "/");
break;
case "dotprefix":
// Dot separated data. Bare values only.
$prefix = ".";
$prefix_on_missing = true;
$data = $this->replaceVars($data, $parameters, ".");
break;
case "semicolon":
// Semicolon prefixed and separated. Uses the key name
$prefix = ";";
$data = $this->replaceVars($data, $parameters, ";", "=", false, true, false);
break;
case "form":
// Standard URL format. Uses the key name
$prefix = "?";
$data = $this->replaceVars($data, $parameters, "&", "=");
break;
case "continuation":
// Standard URL, but with leading ampersand. Uses key name.
$prefix = "&";
$data = $this->replaceVars($data, $parameters, "&", "=");
break;
}
// Add the initial prefix character if data is valid.
if ($data || ($data !== false && $prefix_on_missing)) {
$data = $prefix . $data;
}
} else {
// If no operator we replace with the defaults.
$data = $this->replaceVars($data, $parameters);
}
// This is chops out the {...} and replaces with the new section.
return substr($string, 0, $start) . $data . substr($string, $end + 1);
}
private function replaceVars(
$section,
$parameters,
$sep = ",",
$combine = null,
$reserved = false,
$tag_empty = false,
$combine_on_empty = true
) {
if (strpos($section, ",") === false) {
// If we only have a single value, we can immediately process.
return $this->combine(
$section,
$parameters,
$sep,
$combine,
$reserved,
$tag_empty,
$combine_on_empty
);
} else {
// If we have multiple values, we need to split and loop over them.
// Each is treated individually, then glued together with the
// separator character.
$vars = explode(",", $section);
return $this->combineList(
$vars,
$sep,
$parameters,
$combine,
$reserved,
false, // Never emit empty strings in multi-param replacements
$combine_on_empty
);
}
}
public function combine(
$key,
$parameters,
$sep,
$combine,
$reserved,
$tag_empty,
$combine_on_empty
) {
$length = false;
$explode = false;
$skip_final_combine = false;
$value = false;
// Check for length restriction.
if (strpos($key, ":") !== false) {
list($key, $length) = explode(":", $key);
}
// Check for explode parameter.
if ($key[strlen($key) - 1] == "*") {
$explode = true;
$key = substr($key, 0, -1);
$skip_final_combine = true;
}
// Define the list separator.
$list_sep = $explode ? $sep : ",";
if (isset($parameters[$key])) {
$data_type = $this->getDataType($parameters[$key]);
switch ($data_type) {
case self::TYPE_SCALAR:
$value = $this->getValue($parameters[$key], $length);
break;
case self::TYPE_LIST:
$values = array();
foreach ($parameters[$key] as $pkey => $pvalue) {
$pvalue = $this->getValue($pvalue, $length);
if ($combine && $explode) {
$values[$pkey] = $key . $combine . $pvalue;
} else {
$values[$pkey] = $pvalue;
}
}
$value = implode($list_sep, $values);
if ($value == '') {
return '';
}
break;
case self::TYPE_MAP:
$values = array();
foreach ($parameters[$key] as $pkey => $pvalue) {
$pvalue = $this->getValue($pvalue, $length);
if ($explode) {
$pkey = $this->getValue($pkey, $length);
$values[] = $pkey . "=" . $pvalue; // Explode triggers = combine.
} else {
$values[] = $pkey;
$values[] = $pvalue;
}
}
$value = implode($list_sep, $values);
if ($value == '') {
return false;
}
break;
}
} else if ($tag_empty) {
// If we are just indicating empty values with their key name, return that.
return $key;
} else {
// Otherwise we can skip this variable due to not being defined.
return false;
}
if ($reserved) {
$value = str_replace($this->reservedEncoded, $this->reserved, $value);
}
// If we do not need to include the key name, we just return the raw
// value.
if (!$combine || $skip_final_combine) {
return $value;
}
// Else we combine the key name: foo=bar, if value is not the empty string.
return $key . ($value != '' || $combine_on_empty ? $combine . $value : '');
}
/**
* Return the type of a passed in value
*/
private function getDataType($data)
{
if (is_array($data)) {
reset($data);
if (key($data) !== 0) {
return self::TYPE_MAP;
}
return self::TYPE_LIST;
}
return self::TYPE_SCALAR;
}
/**
* Utility function that merges multiple combine calls
* for multi-key templates.
*/
private function combineList(
$vars,
$sep,
$parameters,
$combine,
$reserved,
$tag_empty,
$combine_on_empty
) {
$ret = array();
foreach ($vars as $var) {
$response = $this->combine(
$var,
$parameters,
$sep,
$combine,
$reserved,
$tag_empty,
$combine_on_empty
);
if ($response === false) {
continue;
}
$ret[] = $response;
}
return implode($sep, $ret);
}
/**
* Utility function to encode and trim values
*/
private function getValue($value, $length)
{
if ($length) {
$value = substr($value, 0, $length);
}
$value = rawurlencode($value);
return $value;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/AccessToken/Verify.php 0000644 00000016550 15132770567 0023064 0 ustar 00 <?php
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use Firebase\JWT\ExpiredException as ExpiredExceptionV3;
use Firebase\JWT\SignatureInvalidException;
use WPvividGuzzleHttp\Client;
use WPvividGuzzleHttp\ClientInterface;
use WPvividPsr\Cache\CacheItemPoolInterface;
use WPvividGoogle\Auth\Cache\MemoryCacheItemPool;
use Stash\Driver\FileSystem;
use Stash\Pool;
/**
* Wrapper around Google Access Tokens which provides convenience functions
*
*/
class WPvivid_Google_AccessToken_Verify
{
const FEDERATED_SIGNON_CERT_URL = 'https://www.googleapis.com/oauth2/v3/certs';
const OAUTH2_ISSUER = 'accounts.google.com';
const OAUTH2_ISSUER_HTTPS = 'https://accounts.google.com';
/**
* @var WPvividGuzzleHttp\ClientInterface The http client
*/
private $http;
/**
* @var WPvividPsr\Cache\CacheItemPoolInterface cache class
*/
private $cache;
/**
* Instantiates the class, but does not initiate the login flow, leaving it
* to the discretion of the caller.
*/
public function __construct(
ClientInterface $http = null,
CacheItemPoolInterface $cache = null,
$jwt = null
) {
if (null === $http) {
$http = new Client();
}
if (null === $cache) {
$cache = new MemoryCacheItemPool;
}
$this->http = $http;
$this->cache = $cache;
$this->jwt = $jwt ?: $this->getJwtService();
}
/**
* Verifies an id token and returns the authenticated apiLoginTicket.
* Throws an exception if the id token is not valid.
* The audience parameter can be used to control which id tokens are
* accepted. By default, the id token must have been issued to this OAuth2 client.
*
* @param $audience
* @return array the token payload, if successful
*/
public function verifyIdToken($idToken, $audience = null)
{
if (empty($idToken)) {
throw new LogicException('id_token cannot be null');
}
// set phpseclib constants if applicable
$this->setPhpsecConstants();
// Check signature
$certs = $this->getFederatedSignOnCerts();
foreach ($certs as $cert) {
$bigIntClass = $this->getBigIntClass();
$rsaClass = $this->getRsaClass();
$modulus = new $bigIntClass($this->jwt->urlsafeB64Decode($cert['n']), 256);
$exponent = new $bigIntClass($this->jwt->urlsafeB64Decode($cert['e']), 256);
$rsa = new $rsaClass();
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
try {
$payload = $this->jwt->decode(
$idToken,
$rsa->getPublicKey(),
array('RS256')
);
if (property_exists($payload, 'aud')) {
if ($audience && $payload->aud != $audience) {
return false;
}
}
// support HTTP and HTTPS issuers
// @see https://developers.google.com/identity/sign-in/web/backend-auth
$issuers = array(self::OAUTH2_ISSUER, self::OAUTH2_ISSUER_HTTPS);
if (!isset($payload->iss) || !in_array($payload->iss, $issuers)) {
return false;
}
return (array) $payload;
} catch (ExpiredException $e) {
return false;
} catch (ExpiredExceptionV3 $e) {
return false;
} catch (SignatureInvalidException $e) {
// continue
} catch (DomainException $e) {
// continue
}
}
return false;
}
private function getCache()
{
return $this->cache;
}
/**
* Retrieve and cache a certificates file.
*
* @param $url string location
* @throws WPvivid_Google_Exception
* @return array certificates
*/
private function retrieveCertsFromLocation($url)
{
// If we're retrieving a local file, just grab it.
if (0 !== strpos($url, 'http')) {
if (!$file = file_get_contents($url)) {
throw new WPvivid_Google_Exception(
"Failed to retrieve verification certificates: '" .
esc_url($url) . "'."
);
}
return json_decode($file, true);
}
$response = $this->http->get($url);
if ($response->getStatusCode() == 200) {
return json_decode((string) $response->getBody(), true);
}
throw new WPvivid_Google_Exception(
sprintf(
'Failed to retrieve verification certificates: "%s".',
esc_html($response->getBody()->getContents())
),
esc_attr($response->getStatusCode())
);
}
// Gets federated sign-on certificates to use for verifying identity tokens.
// Returns certs as array structure, where keys are key ids, and values
// are PEM encoded certificates.
private function getFederatedSignOnCerts()
{
$certs = null;
if ($cache = $this->getCache()) {
$cacheItem = $cache->getItem('federated_signon_certs_v3');
$certs = $cacheItem->get();
}
if (!$certs) {
$certs = $this->retrieveCertsFromLocation(
self::FEDERATED_SIGNON_CERT_URL
);
if ($cache) {
$cacheItem->expiresAt(new DateTime('+1 hour'));
$cacheItem->set($certs);
$cache->save($cacheItem);
}
}
if (!isset($certs['keys'])) {
throw new InvalidArgumentException(
'federated sign-on certs expects "keys" to be set'
);
}
return $certs['keys'];
}
private function getJwtService()
{
$jwtClass = 'JWT';
if (class_exists('\Firebase\JWT\JWT')) {
$jwtClass = 'Firebase\JWT\JWT';
}
if (property_exists($jwtClass, 'leeway') && $jwtClass::$leeway < 1) {
// Ensures JWT leeway is at least 1
// @see https://github.com/google/google-api-php-client/issues/827
$jwtClass::$leeway = 1;
}
return new $jwtClass;
}
private function getRsaClass()
{
if (class_exists('phpseclib\Crypt\RSA')) {
return 'phpseclib\Crypt\RSA';
}
return 'Crypt_RSA';
}
private function getBigIntClass()
{
if (class_exists('phpseclib\Math\BigInteger')) {
return 'phpseclib\Math\BigInteger';
}
return 'Math_BigInteger';
}
private function getOpenSslConstant()
{
if (class_exists('phpseclib\Crypt\RSA')) {
return 'phpseclib\Crypt\RSA::MODE_OPENSSL';
}
if (class_exists('Crypt_RSA')) {
return 'CRYPT_RSA_MODE_OPENSSL';
}
throw new \Exception('Cannot find RSA class');
}
/**
* phpseclib calls "phpinfo" by default, which requires special
* whitelisting in the AppEngine VM environment. This function
* sets constants to bypass the need for phpseclib to check phpinfo
*
* @see phpseclib/Math/BigInteger
* @see https://github.com/GoogleCloudPlatform/getting-started-php/issues/85
*/
private function setPhpsecConstants()
{
if (filter_var(getenv('GAE_VM'), FILTER_VALIDATE_BOOLEAN)) {
if (!defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) {
define('MATH_BIGINTEGER_OPENSSL_ENABLED', true);
}
if (!defined('CRYPT_RSA_MODE')) {
define('CRYPT_RSA_MODE', constant($this->getOpenSslConstant()));
}
}
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/AccessToken/Revoke.php 0000644 00000004275 15132770567 0023054 0 ustar 00 <?php
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGoogle\Auth\HttpHandler\HttpHandlerFactory;
use WPvividGuzzleHttp\ClientInterface;
use WPvividGuzzleHttp\Psr7;
use WPvividGuzzleHttp\Psr7\Request;
/**
* Wrapper around Google Access Tokens which provides convenience functions
*
*/
class WPvivid_Google_AccessToken_Revoke
{
/**
* @var WPvividGuzzleHttp\ClientInterface The http client
*/
private $http;
/**
* Instantiates the class, but does not initiate the login flow, leaving it
* to the discretion of the caller.
*/
public function __construct(ClientInterface $http = null)
{
$this->http = $http;
}
/**
* Revoke an OAuth2 access token or refresh token. This method will revoke the current access
* token, if a token isn't provided.
*
* @param string|array $token The token (access token or a refresh token) that should be revoked.
* @return boolean Returns True if the revocation was successful, otherwise False.
*/
public function revokeToken($token)
{
if (is_array($token)) {
if (isset($token['refresh_token'])) {
$token = $token['refresh_token'];
} else {
$token = $token['access_token'];
}
}
$body = Psr7\stream_for(http_build_query(array('token' => $token)));
$request = new Request(
'POST',
WPvivid_Google_Client::OAUTH2_REVOKE_URI,
[
'Cache-Control' => 'no-store',
'Content-Type' => 'application/x-www-form-urlencoded',
],
$body
);
$httpHandler = HttpHandlerFactory::build($this->http);
$response = $httpHandler($request);
return $response->getStatusCode() == 200;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Task/Runner.php 0000644 00000016170 15132770567 0021567 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A task runner with exponential backoff support.
*
* @see https://developers.google.com/drive/web/handle-errors#implementing_exponential_backoff
*/
class WPvivid_Google_Task_Runner
{
const TASK_RETRY_NEVER = 0;
const TASK_RETRY_ONCE = 1;
const TASK_RETRY_ALWAYS = -1;
/**
* @var integer $maxDelay The max time (in seconds) to wait before a retry.
*/
private $maxDelay = 60;
/**
* @var integer $delay The previous delay from which the next is calculated.
*/
private $delay = 1;
/**
* @var integer $factor The base number for the exponential back off.
*/
private $factor = 2;
/**
* @var float $jitter A random number between -$jitter and $jitter will be
* added to $factor on each iteration to allow for a better distribution of
* retries.
*/
private $jitter = 0.5;
/**
* @var integer $attempts The number of attempts that have been tried so far.
*/
private $attempts = 0;
/**
* @var integer $maxAttempts The max number of attempts allowed.
*/
private $maxAttempts = 1;
/**
* @var callable $action The task to run and possibly retry.
*/
private $action;
/**
* @var array $arguments The task arguments.
*/
private $arguments;
/**
* @var array $retryMap Map of errors with retry counts.
*/
protected $retryMap = [
'500' => self::TASK_RETRY_ALWAYS,
'503' => self::TASK_RETRY_ALWAYS,
'rateLimitExceeded' => self::TASK_RETRY_ALWAYS,
'userRateLimitExceeded' => self::TASK_RETRY_ALWAYS,
6 => self::TASK_RETRY_ALWAYS, // CURLE_COULDNT_RESOLVE_HOST
7 => self::TASK_RETRY_ALWAYS, // CURLE_COULDNT_CONNECT
28 => self::TASK_RETRY_ALWAYS, // CURLE_OPERATION_TIMEOUTED
35 => self::TASK_RETRY_ALWAYS, // CURLE_SSL_CONNECT_ERROR
52 => self::TASK_RETRY_ALWAYS // CURLE_GOT_NOTHING
];
/**
* Creates a new task runner with exponential backoff support.
*
* @param array $config The task runner config
* @param string $name The name of the current task (used for logging)
* @param callable $action The task to run and possibly retry
* @param array $arguments The task arguments
* @throws WPvivid_Google_Task_Exception when misconfigured
*/
public function __construct(
$config,
$name,
$action,
array $arguments = array()
) {
if (isset($config['initial_delay'])) {
if ($config['initial_delay'] < 0) {
throw new WPvivid_Google_Task_Exception(
'Task configuration `initial_delay` must not be negative.'
);
}
$this->delay = $config['initial_delay'];
}
if (isset($config['max_delay'])) {
if ($config['max_delay'] <= 0) {
throw new WPvivid_Google_Task_Exception(
'Task configuration `max_delay` must be greater than 0.'
);
}
$this->maxDelay = $config['max_delay'];
}
if (isset($config['factor'])) {
if ($config['factor'] <= 0) {
throw new WPvivid_Google_Task_Exception(
'Task configuration `factor` must be greater than 0.'
);
}
$this->factor = $config['factor'];
}
if (isset($config['jitter'])) {
if ($config['jitter'] <= 0) {
throw new WPvivid_Google_Task_Exception(
'Task configuration `jitter` must be greater than 0.'
);
}
$this->jitter = $config['jitter'];
}
if (isset($config['retries'])) {
if ($config['retries'] < 0) {
throw new WPvivid_Google_Task_Exception(
'Task configuration `retries` must not be negative.'
);
}
$this->maxAttempts += $config['retries'];
}
if (!is_callable($action)) {
throw new WPvivid_Google_Task_Exception(
'Task argument `$action` must be a valid callable.'
);
}
$this->action = $action;
$this->arguments = $arguments;
}
/**
* Checks if a retry can be attempted.
*
* @return boolean
*/
public function canAttempt()
{
return $this->attempts < $this->maxAttempts;
}
/**
* Runs the task and (if applicable) automatically retries when errors occur.
*
* @return mixed
* @throws WPvivid_Google_Service_Exception on failure when no retries are available.
*/
public function run()
{
while ($this->attempt()) {
try {
return call_user_func_array($this->action, $this->arguments);
} catch (WPvivid_Google_Service_Exception $exception) {
$allowedRetries = $this->allowedRetries(
$exception->getCode(),
$exception->getErrors()
);
if (!$this->canAttempt() || !$allowedRetries) {
throw $exception;
}
if ($allowedRetries > 0) {
$this->maxAttempts = min(
$this->maxAttempts,
$this->attempts + $allowedRetries
);
}
}
}
}
/**
* Runs a task once, if possible. This is useful for bypassing the `run()`
* loop.
*
* NOTE: If this is not the first attempt, this function will sleep in
* accordance to the backoff configurations before running the task.
*
* @return boolean
*/
public function attempt()
{
if (!$this->canAttempt()) {
return false;
}
if ($this->attempts > 0) {
$this->backOff();
}
$this->attempts++;
return true;
}
/**
* Sleeps in accordance to the backoff configurations.
*/
private function backOff()
{
$delay = $this->getDelay();
usleep($delay * 1000000);
}
/**
* Gets the delay (in seconds) for the current backoff period.
*
* @return float
*/
private function getDelay()
{
$jitter = $this->getJitter();
$factor = $this->attempts > 1 ? $this->factor + $jitter : 1 + abs($jitter);
return $this->delay = min($this->maxDelay, $this->delay * $factor);
}
/**
* Gets the current jitter (random number between -$this->jitter and
* $this->jitter).
*
* @return float
*/
private function getJitter()
{
return $this->jitter * 2 * mt_rand() / mt_getrandmax() - $this->jitter;
}
/**
* Gets the number of times the associated task can be retried.
*
* NOTE: -1 is returned if the task can be retried indefinitely
*
* @return integer
*/
public function allowedRetries($code, $errors = array())
{
if (isset($this->retryMap[$code])) {
return $this->retryMap[$code];
}
if (
!empty($errors) &&
isset($errors[0]['reason'], $this->retryMap[$errors[0]['reason']])
) {
return $this->retryMap[$errors[0]['reason']];
}
return 0;
}
public function setRetryMap($retryMap)
{
$this->retryMap = $retryMap;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Task/Retryable.php 0000644 00000001353 15132770567 0022244 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Interface for checking how many times a given task can be retried following
* a failure.
*/
interface WPvivid_Google_Task_Retryable
{
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Task/Exception.php 0000644 00000001243 15132770567 0022247 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class WPvivid_Google_Task_Exception extends WPvivid_Google_Exception
{
}
includes/lib2/google-api-php-client/src/WPvivid/Google/AuthHandler/AuthHandlerFactory.php 0000644 00000002573 15132770567 0025344 0 ustar 00 <?php
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGuzzleHttp\Client;
use WPvividGuzzleHttp\ClientInterface;
class WPvivid_Google_AuthHandler_AuthHandlerFactory
{
/**
* Builds out a default http handler for the installed version of guzzle.
*
* @return WPvivid_Google_AuthHandler_Guzzle5AuthHandler|WPvivid_Google_AuthHandler_Guzzle6AuthHandler
* @throws Exception
*/
public static function build($cache = null, array $cacheConfig = [])
{
$version = ClientInterface::VERSION;
switch ($version[0]) {
case '5':
return new WPvivid_Google_AuthHandler_Guzzle5AuthHandler($cache, $cacheConfig);
case '6':
return new WPvivid_Google_AuthHandler_Guzzle6AuthHandler($cache, $cacheConfig);
default:
throw new Exception('Version not supported');
}
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/AuthHandler/Guzzle5AuthHandler.php 0000644 00000005060 15132770567 0025274 0 ustar 00 <?php
use WPvividGoogle\Auth\CredentialsLoader;
use WPvividGoogle\Auth\HttpHandler\HttpHandlerFactory;
use WPvividGoogle\Auth\FetchAuthTokenCache;
use WPvividGoogle\Auth\Subscriber\AuthTokenSubscriber;
use WPvividGoogle\Auth\Subscriber\ScopedAccessTokenSubscriber;
use WPvividGoogle\Auth\Subscriber\SimpleSubscriber;
use WPvividGuzzleHttp\Client;
use WPvividGuzzleHttp\ClientInterface;
use WPvividPsr\Cache\CacheItemPoolInterface;
/**
*
*/
class WPvivid_Google_AuthHandler_Guzzle5AuthHandler
{
protected $cache;
protected $cacheConfig;
public function __construct(CacheItemPoolInterface $cache = null, array $cacheConfig = [])
{
$this->cache = $cache;
$this->cacheConfig = $cacheConfig;
}
public function attachCredentials(
ClientInterface $http,
CredentialsLoader $credentials,
callable $tokenCallback = null
) {
// use the provided cache
if ($this->cache) {
$credentials = new FetchAuthTokenCache(
$credentials,
$this->cacheConfig,
$this->cache
);
}
// if we end up needing to make an HTTP request to retrieve credentials, we
// can use our existing one, but we need to throw exceptions so the error
// bubbles up.
$authHttp = $this->createAuthHttp($http);
$authHttpHandler = HttpHandlerFactory::build($authHttp);
$subscriber = new AuthTokenSubscriber(
$credentials,
$authHttpHandler,
$tokenCallback
);
$http->setDefaultOption('auth', 'google_auth');
$http->getEmitter()->attach($subscriber);
return $http;
}
public function attachToken(ClientInterface $http, array $token, array $scopes)
{
$tokenFunc = function ($scopes) use ($token) {
return $token['access_token'];
};
$subscriber = new ScopedAccessTokenSubscriber(
$tokenFunc,
$scopes,
$this->cacheConfig,
$this->cache
);
$http->setDefaultOption('auth', 'scoped');
$http->getEmitter()->attach($subscriber);
return $http;
}
public function attachKey(ClientInterface $http, $key)
{
$subscriber = new SimpleSubscriber(['key' => $key]);
$http->setDefaultOption('auth', 'simple');
$http->getEmitter()->attach($subscriber);
return $http;
}
private function createAuthHttp(ClientInterface $http)
{
return new Client(
[
'base_url' => $http->getBaseUrl(),
'defaults' => [
'exceptions' => true,
'verify' => $http->getDefaultOption('verify'),
'proxy' => $http->getDefaultOption('proxy'),
]
]
);
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/AuthHandler/Guzzle6AuthHandler.php 0000644 00000005514 15132770567 0025301 0 ustar 00 <?php
use WPvividGoogle\Auth\CredentialsLoader;
use WPvividGoogle\Auth\HttpHandler\HttpHandlerFactory;
use WPvividGoogle\Auth\FetchAuthTokenCache;
use WPvividGoogle\Auth\Middleware\AuthTokenMiddleware;
use WPvividGoogle\Auth\Middleware\ScopedAccessTokenMiddleware;
use WPvividGoogle\Auth\Middleware\SimpleMiddleware;
use WPvividGuzzleHttp\Client;
use WPvividGuzzleHttp\ClientInterface;
use WPvividPsr\Cache\CacheItemPoolInterface;
/**
*
*/
class WPvivid_Google_AuthHandler_Guzzle6AuthHandler
{
protected $cache;
protected $cacheConfig;
public function __construct(CacheItemPoolInterface $cache = null, array $cacheConfig = [])
{
$this->cache = $cache;
$this->cacheConfig = $cacheConfig;
}
public function attachCredentials(
ClientInterface $http,
CredentialsLoader $credentials,
callable $tokenCallback = null
) {
// use the provided cache
if ($this->cache) {
$credentials = new FetchAuthTokenCache(
$credentials,
$this->cacheConfig,
$this->cache
);
}
// if we end up needing to make an HTTP request to retrieve credentials, we
// can use our existing one, but we need to throw exceptions so the error
// bubbles up.
$authHttp = $this->createAuthHttp($http);
$authHttpHandler = HttpHandlerFactory::build($authHttp);
$middleware = new AuthTokenMiddleware(
$credentials,
$authHttpHandler,
$tokenCallback
);
$config = $http->getConfig();
$config['handler']->remove('google_auth');
$config['handler']->push($middleware, 'google_auth');
$config['auth'] = 'google_auth';
$http = new Client($config);
return $http;
}
public function attachToken(ClientInterface $http, array $token, array $scopes)
{
$tokenFunc = function ($scopes) use ($token) {
return $token['access_token'];
};
$middleware = new ScopedAccessTokenMiddleware(
$tokenFunc,
$scopes,
$this->cacheConfig,
$this->cache
);
$config = $http->getConfig();
$config['handler']->remove('google_auth');
$config['handler']->push($middleware, 'google_auth');
$config['auth'] = 'scoped';
$http = new Client($config);
return $http;
}
public function attachKey(ClientInterface $http, $key)
{
$middleware = new SimpleMiddleware(['key' => $key]);
$config = $http->getConfig();
$config['handler']->remove('google_auth');
$config['handler']->push($middleware, 'google_auth');
$config['auth'] = 'simple';
$http = new Client($config);
return $http;
}
private function createAuthHttp(ClientInterface $http)
{
return new Client(
[
'base_uri' => $http->getConfig('base_uri'),
'exceptions' => true,
'verify' => $http->getConfig('verify'),
'proxy' => $http->getConfig('proxy'),
]
);
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Model.php 0000644 00000021371 15132770567 0020453 0 ustar 00 <?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This class defines attributes, valid values, and usage which is generated
* from a given json schema.
* http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5
*
*/
class WPvivid_Google_Model implements ArrayAccess
{
/**
* If you need to specify a NULL JSON value, use WPvivid_Google_Model::NULL_VALUE
* instead - it will be replaced when converting to JSON with a real null.
*/
const NULL_VALUE = "{}gapi-php-null";
protected $internal_gapi_mappings = array();
protected $modelData = array();
protected $processed = array();
/**
* Polymorphic - accepts a variable number of arguments dependent
* on the type of the model subclass.
*/
final public function __construct()
{
if (func_num_args() == 1 && is_array(func_get_arg(0))) {
// Initialize the model with the array's contents.
$array = func_get_arg(0);
$this->mapTypes($array);
}
$this->gapiInit();
}
/**
* Getter that handles passthrough access to the data array, and lazy object creation.
* @param string $key Property name.
* @return mixed The value if any, or null.
*/
public function __get($key)
{
$keyType = $this->keyType($key);
$keyDataType = $this->dataType($key);
if ($keyType && !isset($this->processed[$key])) {
if (isset($this->modelData[$key])) {
$val = $this->modelData[$key];
} elseif ($keyDataType == 'array' || $keyDataType == 'map') {
$val = array();
} else {
$val = null;
}
if ($this->isAssociativeArray($val)) {
if ($keyDataType && 'map' == $keyDataType) {
foreach ($val as $arrayKey => $arrayItem) {
$this->modelData[$key][$arrayKey] =
new $keyType($arrayItem);
}
} else {
$this->modelData[$key] = new $keyType($val);
}
} else if (is_array($val)) {
$arrayObject = array();
foreach ($val as $arrayIndex => $arrayItem) {
$arrayObject[$arrayIndex] = new $keyType($arrayItem);
}
$this->modelData[$key] = $arrayObject;
}
$this->processed[$key] = true;
}
return isset($this->modelData[$key]) ? $this->modelData[$key] : null;
}
/**
* Initialize this object's properties from an array.
*
* @param array $array Used to seed this object's properties.
* @return void
*/
protected function mapTypes($array)
{
// Hard initialise simple types, lazy load more complex ones.
foreach ($array as $key => $val) {
if ($keyType = $this->keyType($key)) {
$dataType = $this->dataType($key);
if ($dataType == 'array' || $dataType == 'map') {
$this->$key = array();
foreach ($val as $itemKey => $itemVal) {
if ($itemVal instanceof $keyType) {
$this->{$key}[$itemKey] = $itemVal;
} else {
$this->{$key}[$itemKey] = new $keyType($itemVal);
}
}
} elseif ($val instanceof $keyType) {
$this->$key = $val;
} else {
$this->$key = new $keyType($val);
}
unset($array[$key]);
} elseif (property_exists($this, $key)) {
$this->$key = $val;
unset($array[$key]);
} elseif (property_exists($this, $camelKey = $this->camelCase($key))) {
// This checks if property exists as camelCase, leaving it in array as snake_case
// in case of backwards compatibility issues.
$this->$camelKey = $val;
}
}
$this->modelData = $array;
}
/**
* Blank initialiser to be used in subclasses to do post-construction initialisation - this
* avoids the need for subclasses to have to implement the variadics handling in their
* constructors.
*/
protected function gapiInit()
{
return;
}
/**
* Create a simplified object suitable for straightforward
* conversion to JSON. This is relatively expensive
* due to the usage of reflection, but shouldn't be called
* a whole lot, and is the most straightforward way to filter.
*/
public function toSimpleObject()
{
$object = new stdClass();
// Process all other data.
foreach ($this->modelData as $key => $val) {
$result = $this->getSimpleValue($val);
if ($result !== null) {
$object->$key = $this->nullPlaceholderCheck($result);
}
}
// Process all public properties.
$reflect = new ReflectionObject($this);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($props as $member) {
$name = $member->getName();
$result = $this->getSimpleValue($this->$name);
if ($result !== null) {
$name = $this->getMappedName($name);
$object->$name = $this->nullPlaceholderCheck($result);
}
}
return $object;
}
/**
* Handle different types of values, primarily
* other objects and map and array data types.
*/
private function getSimpleValue($value)
{
if ($value instanceof WPvivid_Google_Model) {
return $value->toSimpleObject();
} else if (is_array($value)) {
$return = array();
foreach ($value as $key => $a_value) {
$a_value = $this->getSimpleValue($a_value);
if ($a_value !== null) {
$key = $this->getMappedName($key);
$return[$key] = $this->nullPlaceholderCheck($a_value);
}
}
return $return;
}
return $value;
}
/**
* Check whether the value is the null placeholder and return true null.
*/
private function nullPlaceholderCheck($value)
{
if ($value === self::NULL_VALUE) {
return null;
}
return $value;
}
/**
* If there is an internal name mapping, use that.
*/
private function getMappedName($key)
{
if (isset($this->internal_gapi_mappings, $this->internal_gapi_mappings[$key])) {
$key = $this->internal_gapi_mappings[$key];
}
return $key;
}
/**
* Returns true only if the array is associative.
* @param array $array
* @return bool True if the array is associative.
*/
protected function isAssociativeArray($array)
{
if (!is_array($array)) {
return false;
}
$keys = array_keys($array);
foreach ($keys as $key) {
if (is_string($key)) {
return true;
}
}
return false;
}
/**
* Verify if $obj is an array.
* @throws WPvivid_Google_Exception Thrown if $obj isn't an array.
* @param array $obj Items that should be validated.
* @param string $method Method expecting an array as an argument.
*/
public function assertIsArray($obj, $method)
{
if ($obj && !is_array($obj)) {
throw new WPvivid_Google_Exception(
esc_html("Incorrect parameter type passed to $method(). Expected an array.")
);
}
}
#[\ReturnTypeWillChange]
public function offsetExists($offset)
{
return isset($this->$offset) || isset($this->modelData[$offset]);
}
#[\ReturnTypeWillChange]
public function offsetGet($offset)
{
return isset($this->$offset) ?
$this->$offset :
$this->__get($offset);
}
#[\ReturnTypeWillChange]
public function offsetSet($offset, $value)
{
if (property_exists($this, $offset)) {
$this->$offset = $value;
} else {
$this->modelData[$offset] = $value;
$this->processed[$offset] = true;
}
}
#[\ReturnTypeWillChange]
public function offsetUnset($offset)
{
unset($this->modelData[$offset]);
}
protected function keyType($key)
{
$keyType = $key . "Type";
// ensure keyType is a valid class
if (property_exists($this, $keyType) && class_exists($this->$keyType)) {
return $this->$keyType;
}
}
protected function dataType($key)
{
$dataType = $key . "DataType";
if (property_exists($this, $dataType)) {
return $this->$dataType;
}
}
public function __isset($key)
{
return isset($this->modelData[$key]);
}
public function __unset($key)
{
unset($this->modelData[$key]);
}
/**
* Convert a string to camelCase
* @param string $value
* @return string
*/
private function camelCase($value)
{
$value = ucwords(str_replace(array('-', '_'), ' ', $value));
$value = str_replace(' ', '', $value);
$value[0] = strtolower($value[0]);
return $value;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Http/Batch.php 0000644 00000015506 15132770567 0021356 0 ustar 00 <?php
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGuzzleHttp\Psr7;
use WPvividGuzzleHttp\Psr7\Request;
use WPvividGuzzleHttp\Psr7\Response;
use WPvividPsr\Http\Message\RequestInterface;
use WPvividPsr\Http\Message\ResponseInterface;
/**
* Class to handle batched requests to the Google API service.
*/
class WPvivid_Google_Http_Batch
{
const BATCH_PATH = 'batch';
private static $CONNECTION_ESTABLISHED_HEADERS = array(
"HTTP/1.0 200 Connection established\r\n\r\n",
"HTTP/1.1 200 Connection established\r\n\r\n",
);
/** @var string Multipart Boundary. */
private $boundary;
/** @var array service requests to be executed. */
private $requests = array();
/** @var WPvivid_Google_Client */
private $client;
private $rootUrl;
private $batchPath;
public function __construct(
WPvivid_Google_Client $client,
$boundary = false,
$rootUrl = null,
$batchPath = null
) {
$this->client = $client;
$this->boundary = $boundary ?: mt_rand();
$this->rootUrl = rtrim($rootUrl ?: $this->client->getConfig('base_path'), '/');
$this->batchPath = $batchPath ?: self::BATCH_PATH;
}
public function add(RequestInterface $request, $key = false)
{
if (false == $key) {
$key = mt_rand();
}
$this->requests[$key] = $request;
}
public function execute()
{
$body = '';
$classes = array();
$batchHttpTemplate = <<<EOF
--%s
Content-Type: application/http
Content-Transfer-Encoding: binary
MIME-Version: 1.0
Content-ID: %s
%s
%s%s
EOF;
/** @var WPvivid_Google_Http_Request $req */
foreach ($this->requests as $key => $request) {
$firstLine = sprintf(
'%s %s HTTP/%s',
$request->getMethod(),
$request->getRequestTarget(),
$request->getProtocolVersion()
);
$content = (string) $request->getBody();
$headers = '';
foreach ($request->getHeaders() as $name => $values) {
$headers .= sprintf("%s:%s\r\n", $name, implode(', ', $values));
}
$body .= sprintf(
$batchHttpTemplate,
$this->boundary,
$key,
$firstLine,
$headers,
$content ? "\n".$content : ''
);
$classes['response-' . $key] = $request->getHeaderLine('X-Php-Expected-Class');
}
$body .= "--{$this->boundary}--";
$body = trim($body);
$url = $this->rootUrl . '/' . $this->batchPath;
$headers = array(
'Content-Type' => sprintf('multipart/mixed; boundary=%s', $this->boundary),
'Content-Length' => strlen($body),
);
$request = new Request(
'POST',
$url,
$headers,
$body
);
$response = $this->client->execute($request);
return $this->parseResponse($response, $classes);
}
public function parseResponse(ResponseInterface $response, $classes = array())
{
$contentType = $response->getHeaderLine('content-type');
$contentType = explode(';', $contentType);
$boundary = false;
foreach ($contentType as $part) {
$part = explode('=', $part, 2);
if (isset($part[0]) && 'boundary' == trim($part[0])) {
$boundary = $part[1];
}
}
$body = (string) $response->getBody();
if (!empty($body)) {
$body = str_replace("--$boundary--", "--$boundary", $body);
$parts = explode("--$boundary", $body);
$responses = array();
$requests = array_values($this->requests);
foreach ($parts as $i => $part) {
$part = trim($part);
if (!empty($part)) {
list($rawHeaders, $part) = explode("\r\n\r\n", $part, 2);
$headers = $this->parseRawHeaders($rawHeaders);
$status = substr($part, 0, strpos($part, "\n"));
$status = explode(" ", $status);
$status = $status[1];
list($partHeaders, $partBody) = $this->parseHttpResponse($part, false);
$response = new Response(
$status,
$partHeaders,
Psr7\stream_for($partBody)
);
// Need content id.
$key = $headers['content-id'];
try {
$response = WPvivid_Google_Http_REST::decodeHttpResponse($response, $requests[$i-1]);
} catch (WPvivid_Google_Service_Exception $e) {
// Store the exception as the response, so successful responses
// can be processed.
$response = $e;
}
$responses[$key] = $response;
}
}
return $responses;
}
return null;
}
private function parseRawHeaders($rawHeaders)
{
$headers = array();
$responseHeaderLines = explode("\r\n", $rawHeaders);
foreach ($responseHeaderLines as $headerLine) {
if ($headerLine && strpos($headerLine, ':') !== false) {
list($header, $value) = explode(': ', $headerLine, 2);
$header = strtolower($header);
if (isset($headers[$header])) {
$headers[$header] .= "\n" . $value;
} else {
$headers[$header] = $value;
}
}
}
return $headers;
}
/**
* Used by the IO lib and also the batch processing.
*
* @param $respData
* @param $headerSize
* @return array
*/
private function parseHttpResponse($respData, $headerSize)
{
// check proxy header
foreach (self::$CONNECTION_ESTABLISHED_HEADERS as $established_header) {
if (stripos($respData, $established_header) !== false) {
// existed, remove it
$respData = str_ireplace($established_header, '', $respData);
// Subtract the proxy header size unless the cURL bug prior to 7.30.0
// is present which prevented the proxy header size from being taken into
// account.
// @TODO look into this
// if (!$this->needsQuirk()) {
// $headerSize -= strlen($established_header);
// }
break;
}
}
if ($headerSize) {
$responseBody = substr($respData, $headerSize);
$responseHeaders = substr($respData, 0, $headerSize);
} else {
$responseSegments = explode("\r\n\r\n", $respData, 2);
$responseHeaders = $responseSegments[0];
$responseBody = isset($responseSegments[1]) ? $responseSegments[1] :
null;
}
$responseHeaders = $this->parseRawHeaders($responseHeaders);
return array($responseHeaders, $responseBody);
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Http/MediaFileUpload.php 0000644 00000022453 15132770567 0023320 0 ustar 00 <?php
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGuzzleHttp\Psr7;
use WPvividGuzzleHttp\Psr7\Request;
use WPvividGuzzleHttp\Psr7\Uri;
use WPvividPsr\Http\Message\RequestInterface;
/**
* Manage large file uploads, which may be media but can be any type
* of sizable data.
*/
class WPvivid_Google_Http_MediaFileUpload
{
const UPLOAD_MEDIA_TYPE = 'media';
const UPLOAD_MULTIPART_TYPE = 'multipart';
const UPLOAD_RESUMABLE_TYPE = 'resumable';
/** @var string $mimeType */
private $mimeType;
/** @var string $data */
private $data;
/** @var bool $resumable */
private $resumable;
/** @var int $chunkSize */
private $chunkSize;
/** @var int $size */
private $size;
/** @var string $resumeUri */
private $resumeUri;
/** @var int $progress */
private $progress;
/** @var WPvivid_Google_Client */
private $client;
/** @var WPvividPsr\Http\Message\RequestInterface */
private $request;
/** @var string */
private $boundary;
/**
* Result code from last HTTP call
* @var int
*/
private $httpResultCode;
/**
* @param $client WPvivid_Google_Client
* @param $request RequestInterface
* @param $mimeType string
* @param $data string The bytes you want to upload.
* @param $resumable bool
* @param bool $chunkSize File will be uploaded in chunks of this many bytes.
* only used if resumable=True
*/
public function __construct(
WPvivid_Google_Client $client,
RequestInterface $request,
$mimeType,
$data,
$resumable = false,
$chunkSize = false
) {
$this->client = $client;
$this->request = $request;
$this->mimeType = $mimeType;
$this->data = $data;
$this->resumable = $resumable;
$this->chunkSize = $chunkSize;
$this->progress = 0;
$this->process();
}
/**
* Set the size of the file that is being uploaded.
* @param $size - int file size in bytes
*/
public function setFileSize($size)
{
$this->size = $size;
}
/**
* Return the progress on the upload
* @return int progress in bytes uploaded.
*/
public function getProgress()
{
return $this->progress;
}
/**
* Send the next part of the file to upload.
* @param [$chunk] the next set of bytes to send. If false will used $data passed
* at construct time.
*/
public function nextChunk($chunk = false)
{
$resumeUri = $this->getResumeUri();
if (false == $chunk) {
$chunk = substr($this->data, $this->progress, $this->chunkSize);
}
$lastBytePos = $this->progress + strlen($chunk) - 1;
$headers = array(
'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
'content-length' => strlen($chunk),
'expect' => '',
);
$request = new Request(
'PUT',
$resumeUri,
$headers,
Psr7\stream_for($chunk)
);
return $this->makePutRequest($request);
}
/**
* Return the HTTP result code from the last call made.
* @return int code
*/
public function getHttpResultCode()
{
return $this->httpResultCode;
}
/**
* Sends a PUT-Request to google drive and parses the response,
* setting the appropiate variables from the response()
*
* @param WPvivid_Google_Http_Request $httpRequest the Reuqest which will be send
*
* @return false|mixed false when the upload is unfinished or the decoded http response
*
*/
private function makePutRequest(RequestInterface $request)
{
$response = $this->client->execute($request);
$this->httpResultCode = $response->getStatusCode();
if (308 == $this->httpResultCode) {
// Track the amount uploaded.
$range = $response->getHeaderLine('range');
if ($range) {
$range_array = explode('-', $range);
$this->progress = $range_array[1] + 1;
}
// Allow for changing upload URLs.
$location = $response->getHeaderLine('location');
if ($location) {
$this->resumeUri = $location;
}
// No problems, but upload not complete.
return false;
}
return WPvivid_Google_Http_REST::decodeHttpResponse($response, $this->request);
}
/**
* Resume a previously unfinished upload
* @param $resumeUri resume-URI of the unfinished, resumable upload.
*/
public function resume($resumeUri)
{
$this->resumeUri = $resumeUri;
$headers = array(
'content-range' => "bytes */$this->size",
'content-length' => 0,
);
$httpRequest = new Request(
'PUT',
$this->resumeUri,
$headers
);
return $this->makePutRequest($httpRequest);
}
public function setResumeUri($resumeUri)
{
$this->resumeUri = $resumeUri;
}
public function setProgress($progress)
{
$this->progress = $progress;
}
/**
* @return WPvividPsr\Http\Message\RequestInterface $request
* @visible for testing
*/
private function process()
{
$this->transformToUploadUrl();
$request = $this->request;
$postBody = '';
$contentType = false;
$meta = (string) $request->getBody();
$meta = is_string($meta) ? json_decode($meta, true) : $meta;
$uploadType = $this->getUploadType($meta);
$request = $request->withUri(
Uri::withQueryValue($request->getUri(), 'uploadType', $uploadType)
);
$mimeType = $this->mimeType ?: $request->getHeaderLine('content-type');
if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
$contentType = $mimeType;
$postBody = is_string($meta) ? $meta : json_encode($meta);
} else if (self::UPLOAD_MEDIA_TYPE == $uploadType) {
$contentType = $mimeType;
$postBody = $this->data;
} else if (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
// This is a multipart/related upload.
$boundary = $this->boundary ?: mt_rand();
$boundary = str_replace('"', '', $boundary);
$contentType = 'multipart/related; boundary=' . $boundary;
$related = "--$boundary\r\n";
$related .= "Content-Type: application/json; charset=UTF-8\r\n";
$related .= "\r\n" . json_encode($meta) . "\r\n";
$related .= "--$boundary\r\n";
$related .= "Content-Type: $mimeType\r\n";
$related .= "Content-Transfer-Encoding: base64\r\n";
$related .= "\r\n" . base64_encode($this->data) . "\r\n";
$related .= "--$boundary--";
$postBody = $related;
}
$request = $request->withBody(Psr7\stream_for($postBody));
if (isset($contentType) && $contentType) {
$request = $request->withHeader('content-type', $contentType);
}
return $this->request = $request;
}
/**
* Valid upload types:
* - resumable (UPLOAD_RESUMABLE_TYPE)
* - media (UPLOAD_MEDIA_TYPE)
* - multipart (UPLOAD_MULTIPART_TYPE)
* @param $meta
* @return string
* @visible for testing
*/
public function getUploadType($meta)
{
if ($this->resumable) {
return self::UPLOAD_RESUMABLE_TYPE;
}
if (false == $meta && $this->data) {
return self::UPLOAD_MEDIA_TYPE;
}
return self::UPLOAD_MULTIPART_TYPE;
}
public function getResumeUri()
{
if (null === $this->resumeUri) {
$this->resumeUri = $this->fetchResumeUri();
}
return $this->resumeUri;
}
private function fetchResumeUri()
{
$body = $this->request->getBody();
if ($body) {
$headers = array(
'content-type' => 'application/json; charset=UTF-8',
'content-length' => $body->getSize(),
'x-upload-content-type' => $this->mimeType,
'x-upload-content-length' => $this->size,
'expect' => '',
);
foreach ($headers as $key => $value) {
$this->request = $this->request->withHeader($key, $value);
}
}
$response = $this->client->execute($this->request, false);
$location = $response->getHeaderLine('location');
$code = $response->getStatusCode();
if (200 == $code && true == $location) {
return $location;
}
$message = $code;
$body = json_decode((string) $this->request->getBody(), true);
if (isset($body['error']['errors'])) {
$message .= ': ';
foreach ($body['error']['errors'] as $error) {
$message .= "{$error[domain]}, {$error[message]};";
}
$message = rtrim($message, ';');
}
$error = "Failed to start the resumable upload (HTTP {$message})";
$this->client->getLogger()->error($error);
throw new WPvivid_Google_Exception(esc_html($error));
}
private function transformToUploadUrl()
{
$parts = parse_url((string) $this->request->getUri());
if (!isset($parts['path'])) {
$parts['path'] = '';
}
$parts['path'] = '/upload' . $parts['path'];
$uri = Uri::fromParts($parts);
$this->request = $this->request->withUri($uri);
}
public function setChunkSize($chunkSize)
{
$this->chunkSize = $chunkSize;
}
public function getRequest()
{
return $this->request;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Http/REST.php 0000644 00000013126 15132770567 0021106 0 ustar 00 <?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGoogle\Auth\HttpHandler\HttpHandlerFactory;
use WPvividGuzzleHttp\ClientInterface;
use WPvividGuzzleHttp\Exception\RequestException;
use WPvividGuzzleHttp\Psr7\Response;
use WPvividPsr\Http\Message\RequestInterface;
use WPvividPsr\Http\Message\ResponseInterface;
/**
* This class implements the RESTful transport of apiServiceRequest()'s
*/
class WPvivid_Google_Http_REST
{
/**
* Executes a Psr\Http\Message\RequestInterface and (if applicable) automatically retries
* when errors occur.
*
* @param WPvivid_Google_Client $client
* @param WpvividPsr\Http\Message\RequestInterface $req
* @return array decoded result
* @throws WPvivid_Google_Service_Exception on server side error (ie: not authenticated,
* invalid or malformed post body, invalid url)
*/
public static function execute(
ClientInterface $client,
RequestInterface $request,
$expectedClass = null,
$config = array(),
$retryMap = null
) {
$runner = new WPvivid_Google_Task_Runner(
$config,
sprintf('%s %s', $request->getMethod(), (string) $request->getUri()),
array(get_class(), 'doExecute'),
array($client, $request, $expectedClass)
);
if (null !== $retryMap) {
$runner->setRetryMap($retryMap);
}
return $runner->run();
}
/**
* Executes a Psr\Http\Message\RequestInterface
*
* @param WPvivid_Google_Client $client
* @param WPvividPsr\Http\Message\RequestInterface $request
* @return array decoded result
* @throws WPvivid_Google_Service_Exception on server side error (ie: not authenticated,
* invalid or malformed post body, invalid url)
*/
public static function doExecute(ClientInterface $client, RequestInterface $request, $expectedClass = null)
{
try {
$httpHandler = HttpHandlerFactory::build($client);
$response = $httpHandler($request);
} catch (RequestException $e) {
// if Guzzle throws an exception, catch it and handle the response
if (!$e->hasResponse()) {
throw $e;
}
$response = $e->getResponse();
// specific checking for Guzzle 5: convert to PSR7 response
if ($response instanceof \WPvividGuzzleHttp\Message\ResponseInterface) {
$response = new Response(
$response->getStatusCode(),
$response->getHeaders() ?: [],
$response->getBody(),
$response->getProtocolVersion(),
$response->getReasonPhrase()
);
}
}
return self::decodeHttpResponse($response, $request, $expectedClass);
}
/**
* Decode an HTTP Response.
* @static
* @throws WPvivid_Google_Service_Exception
* @param WPvividPsr\Http\Message\RequestInterface $response The http response to be decoded.
* @param WPvividPsr\Http\Message\ResponseInterface $response
* @return mixed|null
*/
public static function decodeHttpResponse(
ResponseInterface $response,
RequestInterface $request = null,
$expectedClass = null
) {
$code = $response->getStatusCode();
// retry strategy
if (intVal($code) >= 400) {
// if we errored out, it should be safe to grab the response body
$body = (string) $response->getBody();
// Check if we received errors, and add those to the Exception for convenience
throw new WPvivid_Google_Service_Exception(esc_html($body), esc_attr($code), null, esc_html(self::getResponseErrors($body)));
}
// Ensure we only pull the entire body into memory if the request is not
// of media type
$body = self::decodeBody($response, $request);
if ($expectedClass = self::determineExpectedClass($expectedClass, $request)) {
$json = json_decode($body, true);
return new $expectedClass($json);
}
return $response;
}
private static function decodeBody(ResponseInterface $response, RequestInterface $request = null)
{
if (self::isAltMedia($request)) {
// don't decode the body, it's probably a really long string
return '';
}
return (string) $response->getBody();
}
private static function determineExpectedClass($expectedClass, RequestInterface $request = null)
{
// "false" is used to explicitly prevent an expected class from being returned
if (false === $expectedClass) {
return null;
}
// if we don't have a request, we just use what's passed in
if (null === $request) {
return $expectedClass;
}
// return what we have in the request header if one was not supplied
return $expectedClass ?: $request->getHeaderLine('X-Php-Expected-Class');
}
private static function getResponseErrors($body)
{
$json = json_decode($body, true);
if (isset($json['error']['errors'])) {
return $json['error']['errors'];
}
return null;
}
private static function isAltMedia(RequestInterface $request = null)
{
if ($request && $qs = $request->getUri()->getQuery()) {
parse_str($qs, $query);
if (isset($query['alt']) && $query['alt'] == 'media') {
return true;
}
}
return false;
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/Collection.php 0000644 00000005007 15132770567 0021504 0 ustar 00 <?php
if (!class_exists('WPvivid_Google_Client')) {
require_once __DIR__ . '/autoload.php';
}
/**
* Extension to the regular WPvivid_Google_Model that automatically
* exposes the items array for iteration, so you can just
* iterate over the object rather than a reference inside.
*/
class WPvivid_Google_Collection extends WPvivid_Google_Model implements Iterator, Countable
{
protected $collection_key = 'items';
#[\ReturnTypeWillChange]
public function rewind()
{
if (isset($this->{$this->collection_key})
&& is_array($this->{$this->collection_key})) {
reset($this->{$this->collection_key});
}
}
#[\ReturnTypeWillChange]
public function current()
{
$this->coerceType($this->key());
if (is_array($this->{$this->collection_key})) {
return current($this->{$this->collection_key});
}
}
#[\ReturnTypeWillChange]
public function key()
{
if (isset($this->{$this->collection_key})
&& is_array($this->{$this->collection_key})) {
return key($this->{$this->collection_key});
}
}
#[\ReturnTypeWillChange]
public function next()
{
return next($this->{$this->collection_key});
}
#[\ReturnTypeWillChange]
public function valid()
{
$key = $this->key();
return $key !== null && $key !== false;
}
#[\ReturnTypeWillChange]
public function count()
{
if (!isset($this->{$this->collection_key})) {
return 0;
}
return count($this->{$this->collection_key});
}
public function offsetExists($offset)
{
if (!is_numeric($offset)) {
return parent::offsetExists($offset);
}
return isset($this->{$this->collection_key}[$offset]);
}
public function offsetGet($offset)
{
if (!is_numeric($offset)) {
return parent::offsetGet($offset);
}
$this->coerceType($offset);
return $this->{$this->collection_key}[$offset];
}
public function offsetSet($offset, $value)
{
if (!is_numeric($offset)) {
return parent::offsetSet($offset, $value);
}
$this->{$this->collection_key}[$offset] = $value;
}
public function offsetUnset($offset)
{
if (!is_numeric($offset)) {
return parent::offsetUnset($offset);
}
unset($this->{$this->collection_key}[$offset]);
}
private function coerceType($offset)
{
$keyType = $this->keyType($this->collection_key);
if ($keyType && !is_object($this->{$this->collection_key}[$offset])) {
$this->{$this->collection_key}[$offset] =
new $keyType($this->{$this->collection_key}[$offset]);
}
}
}
includes/lib2/google-api-php-client/src/WPvivid/Google/autoload.php 0000644 00000001345 15132770567 0021222 0 ustar 00 <?php
/**
* THIS FILE IS FOR BACKWARDS COMPATIBLITY ONLY
*
* If you were not already including this file in your project, please ignore it
*/
$file = __DIR__ . '/../../vendor/autoload.php';
if (!file_exists($file)) {
$exception = 'This library must be installed via composer or by downloading the full package.';
$exception .= ' See the instructions at https://github.com/google/google-api-php-client#installation.';
throw new Exception(esc_html($exception));
}
$error = 'google-api-php-client\'s autoloader was moved to vendor/autoload.php in 2.0.0. This ';
$error .= 'redirect will be removed in 2.1. Please adjust your code to use the new location.';
trigger_error(esc_html($error), E_USER_DEPRECATED);
require_once $file;
includes/lib/google-api-php-client/src/Google/Utils/UriTemplate.php 0000644 00000022346 15132770567 0021277 0 ustar 00 <?php
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Implementation of levels 1-3 of the URI Template spec.
* @see http://tools.ietf.org/html/rfc6570
*/
class Google_Utils_UriTemplate
{
const TYPE_MAP = "1";
const TYPE_LIST = "2";
const TYPE_SCALAR = "4";
/**
* @var $operators array
* These are valid at the start of a template block to
* modify the way in which the variables inside are
* processed.
*/
private $operators = array(
"+" => "reserved",
"/" => "segments",
"." => "dotprefix",
"#" => "fragment",
";" => "semicolon",
"?" => "form",
"&" => "continuation"
);
/**
* @var reserved array
* These are the characters which should not be URL encoded in reserved
* strings.
*/
private $reserved = array(
"=", ",", "!", "@", "|", ":", "/", "?", "#",
"[", "]",'$', "&", "'", "(", ")", "*", "+", ";"
);
private $reservedEncoded = array(
"%3D", "%2C", "%21", "%40", "%7C", "%3A", "%2F", "%3F",
"%23", "%5B", "%5D", "%24", "%26", "%27", "%28", "%29",
"%2A", "%2B", "%3B"
);
public function parse($string, array $parameters)
{
return $this->resolveNextSection($string, $parameters);
}
/**
* This function finds the first matching {...} block and
* executes the replacement. It then calls itself to find
* subsequent blocks, if any.
*/
private function resolveNextSection($string, $parameters)
{
$start = strpos($string, "{");
if ($start === false) {
return $string;
}
$end = strpos($string, "}");
if ($end === false) {
return $string;
}
$string = $this->replace($string, $start, $end, $parameters);
return $this->resolveNextSection($string, $parameters);
}
private function replace($string, $start, $end, $parameters)
{
// We know a data block will have {} round it, so we can strip that.
$data = substr($string, $start + 1, $end - $start - 1);
// If the first character is one of the reserved operators, it effects
// the processing of the stream.
if (isset($this->operators[$data[0]])) {
$op = $this->operators[$data[0]];
$data = substr($data, 1);
$prefix = "";
$prefix_on_missing = false;
switch ($op) {
case "reserved":
// Reserved means certain characters should not be URL encoded
$data = $this->replaceVars($data, $parameters, ",", null, true);
break;
case "fragment":
// Comma separated with fragment prefix. Bare values only.
$prefix = "#";
$prefix_on_missing = true;
$data = $this->replaceVars($data, $parameters, ",", null, true);
break;
case "segments":
// Slash separated data. Bare values only.
$prefix = "/";
$data =$this->replaceVars($data, $parameters, "/");
break;
case "dotprefix":
// Dot separated data. Bare values only.
$prefix = ".";
$prefix_on_missing = true;
$data = $this->replaceVars($data, $parameters, ".");
break;
case "semicolon":
// Semicolon prefixed and separated. Uses the key name
$prefix = ";";
$data = $this->replaceVars($data, $parameters, ";", "=", false, true, false);
break;
case "form":
// Standard URL format. Uses the key name
$prefix = "?";
$data = $this->replaceVars($data, $parameters, "&", "=");
break;
case "continuation":
// Standard URL, but with leading ampersand. Uses key name.
$prefix = "&";
$data = $this->replaceVars($data, $parameters, "&", "=");
break;
}
// Add the initial prefix character if data is valid.
if ($data || ($data !== false && $prefix_on_missing)) {
$data = $prefix . $data;
}
} else {
// If no operator we replace with the defaults.
$data = $this->replaceVars($data, $parameters);
}
// This is chops out the {...} and replaces with the new section.
return substr($string, 0, $start) . $data . substr($string, $end + 1);
}
private function replaceVars(
$section,
$parameters,
$sep = ",",
$combine = null,
$reserved = false,
$tag_empty = false,
$combine_on_empty = true
) {
if (strpos($section, ",") === false) {
// If we only have a single value, we can immediately process.
return $this->combine(
$section,
$parameters,
$sep,
$combine,
$reserved,
$tag_empty,
$combine_on_empty
);
} else {
// If we have multiple values, we need to split and loop over them.
// Each is treated individually, then glued together with the
// separator character.
$vars = explode(",", $section);
return $this->combineList(
$vars,
$sep,
$parameters,
$combine,
$reserved,
false, // Never emit empty strings in multi-param replacements
$combine_on_empty
);
}
}
public function combine(
$key,
$parameters,
$sep,
$combine,
$reserved,
$tag_empty,
$combine_on_empty
) {
$length = false;
$explode = false;
$skip_final_combine = false;
$value = false;
// Check for length restriction.
if (strpos($key, ":") !== false) {
list($key, $length) = explode(":", $key);
}
// Check for explode parameter.
if ($key[strlen($key) - 1] == "*") {
$explode = true;
$key = substr($key, 0, -1);
$skip_final_combine = true;
}
// Define the list separator.
$list_sep = $explode ? $sep : ",";
if (isset($parameters[$key])) {
$data_type = $this->getDataType($parameters[$key]);
switch ($data_type) {
case self::TYPE_SCALAR:
$value = $this->getValue($parameters[$key], $length);
break;
case self::TYPE_LIST:
$values = array();
foreach ($parameters[$key] as $pkey => $pvalue) {
$pvalue = $this->getValue($pvalue, $length);
if ($combine && $explode) {
$values[$pkey] = $key . $combine . $pvalue;
} else {
$values[$pkey] = $pvalue;
}
}
$value = implode($list_sep, $values);
if ($value == '') {
return '';
}
break;
case self::TYPE_MAP:
$values = array();
foreach ($parameters[$key] as $pkey => $pvalue) {
$pvalue = $this->getValue($pvalue, $length);
if ($explode) {
$pkey = $this->getValue($pkey, $length);
$values[] = $pkey . "=" . $pvalue; // Explode triggers = combine.
} else {
$values[] = $pkey;
$values[] = $pvalue;
}
}
$value = implode($list_sep, $values);
if ($value == '') {
return false;
}
break;
}
} else if ($tag_empty) {
// If we are just indicating empty values with their key name, return that.
return $key;
} else {
// Otherwise we can skip this variable due to not being defined.
return false;
}
if ($reserved) {
$value = str_replace($this->reservedEncoded, $this->reserved, $value);
}
// If we do not need to include the key name, we just return the raw
// value.
if (!$combine || $skip_final_combine) {
return $value;
}
// Else we combine the key name: foo=bar, if value is not the empty string.
return $key . ($value != '' || $combine_on_empty ? $combine . $value : '');
}
/**
* Return the type of a passed in value
*/
private function getDataType($data)
{
if (is_array($data)) {
reset($data);
if (key($data) !== 0) {
return self::TYPE_MAP;
}
return self::TYPE_LIST;
}
return self::TYPE_SCALAR;
}
/**
* Utility function that merges multiple combine calls
* for multi-key templates.
*/
private function combineList(
$vars,
$sep,
$parameters,
$combine,
$reserved,
$tag_empty,
$combine_on_empty
) {
$ret = array();
foreach ($vars as $var) {
$response = $this->combine(
$var,
$parameters,
$sep,
$combine,
$reserved,
$tag_empty,
$combine_on_empty
);
if ($response === false) {
continue;
}
$ret[] = $response;
}
return implode($sep, $ret);
}
/**
* Utility function to encode and trim values
*/
private function getValue($value, $length)
{
if ($length) {
$value = substr($value, 0, $length);
}
$value = rawurlencode($value);
return $value;
}
}
includes/lib/google-api-php-client/src/Google/AuthHandler/AuthHandlerFactory.php 0000644 00000002523 15132770567 0023665 0 ustar 00 <?php
/**
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGuzzleHttp\Client;
use WPvividGuzzleHttp\ClientInterface;
class Google_AuthHandler_AuthHandlerFactory
{
/**
* Builds out a default http handler for the installed version of guzzle.
*
* @return Google_AuthHandler_Guzzle5AuthHandler|Google_AuthHandler_Guzzle6AuthHandler
* @throws Exception
*/
public static function build($cache = null, array $cacheConfig = [])
{
$version = ClientInterface::VERSION;
switch ($version[0]) {
case '5':
return new Google_AuthHandler_Guzzle5AuthHandler($cache, $cacheConfig);
case '6':
return new Google_AuthHandler_Guzzle6AuthHandler($cache, $cacheConfig);
default:
throw new Exception('Version not supported');
}
}
}
includes/lib/google-api-php-client/src/Google/AuthHandler/Guzzle5AuthHandler.php 0000644 00000005050 15132770567 0023621 0 ustar 00 <?php
use WPvividGoogle\Auth\CredentialsLoader;
use WPvividGoogle\Auth\HttpHandler\HttpHandlerFactory;
use WPvividGoogle\Auth\FetchAuthTokenCache;
use WPvividGoogle\Auth\Subscriber\AuthTokenSubscriber;
use WPvividGoogle\Auth\Subscriber\ScopedAccessTokenSubscriber;
use WPvividGoogle\Auth\Subscriber\SimpleSubscriber;
use WPvividGuzzleHttp\Client;
use WPvividGuzzleHttp\ClientInterface;
use WPvividPsr\Cache\CacheItemPoolInterface;
/**
*
*/
class Google_AuthHandler_Guzzle5AuthHandler
{
protected $cache;
protected $cacheConfig;
public function __construct(CacheItemPoolInterface $cache = null, array $cacheConfig = [])
{
$this->cache = $cache;
$this->cacheConfig = $cacheConfig;
}
public function attachCredentials(
ClientInterface $http,
CredentialsLoader $credentials,
callable $tokenCallback = null
) {
// use the provided cache
if ($this->cache) {
$credentials = new FetchAuthTokenCache(
$credentials,
$this->cacheConfig,
$this->cache
);
}
// if we end up needing to make an HTTP request to retrieve credentials, we
// can use our existing one, but we need to throw exceptions so the error
// bubbles up.
$authHttp = $this->createAuthHttp($http);
$authHttpHandler = HttpHandlerFactory::build($authHttp);
$subscriber = new AuthTokenSubscriber(
$credentials,
$authHttpHandler,
$tokenCallback
);
$http->setDefaultOption('auth', 'google_auth');
$http->getEmitter()->attach($subscriber);
return $http;
}
public function attachToken(ClientInterface $http, array $token, array $scopes)
{
$tokenFunc = function ($scopes) use ($token) {
return $token['access_token'];
};
$subscriber = new ScopedAccessTokenSubscriber(
$tokenFunc,
$scopes,
$this->cacheConfig,
$this->cache
);
$http->setDefaultOption('auth', 'scoped');
$http->getEmitter()->attach($subscriber);
return $http;
}
public function attachKey(ClientInterface $http, $key)
{
$subscriber = new SimpleSubscriber(['key' => $key]);
$http->setDefaultOption('auth', 'simple');
$http->getEmitter()->attach($subscriber);
return $http;
}
private function createAuthHttp(ClientInterface $http)
{
return new Client(
[
'base_url' => $http->getBaseUrl(),
'defaults' => [
'exceptions' => true,
'verify' => $http->getDefaultOption('verify'),
'proxy' => $http->getDefaultOption('proxy'),
]
]
);
}
}
includes/lib/google-api-php-client/src/Google/AuthHandler/Guzzle6AuthHandler.php 0000644 00000005504 15132770567 0023626 0 ustar 00 <?php
use WPvividGoogle\Auth\CredentialsLoader;
use WPvividGoogle\Auth\HttpHandler\HttpHandlerFactory;
use WPvividGoogle\Auth\FetchAuthTokenCache;
use WPvividGoogle\Auth\Middleware\AuthTokenMiddleware;
use WPvividGoogle\Auth\Middleware\ScopedAccessTokenMiddleware;
use WPvividGoogle\Auth\Middleware\SimpleMiddleware;
use WPvividGuzzleHttp\Client;
use WPvividGuzzleHttp\ClientInterface;
use WPvividPsr\Cache\CacheItemPoolInterface;
/**
*
*/
class Google_AuthHandler_Guzzle6AuthHandler
{
protected $cache;
protected $cacheConfig;
public function __construct(CacheItemPoolInterface $cache = null, array $cacheConfig = [])
{
$this->cache = $cache;
$this->cacheConfig = $cacheConfig;
}
public function attachCredentials(
ClientInterface $http,
CredentialsLoader $credentials,
callable $tokenCallback = null
) {
// use the provided cache
if ($this->cache) {
$credentials = new FetchAuthTokenCache(
$credentials,
$this->cacheConfig,
$this->cache
);
}
// if we end up needing to make an HTTP request to retrieve credentials, we
// can use our existing one, but we need to throw exceptions so the error
// bubbles up.
$authHttp = $this->createAuthHttp($http);
$authHttpHandler = HttpHandlerFactory::build($authHttp);
$middleware = new AuthTokenMiddleware(
$credentials,
$authHttpHandler,
$tokenCallback
);
$config = $http->getConfig();
$config['handler']->remove('google_auth');
$config['handler']->push($middleware, 'google_auth');
$config['auth'] = 'google_auth';
$http = new Client($config);
return $http;
}
public function attachToken(ClientInterface $http, array $token, array $scopes)
{
$tokenFunc = function ($scopes) use ($token) {
return $token['access_token'];
};
$middleware = new ScopedAccessTokenMiddleware(
$tokenFunc,
$scopes,
$this->cacheConfig,
$this->cache
);
$config = $http->getConfig();
$config['handler']->remove('google_auth');
$config['handler']->push($middleware, 'google_auth');
$config['auth'] = 'scoped';
$http = new Client($config);
return $http;
}
public function attachKey(ClientInterface $http, $key)
{
$middleware = new SimpleMiddleware(['key' => $key]);
$config = $http->getConfig();
$config['handler']->remove('google_auth');
$config['handler']->push($middleware, 'google_auth');
$config['auth'] = 'simple';
$http = new Client($config);
return $http;
}
private function createAuthHttp(ClientInterface $http)
{
return new Client(
[
'base_uri' => $http->getConfig('base_uri'),
'exceptions' => true,
'verify' => $http->getConfig('verify'),
'proxy' => $http->getConfig('proxy'),
]
);
}
}
includes/lib/google-api-php-client/src/Google/Collection.php 0000644 00000004505 15132770567 0020034 0 ustar 00 <?php
if (!class_exists('Google_Client')) {
require_once __DIR__ . '/autoload.php';
}
/**
* Extension to the regular Google_Model that automatically
* exposes the items array for iteration, so you can just
* iterate over the object rather than a reference inside.
*/
class Google_Collection extends Google_Model implements Iterator, Countable
{
protected $collection_key = 'items';
public function rewind()
{
if (isset($this->{$this->collection_key})
&& is_array($this->{$this->collection_key})) {
reset($this->{$this->collection_key});
}
}
public function current()
{
$this->coerceType($this->key());
if (is_array($this->{$this->collection_key})) {
return current($this->{$this->collection_key});
}
}
public function key()
{
if (isset($this->{$this->collection_key})
&& is_array($this->{$this->collection_key})) {
return key($this->{$this->collection_key});
}
}
public function next()
{
return next($this->{$this->collection_key});
}
public function valid()
{
$key = $this->key();
return $key !== null && $key !== false;
}
public function count()
{
if (!isset($this->{$this->collection_key})) {
return 0;
}
return count($this->{$this->collection_key});
}
public function offsetExists($offset)
{
if (!is_numeric($offset)) {
return parent::offsetExists($offset);
}
return isset($this->{$this->collection_key}[$offset]);
}
public function offsetGet($offset)
{
if (!is_numeric($offset)) {
return parent::offsetGet($offset);
}
$this->coerceType($offset);
return $this->{$this->collection_key}[$offset];
}
public function offsetSet($offset, $value)
{
if (!is_numeric($offset)) {
return parent::offsetSet($offset, $value);
}
$this->{$this->collection_key}[$offset] = $value;
}
public function offsetUnset($offset)
{
if (!is_numeric($offset)) {
return parent::offsetUnset($offset);
}
unset($this->{$this->collection_key}[$offset]);
}
private function coerceType($offset)
{
$keyType = $this->keyType($this->collection_key);
if ($keyType && !is_object($this->{$this->collection_key}[$offset])) {
$this->{$this->collection_key}[$offset] =
new $keyType($this->{$this->collection_key}[$offset]);
}
}
}
includes/lib/google-api-php-client/src/Google/Http/MediaFileUpload.php 0000644 00000022241 15132770567 0021641 0 ustar 00 <?php
/**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGuzzleHttp\Psr7;
use WPvividGuzzleHttp\Psr7\Request;
use WPvividGuzzleHttp\Psr7\Uri;
use WPvividPsr\Http\Message\RequestInterface;
/**
* Manage large file uploads, which may be media but can be any type
* of sizable data.
*/
class Google_Http_MediaFileUpload
{
const UPLOAD_MEDIA_TYPE = 'media';
const UPLOAD_MULTIPART_TYPE = 'multipart';
const UPLOAD_RESUMABLE_TYPE = 'resumable';
/** @var string $mimeType */
private $mimeType;
/** @var string $data */
private $data;
/** @var bool $resumable */
private $resumable;
/** @var int $chunkSize */
private $chunkSize;
/** @var int $size */
private $size;
/** @var string $resumeUri */
private $resumeUri;
/** @var int $progress */
private $progress;
/** @var Google_Client */
private $client;
/** @var Psr\Http\Message\RequestInterface */
private $request;
/** @var string */
private $boundary;
/**
* Result code from last HTTP call
* @var int
*/
private $httpResultCode;
/**
* @param $mimeType string
* @param $data string The bytes you want to upload.
* @param $resumable bool
* @param bool $chunkSize File will be uploaded in chunks of this many bytes.
* only used if resumable=True
*/
public function __construct(
Google_Client $client,
RequestInterface $request,
$mimeType,
$data,
$resumable = false,
$chunkSize = false
) {
$this->client = $client;
$this->request = $request;
$this->mimeType = $mimeType;
$this->data = $data;
$this->resumable = $resumable;
$this->chunkSize = $chunkSize;
$this->progress = 0;
$this->process();
}
/**
* Set the size of the file that is being uploaded.
* @param $size - int file size in bytes
*/
public function setFileSize($size)
{
$this->size = $size;
}
/**
* Return the progress on the upload
* @return int progress in bytes uploaded.
*/
public function getProgress()
{
return $this->progress;
}
/**
* Send the next part of the file to upload.
* @param [$chunk] the next set of bytes to send. If false will used $data passed
* at construct time.
*/
public function nextChunk($chunk = false)
{
$resumeUri = $this->getResumeUri();
if (false == $chunk) {
$chunk = substr($this->data, $this->progress, $this->chunkSize);
}
$lastBytePos = $this->progress + strlen($chunk) - 1;
$headers = array(
'content-range' => "bytes $this->progress-$lastBytePos/$this->size",
'content-length' => strlen($chunk),
'expect' => '',
);
$request = new Request(
'PUT',
$resumeUri,
$headers,
Psr7\stream_for($chunk)
);
return $this->makePutRequest($request);
}
/**
* Return the HTTP result code from the last call made.
* @return int code
*/
public function getHttpResultCode()
{
return $this->httpResultCode;
}
/**
* Sends a PUT-Request to google drive and parses the response,
* setting the appropiate variables from the response()
*
* @param Google_Http_Request $httpRequest the Reuqest which will be send
*
* @return false|mixed false when the upload is unfinished or the decoded http response
*
*/
private function makePutRequest(RequestInterface $request)
{
$response = $this->client->execute($request);
$this->httpResultCode = $response->getStatusCode();
if (308 == $this->httpResultCode) {
// Track the amount uploaded.
$range = $response->getHeaderLine('range');
if ($range) {
$range_array = explode('-', $range);
$this->progress = $range_array[1] + 1;
}
// Allow for changing upload URLs.
$location = $response->getHeaderLine('location');
if ($location) {
$this->resumeUri = $location;
}
// No problems, but upload not complete.
return false;
}
return Google_Http_REST::decodeHttpResponse($response, $this->request);
}
/**
* Resume a previously unfinished upload
* @param $resumeUri the resume-URI of the unfinished, resumable upload.
*/
public function resume($resumeUri)
{
$this->resumeUri = $resumeUri;
$headers = array(
'content-range' => "bytes */$this->size",
'content-length' => 0,
);
$httpRequest = new Request(
'PUT',
$this->resumeUri,
$headers
);
return $this->makePutRequest($httpRequest);
}
public function setResumeUri($resumeUri)
{
$this->resumeUri = $resumeUri;
}
public function setProgress($progress)
{
$this->progress = $progress;
}
/**
* @return Psr\Http\Message\RequestInterface $request
* @visible for testing
*/
private function process()
{
$this->transformToUploadUrl();
$request = $this->request;
$postBody = '';
$contentType = false;
$meta = (string) $request->getBody();
$meta = is_string($meta) ? json_decode($meta, true) : $meta;
$uploadType = $this->getUploadType($meta);
$request = $request->withUri(
Uri::withQueryValue($request->getUri(), 'uploadType', $uploadType)
);
$mimeType = $this->mimeType ?: $request->getHeaderLine('content-type');
if (self::UPLOAD_RESUMABLE_TYPE == $uploadType) {
$contentType = $mimeType;
$postBody = is_string($meta) ? $meta : json_encode($meta);
} else if (self::UPLOAD_MEDIA_TYPE == $uploadType) {
$contentType = $mimeType;
$postBody = $this->data;
} else if (self::UPLOAD_MULTIPART_TYPE == $uploadType) {
// This is a multipart/related upload.
$boundary = $this->boundary ?: mt_rand();
$boundary = str_replace('"', '', $boundary);
$contentType = 'multipart/related; boundary=' . $boundary;
$related = "--$boundary\r\n";
$related .= "Content-Type: application/json; charset=UTF-8\r\n";
$related .= "\r\n" . json_encode($meta) . "\r\n";
$related .= "--$boundary\r\n";
$related .= "Content-Type: $mimeType\r\n";
$related .= "Content-Transfer-Encoding: base64\r\n";
$related .= "\r\n" . base64_encode($this->data) . "\r\n";
$related .= "--$boundary--";
$postBody = $related;
}
$request = $request->withBody(Psr7\stream_for($postBody));
if (isset($contentType) && $contentType) {
$request = $request->withHeader('content-type', $contentType);
}
return $this->request = $request;
}
/**
* Valid upload types:
* - resumable (UPLOAD_RESUMABLE_TYPE)
* - media (UPLOAD_MEDIA_TYPE)
* - multipart (UPLOAD_MULTIPART_TYPE)
* @param $meta
* @return string
* @visible for testing
*/
public function getUploadType($meta)
{
if ($this->resumable) {
return self::UPLOAD_RESUMABLE_TYPE;
}
if (false == $meta && $this->data) {
return self::UPLOAD_MEDIA_TYPE;
}
return self::UPLOAD_MULTIPART_TYPE;
}
public function getResumeUri()
{
if (null === $this->resumeUri) {
$this->resumeUri = $this->fetchResumeUri();
}
return $this->resumeUri;
}
private function fetchResumeUri()
{
$body = $this->request->getBody();
if ($body) {
$headers = array(
'content-type' => 'application/json; charset=UTF-8',
'content-length' => $body->getSize(),
'x-upload-content-type' => $this->mimeType,
'x-upload-content-length' => $this->size,
'expect' => '',
);
foreach ($headers as $key => $value) {
$this->request = $this->request->withHeader($key, $value);
}
}
$response = $this->client->execute($this->request, false);
$location = $response->getHeaderLine('location');
$code = $response->getStatusCode();
if (200 == $code && true == $location) {
return $location;
}
$message = $code;
$body = json_decode((string) $this->request->getBody(), true);
if (isset($body['error']['errors'])) {
$message .= ': ';
foreach ($body['error']['errors'] as $error) {
$message .= "{$error[domain]}, {$error[message]};";
}
$message = rtrim($message, ';');
}
$error = "Failed to start the resumable upload (HTTP {$message})";
$this->client->getLogger()->error($error);
throw new Google_Exception(esc_html($error));
}
private function transformToUploadUrl()
{
$parts = parse_url((string) $this->request->getUri());
if (!isset($parts['path'])) {
$parts['path'] = '';
}
$parts['path'] = '/upload' . $parts['path'];
$uri = Uri::fromParts($parts);
$this->request = $this->request->withUri($uri);
}
public function setChunkSize($chunkSize)
{
$this->chunkSize = $chunkSize;
}
public function getRequest()
{
return $this->request;
}
}
includes/lib/google-api-php-client/src/Google/Http/Batch.php 0000644 00000015426 15132770567 0017705 0 ustar 00 <?php
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGuzzleHttp\Psr7;
use WPvividGuzzleHttp\Psr7\Request;
use WPvividGuzzleHttp\Psr7\Response;
use WPvividPsr\Http\Message\RequestInterface;
use WPvividPsr\Http\Message\ResponseInterface;
/**
* Class to handle batched requests to the Google API service.
*/
class Google_Http_Batch
{
const BATCH_PATH = 'batch';
private static $CONNECTION_ESTABLISHED_HEADERS = array(
"HTTP/1.0 200 Connection established\r\n\r\n",
"HTTP/1.1 200 Connection established\r\n\r\n",
);
/** @var string Multipart Boundary. */
private $boundary;
/** @var array service requests to be executed. */
private $requests = array();
/** @var Google_Client */
private $client;
private $rootUrl;
private $batchPath;
public function __construct(
Google_Client $client,
$boundary = false,
$rootUrl = null,
$batchPath = null
) {
$this->client = $client;
$this->boundary = $boundary ?: mt_rand();
$this->rootUrl = rtrim($rootUrl ?: $this->client->getConfig('base_path'), '/');
$this->batchPath = $batchPath ?: self::BATCH_PATH;
}
public function add(RequestInterface $request, $key = false)
{
if (false == $key) {
$key = mt_rand();
}
$this->requests[$key] = $request;
}
public function execute()
{
$body = '';
$classes = array();
$batchHttpTemplate = <<<EOF
--%s
Content-Type: application/http
Content-Transfer-Encoding: binary
MIME-Version: 1.0
Content-ID: %s
%s
%s%s
EOF;
/** @var Google_Http_Request $req */
foreach ($this->requests as $key => $request) {
$firstLine = sprintf(
'%s %s HTTP/%s',
$request->getMethod(),
$request->getRequestTarget(),
$request->getProtocolVersion()
);
$content = (string) $request->getBody();
$headers = '';
foreach ($request->getHeaders() as $name => $values) {
$headers .= sprintf("%s:%s\r\n", $name, implode(', ', $values));
}
$body .= sprintf(
$batchHttpTemplate,
$this->boundary,
$key,
$firstLine,
$headers,
$content ? "\n".$content : ''
);
$classes['response-' . $key] = $request->getHeaderLine('X-Php-Expected-Class');
}
$body .= "--{$this->boundary}--";
$body = trim($body);
$url = $this->rootUrl . '/' . $this->batchPath;
$headers = array(
'Content-Type' => sprintf('multipart/mixed; boundary=%s', $this->boundary),
'Content-Length' => strlen($body),
);
$request = new Request(
'POST',
$url,
$headers,
$body
);
$response = $this->client->execute($request);
return $this->parseResponse($response, $classes);
}
public function parseResponse(ResponseInterface $response, $classes = array())
{
$contentType = $response->getHeaderLine('content-type');
$contentType = explode(';', $contentType);
$boundary = false;
foreach ($contentType as $part) {
$part = explode('=', $part, 2);
if (isset($part[0]) && 'boundary' == trim($part[0])) {
$boundary = $part[1];
}
}
$body = (string) $response->getBody();
if (!empty($body)) {
$body = str_replace("--$boundary--", "--$boundary", $body);
$parts = explode("--$boundary", $body);
$responses = array();
$requests = array_values($this->requests);
foreach ($parts as $i => $part) {
$part = trim($part);
if (!empty($part)) {
list($rawHeaders, $part) = explode("\r\n\r\n", $part, 2);
$headers = $this->parseRawHeaders($rawHeaders);
$status = substr($part, 0, strpos($part, "\n"));
$status = explode(" ", $status);
$status = $status[1];
list($partHeaders, $partBody) = $this->parseHttpResponse($part, false);
$response = new Response(
$status,
$partHeaders,
Psr7\stream_for($partBody)
);
// Need content id.
$key = $headers['content-id'];
try {
$response = Google_Http_REST::decodeHttpResponse($response, $requests[$i-1]);
} catch (Google_Service_Exception $e) {
// Store the exception as the response, so successful responses
// can be processed.
$response = $e;
}
$responses[$key] = $response;
}
}
return $responses;
}
return null;
}
private function parseRawHeaders($rawHeaders)
{
$headers = array();
$responseHeaderLines = explode("\r\n", $rawHeaders);
foreach ($responseHeaderLines as $headerLine) {
if ($headerLine && strpos($headerLine, ':') !== false) {
list($header, $value) = explode(': ', $headerLine, 2);
$header = strtolower($header);
if (isset($headers[$header])) {
$headers[$header] .= "\n" . $value;
} else {
$headers[$header] = $value;
}
}
}
return $headers;
}
/**
* Used by the IO lib and also the batch processing.
*
* @param $respData
* @param $headerSize
* @return array
*/
private function parseHttpResponse($respData, $headerSize)
{
// check proxy header
foreach (self::$CONNECTION_ESTABLISHED_HEADERS as $established_header) {
if (stripos($respData, $established_header) !== false) {
// existed, remove it
$respData = str_ireplace($established_header, '', $respData);
// Subtract the proxy header size unless the cURL bug prior to 7.30.0
// is present which prevented the proxy header size from being taken into
// account.
// @TODO look into this
// if (!$this->needsQuirk()) {
// $headerSize -= strlen($established_header);
// }
break;
}
}
if ($headerSize) {
$responseBody = substr($respData, $headerSize);
$responseHeaders = substr($respData, 0, $headerSize);
} else {
$responseSegments = explode("\r\n\r\n", $respData, 2);
$responseHeaders = $responseSegments[0];
$responseBody = isset($responseSegments[1]) ? $responseSegments[1] :
null;
}
$responseHeaders = $this->parseRawHeaders($responseHeaders);
return array($responseHeaders, $responseBody);
}
}
includes/lib/google-api-php-client/src/Google/Http/REST.php 0000644 00000012772 15132770567 0017442 0 ustar 00 <?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGoogle\Auth\HttpHandler\HttpHandlerFactory;
use WPvividGuzzleHttp\ClientInterface;
use WPvividGuzzleHttp\Exception\RequestException;
use WPvividGuzzleHttp\Psr7\Response;
use WPvividPsr\Http\Message\RequestInterface;
use WPvividPsr\Http\Message\ResponseInterface;
/**
* This class implements the RESTful transport of apiServiceRequest()'s
*/
class Google_Http_REST
{
/**
* Executes a Psr\Http\Message\RequestInterface and (if applicable) automatically retries
* when errors occur.
*
* @param Google_Client $client
* @param Psr\Http\Message\RequestInterface $req
* @return array decoded result
* @throws Google_Service_Exception on server side error (ie: not authenticated,
* invalid or malformed post body, invalid url)
*/
public static function execute(
ClientInterface $client,
RequestInterface $request,
$expectedClass = null,
$config = array(),
$retryMap = null
) {
$runner = new Google_Task_Runner(
$config,
sprintf('%s %s', $request->getMethod(), (string) $request->getUri()),
array(get_class(), 'doExecute'),
array($client, $request, $expectedClass)
);
if (null !== $retryMap) {
$runner->setRetryMap($retryMap);
}
return $runner->run();
}
/**
* Executes a Psr\Http\Message\RequestInterface
*
* @param Google_Client $client
* @param Psr\Http\Message\RequestInterface $request
* @return array decoded result
* @throws Google_Service_Exception on server side error (ie: not authenticated,
* invalid or malformed post body, invalid url)
*/
public static function doExecute(ClientInterface $client, RequestInterface $request, $expectedClass = null)
{
try {
$httpHandler = HttpHandlerFactory::build($client);
$response = $httpHandler($request);
} catch (RequestException $e) {
// if Guzzle throws an exception, catch it and handle the response
if (!$e->hasResponse()) {
throw $e;
}
$response = $e->getResponse();
// specific checking for Guzzle 5: convert to PSR7 response
if ($response instanceof \WPvividGuzzleHttp\Message\ResponseInterface) {
$response = new Response(
$response->getStatusCode(),
$response->getHeaders() ?: [],
$response->getBody(),
$response->getProtocolVersion(),
$response->getReasonPhrase()
);
}
}
return self::decodeHttpResponse($response, $request, $expectedClass);
}
/**
* Decode an HTTP Response.
* @static
* @throws Google_Service_Exception
* @param Psr\Http\Message\RequestInterface $response The http response to be decoded.
* @param Psr\Http\Message\ResponseInterface $response
* @return mixed|null
*/
public static function decodeHttpResponse(
ResponseInterface $response,
RequestInterface $request = null,
$expectedClass = null
) {
$code = $response->getStatusCode();
// retry strategy
if (intVal($code) >= 400) {
// if we errored out, it should be safe to grab the response body
$body = (string) $response->getBody();
// Check if we received errors, and add those to the Exception for convenience
throw new Google_Service_Exception(esc_html($body), esc_attr($code), null, esc_html(self::getResponseErrors($body)));
}
// Ensure we only pull the entire body into memory if the request is not
// of media type
$body = self::decodeBody($response, $request);
if ($expectedClass = self::determineExpectedClass($expectedClass, $request)) {
$json = json_decode($body, true);
return new $expectedClass($json);
}
return $response;
}
private static function decodeBody(ResponseInterface $response, RequestInterface $request = null)
{
if (self::isAltMedia($request)) {
// don't decode the body, it's probably a really long string
return '';
}
return (string) $response->getBody();
}
private static function determineExpectedClass($expectedClass, RequestInterface $request = null)
{
// "false" is used to explicitly prevent an expected class from being returned
if (false === $expectedClass) {
return null;
}
// if we don't have a request, we just use what's passed in
if (null === $request) {
return $expectedClass;
}
// return what we have in the request header if one was not supplied
return $expectedClass ?: $request->getHeaderLine('X-Php-Expected-Class');
}
private static function getResponseErrors($body)
{
$json = json_decode($body, true);
if (isset($json['error']['errors'])) {
return $json['error']['errors'];
}
return null;
}
private static function isAltMedia(RequestInterface $request = null)
{
if ($request && $qs = $request->getUri()->getQuery()) {
parse_str($qs, $query);
if (isset($query['alt']) && $query['alt'] == 'media') {
return true;
}
}
return false;
}
}
includes/lib/google-api-php-client/src/Google/Task/Retryable.php 0000644 00000001343 15132770567 0020571 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Interface for checking how many times a given task can be retried following
* a failure.
*/
interface Google_Task_Retryable
{
}
includes/lib/google-api-php-client/src/Google/Task/Exception.php 0000644 00000001223 15132770567 0020573 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class Google_Task_Exception extends Google_Exception
{
}
includes/lib/google-api-php-client/src/Google/Task/Runner.php 0000644 00000016045 15132770567 0020116 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A task runner with exponential backoff support.
*
* @see https://developers.google.com/drive/web/handle-errors#implementing_exponential_backoff
*/
class Google_Task_Runner
{
const TASK_RETRY_NEVER = 0;
const TASK_RETRY_ONCE = 1;
const TASK_RETRY_ALWAYS = -1;
/**
* @var integer $maxDelay The max time (in seconds) to wait before a retry.
*/
private $maxDelay = 60;
/**
* @var integer $delay The previous delay from which the next is calculated.
*/
private $delay = 1;
/**
* @var integer $factor The base number for the exponential back off.
*/
private $factor = 2;
/**
* @var float $jitter A random number between -$jitter and $jitter will be
* added to $factor on each iteration to allow for a better distribution of
* retries.
*/
private $jitter = 0.5;
/**
* @var integer $attempts The number of attempts that have been tried so far.
*/
private $attempts = 0;
/**
* @var integer $maxAttempts The max number of attempts allowed.
*/
private $maxAttempts = 1;
/**
* @var callable $action The task to run and possibly retry.
*/
private $action;
/**
* @var array $arguments The task arguments.
*/
private $arguments;
/**
* @var array $retryMap Map of errors with retry counts.
*/
protected $retryMap = [
'500' => self::TASK_RETRY_ALWAYS,
'503' => self::TASK_RETRY_ALWAYS,
'rateLimitExceeded' => self::TASK_RETRY_ALWAYS,
'userRateLimitExceeded' => self::TASK_RETRY_ALWAYS,
6 => self::TASK_RETRY_ALWAYS, // CURLE_COULDNT_RESOLVE_HOST
7 => self::TASK_RETRY_ALWAYS, // CURLE_COULDNT_CONNECT
28 => self::TASK_RETRY_ALWAYS, // CURLE_OPERATION_TIMEOUTED
35 => self::TASK_RETRY_ALWAYS, // CURLE_SSL_CONNECT_ERROR
52 => self::TASK_RETRY_ALWAYS // CURLE_GOT_NOTHING
];
/**
* Creates a new task runner with exponential backoff support.
*
* @param array $config The task runner config
* @param string $name The name of the current task (used for logging)
* @param callable $action The task to run and possibly retry
* @param array $arguments The task arguments
* @throws Google_Task_Exception when misconfigured
*/
public function __construct(
$config,
$name,
$action,
array $arguments = array()
) {
if (isset($config['initial_delay'])) {
if ($config['initial_delay'] < 0) {
throw new Google_Task_Exception(
'Task configuration `initial_delay` must not be negative.'
);
}
$this->delay = $config['initial_delay'];
}
if (isset($config['max_delay'])) {
if ($config['max_delay'] <= 0) {
throw new Google_Task_Exception(
'Task configuration `max_delay` must be greater than 0.'
);
}
$this->maxDelay = $config['max_delay'];
}
if (isset($config['factor'])) {
if ($config['factor'] <= 0) {
throw new Google_Task_Exception(
'Task configuration `factor` must be greater than 0.'
);
}
$this->factor = $config['factor'];
}
if (isset($config['jitter'])) {
if ($config['jitter'] <= 0) {
throw new Google_Task_Exception(
'Task configuration `jitter` must be greater than 0.'
);
}
$this->jitter = $config['jitter'];
}
if (isset($config['retries'])) {
if ($config['retries'] < 0) {
throw new Google_Task_Exception(
'Task configuration `retries` must not be negative.'
);
}
$this->maxAttempts += $config['retries'];
}
if (!is_callable($action)) {
throw new Google_Task_Exception(
'Task argument `$action` must be a valid callable.'
);
}
$this->action = $action;
$this->arguments = $arguments;
}
/**
* Checks if a retry can be attempted.
*
* @return boolean
*/
public function canAttempt()
{
return $this->attempts < $this->maxAttempts;
}
/**
* Runs the task and (if applicable) automatically retries when errors occur.
*
* @return mixed
* @throws Google_Task_Retryable on failure when no retries are available.
*/
public function run()
{
while ($this->attempt()) {
try {
return call_user_func_array($this->action, $this->arguments);
} catch (Google_Service_Exception $exception) {
$allowedRetries = $this->allowedRetries(
$exception->getCode(),
$exception->getErrors()
);
if (!$this->canAttempt() || !$allowedRetries) {
throw $exception;
}
if ($allowedRetries > 0) {
$this->maxAttempts = min(
$this->maxAttempts,
$this->attempts + $allowedRetries
);
}
}
}
}
/**
* Runs a task once, if possible. This is useful for bypassing the `run()`
* loop.
*
* NOTE: If this is not the first attempt, this function will sleep in
* accordance to the backoff configurations before running the task.
*
* @return boolean
*/
public function attempt()
{
if (!$this->canAttempt()) {
return false;
}
if ($this->attempts > 0) {
$this->backOff();
}
$this->attempts++;
return true;
}
/**
* Sleeps in accordance to the backoff configurations.
*/
private function backOff()
{
$delay = $this->getDelay();
usleep($delay * 1000000);
}
/**
* Gets the delay (in seconds) for the current backoff period.
*
* @return float
*/
private function getDelay()
{
$jitter = $this->getJitter();
$factor = $this->attempts > 1 ? $this->factor + $jitter : 1 + abs($jitter);
return $this->delay = min($this->maxDelay, $this->delay * $factor);
}
/**
* Gets the current jitter (random number between -$this->jitter and
* $this->jitter).
*
* @return float
*/
private function getJitter()
{
return $this->jitter * 2 * mt_rand() / mt_getrandmax() - $this->jitter;
}
/**
* Gets the number of times the associated task can be retried.
*
* NOTE: -1 is returned if the task can be retried indefinitely
*
* @return integer
*/
public function allowedRetries($code, $errors = array())
{
if (isset($this->retryMap[$code])) {
return $this->retryMap[$code];
}
if (
!empty($errors) &&
isset($errors[0]['reason'], $this->retryMap[$errors[0]['reason']])
) {
return $this->retryMap[$errors[0]['reason']];
}
return 0;
}
public function setRetryMap($retryMap)
{
$this->retryMap = $retryMap;
}
}
includes/lib/google-api-php-client/src/Google/Exception.php 0000644 00000001207 15132770567 0017673 0 ustar 00 <?php
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class Google_Exception extends Exception
{
}
includes/lib/google-api-php-client/src/Google/autoload.php 0000644 00000001345 15132770567 0017550 0 ustar 00 <?php
/**
* THIS FILE IS FOR BACKWARDS COMPATIBLITY ONLY
*
* If you were not already including this file in your project, please ignore it
*/
$file = __DIR__ . '/../../vendor/autoload.php';
if (!file_exists($file)) {
$exception = 'This library must be installed via composer or by downloading the full package.';
$exception .= ' See the instructions at https://github.com/google/google-api-php-client#installation.';
throw new Exception(esc_html($exception));
}
$error = 'google-api-php-client\'s autoloader was moved to vendor/autoload.php in 2.0.0. This ';
$error .= 'redirect will be removed in 2.1. Please adjust your code to use the new location.';
trigger_error(esc_html($error), E_USER_DEPRECATED);
require_once $file;
includes/lib/google-api-php-client/src/Google/Model.php 0000644 00000021145 15132770567 0017000 0 ustar 00 <?php
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This class defines attributes, valid values, and usage which is generated
* from a given json schema.
* http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5
*
*/
class Google_Model implements ArrayAccess
{
/**
* If you need to specify a NULL JSON value, use Google_Model::NULL_VALUE
* instead - it will be replaced when converting to JSON with a real null.
*/
const NULL_VALUE = "{}gapi-php-null";
protected $internal_gapi_mappings = array();
protected $modelData = array();
protected $processed = array();
/**
* Polymorphic - accepts a variable number of arguments dependent
* on the type of the model subclass.
*/
final public function __construct()
{
if (func_num_args() == 1 && is_array(func_get_arg(0))) {
// Initialize the model with the array's contents.
$array = func_get_arg(0);
$this->mapTypes($array);
}
$this->gapiInit();
}
/**
* Getter that handles passthrough access to the data array, and lazy object creation.
* @param string $key Property name.
* @return mixed The value if any, or null.
*/
public function __get($key)
{
$keyType = $this->keyType($key);
$keyDataType = $this->dataType($key);
if ($keyType && !isset($this->processed[$key])) {
if (isset($this->modelData[$key])) {
$val = $this->modelData[$key];
} elseif ($keyDataType == 'array' || $keyDataType == 'map') {
$val = array();
} else {
$val = null;
}
if ($this->isAssociativeArray($val)) {
if ($keyDataType && 'map' == $keyDataType) {
foreach ($val as $arrayKey => $arrayItem) {
$this->modelData[$key][$arrayKey] =
new $keyType($arrayItem);
}
} else {
$this->modelData[$key] = new $keyType($val);
}
} else if (is_array($val)) {
$arrayObject = array();
foreach ($val as $arrayIndex => $arrayItem) {
$arrayObject[$arrayIndex] = new $keyType($arrayItem);
}
$this->modelData[$key] = $arrayObject;
}
$this->processed[$key] = true;
}
return isset($this->modelData[$key]) ? $this->modelData[$key] : null;
}
/**
* Initialize this object's properties from an array.
*
* @param array $array Used to seed this object's properties.
* @return void
*/
protected function mapTypes($array)
{
// Hard initialise simple types, lazy load more complex ones.
foreach ($array as $key => $val) {
if ($keyType = $this->keyType($key)) {
$dataType = $this->dataType($key);
if ($dataType == 'array' || $dataType == 'map') {
$this->$key = array();
foreach ($val as $itemKey => $itemVal) {
if ($itemVal instanceof $keyType) {
$this->{$key}[$itemKey] = $itemVal;
} else {
$this->{$key}[$itemKey] = new $keyType($itemVal);
}
}
} elseif ($val instanceof $keyType) {
$this->$key = $val;
} else {
$this->$key = new $keyType($val);
}
unset($array[$key]);
} elseif (property_exists($this, $key)) {
$this->$key = $val;
unset($array[$key]);
} elseif (property_exists($this, $camelKey = $this->camelCase($key))) {
// This checks if property exists as camelCase, leaving it in array as snake_case
// in case of backwards compatibility issues.
$this->$camelKey = $val;
}
}
$this->modelData = $array;
}
/**
* Blank initialiser to be used in subclasses to do post-construction initialisation - this
* avoids the need for subclasses to have to implement the variadics handling in their
* constructors.
*/
protected function gapiInit()
{
return;
}
/**
* Create a simplified object suitable for straightforward
* conversion to JSON. This is relatively expensive
* due to the usage of reflection, but shouldn't be called
* a whole lot, and is the most straightforward way to filter.
*/
public function toSimpleObject()
{
$object = new stdClass();
// Process all other data.
foreach ($this->modelData as $key => $val) {
$result = $this->getSimpleValue($val);
if ($result !== null) {
$object->$key = $this->nullPlaceholderCheck($result);
}
}
// Process all public properties.
$reflect = new ReflectionObject($this);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($props as $member) {
$name = $member->getName();
$result = $this->getSimpleValue($this->$name);
if ($result !== null) {
$name = $this->getMappedName($name);
$object->$name = $this->nullPlaceholderCheck($result);
}
}
return $object;
}
/**
* Handle different types of values, primarily
* other objects and map and array data types.
*/
private function getSimpleValue($value)
{
if ($value instanceof Google_Model) {
return $value->toSimpleObject();
} else if (is_array($value)) {
$return = array();
foreach ($value as $key => $a_value) {
$a_value = $this->getSimpleValue($a_value);
if ($a_value !== null) {
$key = $this->getMappedName($key);
$return[$key] = $this->nullPlaceholderCheck($a_value);
}
}
return $return;
}
return $value;
}
/**
* Check whether the value is the null placeholder and return true null.
*/
private function nullPlaceholderCheck($value)
{
if ($value === self::NULL_VALUE) {
return null;
}
return $value;
}
/**
* If there is an internal name mapping, use that.
*/
private function getMappedName($key)
{
if (isset($this->internal_gapi_mappings, $this->internal_gapi_mappings[$key])) {
$key = $this->internal_gapi_mappings[$key];
}
return $key;
}
/**
* Returns true only if the array is associative.
* @param array $array
* @return bool True if the array is associative.
*/
protected function isAssociativeArray($array)
{
if (!is_array($array)) {
return false;
}
$keys = array_keys($array);
foreach ($keys as $key) {
if (is_string($key)) {
return true;
}
}
return false;
}
/**
* Verify if $obj is an array.
* @throws Google_Exception Thrown if $obj isn't an array.
* @param array $obj Items that should be validated.
* @param string $method Method expecting an array as an argument.
*/
public function assertIsArray($obj, $method)
{
if ($obj && !is_array($obj)) {
throw new Google_Exception(
esc_html("Incorrect parameter type passed to $method(). Expected an array.")
);
}
}
public function offsetExists($offset)
{
return isset($this->$offset) || isset($this->modelData[$offset]);
}
public function offsetGet($offset)
{
return isset($this->$offset) ?
$this->$offset :
$this->__get($offset);
}
public function offsetSet($offset, $value)
{
if (property_exists($this, $offset)) {
$this->$offset = $value;
} else {
$this->modelData[$offset] = $value;
$this->processed[$offset] = true;
}
}
public function offsetUnset($offset)
{
unset($this->modelData[$offset]);
}
protected function keyType($key)
{
$keyType = $key . "Type";
// ensure keyType is a valid class
if (property_exists($this, $keyType) && class_exists($this->$keyType)) {
return $this->$keyType;
}
}
protected function dataType($key)
{
$dataType = $key . "DataType";
if (property_exists($this, $dataType)) {
return $this->$dataType;
}
}
public function __isset($key)
{
return isset($this->modelData[$key]);
}
public function __unset($key)
{
unset($this->modelData[$key]);
}
/**
* Convert a string to camelCase
* @param string $value
* @return string
*/
private function camelCase($value)
{
$value = ucwords(str_replace(array('-', '_'), ' ', $value));
$value = str_replace(' ', '', $value);
$value[0] = strtolower($value[0]);
return $value;
}
}
includes/lib/google-api-php-client/src/Google/Service/Exception.php 0000644 00000003533 15132770567 0021277 0 ustar 00 <?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class Google_Service_Exception extends Google_Exception
{
/**
* Optional list of errors returned in a JSON body of an HTTP error response.
*/
protected $errors = array();
/**
* Override default constructor to add the ability to set $errors and a retry
* map.
*
* @param string $message
* @param int $code
* @param Exception|null $previous
* @param [{string, string}] errors List of errors returned in an HTTP
* response. Defaults to [].
* @param array|null $retryMap Map of errors with retry counts.
*/
public function __construct(
$message,
$code = 0,
Exception $previous = null,
$errors = array()
) {
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
parent::__construct($message, $code, $previous);
} else {
parent::__construct($message, $code);
}
$this->errors = $errors;
}
/**
* An example of the possible errors returned.
*
* {
* "domain": "global",
* "reason": "authError",
* "message": "Invalid Credentials",
* "locationType": "header",
* "location": "Authorization",
* }
*
* @return [{string, string}] List of errors return in an HTTP response or [].
*/
public function getErrors()
{
return $this->errors;
}
}
includes/lib/google-api-php-client/src/Google/Service/README.md 0000644 00000000301 15132770567 0020075 0 ustar 00 # Google API Client Services
Google API Client Service classes have been moved to the
[google-api-php-client-services](https://github.com/google/google-api-php-client-services)
repository.
includes/lib/google-api-php-client/src/Google/Service/Resource.php 0000644 00000023704 15132770567 0021132 0 ustar 00 <?php
/**
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGuzzleHttp\Psr7\Request;
/**
* Implements the actual methods/resources of the discovered Google API using magic function
* calling overloading (__call()), which on call will see if the method name (plus.activities.list)
* is available in this service, and if so construct an apiHttpRequest representing it.
*
*/
class Google_Service_Resource
{
// Valid query parameters that work, but don't appear in discovery.
private $stackParameters = array(
'alt' => array('type' => 'string', 'location' => 'query'),
'fields' => array('type' => 'string', 'location' => 'query'),
'trace' => array('type' => 'string', 'location' => 'query'),
'userIp' => array('type' => 'string', 'location' => 'query'),
'quotaUser' => array('type' => 'string', 'location' => 'query'),
'data' => array('type' => 'string', 'location' => 'body'),
'mimeType' => array('type' => 'string', 'location' => 'header'),
'uploadType' => array('type' => 'string', 'location' => 'query'),
'mediaUpload' => array('type' => 'complex', 'location' => 'query'),
'prettyPrint' => array('type' => 'string', 'location' => 'query'),
);
/** @var string $rootUrl */
private $rootUrl;
/** @var Google_Client $client */
private $client;
/** @var string $serviceName */
private $serviceName;
/** @var string $servicePath */
private $servicePath;
/** @var string $resourceName */
private $resourceName;
/** @var array $methods */
private $methods;
public function __construct($service, $serviceName, $resourceName, $resource)
{
$this->rootUrl = $service->rootUrl;
$this->client = $service->getClient();
$this->servicePath = $service->servicePath;
$this->serviceName = $serviceName;
$this->resourceName = $resourceName;
$this->methods = is_array($resource) && isset($resource['methods']) ?
$resource['methods'] :
array($resourceName => $resource);
}
/**
* TODO: This function needs simplifying.
* @param $name
* @param $arguments
* @param $expectedClass - optional, the expected class name
* @return Google_Http_Request|expectedClass
* @throws Google_Exception
*/
public function call($name, $arguments, $expectedClass = null)
{
if (! isset($this->methods[$name])) {
$this->client->getLogger()->error(
'Service method unknown',
array(
'service' => $this->serviceName,
'resource' => $this->resourceName,
'method' => $name
)
);
throw new Google_Exception(
"Unknown function: " .
esc_html("{$this->serviceName}->{$this->resourceName}->{$name}()")
);
}
$method = $this->methods[$name];
$parameters = $arguments[0];
// postBody is a special case since it's not defined in the discovery
// document as parameter, but we abuse the param entry for storing it.
$postBody = null;
if (isset($parameters['postBody'])) {
if ($parameters['postBody'] instanceof Google_Model) {
// In the cases the post body is an existing object, we want
// to use the smart method to create a simple object for
// for JSONification.
$parameters['postBody'] = $parameters['postBody']->toSimpleObject();
} else if (is_object($parameters['postBody'])) {
// If the post body is another kind of object, we will try and
// wrangle it into a sensible format.
$parameters['postBody'] =
$this->convertToArrayAndStripNulls($parameters['postBody']);
}
$postBody = (array) $parameters['postBody'];
unset($parameters['postBody']);
}
// TODO: optParams here probably should have been
// handled already - this may well be redundant code.
if (isset($parameters['optParams'])) {
$optParams = $parameters['optParams'];
unset($parameters['optParams']);
$parameters = array_merge($parameters, $optParams);
}
if (!isset($method['parameters'])) {
$method['parameters'] = array();
}
$method['parameters'] = array_merge(
$this->stackParameters,
$method['parameters']
);
foreach ($parameters as $key => $val) {
if ($key != 'postBody' && ! isset($method['parameters'][$key])) {
$this->client->getLogger()->error(
'Service parameter unknown',
array(
'service' => $this->serviceName,
'resource' => $this->resourceName,
'method' => $name,
'parameter' => $key
)
);
throw new Google_Exception(esc_html("($name) unknown parameter: '$key'"));
}
}
foreach ($method['parameters'] as $paramName => $paramSpec) {
if (isset($paramSpec['required']) &&
$paramSpec['required'] &&
! isset($parameters[$paramName])
) {
$this->client->getLogger()->error(
'Service parameter missing',
array(
'service' => $this->serviceName,
'resource' => $this->resourceName,
'method' => $name,
'parameter' => $paramName
)
);
throw new Google_Exception(esc_html("($name) missing required param: '$paramName'"));
}
if (isset($parameters[$paramName])) {
$value = $parameters[$paramName];
$parameters[$paramName] = $paramSpec;
$parameters[$paramName]['value'] = $value;
unset($parameters[$paramName]['required']);
} else {
// Ensure we don't pass nulls.
unset($parameters[$paramName]);
}
}
$this->client->getLogger()->info(
'Service Call',
array(
'service' => $this->serviceName,
'resource' => $this->resourceName,
'method' => $name,
'arguments' => $parameters,
)
);
// build the service uri
$url = $this->createRequestUri(
$method['path'],
$parameters
);
// NOTE: because we're creating the request by hand,
// and because the service has a rootUrl property
// the "base_uri" of the Http Client is not accounted for
$request = new Request(
$method['httpMethod'],
$url,
['content-type' => 'application/json'],
$postBody ? json_encode($postBody) : ''
);
// support uploads
if (isset($parameters['data'])) {
$mimeType = isset($parameters['mimeType'])
? $parameters['mimeType']['value']
: 'application/octet-stream';
$data = $parameters['data']['value'];
$upload = new Google_Http_MediaFileUpload($this->client, $request, $mimeType, $data);
// pull down the modified request
$request = $upload->getRequest();
}
// if this is a media type, we will return the raw response
// rather than using an expected class
if (isset($parameters['alt']) && $parameters['alt']['value'] == 'media') {
$expectedClass = null;
}
// if the client is marked for deferring, rather than
// execute the request, return the response
if ($this->client->shouldDefer()) {
// @TODO find a better way to do this
$request = $request
->withHeader('X-Php-Expected-Class', $expectedClass);
return $request;
}
return $this->client->execute($request, $expectedClass);
}
protected function convertToArrayAndStripNulls($o)
{
$o = (array) $o;
foreach ($o as $k => $v) {
if ($v === null) {
unset($o[$k]);
} elseif (is_object($v) || is_array($v)) {
$o[$k] = $this->convertToArrayAndStripNulls($o[$k]);
}
}
return $o;
}
/**
* Parse/expand request parameters and create a fully qualified
* request uri.
* @static
* @param string $restPath
* @param array $params
* @return string $requestUrl
*/
public function createRequestUri($restPath, $params)
{
// Override the default servicePath address if the $restPath use a /
if ('/' == substr($restPath, 0, 1)) {
$requestUrl = substr($restPath, 1);
} else {
$requestUrl = $this->servicePath . $restPath;
}
// code for leading slash
if ($this->rootUrl) {
if ('/' !== substr($this->rootUrl, -1) && '/' !== substr($requestUrl, 0, 1)) {
$requestUrl = '/' . $requestUrl;
}
$requestUrl = $this->rootUrl . $requestUrl;
}
$uriTemplateVars = array();
$queryVars = array();
foreach ($params as $paramName => $paramSpec) {
if ($paramSpec['type'] == 'boolean') {
$paramSpec['value'] = $paramSpec['value'] ? 'true' : 'false';
}
if ($paramSpec['location'] == 'path') {
$uriTemplateVars[$paramName] = $paramSpec['value'];
} else if ($paramSpec['location'] == 'query') {
if (is_array($paramSpec['value'])) {
foreach ($paramSpec['value'] as $value) {
$queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($value));
}
} else {
$queryVars[] = $paramName . '=' . rawurlencode(rawurldecode($paramSpec['value']));
}
}
}
if (count($uriTemplateVars)) {
$uriTemplateParser = new Google_Utils_UriTemplate();
$requestUrl = $uriTemplateParser->parse($requestUrl, $uriTemplateVars);
}
if (count($queryVars)) {
if (version_compare(PHP_VERSION, '7.4', '>=')) {
$requestUrl .= '?' . implode('&', $queryVars);
}
else{
$requestUrl .= '?' . implode($queryVars, '&');
}
}
return $requestUrl;
}
}
includes/lib/google-api-php-client/src/Google/Service.php 0000644 00000002411 15132770567 0017333 0 ustar 00 <?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class Google_Service
{
public $batchPath;
public $rootUrl;
public $version;
public $servicePath;
public $availableScopes;
public $resource;
private $client;
public function __construct(Google_Client $client)
{
$this->client = $client;
}
/**
* Return the associated Google_Client class.
* @return Google_Client
*/
public function getClient()
{
return $this->client;
}
/**
* Create a new HTTP Batch handler for this service
*
* @return Google_Http_Batch
*/
public function createBatch()
{
return new Google_Http_Batch(
$this->client,
false,
$this->rootUrl,
$this->batchPath
);
}
}
includes/lib/google-api-php-client/src/Google/AccessToken/Verify.php 0000644 00000016472 15132770567 0021415 0 ustar 00 <?php
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use Firebase\JWT\ExpiredException as ExpiredExceptionV3;
use Firebase\JWT\SignatureInvalidException;
use WPvividGuzzleHttp\Client;
use WPvividGuzzleHttp\ClientInterface;
use WPvividPsr\Cache\CacheItemPoolInterface;
use WPvividGoogle\Auth\Cache\MemoryCacheItemPool;
use Stash\Driver\FileSystem;
use Stash\Pool;
/**
* Wrapper around Google Access Tokens which provides convenience functions
*
*/
class Google_AccessToken_Verify
{
const FEDERATED_SIGNON_CERT_URL = 'https://www.googleapis.com/oauth2/v3/certs';
const OAUTH2_ISSUER = 'accounts.google.com';
const OAUTH2_ISSUER_HTTPS = 'https://accounts.google.com';
/**
* @var GuzzleHttp\ClientInterface The http client
*/
private $http;
/**
* @var Psr\Cache\CacheItemPoolInterface cache class
*/
private $cache;
/**
* Instantiates the class, but does not initiate the login flow, leaving it
* to the discretion of the caller.
*/
public function __construct(
ClientInterface $http = null,
CacheItemPoolInterface $cache = null,
$jwt = null
) {
if (null === $http) {
$http = new Client();
}
if (null === $cache) {
$cache = new MemoryCacheItemPool;
}
$this->http = $http;
$this->cache = $cache;
$this->jwt = $jwt ?: $this->getJwtService();
}
/**
* Verifies an id token and returns the authenticated apiLoginTicket.
* Throws an exception if the id token is not valid.
* The audience parameter can be used to control which id tokens are
* accepted. By default, the id token must have been issued to this OAuth2 client.
*
* @param $audience
* @return array the token payload, if successful
*/
public function verifyIdToken($idToken, $audience = null)
{
if (empty($idToken)) {
throw new LogicException('id_token cannot be null');
}
// set phpseclib constants if applicable
$this->setPhpsecConstants();
// Check signature
$certs = $this->getFederatedSignOnCerts();
foreach ($certs as $cert) {
$bigIntClass = $this->getBigIntClass();
$rsaClass = $this->getRsaClass();
$modulus = new $bigIntClass($this->jwt->urlsafeB64Decode($cert['n']), 256);
$exponent = new $bigIntClass($this->jwt->urlsafeB64Decode($cert['e']), 256);
$rsa = new $rsaClass();
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
try {
$payload = $this->jwt->decode(
$idToken,
$rsa->getPublicKey(),
array('RS256')
);
if (property_exists($payload, 'aud')) {
if ($audience && $payload->aud != $audience) {
return false;
}
}
// support HTTP and HTTPS issuers
// @see https://developers.google.com/identity/sign-in/web/backend-auth
$issuers = array(self::OAUTH2_ISSUER, self::OAUTH2_ISSUER_HTTPS);
if (!isset($payload->iss) || !in_array($payload->iss, $issuers)) {
return false;
}
return (array) $payload;
} catch (ExpiredException $e) {
return false;
} catch (ExpiredExceptionV3 $e) {
return false;
} catch (SignatureInvalidException $e) {
// continue
} catch (DomainException $e) {
// continue
}
}
return false;
}
private function getCache()
{
return $this->cache;
}
/**
* Retrieve and cache a certificates file.
*
* @param $url string location
* @throws Google_Exception
* @return array certificates
*/
private function retrieveCertsFromLocation($url)
{
// If we're retrieving a local file, just grab it.
if (0 !== strpos($url, 'http')) {
if (!$file = file_get_contents($url)) {
throw new Google_Exception(
"Failed to retrieve verification certificates: '" .
esc_url($url) . "'."
);
}
return json_decode($file, true);
}
$response = $this->http->get($url);
if ($response->getStatusCode() == 200) {
return json_decode((string) $response->getBody(), true);
}
throw new Google_Exception(
sprintf(
'Failed to retrieve verification certificates: "%s".',
esc_html($response->getBody()->getContents())
),
esc_attr($response->getStatusCode())
);
}
// Gets federated sign-on certificates to use for verifying identity tokens.
// Returns certs as array structure, where keys are key ids, and values
// are PEM encoded certificates.
private function getFederatedSignOnCerts()
{
$certs = null;
if ($cache = $this->getCache()) {
$cacheItem = $cache->getItem('federated_signon_certs_v3');
$certs = $cacheItem->get();
}
if (!$certs) {
$certs = $this->retrieveCertsFromLocation(
self::FEDERATED_SIGNON_CERT_URL
);
if ($cache) {
$cacheItem->expiresAt(new DateTime('+1 hour'));
$cacheItem->set($certs);
$cache->save($cacheItem);
}
}
if (!isset($certs['keys'])) {
throw new InvalidArgumentException(
'federated sign-on certs expects "keys" to be set'
);
}
return $certs['keys'];
}
private function getJwtService()
{
$jwtClass = 'JWT';
if (class_exists('\Firebase\JWT\JWT')) {
$jwtClass = 'Firebase\JWT\JWT';
}
if (property_exists($jwtClass, 'leeway') && $jwtClass::$leeway < 1) {
// Ensures JWT leeway is at least 1
// @see https://github.com/google/google-api-php-client/issues/827
$jwtClass::$leeway = 1;
}
return new $jwtClass;
}
private function getRsaClass()
{
if (class_exists('phpseclib\Crypt\RSA')) {
return 'phpseclib\Crypt\RSA';
}
return 'Crypt_RSA';
}
private function getBigIntClass()
{
if (class_exists('phpseclib\Math\BigInteger')) {
return 'phpseclib\Math\BigInteger';
}
return 'Math_BigInteger';
}
private function getOpenSslConstant()
{
if (class_exists('phpseclib\Crypt\RSA')) {
return 'phpseclib\Crypt\RSA::MODE_OPENSSL';
}
if (class_exists('Crypt_RSA')) {
return 'CRYPT_RSA_MODE_OPENSSL';
}
throw new \Exception('Cannot find RSA class');
}
/**
* phpseclib calls "phpinfo" by default, which requires special
* whitelisting in the AppEngine VM environment. This function
* sets constants to bypass the need for phpseclib to check phpinfo
*
* @see phpseclib/Math/BigInteger
* @see https://github.com/GoogleCloudPlatform/getting-started-php/issues/85
*/
private function setPhpsecConstants()
{
if (filter_var(getenv('GAE_VM'), FILTER_VALIDATE_BOOLEAN)) {
if (!defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) {
define('MATH_BIGINTEGER_OPENSSL_ENABLED', true);
}
if (!defined('CRYPT_RSA_MODE')) {
define('CRYPT_RSA_MODE', constant($this->getOpenSslConstant()));
}
}
}
}
includes/lib/google-api-php-client/src/Google/AccessToken/Revoke.php 0000644 00000004246 15132770567 0021400 0 ustar 00 <?php
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGoogle\Auth\HttpHandler\HttpHandlerFactory;
use WPvividGuzzleHttp\ClientInterface;
use WPvividGuzzleHttp\Psr7;
use WPvividGuzzleHttp\Psr7\Request;
/**
* Wrapper around Google Access Tokens which provides convenience functions
*
*/
class Google_AccessToken_Revoke
{
/**
* @var GuzzleHttp\ClientInterface The http client
*/
private $http;
/**
* Instantiates the class, but does not initiate the login flow, leaving it
* to the discretion of the caller.
*/
public function __construct(ClientInterface $http = null)
{
$this->http = $http;
}
/**
* Revoke an OAuth2 access token or refresh token. This method will revoke the current access
* token, if a token isn't provided.
*
* @param string|array $token The token (access token or a refresh token) that should be revoked.
* @return boolean Returns True if the revocation was successful, otherwise False.
*/
public function revokeToken($token)
{
if (is_array($token)) {
if (isset($token['refresh_token'])) {
$token = $token['refresh_token'];
} else {
$token = $token['access_token'];
}
}
$body = Psr7\stream_for(http_build_query(array('token' => $token)));
$request = new Request(
'POST',
Google_Client::OAUTH2_REVOKE_URI,
[
'Cache-Control' => 'no-store',
'Content-Type' => 'application/x-www-form-urlencoded',
],
$body
);
$httpHandler = HttpHandlerFactory::build($this->http);
$response = $httpHandler($request);
return $response->getStatusCode() == 200;
}
}
includes/lib/google-api-php-client/src/Google/Client.php 0000644 00000076714 15132770567 0017172 0 ustar 00 <?php
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use WPvividGoogle\Auth\ApplicationDefaultCredentials;
use WPvividGoogle\Auth\Cache\MemoryCacheItemPool;
use WPvividGoogle\Auth\CredentialsLoader;
use WPvividGoogle\Auth\HttpHandler\HttpHandlerFactory;
use WPvividGoogle\Auth\OAuth2;
use WPvividGoogle\Auth\Credentials\ServiceAccountCredentials;
use WPvividGoogle\Auth\Credentials\UserRefreshCredentials;
use WPvividGuzzleHttp\Client;
use WPvividGuzzleHttp\ClientInterface;
use WPvividGuzzleHttp\Ring\Client\StreamHandler;
use WPvividPsr\Cache\CacheItemPoolInterface;
use WPvividPsr\Http\Message\RequestInterface;
use WPvividPsr\Log\LoggerInterface;
use WPvividMonolog\Logger;
use WPvividMonolog\Handler\StreamHandler as MonologStreamHandler;
use WPvividMonolog\Handler\SyslogHandler as MonologSyslogHandler;
/**
* The Google API Client
* https://github.com/google/google-api-php-client
*/
class Google_Client
{
const LIBVER = "2.2.2";
const USER_AGENT_SUFFIX = "google-api-php-client/";
const OAUTH2_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke';
const OAUTH2_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token';
const OAUTH2_AUTH_URL = 'https://accounts.google.com/o/oauth2/auth';
const API_BASE_PATH = 'https://www.googleapis.com';
/**
* @var Google\Auth\OAuth2 $auth
*/
private $auth;
/**
* @var GuzzleHttp\ClientInterface $http
*/
private $http;
/**
* @var Psr\Cache\CacheItemPoolInterface $cache
*/
private $cache;
/**
* @var array access token
*/
private $token;
/**
* @var array $config
*/
private $config;
/**
* @var Psr\Log\LoggerInterface $logger
*/
private $logger;
/**
* @var boolean $deferExecution
*/
private $deferExecution = false;
/** @var array $scopes */
// Scopes requested by the client
protected $requestedScopes = [];
/**
* Construct the Google Client.
*
* @param array $config
*/
public function __construct(array $config = array())
{
$this->config = array_merge(
[
'application_name' => '',
// Don't change these unless you're working against a special development
// or testing environment.
'base_path' => self::API_BASE_PATH,
// https://developers.google.com/console
'client_id' => '',
'client_secret' => '',
'redirect_uri' => null,
'state' => null,
// Simple API access key, also from the API console. Ensure you get
// a Server key, and not a Browser key.
'developer_key' => '',
// For use with Google Cloud Platform
// fetch the ApplicationDefaultCredentials, if applicable
// @see https://developers.google.com/identity/protocols/application-default-credentials
'use_application_default_credentials' => false,
'signing_key' => null,
'signing_algorithm' => null,
'subject' => null,
// Other OAuth2 parameters.
'hd' => '',
'prompt' => '',
'openid.realm' => '',
'include_granted_scopes' => null,
'login_hint' => '',
'request_visible_actions' => '',
'access_type' => 'online',
'approval_prompt' => 'auto',
// Task Runner retry configuration
// @see Google_Task_Runner
'retry' => array(),
// cache config for downstream auth caching
'cache_config' => [],
// function to be called when an access token is fetched
// follows the signature function ($cacheKey, $accessToken)
'token_callback' => null,
// Service class used in Google_Client::verifyIdToken.
// Explicitly pass this in to avoid setting JWT::$leeway
'jwt' => null,
],
$config
);
}
/**
* Get a string containing the version of the library.
*
* @return string
*/
public function getLibraryVersion()
{
return self::LIBVER;
}
/**
* For backwards compatibility
* alias for fetchAccessTokenWithAuthCode
*
* @param $code string code from accounts.google.com
* @return array access token
* @deprecated
*/
public function authenticate($code)
{
return $this->fetchAccessTokenWithAuthCode($code);
}
/**
* Attempt to exchange a code for an valid authentication token.
* Helper wrapped around the OAuth 2.0 implementation.
*
* @param $code string code from accounts.google.com
* @return array access token
*/
public function fetchAccessTokenWithAuthCode($code)
{
if (strlen($code) == 0) {
throw new InvalidArgumentException("Invalid code");
}
$auth = $this->getOAuth2Service();
$auth->setCode($code);
$auth->setRedirectUri($this->getRedirectUri());
$httpHandler = HttpHandlerFactory::build($this->getHttpClient());
$creds = $auth->fetchAuthToken($httpHandler);
if ($creds && isset($creds['access_token'])) {
$creds['created'] = time();
$this->setAccessToken($creds);
}
return $creds;
}
/**
* For backwards compatibility
* alias for fetchAccessTokenWithAssertion
*
* @return array access token
* @deprecated
*/
public function refreshTokenWithAssertion()
{
return $this->fetchAccessTokenWithAssertion();
}
/**
* Fetches a fresh access token with a given assertion token.
* @param ClientInterface $authHttp optional.
* @return array access token
*/
public function fetchAccessTokenWithAssertion(ClientInterface $authHttp = null)
{
if (!$this->isUsingApplicationDefaultCredentials()) {
throw new DomainException(
'set the JSON service account credentials using'
. ' Google_Client::setAuthConfig or set the path to your JSON file'
. ' with the "GOOGLE_APPLICATION_CREDENTIALS" environment variable'
. ' and call Google_Client::useApplicationDefaultCredentials to'
. ' refresh a token with assertion.'
);
}
$this->getLogger()->log(
'info',
'OAuth2 access token refresh with Signed JWT assertion grants.'
);
$credentials = $this->createApplicationDefaultCredentials();
$httpHandler = HttpHandlerFactory::build($authHttp);
$creds = $credentials->fetchAuthToken($httpHandler);
if ($creds && isset($creds['access_token'])) {
$creds['created'] = time();
$this->setAccessToken($creds);
}
return $creds;
}
/**
* For backwards compatibility
* alias for fetchAccessTokenWithRefreshToken
*
* @param string $refreshToken
* @return array access token
*/
public function refreshToken($refreshToken)
{
return $this->fetchAccessTokenWithRefreshToken($refreshToken);
}
/**
* Fetches a fresh OAuth 2.0 access token with the given refresh token.
* @param string $refreshToken
* @return array access token
*/
public function fetchAccessTokenWithRefreshToken($refreshToken = null)
{
if (null === $refreshToken) {
if (!isset($this->token['refresh_token'])) {
throw new LogicException(
'refresh token must be passed in or set as part of setAccessToken'
);
}
$refreshToken = $this->token['refresh_token'];
}
$this->getLogger()->info('OAuth2 access token refresh');
$auth = $this->getOAuth2Service();
$auth->setRefreshToken($refreshToken);
$httpHandler = HttpHandlerFactory::build($this->getHttpClient());
$creds = $auth->fetchAuthToken($httpHandler);
if ($creds && isset($creds['access_token'])) {
$creds['created'] = time();
if (!isset($creds['refresh_token'])) {
$creds['refresh_token'] = $refreshToken;
}
$this->setAccessToken($creds);
}
return $creds;
}
/**
* Create a URL to obtain user authorization.
* The authorization endpoint allows the user to first
* authenticate, and then grant/deny the access request.
* @param string|array $scope The scope is expressed as an array or list of space-delimited strings.
* @return string
*/
public function createAuthUrl($scope = null)
{
if (empty($scope)) {
$scope = $this->prepareScopes();
}
if (is_array($scope)) {
$scope = implode(' ', $scope);
}
// only accept one of prompt or approval_prompt
$approvalPrompt = $this->config['prompt']
? null
: $this->config['approval_prompt'];
// include_granted_scopes should be string "true", string "false", or null
$includeGrantedScopes = $this->config['include_granted_scopes'] === null
? null
: var_export($this->config['include_granted_scopes'], true);
$params = array_filter(
[
'access_type' => $this->config['access_type'],
'approval_prompt' => $approvalPrompt,
'hd' => $this->config['hd'],
'include_granted_scopes' => $includeGrantedScopes,
'login_hint' => $this->config['login_hint'],
'openid.realm' => $this->config['openid.realm'],
'prompt' => $this->config['prompt'],
'response_type' => 'code',
'scope' => $scope,
'state' => $this->config['state'],
]
);
// If the list of scopes contains plus.login, add request_visible_actions
// to auth URL.
$rva = $this->config['request_visible_actions'];
if (strlen($rva) > 0 && false !== strpos($scope, 'plus.login')) {
$params['request_visible_actions'] = $rva;
}
$auth = $this->getOAuth2Service();
return (string) $auth->buildFullAuthorizationUri($params);
}
/**
* Adds auth listeners to the HTTP client based on the credentials
* set in the Google API Client object
*
* @param WPvividGuzzleHttp\ClientInterface $http the http client object.
* @return WPvividGuzzleHttp\ClientInterface the http client object
*/
public function authorize(ClientInterface $http = null)
{
$credentials = null;
$token = null;
$scopes = null;
if (null === $http) {
$http = $this->getHttpClient();
}
// These conditionals represent the decision tree for authentication
// 1. Check for Application Default Credentials
// 2. Check for API Key
// 3a. Check for an Access Token
// 3b. If access token exists but is expired, try to refresh it
if ($this->isUsingApplicationDefaultCredentials()) {
$credentials = $this->createApplicationDefaultCredentials();
} elseif ($token = $this->getAccessToken()) {
$scopes = $this->prepareScopes();
// add refresh subscriber to request a new token
if (isset($token['refresh_token']) && $this->isAccessTokenExpired()) {
$credentials = $this->createUserRefreshCredentials(
$scopes,
$token['refresh_token']
);
}
}
$authHandler = $this->getAuthHandler();
if ($credentials) {
$callback = $this->config['token_callback'];
$http = $authHandler->attachCredentials($http, $credentials, $callback);
} elseif ($token) {
$http = $authHandler->attachToken($http, $token, (array) $scopes);
} elseif ($key = $this->config['developer_key']) {
$http = $authHandler->attachKey($http, $key);
}
return $http;
}
/**
* Set the configuration to use application default credentials for
* authentication
*
* @see https://developers.google.com/identity/protocols/application-default-credentials
* @param boolean $useAppCreds
*/
public function useApplicationDefaultCredentials($useAppCreds = true)
{
$this->config['use_application_default_credentials'] = $useAppCreds;
}
/**
* To prevent useApplicationDefaultCredentials from inappropriately being
* called in a conditional
*
* @see https://developers.google.com/identity/protocols/application-default-credentials
*/
public function isUsingApplicationDefaultCredentials()
{
return $this->config['use_application_default_credentials'];
}
/**
* @param string|array $token
* @throws InvalidArgumentException
*/
public function setAccessToken($token)
{
if (is_string($token)) {
if ($json = json_decode($token, true)) {
$token = $json;
} else {
// assume $token is just the token string
$token = array(
'access_token' => $token,
);
}
}
if ($token == null) {
throw new InvalidArgumentException('invalid json token');
}
if (!isset($token['access_token'])) {
throw new InvalidArgumentException("Invalid token format");
}
$this->token = $token;
}
public function getAccessToken()
{
return $this->token;
}
/**
* @return string|null
*/
public function getRefreshToken()
{
if (isset($this->token['refresh_token'])) {
return $this->token['refresh_token'];
}
return null;
}
/**
* Returns if the access_token is expired.
* @return bool Returns True if the access_token is expired.
*/
public function isAccessTokenExpired()
{
if (!$this->token) {
return true;
}
$created = 0;
if (isset($this->token['created'])) {
$created = $this->token['created'];
} elseif (isset($this->token['id_token'])) {
// check the ID token for "iat"
// signature verification is not required here, as we are just
// using this for convenience to save a round trip request
// to the Google API server
$idToken = $this->token['id_token'];
if (substr_count($idToken, '.') == 2) {
$parts = explode('.', $idToken);
$payload = json_decode(base64_decode($parts[1]), true);
if ($payload && isset($payload['iat'])) {
$created = $payload['iat'];
}
}
}
// If the token is set to expire in the next 30 seconds.
return ($created + ($this->token['expires_in'] - 30)) < time();
}
/**
* @deprecated See UPGRADING.md for more information
*/
public function getAuth()
{
throw new BadMethodCallException(
'This function no longer exists. See UPGRADING.md for more information'
);
}
/**
* @deprecated See UPGRADING.md for more information
*/
public function setAuth($auth)
{
throw new BadMethodCallException(
'This function no longer exists. See UPGRADING.md for more information'
);
}
/**
* Set the OAuth 2.0 Client ID.
* @param string $clientId
*/
public function setClientId($clientId)
{
$this->config['client_id'] = $clientId;
}
public function getClientId()
{
return $this->config['client_id'];
}
/**
* Set the OAuth 2.0 Client Secret.
* @param string $clientSecret
*/
public function setClientSecret($clientSecret)
{
$this->config['client_secret'] = $clientSecret;
}
public function getClientSecret()
{
return $this->config['client_secret'];
}
/**
* Set the OAuth 2.0 Redirect URI.
* @param string $redirectUri
*/
public function setRedirectUri($redirectUri)
{
$this->config['redirect_uri'] = $redirectUri;
}
public function getRedirectUri()
{
return $this->config['redirect_uri'];
}
/**
* Set OAuth 2.0 "state" parameter to achieve per-request customization.
* @see http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-3.1.2.2
* @param string $state
*/
public function setState($state)
{
$this->config['state'] = $state;
}
/**
* @param string $accessType Possible values for access_type include:
* {@code "offline"} to request offline access from the user.
* {@code "online"} to request online access from the user.
*/
public function setAccessType($accessType)
{
$this->config['access_type'] = $accessType;
}
/**
* @param string $approvalPrompt Possible values for approval_prompt include:
* {@code "force"} to force the approval UI to appear.
* {@code "auto"} to request auto-approval when possible. (This is the default value)
*/
public function setApprovalPrompt($approvalPrompt)
{
$this->config['approval_prompt'] = $approvalPrompt;
}
/**
* Set the login hint, email address or sub id.
* @param string $loginHint
*/
public function setLoginHint($loginHint)
{
$this->config['login_hint'] = $loginHint;
}
/**
* Set the application name, this is included in the User-Agent HTTP header.
* @param string $applicationName
*/
public function setApplicationName($applicationName)
{
$this->config['application_name'] = $applicationName;
}
/**
* If 'plus.login' is included in the list of requested scopes, you can use
* this method to define types of app activities that your app will write.
* You can find a list of available types here:
* @link https://developers.google.com/+/api/moment-types
*
* @param array $requestVisibleActions Array of app activity types
*/
public function setRequestVisibleActions($requestVisibleActions)
{
if (is_array($requestVisibleActions)) {
$requestVisibleActions = implode(" ", $requestVisibleActions);
}
$this->config['request_visible_actions'] = $requestVisibleActions;
}
/**
* Set the developer key to use, these are obtained through the API Console.
* @see http://code.google.com/apis/console-help/#generatingdevkeys
* @param string $developerKey
*/
public function setDeveloperKey($developerKey)
{
$this->config['developer_key'] = $developerKey;
}
/**
* Set the hd (hosted domain) parameter streamlines the login process for
* Google Apps hosted accounts. By including the domain of the user, you
* restrict sign-in to accounts at that domain.
* @param $hd string - the domain to use.
*/
public function setHostedDomain($hd)
{
$this->config['hd'] = $hd;
}
/**
* Set the prompt hint. Valid values are none, consent and select_account.
* If no value is specified and the user has not previously authorized
* access, then the user is shown a consent screen.
* @param $prompt string
*/
public function setPrompt($prompt)
{
$this->config['prompt'] = $prompt;
}
/**
* openid.realm is a parameter from the OpenID 2.0 protocol, not from OAuth
* 2.0. It is used in OpenID 2.0 requests to signify the URL-space for which
* an authentication request is valid.
* @param $realm string - the URL-space to use.
*/
public function setOpenidRealm($realm)
{
$this->config['openid.realm'] = $realm;
}
/**
* If this is provided with the value true, and the authorization request is
* granted, the authorization will include any previous authorizations
* granted to this user/application combination for other scopes.
* @param $include boolean - the URL-space to use.
*/
public function setIncludeGrantedScopes($include)
{
$this->config['include_granted_scopes'] = $include;
}
/**
* sets function to be called when an access token is fetched
* @param callable $tokenCallback - function ($cacheKey, $accessToken)
*/
public function setTokenCallback(callable $tokenCallback)
{
$this->config['token_callback'] = $tokenCallback;
}
/**
* Revoke an OAuth2 access token or refresh token. This method will revoke the current access
* token, if a token isn't provided.
*
* @param string|null $token The token (access token or a refresh token) that should be revoked.
* @return boolean Returns True if the revocation was successful, otherwise False.
*/
public function revokeToken($token = null)
{
$tokenRevoker = new Google_AccessToken_Revoke(
$this->getHttpClient()
);
return $tokenRevoker->revokeToken($token ?: $this->getAccessToken());
}
/**
* Verify an id_token. This method will verify the current id_token, if one
* isn't provided.
*
* @throws LogicException
* @param string|null $idToken The token (id_token) that should be verified.
* @return array|false Returns the token payload as an array if the verification was
* successful, false otherwise.
*/
public function verifyIdToken($idToken = null)
{
$tokenVerifier = new Google_AccessToken_Verify(
$this->getHttpClient(),
$this->getCache(),
$this->config['jwt']
);
if (null === $idToken) {
$token = $this->getAccessToken();
if (!isset($token['id_token'])) {
throw new LogicException(
'id_token must be passed in or set as part of setAccessToken'
);
}
$idToken = $token['id_token'];
}
return $tokenVerifier->verifyIdToken(
$idToken,
$this->getClientId()
);
}
/**
* Set the scopes to be requested. Must be called before createAuthUrl().
* Will remove any previously configured scopes.
* @param array $scopes, ie: array('https://www.googleapis.com/auth/plus.login',
* 'https://www.googleapis.com/auth/moderator')
*/
public function setScopes($scopes)
{
$this->requestedScopes = array();
$this->addScope($scopes);
}
/**
* This functions adds a scope to be requested as part of the OAuth2.0 flow.
* Will append any scopes not previously requested to the scope parameter.
* A single string will be treated as a scope to request. An array of strings
* will each be appended.
* @param $scope_or_scopes string|array e.g. "profile"
*/
public function addScope($scope_or_scopes)
{
if (is_string($scope_or_scopes) && !in_array($scope_or_scopes, $this->requestedScopes)) {
$this->requestedScopes[] = $scope_or_scopes;
} else if (is_array($scope_or_scopes)) {
foreach ($scope_or_scopes as $scope) {
$this->addScope($scope);
}
}
}
/**
* Returns the list of scopes requested by the client
* @return array the list of scopes
*
*/
public function getScopes()
{
return $this->requestedScopes;
}
/**
* @return string|null
* @visible For Testing
*/
public function prepareScopes()
{
if (empty($this->requestedScopes)) {
return null;
}
return implode(' ', $this->requestedScopes);
}
/**
* Helper method to execute deferred HTTP requests.
*
* @param $request Psr\Http\Message\RequestInterface|Google_Http_Batch
* @throws Google_Exception
* @return object of the type of the expected class or Psr\Http\Message\ResponseInterface.
*/
public function execute(RequestInterface $request, $expectedClass = null)
{
$request = $request->withHeader(
'User-Agent',
$this->config['application_name']
. " " . self::USER_AGENT_SUFFIX
. $this->getLibraryVersion()
);
// call the authorize method
// this is where most of the grunt work is done
$http = $this->authorize();
return Google_Http_REST::execute($http, $request, $expectedClass, $this->config['retry']);
}
/**
* Declare whether batch calls should be used. This may increase throughput
* by making multiple requests in one connection.
*
* @param boolean $useBatch True if the batch support should
* be enabled. Defaults to False.
*/
public function setUseBatch($useBatch)
{
// This is actually an alias for setDefer.
$this->setDefer($useBatch);
}
/**
* Are we running in Google AppEngine?
* return bool
*/
public function isAppEngine()
{
return (isset($_SERVER['SERVER_SOFTWARE']) &&
strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== false);
}
public function setConfig($name, $value)
{
$this->config[$name] = $value;
}
public function getConfig($name, $default = null)
{
return isset($this->config[$name]) ? $this->config[$name] : $default;
}
/**
* For backwards compatibility
* alias for setAuthConfig
*
* @param string $file the configuration file
* @throws Google_Exception
* @deprecated
*/
public function setAuthConfigFile($file)
{
$this->setAuthConfig($file);
}
/**
* Set the auth config from new or deprecated JSON config.
* This structure should match the file downloaded from
* the "Download JSON" button on in the Google Developer
* Console.
* @param string|array $config the configuration json
* @throws Google_Exception
*/
public function setAuthConfig($config)
{
if (is_string($config)) {
if (!file_exists($config)) {
throw new InvalidArgumentException('file does not exist');
}
$json = file_get_contents($config);
if (!$config = json_decode($json, true)) {
throw new LogicException('invalid json for auth config');
}
}
$key = isset($config['installed']) ? 'installed' : 'web';
if (isset($config['type']) && $config['type'] == 'service_account') {
// application default credentials
$this->useApplicationDefaultCredentials();
// set the information from the config
$this->setClientId($config['client_id']);
$this->config['client_email'] = $config['client_email'];
$this->config['signing_key'] = $config['private_key'];
$this->config['signing_algorithm'] = 'HS256';
} elseif (isset($config[$key])) {
// old-style
$this->setClientId($config[$key]['client_id']);
$this->setClientSecret($config[$key]['client_secret']);
if (isset($config[$key]['redirect_uris'])) {
$this->setRedirectUri($config[$key]['redirect_uris'][0]);
}
} else {
// new-style
$this->setClientId($config['client_id']);
$this->setClientSecret($config['client_secret']);
if (isset($config['redirect_uris'])) {
$this->setRedirectUri($config['redirect_uris'][0]);
}
}
}
/**
* Use when the service account has been delegated domain wide access.
*
* @param string $subject an email address account to impersonate
*/
public function setSubject($subject)
{
$this->config['subject'] = $subject;
}
/**
* Declare whether making API calls should make the call immediately, or
* return a request which can be called with ->execute();
*
* @param boolean $defer True if calls should not be executed right away.
*/
public function setDefer($defer)
{
$this->deferExecution = $defer;
}
/**
* Whether or not to return raw requests
* @return boolean
*/
public function shouldDefer()
{
return $this->deferExecution;
}
/**
* @return Google\Auth\OAuth2 implementation
*/
public function getOAuth2Service()
{
if (!isset($this->auth)) {
$this->auth = $this->createOAuth2Service();
}
return $this->auth;
}
/**
* create a default google auth object
*/
protected function createOAuth2Service()
{
$auth = new OAuth2(
[
'clientId' => $this->getClientId(),
'clientSecret' => $this->getClientSecret(),
'authorizationUri' => self::OAUTH2_AUTH_URL,
'tokenCredentialUri' => self::OAUTH2_TOKEN_URI,
'redirectUri' => $this->getRedirectUri(),
'issuer' => $this->config['client_id'],
'signingKey' => $this->config['signing_key'],
'signingAlgorithm' => $this->config['signing_algorithm'],
]
);
return $auth;
}
/**
* Set the Cache object
* @param Psr\Cache\CacheItemPoolInterface $cache
*/
public function setCache(CacheItemPoolInterface $cache)
{
$this->cache = $cache;
}
/**
* @return Psr\Cache\CacheItemPoolInterface Cache implementation
*/
public function getCache()
{
if (!$this->cache) {
$this->cache = $this->createDefaultCache();
}
return $this->cache;
}
/**
* @param array $cacheConfig
*/
public function setCacheConfig(array $cacheConfig)
{
$this->config['cache_config'] = $cacheConfig;
}
/**
* Set the Logger object
* @param Psr\Log\LoggerInterface $logger
*/
public function setLogger(LoggerInterface $logger)
{
$this->logger = $logger;
}
/**
* @return Psr\Log\LoggerInterface implementation
*/
public function getLogger()
{
if (!isset($this->logger)) {
$this->logger = $this->createDefaultLogger();
}
return $this->logger;
}
protected function createDefaultLogger()
{
$logger = new Logger('google-api-php-client');
if ($this->isAppEngine()) {
$handler = new MonologSyslogHandler('app', LOG_USER, Logger::NOTICE);
} else {
$handler = new MonologStreamHandler('php://stderr', Logger::NOTICE);
}
$logger->pushHandler($handler);
return $logger;
}
protected function createDefaultCache()
{
return new MemoryCacheItemPool;
}
/**
* Set the Http Client object
* @param WPvividGuzzleHttp\ClientInterface $http
*/
public function setHttpClient(ClientInterface $http)
{
$this->http = $http;
}
/**
* @return WPvividGuzzleHttp\ClientInterface implementation
*/
public function getHttpClient()
{
if (null === $this->http) {
$this->http = $this->createDefaultHttpClient();
}
return $this->http;
}
protected function createDefaultHttpClient()
{
$options = ['exceptions' => false];
$version = ClientInterface::VERSION;
if ('5' === $version[0]) {
$options = [
'base_url' => $this->config['base_path'],
'defaults' => $options,
];
if ($this->isAppEngine()) {
// set StreamHandler on AppEngine by default
$options['handler'] = new StreamHandler();
$options['defaults']['verify'] = '/etc/ca-certificates.crt';
}
} else {
// guzzle 6
$options['base_uri'] = $this->config['base_path'];
$options['verify'] = WPVIVID_PLUGIN_DIR.'/vendor/guzzle/guzzle/src/Guzzle/Http/Resources/cacert.pem';
}
return new WPvividGuzzleHttp\Client($options);
}
private function createApplicationDefaultCredentials()
{
$scopes = $this->prepareScopes();
$sub = $this->config['subject'];
$signingKey = $this->config['signing_key'];
// create credentials using values supplied in setAuthConfig
if ($signingKey) {
$serviceAccountCredentials = array(
'client_id' => $this->config['client_id'],
'client_email' => $this->config['client_email'],
'private_key' => $signingKey,
'type' => 'service_account',
);
$credentials = CredentialsLoader::makeCredentials($scopes, $serviceAccountCredentials);
} else {
$credentials = ApplicationDefaultCredentials::getCredentials($scopes);
}
// for service account domain-wide authority (impersonating a user)
// @see https://developers.google.com/identity/protocols/OAuth2ServiceAccount
if ($sub) {
if (!$credentials instanceof ServiceAccountCredentials) {
throw new DomainException('domain-wide authority requires service account credentials');
}
$credentials->setSub($sub);
}
return $credentials;
}
protected function getAuthHandler()
{
// Be very careful using the cache, as the underlying auth library's cache
// implementation is naive, and the cache keys do not account for user
// sessions.
//
// @see https://github.com/google/google-api-php-client/issues/821
return Google_AuthHandler_AuthHandlerFactory::build(
$this->getCache(),
$this->config['cache_config']
);
}
private function createUserRefreshCredentials($scope, $refreshToken)
{
$creds = array_filter(
array(
'client_id' => $this->getClientId(),
'client_secret' => $this->getClientSecret(),
'refresh_token' => $refreshToken,
)
);
return new UserRefreshCredentials($scope, $creds);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Enum/Size.php 0000644 00000002636 15132770567 0017131 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable byte-size values
*/
class Size extends Enum
{
const B = 1;
const BYTE = 1;
const BYTES = 1;
const KB = 1024;
const KILOBYTE = 1024;
const KILOBYTES = 1024;
const MB = 1048576;
const MEGABYTE = 1048576;
const MEGABYTES = 1048576;
const GB = 1073741824;
const GIGABYTE = 1073741824;
const GIGABYTES = 1073741824;
const TB = 1099511627776;
const TERABYTE = 1099511627776;
const TERABYTES = 1099511627776;
const PB = 1125899906842624;
const PETABYTE = 1125899906842624;
const PETABYTES = 1125899906842624;
const EB = 1152921504606846976;
const EXABYTE = 1152921504606846976;
const EXABYTES = 1152921504606846976;
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Enum/UaString.php 0000644 00000002507 15132770567 0017750 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Enum;
use Aws\Common\Enum;
/**
* User-Agent header strings for various high level operations
*/
class UaString extends Enum
{
/**
* @var string Name of the option used to add to the UA string
*/
const OPTION = 'ua.append';
/**
* @var string Resource iterator
*/
const ITERATOR = 'ITR';
/**
* @var string Resource waiter
*/
const WAITER = 'WTR';
/**
* @var string Session handlers (e.g. Amazon DynamoDB session handler)
*/
const SESSION = 'SES';
/**
* @var string Multipart upload helper for Amazon S3
*/
const MULTIPART_UPLOAD = 'MUP';
/**
* @var string Command executed during a batch transfer
*/
const BATCH = 'BAT';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Enum/DateFormat.php 0000644 00000001655 15132770567 0020245 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable date format values used in the SDK
*/
class DateFormat extends Enum
{
const ISO8601 = 'Ymd\THis\Z';
const ISO8601_S3 = 'Y-m-d\TH:i:s\Z';
const RFC1123 = 'D, d M Y H:i:s \G\M\T';
const RFC2822 = \DateTime::RFC2822;
const SHORT = 'Ymd';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Enum/Time.php 0000644 00000002105 15132770567 0017104 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable time values
*/
class Time extends Enum
{
const SECOND = 1;
const SECONDS = 1;
const MINUTE = 60;
const MINUTES = 60;
const HOUR = 3600;
const HOURS = 3600;
const DAY = 86400;
const DAYS = 86400;
const WEEK = 604800;
const WEEKS = 604800;
const MONTH = 2592000;
const MONTHS = 2592000;
const YEAR = 31557600;
const YEARS = 31557600;
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Enum/ClientOptions.php 0000644 00000011506 15132770567 0021005 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable default factory options that can be passed to a client's factory method
*/
class ClientOptions extends Enum
{
/**
* AWS Access Key ID
*
* @deprecated Use "credentials" instead.
*/
const KEY = 'key';
/**
* AWS secret access key
*
* @deprecated Use "credentials" instead.
*/
const SECRET = 'secret';
/**
* Custom AWS security token to use with request authentication.
*
* @deprecated Use "credentials" instead.
*/
const TOKEN = 'token';
/**
* Provide an array of "key", "secret", and "token" or an instance of
* `Aws\Common\Credentials\CredentialsInterface`.
*/
const CREDENTIALS = 'credentials';
/**
* @var string Name of a credential profile to read from your ~/.aws/credentials file
*/
const PROFILE = 'profile';
/**
* @var string UNIX timestamp for when the custom credentials expire
*/
const TOKEN_TTD = 'token.ttd';
/**
* @var string Used to cache credentials when using providers that require HTTP requests. Set the trueto use the
* default APC cache or provide a `Guzzle\Cache\CacheAdapterInterface` object.
*/
const CREDENTIALS_CACHE = 'credentials.cache';
/**
* @var string Optional custom cache key to use with the credentials
*/
const CREDENTIALS_CACHE_KEY = 'credentials.cache.key';
/**
* @var string Pass this option to specify a custom `Guzzle\Http\ClientInterface` to use if your credentials require
* a HTTP request (e.g. RefreshableInstanceProfileCredentials)
*/
const CREDENTIALS_CLIENT = 'credentials.client';
/**
* @var string Region name (e.g. 'us-east-1', 'us-west-1', 'us-west-2', 'eu-west-1', etc...)
*/
const REGION = 'region';
/**
* @var string URI Scheme of the base URL (e.g. 'https', 'http').
*/
const SCHEME = 'scheme';
/**
* @var string Specify the name of the service
*/
const SERVICE = 'service';
/**
* Instead of using a `region` and `scheme`, you can specify a custom base
* URL for the client.
*
* @deprecated Use the "endpoint" option instead.
*/
const BASE_URL = 'base_url';
/**
* @var string You can optionally provide a custom signature implementation used to sign requests
*/
const SIGNATURE = 'signature';
/**
* @var string Set to explicitly override the service name used in signatures
*/
const SIGNATURE_SERVICE = 'signature.service';
/**
* @var string Set to explicitly override the region name used in signatures
*/
const SIGNATURE_REGION = 'signature.region';
/**
* @var string Option key holding an exponential backoff plugin
*/
const BACKOFF = 'client.backoff';
/**
* @var string Option key holding the exponential backoff retries
*/
const BACKOFF_RETRIES = 'client.backoff.retries';
/**
* @var string `Guzzle\Log\LogAdapterInterface` object used to log backoff retries. Use 'debug' to emit PHP
* warnings when a retry is issued.
*/
const BACKOFF_LOGGER = 'client.backoff.logger';
/**
* @var string Optional template to use for exponential backoff log messages. See
* `Guzzle\Plugin\Backoff\BackoffLogger` for formatting information.
*/
const BACKOFF_LOGGER_TEMPLATE = 'client.backoff.logger.template';
/**
* Set to true to use the bundled CA cert or pass the full path to an SSL
* certificate bundle. This option should be modified when you encounter
* curl error code 60. Set to "system" to use the cacert bundle on your
* system.
*/
const SSL_CERT = 'ssl.certificate_authority';
/**
* @var string Service description to use with the client
*/
const SERVICE_DESCRIPTION = 'service.description';
/**
* @var string Whether or not modeled responses have transformations applied to them
*/
const MODEL_PROCESSING = 'command.model_processing';
/**
* @var bool Set to false to disable validation
*/
const VALIDATION = 'validation';
/**
* @var string API version used by the client
*/
const VERSION = 'version';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Enum/Region.php 0000644 00000003776 15132770567 0017450 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable region code values. These should be useful in most cases,
* with Amazon S3 being the most notable exception
*
* @link http://docs.aws.amazon.com/general/latest/gr/rande.html AWS Regions and Endpoints
*/
class Region extends Enum
{
const US_EAST_1 = 'us-east-1';
const VIRGINIA = 'us-east-1';
const NORTHERN_VIRGINIA = 'us-east-1';
const US_WEST_1 = 'us-west-1';
const CALIFORNIA = 'us-west-1';
const NORTHERN_CALIFORNIA = 'us-west-1';
const US_WEST_2 = 'us-west-2';
const OREGON = 'us-west-2';
const EU_WEST_1 = 'eu-west-1';
const IRELAND = 'eu-west-1';
const EU_CENTRAL_1 = 'eu-central-1';
const FRANKFURT = 'eu-central-1';
const AP_SOUTHEAST_1 = 'ap-southeast-1';
const SINGAPORE = 'ap-southeast-1';
const AP_SOUTHEAST_2 = 'ap-southeast-2';
const SYDNEY = 'ap-southeast-2';
const AP_NORTHEAST_1 = 'ap-northeast-1';
const TOKYO = 'ap-northeast-1';
const SA_EAST_1 = 'sa-east-1';
const SAO_PAULO = 'sa-east-1';
const CN_NORTH_1 = 'cn-north-1';
const BEIJING = 'cn-north-1';
const US_GOV_WEST_1 = 'us-gov-west-1';
const GOV_CLOUD_US = 'us-gov-west-1';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/HostNameUtils.php 0000644 00000004655 15132770567 0020055 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common;
use Guzzle\Http\Url;
/**
* Utility class for parsing regions and services from URLs
*/
class HostNameUtils
{
const DEFAULT_REGION = 'us-east-1';
const DEFAULT_GOV_REGION = 'us-gov-west-1';
/**
* Parse the AWS region name from a URL
*
*
* @param Url $url HTTP URL
*
* @return string
* @link http://docs.aws.amazon.com/general/latest/gr/rande.html
*/
public static function parseRegionName(Url $url)
{
// If we don't recognize the domain, just return the default
if (substr($url->getHost(), -14) != '.amazonaws.com') {
return self::DEFAULT_REGION;
}
$serviceAndRegion = substr($url->getHost(), 0, -14);
// Special handling for S3 regions
$separator = strpos($serviceAndRegion, 's3') === 0 ? '-' : '.';
$separatorPos = strpos($serviceAndRegion, $separator);
// If don't detect a separator, then return the default region
if ($separatorPos === false) {
return self::DEFAULT_REGION;
}
$region = substr($serviceAndRegion, $separatorPos + 1);
// All GOV regions currently use the default GOV region
if ($region == 'us-gov') {
return self::DEFAULT_GOV_REGION;
}
return $region;
}
/**
* Parse the AWS service name from a URL
*
* @param Url $url HTTP URL
*
* @return string Returns a service name (or empty string)
* @link http://docs.aws.amazon.com/general/latest/gr/rande.html
*/
public static function parseServiceName(Url $url)
{
// The service name is the first part of the host
$parts = explode('.', $url->getHost(), 2);
// Special handling for S3
if (stripos($parts[0], 's3') === 0) {
return 's3';
}
return $parts[0];
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Command/JsonCommand.php 0000644 00000003125 15132770567 0021073 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Command;
use Guzzle\Service\Command\OperationCommand;
use Guzzle\Http\Curl\CurlHandle;
/**
* Adds AWS JSON body functionality to dynamically generated HTTP requests
*/
class JsonCommand extends OperationCommand
{
/**
* {@inheritdoc}
*/
protected function build()
{
parent::build();
// Ensure that the body of the request ALWAYS includes some JSON. By default, this is an empty object.
if (!$this->request->getBody()) {
$this->request->setBody('{}');
}
// Never send the Expect header when interacting with a JSON query service
$this->request->removeHeader('Expect');
// Always send JSON requests as a raw string rather than using streams to avoid issues with
// cURL error code 65: "necessary data rewind wasn't possible".
// This could be removed after PHP addresses https://bugs.php.net/bug.php?id=47204
$this->request->getCurlOptions()->set(CurlHandle::BODY_AS_STRING, true);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Command/AwsQueryVisitor.php 0000644 00000011104 15132770567 0022017 0 ustar 00 <?php
namespace Aws\Common\Command;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Command\LocationVisitor\Request\AbstractRequestVisitor;
/**
* Location visitor used to serialize AWS query parameters (e.g. EC2, SES, SNS, SQS, etc) as POST fields
*/
class AwsQueryVisitor extends AbstractRequestVisitor
{
private $fqname;
public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value)
{
$this->fqname = $command->getName();
$query = array();
$this->customResolver($value, $param, $query, $param->getWireName());
$request->addPostFields($query);
}
/**
* Map nested parameters into the location_key based parameters
*
* @param array $value Value to map
* @param Parameter $param Parameter that holds information about the current key
* @param array $query Built up query string values
* @param string $prefix String to prepend to sub query values
*/
protected function customResolver($value, Parameter $param, array &$query, $prefix = '')
{
switch ($param->getType()) {
case 'object':
$this->resolveObject($param, $value, $prefix, $query);
break;
case 'array':
$this->resolveArray($param, $value, $prefix, $query);
break;
default:
$query[$prefix] = $param->filter($value);
}
}
/**
* Custom handling for objects
*
* @param Parameter $param Parameter for the object
* @param array $value Value that is set for this parameter
* @param string $prefix Prefix for the resulting key
* @param array $query Query string array passed by reference
*/
protected function resolveObject(Parameter $param, array $value, $prefix, array &$query)
{
// Maps are implemented using additional properties
$hasAdditionalProperties = ($param->getAdditionalProperties() instanceof Parameter);
$additionalPropertyCount = 0;
foreach ($value as $name => $v) {
if ($subParam = $param->getProperty($name)) {
// if the parameter was found by name as a regular property
$key = $prefix . '.' . $subParam->getWireName();
$this->customResolver($v, $subParam, $query, $key);
} elseif ($hasAdditionalProperties) {
// Handle map cases like &Attribute.1.Name=<name>&Attribute.1.Value=<value>
$additionalPropertyCount++;
$data = $param->getData();
$keyName = isset($data['keyName']) ? $data['keyName'] : 'key';
$valueName = isset($data['valueName']) ? $data['valueName'] : 'value';
$query["{$prefix}.{$additionalPropertyCount}.{$keyName}"] = $name;
$newPrefix = "{$prefix}.{$additionalPropertyCount}.{$valueName}";
if (is_array($v)) {
$this->customResolver($v, $param->getAdditionalProperties(), $query, $newPrefix);
} else {
$query[$newPrefix] = $param->filter($v);
}
}
}
}
/**
* Custom handling for arrays
*
* @param Parameter $param Parameter for the object
* @param array $value Value that is set for this parameter
* @param string $prefix Prefix for the resulting key
* @param array $query Query string array passed by reference
*/
protected function resolveArray(Parameter $param, array $value, $prefix, array &$query)
{
static $serializeEmpty = array(
'SetLoadBalancerPoliciesForBackendServer' => 1,
'SetLoadBalancerPoliciesOfListener' => 1,
'UpdateStack' => 1
);
// For BC, serialize empty lists for specific operations
if (!$value) {
if (isset($serializeEmpty[$this->fqname])) {
if (substr($prefix, -7) === '.member') {
$prefix = substr($prefix, 0, -7);
}
$query[$prefix] = '';
}
return;
}
$offset = $param->getData('offset') ?: 1;
foreach ($value as $index => $v) {
$index += $offset;
if (is_array($v) && $items = $param->getItems()) {
$this->customResolver($v, $items, $query, $prefix . '.' . $index);
} else {
$query[$prefix . '.' . $index] = $param->filter($v);
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Command/XmlResponseLocationVisitor.php 0000644 00000004143 15132770567 0024214 0 ustar 00 <?php
namespace Aws\Common\Command;
use Guzzle\Service\Description\Operation;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Service\Description\Parameter;
use Guzzle\Service\Command\LocationVisitor\Response\XmlVisitor;
/**
* Class used for custom AWS XML response parsing of query services
*/
class XmlResponseLocationVisitor extends XmlVisitor
{
/**
* {@inheritdoc}
*/
public function before(CommandInterface $command, array &$result)
{
parent::before($command, $result);
// Unwrapped wrapped responses
$operation = $command->getOperation();
if ($operation->getServiceDescription()->getData('resultWrapped')) {
$wrappingNode = $operation->getName() . 'Result';
if (isset($result[$wrappingNode])) {
$result = $result[$wrappingNode] + $result;
unset($result[$wrappingNode]);
}
}
}
/**
* Accounts for wrapper nodes
* {@inheritdoc}
*/
public function visit(
CommandInterface $command,
Response $response,
Parameter $param,
&$value,
$context = null
) {
parent::visit($command, $response, $param, $value, $context);
// Account for wrapper nodes (e.g. RDS, ElastiCache, etc)
if ($param->getData('wrapper')) {
$wireName = $param->getWireName();
$value += $value[$wireName];
unset($value[$wireName]);
}
}
/**
* Filter used when converting XML maps into associative arrays in service descriptions
*
* @param array $value Value to filter
* @param string $entryName Name of each entry
* @param string $keyName Name of each key
* @param string $valueName Name of each value
*
* @return array Returns the map of the XML data
*/
public static function xmlMap($value, $entryName, $keyName, $valueName)
{
$result = array();
foreach ($value as $entry) {
$result[$entry[$keyName]] = $entry[$valueName];
}
return $result;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Command/QueryCommand.php 0000644 00000002703 15132770567 0021270 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Command;
use Guzzle\Service\Command\OperationCommand;
/**
* Adds AWS Query service serialization
*/
class QueryCommand extends OperationCommand
{
/**
* @var AwsQueryVisitor
*/
protected static $queryVisitor;
/**
* @var XmlResponseLocationVisitor
*/
protected static $xmlVisitor;
/**
* Register the aws.query visitor
*/
protected function init()
{
// @codeCoverageIgnoreStart
if (!self::$queryVisitor) {
self::$queryVisitor = new AwsQueryVisitor();
}
if (!self::$xmlVisitor) {
self::$xmlVisitor = new XmlResponseLocationVisitor();
}
// @codeCoverageIgnoreEnd
$this->getRequestSerializer()->addVisitor('aws.query', self::$queryVisitor);
$this->getResponseParser()->addVisitor('xml', self::$xmlVisitor);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/InstanceMetadata/Waiter/ServiceAvailable.php 0000644 00000002703 15132770567 0025147 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\InstanceMetadata\Waiter;
use Aws\Common\Waiter\AbstractResourceWaiter;
use Guzzle\Http\Exception\CurlException;
/**
* Waits until the instance metadata service is responding. Will send up to
* 4 requests with a 5 second delay between each try. Each try can last up to
* 11 seconds to complete if the service is not responding.
*
* @codeCoverageIgnore
*/
class ServiceAvailable extends AbstractResourceWaiter
{
protected $interval = 5;
protected $maxAttempts = 4;
/**
* {@inheritdoc}
*/
public function doWait()
{
$request = $this->client->get();
try {
$request->getCurlOptions()->set(CURLOPT_CONNECTTIMEOUT, 10)
->set(CURLOPT_TIMEOUT, 10);
$request->send();
return true;
} catch (CurlException $e) {
return false;
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/InstanceMetadata/InstanceMetadataClient.php 0000644 00000007317 15132770567 0025065 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\InstanceMetadata;
use Aws\Common\Enum\ClientOptions as Options;
use Aws\Common\Exception\InstanceProfileCredentialsException;
use Aws\Common\Credentials\Credentials;
use Aws\Common\Client\AbstractClient;
use Guzzle\Common\Collection;
use Guzzle\Http\Message\RequestFactory;
/**
* Client used for interacting with the Amazon EC2 instance metadata server
*/
class InstanceMetadataClient extends AbstractClient
{
/**
* Factory method to create a new InstanceMetadataClient using an array
* of configuration options.
*
* The configuration options accepts the following array keys and values:
* - base_url: Override the base URL of the instance metadata server
* - version: Version of the metadata server to interact with
*
* @param array|Collection $config Configuration options
*
* @return InstanceMetadataClient
*/
public static function factory($config = array())
{
$config = Collection::fromConfig($config, array(
Options::BASE_URL => 'http://169.254.169.254/{version}/',
'version' => 'latest',
'request.options' => array(
'connect_timeout' => 5,
'timeout' => 10
)
), array('base_url', 'version'));
return new self($config);
}
/**
* Constructor override
*/
public function __construct(Collection $config)
{
$this->setConfig($config);
$this->setBaseUrl($config->get(Options::BASE_URL));
$this->defaultHeaders = new Collection();
$this->setRequestFactory(RequestFactory::getInstance());
}
/**
* Get instance profile credentials
*
* @return Credentials
* @throws InstanceProfileCredentialsException
*/
public function getInstanceProfileCredentials()
{
try {
$request = $this->get('meta-data/iam/security-credentials/');
$credentials = trim($request->send()->getBody(true));
$result = $this->get("meta-data/iam/security-credentials/{$credentials}")->send()->json();
} catch (\Exception $e) {
$message = sprintf('Error retrieving credentials from the instance profile metadata server. When you are'
. ' not running inside of Amazon EC2, you must provide your AWS access key ID and secret access key in'
. ' the "key" and "secret" options when creating a client or provide an instantiated'
. ' Aws\\Common\\Credentials\\CredentialsInterface object. (%s)', $e->getMessage());
throw new InstanceProfileCredentialsException(esc_html($message), esc_attr($e->getCode()));
}
// Ensure that the status code was successful
if ($result['Code'] !== 'Success') {
$e = new InstanceProfileCredentialsException('Unexpected response code: ' . $result['Code']);
$e->setStatusCode($result['Code']);
throw $e;
}
return new Credentials(
$result['AccessKeyId'],
$result['SecretAccessKey'],
$result['Token'],
strtotime($result['Expiration'])
);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Enum.php 0000644 00000002621 15132770567 0016211 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common;
/**
* Represents an enumerable set of values
*/
abstract class Enum
{
/**
* @var array A cache of all enum values to increase performance
*/
protected static $cache = array();
/**
* Returns the names (or keys) of all of constants in the enum
*
* @return array
*/
public static function keys()
{
return array_keys(static::values());
}
/**
* Return the names and values of all the constants in the enum
*
* @return array
*/
public static function values()
{
$class = get_called_class();
if (!isset(self::$cache[$class])) {
$reflected = new \ReflectionClass($class);
self::$cache[$class] = $reflected->getConstants();
}
return self::$cache[$class];
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Facade/facade-classes.php 0000644 00000011600 15132770567 0021303 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Facade;
/**
* The following classes are used to implement the static client facades and are aliased into the global namespaced. We
* discourage the use of these classes directly by their full namespace since they are not autoloaded and are considered
* an implementation detail that could possibly be changed in the future.
*/
// @codeCoverageIgnoreStart
class AutoScaling extends Facade
{
public static function getServiceBuilderKey()
{
return 'autoscaling';
}
}
class CloudFormation extends Facade
{
public static function getServiceBuilderKey()
{
return 'cloudformation';
}
}
class CloudFront extends Facade
{
public static function getServiceBuilderKey()
{
return 'cloudfront';
}
}
class CloudSearch extends Facade
{
public static function getServiceBuilderKey()
{
return 'cloudsearch';
}
}
class CloudTrail extends Facade
{
public static function getServiceBuilderKey()
{
return 'cloudtrail';
}
}
class CloudWatch extends Facade
{
public static function getServiceBuilderKey()
{
return 'cloudwatch';
}
}
class DataPipeline extends Facade
{
public static function getServiceBuilderKey()
{
return 'datapipeline';
}
}
class DirectConnect extends Facade
{
public static function getServiceBuilderKey()
{
return 'directconnect';
}
}
class DynamoDb extends Facade
{
public static function getServiceBuilderKey()
{
return 'dynamodb';
}
}
class Ec2 extends Facade
{
public static function getServiceBuilderKey()
{
return 'ec2';
}
}
class ElastiCache extends Facade
{
public static function getServiceBuilderKey()
{
return 'elasticache';
}
}
class ElasticBeanstalk extends Facade
{
public static function getServiceBuilderKey()
{
return 'elasticbeanstalk';
}
}
class ElasticLoadBalancing extends Facade
{
public static function getServiceBuilderKey()
{
return 'elasticloadbalancing';
}
}
class ElasticTranscoder extends Facade
{
public static function getServiceBuilderKey()
{
return 'elastictranscoder';
}
}
class Emr extends Facade
{
public static function getServiceBuilderKey()
{
return 'emr';
}
}
class Glacier extends Facade
{
public static function getServiceBuilderKey()
{
return 'glacier';
}
}
class Iam extends Facade
{
public static function getServiceBuilderKey()
{
return 'iam';
}
}
class ImportExport extends Facade
{
public static function getServiceBuilderKey()
{
return 'importexport';
}
}
class Kinesis extends Facade
{
public static function getServiceBuilderKey()
{
return 'kinesis';
}
}
class OpsWorks extends Facade
{
public static function getServiceBuilderKey()
{
return 'opsworks';
}
}
class Rds extends Facade
{
public static function getServiceBuilderKey()
{
return 'rds';
}
}
class Redshift extends Facade
{
public static function getServiceBuilderKey()
{
return 'redshift';
}
}
class Route53 extends Facade
{
public static function getServiceBuilderKey()
{
return 'route53';
}
}
class S3 extends Facade
{
public static function getServiceBuilderKey()
{
return 's3';
}
}
class SimpleDb extends Facade
{
public static function getServiceBuilderKey()
{
return 'sdb';
}
}
class Ses extends Facade
{
public static function getServiceBuilderKey()
{
return 'ses';
}
}
class Sns extends Facade
{
public static function getServiceBuilderKey()
{
return 'sns';
}
}
class Sqs extends Facade
{
public static function getServiceBuilderKey()
{
return 'sqs';
}
}
class StorageGateway extends Facade
{
public static function getServiceBuilderKey()
{
return 'storagegateway';
}
}
class Sts extends Facade
{
public static function getServiceBuilderKey()
{
return 'sts';
}
}
class Support extends Facade
{
public static function getServiceBuilderKey()
{
return 'support';
}
}
class Swf extends Facade
{
public static function getServiceBuilderKey()
{
return 'swf';
}
}
// @codeCoverageIgnoreEnd
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Facade/FacadeInterface.php 0000644 00000002225 15132770567 0021434 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Facade;
/**
* Interface that defines a client facade. Facades are convenient static classes that allow you to run client methods
* statically on a default instance from the service builder. The facades themselves are aliased into the global
* namespace for ease of use.
*
* @deprecated "Facades" are being removed in version 3.0 of the SDK.
*/
interface FacadeInterface
{
/**
* Returns the key used to access the client instance from the Service Builder
*
* @return string
*/
public static function getServiceBuilderKey();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Facade/Facade.php 0000644 00000004513 15132770567 0017615 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Facade;
use Aws\Common\Aws;
/**
* Base facade class that handles the delegation logic
*
* @deprecated "Facades" are being removed in version 3.0 of the SDK.
*/
abstract class Facade implements FacadeInterface
{
/** @var Aws */
protected static $serviceBuilder;
/**
* Mounts the facades by extracting information from the service builder config and using creating class aliases
*
* @param string|null $targetNamespace Namespace that the facades should be mounted to. Defaults to global namespace
*
* @param Aws $serviceBuilder
*/
public static function mountFacades(Aws $serviceBuilder, $targetNamespace = null)
{
self::$serviceBuilder = $serviceBuilder;
require_once __DIR__ . '/facade-classes.php';
foreach ($serviceBuilder->getConfig() as $service) {
if (isset($service['alias'], $service['class'])) {
$facadeClass = __NAMESPACE__ . '\\' . $service['alias'];
$facadeAlias = ltrim($targetNamespace . '\\' . $service['alias'], '\\');
if (!class_exists($facadeAlias) && class_exists($facadeClass)) {
// @codeCoverageIgnoreStart
class_alias($facadeClass, $facadeAlias);
// @codeCoverageIgnoreEnd
}
}
}
}
/**
* Returns the instance of the client that the facade operates on
*
* @return \Aws\Common\Client\AwsClientInterface
*/
public static function getClient()
{
return self::$serviceBuilder->get(static::getServiceBuilderKey());
}
public static function __callStatic($method, $args)
{
return call_user_func_array(array(self::getClient(), $method), $args);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Iterator/AwsResourceIterator.php 0000644 00000014102 15132770567 0023047 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Iterator;
use Aws\Common\Enum\UaString as Ua;
use Aws\Common\Exception\RuntimeException;
Use Guzzle\Service\Resource\Model;
use Guzzle\Service\Resource\ResourceIterator;
/**
* Iterate over a client command
*/
class AwsResourceIterator extends ResourceIterator
{
/**
* @var Model Result of a command
*/
protected $lastResult = null;
/**
* Provides access to the most recent result obtained by the iterator. This makes it easier to extract any
* additional information from the result which you do not have access to from the values emitted by the iterator
*
* @return Model|null
*/
public function getLastResult()
{
return $this->lastResult;
}
/**
* {@inheritdoc}
* This AWS specific version of the resource iterator provides a default implementation of the typical AWS iterator
* process. It relies on configuration and extension to implement the operation-specific logic of handling results
* and nextTokens. This method will loop until resources are acquired or there are no more iterations available.
*/
protected function sendRequest()
{
do {
// Prepare the request including setting the next token
$this->prepareRequest();
if ($this->nextToken) {
$this->applyNextToken();
}
// Execute the request and handle the results
$this->command->add(Ua::OPTION, Ua::ITERATOR);
$this->lastResult = $this->command->getResult();
$resources = $this->handleResults($this->lastResult);
$this->determineNextToken($this->lastResult);
// If no resources collected, prepare to reiterate before yielding
if ($reiterate = empty($resources) && $this->nextToken) {
$this->command = clone $this->originalCommand;
}
} while ($reiterate);
return $resources;
}
protected function prepareRequest()
{
// Get the limit parameter key to set
$limitKey = $this->get('limit_key');
if ($limitKey && ($limit = $this->command->get($limitKey))) {
$pageSize = $this->calculatePageSize();
// If the limit of the command is different than the pageSize of the iterator, use the smaller value
if ($limit && $pageSize) {
$realLimit = min($limit, $pageSize);
$this->command->set($limitKey, $realLimit);
}
}
}
protected function handleResults(Model $result)
{
$results = array();
// Get the result key that contains the results
if ($resultKey = $this->get('result_key')) {
$results = $this->getValueFromResult($result, $resultKey) ?: array();
}
return $results;
}
protected function applyNextToken()
{
// Get the token parameter key to set
if ($tokenParam = $this->get('input_token')) {
// Set the next token. Works with multi-value tokens
if (is_array($tokenParam)) {
if (is_array($this->nextToken) && count($tokenParam) === count($this->nextToken)) {
foreach (array_combine($tokenParam, $this->nextToken) as $param => $token) {
$this->command->set($param, $token);
}
} else {
throw new RuntimeException('The definition of the iterator\'s token parameter and the actual token '
. 'value are not compatible.');
}
} else {
$this->command->set($tokenParam, $this->nextToken);
}
}
}
protected function determineNextToken(Model $result)
{
$this->nextToken = null;
// If the value of "more_results" is true or there is no "more_results" to check, then try to get the next token
$moreKey = $this->get('more_results');
if ($moreKey === null || $this->getValueFromResult($result, $moreKey)) {
// Get the token key to check
if ($tokenKey = $this->get('output_token')) {
// Get the next token's value. Works with multi-value tokens
if (is_array($tokenKey)) {
$this->nextToken = array();
foreach ($tokenKey as $key) {
$this->nextToken[] = $this->getValueFromResult($result, $key);
}
} else {
$this->nextToken = $this->getValueFromResult($result, $tokenKey);
}
}
}
}
/**
* Extracts the value from the result using Collection::getPath. Also adds some additional logic for keys that need
* to access n-1 indexes (e.g., ImportExport, Kinesis). The n-1 logic only works for the known cases. We will switch
* to a jmespath implementation in the future to cover all cases
*
* @param Model $result
* @param string $key
*
* @return mixed|null
*/
protected function getValueFromResult(Model $result, $key)
{
// Special handling for keys that need to access n-1 indexes
if (strpos($key, '#') !== false) {
$keyParts = explode('#', $key, 2);
$items = $result->getPath(trim($keyParts[0], '/'));
if ($items && is_array($items)) {
$index = count($items) - 1;
$key = strtr($key, array('#' => $index));
}
}
// Get the value
return $result->getPath($key);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Iterator/AwsResourceIteratorFactory.php 0000644 00000007250 15132770567 0024405 0 ustar 00 <?php
namespace Aws\Common\Iterator;
use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Collection;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Resource\ResourceIteratorFactoryInterface;
/**
* Resource iterator factory used to instantiate the default AWS resource iterator with the correct configuration or
* use a concrete iterator class if one exists
*/
class AwsResourceIteratorFactory implements ResourceIteratorFactoryInterface
{
/**
* @var array Default configuration values for iterators
*/
protected static $defaultIteratorConfig = array(
'input_token' => null,
'output_token' => null,
'limit_key' => null,
'result_key' => null,
'more_results' => null,
);
/**
* @var array Legacy configuration options mapped to their new names
*/
private static $legacyConfigOptions = array(
'token_param' => 'input_token',
'token_key' => 'output_token',
'limit_param' => 'limit_key',
'more_key' => 'more_results',
);
/**
* @var array Iterator configuration for each iterable operation
*/
protected $config;
/**
* @var ResourceIteratorFactoryInterface Another factory that will be used first to instantiate the iterator
*/
protected $primaryIteratorFactory;
/**
* @param array $config An array of configuration values for the factory
* @param ResourceIteratorFactoryInterface $primaryIteratorFactory Another factory to use for chain of command
*/
public function __construct(array $config, ResourceIteratorFactoryInterface $primaryIteratorFactory = null)
{
$this->primaryIteratorFactory = $primaryIteratorFactory;
$this->config = array();
foreach ($config as $name => $operation) {
$this->config[$name] = $operation + self::$defaultIteratorConfig;
}
}
public function build(CommandInterface $command, array $options = array())
{
// Get the configuration data for the command
$commandName = $command->getName();
$commandSupported = isset($this->config[$commandName]);
$options = $this->translateLegacyConfigOptions($options);
$options += $commandSupported ? $this->config[$commandName] : array();
// Instantiate the iterator using the primary factory (if one was provided)
if ($this->primaryIteratorFactory && $this->primaryIteratorFactory->canBuild($command)) {
$iterator = $this->primaryIteratorFactory->build($command, $options);
} elseif (!$commandSupported) {
throw new InvalidArgumentException(esc_html("Iterator was not found for {$commandName}."));
} else {
// Instantiate a generic AWS resource iterator
$iterator = new AwsResourceIterator($command, $options);
}
return $iterator;
}
public function canBuild(CommandInterface $command)
{
if ($this->primaryIteratorFactory) {
return $this->primaryIteratorFactory->canBuild($command);
} else {
return isset($this->config[$command->getName()]);
}
}
/**
* @param array $config The config for a single operation
*
* @return array The modified config with legacy options translated
*/
private function translateLegacyConfigOptions($config)
{
foreach (self::$legacyConfigOptions as $legacyOption => $newOption) {
if (isset($config[$legacyOption])) {
$config[$newOption] = $config[$legacyOption];
unset($config[$legacyOption]);
}
}
return $config;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Waiter/WaiterClassFactory.php 0000644 00000005665 15132770567 0022324 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Waiter;
use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Inflection\Inflector;
use Guzzle\Inflection\InflectorInterface;
/**
* Factory for creating {@see WaiterInterface} objects using a convention of
* storing waiter classes in the Waiter folder of a client class namespace using
* a snake_case to CamelCase conversion (e.g. camel_case => CamelCase).
*/
class WaiterClassFactory implements WaiterFactoryInterface
{
/**
* @var array List of namespaces used to look for classes
*/
protected $namespaces;
/**
* @var InflectorInterface Inflector used to inflect class names
*/
protected $inflector;
/**
* @param array|string $namespaces Namespaces of waiter objects
* @param InflectorInterface $inflector Inflector used to resolve class names
*/
public function __construct($namespaces = array(), InflectorInterface $inflector = null)
{
$this->namespaces = (array) $namespaces;
$this->inflector = $inflector ?: Inflector::getDefault();
}
/**
* Registers a namespace to check for Waiters
*
* @param string $namespace Namespace which contains Waiter classes
*
* @return self
*/
public function registerNamespace($namespace)
{
array_unshift($this->namespaces, $namespace);
return $this;
}
/**
* {@inheritdoc}
*/
public function build($waiter)
{
if (!($className = $this->getClassName($waiter))) {
throw new InvalidArgumentException(esc_html("Waiter was not found matching {$waiter}."));
}
return new $className();
}
/**
* {@inheritdoc}
*/
public function canBuild($waiter)
{
return $this->getClassName($waiter) !== null;
}
/**
* Get the name of a waiter class
*
* @param string $waiter Waiter name
*
* @return string|null
*/
protected function getClassName($waiter)
{
$waiterName = $this->inflector->camel($waiter);
// Determine the name of the class to load
$className = null;
foreach ($this->namespaces as $namespace) {
$potentialClassName = $namespace . '\\' . $waiterName;
if (class_exists($potentialClassName)) {
return $potentialClassName;
}
}
return null;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Waiter/CallableWaiter.php 0000644 00000004110 15132770567 0021406 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Waiter;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\RuntimeException;
/**
* Callable wait implementation
*/
class CallableWaiter extends AbstractWaiter
{
/**
* @var callable Callable function
*/
protected $callable;
/**
* @var array Additional context for the callable function
*/
protected $context = array();
/**
* Set the callable function to call in each wait attempt
*
* @param callable $callable Callable function
*
* @return self
* @throws InvalidArgumentException when the method is not callable
*/
public function setCallable($callable)
{
if (!is_callable($callable)) {
throw new InvalidArgumentException('Value is not callable');
}
$this->callable = $callable;
return $this;
}
/**
* Set additional context for the callable function. This data will be passed into the callable function as the
* second argument
*
* @param array $context Additional context
*
* @return self
*/
public function setContext(array $context)
{
$this->context = $context;
return $this;
}
/**
* {@inheritdoc}
*/
public function doWait()
{
if (!$this->callable) {
throw new RuntimeException('No callable was specified for the wait method');
}
return call_user_func($this->callable, $this->attempts, $this->context);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Waiter/AbstractWaiter.php 0000644 00000007233 15132770567 0021463 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Waiter;
use Aws\Common\Exception\RuntimeException;
use Guzzle\Common\AbstractHasDispatcher;
/**
* Abstract wait implementation
*/
abstract class AbstractWaiter extends AbstractHasDispatcher implements WaiterInterface
{
protected $attempts = 0;
protected $config = array();
/**
* {@inheritdoc}
*/
public static function getAllEvents()
{
return array(
// About to check if the waiter needs to wait
'waiter.before_attempt',
// About to sleep
'waiter.before_wait',
);
}
/**
* The max attempts allowed by the waiter
*
* @return int
*/
public function getMaxAttempts()
{
return isset($this->config[self::MAX_ATTEMPTS]) ? $this->config[self::MAX_ATTEMPTS] : 10;
}
/**
* Get the amount of time in seconds to delay between attempts
*
* @return int
*/
public function getInterval()
{
return isset($this->config[self::INTERVAL]) ? $this->config[self::INTERVAL] : 0;
}
/**
* {@inheritdoc}
*/
public function setMaxAttempts($maxAttempts)
{
$this->config[self::MAX_ATTEMPTS] = $maxAttempts;
return $this;
}
/**
* {@inheritdoc}
*/
public function setInterval($interval)
{
$this->config[self::INTERVAL] = $interval;
return $this;
}
/**
* Set config options associated with the waiter
*
* @param array $config Options to set
*
* @return self
*/
public function setConfig(array $config)
{
if (isset($config['waiter.before_attempt'])) {
$this->getEventDispatcher()->addListener('waiter.before_attempt', $config['waiter.before_attempt']);
unset($config['waiter.before_attempt']);
}
if (isset($config['waiter.before_wait'])) {
$this->getEventDispatcher()->addListener('waiter.before_wait', $config['waiter.before_wait']);
unset($config['waiter.before_wait']);
}
$this->config = $config;
return $this;
}
/**
* {@inheritdoc}
*/
public function wait()
{
$this->attempts = 0;
do {
$this->dispatch('waiter.before_attempt', array(
'waiter' => $this,
'config' => $this->config,
));
if ($this->doWait()) {
break;
}
if (++$this->attempts >= $this->getMaxAttempts()) {
throw new RuntimeException('Wait method never resolved to true after ' . esc_html($this->attempts) . ' attempts');
}
$this->dispatch('waiter.before_wait', array(
'waiter' => $this,
'config' => $this->config,
));
if ($this->getInterval()) {
usleep($this->getInterval() * 1000000);
}
} while (1);
}
/**
* Method to implement in subclasses
*
* @return bool Return true when successful, false on failure
*/
abstract protected function doWait();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Waiter/WaiterConfig.php 0000644 00000004067 15132770567 0021127 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Waiter;
use Guzzle\Common\Collection;
/**
* Configuration info of a waiter object
*/
class WaiterConfig extends Collection
{
const WAITER_NAME = 'name';
const MAX_ATTEMPTS = 'max_attempts';
const INTERVAL = 'interval';
const OPERATION = 'operation';
const IGNORE_ERRORS = 'ignore_errors';
const DESCRIPTION = 'description';
const SUCCESS_TYPE = 'success.type';
const SUCCESS_PATH = 'success.path';
const SUCCESS_VALUE = 'success.value';
const FAILURE_TYPE = 'failure.type';
const FAILURE_PATH = 'failure.path';
const FAILURE_VALUE = 'failure.value';
/**
* @param array $data Array of configuration directives
*/
public function __construct(array $data = array())
{
$this->data = $data;
$this->extractConfig();
}
/**
* Create the command configuration variables
*/
protected function extractConfig()
{
// Populate success.* and failure.* if specified in acceptor.*
foreach ($this->data as $key => $value) {
if (substr($key, 0, 9) == 'acceptor.') {
$name = substr($key, 9);
if (!isset($this->data["success.{$name}"])) {
$this->data["success.{$name}"] = $value;
}
if (!isset($this->data["failure.{$name}"])) {
$this->data["failure.{$name}"] = $value;
}
unset($this->data[$key]);
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Waiter/AbstractResourceWaiter.php 0000644 00000002472 15132770567 0023173 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Waiter;
use Aws\Common\Client\AwsClientInterface;
use Aws\Common\Exception\RuntimeException;
/**
* Abstract waiter implementation used to wait on resources
*/
abstract class AbstractResourceWaiter extends AbstractWaiter implements ResourceWaiterInterface
{
/**
* @var AwsClientInterface
*/
protected $client;
/**
* {@inheritdoc}
*/
public function setClient(AwsClientInterface $client)
{
$this->client = $client;
return $this;
}
/**
* {@inheritdoc}
*/
public function wait()
{
if (!$this->client) {
throw new RuntimeException('No client has been specified on the waiter');
}
parent::wait();
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Waiter/CompositeWaiterFactory.php 0000644 00000004257 15132770567 0023215 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Waiter;
use Aws\Common\Exception\InvalidArgumentException;
/**
* Factory that utilizes multiple factories for creating waiters
*/
class CompositeWaiterFactory implements WaiterFactoryInterface
{
/**
* @var array Array of factories
*/
protected $factories;
/**
* @param array $factories Array of factories used to instantiate waiters
*/
public function __construct(array $factories)
{
$this->factories = $factories;
}
/**
* {@inheritdoc}
*/
public function build($waiter)
{
if (!($factory = $this->getFactory($waiter))) {
throw new InvalidArgumentException(esc_html("Waiter was not found matching {$waiter}."));
}
return $factory->build($waiter);
}
/**
* {@inheritdoc}
*/
public function canBuild($waiter)
{
return (bool) $this->getFactory($waiter);
}
/**
* Add a factory to the composite factory
*
* @param WaiterFactoryInterface $factory Factory to add
*
* @return self
*/
public function addFactory(WaiterFactoryInterface $factory)
{
$this->factories[] = $factory;
return $this;
}
/**
* Get the factory that matches the waiter name
*
* @param string $waiter Name of the waiter
*
* @return WaiterFactoryInterface|bool
*/
protected function getFactory($waiter)
{
foreach ($this->factories as $factory) {
if ($factory->canBuild($waiter)) {
return $factory;
}
}
return false;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Waiter/ResourceWaiterInterface.php 0000644 00000002010 15132770567 0023314 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Waiter;
use Aws\Common\Client\AwsClientInterface;
/**
* Interface used in conjunction with clients to wait on a resource
*/
interface ResourceWaiterInterface extends WaiterInterface
{
/**
* Set the client associated with the waiter
*
* @param AwsClientInterface $client Client to use with the waiter
*
* @return self
*/
public function setClient(AwsClientInterface $client);
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Waiter/ConfigResourceWaiter.php 0000644 00000016660 15132770567 0022641 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Waiter;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\RuntimeException;
use Aws\Common\Exception\ServiceResponseException;
use Guzzle\Service\Resource\Model;
use Guzzle\Service\Exception\ValidationException;
/**
* Resource waiter driven by configuration options
*/
class ConfigResourceWaiter extends AbstractResourceWaiter
{
/**
* @var WaiterConfig Waiter configuration
*/
protected $waiterConfig;
/**
* @param WaiterConfig $waiterConfig Waiter configuration
*/
public function __construct(WaiterConfig $waiterConfig)
{
$this->waiterConfig = $waiterConfig;
$this->setInterval($waiterConfig->get(WaiterConfig::INTERVAL));
$this->setMaxAttempts($waiterConfig->get(WaiterConfig::MAX_ATTEMPTS));
}
/**
* {@inheritdoc}
*/
public function setConfig(array $config)
{
foreach ($config as $key => $value) {
if (substr($key, 0, 7) == 'waiter.') {
$this->waiterConfig->set(substr($key, 7), $value);
}
}
if (!isset($config[self::INTERVAL])) {
$config[self::INTERVAL] = $this->waiterConfig->get(WaiterConfig::INTERVAL);
}
if (!isset($config[self::MAX_ATTEMPTS])) {
$config[self::MAX_ATTEMPTS] = $this->waiterConfig->get(WaiterConfig::MAX_ATTEMPTS);
}
return parent::setConfig($config);
}
/**
* Get the waiter's configuration data
*
* @return WaiterConfig
*/
public function getWaiterConfig()
{
return $this->waiterConfig;
}
/**
* {@inheritdoc}
*/
protected function doWait()
{
$params = $this->config;
// remove waiter settings from the operation's input
foreach (array_keys($params) as $key) {
if (substr($key, 0, 7) == 'waiter.') {
unset($params[$key]);
}
}
$operation = $this->client->getCommand($this->waiterConfig->get(WaiterConfig::OPERATION), $params);
try {
return $this->checkResult($this->client->execute($operation));
} catch (ValidationException $e) {
throw new InvalidArgumentException(
esc_html($this->waiterConfig->get(WaiterConfig::WAITER_NAME)) . ' waiter validation failed: ' . esc_html($e->getMessage()),
esc_attr($e->getCode()),
esc_attr($e)
);
} catch (ServiceResponseException $e) {
// Check if this exception satisfies a success or failure acceptor
$transition = $this->checkErrorAcceptor($e);
if (null !== $transition) {
return $transition;
}
// Check if this exception should be ignored
foreach ((array) $this->waiterConfig->get(WaiterConfig::IGNORE_ERRORS) as $ignore) {
if ($e->getExceptionCode() == $ignore) {
// This exception is ignored, so it counts as a failed attempt rather than a fast-fail
return false;
}
}
// Allow non-ignore exceptions to bubble through
throw $e;
}
}
/**
* Check if an exception satisfies a success or failure acceptor
*
* @param ServiceResponseException $e
*
* @return bool|null Returns true for success, false for failure, and null for no transition
*/
protected function checkErrorAcceptor(ServiceResponseException $e)
{
if ($this->waiterConfig->get(WaiterConfig::SUCCESS_TYPE) == 'error') {
if ($e->getExceptionCode() == $this->waiterConfig->get(WaiterConfig::SUCCESS_VALUE)) {
// Mark as a success
return true;
}
}
// Mark as an attempt
return null;
}
/**
* Check to see if the response model satisfies a success or failure state
*
* @param Model $result Result model
*
* @return bool
* @throws RuntimeException
*/
protected function checkResult(Model $result)
{
// Check if the result evaluates to true based on the path and output model
if ($this->waiterConfig->get(WaiterConfig::SUCCESS_TYPE) == 'output' &&
$this->checkPath(
$result,
$this->waiterConfig->get(WaiterConfig::SUCCESS_PATH),
$this->waiterConfig->get(WaiterConfig::SUCCESS_VALUE)
)
) {
return true;
}
// It did not finish waiting yet. Determine if we need to fail-fast based on the failure acceptor.
if ($this->waiterConfig->get(WaiterConfig::FAILURE_TYPE) == 'output') {
$failureValue = $this->waiterConfig->get(WaiterConfig::FAILURE_VALUE);
if ($failureValue) {
$key = $this->waiterConfig->get(WaiterConfig::FAILURE_PATH);
if ($this->checkPath($result, $key, $failureValue, false)) {
// Determine which of the results triggered the failure
$triggered = array_intersect(
(array) $this->waiterConfig->get(WaiterConfig::FAILURE_VALUE),
array_unique((array) $result->getPath($key))
);
// fast fail because the failure case was satisfied
throw new RuntimeException(
'A resource entered into an invalid state of "'
. esc_html(implode(', ', $triggered)) . '" while waiting with the "'
. esc_html($this->waiterConfig->get(WaiterConfig::WAITER_NAME)) . '" waiter.'
);
}
}
}
return false;
}
/**
* Check to see if the path of the output key is satisfied by the value
*
* @param Model $model Result model
* @param string $key Key to check
* @param string $checkValue Compare the key to the value
* @param bool $all Set to true to ensure all value match or false to only match one
*
* @return bool
*/
protected function checkPath(Model $model, $key = null, $checkValue = array(), $all = true)
{
// If no key is set, then just assume true because the request succeeded
if (!$key) {
return true;
}
if (!($result = $model->getPath($key))) {
return false;
}
$total = $matches = 0;
foreach ((array) $result as $value) {
$total++;
foreach ((array) $checkValue as $check) {
if ($value == $check) {
$matches++;
break;
}
}
}
// When matching all values, ensure that the match count matches the total count
if ($all && $total != $matches) {
return false;
}
return $matches > 0;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Waiter/WaiterConfigFactory.php 0000644 00000005650 15132770567 0022456 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Waiter;
use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Inflection\Inflector;
use Guzzle\Inflection\InflectorInterface;
/**
* Factory for creating {@see WaiterInterface} objects using a configuration DSL.
*/
class WaiterConfigFactory implements WaiterFactoryInterface
{
/**
* @var array Configuration directives
*/
protected $config;
/**
* @var InflectorInterface Inflector used to inflect class names
*/
protected $inflector;
/**
* @param array $config Array of configuration directives
* @param InflectorInterface $inflector Inflector used to resolve class names
*/
public function __construct(
array $config,
InflectorInterface $inflector = null
) {
$this->config = $config;
$this->inflector = $inflector ?: Inflector::getDefault();
}
/**
* {@inheritdoc}
*/
public function build($waiter)
{
return new ConfigResourceWaiter($this->getWaiterConfig($waiter));
}
/**
* {@inheritdoc}
*/
public function canBuild($waiter)
{
return isset($this->config[$waiter]) || isset($this->config[$this->inflector->camel($waiter)]);
}
/**
* Get waiter configuration data, taking __default__ and extensions into account
*
* @param string $name Waiter name
*
* @return WaiterConfig
* @throws InvalidArgumentException
*/
protected function getWaiterConfig($name)
{
if (!$this->canBuild($name)) {
throw new InvalidArgumentException(esc_html('No waiter found matching "' . $name . '"'));
}
// inflect the name if needed
$name = isset($this->config[$name]) ? $name : $this->inflector->camel($name);
$waiter = new WaiterConfig($this->config[$name]);
$waiter['name'] = $name;
// Always use __default__ as the basis if it's set
if (isset($this->config['__default__'])) {
$parentWaiter = new WaiterConfig($this->config['__default__']);
$waiter = $parentWaiter->overwriteWith($waiter);
}
// Allow for configuration extensions
if (isset($this->config[$name]['extends'])) {
$waiter = $this->getWaiterConfig($this->config[$name]['extends'])->overwriteWith($waiter);
}
return $waiter;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Waiter/WaiterInterface.php 0000644 00000003105 15132770567 0021612 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Waiter;
/**
* WaiterInterface used to wait on something to be in a particular state
*/
interface WaiterInterface
{
const INTERVAL = 'waiter.interval';
const MAX_ATTEMPTS = 'waiter.max_attempts';
/**
* Set the maximum number of attempts to make when waiting
*
* @param int $maxAttempts Max number of attempts
*
* @return self
*/
public function setMaxAttempts($maxAttempts);
/**
* Set the amount of time to interval between attempts
*
* @param int $interval Interval in seconds
*
* @return self
*/
public function setInterval($interval);
/**
* Set configuration options associated with the waiter
*
* @param array $config Configuration options to set
*
* @return self
*/
public function setConfig(array $config);
/**
* Begin the waiting loop
*
* @throw RuntimeException if the method never resolves to true
*/
public function wait();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Waiter/WaiterFactoryInterface.php 0000644 00000002152 15132770567 0023143 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Waiter;
/**
* Waiter factory used to create waiter objects by short names
*/
interface WaiterFactoryInterface
{
/**
* Create a waiter by name
*
* @param string $waiter Name of the waiter to create
*
* @return WaiterInterface
*/
public function build($waiter);
/**
* Check if the factory can create a waiter by a specific name
*
* @param string $waiter Name of the waiter to check
*
* @return bool
*/
public function canBuild($waiter);
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Credentials/CredentialsInterface.php 0000644 00000004650 15132770567 0023624 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Credentials;
/**
* Provides access to the AWS credentials used for accessing AWS services: AWS
* access key ID, secret access key, and security token. These credentials are
* used to securely sign requests to AWS services.
*/
interface CredentialsInterface extends \Serializable
{
/**
* Returns the AWS access key ID for this credentials object.
*
* @return string
*/
public function getAccessKeyId();
/**
* Returns the AWS secret access key for this credentials object.
*
* @return string
*/
public function getSecretKey();
/**
* Get the associated security token if available
*
* @return string|null
*/
public function getSecurityToken();
/**
* Get the UNIX timestamp in which the credentials will expire
*
* @return int|null
*/
public function getExpiration();
/**
* Set the AWS access key ID for this credentials object.
*
* @param string $key AWS access key ID
*
* @return self
*/
public function setAccessKeyId($key);
/**
* Set the AWS secret access key for this credentials object.
*
* @param string $secret AWS secret access key
*
* @return CredentialsInterface
*/
public function setSecretKey($secret);
/**
* Set the security token to use with this credentials object
*
* @param string $token Security token
*
* @return self
*/
public function setSecurityToken($token);
/**
* Set the UNIX timestamp in which the credentials will expire
*
* @param int $timestamp UNIX timestamp expiration
*
* @return self
*/
public function setExpiration($timestamp);
/**
* Check if the credentials are expired
*
* @return bool
*/
public function isExpired();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Credentials/NullCredentials.php 0000644 00000002332 15132770567 0022631 0 ustar 00 <?php
namespace Aws\Common\Credentials;
/**
* A blank set of credentials. AWS clients must be provided credentials, but
* there are some types of requests that do not need authentication. This class
* can be used to pivot on that scenario, and also serve as a mock credentials
* object when testing
*
* @codeCoverageIgnore
*/
class NullCredentials implements CredentialsInterface
{
public function getAccessKeyId()
{
return '';
}
public function getSecretKey()
{
return '';
}
public function getSecurityToken()
{
return null;
}
public function getExpiration()
{
return null;
}
public function isExpired()
{
return false;
}
public function serialize()
{
return 'N;';
}
public function unserialize($serialized)
{
// Nothing to do here.
}
public function setAccessKeyId($key)
{
// Nothing to do here.
}
public function setSecretKey($secret)
{
// Nothing to do here.
}
public function setSecurityToken($token)
{
// Nothing to do here.
}
public function setExpiration($timestamp)
{
// Nothing to do here.
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Credentials/AbstractRefreshableCredentials.php 0000644 00000004360 15132770567 0025630 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Credentials;
/**
* Abstract decorator to provide a foundation for refreshable credentials
*/
abstract class AbstractRefreshableCredentials extends AbstractCredentialsDecorator
{
/**
* Get the underlying credentials, refreshing if necessary.
*
* @return Credentials
*/
public function getCredentials()
{
if ($this->credentials->isExpired()) {
$this->refresh();
}
return new Credentials(
$this->credentials->getAccessKeyId(),
$this->credentials->getSecretKey(),
$this->credentials->getSecurityToken(),
$this->credentials->getExpiration()
);
}
/**
* {@inheritdoc}
*/
public function getAccessKeyId()
{
if ($this->credentials->isExpired()) {
$this->refresh();
}
return $this->credentials->getAccessKeyId();
}
/**
* {@inheritdoc}
*/
public function getSecretKey()
{
if ($this->credentials->isExpired()) {
$this->refresh();
}
return $this->credentials->getSecretKey();
}
/**
* {@inheritdoc}
*/
public function getSecurityToken()
{
if ($this->credentials->isExpired()) {
$this->refresh();
}
return $this->credentials->getSecurityToken();
}
/**
* {@inheritdoc}
*/
public function serialize()
{
if ($this->credentials->isExpired()) {
$this->refresh();
}
return $this->credentials->serialize();
}
/**
* Attempt to get new credentials
*/
abstract protected function refresh();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Credentials/RefreshableInstanceProfileCredentials.php0000644 00000005673 15132770567 0027162 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Credentials;
use Aws\Common\InstanceMetadata\InstanceMetadataClient;
use Aws\Common\Exception\InstanceProfileCredentialsException;
/**
* Credentials decorator used to implement retrieving credentials from the
* EC2 metadata server
*/
class RefreshableInstanceProfileCredentials extends AbstractRefreshableCredentials
{
/**
* @var InstanceMetadataClient
*/
protected $client;
/** @var bool */
private $customClient;
/**
* Constructs a new instance profile credentials decorator
*
* @param CredentialsInterface $credentials Credentials to adapt
* @param InstanceMetadataClient $client Client used to get new credentials
*/
public function __construct(CredentialsInterface $credentials, InstanceMetadataClient $client = null)
{
parent::__construct($credentials);
$this->setClient($client);
}
public function setClient(InstanceMetadataClient $client = null)
{
$this->customClient = null !== $client;
$this->client = $client ?: InstanceMetadataClient::factory();
}
public function serialize()
{
$serializable = array(
'credentials' => parent::serialize(),
'customClient' => $this->customClient,
);
if ($this->customClient) {
$serializable['client'] = serialize($this->client);
}
return json_encode($serializable);
}
public function unserialize($value)
{
$serialized = json_decode($value, true);
parent::unserialize($serialized['credentials']);
$this->customClient = $serialized['customClient'];
$this->client = $this->customClient ?
unserialize($serialized['client'])
: InstanceMetadataClient::factory();
}
/**
* Attempt to get new credentials from the instance profile
*
* @throws InstanceProfileCredentialsException On error
*/
protected function refresh()
{
$credentials = $this->client->getInstanceProfileCredentials();
// Expire the token 5 minutes early to pre-fetch before expiring.
$this->credentials->setAccessKeyId($credentials->getAccessKeyId())
->setSecretKey($credentials->getSecretKey())
->setSecurityToken($credentials->getSecurityToken())
->setExpiration($credentials->getExpiration() - 300);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Credentials/CacheableCredentials.php 0000644 00000005201 15132770567 0023544 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Credentials;
use Guzzle\Cache\CacheAdapterInterface;
/**
* Credentials decorator used to implement caching credentials
*/
class CacheableCredentials extends AbstractRefreshableCredentials
{
/**
* @var CacheAdapterInterface Cache adapter used to store credentials
*/
protected $cache;
/**
* @var string Cache key used to store the credentials
*/
protected $cacheKey;
/**
* CacheableCredentials is a decorator that decorates other credentials
*
* @param CredentialsInterface $credentials Credentials to adapt
* @param CacheAdapterInterface $cache Cache to use to store credentials
* @param string $cacheKey Cache key of the credentials
*/
public function __construct(CredentialsInterface $credentials, CacheAdapterInterface $cache, $cacheKey)
{
$this->cache = $cache;
$this->cacheKey = $cacheKey;
parent::__construct($credentials);
}
/**
* Attempt to get new credentials from cache or from the adapted object
*/
protected function refresh()
{
if (!$cache = $this->cache->fetch($this->cacheKey)) {
// The credentials were not found, so try again and cache if new
$this->credentials->getAccessKeyId();
if (!$this->credentials->isExpired()) {
// The credentials were updated, so cache them
$this->cache->save($this->cacheKey, $this->credentials, $this->credentials->getExpiration() - time());
}
} else {
// The credentials were found in cache, so update the adapter object
// if the cached credentials are not expired
if (!$cache->isExpired()) {
$this->credentials->setAccessKeyId($cache->getAccessKeyId());
$this->credentials->setSecretKey($cache->getSecretKey());
$this->credentials->setSecurityToken($cache->getSecurityToken());
$this->credentials->setExpiration($cache->getExpiration());
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Credentials/Credentials.php 0000644 00000027476 15132770567 0022016 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Credentials;
use Aws\Common\Enum\ClientOptions as Options;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\RequiredExtensionNotLoadedException;
use Aws\Common\Exception\RuntimeException;
use Guzzle\Common\FromConfigInterface;
use Guzzle\Cache\CacheAdapterInterface;
use Guzzle\Cache\DoctrineCacheAdapter;
use Guzzle\Common\Collection;
/**
* Basic implementation of the AWSCredentials interface that allows callers to
* pass in the AWS access key and secret access in the constructor.
*/
class Credentials implements CredentialsInterface, FromConfigInterface
{
const ENV_KEY = 'AWS_ACCESS_KEY_ID';
const ENV_SECRET = 'AWS_SECRET_KEY';
const ENV_SECRET_ACCESS_KEY = 'AWS_SECRET_ACCESS_KEY';
const ENV_PROFILE = 'AWS_PROFILE';
/** @var string AWS Access Key ID */
protected $key;
/** @var string AWS Secret Access Key */
protected $secret;
/** @var string AWS Security Token */
protected $token;
/** @var int Time to die of token */
protected $ttd;
/**
* Get the available keys for the factory method
*
* @return array
*/
public static function getConfigDefaults()
{
return array(
Options::KEY => null,
Options::SECRET => null,
Options::TOKEN => null,
Options::TOKEN_TTD => null,
Options::PROFILE => null,
Options::CREDENTIALS_CACHE => null,
Options::CREDENTIALS_CACHE_KEY => null,
Options::CREDENTIALS_CLIENT => null
);
}
/**
* Factory method for creating new credentials. This factory method will
* create the appropriate credentials object with appropriate decorators
* based on the passed configuration options.
*
* @param array $config Options to use when instantiating the credentials
*
* @return CredentialsInterface
* @throws InvalidArgumentException If the caching options are invalid
* @throws RuntimeException If using the default cache and APC is disabled
*/
public static function factory($config = array())
{
// Add default key values
foreach (self::getConfigDefaults() as $key => $value) {
if (!isset($config[$key])) {
$config[$key] = $value;
}
}
// Set up the cache
$cache = $config[Options::CREDENTIALS_CACHE];
$cacheKey = $config[Options::CREDENTIALS_CACHE_KEY] ?:
'credentials_' . ($config[Options::KEY] ?: crc32(gethostname()));
if (
$cacheKey &&
$cache instanceof CacheAdapterInterface &&
$cached = self::createFromCache($cache, $cacheKey)
) {
return $cached;
}
// Create the credentials object
if (!$config[Options::KEY] || !$config[Options::SECRET]) {
$credentials = self::createFromEnvironment($config);
} else {
// Instantiate using short or long term credentials
$credentials = new static(
$config[Options::KEY],
$config[Options::SECRET],
$config[Options::TOKEN],
$config[Options::TOKEN_TTD]
);
}
// Check if the credentials are refreshable, and if so, configure caching
$cache = $config[Options::CREDENTIALS_CACHE];
if ($cacheKey && $cache) {
$credentials = self::createCache($credentials, $cache, $cacheKey);
}
return $credentials;
}
/**
* Create credentials from the credentials ini file in the HOME directory.
*
* @param string|null $profile Pass a specific profile to use. If no
* profile is specified we will attempt to use
* the value specified in the AWS_PROFILE
* environment variable. If AWS_PROFILE is not
* set, the "default" profile is used.
* @param string|null $filename Pass a string to specify the location of the
* credentials files. If null is passed, the
* SDK will attempt to find the configuration
* file at in your HOME directory at
* ~/.aws/credentials.
* @return CredentialsInterface
* @throws \RuntimeException if the file cannot be found, if the file is
* invalid, or if the profile is invalid.
*/
public static function fromIni($profile = null, $filename = null)
{
if (!$filename) {
$filename = self::getHomeDir() . '/.aws/credentials';
}
if (!$profile) {
$profile = self::getEnvVar(self::ENV_PROFILE) ?: 'default';
}
if (!is_readable($filename) || ($data = parse_ini_file($filename, true)) === false) {
throw new \RuntimeException(esc_html("Invalid AWS credentials file: {$filename}."));
}
if (!isset($data[$profile]['aws_access_key_id']) || !isset($data[$profile]['aws_secret_access_key'])) {
throw new \RuntimeException(esc_html("Invalid AWS credentials profile {$profile} in {$filename}."));
}
return new self(
$data[$profile]['aws_access_key_id'],
$data[$profile]['aws_secret_access_key'],
isset($data[$profile]['aws_security_token'])
? $data[$profile]['aws_security_token']
: null
);
}
/**
* Constructs a new BasicAWSCredentials object, with the specified AWS
* access key and AWS secret key
*
* @param string $accessKeyId AWS access key ID
* @param string $secretAccessKey AWS secret access key
* @param string $token Security token to use
* @param int $expiration UNIX timestamp for when credentials expire
*/
public function __construct($accessKeyId, $secretAccessKey, $token = null, $expiration = null)
{
$this->key = trim($accessKeyId);
$this->secret = trim($secretAccessKey);
$this->token = $token;
$this->ttd = $expiration;
}
public function serialize()
{
return json_encode(array(
Options::KEY => $this->key,
Options::SECRET => $this->secret,
Options::TOKEN => $this->token,
Options::TOKEN_TTD => $this->ttd
));
}
public function unserialize($serialized)
{
$data = json_decode($serialized, true);
$this->key = $data[Options::KEY];
$this->secret = $data[Options::SECRET];
$this->token = $data[Options::TOKEN];
$this->ttd = $data[Options::TOKEN_TTD];
}
public function getAccessKeyId()
{
return $this->key;
}
public function getSecretKey()
{
return $this->secret;
}
public function getSecurityToken()
{
return $this->token;
}
public function getExpiration()
{
return $this->ttd;
}
public function isExpired()
{
return $this->ttd !== null && time() >= $this->ttd;
}
public function setAccessKeyId($key)
{
$this->key = $key;
return $this;
}
public function setSecretKey($secret)
{
$this->secret = $secret;
return $this;
}
public function setSecurityToken($token)
{
$this->token = $token;
return $this;
}
public function setExpiration($timestamp)
{
$this->ttd = $timestamp;
return $this;
}
/**
* When no keys are provided, attempt to create them based on the
* environment or instance profile credentials.
*
* @param array|Collection $config
*
* @return CredentialsInterface
*/
private static function createFromEnvironment($config)
{
// Get key and secret from ENV variables
$envKey = self::getEnvVar(self::ENV_KEY);
if (!($envSecret = self::getEnvVar(self::ENV_SECRET))) {
// Use AWS_SECRET_ACCESS_KEY if AWS_SECRET_KEY was not set
$envSecret = self::getEnvVar(self::ENV_SECRET_ACCESS_KEY);
}
// Use credentials from the environment variables if available
if ($envKey && $envSecret) {
return new static($envKey, $envSecret);
}
try {
// Use credentials from the INI file in HOME directory if available
return self::fromIni($config[Options::PROFILE]);
} catch (\RuntimeException $e) {
// Otherwise, try using instance profile credentials (available on EC2 instances)
return new RefreshableInstanceProfileCredentials(
new static('', '', '', 1),
$config[Options::CREDENTIALS_CLIENT]
);
}
}
private static function createFromCache(CacheAdapterInterface $cache, $cacheKey)
{
$cached = $cache->fetch($cacheKey);
if ($cached instanceof CredentialsInterface && !$cached->isExpired()) {
return new CacheableCredentials($cached, $cache, $cacheKey);
}
return null;
}
private static function createCache(CredentialsInterface $credentials, $cache, $cacheKey)
{
if ($cache === 'true' || $cache === true) {
// If no cache adapter was provided, then create one for the user
// @codeCoverageIgnoreStart
if (!extension_loaded('apc')) {
throw new RequiredExtensionNotLoadedException('PHP has not been compiled with APC. Unable to cache '
. 'the credentials.');
} elseif (!class_exists('Doctrine\Common\Cache\ApcCache')) {
throw new RuntimeException(
'Cannot set ' . esc_html(Options::CREDENTIALS_CACHE) . ' to true because the Doctrine cache component is '
. 'not installed. Either install doctrine/cache or pass in an instantiated '
. 'Guzzle\Cache\CacheAdapterInterface object'
);
}
// @codeCoverageIgnoreEnd
$cache = new DoctrineCacheAdapter(new \Doctrine\Common\Cache\ApcCache());
} elseif (!($cache instanceof CacheAdapterInterface)) {
throw new InvalidArgumentException('Unable to utilize caching with the specified options');
}
// Decorate the credentials with a cache
return new CacheableCredentials($credentials, $cache, $cacheKey);
}
private static function getHomeDir()
{
// On Linux/Unix-like systems, use the HOME environment variable
if ($homeDir = self::getEnvVar('HOME')) {
return $homeDir;
}
// Get the HOMEDRIVE and HOMEPATH values for Windows hosts
$homeDrive = self::getEnvVar('HOMEDRIVE');
$homePath = self::getEnvVar('HOMEPATH');
return ($homeDrive && $homePath) ? $homeDrive . $homePath : null;
}
/**
* Fetches the value of an environment variable by checking $_SERVER and getenv().
*
* @param string $var Name of the environment variable
*
* @return mixed|null
*/
private static function getEnvVar($var)
{
return isset($_SERVER[$var]) ? $_SERVER[$var] : getenv($var);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Credentials/AbstractCredentialsDecorator.php 0000644 00000005437 15132770567 0025336 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Credentials;
/**
* Abstract credentials decorator
*/
class AbstractCredentialsDecorator implements CredentialsInterface
{
/**
* @var CredentialsInterface Wrapped credentials object
*/
protected $credentials;
/**
* Constructs a new BasicAWSCredentials object, with the specified AWS
* access key and AWS secret key
*
* @param CredentialsInterface $credentials
*/
public function __construct(CredentialsInterface $credentials)
{
$this->credentials = $credentials;
}
/**
* {@inheritdoc}
*/
public function serialize()
{
return $this->credentials->serialize();
}
/**
* {@inheritdoc}
*/
public function unserialize($serialized)
{
$this->credentials = new Credentials('', '');
$this->credentials->unserialize($serialized);
}
/**
* {@inheritdoc}
*/
public function getAccessKeyId()
{
return $this->credentials->getAccessKeyId();
}
/**
* {@inheritdoc}
*/
public function getSecretKey()
{
return $this->credentials->getSecretKey();
}
/**
* {@inheritdoc}
*/
public function getSecurityToken()
{
return $this->credentials->getSecurityToken();
}
/**
* {@inheritdoc}
*/
public function getExpiration()
{
return $this->credentials->getExpiration();
}
/**
* {@inheritdoc}
*/
public function isExpired()
{
return $this->credentials->isExpired();
}
/**
* {@inheritdoc}
*/
public function setAccessKeyId($key)
{
$this->credentials->setAccessKeyId($key);
return $this;
}
/**
* {@inheritdoc}
*/
public function setSecretKey($secret)
{
$this->credentials->setSecretKey($secret);
return $this;
}
/**
* {@inheritdoc}
*/
public function setSecurityToken($token)
{
$this->credentials->setSecurityToken($token);
return $this;
}
/**
* {@inheritdoc}
*/
public function setExpiration($timestamp)
{
$this->credentials->setExpiration($timestamp);
return $this;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/UnexpectedValueException.php 0000644 00000001441 15132770567 0024222 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
/**
* AWS SDK namespaced version of the SPL UnexpectedValueException.
*/
class UnexpectedValueException extends \UnexpectedValueException implements AwsExceptionInterface {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/OverflowException.php 0000644 00000001414 15132770567 0022724 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
/**
* AWS SDK namespaced version of the SPL OverflowException.
*/
class OverflowException extends \OverflowException implements AwsExceptionInterface {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/InvalidArgumentException.php 0000644 00000001441 15132770567 0024212 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
/**
* AWS SDK namespaced version of the SPL InvalidArgumentException.
*/
class InvalidArgumentException extends \InvalidArgumentException implements AwsExceptionInterface {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/BadMethodCallException.php 0000644 00000001433 15132770567 0023545 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
/**
* AWS SDK namespaced version of the SPL BadMethodCallException.
*/
class BadMethodCallException extends \BadMethodCallException implements AwsExceptionInterface {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/RuntimeException.php 0000644 00000001411 15132770567 0022541 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
/**
* AWS SDK namespaced version of the SPL RuntimeException.
*/
class RuntimeException extends \RuntimeException implements AwsExceptionInterface {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/RequiredExtensionNotLoadedException.php 0000644 00000001463 15132770567 0026374 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
/**
* Thrown when a particular PHP extension is required to execute the guarded logic, but the extension is not loaded
*/
class RequiredExtensionNotLoadedException extends RuntimeException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/TransferException.php 0000644 00000001423 15132770567 0022705 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
use Guzzle\Http\Exception\CurlException;
/**
* Transfer request exception
*/
class TransferException extends CurlException implements AwsExceptionInterface {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/Parser/JsonQueryExceptionParser.php 0000644 00000002356 15132770567 0025477 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception\Parser;
use Guzzle\Http\Message\Response;
/**
* Parses JSON encoded exception responses from query services
*/
class JsonQueryExceptionParser extends AbstractJsonExceptionParser
{
/**
* {@inheritdoc}
*/
protected function doParse(array $data, Response $response)
{
if ($json = $data['parsed']) {
if (isset($json['__type'])) {
$parts = explode('#', $json['__type']);
$data['code'] = isset($parts[1]) ? $parts[1] : $parts[0];
}
$data['message'] = isset($json['message']) ? $json['message'] : null;
}
return $data;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/Parser/DefaultXmlExceptionParser.php 0000644 00000007211 15132770567 0025600 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception\Parser;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
/**
* Parses default XML exception responses
*/
class DefaultXmlExceptionParser implements ExceptionParserInterface
{
public function parse(RequestInterface $request, Response $response)
{
$data = array(
'code' => null,
'message' => null,
'type' => $response->isClientError() ? 'client' : 'server',
'request_id' => null,
'parsed' => null
);
$body = $response->getBody(true);
if (!$body) {
$this->parseHeaders($request, $response, $data);
return $data;
}
try {
$xml = new \SimpleXMLElement($body);
$this->parseBody($xml, $data);
return $data;
} catch (\Exception $e) {
// Gracefully handle parse errors. This could happen when the
// server responds with a non-XML response (e.g., private beta
// services).
$data['code'] = 'PhpInternalXmlParseError';
$data['message'] = 'A non-XML response was received';
return $data;
}
}
/**
* Parses additional exception information from the response headers
*
* @param RequestInterface $request Request that was issued
* @param Response $response The response from the request
* @param array $data The current set of exception data
*/
protected function parseHeaders(RequestInterface $request, Response $response, array &$data)
{
$data['message'] = $response->getStatusCode() . ' ' . $response->getReasonPhrase();
if ($requestId = $response->getHeader('x-amz-request-id')) {
$data['request_id'] = $requestId;
$data['message'] .= " (Request-ID: $requestId)";
}
}
/**
* Parses additional exception information from the response body
*
* @param \SimpleXMLElement $body The response body as XML
* @param array $data The current set of exception data
*/
protected function parseBody(\SimpleXMLElement $body, array &$data)
{
$data['parsed'] = $body;
$namespaces = $body->getDocNamespaces();
if (isset($namespaces[''])) {
// Account for the default namespace being defined and PHP not being able to handle it :(
$body->registerXPathNamespace('ns', $namespaces['']);
$prefix = 'ns:';
} else {
$prefix = '';
}
if ($tempXml = $body->xpath("//{$prefix}Code[1]")) {
$data['code'] = (string) $tempXml[0];
}
if ($tempXml = $body->xpath("//{$prefix}Message[1]")) {
$data['message'] = (string) $tempXml[0];
}
$tempXml = $body->xpath("//{$prefix}RequestId[1]");
if (empty($tempXml)) {
$tempXml = $body->xpath("//{$prefix}RequestID[1]");
}
if (isset($tempXml[0])) {
$data['request_id'] = (string) $tempXml[0];
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/Parser/JsonRestExceptionParser.php 0000644 00000002720 15132770567 0025302 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception\Parser;
use Guzzle\Http\Message\Response;
/**
* Parses JSON encoded exception responses from REST services
*/
class JsonRestExceptionParser extends AbstractJsonExceptionParser
{
/**
* {@inheritdoc}
*/
protected function doParse(array $data, Response $response)
{
// Merge in error data from the JSON body
if ($json = $data['parsed']) {
$data = array_replace($data, $json);
}
// Correct error type from services like Amazon Glacier
if (!empty($data['type'])) {
$data['type'] = strtolower($data['type']);
}
// Retrieve the error code from services like Amazon Elastic Transcoder
if ($code = (string) $response->getHeader('x-amzn-ErrorType')) {
$data['code'] = substr($code, 0, strpos($code, ':'));
}
return $data;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/Parser/ExceptionParserInterface.php 0000644 00000002561 15132770567 0025436 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception\Parser;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
/**
* Interface used to parse exceptions into an associative array of data
*/
interface ExceptionParserInterface
{
/**
* Parses an exception into an array of data containing at minimum the
* following array keys:
* - type: Exception type
* - code: Exception code
* - message: Exception message
* - request_id: Request ID
* - parsed: The parsed representation of the data (array, SimpleXMLElement, etc)
*
* @param RequestInterface $request
* @param Response $response Unsuccessful response
*
* @return array
*/
public function parse(RequestInterface $request, Response $response);
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/Parser/AbstractJsonExceptionParser.php 0000644 00000004220 15132770567 0026125 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception\Parser;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
/**
* Parses JSON encoded exception responses
*/
abstract class AbstractJsonExceptionParser implements ExceptionParserInterface
{
/**
* {@inheritdoc}
*/
public function parse(RequestInterface $request, Response $response)
{
// Build array of default error data
$data = array(
'code' => null,
'message' => null,
'type' => $response->isClientError() ? 'client' : 'server',
'request_id' => (string) $response->getHeader('x-amzn-RequestId'),
'parsed' => null
);
// Parse the json and normalize key casings
if (null !== $json = json_decode($response->getBody(true), true)) {
$data['parsed'] = array_change_key_case($json);
}
// Do additional, protocol-specific parsing and return the result
$data = $this->doParse($data, $response);
// Remove "Fault" suffix from exception names
if (isset($data['code']) && strpos($data['code'], 'Fault')) {
$data['code'] = preg_replace('/^([a-zA-Z]+)Fault$/', '$1', $data['code']);
}
return $data;
}
/**
* Pull relevant exception data out of the parsed json
*
* @param array $data The exception data
* @param Response $response The response from the service containing the error
*
* @return array
*/
abstract protected function doParse(array $data, Response $response);
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/NamespaceExceptionFactory.php 0000644 00000006771 15132770567 0024360 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
use Aws\Common\Exception\Parser\ExceptionParserInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
/**
* Attempts to create exceptions by inferring the name from the code and a base
* namespace that contains exceptions. Exception classes are expected to be in
* upper camelCase and always end in 'Exception'. 'Exception' will be appended
* if it is not present in the exception code.
*/
class NamespaceExceptionFactory implements ExceptionFactoryInterface
{
/**
* @var ExceptionParserInterface $parser Parser used to parse responses
*/
protected $parser;
/**
* @var string Base namespace containing exception classes
*/
protected $baseNamespace;
/**
* @var string Default class to instantiate if a match is not found
*/
protected $defaultException;
/**
* @param ExceptionParserInterface $parser Parser used to parse exceptions
* @param string $baseNamespace Namespace containing exceptions
* @param string $defaultException Default class to use if one is not mapped
*/
public function __construct(
ExceptionParserInterface $parser,
$baseNamespace,
$defaultException = 'Aws\Common\Exception\ServiceResponseException'
) {
$this->parser = $parser;
$this->baseNamespace = $baseNamespace;
$this->defaultException = $defaultException;
}
/**
* {@inheritdoc}
*/
public function fromResponse(RequestInterface $request, Response $response)
{
$parts = $this->parser->parse($request, $response);
// Removing leading 'AWS.' and embedded periods
$className = $this->baseNamespace . '\\' . str_replace(array('AWS.', '.'), '', $parts['code']);
if (substr($className, -9) !== 'Exception') {
$className .= 'Exception';
}
$className = class_exists($className) ? $className : $this->defaultException;
return $this->createException($className, $request, $response, $parts);
}
/**
* Create an prepare an exception object
*
* @param string $className Name of the class to create
* @param RequestInterface $request Request
* @param Response $response Response received
* @param array $parts Parsed exception data
*
* @return \Exception
*/
protected function createException($className, RequestInterface $request, Response $response, array $parts)
{
$class = new $className($parts['message']);
if ($class instanceof ServiceResponseException) {
$class->setExceptionCode($parts['code']);
$class->setExceptionType($parts['type']);
$class->setResponse($response);
$class->setRequest($request);
$class->setRequestId($parts['request_id']);
}
return $class;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/ExceptionListener.php 0000644 00000003227 15132770567 0022712 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
use Guzzle\Common\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Converts generic Guzzle response exceptions into AWS specific exceptions
*/
class ExceptionListener implements EventSubscriberInterface
{
/**
* @var ExceptionFactoryInterface Factory used to create new exceptions
*/
protected $factory;
/**
* @param ExceptionFactoryInterface $factory Factory used to create exceptions
*/
public function __construct(ExceptionFactoryInterface $factory)
{
$this->factory = $factory;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return array('request.error' => array('onRequestError', -1));
}
/**
* Throws a more meaningful request exception if available
*
* @param Event $event Event emitted
*/
public function onRequestError(Event $event)
{
$e = $this->factory->fromResponse($event['request'], $event['response']);
$event->stopPropagation();
throw $e;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/InstanceProfileCredentialsException.php 0000644 00000002416 15132770567 0026367 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
use Aws\Common\Exception\RuntimeException;
/**
* Exception thrown when an error occurs with instance profile credentials
*/
class InstanceProfileCredentialsException extends RuntimeException
{
/**
* @var string
*/
protected $statusCode;
/**
* Set the error response code received from the instance metadata
*
* @param string $code Response code
*/
public function setStatusCode($code)
{
$this->statusCode = $code;
}
/**
* Get the error response code from the service
*
* @return string|null
*/
public function getStatusCode()
{
return $this->statusCode;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/LogicException.php 0000644 00000001403 15132770567 0022154 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
/**
* AWS SDK namespaced version of the SPL LogicException.
*/
class LogicException extends \LogicException implements AwsExceptionInterface {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/AwsExceptionInterface.php 0000644 00000001643 15132770567 0023500 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
/**
* "Marker Interface" implemented by every exception in the AWS SDK
*/
interface AwsExceptionInterface
{
public function getCode();
public function getLine();
public function getFile();
public function getMessage();
public function getPrevious();
public function getTrace();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/ServiceResponseException.php 0000644 00000011504 15132770567 0024241 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
/**
* Default AWS exception
*/
class ServiceResponseException extends RuntimeException
{
/**
* @var Response Response
*/
protected $response;
/**
* @var RequestInterface Request
*/
protected $request;
/**
* @var string Request ID
*/
protected $requestId;
/**
* @var string Exception type (client / server)
*/
protected $exceptionType;
/**
* @var string Exception code
*/
protected $exceptionCode;
/**
* Set the exception code
*
* @param string $code Exception code
*/
public function setExceptionCode($code)
{
$this->exceptionCode = $code;
}
/**
* Get the exception code
*
* @return string|null
*/
public function getExceptionCode()
{
return $this->exceptionCode;
}
/**
* Set the exception type
*
* @param string $type Exception type
*/
public function setExceptionType($type)
{
$this->exceptionType = $type;
}
/**
* Get the exception type (one of client or server)
*
* @return string|null
*/
public function getExceptionType()
{
return $this->exceptionType;
}
/**
* Set the request ID
*
* @param string $id Request ID
*/
public function setRequestId($id)
{
$this->requestId = $id;
}
/**
* Get the Request ID
*
* @return string|null
*/
public function getRequestId()
{
return $this->requestId;
}
/**
* Set the associated response
*
* @param Response $response Response
*/
public function setResponse(Response $response)
{
$this->response = $response;
}
/**
* Get the associated response object
*
* @return Response|null
*/
public function getResponse()
{
return $this->response;
}
/**
* Set the associated request
*
* @param RequestInterface $request
*/
public function setRequest(RequestInterface $request)
{
$this->request = $request;
}
/**
* Get the associated request object
*
* @return RequestInterface|null
*/
public function getRequest()
{
return $this->request;
}
/**
* Get the status code of the response
*
* @return int|null
*/
public function getStatusCode()
{
return $this->response ? $this->response->getStatusCode() : null;
}
/**
* Cast to a string
*
* @return string
*/
public function __toString()
{
$message = get_class($this) . ': '
. 'AWS Error Code: ' . $this->getExceptionCode() . ', '
. 'Status Code: ' . $this->getStatusCode() . ', '
. 'AWS Request ID: ' . $this->getRequestId() . ', '
. 'AWS Error Type: ' . $this->getExceptionType() . ', '
. 'AWS Error Message: ' . $this->getMessage();
// Add the User-Agent if available
if ($this->request) {
$message .= ', ' . 'User-Agent: ' . $this->request->getHeader('User-Agent');
}
return $message;
}
/**
* Get the request ID of the error. This value is only present if a
* response was received, and is not present in the event of a networking
* error.
*
* Same as `getRequestId()` method, but matches the interface for SDKv3.
*
* @return string|null Returns null if no response was received
*/
public function getAwsRequestId()
{
return $this->requestId;
}
/**
* Get the AWS error type.
*
* Same as `getExceptionType()` method, but matches the interface for SDKv3.
*
* @return string|null Returns null if no response was received
*/
public function getAwsErrorType()
{
return $this->exceptionType;
}
/**
* Get the AWS error code.
*
* Same as `getExceptionCode()` method, but matches the interface for SDKv3.
*
* @return string|null Returns null if no response was received
*/
public function getAwsErrorCode()
{
return $this->exceptionCode;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/DomainException.php 0000644 00000001406 15132770567 0022331 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
/**
* AWS SDK namespaced version of the SPL DomainException.
*/
class DomainException extends \DomainException implements AwsExceptionInterface {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/ExceptionFactoryInterface.php 0000644 00000002172 15132770567 0024353 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
/**
* Interface used to create AWS exception
*/
interface ExceptionFactoryInterface
{
/**
* Returns an AWS service specific exception
*
* @param RequestInterface $request Unsuccessful request
* @param Response $response Unsuccessful response that was encountered
*
* @return \Exception|AwsExceptionInterface
*/
public function fromResponse(RequestInterface $request, Response $response);
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/MultipartUploadException.php 0000644 00000003147 15132770567 0024254 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
use Aws\Common\Model\MultipartUpload\TransferStateInterface;
/**
* Thrown when a {@see Aws\Common\MultipartUpload\TransferInterface} object encounters an error during transfer
*/
class MultipartUploadException extends RuntimeException
{
/**
* @var TransferStateInterface State of the transfer when the error was encountered
*/
protected $state;
/**
* @param TransferStateInterface $state Transfer state
* @param \Exception $exception Last encountered exception
*/
public function __construct(TransferStateInterface $state, \Exception $exception = null)
{
parent::__construct(
'An error was encountered while performing a multipart upload: ' . $exception->getMessage(),
0,
$exception
);
$this->state = $state;
}
/**
* Get the state of the transfer
*
* @return TransferStateInterface
*/
public function getState()
{
return $this->state;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Exception/OutOfBoundsException.php 0000644 00000001422 15132770567 0023327 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Exception;
/**
* AWS SDK namespaced version of the SPL OverflowException.
*/
class OutOfBoundsException extends \OutOfBoundsException implements AwsExceptionInterface {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Client/UserAgentListener.php 0000644 00000003643 15132770567 0022133 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Client;
use Guzzle\Common\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Listener used to append strings to the User-Agent header of a request based
* on the `ua.append` option. `ua.append` can contain a string or array of values.
*/
class UserAgentListener implements EventSubscriberInterface
{
/**
* @var string Option used to store User-Agent modifiers
*/
const OPTION = 'ua.append';
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return array('command.before_send' => 'onBeforeSend');
}
/**
* Adds strings to the User-Agent header using the `ua.append` parameter of a command
*
* @param Event $event Event emitted
*/
public function onBeforeSend(Event $event)
{
$command = $event['command'];
if ($userAgentAppends = $command->get(self::OPTION)) {
$request = $command->getRequest();
$userAgent = (string) $request->getHeader('User-Agent');
foreach ((array) $userAgentAppends as $append) {
$append = ' ' . $append;
if (strpos($userAgent, $append) === false) {
$userAgent .= $append;
}
}
$request->setHeader('User-Agent', $userAgent);
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Client/AbstractClient.php 0000644 00000022744 15132770567 0021435 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Client;
use Aws\Common\Aws;
use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Enum\ClientOptions as Options;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\TransferException;
use Aws\Common\RulesEndpointProvider;
use Aws\Common\Signature\EndpointSignatureInterface;
use Aws\Common\Signature\SignatureInterface;
use Aws\Common\Signature\SignatureListener;
use Aws\Common\Waiter\WaiterClassFactory;
use Aws\Common\Waiter\CompositeWaiterFactory;
use Aws\Common\Waiter\WaiterFactoryInterface;
use Aws\Common\Waiter\WaiterConfigFactory;
use Guzzle\Common\Collection;
use Guzzle\Http\Exception\CurlException;
use Guzzle\Http\QueryAggregator\DuplicateAggregator;
use Guzzle\Service\Client;
use Guzzle\Service\Description\ServiceDescriptionInterface;
/**
* Abstract AWS client
*/
abstract class AbstractClient extends Client implements AwsClientInterface
{
/** @var CredentialsInterface AWS credentials */
protected $credentials;
/** @var SignatureInterface Signature implementation of the service */
protected $signature;
/** @var WaiterFactoryInterface Factory used to create waiter classes */
protected $waiterFactory;
/** @var DuplicateAggregator Cached query aggregator*/
protected $aggregator;
/**
* {@inheritdoc}
*/
public static function getAllEvents()
{
return array_merge(Client::getAllEvents(), array(
'client.region_changed',
'client.credentials_changed',
));
}
/**
* @param CredentialsInterface $credentials AWS credentials
* @param SignatureInterface $signature Signature implementation
* @param Collection $config Configuration options
*
* @throws InvalidArgumentException if an endpoint provider isn't provided
*/
public function __construct(CredentialsInterface $credentials, SignatureInterface $signature, Collection $config)
{
// Bootstrap with Guzzle
parent::__construct($config->get(Options::BASE_URL), $config);
$this->credentials = $credentials;
$this->signature = $signature;
$this->aggregator = new DuplicateAggregator();
// Make sure the user agent is prefixed by the SDK version
$this->setUserAgent('aws-sdk-php2/' . Aws::VERSION, true);
// Add the event listener so that requests are signed before they are sent
$dispatcher = $this->getEventDispatcher();
$dispatcher->addSubscriber(new SignatureListener($credentials, $signature));
if ($backoff = $config->get(Options::BACKOFF)) {
$dispatcher->addSubscriber($backoff, -255);
}
}
public function __call($method, $args)
{
if (substr($method, 0, 3) === 'get' && substr($method, -8) === 'Iterator') {
// Allow magic method calls for iterators (e.g. $client->get<CommandName>Iterator($params))
$commandOptions = isset($args[0]) ? $args[0] : null;
$iteratorOptions = isset($args[1]) ? $args[1] : array();
return $this->getIterator(substr($method, 3, -8), $commandOptions, $iteratorOptions);
} elseif (substr($method, 0, 9) == 'waitUntil') {
// Allow magic method calls for waiters (e.g. $client->waitUntil<WaiterName>($params))
return $this->waitUntil(substr($method, 9), isset($args[0]) ? $args[0]: array());
} else {
return parent::__call(ucfirst($method), $args);
}
}
/**
* Get an endpoint for a specific region from a service description
* @deprecated This function will no longer be updated to work with new regions.
*/
public static function getEndpoint(ServiceDescriptionInterface $description, $region, $scheme)
{
try {
$service = $description->getData('endpointPrefix');
$provider = RulesEndpointProvider::fromDefaults();
$result = $provider(array(
'service' => $service,
'region' => $region,
'scheme' => $scheme
));
return $result['endpoint'];
} catch (\InvalidArgumentException $e) {
throw new InvalidArgumentException(esc_html($e->getMessage()), 0, esc_attr($e));
}
}
public function getCredentials()
{
return $this->credentials;
}
public function setCredentials(CredentialsInterface $credentials)
{
$formerCredentials = $this->credentials;
$this->credentials = $credentials;
// Dispatch an event that the credentials have been changed
$this->dispatch('client.credentials_changed', array(
'credentials' => $credentials,
'former_credentials' => $formerCredentials,
));
return $this;
}
public function getSignature()
{
return $this->signature;
}
public function getRegions()
{
return $this->serviceDescription->getData('regions');
}
public function getRegion()
{
return $this->getConfig(Options::REGION);
}
public function setRegion($region)
{
$config = $this->getConfig();
$formerRegion = $config->get(Options::REGION);
$global = $this->serviceDescription->getData('globalEndpoint');
$provider = $config->get('endpoint_provider');
if (!$provider) {
throw new \RuntimeException('No endpoint provider configured');
}
// Only change the region if the service does not have a global endpoint
if (!$global || $this->serviceDescription->getData('namespace') === 'S3') {
$endpoint = call_user_func(
$provider,
array(
'scheme' => $config->get(Options::SCHEME),
'region' => $region,
'service' => $config->get(Options::SERVICE)
)
);
$this->setBaseUrl($endpoint['endpoint']);
$config->set(Options::BASE_URL, $endpoint['endpoint']);
$config->set(Options::REGION, $region);
// Update the signature if necessary
$signature = $this->getSignature();
if ($signature instanceof EndpointSignatureInterface) {
/** @var EndpointSignatureInterface $signature */
$signature->setRegionName($region);
}
// Dispatch an event that the region has been changed
$this->dispatch('client.region_changed', array(
'region' => $region,
'former_region' => $formerRegion,
));
}
return $this;
}
public function waitUntil($waiter, array $input = array())
{
$this->getWaiter($waiter, $input)->wait();
return $this;
}
public function getWaiter($waiter, array $input = array())
{
return $this->getWaiterFactory()->build($waiter)
->setClient($this)
->setConfig($input);
}
public function setWaiterFactory(WaiterFactoryInterface $waiterFactory)
{
$this->waiterFactory = $waiterFactory;
return $this;
}
public function getWaiterFactory()
{
if (!$this->waiterFactory) {
$clientClass = get_class($this);
// Use a composite factory that checks for classes first, then config waiters
$this->waiterFactory = new CompositeWaiterFactory(array(
new WaiterClassFactory(substr($clientClass, 0, strrpos($clientClass, '\\')) . '\\Waiter')
));
if ($this->getDescription()) {
$waiterConfig = $this->getDescription()->getData('waiters') ?: array();
$this->waiterFactory->addFactory(new WaiterConfigFactory($waiterConfig));
}
}
return $this->waiterFactory;
}
public function getApiVersion()
{
return $this->serviceDescription->getApiVersion();
}
/**
* {@inheritdoc}
* @throws \Aws\Common\Exception\TransferException
*/
public function send($requests)
{
try {
return parent::send($requests);
} catch (CurlException $e) {
$wrapped = new TransferException($e->getMessage(), null, $e);
$wrapped->setCurlHandle($e->getCurlHandle())
->setCurlInfo($e->getCurlInfo())
->setError($e->getError(), $e->getErrorNo())
->setRequest($e->getRequest());
throw $wrapped;
}
}
/**
* Ensures that the duplicate query string aggregator is used so that
* query string values are sent over the wire as foo=bar&foo=baz.
* {@inheritdoc}
*/
public function createRequest(
$method = 'GET',
$uri = null,
$headers = null,
$body = null,
array $options = array()
) {
$request = parent::createRequest($method, $uri, $headers, $body, $options);
$request->getQuery()->setAggregator($this->aggregator);
return $request;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Client/ClientBuilder.php 0000644 00000043121 15132770567 0021250 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Client;
use Aws\Common\Credentials\Credentials;
use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Credentials\NullCredentials;
use Aws\Common\Enum\ClientOptions as Options;
use Aws\Common\Exception\ExceptionListener;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\NamespaceExceptionFactory;
use Aws\Common\Exception\Parser\DefaultXmlExceptionParser;
use Aws\Common\Exception\Parser\ExceptionParserInterface;
use Aws\Common\Iterator\AwsResourceIteratorFactory;
use Aws\Common\RulesEndpointProvider;
use Aws\Common\Signature\EndpointSignatureInterface;
use Aws\Common\Signature\SignatureInterface;
use Aws\Common\Signature\SignatureV2;
use Aws\Common\Signature\SignatureV3Https;
use Aws\Common\Signature\SignatureV4;
use Guzzle\Common\Collection;
use Guzzle\Plugin\Backoff\BackoffPlugin;
use Guzzle\Plugin\Backoff\CurlBackoffStrategy;
use Guzzle\Plugin\Backoff\ExponentialBackoffStrategy;
use Guzzle\Plugin\Backoff\HttpBackoffStrategy;
use Guzzle\Plugin\Backoff\TruncatedBackoffStrategy;
use Guzzle\Service\Description\ServiceDescription;
use Guzzle\Service\Resource\ResourceIteratorClassFactory;
use Guzzle\Log\LogAdapterInterface;
use Guzzle\Log\ClosureLogAdapter;
use Guzzle\Plugin\Backoff\BackoffLogger;
/**
* Builder for creating AWS service clients
*/
class ClientBuilder
{
/**
* @var array Default client config
*/
protected static $commonConfigDefaults = array('scheme' => 'https');
/**
* @var array Default client requirements
*/
protected static $commonConfigRequirements = array(Options::SERVICE_DESCRIPTION);
/**
* @var string The namespace of the client
*/
protected $clientNamespace;
/**
* @var array The config options
*/
protected $config = array();
/**
* @var array The config defaults
*/
protected $configDefaults = array();
/**
* @var array The config requirements
*/
protected $configRequirements = array();
/**
* @var ExceptionParserInterface The Parser interface for the client
*/
protected $exceptionParser;
/**
* @var array Array of configuration data for iterators available for the client
*/
protected $iteratorsConfig = array();
/** @var string */
private $clientClass;
/** @var string */
private $serviceName;
/**
* Factory method for creating the client builder
*
* @param string $namespace The namespace of the client
*
* @return ClientBuilder
*/
public static function factory($namespace = null)
{
return new static($namespace);
}
/**
* Constructs a client builder
*
* @param string $namespace The namespace of the client
*/
public function __construct($namespace = null)
{
$this->clientNamespace = $namespace;
// Determine service and class name
$this->clientClass = 'Aws\Common\Client\DefaultClient';
if ($this->clientNamespace) {
$this->serviceName = substr($this->clientNamespace, strrpos($this->clientNamespace, '\\') + 1);
$this->clientClass = $this->clientNamespace . '\\' . $this->serviceName . 'Client';
}
}
/**
* Sets the config options
*
* @param array|Collection $config The config options
*
* @return ClientBuilder
*/
public function setConfig($config)
{
$this->config = $this->processArray($config);
return $this;
}
/**
* Sets the config options' defaults
*
* @param array|Collection $defaults The default values
*
* @return ClientBuilder
*/
public function setConfigDefaults($defaults)
{
$this->configDefaults = $this->processArray($defaults);
return $this;
}
/**
* Sets the required config options
*
* @param array|Collection $required The required config options
*
* @return ClientBuilder
*/
public function setConfigRequirements($required)
{
$this->configRequirements = $this->processArray($required);
return $this;
}
/**
* Sets the exception parser. If one is not provided the builder will use
* the default XML exception parser.
*
* @param ExceptionParserInterface $parser The exception parser
*
* @return ClientBuilder
*/
public function setExceptionParser(ExceptionParserInterface $parser)
{
$this->exceptionParser = $parser;
return $this;
}
/**
* Set the configuration for the client's iterators
*
* @param array $config Configuration data for client's iterators
*
* @return ClientBuilder
*/
public function setIteratorsConfig(array $config)
{
$this->iteratorsConfig = $config;
return $this;
}
/**
* Performs the building logic using all of the parameters that have been
* set and falling back to default values. Returns an instantiate service
* client with credentials prepared and plugins attached.
*
* @return AwsClientInterface
* @throws InvalidArgumentException
*/
public function build()
{
// Resolve configuration
$config = Collection::fromConfig(
$this->config,
array_merge(self::$commonConfigDefaults, $this->configDefaults),
(self::$commonConfigRequirements + $this->configRequirements)
);
if ($config[Options::VERSION] === 'latest') {
$config[Options::VERSION] = constant("{$this->clientClass}::LATEST_API_VERSION");
}
if (!isset($config['endpoint_provider'])) {
$config['endpoint_provider'] = RulesEndpointProvider::fromDefaults();
}
// Resolve the endpoint, signature, and credentials
$description = $this->updateConfigFromDescription($config);
$signature = $this->getSignature($description, $config);
$credentials = $this->getCredentials($config);
$this->extractHttpConfig($config);
// Resolve exception parser
if (!$this->exceptionParser) {
$this->exceptionParser = new DefaultXmlExceptionParser();
}
// Resolve backoff strategy
$backoff = $config->get(Options::BACKOFF);
if ($backoff === null) {
$retries = isset($config[Options::BACKOFF_RETRIES]) ? $config[Options::BACKOFF_RETRIES] : 3;
$backoff = $this->createDefaultBackoff($retries);
$config->set(Options::BACKOFF, $backoff);
}
if ($backoff) {
$this->addBackoffLogger($backoff, $config);
}
/** @var AwsClientInterface $client */
$client = new $this->clientClass($credentials, $signature, $config);
$client->setDescription($description);
// Add exception marshaling so that more descriptive exception are thrown
if ($this->clientNamespace) {
$exceptionFactory = new NamespaceExceptionFactory(
$this->exceptionParser,
"{$this->clientNamespace}\\Exception",
"{$this->clientNamespace}\\Exception\\{$this->serviceName}Exception"
);
$client->addSubscriber(new ExceptionListener($exceptionFactory));
}
// Add the UserAgentPlugin to append to the User-Agent header of requests
$client->addSubscriber(new UserAgentListener());
// Filters used for the cache plugin
$client->getConfig()->set(
'params.cache.key_filter',
'header=date,x-amz-date,x-amz-security-token,x-amzn-authorization'
);
// Set the iterator resource factory based on the provided iterators config
$client->setResourceIteratorFactory(new AwsResourceIteratorFactory(
$this->iteratorsConfig,
new ResourceIteratorClassFactory($this->clientNamespace . '\\Iterator')
));
// Disable parameter validation if needed
if ($config->get(Options::VALIDATION) === false) {
$params = $config->get('command.params') ?: array();
$params['command.disable_validation'] = true;
$config->set('command.params', $params);
}
return $client;
}
/**
* Add backoff logging to the backoff plugin if needed
*
* @param BackoffPlugin $plugin Backoff plugin
* @param Collection $config Configuration settings
*
* @throws InvalidArgumentException
*/
protected function addBackoffLogger(BackoffPlugin $plugin, Collection $config)
{
// The log option can be set to `debug` or an instance of a LogAdapterInterface
if ($logger = $config->get(Options::BACKOFF_LOGGER)) {
$format = $config->get(Options::BACKOFF_LOGGER_TEMPLATE);
if ($logger === 'debug') {
$logger = new ClosureLogAdapter(function ($message) {
trigger_error(esc_html($message) . "\n");
});
} elseif (!($logger instanceof LogAdapterInterface)) {
throw new InvalidArgumentException(
esc_html(Options::BACKOFF_LOGGER) . ' must be set to `debug` or an instance of '
. 'Guzzle\\Common\\Log\\LogAdapterInterface'
);
}
// Create the plugin responsible for logging exponential backoff retries
$logPlugin = new BackoffLogger($logger);
// You can specify a custom format or use the default
if ($format) {
$logPlugin->setTemplate($format);
}
$plugin->addSubscriber($logPlugin);
}
}
/**
* Ensures that an array (e.g. for config data) is actually in array form
*
* @param array|Collection $array The array data
*
* @return array
* @throws InvalidArgumentException if the arg is not an array or Collection
*/
protected function processArray($array)
{
if ($array instanceof Collection) {
$array = $array->getAll();
}
if (!is_array($array)) {
throw new InvalidArgumentException('The config must be provided as an array or Collection.');
}
return $array;
}
/**
* Update a configuration object from a service description
*
* @param Collection $config Config to update
*
* @return ServiceDescription
* @throws InvalidArgumentException
*/
protected function updateConfigFromDescription(Collection $config)
{
$description = $config->get(Options::SERVICE_DESCRIPTION);
if (!($description instanceof ServiceDescription)) {
// Inject the version into the sprintf template if it is a string
if (is_string($description)) {
$description = sprintf($description, $config->get(Options::VERSION));
}
$description = ServiceDescription::factory($description);
$config->set(Options::SERVICE_DESCRIPTION, $description);
}
if (!$config->get(Options::SERVICE)) {
$config->set(Options::SERVICE, $description->getData('endpointPrefix'));
}
if ($iterators = $description->getData('iterators')) {
$this->setIteratorsConfig($iterators);
}
$this->handleRegion($config);
$this->handleEndpoint($config);
return $description;
}
/**
* Return an appropriate signature object for a a client based on the
* "signature" configuration setting, or the default signature specified in
* a service description. The signature can be set to a valid signature
* version identifier string or an instance of Aws\Common\Signature\SignatureInterface.
*
* @param ServiceDescription $description Description that holds a signature option
* @param Collection $config Configuration options
*
* @return SignatureInterface
* @throws InvalidArgumentException
*/
protected function getSignature(ServiceDescription $description, Collection $config)
{
// If a custom signature has not been provided, then use the default
// signature setting specified in the service description.
$signature = $config->get(Options::SIGNATURE) ?: $description->getData('signatureVersion');
if (is_string($signature)) {
if ($signature == 'v4') {
$signature = new SignatureV4();
} elseif ($signature == 'v2') {
$signature = new SignatureV2();
} elseif ($signature == 'v3https') {
$signature = new SignatureV3Https();
} else {
throw new InvalidArgumentException(esc_html("Invalid signature type: {$signature}"));
}
} elseif (!($signature instanceof SignatureInterface)) {
throw new InvalidArgumentException('The provided signature is not '
. 'a signature version string or an instance of '
. 'Aws\\Common\\Signature\\SignatureInterface');
}
// Allow a custom service name or region value to be provided
if ($signature instanceof EndpointSignatureInterface) {
// Determine the service name to use when signing
$signature->setServiceName($config->get(Options::SIGNATURE_SERVICE)
?: $description->getData('signingName')
?: $description->getData('endpointPrefix'));
// Determine the region to use when signing requests
$signature->setRegionName($config->get(Options::SIGNATURE_REGION) ?: $config->get(Options::REGION));
}
return $signature;
}
protected function getCredentials(Collection $config)
{
$credentials = $config->get(Options::CREDENTIALS);
if (is_array($credentials)) {
$credentials = Credentials::factory($credentials);
} elseif ($credentials === false) {
$credentials = new NullCredentials();
} elseif (!$credentials instanceof CredentialsInterface) {
$credentials = Credentials::factory($config);
}
return $credentials;
}
private function handleRegion(Collection $config)
{
// Make sure a valid region is set
$region = $config[Options::REGION];
$description = $config[Options::SERVICE_DESCRIPTION];
$global = $description->getData('globalEndpoint');
if (!$global && !$region) {
throw new InvalidArgumentException(
'A region is required when using ' . esc_html($description->getData('serviceFullName'))
);
} elseif ($global && !$region) {
$config[Options::REGION] = 'us-east-1';
}
}
private function handleEndpoint(Collection $config)
{
// Alias "endpoint" with "base_url" for forwards compatibility.
if ($config['endpoint']) {
$config[Options::BASE_URL] = $config['endpoint'];
return;
}
if ($config[Options::BASE_URL]) {
return;
}
$endpoint = call_user_func(
$config['endpoint_provider'],
array(
'scheme' => $config[Options::SCHEME],
'region' => $config[Options::REGION],
'service' => $config[Options::SERVICE]
)
);
$config[Options::BASE_URL] = $endpoint['endpoint'];
// Set a signature if one was not explicitly provided.
if (!$config->hasKey(Options::SIGNATURE)
&& isset($endpoint['signatureVersion'])
) {
$config->set(Options::SIGNATURE, $endpoint['signatureVersion']);
}
// The the signing region if endpoint rule specifies one.
if (isset($endpoint['credentialScope'])) {
$scope = $endpoint['credentialScope'];
if (isset($scope['region'])) {
$config->set(Options::SIGNATURE_REGION, $scope['region']);
}
}
}
private function createDefaultBackoff($retries = 3)
{
return new BackoffPlugin(
// Retry failed requests up to 3 times if it is determined that the request can be retried
new TruncatedBackoffStrategy($retries,
// Retry failed requests with 400-level responses due to throttling
new ThrottlingErrorChecker($this->exceptionParser,
// Retry failed requests due to transient network or cURL problems
new CurlBackoffStrategy(null,
// Retry failed requests with 500-level responses
new HttpBackoffStrategy(array(500, 503, 509),
// Retry requests that failed due to expired credentials
new ExpiredCredentialsChecker($this->exceptionParser,
new ExponentialBackoffStrategy()
)
)
)
)
)
);
}
private function extractHttpConfig(Collection $config)
{
$http = $config['http'];
if (!is_array($http)) {
return;
}
if (isset($http['verify'])) {
$config[Options::SSL_CERT] = $http['verify'];
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Client/ThrottlingErrorChecker.php 0000644 00000004532 15132770567 0023163 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Client;
use Aws\Common\Exception\Parser\ExceptionParserInterface;
use Guzzle\Http\Exception\HttpException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Backoff\BackoffStrategyInterface;
use Guzzle\Plugin\Backoff\AbstractBackoffStrategy;
/**
* Backoff logic that handles throttling exceptions from services
*/
class ThrottlingErrorChecker extends AbstractBackoffStrategy
{
/** @var array Whitelist of exception codes (as indexes) that indicate throttling */
protected static $throttlingExceptions = array(
'RequestLimitExceeded' => true,
'Throttling' => true,
'ThrottlingException' => true,
'ProvisionedThroughputExceededException' => true,
'RequestThrottled' => true,
);
/**
* @var ExceptionParserInterface Exception parser used to parse exception responses
*/
protected $exceptionParser;
public function __construct(ExceptionParserInterface $exceptionParser, BackoffStrategyInterface $next = null)
{
$this->exceptionParser = $exceptionParser;
if ($next) {
$this->setNext($next);
}
}
/**
* {@inheritdoc}
*/
public function makesDecision()
{
return true;
}
/**
* {@inheritdoc}
*/
protected function getDelay(
$retries,
RequestInterface $request,
Response $response = null,
HttpException $e = null
) {
if ($response && $response->isClientError()) {
$parts = $this->exceptionParser->parse($request, $response);
return isset(self::$throttlingExceptions[$parts['code']]) ? true : null;
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Client/AwsClientInterface.php 0000644 00000006272 15132770567 0022243 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Client;
use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Signature\SignatureInterface;
use Aws\Common\Waiter\WaiterFactoryInterface;
use Aws\Common\Waiter\WaiterInterface;
use Guzzle\Service\ClientInterface;
/**
* Interface that all AWS clients implement
*/
interface AwsClientInterface extends ClientInterface
{
/**
* Returns the AWS credentials associated with the client
*
* @return CredentialsInterface
*/
public function getCredentials();
/**
* Sets the credentials object associated with the client
*
* @param CredentialsInterface $credentials Credentials object to use
*
* @return self
*/
public function setCredentials(CredentialsInterface $credentials);
/**
* Returns the signature implementation used with the client
*
* @return SignatureInterface
*/
public function getSignature();
/**
* Get a list of available regions and region data
*
* @return array
*/
public function getRegions();
/**
* Get the name of the region to which the client is configured to send requests
*
* @return string
*/
public function getRegion();
/**
* Change the region to which the client is configured to send requests
*
* @param string $region Name of the region
*
* @return self
*/
public function setRegion($region);
/**
* Get the waiter factory being used by the client
*
* @return WaiterFactoryInterface
*/
public function getWaiterFactory();
/**
* Set the waiter factory to use with the client
*
* @param WaiterFactoryInterface $waiterFactory Factory used to create waiters
*
* @return self
*/
public function setWaiterFactory(WaiterFactoryInterface $waiterFactory);
/**
* Wait until a resource is available or an associated waiter returns true
*
* @param string $waiter Name of the waiter
* @param array $input Values used as input for the underlying operation and to control the waiter
*
* @return self
*/
public function waitUntil($waiter, array $input = array());
/**
* Get a named waiter object
*
* @param string $waiter Name of the waiter
* @param array $input Values used as input for the underlying operation and to control the waiter
*
* @return WaiterInterface
*/
public function getWaiter($waiter, array $input = array());
/**
* Get the API version of the client (e.g. 2006-03-01)
*
* @return string
*/
public function getApiVersion();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Client/UploadBodyListener.php 0000644 00000006505 15132770567 0022300 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Client;
use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Common\Event;
use Guzzle\Http\EntityBody;
use Guzzle\Service\Command\AbstractCommand as Command;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Prepares the body parameter of a command such that the parameter is more flexible (e.g. accepts file handles) with
* the value it accepts but converts it to the correct format for the command. Also looks for a "Filename" parameter.
*/
class UploadBodyListener implements EventSubscriberInterface
{
/**
* @var array The names of the commands of which to modify the body parameter
*/
protected $commands;
/**
* @var string The key for the upload body parameter
*/
protected $bodyParameter;
/**
* @var string The key for the source file parameter
*/
protected $sourceParameter;
/**
* @param array $commands The commands to modify
* @param string $bodyParameter The key for the body parameter
* @param string $sourceParameter The key for the source file parameter
*/
public function __construct(array $commands, $bodyParameter = 'Body', $sourceParameter = 'SourceFile')
{
$this->commands = $commands;
$this->bodyParameter = (string) $bodyParameter;
$this->sourceParameter = (string) $sourceParameter;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return array('command.before_prepare' => array('onCommandBeforePrepare'));
}
/**
* Converts filenames and file handles into EntityBody objects before the command is validated
*
* @param Event $event Event emitted
* @throws InvalidArgumentException
*/
public function onCommandBeforePrepare(Event $event)
{
/** @var Command $command */
$command = $event['command'];
if (in_array($command->getName(), $this->commands)) {
// Get the interesting parameters
$source = $command->get($this->sourceParameter);
$body = $command->get($this->bodyParameter);
// If a file path is passed in then get the file handle
if (is_string($source) && file_exists($source)) {
$body = fopen($source, 'r');
}
// Prepare the body parameter and remove the source file parameter
if (null !== $body) {
$command->remove($this->sourceParameter);
$command->set($this->bodyParameter, EntityBody::factory($body));
} else {
throw new InvalidArgumentException(esc_html("You must specify a non-null value for the {$this->bodyParameter} or {$this->sourceParameter} parameters."));
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Client/DefaultClient.php 0000644 00000006706 15132770567 0021256 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Client;
use Aws\Common\Enum\ClientOptions as Options;
use Guzzle\Common\Collection;
/**
* Generic client for interacting with an AWS service
*/
class DefaultClient extends AbstractClient
{
/**
* Factory method to create a default client using an array of configuration options.
*
* The following array keys and values are available options:
*
* Credential options ((`key`, `secret`, and optional `token`) OR `credentials` is required):
*
* - key: AWS Access Key ID
* - secret: AWS secret access key
* - credentials: You can optionally provide a custom `Aws\Common\Credentials\CredentialsInterface` object
* - token: Custom AWS security token to use with request authentication. Please note that not all services accept temporary credentials. See http://docs.aws.amazon.com/STS/latest/UsingSTS/UsingTokens.html
* - token.ttd: UNIX timestamp for when the custom credentials expire
* - credentials.cache.key: Optional custom cache key to use with the credentials
* - credentials.client: Pass this option to specify a custom `Guzzle\Http\ClientInterface` to use if your credentials require a HTTP request (e.g. RefreshableInstanceProfileCredentials)
*
* Region and endpoint options (Some services do not require a region while others do. Check the service specific user guide documentation for details):
*
* - region: Region name (e.g. 'us-east-1', 'us-west-1', 'us-west-2', 'eu-west-1', etc...)
* - scheme: URI Scheme of the base URL (e.g. 'https', 'http') used when endpoint is not supplied
* - endpoint: Allows you to specify a custom endpoint instead of building one from the region and scheme
*
* Generic client options:
*
* - signature: Overrides the signature used by the client. Clients will always choose an appropriate default signature. However, it can be useful to override this with a custom setting. This can be set to "v4", "v3https", "v2" or an instance of Aws\Common\Signature\SignatureInterface.
* - ssl.certificate_authority: Set to true to use the bundled CA cert or pass the full path to an SSL certificate bundle
* - curl.options: Associative of CURLOPT_* cURL options to add to each request
* - client.backoff.logger: `Guzzle\Log\LogAdapterInterface` object used to log backoff retries. Use 'debug' to emit PHP warnings when a retry is issued.
* - client.backoff.logger.template: Optional template to use for exponential backoff log messages. See `Guzzle\Plugin\Backoff\BackoffLogger` for formatting information.
*
* @param array|Collection $config Client configuration data
*
* @return self
*/
public static function factory($config = array())
{
return ClientBuilder::factory()
->setConfig($config)
->setConfigDefaults(array(Options::SCHEME => 'https'))
->build();
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Client/ExpiredCredentialsChecker.php 0000644 00000005224 15132770567 0023570 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Client;
use Aws\Common\Credentials\AbstractRefreshableCredentials;
use Aws\Common\Client\AwsClientInterface;
use Aws\Common\Exception\Parser\ExceptionParserInterface;
use Guzzle\Http\Exception\HttpException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Backoff\BackoffStrategyInterface;
use Guzzle\Plugin\Backoff\AbstractBackoffStrategy;
/**
* Backoff logic that handles retrying requests when credentials expire
*/
class ExpiredCredentialsChecker extends AbstractBackoffStrategy
{
/**
* @var array Array of known retrying exception codes
*/
protected $retryable = array(
'RequestExpired' => true,
'ExpiredTokenException' => true,
'ExpiredToken' => true
);
/**
* @var ExceptionParserInterface Exception parser used to parse exception responses
*/
protected $exceptionParser;
public function __construct(ExceptionParserInterface $exceptionParser, BackoffStrategyInterface $next = null) {
$this->exceptionParser = $exceptionParser;
$this->next = $next;
}
public function makesDecision()
{
return true;
}
protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null)
{
if ($response && $response->isClientError()) {
$parts = $this->exceptionParser->parse($request, $response);
if (!isset($this->retryable[$parts['code']]) || !$request->getClient()) {
return null;
}
/** @var AwsClientInterface $client */
$client = $request->getClient();
// Only retry if the credentials can be refreshed
if (!($client->getCredentials() instanceof AbstractRefreshableCredentials)) {
return null;
}
// Resign the request using new credentials
$client->getSignature()->signRequest($request, $client->getCredentials()->setExpiration(-1));
// Retry immediately with no delay
return 0;
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Signature/SignatureListener.php 0000644 00000005033 15132770567 0022715 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Signature;
use Aws\Common\Credentials\AbstractRefreshableCredentials;
use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Credentials\NullCredentials;
use Guzzle\Common\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Listener used to sign requests before they are sent over the wire
*/
class SignatureListener implements EventSubscriberInterface
{
/**
* @var CredentialsInterface
*/
protected $credentials;
/**
* @var SignatureInterface
*/
protected $signature;
/**
* Construct a new request signing plugin
*
* @param CredentialsInterface $credentials Credentials used to sign requests
* @param SignatureInterface $signature Signature implementation
*/
public function __construct(CredentialsInterface $credentials, SignatureInterface $signature)
{
$this->credentials = $credentials;
$this->signature = $signature;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return array(
'request.before_send' => array('onRequestBeforeSend', -255),
'client.credentials_changed' => array('onCredentialsChanged')
);
}
/**
* Updates the listener with new credentials if the client is updated
*
* @param Event $event Event emitted
*/
public function onCredentialsChanged(Event $event)
{
$this->credentials = $event['credentials'];
}
/**
* Signs requests before they are sent
*
* @param Event $event Event emitted
*/
public function onRequestBeforeSend(Event $event)
{
$creds = $this->credentials instanceof AbstractRefreshableCredentials
? $this->credentials->getCredentials()
: $this->credentials;
if(!$creds instanceof NullCredentials) {
$this->signature->signRequest($event['request'], $creds);
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Signature/SignatureV4.php 0000644 00000037546 15132770567 0021437 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Signature;
use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Enum\DateFormat;
use Aws\Common\HostNameUtils;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\RequestFactory;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\QueryString;
use Guzzle\Http\Url;
use Guzzle\Stream\Stream;
/**
* Signature Version 4
* @link http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
*/
class SignatureV4 extends AbstractSignature implements EndpointSignatureInterface
{
/** @var string Cache of the default empty entity-body payload */
const DEFAULT_PAYLOAD = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
/** @var string Explicitly set service name */
protected $serviceName;
/** @var string Explicitly set region name */
protected $regionName;
/** @var int Maximum number of hashes to cache */
protected $maxCacheSize = 50;
/** @var array Cache of previously signed values */
protected $hashCache = array();
/** @var int Size of the hash cache */
protected $cacheSize = 0;
/**
* @param string $serviceName Bind the signing to a particular service name
* @param string $regionName Bind the signing to a particular region name
*/
public function __construct($serviceName = null, $regionName = null)
{
$this->serviceName = $serviceName;
$this->regionName = $regionName;
}
/**
* Set the service name instead of inferring it from a request URL
*
* @param string $service Name of the service used when signing
*
* @return self
*/
public function setServiceName($service)
{
$this->serviceName = $service;
return $this;
}
/**
* Set the region name instead of inferring it from a request URL
*
* @param string $region Name of the region used when signing
*
* @return self
*/
public function setRegionName($region)
{
$this->regionName = $region;
return $this;
}
/**
* Set the maximum number of computed hashes to cache
*
* @param int $maxCacheSize Maximum number of hashes to cache
*
* @return self
*/
public function setMaxCacheSize($maxCacheSize)
{
$this->maxCacheSize = $maxCacheSize;
return $this;
}
public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
{
$timestamp = $this->getTimestamp();
$longDate = gmdate(DateFormat::ISO8601, $timestamp);
$shortDate = substr($longDate, 0, 8);
// Remove any previously set Authorization headers so that retries work
$request->removeHeader('Authorization');
// Requires a x-amz-date header or Date
if ($request->hasHeader('x-amz-date') || !$request->hasHeader('Date')) {
$request->setHeader('x-amz-date', $longDate);
} else {
$request->setHeader('Date', gmdate(DateFormat::RFC1123, $timestamp));
}
// Add the security token if one is present
if ($credentials->getSecurityToken()) {
$request->setHeader('x-amz-security-token', $credentials->getSecurityToken());
}
// Parse the service and region or use one that is explicitly set
$region = $this->regionName;
$service = $this->serviceName;
if (!$region || !$service) {
$url = Url::factory($request->getUrl());
$region = $region ?: HostNameUtils::parseRegionName($url);
$service = $service ?: HostNameUtils::parseServiceName($url);
}
$credentialScope = $this->createScope($shortDate, $region, $service);
$payload = $this->getPayload($request);
$signingContext = $this->createSigningContext($request, $payload);
$signingContext['string_to_sign'] = $this->createStringToSign(
$longDate,
$credentialScope,
$signingContext['canonical_request']
);
// Calculate the signing key using a series of derived keys
$signingKey = $this->getSigningKey($shortDate, $region, $service, $credentials->getSecretKey());
$signature = hash_hmac('sha256', $signingContext['string_to_sign'], $signingKey);
$request->setHeader('Authorization', "AWS4-HMAC-SHA256 "
. "Credential={$credentials->getAccessKeyId()}/{$credentialScope}, "
. "SignedHeaders={$signingContext['signed_headers']}, Signature={$signature}");
// Add debug information to the request
$request->getParams()->set('aws.signature', $signingContext);
}
public function createPresignedUrl(
RequestInterface $request,
CredentialsInterface $credentials,
$expires
) {
$request = $this->createPresignedRequest($request, $credentials);
$query = $request->getQuery();
$httpDate = gmdate(DateFormat::ISO8601, $this->getTimestamp());
$shortDate = substr($httpDate, 0, 8);
$scope = $this->createScope(
$shortDate,
$this->regionName,
$this->serviceName
);
$this->addQueryValues($scope, $request, $credentials, $expires);
$payload = $this->getPresignedPayload($request);
$context = $this->createSigningContext($request, $payload);
$stringToSign = $this->createStringToSign(
$httpDate,
$scope,
$context['canonical_request']
);
$key = $this->getSigningKey(
$shortDate,
$this->regionName,
$this->serviceName,
$credentials->getSecretKey()
);
$query['X-Amz-Signature'] = hash_hmac('sha256', $stringToSign, $key);
return $request->getUrl();
}
/**
* Converts a POST request to a GET request by moving POST fields into the
* query string.
*
* Useful for pre-signing query protocol requests.
*
* @param EntityEnclosingRequestInterface $request Request to clone
*
* @return RequestInterface
* @throws \InvalidArgumentException if the method is not POST
*/
public static function convertPostToGet(EntityEnclosingRequestInterface $request)
{
if ($request->getMethod() !== 'POST') {
throw new \InvalidArgumentException('Expected a POST request but '
. 'received a ' . esc_html($request->getMethod()) . ' request.');
}
$cloned = RequestFactory::getInstance()
->cloneRequestWithMethod($request, 'GET');
// Move POST fields to the query if they are present
foreach ($request->getPostFields() as $name => $value) {
$cloned->getQuery()->set($name, $value);
}
return $cloned;
}
/**
* Get the payload part of a signature from a request.
*
* @param RequestInterface $request
*
* @return string
*/
protected function getPayload(RequestInterface $request)
{
// Calculate the request signature payload
if ($request->hasHeader('x-amz-content-sha256')) {
// Handle streaming operations (e.g. Glacier.UploadArchive)
return (string) $request->getHeader('x-amz-content-sha256');
}
if ($request instanceof EntityEnclosingRequestInterface) {
if ($request->getMethod() == 'POST' && count($request->getPostFields())) {
return hash('sha256', (string) $request->getPostFields());
} elseif ($body = $request->getBody()) {
return Stream::getHash($request->getBody(), 'sha256');
}
}
return self::DEFAULT_PAYLOAD;
}
/**
* Get the payload of a request for use with pre-signed URLs.
*
* @param RequestInterface $request
*
* @return string
*/
protected function getPresignedPayload(RequestInterface $request)
{
return $this->getPayload($request);
}
protected function createCanonicalizedPath(RequestInterface $request)
{
$doubleEncoded = rawurlencode(ltrim($request->getPath(), '/'));
return '/' . str_replace('%2F', '/', $doubleEncoded);
}
private function createStringToSign($longDate, $credentialScope, $creq)
{
return "AWS4-HMAC-SHA256\n{$longDate}\n{$credentialScope}\n"
. hash('sha256', $creq);
}
private function createPresignedRequest(
RequestInterface $request,
CredentialsInterface $credentials
) {
// POST requests can be sent as GET requests instead by moving the
// POST fields into the query string.
if ($request instanceof EntityEnclosingRequestInterface
&& $request->getMethod() === 'POST'
&& strpos($request->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === 0
) {
$sr = RequestFactory::getInstance()
->cloneRequestWithMethod($request, 'GET');
// Move POST fields to the query if they are present
foreach ($request->getPostFields() as $name => $value) {
$sr->getQuery()->set($name, $value);
}
} else {
$sr = clone $request;
}
// Make sure to handle temporary credentials
if ($token = $credentials->getSecurityToken()) {
$sr->setHeader('X-Amz-Security-Token', $token);
$sr->getQuery()->set('X-Amz-Security-Token', $token);
}
$this->moveHeadersToQuery($sr);
return $sr;
}
/**
* Create the canonical representation of a request
*
* @param RequestInterface $request Request to canonicalize
* @param string $payload Request payload (typically the value
* of the x-amz-content-sha256 header.
*
* @return array Returns an array of context information including:
* - canonical_request
* - signed_headers
*/
private function createSigningContext(RequestInterface $request, $payload)
{
$signable = array(
'host' => true,
'date' => true,
'content-md5' => true
);
// Normalize the path as required by SigV4 and ensure it's absolute
$canon = $request->getMethod() . "\n"
. $this->createCanonicalizedPath($request) . "\n"
. $this->getCanonicalizedQueryString($request) . "\n";
$canonHeaders = array();
foreach ($request->getHeaders()->getAll() as $key => $values) {
$key = strtolower($key);
if (isset($signable[$key]) || substr($key, 0, 6) === 'x-amz-') {
$values = $values->toArray();
if (count($values) == 1) {
$values = $values[0];
} else {
sort($values);
$values = implode(',', $values);
}
$canonHeaders[$key] = $key . ':' . preg_replace('/\s+/', ' ', $values);
}
}
ksort($canonHeaders);
$signedHeadersString = implode(';', array_keys($canonHeaders));
$canon .= implode("\n", $canonHeaders) . "\n\n"
. $signedHeadersString . "\n"
. $payload;
return array(
'canonical_request' => $canon,
'signed_headers' => $signedHeadersString
);
}
/**
* Get a hash for a specific key and value. If the hash was previously
* cached, return it
*
* @param string $shortDate Short date
* @param string $region Region name
* @param string $service Service name
* @param string $secretKey Secret Access Key
*
* @return string
*/
private function getSigningKey($shortDate, $region, $service, $secretKey)
{
$cacheKey = $shortDate . '_' . $region . '_' . $service . '_' . $secretKey;
// Retrieve the hash form the cache or create it and add it to the cache
if (!isset($this->hashCache[$cacheKey])) {
// When the cache size reaches the max, then just clear the cache
if (++$this->cacheSize > $this->maxCacheSize) {
$this->hashCache = array();
$this->cacheSize = 0;
}
$dateKey = hash_hmac('sha256', $shortDate, 'AWS4' . $secretKey, true);
$regionKey = hash_hmac('sha256', $region, $dateKey, true);
$serviceKey = hash_hmac('sha256', $service, $regionKey, true);
$this->hashCache[$cacheKey] = hash_hmac('sha256', 'aws4_request', $serviceKey, true);
}
return $this->hashCache[$cacheKey];
}
/**
* Get the canonicalized query string for a request
*
* @param RequestInterface $request
* @return string
*/
private function getCanonicalizedQueryString(RequestInterface $request)
{
$queryParams = $request->getQuery()->getAll();
unset($queryParams['X-Amz-Signature']);
if (empty($queryParams)) {
return '';
}
$qs = '';
ksort($queryParams);
foreach ($queryParams as $key => $values) {
if (is_array($values)) {
sort($values);
} elseif ($values === 0) {
$values = array('0');
} elseif (!$values) {
$values = array('');
}
foreach ((array) $values as $value) {
if ($value === QueryString::BLANK) {
$value = '';
}
$qs .= rawurlencode($key) . '=' . rawurlencode($value) . '&';
}
}
return substr($qs, 0, -1);
}
private function convertExpires($expires)
{
if ($expires instanceof \DateTime) {
$expires = $expires->getTimestamp();
} elseif (!is_numeric($expires)) {
$expires = strtotime($expires);
}
$duration = $expires - time();
// Ensure that the duration of the signature is not longer than a week
if ($duration > 604800) {
throw new \InvalidArgumentException('The expiration date of a '
. 'signature version 4 presigned URL must be less than one '
. 'week');
}
return $duration;
}
private function createScope($shortDate, $region, $service)
{
return $shortDate
. '/' . $region
. '/' . $service
. '/aws4_request';
}
private function addQueryValues(
$scope,
RequestInterface $request,
CredentialsInterface $credentials,
$expires
) {
$credential = $credentials->getAccessKeyId() . '/' . $scope;
// Set query params required for pre-signed URLs
$request->getQuery()
->set('X-Amz-Algorithm', 'AWS4-HMAC-SHA256')
->set('X-Amz-Credential', $credential)
->set('X-Amz-Date', gmdate('Ymd\THis\Z', $this->getTimestamp()))
->set('X-Amz-SignedHeaders', 'Host')
->set('X-Amz-Expires', $this->convertExpires($expires));
}
private function moveHeadersToQuery(RequestInterface $request)
{
$query = $request->getQuery();
foreach ($request->getHeaders() as $name => $header) {
if (substr($name, 0, 5) == 'x-amz') {
$query[$header->getName()] = (string) $header;
}
if ($name !== 'host') {
$request->removeHeader($name);
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Signature/SignatureV3Https.php 0000644 00000004101 15132770567 0022436 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Signature;
use Aws\Common\Credentials\CredentialsInterface;
use Aws\Common\Enum\DateFormat;
use Guzzle\Http\Message\RequestInterface;
/**
* Implementation of Signature Version 3 HTTPS
* @link http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/RESTAuthentication.html
*/
class SignatureV3Https extends AbstractSignature
{
public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
{
// Add a date header if one is not set
if (!$request->hasHeader('date') && !$request->hasHeader('x-amz-date')) {
$request->setHeader('Date', gmdate(DateFormat::RFC1123, $this->getTimestamp()));
}
// Add the security token if one is present
if ($credentials->getSecurityToken()) {
$request->setHeader('x-amz-security-token', $credentials->getSecurityToken());
}
// Determine the string to sign
$stringToSign = (string) ($request->getHeader('Date') ?: $request->getHeader('x-amz-date'));
$request->getParams()->set('aws.string_to_sign', $stringToSign);
// Calculate the signature
$signature = base64_encode(hash_hmac('sha256', $stringToSign, $credentials->getSecretKey(), true));
// Add the authorization header to the request
$headerFormat = 'AWS3-HTTPS AWSAccessKeyId=%s,Algorithm=HmacSHA256,Signature=%s';
$request->setHeader('X-Amzn-Authorization', sprintf($headerFormat, $credentials->getAccessKeyId(), $signature));
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Signature/AbstractSignature.php 0000644 00000002352 15132770567 0022674 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Signature;
use Aws\Common\Credentials\CredentialsInterface;
use Guzzle\Http\Message\RequestInterface;
abstract class AbstractSignature implements SignatureInterface
{
/**
* Provides the timestamp used for the class (used for mocking PHP's time() function)
*
* @return int
*/
protected function getTimestamp()
{
return time();
}
/**
* @codeCoverageIgnore
*/
public function createPresignedUrl(
RequestInterface $request,
CredentialsInterface $credentials,
$expires
) {
throw new \BadMethodCallException(__METHOD__ . ' not implemented');
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Signature/EndpointSignatureInterface.php 0000644 00000002360 15132770567 0024531 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Signature;
/**
* Interface for signatures that use specific region and service names when
* signing requests.
*/
interface EndpointSignatureInterface extends SignatureInterface
{
/**
* Set the service name instead of inferring it from a request URL
*
* @param string $service Name of the service used when signing
*
* @return self
*/
public function setServiceName($service);
/**
* Set the region name instead of inferring it from a request URL
*
* @param string $region Name of the region used when signing
*
* @return self
*/
public function setRegionName($region);
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Signature/SignatureInterface.php 0000644 00000003552 15132770567 0023034 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Signature;
use Aws\Common\Credentials\CredentialsInterface;
use Guzzle\Http\Message\RequestInterface;
/**
* Interface used to provide interchangeable strategies for signing requests
* using the various AWS signature protocols.
*/
interface SignatureInterface
{
/**
* Signs the specified request with an AWS signing protocol by using the
* provided AWS account credentials and adding the required headers to the
* request.
*
* @param RequestInterface $request Request to add a signature to
* @param CredentialsInterface $credentials Signing credentials
*/
public function signRequest(RequestInterface $request, CredentialsInterface $credentials);
/**
* Create a pre-signed URL
*
* @param RequestInterface $request Request to sign
* @param CredentialsInterface $credentials Credentials used to sign
* @param int|string|\DateTime $expires The time at which the URL should expire. This can be a Unix timestamp, a
* PHP DateTime object, or a string that can be evaluated by strtotime
* @return string
*/
public function createPresignedUrl(
RequestInterface $request,
CredentialsInterface $credentials,
$expires
);
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Signature/SignatureV2.php 0000644 00000007065 15132770567 0021426 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Signature;
use Aws\Common\Credentials\CredentialsInterface;
use Guzzle\Http\Message\RequestInterface;
/**
* Implementation of Signature Version 2
* @link http://aws.amazon.com/articles/1928
*/
class SignatureV2 extends AbstractSignature
{
public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
{
// refresh the cached timestamp
$timestamp = $this->getTimestamp(true);
// set values we need in CanonicalizedParameterString
$this->addParameter($request, 'Timestamp', gmdate('c', $timestamp));
$this->addParameter($request, 'SignatureVersion', '2');
$this->addParameter($request, 'SignatureMethod', 'HmacSHA256');
$this->addParameter($request, 'AWSAccessKeyId', $credentials->getAccessKeyId());
if ($token = $credentials->getSecurityToken()) {
$this->addParameter($request, 'SecurityToken', $token);
}
// Get the path and ensure it's absolute
$path = '/' . ltrim($request->getUrl(true)->normalizePath()->getPath(), '/');
// build string to sign
$sign = $request->getMethod() . "\n"
. $request->getHost() . "\n"
. $path . "\n"
. $this->getCanonicalizedParameterString($request);
// Add the string to sign to the request for debugging purposes
$request->getParams()->set('aws.string_to_sign', $sign);
$signature = base64_encode(
hash_hmac(
'sha256',
$sign,
$credentials->getSecretKey(),
true
)
);
$this->addParameter($request, 'Signature', $signature);
}
/**
* Add a parameter key and value to the request according to type
*
* @param RequestInterface $request The request
* @param string $key The name of the parameter
* @param string $value The value of the parameter
*/
public function addParameter(RequestInterface $request, $key, $value)
{
if ($request->getMethod() == 'POST') {
$request->setPostField($key, $value);
} else {
$request->getQuery()->set($key, $value);
}
}
/**
* Get the canonicalized query/parameter string for a request
*
* @param RequestInterface $request Request used to build canonicalized string
*
* @return string
*/
private function getCanonicalizedParameterString(RequestInterface $request)
{
if ($request->getMethod() == 'POST') {
$params = $request->getPostFields()->toArray();
} else {
$params = $request->getQuery()->toArray();
}
// Don't resign a previous signature value
unset($params['Signature']);
uksort($params, 'strcmp');
$str = '';
foreach ($params as $key => $val) {
$str .= rawurlencode($key) . '=' . rawurlencode($val) . '&';
}
return substr($str, 0, -1);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Aws.php 0000644 00000007241 15132770567 0016042 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common;
use Aws\Common\Facade\Facade;
use Guzzle\Service\Builder\ServiceBuilder;
use Guzzle\Service\Builder\ServiceBuilderLoader;
/**
* Base class for interacting with web service clients
*/
class Aws extends ServiceBuilder
{
/**
* @var string Current version of the SDK
*/
const VERSION = '2.8.31';
/**
* Create a new service locator for the AWS SDK
*
* You can configure the service locator is four different ways:
*
* 1. Use the default configuration file shipped with the SDK that wires class names with service short names and
* specify global parameters to add to every definition (e.g. key, secret, credentials, etc)
*
* 2. Use a custom configuration file that extends the default config and supplies credentials for each service.
*
* 3. Use a custom config file that wires services to custom short names for services.
*
* 4. If you are on Amazon EC2, you can use the default configuration file and not provide any credentials so that
* you are using InstanceProfile credentials.
*
* @param array|string $config The full path to a .php or .js|.json file, or an associative array of data
* to use as global parameters to pass to each service.
* @param array $globalParameters Global parameters to pass to every service as it is instantiated.
*
* @return Aws
*/
public static function factory($config = null, array $globalParameters = array())
{
if (!$config) {
// If nothing is passed in, then use the default configuration file with credentials from the environment
$config = self::getDefaultServiceDefinition();
} elseif (is_array($config)) {
// If an array was passed, then use the default configuration file with parameter overrides
$globalParameters = $config;
$config = self::getDefaultServiceDefinition();
}
$loader = new ServiceBuilderLoader();
$loader->addAlias('_aws', self::getDefaultServiceDefinition())
->addAlias('_sdk1', __DIR__ . '/Resources/sdk1-config.php');
return $loader->load($config, $globalParameters);
}
/**
* Get the full path to the default service builder definition file
*
* @return string
*/
public static function getDefaultServiceDefinition()
{
return __DIR__ . '/Resources/aws-config.php';
}
/**
* Returns the configuration for the service builder
*
* @return array
*/
public function getConfig()
{
return $this->builderConfig;
}
/**
* Enables the facades for the clients defined in the service builder
*
* @param string|null $namespace The namespace that the facades should be mounted to. Defaults to global namespace
*
* @return Aws
* @deprecated "Facades" are being removed in version 3.0 of the SDK.
*/
public function enableFacades($namespace = null)
{
Facade::mountFacades($this, $namespace);
return $this;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Model/MultipartUpload/AbstractUploadPart.php 0000644 00000004753 15132770567 0025242 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Model\MultipartUpload;
use Aws\Common\Exception\InvalidArgumentException;
/**
* An object that encapsulates the data for an upload part
*/
abstract class AbstractUploadPart implements UploadPartInterface
{
/**
* @var array A map of external array keys to internal property names
*/
protected static $keyMap = array();
/**
* @var int The number of the upload part representing its order in the overall upload
*/
protected $partNumber;
/**
* {@inheritdoc}
*/
public static function fromArray($data)
{
$part = new static();
$part->loadData($data);
return $part;
}
/**
* {@inheritdoc}
*/
public function getPartNumber()
{
return $this->partNumber;
}
/**
* {@inheritdoc}
*/
public function toArray()
{
$array = array();
foreach (static::$keyMap as $key => $property) {
$array[$key] = $this->{$property};
}
return $array;
}
/**
* {@inheritdoc}
*/
public function serialize()
{
return serialize($this->toArray());
}
/**
* {@inheritdoc}
*/
public function unserialize($serialized)
{
$this->loadData(unserialize($serialized));
}
/**
* Loads an array of data into the upload part by extracting only the needed keys
*
* @param array|\Traversable $data Data to load into the upload part value object
*
* @throws InvalidArgumentException if a required key is missing
*/
protected function loadData($data)
{
foreach (static::$keyMap as $key => $property) {
if (isset($data[$key])) {
$this->{$property} = $data[$key];
} else {
throw new InvalidArgumentException(esc_html("A required key [$key] was missing from the upload part."));
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Model/MultipartUpload/AbstractUploadBuilder.php 0000644 00000010337 15132770567 0025715 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Model\MultipartUpload;
use Aws\Common\Client\AwsClientInterface;
use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Http\EntityBody;
/**
* Easily create a multipart uploader used to quickly and reliably upload a
* large file or data stream to Amazon S3 using multipart uploads
*/
abstract class AbstractUploadBuilder
{
/**
* @var AwsClientInterface Client used to transfer requests
*/
protected $client;
/**
* @var TransferStateInterface State of the transfer
*/
protected $state;
/**
* @var EntityBody Source of the data
*/
protected $source;
/**
* @var array Array of headers to set on the object
*/
protected $headers = array();
/**
* Return a new instance of the UploadBuilder
*
* @return static
*/
public static function newInstance()
{
return new static;
}
/**
* Set the client used to connect to the AWS service
*
* @param AwsClientInterface $client Client to use
*
* @return $this
*/
public function setClient(AwsClientInterface $client)
{
$this->client = $client;
return $this;
}
/**
* Set the state of the upload. This is useful for resuming from a previously started multipart upload.
* You must use a local file stream as the data source if you wish to resume from a previous upload.
*
* @param TransferStateInterface|string $state Pass a TransferStateInterface object or the ID of the initiated
* multipart upload. When an ID is passed, the builder will create a
* state object using the data from a ListParts API response.
*
* @return $this
*/
public function resumeFrom($state)
{
$this->state = $state;
return $this;
}
/**
* Set the data source of the transfer
*
* @param resource|string|EntityBody $source Source of the transfer. Pass a string to transfer from a file on disk.
* You can also stream from a resource returned from fopen or a Guzzle
* {@see EntityBody} object.
*
* @return $this
* @throws InvalidArgumentException when the source cannot be found or opened
*/
public function setSource($source)
{
// Use the contents of a file as the data source
if (is_string($source)) {
if (!file_exists($source)) {
throw new InvalidArgumentException(esc_html("File does not exist: {$source}"));
}
// Clear the cache so that we send accurate file sizes
clearstatcache(true, $source);
$source = fopen($source, 'r');
}
$this->source = EntityBody::factory($source);
if ($this->source->isSeekable() && $this->source->getSize() == 0) {
throw new InvalidArgumentException('Empty body provided to upload builder');
}
return $this;
}
/**
* Specify the headers to set on the upload
*
* @param array $headers Headers to add to the uploaded object
*
* @return $this
*/
public function setHeaders(array $headers)
{
$this->headers = $headers;
return $this;
}
/**
* Build the appropriate uploader based on the builder options
*
* @return TransferInterface
*/
abstract public function build();
/**
* Initiate the multipart upload
*
* @return TransferStateInterface
*/
abstract protected function initiateMultipartUpload();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Model/MultipartUpload/AbstractUploadId.php 0000644 00000004370 15132770567 0024663 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Model\MultipartUpload;
use Aws\Common\Exception\InvalidArgumentException;
/**
* An object that encapsulates the data identifying an upload
*/
abstract class AbstractUploadId implements UploadIdInterface
{
/**
* @var array Expected values (with defaults)
*/
protected static $expectedValues = array();
/**
* @var array Params representing the identifying information
*/
protected $data = array();
/**
* {@inheritdoc}
*/
public static function fromParams($data)
{
$uploadId = new static();
$uploadId->loadData($data);
return $uploadId;
}
/**
* {@inheritdoc}
*/
public function toParams()
{
return $this->data;
}
/**
* {@inheritdoc}
*/
public function serialize()
{
return serialize($this->data);
}
/**
* {@inheritdoc}
*/
public function unserialize($serialized)
{
$this->loadData(unserialize($serialized));
}
/**
* Loads an array of data into the UploadId by extracting only the needed keys
*
* @param array $data Data to load
*
* @throws InvalidArgumentException if a required key is missing
*/
protected function loadData($data)
{
$data = array_replace(static::$expectedValues, array_intersect_key($data, static::$expectedValues));
foreach ($data as $key => $value) {
if (isset($data[$key])) {
$this->data[$key] = $data[$key];
} else {
throw new InvalidArgumentException(esc_html("A required key [$key] was missing from the UploadId."));
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Model/MultipartUpload/TransferInterface.php 0000644 00000003517 15132770567 0025105 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Model\MultipartUpload;
use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Service\Resource\Model;
/**
* Interface for transferring the contents of a data source to an AWS service via a multipart upload interface
*/
interface TransferInterface extends HasDispatcherInterface
{
/**
* Upload the source to using a multipart upload
*
* @return Model|null Result of the complete multipart upload command or null if uploading was stopped
*/
public function upload();
/**
* Abort the upload
*
* @return Model Returns the result of the abort multipart upload command
*/
public function abort();
/**
* Get the current state of the upload
*
* @return TransferStateInterface
*/
public function getState();
/**
* Stop the transfer and retrieve the current state.
*
* This allows you to stop and later resume a long running transfer if needed.
*
* @return TransferStateInterface
*/
public function stop();
/**
* Set an option on the transfer object
*
* @param string $option Option to set
* @param mixed $value The value to set
*
* @return self
*/
public function setOption($option, $value);
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Model/MultipartUpload/UploadIdInterface.php 0000644 00000002151 15132770567 0025013 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Model\MultipartUpload;
/**
* An object that encapsulates the data identifying an upload
*/
interface UploadIdInterface extends \Serializable
{
/**
* Create an UploadId from an array
*
* @param array $data Data representing the upload identification
*
* @return self
*/
public static function fromParams($data);
/**
* Returns the array form of the upload identification for use as command params
*
* @return array
*/
public function toParams();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Model/MultipartUpload/UploadPartInterface.php 0000644 00000002351 15132770567 0025367 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Model\MultipartUpload;
/**
* An object that encapsulates the data for an upload part
*/
interface UploadPartInterface extends \Serializable
{
/**
* Create an upload part from an array
*
* @param array|\Traversable $data Data representing the upload part
*
* @return self
*/
public static function fromArray($data);
/**
* Returns the part number of the upload part which is used as an identifier
*
* @return int
*/
public function getPartNumber();
/**
* Returns the array form of the upload part
*
* @return array
*/
public function toArray();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Model/MultipartUpload/TransferStateInterface.php 0000644 00000004607 15132770567 0026107 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Model\MultipartUpload;
use Aws\Common\Client\AwsClientInterface;
/**
* State of a multipart upload
*/
interface TransferStateInterface extends \Countable, \IteratorAggregate, \Serializable
{
/**
* Create the transfer state from the results of list parts request
*
* @param AwsClientInterface $client Client used to send the request
* @param UploadIdInterface $uploadId Params needed to identify the upload and form the request
*
* @return self
*/
public static function fromUploadId(AwsClientInterface $client, UploadIdInterface $uploadId);
/**
* Get the params used to identify an upload part
*
* @return UploadIdInterface
*/
public function getUploadId();
/**
* Get the part information of a specific part
*
* @param int $partNumber Part to retrieve
*
* @return UploadPartInterface
*/
public function getPart($partNumber);
/**
* Add a part to the transfer state
*
* @param UploadPartInterface $part The part to add
*
* @return self
*/
public function addPart(UploadPartInterface $part);
/**
* Check if a specific part has been uploaded
*
* @param int $partNumber Part to check
*
* @return bool
*/
public function hasPart($partNumber);
/**
* Get a list of all of the uploaded part numbers
*
* @return array
*/
public function getPartNumbers();
/**
* Set whether or not the transfer has been aborted
*
* @param bool $aborted Set to true to mark the transfer as aborted
*
* @return self
*/
public function setAborted($aborted);
/**
* Check if the transfer has been marked as aborted
*
* @return bool
*/
public function isAborted();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Model/MultipartUpload/AbstractTransfer.php 0000644 00000015521 15132770567 0024746 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Model\MultipartUpload;
use Aws\Common\Client\AwsClientInterface;
use Aws\Common\Exception\MultipartUploadException;
use Aws\Common\Exception\RuntimeException;
use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Http\EntityBody;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Service\Command\OperationCommand;
use Guzzle\Service\Resource\Model;
/**
* Abstract class for transfer commonalities
*/
abstract class AbstractTransfer extends AbstractHasDispatcher implements TransferInterface
{
const BEFORE_UPLOAD = 'multipart_upload.before_upload';
const AFTER_UPLOAD = 'multipart_upload.after_upload';
const BEFORE_PART_UPLOAD = 'multipart_upload.before_part_upload';
const AFTER_PART_UPLOAD = 'multipart_upload.after_part_upload';
const AFTER_ABORT = 'multipart_upload.after_abort';
const AFTER_COMPLETE = 'multipart_upload.after_complete';
/**
* @var AwsClientInterface Client used for the transfers
*/
protected $client;
/**
* @var TransferStateInterface State of the transfer
*/
protected $state;
/**
* @var EntityBody Data source of the transfer
*/
protected $source;
/**
* @var array Associative array of options
*/
protected $options;
/**
* @var int Size of each part to upload
*/
protected $partSize;
/**
* @var bool Whether or not the transfer has been stopped
*/
protected $stopped = false;
/**
* Construct a new transfer object
*
* @param AwsClientInterface $client Client used for the transfers
* @param TransferStateInterface $state State used to track transfer
* @param EntityBody $source Data source of the transfer
* @param array $options Array of options to apply
*/
public function __construct(
AwsClientInterface $client,
TransferStateInterface $state,
EntityBody $source,
array $options = array()
) {
$this->client = $client;
$this->state = $state;
$this->source = $source;
$this->options = $options;
$this->init();
$this->partSize = $this->calculatePartSize();
}
public function __invoke()
{
return $this->upload();
}
/**
* {@inheritdoc}
*/
public static function getAllEvents()
{
return array(
self::BEFORE_PART_UPLOAD,
self::AFTER_UPLOAD,
self::BEFORE_PART_UPLOAD,
self::AFTER_PART_UPLOAD,
self::AFTER_ABORT,
self::AFTER_COMPLETE
);
}
/**
* {@inheritdoc}
*/
public function abort()
{
$command = $this->getAbortCommand();
$result = $command->getResult();
$this->state->setAborted(true);
$this->stop();
$this->dispatch(self::AFTER_ABORT, $this->getEventData($command));
return $result;
}
/**
* {@inheritdoc}
*/
public function stop()
{
$this->stopped = true;
return $this->state;
}
/**
* {@inheritdoc}
*/
public function getState()
{
return $this->state;
}
/**
* Get the array of options associated with the transfer
*
* @return array
*/
public function getOptions()
{
return $this->options;
}
/**
* Set an option on the transfer
*
* @param string $option Name of the option
* @param mixed $value Value to set
*
* @return self
*/
public function setOption($option, $value)
{
$this->options[$option] = $value;
return $this;
}
/**
* Get the source body of the upload
*
* @return EntityBodyInterface
*/
public function getSource()
{
return $this->source;
}
/**
* {@inheritdoc}
* @throws MultipartUploadException when an error is encountered. Use getLastException() to get more information.
* @throws RuntimeException when attempting to upload an aborted transfer
*/
public function upload()
{
if ($this->state->isAborted()) {
throw new RuntimeException('The transfer has been aborted and cannot be uploaded');
}
$this->stopped = false;
$eventData = $this->getEventData();
$this->dispatch(self::BEFORE_UPLOAD, $eventData);
try {
$this->transfer();
$this->dispatch(self::AFTER_UPLOAD, $eventData);
if ($this->stopped) {
return null;
} else {
$result = $this->complete();
$this->dispatch(self::AFTER_COMPLETE, $eventData);
}
} catch (\Exception $e) {
throw new MultipartUploadException(esc_attr($this->state), esc_attr($e));
}
return $result;
}
/**
* Get an array used for event notifications
*
* @param OperationCommand $command Command to include in event data
*
* @return array
*/
protected function getEventData(OperationCommand $command = null)
{
$data = array(
'transfer' => $this,
'source' => $this->source,
'options' => $this->options,
'client' => $this->client,
'part_size' => $this->partSize,
'state' => $this->state
);
if ($command) {
$data['command'] = $command;
}
return $data;
}
/**
* Hook to initialize the transfer
*/
protected function init() {}
/**
* Determine the upload part size based on the size of the source data and
* taking into account the acceptable minimum and maximum part sizes.
*
* @return int The part size
*/
abstract protected function calculatePartSize();
/**
* Complete the multipart upload
*
* @return Model Returns the result of the complete multipart upload command
*/
abstract protected function complete();
/**
* Hook to implement in subclasses to perform the actual transfer
*/
abstract protected function transfer();
/**
* Fetches the abort command fom the concrete implementation
*
* @return OperationCommand
*/
abstract protected function getAbortCommand();
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Model/MultipartUpload/AbstractTransferState.php 0000644 00000007077 15132770567 0025756 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Model\MultipartUpload;
use Aws\Common\Exception\RuntimeException;
/**
* State of a multipart upload
*/
abstract class AbstractTransferState implements TransferStateInterface
{
/**
* @var UploadIdInterface Object holding params used to identity the upload part
*/
protected $uploadId;
/**
* @var array Array of parts where the part number is the index
*/
protected $parts = array();
/**
* @var bool Whether or not the transfer was aborted
*/
protected $aborted = false;
/**
* Construct a new transfer state object
*
* @param UploadIdInterface $uploadId Upload identifier object
*/
public function __construct(UploadIdInterface $uploadId)
{
$this->uploadId = $uploadId;
}
/**
* {@inheritdoc}
*/
public function getUploadId()
{
return $this->uploadId;
}
/**
* Get a data value from the transfer state's uploadId
*
* @param string $key Key to retrieve (e.g. Bucket, Key, UploadId, etc)
*
* @return string|null
*/
public function getFromId($key)
{
$params = $this->uploadId->toParams();
return isset($params[$key]) ? $params[$key] : null;
}
/**
* {@inheritdoc}
*/
public function getPart($partNumber)
{
return isset($this->parts[$partNumber]) ? $this->parts[$partNumber] : null;
}
/**
* {@inheritdoc}
*/
public function addPart(UploadPartInterface $part)
{
$partNumber = $part->getPartNumber();
$this->parts[$partNumber] = $part;
return $this;
}
/**
* {@inheritdoc}
*/
public function hasPart($partNumber)
{
return isset($this->parts[$partNumber]);
}
/**
* {@inheritdoc}
*/
public function getPartNumbers()
{
return array_keys($this->parts);
}
/**
* {@inheritdoc}
*/
public function setAborted($aborted)
{
$this->aborted = (bool) $aborted;
return $this;
}
/**
* {@inheritdoc}
*/
public function isAborted()
{
return $this->aborted;
}
/**
* {@inheritdoc}
*/
public function count()
{
return count($this->parts);
}
/**
* {@inheritdoc}
*/
public function getIterator()
{
return new \ArrayIterator($this->parts);
}
/**
* {@inheritdoc}
*/
public function serialize()
{
return serialize(get_object_vars($this));
}
/**
* {@inheritdoc}
*/
public function unserialize($serialized)
{
$data = unserialize($serialized);
foreach (get_object_vars($this) as $property => $oldValue) {
if (array_key_exists($property, $data)) {
$this->{$property} = $data[$property];
} else {
throw new RuntimeException(esc_html("The {$property} property could be restored during unserialization."));
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Resources/sdk1-config.php 0000644 00000007050 15132770567 0021365 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
return array(
'includes' => array('_aws'),
'services' => array(
'sdk1_settings' => array(
'extends' => 'default_settings',
'params' => array(
'certificate_authority' => false
)
),
'v1.autoscaling' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonAS'
),
'v1.cloudformation' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonCloudFormation'
),
'v1.cloudfront' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonCloudFront'
),
'v1.cloudsearch' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonCloudSearch'
),
'v1.cloudwatch' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonCloudWatch'
),
'v1.dynamodb' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonDynamoDB'
),
'v1.ec2' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonEC2'
),
'v1.elasticache' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonElastiCache'
),
'v1.elasticbeanstalk' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonElasticBeanstalk'
),
'v1.elb' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonELB'
),
'v1.emr' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonEMR'
),
'v1.iam' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonIAM'
),
'v1.importexport' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonImportExport'
),
'v1.rds' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonRDS'
),
'v1.s3' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonS3'
),
'v1.sdb' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonSDB'
),
'v1.ses' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonSES'
),
'v1.sns' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonSNS'
),
'v1.sqs' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonSQS'
),
'v1.storagegateway' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonStorageGateway'
),
'v1.sts' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonSTS'
),
'v1.swf' => array(
'extends' => 'sdk1_settings',
'class' => 'AmazonSWF'
)
)
);
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Resources/public-endpoints.php 0000644 00000004612 15132770567 0022540 0 ustar 00 <?php
return array(
'version' => 2,
'endpoints' => array(
'*/*' => array(
'endpoint' => '{service}.{region}.amazonaws.com'
),
'cn-north-1/*' => array(
'endpoint' => '{service}.{region}.amazonaws.com.cn',
'signatureVersion' => 'v4'
),
'us-gov-west-1/iam' => array(
'endpoint' => 'iam.us-gov.amazonaws.com'
),
'us-gov-west-1/sts' => array(
'endpoint' => 'sts.us-gov-west-1.amazonaws.com'
),
'us-gov-west-1/s3' => array(
'endpoint' => 's3-{region}.amazonaws.com'
),
'*/cloudfront' => array(
'endpoint' => 'cloudfront.amazonaws.com',
'credentialScope' => array(
'region' => 'us-east-1'
)
),
'*/iam' => array(
'endpoint' => 'iam.amazonaws.com',
'credentialScope' => array(
'region' => 'us-east-1'
)
),
'*/importexport' => array(
'endpoint' => 'importexport.amazonaws.com',
'credentialScope' => array(
'region' => 'us-east-1'
)
),
'*/route53' => array(
'endpoint' => 'route53.amazonaws.com',
'credentialScope' => array(
'region' => 'us-east-1'
)
),
'*/sts' => array(
'endpoint' => 'sts.amazonaws.com',
'credentialScope' => array(
'region' => 'us-east-1'
)
),
'us-east-1/sdb' => array(
'endpoint' => 'sdb.amazonaws.com'
),
'us-east-1/s3' => array(
'endpoint' => 's3.amazonaws.com'
),
'us-west-1/s3' => array(
'endpoint' => 's3-{region}.amazonaws.com'
),
'us-west-2/s3' => array(
'endpoint' => 's3-{region}.amazonaws.com'
),
'eu-west-1/s3' => array(
'endpoint' => 's3-{region}.amazonaws.com'
),
'ap-southeast-1/s3' => array(
'endpoint' => 's3-{region}.amazonaws.com'
),
'ap-southeast-2/s3' => array(
'endpoint' => 's3-{region}.amazonaws.com'
),
'ap-northeast-1/s3' => array(
'endpoint' => 's3-{region}.amazonaws.com'
),
'sa-east-1/s3' => array(
'endpoint' => 's3-{region}.amazonaws.com'
)
)
);
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Resources/aws-config.php 0000644 00000025222 15132770567 0021316 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
return array(
'class' => 'Aws\Common\Aws',
'services' => array(
'default_settings' => array(
'params' => array()
),
'autoscaling' => array(
'alias' => 'AutoScaling',
'extends' => 'default_settings',
'class' => 'Aws\AutoScaling\AutoScalingClient'
),
'cloudformation' => array(
'alias' => 'CloudFormation',
'extends' => 'default_settings',
'class' => 'Aws\CloudFormation\CloudFormationClient'
),
'cloudfront' => array(
'alias' => 'CloudFront',
'extends' => 'default_settings',
'class' => 'Aws\CloudFront\CloudFrontClient'
),
'cloudfront_20120505' => array(
'extends' => 'cloudfront',
'params' => array(
'version' => '2012-05-05'
)
),
'cloudhsm' => array(
'alias' => 'CloudHsm',
'extends' => 'default_settings',
'class' => 'Aws\CloudHsm\CloudHsmClient'
),
'cloudsearch' => array(
'alias' => 'CloudSearch',
'extends' => 'default_settings',
'class' => 'Aws\CloudSearch\CloudSearchClient'
),
'cloudsearch_20110201' => array(
'extends' => 'cloudsearch',
'params' => array(
'version' => '2011-02-01'
)
),
'cloudsearchdomain' => array(
'alias' => 'CloudSearchDomain',
'extends' => 'default_settings',
'class' => 'Aws\CloudSearchDomain\CloudSearchDomainClient'
),
'cloudtrail' => array(
'alias' => 'CloudTrail',
'extends' => 'default_settings',
'class' => 'Aws\CloudTrail\CloudTrailClient'
),
'cloudwatch' => array(
'alias' => 'CloudWatch',
'extends' => 'default_settings',
'class' => 'Aws\CloudWatch\CloudWatchClient'
),
'cloudwatchlogs' => array(
'alias' => 'CloudWatchLogs',
'extends' => 'default_settings',
'class' => 'Aws\CloudWatchLogs\CloudWatchLogsClient'
),
'cognito-identity' => array(
'alias' => 'CognitoIdentity',
'extends' => 'default_settings',
'class' => 'Aws\CognitoIdentity\CognitoIdentityClient'
),
'cognitoidentity' => array('extends' => 'cognito-identity'),
'cognito-sync' => array(
'alias' => 'CognitoSync',
'extends' => 'default_settings',
'class' => 'Aws\CognitoSync\CognitoSyncClient'
),
'cognitosync' => array('extends' => 'cognito-sync'),
'codecommit' => array(
'alias' => 'CodeCommit',
'extends' => 'default_settings',
'class' => 'Aws\CodeCommit\CodeCommitClient'
),
'codedeploy' => array(
'alias' => 'CodeDeploy',
'extends' => 'default_settings',
'class' => 'Aws\CodeDeploy\CodeDeployClient'
),
'codepipeline' => array(
'alias' => 'CodePipeline',
'extends' => 'default_settings',
'class' => 'Aws\CodePipeline\CodePipelineClient'
),
'config' => array(
'alias' => 'ConfigService',
'extends' => 'default_settings',
'class' => 'Aws\ConfigService\ConfigServiceClient'
),
'datapipeline' => array(
'alias' => 'DataPipeline',
'extends' => 'default_settings',
'class' => 'Aws\DataPipeline\DataPipelineClient'
),
'devicefarm' => array(
'alias' => 'DeviceFarm',
'extends' => 'default_settings',
'class' => 'Aws\DeviceFarm\DeviceFarmClient'
),
'directconnect' => array(
'alias' => 'DirectConnect',
'extends' => 'default_settings',
'class' => 'Aws\DirectConnect\DirectConnectClient'
),
'ds' => array(
'alias' => 'DirectoryService',
'extends' => 'default_settings',
'class' => 'Aws\DirectoryService\DirectoryServiceClient'
),
'dynamodb' => array(
'alias' => 'DynamoDb',
'extends' => 'default_settings',
'class' => 'Aws\DynamoDb\DynamoDbClient'
),
'dynamodb_20111205' => array(
'extends' => 'dynamodb',
'params' => array(
'version' => '2011-12-05'
)
),
'dynamodbstreams' => array(
'alias' => 'DynamoDbStreams',
'extends' => 'default_settings',
'class' => 'Aws\DynamoDbStreams\DynamoDbStreamsClient'
),
'ec2' => array(
'alias' => 'Ec2',
'extends' => 'default_settings',
'class' => 'Aws\Ec2\Ec2Client'
),
'ecs' => array(
'alias' => 'Ecs',
'extends' => 'default_settings',
'class' => 'Aws\Ecs\EcsClient'
),
'elasticache' => array(
'alias' => 'ElastiCache',
'extends' => 'default_settings',
'class' => 'Aws\ElastiCache\ElastiCacheClient'
),
'elasticbeanstalk' => array(
'alias' => 'ElasticBeanstalk',
'extends' => 'default_settings',
'class' => 'Aws\ElasticBeanstalk\ElasticBeanstalkClient'
),
'efs' => array(
'alias' => 'Efs',
'extends' => 'default_settings',
'class' => 'Aws\Efs\EfsClient'
),
'elasticloadbalancing' => array(
'alias' => 'ElasticLoadBalancing',
'extends' => 'default_settings',
'class' => 'Aws\ElasticLoadBalancing\ElasticLoadBalancingClient'
),
'elastictranscoder' => array(
'alias' => 'ElasticTranscoder',
'extends' => 'default_settings',
'class' => 'Aws\ElasticTranscoder\ElasticTranscoderClient'
),
'emr' => array(
'alias' => 'Emr',
'extends' => 'default_settings',
'class' => 'Aws\Emr\EmrClient'
),
'glacier' => array(
'alias' => 'Glacier',
'extends' => 'default_settings',
'class' => 'Aws\Glacier\GlacierClient'
),
'kinesis' => array(
'alias' => 'Kinesis',
'extends' => 'default_settings',
'class' => 'Aws\Kinesis\KinesisClient'
),
'kms' => array(
'alias' => 'Kms',
'extends' => 'default_settings',
'class' => 'Aws\Kms\KmsClient'
),
'lambda' => array(
'alias' => 'Lambda',
'extends' => 'default_settings',
'class' => 'Aws\Lambda\LambdaClient'
),
'iam' => array(
'alias' => 'Iam',
'extends' => 'default_settings',
'class' => 'Aws\Iam\IamClient'
),
'importexport' => array(
'alias' => 'ImportExport',
'extends' => 'default_settings',
'class' => 'Aws\ImportExport\ImportExportClient'
),
'machinelearning' => array(
'alias' => 'MachineLearning',
'extends' => 'default_settings',
'class' => 'Aws\MachineLearning\MachineLearningClient'
),
'opsworks' => array(
'alias' => 'OpsWorks',
'extends' => 'default_settings',
'class' => 'Aws\OpsWorks\OpsWorksClient'
),
'rds' => array(
'alias' => 'Rds',
'extends' => 'default_settings',
'class' => 'Aws\Rds\RdsClient'
),
'redshift' => array(
'alias' => 'Redshift',
'extends' => 'default_settings',
'class' => 'Aws\Redshift\RedshiftClient'
),
'route53' => array(
'alias' => 'Route53',
'extends' => 'default_settings',
'class' => 'Aws\Route53\Route53Client'
),
'route53domains' => array(
'alias' => 'Route53Domains',
'extends' => 'default_settings',
'class' => 'Aws\Route53Domains\Route53DomainsClient'
),
's3' => array(
'alias' => 'S3',
'extends' => 'default_settings',
'class' => 'Aws\S3\S3Client'
),
'sdb' => array(
'alias' => 'SimpleDb',
'extends' => 'default_settings',
'class' => 'Aws\SimpleDb\SimpleDbClient'
),
'ses' => array(
'alias' => 'Ses',
'extends' => 'default_settings',
'class' => 'Aws\Ses\SesClient'
),
'sns' => array(
'alias' => 'Sns',
'extends' => 'default_settings',
'class' => 'Aws\Sns\SnsClient'
),
'sqs' => array(
'alias' => 'Sqs',
'extends' => 'default_settings',
'class' => 'Aws\Sqs\SqsClient'
),
'ssm' => array(
'alias' => 'Ssm',
'extends' => 'default_settings',
'class' => 'Aws\Ssm\SsmClient'
),
'storagegateway' => array(
'alias' => 'StorageGateway',
'extends' => 'default_settings',
'class' => 'Aws\StorageGateway\StorageGatewayClient'
),
'sts' => array(
'alias' => 'Sts',
'extends' => 'default_settings',
'class' => 'Aws\Sts\StsClient'
),
'support' => array(
'alias' => 'Support',
'extends' => 'default_settings',
'class' => 'Aws\Support\SupportClient'
),
'swf' => array(
'alias' => 'Swf',
'extends' => 'default_settings',
'class' => 'Aws\Swf\SwfClient'
),
'workspaces' => array(
'alias' => 'WorkSpaces',
'extends' => 'default_settings',
'class' => 'Aws\WorkSpaces\WorkSpacesClient'
),
)
);
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/RulesEndpointProvider.php 0000644 00000003437 15132770567 0021621 0 ustar 00 <?php
namespace Aws\Common;
/**
* Provides endpoints based on a rules configuration file.
*/
class RulesEndpointProvider
{
/** @var array */
private $patterns;
/**
* @param array $patterns Hash of endpoint patterns mapping to endpoint
* configurations.
*/
public function __construct(array $patterns)
{
$this->patterns = $patterns;
}
/**
* Creates and returns the default RulesEndpointProvider based on the
* public rule sets.
*
* @return self
*/
public static function fromDefaults()
{
return new self(require __DIR__ . '/Resources/public-endpoints.php');
}
public function __invoke(array $args = array())
{
if (!isset($args['service'])) {
throw new \InvalidArgumentException('Requires a "service" value');
}
if (!isset($args['region'])) {
throw new \InvalidArgumentException('Requires a "region" value');
}
foreach ($this->getKeys($args['region'], $args['service']) as $key) {
if (isset($this->patterns['endpoints'][$key])) {
return $this->expand($this->patterns['endpoints'][$key], $args);
}
}
throw new \RuntimeException('Could not resolve endpoint');
}
private function expand(array $config, array $args)
{
$scheme = isset($args['scheme']) ? $args['scheme'] : 'https';
$config['endpoint'] = $scheme . '://' . str_replace(
array('{service}', '{region}'),
array($args['service'], $args['region']),
$config['endpoint']
);
return $config;
}
private function getKeys($region, $service)
{
return array("$region/$service", "$region/*", "*/$service", "*/*");
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Hash/TreeHash.php 0000644 00000014031 15132770567 0017671 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Hash;
use Aws\Common\Enum\Size;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\LogicException;
use Guzzle\Http\EntityBody;
/**
* Encapsulates the creation of a tree hash from streamed chunks of data
*/
class TreeHash implements ChunkHashInterface
{
/**
* @var string The algorithm used for hashing
*/
protected $algorithm;
/**
* @var array Set of binary checksums from which the tree hash is derived
*/
protected $checksums = array();
/**
* @var string The resulting hash in hex form
*/
protected $hash;
/**
* @var string The resulting hash in binary form
*/
protected $hashRaw;
/**
* Create a tree hash from an array of existing tree hash checksums
*
* @param array $checksums Set of checksums
* @param bool $inBinaryForm Whether or not the checksums are already in binary form
* @param string $algorithm A valid hash algorithm name as returned by `hash_algos()`
*
* @return TreeHash
*/
public static function fromChecksums(array $checksums, $inBinaryForm = false, $algorithm = self::DEFAULT_ALGORITHM)
{
$treeHash = new self($algorithm);
// Convert checksums to binary form if provided in hex form and add them to the tree hash
$treeHash->checksums = $inBinaryForm ? $checksums : array_map('Aws\Common\Hash\HashUtils::hexToBin', $checksums);
// Pre-calculate hash
$treeHash->getHash();
return $treeHash;
}
/**
* Create a tree hash from a content body
*
* @param string|resource|EntityBody $content Content to create a tree hash for
* @param string $algorithm A valid hash algorithm name as returned by `hash_algos()`
*
* @return TreeHash
*/
public static function fromContent($content, $algorithm = self::DEFAULT_ALGORITHM)
{
$treeHash = new self($algorithm);
// Read the data in 1MB chunks and add to tree hash
$content = EntityBody::factory($content);
while ($data = $content->read(Size::MB)) {
$treeHash->addData($data);
}
// Pre-calculate hash
$treeHash->getHash();
return $treeHash;
}
/**
* Validates an entity body with a tree hash checksum
*
* @param string|resource|EntityBody $content Content to create a tree hash for
* @param string $checksum The checksum to use for validation
* @param string $algorithm A valid hash algorithm name as returned by `hash_algos()`
*
* @return bool
*/
public static function validateChecksum($content, $checksum, $algorithm = self::DEFAULT_ALGORITHM)
{
$treeHash = self::fromContent($content, $algorithm);
return ($checksum === $treeHash->getHash());
}
/**
* {@inheritdoc}
*/
public function __construct($algorithm = self::DEFAULT_ALGORITHM)
{
HashUtils::validateAlgorithm($algorithm);
$this->algorithm = $algorithm;
}
/**
* {@inheritdoc}
* @throws LogicException if the root tree hash is already calculated
* @throws InvalidArgumentException if the data is larger than 1MB
*/
public function addData($data)
{
// Error if hash is already calculated
if ($this->hash) {
throw new LogicException('You may not add more data to a finalized tree hash.');
}
// Make sure that only 1MB chunks or smaller get passed in
if (strlen($data) > Size::MB) {
throw new InvalidArgumentException('The chunk of data added is too large for tree hashing.');
}
// Store the raw hash of this data segment
$this->checksums[] = hash($this->algorithm, $data, true);
return $this;
}
/**
* Add a checksum to the tree hash directly
*
* @param string $checksum The checksum to add
* @param bool $inBinaryForm Whether or not the checksum is already in binary form
*
* @return self
* @throws LogicException if the root tree hash is already calculated
*/
public function addChecksum($checksum, $inBinaryForm = false)
{
// Error if hash is already calculated
if ($this->hash) {
throw new LogicException('You may not add more checksums to a finalized tree hash.');
}
// Convert the checksum to binary form if necessary
$this->checksums[] = $inBinaryForm ? $checksum : HashUtils::hexToBin($checksum);
return $this;
}
/**
* {@inheritdoc}
*/
public function getHash($returnBinaryForm = false)
{
if (!$this->hash) {
// Perform hashes up the tree to arrive at the root checksum of the tree hash
$hashes = $this->checksums;
while (count($hashes) > 1) {
$sets = array_chunk($hashes, 2);
$hashes = array();
foreach ($sets as $set) {
$hashes[] = (count($set) === 1) ? $set[0] : hash($this->algorithm, $set[0] . $set[1], true);
}
}
$this->hashRaw = $hashes[0];
$this->hash = HashUtils::binToHex($this->hashRaw);
}
return $returnBinaryForm ? $this->hashRaw : $this->hash;
}
/**
* @return array Array of raw checksums composing the tree hash
*/
public function getChecksums()
{
return $this->checksums;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Hash/ChunkHashInterface.php 0000644 00000002714 15132770567 0021670 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Hash;
/**
* Interface for objects that encapsulate the creation of a hash from streamed chunks of data
*/
interface ChunkHashInterface
{
const DEFAULT_ALGORITHM = 'sha256';
/**
* Constructs the chunk hash and sets the algorithm to use for hashing
*
* @param string $algorithm A valid hash algorithm name as returned by `hash_algos()`
*
* @return self
*/
public function __construct($algorithm = 'sha256');
/**
* Add a chunk of data to be hashed
*
* @param string $data Data to be hashed
*
* @return self
*/
public function addData($data);
/**
* Return the results of the hash
*
* @param bool $returnBinaryForm If true, returns the hash in binary form instead of hex form
*
* @return string
*/
public function getHash($returnBinaryForm = false);
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Hash/ChunkHash.php 0000644 00000004120 15132770567 0020040 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Hash;
use Aws\Common\Exception\LogicException;
/**
* Encapsulates the creation of a hash from streamed chunks of data
*/
class ChunkHash implements ChunkHashInterface
{
/**
* @var resource The hash context as created by `hash_init()`
*/
protected $context;
/**
* @var string The resulting hash in hex form
*/
protected $hash;
/**
* @var string The resulting hash in binary form
*/
protected $hashRaw;
/**
* {@inheritdoc}
*/
public function __construct($algorithm = self::DEFAULT_ALGORITHM)
{
HashUtils::validateAlgorithm($algorithm);
$this->context = hash_init($algorithm);
}
/**
* {@inheritdoc}
*/
public function addData($data)
{
if (!$this->context) {
throw new LogicException('You may not add more data to a finalized chunk hash.');
}
hash_update($this->context, $data);
return $this;
}
/**
* {@inheritdoc}
*/
public function getHash($returnBinaryForm = false)
{
if (!$this->hash) {
$this->hashRaw = hash_final($this->context, true);
$this->hash = HashUtils::binToHex($this->hashRaw);
$this->context = null;
}
return $returnBinaryForm ? $this->hashRaw : $this->hash;
}
/**
* {@inheritdoc}
*/
public function __clone()
{
if ($this->context) {
$this->context = hash_copy($this->context);
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Common/Hash/HashUtils.php 0000644 00000004127 15132770567 0020077 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Common\Hash;
use Aws\Common\Exception\InvalidArgumentException;
/**
* Contains hashing utilities
*/
class HashUtils
{
/**
* Converts a hash in hex form to binary form
*
* @param string $hash Hash in hex form
*
* @return string Hash in binary form
*/
public static function hexToBin($hash)
{
// If using PHP 5.4, there is a native function to convert from hex to binary
static $useNative;
if ($useNative === null) {
$useNative = function_exists('hex2bin');
}
if (!$useNative && strlen($hash) % 2 !== 0) {
$hash = '0' . $hash;
}
return $useNative ? hex2bin($hash) : pack("H*", $hash);
}
/**
* Converts a hash in binary form to hex form
*
* @param string $hash Hash in binary form
*
* @return string Hash in hex form
*/
public static function binToHex($hash)
{
return bin2hex($hash);
}
/**
* Checks if the algorithm specified exists and throws an exception if it does not
*
* @param string $algorithm Name of the algorithm to validate
*
* @return bool
* @throws InvalidArgumentException if the algorithm doesn't exist
*/
public static function validateAlgorithm($algorithm)
{
if (!in_array($algorithm, hash_algos(), true)) {
throw new InvalidArgumentException(esc_html("The hashing algorithm specified ({$algorithm}) does not exist."));
}
return true;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/AcpListener.php 0000644 00000004762 15132770567 0016563 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\S3\Model\Acp;
use Guzzle\Common\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Listener used to add an Access Control Policy to a request
*/
class AcpListener implements EventSubscriberInterface
{
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return array('command.before_prepare' => array('onCommandBeforePrepare', -255));
}
/**
* An event handler for constructing ACP definitions.
*
* @param Event $event The event to respond to.
*
* @throws InvalidArgumentException
*/
public function onCommandBeforePrepare(Event $event)
{
/** @var \Guzzle\Service\Command\AbstractCommand $command */
$command = $event['command'];
$operation = $command->getOperation();
if ($operation->hasParam('ACP') && $command->hasKey('ACP')) {
if ($acp = $command->get('ACP')) {
// Ensure that the correct object was passed
if (!($acp instanceof Acp)) {
throw new InvalidArgumentException('ACP must be an instance of Aws\S3\Model\Acp');
}
// Check if the user specified both an ACP and Grants
if ($command->hasKey('Grants')) {
throw new InvalidArgumentException(
'Use either the ACP parameter or the Grants parameter. Do not use both.'
);
}
// Add the correct headers/body based parameters to the command
if ($operation->hasParam('Grants')) {
$command->overwriteWith($acp->toArray());
} else {
$acp->updateCommand($command);
}
}
// Remove the ACP parameter
$command->remove('ACP');
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/S3Signature.php 0000644 00000022114 15132770567 0016510 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3;
use Aws\Common\Credentials\CredentialsInterface;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\QueryString;
use Guzzle\Http\Url;
/**
* Default Amazon S3 signature implementation
* @link http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html
*/
class S3Signature implements S3SignatureInterface
{
/**
* @var array Query string values that must be signed
*/
protected $signableQueryString = array (
'acl',
'cors',
'delete',
'lifecycle',
'location',
'logging',
'notification',
'partNumber',
'policy',
'requestPayment',
'response-cache-control',
'response-content-disposition',
'response-content-encoding',
'response-content-language',
'response-content-type',
'response-expires',
'restore',
'tagging',
'torrent',
'uploadId',
'uploads',
'versionId',
'versioning',
'versions',
'website',
);
/** @var array Sorted headers that must be signed */
private $signableHeaders = array('Content-MD5', 'Content-Type');
public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
{
// Ensure that the signable query string parameters are sorted
sort($this->signableQueryString);
// Add the security token header if one is being used by the credentials
if ($token = $credentials->getSecurityToken()) {
$request->setHeader('x-amz-security-token', $token);
}
$request->removeHeader('x-amz-date');
$request->setHeader('Date', gmdate(\DateTime::RFC2822));
$stringToSign = $this->createCanonicalizedString($request);
$request->getParams()->set('aws.string_to_sign', $stringToSign);
$request->setHeader(
'Authorization',
'AWS ' . $credentials->getAccessKeyId() . ':' . $this->signString($stringToSign, $credentials)
);
}
public function createPresignedUrl(
RequestInterface $request,
CredentialsInterface $credentials,
$expires
) {
if ($expires instanceof \DateTime) {
$expires = $expires->getTimestamp();
} elseif (!is_numeric($expires)) {
$expires = strtotime($expires);
}
// Operate on a clone of the request, so the original is not altered
$request = clone $request;
// URL encoding already occurs in the URI template expansion. Undo that and encode using the same encoding as
// GET object, PUT object, etc.
$path = S3Client::encodeKey(rawurldecode($request->getPath()));
$request->setPath($path);
// Make sure to handle temporary credentials
if ($token = $credentials->getSecurityToken()) {
$request->setHeader('x-amz-security-token', $token);
$request->getQuery()->set('x-amz-security-token', $token);
}
// Set query params required for pre-signed URLs
$request->getQuery()
->set('AWSAccessKeyId', $credentials->getAccessKeyId())
->set('Expires', $expires)
->set('Signature', $this->signString(
$this->createCanonicalizedString($request, $expires),
$credentials
));
// Move X-Amz-* headers to the query string
foreach ($request->getHeaders() as $name => $header) {
$name = strtolower($name);
if (strpos($name, 'x-amz-') === 0) {
$request->getQuery()->set($name, (string) $header);
$request->removeHeader($name);
}
}
return $request->getUrl();
}
public function signString($string, CredentialsInterface $credentials)
{
return base64_encode(hash_hmac('sha1', $string, $credentials->getSecretKey(), true));
}
public function createCanonicalizedString(RequestInterface $request, $expires = null)
{
$buffer = $request->getMethod() . "\n";
// Add the interesting headers
foreach ($this->signableHeaders as $header) {
$buffer .= (string) $request->getHeader($header) . "\n";
}
// Choose dates from left to right based on what's set
$date = $expires ?: (string) $request->getHeader('date');
$buffer .= "{$date}\n"
. $this->createCanonicalizedAmzHeaders($request)
. $this->createCanonicalizedResource($request);
return $buffer;
}
/**
* Create a canonicalized AmzHeaders string for a signature.
*
* @param RequestInterface $request Request from which to gather headers
*
* @return string Returns canonicalized AMZ headers.
*/
private function createCanonicalizedAmzHeaders(RequestInterface $request)
{
$headers = array();
foreach ($request->getHeaders() as $name => $header) {
$name = strtolower($name);
if (strpos($name, 'x-amz-') === 0) {
$value = trim((string) $header);
if ($value || $value === '0') {
$headers[$name] = $name . ':' . $value;
}
}
}
if (!$headers) {
return '';
}
ksort($headers);
return implode("\n", $headers) . "\n";
}
/**
* Create a canonicalized resource for a request
*
* @param RequestInterface $request Request for the resource
*
* @return string
*/
private function createCanonicalizedResource(RequestInterface $request)
{
$buffer = $request->getParams()->get('s3.resource');
// When sending a raw HTTP request (e.g. $client->get())
if (null === $buffer) {
$bucket = $request->getParams()->get('bucket') ?: $this->parseBucketName($request);
// Use any specified bucket name, the parsed bucket name, or no bucket name when interacting with GetService
$buffer = $bucket ? "/{$bucket}" : '';
// Remove encoding from the path and use the S3 specific encoding
$path = S3Client::encodeKey(rawurldecode($request->getPath()));
// if the bucket was path style, then ensure that the bucket wasn't duplicated in the resource
$buffer .= preg_replace("#^/{$bucket}/{$bucket}#", "/{$bucket}", $path);
}
// Remove double slashes
$buffer = str_replace('//', '/', $buffer);
// Add sub resource parameters
$query = $request->getQuery();
$first = true;
foreach ($this->signableQueryString as $key) {
if ($query->hasKey($key)) {
$value = $query[$key];
$buffer .= $first ? '?' : '&';
$first = false;
$buffer .= $key;
// Don't add values for empty sub-resources
if ($value !== '' &&
$value !== false &&
$value !== null &&
$value !== QueryString::BLANK
) {
$buffer .= "={$value}";
}
}
}
return $buffer;
}
/**
* Parse the bucket name from a request object
*
* @param RequestInterface $request Request to parse
*
* @return string
*/
private function parseBucketName(RequestInterface $request)
{
$baseUrl = Url::factory($request->getClient()->getBaseUrl());
$baseHost = $baseUrl->getHost();
$host = $request->getHost();
if (strpos($host, $baseHost) === false) {
// Does not contain the base URL, so it's either a redirect, CNAME, or using a different region
$baseHost = '';
// For every known S3 host, check if that host is present on the request
$regions = $request->getClient()->getDescription()->getData('regions');
foreach ($regions as $region) {
if (strpos($host, $region['hostname']) !== false) {
// This host matches the request host. Tells use the region and endpoint-- we can derive the bucket
$baseHost = $region['hostname'];
break;
}
}
// If no matching base URL was found, then assume that this is a CNAME, and the CNAME is the bucket
if (!$baseHost) {
return $host;
}
}
// Remove the baseURL from the host of the request to attempt to determine the bucket name
return trim(str_replace($baseHost, '', $request->getHost()), ' .');
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Resources/s3-2006-03-01.php 0000644 00000712626 15132770567 0017701 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
return array (
'apiVersion' => '2006-03-01',
'endpointPrefix' => 's3',
'serviceFullName' => 'Amazon Simple Storage Service',
'serviceAbbreviation' => 'Amazon S3',
'serviceType' => 'rest-xml',
'timestampFormat' => 'rfc822',
'globalEndpoint' => 's3.amazonaws.com',
'signatureVersion' => 's3',
'namespace' => 'S3',
'regions' => array(
'us-east-1' => array(
'http' => true,
'https' => true,
'hostname' => 's3.amazonaws.com',
),
'us-west-1' => array(
'http' => true,
'https' => true,
'hostname' => 's3-us-west-1.amazonaws.com',
),
'us-west-2' => array(
'http' => true,
'https' => true,
'hostname' => 's3-us-west-2.amazonaws.com',
),
'eu-west-1' => array(
'http' => true,
'https' => true,
'hostname' => 's3-eu-west-1.amazonaws.com',
),
'eu-central-1' => array(
'http' => true,
'https' => true,
'hostname' => 's3-eu-central-1.amazonaws.com',
),
'ap-northeast-1' => array(
'http' => true,
'https' => true,
'hostname' => 's3-ap-northeast-1.amazonaws.com',
),
'ap-southeast-1' => array(
'http' => true,
'https' => true,
'hostname' => 's3-ap-southeast-1.amazonaws.com',
),
'ap-southeast-2' => array(
'http' => true,
'https' => true,
'hostname' => 's3-ap-southeast-2.amazonaws.com',
),
'sa-east-1' => array(
'http' => true,
'https' => true,
'hostname' => 's3-sa-east-1.amazonaws.com',
),
'cn-north-1' => array(
'http' => true,
'https' => true,
'hostname' => 's3.cn-north-1.amazonaws.com.cn',
),
'us-gov-west-1' => array(
'http' => true,
'https' => true,
'hostname' => 's3-us-gov-west-1.amazonaws.com',
),
),
'operations' => array(
'AbortMultipartUpload' => array(
'httpMethod' => 'DELETE',
'uri' => '/{Bucket}{/Key*}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'AbortMultipartUploadOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadAbort.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'UploadId' => array(
'required' => true,
'type' => 'string',
'location' => 'query',
'sentAs' => 'uploadId',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
),
'errorResponses' => array(
array(
'reason' => 'The specified multipart upload does not exist.',
'class' => 'NoSuchUploadException',
),
),
),
'CompleteMultipartUpload' => array(
'httpMethod' => 'POST',
'uri' => '/{Bucket}{/Key*}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'CompleteMultipartUploadOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadComplete.html',
'data' => array(
'xmlRoot' => array(
'name' => 'CompleteMultipartUpload',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'Parts' => array(
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'CompletedPart',
'type' => 'object',
'sentAs' => 'Part',
'properties' => array(
'ETag' => array(
'type' => 'string',
),
'PartNumber' => array(
'type' => 'numeric',
),
),
),
),
'UploadId' => array(
'required' => true,
'type' => 'string',
'location' => 'query',
'sentAs' => 'uploadId',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'CopyObject' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}{/Key*}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'CopyObjectOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectCOPY.html',
'data' => array(
'xmlRoot' => array(
'name' => 'CopyObjectRequest',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'ACL' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-acl',
),
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'CacheControl' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Cache-Control',
),
'ContentDisposition' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Disposition',
),
'ContentEncoding' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Encoding',
),
'ContentLanguage' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Language',
),
'ContentType' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Type',
),
'CopySource' => array(
'required' => true,
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source',
),
'CopySourceIfMatch' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-if-match',
),
'CopySourceIfModifiedSince' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-if-modified-since',
),
'CopySourceIfNoneMatch' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-if-none-match',
),
'CopySourceIfUnmodifiedSince' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-if-unmodified-since',
),
'Expires' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'header',
),
'GrantFullControl' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-full-control',
),
'GrantRead' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read',
),
'GrantReadACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read-acp',
),
'GrantWriteACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-write-acp',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'Metadata' => array(
'type' => 'object',
'location' => 'header',
'sentAs' => 'x-amz-meta-',
'additionalProperties' => array(
'type' => 'string',
),
),
'MetadataDirective' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-metadata-directive',
),
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'StorageClass' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-storage-class',
),
'WebsiteRedirectLocation' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-website-redirect-location',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKey' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'SSEKMSKeyId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id',
),
'CopySourceSSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-algorithm',
),
'CopySourceSSECustomerKey' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key',
),
'CopySourceSSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key-MD5',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
'ACP' => array(
'type' => 'object',
'additionalProperties' => true,
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
'errorResponses' => array(
array(
'reason' => 'The source object of the COPY operation is not in the active tier and is only stored in Amazon Glacier.',
'class' => 'ObjectNotInActiveTierErrorException',
),
),
),
'CreateBucket' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'CreateBucketOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUT.html',
'data' => array(
'xmlRoot' => array(
'name' => 'CreateBucketConfiguration',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'ACL' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-acl',
),
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'LocationConstraint' => array(
'type' => 'string',
'location' => 'xml',
),
'GrantFullControl' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-full-control',
),
'GrantRead' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read',
),
'GrantReadACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read-acp',
),
'GrantWrite' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-write',
),
'GrantWriteACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-write-acp',
),
'ACP' => array(
'type' => 'object',
'additionalProperties' => true,
),
),
'errorResponses' => array(
array(
'reason' => 'The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.',
'class' => 'BucketAlreadyExistsException',
),
),
),
'CreateMultipartUpload' => array(
'httpMethod' => 'POST',
'uri' => '/{Bucket}{/Key*}?uploads',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'CreateMultipartUploadOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadInitiate.html',
'data' => array(
'xmlRoot' => array(
'name' => 'CreateMultipartUploadRequest',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'ACL' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-acl',
),
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'CacheControl' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Cache-Control',
),
'ContentDisposition' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Disposition',
),
'ContentEncoding' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Encoding',
),
'ContentLanguage' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Language',
),
'ContentType' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Type',
),
'Expires' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'header',
),
'GrantFullControl' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-full-control',
),
'GrantRead' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read',
),
'GrantReadACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read-acp',
),
'GrantWriteACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-write-acp',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'Metadata' => array(
'type' => 'object',
'location' => 'header',
'sentAs' => 'x-amz-meta-',
'additionalProperties' => array(
'type' => 'string',
),
),
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'StorageClass' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-storage-class',
),
'WebsiteRedirectLocation' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-website-redirect-location',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKey' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'SSEKMSKeyId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
'ACP' => array(
'type' => 'object',
'additionalProperties' => true,
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'DeleteBucket' => array(
'httpMethod' => 'DELETE',
'uri' => '/{Bucket}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'DeleteBucketOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETE.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
),
),
'DeleteBucketCors' => array(
'httpMethod' => 'DELETE',
'uri' => '/{Bucket}?cors',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'DeleteBucketCorsOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEcors.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
),
),
'DeleteBucketLifecycle' => array(
'httpMethod' => 'DELETE',
'uri' => '/{Bucket}?lifecycle',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'DeleteBucketLifecycleOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETElifecycle.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
),
),
'DeleteBucketPolicy' => array(
'httpMethod' => 'DELETE',
'uri' => '/{Bucket}?policy',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'DeleteBucketPolicyOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEpolicy.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
),
),
'DeleteBucketReplication' => array(
'httpMethod' => 'DELETE',
'uri' => '/{Bucket}?replication',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'DeleteBucketReplicationOutput',
'responseType' => 'model',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
),
),
'DeleteBucketTagging' => array(
'httpMethod' => 'DELETE',
'uri' => '/{Bucket}?tagging',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'DeleteBucketTaggingOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEtagging.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
),
),
'DeleteBucketWebsite' => array(
'httpMethod' => 'DELETE',
'uri' => '/{Bucket}?website',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'DeleteBucketWebsiteOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETEwebsite.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
),
),
'DeleteObject' => array(
'httpMethod' => 'DELETE',
'uri' => '/{Bucket}{/Key*}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'DeleteObjectOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'MFA' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-mfa',
),
'VersionId' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'versionId',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
),
),
'DeleteObjects' => array(
'httpMethod' => 'POST',
'uri' => '/{Bucket}?delete',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'DeleteObjectsOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/multiobjectdeleteapi.html',
'data' => array(
'xmlRoot' => array(
'name' => 'Delete',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
'contentMd5' => true,
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Objects' => array(
'required' => true,
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'ObjectIdentifier',
'type' => 'object',
'sentAs' => 'Object',
'properties' => array(
'Key' => array(
'required' => true,
'type' => 'string',
'minLength' => 1,
),
'VersionId' => array(
'type' => 'string',
),
),
),
),
'Quiet' => array(
'type' => 'boolean',
'format' => 'boolean-string',
'location' => 'xml',
),
'MFA' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-mfa',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketAcl' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?acl',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketAclOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETacl.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketCors' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?cors',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketCorsOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETcors.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketLifecycle' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?lifecycle',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketLifecycleOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlifecycle.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketLifecycleConfiguration' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?lifecycle',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketLifecycleConfigurationOutput',
'responseType' => 'model',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketLocation' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?location',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketLocationOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlocation.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
),
),
'GetBucketLogging' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?logging',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketLoggingOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETlogging.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketNotification' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?notification',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'NotificationConfigurationDeprecated',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETnotification.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketNotificationConfiguration' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?notification',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'NotificationConfiguration',
'responseType' => 'model',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketPolicy' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?policy',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketPolicyOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETpolicy.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
),
),
'GetBucketReplication' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?replication',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketReplicationOutput',
'responseType' => 'model',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketRequestPayment' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?requestPayment',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketRequestPaymentOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTrequestPaymentGET.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketTagging' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?tagging',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketTaggingOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETtagging.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketVersioning' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?versioning',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketVersioningOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETversioningStatus.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetBucketWebsite' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?website',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetBucketWebsiteOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETwebsite.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'GetObject' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}{/Key*}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetObjectOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'IfMatch' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'If-Match',
),
'IfModifiedSince' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'header',
'sentAs' => 'If-Modified-Since',
),
'IfNoneMatch' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'If-None-Match',
),
'IfUnmodifiedSince' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'header',
'sentAs' => 'If-Unmodified-Since',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'Range' => array(
'type' => 'string',
'location' => 'header',
),
'ResponseCacheControl' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'response-cache-control',
),
'ResponseContentDisposition' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'response-content-disposition',
),
'ResponseContentEncoding' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'response-content-encoding',
),
'ResponseContentLanguage' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'response-content-language',
),
'ResponseContentType' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'response-content-type',
),
'ResponseExpires' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'query',
'sentAs' => 'response-expires',
),
'VersionId' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'versionId',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKey' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
'SaveAs' => array(
'location' => 'response_body',
),
),
'errorResponses' => array(
array(
'reason' => 'The specified key does not exist.',
'class' => 'NoSuchKeyException',
),
),
),
'GetObjectAcl' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}{/Key*}?acl',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetObjectAclOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGETacl.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'VersionId' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'versionId',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
'errorResponses' => array(
array(
'reason' => 'The specified key does not exist.',
'class' => 'NoSuchKeyException',
),
),
),
'GetObjectTorrent' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}{/Key*}?torrent',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'GetObjectTorrentOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGETtorrent.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
),
),
'HeadBucket' => array(
'httpMethod' => 'HEAD',
'uri' => '/{Bucket}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'HeadBucketOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
),
'errorResponses' => array(
array(
'reason' => 'The specified bucket does not exist.',
'class' => 'NoSuchBucketException',
),
),
),
'HeadObject' => array(
'httpMethod' => 'HEAD',
'uri' => '/{Bucket}{/Key*}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'HeadObjectOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'IfMatch' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'If-Match',
),
'IfModifiedSince' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'header',
'sentAs' => 'If-Modified-Since',
),
'IfNoneMatch' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'If-None-Match',
),
'IfUnmodifiedSince' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'header',
'sentAs' => 'If-Unmodified-Since',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'Range' => array(
'type' => 'string',
'location' => 'header',
),
'VersionId' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'versionId',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKey' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
),
'errorResponses' => array(
array(
'reason' => 'The specified key does not exist.',
'class' => 'NoSuchKeyException',
),
),
),
'ListBuckets' => array(
'httpMethod' => 'GET',
'uri' => '/',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'ListBucketsOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTServiceGET.html',
'parameters' => array(
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'ListMultipartUploads' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?uploads',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'ListMultipartUploadsOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadListMPUpload.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Delimiter' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'delimiter',
),
'EncodingType' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'encoding-type',
),
'KeyMarker' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'key-marker',
),
'MaxUploads' => array(
'type' => 'numeric',
'location' => 'query',
'sentAs' => 'max-uploads',
),
'Prefix' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'prefix',
),
'UploadIdMarker' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'upload-id-marker',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'ListObjectVersions' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}?versions',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'ListObjectVersionsOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGETVersion.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Delimiter' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'delimiter',
),
'EncodingType' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'encoding-type',
),
'KeyMarker' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'key-marker',
),
'MaxKeys' => array(
'type' => 'numeric',
'location' => 'query',
'sentAs' => 'max-keys',
),
'Prefix' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'prefix',
),
'VersionIdMarker' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'version-id-marker',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'ListObjects' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'ListObjectsOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Delimiter' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'delimiter',
),
'EncodingType' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'encoding-type',
),
'Marker' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'marker',
),
'MaxKeys' => array(
'type' => 'numeric',
'location' => 'query',
'sentAs' => 'max-keys',
),
'Prefix' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'prefix',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
'errorResponses' => array(
array(
'reason' => 'The specified bucket does not exist.',
'class' => 'NoSuchBucketException',
),
),
),
'ListParts' => array(
'httpMethod' => 'GET',
'uri' => '/{Bucket}{/Key*}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'ListPartsOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadListParts.html',
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'MaxParts' => array(
'type' => 'numeric',
'location' => 'query',
'sentAs' => 'max-parts',
),
'PartNumberMarker' => array(
'type' => 'numeric',
'location' => 'query',
'sentAs' => 'part-number-marker',
),
'UploadId' => array(
'required' => true,
'type' => 'string',
'location' => 'query',
'sentAs' => 'uploadId',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
'PutBucketAcl' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?acl',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketAclOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html',
'data' => array(
'xmlRoot' => array(
'name' => 'AccessControlPolicy',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'ACL' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-acl',
),
'Grants' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'AccessControlList',
'items' => array(
'name' => 'Grant',
'type' => 'object',
'properties' => array(
'Grantee' => array(
'type' => 'object',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'EmailAddress' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
'Type' => array(
'required' => true,
'type' => 'string',
'sentAs' => 'xsi:type',
'data' => array(
'xmlAttribute' => true,
'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance',
),
),
'URI' => array(
'type' => 'string',
),
),
),
'Permission' => array(
'type' => 'string',
),
),
),
),
'Owner' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
),
),
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'GrantFullControl' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-full-control',
),
'GrantRead' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read',
),
'GrantReadACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read-acp',
),
'GrantWrite' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-write',
),
'GrantWriteACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-write-acp',
),
'ACP' => array(
'type' => 'object',
'additionalProperties' => true,
),
),
),
'PutBucketCors' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?cors',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketCorsOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTcors.html',
'data' => array(
'xmlRoot' => array(
'name' => 'CORSConfiguration',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
'contentMd5' => true,
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'CORSRules' => array(
'required' => true,
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'CORSRule',
'type' => 'object',
'sentAs' => 'CORSRule',
'properties' => array(
'AllowedHeaders' => array(
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'AllowedHeader',
'type' => 'string',
'sentAs' => 'AllowedHeader',
),
),
'AllowedMethods' => array(
'required' => true,
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'AllowedMethod',
'type' => 'string',
'sentAs' => 'AllowedMethod',
),
),
'AllowedOrigins' => array(
'required' => true,
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'AllowedOrigin',
'type' => 'string',
'sentAs' => 'AllowedOrigin',
),
),
'ExposeHeaders' => array(
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'ExposeHeader',
'type' => 'string',
'sentAs' => 'ExposeHeader',
),
),
'MaxAgeSeconds' => array(
'type' => 'numeric',
),
),
),
),
),
),
'PutBucketLifecycle' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?lifecycle',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketLifecycleOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlifecycle.html',
'data' => array(
'xmlRoot' => array(
'name' => 'LifecycleConfiguration',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
'contentMd5' => true,
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Rules' => array(
'required' => true,
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Rule',
'type' => 'object',
'sentAs' => 'Rule',
'properties' => array(
'Expiration' => array(
'type' => 'object',
'properties' => array(
'Date' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time',
),
'Days' => array(
'type' => 'numeric',
),
),
),
'ID' => array(
'type' => 'string',
),
'Prefix' => array(
'required' => true,
'type' => 'string',
),
'Status' => array(
'required' => true,
'type' => 'string',
),
'Transition' => array(
'type' => 'object',
'properties' => array(
'Date' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time',
),
'Days' => array(
'type' => 'numeric',
),
'StorageClass' => array(
'type' => 'string',
),
),
),
'NoncurrentVersionTransition' => array(
'type' => 'object',
'properties' => array(
'NoncurrentDays' => array(
'type' => 'numeric',
),
'StorageClass' => array(
'type' => 'string',
),
),
),
'NoncurrentVersionExpiration' => array(
'type' => 'object',
'properties' => array(
'NoncurrentDays' => array(
'type' => 'numeric',
),
),
),
),
),
),
),
),
'PutBucketLifecycleConfiguration' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?lifecycle',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketLifecycleConfigurationOutput',
'responseType' => 'model',
'data' => array(
'xmlRoot' => array(
'name' => 'LifecycleConfiguration',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Rules' => array(
'required' => true,
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'LifecycleRule',
'type' => 'object',
'sentAs' => 'Rule',
'properties' => array(
'Expiration' => array(
'type' => 'object',
'properties' => array(
'Date' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
),
'Days' => array(
'type' => 'numeric',
),
),
),
'ID' => array(
'type' => 'string',
),
'Prefix' => array(
'required' => true,
'type' => 'string',
),
'Status' => array(
'required' => true,
'type' => 'string',
),
'Transitions' => array(
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Transition',
'type' => 'object',
'sentAs' => 'Transition',
'properties' => array(
'Date' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
),
'Days' => array(
'type' => 'numeric',
),
'StorageClass' => array(
'type' => 'string',
),
),
),
),
'NoncurrentVersionTransitions' => array(
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'NoncurrentVersionTransition',
'type' => 'object',
'sentAs' => 'NoncurrentVersionTransition',
'properties' => array(
'NoncurrentDays' => array(
'type' => 'numeric',
),
'StorageClass' => array(
'type' => 'string',
),
),
),
),
'NoncurrentVersionExpiration' => array(
'type' => 'object',
'properties' => array(
'NoncurrentDays' => array(
'type' => 'numeric',
),
),
),
),
),
),
),
),
'PutBucketLogging' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?logging',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketLoggingOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTlogging.html',
'data' => array(
'xmlRoot' => array(
'name' => 'BucketLoggingStatus',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
'xmlAllowEmpty' => true,
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'LoggingEnabled' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'TargetBucket' => array(
'type' => 'string',
),
'TargetGrants' => array(
'type' => 'array',
'items' => array(
'name' => 'Grant',
'type' => 'object',
'properties' => array(
'Grantee' => array(
'type' => 'object',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'EmailAddress' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
'Type' => array(
'required' => true,
'type' => 'string',
'sentAs' => 'xsi:type',
'data' => array(
'xmlAttribute' => true,
'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance',
),
),
'URI' => array(
'type' => 'string',
),
),
),
'Permission' => array(
'type' => 'string',
),
),
),
),
'TargetPrefix' => array(
'type' => 'string',
),
),
),
),
),
'PutBucketNotification' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?notification',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketNotificationOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTnotification.html',
'data' => array(
'xmlRoot' => array(
'name' => 'NotificationConfiguration',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
'xmlAllowEmpty' => true,
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'TopicConfiguration' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'Events' => array(
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
),
),
'Event' => array(
'type' => 'string',
),
'Topic' => array(
'type' => 'string',
),
),
),
'QueueConfiguration' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'Event' => array(
'type' => 'string',
),
'Events' => array(
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
),
),
'Queue' => array(
'type' => 'string',
),
),
),
'CloudFunctionConfiguration' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'Event' => array(
'type' => 'string',
),
'Events' => array(
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
),
),
'CloudFunction' => array(
'type' => 'string',
),
'InvocationRole' => array(
'type' => 'string',
),
),
),
),
),
'PutBucketNotificationConfiguration' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?notification',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketNotificationConfigurationOutput',
'responseType' => 'model',
'data' => array(
'xmlRoot' => array(
'name' => 'NotificationConfiguration',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'TopicConfigurations' => array(
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'TopicConfiguration',
'type' => 'object',
'sentAs' => 'TopicConfiguration',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'TopicArn' => array(
'required' => true,
'type' => 'string',
'sentAs' => 'Topic',
),
'Events' => array(
'required' => true,
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
'sentAs' => 'Event',
),
),
'Filter' => array(
'type' => 'object',
'properties' => array(
'Key' => array(
'type' => 'object',
'sentAs' => 'S3Key',
'properties' => array(
'FilterRules' => array(
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'FilterRule',
'type' => 'object',
'sentAs' => 'FilterRule',
'properties' => array(
'Name' => array(
'type' => 'string',
),
'Value' => array(
'type' => 'string',
),
),
),
),
),
),
),
),
),
),
),
'QueueConfigurations' => array(
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'QueueConfiguration',
'type' => 'object',
'sentAs' => 'QueueConfiguration',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'QueueArn' => array(
'required' => true,
'type' => 'string',
'sentAs' => 'Queue',
),
'Events' => array(
'required' => true,
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
'sentAs' => 'Event',
),
),
'Filter' => array(
'type' => 'object',
'properties' => array(
'Key' => array(
'type' => 'object',
'sentAs' => 'S3Key',
'properties' => array(
'FilterRules' => array(
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'FilterRule',
'type' => 'object',
'sentAs' => 'FilterRule',
'properties' => array(
'Name' => array(
'type' => 'string',
),
'Value' => array(
'type' => 'string',
),
),
),
),
),
),
),
),
),
),
),
'LambdaFunctionConfigurations' => array(
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'LambdaFunctionConfiguration',
'type' => 'object',
'sentAs' => 'CloudFunctionConfiguration',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'LambdaFunctionArn' => array(
'required' => true,
'type' => 'string',
'sentAs' => 'CloudFunction',
),
'Events' => array(
'required' => true,
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
'sentAs' => 'Event',
),
),
'Filter' => array(
'type' => 'object',
'properties' => array(
'Key' => array(
'type' => 'object',
'sentAs' => 'S3Key',
'properties' => array(
'FilterRules' => array(
'type' => 'array',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'FilterRule',
'type' => 'object',
'sentAs' => 'FilterRule',
'properties' => array(
'Name' => array(
'type' => 'string',
),
'Value' => array(
'type' => 'string',
),
),
),
),
),
),
),
),
),
),
),
),
),
'PutBucketPolicy' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?policy',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketPolicyOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTpolicy.html',
'data' => array(
'xmlRoot' => array(
'name' => 'PutBucketPolicyRequest',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Policy' => array(
'required' => true,
'type' => array(
'string',
'object',
),
'location' => 'body',
),
),
),
'PutBucketReplication' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?replication',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketReplicationOutput',
'responseType' => 'model',
'data' => array(
'xmlRoot' => array(
'name' => 'ReplicationConfiguration',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Role' => array(
'required' => true,
'type' => 'string',
'location' => 'xml',
),
'Rules' => array(
'required' => true,
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'ReplicationRule',
'type' => 'object',
'sentAs' => 'Rule',
'properties' => array(
'ID' => array(
'type' => 'string',
),
'Prefix' => array(
'required' => true,
'type' => 'string',
),
'Status' => array(
'required' => true,
'type' => 'string',
),
'Destination' => array(
'required' => true,
'type' => 'object',
'properties' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
),
'StorageClass' => array(
'type' => 'string',
),
),
),
),
),
),
),
),
'PutBucketRequestPayment' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?requestPayment',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketRequestPaymentOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTrequestPaymentPUT.html',
'data' => array(
'xmlRoot' => array(
'name' => 'RequestPaymentConfiguration',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Payer' => array(
'required' => true,
'type' => 'string',
'location' => 'xml',
),
),
),
'PutBucketTagging' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?tagging',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketTaggingOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTtagging.html',
'data' => array(
'xmlRoot' => array(
'name' => 'Tagging',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
'contentMd5' => true,
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'TagSet' => array(
'required' => true,
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'Tag',
'type' => 'object',
'properties' => array(
'Key' => array(
'required' => true,
'type' => 'string',
'minLength' => 1,
),
'Value' => array(
'required' => true,
'type' => 'string',
),
),
),
),
),
),
'PutBucketVersioning' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?versioning',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketVersioningOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTVersioningStatus.html',
'data' => array(
'xmlRoot' => array(
'name' => 'VersioningConfiguration',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'MFA' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-mfa',
),
'MFADelete' => array(
'type' => 'string',
'location' => 'xml',
'sentAs' => 'MfaDelete',
),
'Status' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'PutBucketWebsite' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}?website',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutBucketWebsiteOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTwebsite.html',
'data' => array(
'xmlRoot' => array(
'name' => 'WebsiteConfiguration',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
'xmlAllowEmpty' => true,
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'ErrorDocument' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Key' => array(
'required' => true,
'type' => 'string',
'minLength' => 1,
),
),
),
'IndexDocument' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Suffix' => array(
'required' => true,
'type' => 'string',
),
),
),
'RedirectAllRequestsTo' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'HostName' => array(
'required' => true,
'type' => 'string',
),
'Protocol' => array(
'type' => 'string',
),
),
),
'RoutingRules' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'RoutingRule',
'type' => 'object',
'properties' => array(
'Condition' => array(
'type' => 'object',
'properties' => array(
'HttpErrorCodeReturnedEquals' => array(
'type' => 'string',
),
'KeyPrefixEquals' => array(
'type' => 'string',
),
),
),
'Redirect' => array(
'required' => true,
'type' => 'object',
'properties' => array(
'HostName' => array(
'type' => 'string',
),
'HttpRedirectCode' => array(
'type' => 'string',
),
'Protocol' => array(
'type' => 'string',
),
'ReplaceKeyPrefixWith' => array(
'type' => 'string',
),
'ReplaceKeyWith' => array(
'type' => 'string',
),
),
),
),
),
),
),
),
'PutObject' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}{/Key*}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutObjectOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html',
'data' => array(
'xmlRoot' => array(
'name' => 'PutObjectRequest',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'ACL' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-acl',
),
'Body' => array(
'type' => array(
'string',
'object',
),
'location' => 'body',
),
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'CacheControl' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Cache-Control',
),
'ContentDisposition' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Disposition',
),
'ContentEncoding' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Encoding',
),
'ContentLanguage' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Language',
),
'ContentLength' => array(
'type' => 'numeric',
'location' => 'header',
'sentAs' => 'Content-Length',
),
'ContentMD5' => array(
'type' => array(
'string',
'boolean',
),
'location' => 'header',
'sentAs' => 'Content-MD5',
),
'ContentType' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Type',
),
'Expires' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'header',
),
'GrantFullControl' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-full-control',
),
'GrantRead' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read',
),
'GrantReadACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read-acp',
),
'GrantWriteACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-write-acp',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'Metadata' => array(
'type' => 'object',
'location' => 'header',
'sentAs' => 'x-amz-meta-',
'additionalProperties' => array(
'type' => 'string',
),
),
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'StorageClass' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-storage-class',
),
'WebsiteRedirectLocation' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-website-redirect-location',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKey' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'SSEKMSKeyId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
'ACP' => array(
'type' => 'object',
'additionalProperties' => true,
),
),
),
'PutObjectAcl' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}{/Key*}?acl',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'PutObjectAclOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUTacl.html',
'data' => array(
'xmlRoot' => array(
'name' => 'AccessControlPolicy',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'ACL' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-acl',
),
'Grants' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'AccessControlList',
'items' => array(
'name' => 'Grant',
'type' => 'object',
'properties' => array(
'Grantee' => array(
'type' => 'object',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'EmailAddress' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
'Type' => array(
'required' => true,
'type' => 'string',
'sentAs' => 'xsi:type',
'data' => array(
'xmlAttribute' => true,
'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance',
),
),
'URI' => array(
'type' => 'string',
),
),
),
'Permission' => array(
'type' => 'string',
),
),
),
),
'Owner' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
),
),
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'GrantFullControl' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-full-control',
),
'GrantRead' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read',
),
'GrantReadACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-read-acp',
),
'GrantWrite' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-write',
),
'GrantWriteACP' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-grant-write-acp',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
'ACP' => array(
'type' => 'object',
'additionalProperties' => true,
),
),
'errorResponses' => array(
array(
'reason' => 'The specified key does not exist.',
'class' => 'NoSuchKeyException',
),
),
),
'RestoreObject' => array(
'httpMethod' => 'POST',
'uri' => '/{Bucket}{/Key*}?restore',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'RestoreObjectOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectRestore.html',
'data' => array(
'xmlRoot' => array(
'name' => 'RestoreRequest',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'VersionId' => array(
'type' => 'string',
'location' => 'query',
'sentAs' => 'versionId',
),
'Days' => array(
'required' => true,
'type' => 'numeric',
'location' => 'xml',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
),
'errorResponses' => array(
array(
'reason' => 'This operation is not allowed against this storage tier',
'class' => 'ObjectAlreadyInActiveTierErrorException',
),
),
),
'UploadPart' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}{/Key*}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'UploadPartOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html',
'data' => array(
'xmlRoot' => array(
'name' => 'UploadPartRequest',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'Body' => array(
'type' => array(
'string',
'object',
),
'location' => 'body',
),
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'ContentLength' => array(
'type' => 'numeric',
'location' => 'header',
'sentAs' => 'Content-Length',
),
'ContentMD5' => array(
'type' => array(
'string',
'boolean',
),
'location' => 'header',
'sentAs' => 'Content-MD5',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'PartNumber' => array(
'required' => true,
'type' => 'numeric',
'location' => 'query',
'sentAs' => 'partNumber',
),
'UploadId' => array(
'required' => true,
'type' => 'string',
'location' => 'query',
'sentAs' => 'uploadId',
),
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKey' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
),
),
'UploadPartCopy' => array(
'httpMethod' => 'PUT',
'uri' => '/{Bucket}{/Key*}',
'class' => 'Aws\\S3\\Command\\S3Command',
'responseClass' => 'UploadPartCopyOutput',
'responseType' => 'model',
'documentationUrl' => 'http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPartCopy.html',
'data' => array(
'xmlRoot' => array(
'name' => 'UploadPartCopyRequest',
'namespaces' => array(
'http://s3.amazonaws.com/doc/2006-03-01/',
),
),
),
'parameters' => array(
'Bucket' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
),
'CopySource' => array(
'required' => true,
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source',
),
'CopySourceIfMatch' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-if-match',
),
'CopySourceIfModifiedSince' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-if-modified-since',
),
'CopySourceIfNoneMatch' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-if-none-match',
),
'CopySourceIfUnmodifiedSince' => array(
'type' => array(
'object',
'string',
'integer',
),
'format' => 'date-time-http',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-if-unmodified-since',
),
'CopySourceRange' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-range',
),
'Key' => array(
'required' => true,
'type' => 'string',
'location' => 'uri',
'minLength' => 1,
'filters' => array(
'Aws\\S3\\S3Client::explodeKey',
),
),
'PartNumber' => array(
'required' => true,
'type' => 'numeric',
'location' => 'query',
'sentAs' => 'partNumber',
),
'UploadId' => array(
'required' => true,
'type' => 'string',
'location' => 'query',
'sentAs' => 'uploadId',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKey' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'CopySourceSSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-algorithm',
),
'CopySourceSSECustomerKey' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key',
),
'CopySourceSSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-server-side-encryption-customer-key-MD5',
),
'RequestPayer' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-payer',
),
'command.expects' => array(
'static' => true,
'default' => 'application/xml',
),
),
),
),
'models' => array(
'AbortMultipartUploadOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'CompleteMultipartUploadOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Location' => array(
'type' => 'string',
'location' => 'xml',
),
'Bucket' => array(
'type' => 'string',
'location' => 'xml',
),
'Key' => array(
'type' => 'string',
'location' => 'xml',
),
'Expiration' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-expiration',
),
'ETag' => array(
'type' => 'string',
'location' => 'xml',
),
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'VersionId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-version-id',
),
'SSEKMSKeyId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id',
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'CopyObjectOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'ETag' => array(
'type' => 'string',
'location' => 'xml',
),
'LastModified' => array(
'type' => 'string',
'location' => 'xml',
),
'Expiration' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-expiration',
),
'CopySourceVersionId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-version-id',
),
'VersionId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-version-id',
),
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'SSEKMSKeyId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id',
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'CreateBucketOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Location' => array(
'type' => 'string',
'location' => 'header',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'CreateMultipartUploadOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Bucket' => array(
'type' => 'string',
'location' => 'xml',
'sentAs' => 'Bucket',
),
'Key' => array(
'type' => 'string',
'location' => 'xml',
),
'UploadId' => array(
'type' => 'string',
'location' => 'xml',
),
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'SSEKMSKeyId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id',
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'DeleteBucketOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'DeleteBucketCorsOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'DeleteBucketLifecycleOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'DeleteBucketPolicyOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'DeleteBucketReplicationOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'DeleteBucketTaggingOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'DeleteBucketWebsiteOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'DeleteObjectOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'DeleteMarker' => array(
'type' => 'boolean',
'location' => 'header',
'sentAs' => 'x-amz-delete-marker',
),
'VersionId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-version-id',
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'DeleteObjectsOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Deleted' => array(
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'DeletedObject',
'type' => 'object',
'properties' => array(
'Key' => array(
'type' => 'string',
),
'VersionId' => array(
'type' => 'string',
),
'DeleteMarker' => array(
'type' => 'boolean',
),
'DeleteMarkerVersionId' => array(
'type' => 'string',
),
),
),
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'Errors' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'Error',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Error',
'type' => 'object',
'sentAs' => 'Error',
'properties' => array(
'Key' => array(
'type' => 'string',
),
'VersionId' => array(
'type' => 'string',
),
'Code' => array(
'type' => 'string',
),
'Message' => array(
'type' => 'string',
),
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetBucketAclOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Owner' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
),
),
'Grants' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'AccessControlList',
'items' => array(
'name' => 'Grant',
'type' => 'object',
'sentAs' => 'Grant',
'properties' => array(
'Grantee' => array(
'type' => 'object',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'EmailAddress' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
'Type' => array(
'type' => 'string',
'sentAs' => 'xsi:type',
'data' => array(
'xmlAttribute' => true,
'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance',
),
),
'URI' => array(
'type' => 'string',
),
),
),
'Permission' => array(
'type' => 'string',
),
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetBucketCorsOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'CORSRules' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'CORSRule',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'CORSRule',
'type' => 'object',
'sentAs' => 'CORSRule',
'properties' => array(
'AllowedHeaders' => array(
'type' => 'array',
'sentAs' => 'AllowedHeader',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'AllowedHeader',
'type' => 'string',
'sentAs' => 'AllowedHeader',
),
),
'AllowedMethods' => array(
'type' => 'array',
'sentAs' => 'AllowedMethod',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'AllowedMethod',
'type' => 'string',
'sentAs' => 'AllowedMethod',
),
),
'AllowedOrigins' => array(
'type' => 'array',
'sentAs' => 'AllowedOrigin',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'AllowedOrigin',
'type' => 'string',
'sentAs' => 'AllowedOrigin',
),
),
'ExposeHeaders' => array(
'type' => 'array',
'sentAs' => 'ExposeHeader',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'ExposeHeader',
'type' => 'string',
'sentAs' => 'ExposeHeader',
),
),
'MaxAgeSeconds' => array(
'type' => 'numeric',
),
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetBucketLifecycleOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Rules' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'Rule',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Rule',
'type' => 'object',
'sentAs' => 'Rule',
'properties' => array(
'Expiration' => array(
'type' => 'object',
'properties' => array(
'Date' => array(
'type' => 'string',
),
'Days' => array(
'type' => 'numeric',
),
),
),
'ID' => array(
'type' => 'string',
),
'Prefix' => array(
'type' => 'string',
),
'Status' => array(
'type' => 'string',
),
'Transition' => array(
'type' => 'object',
'properties' => array(
'Date' => array(
'type' => 'string',
),
'Days' => array(
'type' => 'numeric',
),
'StorageClass' => array(
'type' => 'string',
),
),
),
'NoncurrentVersionTransition' => array(
'type' => 'object',
'properties' => array(
'NoncurrentDays' => array(
'type' => 'numeric',
),
'StorageClass' => array(
'type' => 'string',
),
),
),
'NoncurrentVersionExpiration' => array(
'type' => 'object',
'properties' => array(
'NoncurrentDays' => array(
'type' => 'numeric',
),
),
),
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetBucketLifecycleConfigurationOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Rules' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'Rule',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'LifecycleRule',
'type' => 'object',
'sentAs' => 'Rule',
'properties' => array(
'Expiration' => array(
'type' => 'object',
'properties' => array(
'Date' => array(
'type' => 'string',
),
'Days' => array(
'type' => 'numeric',
),
),
),
'ID' => array(
'type' => 'string',
),
'Prefix' => array(
'type' => 'string',
),
'Status' => array(
'type' => 'string',
),
'Transitions' => array(
'type' => 'array',
'sentAs' => 'Transition',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Transition',
'type' => 'object',
'sentAs' => 'Transition',
'properties' => array(
'Date' => array(
'type' => 'string',
),
'Days' => array(
'type' => 'numeric',
),
'StorageClass' => array(
'type' => 'string',
),
),
),
),
'NoncurrentVersionTransitions' => array(
'type' => 'array',
'sentAs' => 'NoncurrentVersionTransition',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'NoncurrentVersionTransition',
'type' => 'object',
'sentAs' => 'NoncurrentVersionTransition',
'properties' => array(
'NoncurrentDays' => array(
'type' => 'numeric',
),
'StorageClass' => array(
'type' => 'string',
),
),
),
),
'NoncurrentVersionExpiration' => array(
'type' => 'object',
'properties' => array(
'NoncurrentDays' => array(
'type' => 'numeric',
),
),
),
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetBucketLocationOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Location' => array(
'type' => 'string',
'location' => 'body',
'filters' => array(
'strval',
'strip_tags',
'trim',
),
),
),
),
'GetBucketLoggingOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'LoggingEnabled' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'TargetBucket' => array(
'type' => 'string',
),
'TargetGrants' => array(
'type' => 'array',
'items' => array(
'name' => 'Grant',
'type' => 'object',
'sentAs' => 'Grant',
'properties' => array(
'Grantee' => array(
'type' => 'object',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'EmailAddress' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
'Type' => array(
'type' => 'string',
'sentAs' => 'xsi:type',
'data' => array(
'xmlAttribute' => true,
'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance',
),
),
'URI' => array(
'type' => 'string',
),
),
),
'Permission' => array(
'type' => 'string',
),
),
),
),
'TargetPrefix' => array(
'type' => 'string',
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'NotificationConfigurationDeprecated' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'TopicConfiguration' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'Events' => array(
'type' => 'array',
'sentAs' => 'Event',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
'sentAs' => 'Event',
),
),
'Event' => array(
'type' => 'string',
),
'Topic' => array(
'type' => 'string',
),
),
),
'QueueConfiguration' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'Event' => array(
'type' => 'string',
),
'Events' => array(
'type' => 'array',
'sentAs' => 'Event',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
'sentAs' => 'Event',
),
),
'Queue' => array(
'type' => 'string',
),
),
),
'CloudFunctionConfiguration' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'Event' => array(
'type' => 'string',
),
'Events' => array(
'type' => 'array',
'sentAs' => 'Event',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
'sentAs' => 'Event',
),
),
'CloudFunction' => array(
'type' => 'string',
),
'InvocationRole' => array(
'type' => 'string',
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'NotificationConfiguration' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'TopicConfigurations' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'TopicConfiguration',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'TopicConfiguration',
'type' => 'object',
'sentAs' => 'TopicConfiguration',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'TopicArn' => array(
'type' => 'string',
'sentAs' => 'Topic',
),
'Events' => array(
'type' => 'array',
'sentAs' => 'Event',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
'sentAs' => 'Event',
),
),
'Filter' => array(
'type' => 'object',
'properties' => array(
'Key' => array(
'type' => 'object',
'sentAs' => 'S3Key',
'properties' => array(
'FilterRules' => array(
'type' => 'array',
'sentAs' => 'FilterRule',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'FilterRule',
'type' => 'object',
'sentAs' => 'FilterRule',
'properties' => array(
'Name' => array(
'type' => 'string',
),
'Value' => array(
'type' => 'string',
),
),
),
),
),
),
),
),
),
),
),
'QueueConfigurations' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'QueueConfiguration',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'QueueConfiguration',
'type' => 'object',
'sentAs' => 'QueueConfiguration',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'QueueArn' => array(
'type' => 'string',
'sentAs' => 'Queue',
),
'Events' => array(
'type' => 'array',
'sentAs' => 'Event',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
'sentAs' => 'Event',
),
),
'Filter' => array(
'type' => 'object',
'properties' => array(
'Key' => array(
'type' => 'object',
'sentAs' => 'S3Key',
'properties' => array(
'FilterRules' => array(
'type' => 'array',
'sentAs' => 'FilterRule',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'FilterRule',
'type' => 'object',
'sentAs' => 'FilterRule',
'properties' => array(
'Name' => array(
'type' => 'string',
),
'Value' => array(
'type' => 'string',
),
),
),
),
),
),
),
),
),
),
),
'LambdaFunctionConfigurations' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'CloudFunctionConfiguration',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'LambdaFunctionConfiguration',
'type' => 'object',
'sentAs' => 'CloudFunctionConfiguration',
'properties' => array(
'Id' => array(
'type' => 'string',
),
'LambdaFunctionArn' => array(
'type' => 'string',
'sentAs' => 'CloudFunction',
),
'Events' => array(
'type' => 'array',
'sentAs' => 'Event',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Event',
'type' => 'string',
'sentAs' => 'Event',
),
),
'Filter' => array(
'type' => 'object',
'properties' => array(
'Key' => array(
'type' => 'object',
'sentAs' => 'S3Key',
'properties' => array(
'FilterRules' => array(
'type' => 'array',
'sentAs' => 'FilterRule',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'FilterRule',
'type' => 'object',
'sentAs' => 'FilterRule',
'properties' => array(
'Name' => array(
'type' => 'string',
),
'Value' => array(
'type' => 'string',
),
),
),
),
),
),
),
),
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetBucketPolicyOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Policy' => array(
'type' => 'string',
'instanceOf' => 'Guzzle\\Http\\EntityBody',
'location' => 'body',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetBucketReplicationOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Role' => array(
'type' => 'string',
'location' => 'xml',
),
'Rules' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'Rule',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'ReplicationRule',
'type' => 'object',
'sentAs' => 'Rule',
'properties' => array(
'ID' => array(
'type' => 'string',
),
'Prefix' => array(
'type' => 'string',
),
'Status' => array(
'type' => 'string',
),
'Destination' => array(
'type' => 'object',
'properties' => array(
'Bucket' => array(
'type' => 'string',
),
'StorageClass' => array(
'type' => 'string',
),
),
),
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetBucketRequestPaymentOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Payer' => array(
'type' => 'string',
'location' => 'xml',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetBucketTaggingOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'TagSet' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'Tag',
'type' => 'object',
'sentAs' => 'Tag',
'properties' => array(
'Key' => array(
'type' => 'string',
),
'Value' => array(
'type' => 'string',
),
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetBucketVersioningOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Status' => array(
'type' => 'string',
'location' => 'xml',
),
'MFADelete' => array(
'type' => 'string',
'location' => 'xml',
'sentAs' => 'MfaDelete',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetBucketWebsiteOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RedirectAllRequestsTo' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'HostName' => array(
'type' => 'string',
),
'Protocol' => array(
'type' => 'string',
),
),
),
'IndexDocument' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Suffix' => array(
'type' => 'string',
),
),
),
'ErrorDocument' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Key' => array(
'type' => 'string',
),
),
),
'RoutingRules' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'RoutingRule',
'type' => 'object',
'sentAs' => 'RoutingRule',
'properties' => array(
'Condition' => array(
'type' => 'object',
'properties' => array(
'HttpErrorCodeReturnedEquals' => array(
'type' => 'string',
),
'KeyPrefixEquals' => array(
'type' => 'string',
),
),
),
'Redirect' => array(
'type' => 'object',
'properties' => array(
'HostName' => array(
'type' => 'string',
),
'HttpRedirectCode' => array(
'type' => 'string',
),
'Protocol' => array(
'type' => 'string',
),
'ReplaceKeyPrefixWith' => array(
'type' => 'string',
),
'ReplaceKeyWith' => array(
'type' => 'string',
),
),
),
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetObjectOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Body' => array(
'type' => 'string',
'instanceOf' => 'Guzzle\\Http\\EntityBody',
'location' => 'body',
),
'DeleteMarker' => array(
'type' => 'boolean',
'location' => 'header',
'sentAs' => 'x-amz-delete-marker',
),
'AcceptRanges' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'accept-ranges',
),
'Expiration' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-expiration',
),
'Restore' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-restore',
),
'LastModified' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Last-Modified',
),
'ContentLength' => array(
'type' => 'numeric',
'location' => 'header',
'sentAs' => 'Content-Length',
),
'ETag' => array(
'type' => 'string',
'location' => 'header',
),
'MissingMeta' => array(
'type' => 'numeric',
'location' => 'header',
'sentAs' => 'x-amz-missing-meta',
),
'VersionId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-version-id',
),
'CacheControl' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Cache-Control',
),
'ContentDisposition' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Disposition',
),
'ContentEncoding' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Encoding',
),
'ContentLanguage' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Language',
),
'ContentRange' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Range',
),
'ContentType' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Type',
),
'Expires' => array(
'type' => 'string',
'location' => 'header',
),
'WebsiteRedirectLocation' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-website-redirect-location',
),
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'Metadata' => array(
'type' => 'object',
'location' => 'header',
'sentAs' => 'x-amz-meta-',
'additionalProperties' => array(
'type' => 'string',
),
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'SSEKMSKeyId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id',
),
'StorageClass' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-storage-class',
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'ReplicationStatus' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-replication-status',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetObjectAclOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Owner' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
),
),
'Grants' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'AccessControlList',
'items' => array(
'name' => 'Grant',
'type' => 'object',
'sentAs' => 'Grant',
'properties' => array(
'Grantee' => array(
'type' => 'object',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'EmailAddress' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
'Type' => array(
'type' => 'string',
'sentAs' => 'xsi:type',
'data' => array(
'xmlAttribute' => true,
'xmlNamespace' => 'http://www.w3.org/2001/XMLSchema-instance',
),
),
'URI' => array(
'type' => 'string',
),
),
),
'Permission' => array(
'type' => 'string',
),
),
),
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'GetObjectTorrentOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Body' => array(
'type' => 'string',
'instanceOf' => 'Guzzle\\Http\\EntityBody',
'location' => 'body',
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'HeadBucketOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'HeadObjectOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'DeleteMarker' => array(
'type' => 'boolean',
'location' => 'header',
'sentAs' => 'x-amz-delete-marker',
),
'AcceptRanges' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'accept-ranges',
),
'Expiration' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-expiration',
),
'Restore' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-restore',
),
'LastModified' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Last-Modified',
),
'ContentLength' => array(
'type' => 'numeric',
'location' => 'header',
'sentAs' => 'Content-Length',
),
'ETag' => array(
'type' => 'string',
'location' => 'header',
),
'MissingMeta' => array(
'type' => 'numeric',
'location' => 'header',
'sentAs' => 'x-amz-missing-meta',
),
'VersionId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-version-id',
),
'CacheControl' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Cache-Control',
),
'ContentDisposition' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Disposition',
),
'ContentEncoding' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Encoding',
),
'ContentLanguage' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Language',
),
'ContentType' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'Content-Type',
),
'Expires' => array(
'type' => 'string',
'location' => 'header',
),
'WebsiteRedirectLocation' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-website-redirect-location',
),
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'Metadata' => array(
'type' => 'object',
'location' => 'header',
'sentAs' => 'x-amz-meta-',
'additionalProperties' => array(
'type' => 'string',
),
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'SSEKMSKeyId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id',
),
'StorageClass' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-storage-class',
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'ReplicationStatus' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-replication-status',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'ListBucketsOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Buckets' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'Bucket',
'type' => 'object',
'sentAs' => 'Bucket',
'properties' => array(
'Name' => array(
'type' => 'string',
),
'CreationDate' => array(
'type' => 'string',
),
),
),
),
'Owner' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
),
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'ListMultipartUploadsOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Bucket' => array(
'type' => 'string',
'location' => 'xml',
),
'KeyMarker' => array(
'type' => 'string',
'location' => 'xml',
),
'UploadIdMarker' => array(
'type' => 'string',
'location' => 'xml',
),
'NextKeyMarker' => array(
'type' => 'string',
'location' => 'xml',
),
'Prefix' => array(
'type' => 'string',
'location' => 'xml',
),
'Delimiter' => array(
'type' => 'string',
'location' => 'xml',
),
'NextUploadIdMarker' => array(
'type' => 'string',
'location' => 'xml',
),
'MaxUploads' => array(
'type' => 'numeric',
'location' => 'xml',
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Uploads' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'Upload',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'MultipartUpload',
'type' => 'object',
'sentAs' => 'Upload',
'properties' => array(
'UploadId' => array(
'type' => 'string',
),
'Key' => array(
'type' => 'string',
),
'Initiated' => array(
'type' => 'string',
),
'StorageClass' => array(
'type' => 'string',
),
'Owner' => array(
'type' => 'object',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
),
),
'Initiator' => array(
'type' => 'object',
'properties' => array(
'ID' => array(
'type' => 'string',
),
'DisplayName' => array(
'type' => 'string',
),
),
),
),
),
),
'CommonPrefixes' => array(
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'CommonPrefix',
'type' => 'object',
'properties' => array(
'Prefix' => array(
'type' => 'string',
),
),
),
),
'EncodingType' => array(
'type' => 'string',
'location' => 'xml',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'ListObjectVersionsOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'KeyMarker' => array(
'type' => 'string',
'location' => 'xml',
),
'VersionIdMarker' => array(
'type' => 'string',
'location' => 'xml',
),
'NextKeyMarker' => array(
'type' => 'string',
'location' => 'xml',
),
'NextVersionIdMarker' => array(
'type' => 'string',
'location' => 'xml',
),
'Versions' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'Version',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'ObjectVersion',
'type' => 'object',
'sentAs' => 'Version',
'properties' => array(
'ETag' => array(
'type' => 'string',
),
'Size' => array(
'type' => 'numeric',
),
'StorageClass' => array(
'type' => 'string',
),
'Key' => array(
'type' => 'string',
),
'VersionId' => array(
'type' => 'string',
),
'IsLatest' => array(
'type' => 'boolean',
),
'LastModified' => array(
'type' => 'string',
),
'Owner' => array(
'type' => 'object',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
),
),
),
),
),
'DeleteMarkers' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'DeleteMarker',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'DeleteMarkerEntry',
'type' => 'object',
'sentAs' => 'DeleteMarker',
'properties' => array(
'Owner' => array(
'type' => 'object',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
),
),
'Key' => array(
'type' => 'string',
),
'VersionId' => array(
'type' => 'string',
),
'IsLatest' => array(
'type' => 'boolean',
),
'LastModified' => array(
'type' => 'string',
),
),
),
),
'Name' => array(
'type' => 'string',
'location' => 'xml',
),
'Prefix' => array(
'type' => 'string',
'location' => 'xml',
),
'Delimiter' => array(
'type' => 'string',
'location' => 'xml',
),
'MaxKeys' => array(
'type' => 'numeric',
'location' => 'xml',
),
'CommonPrefixes' => array(
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'CommonPrefix',
'type' => 'object',
'properties' => array(
'Prefix' => array(
'type' => 'string',
),
),
),
),
'EncodingType' => array(
'type' => 'string',
'location' => 'xml',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'ListObjectsOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
'NextMarker' => array(
'type' => 'string',
'location' => 'xml',
),
'Contents' => array(
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Object',
'type' => 'object',
'properties' => array(
'Key' => array(
'type' => 'string',
),
'LastModified' => array(
'type' => 'string',
),
'ETag' => array(
'type' => 'string',
),
'Size' => array(
'type' => 'numeric',
),
'StorageClass' => array(
'type' => 'string',
),
'Owner' => array(
'type' => 'object',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
),
),
),
),
),
'Name' => array(
'type' => 'string',
'location' => 'xml',
),
'Prefix' => array(
'type' => 'string',
'location' => 'xml',
),
'Delimiter' => array(
'type' => 'string',
'location' => 'xml',
),
'MaxKeys' => array(
'type' => 'numeric',
'location' => 'xml',
),
'CommonPrefixes' => array(
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'CommonPrefix',
'type' => 'object',
'properties' => array(
'Prefix' => array(
'type' => 'string',
),
),
),
),
'EncodingType' => array(
'type' => 'string',
'location' => 'xml',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'ListPartsOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Bucket' => array(
'type' => 'string',
'location' => 'xml',
),
'Key' => array(
'type' => 'string',
'location' => 'xml',
),
'UploadId' => array(
'type' => 'string',
'location' => 'xml',
),
'PartNumberMarker' => array(
'type' => 'numeric',
'location' => 'xml',
),
'NextPartNumberMarker' => array(
'type' => 'numeric',
'location' => 'xml',
),
'MaxParts' => array(
'type' => 'numeric',
'location' => 'xml',
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Parts' => array(
'type' => 'array',
'location' => 'xml',
'sentAs' => 'Part',
'data' => array(
'xmlFlattened' => true,
),
'items' => array(
'name' => 'Part',
'type' => 'object',
'sentAs' => 'Part',
'properties' => array(
'PartNumber' => array(
'type' => 'numeric',
),
'LastModified' => array(
'type' => 'string',
),
'ETag' => array(
'type' => 'string',
),
'Size' => array(
'type' => 'numeric',
),
),
),
),
'Initiator' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'ID' => array(
'type' => 'string',
),
'DisplayName' => array(
'type' => 'string',
),
),
),
'Owner' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'DisplayName' => array(
'type' => 'string',
),
'ID' => array(
'type' => 'string',
),
),
),
'StorageClass' => array(
'type' => 'string',
'location' => 'xml',
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketAclOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketCorsOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketLifecycleOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketLifecycleConfigurationOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketLoggingOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketNotificationOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketNotificationConfigurationOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketPolicyOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketReplicationOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketRequestPaymentOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketTaggingOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketVersioningOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutBucketWebsiteOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'PutObjectOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Expiration' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-expiration',
),
'ETag' => array(
'type' => 'string',
'location' => 'header',
),
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'VersionId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-version-id',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'SSEKMSKeyId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id',
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
'ObjectURL' => array(
),
),
),
'PutObjectAclOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'RestoreObjectOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'UploadPartOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'ETag' => array(
'type' => 'string',
'location' => 'header',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'SSEKMSKeyId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id',
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
'UploadPartCopyOutput' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'CopySourceVersionId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-copy-source-version-id',
),
'ETag' => array(
'type' => 'string',
'location' => 'xml',
),
'LastModified' => array(
'type' => 'string',
'location' => 'xml',
),
'ServerSideEncryption' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption',
),
'SSECustomerAlgorithm' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-algorithm',
),
'SSECustomerKeyMD5' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-customer-key-MD5',
),
'SSEKMSKeyId' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-server-side-encryption-aws-kms-key-id',
),
'RequestCharged' => array(
'type' => 'string',
'location' => 'header',
'sentAs' => 'x-amz-request-charged',
),
'RequestId' => array(
'location' => 'header',
'sentAs' => 'x-amz-request-id',
),
),
),
),
'iterators' => array(
'ListBuckets' => array(
'result_key' => 'Buckets',
),
'ListMultipartUploads' => array(
'limit_key' => 'MaxUploads',
'more_results' => 'IsTruncated',
'output_token' => array(
'NextKeyMarker',
'NextUploadIdMarker',
),
'input_token' => array(
'KeyMarker',
'UploadIdMarker',
),
'result_key' => array(
'Uploads',
'CommonPrefixes',
),
),
'ListObjectVersions' => array(
'more_results' => 'IsTruncated',
'limit_key' => 'MaxKeys',
'output_token' => array(
'NextKeyMarker',
'NextVersionIdMarker',
),
'input_token' => array(
'KeyMarker',
'VersionIdMarker',
),
'result_key' => array(
'Versions',
'DeleteMarkers',
'CommonPrefixes',
),
),
'ListObjects' => array(
'more_results' => 'IsTruncated',
'limit_key' => 'MaxKeys',
'output_token' => 'NextMarker',
'input_token' => 'Marker',
'result_key' => array(
'Contents',
'CommonPrefixes',
),
),
'ListParts' => array(
'more_results' => 'IsTruncated',
'limit_key' => 'MaxParts',
'output_token' => 'NextPartNumberMarker',
'input_token' => 'PartNumberMarker',
'result_key' => 'Parts',
),
),
'waiters' => array(
'__default__' => array(
'interval' => 5,
'max_attempts' => 20,
),
'BucketExists' => array(
'operation' => 'HeadBucket',
'success.type' => 'output',
'ignore_errors' => array(
'NoSuchBucket',
),
),
'BucketNotExists' => array(
'operation' => 'HeadBucket',
'success.type' => 'error',
'success.value' => 'NoSuchBucket',
),
'ObjectExists' => array(
'operation' => 'HeadObject',
'success.type' => 'output',
'ignore_errors' => array(
'NoSuchKey',
),
),
'ObjectNotExists' => array(
'operation' => 'HeadObject',
'success.type' => 'error',
'success.value' => 'NoSuchKey'
),
),
);
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Sync/DownloadSync.php 0000644 00000006516 15132770567 0017671 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Sync;
use Aws\Common\Exception\RuntimeException;
use Aws\S3\ResumableDownload;
/**
* Downloads and Amazon S3 bucket to a local directory
*/
class DownloadSync extends AbstractSync
{
protected function createTransferAction(\SplFileInfo $file)
{
$sourceFilename = $file->getPathname();
list($bucket, $key) = explode('/', substr($sourceFilename, 5), 2);
$filename = $this->options['source_converter']->convert($sourceFilename);
$this->createDirectory($filename);
// Some S3 buckets contains nested files under the same name as a directory
if (is_dir($filename)) {
return false;
}
// Allow a previously interrupted download to resume
if (file_exists($filename) && $this->options['resumable']) {
return new ResumableDownload($this->options['client'], $bucket, $key, $filename);
}
return $this->options['client']->getCommand('GetObject', array(
'Bucket' => $bucket,
'Key' => $key,
'SaveAs' => $filename
));
}
/**
* @codeCoverageIgnore
*/
protected function createDirectory($filename)
{
$directory = dirname($filename);
// Some S3 clients create empty files to denote directories. Remove these so that we can create the directory.
if (is_file($directory) && filesize($directory) == 0) {
unlink($directory);
}
// Create the directory if it does not exist
if (!is_dir($directory) && !mkdir($directory, 0777, true)) {
$errors = error_get_last();
throw new RuntimeException('Could not create directory: ' . esc_html($directory) . ' - ' . esc_html($errors['message']));
}
}
protected function filterCommands(array $commands)
{
// Build a list of all of the directories in each command so that we don't attempt to create an empty dir in
// the same parallel transfer as attempting to create a file in that dir
$dirs = array();
foreach ($commands as $command) {
$parts = array_values(array_filter(explode('/', $command['SaveAs'])));
for ($i = 0, $total = count($parts); $i < $total; $i++) {
$dir = '';
for ($j = 0; $j < $i; $j++) {
$dir .= '/' . $parts[$j];
}
if ($dir && !in_array($dir, $dirs)) {
$dirs[] = $dir;
}
}
}
return array_filter($commands, function ($command) use ($dirs) {
return !in_array($command['SaveAs'], $dirs);
});
}
protected function transferCommands(array $commands)
{
parent::transferCommands($this->filterCommands($commands));
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Sync/DownloadSyncBuilder.php 0000644 00000010124 15132770567 0021166 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Sync;
use Aws\Common\Exception\RuntimeException;
use Aws\S3\ResumableDownload;
use Guzzle\Common\Event;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Service\Command\CommandInterface;
class DownloadSyncBuilder extends AbstractSyncBuilder
{
/** @var bool */
protected $resumable = false;
/** @var string */
protected $directory;
/** @var int Number of files that can be transferred concurrently */
protected $concurrency = 5;
/**
* Set the directory where the objects from be downloaded to
*
* @param string $directory Directory
*
* @return $this
*/
public function setDirectory($directory)
{
$this->directory = $directory;
return $this;
}
/**
* Call this function to allow partial downloads to be resumed if the download was previously interrupted
*
* @return self
*/
public function allowResumableDownloads()
{
$this->resumable = true;
return $this;
}
protected function specificBuild()
{
$sync = new DownloadSync(array(
'client' => $this->client,
'bucket' => $this->bucket,
'iterator' => $this->sourceIterator,
'source_converter' => $this->sourceConverter,
'target_converter' => $this->targetConverter,
'concurrency' => $this->concurrency,
'resumable' => $this->resumable,
'directory' => $this->directory
));
return $sync;
}
protected function getTargetIterator()
{
if (!$this->directory) {
throw new RuntimeException('A directory is required');
}
if (!is_dir($this->directory) && !mkdir($this->directory, 0777, true)) {
// @codeCoverageIgnoreStart
throw new RuntimeException('Unable to create root download directory: ' . esc_html($this->directory));
// @codeCoverageIgnoreEnd
}
return $this->filterIterator(
new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->directory))
);
}
protected function getDefaultSourceConverter()
{
return new KeyConverter(
"s3://{$this->bucket}/{$this->baseDir}",
$this->directory . DIRECTORY_SEPARATOR, $this->delimiter
);
}
protected function getDefaultTargetConverter()
{
return new KeyConverter("s3://{$this->bucket}/{$this->baseDir}", '', $this->delimiter);
}
protected function assertFileIteratorSet()
{
$this->sourceIterator = $this->sourceIterator ?: $this->createS3Iterator();
}
protected function addDebugListener(AbstractSync $sync, $resource)
{
$sync->getEventDispatcher()->addListener(UploadSync::BEFORE_TRANSFER, function (Event $e) use ($resource) {
if ($e['command'] instanceof CommandInterface) {
$from = $e['command']['Bucket'] . '/' . $e['command']['Key'];
$to = $e['command']['SaveAs'] instanceof EntityBodyInterface
? $e['command']['SaveAs']->getUri()
: $e['command']['SaveAs'];
fwrite($resource, "Downloading {$from} -> {$to}\n");
} elseif ($e['command'] instanceof ResumableDownload) {
$from = $e['command']->getBucket() . '/' . $e['command']->getKey();
$to = $e['command']->getFilename();
fwrite($resource, "Resuming {$from} -> {$to}\n");
}
});
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Sync/AbstractSync.php 0000644 00000007745 15132770567 0017672 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Sync;
use Aws\S3\S3Client;
use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Common\Collection;
use Guzzle\Iterator\ChunkedIterator;
use Guzzle\Service\Command\CommandInterface;
abstract class AbstractSync extends AbstractHasDispatcher
{
const BEFORE_TRANSFER = 's3.sync.before_transfer';
const AFTER_TRANSFER = 's3.sync.after_transfer';
/** @var Collection */
protected $options;
/**
* @param array $options Associative array of options:
* - client: (S3Client) used to transfer requests
* - bucket: (string) Amazon S3 bucket
* - iterator: (\Iterator) Iterator that yields SplFileInfo objects to transfer
* - source_converter: (FilenameConverterInterface) Converter used to convert filenames
* - *: Any other options required by subclasses
*/
public function __construct(array $options)
{
$this->options = Collection::fromConfig(
$options,
array('concurrency' => 10),
array('client', 'bucket', 'iterator', 'source_converter')
);
$this->init();
}
public static function getAllEvents()
{
return array(self::BEFORE_TRANSFER, self::AFTER_TRANSFER);
}
/**
* Begin transferring files
*/
public function transfer()
{
// Pull out chunks of uploads to upload in parallel
$iterator = new ChunkedIterator($this->options['iterator'], $this->options['concurrency']);
foreach ($iterator as $files) {
$this->transferFiles($files);
}
}
/**
* Create a command or special transfer action for the
*
* @param \SplFileInfo $file File used to build the transfer
*
* @return CommandInterface|callable
*/
abstract protected function createTransferAction(\SplFileInfo $file);
/**
* Hook to initialize subclasses
* @codeCoverageIgnore
*/
protected function init() {}
/**
* Process and transfer a group of files
*
* @param array $files Files to transfer
*/
protected function transferFiles(array $files)
{
// Create the base event data object
$event = array('sync' => $this, 'client' => $this->options['client']);
$commands = array();
foreach ($files as $file) {
if ($action = $this->createTransferAction($file)) {
$event = array('command' => $action, 'file' => $file) + $event;
$this->dispatch(self::BEFORE_TRANSFER, $event);
if ($action instanceof CommandInterface) {
$commands[] = $action;
} elseif (is_callable($action)) {
$action();
$this->dispatch(self::AFTER_TRANSFER, $event);
}
}
}
$this->transferCommands($commands);
}
/**
* Transfer an array of commands in parallel
*
* @param array $commands Commands to transfer
*/
protected function transferCommands(array $commands)
{
if ($commands) {
$this->options['client']->execute($commands);
// Notify listeners that each command finished
$event = array('sync' => $this, 'client' => $this->options['client']);
foreach ($commands as $command) {
$event['command'] = $command;
$this->dispatch(self::AFTER_TRANSFER, $event);
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Sync/KeyConverter.php 0000644 00000004421 15132770567 0017676 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Sync;
/**
* Converts filenames from one system to another
*/
class KeyConverter implements FilenameConverterInterface
{
/** @var string Directory separator for Amazon S3 keys */
protected $delimiter;
/** @var string Prefix to prepend to each Amazon S3 object key */
protected $prefix;
/** @var string Base directory to remove from each file path before converting to an object key */
protected $baseDir;
/**
* @param string $baseDir Base directory to remove from each converted name
* @param string $prefix Amazon S3 prefix
* @param string $delimiter Directory separator used with generated names
*/
public function __construct($baseDir = '', $prefix = '', $delimiter = '/')
{
$this->baseDir = (string) $baseDir;
$this->prefix = $prefix;
$this->delimiter = $delimiter;
}
public function convert($filename)
{
$key = $filename;
// Remove base directory from the key (only the first occurrence)
if ($this->baseDir && (false !== $pos = strpos($filename, $this->baseDir))) {
$key = substr_replace($key, '', $pos, strlen($this->baseDir));
}
// Replace Windows directory separators to become Unix style, and convert that to the custom dir separator
$key = str_replace('/', $this->delimiter, str_replace('\\', '/', $key));
// Add the key prefix and remove double slashes that are not in the protocol (e.g. prefixed with ":")
$delim = preg_quote($this->delimiter);
$key = preg_replace(
"#(?<!:){$delim}{$delim}#",
$this->delimiter,
$this->prefix . $key
);
return $key;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Sync/UploadSync.php 0000644 00000005704 15132770567 0017344 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Sync;
use Aws\Common\Exception\RuntimeException;
use Aws\S3\Model\MultipartUpload\UploadBuilder;
use Aws\S3\Model\MultipartUpload\AbstractTransfer;
use Guzzle\Http\EntityBody;
/**
* Uploads a local directory tree to Amazon S3
*/
class UploadSync extends AbstractSync
{
const BEFORE_MULTIPART_BUILD = 's3.sync.before_multipart_build';
protected function init()
{
if (null == $this->options['multipart_upload_size']) {
$this->options['multipart_upload_size'] = AbstractTransfer::MIN_PART_SIZE;
}
}
protected function createTransferAction(\SplFileInfo $file)
{
// Open the file for reading
$filename = $file->getRealPath() ?: $file->getPathName();
if (!($resource = fopen($filename, 'r'))) {
// @codeCoverageIgnoreStart
throw new RuntimeException('Could not open ' . esc_html($file->getPathname()) . ' for reading');
// @codeCoverageIgnoreEnd
}
$key = $this->options['source_converter']->convert($filename);
$body = EntityBody::factory($resource);
// Determine how the ACL should be applied
if ($acl = $this->options['acl']) {
$aclType = is_string($this->options['acl']) ? 'ACL' : 'ACP';
} else {
$acl = 'private';
$aclType = 'ACL';
}
// Use a multi-part upload if the file is larger than the cutoff size and is a regular file
if ($body->getWrapper() == 'plainfile' && $file->getSize() >= $this->options['multipart_upload_size']) {
$builder = UploadBuilder::newInstance()
->setBucket($this->options['bucket'])
->setKey($key)
->setMinPartSize($this->options['multipart_upload_size'])
->setOption($aclType, $acl)
->setClient($this->options['client'])
->setSource($body)
->setConcurrency($this->options['concurrency']);
$this->dispatch(
self::BEFORE_MULTIPART_BUILD,
array('builder' => $builder, 'file' => $file)
);
return $builder->build();
}
return $this->options['client']->getCommand('PutObject', array(
'Bucket' => $this->options['bucket'],
'Key' => $key,
'Body' => $body,
$aclType => $acl
));
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Sync/FilenameConverterInterface.php 0000644 00000001625 15132770567 0022512 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Sync;
/**
* Converts filenames from one system to another (e.g. local to Amazon S3)
*/
interface FilenameConverterInterface
{
/**
* Convert a filename
*
* @param string $filename Name of the file to convert
*
* @return string
*/
public function convert($filename);
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Sync/AbstractSyncBuilder.php 0000644 00000030352 15132770567 0021167 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Sync;
use Aws\Common\Exception\RuntimeException;
use Aws\Common\Exception\UnexpectedValueException;
use Aws\S3\S3Client;
use Aws\S3\Iterator\OpendirIterator;
use Guzzle\Common\Event;
use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Iterator\FilterIterator;
use Guzzle\Service\Command\CommandInterface;
abstract class AbstractSyncBuilder
{
/** @var \Iterator Iterator that returns SplFileInfo objects to upload */
protected $sourceIterator;
/** @var S3Client Amazon S3 client used to send requests */
protected $client;
/** @var string Bucket used with the transfer */
protected $bucket;
/** @var int Number of files that can be transferred concurrently */
protected $concurrency = 10;
/** @var array Custom parameters to add to each operation sent while transferring */
protected $params = array();
/** @var FilenameConverterInterface */
protected $sourceConverter;
/** @var FilenameConverterInterface */
protected $targetConverter;
/** @var string Prefix at prepend to each Amazon S3 object key */
protected $keyPrefix = '';
/** @var string Directory separator for Amazon S3 keys */
protected $delimiter = '/';
/** @var string Base directory to remove from each file path before converting to an object name or file name */
protected $baseDir;
/** @var bool Whether or not to only transfer modified or new files */
protected $forcing = false;
/** @var bool Whether or not debug output is enable */
protected $debug;
/**
* @return static
*/
public static function getInstance()
{
return new static();
}
/**
* Set the bucket to use with the sync
*
* @param string $bucket Amazon S3 bucket name
*
* @return $this
*/
public function setBucket($bucket)
{
$this->bucket = $bucket;
return $this;
}
/**
* Set the Amazon S3 client object that will send requests
*
* @param S3Client $client Amazon S3 client
*
* @return $this
*/
public function setClient(S3Client $client)
{
$this->client = $client;
return $this;
}
/**
* Set a custom iterator that returns \SplFileInfo objects for the source data
*
* @param \Iterator $iterator
*
* @return $this
*/
public function setSourceIterator(\Iterator $iterator)
{
$this->sourceIterator = $iterator;
return $this;
}
/**
* Set a custom object key provider instead of building one internally
*
* @param FileNameConverterInterface $converter Filename to object key provider
*
* @return $this
*/
public function setSourceFilenameConverter(FilenameConverterInterface $converter)
{
$this->sourceConverter = $converter;
return $this;
}
/**
* Set a custom object key provider instead of building one internally
*
* @param FileNameConverterInterface $converter Filename to object key provider
*
* @return $this
*/
public function setTargetFilenameConverter(FilenameConverterInterface $converter)
{
$this->targetConverter = $converter;
return $this;
}
/**
* Set the base directory of the files being transferred. The base directory is removed from each file path before
* converting the file path to an object key or vice versa.
*
* @param string $baseDir Base directory, which will be deleted from each uploaded object key
*
* @return $this
*/
public function setBaseDir($baseDir)
{
$this->baseDir = $baseDir;
return $this;
}
/**
* Specify a prefix to prepend to each Amazon S3 object key or the prefix where object are stored in a bucket
*
* Can be used to upload files to a pseudo sub-folder key or only download files from a pseudo sub-folder
*
* @param string $keyPrefix Prefix for each uploaded key
*
* @return $this
*/
public function setKeyPrefix($keyPrefix)
{
// Removing leading slash
$this->keyPrefix = ltrim($keyPrefix, '/');
return $this;
}
/**
* Specify the delimiter used for the targeted filesystem (default delimiter is "/")
*
* @param string $delimiter Delimiter to use to separate paths
*
* @return $this
*/
public function setDelimiter($delimiter)
{
$this->delimiter = $delimiter;
return $this;
}
/**
* Specify an array of operation parameters to apply to each operation executed by the sync object
*
* @param array $params Associative array of PutObject (upload) GetObject (download) parameters
*
* @return $this
*/
public function setOperationParams(array $params)
{
$this->params = $params;
return $this;
}
/**
* Set the number of files that can be transferred concurrently
*
* @param int $concurrency Number of concurrent transfers
*
* @return $this
*/
public function setConcurrency($concurrency)
{
$this->concurrency = $concurrency;
return $this;
}
/**
* Set to true to force transfers even if a file already exists and has not changed
*
* @param bool $force Set to true to force transfers without checking if it has changed
*
* @return $this
*/
public function force($force = false)
{
$this->forcing = (bool) $force;
return $this;
}
/**
* Enable debug mode
*
* @param bool|resource $enabledOrResource Set to true or false to enable or disable debug output. Pass an opened
* fopen resource to write to instead of writing to standard out.
* @return $this
*/
public function enableDebugOutput($enabledOrResource = true)
{
$this->debug = $enabledOrResource;
return $this;
}
/**
* Add a filename filter that uses a regular expression to filter out files that you do not wish to transfer.
*
* @param string $search Regular expression search (in preg_match format). Any filename that matches this regex
* will not be transferred.
* @return $this
*/
public function addRegexFilter($search)
{
$this->assertFileIteratorSet();
$this->sourceIterator = new FilterIterator($this->sourceIterator, function ($i) use ($search) {
return !preg_match($search, (string) $i);
});
$this->sourceIterator->rewind();
return $this;
}
/**
* Builds a UploadSync or DownloadSync object
*
* @return AbstractSync
*/
public function build()
{
$this->validateRequirements();
$this->sourceConverter = $this->sourceConverter ?: $this->getDefaultSourceConverter();
$this->targetConverter = $this->targetConverter ?: $this->getDefaultTargetConverter();
// Only wrap the source iterator in a changed files iterator if we are not forcing the transfers
if (!$this->forcing) {
$this->sourceIterator->rewind();
$this->sourceIterator = new ChangedFilesIterator(
new \NoRewindIterator($this->sourceIterator),
$this->getTargetIterator(),
$this->sourceConverter,
$this->targetConverter
);
$this->sourceIterator->rewind();
}
$sync = $this->specificBuild();
if ($this->params) {
$this->addCustomParamListener($sync);
}
if ($this->debug) {
$this->addDebugListener($sync, is_bool($this->debug) ? STDOUT : $this->debug);
}
return $sync;
}
/**
* Hook to implement in subclasses
*
* @return AbstractSync
*/
abstract protected function specificBuild();
/**
* @return \Iterator
*/
abstract protected function getTargetIterator();
/**
* @return FilenameConverterInterface
*/
abstract protected function getDefaultSourceConverter();
/**
* @return FilenameConverterInterface
*/
abstract protected function getDefaultTargetConverter();
/**
* Add a listener to the sync object to output debug information while transferring
*
* @param AbstractSync $sync Sync object to listen to
* @param resource $resource Where to write debug messages
*/
abstract protected function addDebugListener(AbstractSync $sync, $resource);
/**
* Validate that the builder has the minimal requirements
*
* @throws RuntimeException if the builder is not configured completely
*/
protected function validateRequirements()
{
if (!$this->client) {
throw new RuntimeException('No client was provided');
}
if (!$this->bucket) {
throw new RuntimeException('No bucket was provided');
}
$this->assertFileIteratorSet();
}
/**
* Ensure that the base file iterator has been provided
*
* @throws RuntimeException
*/
protected function assertFileIteratorSet()
{
// Interesting... Need to use isset because: Object of class GlobIterator could not be converted to boolean
if (!isset($this->sourceIterator)) {
throw new RuntimeException('A source file iterator must be specified');
}
}
/**
* Wraps a generated iterator in a filter iterator that removes directories
*
* @param \Iterator $iterator Iterator to wrap
*
* @return \Iterator
* @throws UnexpectedValueException
*/
protected function filterIterator(\Iterator $iterator)
{
$f = new FilterIterator($iterator, function ($i) {
if (!$i instanceof \SplFileInfo) {
throw new UnexpectedValueException('All iterators for UploadSync must return SplFileInfo objects');
}
return $i->isFile();
});
$f->rewind();
return $f;
}
/**
* Add the custom param listener to a transfer object
*
* @param HasDispatcherInterface $sync
*/
protected function addCustomParamListener(HasDispatcherInterface $sync)
{
$params = $this->params;
$sync->getEventDispatcher()->addListener(
UploadSync::BEFORE_TRANSFER,
function (Event $e) use ($params) {
if ($e['command'] instanceof CommandInterface) {
$e['command']->overwriteWith($params);
}
}
);
}
/**
* Create an Amazon S3 file iterator based on the given builder settings
*
* @return OpendirIterator
*/
protected function createS3Iterator()
{
// Ensure that the stream wrapper is registered
$this->client->registerStreamWrapper();
// Calculate the opendir() bucket and optional key prefix location
$dir = "s3://{$this->bucket}";
if ($this->keyPrefix) {
$dir .= '/' . ltrim($this->keyPrefix, '/ ');
}
// Use opendir so that we can pass stream context to the iterator
$dh = opendir($dir, stream_context_create(array(
's3' => array(
'delimiter' => '',
'listFilter' => function ($obj) {
// Ensure that we do not try to download a glacier object.
return !isset($obj['StorageClass']) ||
$obj['StorageClass'] != 'GLACIER';
}
)
)));
// Add the trailing slash for the OpendirIterator concatenation
if (!$this->keyPrefix) {
$dir .= '/';
}
return $this->filterIterator(new \NoRewindIterator(new OpendirIterator($dh, $dir)));
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Sync/UploadSyncBuilder.php 0000644 00000013221 15132770567 0020644 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Sync;
use FilesystemIterator as FI;
use Aws\Common\Model\MultipartUpload\AbstractTransfer;
use Aws\S3\Model\Acp;
use Guzzle\Common\HasDispatcherInterface;
use Guzzle\Common\Event;
use Guzzle\Service\Command\CommandInterface;
class UploadSyncBuilder extends AbstractSyncBuilder
{
/** @var string|Acp Access control policy to set on each object */
protected $acp = 'private';
/** @var int */
protected $multipartUploadSize;
/**
* Set the path that contains files to recursively upload to Amazon S3
*
* @param string $path Path that contains files to upload
*
* @return $this
*/
public function uploadFromDirectory($path)
{
$this->baseDir = realpath($path);
$this->sourceIterator = $this->filterIterator(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(
$path,
FI::SKIP_DOTS | FI::UNIX_PATHS | FI::FOLLOW_SYMLINKS
)));
return $this;
}
/**
* Set a glob expression that will match files to upload to Amazon S3
*
* @param string $glob Glob expression
*
* @return $this
* @link http://www.php.net/manual/en/function.glob.php
*/
public function uploadFromGlob($glob)
{
$this->sourceIterator = $this->filterIterator(
new \GlobIterator($glob, FI::SKIP_DOTS | FI::UNIX_PATHS | FI::FOLLOW_SYMLINKS)
);
return $this;
}
/**
* Set a canned ACL to apply to each uploaded object
*
* @param string $acl Canned ACL for each upload
*
* @return $this
*/
public function setAcl($acl)
{
$this->acp = $acl;
return $this;
}
/**
* Set an Access Control Policy to apply to each uploaded object
*
* @param Acp $acp Access control policy
*
* @return $this
*/
public function setAcp(Acp $acp)
{
$this->acp = $acp;
return $this;
}
/**
* Set the multipart upload size threshold. When the size of a file exceeds this value, the file will be uploaded
* using a multipart upload.
*
* @param int $size Size threshold
*
* @return $this
*/
public function setMultipartUploadSize($size)
{
$this->multipartUploadSize = $size;
return $this;
}
protected function specificBuild()
{
$sync = new UploadSync(array(
'client' => $this->client,
'bucket' => $this->bucket,
'iterator' => $this->sourceIterator,
'source_converter' => $this->sourceConverter,
'target_converter' => $this->targetConverter,
'concurrency' => $this->concurrency,
'multipart_upload_size' => $this->multipartUploadSize,
'acl' => $this->acp
));
return $sync;
}
protected function addCustomParamListener(HasDispatcherInterface $sync)
{
// Handle the special multi-part upload event
parent::addCustomParamListener($sync);
$params = $this->params;
$sync->getEventDispatcher()->addListener(
UploadSync::BEFORE_MULTIPART_BUILD,
function (Event $e) use ($params) {
foreach ($params as $k => $v) {
$e['builder']->setOption($k, $v);
}
}
);
}
protected function getTargetIterator()
{
return $this->createS3Iterator();
}
protected function getDefaultSourceConverter()
{
return new KeyConverter($this->baseDir, $this->keyPrefix . $this->delimiter, $this->delimiter);
}
protected function getDefaultTargetConverter()
{
return new KeyConverter('s3://' . $this->bucket . '/', '', DIRECTORY_SEPARATOR);
}
protected function addDebugListener(AbstractSync $sync, $resource)
{
$sync->getEventDispatcher()->addListener(UploadSync::BEFORE_TRANSFER, function (Event $e) use ($resource) {
$c = $e['command'];
if ($c instanceof CommandInterface) {
$uri = $c['Body']->getUri();
$size = $c['Body']->getSize();
fwrite($resource, "Uploading {$uri} -> {$c['Key']} ({$size} bytes)\n");
return;
}
// Multipart upload
$body = $c->getSource();
$totalSize = $body->getSize();
$progress = 0;
fwrite($resource, "Beginning multipart upload: " . $body->getUri() . ' -> ');
fwrite($resource, $c->getState()->getFromId('Key') . " ({$totalSize} bytes)\n");
$c->getEventDispatcher()->addListener(
AbstractTransfer::BEFORE_PART_UPLOAD,
function ($e) use (&$progress, $totalSize, $resource) {
$command = $e['command'];
$size = $command['Body']->getContentLength();
$percentage = number_format(($progress / $totalSize) * 100, 2);
fwrite($resource, "- Part {$command['PartNumber']} ({$size} bytes, {$percentage}%)\n");
$progress += $size;
}
);
});
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Sync/ChangedFilesIterator.php 0000644 00000007557 15132770567 0021321 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Sync;
/**
* Iterator used to filter an internal iterator to only yield files that do not exist in the target iterator or files
* that have changed
*/
class ChangedFilesIterator extends \FilterIterator
{
/** @var \Iterator */
protected $sourceIterator;
/** @var \Iterator */
protected $targetIterator;
/** @var FilenameConverterInterface */
protected $sourceConverter;
/** @var FilenameConverterInterface */
protected $targetConverter;
/** @var array Previously loaded data */
protected $cache = array();
/**
* @param \Iterator $sourceIterator Iterator to wrap and filter
* @param \Iterator $targetIterator Iterator used to compare against the source iterator
* @param FilenameConverterInterface $sourceConverter Key converter to convert source to target keys
* @param FilenameConverterInterface $targetConverter Key converter to convert target to source keys
*/
public function __construct(
\Iterator $sourceIterator,
\Iterator $targetIterator,
FilenameConverterInterface $sourceConverter,
FilenameConverterInterface $targetConverter
) {
$this->targetIterator = $targetIterator;
$this->sourceConverter = $sourceConverter;
$this->targetConverter = $targetConverter;
parent::__construct($sourceIterator);
}
public function accept()
{
$current = $this->current();
$key = $this->sourceConverter->convert($this->normalize($current));
if (!($data = $this->getTargetData($key))) {
return true;
}
// Ensure the Content-Length matches and it hasn't been modified since the mtime
return $current->getSize() != $data[0] || $current->getMTime() > $data[1];
}
/**
* Returns an array of the files from the target iterator that were not found in the source iterator
*
* @return array
*/
public function getUnmatched()
{
return array_keys($this->cache);
}
/**
* Get key information from the target iterator for a particular filename
*
* @param string $key Target iterator filename
*
* @return array|bool Returns an array of data, or false if the key is not in the iterator
*/
protected function getTargetData($key)
{
$key = $this->cleanKey($key);
if (isset($this->cache[$key])) {
$result = $this->cache[$key];
unset($this->cache[$key]);
return $result;
}
$it = $this->targetIterator;
while ($it->valid()) {
$value = $it->current();
$data = array($value->getSize(), $value->getMTime());
$filename = $this->targetConverter->convert($this->normalize($value));
$filename = $this->cleanKey($filename);
if ($filename == $key) {
return $data;
}
$this->cache[$filename] = $data;
$it->next();
}
return false;
}
private function normalize($current)
{
$asString = (string) $current;
return strpos($asString, 's3://') === 0
? $asString
: $current->getRealPath();
}
private function cleanKey($key)
{
return ltrim($key, '/');
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/SocketTimeoutChecker.php 0000644 00000004321 15132770567 0020425 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3;
use Guzzle\Http\Exception\HttpException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Backoff\BackoffStrategyInterface;
use Guzzle\Plugin\Backoff\AbstractBackoffStrategy;
/**
* Custom S3 exponential backoff checking use to retry 400 responses containing the following reason phrase:
* "Your socket connection to the server was not read from or written to within the timeout period.".
* This error has been reported as intermittent/random, and in most cases, seems to occur during the middle of a
* transfer. This plugin will attempt to retry these failed requests, and if using a local file, will clear the
* stat cache of the file and set a new content-length header on the upload.
*/
class SocketTimeoutChecker extends AbstractBackoffStrategy
{
const ERR = 'Your socket connection to the server was not read from or written to within the timeout period';
/**
* {@inheridoc}
*/
public function __construct(BackoffStrategyInterface $next = null)
{
if ($next) {
$this->setNext($next);
}
}
/**
* {@inheridoc}
*/
public function makesDecision()
{
return true;
}
/**
* {@inheritdoc}
*/
protected function getDelay(
$retries,
RequestInterface $request,
Response $response = null,
HttpException $e = null
) {
if ($response
&& $response->getStatusCode() == 400
&& strpos($response->getBody(), self::ERR)
) {
return true;
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NoSuchLifecycleConfigurationException.php 0000644 00000001347 15132770567 0025732 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The lifecycle configuration does not exist.
*/
class NoSuchLifecycleConfigurationException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/UserKeyMustBeSpecifiedException.php 0000644 00000001446 15132770567 0024506 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The bucket POST must contain the specified field name. If it is specified, please check the order of the fields.
*/
class UserKeyMustBeSpecifiedException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidBucketNameException.php 0000644 00000001323 15132770567 0023502 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The specified bucket is not valid.
*/
class InvalidBucketNameException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/BucketAlreadyExistsException.php 0000644 00000001507 15132770567 0024100 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.
*/
class BucketAlreadyExistsException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/AmbiguousGrantByEmailAddressException.php 0000644 00000001405 15132770567 0025656 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The e-mail address you provided is associated with more than one account.
*/
class AmbiguousGrantByEmailAddressException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/DeleteMultipleObjectsException.php 0000644 00000002545 15132770567 0024414 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Exception thrown when errors occur in a DeleteMultipleObjects request
*/
class DeleteMultipleObjectsException extends S3Exception
{
/**
* @var array Array of errors
*/
protected $errors = array();
/**
* @param array $errors Array of errors
*/
public function __construct(array $errors = array())
{
parent::__construct('Unable to delete certain keys when executing a DeleteMultipleObjects request');
$this->errors = $errors;
}
/**
* Get the errored objects
*
* @return array Returns an array of associative arrays, each containing
* a 'Code', 'Message', and 'Key' key.
*/
public function getErrors()
{
return $this->errors;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InlineDataTooLargeException.php 0000644 00000001337 15132770567 0023627 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Inline data exceeds the maximum allowed size.
*/
class InlineDataTooLargeException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/ServiceUnavailableException.php 0000644 00000001322 15132770567 0023720 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Please reduce your request rate.
*/
class ServiceUnavailableException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NoSuchCORSConfigurationException.php 0000644 00000001357 15132770567 0024602 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The specified bucket does not have a CORs configuration.
*/
class NoSuchCORSConfigurationException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/CrossLocationLoggingProhibitedException.php 0000644 00000001474 15132770567 0026267 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Cross location logging not allowed. Buckets in one geographic location cannot log information to a bucket in another location.
*/
class CrossLocationLoggingProhibitedException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MalformedXMLException.php 0000644 00000001626 15132770567 0022452 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* This happens when the user sends a malformed xml (xml that doesn't conform to the published xsd) for the configuration. The error message is, "The XML you provided was not well-formed or did not validate against our published schema."
*/
class MalformedXMLException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/BadDigestException.php 0000644 00000001346 15132770567 0022010 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The Content-MD5 you specified did not match what we received.
*/
class BadDigestException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/ObjectAlreadyInActiveTierErrorException.php 0000644 00000001365 15132770567 0026154 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* This operation is not allowed against this storage tier
*/
class ObjectAlreadyInActiveTierErrorException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/SlowDownException.php 0000644 00000001310 15132770567 0021725 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Please reduce your request rate.
*/
class SlowDownException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidRequestException.php 0000644 00000001342 15132770567 0023115 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* SOAP requests must be made over an HTTPS connection.
*/
class InvalidRequestException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NotImplementedException.php 0000644 00000001362 15132770567 0023104 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* A header you provided implies functionality that is not implemented.
*/
class NotImplementedException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MissingSecurityHeaderException.php 0000644 00000001340 15132770567 0024426 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Your request was missing a required header.
*/
class MissingSecurityHeaderException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidURIException.php 0000644 00000001313 15132770567 0022122 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Couldn't parse the specified URI.
*/
class InvalidURIException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NoLoggingStatusForKeyException.php 0000644 00000001367 15132770567 0024374 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* There is no such thing as a logging status sub-resource for a key.
*/
class NoLoggingStatusForKeyException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InternalErrorException.php 0000644 00000001340 15132770567 0022742 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* We encountered an internal error. Please try again.
*/
class InternalErrorException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NoSuchBucketException.php 0000644 00000001320 15132770567 0022507 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The specified bucket does not exist.
*/
class NoSuchBucketException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MalformedACLErrorException.php 0000644 00000001413 15132770567 0023415 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The XML you provided was not well-formed or did not validate against our published schema.
*/
class MalformedACLErrorException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/PermanentRedirectException.php 0000644 00000001472 15132770567 0023575 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.
*/
class PermanentRedirectException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NotSignedUpException.php 0000644 00000001521 15132770567 0022354 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Your account is not signed up for the Amazon S3 service. You must sign up before you can use Amazon S3. You can sign up at the following URL: http://aws.amazon.com/s3
*/
class NotSignedUpException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/AccountProblemException.php 0000644 00000001447 15132770567 0023101 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* There is a problem with your AWS account that prevents the operation from completing successfully. Please use Contact Us.
*/
class AccountProblemException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidTokenException.php 0000644 00000001341 15132770567 0022544 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The provided token is malformed or otherwise invalid.
*/
class InvalidTokenException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/UnresolvableGrantByEmailAddressException.php 0000644 00000001404 15132770567 0026363 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The e-mail address you provided does not match any account on record.
*/
class UnresolvableGrantByEmailAddressException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NoSuchVersionException.php 0000644 00000001407 15132770567 0022725 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Indicates that the version ID specified in the request does not match an existing version.
*/
class NoSuchVersionException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidTargetBucketForLoggingException.php 0000644 00000001503 15132770567 0026026 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The target bucket for logging does not exist, is not owned by you, or does not have the appropriate grants for the log-delivery group.
*/
class InvalidTargetBucketForLoggingException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MissingRequestBodyErrorException.php 0000644 00000001452 15132770567 0024772 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* This happens when the user sends an empty xml document as a request. The error message is, "Request body is empty."
*/
class MissingRequestBodyErrorException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidStorageClassException.php 0000644 00000001340 15132770567 0024055 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The storage class you specified is not valid.
*/
class InvalidStorageClassException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/PreconditionFailedException.php 0000644 00000001357 15132770567 0023726 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* At least one of the preconditions you specified did not hold.
*/
class PreconditionFailedException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/RequestTimeoutException.php 0000644 00000001415 15132770567 0023156 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Your socket connection to the server was not read from or written to within the timeout period.
*/
class RequestTimeoutException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidSecurityException.php 0000644 00000001337 15132770567 0023300 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The provided security credentials are not valid.
*/
class InvalidSecurityException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/OperationAbortedException.php 0000644 00000001425 15132770567 0023421 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* A conflicting conditional operation is currently in progress against this resource. Please try again.
*/
class OperationAbortedException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/ExpiredTokenException.php 0000644 00000001313 15132770567 0022555 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The provided token has expired.
*/
class ExpiredTokenException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MaxMessageLengthExceededException.php 0000644 00000001321 15132770567 0024776 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Your request was too big.
*/
class MaxMessageLengthExceededException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidRangeException.php 0000644 00000001324 15132770567 0022521 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The requested range cannot be satisfied.
*/
class InvalidRangeException extends S3Exception {}
lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/IncorrectNumberOfFilesInPostRequestException.php 0000644 00000001365 15132770567 0027163 0 ustar 00 includes <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* POST requires exactly one file upload per request.
*/
class IncorrectNumberOfFilesInPostRequestException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/TokenRefreshRequiredException.php 0000644 00000001331 15132770567 0024254 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The provided token must be refreshed.
*/
class TokenRefreshRequiredException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MissingAttachmentException.php 0000644 00000001345 15132770567 0023603 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* A SOAP attachment was expected, but none were found.
*/
class MissingAttachmentException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/UnexpectedContentException.php 0000644 00000001327 15132770567 0023620 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* This request does not support content.
*/
class UnexpectedContentException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/BucketNotEmptyException.php 0000644 00000001332 15132770567 0023072 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The bucket you tried to delete is not empty.
*/
class BucketNotEmptyException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/ObjectNotInActiveTierErrorException.php 0000644 00000001441 15132770567 0025326 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The source object of the COPY operation is not in the active tier and is only stored in Amazon Glacier.
*/
class ObjectNotInActiveTierErrorException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MissingSecurityElementException.php 0000644 00000001351 15132770567 0024631 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The SOAP 1.1 request is missing a security element.
*/
class MissingSecurityElementException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidArgumentException.php 0000644 00000001277 15132770567 0023256 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Invalid Argument
*/
class InvalidArgumentException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NoSuchKeyException.php 0000644 00000001312 15132770567 0022023 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The specified key does not exist.
*/
class NoSuchKeyException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/EntityTooLargeException.php 0000644 00000001353 15132770567 0023071 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Your proposed upload exceeds the maximum allowed object size.
*/
class EntityTooLargeException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/CredentialsNotSupportedException.php 0000644 00000001341 15132770567 0025001 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* This request does not support credentials.
*/
class CredentialsNotSupportedException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NoSuchWebsiteConfigurationException.php 0000644 00000001365 15132770567 0025435 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The specified bucket does not have a website configuration.
*/
class NoSuchWebsiteConfigurationException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/S3Exception.php 0000644 00000001402 15132770567 0020440 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
use Aws\Common\Exception\ServiceResponseException;
/**
* Default service exception class
*/
class S3Exception extends ServiceResponseException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidAddressingHeaderException.php 0000644 00000001333 15132770567 0024661 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* You must specify the Anonymous role.
*/
class InvalidAddressingHeaderException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/TooManyBucketsException.php 0000644 00000001345 15132770567 0023070 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* You have attempted to create more buckets than allowed.
*/
class TooManyBucketsException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/TemporaryRedirectException.php 0000644 00000001352 15132770567 0023623 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* You are being redirected to the bucket while DNS updates.
*/
class TemporaryRedirectException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/IllegalVersioningConfigurationException.php 0000644 00000001416 15132770567 0026325 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Indicates that the Versioning configuration specified in the request is invalid.
*/
class IllegalVersioningConfigurationException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/RequestTimeTooSkewedException.php 0000644 00000001377 15132770567 0024262 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The difference between the request time and the server's time is too large.
*/
class RequestTimeTooSkewedException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/IncompleteBodyException.php 0000644 00000001401 15132770567 0023067 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* You did not provide the number of bytes specified by the Content-Length HTTP header
*/
class IncompleteBodyException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidLocationConstraintException.php 0000644 00000001471 15132770567 0025305 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The specified location constraint is not valid. For more information about Regions, see How to Select a Region for Your Buckets.
*/
class InvalidLocationConstraintException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/AccessDeniedException.php 0000644 00000001271 15132770567 0022471 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Access Denied
*/
class AccessDeniedException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidBucketStateException.php 0000644 00000001360 15132770567 0023703 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The request is not valid with the current state of the bucket.
*/
class InvalidBucketStateException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NoSuchTagSetException.php 0000644 00000001332 15132770567 0022464 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* There is no TagSet associated with the bucket.
*/
class NoSuchTagSetException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidTagErrorException.php 0000644 00000001515 15132770567 0023214 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The Tag provided was not a valid tag. This can occur if the Tag did not pass input validation. See the
* CostAllocation docs for a description of valid tags.
*/
class InvalidTagErrorException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MissingContentLengthException.php 0000644 00000001344 15132770567 0024266 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* You must provide the Content-Length HTTP header.
*/
class MissingContentLengthException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/RedirectException.php 0000644 00000001273 15132770567 0021722 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Temporary redirect.
*/
class RedirectException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NoSuchBucketPolicyException.php 0000644 00000001335 15132770567 0023675 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The specified bucket policy does not exist.
*/
class NoSuchBucketPolicyException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidPartOrderException.php 0000644 00000001417 15132770567 0023372 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The list of parts was not in ascending order.Parts list must specified in order by part number.
*/
class InvalidPartOrderException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/SignatureDoesNotMatchException.php 0000644 00000001613 15132770567 0024371 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. For more information, see REST Authentication and SOAP Authentication for details.
*/
class SignatureDoesNotMatchException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/BucketAlreadyOwnedByYouException.php 0000644 00000001411 15132770567 0024657 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Your previous request to create the named bucket succeeded and you already own it.
*/
class BucketAlreadyOwnedByYouException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MethodNotAllowedException.php 0000644 00000001352 15132770567 0023370 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The specified method is not allowed against this resource.
*/
class MethodNotAllowedException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/Parser/S3ExceptionParser.php 0000644 00000004361 15132770567 0023060 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception\Parser;
use Aws\Common\Exception\Parser\DefaultXmlExceptionParser;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\Response;
/**
* Parses S3 exception responses
*/
class S3ExceptionParser extends DefaultXmlExceptionParser
{
/**
* {@inheritdoc}
*/
public function parse(RequestInterface $request, Response $response)
{
$data = parent::parse($request, $response);
if ($response->getStatusCode() === 301) {
$data['type'] = 'client';
if (isset($data['message'], $data['parsed'])) {
$data['message'] = rtrim($data['message'], '.') . ': "' . $data['parsed']->Endpoint . '".';
}
}
return $data;
}
/**
* {@inheritdoc}
*/
protected function parseHeaders(RequestInterface $request, Response $response, array &$data)
{
parent::parseHeaders($request, $response, $data);
// Get the request
$status = $response->getStatusCode();
$method = $request->getMethod();
// Attempt to determine code for 403s and 404s
if ($status === 403) {
$data['code'] = 'AccessDenied';
} elseif ($method === 'HEAD' && $status === 404) {
$path = explode('/', trim($request->getPath(), '/'));
$host = explode('.', $request->getHost());
$bucket = (count($host) === 4) ? $host[0] : array_shift($path);
$object = array_shift($path);
if ($bucket && $object) {
$data['code'] = 'NoSuchKey';
} elseif ($bucket) {
$data['code'] = 'NoSuchBucket';
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidPayerException.php 0000644 00000001330 15132770567 0022542 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* All access to this object has been disabled.
*/
class InvalidPayerException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MetadataTooLargeException.php 0000644 00000001357 15132770567 0023341 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Your metadata headers exceed the maximum allowed metadata size.
*/
class MetadataTooLargeException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidPartException.php 0000644 00000001522 15132770567 0022373 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* One or more of the specified parts could not be found. The part might not have been uploaded, or the specified entity tag might not have matched the part's entity tag.
*/
class InvalidPartException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/KeyTooLongException.php 0000644 00000001277 15132770567 0022217 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Your key is too long.
*/
class KeyTooLongException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidPolicyDocumentException.php 0000644 00000001413 15132770567 0024422 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The content of the form does not meet the conditions specified in the policy document.
*/
class InvalidPolicyDocumentException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NotSuchBucketPolicyException.php 0000644 00000001346 15132770567 0024063 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The specified bucket does not have a bucket policy.
*/
class NotSuchBucketPolicyException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/RequestTorrentOfBucketErrorException.php 0000644 00000001364 15132770567 0025625 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Requesting the torrent file of a bucket is not permitted.
*/
class RequestTorrentOfBucketErrorException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/EntityTooSmallException.php 0000644 00000001363 15132770567 0023110 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Your proposed upload is smaller than the minimum allowed object size.
*/
class EntityTooSmallException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidSOAPRequestException.php 0000644 00000001323 15132770567 0023577 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The SOAP request body is invalid.
*/
class InvalidSOAPRequestException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MalformedPOSTRequestException.php 0000644 00000001371 15132770567 0024145 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The body of your POST request is not well-formed multipart/form-data.
*/
class MalformedPOSTRequestException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/MaxPostPreDataLengthExceededErrorException.php 0000644 00000001403 15132770567 0026613 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Your POST request fields preceding the upload file were too large.
*/
class MaxPostPreDataLengthExceededErrorException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidAccessKeyIdException.php 0000644 00000001363 15132770567 0023617 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The AWS Access Key Id you provided does not exist in our records.
*/
class InvalidAccessKeyIdException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/NoSuchUploadException.php 0000644 00000001332 15132770567 0022521 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The specified multipart upload does not exist.
*/
class NoSuchUploadException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/InvalidDigestException.php 0000644 00000001332 15132770567 0022703 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* The Content-MD5 you specified was an invalid.
*/
class InvalidDigestException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Exception/RequestIsNotMultiPartContentException.php 0000644 00000001372 15132770567 0025763 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Exception;
/**
* Bucket POST must be of the enclosure-type multipart/form-data.
*/
class RequestIsNotMultiPartContentException extends S3Exception {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/SseCpkListener.php 0000644 00000004150 15132770567 0017237 0 ustar 00 <?php
namespace Aws\S3;
use Aws\Common\Exception\RuntimeException;
use Guzzle\Common\Event;
use Guzzle\Service\Command\CommandInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* This listener simplifies the SSE-C process by encoding and hashing the key.
*/
class SseCpkListener implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array('command.before_prepare' => 'onCommandBeforePrepare');
}
public function onCommandBeforePrepare(Event $event)
{
/** @var CommandInterface $command */
$command = $event['command'];
// Allows only HTTPS connections when using SSE-C
if ($command['SSECustomerKey'] ||
$command['CopySourceSSECustomerKey']
) {
$this->validateScheme($command);
}
// Prepare the normal SSE-CPK headers
if ($command['SSECustomerKey']) {
$this->prepareSseParams($command);
}
// If it's a copy operation, prepare the SSE-CPK headers for the source.
if ($command['CopySourceSSECustomerKey']) {
$this->prepareSseParams($command, true);
}
}
private function validateScheme(CommandInterface $command)
{
if ($command->getClient()->getConfig('scheme') !== 'https') {
throw new RuntimeException('You must configure your S3 client to '
. 'use HTTPS in order to use the SSE-C features.');
}
}
private function prepareSseParams(
CommandInterface $command,
$isCopy = false
) {
$prefix = $isCopy ? 'CopySource' : '';
// Base64 encode the provided key
$key = $command[$prefix . 'SSECustomerKey'];
$command[$prefix . 'SSECustomerKey'] = base64_encode($key);
// Base64 the provided MD5 or, generate an MD5 if not provided
if ($md5 = $command[$prefix . 'SSECustomerKeyMD5']) {
$command[$prefix . 'SSECustomerKeyMD5'] = base64_encode($md5);
} else {
$command[$prefix . 'SSECustomerKeyMD5'] = base64_encode(md5($key, true));
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/S3Client.php 0000644 00000076657 15132770567 0016012 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3;
use Aws\Common\Client\AbstractClient;
use Aws\Common\Client\ClientBuilder;
use Aws\Common\Client\ExpiredCredentialsChecker;
use Aws\Common\Client\UploadBodyListener;
use Aws\Common\Enum\ClientOptions as Options;
use Aws\Common\Exception\RuntimeException;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Signature\SignatureV4;
use Aws\Common\Model\MultipartUpload\AbstractTransfer;
use Aws\S3\Exception\AccessDeniedException;
use Aws\S3\Exception\Parser\S3ExceptionParser;
use Aws\S3\Exception\S3Exception;
use Aws\S3\Model\ClearBucket;
use Aws\S3\Model\MultipartUpload\AbstractTransfer as AbstractMulti;
use Aws\S3\Model\MultipartUpload\UploadBuilder;
use Aws\S3\Sync\DownloadSyncBuilder;
use Aws\S3\Sync\UploadSyncBuilder;
use Guzzle\Common\Collection;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Iterator\FilterIterator;
use Guzzle\Plugin\Backoff\BackoffPlugin;
use Guzzle\Plugin\Backoff\CurlBackoffStrategy;
use Guzzle\Plugin\Backoff\ExponentialBackoffStrategy;
use Guzzle\Plugin\Backoff\HttpBackoffStrategy;
use Guzzle\Plugin\Backoff\TruncatedBackoffStrategy;
use Guzzle\Service\Command\CommandInterface;
use Guzzle\Service\Command\Factory\AliasFactory;
use Guzzle\Service\Command\Factory\CompositeFactory;
use Guzzle\Service\Resource\Model;
use Guzzle\Service\Resource\ResourceIteratorInterface;
/**
* Client to interact with Amazon Simple Storage Service
*
* @method S3SignatureInterface getSignature() Returns the signature implementation used with the client
* @method Model abortMultipartUpload(array $args = array()) {@command S3 AbortMultipartUpload}
* @method Model completeMultipartUpload(array $args = array()) {@command S3 CompleteMultipartUpload}
* @method Model copyObject(array $args = array()) {@command S3 CopyObject}
* @method Model createBucket(array $args = array()) {@command S3 CreateBucket}
* @method Model createMultipartUpload(array $args = array()) {@command S3 CreateMultipartUpload}
* @method Model deleteBucket(array $args = array()) {@command S3 DeleteBucket}
* @method Model deleteBucketCors(array $args = array()) {@command S3 DeleteBucketCors}
* @method Model deleteBucketLifecycle(array $args = array()) {@command S3 DeleteBucketLifecycle}
* @method Model deleteBucketPolicy(array $args = array()) {@command S3 DeleteBucketPolicy}
* @method Model deleteBucketReplication(array $args = array()) {@command S3 DeleteBucketReplication}
* @method Model deleteBucketTagging(array $args = array()) {@command S3 DeleteBucketTagging}
* @method Model deleteBucketWebsite(array $args = array()) {@command S3 DeleteBucketWebsite}
* @method Model deleteObject(array $args = array()) {@command S3 DeleteObject}
* @method Model deleteObjects(array $args = array()) {@command S3 DeleteObjects}
* @method Model getBucketAcl(array $args = array()) {@command S3 GetBucketAcl}
* @method Model getBucketCors(array $args = array()) {@command S3 GetBucketCors}
* @method Model getBucketLifecycle(array $args = array()) {@command S3 GetBucketLifecycle}
* @method Model getBucketLifecycleConfiguration(array $args = array()) {@command S3 GetBucketLifecycleConfiguration}
* @method Model getBucketLocation(array $args = array()) {@command S3 GetBucketLocation}
* @method Model getBucketLogging(array $args = array()) {@command S3 GetBucketLogging}
* @method Model getBucketNotification(array $args = array()) {@command S3 GetBucketNotification}
* @method Model getBucketNotificationConfiguration(array $args = array()) {@command S3 GetBucketNotificationConfiguration}
* @method Model getBucketPolicy(array $args = array()) {@command S3 GetBucketPolicy}
* @method Model getBucketReplication(array $args = array()) {@command S3 GetBucketReplication}
* @method Model getBucketRequestPayment(array $args = array()) {@command S3 GetBucketRequestPayment}
* @method Model getBucketTagging(array $args = array()) {@command S3 GetBucketTagging}
* @method Model getBucketVersioning(array $args = array()) {@command S3 GetBucketVersioning}
* @method Model getBucketWebsite(array $args = array()) {@command S3 GetBucketWebsite}
* @method Model getObject(array $args = array()) {@command S3 GetObject}
* @method Model getObjectAcl(array $args = array()) {@command S3 GetObjectAcl}
* @method Model getObjectTorrent(array $args = array()) {@command S3 GetObjectTorrent}
* @method Model headBucket(array $args = array()) {@command S3 HeadBucket}
* @method Model headObject(array $args = array()) {@command S3 HeadObject}
* @method Model listBuckets(array $args = array()) {@command S3 ListBuckets}
* @method Model listMultipartUploads(array $args = array()) {@command S3 ListMultipartUploads}
* @method Model listObjectVersions(array $args = array()) {@command S3 ListObjectVersions}
* @method Model listObjects(array $args = array()) {@command S3 ListObjects}
* @method Model listParts(array $args = array()) {@command S3 ListParts}
* @method Model putBucketAcl(array $args = array()) {@command S3 PutBucketAcl}
* @method Model putBucketCors(array $args = array()) {@command S3 PutBucketCors}
* @method Model putBucketLifecycle(array $args = array()) {@command S3 PutBucketLifecycle}
* @method Model putBucketLifecycleConfiguration(array $args = array()) {@command S3 PutBucketLifecycleConfiguration}
* @method Model putBucketLogging(array $args = array()) {@command S3 PutBucketLogging}
* @method Model putBucketNotification(array $args = array()) {@command S3 PutBucketNotification}
* @method Model putBucketNotificationConfiguration(array $args = array()) {@command S3 PutBucketNotificationConfiguration}
* @method Model putBucketPolicy(array $args = array()) {@command S3 PutBucketPolicy}
* @method Model putBucketReplication(array $args = array()) {@command S3 PutBucketReplication}
* @method Model putBucketRequestPayment(array $args = array()) {@command S3 PutBucketRequestPayment}
* @method Model putBucketTagging(array $args = array()) {@command S3 PutBucketTagging}
* @method Model putBucketVersioning(array $args = array()) {@command S3 PutBucketVersioning}
* @method Model putBucketWebsite(array $args = array()) {@command S3 PutBucketWebsite}
* @method Model putObject(array $args = array()) {@command S3 PutObject}
* @method Model putObjectAcl(array $args = array()) {@command S3 PutObjectAcl}
* @method Model restoreObject(array $args = array()) {@command S3 RestoreObject}
* @method Model uploadPart(array $args = array()) {@command S3 UploadPart}
* @method Model uploadPartCopy(array $args = array()) {@command S3 UploadPartCopy}
* @method waitUntilBucketExists(array $input) The input array uses the parameters of the HeadBucket operation and waiter specific settings
* @method waitUntilBucketNotExists(array $input) The input array uses the parameters of the HeadBucket operation and waiter specific settings
* @method waitUntilObjectExists(array $input) The input array uses the parameters of the HeadObject operation and waiter specific settings
* @method ResourceIteratorInterface getListBucketsIterator(array $args = array()) The input array uses the parameters of the ListBuckets operation
* @method ResourceIteratorInterface getListMultipartUploadsIterator(array $args = array()) The input array uses the parameters of the ListMultipartUploads operation
* @method ResourceIteratorInterface getListObjectVersionsIterator(array $args = array()) The input array uses the parameters of the ListObjectVersions operation
* @method ResourceIteratorInterface getListObjectsIterator(array $args = array()) The input array uses the parameters of the ListObjects operation
* @method ResourceIteratorInterface getListPartsIterator(array $args = array()) The input array uses the parameters of the ListParts operation
*
* @link http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-s3.html User guide
* @link http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.S3.S3Client.html API docs
*/
class S3Client extends AbstractClient
{
const LATEST_API_VERSION = '2006-03-01';
/**
* @var array Aliases for S3 operations
*/
protected static $commandAliases = array(
// REST API Docs Aliases
'GetService' => 'ListBuckets',
'GetBucket' => 'ListObjects',
'PutBucket' => 'CreateBucket',
// SDK 1.x Aliases
'GetBucketHeaders' => 'HeadBucket',
'GetObjectHeaders' => 'HeadObject',
'SetBucketAcl' => 'PutBucketAcl',
'CreateObject' => 'PutObject',
'DeleteObjects' => 'DeleteMultipleObjects',
'PutObjectCopy' => 'CopyObject',
'SetObjectAcl' => 'PutObjectAcl',
'GetLogs' => 'GetBucketLogging',
'GetVersioningStatus' => 'GetBucketVersioning',
'SetBucketPolicy' => 'PutBucketPolicy',
'CreateBucketNotification' => 'PutBucketNotification',
'GetBucketNotifications' => 'GetBucketNotification',
'CopyPart' => 'UploadPartCopy',
'CreateWebsiteConfig' => 'PutBucketWebsite',
'GetWebsiteConfig' => 'GetBucketWebsite',
'DeleteWebsiteConfig' => 'DeleteBucketWebsite',
'CreateObjectExpirationConfig' => 'PutBucketLifecycle',
'GetObjectExpirationConfig' => 'GetBucketLifecycle',
'DeleteObjectExpirationConfig' => 'DeleteBucketLifecycle',
);
protected $directory = __DIR__;
/**
* Factory method to create a new Amazon S3 client using an array of configuration options.
*
* @param array|Collection $config Client configuration data
*
* @return S3Client
* @link http://docs.aws.amazon.com/aws-sdk-php/v2/guide/configuration.html#client-configuration-options
*/
public static function factory($config = array())
{
$exceptionParser = new S3ExceptionParser();
// Configure the custom exponential backoff plugin for retrying S3 specific errors
if (!isset($config[Options::BACKOFF])) {
$retries = isset($config[Options::BACKOFF_RETRIES]) ? $config[Options::BACKOFF_RETRIES] : 3;
$config[Options::BACKOFF] = static::createBackoffPlugin($exceptionParser, $retries);
}
$config[Options::SIGNATURE] = $signature = static::createSignature($config);
$client = ClientBuilder::factory(__NAMESPACE__)
->setConfig($config)
->setConfigDefaults(array(
Options::VERSION => self::LATEST_API_VERSION,
Options::SERVICE_DESCRIPTION => __DIR__ . '/Resources/s3-%s.php'
))
->setExceptionParser($exceptionParser)
->setIteratorsConfig(array(
'more_key' => 'IsTruncated',
'operations' => array(
'ListBuckets',
'ListMultipartUploads' => array(
'limit_param' => 'MaxUploads',
'token_param' => array('KeyMarker', 'UploadIdMarker'),
'token_key' => array('NextKeyMarker', 'NextUploadIdMarker'),
),
'ListObjects' => array(
'limit_param' => 'MaxKeys',
'token_param' => 'Marker',
'token_key' => 'NextMarker',
),
'ListObjectVersions' => array(
'limit_param' => 'MaxKeys',
'token_param' => array('KeyMarker', 'VersionIdMarker'),
'token_key' => array('nextKeyMarker', 'nextVersionIdMarker'),
),
'ListParts' => array(
'limit_param' => 'MaxParts',
'result_key' => 'Parts',
'token_param' => 'PartNumberMarker',
'token_key' => 'NextPartNumberMarker',
),
)
))
->build();
// Use virtual hosted buckets when possible
$client->addSubscriber(new BucketStyleListener());
// Ensure that ACP headers are applied when needed
$client->addSubscriber(new AcpListener());
// Validate and add required Content-MD5 hashes (e.g. DeleteObjects)
$client->addSubscriber(new S3Md5Listener($signature));
// Allow for specifying bodies with file paths and file handles
$client->addSubscriber(new UploadBodyListener(array('PutObject', 'UploadPart')));
// Ensures that if a SSE-CPK key is provided, the key and md5 are formatted correctly
$client->addSubscriber(new SseCpkListener);
// Add aliases for some S3 operations
$default = CompositeFactory::getDefaultChain($client);
$default->add(
new AliasFactory($client, static::$commandAliases),
'Guzzle\Service\Command\Factory\ServiceDescriptionFactory'
);
$client->setCommandFactory($default);
return $client;
}
/**
* Create an Amazon S3 specific backoff plugin
*
* @param S3ExceptionParser $exceptionParser
*
* @return BackoffPlugin
*/
private static function createBackoffPlugin(S3ExceptionParser $exceptionParser, $retries = 3)
{
return new BackoffPlugin(
new TruncatedBackoffStrategy($retries,
new IncompleteMultipartUploadChecker(
new CurlBackoffStrategy(null,
new HttpBackoffStrategy(null,
new SocketTimeoutChecker(
new ExpiredCredentialsChecker($exceptionParser,
new ExponentialBackoffStrategy()
)
)
)
)
)
)
);
}
/**
* Create an appropriate signature based on the configuration settings
*
* @param $config
*
* @return \Aws\Common\Signature\SignatureInterface
* @throws InvalidArgumentException
*/
private static function createSignature($config)
{
$currentValue = isset($config[Options::SIGNATURE]) ? $config[Options::SIGNATURE] : null;
// Force v4 if no value is provided, a region is in the config, and
// the region starts with "cn-" or "eu-central-".
$requiresV4 = !$currentValue
&& isset($config['region'])
&& (strpos($config['region'], 'eu-central-') === 0
|| strpos($config['region'], 'cn-') === 0);
// Use the Amazon S3 signature V4 when the value is set to "v4" or when
// the value is not set and the region starts with "cn-".
if ($currentValue == 'v4' || $requiresV4) {
// Force SignatureV4 for specific regions or if specified in the config
$currentValue = new S3SignatureV4('s3');
} elseif (!$currentValue || $currentValue == 's3') {
// Use the Amazon S3 signature by default
$currentValue = new S3Signature();
}
// A region is require with v4
if ($currentValue instanceof SignatureV4 && !isset($config['region'])) {
throw new InvalidArgumentException('A region must be specified '
. 'when using signature version 4');
}
return $currentValue;
}
/**
* Determine if a string is a valid name for a DNS compatible Amazon S3
* bucket, meaning the bucket can be used as a subdomain in a URL (e.g.,
* "<bucket>.s3.amazonaws.com").
*
* @param string $bucket The name of the bucket to check.
*
* @return bool TRUE if the bucket name is valid or FALSE if it is invalid.
*/
public static function isValidBucketName($bucket)
{
$bucketLen = strlen($bucket);
if ($bucketLen < 3 || $bucketLen > 63 ||
// Cannot look like an IP address
preg_match('/(\d+\.){3}\d+$/', $bucket) ||
// Cannot include special characters, must start and end with lower alnum
!preg_match('/^[a-z0-9]([a-z0-9\-\.]*[a-z0-9])?$/', $bucket)
) {
return false;
}
return true;
}
/**
* Create a pre-signed URL for a request
*
* @param RequestInterface $request Request to generate the URL for. Use the factory methods of the client to
* create this request object
* @param int|string|\DateTime $expires The time at which the URL should expire. This can be a Unix timestamp, a
* PHP DateTime object, or a string that can be evaluated by strtotime
*
* @return string
* @throws InvalidArgumentException if the request is not associated with this client object
*/
public function createPresignedUrl(RequestInterface $request, $expires)
{
if ($request->getClient() !== $this) {
throw new InvalidArgumentException('The request object must be associated with the client. Use the '
. '$client->get(), $client->head(), $client->post(), $client->put(), etc. methods when passing in a '
. 'request object');
}
return $this->signature->createPresignedUrl($request, $this->credentials, $expires);
}
/**
* Returns the URL to an object identified by its bucket and key. If an expiration time is provided, the URL will
* be signed and set to expire at the provided time.
*
* Note: This method does not ensure that the generated URL is valid. For example, the bucket referenced may not
* exist, the key referenced may not exist, and the URL might include parameters that require it to be signed.
* If you need to use parameters that require a signed URL (e.g., ResponseCacheControl), then you must sign the
* URL either by providing an $expires argument or by signing the URL returned by this method in some other
* manner.
*
* @param string $bucket The name of the bucket where the object is located
* @param string $key The key of the object
* @param mixed $expires The time at which the URL should expire
* @param array $args Arguments to the GetObject command. Additionally you can specify a "Scheme" if you would
* like the URL to use a different scheme than what the client is configured to use
*
* @return string The URL to the object
*/
public function getObjectUrl($bucket, $key, $expires = null, array $args = array())
{
$command = $this->getCommand('GetObject', $args + array('Bucket' => $bucket, 'Key' => $key));
if ($command->hasKey('Scheme')) {
$scheme = $command['Scheme'];
$request = $command->remove('Scheme')->prepare()->setScheme($scheme)->setPort(null);
} else {
$request = $command->prepare();
}
return $expires ? $this->createPresignedUrl($request, $expires) : $request->getUrl();
}
/**
* Helper used to clear the contents of a bucket. Use the {@see ClearBucket} object directly
* for more advanced options and control.
*
* @param string $bucket Name of the bucket to clear.
*
* @return int Returns the number of deleted keys
*/
public function clearBucket($bucket)
{
$clear = new ClearBucket($this, $bucket);
return $clear->clear();
}
/**
* Determines whether or not a bucket exists by name
*
* @param string $bucket The name of the bucket
* @param bool $accept403 Set to true if 403s are acceptable
* @param array $options Additional options to add to the executed command
*
* @return bool
*/
public function doesBucketExist($bucket, $accept403 = true, array $options = array())
{
return $this->checkExistenceWithCommand(
$this->getCommand('HeadBucket', array_merge($options, array(
'Bucket' => $bucket
))), $accept403
);
}
/**
* Determines whether or not an object exists by name
*
* @param string $bucket The name of the bucket
* @param string $key The key of the object
* @param array $options Additional options to add to the executed command
*
* @return bool
*/
public function doesObjectExist($bucket, $key, array $options = array())
{
return $this->checkExistenceWithCommand(
$this->getCommand('HeadObject', array_merge($options, array(
'Bucket' => $bucket,
'Key' => $key
)))
);
}
/**
* Determines whether or not a bucket policy exists for a bucket
*
* @param string $bucket The name of the bucket
* @param array $options Additional options to add to the executed command
*
* @return bool
*/
public function doesBucketPolicyExist($bucket, array $options = array())
{
return $this->checkExistenceWithCommand(
$this->getCommand('GetBucketPolicy', array_merge($options, array(
'Bucket' => $bucket
)))
);
}
/**
* Raw URL encode a key and allow for '/' characters
*
* @param string $key Key to encode
*
* @return string Returns the encoded key
*/
public static function encodeKey($key)
{
return str_replace('%2F', '/', rawurlencode($key));
}
/**
* Explode a prefixed key into an array of values
*
* @param string $key Key to explode
*
* @return array Returns the exploded
*/
public static function explodeKey($key)
{
// Remove a leading slash if one is found
return explode('/', $key && $key[0] == '/' ? substr($key, 1) : $key);
}
/**
* Register the Amazon S3 stream wrapper and associates it with this client object
*
* @return $this
*/
public function registerStreamWrapper()
{
StreamWrapper::register($this);
return $this;
}
/**
* Upload a file, stream, or string to a bucket. If the upload size exceeds the specified threshold, the upload
* will be performed using parallel multipart uploads.
*
* @param string $bucket Bucket to upload the object
* @param string $key Key of the object
* @param mixed $body Object data to upload. Can be a Guzzle\Http\EntityBodyInterface, stream resource, or
* string of data to upload.
* @param string $acl ACL to apply to the object
* @param array $options Custom options used when executing commands:
* - params: Custom parameters to use with the upload. The parameters must map to a PutObject
* or InitiateMultipartUpload operation parameters.
* - min_part_size: Minimum size to allow for each uploaded part when performing a multipart upload.
* - concurrency: Maximum number of concurrent multipart uploads.
* - before_upload: Callback to invoke before each multipart upload. The callback will receive a
* Guzzle\Common\Event object with context.
*
* @see Aws\S3\Model\MultipartUpload\UploadBuilder for more options and customization
* @return \Guzzle\Service\Resource\Model Returns the modeled result of the performed operation
*/
public function upload($bucket, $key, $body, $acl = 'private', array $options = array())
{
$body = EntityBody::factory($body);
$options = Collection::fromConfig(array_change_key_case($options), array(
'min_part_size' => AbstractMulti::MIN_PART_SIZE,
'params' => array(),
'concurrency' => $body->getWrapper() == 'plainfile' ? 3 : 1
));
if ($body->getSize() < $options['min_part_size']) {
// Perform a simple PutObject operation
return $this->putObject(array(
'Bucket' => $bucket,
'Key' => $key,
'Body' => $body,
'ACL' => $acl
) + $options['params']);
}
// Perform a multipart upload if the file is large enough
$transfer = UploadBuilder::newInstance()
->setBucket($bucket)
->setKey($key)
->setMinPartSize($options['min_part_size'])
->setConcurrency($options['concurrency'])
->setClient($this)
->setSource($body)
->setTransferOptions($options->toArray())
->addOptions($options['params'])
->setOption('ACL', $acl)
->build();
if ($options['before_upload']) {
$transfer->getEventDispatcher()->addListener(
AbstractTransfer::BEFORE_PART_UPLOAD,
$options['before_upload']
);
}
return $transfer->upload();
}
/**
* Recursively uploads all files in a given directory to a given bucket.
*
* @param string $directory Full path to a directory to upload
* @param string $bucket Name of the bucket
* @param string $keyPrefix Virtual directory key prefix to add to each upload
* @param array $options Associative array of upload options
* - params: Array of parameters to use with each PutObject operation performed during the transfer
* - base_dir: Base directory to remove from each object key
* - force: Set to true to upload every file, even if the file is already in Amazon S3 and has not changed
* - concurrency: Maximum number of parallel uploads (defaults to 10)
* - debug: Set to true or an fopen resource to enable debug mode to print information about each upload
* - multipart_upload_size: When the size of a file exceeds this value, the file will be uploaded using a
* multipart upload.
*
* @see Aws\S3\S3Sync\S3Sync for more options and customization
*/
public function uploadDirectory($directory, $bucket, $keyPrefix = null, array $options = array())
{
$options = Collection::fromConfig(
$options,
array(
'base_dir' => realpath($directory) ?: $directory
)
);
$builder = $options['builder'] ?: UploadSyncBuilder::getInstance();
$builder->uploadFromDirectory($directory)
->setClient($this)
->setBucket($bucket)
->setKeyPrefix($keyPrefix)
->setConcurrency($options['concurrency'] ?: 5)
->setBaseDir($options['base_dir'])
->force($options['force'])
->setOperationParams($options['params'] ?: array())
->enableDebugOutput($options['debug']);
if ($options->hasKey('multipart_upload_size')) {
$builder->setMultipartUploadSize($options['multipart_upload_size']);
}
$builder->build()->transfer();
}
/**
* Downloads a bucket to the local filesystem
*
* @param string $directory Directory to download to
* @param string $bucket Bucket to download from
* @param string $keyPrefix Only download objects that use this key prefix
* @param array $options Associative array of download options
* - params: Array of parameters to use with each GetObject operation performed during the transfer
* - base_dir: Base directory to remove from each object key when storing in the local filesystem
* - force: Set to true to download every file, even if the file is already on the local filesystem and has not
* changed
* - concurrency: Maximum number of parallel downloads (defaults to 10)
* - debug: Set to true or a fopen resource to enable debug mode to print information about each download
* - allow_resumable: Set to true to allow previously interrupted downloads to be resumed using a Range GET
*/
public function downloadBucket($directory, $bucket, $keyPrefix = '', array $options = array())
{
$options = new Collection($options);
$builder = $options['builder'] ?: DownloadSyncBuilder::getInstance();
$builder->setDirectory($directory)
->setClient($this)
->setBucket($bucket)
->setKeyPrefix($keyPrefix)
->setConcurrency($options['concurrency'] ?: 10)
->setBaseDir($options['base_dir'])
->force($options['force'])
->setOperationParams($options['params'] ?: array())
->enableDebugOutput($options['debug']);
if ($options['allow_resumable']) {
$builder->allowResumableDownloads();
}
$builder->build()->transfer();
}
/**
* Deletes objects from Amazon S3 that match the result of a ListObjects operation. For example, this allows you
* to do things like delete all objects that match a specific key prefix.
*
* @param string $bucket Bucket that contains the object keys
* @param string $prefix Optionally delete only objects under this key prefix
* @param string $regex Delete only objects that match this regex
* @param array $options Options used when deleting the object:
* - before_delete: Callback to invoke before each delete. The callback will receive a
* Guzzle\Common\Event object with context.
*
* @see Aws\S3\S3Client::listObjects
* @see Aws\S3\Model\ClearBucket For more options or customization
* @return int Returns the number of deleted keys
* @throws RuntimeException if no prefix and no regex is given
*/
public function deleteMatchingObjects($bucket, $prefix = '', $regex = '', array $options = array())
{
if (!$prefix && !$regex) {
throw new RuntimeException('A prefix or regex is required, or use S3Client::clearBucket().');
}
$clear = new ClearBucket($this, $bucket);
$iterator = $this->getIterator('ListObjects', array('Bucket' => $bucket, 'Prefix' => $prefix));
if ($regex) {
$iterator = new FilterIterator($iterator, function ($current) use ($regex) {
return preg_match($regex, $current['Key']);
});
}
$clear->setIterator($iterator);
if (isset($options['before_delete'])) {
$clear->getEventDispatcher()->addListener(ClearBucket::BEFORE_CLEAR, $options['before_delete']);
}
return $clear->clear();
}
/**
* Determines whether or not a resource exists using a command
*
* @param CommandInterface $command Command used to poll for the resource
* @param bool $accept403 Set to true if 403s are acceptable
*
* @return bool
* @throws S3Exception|\Exception if there is an unhandled exception
*/
protected function checkExistenceWithCommand(CommandInterface $command, $accept403 = false)
{
try {
$command->execute();
$exists = true;
} catch (AccessDeniedException $e) {
$exists = (bool) $accept403;
} catch (S3Exception $e) {
$exists = false;
if ($e->getResponse()->getStatusCode() >= 500) {
// @codeCoverageIgnoreStart
throw $e;
// @codeCoverageIgnoreEnd
}
}
return $exists;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/DeleteObjectsBatch.php 0000644 00000005331 15132770567 0021061 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model;
use Aws\Common\Client\AwsClientInterface;
use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Service\Command\AbstractCommand;
use Guzzle\Batch\BatchBuilder;
use Guzzle\Batch\BatchSizeDivisor;
use Guzzle\Batch\AbstractBatchDecorator;
/**
* The DeleteObjectsBatch is a BatchDecorator for Guzzle that implements a
* queue for deleting keys from an Amazon S3 bucket. You can add DeleteObject
* or an array of [Key => %s, VersionId => %s] and call flush when the objects
* should be deleted.
*/
class DeleteObjectsBatch extends AbstractBatchDecorator
{
/**
* Factory for creating a DeleteObjectsBatch
*
* @param AwsClientInterface $client Client used to transfer requests
* @param string $bucket Bucket that contains the objects to delete
* @param string $mfa MFA token to use with the request
*
* @return static
*/
public static function factory(AwsClientInterface $client, $bucket, $mfa = null)
{
$batch = BatchBuilder::factory()
->createBatchesWith(new BatchSizeDivisor(1000))
->transferWith(new DeleteObjectsTransfer($client, $bucket, $mfa))
->build();
return new static($batch);
}
/**
* Add an object to be deleted
*
* @param string $key Key of the object
* @param string $versionId VersionID of the object
*
* @return $this
*/
public function addKey($key, $versionId = null)
{
return $this->add(array(
'Key' => $key,
'VersionId' => $versionId
));
}
/**
* {@inheritdoc}
*/
public function add($item)
{
if ($item instanceof AbstractCommand && $item->getName() == 'DeleteObject') {
$item = array(
'Key' => $item['Key'],
'VersionId' => $item['VersionId']
);
}
if (!is_array($item) || (!isset($item['Key']))) {
throw new InvalidArgumentException('Item must be a DeleteObject command or array containing a Key and VersionId key.');
}
return parent::add($item);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/Grantee.php 0000644 00000014224 15132770567 0016771 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model;
use Aws\S3\Enum\Group;
use Aws\S3\Enum\GranteeType;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\UnexpectedValueException;
use Aws\Common\Exception\LogicException;
use Guzzle\Common\ToArrayInterface;
/**
* Amazon S3 Grantee model
*/
class Grantee implements ToArrayInterface
{
/**
* @var array A map of grantee types to grant header value prefixes
*/
protected static $headerMap = array(
GranteeType::USER => 'id',
GranteeType::EMAIL => 'emailAddress',
GranteeType::GROUP => 'uri'
);
/**
* @var string The account ID, email, or URL identifying the grantee
*/
protected $id;
/**
* @var string The display name of the grantee
*/
protected $displayName;
/**
* @var string The type of the grantee (CanonicalUser or Group)
*/
protected $type;
/**
* Constructs a Grantee
*
* @param string $id Grantee identifier
* @param string $displayName Grantee display name
* @param string $expectedType The expected type of the grantee
*/
public function __construct($id, $displayName = null, $expectedType = null)
{
$this->type = GranteeType::USER;
$this->setId($id, $expectedType);
$this->setDisplayName($displayName);
}
/**
* Sets the account ID, email, or URL identifying the grantee
*
* @param string $id Grantee identifier
* @param string $expectedType The expected type of the grantee
*
* @return Grantee
*
* @throws UnexpectedValueException if $expectedType is set and the grantee
* is not of that type after instantiation
* @throws InvalidArgumentException when the ID provided is not a string
*/
public function setId($id, $expectedType = null)
{
if (in_array($id, Group::values())) {
$this->type = GranteeType::GROUP;
} elseif (!is_string($id)) {
throw new InvalidArgumentException('The grantee ID must be provided as a string value.');
}
if (strpos($id, '@') !== false) {
$this->type = GranteeType::EMAIL;
}
if ($expectedType && $expectedType !== $this->type) {
throw new UnexpectedValueException('The type of the grantee after '
. 'setting the ID did not match the specified, expected type "'
. esc_html($expectedType) . '" but received "' . esc_html($this->type) . '".');
}
$this->id = $id;
return $this;
}
/**
* Gets the grantee identifier
*
* @return string
*/
public function getId()
{
return $this->id;
}
/**
* Gets the grantee email address (if it is set)
*
* @return null|string
*/
public function getEmailAddress()
{
return $this->isAmazonCustomerByEmail() ? $this->id : null;
}
/**
* Gets the grantee URI (if it is set)
*
* @return null|string
*/
public function getGroupUri()
{
return $this->isGroup() ? $this->id : null;
}
/**
* Sets the display name of the grantee
*
* @param string $displayName Grantee name
*
* @return Grantee
*
* @throws LogicException when the grantee type not CanonicalUser
*/
public function setDisplayName($displayName)
{
if ($this->type === GranteeType::USER) {
if (empty($displayName) || !is_string($displayName)) {
$displayName = $this->id;
}
$this->displayName = $displayName;
} else {
if ($displayName) {
throw new LogicException('The display name can only be set '
. 'for grantees specified by ID.');
}
}
return $this;
}
/**
* Gets the grantee display name
*
* @return string
*/
public function getDisplayName()
{
return $this->displayName;
}
/**
* Gets the grantee type (determined by ID)
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Returns true if this grantee object represents a canonical user by ID
*
* @return bool
*/
public function isCanonicalUser()
{
return ($this->type === GranteeType::USER);
}
/**
* Returns true if this grantee object represents a customer by email
*
* @return bool
*/
public function isAmazonCustomerByEmail()
{
return ($this->type === GranteeType::EMAIL);
}
/**
* Returns true if this grantee object represents a group by URL
*
* @return bool
*/
public function isGroup()
{
return ($this->type === GranteeType::GROUP);
}
/**
* Returns the value used in headers to specify this grantee
*
* @return string
*/
public function getHeaderValue()
{
$key = static::$headerMap[$this->type];
return "{$key}=\"{$this->id}\"";
}
/**
* {@inheritdoc}
*/
public function toArray()
{
$result = array(
'Type' => $this->type
);
switch ($this->type) {
case GranteeType::USER:
$result['ID'] = $this->id;
$result['DisplayName'] = $this->displayName;
break;
case GranteeType::EMAIL:
$result['EmailAddress'] = $this->id;
break;
case GranteeType::GROUP:
$result['URI'] = $this->id;
}
return $result;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/AcpBuilder.php 0000644 00000006517 15132770567 0017424 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model;
use Aws\S3\Enum\GranteeType;
/**
* Builder for creating Access Control Policies
*/
class AcpBuilder
{
/**
* @var Grantee The owner for the ACL
*/
protected $owner;
/**
* @var array An array of Grant objects for the ACL
*/
protected $grants = array();
/**
* Static method for chainable instantiation
*
* @return static
*/
public static function newInstance()
{
return new static;
}
/**
* Sets the owner to be set on the ACL
*
* @param string $id Owner identifier
* @param string $displayName Owner display name
*
* @return $this
*/
public function setOwner($id, $displayName = null)
{
$this->owner = new Grantee($id, $displayName ?: $id, GranteeType::USER);
return $this;
}
/**
* Create and store a Grant with a CanonicalUser Grantee for the ACL
*
* @param string $permission Permission for the Grant
* @param string $id Grantee identifier
* @param string $displayName Grantee display name
*
* @return $this
*/
public function addGrantForUser($permission, $id, $displayName = null)
{
$grantee = new Grantee($id, $displayName ?: $id, GranteeType::USER);
$this->addGrant($permission, $grantee);
return $this;
}
/**
* Create and store a Grant with a AmazonCustomerByEmail Grantee for the ACL
*
* @param string $permission Permission for the Grant
* @param string $email Grantee email address
*
* @return $this
*/
public function addGrantForEmail($permission, $email)
{
$grantee = new Grantee($email, null, GranteeType::EMAIL);
$this->addGrant($permission, $grantee);
return $this;
}
/**
* Create and store a Grant with a Group Grantee for the ACL
*
* @param string $permission Permission for the Grant
* @param string $group Grantee group
*
* @return $this
*/
public function addGrantForGroup($permission, $group)
{
$grantee = new Grantee($group, null, GranteeType::GROUP);
$this->addGrant($permission, $grantee);
return $this;
}
/**
* Create and store a Grant for the ACL
*
* @param string $permission Permission for the Grant
* @param Grantee $grantee The Grantee for the Grant
*
* @return $this
*/
public function addGrant($permission, Grantee $grantee)
{
$this->grants[] = new Grant($grantee, $permission);
return $this;
}
/**
* Builds the ACP and returns it
*
* @return Acp
*/
public function build()
{
return new Acp($this->owner, $this->grants);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/MultipartUpload/UploadBuilder.php 0000644 00000020721 15132770567 0023264 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model\MultipartUpload;
use Aws\Common\Enum\UaString as Ua;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Model\MultipartUpload\AbstractUploadBuilder;
use Aws\S3\Model\Acp;
/**
* Easily create a multipart uploader used to quickly and reliably upload a
* large file or data stream to Amazon S3 using multipart uploads
*/
class UploadBuilder extends AbstractUploadBuilder
{
/**
* @var int Concurrency level to transfer the parts
*/
protected $concurrency = 1;
/**
* @var int Minimum part size to upload
*/
protected $minPartSize = AbstractTransfer::MIN_PART_SIZE;
/**
* @var string MD5 hash of the entire body to transfer
*/
protected $md5;
/**
* @var bool Whether or not to calculate the entire MD5 hash of the object
*/
protected $calculateEntireMd5 = false;
/**
* @var bool Whether or not to calculate MD5 hash of each part
*/
protected $calculatePartMd5 = true;
/**
* @var array Array of initiate command options
*/
protected $commandOptions = array();
/**
* @var array Array of transfer options
*/
protected $transferOptions = array();
/**
* Set the bucket to upload the object to
*
* @param string $bucket Name of the bucket
*
* @return $this
*/
public function setBucket($bucket)
{
return $this->setOption('Bucket', $bucket);
}
/**
* Set the key of the object
*
* @param string $key Key of the object to upload
*
* @return $this
*/
public function setKey($key)
{
return $this->setOption('Key', $key);
}
/**
* Set the minimum acceptable part size
*
* @param int $minSize Minimum acceptable part size in bytes
*
* @return $this
*/
public function setMinPartSize($minSize)
{
$this->minPartSize = (int) max((int) $minSize, AbstractTransfer::MIN_PART_SIZE);
return $this;
}
/**
* Set the concurrency level to use when uploading parts. This affects how
* many parts are uploaded in parallel. You must use a local file as your
* data source when using a concurrency greater than 1
*
* @param int $concurrency Concurrency level
*
* @return $this
*/
public function setConcurrency($concurrency)
{
$this->concurrency = $concurrency;
return $this;
}
/**
* Explicitly set the MD5 hash of the entire body
*
* @param string $md5 MD5 hash of the entire body
*
* @return $this
*/
public function setMd5($md5)
{
$this->md5 = $md5;
return $this;
}
/**
* Set to true to have the builder calculate the MD5 hash of the entire data
* source before initiating a multipart upload (this could be an expensive
* operation). This setting can ony be used with seekable data sources.
*
* @param bool $calculateMd5 Set to true to calculate the MD5 hash of the body
*
* @return $this
*/
public function calculateMd5($calculateMd5)
{
$this->calculateEntireMd5 = (bool) $calculateMd5;
return $this;
}
/**
* Specify whether or not to calculate the MD5 hash of each uploaded part.
* This setting defaults to true.
*
* @param bool $usePartMd5 Set to true to calculate the MD5 has of each part
*
* @return $this
*/
public function calculatePartMd5($usePartMd5)
{
$this->calculatePartMd5 = (bool) $usePartMd5;
return $this;
}
/**
* Set the ACP to use on the object
*
* @param Acp $acp ACP to set on the object
*
* @return $this
*/
public function setAcp(Acp $acp)
{
return $this->setOption('ACP', $acp);
}
/**
* Set an option to pass to the initial CreateMultipartUpload operation
*
* @param string $name Option name
* @param string $value Option value
*
* @return $this
*/
public function setOption($name, $value)
{
$this->commandOptions[$name] = $value;
return $this;
}
/**
* Add an array of options to pass to the initial CreateMultipartUpload operation
*
* @param array $options Array of CreateMultipartUpload operation parameters
*
* @return $this
*/
public function addOptions(array $options)
{
$this->commandOptions = array_replace($this->commandOptions, $options);
return $this;
}
/**
* Set an array of transfer options to apply to the upload transfer object
*
* @param array $options Transfer options
*
* @return $this
*/
public function setTransferOptions(array $options)
{
$this->transferOptions = $options;
return $this;
}
/**
* {@inheritdoc}
* @throws InvalidArgumentException when attempting to resume a transfer using a non-seekable stream
* @throws InvalidArgumentException when missing required properties (bucket, key, client, source)
*/
public function build()
{
if ($this->state instanceof TransferState) {
$this->commandOptions = array_replace($this->commandOptions, $this->state->getUploadId()->toParams());
}
if (!isset($this->commandOptions['Bucket']) || !isset($this->commandOptions['Key'])
|| !$this->client || !$this->source
) {
throw new InvalidArgumentException('You must specify a Bucket, Key, client, and source.');
}
if ($this->state && !$this->source->isSeekable()) {
throw new InvalidArgumentException('You cannot resume a transfer using a non-seekable source.');
}
// If no state was set, then create one by initiating or loading a multipart upload
if (is_string($this->state)) {
$this->state = TransferState::fromUploadId($this->client, UploadId::fromParams(array(
'Bucket' => $this->commandOptions['Bucket'],
'Key' => $this->commandOptions['Key'],
'UploadId' => $this->state
)));
} elseif (!$this->state) {
$this->state = $this->initiateMultipartUpload();
}
$options = array_replace(array(
'min_part_size' => $this->minPartSize,
'part_md5' => (bool) $this->calculatePartMd5,
'concurrency' => $this->concurrency
), $this->transferOptions);
return $this->concurrency > 1
? new ParallelTransfer($this->client, $this->state, $this->source, $options)
: new SerialTransfer($this->client, $this->state, $this->source, $options);
}
/**
* {@inheritdoc}
*/
protected function initiateMultipartUpload()
{
// Determine Content-Type
if (!isset($this->commandOptions['ContentType'])) {
if ($mimeType = $this->source->getContentType()) {
$this->commandOptions['ContentType'] = $mimeType;
}
}
$params = array_replace(array(
Ua::OPTION => Ua::MULTIPART_UPLOAD,
'command.headers' => $this->headers,
'Metadata' => array()
), $this->commandOptions);
// Calculate the MD5 hash if none was set and it is asked of the builder
if ($this->calculateEntireMd5) {
$this->md5 = $this->source->getContentMd5();
}
// If an MD5 is specified, then add it to the custom headers of the request
// so that it will be returned when downloading the object from Amazon S3
if ($this->md5) {
$params['Metadata']['x-amz-Content-MD5'] = $this->md5;
}
$result = $this->client->getCommand('CreateMultipartUpload', $params)->execute();
// Create a new state based on the initiated upload
$params['UploadId'] = $result['UploadId'];
return new TransferState(UploadId::fromParams($params));
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/MultipartUpload/SerialTransfer.php 0000644 00000006164 15132770567 0023462 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model\MultipartUpload;
use Aws\Common\Enum\DateFormat;
use Aws\Common\Enum\Size;
use Aws\Common\Enum\UaString as Ua;
use Guzzle\Http\EntityBody;
use Guzzle\Http\ReadLimitEntityBody;
/**
* Transfers multipart upload parts serially
*/
class SerialTransfer extends AbstractTransfer
{
/**
* {@inheritdoc}
*/
protected function transfer()
{
while (!$this->stopped && !$this->source->isConsumed()) {
if ($this->source->getContentLength() && $this->source->isSeekable()) {
// If the stream is seekable and the Content-Length known, then stream from the data source
$body = new ReadLimitEntityBody($this->source, $this->partSize, $this->source->ftell());
} else {
// We need to read the data source into a temporary buffer before streaming
$body = EntityBody::factory();
while ($body->getContentLength() < $this->partSize
&& $body->write(
$this->source->read(max(1, min(10 * Size::KB, $this->partSize - $body->getContentLength())))
));
}
// @codeCoverageIgnoreStart
if ($body->getContentLength() == 0) {
break;
}
// @codeCoverageIgnoreEnd
$params = $this->state->getUploadId()->toParams();
$command = $this->client->getCommand('UploadPart', array_replace($params, array(
'PartNumber' => count($this->state) + 1,
'Body' => $body,
'ContentMD5' => (bool) $this->options['part_md5'],
Ua::OPTION => Ua::MULTIPART_UPLOAD
)));
// Notify observers that the part is about to be uploaded
$eventData = $this->getEventData();
$eventData['command'] = $command;
$this->dispatch(self::BEFORE_PART_UPLOAD, $eventData);
// Allow listeners to stop the transfer if needed
if ($this->stopped) {
break;
}
$response = $command->getResponse();
$this->state->addPart(UploadPart::fromArray(array(
'PartNumber' => $command['PartNumber'],
'ETag' => $response->getEtag(),
'Size' => $body->getContentLength(),
'LastModified' => gmdate(DateFormat::RFC2822)
)));
// Notify observers that the part was uploaded
$this->dispatch(self::AFTER_PART_UPLOAD, $eventData);
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/MultipartUpload/ParallelTransfer.php 0000644 00000011027 15132770567 0023771 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model\MultipartUpload;
use Aws\Common\Exception\RuntimeException;
use Aws\Common\Enum\DateFormat;
use Aws\Common\Enum\UaString as Ua;
use Guzzle\Http\EntityBody;
use Guzzle\Http\ReadLimitEntityBody;
/**
* Transfers multipart upload parts in parallel
*/
class ParallelTransfer extends AbstractTransfer
{
/**
* {@inheritdoc}
*/
protected function init()
{
parent::init();
if (!$this->source->isLocal() || $this->source->getWrapper() != 'plainfile') {
throw new RuntimeException('The source data must be a local file stream when uploading in parallel.');
}
if (empty($this->options['concurrency'])) {
throw new RuntimeException('The `concurrency` option must be specified when instantiating.');
}
}
/**
* {@inheritdoc}
*/
protected function transfer()
{
$totalParts = (int) ceil($this->source->getContentLength() / $this->partSize);
$concurrency = min($totalParts, $this->options['concurrency']);
$partsToSend = $this->prepareParts($concurrency);
$eventData = $this->getEventData();
while (!$this->stopped && count($this->state) < $totalParts) {
$currentTotal = count($this->state);
$commands = array();
for ($i = 0; $i < $concurrency && $i + $currentTotal < $totalParts; $i++) {
// Move the offset to the correct position
$partsToSend[$i]->setOffset(($currentTotal + $i) * $this->partSize);
// @codeCoverageIgnoreStart
if ($partsToSend[$i]->getContentLength() == 0) {
break;
}
// @codeCoverageIgnoreEnd
$params = $this->state->getUploadId()->toParams();
$eventData['command'] = $this->client->getCommand('UploadPart', array_replace($params, array(
'PartNumber' => count($this->state) + 1 + $i,
'Body' => $partsToSend[$i],
'ContentMD5' => (bool) $this->options['part_md5'],
Ua::OPTION => Ua::MULTIPART_UPLOAD
)));
$commands[] = $eventData['command'];
// Notify any listeners of the part upload
$this->dispatch(self::BEFORE_PART_UPLOAD, $eventData);
}
// Allow listeners to stop the transfer if needed
if ($this->stopped) {
break;
}
// Execute each command, iterate over the results, and add to the transfer state
/** @var \Guzzle\Service\Command\OperationCommand $command */
foreach ($this->client->execute($commands) as $command) {
$this->state->addPart(UploadPart::fromArray(array(
'PartNumber' => $command['PartNumber'],
'ETag' => $command->getResponse()->getEtag(),
'Size' => (int) $command->getRequest()->getBody()->getContentLength(),
'LastModified' => gmdate(DateFormat::RFC2822)
)));
$eventData['command'] = $command;
// Notify any listeners the the part was uploaded
$this->dispatch(self::AFTER_PART_UPLOAD, $eventData);
}
}
}
/**
* Prepare the entity body handles to use while transferring
*
* @param int $concurrency Number of parts to prepare
*
* @return array Parts to send
*/
protected function prepareParts($concurrency)
{
$url = $this->source->getUri();
// Use the source EntityBody as the first part
$parts = array(new ReadLimitEntityBody($this->source, $this->partSize));
// Open EntityBody handles for each part to upload in parallel
for ($i = 1; $i < $concurrency; $i++) {
$parts[] = new ReadLimitEntityBody(new EntityBody(fopen($url, 'r')), $this->partSize);
}
return $parts;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/MultipartUpload/AbstractTransfer.php 0000644 00000006414 15132770567 0024004 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model\MultipartUpload;
use Aws\Common\Enum\UaString as Ua;
use Aws\Common\Exception\RuntimeException;
use Aws\Common\Model\MultipartUpload\AbstractTransfer as CommonAbstractTransfer;
use Guzzle\Service\Command\OperationCommand;
/**
* Abstract class for transfer commonalities
*/
abstract class AbstractTransfer extends CommonAbstractTransfer
{
// An S3 upload part can be anywhere from 5 MB to 5 GB, but you can only have 10000 parts per upload
const MIN_PART_SIZE = 5242880;
const MAX_PART_SIZE = 5368709120;
const MAX_PARTS = 10000;
/**
* {@inheritdoc}
* @throws RuntimeException if the part size can not be calculated from the provided data
*/
protected function init()
{
// Merge provided options onto the default option values
$this->options = array_replace(array(
'min_part_size' => self::MIN_PART_SIZE,
'part_md5' => true
), $this->options);
// Make sure the part size can be calculated somehow
if (!$this->options['min_part_size'] && !$this->source->getContentLength()) {
throw new RuntimeException('The ContentLength of the data source could not be determined, and no '
. 'min_part_size option was provided');
}
}
/**
* {@inheritdoc}
*/
protected function calculatePartSize()
{
$partSize = $this->source->getContentLength()
? (int) ceil(($this->source->getContentLength() / self::MAX_PARTS))
: self::MIN_PART_SIZE;
$partSize = max($this->options['min_part_size'], $partSize);
$partSize = min($partSize, self::MAX_PART_SIZE);
$partSize = max($partSize, self::MIN_PART_SIZE);
return $partSize;
}
/**
* {@inheritdoc}
*/
protected function complete()
{
/** @var UploadPart $part */
$parts = array();
foreach ($this->state as $part) {
$parts[] = array(
'PartNumber' => $part->getPartNumber(),
'ETag' => $part->getETag(),
);
}
$params = $this->state->getUploadId()->toParams();
$params[Ua::OPTION] = Ua::MULTIPART_UPLOAD;
$params['Parts'] = $parts;
$command = $this->client->getCommand('CompleteMultipartUpload', $params);
return $command->getResult();
}
/**
* {@inheritdoc}
*/
protected function getAbortCommand()
{
$params = $this->state->getUploadId()->toParams();
$params[Ua::OPTION] = Ua::MULTIPART_UPLOAD;
/** @var OperationCommand $command */
$command = $this->client->getCommand('AbortMultipartUpload', $params);
return $command;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/MultipartUpload/UploadPart.php 0000644 00000003204 15132770567 0022601 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model\MultipartUpload;
use Aws\Common\Model\MultipartUpload\AbstractUploadPart;
/**
* An object that encapsulates the data for a Glacier upload operation
*/
class UploadPart extends AbstractUploadPart
{
/**
* {@inheritdoc}
*/
protected static $keyMap = array(
'PartNumber' => 'partNumber',
'ETag' => 'eTag',
'LastModified' => 'lastModified',
'Size' => 'size'
);
/**
* @var string The ETag for this part
*/
protected $eTag;
/**
* @var string The last modified date
*/
protected $lastModified;
/**
* @var int The size (or content-length) in bytes of the upload body
*/
protected $size;
/**
* @return string
*/
public function getETag()
{
return $this->eTag;
}
/**
* @return string
*/
public function getLastModified()
{
return $this->lastModified;
}
/**
* @return int
*/
public function getSize()
{
return $this->size;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/MultipartUpload/UploadId.php 0000644 00000001770 15132770567 0022235 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model\MultipartUpload;
use Aws\Common\Model\MultipartUpload\AbstractUploadId;
/**
* An object that encapsulates the identification for a Glacier upload part
* @codeCoverageIgnore
*/
class UploadId extends AbstractUploadId
{
/**
* {@inheritdoc}
*/
protected static $expectedValues = array(
'Bucket' => false,
'Key' => false,
'UploadId' => false
);
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/MultipartUpload/TransferState.php 0000644 00000002371 15132770567 0023317 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model\MultipartUpload;
use Aws\Common\Client\AwsClientInterface;
use Aws\Common\Model\MultipartUpload\AbstractTransferState;
use Aws\Common\Model\MultipartUpload\UploadIdInterface;
/**
* State of a multipart upload
*/
class TransferState extends AbstractTransferState
{
/**
* {@inheritdoc}
*/
public static function fromUploadId(AwsClientInterface $client, UploadIdInterface $uploadId)
{
$transferState = new self($uploadId);
foreach ($client->getIterator('ListParts', $uploadId->toParams()) as $part) {
$transferState->addPart(UploadPart::fromArray($part));
}
return $transferState;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/Acp.php 0000644 00000014452 15132770567 0016112 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model;
use Aws\Common\Exception\InvalidArgumentException;
use Aws\Common\Exception\OverflowException;
use Guzzle\Common\ToArrayInterface;
use Guzzle\Service\Command\AbstractCommand;
/**
* Amazon S3 Access Control Policy (ACP)
*/
class Acp implements ToArrayInterface, \IteratorAggregate, \Countable
{
/**
* @var \SplObjectStorage List of grants on the ACP
*/
protected $grants = array();
/**
* @var Grantee The owner of the ACP
*/
protected $owner;
/**
* Constructs an ACP
*
* @param Grantee $owner ACP policy owner
* @param array|\Traversable $grants List of grants for the ACP
*/
public function __construct(Grantee $owner, $grants = null)
{
$this->setOwner($owner);
$this->setGrants($grants);
}
/**
* Create an Acp object from an array. This can be used to create an ACP from a response to a GetObject/Bucket ACL
* operation.
*
* @param array $data Array of ACP data
*
* @return Acp
*/
public static function fromArray(array $data)
{
$builder = new AcpBuilder();
$builder->setOwner((string) $data['Owner']['ID'], $data['Owner']['DisplayName']);
// Add each Grantee to the ACP
foreach ($data['Grants'] as $grant) {
$permission = $grant['Permission'];
// Determine the type for response bodies that are missing the Type parameter
if (!isset($grant['Grantee']['Type'])) {
if (isset($grant['Grantee']['ID'])) {
$grant['Grantee']['Type'] = 'CanonicalUser';
} elseif (isset($grant['Grantee']['URI'])) {
$grant['Grantee']['Type'] = 'Group';
} else {
$grant['Grantee']['Type'] = 'AmazonCustomerByEmail';
}
}
switch ($grant['Grantee']['Type']) {
case 'Group':
$builder->addGrantForGroup($permission, $grant['Grantee']['URI']);
break;
case 'AmazonCustomerByEmail':
$builder->addGrantForEmail($permission, $grant['Grantee']['EmailAddress']);
break;
case 'CanonicalUser':
$builder->addGrantForUser(
$permission,
$grant['Grantee']['ID'],
$grant['Grantee']['DisplayName']
);
}
}
return $builder->build();
}
/**
* Set the owner of the ACP policy
*
* @param Grantee $owner ACP policy owner
*
* @return $this
*
* @throws InvalidArgumentException if the grantee does not have an ID set
*/
public function setOwner(Grantee $owner)
{
if (!$owner->isCanonicalUser()) {
throw new InvalidArgumentException('The owner must have an ID set.');
}
$this->owner = $owner;
return $this;
}
/**
* Get the owner of the ACP policy
*
* @return Grantee
*/
public function getOwner()
{
return $this->owner;
}
/**
* Set the grants for the ACP
*
* @param array|\Traversable $grants List of grants for the ACP
*
* @return $this
*
* @throws InvalidArgumentException
*/
public function setGrants($grants = array())
{
$this->grants = new \SplObjectStorage();
if ($grants) {
if (is_array($grants) || $grants instanceof \Traversable) {
/** @var Grant $grant */
foreach ($grants as $grant) {
$this->addGrant($grant);
}
} else {
throw new InvalidArgumentException('Grants must be passed in as an array or Traversable object.');
}
}
return $this;
}
/**
* Get all of the grants
*
* @return \SplObjectStorage
*/
public function getGrants()
{
return $this->grants;
}
/**
* Add a Grant
*
* @param Grant $grant Grant to add
*
* @return $this
*/
public function addGrant(Grant $grant)
{
if (count($this->grants) < 100) {
$this->grants->attach($grant);
} else {
throw new OverflowException('An ACP may contain up to 100 grants.');
}
return $this;
}
/**
* Get the total number of attributes
*
* @return int
*/
public function count()
{
return count($this->grants);
}
/**
* Returns the grants for iteration
*
* @return \SplObjectStorage
*/
public function getIterator()
{
return $this->grants;
}
/**
* Applies grant headers to a command's parameters
*
* @param AbstractCommand $command Command to be updated
*
* @return $this
*/
public function updateCommand(AbstractCommand $command)
{
$parameters = array();
foreach ($this->grants as $grant) {
/** @var Grant $grant */
$parameters = array_merge_recursive($parameters, $grant->getParameterArray());
}
foreach ($parameters as $name => $values) {
$command->set($name, implode(', ', (array) $values));
}
return $this;
}
/**
* {@inheritdoc}
*/
public function toArray()
{
$grants = array();
foreach ($this->grants as $grant) {
$grants[] = $grant->toArray();
}
return array(
'Owner' => array(
'ID' => $this->owner->getId(),
'DisplayName' => $this->owner->getDisplayName()
),
'Grants' => $grants
);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/DeleteObjectsTransfer.php 0000644 00000007612 15132770567 0021630 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model;
use Aws\Common\Client\AwsClientInterface;
use Aws\Common\Exception\OverflowException;
use Aws\Common\Enum\UaString as Ua;
use Aws\S3\Exception\InvalidArgumentException;
use Aws\S3\Exception\DeleteMultipleObjectsException;
use Guzzle\Batch\BatchTransferInterface;
use Guzzle\Service\Command\CommandInterface;
/**
* Transfer logic for deleting multiple objects from an Amazon S3 bucket in a
* single request
*/
class DeleteObjectsTransfer implements BatchTransferInterface
{
/**
* @var AwsClientInterface The Amazon S3 client for doing transfers
*/
protected $client;
/**
* @var string Bucket from which to delete the objects
*/
protected $bucket;
/**
* @var string MFA token to apply to the request
*/
protected $mfa;
/**
* Constructs a transfer using the injected client
*
* @param AwsClientInterface $client Client used to transfer the requests
* @param string $bucket Name of the bucket that stores the objects
* @param string $mfa MFA token used when contacting the Amazon S3 API
*/
public function __construct(AwsClientInterface $client, $bucket, $mfa = null)
{
$this->client = $client;
$this->bucket = $bucket;
$this->mfa = $mfa;
}
/**
* Set a new MFA token value
*
* @param string $token MFA token
*
* @return $this
*/
public function setMfa($token)
{
$this->mfa = $token;
return $this;
}
/**
* {@inheritdoc}
* @throws OverflowException if a batch has more than 1000 items
* @throws InvalidArgumentException when an invalid batch item is encountered
*/
public function transfer(array $batch)
{
if (empty($batch)) {
return;
}
if (count($batch) > 1000) {
throw new OverflowException('Batches should be divided into chunks of no larger than 1000 keys');
}
$del = array();
$command = $this->client->getCommand('DeleteObjects', array(
'Bucket' => $this->bucket,
Ua::OPTION => Ua::BATCH
));
if ($this->mfa) {
$command->getRequestHeaders()->set('x-amz-mfa', $this->mfa);
}
foreach ($batch as $object) {
// Ensure that the batch item is valid
if (!is_array($object) || !isset($object['Key'])) {
throw new InvalidArgumentException('Invalid batch item encountered: ' . esc_html(var_export($batch, true)));
}
$del[] = array(
'Key' => $object['Key'],
'VersionId' => isset($object['VersionId']) ? $object['VersionId'] : null
);
}
$command['Objects'] = $del;
$command->execute();
$this->processResponse($command);
}
/**
* Process the response of the DeleteMultipleObjects request
*
* @paramCommandInterface $command Command executed
*/
protected function processResponse(CommandInterface $command)
{
$result = $command->getResult();
// Ensure that the objects were deleted successfully
if (!empty($result['Errors'])) {
$errors = $result['Errors'];
throw new DeleteMultipleObjectsException(esc_html($errors));
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/ClearBucket.php 0000644 00000012655 15132770567 0017576 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model;
use Aws\Common\Client\AwsClientInterface;
use Guzzle\Common\AbstractHasDispatcher;
use Guzzle\Batch\FlushingBatch;
use Guzzle\Batch\ExceptionBufferingBatch;
use Guzzle\Batch\NotifyingBatch;
use Guzzle\Common\Exception\ExceptionCollection;
/**
* Class used to clear the contents of a bucket or the results of an iterator
*/
class ClearBucket extends AbstractHasDispatcher
{
/**
* @var string Event emitted when a batch request has completed
*/
const AFTER_DELETE = 'clear_bucket.after_delete';
/**
* @var string Event emitted before the bucket is cleared
*/
const BEFORE_CLEAR = 'clear_bucket.before_clear';
/**
* @var string Event emitted after the bucket is cleared
*/
const AFTER_CLEAR = 'clear_bucket.after_clear';
/**
* @var AwsClientInterface Client used to execute the requests
*/
protected $client;
/**
* @var AbstractS3ResourceIterator Iterator used to yield keys
*/
protected $iterator;
/**
* @var string MFA used with each request
*/
protected $mfa;
/**
* @param AwsClientInterface $client Client used to execute requests
* @param string $bucket Name of the bucket to clear
*/
public function __construct(AwsClientInterface $client, $bucket)
{
$this->client = $client;
$this->bucket = $bucket;
}
/**
* {@inheritdoc}
*/
public static function getAllEvents()
{
return array(self::AFTER_DELETE, self::BEFORE_CLEAR, self::AFTER_CLEAR);
}
/**
* Set the bucket that is to be cleared
*
* @param string $bucket Name of the bucket to clear
*
* @return $this
*/
public function setBucket($bucket)
{
$this->bucket = $bucket;
return $this;
}
/**
* Get the iterator used to yield the keys to be deleted. A default iterator
* will be created and returned if no iterator has been explicitly set.
*
* @return \Iterator
*/
public function getIterator()
{
if (!$this->iterator) {
$this->iterator = $this->client->getIterator('ListObjectVersions', array(
'Bucket' => $this->bucket
));
}
return $this->iterator;
}
/**
* Sets a different iterator to use than the default iterator. This can be helpful when you wish to delete
* only specific keys from a bucket (e.g. keys that match a certain prefix or delimiter, or perhaps keys that
* pass through a filtered, decorated iterator).
*
* @param \Iterator $iterator Iterator used to yield the keys to be deleted
*
* @return $this
*/
public function setIterator(\Iterator $iterator)
{
$this->iterator = $iterator;
return $this;
}
/**
* Set the MFA token to send with each request
*
* @param string $mfa MFA token to send with each request. The value is the concatenation of the authentication
* device's serial number, a space, and the value displayed on your authentication device.
*
* @return $this
*/
public function setMfa($mfa)
{
$this->mfa = $mfa;
return $this;
}
/**
* Clear the bucket
*
* @return int Returns the number of deleted keys
* @throws ExceptionCollection
*/
public function clear()
{
$that = $this;
$batch = DeleteObjectsBatch::factory($this->client, $this->bucket, $this->mfa);
$batch = new NotifyingBatch($batch, function ($items) use ($that) {
$that->dispatch(ClearBucket::AFTER_DELETE, array('keys' => $items));
});
$batch = new FlushingBatch(new ExceptionBufferingBatch($batch), 1000);
// Let any listeners know that the bucket is about to be cleared
$this->dispatch(self::BEFORE_CLEAR, array(
'iterator' => $this->getIterator(),
'batch' => $batch,
'mfa' => $this->mfa
));
$deleted = 0;
foreach ($this->getIterator() as $object) {
if (isset($object['VersionId'])) {
$versionId = $object['VersionId'] == 'null' ? null : $object['VersionId'];
} else {
$versionId = null;
}
$batch->addKey($object['Key'], $versionId);
$deleted++;
}
$batch->flush();
// If any errors were encountered, then throw an ExceptionCollection
if (count($batch->getExceptions())) {
$e = new ExceptionCollection();
foreach ($batch->getExceptions() as $exception) {
$e->add($exception->getPrevious());
}
throw $e;
}
// Let any listeners know that the bucket was cleared
$this->dispatch(self::AFTER_CLEAR, array('deleted' => $deleted));
return $deleted;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/Grant.php 0000644 00000006473 15132770567 0016466 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model;
use Aws\S3\Enum\Permission;
use Aws\Common\Exception\InvalidArgumentException;
use Guzzle\Common\ToArrayInterface;
/**
* Amazon S3 Grant model
*/
class Grant implements ToArrayInterface
{
/**
* @var array A map of permissions to operation parameters
*/
protected static $parameterMap = array(
Permission::READ => 'GrantRead',
Permission::WRITE => 'GrantWrite',
Permission::READ_ACP => 'GrantReadACP',
Permission::WRITE_ACP => 'GrantWriteACP',
Permission::FULL_CONTROL => 'GrantFullControl'
);
/**
* @var Grantee The grantee affected by the grant
*/
protected $grantee;
/**
* @var string The permission set by the grant
*/
protected $permission;
/**
* Constructs an ACL
*
* @param Grantee $grantee Affected grantee
* @param string $permission Permission applied
*/
public function __construct(Grantee $grantee, $permission)
{
$this->setGrantee($grantee);
$this->setPermission($permission);
}
/**
* Set the grantee affected by the grant
*
* @param Grantee $grantee Affected grantee
*
* @return $this
*/
public function setGrantee(Grantee $grantee)
{
$this->grantee = $grantee;
return $this;
}
/**
* Get the grantee affected by the grant
*
* @return Grantee
*/
public function getGrantee()
{
return $this->grantee;
}
/**
* Set the permission set by the grant
*
* @param string $permission Permission applied
*
* @return $this
*
* @throws InvalidArgumentException
*/
public function setPermission($permission)
{
$valid = Permission::values();
if (!in_array($permission, $valid)) {
throw new InvalidArgumentException('The permission must be one of '
. 'the following: ' . esc_html(implode(', ', $valid)) . '.');
}
$this->permission = $permission;
return $this;
}
/**
* Get the permission set by the grant
*
* @return string
*/
public function getPermission()
{
return $this->permission;
}
/**
* Returns an array of the operation parameter and value to set on the operation
*
* @return array
*/
public function getParameterArray()
{
return array(
self::$parameterMap[$this->permission] => $this->grantee->getHeaderValue()
);
}
/**
* {@inheritdoc}
*/
public function toArray()
{
return array(
'Grantee' => $this->grantee->toArray(),
'Permission' => $this->permission
);
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Model/PostObject.php 0000644 00000021612 15132770567 0017457 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Model;
use Aws\Common\Enum\DateFormat;
use Aws\S3\S3Client;
use Guzzle\Common\Collection;
use Guzzle\Http\Url;
/**
* Encapsulates the logic for getting the data for an S3 object POST upload form
*/
class PostObject extends Collection
{
/**
* @var S3Client The S3 client being used to sign the policy
*/
protected $client;
/**
* @var string The bucket name where the object will be posted
*/
protected $bucket;
/**
* @var array The <form> tag attributes as an array
*/
protected $formAttributes;
/**
* @var array The form's <input> elements as an array
*/
protected $formInputs;
/**
* @var string The raw json policy
*/
protected $jsonPolicy;
/**
* Constructs the PostObject
*
* The options array accepts the following keys:
*
* - acl: The access control setting to apply to the uploaded file. Accepts any of the
* CannedAcl constants
* - Cache-Control: The Cache-Control HTTP header value to apply to the uploaded file
* - Content-Disposition: The Content-Disposition HTTP header value to apply to the uploaded file
* - Content-Encoding: The Content-Encoding HTTP header value to apply to the uploaded file
* - Content-Type: The Content-Type HTTP header value to apply to the uploaded file. The default
* value is `application/octet-stream`
* - Expires: The Expires HTTP header value to apply to the uploaded file
* - key: The location where the file should be uploaded to. The default value is
* `^${filename}` which will use the name of the uploaded file
* - policy: A raw policy in JSON format. By default, the PostObject creates one for you
* - policy_callback: A callback used to modify the policy before encoding and signing it. The
* method signature for the callback should accept an array of the policy data as
* the 1st argument, (optionally) the PostObject as the 2nd argument, and return
* the policy data with the desired modifications.
* - success_action_redirect: The URI for Amazon S3 to redirect to upon successful upload
* - success_action_status: The status code for Amazon S3 to return upon successful upload
* - ttd: The expiration time for the generated upload form data
* - x-amz-meta-*: Any custom meta tag that should be set to the object
* - x-amz-server-side-encryption: The server-side encryption mechanism to use
* - x-amz-storage-class: The storage setting to apply to the object
* - x-amz-server-side-encryption-customer-algorithm: The SSE-C algorithm
* - x-amz-server-side-encryption-customer-key: The SSE-C customer secret key
* - x-amz-server-side-encryption-customer-key-MD5: The MD5 hash of the SSE-C customer secret key
*
* For the Cache-Control, Content-Disposition, Content-Encoding,
* Content-Type, Expires, and key options, to use a "starts-with" comparison
* instead of an equals comparison, prefix the value with a ^ (carat)
* character
*
* @param S3Client $client
* @param $bucket
* @param array $options
*/
public function __construct(S3Client $client, $bucket, array $options = array())
{
$this->setClient($client);
$this->setBucket($bucket);
parent::__construct($options);
}
/**
* Analyzes the provided data and turns it into useful data that can be
* consumed and used to build an upload form
*
* @return PostObject
*/
public function prepareData()
{
// Validate required options
$options = Collection::fromConfig($this->data, array(
'ttd' => '+1 hour',
'key' => '^${filename}',
));
// Format ttd option
$ttd = $options['ttd'];
$ttd = is_numeric($ttd) ? (int) $ttd : strtotime($ttd);
unset($options['ttd']);
// If a policy or policy callback were provided, extract those from the options
$rawJsonPolicy = $options['policy'];
$policyCallback = $options['policy_callback'];
unset($options['policy'], $options['policy_callback']);
// Setup policy document
$policy = array(
'expiration' => gmdate(DateFormat::ISO8601_S3, $ttd),
'conditions' => array(array('bucket' => $this->bucket))
);
// Configure the endpoint/action
$url = Url::factory($this->client->getBaseUrl());
if ($url->getScheme() === 'https' && strpos($this->bucket, '.') !== false) {
// Use path-style URLs
$url->setPath($this->bucket);
} else {
// Use virtual-style URLs
$url->setHost($this->bucket . '.' . $url->getHost());
}
// Setup basic form
$this->formAttributes = array(
'action' => (string) $url,
'method' => 'POST',
'enctype' => 'multipart/form-data'
);
$this->formInputs = array(
'AWSAccessKeyId' => $this->client->getCredentials()->getAccessKeyId()
);
// Add success action status
$status = (int) $options->get('success_action_status');
if ($status && in_array($status, array(200, 201, 204))) {
$this->formInputs['success_action_status'] = (string) $status;
$policy['conditions'][] = array(
'success_action_status' => (string) $status
);
unset($options['success_action_status']);
}
// Add other options
foreach ($options as $key => $value) {
$value = (string) $value;
if ($value[0] === '^') {
$value = substr($value, 1);
$this->formInputs[$key] = $value;
$value = preg_replace('/\$\{(\w*)\}/', '', $value);
$policy['conditions'][] = array('starts-with', '$' . $key, $value);
} else {
$this->formInputs[$key] = $value;
$policy['conditions'][] = array($key => $value);
}
}
// Handle the policy
$policy = is_callable($policyCallback) ? $policyCallback($policy, $this) : $policy;
$this->jsonPolicy = $rawJsonPolicy ?: json_encode($policy);
$this->applyPolicy();
return $this;
}
/**
* Sets the S3 client
*
* @param S3Client $client
*
* @return PostObject
*/
public function setClient(S3Client $client)
{
$this->client = $client;
return $this;
}
/**
* Gets the S3 client
*
* @return S3Client
*/
public function getClient()
{
return $this->client;
}
/**
* Sets the bucket and makes sure it is a valid bucket name
*
* @param string $bucket
*
* @return PostObject
*/
public function setBucket($bucket)
{
$this->bucket = $bucket;
return $this;
}
/**
* Gets the bucket name
*
* @return string
*/
public function getBucket()
{
return $this->bucket;
}
/**
* Gets the form attributes as an array
*
* @return array
*/
public function getFormAttributes()
{
return $this->formAttributes;
}
/**
* Gets the form inputs as an array
*
* @return array
*/
public function getFormInputs()
{
return $this->formInputs;
}
/**
* Gets the raw JSON policy
*
* @return string
*/
public function getJsonPolicy()
{
return $this->jsonPolicy;
}
/**
* Handles the encoding, singing, and injecting of the policy
*/
protected function applyPolicy()
{
$jsonPolicy64 = base64_encode($this->jsonPolicy);
$this->formInputs['policy'] = $jsonPolicy64;
$this->formInputs['signature'] = base64_encode(hash_hmac(
'sha1',
$jsonPolicy64,
$this->client->getCredentials()->getSecretKey(),
true
));
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Command/S3Command.php 0000644 00000003732 15132770567 0017510 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Command;
use Guzzle\Service\Command\OperationCommand;
use Guzzle\Service\Resource\Model;
use Guzzle\Common\Event;
/**
* Adds functionality to Amazon S3 commands:
* - Adds the PutObject URL to a response
* - Allows creating a Pre-signed URL from any command
*/
class S3Command extends OperationCommand
{
/**
* Create a pre-signed URL for the operation
*
* @param int|string $expires The Unix timestamp to expire at or a string that can be evaluated by strtotime
*
* @return string
*/
public function createPresignedUrl($expires)
{
return $this->client->createPresignedUrl($this->prepare(), $expires);
}
/**
* {@inheritdoc}
*/
protected function process()
{
$request = $this->getRequest();
$response = $this->getResponse();
// Dispatch an error if a 301 redirect occurred
if ($response->getStatusCode() == 301) {
$this->getClient()->getEventDispatcher()->dispatch('request.error', new Event(array(
'request' => $this->getRequest(),
'response' => $response
)));
}
parent::process();
// Set the GetObject URL if using the PutObject operation
if ($this->result instanceof Model && $this->getName() == 'PutObject') {
$this->result->set('ObjectURL', $request->getUrl());
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/IncompleteMultipartUploadChecker.php 0000644 00000003642 15132770567 0023001 0 ustar 00 <?php
namespace Aws\S3;
use Guzzle\Http\Exception\HttpException;
use Guzzle\Http\Message\RequestInterface;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\Response;
use Guzzle\Plugin\Backoff\BackoffStrategyInterface;
use Guzzle\Plugin\Backoff\AbstractBackoffStrategy;
/**
* Retries CompleteMultipartUpload requests in the case of failure.
*
* From the S3 API Documentation:
*
* Processing of a Complete Multipart Upload request could take several
* minutes to complete. After Amazon S3 begins processing the request, it
* sends an HTTP response header that specifies a 200 OK response. While
* processing is in progress, Amazon S3 periodically sends whitespace
* characters to keep the connection from timing out. Because a request
* could fail after the initial 200 OK response has been sent, it is
* important that you check the response body to determine whether the
* request succeeded. Note that if Complete Multipart Upload fails,
* applications should be prepared to retry the failed requests.
*/
class IncompleteMultipartUploadChecker extends AbstractBackoffStrategy
{
public function __construct(BackoffStrategyInterface $next = null)
{
if ($next) {
$this->setNext($next);
}
}
public function makesDecision()
{
return true;
}
protected function getDelay(
$retries,
RequestInterface $request,
Response $response = null,
HttpException $e = null
) {
if ($response && $request->getMethod() === 'POST'
&& $request instanceof EntityEnclosingRequestInterface
&& $response->getStatusCode() == 200
&& strpos($request->getBody(), '<CompleteMultipartUpload xmlns') !== false
&& strpos($response->getBody(), '<CompleteMultipartUploadResult xmlns') === false
) {
return true;
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/S3SignatureInterface.php 0000644 00000001345 15132770567 0020334 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3;
use Aws\Common\Signature\SignatureInterface;
/**
* @deprecated
*/
interface S3SignatureInterface extends SignatureInterface {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/S3Md5Listener.php 0000644 00000004453 15132770567 0016710 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3;
use Aws\Common\Signature\SignatureV4;
use Aws\Common\Signature\SignatureInterface;
use Guzzle\Common\Event;
use Guzzle\Service\Command\CommandInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Adds required and optional Content-MD5 headers
*/
class S3Md5Listener implements EventSubscriberInterface
{
/** @var S3SignatureInterface */
private $signature;
public static function getSubscribedEvents()
{
return array('command.after_prepare' => 'onCommandAfterPrepare');
}
public function __construct(SignatureInterface $signature)
{
$this->signature = $signature;
}
public function onCommandAfterPrepare(Event $event)
{
$command = $event['command'];
$operation = $command->getOperation();
if ($operation->getData('contentMd5')) {
// Add the MD5 if it is required for all signers
$this->addMd5($command);
} elseif ($operation->hasParam('ContentMD5')) {
$value = $command['ContentMD5'];
// Add a computed MD5 if the parameter is set to true or if
// not using Signature V4 and the value is not set (null).
if ($value === true ||
($value === null && !($this->signature instanceof SignatureV4))
) {
$this->addMd5($command);
}
}
}
private function addMd5(CommandInterface $command)
{
$request = $command->getRequest();
$body = $request->getBody();
if ($body && $body->getSize() > 0) {
if (false !== ($md5 = $body->getContentMd5(true, true))) {
$request->setHeader('Content-MD5', $md5);
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/StreamWrapper.php 0000644 00000071021 15132770567 0017136 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3;
use Aws\Common\Exception\RuntimeException;
use Aws\S3\Exception\S3Exception;
use Aws\S3\Exception\NoSuchKeyException;
use Aws\S3\Iterator\ListObjectsIterator;
use Guzzle\Http\EntityBody;
use Guzzle\Http\CachingEntityBody;
use Guzzle\Http\Mimetypes;
use Guzzle\Iterator\FilterIterator;
use Guzzle\Stream\PhpStreamRequestFactory;
use Guzzle\Service\Command\CommandInterface;
/**
* Amazon S3 stream wrapper to use "s3://<bucket>/<key>" files with PHP streams, supporting "r", "w", "a", "x".
*
* # Supported stream related PHP functions:
* - fopen, fclose, fread, fwrite, fseek, ftell, feof, fflush
* - opendir, closedir, readdir, rewinddir
* - copy, rename, unlink
* - mkdir, rmdir, rmdir (recursive)
* - file_get_contents, file_put_contents
* - file_exists, filesize, is_file, is_dir
*
* # Opening "r" (read only) streams:
*
* Read only streams are truly streaming by default and will not allow you to seek. This is because data
* read from the stream is not kept in memory or on the local filesystem. You can force a "r" stream to be seekable
* by setting the "seekable" stream context option true. This will allow true streaming of data from Amazon S3, but
* will maintain a buffer of previously read bytes in a 'php://temp' stream to allow seeking to previously read bytes
* from the stream.
*
* You may pass any GetObject parameters as 's3' stream context options. These options will affect how the data is
* downloaded from Amazon S3.
*
* # Opening "w" and "x" (write only) streams:
*
* Because Amazon S3 requires a Content-Length header, write only streams will maintain a 'php://temp' stream to buffer
* data written to the stream until the stream is flushed (usually by closing the stream with fclose).
*
* You may pass any PutObject parameters as 's3' stream context options. These options will affect how the data is
* uploaded to Amazon S3.
*
* When opening an "x" stream, the file must exist on Amazon S3 for the stream to open successfully.
*
* # Opening "a" (write only append) streams:
*
* Similar to "w" streams, opening append streams requires that the data be buffered in a "php://temp" stream. Append
* streams will attempt to download the contents of an object in Amazon S3, seek to the end of the object, then allow
* you to append to the contents of the object. The data will then be uploaded using a PutObject operation when the
* stream is flushed (usually with fclose).
*
* You may pass any GetObject and/or PutObject parameters as 's3' stream context options. These options will affect how
* the data is downloaded and uploaded from Amazon S3.
*
* Stream context options:
*
* - "seekable": Set to true to create a seekable "r" (read only) stream by using a php://temp stream buffer
* - For "unlink" only: Any option that can be passed to the DeleteObject operation
*/
class StreamWrapper
{
/**
* @var resource|null Stream context (this is set by PHP when a context is used)
*/
public $context;
/**
* @var S3Client Client used to send requests
*/
protected static $client;
/**
* @var string Mode the stream was opened with
*/
protected $mode;
/**
* @var EntityBody Underlying stream resource
*/
protected $body;
/**
* @var array Current parameters to use with the flush operation
*/
protected $params;
/**
* @var ListObjectsIterator Iterator used with opendir() and subsequent readdir() calls
*/
protected $objectIterator;
/**
* @var string The bucket that was opened when opendir() was called
*/
protected $openedBucket;
/**
* @var string The prefix of the bucket that was opened with opendir()
*/
protected $openedBucketPrefix;
/**
* @var array The next key to retrieve when using a directory iterator. Helps for fast directory traversal.
*/
protected static $nextStat = array();
/**
* Register the 's3://' stream wrapper
*
* @param S3Client $client Client to use with the stream wrapper
*/
public static function register(S3Client $client)
{
if (in_array('s3', stream_get_wrappers())) {
stream_wrapper_unregister('s3');
}
stream_wrapper_register('s3', get_called_class(), STREAM_IS_URL);
static::$client = $client;
}
/**
* Close the stream
*/
public function stream_close()
{
$this->body = null;
}
/**
* @param string $path
* @param string $mode
* @param int $options
* @param string $opened_path
*
* @return bool
*/
public function stream_open($path, $mode, $options, &$opened_path)
{
// We don't care about the binary flag
$this->mode = $mode = rtrim($mode, 'bt');
$this->params = $params = $this->getParams($path);
$errors = array();
if (!$params['Key']) {
$errors[] = 'Cannot open a bucket. You must specify a path in the form of s3://bucket/key';
}
if (strpos($mode, '+')) {
$errors[] = 'The Amazon S3 stream wrapper does not allow simultaneous reading and writing.';
}
if (!in_array($mode, array('r', 'w', 'a', 'x'))) {
$errors[] = "Mode not supported: {$mode}. Use one 'r', 'w', 'a', or 'x'.";
}
// When using mode "x" validate if the file exists before attempting to read
if ($mode == 'x' && static::$client->doesObjectExist($params['Bucket'], $params['Key'], $this->getOptions())) {
$errors[] = "{$path} already exists on Amazon S3";
}
if (!$errors) {
if ($mode == 'r') {
return $this->openReadStream($params, $errors);
} elseif ($mode == 'a') {
return $this->openAppendStream($params, $errors);
} else {
return $this->openWriteStream($params, $errors);
}
}
return $this->triggerError($errors);
}
/**
* @return bool
*/
public function stream_eof()
{
return $this->body->feof();
}
/**
* @return bool
*/
public function stream_flush()
{
if ($this->mode == 'r') {
return false;
}
$this->body->rewind();
$params = $this->params;
$params['Body'] = $this->body;
// Attempt to guess the ContentType of the upload based on the
// file extension of the key
if (!isset($params['ContentType']) &&
($type = Mimetypes::getInstance()->fromFilename($params['Key']))
) {
$params['ContentType'] = $type;
}
try {
static::$client->putObject($params);
return true;
} catch (\Exception $e) {
return $this->triggerError($e->getMessage());
}
}
/**
* Read data from the underlying stream
*
* @param int $count Amount of bytes to read
*
* @return string
*/
public function stream_read($count)
{
return $this->body->read($count);
}
/**
* Seek to a specific byte in the stream
*
* @param int $offset Seek offset
* @param int $whence Whence (SEEK_SET, SEEK_CUR, SEEK_END)
*
* @return bool
*/
public function stream_seek($offset, $whence = SEEK_SET)
{
return $this->body->seek($offset, $whence);
}
/**
* Get the current position of the stream
*
* @return int Returns the current position in the stream
*/
public function stream_tell()
{
return $this->body->ftell();
}
/**
* Write data the to the stream
*
* @param string $data
*
* @return int Returns the number of bytes written to the stream
*/
public function stream_write($data)
{
return $this->body->write($data);
}
/**
* Delete a specific object
*
* @param string $path
* @return bool
*/
public function unlink($path)
{
try {
$this->clearStatInfo($path);
static::$client->deleteObject($this->getParams($path));
return true;
} catch (\Exception $e) {
return $this->triggerError($e->getMessage());
}
}
/**
* @return array
*/
public function stream_stat()
{
$stat = fstat($this->body->getStream());
// Add the size of the underlying stream if it is known
if ($this->mode == 'r' && $this->body->getSize()) {
$stat[7] = $stat['size'] = $this->body->getSize();
}
return $stat;
}
/**
* Provides information for is_dir, is_file, filesize, etc. Works on buckets, keys, and prefixes
*
* @param string $path
* @param int $flags
*
* @return array Returns an array of stat data
* @link http://www.php.net/manual/en/streamwrapper.url-stat.php
*/
public function url_stat($path, $flags)
{
// Check if this path is in the url_stat cache
if (isset(static::$nextStat[$path])) {
return static::$nextStat[$path];
}
$parts = $this->getParams($path);
if (!$parts['Key']) {
// Stat "directories": buckets, or "s3://"
if (!$parts['Bucket'] || static::$client->doesBucketExist($parts['Bucket'])) {
return $this->formatUrlStat($path);
} else {
return $this->triggerError("File or directory not found: {$path}", $flags);
}
}
try {
try {
$result = static::$client->headObject($parts)->toArray();
if (substr($parts['Key'], -1, 1) == '/' && $result['ContentLength'] == 0) {
// Return as if it is a bucket to account for console bucket objects (e.g., zero-byte object "foo/")
return $this->formatUrlStat($path);
} else {
// Attempt to stat and cache regular object
return $this->formatUrlStat($result);
}
} catch (NoSuchKeyException $e) {
// Maybe this isn't an actual key, but a prefix. Do a prefix listing of objects to determine.
$result = static::$client->listObjects(array(
'Bucket' => $parts['Bucket'],
'Prefix' => rtrim($parts['Key'], '/') . '/',
'MaxKeys' => 1
));
if (!$result['Contents'] && !$result['CommonPrefixes']) {
return $this->triggerError("File or directory not found: {$path}", $flags);
}
// This is a directory prefix
return $this->formatUrlStat($path);
}
} catch (\Exception $e) {
return $this->triggerError($e->getMessage(), $flags);
}
}
/**
* Support for mkdir().
*
* @param string $path Directory which should be created.
* @param int $mode Permissions. 700-range permissions map to ACL_PUBLIC. 600-range permissions map to
* ACL_AUTH_READ. All other permissions map to ACL_PRIVATE. Expects octal form.
* @param int $options A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.
*
* @return bool
* @link http://www.php.net/manual/en/streamwrapper.mkdir.php
*/
public function mkdir($path, $mode, $options)
{
$params = $this->getParams($path);
if (!$params['Bucket']) {
return false;
}
if (!isset($params['ACL'])) {
$params['ACL'] = $this->determineAcl($mode);
}
return !isset($params['Key']) || $params['Key'] === '/'
? $this->createBucket($path, $params)
: $this->createPseudoDirectory($path, $params);
}
/**
* Remove a bucket from Amazon S3
*
* @param string $path the directory path
* @param int $options A bitwise mask of values
*
* @return bool true if directory was successfully removed
* @link http://www.php.net/manual/en/streamwrapper.rmdir.php
*/
public function rmdir($path, $options)
{
$params = $this->getParams($path);
if (!$params['Bucket']) {
return $this->triggerError('You cannot delete s3://. Please specify a bucket.');
}
try {
if (!$params['Key']) {
static::$client->deleteBucket(array('Bucket' => $params['Bucket']));
$this->clearStatInfo($path);
return true;
}
// Use a key that adds a trailing slash if needed.
$prefix = rtrim($params['Key'], '/') . '/';
$result = static::$client->listObjects(array(
'Bucket' => $params['Bucket'],
'Prefix' => $prefix,
'MaxKeys' => 1
));
// Check if the bucket contains keys other than the placeholder
if ($result['Contents']) {
foreach ($result['Contents'] as $key) {
if ($key['Key'] == $prefix) {
continue;
}
return $this->triggerError('Psuedo folder is not empty');
}
return $this->unlink(rtrim($path, '/') . '/');
}
return $result['CommonPrefixes']
? $this->triggerError('Pseudo folder contains nested folders')
: true;
} catch (\Exception $e) {
return $this->triggerError($e->getMessage());
}
}
/**
* Support for opendir().
*
* The opendir() method of the Amazon S3 stream wrapper supports a stream
* context option of "listFilter". listFilter must be a callable that
* accepts an associative array of object data and returns true if the
* object should be yielded when iterating the keys in a bucket.
*
* @param string $path The path to the directory (e.g. "s3://dir[</prefix>]")
* @param string $options Whether or not to enforce safe_mode (0x04). Unused.
*
* @return bool true on success
* @see http://www.php.net/manual/en/function.opendir.php
*/
public function dir_opendir($path, $options)
{
// Reset the cache
$this->clearStatInfo();
$params = $this->getParams($path);
$delimiter = $this->getOption('delimiter');
$filterFn = $this->getOption('listFilter');
if ($delimiter === null) {
$delimiter = '/';
}
if ($params['Key']) {
$params['Key'] = rtrim($params['Key'], $delimiter) . $delimiter;
}
$this->openedBucket = $params['Bucket'];
$this->openedBucketPrefix = $params['Key'];
$operationParams = array('Bucket' => $params['Bucket'], 'Prefix' => $params['Key']);
if ($delimiter) {
$operationParams['Delimiter'] = $delimiter;
}
$objectIterator = static::$client->getIterator('ListObjects', $operationParams, array(
'return_prefixes' => true,
'sort_results' => true
));
// Filter our "/" keys added by the console as directories, and ensure
// that if a filter function is provided that it passes the filter.
$this->objectIterator = new FilterIterator(
$objectIterator,
function ($key) use ($filterFn) {
// Each yielded results can contain a "Key" or "Prefix"
return (!$filterFn || call_user_func($filterFn, $key)) &&
(!isset($key['Key']) || substr($key['Key'], -1, 1) !== '/');
}
);
$this->objectIterator->next();
return true;
}
/**
* Close the directory listing handles
*
* @return bool true on success
*/
public function dir_closedir()
{
$this->objectIterator = null;
return true;
}
/**
* This method is called in response to rewinddir()
*
* @return boolean true on success
*/
public function dir_rewinddir()
{
$this->clearStatInfo();
$this->objectIterator->rewind();
return true;
}
/**
* This method is called in response to readdir()
*
* @return string Should return a string representing the next filename, or false if there is no next file.
*
* @link http://www.php.net/manual/en/function.readdir.php
*/
public function dir_readdir()
{
// Skip empty result keys
if (!$this->objectIterator->valid()) {
return false;
}
$current = $this->objectIterator->current();
if (isset($current['Prefix'])) {
// Include "directories". Be sure to strip a trailing "/"
// on prefixes.
$prefix = rtrim($current['Prefix'], '/');
$result = str_replace($this->openedBucketPrefix, '', $prefix);
$key = "s3://{$this->openedBucket}/{$prefix}";
$stat = $this->formatUrlStat($prefix);
} else {
// Remove the prefix from the result to emulate other
// stream wrappers.
$result = str_replace($this->openedBucketPrefix, '', $current['Key']);
$key = "s3://{$this->openedBucket}/{$current['Key']}";
$stat = $this->formatUrlStat($current);
}
// Cache the object data for quick url_stat lookups used with
// RecursiveDirectoryIterator.
static::$nextStat = array($key => $stat);
$this->objectIterator->next();
return $result;
}
/**
* Called in response to rename() to rename a file or directory. Currently only supports renaming objects.
*
* @param string $path_from the path to the file to rename
* @param string $path_to the new path to the file
*
* @return bool true if file was successfully renamed
* @link http://www.php.net/manual/en/function.rename.php
*/
public function rename($path_from, $path_to)
{
$partsFrom = $this->getParams($path_from);
$partsTo = $this->getParams($path_to);
$this->clearStatInfo($path_from);
$this->clearStatInfo($path_to);
if (!$partsFrom['Key'] || !$partsTo['Key']) {
return $this->triggerError('The Amazon S3 stream wrapper only supports copying objects');
}
try {
// Copy the object and allow overriding default parameters if desired, but by default copy metadata
static::$client->copyObject($this->getOptions() + array(
'Bucket' => $partsTo['Bucket'],
'Key' => $partsTo['Key'],
'CopySource' => '/' . $partsFrom['Bucket'] . '/' . rawurlencode($partsFrom['Key']),
'MetadataDirective' => 'COPY'
));
// Delete the original object
static::$client->deleteObject(array(
'Bucket' => $partsFrom['Bucket'],
'Key' => $partsFrom['Key']
) + $this->getOptions());
} catch (\Exception $e) {
return $this->triggerError($e->getMessage());
}
return true;
}
/**
* Cast the stream to return the underlying file resource
*
* @param int $cast_as STREAM_CAST_FOR_SELECT or STREAM_CAST_AS_STREAM
*
* @return resource
*/
public function stream_cast($cast_as)
{
return $this->body->getStream();
}
/**
* Get the stream context options available to the current stream
*
* @return array
*/
protected function getOptions()
{
$context = $this->context ?: stream_context_get_default();
$options = stream_context_get_options($context);
return isset($options['s3']) ? $options['s3'] : array();
}
/**
* Get a specific stream context option
*
* @param string $name Name of the option to retrieve
*
* @return mixed|null
*/
protected function getOption($name)
{
$options = $this->getOptions();
return isset($options[$name]) ? $options[$name] : null;
}
/**
* Get the bucket and key from the passed path (e.g. s3://bucket/key)
*
* @param string $path Path passed to the stream wrapper
*
* @return array Hash of 'Bucket', 'Key', and custom params
*/
protected function getParams($path)
{
$parts = explode('/', substr($path, 5), 2);
$params = $this->getOptions();
unset($params['seekable']);
return array(
'Bucket' => $parts[0],
'Key' => isset($parts[1]) ? $parts[1] : null
) + $params;
}
/**
* Serialize and sign a command, returning a request object
*
* @param CommandInterface $command Command to sign
*
* @return RequestInterface
*/
protected function getSignedRequest($command)
{
$request = $command->prepare();
$request->dispatch('request.before_send', array('request' => $request));
return $request;
}
/**
* Initialize the stream wrapper for a read only stream
*
* @param array $params Operation parameters
* @param array $errors Any encountered errors to append to
*
* @return bool
*/
protected function openReadStream(array $params, array &$errors)
{
// Create the command and serialize the request
$request = $this->getSignedRequest(static::$client->getCommand('GetObject', $params));
// Create a stream that uses the EntityBody object
$factory = $this->getOption('stream_factory') ?: new PhpStreamRequestFactory();
$this->body = $factory->fromRequest($request, array(), array('stream_class' => 'Guzzle\Http\EntityBody'));
// Headers are placed in the "wrapper_data" array. The array of headers
// is simply an array of header lines of which the first line is the
// status line of the HTTP response.
$headers = $this->body->getMetaData('wrapper_data');
if ($headers && isset($headers[0])) {
$statusParts = explode(' ', $headers[0]);
$status = $statusParts[1];
if ($status != 200) {
return $this->triggerError('Cannot open file: ' . $this->body);
}
}
// Wrap the body in a caching entity body if seeking is allowed
if ($this->getOption('seekable')) {
$this->body = new CachingEntityBody($this->body);
}
return true;
}
/**
* Initialize the stream wrapper for a write only stream
*
* @param array $params Operation parameters
* @param array $errors Any encountered errors to append to
*
* @return bool
*/
protected function openWriteStream(array $params, array &$errors)
{
$this->body = new EntityBody(fopen('php://temp', 'r+'));
return true;
}
/**
* Initialize the stream wrapper for an append stream
*
* @param array $params Operation parameters
* @param array $errors Any encountered errors to append to
*
* @return bool
*/
protected function openAppendStream(array $params, array &$errors)
{
try {
// Get the body of the object
$this->body = static::$client->getObject($params)->get('Body');
$this->body->seek(0, SEEK_END);
} catch (S3Exception $e) {
// The object does not exist, so use a simple write stream
$this->openWriteStream($params, $errors);
}
return true;
}
/**
* Trigger one or more errors
*
* @param string|array $errors Errors to trigger
* @param mixed $flags If set to STREAM_URL_STAT_QUIET, then no error or exception occurs
*
* @return bool Returns false
* @throws RuntimeException if throw_errors is true
*/
protected function triggerError($errors, $flags = null)
{
if ($flags & STREAM_URL_STAT_QUIET) {
// This is triggered with things like file_exists()
if ($flags & STREAM_URL_STAT_LINK) {
// This is triggered for things like is_link()
return $this->formatUrlStat(false);
}
return false;
}
// This is triggered when doing things like lstat() or stat()
trigger_error(implode("\n", array_map('esc_html', (array) $errors)), E_USER_WARNING);
return false;
}
/**
* Prepare a url_stat result array
*
* @param string|array $result Data to add
*
* @return array Returns the modified url_stat result
*/
protected function formatUrlStat($result = null)
{
static $statTemplate = array(
0 => 0, 'dev' => 0,
1 => 0, 'ino' => 0,
2 => 0, 'mode' => 0,
3 => 0, 'nlink' => 0,
4 => 0, 'uid' => 0,
5 => 0, 'gid' => 0,
6 => -1, 'rdev' => -1,
7 => 0, 'size' => 0,
8 => 0, 'atime' => 0,
9 => 0, 'mtime' => 0,
10 => 0, 'ctime' => 0,
11 => -1, 'blksize' => -1,
12 => -1, 'blocks' => -1,
);
$stat = $statTemplate;
$type = gettype($result);
// Determine what type of data is being cached
if ($type == 'NULL' || $type == 'string') {
// Directory with 0777 access - see "man 2 stat".
$stat['mode'] = $stat[2] = 0040777;
} elseif ($type == 'array' && isset($result['LastModified'])) {
// ListObjects or HeadObject result
$stat['mtime'] = $stat[9] = $stat['ctime'] = $stat[10] = strtotime($result['LastModified']);
$stat['size'] = $stat[7] = (isset($result['ContentLength']) ? $result['ContentLength'] : $result['Size']);
// Regular file with 0777 access - see "man 2 stat".
$stat['mode'] = $stat[2] = 0100777;
}
return $stat;
}
/**
* Clear the next stat result from the cache
*
* @param string $path If a path is specific, clearstatcache() will be called
*/
protected function clearStatInfo($path = null)
{
static::$nextStat = array();
if ($path) {
clearstatcache(true, $path);
}
}
/**
* Creates a bucket for the given parameters.
*
* @param string $path Stream wrapper path
* @param array $params A result of StreamWrapper::getParams()
*
* @return bool Returns true on success or false on failure
*/
private function createBucket($path, array $params)
{
if (static::$client->doesBucketExist($params['Bucket'])) {
return $this->triggerError("Directory already exists: {$path}");
}
try {
static::$client->createBucket($params);
$this->clearStatInfo($path);
return true;
} catch (\Exception $e) {
return $this->triggerError($e->getMessage());
}
}
/**
* Creates a pseudo-folder by creating an empty "/" suffixed key
*
* @param string $path Stream wrapper path
* @param array $params A result of StreamWrapper::getParams()
*
* @return bool
*/
private function createPseudoDirectory($path, array $params)
{
// Ensure the path ends in "/" and the body is empty.
$params['Key'] = rtrim($params['Key'], '/') . '/';
$params['Body'] = '';
// Fail if this pseudo directory key already exists
if (static::$client->doesObjectExist($params['Bucket'], $params['Key'])) {
return $this->triggerError("Directory already exists: {$path}");
}
try {
static::$client->putObject($params);
$this->clearStatInfo($path);
return true;
} catch (\Exception $e) {
return $this->triggerError($e->getMessage());
}
}
/**
* Determine the most appropriate ACL based on a file mode.
*
* @param int $mode File mode
*
* @return string
*/
private function determineAcl($mode)
{
$mode = decoct($mode);
if ($mode >= 700 && $mode <= 799) {
return 'public-read';
}
if ($mode >= 600 && $mode <= 699) {
return 'authenticated-read';
}
return 'private';
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Iterator/OpendirIterator.php 0000644 00000004066 15132770567 0021252 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Iterator;
/**
* Provides an iterator around an opendir resource. This is useful when you need to provide context to an opendir so
* you can't use RecursiveDirectoryIterator
*/
class OpendirIterator implements \Iterator
{
/** @var resource */
protected $dirHandle;
/** @var \SplFileInfo */
protected $currentFile;
/** @var int */
protected $key = -1;
/** @var string */
protected $filePrefix;
/**
* @param resource $dirHandle Opened directory handled returned from opendir
* @param string $filePrefix Prefix to add to each filename
*/
public function __construct($dirHandle, $filePrefix = '')
{
$this->filePrefix = $filePrefix;
$this->dirHandle = $dirHandle;
$this->next();
}
public function __destruct()
{
if ($this->dirHandle) {
closedir($this->dirHandle);
}
}
public function rewind()
{
$this->key = 0;
rewinddir($this->dirHandle);
}
public function current()
{
return $this->currentFile;
}
public function next()
{
if ($file = readdir($this->dirHandle)) {
$this->currentFile = new \SplFileInfo($this->filePrefix . $file);
} else {
$this->currentFile = false;
}
$this->key++;
}
public function key()
{
return $this->key;
}
public function valid()
{
return $this->currentFile !== false;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Iterator/ListBucketsIterator.php 0000644 00000002534 15132770567 0022104 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Iterator;
use Aws\Common\Iterator\AwsResourceIterator;
use Guzzle\Service\Resource\Model;
/**
* Iterator for the S3 ListBuckets command
*
* This iterator includes the following additional options:
*
* - names_only: Set to true to receive only the object/prefix names
*/
class ListBucketsIterator extends AwsResourceIterator
{
/**
* {@inheritdoc}
*/
protected function handleResults(Model $result)
{
// Get the results
$buckets = $result->get('Buckets') ?: array();
// If only the names_only set, change arrays to a string
if ($this->get('names_only')) {
foreach ($buckets as &$bucket) {
$bucket = $bucket['Name'];
}
}
return $buckets;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Iterator/ListObjectsIterator.php 0000644 00000005234 15132770567 0022075 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Iterator;
use Aws\Common\Iterator\AwsResourceIterator;
use Guzzle\Service\Resource\Model;
/**
* Iterator for an S3 ListObjects command
*
* This iterator includes the following additional options:
*
* - return_prefixes: Set to true to receive both prefixes and objects in results
* - sort_results: Set to true to sort mixed (object/prefix) results
* - names_only: Set to true to receive only the object/prefix names
*/
class ListObjectsIterator extends AwsResourceIterator
{
protected function handleResults(Model $result)
{
// Get the list of objects and record the last key
$objects = $result->get('Contents') ?: array();
$numObjects = count($objects);
$lastKey = $numObjects ? $objects[$numObjects - 1]['Key'] : false;
if ($lastKey && !$result->hasKey($this->get('output_token'))) {
$result->set($this->get('output_token'), $lastKey);
}
// Closure for getting the name of an object or prefix
$getName = function ($object) {
return isset($object['Key']) ? $object['Key'] : $object['Prefix'];
};
// If common prefixes returned (i.e. a delimiter was set) and they need to be returned, there is more to do
if ($this->get('return_prefixes') && $result->hasKey('CommonPrefixes')) {
// Collect and format the prefixes to include with the objects
$objects = array_merge($objects, $result->get('CommonPrefixes'));
// Sort the objects and prefixes to maintain alphabetical order, but only if some of each were returned
if ($this->get('sort_results') && $lastKey && $objects) {
usort($objects, function ($object1, $object2) use ($getName) {
return strcmp($getName($object1), $getName($object2));
});
}
}
// If only the names are desired, iterate through the results and convert the arrays to the object/prefix names
if ($this->get('names_only')) {
$objects = array_map($getName, $objects);
}
return $objects;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Iterator/ListMultipartUploadsIterator.php 0000644 00000002611 15132770567 0024011 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Iterator;
use Guzzle\Service\Resource\Model;
use Aws\Common\Iterator\AwsResourceIterator;
/**
* Iterator for the S3 ListMultipartUploads command
*
* This iterator includes the following additional options:
*
* - return_prefixes: Set to true to return both prefixes and uploads
*/
class ListMultipartUploadsIterator extends AwsResourceIterator
{
/**
* {@inheritdoc}
*/
protected function handleResults(Model $result)
{
// Get the list of uploads
$uploads = $result->get('Uploads') ?: array();
// If there are prefixes and we want them, merge them in
if ($this->get('return_prefixes') && $result->hasKey('CommonPrefixes')) {
$uploads = array_merge($uploads, $result->get('CommonPrefixes'));
}
return $uploads;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Iterator/ListObjectVersionsIterator.php 0000644 00000003035 15132770567 0023440 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Iterator;
use Aws\Common\Iterator\AwsResourceIterator;
use Guzzle\Service\Resource\Model;
/**
* Iterator for an S3 ListObjectVersions command
*
* This iterator includes the following additional options:
*
* - return_prefixes: Set to true to receive both prefixes and versions in results
*/
class ListObjectVersionsIterator extends AwsResourceIterator
{
/**
* {@inheritdoc}
*/
protected function handleResults(Model $result)
{
// Get the list of object versions
$versions = $result->get('Versions') ?: array();
$deleteMarkers = $result->get('DeleteMarkers') ?: array();
$versions = array_merge($versions, $deleteMarkers);
// If there are prefixes and we want them, merge them in
if ($this->get('return_prefixes') && $result->hasKey('CommonPrefixes')) {
$versions = array_merge($versions, $result->get('CommonPrefixes'));
}
return $versions;
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/S3SignatureV4.php 0000644 00000003463 15132770567 0016730 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3;
use Aws\Common\Signature\SignatureV4;
use Aws\Common\Credentials\CredentialsInterface;
use Guzzle\Http\Message\EntityEnclosingRequestInterface;
use Guzzle\Http\Message\RequestInterface;
/**
* Amazon S3 signature version 4 overrides.
*/
class S3SignatureV4 extends SignatureV4 implements S3SignatureInterface
{
/**
* Always add a x-amz-content-sha-256 for data integrity.
*/
public function signRequest(RequestInterface $request, CredentialsInterface $credentials)
{
if (!$request->hasHeader('x-amz-content-sha256')) {
$request->setHeader(
'x-amz-content-sha256',
$this->getPayload($request)
);
}
parent::signRequest($request, $credentials);
}
/**
* Override used to allow pre-signed URLs to be created for an
* in-determinate request payload.
*/
protected function getPresignedPayload(RequestInterface $request)
{
return 'UNSIGNED-PAYLOAD';
}
/**
* Amazon S3 does not double-encode the path component in the canonical req
*/
protected function createCanonicalizedPath(RequestInterface $request)
{
return '/' . ltrim($request->getPath(), '/');
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/ResumableDownload.php 0000644 00000014131 15132770567 0017750 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3;
use Aws\Common\Exception\RuntimeException;
use Aws\Common\Exception\UnexpectedValueException;
use Guzzle\Http\EntityBody;
use Guzzle\Http\ReadLimitEntityBody;
use Guzzle\Http\EntityBodyInterface;
use Guzzle\Service\Resource\Model;
/**
* Allows you to resume the download of a partially downloaded object.
*
* Downloads objects from Amazon S3 in using "Range" downloads. This allows a partially downloaded object to be resumed
* so that only the remaining portion of the object is downloaded.
*/
class ResumableDownload
{
/** @var S3Client The S3 client to use to download objects and issue HEAD requests */
protected $client;
/** @var Model Model object returned when the initial HeadObject operation was called */
protected $meta;
/** @var array Array of parameters to pass to a GetObject operation */
protected $params;
/** @var EntityBody Where the object will be downloaded */
protected $target;
/**
* @param S3Client $client Client to use when executing requests
* @param string $bucket Bucket that holds the object
* @param string $key Key of the object
* @param string|resource|EntityBodyInterface $target Where the object should be downloaded to. Pass a string to
* save the object to a file, pass a resource returned by
* fopen() to save the object to a stream resource, or pass a
* Guzzle EntityBody object to save the contents to an
* EntityBody.
* @param array $params Any additional GetObject or HeadObject parameters to use
* with each command issued by the client. (e.g. pass "Version"
* to download a specific version of an object)
* @throws RuntimeException if the target variable points to a file that cannot be opened
*/
public function __construct(S3Client $client, $bucket, $key, $target, array $params = array())
{
$this->params = $params;
$this->client = $client;
$this->params['Bucket'] = $bucket;
$this->params['Key'] = $key;
// If a string is passed, then assume that the download should stream to a file on disk
if (is_string($target)) {
if (!($target = fopen($target, 'a+'))) {
throw new RuntimeException(esc_html("Unable to open {$target} for writing"));
}
// Always append to the file
fseek($target, 0, SEEK_END);
}
// Get the metadata and Content-MD5 of the object
$this->target = EntityBody::factory($target);
}
/**
* Get the bucket of the download
*
* @return string
*/
public function getBucket()
{
return $this->params['Bucket'];
}
/**
* Get the key of the download
*
* @return string
*/
public function getKey()
{
return $this->params['Key'];
}
/**
* Get the file to which the contents are downloaded
*
* @return string
*/
public function getFilename()
{
return $this->target->getUri();
}
/**
* Download the remainder of the object from Amazon S3
*
* Performs a message integrity check if possible
*
* @return Model
*/
public function __invoke()
{
$command = $this->client->getCommand('HeadObject', $this->params);
$this->meta = $command->execute();
if ($this->target->ftell() >= $this->meta['ContentLength']) {
return false;
}
$this->meta['ContentMD5'] = (string) $command->getResponse()->getHeader('Content-MD5');
// Use a ReadLimitEntityBody so that rewinding the stream after an error does not cause the file pointer
// to enter an inconsistent state with the data being downloaded
$this->params['SaveAs'] = new ReadLimitEntityBody(
$this->target,
$this->meta['ContentLength'],
$this->target->ftell()
);
$result = $this->getRemaining();
$this->checkIntegrity();
return $result;
}
/**
* Send the command to get the remainder of the object
*
* @return Model
*/
protected function getRemaining()
{
$current = $this->target->ftell();
$targetByte = $this->meta['ContentLength'] - 1;
$this->params['Range'] = "bytes={$current}-{$targetByte}";
// Set the starting offset so that the body is never seeked to before this point in the event of a retry
$this->params['SaveAs']->setOffset($current);
$command = $this->client->getCommand('GetObject', $this->params);
return $command->execute();
}
/**
* Performs an MD5 message integrity check if possible
*
* @throws UnexpectedValueException if the message does not validate
*/
protected function checkIntegrity()
{
if ($this->target->isReadable() && $expected = $this->meta['ContentMD5']) {
$actual = $this->target->getContentMd5();
if ($actual != $expected) {
throw new UnexpectedValueException(
esc_html("Message integrity check failed. Expected {$expected} but got {$actual}.")
);
}
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/CannedAcl.php 0000644 00000001772 15132770567 0017064 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable CannedAcl values
*/
class CannedAcl extends Enum
{
const PRIVATE_ACCESS = 'private';
const PUBLIC_READ = 'public-read';
const PUBLIC_READ_WRITE = 'public-read-write';
const AUTHENTICATED_READ = 'authenticated-read';
const BUCKET_OWNER_READ = 'bucket-owner-read';
const BUCKET_OWNER_FULL_CONTROL = 'bucket-owner-full-control';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/Storage.php 0000644 00000001501 15132770567 0016646 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable Amazon S3 storage options
*/
class Storage extends Enum
{
const STANDARD = 'STANDARD';
const REDUCED = 'REDUCED_REDUNDANCY';
const GLACIER = 'GLACIER';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/GranteeType.php 0000644 00000001473 15132770567 0017501 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable GranteeType values
*/
class GranteeType extends Enum
{
const USER = 'CanonicalUser';
const EMAIL = 'AmazonCustomerByEmail';
const GROUP = 'Group';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/MFADelete.php 0000644 00000001417 15132770567 0016776 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable MFADelete values
*/
class MFADelete extends Enum
{
const ENABLED = 'Enabled';
const DISABLED = 'Disabled';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/Status.php 0000644 00000001413 15132770567 0016527 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable Status values
*/
class Status extends Enum
{
const ENABLED = 'Enabled';
const SUSPENDED = 'Suspended';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/ServerSideEncryption.php 0000644 00000001402 15132770567 0021370 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable ServerSideEncryption values
*/
class ServerSideEncryption extends Enum
{
const AES256 = 'AES256';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/EncodingType.php 0000644 00000001354 15132770567 0017640 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable EncodingType values
*/
class EncodingType extends Enum
{
const URL = 'url';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/Permission.php 0000644 00000001562 15132770567 0017401 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable Permission values
*/
class Permission extends Enum
{
const FULL_CONTROL = 'FULL_CONTROL';
const WRITE = 'WRITE';
const WRITE_ACP = 'WRITE_ACP';
const READ = 'READ';
const READ_ACP = 'READ_ACP';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/MetadataDirective.php 0000644 00000001427 15132770567 0020630 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable MetadataDirective values
*/
class MetadataDirective extends Enum
{
const COPY = 'COPY';
const REPLACE = 'REPLACE';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/Protocol.php 0000644 00000001401 15132770567 0017042 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable Protocol values
*/
class Protocol extends Enum
{
const HTTP = 'http';
const HTTPS = 'https';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/Group.php 0000644 00000001745 15132770567 0016350 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable Amazon S3 group options for ACL grantees
*/
class Group extends Enum
{
const AUTHENTICATED_USERS = 'http://acs.amazonaws.com/groups/global/AuthenticatedUsers';
const ALL_USERS = 'http://acs.amazonaws.com/groups/global/AllUsers';
const LOG_DELIVERY = 'http://acs.amazonaws.com/groups/s3/LogDelivery';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/Payer.php 0000644 00000001422 15132770567 0016324 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable Payer values
*/
class Payer extends Enum
{
const REQUESTER = 'Requester';
const BUCKET_OWNER = 'BucketOwner';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/StorageClass.php 0000644 00000001453 15132770567 0017642 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable StorageClass values
*/
class StorageClass extends Enum
{
const STANDARD = 'STANDARD';
const REDUCED_REDUNDANCY = 'REDUCED_REDUNDANCY';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/Enum/Event.php 0000644 00000001424 15132770567 0016327 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable Event values
*/
class Event extends Enum
{
const REDUCED_REDUNDANCY_LOST_OBJECT = 's3:ReducedRedundancyLostObject';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/S3/BucketStyleListener.php 0000644 00000006261 15132770567 0020312 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\S3;
use Guzzle\Common\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Listener used to change the way in which buckets are referenced (path/virtual style) based on context
*/
class BucketStyleListener implements EventSubscriberInterface
{
private static $exclusions = array('GetBucketLocation' => true);
public static function getSubscribedEvents()
{
return array('command.after_prepare' => array('onCommandAfterPrepare', -255));
}
/**
* Changes how buckets are referenced in the HTTP request
*
* @param Event $event Event emitted
*/
public function onCommandAfterPrepare(Event $event)
{
$command = $event['command'];
$bucket = $command['Bucket'];
$request = $command->getRequest();
$pathStyle = false;
// Skip operations that do not need the bucket moved to the host.
if (isset(self::$exclusions[$command->getName()])) {
return;
}
if ($key = $command['Key']) {
// Modify the command Key to account for the {/Key*} explosion into an array
if (is_array($key)) {
$command['Key'] = $key = implode('/', $key);
}
}
// Set the key and bucket on the request
$request->getParams()->set('bucket', $bucket)->set('key', $key);
// Switch to virtual if PathStyle is disabled, or not a DNS compatible bucket name, or the scheme is
// http, or the scheme is https and there are no dots in the host header (avoids SSL issues)
if (!$command['PathStyle'] && $command->getClient()->isValidBucketName($bucket)
&& !($command->getRequest()->getScheme() == 'https' && strpos($bucket, '.'))
) {
// Switch to virtual hosted bucket
$request->setHost($bucket . '.' . $request->getHost());
$request->setPath(preg_replace("#^/{$bucket}#", '', $request->getPath()));
} else {
$pathStyle = true;
}
if (!$bucket) {
$request->getParams()->set('s3.resource', '/');
} elseif ($pathStyle) {
// Path style does not need a trailing slash
$request->getParams()->set(
's3.resource',
'/' . rawurlencode($bucket) . ($key ? ('/' . S3Client::encodeKey($key)) : '')
);
} else {
// Bucket style needs a trailing slash
$request->getParams()->set(
's3.resource',
'/' . rawurlencode($bucket) . ($key ? ('/' . S3Client::encodeKey($key)) : '/')
);
}
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/IamClient.php 0000644 00000037604 15132770567 0016441 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam;
use Aws\Common\Client\AbstractClient;
use Aws\Common\Client\ClientBuilder;
use Aws\Common\Enum\ClientOptions as Options;
use Guzzle\Common\Collection;
use Guzzle\Service\Resource\Model;
use Guzzle\Service\Resource\ResourceIteratorInterface;
/**
* Client to interact with AWS Identity and Access Management
*
* @method Model addClientIDToOpenIDConnectProvider(array $args = array()) {@command Iam AddClientIDToOpenIDConnectProvider}
* @method Model addRoleToInstanceProfile(array $args = array()) {@command Iam AddRoleToInstanceProfile}
* @method Model addUserToGroup(array $args = array()) {@command Iam AddUserToGroup}
* @method Model attachGroupPolicy(array $args = array()) {@command Iam AttachGroupPolicy}
* @method Model attachRolePolicy(array $args = array()) {@command Iam AttachRolePolicy}
* @method Model attachUserPolicy(array $args = array()) {@command Iam AttachUserPolicy}
* @method Model changePassword(array $args = array()) {@command Iam ChangePassword}
* @method Model createAccessKey(array $args = array()) {@command Iam CreateAccessKey}
* @method Model createAccountAlias(array $args = array()) {@command Iam CreateAccountAlias}
* @method Model createGroup(array $args = array()) {@command Iam CreateGroup}
* @method Model createInstanceProfile(array $args = array()) {@command Iam CreateInstanceProfile}
* @method Model createLoginProfile(array $args = array()) {@command Iam CreateLoginProfile}
* @method Model createOpenIDConnectProvider(array $args = array()) {@command Iam CreateOpenIDConnectProvider}
* @method Model createPolicy(array $args = array()) {@command Iam CreatePolicy}
* @method Model createPolicyVersion(array $args = array()) {@command Iam CreatePolicyVersion}
* @method Model createRole(array $args = array()) {@command Iam CreateRole}
* @method Model createSAMLProvider(array $args = array()) {@command Iam CreateSAMLProvider}
* @method Model createUser(array $args = array()) {@command Iam CreateUser}
* @method Model createVirtualMFADevice(array $args = array()) {@command Iam CreateVirtualMFADevice}
* @method Model deactivateMFADevice(array $args = array()) {@command Iam DeactivateMFADevice}
* @method Model deleteAccessKey(array $args = array()) {@command Iam DeleteAccessKey}
* @method Model deleteAccountAlias(array $args = array()) {@command Iam DeleteAccountAlias}
* @method Model deleteAccountPasswordPolicy(array $args = array()) {@command Iam DeleteAccountPasswordPolicy}
* @method Model deleteGroup(array $args = array()) {@command Iam DeleteGroup}
* @method Model deleteGroupPolicy(array $args = array()) {@command Iam DeleteGroupPolicy}
* @method Model deleteInstanceProfile(array $args = array()) {@command Iam DeleteInstanceProfile}
* @method Model deleteLoginProfile(array $args = array()) {@command Iam DeleteLoginProfile}
* @method Model deleteOpenIDConnectProvider(array $args = array()) {@command Iam DeleteOpenIDConnectProvider}
* @method Model deletePolicy(array $args = array()) {@command Iam DeletePolicy}
* @method Model deletePolicyVersion(array $args = array()) {@command Iam DeletePolicyVersion}
* @method Model deleteRole(array $args = array()) {@command Iam DeleteRole}
* @method Model deleteRolePolicy(array $args = array()) {@command Iam DeleteRolePolicy}
* @method Model deleteSAMLProvider(array $args = array()) {@command Iam DeleteSAMLProvider}
* @method Model deleteSSHPublicKey(array $args = array()) {@command Iam DeleteSSHPublicKey}
* @method Model deleteServerCertificate(array $args = array()) {@command Iam DeleteServerCertificate}
* @method Model deleteSigningCertificate(array $args = array()) {@command Iam DeleteSigningCertificate}
* @method Model deleteUser(array $args = array()) {@command Iam DeleteUser}
* @method Model deleteUserPolicy(array $args = array()) {@command Iam DeleteUserPolicy}
* @method Model deleteVirtualMFADevice(array $args = array()) {@command Iam DeleteVirtualMFADevice}
* @method Model detachGroupPolicy(array $args = array()) {@command Iam DetachGroupPolicy}
* @method Model detachRolePolicy(array $args = array()) {@command Iam DetachRolePolicy}
* @method Model detachUserPolicy(array $args = array()) {@command Iam DetachUserPolicy}
* @method Model enableMFADevice(array $args = array()) {@command Iam EnableMFADevice}
* @method Model generateCredentialReport(array $args = array()) {@command Iam GenerateCredentialReport}
* @method Model getAccessKeyLastUsed(array $args = array()) {@command Iam GetAccessKeyLastUsed}
* @method Model getAccountAuthorizationDetails(array $args = array()) {@command Iam GetAccountAuthorizationDetails}
* @method Model getAccountPasswordPolicy(array $args = array()) {@command Iam GetAccountPasswordPolicy}
* @method Model getAccountSummary(array $args = array()) {@command Iam GetAccountSummary}
* @method Model getContextKeysForCustomPolicy(array $args = array()) {@command Iam GetContextKeysForCustomPolicy}
* @method Model getContextKeysForPrincipalPolicy(array $args = array()) {@command Iam GetContextKeysForPrincipalPolicy}
* @method Model getCredentialReport(array $args = array()) {@command Iam GetCredentialReport}
* @method Model getGroup(array $args = array()) {@command Iam GetGroup}
* @method Model getGroupPolicy(array $args = array()) {@command Iam GetGroupPolicy}
* @method Model getInstanceProfile(array $args = array()) {@command Iam GetInstanceProfile}
* @method Model getLoginProfile(array $args = array()) {@command Iam GetLoginProfile}
* @method Model getOpenIDConnectProvider(array $args = array()) {@command Iam GetOpenIDConnectProvider}
* @method Model getPolicy(array $args = array()) {@command Iam GetPolicy}
* @method Model getPolicyVersion(array $args = array()) {@command Iam GetPolicyVersion}
* @method Model getRole(array $args = array()) {@command Iam GetRole}
* @method Model getRolePolicy(array $args = array()) {@command Iam GetRolePolicy}
* @method Model getSAMLProvider(array $args = array()) {@command Iam GetSAMLProvider}
* @method Model getSSHPublicKey(array $args = array()) {@command Iam GetSSHPublicKey}
* @method Model getServerCertificate(array $args = array()) {@command Iam GetServerCertificate}
* @method Model getUser(array $args = array()) {@command Iam GetUser}
* @method Model getUserPolicy(array $args = array()) {@command Iam GetUserPolicy}
* @method Model listAccessKeys(array $args = array()) {@command Iam ListAccessKeys}
* @method Model listAccountAliases(array $args = array()) {@command Iam ListAccountAliases}
* @method Model listAttachedGroupPolicies(array $args = array()) {@command Iam ListAttachedGroupPolicies}
* @method Model listAttachedRolePolicies(array $args = array()) {@command Iam ListAttachedRolePolicies}
* @method Model listAttachedUserPolicies(array $args = array()) {@command Iam ListAttachedUserPolicies}
* @method Model listEntitiesForPolicy(array $args = array()) {@command Iam ListEntitiesForPolicy}
* @method Model listGroupPolicies(array $args = array()) {@command Iam ListGroupPolicies}
* @method Model listGroups(array $args = array()) {@command Iam ListGroups}
* @method Model listGroupsForUser(array $args = array()) {@command Iam ListGroupsForUser}
* @method Model listInstanceProfiles(array $args = array()) {@command Iam ListInstanceProfiles}
* @method Model listInstanceProfilesForRole(array $args = array()) {@command Iam ListInstanceProfilesForRole}
* @method Model listMFADevices(array $args = array()) {@command Iam ListMFADevices}
* @method Model listOpenIDConnectProviders(array $args = array()) {@command Iam ListOpenIDConnectProviders}
* @method Model listPolicies(array $args = array()) {@command Iam ListPolicies}
* @method Model listPolicyVersions(array $args = array()) {@command Iam ListPolicyVersions}
* @method Model listRolePolicies(array $args = array()) {@command Iam ListRolePolicies}
* @method Model listRoles(array $args = array()) {@command Iam ListRoles}
* @method Model listSAMLProviders(array $args = array()) {@command Iam ListSAMLProviders}
* @method Model listSSHPublicKeys(array $args = array()) {@command Iam ListSSHPublicKeys}
* @method Model listServerCertificates(array $args = array()) {@command Iam ListServerCertificates}
* @method Model listSigningCertificates(array $args = array()) {@command Iam ListSigningCertificates}
* @method Model listUserPolicies(array $args = array()) {@command Iam ListUserPolicies}
* @method Model listUsers(array $args = array()) {@command Iam ListUsers}
* @method Model listVirtualMFADevices(array $args = array()) {@command Iam ListVirtualMFADevices}
* @method Model putGroupPolicy(array $args = array()) {@command Iam PutGroupPolicy}
* @method Model putRolePolicy(array $args = array()) {@command Iam PutRolePolicy}
* @method Model putUserPolicy(array $args = array()) {@command Iam PutUserPolicy}
* @method Model removeClientIDFromOpenIDConnectProvider(array $args = array()) {@command Iam RemoveClientIDFromOpenIDConnectProvider}
* @method Model removeRoleFromInstanceProfile(array $args = array()) {@command Iam RemoveRoleFromInstanceProfile}
* @method Model removeUserFromGroup(array $args = array()) {@command Iam RemoveUserFromGroup}
* @method Model resyncMFADevice(array $args = array()) {@command Iam ResyncMFADevice}
* @method Model setDefaultPolicyVersion(array $args = array()) {@command Iam SetDefaultPolicyVersion}
* @method Model simulateCustomPolicy(array $args = array()) {@command Iam SimulateCustomPolicy}
* @method Model simulatePrincipalPolicy(array $args = array()) {@command Iam SimulatePrincipalPolicy}
* @method Model updateAccessKey(array $args = array()) {@command Iam UpdateAccessKey}
* @method Model updateAccountPasswordPolicy(array $args = array()) {@command Iam UpdateAccountPasswordPolicy}
* @method Model updateAssumeRolePolicy(array $args = array()) {@command Iam UpdateAssumeRolePolicy}
* @method Model updateGroup(array $args = array()) {@command Iam UpdateGroup}
* @method Model updateLoginProfile(array $args = array()) {@command Iam UpdateLoginProfile}
* @method Model updateOpenIDConnectProviderThumbprint(array $args = array()) {@command Iam UpdateOpenIDConnectProviderThumbprint}
* @method Model updateSAMLProvider(array $args = array()) {@command Iam UpdateSAMLProvider}
* @method Model updateSSHPublicKey(array $args = array()) {@command Iam UpdateSSHPublicKey}
* @method Model updateServerCertificate(array $args = array()) {@command Iam UpdateServerCertificate}
* @method Model updateSigningCertificate(array $args = array()) {@command Iam UpdateSigningCertificate}
* @method Model updateUser(array $args = array()) {@command Iam UpdateUser}
* @method Model uploadSSHPublicKey(array $args = array()) {@command Iam UploadSSHPublicKey}
* @method Model uploadServerCertificate(array $args = array()) {@command Iam UploadServerCertificate}
* @method Model uploadSigningCertificate(array $args = array()) {@command Iam UploadSigningCertificate}
* @method ResourceIteratorInterface getGetGroupIterator(array $args = array()) The input array uses the parameters of the GetGroup operation
* @method ResourceIteratorInterface getListAccessKeysIterator(array $args = array()) The input array uses the parameters of the ListAccessKeys operation
* @method ResourceIteratorInterface getListAccountAliasesIterator(array $args = array()) The input array uses the parameters of the ListAccountAliases operation
* @method ResourceIteratorInterface getListAttachedGroupPoliciesIterator(array $args = array()) The input array uses the parameters of the ListAttachedGroupPolicies operation
* @method ResourceIteratorInterface getListAttachedRolePoliciesIterator(array $args = array()) The input array uses the parameters of the ListAttachedRolePolicies operation
* @method ResourceIteratorInterface getListAttachedUserPoliciesIterator(array $args = array()) The input array uses the parameters of the ListAttachedUserPolicies operation
* @method ResourceIteratorInterface getListEntitiesForPolicyIterator(array $args = array()) The input array uses the parameters of the ListEntitiesForPolicy operation
* @method ResourceIteratorInterface getListGroupPoliciesIterator(array $args = array()) The input array uses the parameters of the ListGroupPolicies operation
* @method ResourceIteratorInterface getListGroupsIterator(array $args = array()) The input array uses the parameters of the ListGroups operation
* @method ResourceIteratorInterface getListGroupsForUserIterator(array $args = array()) The input array uses the parameters of the ListGroupsForUser operation
* @method ResourceIteratorInterface getListInstanceProfilesIterator(array $args = array()) The input array uses the parameters of the ListInstanceProfiles operation
* @method ResourceIteratorInterface getListInstanceProfilesForRoleIterator(array $args = array()) The input array uses the parameters of the ListInstanceProfilesForRole operation
* @method ResourceIteratorInterface getListMFADevicesIterator(array $args = array()) The input array uses the parameters of the ListMFADevices operation
* @method ResourceIteratorInterface getListPoliciesIterator(array $args = array()) The input array uses the parameters of the ListPolicies operation
* @method ResourceIteratorInterface getListRolePoliciesIterator(array $args = array()) The input array uses the parameters of the ListRolePolicies operation
* @method ResourceIteratorInterface getListRolesIterator(array $args = array()) The input array uses the parameters of the ListRoles operation
* @method ResourceIteratorInterface getListSAMLProvidersIterator(array $args = array()) The input array uses the parameters of the ListSAMLProviders operation
* @method ResourceIteratorInterface getListServerCertificatesIterator(array $args = array()) The input array uses the parameters of the ListServerCertificates operation
* @method ResourceIteratorInterface getListSigningCertificatesIterator(array $args = array()) The input array uses the parameters of the ListSigningCertificates operation
* @method ResourceIteratorInterface getListUserPoliciesIterator(array $args = array()) The input array uses the parameters of the ListUserPolicies operation
* @method ResourceIteratorInterface getListUsersIterator(array $args = array()) The input array uses the parameters of the ListUsers operation
* @method ResourceIteratorInterface getListVirtualMFADevicesIterator(array $args = array()) The input array uses the parameters of the ListVirtualMFADevices operation
* @method ResourceIteratorInterface getGetAccountAuthorizationDetailsIterator(array $args = array()) The input array uses the parameters of the GetAccountAuthorizationDetails operation
*
* @link http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-iam.html User guide
* @link http://docs.aws.amazon.com/aws-sdk-php/v2/api/class-Aws.Iam.IamClient.html API docs
*/
class IamClient extends AbstractClient
{
const LATEST_API_VERSION = '2010-05-08';
/**
* Factory method to create a new AWS Identity and Access Management client using an array of configuration options.
*
* @param array|Collection $config Client configuration data
*
* @return self
* @link http://docs.aws.amazon.com/aws-sdk-php/v2/guide/configuration.html#client-configuration-options
*/
public static function factory($config = array())
{
return ClientBuilder::factory(__NAMESPACE__)
->setConfig($config)
->setConfigDefaults(array(
Options::VERSION => self::LATEST_API_VERSION,
Options::SERVICE_DESCRIPTION => __DIR__ . '/Resources/iam-%s.php'
))
->build();
}
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Enum/AssignmentStatusType.php 0000644 00000001503 15132770567 0021643 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable AssignmentStatusType values
*/
class AssignmentStatusType extends Enum
{
const ASSIGNED = 'Assigned';
const UNASSIGNED = 'Unassigned';
const ANY = 'Any';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Enum/StatusType.php 0000644 00000001420 15132770567 0017610 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Enum;
use Aws\Common\Enum;
/**
* Contains enumerable StatusType values
*/
class StatusType extends Enum
{
const ACTIVE = 'Active';
const INACTIVE = 'Inactive';
}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Resources/iam-2010-05-08.php 0000644 00001234744 15132770567 0020350 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
return array (
'apiVersion' => '2010-05-08',
'endpointPrefix' => 'iam',
'serviceFullName' => 'AWS Identity and Access Management',
'serviceAbbreviation' => 'IAM',
'serviceType' => 'query',
'globalEndpoint' => 'iam.amazonaws.com',
'resultWrapped' => true,
'signatureVersion' => 'v4',
'namespace' => 'Iam',
'regions' => array(
'us-east-1' => array(
'http' => false,
'https' => true,
'hostname' => 'iam.amazonaws.com',
),
'us-west-1' => array(
'http' => false,
'https' => true,
'hostname' => 'iam.amazonaws.com',
),
'us-west-2' => array(
'http' => false,
'https' => true,
'hostname' => 'iam.amazonaws.com',
),
'eu-west-1' => array(
'http' => false,
'https' => true,
'hostname' => 'iam.amazonaws.com',
),
'ap-northeast-1' => array(
'http' => false,
'https' => true,
'hostname' => 'iam.amazonaws.com',
),
'ap-southeast-1' => array(
'http' => false,
'https' => true,
'hostname' => 'iam.amazonaws.com',
),
'ap-southeast-2' => array(
'http' => false,
'https' => true,
'hostname' => 'iam.amazonaws.com',
),
'sa-east-1' => array(
'http' => false,
'https' => true,
'hostname' => 'iam.amazonaws.com',
),
'cn-north-1' => array(
'http' => false,
'https' => true,
'hostname' => 'iam.cn-north-1.amazonaws.com.cn',
),
'us-gov-west-1' => array(
'http' => false,
'https' => true,
'hostname' => 'iam.us-gov.amazonaws.com',
),
),
'operations' => array(
'AddClientIDToOpenIDConnectProvider' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'AddClientIDToOpenIDConnectProvider',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'OpenIDConnectProviderArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'ClientID' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'AddRoleToInstanceProfile' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'AddRoleToInstanceProfile',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'InstanceProfileName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'AddUserToGroup' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'AddUserToGroup',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'AttachGroupPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'AttachGroupPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'AttachRolePolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'AttachRolePolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'AttachUserPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'AttachUserPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ChangePassword' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ChangePassword',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'OldPassword' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'NewPassword' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because the type of user for the transaction was incorrect.',
'class' => 'InvalidUserTypeException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that is temporarily unmodifiable, such as a user name that was deleted and then recreated. The error indicates that the request is likely to succeed if you try again after waiting several minutes. The error message describes the entity.',
'class' => 'EntityTemporarilyUnmodifiableException',
),
array(
'reason' => 'The request was rejected because the provided password did not meet the requirements imposed by the account password policy.',
'class' => 'PasswordPolicyViolationException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreateAccessKey' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'CreateAccessKeyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreateAccessKey',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreateAccountAlias' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreateAccountAlias',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'AccountAlias' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 3,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreateGroup' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'CreateGroupResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreateGroup',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'Path' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreateInstanceProfile' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'CreateInstanceProfileResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreateInstanceProfile',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'InstanceProfileName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Path' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreateLoginProfile' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'CreateLoginProfileResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreateLoginProfile',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Password' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PasswordResetRequired' => array(
'type' => 'boolean',
'format' => 'boolean-string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because the provided password did not meet the requirements imposed by the account password policy.',
'class' => 'PasswordPolicyViolationException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreateOpenIDConnectProvider' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'CreateOpenIDConnectProviderResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreateOpenIDConnectProvider',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'Url' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'ClientIDList' => array(
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'ClientIDList.member',
'items' => array(
'name' => 'clientIDType',
'type' => 'string',
'minLength' => 1,
),
),
'ThumbprintList' => array(
'required' => true,
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'ThumbprintList.member',
'items' => array(
'name' => 'thumbprintType',
'type' => 'string',
'minLength' => 40,
),
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreatePolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'CreatePolicyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreatePolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicyName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Path' => array(
'type' => 'string',
'location' => 'aws.query',
),
'PolicyDocument' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Description' => array(
'type' => 'string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because the policy document was malformed. The error message describes the specific error.',
'class' => 'MalformedPolicyDocumentException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreatePolicyVersion' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'CreatePolicyVersionResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreatePolicyVersion',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'PolicyDocument' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'SetAsDefault' => array(
'type' => 'boolean',
'format' => 'boolean-string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because the policy document was malformed. The error message describes the specific error.',
'class' => 'MalformedPolicyDocumentException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreateRole' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'CreateRoleResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreateRole',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'Path' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'AssumeRolePolicyDocument' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because the policy document was malformed. The error message describes the specific error.',
'class' => 'MalformedPolicyDocumentException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreateSAMLProvider' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'CreateSAMLProviderResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreateSAMLProvider',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'SAMLMetadataDocument' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1000,
),
'Name' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreateUser' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'CreateUserResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreateUser',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'Path' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'CreateVirtualMFADevice' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'CreateVirtualMFADeviceResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'CreateVirtualMFADevice',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'Path' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'VirtualMFADeviceName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeactivateMFADevice' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeactivateMFADevice',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'SerialNumber' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 9,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that is temporarily unmodifiable, such as a user name that was deleted and then recreated. The error indicates that the request is likely to succeed if you try again after waiting several minutes. The error message describes the entity.',
'class' => 'EntityTemporarilyUnmodifiableException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteAccessKey' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteAccessKey',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'AccessKeyId' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 16,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteAccountAlias' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteAccountAlias',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'AccountAlias' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 3,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteAccountPasswordPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteAccountPasswordPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteGroup' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteGroup',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to delete a resource that has attached subordinate entities. The error message describes these entities.',
'class' => 'DeleteConflictException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteGroupPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteGroupPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteInstanceProfile' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteInstanceProfile',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'InstanceProfileName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to delete a resource that has attached subordinate entities. The error message describes these entities.',
'class' => 'DeleteConflictException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteLoginProfile' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteLoginProfile',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that is temporarily unmodifiable, such as a user name that was deleted and then recreated. The error indicates that the request is likely to succeed if you try again after waiting several minutes. The error message describes the entity.',
'class' => 'EntityTemporarilyUnmodifiableException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteOpenIDConnectProvider' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteOpenIDConnectProvider',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'OpenIDConnectProviderArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeletePolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeletePolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it attempted to delete a resource that has attached subordinate entities. The error message describes these entities.',
'class' => 'DeleteConflictException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeletePolicyVersion' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeletePolicyVersion',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'VersionId' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it attempted to delete a resource that has attached subordinate entities. The error message describes these entities.',
'class' => 'DeleteConflictException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteRole' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteRole',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to delete a resource that has attached subordinate entities. The error message describes these entities.',
'class' => 'DeleteConflictException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteRolePolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteRolePolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteSAMLProvider' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteSAMLProvider',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'SAMLProviderArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteSSHPublicKey' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteSSHPublicKey',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'SSHPublicKeyId' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
),
),
'DeleteServerCertificate' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteServerCertificate',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'ServerCertificateName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to delete a resource that has attached subordinate entities. The error message describes these entities.',
'class' => 'DeleteConflictException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteSigningCertificate' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteSigningCertificate',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'CertificateId' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 24,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteUser' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteUser',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to delete a resource that has attached subordinate entities. The error message describes these entities.',
'class' => 'DeleteConflictException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteUserPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteUserPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DeleteVirtualMFADevice' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DeleteVirtualMFADevice',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'SerialNumber' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 9,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to delete a resource that has attached subordinate entities. The error message describes these entities.',
'class' => 'DeleteConflictException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DetachGroupPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DetachGroupPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DetachRolePolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DetachRolePolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'DetachUserPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'DetachUserPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'EnableMFADevice' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'EnableMFADevice',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'SerialNumber' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 9,
),
'AuthenticationCode1' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 6,
),
'AuthenticationCode2' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 6,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that is temporarily unmodifiable, such as a user name that was deleted and then recreated. The error indicates that the request is likely to succeed if you try again after waiting several minutes. The error message describes the entity.',
'class' => 'EntityTemporarilyUnmodifiableException',
),
array(
'reason' => 'The request was rejected because the authentication code was not recognized. The error message describes the specific error.',
'class' => 'InvalidAuthenticationCodeException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GenerateCredentialReport' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GenerateCredentialReportResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GenerateCredentialReport',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetAccessKeyLastUsed' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetAccessKeyLastUsedResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetAccessKeyLastUsed',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'AccessKeyId' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 16,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
),
),
'GetAccountAuthorizationDetails' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetAccountAuthorizationDetailsResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetAccountAuthorizationDetails',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'Filter' => array(
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'Filter.member',
'items' => array(
'name' => 'EntityType',
'type' => 'string',
),
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetAccountPasswordPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetAccountPasswordPolicyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetAccountPasswordPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetAccountSummary' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetAccountSummaryResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetAccountSummary',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
),
'errorResponses' => array(
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetContextKeysForCustomPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetContextKeysForPolicyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetContextKeysForCustomPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicyInputList' => array(
'required' => true,
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'PolicyInputList.member',
'items' => array(
'name' => 'policyDocumentType',
'type' => 'string',
'minLength' => 1,
),
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
),
),
'GetContextKeysForPrincipalPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetContextKeysForPolicyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetContextKeysForPrincipalPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicySourceArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'PolicyInputList' => array(
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'PolicyInputList.member',
'items' => array(
'name' => 'policyDocumentType',
'type' => 'string',
'minLength' => 1,
),
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
),
),
'GetCredentialReport' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetCredentialReportResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetCredentialReport',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because the credential report does not exist. To generate a credential report, use GenerateCredentialReport.',
'class' => 'CredentialReportNotPresentException',
),
array(
'reason' => 'The request was rejected because the most recent credential report has expired. To generate a new credential report, use GenerateCredentialReport. For more information about credential report expiration, see Getting Credential Reports in the IAM User Guide.',
'class' => 'CredentialReportExpiredException',
),
array(
'reason' => 'The request was rejected because the credential report is still being generated.',
'class' => 'CredentialReportNotReadyException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetGroup' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetGroupResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetGroup',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetGroupPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetGroupPolicyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetGroupPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetInstanceProfile' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetInstanceProfileResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetInstanceProfile',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'InstanceProfileName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetLoginProfile' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetLoginProfileResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetLoginProfile',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetOpenIDConnectProvider' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetOpenIDConnectProviderResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetOpenIDConnectProvider',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'OpenIDConnectProviderArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetPolicyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetPolicyVersion' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetPolicyVersionResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetPolicyVersion',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'VersionId' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetRole' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetRoleResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetRole',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetRolePolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetRolePolicyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetRolePolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetSAMLProvider' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetSAMLProviderResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetSAMLProvider',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'SAMLProviderArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetSSHPublicKey' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetSSHPublicKeyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetSSHPublicKey',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'SSHPublicKeyId' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'Encoding' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because the public key encoding format is unsupported or unrecognized.',
'class' => 'UnrecognizedPublicKeyEncodingException',
),
),
),
'GetServerCertificate' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetServerCertificateResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetServerCertificate',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'ServerCertificateName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetUser' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetUserResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetUser',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'GetUserPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'GetUserPolicyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'GetUserPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListAccessKeys' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListAccessKeysResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListAccessKeys',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListAccountAliases' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListAccountAliasesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListAccountAliases',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListAttachedGroupPolicies' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListAttachedGroupPoliciesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListAttachedGroupPolicies',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PathPrefix' => array(
'type' => 'string',
'location' => 'aws.query',
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListAttachedRolePolicies' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListAttachedRolePoliciesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListAttachedRolePolicies',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PathPrefix' => array(
'type' => 'string',
'location' => 'aws.query',
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListAttachedUserPolicies' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListAttachedUserPoliciesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListAttachedUserPolicies',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PathPrefix' => array(
'type' => 'string',
'location' => 'aws.query',
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListEntitiesForPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListEntitiesForPolicyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListEntitiesForPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'EntityFilter' => array(
'type' => 'string',
'location' => 'aws.query',
),
'PathPrefix' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListGroupPolicies' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListGroupPoliciesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListGroupPolicies',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListGroups' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListGroupsResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListGroups',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PathPrefix' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListGroupsForUser' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListGroupsForUserResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListGroupsForUser',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListInstanceProfiles' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListInstanceProfilesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListInstanceProfiles',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PathPrefix' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListInstanceProfilesForRole' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListInstanceProfilesForRoleResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListInstanceProfilesForRole',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListMFADevices' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListMFADevicesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListMFADevices',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListOpenIDConnectProviders' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListOpenIDConnectProvidersResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListOpenIDConnectProviders',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
),
'errorResponses' => array(
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListPolicies' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListPoliciesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListPolicies',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'Scope' => array(
'type' => 'string',
'location' => 'aws.query',
),
'OnlyAttached' => array(
'type' => 'boolean',
'format' => 'boolean-string',
'location' => 'aws.query',
),
'PathPrefix' => array(
'type' => 'string',
'location' => 'aws.query',
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListPolicyVersions' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListPolicyVersionsResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListPolicyVersions',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListRolePolicies' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListRolePoliciesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListRolePolicies',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListRoles' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListRolesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListRoles',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PathPrefix' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListSAMLProviders' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListSAMLProvidersResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListSAMLProviders',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
),
'errorResponses' => array(
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListSSHPublicKeys' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListSSHPublicKeysResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListSSHPublicKeys',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
),
),
'ListServerCertificates' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListServerCertificatesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListServerCertificates',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PathPrefix' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListSigningCertificates' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListSigningCertificatesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListSigningCertificates',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListUserPolicies' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListUserPoliciesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListUserPolicies',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListUsers' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListUsersResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListUsers',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PathPrefix' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
'errorResponses' => array(
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ListVirtualMFADevices' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'ListVirtualMFADevicesResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ListVirtualMFADevices',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'AssignmentStatus' => array(
'type' => 'string',
'location' => 'aws.query',
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
),
),
'PutGroupPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'PutGroupPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyDocument' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because the policy document was malformed. The error message describes the specific error.',
'class' => 'MalformedPolicyDocumentException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'PutRolePolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'PutRolePolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyDocument' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because the policy document was malformed. The error message describes the specific error.',
'class' => 'MalformedPolicyDocumentException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'PutUserPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'PutUserPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyDocument' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because the policy document was malformed. The error message describes the specific error.',
'class' => 'MalformedPolicyDocumentException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'RemoveClientIDFromOpenIDConnectProvider' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'RemoveClientIDFromOpenIDConnectProvider',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'OpenIDConnectProviderArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'ClientID' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'RemoveRoleFromInstanceProfile' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'RemoveRoleFromInstanceProfile',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'InstanceProfileName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'RemoveUserFromGroup' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'RemoveUserFromGroup',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'ResyncMFADevice' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'ResyncMFADevice',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'SerialNumber' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 9,
),
'AuthenticationCode1' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 6,
),
'AuthenticationCode2' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 6,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because the authentication code was not recognized. The error message describes the specific error.',
'class' => 'InvalidAuthenticationCodeException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'SetDefaultPolicyVersion' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'SetDefaultPolicyVersion',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicyArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'VersionId' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'SimulateCustomPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'SimulatePolicyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'SimulateCustomPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicyInputList' => array(
'required' => true,
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'PolicyInputList.member',
'items' => array(
'name' => 'policyDocumentType',
'type' => 'string',
'minLength' => 1,
),
),
'ActionNames' => array(
'required' => true,
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'ActionNames.member',
'items' => array(
'name' => 'ActionNameType',
'type' => 'string',
'minLength' => 3,
),
),
'ResourceArns' => array(
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'ResourceArns.member',
'items' => array(
'name' => 'ResourceNameType',
'type' => 'string',
'minLength' => 1,
),
),
'ResourcePolicy' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'ResourceOwner' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'CallerArn' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'ContextEntries' => array(
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'ContextEntries.member',
'items' => array(
'name' => 'ContextEntry',
'type' => 'object',
'properties' => array(
'ContextKeyName' => array(
'type' => 'string',
'minLength' => 5,
),
'ContextKeyValues' => array(
'type' => 'array',
'sentAs' => 'ContextKeyValues.member',
'items' => array(
'name' => 'ContextKeyValueType',
'type' => 'string',
),
),
'ContextKeyType' => array(
'type' => 'string',
),
),
),
),
'ResourceHandlingOption' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request failed because a provided policy could not be successfully evaluated. An additional detail message indicates the source of the failure.',
'class' => 'PolicyEvaluationException',
),
),
),
'SimulatePrincipalPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'SimulatePolicyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'SimulatePrincipalPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'PolicySourceArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'PolicyInputList' => array(
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'PolicyInputList.member',
'items' => array(
'name' => 'policyDocumentType',
'type' => 'string',
'minLength' => 1,
),
),
'ActionNames' => array(
'required' => true,
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'ActionNames.member',
'items' => array(
'name' => 'ActionNameType',
'type' => 'string',
'minLength' => 3,
),
),
'ResourceArns' => array(
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'ResourceArns.member',
'items' => array(
'name' => 'ResourceNameType',
'type' => 'string',
'minLength' => 1,
),
),
'ResourcePolicy' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'ResourceOwner' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'CallerArn' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'ContextEntries' => array(
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'ContextEntries.member',
'items' => array(
'name' => 'ContextEntry',
'type' => 'object',
'properties' => array(
'ContextKeyName' => array(
'type' => 'string',
'minLength' => 5,
),
'ContextKeyValues' => array(
'type' => 'array',
'sentAs' => 'ContextKeyValues.member',
'items' => array(
'name' => 'ContextKeyValueType',
'type' => 'string',
),
),
'ContextKeyType' => array(
'type' => 'string',
),
),
),
),
'ResourceHandlingOption' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'MaxItems' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1000,
),
'Marker' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request failed because a provided policy could not be successfully evaluated. An additional detail message indicates the source of the failure.',
'class' => 'PolicyEvaluationException',
),
),
),
'UpdateAccessKey' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UpdateAccessKey',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'AccessKeyId' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 16,
),
'Status' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'UpdateAccountPasswordPolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UpdateAccountPasswordPolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'MinimumPasswordLength' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 6,
'maximum' => 128,
),
'RequireSymbols' => array(
'type' => 'boolean',
'format' => 'boolean-string',
'location' => 'aws.query',
),
'RequireNumbers' => array(
'type' => 'boolean',
'format' => 'boolean-string',
'location' => 'aws.query',
),
'RequireUppercaseCharacters' => array(
'type' => 'boolean',
'format' => 'boolean-string',
'location' => 'aws.query',
),
'RequireLowercaseCharacters' => array(
'type' => 'boolean',
'format' => 'boolean-string',
'location' => 'aws.query',
),
'AllowUsersToChangePassword' => array(
'type' => 'boolean',
'format' => 'boolean-string',
'location' => 'aws.query',
),
'MaxPasswordAge' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 1095,
),
'PasswordReusePrevention' => array(
'type' => 'numeric',
'location' => 'aws.query',
'minimum' => 1,
'maximum' => 24,
),
'HardExpiry' => array(
'type' => 'boolean',
'format' => 'boolean-string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because the policy document was malformed. The error message describes the specific error.',
'class' => 'MalformedPolicyDocumentException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'UpdateAssumeRolePolicy' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UpdateAssumeRolePolicy',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'RoleName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PolicyDocument' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because the policy document was malformed. The error message describes the specific error.',
'class' => 'MalformedPolicyDocumentException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'UpdateGroup' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UpdateGroup',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'GroupName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'NewPath' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'NewGroupName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'UpdateLoginProfile' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UpdateLoginProfile',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'Password' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PasswordResetRequired' => array(
'type' => 'boolean',
'format' => 'boolean-string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that is temporarily unmodifiable, such as a user name that was deleted and then recreated. The error indicates that the request is likely to succeed if you try again after waiting several minutes. The error message describes the entity.',
'class' => 'EntityTemporarilyUnmodifiableException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because the provided password did not meet the requirements imposed by the account password policy.',
'class' => 'PasswordPolicyViolationException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'UpdateOpenIDConnectProviderThumbprint' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UpdateOpenIDConnectProviderThumbprint',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'OpenIDConnectProviderArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'ThumbprintList' => array(
'required' => true,
'type' => 'array',
'location' => 'aws.query',
'sentAs' => 'ThumbprintList.member',
'items' => array(
'name' => 'thumbprintType',
'type' => 'string',
'minLength' => 40,
),
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'UpdateSAMLProvider' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'UpdateSAMLProviderResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UpdateSAMLProvider',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'SAMLMetadataDocument' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1000,
),
'SAMLProviderArn' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because an invalid or out-of-range value was supplied for an input parameter.',
'class' => 'InvalidInputException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'UpdateSSHPublicKey' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UpdateSSHPublicKey',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'SSHPublicKeyId' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 20,
),
'Status' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
),
),
'UpdateServerCertificate' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UpdateServerCertificate',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'ServerCertificateName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'NewPath' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'NewServerCertificateName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'UpdateSigningCertificate' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UpdateSigningCertificate',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'CertificateId' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 24,
),
'Status' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'UpdateUser' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'EmptyOutput',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UpdateUser',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'NewPath' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'NewUserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that is temporarily unmodifiable, such as a user name that was deleted and then recreated. The error indicates that the request is likely to succeed if you try again after waiting several minutes. The error message describes the entity.',
'class' => 'EntityTemporarilyUnmodifiableException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'UploadSSHPublicKey' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'UploadSSHPublicKeyResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UploadSSHPublicKey',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'SSHPublicKeyBody' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request was rejected because the public key is malformed or otherwise invalid.',
'class' => 'InvalidPublicKeyException',
),
array(
'reason' => 'The request was rejected because the SSH public key is already associated with the specified IAM user.',
'class' => 'DuplicateSSHPublicKeyException',
),
array(
'reason' => 'The request was rejected because the public key encoding format is unsupported or unrecognized.',
'class' => 'UnrecognizedPublicKeyEncodingException',
),
),
),
'UploadServerCertificate' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'UploadServerCertificateResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UploadServerCertificate',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'Path' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'ServerCertificateName' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'CertificateBody' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'PrivateKey' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'CertificateChain' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because the certificate was malformed or expired. The error message describes the specific error.',
'class' => 'MalformedCertificateException',
),
array(
'reason' => 'The request was rejected because the public key certificate and the private key do not match.',
'class' => 'KeyPairMismatchException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
'UploadSigningCertificate' => array(
'httpMethod' => 'POST',
'uri' => '/',
'class' => 'Aws\\Common\\Command\\QueryCommand',
'responseClass' => 'UploadSigningCertificateResponse',
'responseType' => 'model',
'parameters' => array(
'Action' => array(
'static' => true,
'location' => 'aws.query',
'default' => 'UploadSigningCertificate',
),
'Version' => array(
'static' => true,
'location' => 'aws.query',
'default' => '2010-05-08',
),
'UserName' => array(
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
'CertificateBody' => array(
'required' => true,
'type' => 'string',
'location' => 'aws.query',
'minLength' => 1,
),
),
'errorResponses' => array(
array(
'reason' => 'The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.',
'class' => 'LimitExceededException',
),
array(
'reason' => 'The request was rejected because it attempted to create a resource that already exists.',
'class' => 'EntityAlreadyExistsException',
),
array(
'reason' => 'The request was rejected because the certificate was malformed or expired. The error message describes the specific error.',
'class' => 'MalformedCertificateException',
),
array(
'reason' => 'The request was rejected because the certificate is invalid.',
'class' => 'InvalidCertificateException',
),
array(
'reason' => 'The request was rejected because the same certificate is associated with an IAM user in the account.',
'class' => 'DuplicateCertificateException',
),
array(
'reason' => 'The request was rejected because it referenced an entity that does not exist. The error message describes the entity.',
'class' => 'NoSuchEntityException',
),
array(
'reason' => 'The request processing has failed because of an unknown error, exception or failure.',
'class' => 'ServiceFailureException',
),
),
),
),
'models' => array(
'EmptyOutput' => array(
'type' => 'object',
'additionalProperties' => true,
),
'CreateAccessKeyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'AccessKey' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'UserName' => array(
'type' => 'string',
),
'AccessKeyId' => array(
'type' => 'string',
),
'Status' => array(
'type' => 'string',
),
'SecretAccessKey' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
),
),
),
),
'CreateGroupResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Group' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'GroupName' => array(
'type' => 'string',
),
'GroupId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
),
),
),
),
'CreateInstanceProfileResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'InstanceProfile' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'InstanceProfileName' => array(
'type' => 'string',
),
'InstanceProfileId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'Roles' => array(
'type' => 'array',
'items' => array(
'name' => 'Role',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'RoleName' => array(
'type' => 'string',
),
'RoleId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'AssumeRolePolicyDocument' => array(
'type' => 'string',
),
),
),
),
),
),
),
),
'CreateLoginProfileResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'LoginProfile' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'UserName' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'PasswordResetRequired' => array(
'type' => 'boolean',
),
),
),
),
),
'CreateOpenIDConnectProviderResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'OpenIDConnectProviderArn' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'CreatePolicyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Policy' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'Path' => array(
'type' => 'string',
),
'DefaultVersionId' => array(
'type' => 'string',
),
'AttachmentCount' => array(
'type' => 'numeric',
),
'IsAttachable' => array(
'type' => 'boolean',
),
'Description' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'UpdateDate' => array(
'type' => 'string',
),
),
),
),
),
'CreatePolicyVersionResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'PolicyVersion' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Document' => array(
'type' => 'string',
),
'VersionId' => array(
'type' => 'string',
),
'IsDefaultVersion' => array(
'type' => 'boolean',
),
'CreateDate' => array(
'type' => 'string',
),
),
),
),
),
'CreateRoleResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Role' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'RoleName' => array(
'type' => 'string',
),
'RoleId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'AssumeRolePolicyDocument' => array(
'type' => 'string',
),
),
),
),
),
'CreateSAMLProviderResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'SAMLProviderArn' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'CreateUserResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'User' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'UserName' => array(
'type' => 'string',
),
'UserId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'PasswordLastUsed' => array(
'type' => 'string',
),
),
),
),
),
'CreateVirtualMFADeviceResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'VirtualMFADevice' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'SerialNumber' => array(
'type' => 'string',
),
'Base32StringSeed' => array(
'type' => 'string',
),
'QRCodePNG' => array(
'type' => 'string',
),
'User' => array(
'type' => 'object',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'UserName' => array(
'type' => 'string',
),
'UserId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'PasswordLastUsed' => array(
'type' => 'string',
),
),
),
'EnableDate' => array(
'type' => 'string',
),
),
),
),
),
'GenerateCredentialReportResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'State' => array(
'type' => 'string',
'location' => 'xml',
),
'Description' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'GetAccessKeyLastUsedResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'UserName' => array(
'type' => 'string',
'location' => 'xml',
),
'AccessKeyLastUsed' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'LastUsedDate' => array(
'type' => 'string',
),
'ServiceName' => array(
'type' => 'string',
),
'Region' => array(
'type' => 'string',
),
),
),
),
),
'GetAccountAuthorizationDetailsResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'UserDetailList' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'UserDetail',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'UserName' => array(
'type' => 'string',
),
'UserId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'UserPolicyList' => array(
'type' => 'array',
'items' => array(
'name' => 'PolicyDetail',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyDocument' => array(
'type' => 'string',
),
),
),
),
'GroupList' => array(
'type' => 'array',
'items' => array(
'name' => 'groupNameType',
'type' => 'string',
'sentAs' => 'member',
),
),
'AttachedManagedPolicies' => array(
'type' => 'array',
'items' => array(
'name' => 'AttachedPolicy',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyArn' => array(
'type' => 'string',
),
),
),
),
),
),
),
'GroupDetailList' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'GroupDetail',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'GroupName' => array(
'type' => 'string',
),
'GroupId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'GroupPolicyList' => array(
'type' => 'array',
'items' => array(
'name' => 'PolicyDetail',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyDocument' => array(
'type' => 'string',
),
),
),
),
'AttachedManagedPolicies' => array(
'type' => 'array',
'items' => array(
'name' => 'AttachedPolicy',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyArn' => array(
'type' => 'string',
),
),
),
),
),
),
),
'RoleDetailList' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'RoleDetail',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'RoleName' => array(
'type' => 'string',
),
'RoleId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'AssumeRolePolicyDocument' => array(
'type' => 'string',
),
'InstanceProfileList' => array(
'type' => 'array',
'items' => array(
'name' => 'InstanceProfile',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'InstanceProfileName' => array(
'type' => 'string',
),
'InstanceProfileId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'Roles' => array(
'type' => 'array',
'items' => array(
'name' => 'Role',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'RoleName' => array(
'type' => 'string',
),
'RoleId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'AssumeRolePolicyDocument' => array(
'type' => 'string',
),
),
),
),
),
),
),
'RolePolicyList' => array(
'type' => 'array',
'items' => array(
'name' => 'PolicyDetail',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyDocument' => array(
'type' => 'string',
),
),
),
),
'AttachedManagedPolicies' => array(
'type' => 'array',
'items' => array(
'name' => 'AttachedPolicy',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyArn' => array(
'type' => 'string',
),
),
),
),
),
),
),
'Policies' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'ManagedPolicyDetail',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'Path' => array(
'type' => 'string',
),
'DefaultVersionId' => array(
'type' => 'string',
),
'AttachmentCount' => array(
'type' => 'numeric',
),
'IsAttachable' => array(
'type' => 'boolean',
),
'Description' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'UpdateDate' => array(
'type' => 'string',
),
'PolicyVersionList' => array(
'type' => 'array',
'items' => array(
'name' => 'PolicyVersion',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Document' => array(
'type' => 'string',
),
'VersionId' => array(
'type' => 'string',
),
'IsDefaultVersion' => array(
'type' => 'boolean',
),
'CreateDate' => array(
'type' => 'string',
),
),
),
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'GetAccountPasswordPolicyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'PasswordPolicy' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'MinimumPasswordLength' => array(
'type' => 'numeric',
),
'RequireSymbols' => array(
'type' => 'boolean',
),
'RequireNumbers' => array(
'type' => 'boolean',
),
'RequireUppercaseCharacters' => array(
'type' => 'boolean',
),
'RequireLowercaseCharacters' => array(
'type' => 'boolean',
),
'AllowUsersToChangePassword' => array(
'type' => 'boolean',
),
'ExpirePasswords' => array(
'type' => 'boolean',
),
'MaxPasswordAge' => array(
'type' => 'numeric',
),
'PasswordReusePrevention' => array(
'type' => 'numeric',
),
'HardExpiry' => array(
'type' => 'boolean',
),
),
),
),
),
'GetAccountSummaryResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'SummaryMap' => array(
'type' => 'array',
'location' => 'xml',
'data' => array(
'xmlMap' => array(
'Users',
'UsersQuota',
'Groups',
'GroupsQuota',
'ServerCertificates',
'ServerCertificatesQuota',
'UserPolicySizeQuota',
'GroupPolicySizeQuota',
'GroupsPerUserQuota',
'SigningCertificatesPerUserQuota',
'AccessKeysPerUserQuota',
'MFADevices',
'MFADevicesInUse',
'AccountMFAEnabled',
'AccountAccessKeysPresent',
'AccountSigningCertificatesPresent',
'AttachedPoliciesPerGroupQuota',
'AttachedPoliciesPerRoleQuota',
'AttachedPoliciesPerUserQuota',
'Policies',
'PoliciesQuota',
'PolicySizeQuota',
'PolicyVersionsInUse',
'PolicyVersionsInUseQuota',
'VersionsPerPolicyQuota',
),
),
'filters' => array(
array(
'method' => 'Aws\\Common\\Command\\XmlResponseLocationVisitor::xmlMap',
'args' => array(
'@value',
'entry',
'key',
'value',
),
),
),
'items' => array(
'name' => 'entry',
'type' => 'object',
'sentAs' => 'entry',
'additionalProperties' => true,
'properties' => array(
'key' => array(
'type' => 'string',
),
'value' => array(
'type' => 'numeric',
),
),
),
'additionalProperties' => false,
),
),
),
'GetContextKeysForPolicyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'ContextKeyNames' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'ContextKeyNameType',
'type' => 'string',
'sentAs' => 'member',
),
),
),
),
'GetCredentialReportResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Content' => array(
'type' => 'string',
'location' => 'xml',
),
'ReportFormat' => array(
'type' => 'string',
'location' => 'xml',
),
'GeneratedTime' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'GetGroupResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Group' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'GroupName' => array(
'type' => 'string',
),
'GroupId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
),
),
'Users' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'User',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'UserName' => array(
'type' => 'string',
),
'UserId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'PasswordLastUsed' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'GetGroupPolicyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'GroupName' => array(
'type' => 'string',
'location' => 'xml',
),
'PolicyName' => array(
'type' => 'string',
'location' => 'xml',
),
'PolicyDocument' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'GetInstanceProfileResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'InstanceProfile' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'InstanceProfileName' => array(
'type' => 'string',
),
'InstanceProfileId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'Roles' => array(
'type' => 'array',
'items' => array(
'name' => 'Role',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'RoleName' => array(
'type' => 'string',
),
'RoleId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'AssumeRolePolicyDocument' => array(
'type' => 'string',
),
),
),
),
),
),
),
),
'GetLoginProfileResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'LoginProfile' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'UserName' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'PasswordResetRequired' => array(
'type' => 'boolean',
),
),
),
),
),
'GetOpenIDConnectProviderResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Url' => array(
'type' => 'string',
'location' => 'xml',
),
'ClientIDList' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'clientIDType',
'type' => 'string',
'sentAs' => 'member',
),
),
'ThumbprintList' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'thumbprintType',
'type' => 'string',
'sentAs' => 'member',
),
),
'CreateDate' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'GetPolicyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Policy' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'Path' => array(
'type' => 'string',
),
'DefaultVersionId' => array(
'type' => 'string',
),
'AttachmentCount' => array(
'type' => 'numeric',
),
'IsAttachable' => array(
'type' => 'boolean',
),
'Description' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'UpdateDate' => array(
'type' => 'string',
),
),
),
),
),
'GetPolicyVersionResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'PolicyVersion' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Document' => array(
'type' => 'string',
),
'VersionId' => array(
'type' => 'string',
),
'IsDefaultVersion' => array(
'type' => 'boolean',
),
'CreateDate' => array(
'type' => 'string',
),
),
),
),
),
'GetRoleResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Role' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'RoleName' => array(
'type' => 'string',
),
'RoleId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'AssumeRolePolicyDocument' => array(
'type' => 'string',
),
),
),
),
),
'GetRolePolicyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'RoleName' => array(
'type' => 'string',
'location' => 'xml',
),
'PolicyName' => array(
'type' => 'string',
'location' => 'xml',
),
'PolicyDocument' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'GetSAMLProviderResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'SAMLMetadataDocument' => array(
'type' => 'string',
'location' => 'xml',
),
'CreateDate' => array(
'type' => 'string',
'location' => 'xml',
),
'ValidUntil' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'GetSSHPublicKeyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'SSHPublicKey' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'UserName' => array(
'type' => 'string',
),
'SSHPublicKeyId' => array(
'type' => 'string',
),
'Fingerprint' => array(
'type' => 'string',
),
'SSHPublicKeyBody' => array(
'type' => 'string',
),
'Status' => array(
'type' => 'string',
),
'UploadDate' => array(
'type' => 'string',
),
),
),
),
),
'GetServerCertificateResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'ServerCertificate' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'ServerCertificateMetadata' => array(
'type' => 'object',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'ServerCertificateName' => array(
'type' => 'string',
),
'ServerCertificateId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'UploadDate' => array(
'type' => 'string',
),
'Expiration' => array(
'type' => 'string',
),
),
),
'CertificateBody' => array(
'type' => 'string',
),
'CertificateChain' => array(
'type' => 'string',
),
),
),
),
),
'GetUserResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'User' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'UserName' => array(
'type' => 'string',
),
'UserId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'PasswordLastUsed' => array(
'type' => 'string',
),
),
),
),
),
'GetUserPolicyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'UserName' => array(
'type' => 'string',
'location' => 'xml',
),
'PolicyName' => array(
'type' => 'string',
'location' => 'xml',
),
'PolicyDocument' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListAccessKeysResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'AccessKeyMetadata' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'AccessKeyMetadata',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'UserName' => array(
'type' => 'string',
),
'AccessKeyId' => array(
'type' => 'string',
),
'Status' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListAccountAliasesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'AccountAliases' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'accountAliasType',
'type' => 'string',
'sentAs' => 'member',
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListAttachedGroupPoliciesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'AttachedPolicies' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'AttachedPolicy',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyArn' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListAttachedRolePoliciesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'AttachedPolicies' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'AttachedPolicy',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyArn' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListAttachedUserPoliciesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'AttachedPolicies' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'AttachedPolicy',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyArn' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListEntitiesForPolicyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'PolicyGroups' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'PolicyGroup',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'GroupName' => array(
'type' => 'string',
),
),
),
),
'PolicyUsers' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'PolicyUser',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'UserName' => array(
'type' => 'string',
),
),
),
),
'PolicyRoles' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'PolicyRole',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'RoleName' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListGroupPoliciesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'PolicyNames' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'policyNameType',
'type' => 'string',
'sentAs' => 'member',
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListGroupsResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Groups' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'Group',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'GroupName' => array(
'type' => 'string',
),
'GroupId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListGroupsForUserResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Groups' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'Group',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'GroupName' => array(
'type' => 'string',
),
'GroupId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListInstanceProfilesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'InstanceProfiles' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'InstanceProfile',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'InstanceProfileName' => array(
'type' => 'string',
),
'InstanceProfileId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'Roles' => array(
'type' => 'array',
'items' => array(
'name' => 'Role',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'RoleName' => array(
'type' => 'string',
),
'RoleId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'AssumeRolePolicyDocument' => array(
'type' => 'string',
),
),
),
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListInstanceProfilesForRoleResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'InstanceProfiles' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'InstanceProfile',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'InstanceProfileName' => array(
'type' => 'string',
),
'InstanceProfileId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'Roles' => array(
'type' => 'array',
'items' => array(
'name' => 'Role',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'RoleName' => array(
'type' => 'string',
),
'RoleId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'AssumeRolePolicyDocument' => array(
'type' => 'string',
),
),
),
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListMFADevicesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'MFADevices' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'MFADevice',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'UserName' => array(
'type' => 'string',
),
'SerialNumber' => array(
'type' => 'string',
),
'EnableDate' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListOpenIDConnectProvidersResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'OpenIDConnectProviderList' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'OpenIDConnectProviderListEntry',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Arn' => array(
'type' => 'string',
),
),
),
),
),
),
'ListPoliciesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Policies' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'Policy',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'PolicyName' => array(
'type' => 'string',
),
'PolicyId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'Path' => array(
'type' => 'string',
),
'DefaultVersionId' => array(
'type' => 'string',
),
'AttachmentCount' => array(
'type' => 'numeric',
),
'IsAttachable' => array(
'type' => 'boolean',
),
'Description' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'UpdateDate' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListPolicyVersionsResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Versions' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'PolicyVersion',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Document' => array(
'type' => 'string',
),
'VersionId' => array(
'type' => 'string',
),
'IsDefaultVersion' => array(
'type' => 'boolean',
),
'CreateDate' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListRolePoliciesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'PolicyNames' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'policyNameType',
'type' => 'string',
'sentAs' => 'member',
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListRolesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Roles' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'Role',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'RoleName' => array(
'type' => 'string',
),
'RoleId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'AssumeRolePolicyDocument' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListSAMLProvidersResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'SAMLProviderList' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'SAMLProviderListEntry',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Arn' => array(
'type' => 'string',
),
'ValidUntil' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
),
),
),
),
),
'ListSSHPublicKeysResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'SSHPublicKeys' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'SSHPublicKeyMetadata',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'UserName' => array(
'type' => 'string',
),
'SSHPublicKeyId' => array(
'type' => 'string',
),
'Status' => array(
'type' => 'string',
),
'UploadDate' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListServerCertificatesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'ServerCertificateMetadataList' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'ServerCertificateMetadata',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'ServerCertificateName' => array(
'type' => 'string',
),
'ServerCertificateId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'UploadDate' => array(
'type' => 'string',
),
'Expiration' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListSigningCertificatesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Certificates' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'SigningCertificate',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'UserName' => array(
'type' => 'string',
),
'CertificateId' => array(
'type' => 'string',
),
'CertificateBody' => array(
'type' => 'string',
),
'Status' => array(
'type' => 'string',
),
'UploadDate' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListUserPoliciesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'PolicyNames' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'policyNameType',
'type' => 'string',
'sentAs' => 'member',
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListUsersResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Users' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'User',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'UserName' => array(
'type' => 'string',
),
'UserId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'PasswordLastUsed' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'ListVirtualMFADevicesResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'VirtualMFADevices' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'VirtualMFADevice',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'SerialNumber' => array(
'type' => 'string',
),
'Base32StringSeed' => array(
'type' => 'string',
),
'QRCodePNG' => array(
'type' => 'string',
),
'User' => array(
'type' => 'object',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'UserName' => array(
'type' => 'string',
),
'UserId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'CreateDate' => array(
'type' => 'string',
),
'PasswordLastUsed' => array(
'type' => 'string',
),
),
),
'EnableDate' => array(
'type' => 'string',
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'SimulatePolicyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'EvaluationResults' => array(
'type' => 'array',
'location' => 'xml',
'items' => array(
'name' => 'EvaluationResult',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'EvalActionName' => array(
'type' => 'string',
),
'EvalResourceName' => array(
'type' => 'string',
),
'EvalDecision' => array(
'type' => 'string',
),
'MatchedStatements' => array(
'type' => 'array',
'items' => array(
'name' => 'Statement',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'SourcePolicyId' => array(
'type' => 'string',
),
'SourcePolicyType' => array(
'type' => 'string',
),
'StartPosition' => array(
'type' => 'object',
'properties' => array(
'Line' => array(
'type' => 'numeric',
),
'Column' => array(
'type' => 'numeric',
),
),
),
'EndPosition' => array(
'type' => 'object',
'properties' => array(
'Line' => array(
'type' => 'numeric',
),
'Column' => array(
'type' => 'numeric',
),
),
),
),
),
),
'MissingContextValues' => array(
'type' => 'array',
'items' => array(
'name' => 'ContextKeyNameType',
'type' => 'string',
'sentAs' => 'member',
),
),
'EvalDecisionDetails' => array(
'type' => 'array',
'filters' => array(
array(
'method' => 'Aws\\Common\\Command\\XmlResponseLocationVisitor::xmlMap',
'args' => array(
'@value',
'entry',
'key',
'value',
),
),
),
'items' => array(
'name' => 'entry',
'type' => 'object',
'sentAs' => 'entry',
'additionalProperties' => true,
'properties' => array(
'key' => array(
'type' => 'string',
),
'value' => array(
'type' => 'string',
),
),
),
'additionalProperties' => false,
),
'ResourceSpecificResults' => array(
'type' => 'array',
'items' => array(
'name' => 'ResourceSpecificResult',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'EvalResourceName' => array(
'type' => 'string',
),
'EvalResourceDecision' => array(
'type' => 'string',
),
'MatchedStatements' => array(
'type' => 'array',
'items' => array(
'name' => 'Statement',
'type' => 'object',
'sentAs' => 'member',
'properties' => array(
'SourcePolicyId' => array(
'type' => 'string',
),
'SourcePolicyType' => array(
'type' => 'string',
),
'StartPosition' => array(
'type' => 'object',
'properties' => array(
'Line' => array(
'type' => 'numeric',
),
'Column' => array(
'type' => 'numeric',
),
),
),
'EndPosition' => array(
'type' => 'object',
'properties' => array(
'Line' => array(
'type' => 'numeric',
),
'Column' => array(
'type' => 'numeric',
),
),
),
),
),
),
'MissingContextValues' => array(
'type' => 'array',
'items' => array(
'name' => 'ContextKeyNameType',
'type' => 'string',
'sentAs' => 'member',
),
),
'EvalDecisionDetails' => array(
'type' => 'array',
'filters' => array(
array(
'method' => 'Aws\\Common\\Command\\XmlResponseLocationVisitor::xmlMap',
'args' => array(
'@value',
'entry',
'key',
'value',
),
),
),
'items' => array(
'name' => 'entry',
'type' => 'object',
'sentAs' => 'entry',
'additionalProperties' => true,
'properties' => array(
'key' => array(
'type' => 'string',
),
'value' => array(
'type' => 'string',
),
),
),
'additionalProperties' => false,
),
),
),
),
),
),
),
'IsTruncated' => array(
'type' => 'boolean',
'location' => 'xml',
),
'Marker' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'UpdateSAMLProviderResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'SAMLProviderArn' => array(
'type' => 'string',
'location' => 'xml',
),
),
),
'UploadSSHPublicKeyResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'SSHPublicKey' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'UserName' => array(
'type' => 'string',
),
'SSHPublicKeyId' => array(
'type' => 'string',
),
'Fingerprint' => array(
'type' => 'string',
),
'SSHPublicKeyBody' => array(
'type' => 'string',
),
'Status' => array(
'type' => 'string',
),
'UploadDate' => array(
'type' => 'string',
),
),
),
),
),
'UploadServerCertificateResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'ServerCertificateMetadata' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'Path' => array(
'type' => 'string',
),
'ServerCertificateName' => array(
'type' => 'string',
),
'ServerCertificateId' => array(
'type' => 'string',
),
'Arn' => array(
'type' => 'string',
),
'UploadDate' => array(
'type' => 'string',
),
'Expiration' => array(
'type' => 'string',
),
),
),
),
),
'UploadSigningCertificateResponse' => array(
'type' => 'object',
'additionalProperties' => true,
'properties' => array(
'Certificate' => array(
'type' => 'object',
'location' => 'xml',
'properties' => array(
'UserName' => array(
'type' => 'string',
),
'CertificateId' => array(
'type' => 'string',
),
'CertificateBody' => array(
'type' => 'string',
),
'Status' => array(
'type' => 'string',
),
'UploadDate' => array(
'type' => 'string',
),
),
),
),
),
),
'iterators' => array(
'GetGroup' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'Users',
),
'ListAccessKeys' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'AccessKeyMetadata',
),
'ListAccountAliases' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'AccountAliases',
),
'ListAttachedGroupPolicies' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'AttachedPolicies',
),
'ListAttachedRolePolicies' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'AttachedPolicies',
),
'ListAttachedUserPolicies' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'AttachedPolicies',
),
'ListEntitiesForPolicy' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => array(
'PolicyGroups',
'PolicyUsers',
'PolicyRoles',
),
),
'ListGroupPolicies' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'PolicyNames',
),
'ListGroups' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'Groups',
),
'ListGroupsForUser' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'Groups',
),
'ListInstanceProfiles' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'InstanceProfiles',
),
'ListInstanceProfilesForRole' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'InstanceProfiles',
),
'ListMFADevices' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'MFADevices',
),
'ListPolicies' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'Policies',
),
'ListRolePolicies' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'PolicyNames',
),
'ListRoles' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'Roles',
),
'ListSAMLProviders' => array(
'result_key' => 'SAMLProviderList',
),
'ListServerCertificates' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'ServerCertificateMetadataList',
),
'ListSigningCertificates' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'Certificates',
),
'ListUserPolicies' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'PolicyNames',
),
'ListUsers' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'Users',
),
'ListVirtualMFADevices' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
'result_key' => 'VirtualMFADevices',
),
'GetAccountAuthorizationDetails' => array(
'input_token' => 'Marker',
'output_token' => 'Marker',
'more_results' => 'IsTruncated',
'limit_key' => 'MaxItems',
),
),
);
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/NoSuchEntityException.php 0000644 00000001443 15132770567 0022775 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because it referenced an entity that does not exist. The error message describes the entity.
*/
class NoSuchEntityException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/MalformedPolicyDocumentException.php 0000644 00000001454 15132770567 0025170 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because the policy document was malformed. The error message describes the specific error.
*/
class MalformedPolicyDocumentException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/InvalidCertificateException.php 0000644 00000001360 15132770567 0024130 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because the certificate is invalid.
*/
class InvalidCertificateException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/EntityAlreadyExistsException.php 0000644 00000001414 15132770567 0024355 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because it attempted to create a resource that already exists.
*/
class EntityAlreadyExistsException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/InvalidUserTypeException.php 0000644 00000001405 15132770567 0023466 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because the type of user for the transaction was incorrect.
*/
class InvalidUserTypeException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/LimitExceededException.php 0000644 00000001507 15132770567 0023107 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because it attempted to create resources beyond the current AWS account limits. The error message describes the limit exceeded.
*/
class LimitExceededException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/InvalidAuthenticationCodeException.php 0000644 00000001467 15132770567 0025470 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because the authentication code was not recognized. The error message describes the specific error.
*/
class InvalidAuthenticationCodeException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/DuplicateCertificateException.php 0000644 00000001434 15132770567 0024456 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because the same certificate is associated to another user under the account.
*/
class DuplicateCertificateException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/EntityTemporarilyUnmodifiableException.php 0000644 00000001744 15132770567 0026430 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because it referenced an entity that is temporarily unmodifiable, such as a user name that was deleted and then recreated. The error indicates that the request is likely to succeed if you try again after waiting several minutes. The error message describes the entity.
*/
class EntityTemporarilyUnmodifiableException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/DeleteConflictException.php 0000644 00000001506 15132770567 0023265 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because it attempted to delete a resource that has attached subordinate entities. The error message describes these entities.
*/
class DeleteConflictException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/IamException.php 0000644 00000001404 15132770567 0021104 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
use Aws\Common\Exception\ServiceResponseException;
/**
* Default service exception class
*/
class IamException extends ServiceResponseException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/InvalidInputException.php 0000644 00000001365 15132770567 0023012 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* Exception that occurs when a InvalidInputException error is encountered
*/
class InvalidInputException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/PasswordPolicyViolationException.php 0000644 00000001465 15132770567 0025254 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because the provided password did not meet the requirements imposed by the account password policy.
*/
class PasswordPolicyViolationException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/MalformedCertificateException.php 0000644 00000001460 15132770567 0024451 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because the certificate was malformed or expired. The error message describes the specific error.
*/
class MalformedCertificateException extends IamException {}
includes/lib/aws-sdk-php-2.8.31/src/Aws/Iam/Exception/KeyPairMismatchException.php 0000644 00000001416 15132770567 0023433 0 ustar 00 <?php
/**
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
namespace Aws\Iam\Exception;
/**
* The request was rejected because the public key certificate and the private key do not match.
*/
class KeyPairMismatchException extends IamException {}
includes/class-wpvivid-backup.php 0000644 00000347261 15132770567 0013153 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
define('WPVIVID_BACKUP_TYPE_DB','backup_db');
define('WPVIVID_BACKUP_TYPE_THEMES','backup_themes');
define('WPVIVID_BACKUP_TYPE_PLUGIN','backup_plugin');
define('WPVIVID_BACKUP_TYPE_UPLOADS','backup_uploads');
define('WPVIVID_BACKUP_TYPE_UPLOADS_FILES','backup_uploads_files');
//define('WPVIVID_BACKUP_TYPE_UPLOADS_FILES_OTHER','backup_uploads_files_other');
define('WPVIVID_BACKUP_TYPE_CONTENT','backup_content');
define('WPVIVID_BACKUP_TYPE_CORE','backup_core');
define('WPVIVID_BACKUP_TYPE_OTHERS','backup_others');
define('WPVIVID_BACKUP_TYPE_MERGE','backup_merge');
define('WPVIVID_BACKUP_ROOT_WP_CONTENT','wp-content');
define('WPVIVID_BACKUP_ROOT_CUSTOM','custom');
define('WPVIVID_BACKUP_ROOT_WP_ROOT','root');
define('WPVIVID_BACKUP_ROOT_WP_UPLOADS','uploads');
class WPvivid_Backup_Task
{
protected $task;
public $backup_type_collect;
public function __construct($task_id=false,$task=false)
{
if($task_id!==false)
{
$this->task=WPvivid_taskmanager::get_task($task_id);
}
if($task!==false)
{
$this->task=$task;
}
$this->backup_type_collect[WPVIVID_BACKUP_TYPE_DB]=1;
$this->backup_type_collect[WPVIVID_BACKUP_TYPE_THEMES]=1;
$this->backup_type_collect[WPVIVID_BACKUP_TYPE_PLUGIN]=1;
$this->backup_type_collect[WPVIVID_BACKUP_TYPE_UPLOADS]=1;
$this->backup_type_collect[WPVIVID_BACKUP_TYPE_UPLOADS_FILES]=1;
//$this->backup_type_collect[WPVIVID_BACKUP_TYPE_UPLOADS_FILES_OTHER]=1;
$this->backup_type_collect[WPVIVID_BACKUP_TYPE_CONTENT]=1;
$this->backup_type_collect[WPVIVID_BACKUP_TYPE_CORE]=1;
$this->backup_type_collect[WPVIVID_BACKUP_TYPE_OTHERS]=1;
$this->backup_type_collect[WPVIVID_BACKUP_TYPE_MERGE]=1;
add_filter('wpvivid_set_backup', array($this, 'wpvivid_set_backup'),10);
add_filter('wpvivid_exclude_plugins',array($this,'exclude_plugins'),20);
add_filter('wpvivid_get_backup_exclude_regex',array($this, 'get_backup_exclude_regex'),10,2);
}
public function get_backup_exclude_regex($exclude_regex,$backup_type)
{
if($backup_type==WPVIVID_BACKUP_TYPE_UPLOADS||$backup_type==WPVIVID_BACKUP_TYPE_UPLOADS_FILES)
{
$upload_dir = wp_upload_dir();
$backup_data['files_root']=$this -> transfer_path($upload_dir['basedir']);
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($upload_dir['basedir']).DIRECTORY_SEPARATOR.'backwpup', '/').'#'; // BackWPup backup directory
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($upload_dir['basedir']).DIRECTORY_SEPARATOR.'ShortpixelBackups', '/').'#';//ShortpixelBackups
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($upload_dir['basedir']).DIRECTORY_SEPARATOR.'backup', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($upload_dir['basedir']).DIRECTORY_SEPARATOR.'backwpup', '/').'#'; // BackWPup backup directory
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($upload_dir['basedir']).DIRECTORY_SEPARATOR.'backup-guard', '/').'#'; // Wordpress Backup and Migrate Plugin backup directory
}
else if($backup_type==WPVIVID_BACKUP_TYPE_CONTENT)
{
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'updraft', '/').'#'; // Updraft Plus backup directory
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'ai1wm-backups', '/').'#'; // All-in-one WP migration backup directory
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'backups', '/').'#'; // Xcloner backup directory
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'upgrade', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'wpvivid', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir(), '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'plugins', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'cache', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'wphb-cache', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'backup', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'Dropbox_Backup', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'mysql.sql', '/').'#';//mysql
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'backup-migration', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.'backups-dup-lite', '/').'#';
if(defined('WPVIVID_UPLOADS_ISO_DIR'))
{
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR, '/').'#';
}
$upload_dir = wp_upload_dir();
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($upload_dir['basedir']), '/').'$#';
$exclude_regex[]='#^'.preg_quote($this->transfer_path(get_theme_root()), '/').'#';
}
return $exclude_regex;
}
public function exclude_plugins($exclude_plugins)
{
if(in_array('wpvivid-backuprestore',$exclude_plugins))
{
$exclude_plugins[]='wpvivid-backuprestore';
}
if(in_array('wp-cerber',$exclude_plugins))
{
$exclude_plugins[]='wp-cerber';
}
if(in_array('.',$exclude_plugins))
{
$exclude_plugins[]='.';
}
if(in_array('wpvivid-backup-pro',$exclude_plugins))
{
$exclude_plugins[]='wpvivid-backup-pro';
}
return $exclude_plugins;
}
public function get_id()
{
return $this->task['id'];
}
public function new_backup_task($options,$type,$action='backup')
{
$id=uniqid('wpvivid-');
$this->task=false;
$this->task['id']=$id;
$this->task['action']=$action;
$this->task['type']=$type;
$this->task['status']['start_time']=time();
$this->task['status']['run_time']=time();
$this->task['status']['timeout']=time();
$this->task['status']['str']='ready';
$this->task['status']['resume_count']=0;
if(isset($options['remote']))
{
if($options['remote']=='1')
{
if(isset($options['remote_options']))
{
$this->task['options']['remote_options']=$options['remote_options'];
}
else
{
$this->task['options']['remote_options']=WPvivid_Setting::get_remote_options();
}
}
else {
$this->task['options']['remote_options']=false;
}
}
else
{
$this->task['options']['remote_options']=false;
}
$this->task['options']['remote_options'] = apply_filters('wpvivid_set_remote_options', $this->task['options']['remote_options'],$options);
if(isset($options['local']))
{
if($options['local']=='1')
{
$this->task['options']['save_local']=1;
}
else
{
$this->task['options']['save_local']=0;
}
}
else
{
$this->task['options']['save_local']=1;
}
if(isset($options['lock']))
{
$this->task['options']['lock']=$options['lock'];
}
else
{
$this->task['options']['lock']=0;
}
$general_setting=WPvivid_Setting::get_setting(true, "");
if(isset($options['backup_prefix']) && !empty($options['backup_prefix']))
{
$backup_prefix=$options['backup_prefix'];
}
else
{
if(isset($general_setting['options']['wpvivid_common_setting']['domain_include'])&&$general_setting['options']['wpvivid_common_setting']['domain_include'])
{
$check_addon = apply_filters('wpvivid_check_setting_addon', 'not_addon');
if (isset($general_setting['options']['wpvivid_common_setting']['backup_prefix']) && $check_addon == 'addon')
{
$backup_prefix = $general_setting['options']['wpvivid_common_setting']['backup_prefix'];
}
else {
$home_url_prefix = get_home_url();
$home_url_prefix = $this->parse_url_all($home_url_prefix);
$backup_prefix = $home_url_prefix;
}
}
else
{
$backup_prefix='';
}
}
$this->task['options']['backup_prefix']=$backup_prefix;
$offset=get_option('gmt_offset');
if(empty($backup_prefix))
$this->task['options']['file_prefix'] = $this->task['id'] . '_' . gmdate('Y-m-d-H-i', $this->task['status']['start_time']+$offset*60*60);
else
$this->task['options']['file_prefix'] = $backup_prefix . '_' . $this->task['id'] . '_' . gmdate('Y-m-d-H-i', $this->task['status']['start_time']+$offset*60*60);
$this->task['options']['file_prefix'] = apply_filters('wpvivid_backup_file_prefix',$this->task['options']['file_prefix'],$backup_prefix,$this->task['id'],$this->task['status']['start_time']);
if(isset($general_setting['options']['wpvivid_common_setting']['ismerge']))
{
if($general_setting['options']['wpvivid_common_setting']['ismerge']==1)
{
$this->task['options']['backup_options']['ismerge']=1;
}
else {
$this->task['options']['backup_options']['ismerge']=0;
}
}
else {
$this->task['options']['backup_options']['ismerge']=1;
}
$this->task['options']['backup_options']['ismerge']=apply_filters('wpvivid_set_backup_ismerge',$this->task['options']['backup_options']['ismerge'],$options);
$this->task['options']['log_file_name']=$id.'_backup';
$log=new WPvivid_Log();
$log->CreateLogFile($this->task['options']['log_file_name'],'no_folder','backup');
//$log->WriteLog(get_home_path(),'test');
$this->task['options']['backup_options']['prefix']=$this->task['options']['file_prefix'];
$this->task['options']['backup_options']['compress']=WPvivid_Setting::get_option('wpvivid_compress_setting');
$this->task['options']['backup_options']['dir']=WPvivid_Setting::get_backupdir();
$this->task['options']['backup_options']['backup']=array();
if(isset($options['backup_files']))
{
if($options['backup_files']=='files+db')
{
$this->set_backup(WPVIVID_BACKUP_TYPE_DB);
$this->set_backup(WPVIVID_BACKUP_TYPE_THEMES);
$this->set_backup(WPVIVID_BACKUP_TYPE_PLUGIN);
$general_setting=WPvivid_Setting::get_setting(true, "");
if(isset($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload']) && !empty($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload'])){
if($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload']){
$this->set_backup(WPVIVID_BACKUP_TYPE_UPLOADS_FILES);
//$this->set_backup(WPVIVID_BACKUP_TYPE_UPLOADS_FILES_OTHER);
}
else{
$this->set_backup(WPVIVID_BACKUP_TYPE_UPLOADS);
}
}
else{
$this->set_backup(WPVIVID_BACKUP_TYPE_UPLOADS);
}
$this->set_backup(WPVIVID_BACKUP_TYPE_CONTENT);
$this->set_backup(WPVIVID_BACKUP_TYPE_CORE);
}
else if($options['backup_files']=='files')
{
$this->set_backup(WPVIVID_BACKUP_TYPE_THEMES);
$this->set_backup(WPVIVID_BACKUP_TYPE_PLUGIN);
$general_setting=WPvivid_Setting::get_setting(true, "");
if(isset($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload']) && !empty($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload'])){
if($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload']){
$this->set_backup(WPVIVID_BACKUP_TYPE_UPLOADS_FILES);
//$this->set_backup(WPVIVID_BACKUP_TYPE_UPLOADS_FILES_OTHER);
}
else{
$this->set_backup(WPVIVID_BACKUP_TYPE_UPLOADS);
}
}
else{
$this->set_backup(WPVIVID_BACKUP_TYPE_UPLOADS);
}
$this->set_backup(WPVIVID_BACKUP_TYPE_CONTENT);
$this->set_backup(WPVIVID_BACKUP_TYPE_CORE);
}
else if($options['backup_files']=='db')
{
$this->set_backup(WPVIVID_BACKUP_TYPE_DB);
}
}
else
{
$this->task['options']['backup_options'] = apply_filters('wpvivid_set_backup_type', $this->task['options']['backup_options'],$options);
}
$this->task['data']['doing']='backup';
$this->task['data']['backup']['doing']='';
$this->task['data']['backup']['finished']=0;
$this->task['data']['backup']['progress']=0;
$this->task['data']['backup']['job_data']=array();
$this->task['data']['backup']['sub_job']=array();
$this->task['data']['backup']['db_size']='0';
$this->task['data']['backup']['files_size']['sum']='0';
$this->task['data']['upload']['doing']='';
$this->task['data']['upload']['finished']=0;
$this->task['data']['upload']['progress']=0;
$this->task['data']['upload']['job_data']=array();
$this->task['data']['upload']['sub_job']=array();
WPvivid_Setting::update_task($id,$this->task);
$ret['result']='success';
$ret['task_id']=$this->task['id'];
$log->CloseFile();
return $ret;
}
protected function parse_url_all($url)
{
$parse = wp_parse_url($url);
//$path=str_replace('/','_',$parse['path']);
$path = '';
if(isset($parse['path'])) {
$parse['path'] = str_replace('/', '_', $parse['path']);
$path = $parse['path'];
}
return $parse['host'].$path;
}
public function set_backup($backup, $task_type='')
{
if(is_string($backup))
{
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
$backup_data['key']=$backup;
$backup_data['result']=false;
$backup_data['compress']=$this->task['options']['backup_options']['compress'];
$backup_data['finished']=0;
$backup_data['path']=WP_CONTENT_DIR.DIRECTORY_SEPARATOR. $this->task['options']['backup_options']['dir'].DIRECTORY_SEPARATOR;
if($backup==WPVIVID_BACKUP_TYPE_DB)
{
//$backup_data['root_path']=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$this->task['options']['backup_options']['dir'];
$backup_data['root_flag']=WPVIVID_BACKUP_ROOT_CUSTOM;
$backup_data['dump_db']=1;
$backup_data['sql_file_name']=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$this->task['options']['backup_options']['dir'].DIRECTORY_SEPARATOR.$this->get_prefix().'_backup_db.sql';
$backup_data['json_info']['dump_db']=1;
$backup_data['json_info']['home_url']=home_url();
$backup_data['json_info']['file_type']='databases';
if(is_multisite())
{
$backup_data['json_info']['is_mu']=1;
}
$backup_data['prefix']=$this->get_prefix().'_backup_db';
}
else if($backup==WPVIVID_BACKUP_TYPE_THEMES)
{
//$backup_data['root_path']=WP_CONTENT_DIR;
$backup_data['root_flag']=WPVIVID_BACKUP_ROOT_WP_CONTENT;
$backup_data['prefix']=$this->get_prefix().'_backup_themes';
$backup_data['files_root']=$this->transfer_path(get_theme_root());
$backup_data['exclude_regex']=array();
$backup_data['include_regex']=array();
$backup_data['json_info']['file_type']='themes';
$backup_data['json_info']['themes']=$this->get_themes_list();
$this->task['options']['backup_options']['backup'][$backup_data['key']]=$backup_data;
}
else if($backup==WPVIVID_BACKUP_TYPE_PLUGIN)
{
//$backup_data['root_path']=WP_CONTENT_DIR;
$backup_data['root_flag']=WPVIVID_BACKUP_ROOT_WP_CONTENT;
$backup_data['prefix']=$this->get_prefix().'_backup_plugin';
if(isset($backup_data['compress']['subpackage_plugin_upload'])&&$backup_data['compress']['subpackage_plugin_upload'])
{
$backup_data['plugin_subpackage']=1;
}
$backup_data['files_root']=$this->transfer_path(WP_PLUGIN_DIR);
$exclude_plugins=array();
$exclude_plugins=apply_filters('wpvivid_exclude_plugins',$exclude_plugins);
$exclude_regex=array();
foreach ($exclude_plugins as $exclude_plugin)
{
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_PLUGIN_DIR.DIRECTORY_SEPARATOR.$exclude_plugin), '/').'#';
}
$backup_data['exclude_regex']=$exclude_regex;
$backup_data['include_regex']=array();
$backup_data['json_info']['file_type']='plugin';
$backup_data['json_info']['plugin']=$this->get_plugins_list();
}
else if($backup==WPVIVID_BACKUP_TYPE_UPLOADS)
{
//$backup_data['root_path']=WP_CONTENT_DIR;
$backup_data['root_flag']=WPVIVID_BACKUP_ROOT_WP_CONTENT;
$backup_data['prefix']=$this->get_prefix().'_backup_uploads';
$upload_dir = wp_upload_dir();
$backup_data['files_root']=$this -> transfer_path($upload_dir['basedir']);
$exclude_regex=array();
$exclude_regex=apply_filters('wpvivid_get_backup_exclude_regex',$exclude_regex,WPVIVID_BACKUP_TYPE_UPLOADS);
$backup_data['exclude_regex']=$exclude_regex;
$backup_data['include_regex']=array();
$backup_data['json_info']['file_type']='upload';
}
else if($backup==WPVIVID_BACKUP_TYPE_UPLOADS_FILES)
{
//$backup_data['root_path']=WP_CONTENT_DIR;
$backup_data['root_flag']=WPVIVID_BACKUP_ROOT_WP_CONTENT;
$backup_data['prefix']=$this->get_prefix().'_backup_uploads';
$backup_data['uploads_subpackage']=1;
$upload_dir = wp_upload_dir();
$backup_data['files_root']=$this -> transfer_path($upload_dir['basedir']);
$exclude_regex=array();
$exclude_regex=apply_filters('wpvivid_get_backup_exclude_regex',$exclude_regex,WPVIVID_BACKUP_TYPE_UPLOADS_FILES);
$backup_data['include_regex']=array();
$backup_data['exclude_regex']=$exclude_regex;
//$backup_data['include_regex'][]='#^'.preg_quote($this -> transfer_path($upload_dir['basedir']).DIRECTORY_SEPARATOR, '/').'[0-9]{4}#';
$backup_data['json_info']['file_type']='upload';
}
else if($backup==WPVIVID_BACKUP_TYPE_CONTENT)
{
//$backup_data['root_path']=get_home_path();
$backup_data['root_flag']=WPVIVID_BACKUP_ROOT_WP_ROOT;
$backup_data['prefix']=$this->get_prefix().'_backup_content';
$backup_data['files_root']=$this -> transfer_path(WP_CONTENT_DIR);
$exclude_regex=array();
$exclude_regex=apply_filters('wpvivid_get_backup_exclude_regex',$exclude_regex,WPVIVID_BACKUP_TYPE_CONTENT);
$backup_data['exclude_regex']=$exclude_regex;
$backup_data['include_regex']=array();
$backup_data['json_info']['file_type']='wp-content';
}
else if($backup==WPVIVID_BACKUP_TYPE_CORE)
{
//$backup_data['root_path']=ABSPATH;
$backup_data['root_flag']=WPVIVID_BACKUP_ROOT_WP_ROOT;
$backup_data['prefix']=$this->get_prefix().'_backup_core';
$backup_data['files_root']=$this -> transfer_path(ABSPATH);
$backup_data['json_info']['include_path'][]='wp-includes';
$backup_data['json_info']['include_path'][]='wp-admin';
$backup_data['json_info']['wp_core']=1;
$backup_data['json_info']['home_url']=home_url();
$include_regex[]='#^'.preg_quote($this -> transfer_path(ABSPATH.DIRECTORY_SEPARATOR.'wp-admin'), '/').'#';
$include_regex[]='#^'.preg_quote($this->transfer_path(ABSPATH.DIRECTORY_SEPARATOR.'wp-includes'), '/').'#';
$exclude_regex[]='#^'.preg_quote($this->transfer_path(ABSPATH.DIRECTORY_SEPARATOR.'wp-admin'.DIRECTORY_SEPARATOR), '/').'pclzip-.*\.tmp#';
$exclude_regex[]='#^'.preg_quote($this->transfer_path(ABSPATH.DIRECTORY_SEPARATOR.'wp-admin'.DIRECTORY_SEPARATOR), '/').'pclzip-.*\.gz#';
$exclude_regex[]='#session_mm_cgi-fcgi#';
$exclude_regex=apply_filters('wpvivid_get_backup_exclude_regex',$exclude_regex,WPVIVID_BACKUP_TYPE_CORE);
$backup_data['exclude_regex']=$exclude_regex;
$backup_data['include_regex']=$include_regex;
$backup_data['json_info']['file_type']='wp-core';
}
else if($backup==WPVIVID_BACKUP_TYPE_MERGE)
{
//$backup_data['root_path']=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$this->task['options']['backup_options']['dir'];
$backup_data['root_flag']=WPVIVID_BACKUP_ROOT_CUSTOM;
$file_name = $this->get_prefix().'_backup_all';
$file_name = apply_filters('wpvivid_set_incremental_backup_file_name', $file_name, $this->get_prefix(), $task_type);
$backup_data['prefix']=$file_name;
$backup_data['files']=array();
$backup_data['json_info']['has_child']=1;
foreach ($this->task['options']['backup_options']['backup'] as $backup_finished_data)
{
$backup_data['files']=array_merge($backup_data['files'],$this->get_backup_file($backup_finished_data['key']));
}
$backup_data['json_info']['home_url']=home_url();
}
else
{
$backup_data=false;
}
if($backup_data!==false)
{
$backup_data=apply_filters('wpvivid_set_backup',$backup_data);
$this->task['options']['backup_options']['backup'][$backup_data['key']]=$backup_data;
}
}
}
public function get_themes_list()
{
$themes_list=array();
$list=wp_get_themes();
foreach ($list as $key=>$item)
{
$themes_list[$key]['slug']=$key;
$themes_list[$key]['size']=$this->get_folder_size(get_theme_root().DIRECTORY_SEPARATOR.$key,0);
}
return $themes_list;
}
public function get_plugins_list()
{
$plugins_list=array();
if(!function_exists('get_plugins'))
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
$list=get_plugins();
$exclude_plugins[]='wpvivid-backuprestore';
$exclude_plugins[]='wp-cerber';
$exclude_plugins[]='.';
$exclude_plugins=apply_filters('wpvivid_exclude_plugins',$exclude_plugins);
foreach ($list as $key=>$item)
{
if(in_array(dirname($key),$exclude_plugins))
{
continue;
}
$plugins_list[dirname($key)]['slug']=dirname($key);
$plugins_list[dirname($key)]['size']=$this->get_folder_size(WP_PLUGIN_DIR.DIRECTORY_SEPARATOR.dirname($key),0);
//
}
return $plugins_list;
}
public function get_folder_size($root,$size)
{
$count = 0;
if(is_dir($root))
{
$handler = opendir($root);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..") {
$count++;
if (is_dir($root . DIRECTORY_SEPARATOR . $filename))
{
$size=$this->get_folder_size($root . DIRECTORY_SEPARATOR . $filename,$size);
} else {
$size+=filesize($root . DIRECTORY_SEPARATOR . $filename);
}
}
}
if($handler)
@closedir($handler);
}
}
return $size;
}
public function wpvivid_set_backup($backup_data)
{
if(isset($backup_data['uploads_subpackage'])||isset($backup_data['plugin_subpackage']))
{
$backup_data['resume_packages'] = 1;
}
else if($backup_data['key']==WPVIVID_BACKUP_TYPE_MERGE)
{
$backup_data['resume_packages'] = 1;
}
return $backup_data;
}
public function get_need_backup_files($backup_data)
{
if(isset($backup_data['uploads_subpackage']))
{
return $backup_data['files']=$this->get_need_uploads_backup_folder($backup_data);
}
if(isset($backup_data['plugin_subpackage']))
{
return $backup_data['files']=$this->get_need_backup_folder($backup_data);
}
if(isset($backup_data['files'])&&!empty($backup_data['files']))
{
return $backup_data['files'];
}
else
{
return $this->get_file_list($backup_data['files_root'],$backup_data['exclude_regex'],$backup_data['include_regex'],$this->task['options']['backup_options']['compress']['exclude_file_size']);
}
}
public function get_backup_file($key)
{
$files=array();
if(array_key_exists($key,$this->task['options']['backup_options']['backup']))
{
$backup=$this->task['options']['backup_options']['backup'][$key];
if($backup['finished'])
{
if($backup['result']!=false)
{
foreach ($backup['result']['files'] as $file_data)
{
$files[]=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$this->task['options']['backup_options']['dir'].DIRECTORY_SEPARATOR.$file_data['file_name'];
}
}
}
}
return $files;
}
public function get_need_backup()
{
$this->task=WPvivid_taskmanager::get_task($this->task['id']);
$backup=false;
$i_finished_backup_count=0;
$i_count_of_backup=sizeof($this->task['options']['backup_options']['backup']);
foreach ($this->task['options']['backup_options']['backup'] as $key=>$backup_data)
{
if($backup_data['result']!==false)
{
$ret=$backup_data['result'];
if($ret['result']!==WPVIVID_SUCCESS)
{
return false;
}
}
if( $backup_data['finished']==0)
{
if($backup===false)
{
add_filter('wpvivid_get_need_backup_files', array($this, 'wpvivid_get_need_backup_files'),10);
$backup_data=apply_filters('wpvivid_get_need_backup_files',$backup_data);
$backup=$backup_data;
}
}
else {
$i_finished_backup_count++;
}
}
if($i_count_of_backup>0)
{
$i_progress=intval(1/$i_count_of_backup*100);
WPvivid_taskmanager::update_backup_main_task_progress($this->task['id'],'backup',$i_progress*$i_finished_backup_count,0);
if($i_finished_backup_count>=$i_count_of_backup)
{
if($this->task['options']['backup_options']['ismerge']==1)
{
if(!array_key_exists(WPVIVID_BACKUP_TYPE_MERGE,$this->task['options']['backup_options']['backup']))
{
$this->set_backup(WPVIVID_BACKUP_TYPE_MERGE, $this->task['type']);
WPvivid_Setting::update_task($this->task['id'],$this->task);
$backup=$this->task['options']['backup_options']['backup'][WPVIVID_BACKUP_TYPE_MERGE];
}
}
}
}
return $backup;
}
public function get_need_backup_files_size($backup_data)
{
if(isset($backup_data['files'])&&!empty($backup_data['files']))
{
return $backup_data['files'];
}
else
{
return $this->get_file_list($backup_data['files_root'],$backup_data['exclude_regex'],$backup_data['include_regex'],$this->task['options']['backup_options']['compress']['exclude_file_size']);
}
}
public function wpvivid_get_need_backup_files($backup_data)
{
if(!isset($backup_data['dump_db']))
{
if(array_key_exists($backup_data['key'],$this->backup_type_collect))
{
$backup_data['files'] = $this->get_need_backup_files($backup_data);
}
else
{
if(!isset($backup_data['files']))
{
$backup_data['files']=array();
}
$backup_data['files'] =apply_filters('wpvivid_get_custom_need_backup_files', $backup_data['files'],$backup_data,$this->task['options']['backup_options']['compress']);
}
$need=false;
add_filter('wpvivid_need_backup_files_update', array($this, 'need_backup_files_update'), 10, 2);
if(apply_filters('wpvivid_need_backup_files_update',$need,$backup_data))
{
$this->task['options']['backup_options']['backup'][$backup_data['key']]=$backup_data;
WPvivid_Setting::update_task($this->task['id'],$this->task);
}
}
return $backup_data;
}
public function need_backup_files_update($need,$backup_data)
{
if(isset($backup_data['uploads_subpackage'])||isset($backup_data['plugin_subpackage']))
{
return true;
}
else
{
return $need;
}
}
public function update_backup_result($backup_data,$result)
{
$this->task=WPvivid_taskmanager::get_task($this->task['id']);
if(array_key_exists($backup_data['key'],$this->task['options']['backup_options']['backup']))
{
$this->task['options']['backup_options']['backup'][$backup_data['key']]['finished']=1;
add_filter('wpvivid_backup_update_result', array($this, 'wpvivid_backup_update_result'),10,2);
$result=apply_filters('wpvivid_backup_update_result',$result,$backup_data);
$this->task['options']['backup_options']['backup'][$backup_data['key']]['result']=$result;
WPvivid_taskmanager::update_task_options($this->task['id'],'backup_options', $this->task['options']['backup_options']);
if($result['result']==WPVIVID_FAILED)
{
WPvivid_taskmanager::update_backup_task_status($this->task['id'],false,'error',false,false,$result['error']);
return ;
}
}
$i_finished_backup_count=0;
$i_count_of_backup=sizeof($this->task['options']['backup_options']['backup']);
foreach ($this->task['options']['backup_options']['backup'] as $backup_data)
{
if( $backup_data['finished']==1)
{
$i_finished_backup_count++;
}
}
if($i_finished_backup_count>=$i_count_of_backup)
{
WPvivid_taskmanager::update_backup_main_task_progress($this->task['id'],'backup',100,1);
}
//WPvivid_Setting::update_task($this->task['id'],$this->task);
}
public function wpvivid_backup_update_result($result,$backup_data)
{
if($result['result']==WPVIVID_SUCCESS)
{
$exist_files_name=array();
foreach ($result['files'] as $temp_file_data)
{
$exist_files_name[$temp_file_data['file_name']]=$temp_file_data['file_name'];
}
if(isset($backup_data['resume_packages'])&&$backup_data['resume_packages'])
{
$packages_files_info = $this->get_packages_files_info($backup_data['key']);
if ($packages_files_info !== false)
{
foreach ($packages_files_info as $file_data)
{
if(!array_key_exists($file_data['file_name'],$exist_files_name))
{
$result['files'][]=$file_data;
}
}
}
}
}
return $result;
}
public function get_backup_result()
{
$ret['result']=WPVIVID_SUCCESS;
$ret['files']=array();
foreach ($this->task['options']['backup_options']['backup'] as $backup_data)
{
if($this->task['options']['backup_options']['ismerge']==1)
{
if(WPVIVID_BACKUP_TYPE_MERGE==$backup_data['key'])
{
$ret=$backup_data['result'];
if($ret['result']!==WPVIVID_SUCCESS)
{
return $ret;
}
}
}
else
{
$ret['files']=array_merge($ret['files'],$backup_data['result']['files']);
}
}
return $ret;
}
private function transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode(DIRECTORY_SEPARATOR,$values);
}
public function get_file_list($root,$exclude_regex,$include_regex,$exclude_file_size)
{
$files=array();
$this->getFileLoop($files,$root,$exclude_regex,$include_regex,$exclude_file_size);
return $files;
}
public function getFileLoop(&$files,$path,$exclude_regex=array(),$include_regex=array(),$exclude_file_size=0,$include_dir = true)
{
$count = 0;
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..") {
$count++;
if (is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
if ($this->regex_match($exclude_regex, $path . DIRECTORY_SEPARATOR . $filename, 0)) {
if ($this->regex_match($include_regex, $path . DIRECTORY_SEPARATOR . $filename, 1)) {
$this->getFileLoop($files, $path . DIRECTORY_SEPARATOR . $filename, $exclude_regex, $include_regex, $exclude_file_size, $include_dir);
}
}
} else {
if($this->regex_match($exclude_regex, $path . DIRECTORY_SEPARATOR . $filename, 0)){
if ($exclude_file_size == 0)
{
if(is_readable($path . DIRECTORY_SEPARATOR . $filename))
{
$files[] = $path . DIRECTORY_SEPARATOR . $filename;
}
} else {
if(is_readable($path . DIRECTORY_SEPARATOR . $filename))
{
if (filesize($path . DIRECTORY_SEPARATOR . $filename) < $exclude_file_size * 1024 * 1024) {
$files[] = $path . DIRECTORY_SEPARATOR . $filename;
}
}
}
}
}
}
}
if($handler)
@closedir($handler);
}
}
if($include_dir && $count == 0){
$files[] = $path;
}
}
private function regex_match($regex_array,$string,$mode)
{
if(empty($regex_array))
{
return true;
}
if($mode==0)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return false;
}
}
return true;
}
if($mode==1)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return true;
}
}
return false;
}
return true;
}
public function get_need_cleanup_files($all=false)
{
$files=array();
if($this->task['options']['backup_options']['ismerge']==1)
{
foreach ($this->task['options']['backup_options']['backup'] as $backup_finished_data)
{
if($all===false)
{
if(WPVIVID_BACKUP_TYPE_MERGE==$backup_finished_data['key'])
continue;
}
$files=array_merge($files,$this->get_backup_file($backup_finished_data['key']));
add_filter('wpvivid_get_need_cleanup_files', array($this, 'wpvivid_get_need_cleanup_files'),10,2);
$files=apply_filters('wpvivid_get_need_cleanup_files',$files,$backup_finished_data);
}
}
return $files;
}
public function wpvivid_get_need_cleanup_files($files,$backup_finished_data)
{
if(WPVIVID_BACKUP_TYPE_PLUGIN==$backup_finished_data['key'])
{
$general_setting=WPvivid_Setting::get_setting(true, "");
if(isset($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload']) && !empty($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload'])){
if($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload']){
$packages_files_info = $this->get_packages_files_info(WPVIVID_BACKUP_TYPE_PLUGIN);
if ($packages_files_info !== false) {
foreach ($packages_files_info as $file_data) {
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $this->task['options']['backup_options']['dir'] . DIRECTORY_SEPARATOR . $file_data['file_name'];
if (!in_array($path, $files))
$files[] = $path;
}
}
}
}
}
else if(WPVIVID_BACKUP_TYPE_UPLOADS_FILES==$backup_finished_data['key'])
{
$general_setting=WPvivid_Setting::get_setting(true, "");
if(isset($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload']) && !empty($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload'])){
if($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload']){
$packages_files_info = $this->get_packages_files_info(WPVIVID_BACKUP_TYPE_UPLOADS_FILES);
if ($packages_files_info !== false) {
foreach ($packages_files_info as $file_data) {
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $this->task['options']['backup_options']['dir'] . DIRECTORY_SEPARATOR . $file_data['file_name'];
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('test:' . $path, 'notice');
if (!in_array($path, $files))
$files[] = $path;
}
}
}
}
}
return $files;
}
public function get_prefix()
{
return $this->task['options']['backup_options']['prefix'];
}
public function set_file_and_db_info($db_size,$file_size)
{
$this->task['data']['backup']['db_size']=$db_size;
$this->task['data']['backup']['files_size']=$file_size;
WPvivid_Setting::update_task($this->task['id'],$this->task);
}
public function get_file_info()
{
$file_size['sum_size']=0;
$file_size['sum_count']=0;
$memory_limit = ini_get('memory_limit');
$ret['memory_limit']=$memory_limit;
$memory_limit = trim($memory_limit);
$memory_limit_int = (int) $memory_limit;
$last = strtolower(substr($memory_limit, -1));
if($last == 'g')
$memory_limit_int = $memory_limit_int*1024*1024*1024;
if($last == 'm')
$memory_limit_int = $memory_limit_int*1024*1024;
if($last == 'k')
$memory_limit_int = $memory_limit_int*1024;
$files=array();
foreach ($this->task['options']['backup_options']['backup'] as $backup_data)
{
if(!isset($backup_data['dump_db']))
{
if(array_key_exists($backup_data['key'],$this->backup_type_collect))
{
$backup_files = $this->get_need_backup_files_size($backup_data);
}
else
{
$backup_data['files']=array();
$backup_files =apply_filters('wpvivid_get_custom_need_backup_files_size', $backup_data['files'],$backup_data,$this->task['options']['backup_options']['compress']);
}
$files=array_merge($backup_files,$files);
}
}
foreach ($files as $file)
{
$size=0;
$_file_size=filesize($file);
if($_file_size>($memory_limit_int*0.9))
{
$ret['alter_big_file']=true;
$ret['alter_files']=true;
}
$size+=$_file_size;
$file_size['sum_count']++;
$file_size['sum_size']+=$size;
}
return $file_size;
}
public function is_cancel_file_exist()
{
$file_name=$this->task['options']['file_prefix'];
$file=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$this->task['options']['backup_options']['dir'].DIRECTORY_SEPARATOR.$file_name.'_cancel';
if(file_exists($file))
{
return true;
}
else
{
return false;
}
}
public function update_status($status)
{
$this->task['status']['str']=$status;
WPvivid_Setting::update_task($this->task['id'],$this->task);
}
public function get_backup_task_info($task_id){
$list_tasks['status']=WPvivid_taskmanager::get_backup_tasks_status($task_id);
$list_tasks['is_canceled']=WPvivid_taskmanager::is_task_canceled($task_id);
$list_tasks['size']=WPvivid_taskmanager::get_backup_size($task_id);
$list_tasks['data']=WPvivid_taskmanager::get_backup_tasks_progress($task_id);
//
$list_tasks['task_info']['need_next_schedule']=false;
if($list_tasks['status']['str']=='running'||$list_tasks['status']['str']=='no_responds')
{
if($list_tasks['data']['running_stamp']>180) {
$list_tasks['task_info']['need_next_schedule'] = true;
}
else{
$list_tasks['task_info']['need_next_schedule'] = false;
}
}
//
$general_setting=WPvivid_Setting::get_setting(true, "");
if($general_setting['options']['wpvivid_common_setting']['estimate_backup'] == 0){
$list_tasks['task_info']['display_estimate_backup'] = 'display: none';
}
else{
$list_tasks['task_info']['display_estimate_backup'] = '';
}
//
$list_tasks['task_info']['backup_percent']=$list_tasks['data']['progress'].'%';
//
if($list_tasks['size']['db_size'] == false){
$list_tasks['task_info']['db_size']=0;
}
else{
$list_tasks['task_info']['db_size']=$list_tasks['size']['db_size'];
}
if($list_tasks['size']['files_size'] == false){
$list_tasks['task_info']['file_size']=0;
}
else{
$list_tasks['task_info']['file_size']=$list_tasks['size']['files_size']['sum'];
}
//
$list_tasks['task_info']['descript']='';
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['total'] = 'N/A';
$list_tasks['task_info']['upload'] = 'N/A';
$list_tasks['task_info']['speed'] = 'N/A';
$list_tasks['task_info']['network_connection'] = 'N/A';
$list_tasks['task_info']['need_update_last_task']=false;
if($list_tasks['status']['str']=='ready')
{
$list_tasks['task_info']['descript']=__('Ready to backup. Progress: 0%, running time: 0second.','wpvivid-backuprestore');
$list_tasks['task_info']['css_btn_cancel']='pointer-events: none; opacity: 0.4;';
$list_tasks['task_info']['css_btn_log']='pointer-events: none; opacity: 0.4;';
}
else if($list_tasks['status']['str']=='running')
{
if($list_tasks['is_canceled'] == false)
{
if($list_tasks['data']['type'] == 'upload')
{
if(isset($list_tasks['data']['upload_data']) && !empty($list_tasks['data']['upload_data'])) {
$descript = $list_tasks['data']['upload_data']['descript'];
$offset = $list_tasks['data']['upload_data']['offset'];
$current_size = $list_tasks['data']['upload_data']['current_size'];
$last_time = $list_tasks['data']['upload_data']['last_time'];
$last_size = $list_tasks['data']['upload_data']['last_size'];
$speed = ($offset - $last_size) / (time() - $last_time);
$speed /= 1000;
$speed = round($speed, 2);
$speed .= 'kb/s';
if(!empty($current_size)) {
$list_tasks['task_info']['total'] = size_format($current_size,2);
}
if(!empty($offset)) {
$list_tasks['task_info']['upload'] = size_format($offset, 2);
}
}
else{
$descript = 'Start uploading.';
$speed = '0kb/s';
$list_tasks['task_info']['total'] = 'N/A';
$list_tasks['task_info']['upload'] = 'N/A';
}
$list_tasks['task_info']['speed'] = $speed;
$list_tasks['task_info']['descript'] = $descript.' '.__('Progress: ', 'wpvivid-backuprestore') . $list_tasks['task_info']['backup_percent'] . ', ' . __('running time: ', 'wpvivid-backuprestore') . $list_tasks['data']['running_time'];
$time_spend=time()-$list_tasks['status']['run_time'];
if($time_spend>30)
{
$list_tasks['task_info']['network_connection']='Retrying';
}
else
{
$list_tasks['task_info']['network_connection']='OK';
}
}
else {
$list_tasks['task_info']['descript'] = $list_tasks['data']['descript'] . ' '. __('Progress: ', 'wpvivid-backuprestore') . $list_tasks['task_info']['backup_percent'] . ', '. __('running time: ', 'wpvivid-backuprestore') . $list_tasks['data']['running_time'];
}
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
}
else{
$list_tasks['task_info']['descript']=__('The backup will be canceled after backing up the current chunk ends.','wpvivid-backuprestore');
$list_tasks['task_info']['css_btn_cancel']='pointer-events: none; opacity: 0.4;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
}
}
else if($list_tasks['status']['str']=='wait_resume'){
$list_tasks['task_info']['descript']='Task '.$task_id.' timed out, backup task will retry in '.$list_tasks['data']['next_resume_time'].' seconds, retry times: '.$list_tasks['status']['resume_count'].'.';
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
}
else if($list_tasks['status']['str']=='no_responds'){
if($list_tasks['is_canceled'] == false){
$list_tasks['task_info']['descript']='Task , '.$list_tasks['data']['doing'].' is not responding. Progress: '.$list_tasks['task_info']['backup_percent'].', running time: '.$list_tasks['data']['running_time'];
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
}
else{
$list_tasks['task_info']['descript']=__('The backup will be canceled after backing up the current chunk ends.','wpvivid-backuprestore');
$list_tasks['task_info']['css_btn_cancel']='pointer-events: none; opacity: 0.4;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
}
}
else if($list_tasks['status']['str']=='completed'){
$list_tasks['task_info']['descript']='Task '.$task_id.' completed.';
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['need_update_last_task']=true;
}
else if($list_tasks['status']['str']=='error'){
$list_tasks['task_info']['descript']='Backup error: '.$list_tasks['status']['error'];
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['need_update_last_task']=true;
}
return $list_tasks;
}
public function get_packages_info($key)
{
if(isset($this->task['data']['backup']['sub_job'][$key]))
{
if(empty($this->task['data']['backup']['sub_job'][$key]['job_data']))
{
return false;
}
else
{
$packages=array();
foreach ($this->task['data']['backup']['sub_job'][$key]['job_data'] as $key=>$package)
{
if($key=='files')
{
continue;
}
$packages[]=$package;
}
if(empty($packages))
{
return false;
}
else
{
return $packages;
}
}
}
else
{
return false;
}
}
public function get_packages_files_info($key)
{
if(isset($this->task['data']['backup']['sub_job'][$key]))
{
if(empty($this->task['data']['backup']['sub_job'][$key]['job_data']))
{
return false;
}
else
{
if(isset($this->task['data']['backup']['sub_job'][$key]['job_data']['files']))
{
return $this->task['data']['backup']['sub_job'][$key]['job_data']['files'];
}
else
{
return false;
}
}
}
else
{
return false;
}
}
public function set_packages_info($key,$packages)
{
$this->task=WPvivid_taskmanager::get_task($this->task['id']);
$job_data=array();
foreach ($packages as $package)
{
$package['backup']=false;
$job_data[basename($package['path'])]=$package;
}
$this->task['data']['backup']['sub_job'][$key]['job_data']=$job_data;
WPvivid_Setting::update_task($this->task['id'],$this->task);
return $job_data;
}
public function update_packages_info($key,$package,$file_data=false)
{
$this->task=WPvivid_taskmanager::get_task($this->task['id']);
$this->task['data']['backup']['sub_job'][$key]['job_data'][basename($package['path'])]=$package;
if($file_data!==false)
{
$this->task['data']['backup']['sub_job'][$key]['job_data']['files'][]=$file_data;
}
WPvivid_Setting::update_task($this->task['id'],$this->task);
}
public function update_sub_task_progress($key,$finished,$progress)
{
$this->task=WPvivid_taskmanager::get_task($this->task['id']);
$this->task['status']['run_time']=time();
$this->task['status']['str']='running';
$this->task['data']['doing']='backup';
$sub_job_name=$key;
$this->task['data']['backup']['doing']=$key;
$this->task['data']['backup']['sub_job'][$sub_job_name]['finished']=$finished;
$this->task['data']['backup']['sub_job'][$sub_job_name]['progress']=$progress;
if(!isset( $this->task['data']['backup']['sub_job'][$sub_job_name]['job_data']))
{
$this->task['data']['backup']['sub_job'][$sub_job_name]['job_data']=array();
}
WPvivid_Setting::update_task($this->task['id'],$this->task);
}
public function get_need_backup_folder($backup_data)
{
if(isset($backup_data['files'])&&empty($backup_data['files']))
{
return $backup_data['files'];
}
else
{
return $this->get_folder_list($backup_data['files_root'],$backup_data['exclude_regex'],$backup_data['include_regex'],$this->task['options']['backup_options']['compress']['exclude_file_size']);
}
}
public function get_folder_list($root,$exclude_regex,$include_regex,$exclude_file_size)
{
$files=array();
$this->getFolder($files,$root,$exclude_regex,$include_regex,$exclude_file_size);
return $files;
}
public function getFolder(&$files,$path,$exclude_regex=array(),$include_regex=array(),$exclude_file_size=0,$include_dir = true)
{
$count = 0;
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
$count++;
if (is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
if ($this->regex_match($exclude_regex, $path . DIRECTORY_SEPARATOR . $filename, 0))
{
if ($this->regex_match($include_regex, $path . DIRECTORY_SEPARATOR . $filename, 1))
{
$files[] = $path . DIRECTORY_SEPARATOR . $filename;
}
}
} else {
if($this->regex_match($exclude_regex, $path . DIRECTORY_SEPARATOR . $filename, 0)){
if ($exclude_file_size == 0)
{
if(is_readable($path . DIRECTORY_SEPARATOR . $filename))
{
$files[] = $path . DIRECTORY_SEPARATOR . $filename;
}
} else {
if(is_readable($path . DIRECTORY_SEPARATOR . $filename))
{
if (filesize($path . DIRECTORY_SEPARATOR . $filename) < $exclude_file_size * 1024 * 1024)
{
$files[] = $path . DIRECTORY_SEPARATOR . $filename;
}
}
}
}
}
}
}
if($handler)
@closedir($handler);
}
}
if($include_dir && $count == 0)
{
$files[] = $path;
}
}
public function get_need_uploads_backup_folder($backup_data)
{
if(isset($backup_data['files'])&&empty($backup_data['files']))
{
return $backup_data['files'];
}
else
{
return $this->get_uploads_folder_list($backup_data['files_root'],$backup_data['exclude_regex'],$backup_data['include_regex'],$this->task['options']['backup_options']['compress']['exclude_file_size']);
}
}
public function get_uploads_folder_list($root,$exclude_regex,$include_regex,$exclude_file_size)
{
$files=array();
$files[] = $root;
$this->getUploadsFolder($files,$root,$exclude_regex,$include_regex,$exclude_file_size);
return $files;
}
public function getUploadsFolder(&$files,$path,$exclude_regex=array(),$include_regex=array(),$exclude_file_size=array(),$include_dir = true)
{
$count = 0;
if(is_dir($path))
{
$handler = opendir($path);
if($handler===false)
return;
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
$count++;
if (is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
if ($this->regex_match($exclude_regex, $path . DIRECTORY_SEPARATOR . $filename, 0))
{
if ($this->regex_match($include_regex, $path . DIRECTORY_SEPARATOR . $filename, 1))
{
$this->getUploadsFolder($files,$path . DIRECTORY_SEPARATOR . $filename,$exclude_regex,$include_regex,$exclude_file_size,$include_dir);
}
}
}
}
}
if($handler)
@closedir($handler);
}
if($include_dir && $count == 0)
{
$files[] = $path;
}
}
public function add_new_backup()
{
$this->task=WPvivid_taskmanager::get_task($this->task['id']);
$backup_data=array();
$backup_data['type']=$this->task['type'];
$status=WPvivid_taskmanager::get_backup_task_status($this->task['id']);
$backup_data['create_time']=$status['start_time'];
$backup_data['manual_delete']=0;
$backup_options=WPvivid_taskmanager::get_task_options($this->task['id'],'backup_options');
$lock=WPvivid_taskmanager::get_task_options($this->task['id'],'lock');
$backup_data['local']['path']=$backup_options['dir'];
$backup_data['compress']['compress_type']=$backup_options['compress']['compress_type'];
$backup_data['save_local']=$this->task['options']['save_local'];
if(isset($this->task['options']['backup_prefix']))
{
$backup_data['backup_prefix'] = $this->task['options']['backup_prefix'];
}
global $wpvivid_plugin;
$backup_data['log']=$wpvivid_plugin->wpvivid_log->log_file;
$backup_data['backup']=$this->get_backup_result();
$backup_data['remote']=array();
if($lock==1)
$backup_data['lock']=1;
$backup_list='wpvivid_backup_list';
$backup_list=apply_filters('get_wpvivid_backup_list_name',$backup_list,$this->task['id']);
$list = WPvivid_Setting::get_option($backup_list);
$list[$this->task['id']]=$backup_data;
WPvivid_Setting::update_option($backup_list,$list);
}
public function get_backup_files()
{
$files=array();
foreach ($this->task['options']['backup_options']['backup'] as $backup_data)
{
if($this->task['options']['backup_options']['ismerge']==1)
{
if(WPVIVID_BACKUP_TYPE_MERGE==$backup_data['key'])
{
if($backup_data['result']!==false)
{
$ret=$backup_data['result'];
if($ret['result']===WPVIVID_SUCCESS)
{
foreach ($ret['files'] as $file)
{
$files[]=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$this->task['options']['backup_options']['dir'].DIRECTORY_SEPARATOR.$file['file_name'];
}
}
}
}
}
else
{
if($backup_data['result']!==false)
{
$ret=$backup_data['result'];
if($ret['result']===WPVIVID_SUCCESS)
{
foreach ($ret['files'] as $file)
{
$files[]=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$this->task['options']['backup_options']['dir'].DIRECTORY_SEPARATOR.$file['file_name'];
}
}
}
}
}
return $files;
}
}
class WPvivid_Backup_Item
{
private $config;
public function __construct($options)
{
$this->config=$options;
}
public function get_backup_type()
{
return $this->config['type'];
}
public function get_backup_path($file_name)
{
$path = $this->get_local_path() . $file_name;
if (file_exists($path)) {
return $path;
}
else{
$local_setting = get_option('wpvivid_local_setting', array());
if(!empty($local_setting))
{
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $local_setting['path'] . DIRECTORY_SEPARATOR . $file_name;
}
else {
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'wpvividbackups' . DIRECTORY_SEPARATOR . $file_name;
}
}
return $path;
}
public function get_files($has_dir=true)
{
global $wpvivid_plugin;
$files=array();
if(isset($this->config['backup']['files']))
{
//file_name
foreach ($this->config['backup']['files'] as $file)
{
if($has_dir)
$files[]=$this->get_backup_path($file['file_name']);//$this->get_local_path().$file['file_name'];
else
$files[]=$file['file_name'];
}
}
else{
if(isset($this->config['backup']['data']['meta']['files']))
{
foreach ($this->config['backup']['data']['meta']['files'] as $file)
{
if($has_dir)
$files[]=$this->get_backup_path($file['file_name']);//$this->get_local_path().$file['file_name'];
else
$files[]=$file['file_name'];
}
}
}
return $files;
}
public function is_lock()
{
if(isset($this->config['lock']))
{
return $this->config['lock'];
}
else{
return false;
}
}
public function check_backup_files()
{
global $wpvivid_plugin;
$b_has_data=false;
$tmp_data=array();
if(isset($this->config['backup']['files']))
{
$b_has_data = true;
$tmp_data = $this->config['backup']['files'];
}
else if(isset($this->config['backup']['data']['meta']['files'])){
$b_has_data = true;
$tmp_data = $this->config['backup']['data']['meta']['files'];
}
if($b_has_data)
{
$b_need_download=false;
$b_not_found=false;
$b_test=false;
foreach ($tmp_data as $file)
{
$need_download=false;
$path=$this->get_backup_path($file['file_name']);//$this->get_local_path().$file['file_name'];
if(file_exists($path))
{
if(filesize($path) == $file['size'])
{
if($wpvivid_plugin->wpvivid_check_zip_valid())
{
$res = TRUE;
}
else{
$res = FALSE;
}
}
else {
$res = FALSE;
}
if ($res !== TRUE)
{
$need_download=true;
}
}
else
{
$b_test=true;
$need_download=true;
}
if($need_download)
{
if(empty($this->config['remote']))
{
$b_not_found=true;
$ret['files'][$file['file_name']]['status']='file_not_found';
$ret['files'][$file['file_name']]['size']=$file['size'];
//$ret['files'][$file['file_name']]['md5']=$file['md5'];
}
else
{
$b_need_download=true;
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
$ret['files'][$file['file_name']]['status']='need_download';
$ret['files'][$file['file_name']]['size']=$file['size'];
//$ret['files'][$file['file_name']]['md5']=$file['md5'];
}
}
}
if($b_not_found)
{
$ret['result']=WPVIVID_FAILED;
if($b_test)
$ret['error']='Backup files doesn\'t exist. Restore failed.';
else
$ret['error']='Backup doesn\'t exist in both web server and remote storage. Restore failed.';
}
else if($b_need_download)
{
$ret['result']='need_download';
}
else
{
$ret['result']=WPVIVID_SUCCESS;
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='Unknown error.';
}
return $ret;
}
public function check_migrate_file()
{
if(isset($this->config['backup']['files']))
{
$tmp_data = $this->config['backup']['files'];
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
foreach ($tmp_data as $file)
{
$path=$this->get_backup_path($file['file_name']);//$this->get_local_path().$file['file_name'];
if(file_exists($path))
{
$ret=$zip->get_json_data($path);
if($ret['result'] === WPVIVID_SUCCESS) {
$json=$ret['json_data'];
$json = json_decode($json, 1);
if (!is_null($json)) {
if (isset($json['home_url']) && home_url() != $json['home_url']) {
return 1;
}
}
else{
return 0;
}
}
elseif($ret['result'] === WPVIVID_FAILED){
return 0;
}
}
}
return 0;
}
else
{
return 0;
}
}
public function is_display_migrate_option(){
if(isset($this->config['backup']['files']))
{
$tmp_data = $this->config['backup']['files'];
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
foreach ($tmp_data as $file)
{
$path=$this->get_backup_path($file['file_name']);//$this->get_local_path().$file['file_name'];
if(file_exists($path))
{
$ret=$zip->get_json_data($path);
if($ret['result'] === WPVIVID_SUCCESS) {
$json=$ret['json_data'];
$json = json_decode($json, 1);
if (!is_null($json)) {
if (isset($json['home_url'])){
return false;
}
else{
return true;
}
}
else{
return true;
}
}
elseif($ret['result'] === WPVIVID_FAILED){
return true;
}
}
}
return true;
}
else
{
return true;
}
}
public function get_local_path()
{
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$this->config['local']['path'].DIRECTORY_SEPARATOR;
$path=apply_filters('wpvivid_get_site_wpvivid_path',$path,$this->config['local']['path']);
return $path;
}
public function get_local_url()
{
$url=content_url().DIRECTORY_SEPARATOR.$this->config['local']['path'].DIRECTORY_SEPARATOR;
$url=apply_filters('wpvivid_get_site_wpvivid_url',$url,$this->config['local']['path']);
return $url;
}
public function get_remote()
{
$remote_option=array_shift($this->config['remote']);
if(is_null($remote_option))
{
return false;
}
else
{
return $remote_option;
}
}
public function get_backup_packages()
{
$packages=array();
$index=0;
if(isset($this->config['backup']['files']))
{
$db_package=array();
$file_added=array();
//file_name
foreach ($this->config['backup']['files'] as $file)
{
if(isset($file_added[$file['file_name']]))
{
continue;
}
if (preg_match('/wpvivid-.*_.*_.*\.part[0-9]+\.zip$/', $file['file_name'],$matches))
{
$this->get_all_part_files($file['file_name'],$this->config['backup']['files'],$packages[$index],$file_added);
}
else
{
if($this->check_file_is_a_db_package($file['file_name']))
{
$db_package['files'][]=$file['file_name'];
}
else
{
$packages[$index]['files'][]=$file['file_name'];
}
$file_added[$file['file_name']]=1;
}
$index++;
}
$file_added=array();
$child_packages=array();
foreach ($packages as $key=>$package)
{
$files=array();
foreach ($package['files'] as $package_files)
{
$files=array_merge($files,$this->get_child_files($package_files));
}
if(empty($files))
{
continue;
}
foreach ($files as $file)
{
if (isset($file_added[$file['file_name']]))
{
continue;
}
if (preg_match('/wpvivid-.*_.*_.*\.part[0-9]+\.zip$/', $file['file_name'],$matches))
{
$this->get_all_part_files($file['file_name'],$files,$child_packages[$index],$file_added);
}
else
{
if($this->check_file_is_a_db_package($file['file_name']))
{
$db_package['files'][]=$file['file_name'];
}
else
{
$child_packages[$index]['files'][]=$file['file_name'];
}
$file_added[$file['file_name']]=1;
}
$index++;
}
}
$packages=array_merge($packages,$child_packages);
if(!empty($db_package))
{
$packages[$index]=$db_package;
}
}
else if(isset($this->config['backup']['data']))
{
if(isset($this->config['backup']['ismerge'])&&$this->config['backup']['ismerge']==1)
{
$packages[$index]['option']['has_child']=1;
//$packages[$index]['option']['root']='wp-content';
$packages[$index]['option']['root_flag']=WPVIVID_BACKUP_ROOT_WP_CONTENT;
foreach ($this->config['backup']['data']['meta']['files'] as $file)
{
$packages[$index]['files'][]=$file['file_name'];
}
$index++;
}
foreach ($this->config['backup']['data']['type'] as $type)
{
if($type['type_name']=='backup_db')
{
$packages[$index]['option']['dump_db']=1;
//$packages[$index]['option']['root']='wp-content\\'.$this->config['local']['path'];
$packages[$index]['option']['root_flag']=WPVIVID_BACKUP_ROOT_CUSTOM;
}
else if($type['type_name']=='backup_themes')
{
//$packages[$index]['option']['root']='wp-content';
$packages[$index]['option']['root_flag']=WPVIVID_BACKUP_ROOT_WP_CONTENT;
}
else if($type['type_name']=='backup_plugin')
{
//$packages[$index]['option']['root']='wp-content';
$packages[$index]['option']['root_flag']=WPVIVID_BACKUP_ROOT_WP_CONTENT;
}
else if($type['type_name']=='backup_uploads')
{
//$packages[$index]['option']['root']='wp-content';
$packages[$index]['option']['root_flag']=WPVIVID_BACKUP_ROOT_WP_CONTENT;
}
else if($type['type_name']=='backup_content')
{
//$packages[$index]['option']['root']='';
$packages[$index]['option']['root_flag']=WPVIVID_BACKUP_ROOT_WP_ROOT;
}
else if($type['type_name']=='backup_core')
{
//$packages[$index]['option']['root']='';
$packages[$index]['option']['root_flag']=WPVIVID_BACKUP_ROOT_WP_ROOT;
$packages[$index]['option']['include_path'][]='wp-includes';
$packages[$index]['option']['include_path'][]='wp-admin';
}
foreach ($type['files'] as $file)
{
$packages[$index]['files'][]=$file['file_name'];
}
$index++;
}
}
return $packages;
}
public function check_file_is_a_db_package($file_name)
{
//backup_db.zip
if (preg_match('#.*_backup_db.zip?#', $file_name, $matches))
{
return true;
}
else
{
return false;
}
}
public function get_all_part_files($file_name,$files,&$package,&$file_added)
{
if (preg_match('#\.part[0-9]+\.zip$#',$file_name,$matches))
{
$prefix=$matches[0];
$file_prefix=substr($file_name,0,strlen($file_name)-strlen($prefix));
foreach ($files as $file)
{
if(isset($file_added[$file['file_name']]))
{
continue;
}
if (strpos($file['file_name'], $file_prefix) !== false)
{
$package['files'][]=$file['file_name'];
$file_added[$file['file_name']]=1;
}
}
}
}
public function get_child_files($file_name)
{
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
$path=$this->get_backup_path($file_name);//$this->get_local_path().$file_name;
$files = array();
$ret=$zip->get_json_data($path);
if($ret['result'] === WPVIVID_SUCCESS) {
$json=$ret['json_data'];
$json = json_decode($json, 1);
if (isset($json['has_child'])) {
$files = $zip->list_file($path);
}
}
return $files;
}
public function get_file_info($file_name)
{
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
$path=$this->get_backup_path($file_name);//$this->get_local_path().$file_name;
$ret=$zip->get_json_data($path);
if($ret['result'] === WPVIVID_SUCCESS) {
$json=$ret['json_data'];
$json = json_decode($json, 1);
if (is_null($json)) {
return false;
} else {
return $json;
}
}
elseif($ret['result'] === WPVIVID_FAILED){
return false;
}
}
static public function get_backup_file_info($file_name)
{
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
$ret=$zip->get_json_data($file_name);
if($ret['result'] === WPVIVID_SUCCESS)
{
$json=$ret['json_data'];
$json = json_decode($json, 1);
if (is_null($json)) {
return array('result'=>WPVIVID_FAILED,'error'=>'Failed to decode json');
} else {
return array('result'=>WPVIVID_SUCCESS,'json_data'=>$json);
}
}
elseif($ret['result'] === WPVIVID_FAILED){
return $ret;
}
}
public function get_sql_file($file_name)
{
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
$path=$this->get_backup_path($file_name);//$this->get_local_path().$file_name;
$files=$zip->list_file($path);
return $files[0]['file_name'];
}
public static function get_backup_files($backup){
$files=array();
if(isset($backup['backup']['files'])){
$files=$backup['backup']['files'];
}
else{
if(isset($backup['backup']['ismerge'])) {
if ($backup['backup']['ismerge'] == 1) {
if(isset($backup['backup']['data']['meta']['files'])){
$files=$backup['backup']['data']['meta']['files'];
}
}
}
}
asort($files);
uasort($files, function ($a, $b) {
$file_name_1 = $a['file_name'];
$file_name_2 = $b['file_name'];
$index_1 = 0;
if(preg_match('/wpvivid-.*_.*_.*\.part.*\.zip$/', $file_name_1)) {
if (preg_match('/part.*$/', $file_name_1, $matches)) {
$index_1 = $matches[0];
$index_1 = preg_replace("/part/","", $index_1);
$index_1 = preg_replace("/.zip/","", $index_1);
}
}
$index_2 = 0;
if(preg_match('/wpvivid-.*_.*_.*\.part.*\.zip$/', $file_name_2)) {
if (preg_match('/part.*$/', $file_name_2, $matches)) {
$index_2 = $matches[0];
$index_2 = preg_replace("/part/", "", $index_2);
$index_2 = preg_replace("/.zip/", "", $index_2);
}
}
if($index_1 !== 0 && $index_2 === 0){
return -1;
}
if($index_1 === 0 && $index_2 !== 0){
return 1;
}
});
return $files;
}
public function get_download_backup_files($backup_id){
$ret['result']=WPVIVID_FAILED;
$data=array();
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
if(!$backup)
{
$ret['error']='Backup id not found.';
return $ret;
}
$files=array();
$files = self::get_backup_files($backup);
if(empty($files)){
$ret['error']='Failed to get backup files.';
}
else{
$ret['result']=WPVIVID_SUCCESS;
$ret['files']=$files;
}
return $ret;
}
public function get_download_progress($backup_id, $files){
global $wpvivid_plugin;
$b_need_download=false;
$b_not_found=false;
$file_count=0;
$file_part_num=1;
$check_type='';
foreach ($files as $file)
{
$need_download=false;
$path=$this->get_backup_path($file['file_name']);//$this->get_local_path().$file['file_name'];
$download_url=content_url().DIRECTORY_SEPARATOR.$this->config['local']['path'].DIRECTORY_SEPARATOR.$file['file_name'];
if(file_exists($path)) {
if(filesize($path) == $file['size']){
if($wpvivid_plugin->wpvivid_check_zip_valid()) {
$res = TRUE;
}
else{
$res = FALSE;
}
}
else{
$res = FALSE;
}
if ($res !== TRUE)
{
$need_download=true;
}
}
else {
$need_download=true;
}
if($file_part_num < 10){
$format_part=sprintf("%02d", $file_part_num);
}
else{
$format_part=$file_part_num;
}
if($need_download) {
if(empty($this->config['remote'])) {
$b_not_found=true;
$ret['result'] = WPVIVID_SUCCESS;
$ret['files'][$file['file_name']]['status']='file_not_found';
}
else{
$task = WPvivid_taskmanager::get_download_task_v2($file['file_name']);
$ret['task']=$task;
if ($task === false) {
$ret['result'] = WPVIVID_SUCCESS;
$ret['files'][$file['file_name']]['status']='need_download';
$ret['files'][$file['file_name']]['html']='<div style="float:left;margin:10px 10px 10px 0;text-align:center; width:180px;">
<span>Part'.$format_part.'</span></br>
<span id=\''.$backup_id.'-text-part-'.$file_part_num.'\'><a onclick="wpvivid_prepare_download(\''.$file_part_num.'\', \''.$backup_id.'\', \''.$file['file_name'].'\');" style="cursor: pointer;">Prepare to Download</a></span></br>
<div style="width:100%;height:5px; background-color:#dcdcdc;"><div id=\''.$backup_id.'-progress-part-'.$file_part_num.'\' style="background-color:#0085ba; float:left;width:0;height:5px;"></div></div>
<span>size:</span><span>'.$wpvivid_plugin->formatBytes($file['size']).'</span>
</div>';
} else {
$ret['result'] = WPVIVID_SUCCESS;
if($task['status'] === 'running'){
$ret['files'][$file['file_name']]['status'] = 'running';
$ret['files'][$file['file_name']]['html']='<div style="float:left;margin:10px 10px 10px 0;text-align:center; width:180px;">
<span>Part'.$format_part.'</span></br>
<span id=\''.$backup_id.'-text-part-'.$file_part_num.'\'><a >Retriving(remote storage to web server)</a></span></br>
<div style="width:100%;height:5px; background-color:#dcdcdc;"><div id=\''.$backup_id.'-progress-part-'.$file_part_num.'\' style="background-color:#0085ba; float:left;width:'.$task['progress_text'].'%;height:5px;"></div></div>
<span>size:</span><span>'.$wpvivid_plugin->formatBytes($file['size']).'</span>
</div>';
$ret['files'][$file['file_name']]['progress_text']=$task['progress_text'];
}
elseif($task['status'] === 'timeout'){
$ret['files'][$file['file_name']]['status']='timeout';
$ret['files'][$file['file_name']]['html']='<div style="float:left;margin:10px 10px 10px 0;text-align:center; width:180px;">
<span>Part'.$format_part.'</span></br>
<span id=\''.$backup_id.'-text-part-'.$file_part_num.'\'><a onclick="wpvivid_prepare_download(\''.$file_part_num.'\', \''.$backup_id.'\', \''.$file['file_name'].'\');" style="cursor: pointer;">Prepare to Download</a></span></br>
<div style="width:100%;height:5px; background-color:#dcdcdc;"><div id=\''.$backup_id.'-progress-part-'.$file_part_num.'\' style="background-color:#0085ba; float:left;width:'.$task['progress_text'].'%;height:5px;"></div></div>
<span>size:</span><span>'.$wpvivid_plugin->formatBytes($file['size']).'</span>
</div>';
$ret['files'][$file['file_name']]['progress_text']=$task['progress_text'];
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
}
elseif($task['status'] === 'completed'){
$ret['files'][$file['file_name']]['status']='completed';
$ret['files'][$file['file_name']]['html']='<div style="float:left;margin:10px 10px 10px 0;text-align:center; width:180px;">
<span>Part'.$format_part.'</span></br>
<span id=\''.$backup_id.'-text-part-'.$file_part_num.'\'><a onclick="wpvivid_download(\''.$backup_id.'\', \''.$check_type.'\', \''.$file['file_name'].'\');" style="cursor: pointer;">Download</a></span></br>
<div style="width:100%;height:5px; background-color:#dcdcdc;"><div id=\''.$backup_id.'-progress-part-'.$file_part_num.'\' style="background-color:#0085ba; float:left;width:100%;height:5px;"></div></div>
<span>size:</span><span>'.$wpvivid_plugin->formatBytes($file['size']).'</span>
</div>';
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
}
elseif($task['status'] === 'error'){
$ret['files'][$file['file_name']]['status']='error';
$ret['files'][$file['file_name']]['html']='<div style="float:left;margin:10px 10px 10px 0;text-align:center; width:180px;">
<span>Part'.$format_part.'</span></br>
<span id=\''.$backup_id.'-text-part-'.$file_part_num.'\'><a onclick="wpvivid_prepare_download(\''.$file_part_num.'\', \''.$backup_id.'\', \''.$file['file_name'].'\');" style="cursor: pointer;">Prepare to Download</a></span></br>
<div style="width:100%;height:5px; background-color:#dcdcdc;"><div id=\''.$backup_id.'-progress-part-'.$file_part_num.'\' style="background-color:#0085ba; float:left;width:0;height:5px;"></div></div>
<span>size:</span><span>'.$wpvivid_plugin->formatBytes($file['size']).'</span>
</div>';
$ret['files'][$file['file_name']]['error'] = $task['error'];
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
}
}
}
}
else{
$ret['result'] = WPVIVID_SUCCESS;
if(WPvivid_taskmanager::get_download_task_v2($file['file_name']))
WPvivid_taskmanager::delete_download_task_v2($file['file_name']);
$ret['files'][$file['file_name']]['status']='completed';
$ret['files'][$file['file_name']]['download_path']=$path;
$ret['files'][$file['file_name']]['download_url']=$download_url;
$ret['files'][$file['file_name']]['html']='<div style="float:left;margin:10px 10px 10px 0;text-align:center; width:180px;">
<span>Part'.$format_part.'</span></br>
<span id=\''.$backup_id.'-text-part-'.$file_part_num.'\'><a onclick="wpvivid_download(\''.$backup_id.'\', \''.$check_type.'\', \''.$file['file_name'].'\');" style="cursor: pointer;">Download</a></span></br>
<div style="width:100%;height:5px; background-color:#dcdcdc;"><div id=\''.$backup_id.'-progress-part-'.$file_part_num.'\' style="background-color:#0085ba; float:left;width:100%;height:5px;"></div></div>
<span>size:</span><span>'.$wpvivid_plugin->formatBytes($file['size']).'</span>
</div>';
}
$ret['files'][$file['file_name']]['size']=$wpvivid_plugin->formatBytes($file['size']);
$file_count++;
$file_part_num++;
}
if ($file_count % 2 != 0) {
$file_count++;
if($file_count < 10){
$format_part=sprintf("%02d", $file_count);
}
else{
$format_part=$file_count;
}
$ret['place_html']='<div style="float:left;margin:10px 10px 10px 0;text-align:center; width:180px; color:#cccccc;">
<span>Part'.$format_part.'</span></br>
<span>Download</span></br>
<div style="width:100%;height:5px; background-color:#dcdcdc;"><div style="background-color:#0085ba; float:left;width:0;height:5px;"></div></div>
<span>size:</span><span>0</span>
</div>';
}
else{
$ret['place_html']='';
}
return $ret;
}
public function update_download_page($backup_id){
$ret=$this->get_download_backup_files($backup_id);
if($ret['result']==WPVIVID_SUCCESS){
$ret=$this->get_download_progress($backup_id, $ret['files']);
WPvivid_taskmanager::update_download_cache($backup_id,$ret);
}
return $ret;
}
public function cleanup_local_backup()
{
$files=array();
$download_dir=$this->config['local']['path'];
$file=$this->get_files(false);
foreach ($file as $filename)
{
$files[] = $filename;
}
foreach ($files as $file)
{
$download_path = WP_CONTENT_DIR .DIRECTORY_SEPARATOR . $download_dir . DIRECTORY_SEPARATOR . $file;
if (file_exists($download_path))
{
@wp_delete_file($download_path);
}
else{
$backup_dir=WPvivid_Setting::get_backupdir();
$download_path = WP_CONTENT_DIR .DIRECTORY_SEPARATOR . $backup_dir . DIRECTORY_SEPARATOR . $file;
if (file_exists($download_path))
{
@wp_delete_file($download_path);
}
}
}
}
public function cleanup_remote_backup()
{
if(!empty($this->config['remote']))
{
$files=$this->get_files(false);
foreach($this->config['remote'] as $remote)
{
if(!class_exists('WPvivid_downloader'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-downloader.php';
WPvivid_downloader::delete($remote,$files);
}
}
}
public function check_has_zero_date()
{
if(isset($this->config['backup']['files']))
{
$tmp_data = $this->config['backup']['files'];
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
foreach ($tmp_data as $file)
{
$path=$this->get_backup_path($file['file_name']);
if(file_exists($path))
{
$ret=$zip->get_json_data($path);
if($ret['result'] === WPVIVID_SUCCESS)
{
$json=$ret['json_data'];
$json = json_decode($json, 1);
if (!is_null($json))
{
if (isset($json['has_child']))
{
if (isset($json['child_file']))
{
foreach ($json['child_file'] as $child_file_name => $child_file_info)
{
if(isset($child_file_info['find_zero_date']) && $child_file_info['find_zero_date'] == 1)
{
return true;
}
}
}
}
else
{
if(isset($json['find_zero_date']) && $json['find_zero_date'] == 1)
{
return true;
}
}
}
else {
return false;
}
}
elseif($ret['result'] === WPVIVID_FAILED)
{
return false;
}
}
}
return false;
}
else
{
return false;
}
}
public function check_wp_version()
{
if(isset($this->config['backup']['files']))
{
$tmp_data = $this->config['backup']['files'];
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
foreach ($tmp_data as $file)
{
$path=$this->get_backup_path($file['file_name']);
if(file_exists($path))
{
$ret=$zip->get_json_data($path);
if($ret['result'] === WPVIVID_SUCCESS)
{
$json=$ret['json_data'];
$json = json_decode($json, 1);
if (!is_null($json))
{
if (isset($json['has_child']))
{
if (isset($json['child_file']))
{
foreach ($json['child_file'] as $child_file_name => $child_file_info)
{
if(isset($child_file_info['wp_version']))
{
$backup_wp_version=$child_file_info['wp_version'];
$wp_version = get_bloginfo( 'version' );
if (version_compare($wp_version,$backup_wp_version,'>'))
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
}
}
else
{
if(isset($json['wp_version']))
{
$backup_wp_version=$json['wp_version'];
$wp_version = get_bloginfo( 'version' );
if (version_compare($wp_version,$backup_wp_version,'>'))
{
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
}
else {
return true;
}
}
elseif($ret['result'] === WPVIVID_FAILED)
{
return true;
}
}
}
return true;
}
else
{
return true;
}
}
}
class WPvivid_Backup
{
public $task;
public $backup_type_report = '';
//public $config;
public function __construct($task_id=false,$task=false)
{
if($task_id!==false)
{
$this->task=new WPvivid_Backup_Task($task_id);
}
else if($task!==false)
{
$this->task=new WPvivid_Backup_Task(false,$task);
}
else
{
$this->task=new WPvivid_Backup_Task();
}
//$this->config=$config;
}
public function init_options($task_id)
{
$this->task=new WPvivid_Backup_Task($task_id);
}
public function backup($task_id)
{
$this->init_options($task_id);
$next_backup=$this->task->get_need_backup();
$this->backup_type_report = '';
while($next_backup!==false)
{
global $wpvivid_plugin;
$wpvivid_plugin->set_time_limit($this->task->get_id());
$this->task->update_sub_task_progress($next_backup['key'],0, sprintf('Start backing up %s.', $next_backup['key']));
$wpvivid_plugin->wpvivid_log->WriteLog('Prepare to backup '.$next_backup['key'].' files.','notice');
$this->backup_type_report .= $next_backup['key'].',';
if(isset($next_backup['files'])) {
$wpvivid_plugin->wpvivid_log->WriteLog('File number: ' . sizeof($next_backup['files']), 'notice');
}
$result = $this->_backup($next_backup);
$wpvivid_plugin->wpvivid_log->WriteLog('Backing up '.$next_backup['key'].' completed.','notice');
$this->task->update_sub_task_progress($next_backup['key'],1, sprintf('Backing up %s finished.', $next_backup['key']));
$this->task->update_backup_result($next_backup,$result);
$wpvivid_plugin->check_cancel_backup($task_id);
unset($next_backup);
$next_backup=$this->task->get_need_backup();
}
WPvivid_Setting::update_option('wpvivid_backup_report', $this->backup_type_report);
$this->cleanup();
$ret=$this->task->get_backup_result();
return $ret;
}
private function _backup($data)
{
global $wpvivid_plugin;
$result['result']=WPVIVID_FAILED;
$result['error']='test error';
$is_type_db = false;
$is_type_db = apply_filters('wpvivid_check_type_database', $is_type_db, $data);
if($is_type_db)
{
include_once WPVIVID_PLUGIN_DIR .'/includes/class-wpvivid-backup-database.php';
$wpvivid_plugin->wpvivid_log->WriteLog('Start exporting database.','notice');
$backup_database = new WPvivid_Backup_Database();
$result = $backup_database -> backup_database($data,$this->task->get_id());
$wpvivid_plugin->wpvivid_log->WriteLog('Exporting database finished.','notice');
if($result['result']==WPVIVID_SUCCESS)
{
$data['files']=$result['files'];
}
else
{
return $result;
}
}
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip = new WPvivid_ZipClass();
if(is_array($zip->last_error))
{
return $zip->last_error;
}
if(isset($data['resume_packages']))
{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Start compressing '.$data['key'],'notice');
$packages=$this->task->get_packages_info($data['key']);
if($packages===false)
{
if(isset($data['plugin_subpackage']))
{
$ret =$zip->get_plugin_packages($data);
}
else if(isset($data['uploads_subpackage']))
{
$ret =$zip->get_upload_packages($data);
}
else
{
if($data['key']==WPVIVID_BACKUP_TYPE_MERGE)
$ret =$zip->get_packages($data,true);
else
$ret =$zip->get_packages($data);
}
$packages=$this->task->set_packages_info($data['key'],$ret['packages']);
}
$temp_dir = $data['path'].'temp-'.$data['prefix'].DIRECTORY_SEPARATOR;
define(PCLZIP_TEMPORARY_DIR,$temp_dir);
$result['result']=WPVIVID_SUCCESS;
$result['files']=array();
foreach ($packages as $package)
{
$wpvivid_plugin->set_time_limit($this->task->get_id());
if(!empty($package['files'])&&$package['backup']==false)
{
if(isset($data['uploads_subpackage']))
{
$files=$zip->get_upload_files_from_cache($package['files']);
}
else
{
$files=$package['files'];
}
if(empty($files))
continue;
$zip_ret=$zip->_zip($package['path'],$files, $data,$package['json']);
if($zip_ret['result']==WPVIVID_SUCCESS)
{
if(isset($data['uploads_subpackage']))
{
if(file_exists($package['files']))
{
@wp_delete_file($package['files']);
}
}
$result['files'][] = $zip_ret['file_data'];
$package['backup']=true;
$this->task->update_packages_info($data['key'],$package,$zip_ret['file_data']);
if($data['key']==WPVIVID_BACKUP_TYPE_MERGE)
{
$this->cleanup_finished_package($package['files']);
}
}
else
{
$result=$zip_ret;
break;
}
}else {
continue;
}
}
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing '.$data['key'].' completed','notice');
return $result;
}
else
{
$is_additional_db = false;
$is_additional_db = apply_filters('wpvivid_check_additional_database', $is_additional_db, $data);
if($is_additional_db){
$result =$zip->compress_additional_database($data);
}
else {
$result =$zip->compress($data);
}
if($is_type_db)
{
foreach ($data['files'] as $sql_file)
{
@wp_delete_file($sql_file);
}
}
}
return $result;
}
public function cleanup()
{
$files=$this->task->get_need_cleanup_files();
foreach ($files as $file)
{
if(file_exists($file)) {
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Cleaned up file, filename: '.$file,'notice');
@wp_delete_file($file);
}
}
}
public function cleanup_finished_package($files)
{
foreach ($files as $file)
{
if(file_exists($file))
{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Cleaned up file, filename: '.$file,'notice');
@wp_delete_file($file);
}
}
}
public function clean_backup()
{
$path = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
$handler=opendir($path);
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if(preg_match('#'.$this->task->get_id().'#',$filename) || preg_match('#'.apply_filters('wpvivid_fix_wpvivid_free', $this->task->get_id()).'#',$filename))
{
@wp_delete_file($path.DIRECTORY_SEPARATOR.$filename);
}
}
@closedir($handler);
}
}
public function clearcache()
{
$task_id=$this->task->get_prefix();
$path = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
$handler=opendir($path);
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if(is_dir($path.DIRECTORY_SEPARATOR.$filename) && preg_match('#temp-'.$task_id.'#',$filename))
{
$this->deldir($path.DIRECTORY_SEPARATOR.$filename,'',true);
}
if(is_dir($path.DIRECTORY_SEPARATOR.$filename) && preg_match('#temp-'.$task_id.'#',$filename))
{
$this->deldir($path.DIRECTORY_SEPARATOR.$filename,'',true);
}
if(preg_match('#pclzip-.*\.tmp#', $filename)){
@wp_delete_file($path.DIRECTORY_SEPARATOR.$filename);
}
if(preg_match('#pclzip-.*\.gz#', $filename)){
@wp_delete_file($path.DIRECTORY_SEPARATOR.$filename);
}
}
@closedir($handler);
}
}
public function deldir($path,$exclude=array(),$flag = false)
{
if(!is_dir($path))
{
return ;
}
$handler=opendir($path);
if(empty($handler))
return ;
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($path.DIRECTORY_SEPARATOR.$filename)){
if(empty($exclude)||$this->regex_match($exclude['directory'],$path.DIRECTORY_SEPARATOR.$filename ,0)){
$this->deldir( $path.DIRECTORY_SEPARATOR.$filename ,$exclude, $flag);
@rmdir( $path.DIRECTORY_SEPARATOR.$filename );
}
}else{
if(empty($exclude)||$this->regex_match($exclude['file'],$path.DIRECTORY_SEPARATOR.$filename ,0)){
@wp_delete_file($path.DIRECTORY_SEPARATOR.$filename);
}
}
}
}
if($handler)
@closedir($handler);
if($flag)
@rmdir($path);
}
public function regex_match($regex_array,$string,$mode)
{
if(empty($regex_array))
{
return true;
}
if($mode==0)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return false;
}
}
return true;
}
if($mode==1)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return true;
}
}
return false;
}
return true;
}
public function clean_remote_backup($remotes,$files)
{
$remote_option=array_shift($remotes);
if(!is_null($remote_option))
{
global $wpvivid_plugin;
if(!class_exists('WPvivid_Remote_collection'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-remote-collection.php';
$wpvivid_plugin->remote_collection=new WPvivid_Remote_collection();
}
$remote=$wpvivid_plugin->remote_collection->get_remote($remote_option);
$remote ->cleanup($files);
}
}
} includes/class-wpvivid-log.php 0000644 00000013075 15132770567 0012460 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_Log
{
public $log_file;
public $log_file_handle;
public function __construct()
{
$this->log_file_handle=false;
}
public function CreateLogFile($file_name,$type,$describe)
{
if($type=='has_folder')
{
$this->log_file=$file_name;
}
else
{
$this->log_file=$this->GetSaveLogFolder().$file_name.'_log.txt';
}
if(file_exists($this->log_file))
{
@wp_delete_file( $this->log_file);
}
$this->log_file_handle = fopen($this->log_file, 'a');
$offset=get_option('gmt_offset');
$time =gmdate("Y-m-d H:i:s",time()+$offset*60*60);
$text='Log created: '.$time."\n";
$text.='Type: '.$describe."\n";
fwrite($this->log_file_handle,$text);
return $this->log_file;
}
public function OpenLogFile($file_name,$type='no_folder',$delete=0)
{
if($type=='has_folder')
{
$this->log_file=$file_name;
}
else
{
$this->log_file=$this->GetSaveLogFolder().$file_name.'_log.txt';
}
if($delete==1)
{
wp_delete_file( $this->log_file);
}
$this->log_file_handle = fopen($this->log_file, 'a');
return $this->log_file;
}
public function WriteLog($log,$type)
{
if ($this->log_file_handle)
{
$offset=get_option('gmt_offset');
$time =gmdate("Y-m-d H:i:s",time()+$offset*60*60);
$text='['.$time.']'.'['.$type.']'.$log."\n";
fwrite($this->log_file_handle,$text );
}
}
public function CloseFile()
{
if ($this->log_file_handle)
{
fclose($this->log_file_handle);
$this->log_file_handle=false;
}
}
public function GetSaveLogFolder()
{
include_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-wpvivid-setting.php';
$options = WPvivid_Setting::get_option('wpvivid_common_setting');
if(!isset($options['log_save_location']))
{
//WPvivid_Setting::set_default_common_option();
$options['log_save_location']=WPVIVID_DEFAULT_LOG_DIR;
update_option('wpvivid_common_setting', $options, 'no');
$options = WPvivid_Setting::get_option('wpvivid_common_setting');
}
if(!is_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['log_save_location']))
{
@mkdir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['log_save_location'],0777,true);
//@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['log_save_location'].DIRECTORY_SEPARATOR.'index.html', 'x');
$tempfile=@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['log_save_location'].DIRECTORY_SEPARATOR.'.htaccess', 'x');
if($tempfile)
{
//$text="deny from all";
$text="<IfModule mod_rewrite.c>\r\nRewriteEngine On\r\nRewriteRule .* - [F,L]\r\n</IfModule>";
fwrite($tempfile,$text );
}
}
return WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['log_save_location'].DIRECTORY_SEPARATOR;
}
public function WriteLogHander()
{
if ($this->log_file_handle)
{
global $wp_version;
global $wpdb;
$sapi_type=php_sapi_name();
if($sapi_type=='cgi-fcgi'||$sapi_type==' fpm-fcgi') {
$fcgi='On';
}
else {
$fcgi='Off';
}
$options=WPvivid_Setting::get_option('wpvivid_common_setting');
if(isset($options['max_execution_time'])) {
$max_execution_time=$options['max_execution_time'];
}
else {
$max_execution_time=WPVIVID_MAX_EXECUTION_TIME;
}
$log='server info fcgi:'.$fcgi.' max execution time: '.$max_execution_time.' wp version:'.$wp_version.' php version:'.phpversion().' db version:'.$wpdb->db_version().' php ini:safe_mode:'.ini_get('safe_mode').' ';
$log.='memory_limit:'.ini_get('memory_limit').' memory_get_usage:'.size_format(memory_get_usage(),2).' memory_get_peak_usage:'.size_format(memory_get_peak_usage(),2);
$log.=' extensions:';
$loaded_extensions = get_loaded_extensions();
if(!in_array('PDO', $loaded_extensions))
{
$log.='PDO not enabled ';
}
else
{
$log.='PDO enabled ';
}
if(!in_array('curl', $loaded_extensions))
{
$log.='curl not enabled ';
}
else
{
$log.='curl enabled ';
}
if(!in_array('zlib', $loaded_extensions)) {
$log .= 'zlib not enabled ';
}
else
{
$log.='zlib enabled ';
}
$log.=' ';
if(is_multisite())
{
$log.=' is_multisite:1';
}
else
{
$log.=' is_multisite:0';
}
$offset=get_option('gmt_offset');
$time =gmdate("Y-m-d H:i:s",time()+$offset*60*60);
$text='['.$time.']'.'[notice]'.$log."\n";
fwrite($this->log_file_handle,$text );
}
}
} includes/class-wpvivid-backup-database.php 0000644 00000012464 15132770567 0014707 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
define('NECESSARY','1');
define('OPTION','0');
class WPvivid_Backup_Database
{
private $task_id;
public function __construct()
{
}
public function wpvivid_archieve_database_info($databases, $data)
{
if(isset($data['dump_db']))
{
$sql_info['file_name'] =$data['sql_file_name'];
$sql_info['database'] = DB_NAME;
$sql_info['host'] = DB_HOST;
$sql_info['user'] = DB_USER;
$sql_info['pass'] = DB_PASSWORD;
$databases[] = $sql_info;
}
return $databases;
}
public function backup_database($data,$task_id = '')
{
global $wpvivid_plugin;
$dump=null;
try
{
$this->task_id=$task_id;
//$backup_file =$data['sql_file_name'];
require_once 'class-wpvivid-mysqldump-method.php';
require_once 'class-wpvivid-mysqldump.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-db-method.php';
$db_method=new WPvivid_DB_Method();
$version =$db_method->get_mysql_version();
if(version_compare('4.1.0',$version) > 0)
{
return array('result'=>WPVIVID_FAILED,'error'=>'Your MySQL version is too old. Please upgrade at least to MySQL 4.1.0.');
}
if(version_compare('5.3.0',phpversion()) > 0){
return array('result'=>WPVIVID_FAILED,'error'=>'Your PHP version is too old. Please upgrade at least to PHP 5.3.0.');
}
$db_method->check_max_allowed_packet();
add_filter('wpvivid_exclude_db_table', array($this, 'exclude_table'),10,2);
$exclude=array();
$exclude = apply_filters('wpvivid_exclude_db_table',$exclude, $data);
$include=array();
$include = apply_filters('wpvivid_include_db_table',$include, $data);
$site_url = apply_filters('wpvivid_dump_set_site_url',get_site_url(), $data);
$home_url = apply_filters('wpvivid_dump_set_home_url',get_home_url(), $data);
$content_url=apply_filters('wpvivid_dump_set_content_url',content_url(), $data);
global $wpdb;
if (is_multisite() && !defined('MULTISITE'))
{
$prefix = $wpdb->base_prefix;
} else {
$prefix = $wpdb->get_blog_prefix(0);
}
$prefix=apply_filters('wpvivid_dump_set_prefix',$prefix, $data);
add_filter('wpvivid_archieve_database_info', array($this, 'wpvivid_archieve_database_info'), 10, 2);
$databases=array();
$databases = apply_filters('wpvivid_archieve_database_info', $databases, $data);
$is_additional_db = false;
if($data['key'] === 'backup_additional_db')
{
$is_additional_db = true;
}
$backup_files = array();
foreach ($databases as $sql_info)
{
$database_name = $sql_info['database'];
$backup_file = $sql_info['file_name'];
$backup_files[] = $backup_file;
$host = $sql_info['host'];
$user = $sql_info['user'];
$pass = $sql_info['pass'];
$dumpSettings=array();
$dumpSettings['exclude-tables']=$exclude;
$dumpSettings['include-tables']=$include;
$dumpSettings['add-drop-table']=true;
$dumpSettings['extended-insert']=false;
$dumpSettings['site_url']=$site_url;
$dumpSettings['home_url']=$home_url;
$dumpSettings['content_url']=$content_url;
$dumpSettings['prefix']=$prefix;
$dump = new WPvivid_Mysqldump($host, $database_name, $user, $pass, $is_additional_db, $dumpSettings);
if (file_exists($backup_file))
@wp_delete_file($backup_file);
$dump->task_id=$task_id;
$dump->start($backup_file);
}
unset($pdo);
}
catch (Exception $e)
{
$str_last_query_string='';
if(!is_null($dump))
{
$str_last_query_string=$dump->last_query_string;
}
if(!empty($str_last_query_string))
{
$wpvivid_plugin->wpvivid_log->WriteLog('last query string:'.$str_last_query_string,'error');
}
$message = 'A exception ('.get_class($e).') occurred '.$e->getMessage().' (Code: '.$e->getCode().', line '.$e->getLine().' in '.$e->getFile().')';
return array('result'=>WPVIVID_FAILED,'error'=>$message);
}
$files = array();
$files = $backup_files;
return array('result'=>WPVIVID_SUCCESS,'files'=>$files);
}
public function exclude_table($exclude,$data)
{
global $wpdb;
if (is_multisite() && !defined('MULTISITE'))
{
$prefix = $wpdb->base_prefix;
} else {
$prefix = $wpdb->get_blog_prefix(0);
}
$exclude = array('/^(?!' . $prefix . ')/i');
return $exclude;
}
} includes/class-wpvivid-public-interface.php 0000644 00000037502 15132770567 0015114 0 ustar 00 <?php
class WPvivid_Public_Interface
{
public function __construct()
{
}
public function mainwp_data($data){
$action = sanitize_text_field($data['mwp_action']);
if (has_filter($action)) {
$ret = apply_filters($action, $data);
} else {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'Unknown function';
}
return $ret;
}
public function prepare_backup($backup_options){
global $wpvivid_plugin;
if(isset($backup_options)&&!empty($backup_options)){
if (is_null($backup_options)) {
$ret['error']='Invalid parameter param:'.$backup_options;
return $ret;
}
$backup_options = apply_filters('wpvivid_custom_backup_options', $backup_options);
if(!isset($backup_options['type']))
{
$backup_options['type']=__('Manual', 'wpvivid-backuprestore');
$backup_options['action']='backup';
}
$ret = $wpvivid_plugin->check_backup_option($backup_options, $backup_options['type']);
if($ret['result']!='success') {
return $ret;
}
$ret=$wpvivid_plugin->pre_backup($backup_options);
if($ret['result']=='success') {
//Check the website data to be backed up
$ret['check']=$wpvivid_plugin->check_backup($ret['task_id'],$backup_options);
if(isset($ret['check']['result']) && $ret['check']['result'] == 'failed') {
$ret['error']=$ret['check']['error'];
return $ret;
}
}
}
else{
$ret['error']='Error occurred while parsing the request data. Please try to run backup again.';
return $ret;
}
return $ret;
}
public function get_status(){
$ret['result']='success';
$list_tasks=array();
$tasks=WPvivid_Setting::get_tasks();
foreach ($tasks as $task)
{
$backup = new WPvivid_Backup_Task($task['id']);
$list_tasks[$task['id']]=$backup->get_backup_task_info($task['id']);
if($list_tasks[$task['id']]['task_info']['need_update_last_task']===true){
$task_msg = WPvivid_taskmanager::get_task($task['id']);
WPvivid_Setting::update_option('wpvivid_last_msg',$task_msg);
apply_filters('wpvivid_set_backup_report_addon_mainwp', $task_msg);
}
}
$ret['wpvivid']['task']=$list_tasks;
$backuplist=WPvivid_Backuplist::get_backuplist();
$schedule=WPvivid_Schedule::get_schedule();
$ret['wpvivid']['backup_list']=$backuplist;
$ret['wpvivid']['schedule']=$schedule;
$ret['wpvivid']['schedule']['last_message']=WPvivid_Setting::get_last_backup_message('wpvivid_last_msg');
WPvivid_taskmanager::delete_marked_task();
return $ret;
}
public function get_backup_schedule(){
$schedule=WPvivid_Schedule::get_schedule();
$ret['result']='success';
$ret['wpvivid']['schedule']=$schedule;
$ret['wpvivid']['schedule']['last_message']=WPvivid_Setting::get_last_backup_message('wpvivid_last_msg');
return $ret;
}
public function get_backup_list(){
$backuplist=WPvivid_Backuplist::get_backuplist();
$ret['result']='success';
$ret['wpvivid']['backup_list']=$backuplist;
return $ret;
}
public function get_default_remote(){
global $wpvivid_plugin;
$ret['result']='success';
$ret['remote_storage_type']=$wpvivid_plugin->function_realize->_get_default_remote_storage();
return $ret;
}
public function delete_backup($backup_id, $force_del){
global $wpvivid_plugin;
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id)) {
$ret['error']='Invalid parameter param: backup_id.';
return $ret;
}
if(!isset($force_del)){
$ret['error']='Invalid parameter param: force.';
return $ret;
}
if($force_del==0||$force_del==1) {
}
else {
$force_del=0;
}
$backup_id=sanitize_key($backup_id);
$ret=$wpvivid_plugin->delete_backup_by_id($backup_id, $force_del);
$backuplist=WPvivid_Backuplist::get_backuplist();
$ret['wpvivid']['backup_list']=$backuplist;
return $ret;
}
public function delete_backup_array($backup_id_array){
global $wpvivid_plugin;
if(!isset($backup_id_array)||empty($backup_id_array)||!is_array($backup_id_array)) {
$ret['error']='Invalid parameter param: backup_id';
return $ret;
}
$ret=array();
foreach($backup_id_array as $backup_id)
{
$backup_id=sanitize_key($backup_id);
$ret=$wpvivid_plugin->delete_backup_by_id($backup_id);
}
$backuplist=WPvivid_Backuplist::get_backuplist();
$ret['wpvivid']['backup_list']=$backuplist;
return $ret;
}
public function set_security_lock($backup_id, $lock){
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id)){
$ret['error']='Backup id not found';
return $ret;
}
if(!isset($lock)){
$ret['error']='Invalid parameter param: lock';
return $ret;
}
$backup_id=sanitize_key($backup_id);
if($lock==0||$lock==1) {
}
else {
$lock=0;
}
WPvivid_Backuplist::set_security_lock($backup_id,$lock);
$backuplist=WPvivid_Backuplist::get_backuplist();
$ret['wpvivid']['backup_list']=$backuplist;
return $ret;
}
public function view_log($backup_id){
global $wpvivid_plugin;
if (!isset($backup_id)||empty($backup_id)||!is_string($backup_id)){
$ret['error']='Backup id not found';
return $ret;
}
$backup_id=sanitize_key($backup_id);
$ret=$wpvivid_plugin->function_realize->_get_log_file('backuplist', $backup_id);
if($ret['result'] == 'success') {
$file = fopen($ret['log_file'], 'r');
if (!$file) {
$ret['result'] = 'failed';
$ret['error'] = __('Unable to open the log file.', 'wpvivid-backuprestore');
return $ret;
}
$buffer = '';
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
$ret['data'] = $buffer;
}
else{
$ret['error']='Unknown error';
}
return $ret;
}
public function read_last_backup_log($log_file_name){
global $wpvivid_plugin;
if(!isset($log_file_name)||empty($log_file_name)||!is_string($log_file_name))
{
$ret['result']='failed';
$ret['error']=__('Reading the log failed. Please try again.', 'wpvivid-backuprestore');
return $ret;
}
$log_file_name=sanitize_text_field($log_file_name);
$ret=$wpvivid_plugin->function_realize->_get_log_file('lastlog', $log_file_name);
if($ret['result'] == 'success') {
$file = fopen($ret['log_file'], 'r');
if (!$file) {
$ret['result'] = 'failed';
$ret['error'] = __('Unable to open the log file.', 'wpvivid-backuprestore');
return $ret;
}
$buffer = '';
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
$ret['result'] = 'success';
$ret['data'] = $buffer;
}
else{
$ret['error']='Unknown error';
}
return $ret;
}
public function view_backup_task_log($backup_task_id){
global $wpvivid_plugin;
if (!isset($backup_task_id)||empty($backup_task_id)||!is_string($backup_task_id)){
$ret['error']='Reading the log failed. Please try again.';
return $ret;
}
$backup_task_id = sanitize_key($backup_task_id);
$ret=$wpvivid_plugin->function_realize->_get_log_file('tasklog', $backup_task_id);
if($ret['result'] == 'success') {
$file = fopen($ret['log_file'], 'r');
if (!$file) {
$ret['result'] = 'failed';
$ret['error'] = __('Unable to open the log file.', 'wpvivid-backuprestore');
return $ret;
}
$buffer = '';
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
$ret['result'] = 'success';
$ret['data'] = $buffer;
}
else{
$ret['error']='Unknown error';
}
return $ret;
}
public function backup_cancel($task_id = ''){
global $wpvivid_plugin;
$ret=$wpvivid_plugin->function_realize->_backup_cancel();
return $ret;
}
public function init_download_page($backup_id){
global $wpvivid_plugin;
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id)) {
$ret['error']='Invalid parameter param:'.$backup_id;
return $ret;
}
else {
$backup_id=sanitize_key($backup_id);
return $wpvivid_plugin->init_download($backup_id);
}
}
public function prepare_download_backup($backup_id, $file_name){
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id))
{
$ret['error']='Invalid parameter param:'.$backup_id;
return $ret;
}
if(!isset($file_name)||empty($file_name)||!is_string($file_name))
{
$ret['error']='Invalid parameter param:'.$file_name;
return $ret;
}
$download_info=array();
$download_info['backup_id']=sanitize_key($backup_id);
$download_info['file_name'] = $file_name;
@set_time_limit(600);
if (session_id())
session_write_close();
try
{
$downloader=new WPvivid_downloader();
$downloader->ready_download($download_info);
}
catch (Exception $e)
{
$message = 'A exception ('.get_class($e).') occurred '.$e->getMessage().' (Code: '.$e->getCode().', line '.$e->getLine().' in '.$e->getFile().')';
error_log($message);
return array('error'=>$message);
}
catch (Error $e)
{
$message = 'A error ('.get_class($e).') has occurred: '.$e->getMessage().' (Code: '.$e->getCode().', line '.$e->getLine().' in '.$e->getFile().')';
error_log($message);
return array('error'=>$message);
}
$ret['result']='success';
return $ret;
}
public function get_download_task($backup_id){
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id)) {
$ret['error']='Invalid parameter param:'.$backup_id;
return $ret;
}
else {
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
if ($backup === false) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'backup id not found';
return $ret;
}
$backup_item = new WPvivid_Backup_Item($backup);
$ret = $backup_item->update_download_page($backup_id);
return $ret;
}
}
public function download_backup($backup_id, $file_name){
global $wpvivid_plugin;
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id)) {
$ret['error']='Invalid parameter param: backup_id';
return $ret;
}
if(!isset($file_name)||empty($file_name)||!is_string($file_name)) {
$ret['error']='Invalid parameter param: file_name';
return $ret;
}
$backup_id=sanitize_key($backup_id);
$cache=WPvivid_taskmanager::get_download_cache($backup_id);
if($cache===false) {
$wpvivid_plugin->init_download($backup_id);
$cache=WPvivid_taskmanager::get_download_cache($backup_id);
}
$path=false;
if(array_key_exists($file_name,$cache['files'])) {
if($cache['files'][$file_name]['status']=='completed') {
$path=$cache['files'][$file_name]['download_path'];
$download_url = $cache['files'][$file_name]['download_url'];
}
}
if($path!==false) {
if (file_exists($path)) {
$ret['download_url'] = $download_url;
$ret['size'] = filesize($path);
}
}
return $ret;
}
public function set_general_setting($setting){
$ret=array();
try {
if(isset($setting)&&!empty($setting)) {
$json_setting = $setting;
$json_setting = stripslashes($json_setting);
$setting = json_decode($json_setting, true);
if (is_null($setting)) {
$ret['error']='bad parameter';
return $ret;
}
WPvivid_Setting::update_setting($setting);
}
$ret['result']='success';
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('error'=>$message);
}
return $ret;
}
public function set_schedule($schedule){
$ret=array();
try {
if(isset($schedule)&&!empty($schedule)) {
$json = $schedule;
$json = stripslashes($json);
$schedule = json_decode($json, true);
if (is_null($schedule)) {
$ret['error']='bad parameter';
return $ret;
}
$ret=WPvivid_Schedule::set_schedule_ex($schedule);
if($ret['result']!='success') {
return $ret;
}
}
$ret['result']='success';
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('error'=>$message);
}
return $ret;
}
public function set_remote($remote){
global $wpvivid_plugin;
$ret=array();
try {
if(isset($remote)&&!empty($remote)) {
$json = $remote;
$json = stripslashes($json);
$remote = json_decode($json, true);
if (is_null($remote)) {
$ret['error']='bad parameter';
return $ret;
}
$wpvivid_plugin->function_realize->_set_remote($remote);
}
$ret['result']='success';
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('error'=>$message);
}
return $ret;
}
} includes/index.php 0000644 00000000032 15132770567 0010202 0 ustar 00 <?php // Silence is golden includes/staging/class-wpvivid-staging-log.php 0000644 00000023660 15132770567 0015547 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Staging_Log_Free
{
public $log_file;
public $log_file_handle;
public function __construct()
{
$this->log_file_handle=false;
}
public function CreateLogFile($file_name,$type,$describe)
{
if($type=='has_folder')
{
$this->log_file=$file_name;
}
else
{
$this->log_file=$this->GetSaveLogFolder().$file_name.'_log.txt';
}
if(file_exists($this->log_file))
{
@wp_delete_file( $this->log_file);
}
$this->log_file_handle = fopen($this->log_file, 'a');
$offset=get_option('gmt_offset');
$time =gmdate("Y-m-d H:i:s",time()+$offset*60*60);
$text='Log created: '.$time."\n";
$text.='Type: '.$describe."\n";
fwrite($this->log_file_handle,$text);
return $this->log_file;
}
public function OpenLogFile($file_name,$type='no_folder',$delete=0)
{
if($type=='has_folder')
{
$this->log_file=$file_name;
}
else
{
$this->log_file=$this->GetSaveLogFolder().$file_name.'_log.txt';
}
if($delete==1)
{
wp_delete_file( $this->log_file);
}
$this->log_file_handle = fopen($this->log_file, 'a');
return $this->log_file;
}
public function WriteLog($log,$type)
{
if ($this->log_file_handle)
{
$offset=get_option('gmt_offset');
$time =gmdate("Y-m-d H:i:s",time()+$offset*60*60);
$text='['.$time.']'.'['.$type.']'.$log."\n";
fwrite($this->log_file_handle,$text );
}
}
public function CloseFile()
{
if ($this->log_file_handle)
{
fclose($this->log_file_handle);
$this->log_file_handle=false;
}
}
public function GetSaveLogFolder()
{
if(!is_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'wpvivid_staging'))
{
@mkdir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'wpvivid_staging',0777,true);
@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'wpvivid_staging'.DIRECTORY_SEPARATOR.'index.html', 'x');
$tempfile=@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'wpvivid_staging'.DIRECTORY_SEPARATOR.'.htaccess', 'x');
if($tempfile)
{
//$text="deny from all";
$text="<IfModule mod_rewrite.c>\r\nRewriteEngine On\r\nRewriteRule .* - [F,L]\r\n</IfModule>";
fwrite($tempfile,$text );
}
}
return WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'wpvivid_staging'.DIRECTORY_SEPARATOR;
}
public function WriteLogHander()
{
if ($this->log_file_handle)
{
global $wp_version;
global $wpdb;
$sapi_type=php_sapi_name();
if($sapi_type=='cgi-fcgi'||$sapi_type==' fpm-fcgi') {
$fcgi='On';
}
else {
$fcgi='Off';
}
$options=get_option('wpvivid_staging_options',array());
if(isset($options['max_execution_time']))
{
$max_execution_time=$options['staging_max_execution_time'];
}
else {
$max_execution_time=900;
}
$log='server info fcgi:'.$fcgi.' max execution time: '.$max_execution_time.' wp version:'.$wp_version.' php version:'.phpversion().' db version:'.$wpdb->db_version().' php ini:safe_mode:'.ini_get('safe_mode').' ';
$log.='memory_limit:'.ini_get('memory_limit').' memory_get_usage:'.size_format(memory_get_usage(),2).' memory_get_peak_usage:'.size_format(memory_get_peak_usage(),2);
$log.=' extensions:';
$loaded_extensions = get_loaded_extensions();
if(!in_array('PDO', $loaded_extensions))
{
$log.='PDO not enabled ';
}
else
{
$log.='PDO enabled ';
}
if(!in_array('curl', $loaded_extensions))
{
$log.='curl not enabled ';
}
else
{
$log.='curl enabled ';
}
if(!in_array('zlib', $loaded_extensions)) {
$log .= 'zlib not enabled ';
}
else
{
$log.='zlib enabled ';
}
$log.=' ';
if(is_multisite())
{
$log.=' is_multisite:1';
}
else
{
$log.=' is_multisite:0';
}
$offset=get_option('gmt_offset');
$time =gmdate("Y-m-d H:i:s",time()+$offset*60*60);
$text='['.$time.']'.'[notice]'.$log."\n";
fwrite($this->log_file_handle,$text );
}
}
}
class WPvivid_Staging_error_log_free
{
public static function create_error_log($log_file_name)
{
$dir=dirname($log_file_name);
$file=basename($log_file_name);
if(!is_dir($dir.DIRECTORY_SEPARATOR.'error'))
{
@mkdir($dir.DIRECTORY_SEPARATOR.'error',0777,true);
@fopen($dir.DIRECTORY_SEPARATOR.'error'.'/index.html', 'x');
$tempfile=@fopen($dir.DIRECTORY_SEPARATOR.'error'.'/.htaccess', 'x');
if($tempfile)
{
//$text="deny from all";
$text="<IfModule mod_rewrite.c>\r\nRewriteEngine On\r\nRewriteRule .* - [F,L]\r\n</IfModule>";
fwrite($tempfile,$text );
@fclose($tempfile);
}
}
if(!file_exists($log_file_name))
{
return ;
}
if(file_exists($dir.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file))
{
@wp_delete_file($dir.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file);
}
@rename($log_file_name,$dir.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file);
//self::delete_oldest_error_log();
}
public static function create_restore_error_log($log_file_name)
{
$dir=dirname($log_file_name);
if(!is_dir($dir.DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'error'))
{
@mkdir($dir.DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'error',0777,true);
@fopen($dir.DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'error'.'/index.html', 'x');
$tempfile=@fopen($dir.DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'error'.'/.htaccess', 'x');
if($tempfile)
{
//$text="deny from all";
$text="<IfModule mod_rewrite.c>\r\nRewriteEngine On\r\nRewriteRule .* - [F,L]\r\n</IfModule>";
fwrite($tempfile,$text );
@fclose($tempfile);
}
}
$id = uniqid('wpvivid-');
$file=$id.'_restore_log.txt';
if(file_exists($dir.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file))
{
@wp_delete_file($dir.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file);
}
@copy($log_file_name,$dir.DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file);
//self::delete_oldest_error_log();
}
public static function delete_oldest_error_log()
{
$files=array();
$log=new WPvivid_Staging_Log_Free();
$dir=$log->GetSaveLogFolder();
$dir=$dir.'error';
@$handler=opendir($dir);
if($handler===false)
return;
$regex='#^wpvivid.*_log.txt#';
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.DIRECTORY_SEPARATOR.$filename))
{
continue;
}else{
if(preg_match($regex,$filename))
{
$files[$filename] = $dir.DIRECTORY_SEPARATOR.$filename;
}
}
}
}
if($handler)
@closedir($handler);
$oldest=0;
$oldest_filename='';
$max_count=5;
if(sizeof($files)>$max_count)
{
foreach ($files as $file)
{
if($oldest==0)
{
$oldest=filemtime($file);
$oldest_filename=$file;
}
else
{
if($oldest>filemtime($file))
{
$oldest=filemtime($file);
$oldest_filename=$file;
}
}
}
if($oldest_filename!='')
{
@wp_delete_file($oldest_filename);
}
}
}
public static function get_error_log()
{
$log=new WPvivid_Staging_Log_Free();
$dir=$log->GetSaveLogFolder();
$dir=$dir.'error';
$files=array();
$handler=opendir($dir);
if($handler === false){
return $files;
}
$regex='#^wpvivid.*_log.txt#';
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.$filename))
{
continue;
}
else{
if(preg_match($regex,$filename))
{
$files[] = $dir.DIRECTORY_SEPARATOR.$filename;
}
}
}
}
if($handler)
@closedir($handler);
return $files;
}
} includes/staging/class-wpvivid-staging-copy-db-ex.php 0000644 00000167474 15132770567 0016751 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Staging_Copy_DB
{
public $task;
public $db_src_instance;
public $db_des_instance;
public $old_prefix;
public $replace_prefix;
public $new_prefix;
public $old_site_url;
public $old_home_url;
public $new_site_url;
public $new_home_url;
public $replacing_table;
public $placeholder;
public $path_site;
public function __construct($task_id)
{
$this->task=new WPvivid_Staging_Task($task_id);
$this->db_src_instance=false;
$this->db_des_instance=false;
$this->placeholder=array();
add_filter('wpvivid_restore_db_skip_replace_tables', array($this, 'skip_tables'),10,2);
add_filter('wpvivid_restore_db_skip_replace_rows', array($this, 'skip_rows'),10,3);
}
public function skip_tables($skip_table,$table_name)
{
$skip_tables[]='adrotate_stats';
$skip_tables[]='login_security_solution_fail';
$skip_tables[]='icl_strings';
$skip_tables[]='icl_string_positions';
$skip_tables[]='icl_string_translations';
$skip_tables[]='icl_languages_translations';
$skip_tables[]='slim_stats';
$skip_tables[]='slim_stats_archive';
$skip_tables[]='es_online';
$skip_tables[]='ahm_download_stats';
$skip_tables[]='woocommerce_order_items';
$skip_tables[]='woocommerce_sessions';
$skip_tables[]='redirection_404';
$skip_tables[]='redirection_logs';
$skip_tables[]='wbz404_logs';
$skip_tables[]='wbz404_redirects';
$skip_tables[]='Counterize';
$skip_tables[]='Counterize_UserAgents';
$skip_tables[]='Counterize_Referers';
$skip_tables[]='et_bloom_stats';
$skip_tables[]='term_relationships';
$skip_tables[]='lbakut_activity_log';
$skip_tables[]='simple_feed_stats';
$skip_tables[]='svisitor_stat';
$skip_tables[]='itsec_log';
$skip_tables[]='relevanssi_log';
$skip_tables[]='wysija_email_user_stat';
$skip_tables[]='wponlinebackup_generations';
$skip_tables[]='blc_instances';
$skip_tables[]='wp_rp_tags';
$skip_tables[]='statpress';
$skip_tables[]='wfHits';
$skip_tables[]='wp_wfFileMods';
$skip_tables[]='tts_trafficstats';
$skip_tables[]='tts_referrer_stats';
$skip_tables[]='dmsguestbook';
$skip_tables[]='relevanssi';
$skip_tables[]='wfFileMods';
$skip_tables[]='learnpress_sessions';
$skip_tables[]='icl_string_pages';
$skip_tables[]='webarx_event_log';
$skip_tables[]='duplicator_packages';
$skip_tables[]='wsal_metadata';
$skip_tables[]='wsal_occurrences';
if(in_array(substr($table_name, strlen($this->new_prefix)),$skip_tables))
{
$skip_table=true;
}
else
{
$skip_table=false;
}
return $skip_table;
}
public function skip_rows($skip_rows,$table_name,$column_name)
{
$row['table_name']='posts';
$row['column_name']='guid';
$rows[]=$row;
$row['table_name']='options';
$row['column_name']='mainwp_child_subpages';
$rows[]=$row;
foreach ($rows as $row)
{
if($column_name==$row['column_name']&&$table_name==$this->new_prefix.$row['table_name'])
{
$skip_rows=true;
break;
}
}
return $skip_rows;
}
public function do_copy_db()
{
global $wpvivid_plugin;
$this->db_src_instance=false;
$this->db_des_instance=false;
if($this->task->is_restore())
$this->new_prefix=$this->task->get_temp_prefix();
else
$this->new_prefix=$this->task->get_db_prefix(true);
$this->old_prefix=$this->task->get_db_prefix();
if(!$this->init_copy_tables_list())
return false;
$table=$this->task->get_start('db');
$this->task->update_calc_db_size('db');
while($table&&!$table['finished'])
{
$ret=$this->copy_table($table,$this->task->get_db_insert_count());
if($ret['result']=='failed')
{
$this->task->set_error($ret['error']);
return false;
}
if(!$table['finished'])
{
$wpvivid_plugin->staging->log->WriteLog('Copying '.$this->task->get_db_insert_count().' queries is completed.','notice');
$wpvivid_plugin->staging->log->WriteLog('The next copying table info: '.wp_json_encode($table),'notice');
}
$this->task->update_table('db',$table);
}
if($this->task->get_start('db')===false)
{
$wpvivid_plugin->staging->log->WriteLog('Copying '.$table['name'].' is completed.','notice');
$this->task->update_calc_db_finish_size('db');
$wpvivid_plugin->staging->log->WriteLog('Database copying is completed.','notice');
$this->task->update_job_finished('db');
}
else
{
$wpvivid_plugin->staging->log->WriteLog('Copying '.$table['name'].' is completed.','notice');
$this->task->update_table_finished('db',$table);
$this->task->update_calc_db_finish_size('db');
}
return true;
}
public function do_replace_db()
{
global $wpvivid_plugin;
$this->replace_prefix=$this->task->get_temp_prefix();
$this->new_prefix=$this->task->get_db_prefix(true);
$this->old_prefix=$this->task->get_db_prefix();
$this->old_site_url= $this->task->get_site_url();
$this->old_home_url= $this->task->get_home_url();
$this->new_site_url=$this->task->get_site_url(true);
$this->new_home_url=$this->task->get_home_url(true);
if(!$this->init_replace_tables_list())
return false;
$table=$this->task->get_start('db_replace');
$this->task->update_calc_db_size('db_replace');
while($table&&!$table['finished'])
{
$ret=$this->replace_table($table,$this->task->get_db_replace_count());
if($ret['result']=='failed')
{
$this->task->set_error($ret['error']);
return false;
}
if(!$table['finished'])
{
$wpvivid_plugin->staging->log->WriteLog($this->task->get_db_replace_count().' queries of '.$table['name'].' is replaced.','notice');
$wpvivid_plugin->staging->log->WriteLog('The next replacing table info: '.wp_json_encode($table),'notice');
}
$this->task->update_table('db_replace',$table);
}
$wpvivid_plugin->staging->log->WriteLog('Replacing '.$table['name'].' is completed.','notice');
$this->task->update_table_finished('db_replace',$table);
$this->task->update_calc_db_finish_size('db_replace');
if($this->task->get_start('db_replace')===false)
{
if(!$this->task->is_restore())
{
$this->set_staging_site_data();
}
//$this->set_staging_site_data();
$wpvivid_plugin->staging->log->WriteLog('Replacing database is completed.','notice');
$this->task->update_job_finished('db_replace');
}
return true;
}
public function do_rename_db()
{
global $wpvivid_plugin;
$this->replace_prefix=$this->task->get_temp_prefix();
$this->new_prefix=$this->task->get_db_prefix(true);
$this->old_prefix=$this->task->get_db_prefix();
$this->old_site_url= $this->task->get_site_url();
$this->old_home_url= $this->task->get_home_url();
$this->new_site_url=$this->task->get_site_url(true);
$this->new_home_url=$this->task->get_home_url(true);
if(!$this->init_rename_tables_list())
return false;
$table=$this->task->get_start('db_rename');
$this->task->update_calc_db_size('db_rename');
while($table)
{
$ret= $this->rename_table($table);
if($ret['result']=='failed')
{
$this->task->set_error($ret['error']);
return false;
}
$wpvivid_plugin->staging->log->WriteLog('Rename '.$table['name'].' is completed.','notice');
$this->task->update_table_finished('db_rename',$table);
$table=$this->task->get_start('db_rename');
$this->task->update_calc_db_finish_size('db_rename');
}
$this->set_staging_site_data();
$wpvivid_plugin->staging->log->WriteLog('Rename tables is completed.','notice');
$this->task->update_job_finished('db_rename');
return true;
}
public function set_staging_site_data()
{
global $wpvivid_plugin;
$db=$this->get_db_instance(true);
$prefix=$this->new_prefix;
$query=$db->prepare("UPDATE {$prefix}options SET option_value = %s WHERE option_name = 'siteurl' or option_name='home'",$this->new_site_url);
if ($db->get_results($query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$update_query=$db->prepare("UPDATE {$prefix}options SET option_value = %s WHERE option_name = 'rewrite_rules'", '');
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$update_query=$db->prepare("INSERT INTO {$prefix}options (option_name,option_value) VALUES ('wpvivid_staging_finish',%d)", 1);
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$is_overwrite_permalink_structure = $this->task->get_is_overwrite_permalink_structure();
if($is_overwrite_permalink_structure == 0)
{
if(!$this->task->is_restore()){
$update_query = $db->prepare("INSERT INTO {$prefix}options (option_name,option_value) VALUES ('wpvivid_staging_init',%d)", 1);
}
else{
$permalink_structure = $this->task->get_permalink_structure();
$update_query = $db->prepare("INSERT INTO {$prefix}options (option_name,option_value) VALUES ('wpvivid_staging_init',%s)", $permalink_structure);
}
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($db->get_results($update_query) === false) {
$error = $db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
}
if($this->task->is_restore())
{
delete_option('wpvivid_staging_data');
update_option('blog_public','1');
$push_staging_history = $this->task->get_push_staging_history();
update_option('wpvivid_push_staging_history', $push_staging_history,'no');
if($this->task->get_site_mu_single())
{
switch_to_blog( $this->task->get_site_mu_single_site_id());
delete_option('wpvivid_staging_data');
delete_option('wpvivid_staging_finish');
delete_option('wpvivid_staging_init');
restore_current_blog();
}
}
else
{
$data['id']=$this->task->get_id();
$data['name']=$this->task->get_path(true);
$data['prefix']= $prefix;
$admin_url = apply_filters('wpvividstg_get_admin_url', '');
$admin_url .= 'admin.php?page='.apply_filters('wpvivid_white_label_slug', 'WPvivid');
$data['parent_admin_url']=$admin_url;
$data['live_site_url']=home_url();
$data['live_site_staging_url']=apply_filters('wpvividstg_get_admin_url', '').'admin.php?page='.apply_filters('wpvivid_white_label_plugin_name', 'WPvivid_Staging');
$data=serialize($data);
$update_query = $db->prepare("INSERT INTO {$prefix}options (option_name,option_value) VALUES ('wpvivid_staging_data',%s)", $data);
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$update_query =$db->prepare("UPDATE {$prefix}options SET option_value = %s WHERE option_name = 'blog_public'", '0');
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$delete_query = $db->prepare("DELETE FROM {$prefix}options WHERE option_name = %s", 'wpvivid_backup_list');
$wpvivid_plugin->staging->log->WriteLog($delete_query, 'notice');
if ($db->get_results($delete_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
}
if(!$this->task->is_restore())
{
$permalink = get_option( 'permalink_structure','');
$update_query = $db->prepare("UPDATE {$prefix}options SET option_value = %s WHERE option_name = 'permalink_structure'", $permalink);
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
}
$update_query =$db->prepare("UPDATE {$prefix}options SET option_value = %s WHERE option_name = 'upload_path'", "");
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
if($this->task->is_mu_single()&&!$this->task->is_restore())
{
if($this->task->is_mu_single())
{
switch_to_blog($this->task->get_mu_single_site_id());
$current = get_option( 'active_plugins', array() );
restore_current_blog();
}
else
{
$current = get_option('active_plugins',array());
}
if(!in_array('wpvivid-backuprestore/wpvivid-backuprestore.php',$current))
$current[] = 'wpvivid-backuprestore/wpvivid-backuprestore.php.php';
sort( $current );
$value=serialize($current);
$update_query = $db->prepare("UPDATE {$prefix}options SET option_value=%s WHERE option_name='active_plugins'" , $value);
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
}
}
public function init_replace_tables_list()
{
if(empty($this->task->get_tables('db_replace')))
{
global $wpvivid_plugin;
$wpvivid_plugin->staging->log->WriteLog('Retrieve the tables required to replace.','notice');
$tables=array();
$db=$this->get_db_instance(true);
$copyed_tables=$this->task->get_tables('db');
foreach ($copyed_tables as $table)
{
global $wpdb;
if($this->task->is_mu_single()&&($table['name']==$wpdb->base_prefix.'users'||$table['name']==$wpdb->base_prefix.'usermeta'))
{
$og_table_name=$this->str_replace_limit($wpdb->base_prefix,'',$table['name'], 1);
$new_table_name=$this->replace_prefix.$og_table_name;
}
else
{
$og_table_name=$this->str_replace_limit($this->old_prefix,'',$table['name'], 1);
$new_table_name=$this->replace_prefix.$og_table_name;
}
//$og_table_name=$this->str_replace_limit($this->old_prefix,'',$table['name'], 1);
//$new_table_name=$this->replace_prefix.$og_table_name;
if(!$this->task->is_tables_exclude($new_table_name,$this->replace_prefix))
{
$table['name']=$new_table_name;
$table['start']=0;
$table['finished']=0;
$tables[$new_table_name]=$table;
}
}
/*
$sql=$db->prepare("SHOW TABLES LIKE %s;", $db->esc_like($this->replace_prefix) . '%');
$result = $db->get_results($sql, OBJECT_K);
if($result===false)
{
$error='Failed to retrieve database tables, error:'.$db->last_error;
$wpvivid_staging->log->WriteLog($error,'error');
$this->task->set_error($error);
return false;
}
if(empty($result))
{
$error='Tables not found in database.';
$wpvivid_staging->log->WriteLog($error,'error');
$this->task->set_error($error);
return false;
}
foreach ($result as $table_name=>$value)
{
if(!$this->task->is_tables_exclude($table_name,$this->replace_prefix))
{
$table['name']=$table_name;
$table['start']=0;
$table['finished']=0;
$tables[$table_name]=$table;
}
}*/
//$wpvivid_staging->log->WriteLog(wp_json_encode($tables),'test');
$this->task->update_tables('db_replace',$tables);
}
return true;
}
public function init_copy_tables_list()
{
if(empty($this->task->get_tables('db')))
{
global $wpvivid_plugin;
$wpvivid_plugin->staging->log->WriteLog('Retrieve the tables required to copy.','notice');
$tables=array();
$db=$this->get_db_instance(false);
$sql=$db->prepare("SHOW TABLES LIKE %s;", $db->esc_like($this->old_prefix) . '%');
$result = $db->get_results($sql, OBJECT_K);
if($result===false)
{
$error='Failed to retrieve database tables, error:'.$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error,'error');
$this->task->set_error($error);
return false;
}
if(empty($result))
{
$error='Tables not found in database.';
$wpvivid_plugin->staging->log->WriteLog($error,'error');
$this->task->set_error($error);
return false;
}
foreach ($result as $table_name=>$value)
{
if(!$this->task->is_tables_exclude($table_name))
{
$table['name']=$table_name;
$table['create']=0;
$table['start']=0;
$table['finished']=0;
$tables[$table_name]=$table;
}
}
if($this->task->is_mu_single())
{
global $wpdb;
$sql=$db->prepare("SHOW TABLES LIKE %s;", $db->esc_like($wpdb->base_prefix) . '%');
$result = $db->get_results($sql, OBJECT_K);
foreach ($result as $table_name=>$value)
{
if(!$this->task->is_tables_exclude($table_name))
{
$table['name']=$table_name;
$table['create']=0;
$table['start']=0;
$table['finished']=0;
$tables[$table_name]=$table;
}
}
}
global $wpdb;
$all_tables = (array) $wpdb->get_results( "SHOW FULL TABLES", ARRAY_N );
if(!empty($all_tables) && !empty($tables)){
foreach ($tables as $table_name => $table){
foreach ($all_tables as $table_arr){
if($table_name === $table_arr[0] && $table_arr[1] === 'VIEW'){
unset($tables[$table_name]);
}
}
}
}
$this->task->update_tables('db',$tables);
}
return true;
}
public function init_rename_tables_list()
{
if(empty($this->task->get_tables('db_rename')))
{
global $wpvivid_plugin;
$wpvivid_plugin->staging->log->WriteLog('Retrieve the tables required to rename.','notice');
$tables=array();
$db=$this->get_db_instance(true);
$sql=$db->prepare("SHOW TABLES LIKE %s;", $db->esc_like($this->replace_prefix) . '%');
$result = $db->get_results($sql, OBJECT_K);
if($result===false)
{
$error='Failed to retrieve database tables, error:'.$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error,'error');
$this->task->set_error($error);
return false;
}
if(empty($result))
{
$error='Tables not found in database.';
$wpvivid_plugin->staging->log->WriteLog($error,'error');
$this->task->set_error($error);
return false;
}
foreach ($result as $table_name=>$value)
{
$table['name']=$table_name;
$table['start']=0;
$table['finished']=0;
$tables[$table_name]=$table;
}
$this->task->update_tables('db_rename',$tables);
}
return true;
}
public function get_db_instance($des=false)
{
$db=$this->task->get_db_connect();
if($des)
{
if( $this->db_des_instance===false)
{
if($db['des_use_additional_db']===false)
{
global $wpdb;
$this->db_des_instance=$wpdb;
return $this->db_des_instance;
}
else
{
$this->db_des_instance=new wpdb($db['des_dbuser'],$db['des_dbpassword'],$db['des_dbname'],$db['des_dbhost']);
return $this->db_des_instance;
}
}
else
{
return $this->db_des_instance;
}
}
else
{
if( $this->db_src_instance===false)
{
if($db['src_use_additional_db']===false)
{
global $wpdb;
$this->db_src_instance=$wpdb;
return $this->db_src_instance;
}
else
{
$this->db_src_instance=new wpdb($db['src_dbuser'],$db['src_dbpassword'],$db['src_dbname'],$db['src_dbhost']);
return $this->db_src_instance;
}
}
else
{
return $this->db_src_instance;
}
}
}
public function is_same_database()
{
$db=$this->task->get_db_connect();
if( $db['des_use_additional_db']||$db['src_use_additional_db'])
{
return false;
}
else
{
return true;
}
}
public function copy_table(&$table,$count)
{
$ret['result']='success';
if($table==false)
{
return $ret;
}
if($table['create']==0)
{
$ret=$this->create_table($table['name']);
if($ret['result']=='success')
{
$table['create']=1;
}
else
{
return $ret;
}
}
return $this->copy_table_data($table,$count);
}
function str_replace_limit($search, $replace, $subject, $limit=-1)
{
if (is_array($search)) {
foreach ($search as $k=>$v) {
$search[$k] = '`' . preg_quote($search[$k],'`') . '`';
}
}
else {
$search = '`' . preg_quote($search,'`') . '`';
}
return preg_replace($search, $replace, $subject, $limit);
}
public function create_table($table_name)
{
global $wpvivid_plugin,$wpdb;
if($this->task->is_mu_single()&&($table_name==$wpdb->base_prefix.'users'||$table_name==$wpdb->base_prefix.'usermeta'))
{
$og_table_name=$this->str_replace_limit($wpdb->base_prefix,'',$table_name, 1);
$new_table_name=$this->new_prefix.$og_table_name;
}
else
{
$og_table_name=$this->str_replace_limit($this->old_prefix,'',$table_name, 1);
$new_table_name=$this->new_prefix.$og_table_name;
}
$new_db=$this->get_db_instance(true);
$old_db=$this->get_db_instance();
$query = $old_db->prepare( 'SHOW TABLES LIKE %s', $new_db->esc_like( $new_table_name ) );
if ( $new_db->get_var( $query ) == $new_table_name )
{
$new_db->query('SET foreign_key_checks = 0');
$new_db->query("DROP TABLE IF EXISTS {$new_table_name}");
}
$result = $old_db->get_results( "SHOW CREATE TABLE `{$table_name}`", ARRAY_A );
if( isset($result[0]['Create Table']))
{
$query=$result[0]['Create Table'];
$query = str_replace( "CREATE TABLE `{$table_name}`", "CREATE TABLE `{$new_table_name}`", $query );
$query = preg_replace_callback( "/CONSTRAINT\s`(\w+)`/", function()
{
$new="CONSTRAINT `" . uniqid() . "`";
return $new;
}, $query );
$query = preg_replace_callback( "/REFERENCES\s`(\w+)`/", function($matches)
{
$new=str_replace($this->old_prefix,$this->new_prefix,$matches[0]);
return $new;
}, $query );
$new_db->query('SET FOREIGN_KEY_CHECKS=0;');
if( false === $new_db->query( $query ) )
{
$error='Failed to create a table. Error:'.$new_db->last_error.', query:'.$query;
$wpvivid_plugin->staging->log->WriteLog($error,'error');
$ret['result']='failed';
$ret['error']=$error;
}
else
{
$ret['result']='success';
}
}
else
{
$error='Failed to retrieve the table structure. Table name: '.$table_name;
$wpvivid_plugin->staging->log->WriteLog($error,'error');
$ret['result']='failed';
$ret['error']=$error;
}
return $ret;
}
public function copy_table_data(&$table,$count)
{
$ret['result']='success';
$new_db=$this->get_db_instance(true);
$old_db=$this->get_db_instance();
global $wpdb;
if($this->task->is_mu_single()&&($table['name']==$wpdb->base_prefix.'users'||$table['name']==$wpdb->base_prefix.'usermeta'))
{
$og_table_name=$this->str_replace_limit($wpdb->base_prefix,'',$table['name'], 1);
$new_table_name=$this->new_prefix.$og_table_name;
}
else
{
$og_table_name=$this->str_replace_limit($this->old_prefix,'',$table['name'], 1);
$new_table_name=$this->new_prefix.$og_table_name;
}
$old_table_name=$table['name'];
$sum =$old_db->get_var("SELECT COUNT(1) FROM `{$old_table_name}`");
if($sum==0)
{
$table['finished']=1;
return $ret;
}
$limit = " LIMIT {$count} OFFSET {$table['start']}";
$new_db->query('SET FOREIGN_KEY_CHECKS=0;');
if($this->is_same_database())
{
$select = "SELECT * FROM `{$old_table_name}` {$limit}";
if($new_db->query( "INSERT INTO `{$new_table_name}` ".$select )===false)
{
$error='Failed to insert '.$new_table_name.', error: '.$new_db->last_error;
global $wpvivid_plugin;
$wpvivid_plugin->staging->log->WriteLog($error,'warning');
$start =$new_db->get_var("SELECT COUNT(1) FROM `{$new_table_name}`");
if($start===false)
{
$ret['result']='failed';
$ret['error']=$error;
return $ret;
}
global $wpvivid_plugin;
$wpvivid_plugin->staging->log->WriteLog('new start offset '.$start,'warning');
$limit = " LIMIT {$count} OFFSET {$start}";
$select = "SELECT * FROM `{$old_table_name}` {$limit}";
if($new_db->query( "INSERT INTO `{$new_table_name}` ".$select )===false)
{
$error='Failed to insert '.$new_table_name.', error: '.$new_db->last_error;
global $wpvivid_plugin;
$wpvivid_plugin->staging->log->WriteLog($error,'error');
$ret['result']='failed';
$ret['error']=$error;
return $ret;
}
else
{
$table['start']=$start;
}
}
}
else
{
$rows = $old_db->get_results( "SELECT * FROM `{$old_table_name}` {$limit}", ARRAY_A );
foreach ( $rows as $row )
{
if($new_db->insert($new_table_name,$row)===false)
{
//global $wpvivid_staging;
//$error='Failed to insert '.$new_table_name.', error: '.$new_db->last_error;
}
}
}
$table['start'] += $count;
if( $table['start'] > $sum )
{
$table['finished']=1;
}
return $ret;
}
public function replace_table(&$table,$count)
{
$ret['result']='success';
global $wpvivid_plugin;
$this->replacing_table=$table['name'];
$db=$this->get_db_instance(true);
if(substr($table['name'], strlen($this->replace_prefix))=='usermeta')
{
if($this->old_prefix!=$this->new_prefix)
{
$update_query ='UPDATE '.$table['name'].' SET meta_key=REPLACE(meta_key,"'.$this->old_prefix.'","'.$this->new_prefix.'") WHERE meta_key LIKE "'.str_replace('_','\_',$this->old_prefix).'%";';
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
$wpvivid_plugin->staging->log->WriteLog('The length of UPDATE statement: '.strlen($update_query), 'notice');
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$table['finished']=1;
if($this->task->is_mu_single())
{
global $wpdb;
$update_query ='UPDATE '.$table['name'].' SET meta_key=REPLACE(meta_key,"'.$wpdb->base_prefix.'","'.$this->new_prefix.'") WHERE meta_key LIKE "'.str_replace('_','\_',$wpdb->base_prefix).'%";';
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
$wpvivid_plugin->staging->log->WriteLog('The length of UPDATE statement: '.strlen($update_query), 'notice');
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
}
return $ret;
}
}
if(is_multisite())
{
if(substr($table['name'], strlen($this->replace_prefix))=='blogs')
{
$wpvivid_plugin->staging->log->WriteLog('update mu blogs', 'notice');
if((preg_match('#^https?://([^/]+)#i', $this->new_home_url, $matches) || preg_match('#^https?://([^/]+)#i', $this->new_site_url, $matches)) && (preg_match('#^https?://([^/]+)#i', $this->old_home_url, $old_matches) || preg_match('#^https?://([^/]+)#i', $this->old_site_url, $old_matches)))
{
$new_string = strtolower($matches[1]);
$old_string = strtolower($old_matches[1]);
$query = 'SELECT * FROM `'.$table['name'].'`';
$result=$db->get_results($query,ARRAY_A);
if($result && sizeof($result)>0)
{
$rows = $result;
$mu_option=$this->task->get_mu_option();
$wpvivid_plugin->staging->log->WriteLog(wp_json_encode($mu_option), 'notice');
foreach ($rows as $row)
{
$update=array();
$where=array();
$old_domain_data = $row['domain'];
$new_domain_data=str_replace($old_string,$new_string,$old_domain_data);
$temp_where='`blog_id` = "' . $row['blog_id'] . '"';
if (is_callable(array($db, 'remove_placeholder_escape')))
$temp_where = $db->remove_placeholder_escape($temp_where);
$where[] = $temp_where;
$update[] = '`domain` = "' . $new_domain_data . '"';
$new_path_data=$mu_option['site'][$row['blog_id']]['path_site'];
$update[] = '`path` = "' . $new_path_data . '"';
if(!empty($update)&&!empty($where))
{
$update_query = 'UPDATE `'.$table['name'].'` SET '.implode(', ', $update).' WHERE '.implode(' AND ', array_filter($where)).';';
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
$db->get_results($update_query);
}
}
}
}
}
}
$skip_table=false;
if(apply_filters('wpvivid_restore_db_skip_replace_tables',$skip_table,$table['name']))
{
$wpvivid_plugin->staging->log->WriteLog('Ignore table '.$table['name'], 'Warning');
$table['finished']=1;
return $ret;
}
if(preg_match('/aiowps_audit_log/i', $table['name']) || preg_match('/aiowps_debug_log/i', $table['name']))
{
$wpvivid_plugin->staging->log->WriteLog('Skip replace table '.$table['name'], 'Warning');
$table['finished']=1;
return $ret;
}
$sum =$db->get_var("SELECT COUNT(1) FROM `{$table['name']}`");
if($sum>0)
{
$query='DESCRIBE `'.$table['name'].'`';
$result=$db->get_results($query,ARRAY_A);
if($result===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
$table['finished']=1;
return $ret;
}
$columns=array();
foreach ($result as $data)
{
$column['Field']=$data['Field'];
if($data['Key']=='PRI')
$column['PRI']=1;
else
$column['PRI']=0;
if($data['Type']=='mediumblob')
{
$column['skip']=1;
}
$columns[]=$column;
}
$update_query='';
$start_row=$table['start'];
$wpvivid_plugin->staging->log->WriteLog('Start replacing the table prefix from '.$start_row. ' row.', 'notice');
$end_row=$count;
$query = 'SELECT * FROM `'.$table['name'].'` LIMIT '.$start_row.', '.$end_row;
$result=$db->get_results($query,ARRAY_A);
if($result && sizeof($result)>0)
{
$rows = $result;
foreach ($rows as $row)
{
if( isset( $row['option_value'] ) && strlen( $row['option_value'] ) >= 5000000 )
{
continue;
}
$update=array();
$where=array();
foreach ($columns as $column)
{
if(isset($column['skip']))
{
//$wpvivid_plugin->staging->log->WriteLog('Skip MEDIUMBLOB data.', 'notice');
continue;
}
if($column['Field']=='option_name'&&$row[$column['Field']]=='mainwp_child_subpages')
{
break;
}
$old_data = $row[$column['Field']];
$size = strlen( $old_data );
if( $size >= 5000000 )
{
continue;
}
if($column['PRI']==1)
{
$db->escape_by_ref($old_data);
$temp_where='`'.$column['Field'].'` = "' . $old_data . '"';
if (is_callable(array($db, 'remove_placeholder_escape')))
$temp_where = $db->remove_placeholder_escape($temp_where);
$where[] = $temp_where;
}
$skip_row=false;
if(apply_filters('wpvivid_restore_db_skip_replace_rows',$skip_row,$table['name'],$column['Field']))
{
continue;
}
$new_data=$this->replace_row_data($old_data);
if($new_data==$old_data)
continue;
$db->escape_by_ref($new_data);
if (is_callable(array($db, 'remove_placeholder_escape')))
$new_data = $db->remove_placeholder_escape($new_data);
$update[] = '`'.$column['Field'].'` = "' . $new_data . '"';
}
if(!empty($update)&&!empty($where))
{
$temp_query = 'UPDATE `'.$table['name'].'` SET '.implode(', ', $update).' WHERE '.implode(' AND ', array_filter($where)).';';
$update_query=$temp_query;
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$update_query='';
}
}
}
if(!empty($update_query))
{
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
}
}
$wpvivid_plugin->staging->log->WriteLog('Replacing database tables is completed.', 'notice');
$table['start'] += $count;
if( $table['start'] > $sum )
{
$table['finished']=1;
}
if($table['finished'])
{
if(substr($table['name'], strlen($this->replace_prefix))=='options')
{
$update_query ='UPDATE '.$table['name'].' SET option_name="'.$this->new_prefix.'user_roles" WHERE option_name="'.$this->old_prefix.'user_roles";';
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
$wpvivid_plugin->staging->log->WriteLog('The length of UPDATE statement: '.strlen($update_query), 'notice');
if ($db->get_results($update_query)===false)
{
$error=$db->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
}
}
return $ret;
}
public function replace_row_data($old_data)
{
$unserialize_data = @unserialize($old_data, array('allowed_classes' => false));
if($unserialize_data===false)
{
$old_data=$this->replace_string_v2($old_data);
}
else
{
$old_data=$this->replace_serialize_data($unserialize_data);
$old_data=serialize($old_data);
}
return $old_data;
}
private function replace_serialize_data($data,$serialized = false)
{
if(is_serialized( $data ) && ( $serialize_data = @unserialize( $data, array('allowed_classes' => false) ) ) !== false)
{
$data=$this->replace_serialize_data($serialize_data,true);
}
else if(is_array($data))
{
foreach ($data as $key => $value)
{
$data[$key]=$this->replace_serialize_data($value);
}
}
else if(is_object($data))
{
$temp = $data; // new $data_class();
if (is_a($data, '__PHP_Incomplete_Class'))
{
}
else
{
$props = get_object_vars($data);
foreach ($props as $key => $value)
{
if (strpos($key, "\0")===0)
continue;
$temp->$key = $this->replace_serialize_data($value);
}
}
$data = $temp;
unset($temp);
}
else if(is_string($data))
{
$data=$this->replace_string_v2($data);
}
if($serialized)
$data=serialize($data);
return $data;
}
public function get_mix_link($url)
{
if (0 === stripos($url, 'https://'))
{
$mix_link = 'http://'.substr($url, 8);
} elseif (0 === stripos($url, 'http://')) {
$mix_link = 'https://'.substr($url, 7);
}
else
{
$mix_link=false;
}
return $mix_link;
}
public function get_remove_http_link($url)
{
if (0 === stripos($url, 'https://'))
{
$mix_link = '//'.substr($url, 8);
} elseif (0 === stripos($url, 'http://')) {
$mix_link = '//'.substr($url, 7);
}
else
{
$mix_link=false;
}
return $mix_link;
}
public function get_remove_http_link_ex($url)
{
if (0 === stripos($url, 'https://'))
{
$mix_link = '\/\/'.substr($url, 8);
} elseif (0 === stripos($url, 'http://')) {
$mix_link = '\/\/'.substr($url, 7);
}
else
{
$mix_link=false;
}
return $mix_link;
}
public function replace_string_v2($old_string)
{
if(!is_string($old_string))
{
return $old_string;
}
$from=array();
$to=array();
$new_url_use_https=false;
if (0 === stripos($this->new_site_url, 'https://')|| stripos($this->new_site_url, 'https:\/\/'))
{
$new_url_use_https=true;
}
else if (0 === stripos($this->new_site_url, 'http://')|| stripos($this->new_site_url, 'http:\/\/'))
{
$new_url_use_https=false;
}
$prefix=$this->replace_prefix;
if($this->old_site_url!=$this->new_site_url)
{
if(substr($this->replacing_table, strlen($prefix))=='posts'||substr($this->replacing_table, strlen($prefix))=='postmeta'||substr($this->replacing_table, strlen($prefix))=='options')
{
$remove_http_link=$this->get_remove_http_link($this->old_site_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link($this->new_site_url);
$from[]=$remove_http_link;
$to[]=$new_remove_http_link;
if($new_url_use_https)
{
$from[]='http:'.$new_remove_http_link;
$to[]='https:'.$new_remove_http_link;
}
else
{
$from[]='https:'.$new_remove_http_link;
$to[]='http:'.$new_remove_http_link;
}
$quote_old_site_url=$this->get_http_link_at_quote($remove_http_link);
$quote_new_site_url=$this->get_http_link_at_quote($new_remove_http_link);
$from[]=$quote_old_site_url;
$to[]=$quote_new_site_url;
if($new_url_use_https)
{
$from[]='http:'.$quote_new_site_url;
$to[]='https:'.$quote_new_site_url;
}
else
{
$from[]='https:'.$quote_new_site_url;
$to[]='http:'.$quote_new_site_url;
}
}
else
{
$remove_http_link=$this->get_remove_http_link_ex($this->old_site_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link_ex($this->new_site_url);
$from[]=$remove_http_link;
$to[]=$new_remove_http_link;
if($new_url_use_https)
{
$from[]='http:'.$new_remove_http_link;
$to[]='https:'.$new_remove_http_link;
}
else
{
$from[]='https:'.$new_remove_http_link;
$to[]='http:'.$new_remove_http_link;
}
}
}
}
else
{
$from[]=$this->old_site_url;
$to[]=$this->new_site_url;
}
}
if($this->old_home_url!=$this->old_site_url&&$this->old_home_url!=$this->new_home_url)
{
if(substr($this->replacing_table, strlen($prefix))=='posts'||substr($this->replacing_table, strlen($prefix))=='postmeta'||substr($this->replacing_table, strlen($prefix))=='options')
{
$remove_http_link=$this->get_remove_http_link($this->old_home_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link($this->new_home_url);
$from[]=$remove_http_link;
$to[]=$new_remove_http_link;
if($new_url_use_https)
{
$from[]='http:'.$new_remove_http_link;
$to[]='https:'.$new_remove_http_link;
}
else
{
$from[]='https:'.$new_remove_http_link;
$to[]='http:'.$new_remove_http_link;
}
$quote_old_site_url=$this->get_http_link_at_quote($remove_http_link);
$quote_new_site_url=$this->get_http_link_at_quote($new_remove_http_link);
$from[]=$quote_old_site_url;
$to[]=$quote_new_site_url;
if($new_url_use_https)
{
$from[]='http:'.$quote_new_site_url;
$to[]='https:'.$quote_new_site_url;
}
else
{
$from[]='https:'.$quote_new_site_url;
$to[]='http:'.$quote_new_site_url;
}
}
else
{
$remove_http_link=$this->get_remove_http_link_ex($this->old_home_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link_ex($this->new_home_url);
$from[]=$remove_http_link;
$to[]=$new_remove_http_link;
if($new_url_use_https)
{
$from[]='http:'.$new_remove_http_link;
$to[]='https:'.$new_remove_http_link;
}
else
{
$from[]='https:'.$new_remove_http_link;
$to[]='http:'.$new_remove_http_link;
}
}
}
}
else
{
$from[]=$this->old_home_url;
$to[]=$this->new_home_url;
}
}
if(!empty($from)&&!empty($to))
{
$old_string=str_replace($from,$to,$old_string);
}
return $old_string;
}
public function replace_string($old_string)
{
if(!is_string($old_string))
{
return $old_string;
}
$from=array();
$to=array();
if($this->old_site_url!=$this->new_site_url)
{
$remove_http_link=$this->get_remove_http_link($this->old_site_url);
$new_remove_http_link=$this->get_remove_http_link($this->new_site_url);
if(strpos($new_remove_http_link,$remove_http_link)!==false)
{
return $this->replace_string_ex($old_string);
}
}
if($this->old_site_url!=$this->new_site_url)
{
$from[]=$this->old_site_url;
$to[]=$this->new_site_url;
$old_mix_link=$this->get_mix_link($this->old_site_url);
if($old_mix_link!==false)
{
$from[]=$old_mix_link;
$to[]=$this->new_site_url;
}
if(substr($this->replacing_table, strlen($this->new_prefix))=='posts'||substr($this->replacing_table, strlen($this->new_prefix))=='postmeta'||substr($this->replacing_table, strlen($this->new_prefix))=='options')
{
$remove_http_link=$this->get_remove_http_link($this->old_site_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link($this->new_site_url);
$from[]=$remove_http_link;
$to[]=$new_remove_http_link;
$quote_old_site_url=$this->get_http_link_at_quote($remove_http_link);
$quote_new_site_url=$this->get_http_link_at_quote($new_remove_http_link);
$from[]=$quote_old_site_url;
$to[]=$quote_new_site_url;
}
$remove_http_link=$this->get_remove_http_link_ex($this->old_site_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link_ex($this->new_site_url);
$from[]=$remove_http_link;
$to[]=$new_remove_http_link;
$quote_old_site_url=$this->get_http_link_at_quote($remove_http_link);
$quote_new_site_url=$this->get_http_link_at_quote($new_remove_http_link);
$from[]=$quote_old_site_url;
$to[]=$quote_new_site_url;
}
}
$quote_old_site_url=$this->get_http_link_at_quote($this->old_site_url);
$quote_new_site_url=$this->get_http_link_at_quote($this->new_site_url);
$from[]=$quote_old_site_url;
$to[]=$quote_new_site_url;
}
if($this->old_home_url!=$this->new_home_url)
{
$from[]=$this->old_home_url;
$to[]=$this->new_home_url;
$old_mix_link=$this->get_mix_link($this->old_home_url);
if($old_mix_link!==false)
{
$from[]=$old_mix_link;
$to[]=$this->new_home_url;
}
}
if(!empty($from)&&!empty($to))
{
$old_string=str_replace($from,$to,$old_string);
}
return $old_string;
}
public function replace_string_ex($old_string)
{
if(!is_string($old_string))
{
return $old_string;
}
$from=array();
$place_holder=array();
$to=array();
if($this->old_site_url!=$this->new_site_url)
{
$remove_http_link=$this->get_remove_http_link($this->old_site_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link($this->new_site_url);
$from[]=$remove_http_link;
//$place_holder[]=$this->get_place_holder(0);
$to[]=$new_remove_http_link;
$quote_old_site_url=$this->get_http_link_at_quote($remove_http_link);
$quote_new_site_url=$this->get_http_link_at_quote($new_remove_http_link);
$from[]=$quote_old_site_url;
//$place_holder[]=$this->get_place_holder(3);
$to[]=$quote_new_site_url;
}
$old_mix_link=$this->get_mix_link($this->old_site_url);
if($old_mix_link!==false)
{
$from[]=$old_mix_link;
//$place_holder[]=$this->get_place_holder(1);
$to[]=$this->new_site_url;
}
if(substr($this->replacing_table, strlen($this->new_prefix))=='posts'||substr($this->replacing_table, strlen($this->new_prefix))=='postmeta'||substr($this->replacing_table, strlen($this->new_prefix))=='options')
{
$remove_http_link=$this->get_remove_http_link_ex($this->old_site_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link_ex($this->new_site_url);
$from[]=$remove_http_link;
//$place_holder[]=$this->get_place_holder(2);
$to[]=$new_remove_http_link;
$quote_old_site_url=$this->get_http_link_at_quote($remove_http_link);
$quote_new_site_url=$this->get_http_link_at_quote($new_remove_http_link);
$from[]=$quote_old_site_url;
//$place_holder[]=$this->get_place_holder(3);
$to[]=$quote_new_site_url;
}
}
$quote_old_site_url=$this->get_http_link_at_quote($this->old_site_url);
$quote_new_site_url=$this->get_http_link_at_quote($this->new_site_url);
$from[]=$quote_old_site_url;
//$place_holder[]=$this->get_place_holder(3);
$to[]=$quote_new_site_url;
}
if($this->old_home_url!=$this->new_home_url&&$this->old_home_url!=$this->old_site_url)
{
$from[]=$this->old_home_url;
//$place_holder[]=$this->get_place_holder(4);
$to[]=$this->new_home_url;
$old_mix_link=$this->get_mix_link($this->old_home_url);
if($old_mix_link!==false)
{
$from[]=$old_mix_link;
//$place_holder[]=$this->get_place_holder(5);
$to[]=$this->new_home_url;
}
}
if(!empty($from)&&!empty($to))
{
//$old_string=str_replace($from,$place_holder,$old_string);
$old_string=str_replace($from,$to,$old_string);
}
return $old_string;
}
public function get_place_holder($index)
{
if ( empty($this->placeholder) )
{
for($i=0;$i<6;$i++)
{
// If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
$algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
// Old WP installs may not have AUTH_SALT defined.
$salt = defined( 'AUTH_SALT' ) && AUTH_SALT ? AUTH_SALT : (string) wp_rand();
$this->placeholder[$i] = '{' . hash_hmac( $algo, uniqid( $salt, true ), $salt ) . '}';
}
}
return $this->placeholder[$index];
}
public function get_http_link_at_quote($url)
{
return str_replace('/','\/',$url);
}
private function rename_table(&$table)
{
global $wpvivid_plugin;
$table_name=$table['name'];
$tasks=array();
$og_table=$this->new_prefix.substr($table_name, strlen($this->replace_prefix));
$db=$this->get_db_instance(true);
$db->query('SET FOREIGN_KEY_CHECKS=0;');
if(substr($table_name, strlen($this->replace_prefix))=='options')
{
$tasks = get_option('wpvivid_staging_task_list', array());
}
$wpvivid_plugin->staging->log->WriteLog('DROP TABLE '.$og_table,'notice');
if($db->query("DROP TABLE IF EXISTS {$og_table}")===false)
{
$wpvivid_plugin->staging->log->WriteLog('Failed to drop table '.$og_table.', error:'.$db->last_error,'notice');
}
$wpvivid_plugin->staging->log->WriteLog('Rename a table named '.$table_name.' to '.$og_table.' ','notice');
if ($db->query("RENAME TABLE {$table_name} TO {$og_table}")===false)
{
$wpvivid_plugin->staging->log->WriteLog('Failed to rename a table named '.$table_name.' to '.$og_table.', error: '.$db->last_error,'notice');
}
if(substr($table_name, strlen($this->replace_prefix))=='options')
{
wp_cache_delete ( 'alloptions', 'options' );
update_option('wpvivid_staging_task_list',$tasks,'no');
}
$table['finished']=1;
$ret['result']='success';
return $ret;
}
} includes/staging/class-wpvivid-staging-setting.php 0000644 00000075742 15132770567 0016453 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Staging_Setting_Free
{
public $main_tab;
public function __construct()
{
add_action('wp_ajax_wpvividstg_save_setting', array($this, 'save_setting'));
add_filter('wpvivid_add_setting_tab_page', array($this, 'add_setting_tab_page'), 10);
add_action('wpvivid_setting_add_staging_cell',array($this, 'output_staging_setting_cell'),10);
add_filter('wpvivid_set_general_setting', array($this, 'set_general_setting'), 12, 3);
}
public function add_setting_tab_page($setting_array)
{
$setting_array['staging_setting'] = array('index' => '3', 'tab_func' => array($this, 'add_tab_staging'), 'page_func' => array($this, 'add_page_staging'));
return $setting_array;
}
public function add_tab_staging()
{
?>
<a href="#" id="wpvivid_tab_staging_setting" class="nav-tab setting-nav-tab" onclick="switchsettingTabs(event,'page-staging-setting')"><?php esc_html_e('Staging Settings', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function add_page_staging()
{
?>
<div class="setting-tab-content wpvivid_tab_staging_setting" id="page-staging-setting" style="margin-top: 10px; display: none;">
<?php do_action('wpvivid_setting_add_staging_cell'); ?>
</div>
<?php
}
public function output_staging_setting_cell()
{
$options=get_option('wpvivid_staging_options',array());
$staging_db_insert_count = isset($options['staging_db_insert_count']) ? $options['staging_db_insert_count'] : 10000;
$staging_db_replace_count = isset($options['staging_db_replace_count']) ? $options['staging_db_replace_count'] : 5000;
$staging_file_copy_count = isset($options['staging_file_copy_count']) ? $options['staging_file_copy_count'] : 500;
$staging_exclude_file_size = isset($options['staging_exclude_file_size']) ? $options['staging_exclude_file_size'] : 30;
$staging_memory_limit = isset($options['staging_memory_limit']) ? $options['staging_memory_limit'] : '256M';
$staging_memory_limit = str_replace('M', '', $staging_memory_limit);
$staging_max_execution_time= isset($options['staging_max_execution_time']) ? $options['staging_max_execution_time'] : 900;
$staging_resume_count = isset($options['staging_resume_count']) ? $options['staging_resume_count'] : 6;
$staging_request_timeout = isset($options['staging_request_timeout']) ? $options['staging_request_timeout'] : 1500;
$staging_keep_setting = isset($options['staging_keep_setting']) ? $options['staging_keep_setting'] : true;
$staging_not_need_login=isset($options['not_need_login']) ? $options['not_need_login'] : true;
if($staging_not_need_login)
{
$staging_not_need_login_check='checked';
}
else
{
$staging_not_need_login_check='';
}
$staging_overwrite_permalink = isset($options['staging_overwrite_permalink']) ? $options['staging_overwrite_permalink'] : true;
if($staging_overwrite_permalink){
$staging_overwrite_permalink_check = 'checked';
}
else{
$staging_overwrite_permalink_check = '';
}
if($staging_keep_setting)
{
$staging_keep_setting='checked';
}
else
{
$staging_keep_setting='';
}
?>
<div style="margin-top: 10px;">
<div class="postbox schedule-tab-block wpvivid-setting-addon" style="margin-bottom: 10px; padding-bottom: 0;">
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('DB Copy Count', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_db_insert_count" value="<?php echo esc_attr($staging_db_insert_count); ?>"
placeholder="10000" onkeyup="value=value.replace(/\D/g,'')" />
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'Number of DB rows, that are copied within one ajax query. The higher value makes the database copy process faster.
Please try a high value to find out the highest possible value. If you encounter timeout errors, try lower values until no
more errors occur.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('DB Replace Count', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_db_replace_count" value="<?php echo esc_attr($staging_db_replace_count); ?>"
placeholder="5000" onkeyup="value=value.replace(/\D/g,'')" />
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'Number of DB rows, that are processed within one ajax query. The higher value makes the DB replacement process faster.
If timeout erros occur, decrease the value because this process consumes a lot of memory.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('File Copy Count', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_file_copy_count" value="<?php echo esc_attr($staging_file_copy_count); ?>"
placeholder="500" onkeyup="value=value.replace(/\D/g,'')" />
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'Number of files to copy that will be copied within one ajax request. The higher value makes the file copy process faster.
Please try a high value to find out the highest possible value. If you encounter timeout errors, try lower values until no more errors occur.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('Max File Size', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_exclude_file_size" value="<?php echo esc_attr($staging_exclude_file_size); ?>"
placeholder="30" onkeyup="value=value.replace(/\D/g,'')" />MB
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'Maximum size of the files copied to a staging site. All files larger than this value will be ignored. If you set the value of 0 MB, all files will be copied to a staging site.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('Staging Memory Limit', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_memory_limit" value="<?php echo esc_attr($staging_memory_limit); ?>"
placeholder="256" onkeyup="value=value.replace(/\D/g,'')" />MB
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e('Adjust this value to apply for a temporary PHP memory limit for the plugin to create a staging site.
We set this value to 256M by default. Increase the value if you encounter a memory exhausted error. Note: some
web hosting providers may not support this.', 'wpvivid-backuprestore'); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('PHP Script Execution Timeout', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_max_execution_time" value="<?php echo esc_attr($staging_max_execution_time); ?>"
placeholder="900" onkeyup="value=value.replace(/\D/g,'')" />
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'The time-out is not your server PHP time-out. With the execution time exhausted, our plugin will shut down the progress of
creating a staging site. If the progress encounters a time-out, that means you have a medium or large sized website. Please try to
scale the value bigger.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('Delay Between Requests', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_request_timeout" value="<?php echo esc_attr($staging_request_timeout); ?>"
placeholder="1500" onkeyup="value=value.replace(/\D/g,'')" />ms
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'A lower value will help speed up the process of creating a staging site. However, if your server has a limit on the number of requests, a higher value is recommended.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom">
<strong><?php esc_html_e('Retrying', 'wpvivid-backuprestore'); ?> </strong>
<select option="setting" name="staging_resume_count">
<?php
for($resume_count=3; $resume_count<10; $resume_count++){
if($resume_count === $staging_resume_count){
echo '<option selected="selected" value="'.esc_attr($resume_count).'">'.esc_html($resume_count).'</option>';
}
else{
echo '<option value="'.esc_attr($resume_count).'">'.esc_html($resume_count).'</option>';
}
}
?>
</select><strong><?php esc_html_e(' times when encountering a time-out error', 'wpvivid-backuprestore'); ?></strong>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="checkbox" option="setting" name="not_need_login" <?php echo esc_attr($staging_not_need_login_check); ?> />
<span><strong><?php esc_html_e('Anyone can visit the staging site', 'wpvivid-backuprestore'); ?></strong></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<span><?php esc_html_e('When the option is checked, anyone will be able to visit the staging site without the need to login. Uncheck it to request a login to visit the staging site.', 'wpvivid-backuprestore'); ?></span>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="checkbox" option="setting" name="staging_overwrite_permalink" <?php echo esc_attr($staging_overwrite_permalink_check); ?> />
<span><strong><?php esc_html_e('Keep permalink when transferring website', 'wpvivid-backuprestore'); ?></strong></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<span><?php esc_html_e('When checked, this option allows you to keep the current permalink structure when you create a staging site or push a staging site to live.', 'wpvivid-backuprestore'); ?></span>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="checkbox" option="setting" name="staging_keep_setting" <?php echo esc_attr($staging_keep_setting); ?> />
<span><strong><?php esc_html_e('Keep staging sites when deleting the plugin', 'wpvivid-backuprestore'); ?></strong></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<span><?php esc_html_e('With this option checked, all staging sites you have created will be retained when the plugin is deleted, just in case you still need them later. The sites will show up again after the plugin is reinstalled.', 'wpvivid-backuprestore'); ?></span>
</div>
</div>
</div>
<?php
}
public function output_staging_setting()
{
?>
<div style="margin-top: 10px;">
<?php
$this->wpvivid_setting_add_staging_cell_addon();
?>
</div>
<?php
}
public function wpvivid_setting_add_staging_cell_addon()
{
$options=get_option('wpvivid_staging_options',array());
$staging_db_insert_count = isset($options['staging_db_insert_count']) ? $options['staging_db_insert_count'] : 10000;
$staging_db_replace_count = isset($options['staging_db_replace_count']) ? $options['staging_db_replace_count'] : 5000;
$staging_file_copy_count = isset($options['staging_file_copy_count']) ? $options['staging_file_copy_count'] : 500;
$staging_exclude_file_size = isset($options['staging_exclude_file_size']) ? $options['staging_exclude_file_size'] : 30;
$staging_memory_limit = isset($options['staging_memory_limit']) ? $options['staging_memory_limit'] : '256M';
$staging_memory_limit = str_replace('M', '', $staging_memory_limit);
$staging_max_execution_time= isset($options['staging_max_execution_time']) ? $options['staging_max_execution_time'] : 900;
$staging_resume_count = isset($options['staging_resume_count']) ? $options['staging_resume_count'] : 6;
$staging_request_timeout = isset($options['staging_request_timeout']) ? $options['staging_request_timeout'] : 1500;
$staging_keep_setting = isset($options['staging_keep_setting']) ? $options['staging_keep_setting'] : true;
$staging_not_need_login=isset($options['not_need_login']) ? $options['not_need_login'] : true;
if($staging_not_need_login)
{
$staging_not_need_login_check='checked';
}
else
{
$staging_not_need_login_check='';
}
$staging_overwrite_permalink = isset($options['staging_overwrite_permalink']) ? $options['staging_overwrite_permalink'] : true;
if($staging_overwrite_permalink){
$staging_overwrite_permalink_check = 'checked';
}
else{
$staging_overwrite_permalink_check = '';
}
if($staging_keep_setting)
{
$staging_keep_setting='checked';
}
else
{
$staging_keep_setting='';
}
?>
<div class="postbox schedule-tab-block wpvivid-setting-addon" style="margin-bottom: 10px; padding-bottom: 0;">
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('DB Copy Count', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_db_insert_count" value="<?php echo esc_attr($staging_db_insert_count); ?>"
placeholder="10000" onkeyup="value=value.replace(/\D/g,'')" />
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'Number of DB rows, that are copied within one ajax query. The higher value makes the database copy process faster.
Please try a high value to find out the highest possible value. If you encounter timeout errors, try lower values until no
more errors occur.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('DB Replace Count', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_db_replace_count" value="<?php echo esc_attr($staging_db_replace_count); ?>"
placeholder="5000" onkeyup="value=value.replace(/\D/g,'')" />
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'Number of DB rows, that are processed within one ajax query. The higher value makes the DB replacement process faster.
If timeout erros occur, decrease the value because this process consumes a lot of memory.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('File Copy Count', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_file_copy_count" value="<?php echo esc_attr($staging_file_copy_count); ?>"
placeholder="500" onkeyup="value=value.replace(/\D/g,'')" />
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'Number of files to copy that will be copied within one ajax request. The higher value makes the file copy process faster.
Please try a high value to find out the highest possible value. If you encounter timeout errors, try lower values until no more errors occur.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('Max File Size', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_exclude_file_size" value="<?php echo esc_attr($staging_exclude_file_size); ?>"
placeholder="30" onkeyup="value=value.replace(/\D/g,'')" />MB
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'Maximum size of the files copied to a staging site. All files larger than this value will be ignored. If you set the value of 0 MB, all files will be copied to a staging site.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('Staging Memory Limit', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_memory_limit" value="<?php echo esc_attr($staging_memory_limit); ?>"
placeholder="256" onkeyup="value=value.replace(/\D/g,'')" />MB
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e('Adjust this value to apply for a temporary PHP memory limit for the plugin to create a staging site.
We set this value to 256M by default. Increase the value if you encounter a memory exhausted error. Note: some
web hosting providers may not support this.', 'wpvivid-backuprestore'); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('PHP Script Execution Timeout', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_max_execution_time" value="<?php echo esc_attr($staging_max_execution_time); ?>"
placeholder="900" onkeyup="value=value.replace(/\D/g,'')" />
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'The time-out is not your server PHP time-out. With the execution time exhausted, our plugin will shut down the progress of
creating a staging site. If the progress encounters a time-out, that means you have a medium or large sized website. Please try to
scale the value bigger.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('Delay Between Requests', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input type="text" class="all-options" option="setting" name="staging_request_timeout" value="<?php echo esc_attr($staging_request_timeout); ?>"
placeholder="1500" onkeyup="value=value.replace(/\D/g,'')" />ms
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'A lower value will help speed up the process of creating a staging site. However, if your server has a limit on the number of requests, a higher value is recommended.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom">
<strong><?php esc_html_e('Retrying', 'wpvivid-backuprestore'); ?></strong>
<select option="setting" name="staging_resume_count">
<?php
for($resume_count=3; $resume_count<10; $resume_count++){
if($resume_count === $staging_resume_count){
echo '<option selected="selected" value="'.esc_attr($resume_count).'">'.esc_html($resume_count).'</option>';
}
else{
echo'<option value="'.esc_attr($resume_count).'">'.esc_html($resume_count).'</option>';
}
}
?>
</select><strong><?php esc_html_e(' times when encountering a time-out error', 'wpvivid-backuprestore'); ?></strong>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="checkbox" option="setting" name="not_need_login" <?php echo esc_attr($staging_not_need_login_check); ?> />
<span><strong><?php esc_html_e('Anyone can visit the staging site', 'wpvivid-backuprestore'); ?></strong></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<span><?php esc_html_e('When the option is checked, anyone will be able to visit the staging site without the need to login. Uncheck it to request a login to visit the staging site.', 'wpvivid-backuprestore'); ?></span>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="checkbox" option="setting" name="staging_overwrite_permalink" <?php echo esc_attr($staging_overwrite_permalink_check); ?> />
<span><strong><?php esc_html_e('Keep permalink when transferring website', 'wpvivid-backuprestore'); ?></strong></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<span><?php esc_html_e('When checked, this option allows you to keep the current permalink structure when you create a staging site or push a staging site to live.', 'wpvivid-backuprestore'); ?></span>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="checkbox" option="setting" name="staging_keep_setting" <?php echo esc_attr($staging_keep_setting); ?> />
<span><strong><?php esc_html_e('Keep staging sites when deleting the plugin', 'wpvivid-backuprestore'); ?></strong></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<span><?php esc_html_e('With this option checked, all staging sites you have created will be retained when the plugin is deleted, just in case you still need them later. The sites will show up again after the plugin is reinstalled.', 'wpvivid-backuprestore'); ?></span>
</div>
</div>
<div><input class="button-primary wpvividstg_save_setting" type="submit" value="<?php echo esc_attr( 'Save Changes'); ?>" /></div>
<script>
jQuery('.wpvividstg_save_setting').click(function()
{
wpvividstg_save_setting();
});
function wpvividstg_save_setting()
{
var setting_data = wpvivid_ajax_data_transfer('setting');
var ajax_data = {
'action': 'wpvividstg_save_setting',
'setting': setting_data,
};
jQuery('.wpvividstg_save_setting').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
jQuery('.wpvividstg_save_setting').css({'pointer-events': 'auto', 'opacity': '1'});
if (jsonarray.result === 'success')
{
location.href='<?php echo esc_url(apply_filters('wpvividstg_get_admin_url', '')) . 'admin.php?page=wpvividstg-setting'; ?>';
}
else {
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
jQuery('.wpvividstg_save_setting').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
jQuery('.wpvividstg_save_setting').css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = wpvivid_output_ajaxerror('changing base settings', textStatus, errorThrown);
alert(error_message);
});
}
</script>
<?php
}
public function set_general_setting($setting_data, $setting, $options)
{
$options=get_option('wpvivid_staging_options',array());
if(isset($setting['staging_db_insert_count']))
$options['staging_db_insert_count'] = intval($setting['staging_db_insert_count']);
if(isset($setting['staging_db_replace_count']))
$options['staging_db_replace_count'] = intval($setting['staging_db_replace_count']);
if(isset($setting['staging_file_copy_count']))
$options['staging_file_copy_count'] = intval($setting['staging_file_copy_count']);
if(isset($setting['staging_exclude_file_size']))
$options['staging_exclude_file_size'] = intval($setting['staging_exclude_file_size']);
if(isset($setting['staging_memory_limit']))
$options['staging_memory_limit'] = $setting['staging_memory_limit'].'M';
if(isset($setting['staging_max_execution_time']))
$options['staging_max_execution_time'] = intval($setting['staging_max_execution_time']);
if(isset($setting['staging_resume_count']))
$options['staging_resume_count'] = intval($setting['staging_resume_count']);
if(isset($setting['not_need_login']))
$options['not_need_login']= intval($setting['not_need_login']);
if(isset($setting['staging_overwrite_permalink']))
$options['staging_overwrite_permalink'] = intval($setting['staging_overwrite_permalink']);
if(isset($setting['staging_request_timeout']))
$options['staging_request_timeout']= intval($setting['staging_request_timeout']);
if(isset($setting['staging_keep_setting']))
$options['staging_keep_setting']= intval($setting['staging_keep_setting']);
update_option('wpvivid_staging_options',$options,'no');
return $setting_data;
}
public function save_setting()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$ret=array();
try
{
if(isset($_POST['setting'])&&!empty($_POST['setting']))
{
$json_setting = sanitize_text_field($_POST['setting']);
$json_setting = stripslashes($json_setting);
$setting = json_decode($json_setting, true);
if (is_null($setting))
{
echo 'json decode failed';
die();
}
$options=get_option('wpvivid_staging_options',array());
$options['staging_db_insert_count'] = intval($setting['staging_db_insert_count']);
$options['staging_db_replace_count'] = intval($setting['staging_db_replace_count']);
$options['staging_file_copy_count'] = intval($setting['staging_file_copy_count']);
$options['staging_exclude_file_size'] = intval($setting['staging_exclude_file_size']);
$options['staging_memory_limit'] = $setting['staging_memory_limit'].'M';
$options['staging_max_execution_time'] = intval($setting['staging_max_execution_time']);
$options['staging_resume_count'] = intval($setting['staging_resume_count']);
$options['not_need_login']= intval($setting['not_need_login']);
$options['staging_overwrite_permalink'] = intval($setting['staging_overwrite_permalink']);
$options['staging_request_timeout']= intval($setting['staging_request_timeout']);
$options['staging_keep_setting']= intval($setting['staging_keep_setting']);
update_option('wpvivid_staging_options',$options,'no');
$ret['result']='success';
}
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
} includes/staging/class-wpvivid-staging-copy-files-ex.php 0000644 00000066570 15132770567 0017461 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Staging_Copy_Files
{
public $task;
public $cache_file;
public $cache_file_name;
public function __construct($task_id)
{
$this->task=new WPvivid_Staging_Task($task_id);
$this->cache_file_name=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'wpvivid_staging'.DIRECTORY_SEPARATOR.$this->task->get_id().'_staging_cache.txt';
$this->cache_file=false;
}
public function do_copy_file($key)
{
global $wpvivid_plugin;
$src_path=$des_path='';
$wpvivid_plugin->staging->log->WriteLog('Retrieve the files required to copy.','notice');
$list=$this->get_copy_dir_list($key,$src_path,$des_path);
if(!file_exists($this->cache_file_name))
{
$wpvivid_plugin->staging->log->WriteLog('Create a cache file.','notice');
$this->create_cache_file($list);
}
$start=$this->task->get_start($key);
$wpvivid_plugin->staging->log->WriteLog('Copying files starts from: '.$start,'notice');
$wpvivid_plugin->staging->log->WriteLog('Copying files from '.$src_path.' to '.$des_path,'notice');
while($this->copy_files($start,$this->task->get_files_copy_count(),$src_path,$des_path))
{
$wpvivid_plugin->staging->log->WriteLog('The count of copied files: '.$this->task->get_files_copy_count(),'notice');
$wpvivid_plugin->staging->log->WriteLog('The next copying files starts from:'.$start,'notice');
$this->task->update_start($key,$start);
}
$wpvivid_plugin->staging->log->WriteLog('Copying '.$key.' files is completed.','notice');
if($key=='core')
{
$this->check_wp_config();
if(is_multisite()&&$this->task->is_restore())
{
}
else
{
$this->change_wp_config();
}
if(is_multisite()&&!$this->task->is_restore())
{
$this->change_htaccess();
}
}
$this->task->update_job_finished($key);
$this->clean_up();
return true;
}
public function check_wp_config()
{
$des_path=$this->task->get_path();
$des=$des_path.DIRECTORY_SEPARATOR.'wp-config.php';
if(file_exists($des))
{
return;
}
else
{
if ( file_exists( ABSPATH . 'wp-config.php' ) )
{
$src=ABSPATH . 'wp-config.php';
}
else if ( @file_exists( dirname( ABSPATH ) . '/wp-config.php' ))
{
$src=dirname( ABSPATH ) . '/wp-config.php';
}
else
{
global $wpvivid_plugin;
$wpvivid_plugin->staging->log->WriteLog('not found wp-config.php file','notice');
return ;
}
if(copy($src,$des))
{
@chmod($des,0755);
}
}
}
public function change_wp_config()
{
global $wpvivid_plugin;
$des_path=$this->task->get_path();
$path=$des_path.DIRECTORY_SEPARATOR.'wp-config.php';
$data=file_get_contents($path);
if( $data === false )
{
$wpvivid_plugin->staging->log->WriteLog('wp-config.php not found in '.$path,'notice');
return false;
}
$pattern = '/\$table_prefix\s*=\s*(.*)/';
$replacement = '$table_prefix = \'' . $this->task->get_db_prefix(true) . '\';';
$data = preg_replace( $pattern, $replacement, $data );
if( $data===null )
{
$wpvivid_plugin->staging->log->WriteLog('table_prefix not found in wp-config.php','notice');
return false;
}
preg_match( "/define\s*\(\s*['\"]WP_HOME['\"]\s*,\s*(.*)\s*\);/", $data, $matches );
if( !empty( $matches[1] ) )
{
$wpvivid_plugin->staging->log->WriteLog('WP_HOME found in wp-config.php','notice');
$pattern = "/define\s*\(\s*['\"]WP_HOME['\"]\s*,\s*(.*)\s*\);.*/";
$replace = "define('WP_HOME','" . $this->task->get_home_url(true) . "'); //";
$data = preg_replace( array($pattern), $replace, $data );
if( null === ($data) )
{
$wpvivid_plugin->staging->log->WriteLog('WP_HOME not replace in wp-config.php','notice');
return false;
}
}
preg_match( "/define\s*\(\s*['\"]WP_SITEURL['\"]\s*,\s*(.*)\s*\);/", $data, $matches );
if( !empty( $matches[1] ) )
{
$wpvivid_plugin->staging->log->WriteLog('WP_SITEURL found in wp-config.php','notice');
$pattern = "/define\s*\(\s*['\"]WP_SITEURL['\"]\s*,\s*(.*)\s*\);.*/";
$replace = "define('WP_SITEURL','" . $this->task->get_site_url(true) . "'); //";
$data = preg_replace( array($pattern), $replace, $data );
if( null === ($data) )
{
$wpvivid_plugin->staging->log->WriteLog('WP_SITEURL not replace in wp-config.php','notice');
return false;
}
}
if(is_multisite()&&!$this->task->is_restore())
{
preg_match( "/define\s*\(\s*['\"]PATH_CURRENT_SITE['\"]\s*,\s*(.*)\s*\);/", $data, $matches );
if( !empty( $matches[1] ) )
{
$mu_option=$this->task->get_mu_option();
$wpvivid_plugin->staging->log->WriteLog('PATH_CURRENT_SITE found in wp-config.php','notice');
$pattern = "/define\s*\(\s*['\"]PATH_CURRENT_SITE['\"]\s*,\s*(.*)\s*\);.*/";
$replace = "define('PATH_CURRENT_SITE','" .$mu_option['path_current_site'] . "'); //";
$data = preg_replace( array($pattern), $replace, $data );
if( null === ($data) )
{
$wpvivid_plugin->staging->log->WriteLog('PATH_CURRENT_SITE not replace in wp-config.php','notice');
return false;
}
}
if($this->task->is_mu_single())
{
preg_match( "/define\s*\(\s*['\"]WP_ALLOW_MULTISITE['\"]\s*,\s*(.*)\s*\);/", $data, $matches );
if( !empty( $matches[1] ) )
{
$wpvivid_plugin->staging->log->WriteLog('WP_ALLOW_MULTISITE found in wp-config.php','notice');
$pattern = "/define\s*\(\s*['\"]WP_ALLOW_MULTISITE['\"]\s*,\s*(.*)\s*\);.*/";
$replace = "define('WP_ALLOW_MULTISITE',false); //";
$data = preg_replace( array($pattern), $replace, $data );
if( null === ($data) )
{
$wpvivid_plugin->staging->log->WriteLog('WP_ALLOW_MULTISITE not replace in wp-config.php','notice');
return false;
}
}
preg_match( "/define\s*\(\s*['\"]MULTISITE['\"]\s*,\s*(.*)\s*\);/", $data, $matches );
if( !empty( $matches[1] ) )
{
$wpvivid_plugin->staging->log->WriteLog('MULTISITE found in wp-config.php','notice');
$pattern = "/define\s*\(\s*['\"]MULTISITE['\"]\s*,\s*(.*)\s*\);.*/";
$replace = "define('MULTISITE',false); //";
$data = preg_replace( array($pattern), $replace, $data );
if( null === ($data) )
{
$wpvivid_plugin->staging->log->WriteLog('MULTISITE not replace in wp-config.php','notice');
return false;
}
}
preg_match( "/define\s*\(\s*['\"]UPLOADS['\"]\s*,\s*(.*)\s*\);/", $data, $matches );
if( !empty( $matches[1] ) )
{
$wpvivid_plugin->staging->log->WriteLog('UPLOADS found in wp-config.php','notice');
$pattern = "/define\s*\(\s*['\"]UPLOADS['\"]\s*,\s*(.*)\s*\);.*/";
$replace = "define('UPLOADS','".$this->task->get_mu_single_upload()."'); //";
$data = preg_replace( array($pattern), $replace, $data );
if( null === ($data) )
{
$wpvivid_plugin->staging->log->WriteLog('MULTISITE not replace in wp-config.php','notice');
return false;
}
}
else
{
preg_match("/if\s*\(\s*\s*!\s*defined\s*\(\s*['\"]ABSPATH['\"]\s*(.*)\s*\)\s*\)/", $data, $matches);
if (!empty($matches[0]))
{
$matches[0];
$pattern = "/if\s*\(\s*\s*!\s*defined\s*\(\s*['\"]ABSPATH['\"]\s*(.*)\s*\)\s*\)/";
$replace = "define('UPLOADS', '".$this->task->get_mu_single_upload()."'); \n".
"if ( ! defined( 'ABSPATH' ) )";
$data = preg_replace( array($pattern), $replace, $data );
if (null === ($data))
{
$wpvivid_plugin->staging->log->WriteLog('UPLOADS not replace in wp-config.php','notice');
return false;
}
}
}
}
}
$db=$this->task->get_db_connect();
if($this->task->is_restore())
{
$wpvivid_plugin->staging->log->WriteLog('Edit wp-config.php','notice');
if( $db['src_use_additional_db'])
{
$pattern = "/define\s*\(\s*'DB_NAME'\s*,\s*(.*)\s*\);.*/";
$replacement = "define( 'DB_NAME', '".DB_NAME."');";
$data = preg_replace( $pattern, $replacement, $data );
$pattern = "/define\s*\(\s*'DB_USER'\s*,\s*(.*)\s*\);.*/";
$replacement = "define( 'DB_USER', '".DB_USER."');";
$data = preg_replace( $pattern, $replacement, $data );
$pattern = "/define\s*\(\s*'DB_PASSWORD'\s*,\s*(.*)\s*\);.*/";
$replacement = "define( 'DB_PASSWORD', '".DB_PASSWORD."');";
$data = preg_replace( $pattern, $replacement, $data );
$pattern = "/define\s*\(\s*'DB_HOST'\s*,\s*(.*)\s*\);.*/";
$replacement = "define( 'DB_HOST', '".DB_HOST."');";
$data = preg_replace( $pattern, $replacement, $data );
}
}
else
{
if( $db['des_use_additional_db'])
{
$pattern = "/define\s*\(\s*'DB_NAME'\s*,\s*(.*)\s*\);.*/";
$replacement = "define( 'DB_NAME', '{$db['des_dbname']}');";
$data = preg_replace( $pattern, $replacement, $data );
$pattern = "/define\s*\(\s*'DB_USER'\s*,\s*(.*)\s*\);.*/";
$replacement = "define( 'DB_USER', '{$db['des_dbuser']}');";
$data = preg_replace( $pattern, $replacement, $data );
$pattern = "/define\s*\(\s*'DB_PASSWORD'\s*,\s*(.*)\s*\);.*/";
$replacement = "define( 'DB_PASSWORD', '{$db['des_dbpassword']}');";
$data = preg_replace( $pattern, $replacement, $data );
$pattern = "/define\s*\(\s*'DB_HOST'\s*,\s*(.*)\s*\);.*/";
$replacement = "define( 'DB_HOST', '{$db['des_dbhost']}');";
$data = preg_replace( $pattern, $replacement, $data );
}
}
file_put_contents($path,$data);
$wpvivid_plugin->staging->log->WriteLog('Replacing table_prefix in wp-config.php is completed.','notice');
return true;
}
public function change_htaccess()
{
global $wpvivid_plugin;
$des_path=$this->task->get_path();
$path=$des_path.DIRECTORY_SEPARATOR.'.htaccess';
if(file_exists($path))
{
if(is_multisite()&&!$this->task->is_restore())
{
$mu_option=$this->task->get_mu_option();
$data=file_get_contents($path);
//$data = str_replace(PATH_CURRENT_SITE,$mu_option['path_current_site'],$data);
preg_match( "/RewriteBase\s*(.*)\s*/", $data, $matches );
if( !empty( $matches[1] ) )
{
$new_rewrite_base = $mu_option['path_current_site'];
$wpvivid_plugin->staging->log->WriteLog('RewriteBase found in .htaccess','notice');
$pattern = "/RewriteBase\s*(.*)\s*.*/";
$replace = "RewriteBase $new_rewrite_base";
$data = preg_replace( array($pattern), $replace, $data );
if( null === ($data) )
{
$wpvivid_plugin->staging->log->WriteLog('WP_HOME not replace in wp-config.php','notice');
}
}
file_put_contents($path,$data);
}
}
}
public function get_copy_dir_list($key,&$src_path,&$des_path)
{
$list=array();
if($key=='core')
{
$src_path=$this->task->get_path(false);
$des_path=$this->task->get_path(true);
$dir_info['root']=$this -> transfer_path($src_path);
$dir_info['recursive']=false;
if($this->task->is_restore()&&is_multisite())
{
$exclude_files_regex[]='#.htaccess#';
$exclude_files_regex[]='#wp-config.php#';
$dir_info['exclude_files_regex']=$exclude_files_regex;
}
$list[]=$dir_info;
$dir_info['root']=$src_path.DIRECTORY_SEPARATOR.'wp-admin';
$dir_info['recursive']=true;
$list[]=$dir_info;
$dir_info['root']=$src_path.DIRECTORY_SEPARATOR.'wp-includes';
$list[]=$dir_info;
}
else if($key=='wp-content')
{
$des_path=$this->get_content_dir(true);
$src_path=untrailingslashit($this->get_content_dir());
$dir_info['root']=$this -> transfer_path($src_path);
$dir_info['recursive']=true;
$exclude_regex=$this->task->get_job_option($key,'exclude_regex');
$exclude_files_regex=$this->task->get_job_option($key,'exclude_files_regex');
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_content_dir()).DIRECTORY_SEPARATOR.'updraft', '/').'#'; // Updraft Plus backup directory
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_content_dir()).DIRECTORY_SEPARATOR.'ai1wm-backups', '/').'#'; // All-in-one WP migration backup directory
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_content_dir()).DIRECTORY_SEPARATOR.'backups', '/').'#'; // Xcloner backup directory
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_content_dir()).DIRECTORY_SEPARATOR.'upgrade', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_content_dir()).DIRECTORY_SEPARATOR.'wpvivid', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_content_dir()).DIRECTORY_SEPARATOR.'wpvivid_staging', '/').'#';
//$exclude_regex[]='#^'.preg_quote($this->transfer_path($this->get_content_dir()), '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_content_dir()).DIRECTORY_SEPARATOR.'cache', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_content_dir()).DIRECTORY_SEPARATOR.'w3tc-config', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_content_dir()).DIRECTORY_SEPARATOR.'Dropbox_Backup', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_upload_dir()), '/').'#';
$exclude_regex[]='#^'.preg_quote($this->transfer_path($this->get_theme_dir()), '/').'#';
$exclude_regex[]='#^'.preg_quote($this->transfer_path($this->get_plugin_dir()), '/').'#';
//$self_dir = str_replace($src_path, '', $this -> transfer_path($des_path));
//$self_dir = str_replace('wp-content', '', $self_dir);
//$self_dir = str_replace('\\', '', $self_dir);
//$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_content_dir()).DIRECTORY_SEPARATOR.$self_dir, '/').'#';
$staging_list = get_option('wpvivid_staging_task_list',array());
if(!empty($staging_list))
{
foreach ($staging_list as $key => $value)
{
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($value['path']['des_path']), '/').'$#';
}
}
$dir_info['exclude_regex']=$exclude_regex;
$dir_info['exclude_files_regex']=$exclude_files_regex;
$list[]=$dir_info;
}
else if($key=='plugins')
{
$des_path=$this->get_plugin_dir(true);
$src_path=untrailingslashit($this->get_plugin_dir());
$dir_info['root']=$this -> transfer_path($src_path);
$exclude_regex=$this->task->get_job_option($key,'exclude_regex');
if($this->task->is_restore())
{
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_plugin_dir().DIRECTORY_SEPARATOR.'wpvivid-backuprestore'), '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_plugin_dir().DIRECTORY_SEPARATOR.'wpvivid-staging'), '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($this->get_plugin_dir().DIRECTORY_SEPARATOR.'wpvivid-backup-pro'), '/').'#';
}
$dir_info['exclude_regex']=$exclude_regex;
$dir_info['recursive']=true;
$list[]=$dir_info;
}
else if($key=='theme')
{
$des_path=$this->get_theme_dir(true);
$src_path=$this->get_theme_dir();
$dir_info['root']=$this -> transfer_path($src_path);
$dir_info['exclude_regex']=$this->task->get_job_option($key,'exclude_regex');
$dir_info['recursive']=true;
$list[]=$dir_info;
}
else if($key=='upload')
{
$des_path=$this->get_upload_dir(true);
$src_path=$this->get_upload_dir();
$dir_info['root']=$this -> transfer_path($src_path);
$dir_info['exclude_regex']=$this->task->get_job_option($key,'exclude_regex');
$exclude_files_regex=$this->task->get_job_option($key,'exclude_files_regex');
if($this->task->get_job_option($key,'include_regex'))
{
$dir_info['include_regex']=$this->task->get_job_option($key,'include_regex');
}
$dir_info['exclude_files_regex']=$exclude_files_regex;
$dir_info['recursive']=true;
$list[]=$dir_info;
}
else
{
$src_path=$this->task->get_path(false);
$des_path=$this->task->get_path();
$path=$this->task->get_job_option($key,'root');
$dir_info['root']=$this -> transfer_path($src_path.DIRECTORY_SEPARATOR.$path);
$dir_info['exclude_regex']=$this->task->get_job_option($key,'exclude_regex');
$exclude_files_regex=$this->task->get_job_option($key,'exclude_files_regex');
$dir_info['exclude_files_regex']=$exclude_files_regex;
$dir_info['recursive']=true;
$list[]=$dir_info;
}
$src_path=$this -> transfer_path($src_path);
$des_path=$this -> transfer_path($des_path);
return $list;
}
public function get_content_dir($des=false)
{
$dir = str_replace( ABSPATH, '', WP_CONTENT_DIR );
$src_path=$this->task->get_path($des);
return $src_path.DIRECTORY_SEPARATOR.$dir;
}
public function get_upload_dir($des=false)
{
$upload_dir = wp_upload_dir();
$dir = str_replace( ABSPATH, '', $upload_dir['basedir'] );
$src_path=$this->task->get_path($des);
return $src_path.DIRECTORY_SEPARATOR.$dir;
}
public function get_theme_dir($des=false)
{
$dir = str_replace( ABSPATH, '',get_theme_root() );
$src_path=$this->task->get_path($des);
return $src_path.DIRECTORY_SEPARATOR.$dir;
}
public function get_plugin_dir($des=false)
{
$dir = str_replace( ABSPATH, '',WP_PLUGIN_DIR );
$src_path=$this->task->get_path($des);
return $src_path.DIRECTORY_SEPARATOR.$dir;
}
private function transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode(DIRECTORY_SEPARATOR,$values);
}
public function create_cache_file($list)
{
if(file_exists($this->cache_file_name))
@wp_delete_file($this->cache_file_name);
$this->cache_file=fopen($this->cache_file_name,'a');
foreach ($list as $item)
{
$exclude_regex=array();
$exclude_files_regex=array();
if(isset($item['exclude_regex'])&&$item['exclude_regex']!=false)
{
$exclude_regex=$item['exclude_regex'];
}
if(isset($item['exclude_files_regex'])&&$item['exclude_files_regex']!=false)
{
$exclude_files_regex=$item['exclude_files_regex'];
}
//
if(isset($item['include_regex'])&&$item['include_regex']!=false)
{
$include_regex=$item['include_regex'];
}
else
{
$include_regex=array();
}
$this->create_cache_from_folder($item['root'],$item['recursive'],$exclude_regex,$exclude_files_regex,$include_regex);
}
}
public function copy_files(&$start,$count,$src_path,$des_path)
{
global $wpvivid_plugin;
$file = new SplFileObject($this->cache_file_name);
if($start==0)
$file->seek($start);
else
$file->seek($start-1);
$file->setFlags( \SplFileObject::SKIP_EMPTY | \SplFileObject::READ_AHEAD );
for ( $i = 0; $i < $count; $i++ )
{
if( $file->eof() )
{
return false;
}
$src = $file->fgets();
$src=trim($src,PHP_EOL);
if(empty($src))
continue;
$start++;
if(!file_exists($src))
{
continue;
}
$src=$this -> transfer_path($src);
$des=str_replace($src_path,$des_path,$src);
if(is_dir($src))
{
@mkdir($des,0755,true);
}
else
{
if(copy($src,$des))
{
@chmod($des,0755);
}
else
{
$wpvivid_plugin->staging->log->WriteLog('Failed to copy files from '.$src.' to '.$des.'.','warning');
}
}
}
$file = null;
return true;
}
public function create_cache_from_folder($folder,$recursive=false,$exclude_regex=array(),$exclude_files_regex=array(),$include_regex=array())
{
$this->getFolder($folder,$recursive,$exclude_regex,$exclude_files_regex,$include_regex);
}
public function getFolder($path,$recursive,$exclude_regex,$exclude_files_regex,$include_regex)
{
if($this->cache_file==false)
$this->cache_file=fopen($this->cache_file_name,'a');
if(is_dir($path))
{
$line = $path.PHP_EOL;
fwrite($this->cache_file, $line);
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if (is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
if($recursive&&$this->regex_match($exclude_regex, $path . DIRECTORY_SEPARATOR . $filename, 0))
{
if(!empty($include_regex))
{
if($recursive&&$this->regex_match($include_regex, $path . DIRECTORY_SEPARATOR . $filename, 1))
{
$this->getFolder($path . DIRECTORY_SEPARATOR . $filename,$recursive,$exclude_regex,$exclude_files_regex,$include_regex);
}
}
else
{
$this->getFolder($path . DIRECTORY_SEPARATOR . $filename,$recursive,$exclude_regex,$exclude_files_regex,$include_regex);
}
}
} else {
if($this->regex_match($exclude_files_regex, $filename, 0))
{
if ($this->regex_match($exclude_regex, $path . DIRECTORY_SEPARATOR . $filename, 0))
{
if(is_readable($path . DIRECTORY_SEPARATOR . $filename))
{
if (filesize($path . DIRECTORY_SEPARATOR . $filename) < $this->task->get_exclude_file_size() * 1024 * 1024 || $this->task->get_exclude_file_size() === 0)
{
$line = $path . DIRECTORY_SEPARATOR . $filename.PHP_EOL;
fwrite($this->cache_file, $line);
}
}
}
}
}
}
}
if($handler)
@closedir($handler);
}
}
}
private function regex_match($regex_array,$string,$mode)
{
if(empty($regex_array))
{
return true;
}
if($mode==0)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return false;
}
}
return true;
}
if($mode==1)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return true;
}
}
return false;
}
return true;
}
public function clean_up()
{
if($this->cache_file)
fclose($this->cache_file);
@wp_delete_file($this->cache_file_name);
}
} includes/staging/class-wpvivid-staging-list-ui-display.php 0000644 00000222044 15132770567 0020014 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Staging_List_UI_Display_Free
{
public function __construct()
{
}
public function get_staging_site_data()
{
if(is_multisite())
{
switch_to_blog(get_main_site_id());
$staging=get_option('wpvivid_staging_data',false);
restore_current_blog();
}
else
{
$staging=get_option('wpvivid_staging_data',false);
}
return $staging;
}
public function output_staging_sites_list_page()
{
?>
<div class="postbox quickstaging">
<div class="wpvivid-one-coloum" style="border:1px solid #f1f1f1;padding-top:0em;padding-bottom:0em;">
<div class="wpvivid-two-col">
<ul class="">
<li>
<input type="button" class="button button-primary" id="wpvivid_switch_create_staging_page" value="Create A Staging Site">
<p>Click to start creating a staging site.
</li>
</ul>
</div>
<?php
if(!is_multisite()){
?>
<div class="wpvivid-two-col">
<ul class="">
<li>
<input type="button" class="button button-primary" id="wpvivid_switch_create_fresh_install_page" value="Create A Fresh WP Site">
<p>Click to start creating a fresh WP install.
</li>
</ul>
</div>
<?php
}
?>
<div style="clear: both;"></div>
</div>
<div id="wpvivid_staging_list">
<?php
$list = get_option('wpvivid_staging_task_list',array());
if(!empty($list))
{
foreach ($list as $id => $staging)
{
if(isset($staging['site']['path']) && !empty($staging['site']['path']))
{
$staging_site_name = basename($staging['site']['path']);
}
else{
$staging_site_name = 'N/A';
}
$home_url = home_url();
global $wpdb;
$home_url_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->options WHERE option_name = %s", 'home' ) );
foreach ( $home_url_sql as $home ){
$home_url = $home->option_value;
}
$home_url = untrailingslashit($home_url);
$admin_url = apply_filters('wpvividstg_get_admin_url', '');
//$admin_name = str_replace($home_url, '', $admin_url);
//$admin_name = trim($admin_name, '/');
if(!isset($staging['login_url']))
{
$admin_name = str_replace($home_url, '', $admin_url);
$admin_name = trim($admin_name, '/');
$admin_url_descript = 'Admin URL';
}
else
{
$login_url = $staging['login_url'];
$login_name = str_replace($home_url, '', $login_url);
$login_name = trim($login_name, '/');
if($login_name !== 'wp-login.php' && !isset($staging['site']['fresh_install']))
{
$admin_name = $login_name;
$admin_url_descript = 'Login URL';
}
else
{
$admin_name = str_replace($home_url, '', $admin_url);
$admin_name = trim($admin_name, '/');
$admin_url_descript = 'Admin URL';
}
}
if(isset($staging['site']['home_url']) && !empty($staging['site']['home_url']))
{
$site_url = esc_url($staging['site']['home_url']);
$admin_url = esc_url($staging['site']['home_url'].'/'.$admin_name.'/');
}
else{
$site_url = 'N/A';
$admin_url = 'N/A';
}
if(isset($staging['site']['prefix']) && !empty($staging['site']['prefix']))
{
$prefix = $staging['site']['prefix'];
if(isset($staging['site']['db_connect']['dbname']) && !empty($staging['site']['db_connect']['dbname'])){
$db_name = $staging['site']['db_connect']['dbname'];
}
else{
$db_name = DB_NAME;
}
}
else{
$prefix = 'N/A';
$db_name = 'N/A';
}
if(isset($staging['site']['path']) && !empty($staging['site']['path'])){
$site_dir = $staging['site']['path'];
}
else{
$site_dir = 'N/A';
}
if(isset($staging['site']['fresh_install']))
{
$copy_btn='Copy the Fresh Install to Live(pro feature)';
$update_btn='Update the Fresh Install(pro feature)';
$class_btn='fresh-install';
}
else
{
$copy_btn='Copy the Staging Site to Live(pro feature)';
$update_btn='Update the Staging Site(pro feature)';
$class_btn='staging-site';
}
if(isset($staging['create_time']))
{
$staging_create_time = $staging['create_time'];
$offset=get_option('gmt_offset');
$utc_time = $staging_create_time + $offset * 60 * 60;
$staging_create_time = gmdate('M-d-Y H:i', $utc_time);
}
else
{
$staging_create_time = 'N/A';
}
if(isset($staging['copy_time']))
{
$staging_copy_time = $staging['copy_time'];
$offset=get_option('gmt_offset');
$utc_time = $staging_copy_time + $offset * 60 * 60;
$staging_copy_time = gmdate('M-d-Y H:i', $utc_time);
}
else
{
$staging_copy_time = 'N/A';
}
?>
<div class="wpvivid-one-coloum" style="border:1px solid #f1f1f1;padding-top:0em; margin-top:1em;" id="<?php echo esc_attr($id); ?>">
<div class="wpvivid-two-col">
<p><span class="dashicons dashicons-awards wpvivid-dashicons-blue"></span><span><strong>Site Name: </strong></span><span><?php echo esc_html($staging_site_name); ?></span></p>
<p><span class="dashicons dashicons-admin-home wpvivid-dashicons-blue"></span><span><strong>Home URL: </strong></span><span><a href="<?php echo esc_url($site_url); ?>"><?php echo esc_url($site_url); ?></a></span></p>
<p><span class="dashicons dashicons-rest-api wpvivid-dashicons-blue"></span><span><strong><?php echo esc_html($admin_url_descript); ?>: </strong></span><span><a href="<?php echo esc_url($admin_url); ?>"><?php echo esc_url($admin_url); ?></a></span></p>
<p><span class="dashicons dashicons-clock wpvivid-dashicons-blue"></span><span><strong>Create Time: </strong></span><span><?php echo esc_html($staging_create_time); ?></span></p>
</div>
<div class="wpvivid-two-col">
<p><span class="dashicons dashicons-admin-site-alt3 wpvivid-dashicons-blue"></span><span><strong>Database Name: </strong></span><span><?php echo esc_html($db_name); ?></span></p>
<p><span class="dashicons dashicons-list-view wpvivid-dashicons-blue"></span><span><strong>Table Prefix: </strong></span><span><?php echo esc_html($prefix); ?></span></p>
<p><span class="dashicons dashicons-portfolio wpvivid-dashicons-blue"></span><span><strong>Directory: </strong></span><span><?php echo esc_html($site_dir); ?></span></p>
<p><span class="dashicons dashicons-clock wpvivid-dashicons-blue"></span><span><strong>Update Time: </strong></span><span><?php echo esc_html($staging_copy_time); ?></span></p>
</div>
<div class="wpvivid-copy-staging-to-live-block <?php echo esc_attr($class_btn); ?>" name="<?php echo esc_attr($id); ?>" style="padding:1em 1em 0 0;">
<?php
if($staging['status']['str'] === 'completed')
{
?>
<span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-staging-operate wpvivid-update-live-to-staging"><?php echo esc_html($update_btn); ?></span>
<span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-staging-operate wpvivid-copy-staging-to-live"><?php echo esc_html($copy_btn); ?></span>
<?php
}
?>
<span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-staging-operate wpvivid-delete-staging-site">Delete</span>
<?php
if($staging['status']['str'] === 'ready')
{
?>
<span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-staging-operate wpvivid-restart-staging-site">Resume</span>
<span class="dashicons dashicons-editor-help wpvivid-dashicons-editor-help wpvivid-tooltip" style="margin-top: 4px;">
<div class="wpvivid-bottom">
<!-- The content you need -->
<p>The staging site is not fully created yet due to an interruption. Click the Resume button to continue the creation.</p>
<i></i> <!-- do not delete this line -->
</div>
</span>
<?php
}
?>
</div>
<div style="clear: both;"></div>
</div>
<?php
}
}
?>
</div>
<script>
<?php
$upload_dir = wp_upload_dir();
$upload_path = $upload_dir['basedir'];
$upload_path = str_replace('\\','/',$upload_path);
$upload_path = $upload_path.'/';
$content_dir = WP_CONTENT_DIR;
$content_path = str_replace('\\','/',$content_dir);
$content_path = $content_path.'/';
$home_path = str_replace('\\','/', get_home_path());
$theme_path = str_replace('\\','/', get_theme_root());
$theme_path = $theme_path.'/';
$plugin_path = str_replace('\\','/', WP_PLUGIN_DIR);
$plugin_path = $plugin_path.'/';
?>
var path_arr = {};
path_arr['core'] = '<?php echo esc_attr($home_path); ?>';
path_arr['content'] = '<?php echo esc_attr($content_path); ?>';
path_arr['uploads'] = '<?php echo esc_attr($upload_path); ?>';
path_arr['themes'] = '<?php echo esc_attr($theme_path); ?>';
path_arr['plugins'] = '<?php echo esc_attr($plugin_path); ?>';
var push_staging_site_id='';
var wpvivid_ajax_lock=false;
function wpvivid_create_standard_json(){
var json = {};
json['database_check_ex'] = '1';
json['folder_check_ex'] = '1';
json['exclude_custom'] = '0';
json['core_list'] = Array();
json['core_check'] = '0';
json['database_list'] = Array();
json['database_check'] = '1';
json['themes_list'] = {};
json['themes_check'] = '0';
json['themes_extension']= Array();
json['plugins_list'] = {};
json['plugins_check'] = '0';
json['plugins_extension']= Array();
json['uploads_list'] = {};
json['uploads_check'] = '1';
json['upload_extension']= Array();
json['content_list'] = {};
json['content_check'] = '0';
json['content_extension']= Array();
json['additional_file_list'] = {};
json['additional_file_check'] = '0';
json['additional_file_extension']= Array();
return json;
}
function wpvivid_lock_unlock_push_ui(action){
if(action === 'lock'){
jQuery('#wpvivid_staging_list').find('a').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#wpvivid_staging_list').find('input').attr('disabled', true);
jQuery('#wpvivid_staging_list').find('div.wpvivid-delete-staging-site').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#wpvivid_staging_list').find('div#wpvivid_custom_staging_site').css({'pointer-events': 'none', 'opacity': '0.4'});
}
else{
jQuery('#wpvivid_staging_list').find('a').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#wpvivid_staging_list').find('input').attr('disabled', false);
jQuery('#wpvivid_staging_list').find('div.wpvivid-delete-staging-site').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#wpvivid_staging_list').find('div#wpvivid_custom_staging_site').css({'pointer-events': 'auto', 'opacity': '1'});
}
}
function wpvivid_delete_staging_site_lock_unlock(id, action){
if(action === 'lock'){
jQuery('#wpvivid_staging_list').css({'pointer-events': 'none', 'opacity': '0.4'});
}
else{
jQuery('#wpvivid_staging_list').css({'pointer-events': 'auto', 'opacity': '1'});
}
}
function wpvivid_staging_js_fix(parent_id, is_staging, themes_path, plugins_path, uploads_path, content_path, home_path, staging_site_id){
var tree_path = themes_path;
var path_arr = {};
path_arr['core'] = home_path;
path_arr['content'] = content_path;
path_arr['uploads'] = uploads_path;
path_arr['themes'] = themes_path;
path_arr['plugins'] = plugins_path;
jQuery('#'+parent_id).on('click', '.wpvivid-handle-additional-folder-detail', function(){
wpvivid_init_custom_include_tree(home_path, is_staging, parent_id);
});
jQuery('#'+parent_id).on('click', '.wpvivid-refresh-include-tree', function(){
wpvivid_init_custom_include_tree(home_path, is_staging, parent_id, 1);
});
jQuery('#'+parent_id).on('click', '.wpvivid-handle-tree-detail', function(){
var value = jQuery('#'+parent_id).find('.wpvivid-custom-tree-selector').val();
if(value === 'themes'){
tree_path = themes_path;
}
else if(value === 'plugins'){
tree_path = plugins_path;
}
else if(value === 'content'){
tree_path = content_path;
}
else if(value === 'uploads'){
tree_path = uploads_path;
}
wpvivid_init_custom_exclude_tree(tree_path, is_staging, parent_id);
});
jQuery('#'+parent_id).on('change', '.wpvivid-custom-tree-selector', function(){
var value = jQuery('#'+parent_id).find('.wpvivid-custom-tree-selector').val();
if(value === 'themes'){
tree_path = themes_path;
}
else if(value === 'plugins'){
tree_path = plugins_path;
}
else if(value === 'content'){
tree_path = content_path;
}
else if(value === 'uploads'){
tree_path = uploads_path;
}
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-tree-info').jstree("destroy").empty();
wpvivid_init_custom_exclude_tree(tree_path, is_staging, parent_id);
});
jQuery('#'+parent_id).on('click', '.wpvivid-refresh-exclude-tree', function(){
var value = jQuery('#'+parent_id).find('.wpvivid-custom-tree-selector').val();
if(value === 'themes'){
tree_path = themes_path;
}
else if(value === 'plugins'){
tree_path = plugins_path;
}
else if(value === 'content'){
tree_path = content_path;
}
else if(value === 'uploads'){
tree_path = uploads_path;
}
wpvivid_init_custom_exclude_tree(tree_path, is_staging, parent_id, 1);
});
jQuery('#'+parent_id).on('click', '.wpvivid-custom-tree-exclude-btn', function(){
var select_folders = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-tree-info').jstree(true).get_selected(true);
var tree_type = jQuery('#'+parent_id).find('.wpvivid-custom-tree-selector').val();
var tree_path = path_arr[tree_type];
if(tree_type === 'themes'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-themes-list');
}
else if(tree_type === 'plugins'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-plugins-list');
}
else if(tree_type === 'content'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-content-list');
}
else if(tree_type === 'uploads'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-uploads-list');
}
jQuery.each(select_folders, function (index, select_item) {
if (select_item.id !== tree_path) {
var value = select_item.id;
value = value.replace(tree_path, '');
if (!wpvivid_check_tree_repeat(tree_type, value, parent_id)) {
var class_name = select_item.icon;
if(class_name === 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer'){
var type = 'folder';
}
else{
var type = 'file';
}
var tr = "<div class='wpvivid-text-line' type='"+type+"'>" +
"<span class='dashicons dashicons-trash wpvivid-icon-16px wpvivid-remove-custom-exlcude-tree'></span>" +
"<span class='"+class_name+"'></span>" +
"<span class='wpvivid-text-line'>" + value + "</span>" +
"</div>";
list_obj.append(tr);
}
}
});
});
if(is_staging){
is_staging = '1';
}
else{
is_staging = '0';
}
wpvivid_get_custom_database_tables_info(parent_id, is_staging, staging_site_id);
}
function wpvivid_load_mu_staging_js(parent_id){
function wpvivid_handle_custom_open_close_ex(handle_obj, obj, parent_id){
if(obj.is(":hidden")) {
handle_obj.each(function(){
if(jQuery(this).hasClass('dashicons-arrow-down-alt2')){
jQuery(this).removeClass('dashicons-arrow-down-alt2');
jQuery(this).addClass('dashicons-arrow-up-alt2');
}
});
obj.show();
}
else{
handle_obj.each(function(){
if(jQuery(this).hasClass('dashicons-arrow-up-alt2')){
jQuery(this).removeClass('dashicons-arrow-up-alt2');
jQuery(this).addClass('dashicons-arrow-down-alt2');
}
});
obj.hide();
}
}
function wpvivid_change_custom_exclude_info(type, parent_id){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-module').hide();
if(type === 'themes'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-themes-module').show();
}
else if(type === 'plugins'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-plugins-module').show();
}
else if(type === 'content'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-content-module').show();
}
else if(type === 'uploads'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-uploads-module').show();
}
}
function wpvivid_check_tree_repeat(tree_type, value, parent_id) {
if(tree_type === 'themes'){
var list = 'wpvivid-custom-exclude-themes-list';
}
else if(tree_type === 'plugins'){
var list = 'wpvivid-custom-exclude-plugins-list';
}
else if(tree_type === 'content'){
var list = 'wpvivid-custom-exclude-content-list';
}
else if(tree_type === 'uploads'){
var list = 'wpvivid-custom-exclude-uploads-list';
}
else if(tree_type === 'additional-folder'){
var list = 'wpvivid-custom-include-additional-folder-list';
}
var brepeat = false;
jQuery('#'+parent_id).find('.'+list+' div').find('span:eq(2)').each(function (){
if (value === this.innerHTML) {
brepeat = true;
}
});
return brepeat;
}
jQuery('#'+parent_id).on('click', '.wpvivid-handle-database-detail', function(){
var handle_obj = jQuery('#'+parent_id).find('.wpvivid-handle-database-detail');
var obj = jQuery('#'+parent_id).find('.wpvivid-database-detail');
wpvivid_handle_custom_open_close_ex(handle_obj, obj, parent_id);
});
jQuery('#'+parent_id).on('click', '.wpvivid-handle-base-database-detail', function(){
var handle_obj = jQuery('#'+parent_id).find('.wpvivid-handle-base-database-detail');
var obj = jQuery('#'+parent_id).find('.wpvivid-base-database-detail');
wpvivid_handle_custom_open_close_ex(handle_obj, obj, parent_id);
});
jQuery('#'+parent_id).on('click', '.wpvivid-handle-file-detail', function(){
var handle_obj = jQuery('#'+parent_id).find('.wpvivid-handle-file-detail');
var obj = jQuery('#'+parent_id).find('.wpvivid-file-detail');
wpvivid_handle_custom_open_close_ex(handle_obj, obj, parent_id);
});
jQuery('#'+parent_id).on('click', '.wpvivid-handle-additional-folder-detail', function(){
var handle_obj = jQuery('#'+parent_id).find('.wpvivid-handle-additional-folder-detail');
var obj = jQuery('#'+parent_id).find('.wpvivid-additional-folder-detail');
wpvivid_handle_custom_open_close_ex(handle_obj, obj, parent_id);
});
jQuery('#'+parent_id).on('click', '.wpvivid-handle-tree-detail', function(){
var handle_obj = jQuery('#'+parent_id).find('.wpvivid-handle-tree-detail');
var obj = jQuery('#'+parent_id).find('.wpvivid-tree-detail');
var value = jQuery('#'+parent_id).find('.wpvivid-custom-tree-selector').val();
wpvivid_handle_custom_open_close_ex(handle_obj, obj, parent_id);
});
jQuery('#'+parent_id).on('change', '.wpvivid-custom-tree-selector', function(){
var value = jQuery('#'+parent_id).find('.wpvivid-custom-tree-selector').val();
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-tree-info').jstree("destroy").empty();
wpvivid_change_custom_exclude_info(value, parent_id);
});
jQuery('#'+parent_id).on('click', '.wpvivid-include-additional-folder-btn', function(){
var select_folders = jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-tree-info').jstree(true).get_selected(true);
var tree_path = '<?php echo esc_attr($home_path); ?>';
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-include-additional-folder-list');
var tree_type = 'additional-folder';
jQuery.each(select_folders, function (index, select_item) {
if (select_item.id !== tree_path) {
var value = select_item.id;
value = value.replace(tree_path, '');
if (!wpvivid_check_tree_repeat(tree_type, value, parent_id)) {
var class_name = select_item.icon;
if(class_name === 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer'){
var type = 'folder';
}
else{
var type = 'file';
}
var tr = "<div class='wpvivid-text-line' type='"+type+"'>" +
"<span class='dashicons dashicons-trash wpvivid-icon-16px wpvivid-remove-custom-exlcude-tree'></span>" +
"<span class='"+class_name+"'></span>" +
"<span class='wpvivid-text-line'>" + value + "</span>" +
"</div>";
list_obj.append(tr);
}
}
});
});
jQuery('#'+parent_id).on('click', '.wpvivid-custom-tree-exclude-btn', function(){
var select_folders = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-tree-info').jstree(true).get_selected(true);
var tree_type = jQuery('#'+parent_id).find('.wpvivid-custom-tree-selector').val();
var tree_path = path_arr[tree_type];
if(tree_type === 'themes'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-themes-list');
}
else if(tree_type === 'plugins'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-plugins-list');
}
else if(tree_type === 'content'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-content-list');
}
else if(tree_type === 'uploads'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-uploads-list');
}
jQuery.each(select_folders, function (index, select_item) {
if (select_item.id !== tree_path) {
var value = select_item.id;
value = value.replace(tree_path, '');
if (!wpvivid_check_tree_repeat(tree_type, value, parent_id)) {
var class_name = select_item.icon;
if(class_name === 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer'){
var type = 'folder';
}
else{
var type = 'file';
}
var tr = "<div class='wpvivid-text-line' type='"+type+"'>" +
"<span class='dashicons dashicons-trash wpvivid-icon-16px wpvivid-remove-custom-exlcude-tree'></span>" +
"<span class='"+class_name+"'></span>" +
"<span class='wpvivid-text-line'>" + value + "</span>" +
"</div>";
list_obj.append(tr);
}
}
});
});
jQuery('#'+parent_id).on('click', '.wpvivid-remove-custom-exlcude-tree', function(){
jQuery(this).parent().remove();
});
jQuery('#'+parent_id).on('click', '.wpvivid-clear-custom-include-list', function(){
jQuery('#'+parent_id).find('.wpvivid-custom-include-additional-folder-list').html('');
});
jQuery('#'+parent_id).on('click', '.wpvivid-clear-custom-exclude-list', function(){
var tree_type = jQuery('#'+parent_id).find('.wpvivid-custom-tree-selector').val();
if(tree_type === 'themes'){
var list = 'wpvivid-custom-exclude-themes-list';
}
else if(tree_type === 'plugins'){
var list = 'wpvivid-custom-exclude-plugins-list';
}
else if(tree_type === 'content'){
var list = 'wpvivid-custom-exclude-content-list';
}
else if(tree_type === 'uploads'){
var list = 'wpvivid-custom-exclude-uploads-list';
}
jQuery('#'+parent_id).find('.'+list).html('');
});
jQuery('#'+parent_id).on('click', '.wpvivid-database-table-check', function(){
if(jQuery(this).prop('checked')){
if(jQuery(this).hasClass('wpvivid-database-base-table-check')){
jQuery('#'+parent_id).find('input:checkbox[option=base_db][name=Database]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-database-other-table-check')){
jQuery('#'+parent_id).find('input:checkbox[option=other_db][name=Database]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-database-diff-prefix-table-check')){
jQuery('#'+parent_id).find('input:checkbox[option=diff_prefix_db][name=Database]').prop('checked', true);
}
}
else{
var check_status = false;
if (jQuery(this).hasClass('wpvivid-database-base-table-check')) {
jQuery('#'+parent_id).find('input:checkbox[option=other_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
jQuery('#'+parent_id).find('input:checkbox[option=diff_prefix_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#'+parent_id).find('input:checkbox[option=base_db][name=Database]').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
else if (jQuery(this).hasClass('wpvivid-database-other-table-check')) {
jQuery('#'+parent_id).find('input:checkbox[option=base_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
jQuery('#'+parent_id).find('input:checkbox[option=diff_prefix_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#'+parent_id).find('input:checkbox[option=other_db][name=Database]').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
else if (jQuery(this).hasClass('wpvivid-database-diff-prefix-table-check')) {
jQuery('#'+parent_id).find('input:checkbox[option=base_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
jQuery('#'+parent_id).find('input:checkbox[option=other_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#'+parent_id).find('input:checkbox[option=diff_prefix_db][name=Database]').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
}
});
jQuery('#'+parent_id).on("click", 'input:checkbox[option=base_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#'+parent_id).find('input:checkbox[option=base_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#'+parent_id).find('.wpvivid-database-base-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#'+parent_id).find('input:checkbox[name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status){
jQuery('#'+parent_id).find('.wpvivid-database-base-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
});
jQuery('#'+parent_id).on("click", 'input:checkbox[option=other_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#'+parent_id).find('input:checkbox[option=other_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#'+parent_id).find('.wpvivid-database-other-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#'+parent_id).find('input:checkbox[name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status){
jQuery('#'+parent_id).find('.wpvivid-database-other-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
});
jQuery('#'+parent_id).on("click", 'input:checkbox[option=diff_prefix_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#'+parent_id).find('input:checkbox[option=diff_prefix_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#'+parent_id).find('.wpvivid-database-diff-prefix-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#'+parent_id).find('input:checkbox[name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status){
jQuery('#'+parent_id).find('.wpvivid-database-diff-prefix-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
});
jQuery('#'+parent_id).on("click", '.wpvivid-custom-database-part', function(){
if(jQuery(this).prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-database-check').prop('checked', true);
}
else{
var check_status = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked')){
check_status = true;
}
if(check_status){
jQuery('#'+parent_id).find('.wpvivid-custom-database-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under Custom Backup option.');
}
}
});
jQuery('#'+parent_id).on("click", '.wpvivid-custom-database-check', function(){
if(jQuery(this).prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-database-part').prop('checked', true);
}
else{
var check_status = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked')){
check_status = true;
}
if(check_status){
jQuery('#'+parent_id).find('.wpvivid-custom-database-part').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under Custom Backup option.');
}
}
});
jQuery('#'+parent_id).on("click", '.wpvivid-custom-file-part', function(){
if(jQuery(this).prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked', true);
jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked', true);
jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked', true);
jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked', true);
jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked', true);
jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked', true);
}
else{
var check_status = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-database-part').prop('checked')){
check_status = true;
}
if(check_status){
jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked', false);
jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked', false);
jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked', false);
jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked', false);
jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked', false);
jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under Custom Backup option.');
}
}
});
//core
jQuery('#'+parent_id).on("click", '.wpvivid-custom-core-check', function(){
if(jQuery(this).prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', true);
}
else{
var check_status = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-database-part').prop('checked')){
check_status = true;
}
if(check_status){
if(!jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', false);
}
}
else{
if(!jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked')){
jQuery(this).prop('checked', true);
alert('Please select at least one item under Custom Backup option.');
}
}
}
});
//themes
jQuery('#'+parent_id).on("click", '.wpvivid-custom-themes-check', function(){
if(jQuery(this).prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', true);
}
else{
var check_status = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-database-part').prop('checked')){
check_status = true;
}
if(check_status){
if(!jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', false);
}
}
else{
if(!jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked')){
jQuery(this).prop('checked', true);
alert('Please select at least one item under Custom Backup option.');
}
}
}
});
//plugins
jQuery('#'+parent_id).on("click", '.wpvivid-custom-plugins-check', function(){
if(jQuery(this).prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', true);
}
else{
var check_status = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-database-part').prop('checked')){
check_status = true;
}
if(check_status){
if(!jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', false);
}
}
else{
if(!jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked')){
jQuery(this).prop('checked', true);
alert('Please select at least one item under Custom Backup option.');
}
}
}
});
//content
jQuery('#'+parent_id).on("click", '.wpvivid-custom-content-check', function(){
if(jQuery(this).prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', true);
}
else{
var check_status = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-database-part').prop('checked')){
check_status = true;
}
if(check_status){
if(!jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', false);
}
}
else{
if(!jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked')){
jQuery(this).prop('checked', true);
alert('Please select at least one item under Custom Backup option.');
}
}
}
});
//uploads
jQuery('#'+parent_id).on("click", '.wpvivid-custom-uploads-check', function(){
if(jQuery(this).prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', true);
}
else{
var check_status = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-database-part').prop('checked')){
check_status = true;
}
if(check_status){
if(!jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', false);
}
}
else{
if(!jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked')){
jQuery(this).prop('checked', true);
alert('Please select at least one item under Custom Backup option.');
}
}
}
});
//additional_folder
jQuery('#'+parent_id).on("click", '.wpvivid-custom-additional-folder-check', function(){
if(jQuery(this).prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', true);
}
else{
var check_status = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-database-part').prop('checked')){
check_status = true;
}
if(check_status){
if(!jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked', false);
}
}
else{
if(!jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked') &&
!jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked')){
jQuery(this).prop('checked', true);
alert('Please select at least one item under Custom Backup option.');
}
}
}
});
}
function wpvivid_get_mu_site_info(id,copy){
var ajax_data = {
'action':'wpvividstg_get_mu_site_info_free',
'id': id,
'copy':copy
};
wpvivid_lock_unlock_push_ui('lock');
wpvivid_post_request(ajax_data, function(data){
wpvivid_lock_unlock_push_ui('unlock');
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
push_staging_site_id=id;
jQuery('#wpvividstg_select_mu_staging_site').html(jsonarray.html);
jQuery('#'+id).find('.wpvivid-push-content').after(jQuery('#wpvividstg_select_mu_staging_site'));
jQuery('#wpvividstg_select_mu_staging_site').show();
wpvivid_load_mu_staging_js('wpvivid_custom_mu_staging_site');
if(copy == 'true' || copy == true){
//wpvivid_load_staging_tree('wpvivid_custom_mu_staging_site', true);
wpvivid_staging_js_fix('wpvivid_custom_mu_staging_site', true, jsonarray.theme_path, jsonarray.plugin_path, jsonarray.uploads_path, jsonarray.content_path, jsonarray.home_path, id);
}
else{
//wpvivid_load_staging_tree('wpvivid_custom_mu_staging_site', false);
wpvivid_staging_js_fix('wpvivid_custom_mu_staging_site', false, jsonarray.theme_path, jsonarray.plugin_path, jsonarray.uploads_path, jsonarray.content_path, jsonarray.home_path, id);
}
jQuery('#wpvivid_mu_copy_staging_site_list').find('input:checkbox').each(function(){
jQuery(this).prop('checked', true);
});
}
else if (jsonarray.result === 'failed') {
alert(jsonarray.error);
}
jQuery('#wpvivid_staging_list').find('.wpvivid-copy-staging-to-live-block').each(function() {
var tmp_id = jQuery(this).attr('name');
if(id !== tmp_id) {
if(jQuery(this).hasClass('staging-site')){
var class_btn = 'staging-site';
var copy_btn = 'Copy the Staging Site to Live(pro feature)';
var update_btn = 'Update the Staging Site(pro feature)';
var tip_text = 'Tips: Click the \'Copy the Staging Site to Live\' button above to migrate the staging site to your live site. Click the \'Update the Staging Site\' button to update the live site to the staging site.';
}
else{
var class_btn = 'fresh-install';
var copy_btn = 'Copy the Fresh Install to Live(pro feature)';
var update_btn = 'Update the Fresh Install(pro feature)';
var tip_text = 'Tips: Click the \'Copy the Fresh Install to Live\' button above to migrate the fresh install to your live site. Click the \'Update the Fresh Install\' button to update the live site to the fresh install.';
}
if(jQuery(this).hasClass('mu-single')){
var mu_single_class = 'mu-single';
}
else{
var mu_single_class = '';
}
var tmp_html = '<span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-staging-operate wpvivid-update-live-to-staging">Update the Staging Site(pro feature)</span>' +
'<span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-staging-operate wpvivid-copy-staging-to-live">Copy the Staging Site to Live(pro feature)</span>' +
'<span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-staging-operate wpvivid-delete-staging-site">Delete</span>';
jQuery(this).html(tmp_html);
}
});
}, function(XMLHttpRequest, textStatus, errorThrown)
{
wpvivid_lock_unlock_push_ui('unlock');
var error_message = wpvivid_output_ajaxerror('export the previously-exported settings', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#wpvivid_switch_create_staging_page').click(function(){
switch_staging_tab('create_staging');
});
jQuery('#wpvivid_switch_create_fresh_install_page').click(function(){
switch_staging_tab('create_fresh_install');
});
jQuery('#wpvivid_staging_list').on("click", '.wpvivid-delete-staging-site', function(){
var descript = '<?php esc_html_e('Are you sure to delete this staging site?', 'wpvivid-backuprestore'); ?>';
var ret = confirm(descript);
if (ret === true) {
var id = jQuery(this).parent().attr('name');
var ajax_data = {
'action': 'wpvividstg_delete_site_free',
'id': id
};
wpvivid_delete_staging_site_lock_unlock(id, 'lock');
wpvivid_post_request(ajax_data, function (data) {
wpvivid_delete_staging_site_lock_unlock(id, 'unlock');
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
location.href='<?php echo esc_url(apply_filters('wpvividstg_get_admin_url', '') ). 'admin.php?page=wpvivid-staging'; ?>';
}
else if (jsonarray.result === 'failed') {
alert(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
wpvivid_delete_staging_site_lock_unlock(id, 'unlock');
var error_message = wpvivid_output_ajaxerror('export the previously-exported settings', textStatus, errorThrown);
alert(error_message);
});
}
});
jQuery('#wpvivid_staging_list').on("click", '.wpvivid-restart-staging-site', function(){
var descript = '<?php esc_html_e('Are you sure to restart this staging site?', 'wpvivid-backuprestore'); ?>';
var ret = confirm(descript);
if (ret === true) {
var id = jQuery(this).parent().attr('name');
var ajax_data = {
'action':'wpvividstg_set_restart_staging_id_free',
'id': id
};
wpvivid_post_request(ajax_data, function (data) {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
jQuery('#wpvivid_choose_staging_content').hide();
jQuery('#wpvivid_create_btn').hide();
jQuery('#wpvivid_create_staging_step2').show();
switch_staging_tab('create_staging');
wpvivid_restart_staging();
}
else if (jsonarray.result === 'failed') {
alert(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('setting restart staging id', textStatus, errorThrown);
alert(error_message);
});
}
});
</script>
</div>
<?php
}
public function output_staging(){
$data=$this->get_staging_site_data();
$data['live_site_staging_url'] = str_replace('wpvivid-staging', 'WPvivid_Staging', $data['live_site_staging_url']);
$live_site_url = $data['live_site_url'];
$push_site_url = $data['live_site_staging_url'];
?>
<div class="wpvivid-one-coloum" style="border:1px solid #f1f1f1;padding-top:0em;">
<div class="wpvivid-two-col">
<p><span class="dashicons dashicons-awards wpvivid-dashicons-blue"></span><span><strong>Site Name: </strong></span><span><?php echo esc_html(basename(get_home_path())); ?></span></p>
<p><span class="dashicons dashicons-admin-home wpvivid-dashicons-blue"></span><span><strong>Live Site URL: </strong></span><span><?php echo esc_url($live_site_url); ?></span></p>
<p><span class="dashicons dashicons-rest-api wpvivid-dashicons-blue"></span><span><strong>Live Site Staging: </strong></span><span><?php echo esc_url($push_site_url); ?></span></p>
</div>
<div class="wpvivid-two-col">
<p><span class="dashicons dashicons-admin-site-alt3 wpvivid-dashicons-blue"></span><span><strong>Database Name: </strong></span><span><?php echo esc_html(DB_NAME); ?></span></p>
<p><span class="dashicons dashicons-list-view wpvivid-dashicons-blue"></span><span><strong>Table Prefix: </strong></span><span><?php echo esc_html($data['prefix']); ?></span></p>
<p><span class="dashicons dashicons-portfolio wpvivid-dashicons-blue"></span><span><strong>Directory: </strong></span><span><?php echo esc_html(get_home_path()); ?></span></p>
</div>
<div style="clear: both;"></div>
</div>
<?php
}
} includes/staging/class-wpvivid-fresh-install-create-ui-display.php 0000644 00000145045 15132770567 0021430 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Fresh_Install_Create_UI_Display_Free
{
public function __construct()
{
}
public function output_themes_plugins_info($type)
{
$html = '';
if($type === 'theme')
{
$themes_path = get_theme_root();
$has_themes = false;
$themes_table = '';
$themes_table_html = '';
$themes_info = array();
$themes = wp_get_themes();
if (!empty($themes))
{
$has_themes = true;
}
foreach ($themes as $theme)
{
$file = $theme->get_stylesheet();
$parent=$theme->parent();
$themes_info[$file] = $this->get_theme_plugin_info($themes_path . DIRECTORY_SEPARATOR . $file);
$themes_info[$file]['parent']=$parent;
$themes_info[$file]['parent_file']=$theme->get_template();
$themes_info[$file]['child']=array();
$current_theme=wp_get_theme();
if($current_theme->get_stylesheet()==$file)
{
$themes_info[$file]['active'] = 1;
}
else
{
$themes_info[$file]['active'] = 0;
}
}
foreach ($themes_info as $file => $info)
{
if($info['active']&&$info['parent']!=false)
{
$themes_info[$info['parent_file']]['active']=1;
$themes_info[$info['parent_file']]['child'][]=$file;
}
}
$themes_all_check = 'checked';
foreach ($themes_info as $file => $info)
{
$checked = '';
if ($info['active'] == 1)
{
$checked = 'checked';
}
if (empty($checked)) {
$themes_all_check = '';
}
echo '<div class="wpvivid-text-line"><input type="checkbox" option="create_wp" name="Themes" value="' . esc_attr($file) . '" '. esc_html($checked) .'>' . esc_html($file) . '</div>';
}
}
else{
$has_plugins = false;
$plugins_table = '';
$plugins_table_html = '';
$path = WP_PLUGIN_DIR;
$plugin_info = array();
if (!function_exists('get_plugins'))
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
$plugins = get_plugins();
if (!empty($plugins))
{
$has_plugins = true;
}
foreach ($plugins as $key => $plugin)
{
$slug = dirname($key);
if ($slug == '.')
continue;
$plugin_info[$slug] = $this->get_theme_plugin_info($path . DIRECTORY_SEPARATOR . $slug);
$plugin_info[$slug]['Name'] = $plugin['Name'];
$plugin_info[$slug]['slug'] = $slug;
if($slug=='wpvivid-backuprestore')
{
$plugin_info[$slug]['active'] = 1;
$plugin_info[$slug]['disable'] = 1;
}
else
{
$plugin_info[$slug]['active'] = 0;
$plugin_info[$slug]['disable'] = 0;
}
}
$plugins_all_check='checked';
foreach ($plugin_info as $slug => $info)
{
$disable_check = '';
if ($info['disable']==1)
{
$disable_check = 'disabled';
}
$checked = '';
if ($info['active'] == 1)
{
$checked = 'checked';
}
if (empty($checked)) {
$plugins_all_check = '';
}
echo '<div class="wpvivid-text-line"><input type="checkbox" option="create_wp" name="Plugins" value="' . esc_attr($info['slug']) . '" '. esc_html($checked) .'>' . esc_html($info['Name']) . '</div>';
}
}
}
public function get_theme_plugin_info($root)
{
//$theme_info['size']=$this->get_folder_size($root,0);
$theme_info['size']=0;
return $theme_info;
}
public function get_folder_size($root,$size)
{
$count = 0;
if(is_dir($root))
{
$handler = opendir($root);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..") {
$count++;
if (is_dir($root . DIRECTORY_SEPARATOR . $filename))
{
$size=$this->get_folder_size($root . DIRECTORY_SEPARATOR . $filename,$size);
} else {
$size+=filesize($root . DIRECTORY_SEPARATOR . $filename);
}
}
}
if($handler)
@closedir($handler);
}
}
return $size;
}
public function get_database_home_url()
{
$home_url = home_url();
global $wpdb;
$home_url_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->options WHERE option_name = %s", 'home' ) );
foreach ( $home_url_sql as $home ){
$home_url = $home->option_value;
}
return untrailingslashit($home_url);
}
public function output_create_wp_page()
{
$options=get_option('wpvivid_staging_options',array());
if(isset( $options['staging_request_timeout']))
{
$request_timeout=$options['staging_request_timeout'];
}
else
{
$request_timeout=1500;
}
update_option('wpvivid_current_running_staging_task','','no');
update_option('wpvivid_staging_task_cancel', false,'no');
$home_url = $this->get_database_home_url();
$admin_url = admin_url();
$admin_name = basename($admin_url);
$admin_name = trim($admin_name, '/');
$home_path = get_home_path();
$staging_num = 1;
$staging_dir = 'myfreshinstall01';
$staging_content_dir = 'myfreshinstall01';
$default_fresh_install_site = 'myfreshinstall01';
while(1){
$default_fresh_install_site = 'myfreshinstall'.sprintf("%02d", $staging_num);
$staging_dir = $home_path.$default_fresh_install_site;
if(!file_exists($staging_dir)){
break;
}
$staging_num++;
}
$content_dir = WP_CONTENT_DIR;
$content_dir = str_replace('\\','/',$content_dir);
$content_path = $content_dir.'/';
$staging_num = 1;
$default_content_fresh_install_site='myfreshinstall01';
while(1){
$default_content_fresh_install_site = 'myfreshinstall'.sprintf("%02d", $staging_num);
$staging_dir = $content_path.$default_content_fresh_install_site;
if(!file_exists($staging_dir)){
break;
}
$staging_num++;
}
global $wpdb;
$prefix='';
$site_id=1;
$base_prefix=$wpdb->base_prefix;
while(1)
{
if($site_id<10)
{
$prefix='wpvividfresh0'.$site_id.'_';
}
else
{
$prefix='wpvividfresh'.$site_id.'_';
}
$sql=$wpdb->prepare("SHOW TABLES LIKE %s;", $wpdb->esc_like($prefix) . '%');
$result = $wpdb->get_results($sql, OBJECT_K);
if(empty($result))
{
break;
}
$site_id++;
}
$themes_plugins_descript = 'The activated plugins and themes will be copied to a fresh site by default. A Child theme must be copied if it exists.';
?>
<div class="postbox quickstaging">
<div id="wpvivid_create_new_wp_content">
<div class="wpvivid-one-coloum" style="border:1px solid #f1f1f1;padding-bottom:0em; margin-top:0em;margin-bottom:1em;">
<div class="wpvivid-one-coloum" style="background:#f5f5f5;padding-top:0em;padding-bottom:0em;display: none;">
<div class="wpvivid-two-col">
<p><span class="dashicons dashicons-awards wpvivid-dashicons-blue"></span><span><strong>Site Name: </strong></span><span class="wpvivid-fresh-install-staging-site-name"><?php echo esc_html($default_fresh_install_site); ?></span></p>
<p><span class="dashicons dashicons-admin-site-alt3 wpvivid-dashicons-blue"></span><span><strong>Database Name: </strong></span><span class="wpvivid-staging-additional-database-name-display"><?php echo esc_html(DB_NAME); ?></span></p>
<p><span class="dashicons dashicons-list-view wpvivid-dashicons-blue"></span><span><strong>Table Prefix: </strong></span><span class="wpvivid-staging-table-prefix-display"><?php echo esc_html($prefix); ?></span></p>
</div>
<div class="wpvivid-two-col">
<!--<p><span class="dashicons dashicons-admin-site-alt3 wpvivid-dashicons-blue"></span><span><strong>Database Name:</strong></span><span>admin06</span></p>-->
<p><span class="dashicons dashicons-admin-home wpvivid-dashicons-blue"></span><span><strong>Home URL: </strong></span><span class="wpvivid-fresh-install-home-url"><?php echo esc_url($home_url); ?>/</span><span class="wpvivid-fresh-install-staging-site-name"><?php echo esc_html($default_fresh_install_site); ?></span></p>
<p><span class="dashicons dashicons-rest-api wpvivid-dashicons-blue"></span><span><strong>Admin URL: </strong></span><span class="wpvivid-fresh-install-home-url"><?php echo esc_url($home_url); ?>/</span><span class="wpvivid-fresh-install-staging-site-name"><?php echo esc_html($default_fresh_install_site); ?></span><span>/<?php echo esc_html($admin_name); ?></span></p>
</div>
</div>
<div>
<div>
<h2 style="padding-left:1em;padding-top:0.6em; background:#f1f1f1;">
<span class="dashicons dashicons-portfolio wpvivid-dashicons-orange"></span>
<span>Directory to Install the Fresh Install</span>
</h2>
<?php
$server_type = $_SERVER['SERVER_SOFTWARE'];
if(preg_match('/nginx/i', $server_type))
{
?>
<div style="border:1px solid #ccc; padding:0 1em;margin-top:1em; border-radius:0.5em;">
<p>
<span>We detected that your web server is Nginx, please add specific rewrite rules to the Nginx config file for the staging site working properly. <a href="https://docs.wpvivid.com/add-rewrite-rules-to-nginx.html">How to</a></span>
<p>
<div style="clear:both;"></div>
</div>
<?php
}
?>
<p>
<label>
<input type="radio" option="create_wp" name="choose_create_staging_dir" value="0" checked="checked">
<span>website root</span>
</label>
<label>
<input type="radio" option="create_wp" name="choose_create_staging_dir" value="1">
<span>/wp-content/</span>
</label>
<label>
<input type="radio" option="create_wp" name="choose_create_staging_dir" value="2" disabled>
<span>subdomain(pro feature)</span>
</label>
</p>
<div id="wpvivid_fresh_install_path_part" style="border-left: 4px solid #007cba;padding-left:1em;">
<p>
<input type="text" option="create_wp" name="path" id="wpvivid_fresh_install_staging_path" placeholder="<?php echo esc_attr($default_fresh_install_site); ?>" value="<?php echo esc_attr($default_fresh_install_site); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9]/g,'')" onpaste="value=value.replace(/[^\a-\z\A-\Z0-9]/g,'')"><span> Custom directory</span>
</p>
<p>
<span class="dashicons dashicons-admin-home wpvivid-dashicons-blue"></span><span>Home Url: </span><span class="wpvivid-fresh-install-home-url"><?php echo esc_url($home_url); ?>/</span><span class="wpvivid-fresh-install-staging-site-name"><?php echo esc_html($default_fresh_install_site); ?></span>
<span style="margin-left:1em;" class="dashicons dashicons-portfolio wpvivid-dashicons-blue"></span><span><strong>Directory:</strong></span>
<span><?php echo esc_html(untrailingslashit(ABSPATH)); ?>/</span><span class="wpvivid-fresh-install-staging-site-name"><?php echo esc_html($default_fresh_install_site); ?></span>
</p>
</div>
</div>
<h2 style="padding-left:1em;padding-top:0.6em;background:#f1f1f1;">
<span class="dashicons dashicons-cloud wpvivid-dashicons-blue"></span>
<span>Choose Database to Install the Fresh Install</span>
</h2>
<p>
<input type="text" option="create_wp" name="prefix" id="wpvivid_fresh_install_staging_table_prefix" placeholder="<?php echo esc_attr($prefix); ?>" value="<?php echo esc_attr($prefix); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9_]/g,'')" onpaste="value=value.replace(/[^\a-\z\A-\Z0-9_]/g,'')" title="Table Prefix"> Custom Table Prefix, By default: <?php echo esc_html($prefix); ?>
</p>
<p>
<label>
<input type="radio" option="create_wp" name="choose_create_staging_db" value="0" checked="">
<span>Install the staging site to the live site's database (Easy setup)</span>
</label>
</p>
<p>
<label>
<input type="radio" option="create_wp" name="choose_create_staging_db" value="1">
<span>Install the staging site to a separate database (Expert setup)</span>
</label>
</p>
<p></p>
<div class="" id="wpvivid_fresh_install_additional_database_account" style="display: none;">
<form>
<p><label><input type="text" option="create_wp" name="database-name" autocomplete="off" placeholder="DB Name" title="DB Name" readonly></label>
<label><input type="text" option="create_wp" name="database-user" autocomplete="off" placeholder="DB Username" title="DB Username" readonly></label></p>
<p><label><input type="password" option="create_wp" name="database-pass" autocomplete="off" placeholder="Password" title="The Password of the Database Username" readonly></label>
<label><input type="text" option="create_wp" name="database-host" autocomplete="off" placeholder="localhost" title="Database Host" readonly></label></p>
<p><label><input class="button-primary wpvivid_setting_general_save" name="test-fresh-install-additional-db-btn" type="button" onclick="wpvivid_additional_database_connect_test_ex();" value="Test Connection" readonly></label></p>
</form>
</div>
<div style="clear: both;"></div>
</div>
</div>
<div style="clear: both;"></div>
<div style="background:#f1f1f1;">
<h2 style="padding-left:1em;padding-top:0.6em;">
<span class="dashicons dashicons-grid-view wpvivid-dashicons-blue"></span>
<span>Themes And Plugins</span>
</h2>
</div>
<div>
<div class="wpvivid-two-col" style="padding:0.2em;">
<div style="padding:0 0 0.5em 0.2em;">
<span><span>Check All </span><input type="checkbox" name="wpvivid_check_all_fresh_install_themes"></span>
</div>
<div style="padding:0.3em;height:300px;overflow-y:auto; border:1px solid #ccc;">
<?php $this->output_themes_plugins_info('theme'); ?>
</div>
</div>
<div class="wpvivid-two-col" style="padding:0.2em;">
<div style="padding:0 0 0.5em 0.2em;">
<span><span>Check All </span><input type="checkbox" name="wpvivid_check_all_fresh_install_plugins"></span>
</div>
<div style="padding:0.3em;height:300px;overflow-y:auto;border:1px solid #ccc;">
<?php $this->output_themes_plugins_info('plugin'); ?>
</div>
</div>
</div>
<div style="clear: both;"></div>
<div style="padding:1em 1em 0 0;">
<input class="button-primary wpvivid_setting_general_save" id="wpvivid_create_new_wp" type="submit" value="Create Now"><span> Note: Please don't refresh the page while creating a fresh install.</span>
</div>
<div style="padding:1em 1em 0 0;">
<span>Tips: Please temporarily deactivate all cache, firewall and redirect plugins before creating a staging site to rule out possibilities of unknown failures.</span>
</div>
</div>
<div id="wpvivid_create_new_wp_progress" style="display: none;">
<div class="wpvivid-element-space-bottom">
<input class="button button-primary" type="button" id="wpvivid_staging_cancel" value="Cancel" />
</div>
<div class="postbox wpvivid-staging-log wpvivid-element-space-bottom" id="wpvivid_fresh_install_staging_log" style="margin-bottom: 0;"></div>
<div class="action-progress-bar" style="margin: 10px 0 0 0; !important;">
<div class="action-progress-bar-percent" id="wpvivid_fresh_install_staging_progress_bar" style="height:24px;line-height:24px;width:0;">
<div style="float: left; margin-left: 4px;">0</div>
<div style="clear: both;"></div>
</div>
</div>
</div>
<script>
var home_url="<?php echo esc_url($home_url).'/'; ?>";
var content_url="<?php echo esc_url($home_url).'/wp-content/'; ?>";
var staging_requet_timeout=<?php echo esc_attr($request_timeout) ?>;
var default_fresh_install_site = '<?php echo esc_attr($default_fresh_install_site); ?>';
var default_content_fresh_install_site = '<?php echo esc_attr($default_content_fresh_install_site); ?>';
jQuery('input:checkbox[name=wpvivid_check_all_fresh_install_themes]').on("click", function(){
if(jQuery(this).prop('checked'))
{
jQuery('input:checkbox[option=create_wp][name=Themes]').prop('checked', true);
}
else
{
jQuery('input:checkbox[option=create_wp][name=Themes]').prop('checked', false);
}
});
jQuery('input:checkbox[name=wpvivid_check_all_fresh_install_plugins]').on("click", function(){
if(jQuery(this).prop('checked'))
{
jQuery('input:checkbox[option=create_wp][name=Plugins]').prop('checked', true);
}
else
{
jQuery('input:checkbox[option=create_wp][name=Plugins]').prop('checked', false);
}
});
jQuery('input:checkbox[option=create_wp][name=Themes]').on("click", function(){
if(jQuery(this).prop('checked'))
{
var all_check = true;
jQuery('input:checkbox[option=create_wp][name=Themes]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check) {
jQuery('input:checkbox[name=wpvivid_check_all_fresh_install_themes]').prop('checked', true);
}
else {
jQuery('input:checkbox[name=wpvivid_check_all_fresh_install_themes]').prop('checked', false);
}
}
else
{
jQuery('input:checkbox[name=wpvivid_check_all_fresh_install_themes]').prop('checked', false);
}
});
jQuery('input:checkbox[option=create_wp][name=Plugins]').on("click", function(){
if(jQuery(this).prop('checked'))
{
var all_check = true;
jQuery('input:checkbox[option=create_wp][name=Plugins]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check) {
jQuery('input:checkbox[name=wpvivid_check_all_fresh_install_plugins]').prop('checked', true);
}
else {
jQuery('input:checkbox[name=wpvivid_check_all_fresh_install_plugins]').prop('checked', false);
}
}
else
{
jQuery('input:checkbox[name=wpvivid_check_all_fresh_install_plugins]').prop('checked', false);
}
});
jQuery('#wpvivid_create_new_wp_content').on("click", 'input:radio[name=choose_create_staging_db]', function(){
if(jQuery(this).prop('checked')){
var value = jQuery(this).val();
if(value === '0'){
jQuery('#wpvivid_fresh_install_additional_database_account').hide();
jQuery('#wpvivid_fresh_install_additional_database_account').find('input[name=database-name]').attr('readonly', true);
jQuery('#wpvivid_fresh_install_additional_database_account').find('input[name=database-user]').attr('readonly', true);
jQuery('#wpvivid_fresh_install_additional_database_account').find('input[name=database-pass]').attr('readonly', true);
jQuery('#wpvivid_fresh_install_additional_database_account').find('input[name=database-host]').attr('readonly', true);
jQuery('#wpvivid_create_new_wp_content').find('.wpvivid-staging-additional-database-name-display').html('<?php echo esc_html(DB_NAME); ?>');
}
else{
jQuery('#wpvivid_fresh_install_additional_database_account').show();
jQuery('#wpvivid_fresh_install_additional_database_account').find('input[name=database-name]').attr('readonly', false);
jQuery('#wpvivid_fresh_install_additional_database_account').find('input[name=database-user]').attr('readonly', false);
jQuery('#wpvivid_fresh_install_additional_database_account').find('input[name=database-pass]').attr('readonly', false);
jQuery('#wpvivid_fresh_install_additional_database_account').find('input[name=database-host]').attr('readonly', false);
var additional_db_name = jQuery('.wpvivid-additional-database-name').val();
if(additional_db_name !== ''){
jQuery('#wpvivid_create_new_wp_content').find('.wpvivid-staging-additional-database-name-display').html(additional_db_name);
}
else{
jQuery('#wpvivid_create_new_wp_content').find('.wpvivid-staging-additional-database-name-display').html('*');
}
wpvivid_fresh_install_additional_database_table_prefix();
}
}
});
jQuery('#wpvivid_create_new_wp_content').on("click", 'input:radio[name=choose_create_staging_dir]', function()
{
if(jQuery(this).prop('checked'))
{
var value = jQuery(this).val();
if(value === '0')
{
jQuery('.wpvivid-fresh-install-home-url').show();
jQuery('#wpvivid_fresh_install_path_part').show();
jQuery('#wpvivid_fresh_install_staging_path').val(default_fresh_install_site);
var staging_path = jQuery('#wpvivid_fresh_install_staging_path').val();
if(staging_path !== '')
{
jQuery('.wpvivid-fresh-install-staging-site-name').html(staging_path);
}
else{
jQuery('.wpvivid-fresh-install-staging-site-name').html('*');
}
}
else
{
jQuery('.wpvivid-fresh-install-home-url').show();
jQuery('#wpvivid_fresh_install_path_part').show();
jQuery('#wpvivid_fresh_install_staging_path').val(default_content_fresh_install_site);
var staging_path = jQuery('#wpvivid_fresh_install_staging_path').val();
if(staging_path !== '')
{
jQuery('.wpvivid-fresh-install-staging-site-name').html('wp-content/'+staging_path);
}
else{
jQuery('.wpvivid-fresh-install-staging-site-name').html('wp-content/*');
}
}
}
});
jQuery('#wpvivid_create_new_wp_content').on("keyup", '#wpvivid_fresh_install_staging_table_prefix', function(){
wpvivid_fresh_install_additional_database_table_prefix();
});
jQuery('#wpvivid_create_new_wp_content').on("keyup", '#wpvivid_fresh_install_staging_path', function() {
var value = jQuery('input:radio[name=choose_create_staging_dir]:checked').val();
if(value === '0')
{
var staging_path = jQuery('#wpvivid_fresh_install_staging_path').val();
if(staging_path !== ''){
jQuery('.wpvivid-fresh-install-staging-site-name').html(staging_path);
}
else{
jQuery('.wpvivid-fresh-install-staging-site-name').html('*');
}
}
else if(value === '1'){
var staging_path = jQuery('#wpvivid_fresh_install_staging_path').val();
if(staging_path !== ''){
jQuery('.wpvivid-fresh-install-staging-site-name').html('wp-content/'+staging_path);
}
else{
jQuery('.wpvivid-fresh-install-staging-site-name').html('wp-content/*');
}
}
});
jQuery('#wpvivid_create_new_wp').click(function() {
var descript = '<?php esc_html_e('Click OK to start creating fresh WordPress install.', 'wpvivid-backuprestore'); ?>';
var ret = confirm(descript);
if(ret === true)
{
wpvivid_create_new_wp();
}
});
function wpvivid_fresh_install_additional_database_table_prefix(){
var additional_db_prefix = jQuery('#wpvivid_create_new_wp_content').find('#wpvivid_fresh_install_staging_table_prefix').val();
if(additional_db_prefix !== ''){
jQuery('#wpvivid_create_new_wp_content').find('.wpvivid-staging-table-prefix-display').html(additional_db_prefix);
}
else{
jQuery('#wpvivid_create_new_wp_content').find('.wpvivid-staging-table-prefix-display').html('*');
}
}
function wpvivid_create_new_wp() {
var staging_root_dir='0';
jQuery('input[option=create_wp][name=choose_create_staging_dir]').each(function ()
{
if (jQuery(this).prop('checked'))
{
staging_root_dir = jQuery(this).val();
}
});
var table_prefix=jQuery('input[option=create_wp][name=prefix]').val();
if(table_prefix=='')
{
alert('Table Prefix is required.');
return ;
}
var path='';
var path=jQuery('input[option=create_wp][name=path]').val();
if(path === '')
{
alert('A site name is required.');
return;
}
var additional_database_json = {};
var additional_database_option = '0';
jQuery('input[option=create_wp][name=choose_create_staging_db]').each(function ()
{
if (jQuery(this).prop('checked'))
{
additional_database_option = jQuery(this).val();
}
});
if (additional_database_option === '1')
{
additional_database_json['additional_database_check'] = '1';
additional_database_json['additional_database_info'] = {};
additional_database_json['additional_database_info']['db_user'] = jQuery('input[option=create_wp][name=database-user]').val();
additional_database_json['additional_database_info']['db_pass'] = jQuery('input[option=create_wp][name=database-pass]').val();
additional_database_json['additional_database_info']['db_host'] = jQuery('input[option=create_wp][name=database-host]').val();
additional_database_json['additional_database_info']['db_name'] = jQuery('input[option=create_wp][name=database-name]').val();
if (additional_database_json['additional_database_info']['db_name'] === '')
{
alert('Database Name is required.');
return;
}
if (additional_database_json['additional_database_info']['db_user'] === '')
{
alert('Database User is required.');
return;
}
if (additional_database_json['additional_database_info']['db_host'] === '')
{
alert('Database Host is required.');
return;
}
}
else {
additional_database_json['additional_database_check'] = '0';
}
var additional_database_info=JSON.stringify(additional_database_json);
var ajax_data =
{
'action': 'wpvividstg_check_staging_dir_free',
'root_dir':staging_root_dir,
'path': path,
'table_prefix': table_prefix,
'additional_db': additional_database_info
};
wpvivid_post_request(ajax_data, function (data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
}
else
{
var ajax_data =
{
'action': 'wpvividstg_check_filesystem_permissions_free',
'root_dir':staging_root_dir,
'path': path
};
wpvivid_post_request(ajax_data, function (data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
}
else
{
var custom_dir_json = wpvivid_get_custom_create_new_wp_option();
var custom_dir = JSON.stringify(custom_dir_json);
var ajax_data = {
'action': 'wpvividstg_start_staging_free',
'create_new_wp':true,
'path': path,
'table_prefix': table_prefix,
'custom_dir': custom_dir,
'additional_db': additional_database_info,
'root_dir':staging_root_dir,
};
jQuery('#wpvivid_create_new_wp_content').hide();
jQuery('#wpvivid_create_new_wp_progress').show();
wpvivid_post_request(ajax_data, function (data)
{
setTimeout(function ()
{
wpvivid_get_create_new_wp_progress();
}, staging_requet_timeout);
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#wpvivid_create_new_wp_content').hide();
jQuery('#wpvivid_create_new_wp_progress').show();
setTimeout(function () {
wpvivid_get_create_new_wp_progress();
}, staging_requet_timeout);
});
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('creating staging site', textStatus, errorThrown);
alert(error_message);
});
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('creating staging site', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_get_create_new_wp_progress() {
var ajax_data = {
'action':'wpvividstg_get_staging_progress_free',
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
var log_data = jsonarray.log;
jQuery('#wpvivid_fresh_install_staging_log').html("");
while (log_data.indexOf('\n') >= 0)
{
var iLength = log_data.indexOf('\n');
var log = log_data.substring(0, iLength);
log_data = log_data.substring(iLength + 1);
var insert_log = "<div style=\"clear:both;\">" + log + "</div>";
jQuery('#wpvivid_fresh_install_staging_log').append(insert_log);
var div = jQuery('#wpvivid_fresh_install_staging_log');
div[0].scrollTop = div[0].scrollHeight;
}
jQuery('#wpvivid_fresh_install_staging_progress_bar').css('width', jsonarray.percent + '%');
jQuery('#wpvivid_fresh_install_staging_progress_bar').find('div').eq(0).html(jsonarray.percent + '%');
if(jsonarray.continue)
{
if(jsonarray.need_restart)
{
wpvivid_restart_create_new_wp();
}
else
{
setTimeout(function()
{
wpvivid_get_create_new_wp_progress();
}, staging_requet_timeout);
}
}
else
{
if(typeof jsonarray.completed !== 'undefined' && jsonarray.completed)
{
jQuery('#wpvivid_staging_cancel').css({'pointer-events': 'auto', 'opacity': '1'});
var percent = 100;
jQuery('#wpvivid_fresh_install_staging_progress_bar').css('width', percent + '%');
jQuery('#wpvivid_fresh_install_staging_progress_bar').find('div').eq(0).html(percent + '%');
setTimeout(function()
{
alert('Creating a fresh WordPress install completed successfully.');
location.href='<?php echo esc_url(apply_filters('wpvividstg_get_admin_url', '')) . 'admin.php?page=wpvivid-staging'; ?>';
}, 1000);
}
else if(typeof jsonarray.error !== 'undefined' && jsonarray.error)
{
alert(jsonarray.error);
location.href='<?php echo esc_url(apply_filters('wpvividstg_get_admin_url', '')) . 'admin.php?page=wpvivid-staging'; ?>';
}
else if(typeof jsonarray.is_cancel !== 'undefined' && jsonarray.is_cancel)
{
var staging_site_info = {};
staging_site_info['staging_path'] = jsonarray.staging_path;
staging_site_info['staging_additional_db'] = jsonarray.staging_additional_db;
staging_site_info['staging_additional_db_user'] = jsonarray.staging_additional_db_user;
staging_site_info['staging_additional_db_pass'] = jsonarray.staging_additional_db_pass;
staging_site_info['staging_additional_db_host'] = jsonarray.staging_additional_db_host;
staging_site_info['staging_additional_db_name'] = jsonarray.staging_additional_db_name;
staging_site_info['staging_table_prefix'] = jsonarray.staging_table_prefix;
staging_site_info = JSON.stringify(staging_site_info);
ajax_data = {
'action': 'wpvividstg_delete_cancel_staging_site_free',
'staging_site_info': staging_site_info
};
wpvivid_post_request(ajax_data, function (data)
{
location.href='<?php echo esc_url(apply_filters('wpvividstg_get_admin_url', '')) . 'admin.php?page=wpvivid-staging'; ?>';
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('deleting fresh site', textStatus, errorThrown);
alert(error_message);
location.href='<?php echo esc_url(apply_filters('wpvividstg_get_admin_url', '')) . 'admin.php?page=wpvivid-staging'; ?>';
});
}
else{
location.href='<?php echo esc_url(apply_filters('wpvividstg_get_admin_url', '')) . 'admin.php?page=wpvivid-staging'; ?>';
}
}
}
else if (jsonarray.result === 'failed')
{
jQuery('#wpvivid_create_new_wp_content').show();
jQuery('#wpvivid_create_new_wp_progress').hide();
alert(jsonarray.error);
}
}
catch(err)
{
setTimeout(function()
{
wpvivid_get_create_new_wp_progress();
}, 3000);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function()
{
wpvivid_get_create_new_wp_progress();
}, 3000);
});
}
function wpvivid_restart_create_new_wp() {
var ajax_data = {
'action':'wpvividstg_start_staging_free',
};
wpvivid_post_request(ajax_data, function(data)
{
setTimeout(function()
{
wpvivid_get_create_new_wp_progress();
}, staging_requet_timeout);
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function()
{
wpvivid_get_create_new_wp_progress();
}, staging_requet_timeout);
});
}
function wpvivid_get_custom_create_new_wp_option() {
var json = {};
json['themes_list'] = Array();
json['plugins_list'] = Array();
json['themes_check'] = '0';
json['plugins_check'] = '0';
jQuery('input:checkbox[option=create_wp][name=Themes]').each(function()
{
if(jQuery(this).prop('checked'))
{
json['themes_check'] = '1';
}
else{
json['themes_list'].push(jQuery(this).val());
}
});
jQuery('input:checkbox[option=create_wp][name=Plugins]').each(function()
{
if(jQuery(this).prop('checked'))
{
json['plugins_check'] = '1';
}
else{
json['plugins_list'].push(jQuery(this).val());
}
});
return json;
}
function wpvivid_additional_database_connect_test_ex()
{
var db_user =jQuery('input[option=create_wp][name=database-user]').val();
var db_pass =jQuery('input[option=create_wp][name=database-pass]').val();
var db_host =jQuery('input[option=create_wp][name=database-host]').val();
var db_name =jQuery('input[option=create_wp][name=database-name]').val();
if(db_name == '')
{
alert('Database Name is required.');
return;
}
if(db_user == '')
{
alert('Database User is required.');
return;
}
if(db_pass == '')
{
alert('Database Password is required.');
return;
}
if(db_host == '')
{
alert('Database Host is required.');
return ;
}
var db_json = {};
db_json['db_user'] = db_user;
db_json['db_pass'] = db_pass;
db_json['db_host'] = db_host;
db_json['db_name'] = db_name;
var db_connect_info = JSON.stringify(db_json);
var ajax_data = {
'action': 'wpvividstg_test_additional_database_connect_free',
'database_info': db_connect_info
};
wpvivid_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray !== null)
{
if (jsonarray.result === 'success')
{
alert('Connection success.')
}
else
{
alert(jsonarray.error);
}
}
else
{
alert('Connection Failed. Please check the credentials you entered and try again.');
}
}
catch (e)
{
alert('Connection Failed. Please check the credentials you entered and try again.');
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('connecting database', textStatus, errorThrown);
alert(error_message);
});
}
</script>
</div>
<?php
}
} includes/staging/class-wpvivid-staging-create-new-wp.php 0000644 00000022120 15132770567 0017432 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
if ( ! class_exists( 'WP_List_Table' ) )
{
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class WPvivid_Staging_Install_Wordpress_Free
{
public $task;
public $db_src_instance;
public $db_des_instance;
public $new_site_url;
public $new_home_url;
public function __construct($task_id)
{
$this->task=new WPvivid_Staging_Task($task_id);
}
public function do_install_wordpress()
{
global $wpvivid_plugin,$wpdb,$current_user;
$this->db_src_instance=false;
$this->db_des_instance=false;
$this->new_site_url=$this->task->get_site_url(true);
$this->new_home_url=$this->task->get_home_url(true);
$wpvivid_plugin->staging->log->WriteLog('Start install new wordpress.','notice');
if (!function_exists('wp_install'))
{
require ABSPATH . 'wp-admin/includes/upgrade.php';
}
$username=$current_user->user_login;
$email=$current_user->user_email;
$title= get_option('blogname');
$userpassword=$current_user->user_pass;
$prefix=$this->task->get_db_prefix(true);
$old_prefix=$this->task->get_db_prefix();
$permalink_structure = $this->task->get_permalink_structure();
$is_overwrite_permalink_structure = $this->task->get_is_overwrite_permalink_structure();
$data['id']=$this->task->get_id();
$data['name']=$this->task->get_path(true);
$data['prefix']= $prefix;
$admin_url = apply_filters('wpvividstg_get_admin_url', '');
$admin_url .= 'admin.php?page='.apply_filters('wpvivid_white_label_slug', 'WPvivid');
$data['parent_admin_url']=$admin_url;
$data['live_site_url']=home_url();
$data['live_site_staging_url']=apply_filters('wpvividstg_get_admin_url', '').'admin.php?page='.apply_filters('wpvivid_white_label_plugin_name', 'WPvivid_Staging');
$data=serialize($data);
$old_wpdb=$wpdb;
$wpdb=$this->get_db_instance(true);
$wpdb->set_prefix($prefix);
$hook_name = 'update_option_blogname';
if(has_action($hook_name))
{
remove_all_actions($hook_name);
}
$result = @wp_install($title, $username, $email, 0, '', md5(wp_rand()));
$wpvivid_plugin->staging->log->WriteLog(wp_json_encode($result), 'notice');
$user_id = $result['user_id'];
$db_field = 'ID';
if ( ! $wpdb->get_row(
$wpdb->prepare(
"SELECT * FROM $wpdb->users WHERE $db_field = %s LIMIT 1",
$user_id
)
) )
{
$wpvivid_plugin->staging->log->WriteLog('User not create ,so we create it.', 'notice');
$user_id = wp_create_user( $username, md5(wp_rand()), $email );
update_user_option( $user_id, 'default_password_nag', true, true );
}
$query = $wpdb->prepare("UPDATE {$prefix}users SET user_pass = %s, user_activation_key = '' WHERE ID = %d LIMIT 1", array($userpassword, $user_id));
$wpvivid_plugin->staging->log->WriteLog($query, 'notice');
$wpdb->query($query);
$update_query ="UPDATE {$prefix}options SET option_value = '{$this->new_site_url}' WHERE option_name = 'siteurl'";
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($wpdb->get_results($update_query)===false)
{
$error=$wpdb->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$update_query ="UPDATE {$prefix}options SET option_value = '{$this->new_home_url}' WHERE option_name = 'home'";
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($wpdb->get_results($update_query)===false)
{
$error=$wpdb->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$update_query ="UPDATE {$prefix}options SET option_name='{$prefix}user_roles' WHERE option_name='{$old_prefix}user_roles'";
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($wpdb->get_results($update_query)===false)
{
$error=$wpdb->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$update_query=$wpdb->prepare("INSERT INTO {$prefix}options (option_name,option_value) VALUES ('wpvivid_staging_finish',%d)", 1);
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($wpdb->get_results($update_query)===false)
{
$error=$wpdb->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
if($is_overwrite_permalink_structure == 0)
{
$update_query = "INSERT INTO {$prefix}options (option_name,option_value) VALUES ('wpvivid_staging_init','{$permalink_structure}')";
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($wpdb->get_results($update_query) === false)
{
$error = $wpdb->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
}
$update_query = $wpdb->prepare("INSERT INTO {$prefix}options (option_name,option_value) VALUES ('wpvivid_staging_data',%s)", $data);
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($wpdb->get_results($update_query)===false)
{
$error=$wpdb->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$current = array();
$current[] = 'wpvivid-backuprestore/wpvivid-backuprestore.php';
sort( $current );
$value=serialize($current);
$update_query = $wpdb->prepare("UPDATE {$prefix}options SET option_value=%s WHERE option_name='active_plugins'" , $value);
$wpvivid_plugin->staging->log->WriteLog($update_query, 'notice');
if ($wpdb->get_results($update_query)===false)
{
$error=$wpdb->last_error;
$wpvivid_plugin->staging->log->WriteLog($error, 'Warning');
}
$wpdb=$old_wpdb;
$wpvivid_plugin->staging->log->WriteLog('prefix:'.$old_prefix,'notice');
$wpdb->set_prefix($old_prefix);
$des_path=$this->task->get_path();
$path=$des_path.DIRECTORY_SEPARATOR.'wp-config.php';
$data=file_get_contents($path);
if( $data === false )
{
$wpvivid_plugin->staging->log->WriteLog('wp-config.php not found in '.$path,'notice');
}
else
{
preg_match( "/define\s*\(\s*['\"]MULTISITE['\"]\s*,\s*(.*)\s*\);/", $data, $matches );
if( !empty( $matches[1] ) )
{
$wpvivid_plugin->staging->log->WriteLog('MULTISITE found in wp-config.php','notice');
$pattern = "/define\s*\(\s*['\"]MULTISITE['\"]\s*,\s*(.*)\s*\);.*/";
$replace = "define('MULTISITE',false); //";
$data = preg_replace( array($pattern), $replace, $data );
if( null === ($data) )
{
$wpvivid_plugin->staging->log->WriteLog('MULTISITE not replace in wp-config.php','notice');
}
}
file_put_contents($path,$data);
}
$wpvivid_plugin->staging->log->WriteLog('finished install new wordpress.','notice');
$this->task->update_job_finished('create_new_wp');
return true;
}
public function get_db_instance($des=false)
{
$db=$this->task->get_db_connect();
if($des)
{
if( $this->db_des_instance===false)
{
if($db['des_use_additional_db']===false)
{
global $wpdb;
$this->db_des_instance=$wpdb;
return $this->db_des_instance;
}
else
{
$this->db_des_instance=new wpdb($db['des_dbuser'],$db['des_dbpassword'],$db['des_dbname'],$db['des_dbhost']);
return $this->db_des_instance;
}
}
else
{
return $this->db_des_instance;
}
}
else
{
if( $this->db_src_instance===false)
{
if($db['src_use_additional_db']===false)
{
global $wpdb;
$this->db_src_instance=$wpdb;
return $this->db_src_instance;
}
else
{
$this->db_src_instance=new wpdb($db['src_dbuser'],$db['src_dbpassword'],$db['src_dbname'],$db['src_dbhost']);
return $this->db_src_instance;
}
}
else
{
return $this->db_src_instance;
}
}
}
} includes/staging/class-wpvivid-staging-log-page.php 0000644 00000125404 15132770567 0016460 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Staging_Log_List_Free extends WP_List_Table
{
public $page_num;
public $log_list;
public function __construct( $args = array() )
{
parent::__construct(
array(
'plural' => 'log',
'screen' => 'log'
)
);
}
public function get_columns()
{
$columns = array();
$columns['wpvivid_date'] = __( 'Date', 'wpvivid-backuprestore' );
$columns['wpvivid_log_type'] = __( 'Log Type', 'wpvivid-backuprestore' );
$columns['wpvivid_log_file_name'] =__( 'Log File Name ', 'wpvivid-backuprestore' );
$columns['wpvivid_log_action'] = __( 'Action ', 'wpvivid-backuprestore' );
$columns['wpvivid_download'] = __( 'Download', 'wpvivid-backuprestore' );
return $columns;
}
public function set_log_list($log_list,$page_num=1)
{
$this->log_list=$log_list;
$this->page_num=$page_num;
}
public function get_pagenum()
{
if($this->page_num=='first')
{
$this->page_num=1;
}
else if($this->page_num=='last')
{
$this->page_num=$this->_pagination_args['total_pages'];
}
$pagenum = $this->page_num ? $this->page_num : 0;
if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
{
$pagenum = $this->_pagination_args['total_pages'];
}
return max( 1, $pagenum );
}
public function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$this->_column_headers = array($columns, $hidden, $sortable);
$total_items =sizeof($this->log_list);
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => 10,
)
);
}
public function has_items()
{
return !empty($this->log_list);
}
public function _column_wpvivid_date( $log )
{
$offset=get_option('gmt_offset');
$localtime = strtotime($log['time']) + $offset * 60 * 60;
echo '<td><label for="tablecell">'.esc_html(gmdate('F-d-Y H:i:s',$localtime)).'</label></td>';
}
protected function column_wpvivid_log_type($log)
{
if($log['error'])
{
echo '<span>Error</span>';
}
else
{
echo '<span>'.esc_html($log['des']).'</span>';
}
}
public function column_wpvivid_log_file_name( $log )
{
echo '<span>'.esc_html($log['file_name']).'</span>';
}
public function column_wpvivid_log_action( $log )
{
echo '<a class="open-log" log="'.esc_attr($log['file_name']).'" style="cursor:pointer;">
<img src="'.esc_url(WPVIVID_PLUGIN_IMAGES_URL.'Log.png').'" style="vertical-align:middle;">Log
</a>';
}
public function column_wpvivid_download( $log )
{
echo '<a class="download-log" log="'.esc_attr($log['file_name']).'" style="cursor:pointer;">
<img src="' . esc_url(WPVIVID_PLUGIN_IMAGES_URL . 'staging/download.png') . '" style="vertical-align:middle;" />Download
</a>';
}
public function display_rows()
{
$this->_display_rows( $this->log_list );
}
private function _display_rows($log_list)
{
$page=$this->get_pagenum();
$page_log_list=array();
$count=0;
while ( $count<$page )
{
$page_log_list = array_splice( $log_list, 0, 10);
$count++;
}
foreach ( $page_log_list as $log)
{
$this->single_row($log);
}
}
public function single_row($log)
{
?>
<tr>
<?php $this->single_row_columns( $log ); ?>
</tr>
<?php
}
protected function pagination( $which )
{
if ( empty( $this->_pagination_args ) )
{
return;
}
$total_items = $this->_pagination_args['total_items'];
$total_pages = $this->_pagination_args['total_pages'];
$infinite_scroll = false;
if ( isset( $this->_pagination_args['infinite_scroll'] ) )
{
$infinite_scroll = $this->_pagination_args['infinite_scroll'];
}
if ( 'top' === $which && $total_pages > 1 )
{
$this->screen->render_screen_reader_content( 'heading_pagination' );
}
$output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items, 'wpvivid-backuprestore' ), number_format_i18n( $total_items ) ) . '</span>';
$current = $this->get_pagenum();
$page_links = array();
$total_pages_before = '<span class="paging-input">';
$total_pages_after = '</span></span>';
$disable_first = $disable_last = $disable_prev = $disable_next = false;
if ( $current == 1 ) {
$disable_first = true;
$disable_prev = true;
}
if ( $current == 2 ) {
$disable_first = true;
}
if ( $current == $total_pages ) {
$disable_last = true;
$disable_next = true;
}
if ( $current == $total_pages - 1 ) {
$disable_last = true;
}
if ( $disable_first ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>';
} else {
$page_links[] = sprintf(
"<div class='first-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'First page', 'wpvivid-backuprestore' ),
'«'
);
}
if ( $disable_prev ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>';
} else {
$page_links[] = sprintf(
"<div class='prev-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Previous page', 'wpvivid-backuprestore' ),
'‹'
);
}
if ( 'bottom' === $which ) {
$html_current_page = $current;
$total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
} else {
$html_current_page = sprintf(
"%s<input class='current-page' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
'<label class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</label>',
$current,
strlen( $total_pages )
);
}
$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
$page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging', 'wpvivid-backuprestore' ), $html_current_page, $html_total_pages ) . $total_pages_after;
if ( $disable_next ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>';
} else {
$page_links[] = sprintf(
"<div class='next-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Next page', 'wpvivid-backuprestore' ),
'›'
);
}
if ( $disable_last ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>';
} else {
$page_links[] = sprintf(
"<div class='last-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'Last page', 'wpvivid-backuprestore' ),
'»'
);
}
$pagination_links_class = 'pagination-links';
if ( ! empty( $infinite_scroll ) ) {
$pagination_links_class .= ' hide-if-js';
}
$output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
if ( $total_pages ) {
$page_class = $total_pages < 2 ? ' one-page' : '';
} else {
$page_class = ' no-pages';
}
$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
echo $this->_pagination;
}
protected function display_tablenav( $which ) {
$css_type = '';
if ( 'top' === $which ) {
wp_nonce_field( 'bulk-' . $this->_args['plural'] );
$css_type = 'margin: 0 0 10px 0';
}
else if( 'bottom' === $which ) {
$css_type = 'margin: 10px 0 0 0';
}
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
}
class WPvivid_Staging_Log_Page_Free
{
public $main_tab;
public function __construct()
{
add_action('wp_ajax_wpvividstg_get_log_list_page', array($this, 'get_log_list_page'));
add_action('wp_ajax_wpvividstg_view_log_ex', array($this, 'view_log_ex'));
add_action('wp_ajax_wpvividstg_download_log', array($this, 'download_log'));
//add_filter('wpvivid_get_staging_admin_menus', array($this, 'get_menu'), 10);
add_filter('wpvivid_add_log_tab_page', array($this, 'add_log_tab_page'), 11);
add_filter('wpvivid_get_staging_log_list', array($this, 'get_staging_log_list'), 10);
}
public function add_log_tab_page($setting_array)
{
$setting_array['staging_log_page'] = array('index' => '2', 'tab_func' => array($this, 'add_tab_log'), 'page_func' => array($this, 'add_page_log'));
return $setting_array;
}
public function add_tab_log(){
?>
<a href="#" id="wpvivid_tab_staging_log" class="nav-tab log-nav-tab" onclick="switchlogTabs(event,'staging-logs-page')"><?php esc_html_e('Staging Logs', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function add_page_log()
{
global $wpvivid_plugin;
$display_log_count=array(0=>"10",1=>"20",2=>"30",3=>"40",4=>"50");
$max_log_diaplay=20;
$loglist=$this->get_log_list('staging');
?>
<div id="staging-logs-page" class="log-tab-content wpvivid_tab_log" name="tab-logs" style="display: none">
<table class="wp-list-table widefat plugins">
<thead class="log-head">
<tr>
<th class="row-title"><?php esc_html_e( 'Date', 'wpvivid-backuprestore' ); ?></th>
<th><?php esc_html_e( 'Log Type', 'wpvivid-backuprestore' ); ?></th>
<th><?php esc_html_e( 'Log File Name', 'wpvivid-backuprestore' ); ?></th>
<th><?php esc_html_e( 'Action', 'wpvivid-backuprestore' ); ?></th>
</tr>
</thead>
<tbody class="wpvivid-loglist" id="wpvivid_staging_loglist">
<?php
$this->get_staging_log_list();
?>
</tbody>
</table>
<div style="padding-top: 10px; text-align: center;">
<input class="button-secondary log-page" id="wpvivid_staging_pre_log_page" type="submit" value="<?php esc_attr_e( ' < Pre page ', 'wpvivid-backuprestore' ); ?>" />
<div style="font-size: 12px; display: inline-block; padding-left: 10px;">
<span id="wpvivid_staging_log_page_info" style="line-height: 35px;">
<?php
$current_page=1;
$max_page=ceil(sizeof($loglist['log_list']['file'])/$max_log_diaplay);
if($max_page == 0) $max_page = 1;
echo esc_html($current_page.' / '.$max_page);
?>
</span>
</div>
<input class="button-secondary log-page" id="wpvivid_staging_next_log_page" type="submit" value="<?php esc_attr_e( ' Next page > ', 'wpvivid-backuprestore' ); ?>" />
<div style="float: right;">
<select name="" id="wpvivid_staging_display_log_count">
<?php
foreach ($display_log_count as $value){
if($value == $max_log_diaplay){
echo '<option selected="selected" value="' . esc_attr($value) . '">' . esc_html($value) . '</option>';
}
else {
echo '<option value="' . esc_attr($value) . '">' . esc_html($value) . '</option>';
}
}
?>
</select>
</div>
</div>
</div>
<script>
var wpvivid_cur_staging_log_page = 1;
var wpvivid_staging_log_count = '<?php
echo esc_attr(sizeof($loglist['log_list']['file']));
?>';
jQuery('#wpvivid_staging_display_log_count').on("change", function(){
wpvivid_staging_display_log_page();
});
jQuery('#wpvivid_staging_pre_log_page').click(function(){
wpvivid_staging_pre_log_page();
});
jQuery('#wpvivid_staging_next_log_page').click(function(){
wpvivid_staging_next_log_page();
});
function wpvivid_staging_pre_log_page(){
if(wpvivid_cur_staging_log_page > 1){
wpvivid_cur_staging_log_page--;
}
wpvivid_staging_display_log_page();
}
function wpvivid_staging_next_log_page(){
var display_count = jQuery("#wpvivid_staging_display_log_count option:selected").val();
var max_pages=Math.ceil(wpvivid_staging_log_count/display_count);
if(wpvivid_cur_staging_log_page < max_pages){
wpvivid_cur_staging_log_page++;
}
wpvivid_staging_display_log_page();
}
function wpvivid_staging_display_log_page(){
var display_count = jQuery("#wpvivid_staging_display_log_count option:selected").val();
var max_pages=Math.ceil(wpvivid_staging_log_count/display_count);
if(max_pages == 0) max_pages = 1;
jQuery('#wpvivid_staging_log_page_info').html(wpvivid_cur_staging_log_page+ " / "+max_pages);
var begin = (wpvivid_cur_staging_log_page - 1) * display_count;
var end = parseInt(begin) + parseInt(display_count);
jQuery("#wpvivid_staging_loglist tr").hide();
jQuery('#wpvivid_staging_loglist tr').each(function(i){
if (i >= begin && i < end)
{
jQuery(this).show();
}
});
}
</script>
<?php
}
public function get_staging_log_list()
{
$loglist=$this->get_log_list('staging');
$current_num=1;
$max_log_diaplay=20;
$log_index=0;
$pic_log='/admin/partials/images/Log.png';
if(!empty($loglist['log_list']['file']))
{
foreach ($loglist['log_list']['file'] as $value)
{
if ($current_num <= $max_log_diaplay) {
$log_tr_display = '';
} else {
$log_tr_display = 'display: none;';
}
if (empty($value['time'])) {
$value['time'] = 'N/A';
}
else{
$offset=get_option('gmt_offset');
$localtime = strtotime($value['time'])/* + $offset * 60 * 60*/;
$value['time'] = gmdate('F-d-Y H:i:s',$localtime);
}
if (empty($value['des'])) {
$value['des'] = 'N/A';
}
$value['path'] = str_replace('\\', '/', $value['path']);
echo '<tr style="'.esc_attr($log_tr_display).'">
<td class="row-title"><label for="tablecell">'.esc_html($value['time']).'</label>
</td>
<td>'.esc_html($value['des']).'</td>
<td>'.esc_html($value['file_name']).'</td>
<td>
<a onclick="wpvivid_read_log(\'wpvivid_view_log\', \''.esc_attr($value['id']).'\', \'staging\')" style="cursor:pointer;">
<img src="'.esc_url(WPVIVID_PLUGIN_URL.$pic_log).'" style="vertical-align:middle;">Log
</a>
</td>
</tr>';
$log_index++;
$current_num++;
}
}
}
public function output_log()
{
?>
<div class="postbox restore_log" id="wpvivid_read_log_content">
</div>
<?php
}
public function output_staging_log_list()
{
$this->output_log_list('staging','staging_log','wpvivid_staging_log_list');
}
public function output_log_list($type,$slug,$id)
{
?>
<div class="wpvivid-log-list" id="<?php echo esc_attr($id)?>">
<?php
$loglist=$this->get_log_list($type);
$table = new WPvivid_Staging_Log_List_Free();
$table->set_log_list($loglist['log_list']['file']);
$table->prepare_items();
$table->display();
?>
</div>
<script>
jQuery('#<?php echo esc_attr($id)?>').on("click",'.first-page',function()
{
wpvivid_log_change_page('first','<?php echo esc_attr($type);?>','<?php echo esc_attr($id);?>');
});
jQuery('#<?php echo esc_attr($id)?>').on("click",'.prev-page',function()
{
var page=parseInt(jQuery(this).attr('value'));
wpvivid_log_change_page(page-1,'<?php echo esc_attr($type);?>','<?php echo esc_attr($id)?>');
});
jQuery('#<?php echo esc_attr($id)?>').on("click",'.next-page',function()
{
var page=parseInt(jQuery(this).attr('value'));
wpvivid_log_change_page(page+1,'<?php echo esc_attr($type);?>','<?php echo esc_attr($id)?>');
});
jQuery('#<?php echo esc_attr($id)?>').on("click",'.last-page',function()
{
wpvivid_log_change_page('last','<?php echo esc_attr($type);?>','<?php echo esc_attr($id)?>');
});
jQuery('#<?php echo esc_attr($id)?>').on("keypress", '.current-page', function()
{
if(event.keyCode === 13)
{
var page = jQuery(this).val();
wpvivid_log_change_page(page,'<?php echo esc_attr($type);?>','<?php echo esc_attr($id)?>');
}
});
jQuery('#<?php echo esc_attr($id)?>').on("click",'.open-log',function()
{
var log=jQuery(this).attr("log");
wpvivid_open_log(log,'<?php echo esc_attr($slug);?>');
});
jQuery('#<?php echo esc_attr($id)?>').on("click",'.download-log',function()
{
var log=jQuery(this).attr("log");
wpvivid_download_log(log);
});
</script>
<?php
}
public function get_log_list($type='backup')
{
$ret['log_list']['file']=array();
$log=new WPvivid_Staging_Log_Free();
$dir=$log->GetSaveLogFolder();
$files=array();
$error_files=array();
$handler=opendir($dir);
$regex='#^wpvivid.*_log.txt#';
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.$filename))
{
continue;
}else{
if(preg_match($regex,$filename))
{
$files[$filename] = $dir.$filename;
}
}
}
}
if($handler)
@closedir($handler);
}
$dir.='error'.DIRECTORY_SEPARATOR;
if(file_exists($dir))
{
$handler=opendir($dir);
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.$filename))
{
continue;
}else{
if(preg_match($regex,$filename))
{
$error_files[$filename] = $dir.$filename;
}
}
}
}
if($handler)
@closedir($handler);
}
}
foreach ($files as $file)
{
$handle = @fopen($file, "r");
if ($handle)
{
$log_file=array();
$log_file['file_name']=basename($file);
$log_file['id']='';
if(preg_match('/wpvivid-(.*?)_/', basename($file), $matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
$log_file['id']=$id;
}
$log_file['path']=$file;
$log_file['des']='';
$log_file['time']='';
$log_file['error']=false;
if(preg_match('/error/', $file))
{
$log_file['result']='failed';
}
else
{
$log_file['result']='success';
}
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Log created: ');
if($pos!==false)
{
$log_file['time']=substr ($line,$pos+strlen('Log created: '));
}
}
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Type: ');
if($pos!==false)
{
$log_file['des']=substr ($line,$pos+strlen('Type: '));
}
else
{
$log_file['des']='other';
}
}
fclose($handle);
if(preg_match('#'.$type.'#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if($type=='other')
{
if(preg_match('#scan#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#export#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#Add Remote Test Connection #',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#upload#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#import#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#transfer#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#other#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
}
}
}
foreach ($error_files as $file)
{
$handle = @fopen($file, "r");
if ($handle)
{
$log_file=array();
$log_file['file_name']=basename($file);
$log_file['id']='';
if(preg_match('/wpvivid-(.*?)_/', basename($file), $matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
$log_file['id']=$id;
}
$log_file['path']=$file;
$log_file['des']='';
$log_file['time']='';
$log_file['error']=true;
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Log created: ');
if($pos!==false)
{
$log_file['time']=substr ($line,$pos+strlen('Log created: '));
}
}
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Type: ');
if($pos!==false)
{
$log_file['des']=substr ($line,$pos+strlen('Type: '));
}
else
{
$log_file['des']='other';
}
}
fclose($handle);
if(preg_match('#'.$type.'#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if($type=='other')
{
if(preg_match('#scan#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#export#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#Add Remote Test Connection #',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#upload#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#import#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#transfer#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
else if(preg_match('#other#',$log_file['des']))
{
$ret['log_list']['file'][basename($file)]=$log_file;
}
}
}
}
$ret['log_list']['file'] =$this->sort_list($ret['log_list']['file']);
return $ret;
}
public function sort_list($list)
{
uasort ($list,function($a, $b)
{
if($a['error']>$b['error'])
{
return -1;
}
else if($a['error']<$b['error'])
{
return 1;
}
if($a['time']>$b['time'])
{
return -1;
}
else if($a['time']===$b['time'])
{
return 0;
}
else
{
return 1;
}
});
return $list;
}
public function get_log_list_page()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$page = sanitize_key($_POST['page']);
$type=sanitize_text_field($_POST['type']);
$loglist = $this->get_log_list($type);
$table = new WPvivid_Staging_Log_List_Free();
$table->set_log_list($loglist['log_list']['file'], $page);
$table->prepare_items();
ob_start();
$table->display();
$rows = ob_get_clean();
$ret['result'] = 'success';
$ret['rows'] = $rows;
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function view_log_ex()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
if (isset($_POST['log']) && !empty($_POST['log']) && is_string($_POST['log']))
{
$log = sanitize_text_field($_POST['log']);
$loglist=$this->get_log_list_ex();
if(isset($loglist['log_list']['file'][$log]))
{
$log=$loglist['log_list']['file'][$log];
}
else
{
$json['result'] = 'failed';
$json['error'] = __('The log not found.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$path=$log['path'];
if (!file_exists($path))
{
$json['result'] = 'failed';
$json['error'] = __('The log not found.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$file = fopen($path, 'r');
if (!$file) {
$json['result'] = 'failed';
$json['error'] = __('Unable to open the log file.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
die();
}
$buffer = '';
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
$json['result'] = 'success';
$json['data'] = $buffer;
echo wp_json_encode($json);
} else {
$json['result'] = 'failed';
$json['error'] = __('Reading the log failed. Please try again.', 'wpvivid-backuprestore');
echo wp_json_encode($json);
}
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function get_log_list_ex()
{
$ret['log_list']['file']=array();
$log=new WPvivid_Staging_Log_Free();
$dir=$log->GetSaveLogFolder();
$files=array();
$error_files=array();
$handler=opendir($dir);
$regex='#^wpvivid.*_log.txt#';
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.$filename))
{
continue;
}else{
if(preg_match($regex,$filename))
{
$files[$filename] = $dir.$filename;
}
}
}
}
if($handler)
@closedir($handler);
}
$dir.='error'.DIRECTORY_SEPARATOR;
if(file_exists($dir))
{
$handler=opendir($dir);
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.$filename))
{
continue;
}else{
if(preg_match($regex,$filename))
{
$error_files[$filename] = $dir.$filename;
}
}
}
}
if($handler)
@closedir($handler);
}
}
foreach ($files as $file)
{
$handle = @fopen($file, "r");
if ($handle)
{
$log_file=array();
$log_file['file_name']=basename($file);
$log_file['path']=$file;
$log_file['des']='';
$log_file['time']='';
$log_file['error']=false;
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Log created: ');
if($pos!==false)
{
$log_file['time']=substr ($line,$pos+strlen('Log created: '));
}
}
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Type: ');
if($pos!==false)
{
$log_file['des']=substr ($line,$pos+strlen('Type: '));
}
else
{
$log_file['des']='other';
}
}
$ret['log_list']['file'][basename($file)]=$log_file;
fclose($handle);
}
}
foreach ($error_files as $file)
{
$handle = @fopen($file, "r");
if ($handle)
{
$log_file=array();
$log_file['file_name']=basename($file);
$log_file['path']=$file;
$log_file['des']='';
$log_file['time']='';
$log_file['error']=true;
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Log created: ');
if($pos!==false)
{
$log_file['time']=substr ($line,$pos+strlen('Log created: '));
}
}
$line = fgets($handle);
if($line!==false)
{
$pos=strpos($line,'Type: ');
if($pos!==false)
{
$log_file['des']=substr ($line,$pos+strlen('Type: '));
}
else
{
$log_file['des']='other';
}
}
$ret['log_list']['file'][basename($file)]=$log_file;
fclose($handle);
}
}
$ret['log_list']['file'] =$this->sort_list($ret['log_list']['file']);
return $ret;
}
public function download_log()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$admin_url=apply_filters('wpvividstg_get_admin_url', '') . 'admin.php?page=wpvividstg-log';
try
{
if (isset($_REQUEST['log']))
{
$log = sanitize_text_field($_REQUEST['log']);
$loglist=$this->get_log_list_ex();
if(isset($loglist['log_list']['file'][$log]))
{
$log=$loglist['log_list']['file'][$log];
}
else
{
$message= __('The log not found.', 'wpvivid-backuprestore');
echo sprintf(
esc_html($message). '%1$stry again%2$s.',
'<a href="' . esc_url($admin_url) . '">',
'</a>'
);
//echo __($message.' <a href="'.$admin_url.'">retry</a> again.');
die();
}
$path=$log['path'];
if (!file_exists($path))
{
$message= __('The log not found.', 'wpvivid-backuprestore');
echo sprintf(
esc_html($message). '%1$stry again%2$s.',
'<a href="' . esc_url($admin_url) . '">',
'</a>'
);
//echo __($message.' <a href="'.$admin_url.'">retry</a> again.');
die();
}
if (file_exists($path))
{
if (session_id())
session_write_close();
$size = filesize($path);
if (!headers_sent())
{
header('Content-Description: File Transfer');
header('Content-Type: text');
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . $size);
header('Content-Transfer-Encoding: binary');
}
if ($size < 1024 * 1024 * 60) {
ob_end_clean();
readfile($path);
exit;
} else {
ob_end_clean();
$download_rate = 1024 * 10;
$file = fopen($path, "r");
while (!feof($file)) {
@set_time_limit(20);
// send the current file part to the browser
print fread($file, round($download_rate * 1024));
// flush the content to the browser
flush();
if (ob_get_level())
{
ob_end_clean();
}
// sleep one second
sleep(1);
}
fclose($file);
exit;
}
}
else
{
echo sprintf(
'File not found. Please %1$stry again%2$s.',
'<a href="' . esc_url($admin_url) . '">',
'</a>'
);
//echo __(' file not found. please <a href="'.$admin_url.'">retry</a> again.');
die();
}
} else {
$message = __('Reading the log failed. Please try again.', 'wpvivid-backuprestore');
echo sprintf(
esc_html($message). '%1$stry again%2$s.',
'<a href="' . esc_url($admin_url) . '">',
'</a>'
);
//echo __($message.' <a href="'.$admin_url.'">retry</a> again.');
die();
}
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo sprintf(
'An exception has occurred. class: %1$s; msg: %2$s; code: %3$s; line: %4$s; in_file: %5$s. Please %6$stry again%7$s.',
esc_html(get_class($error)),
esc_html($error->getMessage()),
esc_html($error->getCode()),
esc_html($error->getLine()),
esc_html($error->getFile()),
'<a href="' . esc_url($admin_url) . '">',
'</a>'
);
//echo __($message.' <a href="'.$admin_url.'">retry</a> again.');
die();
}
}
} includes/staging/class-wpvivid-staging-ui-display.php 0000644 00000270222 15132770567 0017044 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
if ( ! class_exists( 'WP_List_Table' ) )
{
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class WPvivid_Staging_Custom_Select_List_Free
{
public $parent_id;
public $is_staging_site = false;
public $staging_home_path = false;
public $custom_core_path;
public $custom_theme_path;
public $custom_plugin_path;
public $custom_uploads_path;
public $custom_content_path;
public $custom_additional_file_path;
public function __construct(){
}
public function set_parent_id($parent_id){
$this->parent_id = $parent_id;
}
public function set_staging_home_path($is_staging_site=false, $staging_home_path=false){
$this->is_staging_site = $is_staging_site;
$this->staging_home_path = $staging_home_path;
}
public function display_rows(){
$core_check = 'checked';
$database_check = 'checked';
$themes_check = 'checked';
$plugins_check = 'checked';
$uploads_check = 'checked';
$content_check = 'checked';
$additional_folder_check = '';
$theme_exclude_extension = '';
$plugin_exclude_extension = '';
$upload_exclude_extension = '';
$content_exclude_extension = '';
$additional_folder_exclude_extension = '';
$database_part_check = 'checked="checked"';
$file_part_check = 'checked="checked"';
$exclude_part_check = 'checked="checked"';
if($this->is_staging_site){
$border_css = 'border: 1px solid #f1f1f1;';
$checkbox_disable = '';
$core_descript = 'If the staging site and the live site have the same version of WordPress. Then it is not necessary to copy the WordPress core files to the live site.';
$db_descript = 'It is recommended to copy all tables of the database to the live site.';
$themes_plugins_descript = 'The activated plugins and themes will be copied to the live site by default. The Child theme must be copied if it exists';
$uploads_descript = 'Images and media files are stored in the Uploads directory by default. All files are copied to the live site by default. You can exclude folders you do not want to copy.';
$contents_descript = '<strong style="text-decoration:underline;"><i>Exclude</i></strong> folders you do not want to copy to the live site, except for the wp-content/uploads folder.';
$additional_file_descript = '<strong style="text-decoration:underline;"><i>Include</i></strong> additional files or folders you want to copy to the live site.';
}
else{
$border_css = 'border: none;';
$checkbox_disable = ' disabled';
$core_descript = 'These are the essential files for creating a staging site.';
$db_descript = 'The tables created by WordPress are required for the staging site. Database tables created by themes or plugins are optional.';
$themes_plugins_descript = 'The activated plugins and themes will be copied to a staging site by default. A Child theme must be copied if it exists.';
$uploads_descript = 'Images and media files are stored in the Uploads directory by default. All files are copied to the staging site by default. You can exclude folders you do not want to copy.';
$contents_descript = '<strong style="text-decoration:underline;"><i>Exclude</i></strong> folders you do not want to copy to the staging site, except for the wp-content/uploads folder.';
$additional_file_descript = '<strong style="text-decoration:underline;"><i>Include</i></strong> additional files or folders you want to copy to the staging site.';
$options = get_option('wpvivid_staging_history', array());
if(isset($options['additional_file_check'])) {
$additional_folder_check = $options['additional_file_check'] == '1' ? 'checked' : '';
}
if(isset($options['upload_extension']) && !empty($options['upload_extension'])){
$upload_exclude_extension = implode(",", $options['upload_extension']);
}
if(isset($options['content_extension']) && !empty($options['content_extension'])){
$content_exclude_extension = implode(",", $options['content_extension']);
}
if(isset($options['additional_file_extension']) && !empty($options['additional_file_extension'])){
$additional_folder_exclude_extension = implode(",", $options['additional_file_extension']);
}
}
?>
<div>
<span><input type="checkbox" class="wpvivid-custom-database-part" <?php echo esc_attr($database_part_check.$checkbox_disable); ?>></span>
<span class="dashicons dashicons-admin-site-alt3 wpvivid-dashicons-blue"></span>
<span class="wpvivid-handle-database-detail" style="cursor:pointer;"><strong>Database Will Be Copied</strong></span>
<span class="dashicons dashicons-editor-help wpvivid-dashicons-editor-help wpvivid-tooltip">
<div class="wpvivid-bottom">
<!-- The content you need -->
<p>Won't back up any tables or additional databases if uncheck this.</p>
<i></i> <!-- do not delete this line -->
</div>
</span>
</div>
<!-- files begin -->
<div style="margin-top:1em;">
<span><input type="checkbox" class="wpvivid-custom-file-part" <?php echo esc_attr($file_part_check.$checkbox_disable); ?>></span>
<span class="dashicons dashicons-portfolio wpvivid-dashicons-orange"></span>
<span class="wpvivid-handle-file-detail" style="cursor:pointer;"><strong>Files & Folders Will Be Copied</strong></span>
<span class="wpvivid-handle-file-detail" style="cursor:pointer;"> (</span><span class="wpvivid-total-file-size">calculating</span><span>)</span>
<span class="dashicons dashicons-editor-help wpvivid-dashicons-editor-help wpvivid-tooltip">
<div class="wpvivid-bottom">
<!-- The content you need -->
<p>Won't back up any files or folders if uncheck this.</p>
<i></i> <!-- do not delete this line -->
</div>
</span>
<span class="dashicons dashicons-arrow-down-alt2 wpvivid-dashicons-grey wpvivid-handle-file-detail" style="cursor:pointer;"></span>
</div>
<div class="wpvivid-file-detail" style="padding-left:2em; display: none;">
<p><span><input class="wpvivid-custom-core-check" type="checkbox" <?php echo esc_attr($core_check.$checkbox_disable); ?>><span><strong>Wordpress Core<span> (</span><span class="wpvivid-core-size">calculating</span><span>)</span>: </strong>includes <code>wp-admin</code> folder,<code>wp-includes</code> folder and all other essential files.</span></span></p>
<p><span><input class="wpvivid-custom-themes-check" type="checkbox" <?php echo esc_attr($themes_check.$checkbox_disable); ?>><span><strong>Themes<span> (</span><span class="wpvivid-themes-size">calculating</span><span>)</span>: </strong>includes all folders of themes.</span></p>
<p><span><input class="wpvivid-custom-plugins-check" type="checkbox" <?php echo esc_attr($plugins_check.$checkbox_disable); ?>><span><strong>Plugins<span> (</span><span class="wpvivid-plugins-size">calculating</span><span>)</span>: </strong>includes all folders of plugins.</span></p>
<p><span><input class="wpvivid-custom-content-check" type="checkbox" <?php echo esc_attr($content_check.$checkbox_disable); ?>><span><strong>Wp-content<span> (</span><span class="wpvivid-content-size">calculating</span><span>)</span>: </strong>everything in <code>wp-content</code> <strong>except for</strong> <code>themes</code>, <code>plugins</code> and <code>uploads</code> folders.</span></span></p>
<p><span><input class="wpvivid-custom-uploads-check" type="checkbox" <?php echo esc_attr($uploads_check.$checkbox_disable); ?>><span><strong>Uploads<span> (</span><span class="wpvivid-uploads-size">calculating</span><span>)</span>: </strong>includes images, videos, and any other files such as PDF documents, MS Word docs, and GIFs.</span></span></p>
<p>
<span><input class="wpvivid-custom-additional-folder-check" type="checkbox" disabled><span><strong>Additional Files/Folders<span> (</span><span>pro feature</span><span>)</span>: </strong>all folders/files in root directory of your website except for Wordpress core folders/files.</span></span>
</p>
<p></p>
<div class="wpvivid-additional-folder-detail" style="display: none;">
<div style="padding-left:2em;margin-top:1em;">
<div style="border-bottom:1px solid #eee;border-top:1px solid #eee;">
<p><span class="dashicons dashicons-lightbulb wpvivid-dashicons-orange"></span><span><code>CTRL</code> + <code>Left Click</code> to select multiple files or folders.</span></p>
</div>
</div>
<div style="width:30%;float:left;box-sizing:border-box;padding-right:0.5em;padding-left:2em;">
<div>
<p>
<span class="dashicons dashicons-networking wpvivid-dashicons-blue"></span>
<span><strong>Tree View</strong></span>
<span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-refresh-include-tree">Refresh<span>
</p>
</div>
<div class="wpvivid-custom-additional-folder-tree-info" style="margin-top:10px;height:250px;border:1px solid #eee;padding:0.2em 0.5em;overflow:auto;">Tree Viewer</div>
<div style="clear:both;"></div>
<div style="padding:1em 0 0 0;"><input class="button-primary wpvivid-include-additional-folder-btn" type="submit" value="Include Files/Folders"></div>
</div>
<div style="width:70%; float:left;box-sizing:border-box;padding-left:0.5em;">
<div>
<p>
<span class="dashicons dashicons-portfolio wpvivid-dashicons-orange"></span>
<span><strong>Additional Files/Folders Will Be Backed Up</strong></span>
</p>
</div>
<div class="wpvivid-custom-include-additional-folder-list" style="height:250px;border:1px solid #eee;padding:0.2em 0.5em;overflow-y:auto;">
<?php $this->wpvivid_load_custom_exclude_list('additional-folder'); ?>
</div>
<div style="padding:1em 0 0 0;"><span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-clear-custom-include-list" style="float:right;">Empty Included Files/Folders</span></div>
</div>
</div>
</div>
<div style="clear:both;"></div>
<!-- files end -->
<div style="box-sizing:border-box; margin-top:1em;">
<!-- exclude tree begin -->
<div style="margin-top:1em;">
<span><input type="checkbox" class="wpvivid-custom-exclude-part" disabled></span>
<span class="dashicons dashicons-portfolio wpvivid-dashicons-grey"></span>
<span class="wpvivid-handle-tree-detail" style="cursor:pointer;"><strong>Exclude Additional Files/Folders (pro feature)</strong></span>
</div>
<div class="wpvivid-tree-detail" style="display: none;">
<div style="padding-left:2em;margin-top:1em;">
<div style="border-bottom:1px solid #eee;border-top:1px solid #eee;">
<p><span class="dashicons dashicons-lightbulb wpvivid-dashicons-orange"></span><span><code>CTRL</code> + <code>Left Click</code> to select multiple files or folders.</span></p>
</div>
</div>
<div style="width:30%;float:left;box-sizing:border-box;padding-right:0.5em;padding-left:2em;">
<div>
<p>
<span class="dashicons dashicons-networking wpvivid-dashicons-blue"></span>
<span><strong>Folder Tree View</strong></span>
<span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-refresh-exclude-tree">Refresh<span>
</p>
</div>
<div style="height:250px;">
<div>
<select name="action" class="wpvivid-custom-tree-selector" style="width:100%;border:1px solid #aaa;">
<option value="themes" selected>themes</option>
<option value="plugins">plugins</option>
<option value="content">wp-content</option>
<option value="uploads">uploads</option>
</select>
</div>
<div class="wpvivid-custom-exclude-tree-info" style="margin-top:10px;height:210px;border:1px solid #eee;padding:0.2em 0.5em;overflow:auto;">Tree Viewer
</div>
</div>
<div style="clear:both;"></div>
<div style="padding:1.5em 0 0 0;"><input class="button-primary wpvivid-custom-tree-exclude-btn" type="submit" value="Exclude Files/Folders"></div>
</div>
<div style="width:70%; float:left;box-sizing:border-box;padding-left:0.5em;">
<div>
<p>
<span class="dashicons dashicons-portfolio wpvivid-dashicons-orange"></span>
<span><strong>Excluded Files/Folders/File Types</strong></span>
</p>
</div>
<!-- themes -->
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-themes-module">
<input type="text" class="wpvivid-themes-extension" style="width:100%; border:1px solid #aaa;" value="<?php echo esc_attr($theme_exclude_extension); ?>" placeholder="Exclude file types, separate by comma - for example: gif, jpg, webp, pdf" />
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-themes-module wpvivid-custom-exclude-themes-list" style="margin-top:10px;height:210px;border:1px solid #eee;padding:0.2em 0.5em;overflow-y:auto;">
<?php $this->wpvivid_load_custom_exclude_list('themes'); ?>
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-themes-module" style="padding:1em 0 0 0;"><span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-clear-custom-exclude-list" style="float:right;">Empty Excluded Files/Folders</span></div>
<!-- plugins -->
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-plugins-module" style="display: none;">
<input type="text" class="wpvivid-plugins-extension" style="width:100%; border:1px solid #aaa;" value="<?php echo esc_attr($plugin_exclude_extension); ?>" placeholder="Exclude file types, separate by comma - for example: gif, jpg, webp, pdf" />
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-plugins-module wpvivid-custom-exclude-plugins-list" style="margin-top:10px;height:210px;border:1px solid #eee;padding:0.2em 0.5em;overflow-y:auto;display: none;">
<?php $this->wpvivid_load_custom_exclude_list('plugins'); ?>
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-plugins-module" style="padding:1em 0 0 0;display: none;"><span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-clear-custom-exclude-list" style="float:right;">Empty Excluded Files/Folders</span></div>
<!-- content -->
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-content-module" style="display: none;">
<input type="text" class="wpvivid-content-extension" style="width:100%; border:1px solid #aaa;" value="<?php echo esc_attr($content_exclude_extension); ?>" placeholder="Exclude file types, separate by comma - for example: gif, jpg, webp, pdf" />
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-content-module wpvivid-custom-exclude-content-list" style="margin-top:10px;height:210px;border:1px solid #eee;padding:0.2em 0.5em;overflow-y:auto;display: none;">
<?php $this->wpvivid_load_custom_exclude_list('content'); ?>
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-content-module" style="padding:1em 0 0 0;display: none;"><span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-clear-custom-exclude-list" style="float:right;">Empty Excluded Files/Folders</span></div>
<!-- uploads -->
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-uploads-module" style="display: none;">
<input type="text" class="wpvivid-uploads-extension" style="width:100%; border:1px solid #aaa;" value="<?php echo esc_attr($upload_exclude_extension); ?>" placeholder="Exclude file types, separate by comma - for example: gif, jpg, webp, pdf" />
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-uploads-module wpvivid-custom-exclude-uploads-list" style="margin-top:10px;height:210px;border:1px solid #eee;padding:0.2em 0.5em;overflow-y:auto;display: none;">
<?php $this->wpvivid_load_custom_exclude_list('uploads'); ?>
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-uploads-module" style="padding:1em 0 0 0;display: none;"><span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-clear-custom-exclude-list" style="float:right;">Empty Excluded Files/Folders</span></div>
</div>
</div>
<div style="clear:both;"></div>
<!-- exculde tree end -->
</div>
<?php
}
public function wpvivid_load_custom_exclude_list($backup_type){
$list_type = 'themes_list';
if($backup_type == 'themes'){
$list_type = 'themes_list';
}
else if($backup_type == 'plugins'){
$list_type = 'plugins_list';
}
else if($backup_type == 'content'){
$list_type = 'content_list';
}
else if($backup_type == 'uploads'){
$list_type = 'uploads_list';
}
else if($backup_type == 'additional-folder'){
$list_type = 'additional_file_list';
}
$options = get_option('wpvivid_staging_history', array());
$ret = '';
//fix old data
$need_fix = false;
if($backup_type == 'themes'){
if(isset($options['themes_list']) && !empty($options['themes_list'])){
foreach ($options['themes_list'] as $index => $value) {
if(!isset($value['type'])){
$need_fix = true;
$options['themes_list'][$value]['name'] = $value;
$options['themes_list'][$value]['type'] = 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer';
unset($options['themes_list'][$index]);
}
}
}
}
else if($backup_type == 'plugins'){
if(isset($options['plugins_list']) && !empty($options['plugins_list'])){
foreach ($options['plugins_list'] as $index => $value) {
if(!isset($value['type'])){
$need_fix = true;
$options['plugins_list'][$value]['name'] = $value;
$options['plugins_list'][$value]['type'] = 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer';
unset($options['plugins_list'][$index]);
}
}
}
}
if($need_fix){
update_option('wpvivid_staging_history', $options, 'no');
}
if(isset($options[$list_type]) && !empty($options[$list_type])) {
foreach ($options[$list_type] as $index => $value) {
if(isset($value['type'])){
if($value['type'] === 'wpvivid-custom-li-folder-icon'){
$value['type'] = 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer';
}
else if($value['type'] === 'wpvivid-custom-li-file-icon'){
$value['type'] = 'dashicons dashicons-media-default wpvivid-dashicons-grey wpvivid-icon-16px-nopointer';
}
$class_type = $value['type'];
$exclude_name = $value['name'];
if($value['type'] === 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer'){
$type = 'folder';
}
else{
$type = 'file';
}
}
else{
$class_type = 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer';
$exclude_name = $value;
$type = 'folder';
}
echo '<div class="wpvivid-text-line" type="'.esc_attr($type).'">
<span class="dashicons dashicons-trash wpvivid-icon-16px wpvivid-remove-custom-exlcude-tree"></span><span class="'.esc_attr($class_type).'"></span><span class="wpvivid-text-line">'.esc_html($exclude_name).'</span>
</div>';
}
}
return $ret;
}
public function load_js(){
$core_dir = $this->is_staging_site === false ? str_replace('\\','/',get_home_path()) : str_replace('\\','/',$this->staging_home_path);
$this->custom_core_path = $core_dir;
$upload_dir = wp_upload_dir();
$upload_path = $this->is_staging_site === false ? $upload_dir['basedir'] : $this->staging_home_path.'/wp-content/uploads';
$upload_path = str_replace('\\','/',$upload_path);
$upload_path = $upload_path.'/';
$this->custom_uploads_path = $upload_path;
$content_dir = $this->is_staging_site === false ? WP_CONTENT_DIR : $this->staging_home_path.'/wp-content';
$content_path = str_replace('\\','/',$content_dir);
$content_path = $content_path.'/';
$this->custom_content_path = $content_path;
$additional_file_path = $this->is_staging_site === false ? str_replace('\\','/',get_home_path()) : str_replace('\\','/',$this->staging_home_path);
$this->custom_additional_file_path = $additional_file_path;
$theme_dir = $this->is_staging_site === false ? str_replace('\\','/', get_theme_root()) : str_replace('\\','/', $this->staging_home_path.'/wp-content/themes');
$this->custom_theme_path = $theme_dir.'/';
$plugin_dir = $this->is_staging_site === false ? str_replace('\\','/', WP_PLUGIN_DIR) : str_replace('\\','/', $this->staging_home_path.'/wp-content/plugins');
$this->custom_plugin_path = $plugin_dir.'/';
?>
<script>
var path_arr = {};
path_arr['core'] = '<?php echo esc_attr($this->custom_core_path); ?>';
path_arr['content'] = '<?php echo esc_attr($this->custom_content_path); ?>';
path_arr['uploads'] = '<?php echo esc_attr($this->custom_uploads_path); ?>';
path_arr['themes'] = '<?php echo esc_attr($this->custom_theme_path); ?>';
path_arr['plugins'] = '<?php echo esc_attr($this->custom_plugin_path); ?>';
function wpvivid_handle_custom_open_close_ex(handle_obj, obj, parent_id){
if(obj.is(":hidden")) {
handle_obj.each(function(){
if(jQuery(this).hasClass('dashicons-arrow-down-alt2')){
jQuery(this).removeClass('dashicons-arrow-down-alt2');
jQuery(this).addClass('dashicons-arrow-up-alt2');
}
});
obj.show();
}
else{
handle_obj.each(function(){
if(jQuery(this).hasClass('dashicons-arrow-up-alt2')){
jQuery(this).removeClass('dashicons-arrow-up-alt2');
jQuery(this).addClass('dashicons-arrow-down-alt2');
}
});
obj.hide();
}
}
function wpvivid_change_custom_exclude_info(type, parent_id){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-module').hide();
if(type === 'themes'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-themes-module').show();
}
else if(type === 'plugins'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-plugins-module').show();
}
else if(type === 'content'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-content-module').show();
}
else if(type === 'uploads'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-uploads-module').show();
}
}
function wpvivid_check_tree_repeat(tree_type, value, parent_id) {
if(tree_type === 'themes'){
var list = 'wpvivid-custom-exclude-themes-list';
}
else if(tree_type === 'plugins'){
var list = 'wpvivid-custom-exclude-plugins-list';
}
else if(tree_type === 'content'){
var list = 'wpvivid-custom-exclude-content-list';
}
else if(tree_type === 'uploads'){
var list = 'wpvivid-custom-exclude-uploads-list';
}
else if(tree_type === 'additional-folder'){
var list = 'wpvivid-custom-include-additional-folder-list';
}
var brepeat = false;
jQuery('#'+parent_id).find('.'+list+' div').find('span:eq(2)').each(function (){
if (value === this.innerHTML) {
brepeat = true;
}
});
return brepeat;
}
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-handle-base-database-detail', function(){
var handle_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-handle-base-database-detail');
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-base-database-detail');
wpvivid_handle_custom_open_close_ex(handle_obj, obj, '<?php echo esc_attr($this->parent_id); ?>');
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-handle-file-detail', function(){
var handle_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-handle-file-detail');
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-file-detail');
wpvivid_handle_custom_open_close_ex(handle_obj, obj, '<?php echo esc_attr($this->parent_id); ?>');
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('change', '.wpvivid-custom-tree-selector', function(){
var value = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-tree-selector').val();
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-exclude-tree-info').jstree("destroy").empty();
wpvivid_change_custom_exclude_info(value, '<?php echo esc_attr($this->parent_id); ?>');
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-refresh-include-tree', function(){
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-refresh-exclude-tree', function(){
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-include-additional-folder-btn', function(){
var select_folders = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-additional-folder-tree-info').jstree(true).get_selected(true);
var tree_path = '<?php echo esc_attr($this->custom_additional_file_path); ?>';
var list_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-include-additional-folder-list');
var tree_type = 'additional-folder';
jQuery.each(select_folders, function (index, select_item) {
if (select_item.id !== tree_path) {
var value = select_item.id;
value = value.replace(tree_path, '');
if (!wpvivid_check_tree_repeat(tree_type, value, '<?php echo esc_attr($this->parent_id); ?>')) {
var class_name = select_item.icon;
if(class_name === 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer'){
var type = 'folder';
}
else{
var type = 'file';
}
var tr = "<div class='wpvivid-text-line' type='"+type+"'>" +
"<span class='dashicons dashicons-trash wpvivid-icon-16px wpvivid-remove-custom-exlcude-tree'></span>" +
"<span class='"+class_name+"'></span>" +
"<span class='wpvivid-text-line'>" + value + "</span>" +
"</div>";
list_obj.append(tr);
}
}
});
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-remove-custom-exlcude-tree', function(){
jQuery(this).parent().remove();
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-clear-custom-include-list', function(){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-include-additional-folder-list').html('');
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-clear-custom-exclude-list', function(){
var tree_type = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-tree-selector').val();
if(tree_type === 'themes'){
var list = 'wpvivid-custom-exclude-themes-list';
}
else if(tree_type === 'plugins'){
var list = 'wpvivid-custom-exclude-plugins-list';
}
else if(tree_type === 'content'){
var list = 'wpvivid-custom-exclude-content-list';
}
else if(tree_type === 'uploads'){
var list = 'wpvivid-custom-exclude-uploads-list';
}
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.'+list).html('');
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-database-table-check', function(){
if(jQuery(this).prop('checked')){
if(jQuery(this).hasClass('wpvivid-database-base-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-database-other-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-database-diff-prefix-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=diff_prefix_db][name=Database]').prop('checked', true);
}
}
else{
if (jQuery(this).hasClass('wpvivid-database-base-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').prop('checked', false);
}
else if (jQuery(this).hasClass('wpvivid-database-other-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').prop('checked', false);
}
else if (jQuery(this).hasClass('wpvivid-database-diff-prefix-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=diff_prefix_db][name=Database]').prop('checked', false);
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=base_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-base-table-check').prop('checked', true);
}
}
else{
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-base-table-check').prop('checked', false);
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=other_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-other-table-check').prop('checked', true);
}
}
else{
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-other-table-check').prop('checked', false);
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=diff_prefix_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=diff_prefix_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-diff-prefix-table-check').prop('checked', true);
}
}
else{
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-diff-prefix-table-check').prop('checked', false);
}
});
function wpvivid_get_database_size(){
var ajax_data = {
'action': 'wpvividstg_get_custom_database_size_free'
};
wpvivid_post_request(ajax_data, function (data) {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result == 'success') {
jQuery('.wpvivid-database-size').html(jsonarray.database_size);
}
else {
alert(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('retrieving the last backup log', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_get_files_size(){
var ajax_data = {
'action': 'wpvividstg_get_custom_files_size_free'
};
wpvivid_post_request(ajax_data, function (data) {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result == 'success') {
jQuery('.wpvivid-core-size').html(jsonarray.core_size);
jQuery('.wpvivid-themes-size').html(jsonarray.themes_size);
jQuery('.wpvivid-plugins-size').html(jsonarray.plugins_size);
jQuery('.wpvivid-uploads-size').html(jsonarray.uploads_size);
jQuery('.wpvivid-content-size').html(jsonarray.content_size);
jQuery('.wpvivid-additional-folder-size').html(jsonarray.additional_size);
jQuery('.wpvivid-total-file-size').html(jsonarray.total_file_size);
}
else {
alert(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('retrieving the last backup log', textStatus, errorThrown);
alert(error_message);
});
}
jQuery(document).ready(function () {
wpvivid_get_database_size();
wpvivid_get_files_size();
});
</script>
<?php
}
}
class WPvivid_Staging_Custom_MU_Select_List_Free{
public $parent_id;
public $is_staging_site = false;
public $is_sync_site = false;
public $staging_home_path = false;
public $custom_core_path;
public $custom_theme_path;
public $custom_plugin_path;
public $custom_uploads_path;
public $custom_content_path;
public $custom_additional_file_path;
public function __construct(){
}
public function set_parent_id($parent_id){
$this->parent_id = $parent_id;
}
public function set_staging_home_path($is_staging_site=false, $is_sync_site=false, $staging_home_path=false){
$this->is_staging_site = $is_staging_site;
$this->is_sync_site = $is_sync_site;
$this->staging_home_path = $staging_home_path;
}
public function display_rows(){
$core_check = 'checked';
$database_check = 'checked';
$themes_check = 'checked';
$plugins_check = 'checked';
$uploads_check = 'checked';
$content_check = 'checked';
$additional_folder_check = '';
$theme_exclude_extension = '';
$plugin_exclude_extension = '';
$upload_exclude_extension = '';
$content_exclude_extension = '';
$additional_folder_exclude_extension = '';
$database_part_check = 'checked="checked"';
$file_part_check = 'checked="checked"';
$exclude_part_check = 'checked="checked"';
$db_descript = 'All the tables in the WordPress MU database except for subsites tables.';
$uploads_descript = 'The folder where images and media files of the main site are stored by default. All files will be copied to the staging site by default. You can exclude folders you do not want to copy.';
$core_descript = 'These are the essential files for creating a staging site.';
$themes_plugins_descript = 'All the plugins and themes files used by the MU network. The activated plugins and themes will be copied to the staging site by default. A child theme must be copied if it exists.';
$contents_descript = '<strong style="text-decoration:underline;"><i>Exclude</i></strong> folders you do not want to copy to the staging site, except for the wp-content/uploads folder.';
$additional_file_descript = '<strong style="text-decoration:underline;"><i>Include</i></strong> additional files or folders you want to copy to the staging site.';
?>
<div>
<span><input type="checkbox" class="wpvivid-custom-database-part" <?php echo esc_attr($database_part_check); ?> disabled></span>
<span class="dashicons dashicons-admin-site-alt3 wpvivid-dashicons-blue"></span>
<span class="wpvivid-handle-database-detail" style="cursor:pointer;"><strong>Database Will Be Copied</strong></span>
<span class="wpvivid-handle-database-detail" style="cursor:pointer;"> (</span><span class="wpvivid-database-size">calculating</span><span>)</span>
<span class="dashicons dashicons-editor-help wpvivid-dashicons-editor-help wpvivid-tooltip">
<div class="wpvivid-bottom">
<!-- The content you need -->
<p>Won't back up any tables or additional databases if uncheck this.</p>
<i></i> <!-- do not delete this line -->
</div>
</span>
</div>
<div class="wpvivid-database-detail" style="display: none;">
<!-- database begin -->
<div style="padding-left:2em;">
<p><span><input type="checkbox" class="wpvivid-custom-database-check" <?php echo esc_attr($database_check); ?> disabled><span class="wpvivid-handle-base-database-detail" style="cursor:pointer;"><strong>Tables In The Wordpress Database</strong></span></span></p>
</div>
<div style="clear:both;"></div>
<!-- database end -->
</div>
<!-- files begin -->
<div style="margin-top:1em;">
<span><input type="checkbox" class="wpvivid-custom-file-part" <?php echo esc_attr($file_part_check); ?> disabled></span>
<span class="dashicons dashicons-portfolio wpvivid-dashicons-orange"></span>
<span class="wpvivid-handle-file-detail" style="cursor:pointer;"><strong>Files & Folders Will Be Copied</strong></span>
<span class="wpvivid-handle-file-detail" style="cursor:pointer;"> (</span><span class="wpvivid-total-file-size">calculating</span><span>)</span>
<span class="dashicons dashicons-editor-help wpvivid-dashicons-editor-help wpvivid-tooltip">
<div class="wpvivid-bottom">
<!-- The content you need -->
<p>Won't back up any files or folders if uncheck this.</p>
<i></i> <!-- do not delete this line -->
</div>
</span>
<span class="dashicons dashicons-arrow-down-alt2 wpvivid-dashicons-grey wpvivid-handle-file-detail" style="cursor:pointer;"></span>
</div>
<div class="wpvivid-file-detail" style="padding-left:2em; display: none;">
<p><span><input class="wpvivid-custom-core-check" type="checkbox" <?php echo esc_attr($core_check); ?> disabled><span><strong>Wordpress Core<span> (</span><span class="wpvivid-core-size">calculating</span><span>)</span>: </strong>includes <code>wp-admin</code> folder,<code>wp-includes</code> folder and all other essential files.</span></span></p>
<p><span><input class="wpvivid-custom-themes-check" type="checkbox" <?php echo esc_attr($themes_check); ?> disabled><span><strong>Themes<span> (</span><span class="wpvivid-themes-size">calculating</span><span>)</span>: </strong>includes all folders of themes.</span></p>
<p><span><input class="wpvivid-custom-plugins-check" type="checkbox" <?php echo esc_attr($plugins_check); ?> disabled><span><strong>Plugins<span> (</span><span class="wpvivid-plugins-size">calculating</span><span>)</span>: </strong>includes all folders of plugins.</span></p>
<p><span><input class="wpvivid-custom-content-check" type="checkbox" <?php echo esc_attr($content_check); ?> disabled><span><strong>Wp-content<span> (</span><span class="wpvivid-content-size">calculating</span><span>)</span>: </strong>everything in <code>wp-content</code> <strong>except for</strong> <code>themes</code>, <code>plugins</code> and <code>uploads</code> folders.</span></span></p>
<p><span><input class="wpvivid-custom-uploads-check" type="checkbox" <?php echo esc_attr($uploads_check); ?> disabled><span><strong>Uploads<span> (</span><span class="wpvivid-uploads-size">calculating</span><span>)</span>: </strong>includes images, videos, and any other files such as PDF documents, MS Word docs, and GIFs.</span></span></p>
<p>
<span><input class="wpvivid-custom-additional-folder-check" type="checkbox" disabled><span><strong>Additional Files/Folders<span> (</span><span class="wpvivid-additional-folder-size">calculating</span><span>)</span>: </strong>all folders/files in root directory of your website except for Wordpress core folders/files.</span></span>
</p>
<p></p>
<div class="wpvivid-additional-folder-detail" style="display: none;">
<div style="padding-left:2em;margin-top:1em;">
<div style="border-bottom:1px solid #eee;border-top:1px solid #eee;">
<p><span class="dashicons dashicons-lightbulb wpvivid-dashicons-orange"></span><span><code>CTRL</code> + <code>Left Click</code> to select multiple files or folders.</span></p>
</div>
</div>
<div style="width:30%;float:left;box-sizing:border-box;padding-right:0.5em;padding-left:2em;">
<div>
<p>
<span class="dashicons dashicons-networking wpvivid-dashicons-blue"></span>
<span><strong>Tree View</strong></span>
<span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-refresh-include-tree">Refresh<span>
</p>
</div>
<div class="wpvivid-custom-additional-folder-tree-info" style="margin-top:10px;height:250px;border:1px solid #eee;padding:0.2em 0.5em;overflow:auto;">Tree Viewer</div>
<div style="clear:both;"></div>
<div style="padding:1em 0 0 0;"><input class="button-primary wpvivid-include-additional-folder-btn" type="submit" value="Include Files/Folders"></div>
</div>
<div style="width:70%; float:left;box-sizing:border-box;padding-left:0.5em;">
<div>
<p>
<span class="dashicons dashicons-portfolio wpvivid-dashicons-orange"></span>
<span><strong>Additional Files/Folders Will Be Backed Up</strong></span>
</p>
</div>
<div class="wpvivid-custom-include-additional-folder-list" style="height:250px;border:1px solid #eee;padding:0.2em 0.5em;overflow-y:auto;"></div>
<div style="padding:1em 0 0 0;"><span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-clear-custom-include-list" style="float:right;">Empty Included Files/Folders</span></div>
</div>
</div>
</div>
<div style="clear:both;"></div>
<!-- files end -->
<div style="box-sizing:border-box; margin-top:1em;">
<!-- exclude tree begin -->
<div style="margin-top:1em;">
<span><input type="checkbox" class="wpvivid-custom-exclude-part" disabled></span>
<span class="dashicons dashicons-portfolio wpvivid-dashicons-grey"></span>
<span class="wpvivid-handle-tree-detail" style="cursor:pointer;"><strong>Exclude Additional Files/Folders (pro feature)</strong></span>
</div>
<div class="wpvivid-tree-detail" style="display: none;">
<div style="padding-left:2em;margin-top:1em;">
<div style="border-bottom:1px solid #eee;border-top:1px solid #eee;">
<p><span class="dashicons dashicons-lightbulb wpvivid-dashicons-orange"></span><span><code>CTRL</code> + <code>Left Click</code> to select multiple files or folders.</span></p>
</div>
</div>
<div style="width:30%;float:left;box-sizing:border-box;padding-right:0.5em;padding-left:2em;">
<div>
<p>
<span class="dashicons dashicons-networking wpvivid-dashicons-blue"></span>
<span><strong>Folder Tree View</strong></span>
<span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-refresh-exclude-tree">Refresh<span>
</p>
</div>
<div style="height:250px;">
<div>
<select name="action" class="wpvivid-custom-tree-selector" style="width:100%;border:1px solid #aaa;">
<option value="themes" selected>themes</option>
<option value="plugins">plugins</option>
<option value="content">wp-content</option>
<option value="uploads">uploads</option>
</select>
</div>
<div class="wpvivid-custom-exclude-tree-info" style="margin-top:10px;height:210px;border:1px solid #eee;padding:0.2em 0.5em;overflow:auto;">Tree Viewer
</div>
</div>
<div style="clear:both;"></div>
<div style="padding:1.5em 0 0 0;"><input class="button-primary wpvivid-custom-tree-exclude-btn" type="submit" value="Exclude Files/Folders"></div>
</div>
<div style="width:70%; float:left;box-sizing:border-box;padding-left:0.5em;">
<div>
<p>
<span class="dashicons dashicons-portfolio wpvivid-dashicons-orange"></span>
<span><strong>Excluded Files/Folders/File Types</strong></span>
</p>
</div>
<!-- themes -->
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-themes-module">
<input type="text" class="wpvivid-themes-extension" style="width:100%; border:1px solid #aaa;" value="<?php echo esc_attr($theme_exclude_extension); ?>" placeholder="Exclude file types, separate by comma - for example: gif, jpg, webp, pdf" />
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-themes-module wpvivid-custom-exclude-themes-list" style="margin-top:10px;height:210px;border:1px solid #eee;padding:0.2em 0.5em;overflow-y:auto;"></div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-themes-module" style="padding:1em 0 0 0;"><span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-clear-custom-exclude-list" style="float:right;">Empty Excluded Files/Folders</span></div>
<!-- plugins -->
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-plugins-module" style="display: none;">
<input type="text" class="wpvivid-plugins-extension" style="width:100%; border:1px solid #aaa;" value="<?php echo esc_attr($plugin_exclude_extension); ?>" placeholder="Exclude file types, separate by comma - for example: gif, jpg, webp, pdf" />
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-plugins-module wpvivid-custom-exclude-plugins-list" style="margin-top:10px;height:210px;border:1px solid #eee;padding:0.2em 0.5em;overflow-y:auto;display: none;"></div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-plugins-module" style="padding:1em 0 0 0;display: none;"><span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-clear-custom-exclude-list" style="float:right;">Empty Excluded Files/Folders</span></div>
<!-- content -->
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-content-module" style="display: none;">
<input type="text" class="wpvivid-content-extension" style="width:100%; border:1px solid #aaa;" value="<?php echo esc_attr($content_exclude_extension); ?>" placeholder="Exclude file types, separate by comma - for example: gif, jpg, webp, pdf" />
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-content-module wpvivid-custom-exclude-content-list" style="margin-top:10px;height:210px;border:1px solid #eee;padding:0.2em 0.5em;overflow-y:auto;display: none;"></div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-content-module" style="padding:1em 0 0 0;display: none;"><span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-clear-custom-exclude-list" style="float:right;">Empty Excluded Files/Folders</span></div>
<!-- uploads -->
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-uploads-module" style="display: none;">
<input type="text" class="wpvivid-uploads-extension" style="width:100%; border:1px solid #aaa;" value="<?php echo esc_attr($upload_exclude_extension); ?>" placeholder="Exclude file types, separate by comma - for example: gif, jpg, webp, pdf" />
</div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-uploads-module wpvivid-custom-exclude-uploads-list" style="margin-top:10px;height:210px;border:1px solid #eee;padding:0.2em 0.5em;overflow-y:auto;display: none;"></div>
<div class="wpvivid-custom-exclude-module wpvivid-custom-exclude-uploads-module" style="padding:1em 0 0 0;display: none;"><span class="wpvivid-rectangle wpvivid-grey-light wpvivid-hover-blue wpvivid-clear-custom-exclude-list" style="float:right;">Empty Excluded Files/Folders</span></div>
</div>
</div>
<div style="clear:both;"></div>
<!-- exculde tree end -->
</div>
<?php
}
public function load_js(){
$core_dir = $this->is_staging_site === false ? str_replace('\\','/',get_home_path()) : str_replace('\\','/',$this->staging_home_path);
$this->custom_core_path = $core_dir;
$upload_dir = wp_upload_dir();
$upload_path = $this->is_staging_site === false ? $upload_dir['basedir'] : $this->staging_home_path.'/wp-content/uploads';
$upload_path = str_replace('\\','/',$upload_path);
$upload_path = $upload_path.'/';
$this->custom_uploads_path = $upload_path;
$content_dir = $this->is_staging_site === false ? WP_CONTENT_DIR : $this->staging_home_path.'/wp-content';
$content_path = str_replace('\\','/',$content_dir);
$content_path = $content_path.'/';
$this->custom_content_path = $content_path;
$additional_file_path = $this->is_staging_site === false ? str_replace('\\','/',get_home_path()) : str_replace('\\','/',$this->staging_home_path);
$this->custom_additional_file_path = $additional_file_path;
$theme_dir = $this->is_staging_site === false ? str_replace('\\','/', get_theme_root()) : str_replace('\\','/', $this->staging_home_path.'/wp-content/themes');
$this->custom_theme_path = $theme_dir.'/';
$plugin_dir = $this->is_staging_site === false ? str_replace('\\','/', WP_PLUGIN_DIR) : str_replace('\\','/', $this->staging_home_path.'/wp-content/plugins');
$this->custom_plugin_path = $plugin_dir.'/';
?>
<script>
var path_arr = {};
path_arr['core'] = '<?php echo esc_attr($this->custom_core_path); ?>';
path_arr['content'] = '<?php echo esc_attr($this->custom_content_path); ?>';
path_arr['uploads'] = '<?php echo esc_attr($this->custom_uploads_path); ?>';
path_arr['themes'] = '<?php echo esc_attr($this->custom_theme_path); ?>';
path_arr['plugins'] = '<?php echo esc_attr($this->custom_plugin_path); ?>';
function wpvivid_handle_custom_open_close_ex(handle_obj, obj, parent_id){
if(obj.is(":hidden")) {
handle_obj.each(function(){
if(jQuery(this).hasClass('dashicons-arrow-down-alt2')){
jQuery(this).removeClass('dashicons-arrow-down-alt2');
jQuery(this).addClass('dashicons-arrow-up-alt2');
}
});
obj.show();
}
else{
handle_obj.each(function(){
if(jQuery(this).hasClass('dashicons-arrow-up-alt2')){
jQuery(this).removeClass('dashicons-arrow-up-alt2');
jQuery(this).addClass('dashicons-arrow-down-alt2');
}
});
obj.hide();
}
}
function wpvivid_change_custom_exclude_info(type, parent_id){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-module').hide();
if(type === 'themes'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-themes-module').show();
}
else if(type === 'plugins'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-plugins-module').show();
}
else if(type === 'content'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-content-module').show();
}
else if(type === 'uploads'){
jQuery('#'+parent_id).find('.wpvivid-custom-exclude-uploads-module').show();
}
}
function wpvivid_check_tree_repeat(tree_type, value, parent_id) {
if(tree_type === 'themes'){
var list = 'wpvivid-custom-exclude-themes-list';
}
else if(tree_type === 'plugins'){
var list = 'wpvivid-custom-exclude-plugins-list';
}
else if(tree_type === 'content'){
var list = 'wpvivid-custom-exclude-content-list';
}
else if(tree_type === 'uploads'){
var list = 'wpvivid-custom-exclude-uploads-list';
}
else if(tree_type === 'additional-folder'){
var list = 'wpvivid-custom-include-additional-folder-list';
}
var brepeat = false;
jQuery('#'+parent_id).find('.'+list+' div').find('span:eq(2)').each(function (){
if (value === this.innerHTML) {
brepeat = true;
}
});
return brepeat;
}
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-handle-base-database-detail', function(){
var handle_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-handle-base-database-detail');
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-base-database-detail');
wpvivid_handle_custom_open_close_ex(handle_obj, obj, '<?php echo esc_attr($this->parent_id); ?>');
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-handle-file-detail', function(){
var handle_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-handle-file-detail');
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-file-detail');
wpvivid_handle_custom_open_close_ex(handle_obj, obj, '<?php echo esc_attr($this->parent_id); ?>');
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('change', '.wpvivid-custom-tree-selector', function(){
var value = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-tree-selector').val();
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-exclude-tree-info').jstree("destroy").empty();
wpvivid_change_custom_exclude_info(value, '<?php echo esc_attr($this->parent_id); ?>');
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-refresh-include-tree', function(){
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-refresh-exclude-tree', function(){
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-include-additional-folder-btn', function(){
var select_folders = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-additional-folder-tree-info').jstree(true).get_selected(true);
var tree_path = '<?php echo esc_attr($this->custom_additional_file_path); ?>';
var list_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-include-additional-folder-list');
var tree_type = 'additional-folder';
jQuery.each(select_folders, function (index, select_item) {
if (select_item.id !== tree_path) {
var value = select_item.id;
value = value.replace(tree_path, '');
if (!wpvivid_check_tree_repeat(tree_type, value, '<?php echo esc_attr($this->parent_id); ?>')) {
var class_name = select_item.icon;
if(class_name === 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer'){
var type = 'folder';
}
else{
var type = 'file';
}
var tr = "<div class='wpvivid-text-line' type='"+type+"'>" +
"<span class='dashicons dashicons-trash wpvivid-icon-16px wpvivid-remove-custom-exlcude-tree'></span>" +
"<span class='"+class_name+"'></span>" +
"<span class='wpvivid-text-line'>" + value + "</span>" +
"</div>";
list_obj.append(tr);
}
}
});
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-custom-tree-exclude-btn', function(){
var select_folders = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-exclude-tree-info').jstree(true).get_selected(true);
var tree_type = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-tree-selector').val();
var tree_path = path_arr[tree_type];
if(tree_type === 'themes'){
var list_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-exclude-themes-list');
}
else if(tree_type === 'plugins'){
var list_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-exclude-plugins-list');
}
else if(tree_type === 'content'){
var list_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-exclude-content-list');
}
else if(tree_type === 'uploads'){
var list_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-exclude-uploads-list');
}
jQuery.each(select_folders, function (index, select_item) {
if (select_item.id !== tree_path) {
var value = select_item.id;
value = value.replace(tree_path, '');
if (!wpvivid_check_tree_repeat(tree_type, value, '<?php echo esc_attr($this->parent_id); ?>')) {
var class_name = select_item.icon;
if(class_name === 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer'){
var type = 'folder';
}
else{
var type = 'file';
}
var tr = "<div class='wpvivid-text-line' type='"+type+"'>" +
"<span class='dashicons dashicons-trash wpvivid-icon-16px wpvivid-remove-custom-exlcude-tree'></span>" +
"<span class='"+class_name+"'></span>" +
"<span class='wpvivid-text-line'>" + value + "</span>" +
"</div>";
list_obj.append(tr);
}
}
});
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-remove-custom-exlcude-tree', function(){
jQuery(this).parent().remove();
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-clear-custom-include-list', function(){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-include-additional-folder-list').html('');
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-clear-custom-exclude-list', function(){
var tree_type = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-tree-selector').val();
if(tree_type === 'themes'){
var list = 'wpvivid-custom-exclude-themes-list';
}
else if(tree_type === 'plugins'){
var list = 'wpvivid-custom-exclude-plugins-list';
}
else if(tree_type === 'content'){
var list = 'wpvivid-custom-exclude-content-list';
}
else if(tree_type === 'uploads'){
var list = 'wpvivid-custom-exclude-uploads-list';
}
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.'+list).html('');
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on('click', '.wpvivid-database-table-check', function(){
if(jQuery(this).prop('checked')){
if(jQuery(this).hasClass('wpvivid-database-base-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-database-other-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-database-diff-prefix-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=diff_prefix_db][name=Database]').prop('checked', true);
}
}
else{
if (jQuery(this).hasClass('wpvivid-database-base-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').prop('checked', false);
}
else if (jQuery(this).hasClass('wpvivid-database-other-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').prop('checked', false);
}
else if (jQuery(this).hasClass('wpvivid-database-diff-prefix-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=diff_prefix_db][name=Database]').prop('checked', false);
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=base_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-base-table-check').prop('checked', true);
}
}
else{
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-base-table-check').prop('checked', false);
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=other_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-other-table-check').prop('checked', true);
}
}
else{
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-other-table-check').prop('checked', false);
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=diff_prefix_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=diff_prefix_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-diff-prefix-table-check').prop('checked', true);
}
}
else{
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-diff-prefix-table-check').prop('checked', false);
}
});
function wpvivid_get_database_size(){
var ajax_data = {
'action': 'wpvividstg_get_custom_database_size_free'
};
wpvivid_post_request(ajax_data, function (data) {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result == 'success') {
jQuery('.wpvivid-database-size').html(jsonarray.database_size);
}
else {
alert(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('retrieving the last backup log', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_get_files_size(){
var ajax_data = {
'action': 'wpvividstg_get_custom_files_size_free'
};
wpvivid_post_request(ajax_data, function (data) {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result == 'success') {
jQuery('.wpvivid-core-size').html(jsonarray.core_size);
jQuery('.wpvivid-themes-size').html(jsonarray.themes_size);
jQuery('.wpvivid-plugins-size').html(jsonarray.plugins_size);
jQuery('.wpvivid-uploads-size').html(jsonarray.uploads_size);
jQuery('.wpvivid-content-size').html(jsonarray.content_size);
jQuery('.wpvivid-additional-folder-size').html(jsonarray.additional_size);
jQuery('.wpvivid-total-file-size').html(jsonarray.total_file_size);
}
else {
alert(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('retrieving the last backup log', textStatus, errorThrown);
alert(error_message);
});
}
jQuery(document).ready(function () {
wpvivid_get_database_size();
wpvivid_get_files_size();
});
</script>
<?php
}
}
class WPvivid_Staging_UI_Display_Free
{
public $main_tab;
public $staging_list_ui;
public $staging_create_ui;
public $fresh_install_ui;
public $log_page;
public function __construct()
{
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-list-ui-display.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-create-ui-display.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-fresh-install-create-ui-display.php';
$this->staging_list_ui=new WPvivid_Staging_List_UI_Display_Free();
$this->staging_create_ui=new WPvivid_Staging_Create_UI_Display_Free();
$this->fresh_install_ui=new WPvivid_Fresh_Install_Create_UI_Display_Free();
$this->log_page=new WPvivid_Staging_Log_Page_Free();
}
public function get_staging_site_data()
{
if(is_multisite())
{
switch_to_blog(get_main_site_id());
$staging=get_option('wpvivid_staging_data',false);
restore_current_blog();
}
else
{
$staging=get_option('wpvivid_staging_data',false);
}
return $staging;
}
public static function wpvivid_check_site_url()
{
$site_url = site_url();
$home_url = home_url();
$site_url = untrailingslashit($site_url);
$home_url = untrailingslashit($home_url);
$db_site_url = '';
$db_home_url = '';
global $wpdb;
$site_url_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->options WHERE option_name = %s", 'siteurl' ) );
$home_url_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->options WHERE option_name = %s", 'home' ) );
foreach ( $site_url_sql as $site ){
$db_site_url = $site->option_value;
}
foreach ( $home_url_sql as $home ){
$db_home_url = $home->option_value;
}
if($site_url !== $db_site_url || $home_url !== $db_home_url){
echo '<div class="notice notice-warning inline"><p><strong>Warning:</strong> An inconsistency was detected between the site url, home url of the database and the actual website url.
This can cause inappropriate staging site url issues. Please change the site url and home url in the Options table of the database to the actual
url of your website. For example, if the site url and home url of the database is http://test.com, but the actual url of your website is https://test.com.
You’ll need to change the http to https.
</p></div>';
}
}
public static function wpvivid_check_login_url()
{
$home_url = home_url();
global $wpdb;
$home_url_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->options WHERE option_name = %s", 'home' ) );
foreach ( $home_url_sql as $home ){
$home_url = $home->option_value;
}
$home_url = untrailingslashit($home_url);
$login_url = wp_login_url();
$login_name = str_replace($home_url, '', $login_url);
$login_name = trim($login_name, '/');
if($login_name !== 'wp-login.php')
{
?>
<div class="notice notice-warning inline is-dismissible">
<p>
<strong>Warning:</strong> We detected that the login url of your live site is not the default '/wp-login.php'. <a href="https://docs.wpvivid.com/wpvivid-staging-site-login-issue.html" target="_blank">Learn more</a>
</p>
</div>
<?php
}
}
public function init_page()
{
$options=get_option('wpvivid_staging_options',array());
if(isset( $options['staging_request_timeout']))
{
$request_timeout=$options['staging_request_timeout'];
}
else
{
$request_timeout=1500;
}
?>
<div class="wrap" style="max-width:1720px;">
<h1>
<?php esc_html_e('WPvivid Plugins - Staging', 'wpvivid-backuprestore' ); ?>
</h1>
<?php self::wpvivid_check_site_url(); ?>
<?php self::wpvivid_check_login_url(); ?>
<script>
function wpvivid_include_exclude_folder(type, parent_id, tree_path)
{
var select_folders = '';
if (type === 'uploads')
{
select_folders = jQuery('#' + parent_id).find('.wpvivid-custom-uploads-tree-info').jstree(true).get_selected(true);
var list_obj = jQuery('#' + parent_id).find('.wpvivid-custom-exclude-uploads-list');
}
if (type === 'content')
{
select_folders = jQuery('#' + parent_id).find('.wpvivid-custom-content-tree-info').jstree(true).get_selected(true);
var list_obj = jQuery('#' + parent_id).find('.wpvivid-custom-exclude-content-list');
}
if (type === 'additional_file')
{
select_folders = jQuery('#' + parent_id).find('.wpvivid-custom-additional-file-tree-info').jstree(true).get_selected(true);
var list_obj = jQuery('#' + parent_id).find('.wpvivid-custom-include-additional-file-list');
}
jQuery.each(select_folders, function (index, select_item)
{
if (select_item.id !== tree_path)
{
var value = select_item.id;
value = value.replace(tree_path, '');
if (!wpvivid_check_custom_tree_repeat(type, value, parent_id))
{
var class_name = select_item.icon === 'jstree-folder' ? 'wpvivid-custom-li-folder-icon' : 'wpvivid-custom-li-file-icon';
var tr = "<ul style='margin: 0;'>" +
"<li>" +
"<div class='" + class_name + "'></div>" +
"<div class='wpvivid-custom-li-font'>" + value + "</div>" +
"<div class='wpvivid-custom-li-close' onclick='wpvivid_remove_custom_tree(this);' title='Remove' style='cursor: pointer;'>X</div>" +
"</li>" +
"</ul>";
list_obj.append(tr);
}
}
});
}
function wpvivid_check_custom_tree_repeat(type, value, parent_id)
{
var brepeat = false;
var list_class = 'wpvivid-custom-exclude-uploads-list';
if (type === 'uploads')
{
list_class = 'wpvivid-custom-exclude-uploads-list';
}
if (type === 'content')
{
list_class = 'wpvivid-custom-exclude-content-list';
}
if (type === 'additional_file')
{
list_class = 'wpvivid-custom-include-additional-file-list';
}
jQuery('#' + parent_id).find('.' + list_class + ' ul').find('li div:eq(1)').each(function ()
{
if (value === this.innerHTML)
{
brepeat = true;
}
});
return brepeat;
}
function wpvivid_remove_custom_tree(obj)
{
jQuery(obj).parent().parent().remove();
}
var staging_requet_timeout=<?php echo esc_attr($request_timeout) ?>;
var archieve_info = {};
archieve_info.src_db_retry = 0;
archieve_info.src_theme_retry = 0;
archieve_info.des_db_retry = 0;
archieve_info.des_theme_retry = 0;
function wpvivid_refresh_staging_database(parent_id, is_staging, staging_site_id) {
if(is_staging == '1')
{
archieve_info.des_db_retry = 0;
}
else
{
archieve_info.src_db_retry = 0;
}
var custom_database_loading = '<div class="spinner" style="margin: 0 5px 10px 0; float: left;"></div>' +
'<div style="float: left;">Archieving database tables</div>' +
'<div style="clear: both;"></div>';
jQuery('#' + parent_id).find('.wpvivid-custom-database-info').html('');
jQuery('#' + parent_id).find('.wpvivid-custom-database-info').html(custom_database_loading);
wpvivid_get_custom_database_tables_info(parent_id, is_staging, staging_site_id);
}
function wpvivid_get_custom_database_tables_info(parent_id, is_staging, staging_site_id) {
var id = staging_site_id;
var ajax_data = {
'action': 'wpvividstg_get_custom_database_tables_info_free',
'id': id,
'is_staging': is_staging
};
wpvivid_post_request(ajax_data, function (data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#' + parent_id).find('.wpvivid-custom-database-info').html('');
jQuery('#' + parent_id).find('.wpvivid-custom-database-info').html(jsonarray.html);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var need_retry_custom_database = false;
var retry_times=0;
if(is_staging == '1')
{
archieve_info.des_db_retry++;
retry_times = archieve_info.des_db_retry;
}
else{
archieve_info.src_db_retry++;
retry_times = archieve_info.src_db_retry;
}
if(retry_times < 10){
need_retry_custom_database = true;
}
if(need_retry_custom_database)
{
setTimeout(function()
{
wpvivid_get_custom_database_tables_info(parent_id, is_staging, staging_site_id);
}, 3000);
}
else{
var refresh_btn = '<input type="submit" class="button-primary" value="Refresh" onclick="wpvivid_refresh_staging_database(\''+parent_id+'\', \''+is_staging+'\', \''+staging_site_id+'\');">';
jQuery('#' + parent_id).find('.wpvivid-custom-database-info').html('');
jQuery('#' + parent_id).find('.wpvivid-custom-database-info').html(refresh_btn);
}
});
}
function load_js(parent_id, is_staging, theme_path, plugin_path, upload_path, content_path, home_path, staging_site_id = '')
{
var tree_path = theme_path;
var path_arr = {};
path_arr['core'] = home_path;
path_arr['content'] = content_path;
path_arr['uploads'] = upload_path;
path_arr['themes'] = theme_path;
path_arr['plugins'] = plugin_path;
jQuery('#'+parent_id).on('click', '.wpvivid-custom-tree-exclude-btn', function(){
var select_folders = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-tree-info').jstree(true).get_selected(true);
var tree_type = jQuery('#'+parent_id).find('.wpvivid-custom-tree-selector').val();
var tree_path = path_arr[tree_type];
if(tree_type === 'themes'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-themes-list');
}
else if(tree_type === 'plugins'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-plugins-list');
}
else if(tree_type === 'content'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-content-list');
}
else if(tree_type === 'uploads'){
var list_obj = jQuery('#'+parent_id).find('.wpvivid-custom-exclude-uploads-list');
}
jQuery.each(select_folders, function (index, select_item) {
if (select_item.id !== tree_path) {
var value = select_item.id;
value = value.replace(tree_path, '');
if (!wpvivid_check_tree_repeat(tree_type, value, parent_id)) {
var class_name = select_item.icon;
if(class_name === 'dashicons dashicons-category wpvivid-dashicons-orange wpvivid-icon-16px-nopointer'){
var type = 'folder';
}
else{
var type = 'file';
}
var tr = "<div class='wpvivid-text-line' type='"+type+"'>" +
"<span class='dashicons dashicons-trash wpvivid-icon-16px wpvivid-remove-custom-exlcude-tree'></span>" +
"<span class='"+class_name+"'></span>" +
"<span class='wpvivid-text-line'>" + value + "</span>" +
"</div>";
list_obj.append(tr);
}
}
});
});
if(is_staging){
is_staging = '1';
}
else{
is_staging = '0';
}
wpvivid_get_custom_database_tables_info(parent_id, is_staging, staging_site_id);
}
</script>
<?php
$data=$this->get_staging_site_data();
$args['is_parent_tab']=1;
$this->main_tab=new WPvivid_Tab_Page_Container();
if($data===false)
{
$this->main_tab->add_tab('Staging Sites','staging_sites',array($this->staging_list_ui, 'output_staging_sites_list_page'), $args);
$this->main_tab->add_tab('Create A Staging Site','create_staging',array($this->staging_create_ui, 'output_create_staging_site_page'), $args);
if(!is_multisite())
{
$this->main_tab->add_tab('Create A Fresh WP Install','create_fresh_install',array($this->fresh_install_ui, 'output_create_wp_page'), $args);
}
}
else
{
$this->main_tab->add_tab('Staging Sites','staging_sites',array($this->staging_list_ui, 'output_staging'), $args);
}
$this->main_tab->display();
?>
<script>
function switch_staging_tab(id)
{
jQuery( document ).trigger( '<?php echo esc_attr($this->main_tab->container_id) ?>-show',id);
}
</script>
</div>
<?php
}
} includes/staging/class-wpvivid-staging-create-ui-display.php 0000644 00000143416 15132770567 0020311 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Staging_Create_UI_Display_Free
{
public function __construct()
{
}
public function get_database_home_url()
{
$home_url = home_url();
global $wpdb;
$home_url_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->options WHERE option_name = %s", 'home' ) );
foreach ( $home_url_sql as $home ){
$home_url = $home->option_value;
}
return untrailingslashit($home_url);
}
public function output_create_staging_site_page()
{
update_option('wpvivid_current_running_staging_task','','no');
update_option('wpvivid_staging_task_cancel', false,'no');
$home_url = $this->get_database_home_url();
$admin_url = admin_url();
$admin_name = basename($admin_url);
$admin_name = trim($admin_name, '/');
$home_path = get_home_path();
$staging_num = 1;
$staging_dir = 'mystaging01';
$staging_content_dir = 'mystaging01';
$default_staging_site = 'mystaging01';
while(1){
$default_staging_site = 'mystaging'.sprintf("%02d", $staging_num);
$staging_dir = $home_path.$default_staging_site;
if(!file_exists($staging_dir)){
break;
}
$staging_num++;
}
$content_dir = WP_CONTENT_DIR;
$content_dir = str_replace('\\','/',$content_dir);
$content_path = $content_dir.'/';
$staging_num = 1;
$default_content_staging_site='mystaging01';
while(1){
$default_content_staging_site = 'mystaging'.sprintf("%02d", $staging_num);
$staging_dir = $content_path.$default_content_staging_site;
if(!file_exists($staging_dir)){
break;
}
$staging_num++;
}
global $wpdb;
$prefix='';
$site_id=1;
$base_prefix=$wpdb->base_prefix;
while(1)
{
if($site_id<10)
{
$prefix='wpvividstg0'.$site_id.'_';
}
else
{
$prefix='wpvividstg'.$site_id.'_';
}
$sql=$wpdb->prepare("SHOW TABLES LIKE %s;", $wpdb->esc_like($prefix) . '%');
$result = $wpdb->get_results($sql, OBJECT_K);
if(empty($result))
{
break;
}
$site_id++;
}
?>
<div class="postbox quickstaging">
<div class="wpvivid-one-coloum" id="wpvivid_create_staging_step1" style="border:1px solid #f1f1f1;padding-bottom:0em; margin-top:0em;margin-bottom:1em;">
<div class="wpvivid-one-coloum" style="background:#f5f5f5;padding-top:0em;padding-bottom:0em;display: none;">
<div class="wpvivid-two-col">
<p><span class="dashicons dashicons-awards wpvivid-dashicons-blue"></span><span><strong>Site Name: </strong></span><span class="wpvivid-staging-site-name"><?php echo esc_html($default_staging_site); ?></span></p>
<p><span class="dashicons dashicons-admin-site-alt3 wpvivid-dashicons-blue"></span><span><strong>Database Name: </strong></span><span class="wpvivid-staging-additional-database-name-display"><?php echo esc_html(DB_NAME); ?></span></p>
<p><span class="dashicons dashicons-list-view wpvivid-dashicons-blue"></span><span><strong>Table Prefix: </strong></span><span class="wpvivid-staging-table-prefix-display"><?php echo esc_html($prefix); ?></span></p>
</div>
<div class="wpvivid-two-col">
<!--<p><span class="dashicons dashicons-admin-site-alt3 wpvivid-dashicons-blue"></span><span><strong>Database Name:</strong></span><span>admin06</span></p>-->
<p><span class="dashicons dashicons-admin-home wpvivid-dashicons-blue"></span><span><strong>Home URL: </strong></span><span class="wpvivid-staging-home-url"><?php echo esc_url($home_url); ?>/</span><span class="wpvivid-staging-site-name"><?php echo esc_html($default_staging_site); ?></span></p>
<p><span class="dashicons dashicons-rest-api wpvivid-dashicons-blue"></span><span><strong>Admin URL: </strong></span><span class="wpvivid-staging-home-url"><?php echo esc_url($home_url); ?>/</span><span class="wpvivid-staging-site-name"><?php echo esc_html($default_staging_site); ?></span><span>/<?php echo esc_html($admin_name); ?></span></p>
</div>
</div>
<div>
<div>
<h2 style="padding-left:1em;padding-top:0.6em; background:#f1f1f1;">
<span class="dashicons dashicons-portfolio wpvivid-dashicons-orange"></span>
<span>Directory to Install the Staging Site</span>
</h2>
<?php
$server_type = $_SERVER['SERVER_SOFTWARE'];
if(preg_match('/nginx/i', $server_type))
{
?>
<div style="border:1px solid #ccc; padding:0 1em;margin-top:1em; border-radius:0.5em;">
<p>
<span>We detected that your web server is Nginx, please add specific rewrite rules to the Nginx config file for the staging site working properly. <a href="https://docs.wpvivid.com/add-rewrite-rules-to-nginx.html">How to</a></span>
<p>
<div style="clear:both;"></div>
</div>
<?php
}
?>
<p>
<label>
<input type="radio" name="choose_staging_dir" value="0" checked="checked">
<span>website root</span>
</label>
<label>
<input type="radio" name="choose_staging_dir" value="1">
<span>/wp-content/</span>
</label>
<label>
<input type="radio" name="choose_staging_dir" value="2" disabled>
<span>subdomain(pro feature)</span>
</label>
</p>
<div id="wpvivid_staging_part" style="border-left: 4px solid #007cba;padding-left:1em;">
<p>
<input type="text" id="wpvivid_staging_path" placeholder="<?php echo esc_attr($default_staging_site); ?>" value="<?php echo esc_attr($default_staging_site); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9]/g,'')" onpaste="value=value.replace(/[^\a-\z\A-\Z0-9]/g,'')"><span> Custom directory</span>
</p>
<p>
<span class="dashicons dashicons-admin-home wpvivid-dashicons-blue"></span><span>Home Url: </span><span class="wpvivid-staging-home-url"><?php echo esc_url($home_url); ?>/</span><span class="wpvivid-staging-site-name"><?php echo esc_html($default_staging_site); ?></span>
<span style="margin-left:1em;" class="dashicons dashicons-portfolio wpvivid-dashicons-blue"></span><span><strong>Directory:</strong></span>
<span><?php echo esc_html(untrailingslashit(ABSPATH)); ?>/</span><span class="wpvivid-staging-site-name"><?php echo esc_html($default_staging_site); ?></span>
</p>
</div>
</div>
<h2 style="padding-left:1em;padding-top:0.6em;background:#f1f1f1;">
<span class="dashicons dashicons-cloud wpvivid-dashicons-blue"></span>
<span>Choose Database to Install the Staging Site</span>
</h2>
<p>
<input type="text" id="wpvivid_staging_table_prefix" placeholder="<?php echo esc_attr($prefix); ?>" value="<?php echo esc_attr($prefix); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9_]/g,'')" onpaste="value=value.replace(/[^\a-\z\A-\Z0-9_]/g,'')" title="Table Prefix"> Custom Table Prefix, By default: <?php echo esc_html($prefix); ?>
</p>
<p>
<label>
<input type="radio" name="choose_staging_db" value="0" checked="">
<span>Install the staging site to the live site's database (Easy setup)</span>
</label>
</p>
<p>
<label>
<input type="radio" name="choose_staging_db" value="1">
<span>Install the staging site to a separate database (Expert setup)</span>
</label>
</p>
<p></p>
<div class="" id="wpvivid_additional_database_account" style="display: none;">
<form>
<p><label><input type="text" class="wpvivid-additional-database-name" autocomplete="off" placeholder="DB Name" title="DB Name" readonly></label>
<label><input type="text" class="wpvivid-additional-database-user" autocomplete="off" placeholder="DB Username" title="DB Username" readonly></label></p>
<p><label><input type="password" class="wpvivid-additional-database-pass" autocomplete="off" placeholder="Password" title="The Password of the Database Username" readonly></label>
<label><input type="text" class="wpvivid-additional-database-host" autocomplete="off" placeholder="localhost" title="Database Host" readonly></label></p>
<p><label><input class="button-primary wpvivid_setting_general_save" type="button" id="wpvivid_connect_additional_database" onclick="wpvivid_additional_database_connect_test();" value="Test Connection" readonly></label></p>
</form>
</div>
<div style="clear: both;"></div>
</div>
</div>
<div id="wpvivid_choose_staging_content" class="wpvivid-one-coloum" style="border:1px solid #f1f1f1;padding-bottom:1em; margin-top:1em;margin-bottom:1em;">
<h2 style="padding-left:0em;">
<span class="dashicons dashicons-admin-page wpvivid-dashicons-orange"></span>
<span>Choose What to Copy to The Staging Site</span>
</h2>
<p></p>
<div>
<div id="wpvividstg_custom_backup_content">
<div id="wpvivid_custom_staging_list">
<?php
$custom_staging_list = new WPvivid_Staging_Custom_Select_List_Free();
$custom_staging_list ->set_parent_id('wpvivid_custom_staging_list');
$custom_staging_list ->set_staging_home_path();
$custom_staging_list ->display_rows();
$custom_staging_list ->load_js();
?>
</div>
</div>
<div style="clear: both;"></div>
</div>
</div>
<div id="wpvivid_create_btn" style="padding:1em 1em 0 0;">
<div id="wpvivid_create_staging_content">
<input class="button-primary wpvivid_setting_general_save" id="wpvivid_create_staging" type="submit" value="Create Now" /><span> Note: Please don't refresh the page while creating a staging site.</span>
</div>
<div style="padding:1em 1em 0 0;">
<span>Tips: Please temporarily deactivate all cache, firewall and redirect plugins before creating a staging site to rule out possibilities of unknown failures.</span>
</div>
</div>
<div id="wpvivid_create_staging_step2" style="display: none;">
<div class="wpvivid-element-space-bottom">
<input class="button button-primary" type="button" id="wpvivid_staging_cancel" value="Cancel" />
</div>
<div class="postbox wpvivid-staging-log wpvivid-element-space-bottom" id="wpvivid_staging_log" style="margin-bottom: 0;"></div>
<div class="action-progress-bar" style="margin: 10px 0 0 0; !important;">
<div class="action-progress-bar-percent" id="wpvivid_staging_progress_bar" style="height:24px;line-height:24px;width:0;">
<div style="float: left; margin-left: 4px;">0</div>
<div style="clear: both;"></div>
</div>
</div>
</div>
</div>
<script>
<?php
$upload_dir = wp_upload_dir();
$upload_path = $upload_dir['basedir'];
$upload_path = str_replace('\\','/',$upload_path);
$upload_path = $upload_path.'/';
$content_dir = WP_CONTENT_DIR;
$content_path = str_replace('\\','/',$content_dir);
$content_path = $content_path.'/';
$home_path = str_replace('\\','/', get_home_path());
$theme_path = str_replace('\\','/', get_theme_root());
$theme_path = $theme_path.'/';
$plugin_path = str_replace('\\','/', WP_PLUGIN_DIR);
$plugin_path = $plugin_path.'/';
?>
jQuery('#wpvivid_create_staging_step1').on("keyup", '#wpvivid_staging_path', function()
{
var value = jQuery('#wpvivid_create_staging_step1').find('input:radio[name=choose_staging_dir]:checked').val();
if(value === '0')
{
var staging_path = jQuery('#wpvivid_staging_path').val();
if(staging_path !== ''){
jQuery('.wpvivid-staging-site-name').html(staging_path);
}
else{
jQuery('.wpvivid-staging-site-name').html('*');
}
}
else if(value === '1')
{
var staging_path = jQuery('#wpvivid_staging_path').val();
if(staging_path !== '')
{
jQuery('.wpvivid-staging-site-name').html('wp-content/'+staging_path);
}
else{
jQuery('.wpvivid-staging-site-name').html('wp-content/*');
}
}
});
jQuery('#wpvivid_create_staging_step1').on("click", 'input:radio[name=choose_staging_db]', function(){
if(jQuery(this).prop('checked')){
var value = jQuery(this).val();
if(value === '0'){
jQuery('#wpvivid_additional_database_account').hide();
jQuery('#wpvivid_additional_database_account').find('.wpvivid-additional-database-name').attr('readonly', true);
jQuery('#wpvivid_additional_database_account').find('.wpvivid-additional-database-user').attr('readonly', true);
jQuery('#wpvivid_additional_database_account').find('.wpvivid-additional-database-pass').attr('readonly', true);
jQuery('#wpvivid_additional_database_account').find('.wpvivid-additional-database-host').attr('readonly', true);
jQuery('.wpvivid-staging-additional-database-name-display').html('<?php echo esc_html(DB_NAME); ?>');
}
else{
jQuery('#wpvivid_additional_database_account').show();
jQuery('#wpvivid_additional_database_account').find('.wpvivid-additional-database-name').attr('readonly', false);
jQuery('#wpvivid_additional_database_account').find('.wpvivid-additional-database-user').attr('readonly', false);
jQuery('#wpvivid_additional_database_account').find('.wpvivid-additional-database-pass').attr('readonly', false);
jQuery('#wpvivid_additional_database_account').find('.wpvivid-additional-database-host').attr('readonly', false);
var additional_db_name = jQuery('.wpvivid-additional-database-name').val();
if(additional_db_name !== ''){
jQuery('.wpvivid-staging-additional-database-name-display').html(additional_db_name);
}
else{
jQuery('.wpvivid-staging-additional-database-name-display').html('*');
}
wpvivid_additional_database_table_prefix();
}
}
});
var default_staging_site = '<?php echo esc_attr($default_staging_site); ?>';
var default_content_staging_site = '<?php echo esc_attr($default_content_staging_site); ?>';
var is_mu='<?php echo esc_attr(is_multisite()); ?>';
jQuery('#wpvivid_create_staging_step1').on("click", 'input:radio[name=choose_staging_dir]', function() {
if(jQuery(this).prop('checked'))
{
var value = jQuery(this).val();
if(value === '0')
{
jQuery('.wpvivid-staging-home-url').show();
jQuery('#wpvivid_staging_path_part').show();
jQuery('#wpvivid_staging_path').val(default_staging_site);
var staging_path = jQuery('#wpvivid_staging_path').val();
if(staging_path !== '')
{
jQuery('.wpvivid-staging-site-name').html(staging_path);
}
else{
jQuery('.wpvivid-staging-site-name').html('*');
}
}
else
{
jQuery('.wpvivid-staging-home-url').show();
jQuery('#wpvivid_staging_path_part').show();
jQuery('#wpvivid_staging_path').val(default_content_staging_site);
var staging_path = jQuery('#wpvivid_staging_path').val();
if(staging_path !== '')
{
jQuery('.wpvivid-staging-site-name').html('wp-content/'+staging_path);
}
else{
jQuery('.wpvivid-staging-site-name').html('wp-content/*');
}
}
}
});
jQuery('#wpvivid_create_staging_step1').on("keyup", '.wpvivid-additional-database-name', function(){
var additional_db_name = jQuery(this).val();
if(additional_db_name !== ''){
jQuery('.wpvivid-staging-additional-database-name-display').html(additional_db_name);
}
else{
jQuery('.wpvivid-staging-additional-database-name-display').html('*');
}
});
jQuery('#wpvivid_create_staging_step1').on("keyup", '#wpvivid_staging_table_prefix', function(){
wpvivid_additional_database_table_prefix();
});
function wpvivid_additional_database_table_prefix(){
var additional_db_prefix = jQuery('#wpvivid_create_staging_step1').find('#wpvivid_staging_table_prefix').val();
if(additional_db_prefix !== ''){
jQuery('#wpvivid_create_staging_step1').find('.wpvivid-staging-table-prefix-display').html(additional_db_prefix);
}
else{
jQuery('#wpvivid_create_staging_step1').find('.wpvivid-staging-table-prefix-display').html('*');
}
}
jQuery('#wpvivid_create_staging_step2').on("click", '#wpvivid_staging_cancel', function(){
wpvivid_staging_cancel();
});
function wpvivid_staging_cancel(){
var ajax_data = {
'action': 'wpvividstg_cancel_staging_free'
};
jQuery('#wpvivid_staging_cancel').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function(data){
}, function(XMLHttpRequest, textStatus, errorThrown) {
jQuery('#wpvivid_staging_cancel').css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = wpvivid_output_ajaxerror('cancelling the staging', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#wpvivid_create_staging').click(function() {
var descript = '<?php esc_html_e('Click OK to start creating the staging site.', 'wpvivid-backuprestore'); ?>';
var ret = confirm(descript);
if(ret === true){
jQuery('#wpvivid_staging_notice').hide();
wpvivid_start_staging();
}
});
jQuery('#wpvivid_mu_create_staging').click(function() {
var descript = '<?php esc_html_e('Click OK to start creating the staging site.', 'wpvivid-backuprestore'); ?>';
var ret = confirm(descript);
if(ret === true){
jQuery('#wpvivid_staging_notice').hide();
wpvivid_start_staging();
}
});
jQuery('#wpvivid_mu_single_create_staging').click(function() {
var descript = '<?php esc_html_e('Click OK to start creating the staging site.', 'wpvivid-backuprestore'); ?>';
var ret = confirm(descript);
if(ret === true){
jQuery('#wpvivid_staging_notice').hide();
wpvivid_start_staging();
}
});
function wpvivid_recreate_staging(){
jQuery('#wpvivid_choose_staging_content').show();
jQuery('#wpvivid_create_btn').show();
jQuery('#wpvivid_create_staging_step2').hide();
}
function wpvivid_create_custom_json(parent_id){
var json = {};
//exclude
json['exclude_custom'] = '0';
json['folder_check_ex'] = '0';
//core
json['core_check'] = '1';
json['core_list'] = Array();
//themes
json['themes_check'] = '1';
json['themes_list'] = {};
json['themes_extension'] = '';
//plugins
json['plugins_check'] = '1';
json['plugins_list'] = {};
json['plugins_extension'] = '';
//content
json['content_check'] = '1';
json['content_list'] = {};
json['content_extension'] = '';
//uploads
json['uploads_check'] = '1';
json['uploads_list'] = {};
json['upload_extension'] = '';
//additional folders/files
json['additional_file_check'] = '0';
json['additional_file_list'] = {};
//database
json['database_list'] = Array();
json['database_check'] = '1';
return json;
}
function wpvivid_create_staging_lock_unlock(action){
if(action === 'lock'){
jQuery('#wpvivid_create_staging_step1').find('input').attr('disabled', true);
jQuery('#wpvivid_staging_list').find('div.wpvivid-delete-staging-site').css({'pointer-events': 'none', 'opacity': '0.4'});
}
else{
jQuery('#wpvivid_create_staging_step1').find('input').attr('disabled', false);
jQuery('#wpvivid_staging_list').find('div.wpvivid-delete-staging-site').css({'pointer-events': 'auto', 'opacity': '1'});
}
}
function wpvivid_check_staging_additional_folder_valid(parent_id){
var check_status = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-additional-file-check').prop('checked')){
jQuery('#'+parent_id).find('.wpvivid-custom-include-additional-file-list ul').find('li div:eq(1)').each(function () {
check_status = true;
});
if(check_status === false){
alert('Please select at least one item under the additional files/folder option, or deselect the option.');
}
}
else{
check_status = true;
}
return check_status;
}
function wpvivid_check_backup_option_avail(parent_id, check_database_item)
{
var check_status = true;
//check is backup db or files
var has_select_db_file = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-database-part').prop('checked')){
has_select_db_file = true;
var has_db_item = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-database-check').prop('checked')){
has_db_item = true;
var has_local_table_item = false;
if(!check_database_item){
has_local_table_item = true;
}
jQuery('#'+parent_id).find('input:checkbox[name=Database]').each(function(index, value){
if(jQuery(this).prop('checked')){
has_local_table_item = true;
}
});
if(!has_local_table_item){
check_status = false;
alert('Please select at least one table to back up. Or, deselect the option \'Tables In The Wordpress Database\' under the option \'Databases Will Be Backed up\'.');
return check_status;
}
}
if(!has_db_item){
check_status = false;
alert('Please select at least one option from \'Tables In The Wordpress Database\' and \'Additional Databases\' under the option \'Databases Will Be Backed up\'. Or, deselect the option \'Databases Will Be Backed up\'.');
return check_status;
}
}
if(jQuery('#'+parent_id).find('.wpvivid-custom-file-part').prop('checked')){
has_select_db_file = true;
var has_file_item = false;
if(jQuery('#'+parent_id).find('.wpvivid-custom-core-check').prop('checked')){
has_file_item = true;
}
if(jQuery('#'+parent_id).find('.wpvivid-custom-themes-check').prop('checked')){
has_file_item = true;
}
if(jQuery('#'+parent_id).find('.wpvivid-custom-plugins-check').prop('checked')){
has_file_item = true;
}
if(jQuery('#'+parent_id).find('.wpvivid-custom-content-check').prop('checked')){
has_file_item = true;
}
if(jQuery('#'+parent_id).find('.wpvivid-custom-uploads-check').prop('checked')){
has_file_item = true;
}
if(jQuery('#'+parent_id).find('.wpvivid-custom-additional-folder-check').prop('checked')){
has_file_item = true;
var has_additional_folder = false;
jQuery('#'+parent_id).find('.wpvivid-custom-include-additional-folder-list div').find('span:eq(2)').each(function(){
has_additional_folder = true;
});
if(!has_additional_folder){
check_status = false;
alert('Please select at least one additional file or folder under the option \'Files/Folders Will Be Backed up\', Or, deselect the option \'Additional Files/Folders\'.');
return check_status;
}
}
if(!has_file_item){
check_status = false;
alert('Please select at least one option under the option \'Files/Folders Will Be Backed up\'. Or, deselect the option \'Files/Folders Will Be Backed up\'.');
return check_status;
}
}
if(!has_select_db_file){
check_status = false;
alert('Please select at least one option from \'Databases Will Be Backed up\' and \'Files/Folders Will Be Backed up\'.');
return check_status;
}
return check_status;
}
function wpvivid_start_staging()
{
var staging_root_dir='0';
jQuery('#wpvivid_create_staging_step1').find('input:radio[name=choose_staging_dir]').each(function ()
{
if (jQuery(this).prop('checked'))
{
staging_root_dir = jQuery(this).val();
}
});
var path='';
path=jQuery('#wpvivid_staging_path').val();
if(path === '')
{
alert('A site name is required.');
return;
}
var table_prefix=jQuery('#wpvivid_staging_table_prefix').val();
if(table_prefix === '')
{
alert('Table Prefix is required.');
return;
}
var additional_database_json = {};
var additional_database_option = '0';
jQuery('#wpvivid_create_staging_step1').find('input:radio[name=choose_staging_db]').each(function ()
{
if (jQuery(this).prop('checked')) {
additional_database_option = jQuery(this).val();
}
});
if (additional_database_option === '1')
{
additional_database_json['additional_database_check'] = '1';
additional_database_json['additional_database_info'] = {};
additional_database_json['additional_database_info']['db_user'] = jQuery('.wpvivid-additional-database-user').val();
additional_database_json['additional_database_info']['db_pass'] = jQuery('.wpvivid-additional-database-pass').val();
additional_database_json['additional_database_info']['db_host'] = jQuery('.wpvivid-additional-database-host').val();
additional_database_json['additional_database_info']['db_name'] = jQuery('.wpvivid-additional-database-name').val();
if (additional_database_json['additional_database_info']['db_name'] === '') {
alert('Database Name is required.');
return;
}
if (additional_database_json['additional_database_info']['db_user'] === '') {
alert('Database User is required.');
return;
}
if (additional_database_json['additional_database_info']['db_host'] === '') {
alert('Database Host is required.');
return;
}
}
else {
additional_database_json['additional_database_check'] = '0';
}
var additional_database_info = JSON.stringify(additional_database_json);
var ajax_data =
{
'action': 'wpvividstg_check_staging_dir_free',
'root_dir':staging_root_dir,
'path': path,
'table_prefix': table_prefix,
'additional_db': additional_database_info
};
wpvivid_post_request(ajax_data, function (data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
}
else
{
var ajax_data =
{
'action': 'wpvividstg_check_filesystem_permissions_free',
'root_dir':staging_root_dir,
'path': path
};
wpvivid_post_request(ajax_data, function (data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
}
else
{
jQuery('#wpvivid_staging_log').html("");
jQuery('#wpvivid_staging_progress_bar').css('width', '0%');
jQuery('#wpvivid_staging_progress_bar').find('div').eq(0).html('0%');
var custom_dir_json = wpvivid_create_custom_json('wpvivid_custom_staging_list');
var custom_dir = JSON.stringify(custom_dir_json);
var check_select = true;
wpvivid_create_staging_lock_unlock('lock');
var ajax_data = {
'action': 'wpvividstg_start_staging_free',
'path': path,
'table_prefix': table_prefix,
'custom_dir': custom_dir,
'additional_db': additional_database_info,
'root_dir':staging_root_dir
};
jQuery('#wpvivid_choose_staging_content').hide();
jQuery('#wpvivid_create_btn').hide();
jQuery('#wpvivid_create_staging_step2').show();
wpvivid_post_request(ajax_data, function (data)
{
setTimeout(function () {
wpvivid_get_staging_progress();
}, staging_requet_timeout);
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#wpvivid_choose_staging_content').hide();
jQuery('#wpvivid_create_btn').hide();
jQuery('#wpvivid_create_staging_step2').show();
setTimeout(function () {
wpvivid_get_staging_progress();
}, staging_requet_timeout);
});
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('creating staging site', textStatus, errorThrown);
alert(error_message);
});
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('creating staging site', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_restart_staging() {
var ajax_data = {
'action':'wpvividstg_start_staging_free',
};
wpvivid_post_request(ajax_data, function(data)
{
setTimeout(function()
{
wpvivid_get_staging_progress();
}, staging_requet_timeout);
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function()
{
wpvivid_get_staging_progress();
}, staging_requet_timeout);
});
}
function wpvivid_get_staging_progress() {
console.log(staging_requet_timeout);
var ajax_data = {
'action':'wpvividstg_get_staging_progress_free',
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
var log_data = jsonarray.log;
jQuery('#wpvivid_staging_log').html("");
while (log_data.indexOf('\n') >= 0)
{
var iLength = log_data.indexOf('\n');
var log = log_data.substring(0, iLength);
log_data = log_data.substring(iLength + 1);
var insert_log = "<div style=\"clear:both;\">" + log + "</div>";
jQuery('#wpvivid_staging_log').append(insert_log);
var div = jQuery('#wpvivid_staging_log');
div[0].scrollTop = div[0].scrollHeight;
}
jQuery('#wpvivid_staging_progress_bar').css('width', jsonarray.percent + '%');
jQuery('#wpvivid_staging_progress_bar').find('div').eq(0).html(jsonarray.percent + '%');
if(jsonarray.continue)
{
if(jsonarray.need_restart)
{
wpvivid_restart_staging();
}
else
{
setTimeout(function()
{
wpvivid_get_staging_progress();
}, staging_requet_timeout);
}
}
else{
if(typeof jsonarray.completed !== 'undefined' && jsonarray.completed){
jQuery('#wpvivid_staging_cancel').css({'pointer-events': 'auto', 'opacity': '1'});
wpvivid_create_staging_lock_unlock('unlock');
jQuery('#wpvivid_create_staging_step2').hide();
location.href='<?php echo esc_url(apply_filters('wpvividstg_get_admin_url', '')) . 'admin.php?page=wpvivid-staging'; ?>';
}
else if(typeof jsonarray.error !== 'undefined' && jsonarray.error){
wpvivid_create_staging_lock_unlock('unlock');
var insert_log = "<div style=\"clear:both;\"><a style=\"cursor: pointer;\" onclick=\"wpvivid_recreate_staging();\">Create a staging site</a></div>";
jQuery('#wpvivid_staging_log').append(insert_log);
var div = jQuery('#wpvivid_staging_log');
div[0].scrollTop = div[0].scrollHeight;
}
else if(typeof jsonarray.is_cancel !== 'undefined' && jsonarray.is_cancel){
var staging_site_info = {};
staging_site_info['staging_path'] = jsonarray.staging_path;
staging_site_info['staging_additional_db'] = jsonarray.staging_additional_db;
staging_site_info['staging_additional_db_user'] = jsonarray.staging_additional_db_user;
staging_site_info['staging_additional_db_pass'] = jsonarray.staging_additional_db_pass;
staging_site_info['staging_additional_db_host'] = jsonarray.staging_additional_db_host;
staging_site_info['staging_additional_db_name'] = jsonarray.staging_additional_db_name;
staging_site_info['staging_table_prefix'] = jsonarray.staging_table_prefix;
staging_site_info = JSON.stringify(staging_site_info);
ajax_data = {
'action': 'wpvividstg_delete_cancel_staging_site_free',
'staging_site_info': staging_site_info
};
wpvivid_post_request(ajax_data, function (data) {
jQuery('#wpvivid_staging_cancel').css({'pointer-events': 'auto', 'opacity': '1'});
wpvivid_create_staging_lock_unlock('unlock');
jQuery('#wpvivid_choose_staging_content').show();
jQuery('#wpvivid_create_btn').show();
jQuery('#wpvivid_create_staging_step2').hide();
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray !== null) {
if (jsonarray.result === 'success') {
}
else {
alert(jsonarray.error);
}
}
else {
}
}
catch (e) {
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
wpvivid_create_staging_lock_unlock('unlock');
jQuery('#wpvivid_choose_staging_content').show();
jQuery('#wpvivid_create_btn').show();
jQuery('#wpvivid_create_staging_step2').hide();
var error_message = wpvivid_output_ajaxerror('deleting staging site', textStatus, errorThrown);
alert(error_message);
});
}
else{
jQuery('#wpvivid_staging_cancel').css({'pointer-events': 'auto', 'opacity': '1'});
wpvivid_create_staging_lock_unlock('unlock');
jQuery('#wpvivid_choose_staging_content').show();
jQuery('#wpvivid_create_btn').show();
jQuery('#wpvivid_create_staging_step2').hide();
}
}
}
else if (jsonarray.result === 'failed')
{
wpvivid_create_staging_lock_unlock('unlock');
jQuery('#wpvivid_choose_staging_content').show();
jQuery('#wpvivid_create_btn').show();
jQuery('#wpvivid_create_staging_step2').hide();
alert(jsonarray.error);
}
}
catch(err){
setTimeout(function()
{
wpvivid_get_staging_progress();
}, 3000);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function()
{
wpvivid_get_staging_progress();
}, 3000);
});
}
function wpvivid_additional_database_connect_test(){
var db_user = jQuery('.wpvivid-additional-database-user').val();
var db_pass = jQuery('.wpvivid-additional-database-pass').val();
var db_host = jQuery('.wpvivid-additional-database-host').val();
var db_name = jQuery('.wpvivid-additional-database-name').val();
if(db_name !== ''){
if(db_user !== ''){
if(db_host !== ''){
var db_json = {};
db_json['db_user'] = db_user;
db_json['db_pass'] = db_pass;
db_json['db_host'] = db_host;
db_json['db_name'] = db_name;
var db_connect_info = JSON.stringify(db_json);
var ajax_data = {
'action': 'wpvividstg_test_additional_database_connect_free',
'database_info': db_connect_info
};
jQuery('#wpvivid_connect_additional_database').css({
'pointer-events': 'none',
'opacity': '0.4'
});
wpvivid_post_request(ajax_data, function (data) {
jQuery('#wpvivid_connect_additional_database').css({
'pointer-events': 'auto',
'opacity': '1'
});
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray !== null) {
if (jsonarray.result === 'success') {
alert('Connection success.')
}
else {
alert(jsonarray.error);
}
}
else {
alert('Connection Failed. Please check the credentials you entered and try again.');
}
}
catch (e) {
alert('Connection Failed. Please check the credentials you entered and try again.');
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
jQuery('#wpvivid_connect_additional_database').css({
'pointer-events': 'auto',
'opacity': '1'
});
jQuery(obj).css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = wpvivid_output_ajaxerror('connecting database', textStatus, errorThrown);
alert(error_message);
});
}
else{
alert('Database Host is required.');
}
}
else{
alert('Database User is required.');
}
}
else{
alert('Database Name is required.');
}
}
</script>
<?php
}
} includes/staging/class-wpvivid-staging-sites-list.php 0000644 00000406014 15132770567 0017064 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Staging_List extends WP_List_Table
{
public $list;
public $page_num;
public $parent;
public function __construct( $args = array() )
{
global $wpdb;
parent::__construct(
array(
'plural' => 'staging',
'screen' => 'staging',
)
);
}
public function set_parent($parent)
{
$this->parent=$parent;
}
public function set_list($list)
{
$this->list=$list;
}
protected function get_table_classes() {
return array( 'widefat', 'plugins', $this->_args['plural'] );
}
public function get_columns()
{
$posts_columns = array();
$posts_columns['pic'] ='';
$posts_columns['info'] = '';
return $posts_columns;
}
function prepare_items()
{
$columns = $this->get_columns();
$hidden = array('pic', 'info');
$sortable = array();
$this->_column_headers = array($columns, $hidden, $sortable);
$total_items =sizeof($this->list);
}
public function has_items()
{
return !empty($this->list);
}
protected function _column_pic( $item, $classes, $data, $primary )
{
if(isset($item['site']['fresh_install']))
{
$url=esc_url(WPVIVID_PLUGIN_IMAGES_URL.'staging/Fresh-list.png');
}
else
{
$url=esc_url(WPVIVID_PLUGIN_IMAGES_URL.'staging/living-site.png');
}
echo '<td class="column-primary" style="margin: 10px;">
<div>
<div style="margin:auto; width:100px; height:100px; right:50%;">
<img src="'.esc_url($url).'">
</div>
<div class="'.esc_attr($item['id']).'" style="margin-top:10px;">
<div class="wpvivid-delete-staging-site" style="margin: auto;width: 70px;background-color:#f1f1f1; padding-top:4px;padding-bottom:4px; cursor:pointer;text-align:center;" title="Delete the stating site">Delete</div>
</div>
</div>
</td>';
}
protected function _column_info( $item, $classes, $data, $primary ){
$home_url = home_url();
global $wpdb;
$home_url_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->options WHERE option_name = %s", 'home' ) );
foreach ( $home_url_sql as $home ){
$home_url = $home->option_value;
}
$home_url = untrailingslashit($home_url);
$admin_url = apply_filters('wpvividstg_get_admin_url', '');
if(isset($item['site']['mu_single']))
{
$admin_url =admin_url();
}
$admin_name = str_replace($home_url, '', $admin_url);
$admin_name = trim($admin_name, '/');
if(isset($item['site']['prefix']) && !empty($item['site']['prefix'])){
$prefix = $item['site']['prefix'];
if(isset($item['site']['db_connect']['dbname']) && !empty($item['site']['db_connect']['dbname'])){
$db_name = $item['site']['db_connect']['dbname'];
}
else{
$db_name = DB_NAME;
}
}
else{
$prefix = 'N/A';
$db_name = 'N/A';
}
if(isset($item['site']['path']) && !empty($item['site']['path'])){
$site_dir = $item['site']['path'];
}
else{
$site_dir = 'N/A';
}
if(isset($item['site']['home_url']) && !empty($item['site']['home_url'])){
$site_url = esc_url($item['site']['home_url']);
$admin_url = esc_url($item['site']['home_url'].'/'.$admin_name.'/');
$site_url_link = '<a href="'.esc_url($site_url).'" target="_blank">'.$site_url.'</a>';
$admin_url_link = '<a href="'.esc_url($admin_url).'" target="_blank">'.$admin_url.'</a>';
}
else{
$site_url_link = 'N/A';
$admin_url_link = 'N/A';
}
if(isset($item['site']['fresh_install']))
{
$copy_btn='Copy the Fresh Install to Live';
$update_btn='Update the Fresh Install';
$site_url='Fresh Install URL';
$admin_url='Fresh Install Admin URL';
$tip_text='Tips: Click the \'Copy the Fresh Install to Live\' button above to migrate the fresh install to your live site. Click the \'Update the Fresh Install\' button to update the live site to the fresh install.';
$class_btn='fresh-install';
}
else
{
$copy_btn='Copy the Staging Site to Live';
$update_btn='Update the Staging Site';
$site_url='Staging Site URL';
$admin_url='Staging Site Admin URL';
$tip_text='Tips: Click the \'Copy the Staging Site to Live\' button above to migrate the staging site to your live site. Click the \'Update the Staging Site\' button to update the live site to the staging site.';
$class_btn='staging-site';
}
if(isset($item['site']['mu_single']) && $item['site']['mu_single'] == true){
$mu_single_class = 'mu-single';
}
else{
$mu_single_class = '';
}
echo '<td class="column-description desc" colspan="2">
<div style="border-left:4px solid #00a0d2;padding-left:10px;float:left;">
<div style="height:20px;display:block;float:left;"><span class="wpvivid-element-space-right"><strong>'.esc_url($site_url).':</strong></span><span class="wpvivid-element-space-right">';
if($site_url_link=="'N/A'")
{
echo esc_html($site_url_link);
}
else
{
$site_url = esc_url($item['site']['home_url']);
echo '<a href="'.esc_url($site_url).'" target="_blank">'.esc_html($site_url).'</a>';
}
echo '</span></div>
<div style="height:20px;display:block;float:left;"><span class="wpvivid-element-space-right"><strong>'.esc_url($admin_url).':</strong></span><span class="wpvivid-element-space-right">';
if($admin_url_link=="'N/A'")
{
echo esc_html($admin_url_link);
}
else
{
$admin_url = esc_url($item['site']['home_url'].'/'.$admin_name.'/');
$admin_url_link = '<a href="'.esc_url($admin_url).'" target="_blank">'.esc_html($admin_url).'</a>';
}
echo '</span></div>
</div>
<div style="clear:both"></div>
<div style="border-left:4px solid #00a0d2;padding-left:10px;float:left;">
<div style="height:20px;display:block;float:left;"><span class="wpvivid-element-space-right"><strong>Database:</strong></span><span class="wpvivid-element-space-right">'.esc_html($db_name).'</span></div>
<div style="height:20px;display:block;float:left;"><span class="wpvivid-element-space-right"><strong>Table Prefix:</strong></span><span class="wpvivid-element-space-right">'.esc_html($prefix).'</span></div>
<div style="height:20px;display:block;float:left;"><span class="wpvivid-element-space-right"><strong>Site Directory:</strong></span><span class="wpvivid-element-space-right">'.esc_html($site_dir).'</span></div>
</div>
<div style="clear:both"></div>
<div class="wpvivid-copy-staging-to-live-block '.esc_attr($class_btn).' '.esc_attr($mu_single_class).'" style="margin-top: 10px;">
<div>
<input class="button-primary wpvivid-copy-staging-to-live '.esc_attr($class_btn).' '.esc_attr($mu_single_class).'" type="button" value="'.esc_attr($copy_btn).'" style="margin-right: 10px;" />
<input class="button-primary wpvivid-update-live-to-staging '.esc_attr($class_btn).' '.esc_attr($mu_single_class).'" type="button" value="'.esc_attr($update_btn).'" />
</div>
<div style="border: 1px solid #f1f1f1; border-radius: 6px; margin-top: 10px;padding:5px;"><span>'.esc_html($tip_text).'</span></div>
</div>
</td>';
}
public function display_rows()
{
$this->_display_rows( $this->list );
}
private function _display_rows( $list )
{
foreach ( $list as $key=>$item)
{
$item['id']=$key;
$this->single_row($item);
}
}
public function single_row($item)
{
if(isset($item['site']['path']) && !empty($item['site']['path'])){
$staging_site_name = basename($item['site']['path']);
}
else{
$staging_site_name = 'N/A';
}
if(isset($item['site']['fresh_install']))
{
$text='Fresh Install Name';
}
else
{
$text='Staging Site Name';
}
if(isset($item['db_connect']['old_site_url']))
{
$live_domain = $item['db_connect']['old_site_url'];
}
else{
$live_domain = 'N/A';
}
?>
<tr class="<?php echo esc_attr($item['id']); ?>">
<td class="column-primary" style="border-top:1px solid #f1f1f1; border-bottom:1px solid #f1f1f1;" colspan="3" >
<span><strong><?php echo esc_html($text); ?>: </strong></span><span><?php echo esc_html($staging_site_name); ?></span>
<?php
if(isset($item['site']['mu_single']))
{
$site_id=$item['site']['mu_single_site_id'];
$site_url=get_site_url($site_id);
?>
<span style="margin-left: 20px;"><strong>Live Site: </strong></span><span><?php echo esc_html($site_url); ?></span>
<?php
}
else{
?>
<span style="margin-left: 20px;"><strong>Live Site: </strong></span><span><?php echo esc_html($live_domain); ?></span>
<?php
}
?>
</td>
</tr>
<tr id="<?php echo esc_attr($item['id']); ?>" class="<?php echo esc_attr($item['id']); ?>">
<?php $this->single_row_columns( $item ); ?>
</tr>
<?php
}
public function display() {
$singular = $this->_args['singular'];
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<table class="wp-list-table <?php echo esc_attr(implode( ' ', $this->get_table_classes() )); ?>" style="border: 1px solid #f1f1f1; border-top: none;">
<thead>
<tr>
<?php $this->print_column_headers(); ?>
</tr>
</thead>
<tbody id="the-list"
<?php
if ( $singular ) {
echo esc_attr(" data-wp-lists='list:$singular'");
}
?>
>
<?php $this->display_rows_or_placeholder(); ?>
</tbody>
<tfoot>
<tr>
<?php $this->print_column_headers( false ); ?>
</tr>
</tfoot>
</table>
<?php
}
public function display_js()
{
?>
<script>
</script>
<?php
}
}
class WPvivid_Staging_MU_Site_List_Free extends WP_List_Table
{
public $list;
public $type;
public $page_num;
public $parent;
public function __construct( $args = array() )
{
global $wpdb;
parent::__construct(
array(
'plural' => 'staging_mu_site',
'screen' => 'staging_mu_site',
)
);
}
public function set_parent($parent)
{
$this->parent=$parent;
}
public function set_list($list,$type,$page_num=1)
{
$this->list=$list;
$this->type=$type;
$this->page_num=$page_num;
}
protected function get_table_classes()
{
return array( 'widefat striped' );
}
public function get_columns()
{
$sites_columns = array(
'cb' => '<input type="checkbox" />',
'blogname' => __( 'Subsite URL', 'wpvivid-backuprestore' ),
'tables_folders'=>__( 'Subsite Tables/Folders', 'wpvivid-backuprestore' ),
'title' => __( 'Subsite Title', 'wpvivid-backuprestore' ),
'description' => __( 'Subsite Description', 'wpvivid-backuprestore')
);
return $sites_columns;
}
public function get_pagenum()
{
if($this->page_num=='first')
{
$this->page_num=1;
}
else if($this->page_num=='last')
{
$this->page_num=$this->_pagination_args['total_pages'];
}
$pagenum = $this->page_num ? $this->page_num : 0;
if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
{
$pagenum = $this->_pagination_args['total_pages'];
}
return max( 1, $pagenum );
}
public function column_cb( $subsite )
{
$subsite_id = get_object_vars($subsite)["blog_id"];
$blogname = get_object_vars($subsite)["domain"].get_object_vars($subsite)["path"];
?>
<label class="screen-reader-text" for="blog_<?php echo esc_attr($subsite_id); ?>">
<?php
printf( 'Select %s', esc_html($blogname) );
?>
</label>
<input type="checkbox" name="<?php echo esc_attr( $this->type ); ?>" value="<?php echo esc_attr( $subsite_id ); ?>" checked />
<?php
}
public function column_id( $subsite )
{
$subsite_id = get_object_vars($subsite)["blog_id"];
echo esc_attr($subsite_id);
}
public function column_blogname( $subsite )
{
$subsite_id = get_object_vars($subsite)["blog_id"];
$blogname = untrailingslashit( get_object_vars($subsite)['domain'] . get_object_vars($subsite)['path'] );
?>
<strong>
<a href="<?php echo esc_url( network_admin_url( 'site-info.php?id=' .$subsite_id ) ); ?>" class="edit"><?php echo esc_html($blogname); ?></a>
</strong>
<?php
}
public function column_tables_folders( $subsite )
{
$subsite_id = get_object_vars($subsite)["blog_id"];
$disable='';
/*if( $this->type=='copy_mu_site')
{
$disable='';
}
else
{
$disable='disabled';
}*/
?>
<label>
<input type="checkbox" name="<?php echo esc_attr( $this->type ); ?>_tables" value="<?php echo esc_attr( $subsite_id ); ?>" checked <?php echo esc_attr( $disable ); ?>/>
Tables /
</label>
<label>
<input type="checkbox" name="<?php echo esc_attr( $this->type ); ?>_folders" value="<?php echo esc_attr( $subsite_id ); ?>" checked <?php echo esc_attr( $disable ); ?>/>
Folders
</label>
<?php
}
public function column_title( $subsite )
{
switch_to_blog( get_object_vars($subsite)["blog_id"] );
echo esc_html( get_option( 'blogname' ) ) ;
restore_current_blog();
}
public function column_description( $subsite ) {
switch_to_blog( get_object_vars($subsite)["blog_id"] );
echo esc_html( get_option( 'blogdescription ' ) ) ;
restore_current_blog();
}
public function has_items()
{
return !empty($this->list);
}
public function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$this->_column_headers = array($columns, $hidden, $sortable);
$total_items =sizeof($this->list);
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => 10,
)
);
}
public function display_rows()
{
$this->_display_rows( $this->list );
}
private function _display_rows( $list )
{
$page=$this->get_pagenum();
$page_list=$list;
$temp_page_list=array();
$count=0;
while ( $count<$page )
{
$temp_page_list = array_splice( $page_list, 0, 10);
$count++;
}
foreach ( $temp_page_list as $key=>$item)
{
$this->single_row($item);
}
}
public function single_row($item)
{
?>
<tr>
<?php $this->single_row_columns( $item ); ?>
</tr>
<?php
}
protected function pagination( $which )
{
if ( empty( $this->_pagination_args ) )
{
return;
}
$total_items = $this->_pagination_args['total_items'];
$total_pages = $this->_pagination_args['total_pages'];
$infinite_scroll = false;
if ( isset( $this->_pagination_args['infinite_scroll'] ) )
{
$infinite_scroll = $this->_pagination_args['infinite_scroll'];
}
if ( 'top' === $which && $total_pages > 1 )
{
$this->screen->render_screen_reader_content( 'heading_pagination' );
}
$output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items, 'wpvivid-backuprestore' ), number_format_i18n( $total_items ) ) . '</span>';
$current = $this->get_pagenum();
$page_links = array();
$total_pages_before = '<span class="paging-input">';
$total_pages_after = '</span></span>';
$disable_first = $disable_last = $disable_prev = $disable_next = false;
if ( $current == 1 ) {
$disable_first = true;
$disable_prev = true;
}
if ( $current == 2 ) {
$disable_first = true;
}
if ( $current == $total_pages ) {
$disable_last = true;
$disable_next = true;
}
if ( $current == $total_pages - 1 ) {
$disable_last = true;
}
if ( $disable_first ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>';
} else {
$page_links[] = sprintf(
"<div class='first-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'First page', 'wpvivid-backuprestore' ),
'«'
);
}
if ( $disable_prev ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>';
} else {
$page_links[] = sprintf(
"<div class='prev-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Previous page', 'wpvivid-backuprestore' ),
'‹'
);
}
if ( 'bottom' === $which ) {
$html_current_page = $current;
$total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
} else {
$html_current_page = sprintf(
"%s<input class='current-page' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
'<label class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</label>',
$current,
strlen( $total_pages )
);
}
$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
$page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging', 'wpvivid-backuprestore' ), $html_current_page, $html_total_pages ) . $total_pages_after;
if ( $disable_next ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>';
} else {
$page_links[] = sprintf(
"<div class='next-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Next page', 'wpvivid-backuprestore' ),
'›'
);
}
if ( $disable_last ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>';
} else {
$page_links[] = sprintf(
"<div class='last-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'Last page', 'wpvivid-backuprestore' ),
'»'
);
}
$pagination_links_class = 'pagination-links';
if ( ! empty( $infinite_scroll ) ) {
$pagination_links_class .= ' hide-if-js';
}
$output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
if ( $total_pages ) {
$page_class = $total_pages < 2 ? ' one-page' : '';
} else {
$page_class = ' no-pages';
}
$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
echo $this->_pagination;
}
protected function display_tablenav( $which ) {
$css_type = '';
if ( 'top' === $which ) {
wp_nonce_field( 'bulk-' . $this->_args['plural'] );
$css_type = 'margin: 0 0 10px 0';
}
else if( 'bottom' === $which ) {
$css_type = 'margin: 10px 0 0 0';
}
$total_pages = $this->_pagination_args['total_pages'];
if ( $total_pages >1)
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
}
public function display() {
$singular = $this->_args['singular'];
$this->display_tablenav( 'top' );
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<table class="wp-list-table <?php echo esc_attr(implode( ' ', $this->get_table_classes() )); ?>" >
<thead>
<tr>
<?php $this->print_column_headers(); ?>
</tr>
</thead>
<tbody id="the-list"
<?php
if ( $singular ) {
echo esc_attr(" data-wp-lists='list:$singular'");
}
?>
>
<?php $this->display_rows_or_placeholder(); ?>
</tbody>
<tfoot>
<tr>
<?php $this->print_column_headers( false ); ?>
</tr>
</tfoot>
</table>
<?php
}
}
class WPvivid_Staging_MU_Single_Site_List_Free extends WP_List_Table
{
public $list;
public $type;
public $page_num;
public $parent;
public function __construct( $args = array() )
{
global $wpdb;
parent::__construct(
array(
'plural' => 'staging_mu_site',
'screen' => 'staging_mu_site',
)
);
}
public function set_parent($parent)
{
$this->parent=$parent;
}
public function set_list($list,$type,$page_num=1)
{
$this->list=$list;
$this->type=$type;
$this->page_num=$page_num;
}
protected function get_table_classes()
{
return array( 'widefat striped' );
}
public function get_columns()
{
$sites_columns = array(
'cb' => ' ',
'blogname' => __( 'Subsite URL', 'wpvivid-backuprestore' ),
//'tables_folders'=>__( 'Subsite Tables/Folders', 'wpvivid-backuprestore' ),
'title' => __( 'Subsite Title', 'wpvivid-backuprestore' ),
'description' => __( 'Subsite Description', 'wpvivid-backuprestore' )
);
return $sites_columns;
}
public function get_pagenum()
{
if($this->page_num=='first')
{
$this->page_num=1;
}
else if($this->page_num=='last')
{
$this->page_num=$this->_pagination_args['total_pages'];
}
$pagenum = $this->page_num ? $this->page_num : 0;
if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
{
$pagenum = $this->_pagination_args['total_pages'];
}
return max( 1, $pagenum );
}
public function column_cb( $subsite )
{
$subsite_id = get_object_vars($subsite)["blog_id"];
$blogname = get_object_vars($subsite)["domain"].get_object_vars($subsite)["path"];
?>
<label class="screen-reader-text" for="blog_<?php echo esc_attr($subsite_id); ?>">
<?php
printf( 'Select %s', esc_html($blogname) );
?>
</label>
<input type="checkbox" name="<?php echo esc_attr( $this->type ); ?>" value="<?php echo esc_attr( $subsite_id ); ?>" />
<?php
}
public function column_id( $subsite )
{
$subsite_id = get_object_vars($subsite)["blog_id"];
echo esc_html($subsite_id);
}
public function column_blogname( $subsite )
{
$subsite_id = get_object_vars($subsite)["blog_id"];
$blogname = untrailingslashit( get_object_vars($subsite)['domain'] . get_object_vars($subsite)['path'] );
?>
<strong>
<a href="<?php echo esc_url( network_admin_url( 'site-info.php?id=' .$subsite_id ) ); ?>" class="edit"><?php echo esc_html($blogname); ?></a>
</strong>
<?php
}
public function column_tables_folders( $subsite )
{
$subsite_id = get_object_vars($subsite)["blog_id"];
$disable='';
/*if( $this->type=='copy_mu_site')
{
$disable='';
}
else
{
$disable='disabled';
}*/
?>
<label>
<input type="checkbox" name="<?php echo esc_attr( $this->type ); ?>_tables" value="<?php echo esc_attr( $subsite_id ); ?>" <?php echo esc_attr( $disable ); ?>/>
Tables /
</label>
<label>
<input type="checkbox" name="<?php echo esc_attr( $this->type ); ?>_folders" value="<?php echo esc_attr( $subsite_id ); ?>" <?php echo esc_attr( $disable ); ?>/>
Folders
</label>
<?php
}
public function column_title( $subsite )
{
switch_to_blog( get_object_vars($subsite)["blog_id"] );
echo esc_html( get_option( 'blogname' ) ) ;
restore_current_blog();
}
public function column_description( $subsite ) {
switch_to_blog( get_object_vars($subsite)["blog_id"] );
echo esc_html( get_option( 'blogdescription ' ) ) ;
restore_current_blog();
}
public function has_items()
{
return !empty($this->list);
}
public function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$this->_column_headers = array($columns, $hidden, $sortable);
$total_items =sizeof($this->list);
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => 10,
)
);
}
public function display_rows()
{
$this->_display_rows( $this->list );
}
private function _display_rows( $list )
{
$page=$this->get_pagenum();
$page_list=$list;
$temp_page_list=array();
$count=0;
while ( $count<$page )
{
$temp_page_list = array_splice( $page_list, 0, 10);
$count++;
}
foreach ( $temp_page_list as $key=>$item)
{
$this->single_row($item);
}
}
public function single_row($item)
{
?>
<tr>
<?php $this->single_row_columns( $item ); ?>
</tr>
<?php
}
protected function pagination( $which )
{
if ( empty( $this->_pagination_args ) )
{
return;
}
$total_items = $this->_pagination_args['total_items'];
$total_pages = $this->_pagination_args['total_pages'];
$infinite_scroll = false;
if ( isset( $this->_pagination_args['infinite_scroll'] ) )
{
$infinite_scroll = $this->_pagination_args['infinite_scroll'];
}
if ( 'top' === $which && $total_pages > 1 )
{
$this->screen->render_screen_reader_content( 'heading_pagination' );
}
$output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items, 'wpvivid-backuprestore' ), number_format_i18n( $total_items ) ) . '</span>';
$current = $this->get_pagenum();
$page_links = array();
$total_pages_before = '<span class="paging-input">';
$total_pages_after = '</span></span>';
$disable_first = $disable_last = $disable_prev = $disable_next = false;
if ( $current == 1 ) {
$disable_first = true;
$disable_prev = true;
}
if ( $current == 2 ) {
$disable_first = true;
}
if ( $current == $total_pages ) {
$disable_last = true;
$disable_next = true;
}
if ( $current == $total_pages - 1 ) {
$disable_last = true;
}
if ( $disable_first ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>';
} else {
$page_links[] = sprintf(
"<div class='first-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'First page', 'wpvivid-backuprestore' ),
'«'
);
}
if ( $disable_prev ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>';
} else {
$page_links[] = sprintf(
"<div class='prev-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Previous page', 'wpvivid-backuprestore' ),
'‹'
);
}
if ( 'bottom' === $which ) {
$html_current_page = $current;
$total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
} else {
$html_current_page = sprintf(
"%s<input class='current-page' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
'<label class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</label>',
$current,
strlen( $total_pages )
);
}
$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
$page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging', 'wpvivid-backuprestore' ), $html_current_page, $html_total_pages ) . $total_pages_after;
if ( $disable_next ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>';
} else {
$page_links[] = sprintf(
"<div class='next-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Next page', 'wpvivid-backuprestore' ),
'›'
);
}
if ( $disable_last ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>';
} else {
$page_links[] = sprintf(
"<div class='last-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'Last page', 'wpvivid-backuprestore' ),
'»'
);
}
$pagination_links_class = 'pagination-links';
if ( ! empty( $infinite_scroll ) ) {
$pagination_links_class .= ' hide-if-js';
}
$output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
if ( $total_pages ) {
$page_class = $total_pages < 2 ? ' one-page' : '';
} else {
$page_class = ' no-pages';
}
$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
echo $this->_pagination;
}
protected function display_tablenav( $which ) {
$css_type = '';
if ( 'top' === $which ) {
wp_nonce_field( 'bulk-' . $this->_args['plural'] );
$css_type = 'margin: 0 0 10px 0';
}
else if( 'bottom' === $which ) {
$css_type = 'margin: 10px 0 0 0';
}
$total_pages = $this->_pagination_args['total_pages'];
if ( $total_pages >1)
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
}
public function display() {
$singular = $this->_args['singular'];
$this->display_tablenav( 'top' );
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<table class="wp-list-table <?php echo esc_attr(implode( ' ', $this->get_table_classes() )); ?>" >
<thead>
<tr>
<?php $this->print_column_headers(); ?>
</tr>
</thead>
<tbody id="the-list"
<?php
if ( $singular ) {
echo esc_attr(" data-wp-lists='list:$singular'");
}
?>
>
<?php $this->display_rows_or_placeholder(); ?>
</tbody>
<tfoot>
<tr>
<?php $this->print_column_headers( false ); ?>
</tr>
</tfoot>
</table>
<?php
}
}
class WPvivid_Custom_MU_Staging_List
{
public $parent_id;
public $is_staging_site = false;
public $is_sync_site = false;
public $staging_home_path = false;
public $custom_uploads_path;
public $custom_content_path;
public $custom_additional_file_path;
public function __construct(){
}
public function set_parent_id($parent_id){
$this->parent_id = $parent_id;
}
public function set_staging_home_path($is_staging_site=false, $is_sync_site=false, $staging_home_path=false){
$this->is_staging_site = $is_staging_site;
$this->is_sync_site = $is_sync_site;
$this->staging_home_path = $staging_home_path;
}
public function display_rows()
{
$core_check = 'checked';
$database_check = 'checked';
$database_text_style = 'pointer-events: auto; opacity: 1;';
$themes_check = 'checked';
$plugins_check = 'checked';
$themes_plugins_check = 'checked';
$themes_plugins_text_style = 'pointer-events: auto; opacity: 1;';
$uploads_check = 'checked';
$uploads_text_style = 'pointer-events: auto; opacity: 1;';
$content_check = 'checked';
$content_text_style = 'pointer-events: auto; opacity: 1;';
$additional_file_check = '';
$additional_file_text_style = 'pointer-events: none; opacity: 0.4;';
$upload_extension = '';
$content_extension = '';
$additional_file_extension = '';
$db_descript = 'All the tables in the WordPress MU database except for subsites tables.';
$uploads_descript = 'The folder where images and media files of the main site are stored by default. All files will be copied to the staging site by default. You can exclude folders you do not want to copy.';
$core_descript = 'These are the essential files for creating a staging site.';
$themes_plugins_descript = 'All the plugins and themes files used by the MU network. The activated plugins and themes will be copied to the staging site by default. A child theme must be copied if it exists.';
$contents_descript = '<strong style="text-decoration:underline;"><i>Exclude</i></strong> folders you do not want to copy to the staging site, except for the wp-content/uploads folder.';
$additional_file_descript = '<strong style="text-decoration:underline;"><i>Include</i></strong> additional files or folders you want to copy to the staging site.';
?>
<table class="wp-list-table widefat plugins wpvivid-custom-table">
<tbody>
<!-------- core -------->
<tr>
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" checked disabled/>
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-wordpress-core">WordPress Core</td>
<td class="column-description desc"><?php echo esc_html($core_descript); ?></td>
</tr>
<!-------- database -------->
<tr style="cursor:pointer;">
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" name="checked[]" checked disabled/>
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-handle-database-detail">Database</td>
<td class="column-description desc wpvivid-handle-database-detail database-desc">
<?php echo esc_html($db_descript); ?>
</td>
</tr>
<!-------- uploads -------->
<tr style="cursor:pointer">
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" name="checked[]" class="wpvivid-custom-check wpvivid-custom-uploads-check" checked disabled/>
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-handle-uploads-detail">wp-content/uploads</td>
<td class="column-description desc wpvivid-handle-uploads-detail uploads-desc"><?php echo esc_html($uploads_descript); ?></td>
<th class="wpvivid-handle-uploads-detail">
<details class="primer" onclick="return false;" style="display: inline-block; width: 100%;">
<summary title="Show detail" style="float: right; color: #a0a5aa;"></summary>
</details>
</th>
</tr>
<tr class="wpvivid-custom-detail wpvivid-uploads-detail wpvivid-close" style="<?php echo esc_attr($uploads_text_style); ?> display: none;">
<th class="check-column"></th>
<td colspan="3" class="plugin-title column-primary">
<table class="wp-list-table widefat plugins" style="width:100%;">
<thead>
<tr>
<th class="manage-column column-name column-primary" style="border-bottom: 1px solid #e1e1e1 !important;">
<label class="wpvivid-refresh-tree wpvivid-refresh-uploads-tree" style="margin-bottom: 0; font-size: 13px;">Click Here to Refresh Folder Tree</label>
</th>
<th class="manage-column column-description" style="font-size: 13px; border-bottom: 1px solid #e1e1e1 !important;">Checked Folders or Files to Transfer</th>
</tr>
</thead>
<tbody>
<tr>
<td class="wpvivid-custom-uploads-left" style="padding-right: 0;">
<div class="wpvivid-custom-uploads-tree">
<div class="wpvivid-custom-tree wpvivid-custom-uploads-tree-info"></div>
</div>
</td>
<td class="wpvivid-custom-uploads-right">
<div class="wpvivid-custom-uploads-table wpvivid-custom-exclude-uploads-list">
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<div>
<div style="float: left; margin-right: 10px;">
<input class="button-primary wpvivid-exclude-uploads-folder-btn" type="submit" value="Exclude Folders" disabled />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Double click to open the folder tree, press Ctrl + left-click to select multiple items.</div>
</div>
</small>
<div style="clear: both;"></div>
</div>
</td>
</tr>
</tfoot>
<div style="clear:both;"></div>
</table>
<div style="margin-top: 10px;">
<div style="float: left; margin-right: 10px;">
<input type="text" class="regular-text wpvivid-uploads-extension" placeholder="Exclude file types, for example: gif,jpg,webp" value="<?php echo esc_attr($upload_extension); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_,]/g,'')"/>
<input type="button" class="wpvivid-uploads-extension-rule-btn" value="Save" />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Exclude file types from the copy. All file types are separated by commas, for example: jpg, gif, tmp etc (without a dot before the file type).</div>
</div>
</small>
<div style="clear: both;"></div>
</div>
</td>
</tr>
<!-------- themes and plugins -------->
<tr style="cursor:pointer">
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" name="checked[]" class="wpvivid-custom-check wpvivid-custom-themes-plugins-check" checked disabled/>
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-handle-themes-plugins-detail">Themes and Plugins</td>
<td class="column-description desc wpvivid-handle-themes-plugins-detail themes-plugins-desc">
<?php echo esc_html($themes_plugins_descript); ?>
</td>
<th class="wpvivid-handle-themes-plugins-detail">
<details class="primer" onclick="return false;" style="display: inline-block; width: 100%;">
<summary title="Show detail" style="float: right; color: #a0a5aa;"></summary>
</details>
</th>
</tr>
<tr class="wpvivid-custom-detail wpvivid-themes-plugins-detail wpvivid-close" style="pointer-events: auto; opacity: 1; display: none;">
<th class="check-column"></th>
<td colspan="3" class="plugin-title column-primary wpvivid-custom-themes-plugins-info">
<div class="spinner" style="margin: 0 5px 10px 0; float: left;"></div>
<div style="float: left;">Archieving themes and plugins</div>
<div style="clear: both;"></div>
</td>
</tr>
<!-------- content -------->
<tr style="cursor:pointer">
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" name="checked[]" class="wpvivid-custom-check wpvivid-custom-content-check" checked disabled/>
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-handle-content-detail">wp-content</td>
<td class="column-description desc wpvivid-handle-content-detail content-desc"><?php echo esc_html($contents_descript); ?></td>
<th class="wpvivid-handle-content-detail">
<details class="primer" onclick="return false;" style="display: inline-block; width: 100%;">
<summary title="Show detail" style="float: right; color: #a0a5aa;"></summary>
</details>
</th>
</tr>
<tr class="wpvivid-custom-detail wpvivid-content-detail wpvivid-close" style="<?php echo esc_attr($content_text_style); ?> display: none;">
<th class="check-column"></th>
<td colspan="3" class="plugin-title column-primary">
<table class="wp-list-table widefat plugins" style="width:100%;">
<thead>
<tr>
<th class="manage-column column-name column-primary" style="border-bottom: 1px solid #e1e1e1 !important;">
<label class="wpvivid-refresh-tree wpvivid-refresh-content-tree" style="margin-bottom: 0; font-size: 13px;">Click Here to Refresh Folder Tree</label>
</th>
<th class="manage-column column-description" style="font-size: 13px; border-bottom: 1px solid #e1e1e1 !important;">Checked Folders or Files to Transfer</th>
</tr>
</thead>
<tbody>
<tr>
<td class="wpvivid-custom-uploads-left" style="padding-right: 0;">
<div class="wpvivid-custom-uploads-tree">
<div class="wpvivid-custom-tree wpvivid-custom-content-tree-info"></div>
</div>
</td>
<td class="wpvivid-custom-uploads-right">
<div class="wpvivid-custom-uploads-table wpvivid-custom-exclude-content-list">
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<div style="float: left; margin-right: 10px;">
<input class="button-primary wpvivid-exclude-content-folder-btn" type="submit" value="Exclude Folders" disabled />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Double click to open the folder tree, press Ctrl + left-click to select multiple items.</div>
</div>
</small>
<div style="clear: both;"></div>
</td>
</tr>
</tfoot>
<div style="clear:both;"></div>
</table>
<div style="margin-top: 10px;">
<div style="float: left; margin-right: 10px;">
<input type="text" class="regular-text wpvivid-content-extension" placeholder="Exclude file types, for example: gif,jpg,webp" value="<?php echo esc_attr($content_extension); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_,]/g,'')"/>
<input type="button" class="wpvivid-content-extension-rule-btn" value="Save" />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Exclude file types from the copy. All file types are separated by commas, for example: jpg, gif, tmp etc (without a dot before the file type).</div>
</div>
</small>
<div style="clear: both;"></div>
</div>
</td>
</tr>
<!-------- additional files -------->
<tr style="cursor:pointer">
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" name="checked[]" class="wpvivid-custom-check wpvivid-custom-additional-file-check" <?php echo esc_attr($additional_file_check); ?> />
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-handle-additional-file-detail">Additional Files/Folder</td>
<td class="column-description desc wpvivid-handle-additional-file-detail additional-file-desc"><?php echo esc_html($additional_file_descript); ?></td>
<th class="wpvivid-handle-additional-file-detail">
<details class="primer" onclick="return false;" style="display: inline-block; width: 100%;">
<summary title="Show detail" style="float: right; color: #a0a5aa;"></summary>
</details>
</th>
</tr>
<tr class="wpvivid-custom-detail wpvivid-additional-file-detail wpvivid-close" style="<?php echo esc_attr($additional_file_text_style); ?> display: none;">
<th class="check-column"></th>
<td colspan="3" class="plugin-title column-primary">
<table class="wp-list-table widefat plugins" style="width:100%;">
<thead>
<tr>
<th class="manage-column column-name column-primary" style="border-bottom: 1px solid #e1e1e1 !important;">
<label class="wpvivid-refresh-tree wpvivid-refresh-additional-file-tree" style="margin-bottom: 0; font-size: 13px;">Click Here to Refresh Folder/File Tree</label>
</th>
<th class="manage-column column-description" style="font-size: 13px; border-bottom: 1px solid #e1e1e1 !important;">Checked Folders or Files to Transfer</th>
</tr>
</thead>
<tbody>
<tr>
<td class="wpvivid-custom-uploads-left" style="padding-right: 0;">
<div class="wpvivid-custom-uploads-tree">
<div class="wpvivid-custom-tree wpvivid-custom-additional-file-tree-info"></div>
</div>
</td>
<td class="wpvivid-custom-uploads-right">
<div class="wpvivid-custom-uploads-table wpvivid-custom-include-additional-file-list">
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<div style="float: left; margin-right: 10px;">
<input class="button-primary wpvivid-include-additional-file-btn" type="submit" value="Include folders/files" disabled />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Double click to open the folder tree, press Ctrl + left-click to select multiple items.</div>
</div>
</small>
<div style="clear: both;"></div>
</td>
</tr>
</tfoot>
<div style="clear:both;"></div>
</table>
<div style="margin-top: 10px;">
<div style="float: left; margin-right: 10px;">
<input type="text" class="regular-text wpvivid-additional-file-extension" placeholder="Exclude file types, for example: gif,jpg,webp" value="<?php echo esc_attr($additional_file_extension); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_,]/g,'')"/>
<input type="button" class="wpvivid-additional-file-extension-rule-btn" value="Save" />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Exclude file types from the copy. All file types are separated by commas, for example: jpg, gif, tmp etc (without a dot before the file type).</div>
</div>
</small>
<div style="clear: both;"></div>
</div>
</td>
</tr>
</tbody>
</table>
<?php
}
public function load_js(){
$upload_dir = wp_upload_dir();
$upload_path = $this->is_staging_site === false ? $upload_dir['basedir'] : $this->staging_home_path.'/wp-content/uploads';
$upload_path = str_replace('\\','/',$upload_path);
$upload_path = $upload_path.'/';
$this->custom_uploads_path = $upload_path;
$content_dir = $this->is_staging_site === false ? WP_CONTENT_DIR : $this->staging_home_path.'/wp-content';
$content_path = str_replace('\\','/',$content_dir);
$content_path = $content_path.'/';
$this->custom_content_path = $content_path;
$additional_file_path = $this->is_staging_site === false ? str_replace('\\','/',get_home_path()) : str_replace('\\','/',$this->staging_home_path);
$this->custom_additional_file_path = $additional_file_path;
?>
<script>
function wpvivid_handle_custom_open_close(obj, sub_obj){
if(obj.hasClass('wpvivid-close')) {
sub_obj.hide();
sub_obj.prev().find('details').prop('open', false);
sub_obj.removeClass('wpvivid-open');
sub_obj.addClass('wpvivid-close');
sub_obj.prev().css('background-color', '#fff');
obj.prev().css('background-color', '#f1f1f1');
obj.prev().find('details').prop('open', true);
obj.show();
obj.removeClass('wpvivid-close');
obj.addClass('wpvivid-open');
}
else{
obj.hide();
obj.prev().css('background-color', '#fff');
obj.prev().find('details').prop('open', false);
obj.removeClass('wpvivid-open');
obj.addClass('wpvivid-close');
}
}
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-handle-database-detail', function() {
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-detail');
var sub_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-detail');
wpvivid_handle_custom_open_close(obj, sub_obj);
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-handle-themes-plugins-detail', function() {
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-themes-plugins-detail');
var sub_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-detail');
wpvivid_handle_custom_open_close(obj, sub_obj);
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-handle-uploads-detail', function() {
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-uploads-detail');
var sub_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-detail');
wpvivid_handle_custom_open_close(obj, sub_obj);
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-handle-content-detail', function() {
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-content-detail');
var sub_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-detail');
wpvivid_handle_custom_open_close(obj, sub_obj);
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-handle-additional-file-detail', function() {
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-additional-file-detail');
var sub_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-detail');
wpvivid_handle_custom_open_close(obj, sub_obj);
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-custom-check', function() {
if (jQuery(this).prop('checked')) {
if(!jQuery(this).hasClass('wpvivid-custom-core-check')) {
jQuery(jQuery(this).parents('tr').next().get(0)).css({'pointer-events': 'auto', 'opacity': '1'});
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-check').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
if (!jQuery(this).hasClass('wpvivid-custom-core-check')) {
jQuery(jQuery(this).parents('tr').next().get(0)).css({'pointer-events': 'none', 'opacity': '0.4'});
}
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under Custom option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-database-table-check', function() {
if(jQuery(this).prop('checked')){
if(jQuery(this).hasClass('wpvivid-database-base-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-database-woo-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=woo_db][name=Database]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-database-other-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').prop('checked', true);
}
}
else{
var check_status = false;
if (jQuery(this).hasClass('wpvivid-database-base-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=woo_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
else if (jQuery(this).hasClass('wpvivid-database-woo-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=woo_db][name=Database]').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
else if (jQuery(this).hasClass('wpvivid-database-other-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=woo_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=base_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-base-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-base-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=woo_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=woo_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-woo-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-woo-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=other_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-other-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-other-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-themes-plugins-table-check', function(){
if(jQuery(this).prop('checked')){
if(jQuery(this).hasClass('wpvivid-themes-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-plugins-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').prop('checked', true);
}
}
else{
var check_status = false;
if (jQuery(this).hasClass('wpvivid-themes-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under the Themes and Plugins option, or deselect the option.');
}
}
else if (jQuery(this).hasClass('wpvivid-plugins-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').each(function(){
if(jQuery(this).val() !== 'wpvivid-backuprestore' && jQuery(this).val() !== 'wpvivid-backup-pro'){
jQuery(this).prop('checked', false);
}
});
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under the Themes and Plugins option, or deselect the option.');
}
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=themes][name=Themes]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-themes-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(!check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
}
if(check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-themes-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under the Themes and Plugins option, or deselect the option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=plugins][name=Plugins]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-plugins-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(!check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
}
if(check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-plugins-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under the Themes and Plugins option, or deselect the option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-uploads-extension-rule-btn', function(){
var value = jQuery(this).prev().val();
if(value!=='') {
wpvivid_update_staging_exclude_extension('upload', value);
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-content-extension-rule-btn', function(){
var value = jQuery(this).prev().val();
if(value!=='') {
wpvivid_update_staging_exclude_extension('content', value);
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-additional-file-extension-rule-btn', function(){
var value = jQuery(this).prev().val();
if(value!=='') {
wpvivid_update_staging_exclude_extension('additional_file', value);
}
});
function wpvivid_update_staging_exclude_extension(type, value){
var ajax_data = {
'action': 'wpvividstg_update_staging_exclude_extension_free',
'type': type,
'exclude_content': value
};
jQuery(this).css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function (data) {
jQuery(this).css({'pointer-events': 'auto', 'opacity': '1'});
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
}
}
catch (err) {
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
jQuery(this).css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = wpvivid_output_ajaxerror('saving staging extension', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-custom-li-close', function(){
jQuery(this).parent().parent().remove();
});
</script>
<?php
}
}
class WPvivid_Custom_Staging_List
{
public $parent_id;
public $is_staging_site = false;
public $staging_home_path = false;
public $custom_uploads_path;
public $custom_content_path;
public $custom_additional_file_path;
public function __construct(){
}
public function set_parent_id($parent_id){
$this->parent_id = $parent_id;
}
public function set_staging_home_path($is_staging_site=false, $staging_home_path=false){
$this->is_staging_site = $is_staging_site;
$this->staging_home_path = $staging_home_path;
}
public function display_rows(){
$core_check = 'checked';
$database_check = 'checked';
$database_text_style = 'pointer-events: auto; opacity: 1;';
$themes_check = 'checked';
$plugins_check = 'checked';
$themes_plugins_check = 'checked';
$themes_plugins_text_style = 'pointer-events: auto; opacity: 1;';
$uploads_check = 'checked';
$uploads_text_style = 'pointer-events: auto; opacity: 1;';
$content_check = 'checked';
$content_text_style = 'pointer-events: auto; opacity: 1;';
$additional_file_check = '';
$additional_file_text_style = 'pointer-events: none; opacity: 0.4;';
$upload_extension = '';
$content_extension = '';
$additional_file_extension = '';
if($this->is_staging_site){
$border_css = 'border: 1px solid #f1f1f1;';
$checkbox_disable = '';
$core_descript = 'If the staging site and the live site have the same version of WordPress. Then it is not necessary to copy the WordPress core files to the live site.';
$db_descript = 'It is recommended to copy all tables of the database to the live site.';
$themes_plugins_descript = 'The activated plugins and themes will be copied to the live site by default. The Child theme must be copied if it exists';
$uploads_descript = 'Images and media files are stored in the Uploads directory by default. All files are copied to the live site by default. You can exclude folders you do not want to copy.';
$contents_descript = '<strong style="text-decoration:underline;"><i>Exclude</i></strong> folders you do not want to copy to the live site, except for the wp-content/uploads folder.';
$additional_file_descript = '<strong style="text-decoration:underline;"><i>Include</i></strong> additional files or folders you want to copy to the live site.';
}
else{
$border_css = 'border: none;';
$checkbox_disable = ' disabled';
$core_descript = 'These are the essential files for creating a staging site.';
$db_descript = 'The tables created by WordPress are required for the staging site. Database tables created by themes or plugins are optional.';
$themes_plugins_descript = 'The activated plugins and themes will be copied to a staging site by default. A Child theme must be copied if it exists.';
$uploads_descript = 'Images and media files are stored in the Uploads directory by default. All files are copied to the staging site by default. You can exclude folders you do not want to copy.';
$contents_descript = '<strong style="text-decoration:underline;"><i>Exclude</i></strong> folders you do not want to copy to the staging site, except for the wp-content/uploads folder.';
$additional_file_descript = '<strong style="text-decoration:underline;"><i>Include</i></strong> additional files or folders you want to copy to the staging site.';
$options = get_option('wpvivid_staging_history', array());
if(isset($options['additional_file_check'])) {
$additional_file_check = $options['additional_file_check'] == '1' ? 'checked' : '';
$additional_file_text_style = $options['additional_file_check'] == '1' ? 'pointer-events: auto; opacity: 1;' : 'pointer-events: none; opacity: 0.4;';
}
if(isset($options['upload_extension']) && !empty($options['upload_extension'])){
$upload_extension = implode(",", $options['upload_extension']);
}
if(isset($options['content_extension']) && !empty($options['content_extension'])){
$content_extension = implode(",", $options['content_extension']);
}
if(isset($options['additional_file_extension']) && !empty($options['additional_file_extension'])){
$additional_file_extension = implode(",", $options['additional_file_extension']);
}
}
?>
<table class="wp-list-table widefat plugins wpvivid-custom-table" style="<?php echo esc_attr($border_css); ?>">
<tbody>
<!-------- core -------->
<tr>
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" name="checked[]" class="wpvivid-custom-check wpvivid-custom-core-check" <?php echo esc_attr($core_check.$checkbox_disable); ?> />
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-wordpress-core">Wordpress Core</td>
<td class="column-description desc core-desc"><?php echo esc_html($core_descript); ?></td>
</tr>
<!-------- database -------->
<tr style="cursor:pointer;">
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" name="checked[]" class="wpvivid-custom-check wpvivid-custom-database-check" <?php echo esc_attr($database_check.$checkbox_disable); ?> />
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-handle-database-detail">Database</td>
<td class="column-description desc wpvivid-handle-database-detail database-desc">
<?php echo esc_html($db_descript); ?>
</td>
<th class="wpvivid-handle-database-detail">
<details class="primer" onclick="return false;" style="display: inline-block; width: 100%;">
<summary title="Show detail" style="float: right; color: #a0a5aa;"></summary>
</details>
</th>
</tr>
<tr class="wpvivid-custom-detail wpvivid-database-detail wpvivid-close" style="<?php echo esc_attr($database_text_style); ?> display: none;">
<th class="check-column"></th>
<td colspan="3" class="plugin-title column-primary wpvivid-custom-database-info">
<div class="spinner" style="margin: 0 5px 10px 0; float: left;"></div>
<div style="float: left;">Archieving database tables</div>
<div style="clear: both;"></div>
</td>
</tr>
<!-------- themes and plugins -------->
<tr style="cursor:pointer">
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" name="checked[]" class="wpvivid-custom-check wpvivid-custom-themes-plugins-check" <?php echo esc_attr($themes_plugins_check.$checkbox_disable); ?> />
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-handle-themes-plugins-detail">Themes and Plugins</td>
<td class="column-description desc wpvivid-handle-themes-plugins-detail themes-plugins-desc">
<?php echo esc_html($themes_plugins_descript); ?>
</td>
<th class="wpvivid-handle-themes-plugins-detail">
<details class="primer" onclick="return false;" style="display: inline-block; width: 100%;">
<summary title="Show detail" style="float: right; color: #a0a5aa;"></summary>
</details>
</th>
</tr>
<tr class="wpvivid-custom-detail wpvivid-themes-plugins-detail wpvivid-close" style="<?php echo esc_attr($themes_plugins_text_style); ?> display: none;">
<th class="check-column"></th>
<td colspan="3" class="plugin-title column-primary wpvivid-custom-themes-plugins-info">
<div class="spinner" style="margin: 0 5px 10px 0; float: left;"></div>
<div style="float: left;">Archieving themes and plugins</div>
<div style="clear: both;"></div>
</td>
</tr>
<!-------- uploads -------->
<tr style="cursor:pointer">
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" name="checked[]" class="wpvivid-custom-check wpvivid-custom-uploads-check" <?php echo esc_attr($uploads_check.$checkbox_disable); ?> />
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-handle-uploads-detail">wp-content/uploads</td>
<td class="column-description desc wpvivid-handle-uploads-detail uploads-desc"><?php echo esc_html($uploads_descript); ?></td>
<th class="wpvivid-handle-uploads-detail">
<details class="primer" onclick="return false;" style="display: inline-block; width: 100%;">
<summary title="Show detail" style="float: right; color: #a0a5aa;"></summary>
</details>
</th>
</tr>
<tr class="wpvivid-custom-detail wpvivid-uploads-detail wpvivid-close" style="<?php echo esc_attr($uploads_text_style); ?> display: none;">
<th class="check-column"></th>
<td colspan="3" class="plugin-title column-primary">
<table class="wp-list-table widefat plugins" style="width:100%;">
<thead>
<tr>
<th class="manage-column column-name column-primary" style="border-bottom: 1px solid #e1e1e1 !important;">
<label class="wpvivid-refresh-tree wpvivid-refresh-uploads-tree" style="margin-bottom: 0; font-size: 13px;">Click Here to Refresh Folder Tree</label>
</th>
<th class="manage-column column-description" style="font-size: 13px; border-bottom: 1px solid #e1e1e1 !important;">Checked Folders or Files to Transfer</th>
</tr>
</thead>
<tbody>
<tr>
<td class="wpvivid-custom-uploads-left" style="padding-right: 0;">
<div class="wpvivid-custom-uploads-tree">
<div class="wpvivid-custom-tree wpvivid-custom-uploads-tree-info"></div>
</div>
</td>
<td class="wpvivid-custom-uploads-right">
<div class="wpvivid-custom-uploads-table wpvivid-custom-exclude-uploads-list">
<?php
if(!$this->is_staging_site)
{
$this->wpvivid_load_custom_upload();
}
?>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<div>
<div style="float: left; margin-right: 10px;">
<input class="button-primary wpvivid-exclude-uploads-folder-btn" type="submit" value="Exclude Folders" disabled />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Double click to open the folder tree, press Ctrl + left-click to select multiple items.</div>
</div>
</small>
<div style="clear: both;"></div>
</div>
</td>
</tr>
</tfoot>
<div style="clear:both;"></div>
</table>
<div style="margin-top: 10px;">
<div style="float: left; margin-right: 10px;">
<input type="text" class="regular-text wpvivid-uploads-extension" placeholder="Exclude file types, for example: gif,jpg,webp" value="<?php echo esc_attr($upload_extension); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_,]/g,'')"/>
<input type="button" class="wpvivid-uploads-extension-rule-btn" value="Save" />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Exclude file types from the copy. All file types are separated by commas, for example: jpg, gif, tmp etc (without a dot before the file type).</div>
</div>
</small>
<div style="clear: both;"></div>
</div>
</td>
</tr>
<!-------- content -------->
<tr style="cursor:pointer">
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" name="checked[]" class="wpvivid-custom-check wpvivid-custom-content-check" <?php echo esc_attr($content_check.$checkbox_disable); ?> />
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-handle-content-detail">wp-content</td>
<td class="column-description desc wpvivid-handle-content-detail content-desc"><?php echo esc_html($contents_descript); ?></td>
<th class="wpvivid-handle-content-detail">
<details class="primer" onclick="return false;" style="display: inline-block; width: 100%;">
<summary title="Show detail" style="float: right; color: #a0a5aa;"></summary>
</details>
</th>
</tr>
<tr class="wpvivid-custom-detail wpvivid-content-detail wpvivid-close" style="<?php echo esc_attr($content_text_style); ?> display: none;">
<th class="check-column"></th>
<td colspan="3" class="plugin-title column-primary">
<table class="wp-list-table widefat plugins" style="width:100%;">
<thead>
<tr>
<th class="manage-column column-name column-primary" style="border-bottom: 1px solid #e1e1e1 !important;">
<label class="wpvivid-refresh-tree wpvivid-refresh-content-tree" style="margin-bottom: 0; font-size: 13px;">Click Here to Refresh Folder Tree</label>
</th>
<th class="manage-column column-description" style="font-size: 13px; border-bottom: 1px solid #e1e1e1 !important;">Checked Folders or Files to Transfer</th>
</tr>
</thead>
<tbody>
<tr>
<td class="wpvivid-custom-uploads-left" style="padding-right: 0;">
<div class="wpvivid-custom-uploads-tree">
<div class="wpvivid-custom-tree wpvivid-custom-content-tree-info"></div>
</div>
</td>
<td class="wpvivid-custom-uploads-right">
<div class="wpvivid-custom-uploads-table wpvivid-custom-exclude-content-list">
<?php
if(!$this->is_staging_site){
$this->wpvivid_load_custom_content();
}
?>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<div style="float: left; margin-right: 10px;">
<input class="button-primary wpvivid-exclude-content-folder-btn" type="submit" value="Exclude Folders" disabled />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Double click to open the folder tree, press Ctrl + left-click to select multiple items.</div>
</div>
</small>
<div style="clear: both;"></div>
</td>
</tr>
</tfoot>
<div style="clear:both;"></div>
</table>
<div style="margin-top: 10px;">
<div style="float: left; margin-right: 10px;">
<input type="text" class="regular-text wpvivid-content-extension" placeholder="Exclude file types, for example: gif,jpg,webp" value="<?php echo esc_attr($content_extension); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_,]/g,'')"/>
<input type="button" class="wpvivid-content-extension-rule-btn" value="Save" />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Exclude file types from the copy. All file types are separated by commas, for example: jpg, gif, tmp etc (without a dot before the file type).</div>
</div>
</small>
<div style="clear: both;"></div>
</div>
</td>
</tr>
<!-------- additional files -------->
<tr style="cursor:pointer">
<th class="check-column" scope="row" style="padding-left: 6px;">
<label class="screen-reader-text" for=""></label>
<input type="checkbox" name="checked[]" class="wpvivid-custom-check wpvivid-custom-additional-file-check" <?php echo esc_attr($additional_file_check); ?> />
</th>
<td class="plugin-title column-primary wpvivid-backup-to-font wpvivid-handle-additional-file-detail">Additional Files/Folder</td>
<td class="column-description desc wpvivid-handle-additional-file-detail additional-file-desc"><?php echo esc_html($additional_file_descript); ?></td>
<th class="wpvivid-handle-additional-file-detail">
<details class="primer" onclick="return false;" style="display: inline-block; width: 100%;">
<summary title="Show detail" style="float: right; color: #a0a5aa;"></summary>
</details>
</th>
</tr>
<tr class="wpvivid-custom-detail wpvivid-additional-file-detail wpvivid-close" style="<?php echo esc_attr($additional_file_text_style); ?> display: none;">
<th class="check-column"></th>
<td colspan="3" class="plugin-title column-primary">
<table class="wp-list-table widefat plugins" style="width:100%;">
<thead>
<tr>
<th class="manage-column column-name column-primary" style="border-bottom: 1px solid #e1e1e1 !important;">
<label class="wpvivid-refresh-tree wpvivid-refresh-additional-file-tree" style="margin-bottom: 0; font-size: 13px;">Click Here to Refresh Folder/File Tree</label>
</th>
<th class="manage-column column-description" style="font-size: 13px; border-bottom: 1px solid #e1e1e1 !important;">Checked Folders or Files to Transfer</th>
</tr>
</thead>
<tbody>
<tr>
<td class="wpvivid-custom-uploads-left" style="padding-right: 0;">
<div class="wpvivid-custom-uploads-tree">
<div class="wpvivid-custom-tree wpvivid-custom-additional-file-tree-info"></div>
</div>
</td>
<td class="wpvivid-custom-uploads-right">
<div class="wpvivid-custom-uploads-table wpvivid-custom-include-additional-file-list">
<?php
if(!$this->is_staging_site){
$this->wpvivid_load_additional_file();
}
?>
</div>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<div style="float: left; margin-right: 10px;">
<input class="button-primary wpvivid-include-additional-file-btn" type="submit" value="Include folders/files" disabled />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Double click to open the folder tree, press Ctrl + left-click to select multiple items.</div>
</div>
</small>
<div style="clear: both;"></div>
</td>
</tr>
</tfoot>
<div style="clear:both;"></div>
</table>
<div style="margin-top: 10px;">
<div style="float: left; margin-right: 10px;">
<input type="text" class="regular-text wpvivid-additional-file-extension" placeholder="Exclude file types, for example: gif,jpg,webp" value="<?php echo esc_attr($additional_file_extension); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_,]/g,'')"/>
<input type="button" class="wpvivid-additional-file-extension-rule-btn" value="Save" />
</div>
<small>
<div class="wpvivid_tooltip" style="margin-top: 8px; float: left; line-height: 100%; white-space: normal;">?
<div class="wpvivid_tooltiptext">Exclude file types from the copy. All file types are separated by commas, for example: jpg, gif, tmp etc (without a dot before the file type).</div>
</div>
</small>
<div style="clear: both;"></div>
</div>
</td>
</tr>
</tbody>
</table>
<?php
}
public function wpvivid_load_custom_upload(){
$options = get_option('wpvivid_staging_history', array());
$ret = '';
if(isset($options['uploads_list']) && !empty($options['uploads_list']))
{
foreach ($options['uploads_list'] as $index => $value) {
echo '<ul style=\'margin: 0;\'>
<li>
<div class="'.esc_attr($value['type']).'"></div>
<div class="wpvivid-custom-li-font">'.esc_html($value['name']).'</div>
<div class="wpvivid-custom-li-close" onclick="wpvivid_remove_custom_tree(this);" title="Remove" style="cursor: pointer;">X</div>
</li>
</ul>';
}
}
}
public function wpvivid_load_custom_content(){
$options = get_option('wpvivid_staging_history', array());
$ret = '';
if(isset($options['content_list']) && !empty($options['content_list'])) {
foreach ($options['content_list'] as $index => $value) {
echo '<ul style=\'margin: 0;\'>
<li>
<div class="'.esc_attr($value['type']).'"></div>
<div class="wpvivid-custom-li-font">'.esc_html($value['name']).'</div>
<div class="wpvivid-custom-li-close" onclick="wpvivid_remove_custom_tree(this);" title="Remove" style="cursor: pointer;">X</div>
</li>
</ul>';
}
}
}
public function wpvivid_load_additional_file(){
$options = get_option('wpvivid_staging_history', array());
$ret = '';
if(isset($options['additional_file_list']) && !empty($options['additional_file_list'])) {
foreach ($options['additional_file_list'] as $index => $value) {
echo '<ul style=\'margin: 0;\'>
<li>
<div class="'.esc_attr($value['type']).'"></div>
<div class="wpvivid-custom-li-font">'.esc_html($value['name']).'</div>
<div class="wpvivid-custom-li-close" onclick="wpvivid_remove_custom_tree(this);" title="Remove" style="cursor: pointer;">X</div>
</li>
</ul>';
}
}
}
public function load_js(){
$upload_dir = wp_upload_dir();
$upload_path = $this->is_staging_site === false ? $upload_dir['basedir'] : $this->staging_home_path.'/wp-content/uploads';
$upload_path = str_replace('\\','/',$upload_path);
$upload_path = $upload_path.'/';
$this->custom_uploads_path = $upload_path;
$content_dir = $this->is_staging_site === false ? WP_CONTENT_DIR : $this->staging_home_path.'/wp-content';
$content_path = str_replace('\\','/',$content_dir);
$content_path = $content_path.'/';
$this->custom_content_path = $content_path;
$additional_file_path = $this->is_staging_site === false ? str_replace('\\','/',get_home_path()) : str_replace('\\','/',$this->staging_home_path);
$this->custom_additional_file_path = $additional_file_path;
?>
<script>
function wpvivid_handle_custom_open_close(obj, sub_obj){
if(obj.hasClass('wpvivid-close')) {
sub_obj.hide();
sub_obj.prev().find('details').prop('open', false);
sub_obj.removeClass('wpvivid-open');
sub_obj.addClass('wpvivid-close');
sub_obj.prev().css('background-color', '#fff');
obj.prev().css('background-color', '#f1f1f1');
obj.prev().find('details').prop('open', true);
obj.show();
obj.removeClass('wpvivid-close');
obj.addClass('wpvivid-open');
}
else{
obj.hide();
obj.prev().css('background-color', '#fff');
obj.prev().find('details').prop('open', false);
obj.removeClass('wpvivid-open');
obj.addClass('wpvivid-close');
}
}
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-handle-database-detail', function() {
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-detail');
var sub_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-detail');
wpvivid_handle_custom_open_close(obj, sub_obj);
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-handle-themes-plugins-detail', function() {
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-themes-plugins-detail');
var sub_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-detail');
wpvivid_handle_custom_open_close(obj, sub_obj);
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-handle-uploads-detail', function() {
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-uploads-detail');
var sub_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-detail');
wpvivid_handle_custom_open_close(obj, sub_obj);
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-handle-content-detail', function() {
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-content-detail');
var sub_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-detail');
wpvivid_handle_custom_open_close(obj, sub_obj);
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-handle-additional-file-detail', function() {
var obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-additional-file-detail');
var sub_obj = jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-detail');
wpvivid_handle_custom_open_close(obj, sub_obj);
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-custom-check', function() {
if (jQuery(this).prop('checked')) {
if(!jQuery(this).hasClass('wpvivid-custom-core-check')) {
jQuery(jQuery(this).parents('tr').next().get(0)).css({'pointer-events': 'auto', 'opacity': '1'});
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-custom-check').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
if (!jQuery(this).hasClass('wpvivid-custom-core-check')) {
jQuery(jQuery(this).parents('tr').next().get(0)).css({'pointer-events': 'none', 'opacity': '0.4'});
}
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under Custom option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-database-table-check', function() {
if(jQuery(this).prop('checked')){
if(jQuery(this).hasClass('wpvivid-database-base-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-database-woo-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=woo_db][name=Database]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-database-other-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').prop('checked', true);
}
}
else{
var check_status = false;
if (jQuery(this).hasClass('wpvivid-database-base-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=woo_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
else if (jQuery(this).hasClass('wpvivid-database-woo-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=woo_db][name=Database]').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
else if (jQuery(this).hasClass('wpvivid-database-other-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=woo_db][name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=base_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=base_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-base-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-base-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=woo_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=woo_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-woo-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-woo-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=other_db][name=Database]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=other_db][name=Database]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-other-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[name=Database]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-database-other-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one table type under the Database option, or deselect the option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-themes-plugins-table-check', function(){
if(jQuery(this).prop('checked')){
if(jQuery(this).hasClass('wpvivid-themes-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').prop('checked', true);
}
else if(jQuery(this).hasClass('wpvivid-plugins-table-check')){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').prop('checked', true);
}
}
else{
var check_status = false;
if (jQuery(this).hasClass('wpvivid-themes-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under the Themes and Plugins option, or deselect the option.');
}
}
else if (jQuery(this).hasClass('wpvivid-plugins-table-check')) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(check_status) {
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').each(function(){
if(jQuery(this).val() !== 'wpvivid-backuprestore' && jQuery(this).val() !== 'wpvivid-backup-pro'){
jQuery(this).prop('checked', false);
}
});
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under the Themes and Plugins option, or deselect the option.');
}
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=themes][name=Themes]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-themes-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(!check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
}
if(check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-themes-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under the Themes and Plugins option, or deselect the option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", 'input:checkbox[option=plugins][name=Plugins]', function(){
if(jQuery(this).prop('checked')){
var all_check = true;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').each(function(){
if(!jQuery(this).prop('checked')){
all_check = false;
}
});
if(all_check){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-plugins-table-check').prop('checked', true);
}
}
else{
var check_status = false;
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=plugins][name=Plugins]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
if(!check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('input:checkbox[option=themes][name=Themes]').each(function(){
if(jQuery(this).prop('checked')){
check_status = true;
}
});
}
if(check_status){
jQuery('#<?php echo esc_attr($this->parent_id); ?>').find('.wpvivid-plugins-table-check').prop('checked', false);
}
else{
jQuery(this).prop('checked', true);
alert('Please select at least one item under the Themes and Plugins option, or deselect the option.');
}
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-uploads-extension-rule-btn', function(){
var value = jQuery(this).prev().val();
if(value!=='') {
wpvivid_update_staging_exclude_extension('upload', value);
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-content-extension-rule-btn', function(){
var value = jQuery(this).prev().val();
if(value!=='') {
wpvivid_update_staging_exclude_extension('content', value);
}
});
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-additional-file-extension-rule-btn', function(){
var value = jQuery(this).prev().val();
if(value!=='') {
wpvivid_update_staging_exclude_extension('additional_file', value);
}
});
function wpvivid_update_staging_exclude_extension(type, value){
var ajax_data = {
'action': 'wpvividstg_update_staging_exclude_extension_free',
'type': type,
'exclude_content': value
};
jQuery(this).css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function (data) {
jQuery(this).css({'pointer-events': 'auto', 'opacity': '1'});
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
}
}
catch (err) {
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
jQuery(this).css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = wpvivid_output_ajaxerror('saving staging extension', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#<?php echo esc_attr($this->parent_id); ?>').on("click", '.wpvivid-custom-li-close', function(){
jQuery(this).parent().parent().remove();
});
</script>
<?php
}
}
class WPvivid_Staging_Sites_List_Free
{
public function __construct()
{
}
} includes/staging/class-wpvivid-staging.php 0000644 00000346061 15132770567 0014773 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
if ( ! class_exists( 'WP_List_Table' ) )
{
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class WPvivid_Staging_Free
{
public $main_tab;
public $end_shutdown_function;
public $screen_ids;
public $log;
public $log_page;
public $new_wp_page;
public $ui_display;
public $setting;
public function __construct()
{
if(is_admin())
{
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-copy-db-ex.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-copy-files-ex.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-task-ex.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-log.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-log-page.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-create-new-wp.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-ui-display.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-setting.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-sites-list.php';
$this->log=new WPvivid_Staging_Log_Free();
$this->log_page=new WPvivid_Staging_Log_Page_Free();
$this->ui_display=new WPvivid_Staging_UI_Display_Free();
$this->setting=new WPvivid_Staging_Setting_Free();
add_action('admin_enqueue_scripts',array( $this,'enqueue_styles'));
add_action('admin_enqueue_scripts',array( $this,'enqueue_scripts'));
//add_filter('wpvivid_add_side_bar', array($this, 'add_side_bar'), 11, 2);
add_action('wpvivid_add_staging_side_bar_ex', array($this, 'add_side_bar'), 11, 2);
add_filter('wpvivid_get_toolbar_menus',array($this,'get_toolbar_menus'),22);
add_filter('wpvivid_get_admin_menus',array($this,'get_admin_menus'),22);
add_filter('wpvivid_get_screen_ids',array($this,'get_screen_ids'),12);
$this->load_ajax();
}
add_filter('wpvividstg_get_admin_url',array($this,'get_admin_url'),10);
add_filter('wpvivid_add_staging_side_bar', array($this, 'wpvivid_add_staging_side_bar'), 11, 2);
add_action( "init",array($this,'staging_site'));
}
public function add_side_bar($html, $show_schedule = false)
{
if(get_current_screen()->id=='wpvivid-backup_page_wpvivid-staging')
{
$wpvivid_version = WPVIVID_PLUGIN_VERSION;
$wpvivid_version = apply_filters('wpvivid_display_pro_version', $wpvivid_version);
?>
<div class="postbox">
<h2>
<div style="float: left; margin-right: 5px;"><span style="margin: 0; padding: 0"><?php esc_html_e('Current Version: ', 'wpvivid-backuprestore'); ?><?php echo esc_html($wpvivid_version); ?></span></div>
<div style="float: left; margin-right: 5px;"><span style="margin: 0; padding: 0">|</span></div>
<div style="float: left; margin-left: 0;">
<span style="margin: 0; padding: 0"><a href="https://wordpress.org/plugins/wpvivid-backuprestore/#developers" target="_blank" style="text-decoration: none;"><?php esc_html_e('ChangeLog', 'wpvivid-backuprestore'); ?></a></span>
</div>
<div style="clear: both;"></div>
</h2>
</div>
<div id="wpvivid_backup_schedule_part"></div>
<div class="postbox">
<h2><span><?php esc_html_e('Troubleshooting', 'wpvivid-backuprestore'); ?></span></h2>
<div class="inside">
<table class="widefat" cellpadding="0">
<tbody>
<tr class="alternate">
<td class="row-title">'Read <a href="https://docs.wpvivid.com/troubleshooting-issues-wpvivid-backup-plugin.html" target="_blank">Troubleshooting page</a> for faster solutions.'</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="postbox">
<h2><span><?php esc_html_e('How-to', 'wpvivid-backuprestore'); ?></span></h2>
<div class="inside">
<table class="widefat" cellpadding="0">
<tbody>
<tr class="alternate"><td class="row-title"><a href="https://docs.wpvivid.com/wpvivid-backup-pro-create-staging-site.html" target="_blank"><?php esc_html_e('Create A Staging Site', 'wpvivid-backuprestore'); ?></a></td></tr>
<tr><td class="row-title"><a href="https://docs.wpvivid.com/wpvivid-staging-pro-create-fresh-install.html" target="_blank"><?php esc_html_e('Create A Fresh WordPress Install', 'wpvivid-backuprestore'); ?></a></td></tr>
</tbody>
</table>
</div>
</div>
<?php
/*$html = '<div class="postbox">
<h2>
<div style="float: left; margin-right: 5px;"><span style="margin: 0; padding: 0">'.__('Current Version:', 'wpvivid-backuprestore').' '.$wpvivid_version.'</span></div>
<div style="float: left; margin-right: 5px;"><span style="margin: 0; padding: 0">|</span></div>
<div style="float: left; margin-left: 0;">
<span style="margin: 0; padding: 0"><a href="https://wordpress.org/plugins/wpvivid-backuprestore/#developers" target="_blank" style="text-decoration: none;">'.__('ChangeLog', 'wpvivid-backuprestore').'</a></span>
</div>
<div style="clear: both;"></div>
</h2>
</div>
<div id="wpvivid_backup_schedule_part"></div>
<div class="postbox">
<h2><span>'.__('Troubleshooting', 'wpvivid-backuprestore').'</span></h2>
<div class="inside">
<table class="widefat" cellpadding="0">
<tbody>
<tr class="alternate">
<td class="row-title">'.__('Read <a href="https://docs.wpvivid.com/troubleshooting-issues-wpvivid-backup-plugin.html" target="_blank">Troubleshooting page</a> for faster solutions.', 'wpvivid-backuprestore').'</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="postbox">
<h2><span>'.__('How-to', 'wpvivid-backuprestore').'</span></h2>
<div class="inside">
<table class="widefat" cellpadding="0">
<tbody>
<tr class="alternate"><td class="row-title"><a href="https://docs.wpvivid.com/wpvivid-backup-pro-create-staging-site.html" target="_blank">'.__('Create A Staging Site', 'wpvivid-backuprestore').'</a></td></tr>
<tr><td class="row-title"><a href="https://docs.wpvivid.com/wpvivid-staging-pro-create-fresh-install.html" target="_blank">'.__('Create A Fresh WordPress Install', 'wpvivid-backuprestore').'</a></td></tr>
</tbody>
</table>
</div>
</div>';*/
}
//return $html;
}
public function get_admin_url($admin_url)
{
if(is_multisite())
{
$admin_url = network_admin_url();
}
else
{
$admin_url =admin_url();
}
return $admin_url;
}
public function wpvivid_add_staging_side_bar($html, $show_schedule)
{
$html = '<h2 style="margin-top:0.5em;">
<span class="dashicons dashicons-sticky wpvivid-dashicons-orange"></span>
<span>Troubleshooting</span>
</h2>
<div class="inside" style="padding-top:0;">
<ul class="" >
<li style="border-top:1px solid #f1f1f1;"><span class="dashicons dashicons-editor-help wpvivid-dashicons-orange" ></span>
<a href="https://docs.wpvivid.com/troubleshooting-issues-wpvivid-staging-pro.html"><b>Troubleshooting</b></a>
<small><span style="float: right;"><a href="https://wpvivid.com/troubleshooting-issues-wpvivid-staging-pro" style="text-decoration: none;" target="_blank"><span class="dashicons dashicons-migrate wpvivid-dashicons-grey"></span></a></span></small><br>
</li>
</ul>
</div>
<h2>
<span class="dashicons dashicons-book-alt wpvivid-dashicons-orange" ></span>
<span>Documentation</span>
</h2>
<div class="inside" style="padding-top:0;">
<ul class="">
<li style="border-top:1px solid #f1f1f1;"><span class="dashicons dashicons-migrate wpvivid-dashicons-blue"></span>
<a href="https://docs.wpvivid.com/wpvivid-backup-pro-create-staging-site.html"><b>Create A Staging Site</b></a>
<small><span style="float: right;"><a href="https://wpvivid.com/wpvivid-backup-pro-create-staging-site" style="text-decoration: none;"><span class="dashicons dashicons-migrate wpvivid-dashicons-grey"></span></a></span></small><br>
</li>
<li><span class="dashicons dashicons-migrate wpvivid-dashicons-blue"></span>
<a href="https://docs.wpvivid.com/wpvivid-staging-pro-publish-staging-to-live.html"><b>Publish A Staging Site</b></a>
<small><span style="float: right;"><a href="https://wpvivid.com/wpvivid-backup-pro-publish-staging-to-live" style="text-decoration: none;"><span class="dashicons dashicons-migrate wpvivid-dashicons-grey"></span></a></span></small><br>
</li>
<li><span class="dashicons dashicons-migrate wpvivid-dashicons-blue"></span>
<a href="https://docs.wpvivid.com/wpvivid-staging-pro-create-staging-site-for-wordpress-multisite.html"><b>Create A MU Staging</b></a>
<small><span style="float: right;"><a href="https://wpvivid.com/wpvivid-staging-pro-create-staging-site-for-wordpress-multisite" style="text-decoration: none;"><span class="dashicons dashicons-migrate wpvivid-dashicons-grey"></span></a></span></small><br>
</li>
</ul>
</div>';
return $html;
}
public function load_ajax()
{
add_action('wp_ajax_wpvividstg_start_staging_free', array($this, 'start_staging'));
//add_action('wp_ajax_nopriv_wpvividstg_start_staging_free', array($this, 'start_staging'));
add_action('wp_ajax_wpvividstg_set_restart_staging_id_free', array($this, 'set_restart_staging_id'));
add_action('wp_ajax_wpvividstg_get_staging_progress_free', array($this, 'get_staging_progress'));
//add_action('wp_ajax_nopriv_wpvividstg_get_staging_progress_free', array($this, 'get_staging_progress'));
add_action('wp_ajax_wpvividstg_delete_site_free', array($this, 'delete_site'));
add_action('wp_ajax_wpvividstg_delete_cancel_staging_site_free', array($this, 'delete_cancel_staging_site'));
add_action('wp_ajax_wpvividstg_check_staging_dir_free', array($this, 'check_staging_dir'));
add_action('wp_ajax_wpvividstg_check_filesystem_permissions_free', array($this, 'check_filesystem_permissions'));
//
add_action('wp_ajax_wpvividstg_get_custom_database_tables_info_free',array($this, 'get_custom_database_tables_info'));
add_action('wp_ajax_wpvividstg_cancel_staging_free', array($this, 'cancel_staging'));
add_action('wp_ajax_wpvividstg_test_additional_database_connect_free', array($this, 'test_additional_database_connect'));
add_action('wp_ajax_wpvividstg_update_staging_exclude_extension_free', array($this, 'update_staging_exclude_extension'));
//
add_action('wp_ajax_wpvividstg_get_custom_database_size_free', array($this, 'get_custom_database_size'));
add_action('wp_ajax_wpvividstg_get_custom_files_size_free', array($this, 'get_custom_files_size'));
}
public function enqueue_styles()
{
$this->screen_ids=apply_filters('wpvivid_get_screen_ids',$this->screen_ids);
if(get_current_screen()->id=='wpvivid-backup_page_wpvivid-staging')
{
wp_enqueue_style(WPVIVID_PLUGIN_SLUG.'jstree', WPVIVID_PLUGIN_DIR_URL . 'js/jstree/dist/themes/default/style.min.css', array(), WPVIVID_PLUGIN_VERSION, 'all');
wp_enqueue_style(WPVIVID_PLUGIN_SLUG.'staging', WPVIVID_PLUGIN_DIR_URL . 'css/wpvivid-staging-custom.css', array(), WPVIVID_PLUGIN_VERSION, 'all');
}
}
public function enqueue_scripts()
{
$this->screen_ids=apply_filters('wpvivid_get_screen_ids',$this->screen_ids);
if(in_array(get_current_screen()->id,$this->screen_ids))
{
wp_enqueue_script(WPVIVID_PLUGIN_SLUG.'jstree', WPVIVID_PLUGIN_DIR_URL . 'js/jstree/dist/jstree.min.js', array('jquery'), WPVIVID_PLUGIN_VERSION, false);
wp_enqueue_script('plupload-all');
}
}
public function get_screen_ids($screen_ids)
{
$screen_ids[]=apply_filters('wpvivid_white_label_screen_id', 'wpvivid-backup_page_wpvivid-staging');
return $screen_ids;
}
public function get_toolbar_menus($toolbar_menus)
{
$admin_url = apply_filters('wpvivid_get_admin_url', '');
$menu['id']='wpvivid_admin_menu_staging';
$menu['parent']='wpvivid_admin_menu';
$menu['title']=__('Staging', 'wpvivid-backuprestore');
$menu['tab']= 'admin.php?page='.apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-staging');
$menu['href']=$admin_url . 'admin.php?page='.apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-staging');
$menu['capability']='administrator';
$menu['index']=3;
$toolbar_menus[$menu['parent']]['child'][$menu['id']]=$menu;
return $toolbar_menus;
}
public function get_admin_menus($submenus)
{
$submenu['parent_slug']=apply_filters('wpvivid_white_label_slug', WPVIVID_PLUGIN_SLUG);
$submenu['page_title']= apply_filters('wpvivid_white_label_display', 'WPvivid Backup');
$submenu['menu_title']=__('Staging', 'wpvivid-backuprestore');
$submenu['capability']='administrator';
$submenu['menu_slug']=strtolower(sprintf('%s-staging', apply_filters('wpvivid_white_label_slug', 'wpvivid')));
$submenu['index']=3;
$submenu['function']=array($this, 'display_plugin_setup_page');
$submenus[$submenu['menu_slug']]=$submenu;
return $submenus;
}
public function display_plugin_setup_page()
{
?>
<?php
$this->ui_display->init_page();
?>
<?php
}
public function get_database_site_url()
{
$site_url = site_url();
global $wpdb;
$site_url_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->options WHERE option_name = %s", 'siteurl' ) );
foreach ( $site_url_sql as $site ){
$site_url = $site->option_value;
}
return untrailingslashit($site_url);
}
public function get_database_home_url()
{
$home_url = home_url();
global $wpdb;
$home_url_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->options WHERE option_name = %s", 'home' ) );
foreach ( $home_url_sql as $home ){
$home_url = $home->option_value;
}
return untrailingslashit($home_url);
}
public function get_custom_database_size(){
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$ret['result']='success';
global $wpdb;
$tables = $wpdb->get_results('SHOW TABLE STATUS', ARRAY_A);
if (is_null($tables)) {
$ret['result'] = 'failed';
$ret['error'] = 'Failed to retrieve the table information for the database. Please try again.';
return $ret;
}
$db_size = 0;
$base_table_size = 0;
foreach ($tables as $row) {
$base_table_size += ($row["Data_length"] + $row["Index_length"]);
}
$db_size = size_format($base_table_size, 2);
$ret['database_size'] = $db_size;
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public static function get_custom_path_size($type, $path, $size=0){
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
$home_path = str_replace('\\','/', get_home_path());
$core_file_arr = array('.htaccess', 'index', 'license.txt', 'readme.html', 'wp-activate.php', 'wp-blog-header.php', 'wp-comments-post.php', 'wp-config.php', 'wp-config-sample.php',
'wp-cron.php', 'wp-links-opml.php', 'wp-load.php', 'wp-login.php', 'wp-mail.php', 'wp-settings.php', 'wp-signup.php', 'wp-trackback.php', 'xmlrpc.php');
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..") {
if (is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
if($type === 'content'){
if($filename !== 'plugins' && $filename !== 'themes' && $filename !== 'uploads'){
$size=self::get_custom_path_size($type, $path . DIRECTORY_SEPARATOR . $filename, $size);
}
}
else if($type === 'core' && $home_path === $path){
if($filename === 'wp-admin' || $filename === 'wp-includes'){
$size=self::get_custom_path_size($type, $path . DIRECTORY_SEPARATOR . $filename, $size);
}
}
else if($type === 'additional'){
if($filename !== 'wp-admin' && $filename !== 'wp-content' && $filename !== 'wp-includes'){
$size=self::get_custom_path_size($type, $path . DIRECTORY_SEPARATOR . $filename, $size);
}
}
else{
$size=self::get_custom_path_size($type, $path . DIRECTORY_SEPARATOR . $filename, $size);
}
} else {
if($type === 'core'){
if($home_path === $path){
if(in_array($filename, $core_file_arr)){
$size+=filesize($path . DIRECTORY_SEPARATOR . $filename);
}
}
else{
$size+=filesize($path . DIRECTORY_SEPARATOR . $filename);
}
}
else if($type === 'additional'){
if($home_path === $path){
if(!in_array($filename, $core_file_arr)){
$size+=filesize($path . DIRECTORY_SEPARATOR . $filename);
}
}
else{
$size+=filesize($path . DIRECTORY_SEPARATOR . $filename);
}
}
else{
$size+=filesize($path . DIRECTORY_SEPARATOR . $filename);
}
}
}
}
if($handler)
@closedir($handler);
}
}
return $size;
}
public function get_custom_files_size(){
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$upload_dir = wp_upload_dir();
$path = $upload_dir['basedir'];
$path = str_replace('\\','/',$path);
$uploads_path = $path.'/';
$content_dir = WP_CONTENT_DIR;
$path = str_replace('\\','/',$content_dir);
$content_path = $path.'/';
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
$home_path = str_replace('\\','/', get_home_path());
$themes_path = str_replace('\\','/', get_theme_root());
$themes_path = $themes_path.'/';
$plugins_path = str_replace('\\','/', WP_PLUGIN_DIR);
$plugins_path = $plugins_path.'/';
$ret['result']='success';
$core_size = self::get_custom_path_size('core', $home_path);
$themes_size = self::get_custom_path_size('themes', $themes_path);
$plugins_size = self::get_custom_path_size('plugins', $plugins_path);
$uploads_size = self::get_custom_path_size('uploads', $uploads_path);
$content_size = self::get_custom_path_size('content', $content_path);
$additional_size = self::get_custom_path_size('additional', $home_path);
$ret['core_size'] = size_format($core_size, 2);
$ret['themes_size'] = size_format($themes_size, 2);
$ret['plugins_size'] = size_format($plugins_size, 2);
$ret['uploads_size'] = size_format($uploads_size, 2);
$ret['content_size'] = size_format($content_size, 2);
$ret['additional_size'] = size_format($additional_size, 2);
$ret['total_file_size'] = size_format($core_size+$themes_size+$plugins_size+$uploads_size+$content_size+$additional_size, 2);
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function get_staging_site_data()
{
if(is_multisite())
{
switch_to_blog(get_main_site_id());
$staging=get_option('wpvivid_staging_data',false);
restore_current_blog();
}
else
{
$staging=get_option('wpvivid_staging_data',false);
}
return $staging;
}
public function get_custom_database_tables_info()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
global $wpdb;
$db = array();
$use_additional_db = false;
$staging_site_id = sanitize_key($_POST['id']);
if(empty($_POST['id']))
{
$get_site_mu_single=false;
}
else
{
$task = new WPvivid_Staging_Task($staging_site_id);
$site_id=$task->get_site_mu_single_site_id();
$get_site_mu_single=$task->get_site_mu_single();
}
if (isset($_POST['is_staging']) && !empty($_POST['is_staging']) && is_string($_POST['is_staging'])&&$_POST['is_staging'] == '1')
{
$base_prefix = $task->get_site_prefix();
}
else
{
$base_prefix=$wpdb->base_prefix;
}
if (isset($_POST['is_staging']) && !empty($_POST['is_staging']) && is_string($_POST['is_staging']))
{
if ($_POST['is_staging'] == '1')
{
$is_staging_site = true;
$prefix = $task->get_site_prefix();
$db = $task->get_site_db_connect();
if ($db['use_additional_db'] !== false)
{
$use_additional_db = true;
} else {
$use_additional_db = false;
}
} else {
$is_staging_site = false;
$prefix = $wpdb->get_blog_prefix(0);
}
} else {
$is_staging_site = false;
$prefix = $wpdb->get_blog_prefix(0);
}
$ret['result'] = 'success';
$ret['html'] = '';
if (empty($prefix)) {
echo wp_json_encode($ret);
die();
}
$base_table = '';
$woo_table = '';
$other_table = '';
$default_table = array($prefix . 'commentmeta', $prefix . 'comments', $prefix . 'links', $prefix . 'options', $prefix . 'postmeta', $prefix . 'posts', $prefix . 'term_relationships',
$prefix . 'term_taxonomy', $prefix . 'termmeta', $prefix . 'terms', $prefix . 'usermeta', $prefix . 'users');
$woo_table_arr = array($prefix.'actionscheduler_actions', $prefix.'actionscheduler_claims', $prefix.'actionscheduler_groups', $prefix.'actionscheduler_logs', $prefix.'aelia_dismissed_messages',
$prefix.'aelia_exchange_rates_history', $prefix.'automatewoo_abandoned_carts', $prefix.'automatewoo_customer_meta', $prefix.'automatewoo_customers', $prefix.'automatewoo_events',
$prefix.'automatewoo_guest_meta', $prefix.'automatewoo_guests', $prefix.'automatewoo_log_meta', $prefix.'automatewoo_logs', $prefix.'automatewoo_queue', $prefix.'automatewoo_queue_meta',
$prefix.'automatewoo_unsubscribes', $prefix.'wc_admin_note_actions', $prefix.'wc_admin_notes', $prefix.'wc_am_api_activation', $prefix.'wc_am_api_resource', $prefix.'wc_am_associated_api_key',
$prefix.'wc_am_secure_hash', $prefix.'wc_category_lookup', $prefix.'wc_customer_lookup', $prefix.'wc_download_log', $prefix.'wc_order_coupon_lookup', $prefix.'wc_order_product_lookup',
$prefix.'wc_order_stats', $prefix.'wc_order_tax_lookup', $prefix.'wc_product_meta_lookup', $prefix.'wc_reserved_stock', $prefix.'wc_tax_rate_classes', $prefix.'wc_webhooks',
$prefix.'woocommerce_api_keys', $prefix.'woocommerce_attribute_taxonomies', $prefix.'woocommerce_downloadable_product_permissions', $prefix.'woocommerce_log', $prefix.'woocommerce_order_itemmeta',
$prefix.'woocommerce_order_items', $prefix.'woocommerce_payment_tokenmeta', $prefix.'woocommerce_payment_tokens', $prefix.'woocommerce_sessions', $prefix.'woocommerce_shipping_zone_locations',
$prefix.'woocommerce_shipping_zone_methods', $prefix.'woocommerce_shipping_zones', $prefix.'woocommerce_tax_rate_locations', $prefix.'woocommerce_tax_rates');
if ($is_staging_site) {
$staging_option = self::wpvivid_get_push_staging_history();
if (empty($staging_option)) {
$staging_option = array();
}
if ($use_additional_db) {
$handle = new wpdb($db['dbuser'], $db['dbpassword'], $db['dbname'], $db['dbhost']);
$tables = $handle->get_results('SHOW TABLE STATUS', ARRAY_A);
} else {
$tables = $wpdb->get_results('SHOW TABLE STATUS', ARRAY_A);
}
} else {
$staging_option = self::wpvivid_get_staging_history();
if (empty($staging_option)) {
$staging_option = array();
}
$tables = $wpdb->get_results('SHOW TABLE STATUS', ARRAY_A);
}
if (is_null($tables)) {
$ret['result'] = 'failed';
$ret['error'] = 'Failed to retrieve the table information for the database. Please try again.';
echo wp_json_encode($ret);
die();
}
$tables_info = array();
$has_base_table = false;
$has_woo_table = false;
$has_other_table = false;
$base_count = 0;
$woo_count = 0;
$other_count = 0;
$base_table_all_check = true;
$woo_table_all_check = true;
$other_table_all_check = true;
foreach ($tables as $row)
{
if (preg_match('/^(?!' . $base_prefix . ')/', $row["Name"]) == 1)
{
continue;
}
if($get_site_mu_single)
{
$site_id=$task->get_site_mu_single_site_id();
if(!is_main_site($site_id))
{
if ( 1 == preg_match('/^' . $prefix . '/', $row["Name"]) )
{
}
else if ( 1 == preg_match('/^' . $base_prefix . '\d+_/', $row["Name"]) )
{
continue;
}
else
{
if($row["Name"]==$base_prefix.'users'||$row["Name"]==$base_prefix.'usermeta')
{
}
else
{
continue;
}
}
}
else
{
if ( 1 == preg_match('/^' . $base_prefix . '\d+_/', $row["Name"]) )
{
continue;
}
else
{
if($row["Name"]==$base_prefix.'blogs')
continue;
if($row["Name"]==$base_prefix.'blogmeta')
continue;
if($row["Name"]==$base_prefix.'sitemeta')
continue;
if($row["Name"]==$base_prefix.'site')
continue;
}
}
}
$tables_info[$row["Name"]]["Rows"] = $row["Rows"];
$tables_info[$row["Name"]]["Data_length"] = size_format($row["Data_length"] + $row["Index_length"], 2);
$checked = 'checked';
if (!empty($staging_option['database_list'])) {
if ($is_staging_site) {
$tmp_row = $row["Name"];
$tmp_row = str_replace($base_prefix, $wpdb->base_prefix, $tmp_row);
if (in_array($tmp_row, $staging_option['database_list'])) {
$checked = '';
}
}
else if (in_array($row["Name"], $staging_option['database_list'])) {
$checked = '';
}
}
if (in_array($row["Name"], $default_table)) {
if ($checked == '') {
$base_table_all_check = false;
}
$has_base_table = true;
$base_table .= '<div class="wpvivid-text-line">
<input type="checkbox" option="base_db" name="Database" value="'.esc_html($row["Name"]).'" '.esc_html($checked).' />
<span class="wpvivid-text-line">'.esc_html($row["Name"]).'|Rows:'.$row["Rows"].'|Size:'.$tables_info[$row["Name"]]["Data_length"].'</span>
</div>';
$base_count++;
} else if(in_array($row['Name'], $woo_table_arr)){
if ($checked == '') {
$woo_table_all_check = false;
}
$has_woo_table = true;
$woo_table .= '<div class="wpvivid-text-line">
<input type="checkbox" option="woo_db" name="Database" value="'.esc_html($row["Name"]).'" '.esc_html($checked).' />
<span class="wpvivid-text-line">'.esc_html($row["Name"]).'|Rows:'.$row["Rows"].'|Size:'.$tables_info[$row["Name"]]["Data_length"].'</span>
</div>';
$woo_count++;
}
else {
if ($checked == '') {
$other_table_all_check = false;
}
$has_other_table = true;
$other_table .= '<div class="wpvivid-text-line">
<input type="checkbox" option="other_db" name="Database" value="'.esc_html($row["Name"]).'" '.esc_html($checked).' />
<span class="wpvivid-text-line">'.esc_html($row["Name"]).'|Rows:'.$row["Rows"].'|Size:'.$tables_info[$row["Name"]]["Data_length"].'</span>
</div>';
$other_count++;
}
}
$ret['html'] = '<div style="padding-left:4em;margin-top:1em;">
<div style="border-bottom:1px solid #eee;"></div>
</div>';
$base_table_html = '';
$woo_table_html = '';
$other_table_html = '';
if ($has_base_table) {
$base_all_check = '';
if ($base_table_all_check) {
$base_all_check = 'checked';
}
$base_table_html .= '<div style="width:30%;float:left;box-sizing:border-box;padding-right:0.5em;padding-left:4em;">
<div>
<p>
<span class="dashicons dashicons-list-view wpvivid-dashicons-blue"></span>
<span><input type="checkbox" class="wpvivid-database-table-check wpvivid-database-base-table-check" '.esc_attr($base_all_check).'></span>
<span><strong>Wordpress Default Tables</strong></span>
</p>
</div>
<div style="height:250px;border:1px solid #eee;padding:0.2em 0.5em;overflow:auto;">
'.$base_table.'
</div>
<div style="clear:both;"></div>
</div>';
}
if ($has_other_table) {
$other_all_check = '';
if ($other_table_all_check) {
$other_all_check = 'checked';
}
if($has_woo_table){
$other_table_width = '40%';
}
else{
$other_table_width = '70%';
}
$other_table_html .= '<div style="width:'.$other_table_width.'; float:left;box-sizing:border-box;padding-left:0.5em;">
<div>
<p>
<span class="dashicons dashicons-list-view wpvivid-dashicons-green"></span>
<span><input type="checkbox" class="wpvivid-database-table-check wpvivid-database-other-table-check" '.esc_attr($other_all_check).'></span>
<span><strong>Other Tables</strong></span>
</p>
</div>
<div style="height:250px;border:1px solid #eee;padding:0.2em 0.5em;overflow-y:auto;">
'.$other_table.'
</div>
</div>';
}
if($has_woo_table) {
$woo_all_check = '';
if ($woo_table_all_check) {
$woo_all_check = 'checked';
}
$woo_table_html .= '<div style="width:30%; float:left;box-sizing:border-box;padding-left:0.5em;">
<div>
<p><span class="dashicons dashicons-list-view wpvivid-dashicons-orange"></span>
<span><input type="checkbox" class="wpvivid-database-table-check wpvivid-database-woo-table-check" '.esc_attr($woo_all_check).'></span>
<span><strong>WooCommerce Tables</strong></span>
</p>
</div>
<div style="height:250px;border:1px solid #eee;padding:0.2em 0.5em;overflow:auto;">
'.$woo_table.'
</div>
</div>';
}
$ret['html'] .= $base_table_html . $other_table_html . $woo_table_html;
$ret['tables_info'] = $tables_info;
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function wpvivid_replace_directory( $path ) {
return preg_replace( '/[\\\\]+/', '/', $path );
}
public function getPath( $path, $wpcontentDir, $directory ) {
$realPath = $this->wpvivid_replace_directory($directory->getRealPath());
if( false === strpos( $realPath, $path ) ) {
return false;
}
$path = str_replace( $wpcontentDir . '/', null, $this->wpvivid_replace_directory($directory->getRealPath()) );
// Using strpos() for symbolic links as they could create nasty stuff in nix stuff for directory structures
if( !$directory->isDir() ||
strlen( $path ) < 1 ||
(strpos( $this->wpvivid_replace_directory($directory->getRealPath()), $wpcontentDir . '/' . 'plugins' ) !== 0 &&
strpos( $this->wpvivid_replace_directory($directory->getRealPath()), $wpcontentDir . '/' . 'themes' ) !== 0 &&
strpos( $this->wpvivid_replace_directory($directory->getRealPath()), $wpcontentDir . '/' . 'uploads' ) !== 0 )
) {
return false;
}
return $path;
}
public function wpvivid_search_staging_theme_directories($wpvivid_staging_themes_dir){
if ( empty( $wpvivid_staging_themes_dir ) ) {
return false;
}
$found_themes = array();
$wpvivid_staging_themes_dir = (array) $wpvivid_staging_themes_dir;
foreach ( $wpvivid_staging_themes_dir as $theme_root ) {
$dirs = @ scandir( $theme_root );
if ( ! $dirs ) {
continue;
}
foreach ( $dirs as $dir ) {
if ( ! is_dir( $theme_root . '/' . $dir ) || $dir[0] == '.' || $dir == 'CVS' ) {
continue;
}
if ( file_exists( $theme_root . '/' . $dir . '/style.css' ) ) {
$found_themes[ $dir ] = array(
'theme_file' => $dir . '/style.css',
'theme_root' => $theme_root,
);
}
else {
$found_theme = false;
$sub_dirs = @ scandir( $theme_root . '/' . $dir );
if ( ! $sub_dirs ) {
continue;
}
foreach ( $sub_dirs as $sub_dir ) {
if ( ! is_dir( $theme_root . '/' . $dir . '/' . $sub_dir ) || $dir[0] == '.' || $dir == 'CVS' ) {
continue;
}
if ( ! file_exists( $theme_root . '/' . $dir . '/' . $sub_dir . '/style.css' ) ) {
continue;
}
$found_themes[ $dir . '/' . $sub_dir ] = array(
'theme_file' => $dir . '/' . $sub_dir . '/style.css',
'theme_root' => $theme_root,
);
$found_theme = true;
}
if ( ! $found_theme ) {
$found_themes[ $dir ] = array(
'theme_file' => $dir . '/style.css',
'theme_root' => $theme_root,
);
}
}
}
}
asort( $found_themes );
return $found_themes;
}
public function get_staging_themes_info($wpvivid_staging_themes_dir){
$themes = array();
$theme_directories = $this->wpvivid_search_staging_theme_directories($wpvivid_staging_themes_dir);
if ( !empty( $theme_directories ) ) {
foreach ( $theme_directories as $theme => $theme_root ) {
$themes[ $theme ] = $theme_root['theme_root'] . '/' . $theme;
$themes[ $theme ] = new WP_Theme( $theme, $theme_root['theme_root'] );
}
}
return $themes;
}
public function get_staging_plugins_info($wpvivid_stating_plugins_dir){
$wp_plugins = array();
$plugin_root = $wpvivid_stating_plugins_dir;
$plugins_dir = @ opendir( $plugin_root );
$plugin_files = array();
if ( $plugins_dir ) {
while ( ( $file = readdir( $plugins_dir ) ) !== false ) {
if ( substr( $file, 0, 1 ) == '.' ) {
continue;
}
if ( is_dir( $plugin_root . '/' . $file ) ) {
$plugins_subdir = @ opendir( $plugin_root . '/' . $file );
if ( $plugins_subdir ) {
while ( ( $subfile = readdir( $plugins_subdir ) ) !== false ) {
if ( substr( $subfile, 0, 1 ) == '.' ) {
continue;
}
if ( substr( $subfile, -4 ) == '.php' ) {
$plugin_files[] = "$file/$subfile";
}
}
closedir( $plugins_subdir );
}
} else {
if ( substr( $file, -4 ) == '.php' ) {
$plugin_files[] = $file;
}
}
}
closedir( $plugins_dir );
}
if ( !empty( $plugin_files ) ) {
foreach ( $plugin_files as $plugin_file ) {
if ( ! is_readable( "$plugin_root/$plugin_file" ) ) {
continue;
}
$plugin_data = get_plugin_data( "$plugin_root/$plugin_file", false, false );
if ( empty( $plugin_data['Name'] ) ) {
continue;
}
$wp_plugins[ plugin_basename( $plugin_file ) ] = $plugin_data;
}
}
return $wp_plugins;
}
public function get_staging_directory_info($path){
$wpcontentDir = $path.DIRECTORY_SEPARATOR.'wp-content';
$wpcontentDir = str_replace('\\', '/', $wpcontentDir);
$tmp_path = str_replace('\\', '/', $path);
if(!file_exists($wpcontentDir)){
//return error
}
else {
$directories = new \DirectoryIterator($wpcontentDir);
}
$wpvivid_staging_themes_dir = '';
$wpvivid_stating_plugins_dir = '';
foreach ( $directories as $directory ) {
if( false === ($path = $this->getPath( $tmp_path, $wpcontentDir, $directory )) ) {
continue;
}
if($directory == 'themes'){
$wpvivid_staging_themes_dir = $wpcontentDir . '/' . 'themes';
}
if($directory == 'plugins'){
$wpvivid_stating_plugins_dir = $wpcontentDir . '/' . 'plugins';
}
}
$ret['themes_list'] = $this->get_staging_themes_info($wpvivid_staging_themes_dir);
$ret['plugins_list'] = $this->get_staging_plugins_info($wpvivid_stating_plugins_dir);
return $ret;
}
public function get_theme_plugin_info($root)
{
$theme_info['size']=$this->get_folder_size($root,0);
return $theme_info;
}
public function get_folder_size($root,$size)
{
$count = 0;
if(is_dir($root))
{
$handler = opendir($root);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..") {
$count++;
if (is_dir($root . DIRECTORY_SEPARATOR . $filename))
{
$size=$this->get_folder_size($root . DIRECTORY_SEPARATOR . $filename,$size);
} else {
$size+=filesize($root . DIRECTORY_SEPARATOR . $filename);
}
}
}
if($handler)
@closedir($handler);
}
}
return $size;
}
public function staging_site()
{
$redirect=false;
if(is_multisite())
{
switch_to_blog(get_main_site_id());
$staging_init=get_option('wpvivid_staging_init', false);
$staging_finish=get_option('wpvivid_staging_finish', false);
restore_current_blog();
}
else
{
$staging_init=get_option('wpvivid_staging_init', false);
$staging_finish=get_option('wpvivid_staging_finish', false);
}
if($staging_finish)
{
delete_transient( 'wp_core_block_css_files' );
if ( function_exists( 'save_mod_rewrite_rules' ) ) {
save_mod_rewrite_rules();
}
else{
if(file_exists(ABSPATH . 'wp-admin/includes/misc.php')) {
require_once ABSPATH . 'wp-admin/includes/misc.php';
}
if ( function_exists( 'save_mod_rewrite_rules' ) ) {
save_mod_rewrite_rules();
}
}
flush_rewrite_rules(true);
delete_option('wpvivid_staging_finish');
if(!$this->check_theme_exist())
{
$redirect=true;
}
}
if($staging_init)
{
global $wp_rewrite;
if($staging_init == 1){
//create staging site
$wp_rewrite->set_permalink_structure( null );
}
else{
//push to live site
$wp_rewrite->set_permalink_structure( $staging_init );
}
delete_option('wpvivid_staging_init');
}
$data=$this->get_staging_site_data();
if($data!==false)
{
$user = wp_get_current_user();
if($user->exists())
{
wp_enqueue_style( "wpvivid-admin-bar", WPVIVID_PLUGIN_DIR_URL . "css/wpvivid-admin-bar.css", array(), WPVIVID_PLUGIN_VERSION );
}
if(!$this->is_login_page())
{
if(is_multisite())
{
switch_to_blog(get_main_site_id());
$options=get_option('wpvivid_staging_options', false);
restore_current_blog();
}
else
{
$options=get_option('wpvivid_staging_options',array());
}
$staging_not_need_login=isset($options['not_need_login']) ? $options['not_need_login'] : true;
if(!$staging_not_need_login)
{
if(!current_user_can('manage_options'))
{
$this->output_login_page();
}
}
}
}
if($redirect)
{
?>
<script>
location.reload();
</script>
<?php
}
}
public function check_theme_exist()
{
global $wp_theme_directories;
$stylesheet = get_stylesheet();
$theme_root = get_raw_theme_root( $stylesheet );
if ( false === $theme_root ) {
$theme_root = WP_CONTENT_DIR . '/themes';
}
elseif ( ! in_array( $theme_root, (array) $wp_theme_directories ) )
{
$theme_root = WP_CONTENT_DIR . $theme_root;
}
$theme_dir = $stylesheet;
// Correct a situation where the theme is 'some-directory/some-theme' but 'some-directory' was passed in as part of the theme root instead.
if ( ! in_array( $theme_root, (array) $wp_theme_directories ) && in_array( dirname( $theme_root ), (array) $wp_theme_directories ) ) {
$stylesheet = basename( $theme_root ) . '/' .$theme_dir;
$theme_root = dirname( $theme_root );
}
$theme_file = $stylesheet . '/style.css';
if( ! file_exists( $theme_root . '/' . $theme_file ) )
{
$themes=wp_get_themes();
foreach ($themes as $theme)
{
switch_theme($theme->get_stylesheet());
return false;
}
}
return true;
}
public function is_login_page()
{
return in_array($GLOBALS['pagenow'], array('wp-login.php', 'wp-register.php'));
}
public function wpvivid_logout_redirect()
{
$redirectTo = get_site_url();
wp_logout();
?>
<script>
location.href='<?php echo esc_url($redirectTo); ?>';
</script>
<?php
}
public function output_login_page()
{
if(is_user_logged_in())
{
if(current_user_can( 'manage_options' ))
{
return false;
}
else
{
$this->wpvivid_logout_redirect();
}
}
if( !isset( $_POST['log'] ) || !isset( $_POST['pwd'] ) )
{
}
else
{
$user_data = get_user_by( 'login', sanitize_user($_POST['log']) );
if( !$user_data )
{
$user_data = get_user_by( 'email', sanitize_email($_POST['log']) );
$log=sanitize_email($_POST['log']);
}
else
{
$log=sanitize_user($_POST['log']);
}
if( $user_data )
{
if( wp_check_password( $_POST['pwd'], $user_data->user_pass, $user_data->ID ) )
{
$rememberme = isset( $_POST['rememberme'] ) ? true : false;
wp_set_auth_cookie( $user_data->ID, $rememberme );
wp_set_current_user( $user_data->ID, $log );
do_action( 'wp_login', $log, get_userdata( $user_data->ID ) );
$redirect_to = get_site_url() . '/wp-admin/';
if( !empty( $_POST['redirect_to'] ) )
{
$url=sanitize_url($_POST['redirect_to']);
$redirectTo = wp_safe_redirect($url);
}
header( 'Location:' . $redirectTo );
}
}
}
require_once( ABSPATH . 'wp-login.php' );
?>
<script>
jQuery(document).ready(function ()
{
jQuery('#loginform').prop('action', '');
});
</script>
<?php
die();
}
public function delete_site()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_POST['id'])) {
$id = sanitize_key($_POST['id']);
} else {
die();
}
$ret = $this->_delete_site($id);
$html = '';
$list = get_option('wpvivid_staging_task_list', array());
if (!empty($list)) {
$display_list = new WPvivid_Staging_List();
$display_list->set_parent('wpvivid_staging_list');
$display_list->set_list($list);
$display_list->prepare_items();
ob_start();
$display_list->display();
$html = ob_get_clean();
}
$ret['html'] = $html;
echo wp_json_encode($ret);
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function wpvivid_get_staging_database_object($use_additional_db, $db_user, $db_pass, $db_name, $db_host){
if($use_additional_db){
return new wpdb($db_user, $db_pass, $db_name, $db_host);
}
else{
global $wpdb;
return $wpdb;
}
}
public function delete_cancel_staging_site(){
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_POST['staging_site_info'])) {
$json = sanitize_text_field($_POST['staging_site_info']);
$json = stripslashes($json);
$staging_site_info = json_decode($json, true);
$site_path = $staging_site_info['staging_path'];
$use_additional_db = $staging_site_info['staging_additional_db'];
$db_user = $staging_site_info['staging_additional_db_user'];
$db_pass = $staging_site_info['staging_additional_db_pass'];
$db_name = $staging_site_info['staging_additional_db_name'];
$db_host = $staging_site_info['staging_additional_db_host'];
if (!empty($site_path)) {
$home_path = untrailingslashit(ABSPATH);
if ($home_path != $site_path) {
if (file_exists($site_path)) {
if (!class_exists('WP_Filesystem_Base')) include_once(ABSPATH . '/wp-admin/includes/class-wp-filesystem-base.php');
if (!class_exists('WP_Filesystem_Direct')) include_once(ABSPATH . '/wp-admin/includes/class-wp-filesystem-direct.php');
$fs = new WP_Filesystem_Direct(false);
$fs->rmdir($site_path, true);
}
}
}
$prefix = $staging_site_info['staging_table_prefix'];
if (!empty($prefix)) {
$db = $this->wpvivid_get_staging_database_object($use_additional_db, $db_user, $db_pass, $db_name, $db_host);
$sql = $db->prepare("SHOW TABLES LIKE %s;", $db->esc_like($prefix) . '%');
$result = $db->get_results($sql, OBJECT_K);
if (!empty($result)) {
foreach ($result as $table_name => $value) {
$table['name'] = $table_name;
$db->query("DROP TABLE IF EXISTS {$table_name}");
}
}
}
$ret['result'] = 'success';
echo wp_json_encode($ret);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function _delete_site($site_id,$unfinished=false)
{
try
{
set_time_limit(900);
$task=new WPvivid_Staging_Task($site_id);
if($unfinished)
{
if($task->is_restore()||$task->is_copy())
{
$ret['result']='success';
return $ret;
}
$site_path=$task->get_path(true);
$prefix=$task->get_db_prefix(true);
$copy_db=new WPvivid_Staging_Copy_DB($site_id);
$db=$copy_db->get_db_instance(true);
}
else
{
$site_path=$task->get_site_path();
$prefix=$task->get_site_prefix();
$db=$task->get_site_db_instance();
}
if(empty($site_path))
{
$ret['result']='success';
$default = array();
$tasks = get_option('wpvivid_staging_task_list', $default);
unset($tasks[$site_id]);
update_option('wpvivid_staging_task_list',$tasks,'no');
return $ret;
}
$home_path=untrailingslashit(ABSPATH);
if($home_path!=$site_path)
{
if (file_exists($site_path))
{
if (!class_exists('WP_Filesystem_Base')) include_once(ABSPATH . '/wp-admin/includes/class-wp-filesystem-base.php');
if (!class_exists('WP_Filesystem_Direct')) include_once(ABSPATH . '/wp-admin/includes/class-wp-filesystem-direct.php');
$fs = new WP_Filesystem_Direct(false);
$fs->rmdir($site_path, true);
}
}
if(empty($prefix)||empty($db))
{
$ret['result']='success';
$default = array();
$tasks = get_option('wpvivid_staging_task_list', $default);
unset($tasks[$site_id]);
update_option('wpvivid_staging_task_list',$tasks,'no');
return $ret;
}
$sql=$db->prepare("SHOW TABLES LIKE %s;", $db->esc_like($prefix) . '%');
$result = $db->get_results($sql, OBJECT_K);
if(!empty($result))
{
$db->query( "SET foreign_key_checks = 0" );
foreach ($result as $table_name=>$value)
{
$table['name']=$table_name;
$db->query( "DROP TABLE IF EXISTS {$table_name}" );
}
$db->query( "SET foreign_key_checks = 1" );
}
$default = array();
$tasks = get_option('wpvivid_staging_task_list', $default);
unset($tasks[$site_id]);
update_option('wpvivid_staging_task_list',$tasks,'no');
$ret['result']='success';
}
catch (Exception $error)
{
$ret['result']='failed';
$ret['error']=$error->getMessage();
}
return $ret;
}
public function check_staging_dir()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$ret['result'] = 'success';
if(!isset($_POST['path']) || empty($_POST['path']) || !is_string($_POST['path']))
{
$ret['result']='failed';
$ret['error']='A site path is required.';
echo wp_json_encode($ret);
die();
}
$path = sanitize_text_field($_POST['path']);
$path = sanitize_file_name($path);
if(!isset($_POST['table_prefix']) || empty($_POST['table_prefix']) || !is_string($_POST['table_prefix']))
{
$ret['result']='failed';
$ret['error']='A table prefix is required.';
echo wp_json_encode($ret);
die();
}
$table_prefix = sanitize_text_field($_POST['table_prefix']);
if (isset($_POST['root_dir']) && $_POST['root_dir'] == 0)
{
$path = untrailingslashit(ABSPATH) . DIRECTORY_SEPARATOR. $path;
}
else if(isset($_POST['root_dir']) && $_POST['root_dir'] == 1)
{
$path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $path;
}
else
{
$ret['result'] = 'failed';
$ret['error'] = 'We are not able to authenticate the staging directory, please contact us.';
echo wp_json_encode($ret);
die();
}
if (file_exists($path))
{
$ret['result'] = 'failed';
$ret['error'] = 'A folder with the same name already exists in website\'s root directory.';
}
else
{
if (mkdir($path, 0755, true))
{
rmdir($path);
} else {
$ret['result'] = 'failed';
$ret['error'] = 'Create directory is not allowed in ' . $path . '.Please check the directory permissions and try again';
}
}
if(isset($_POST['additional_db']))
{
$additional_db_json = sanitize_text_field($_POST['additional_db']);
$additional_db_json = stripslashes($additional_db_json);
$additional_db_options = json_decode($additional_db_json, true);
if($additional_db_options['additional_database_check'] === '1')
{
$db_user = sanitize_text_field($additional_db_options['additional_database_info']['db_user']);
$db_pass = sanitize_text_field($additional_db_options['additional_database_info']['db_pass']);
$db_host = sanitize_text_field($additional_db_options['additional_database_info']['db_host']);
$db_name = sanitize_text_field($additional_db_options['additional_database_info']['db_name']);
$db = new wpdb($db_user, $db_pass, $db_name, $db_host);
$sql = $db->prepare("SHOW TABLES LIKE %s;", $db->esc_like($table_prefix) . '%');
$result = $db->get_results($sql, OBJECT_K);
if (!empty($result))
{
$ret['result'] = 'failed';
$ret['error'] = 'The table prefix already exists.';
}
}
else
{
global $wpdb;
$sql = $wpdb->prepare("SHOW TABLES LIKE %s;", $wpdb->esc_like($table_prefix) . '%');
$result = $wpdb->get_results($sql, OBJECT_K);
if (!empty($result))
{
$ret['result'] = 'failed';
$ret['error'] = 'The table prefix already exists.';
}
}
}
else
{
global $wpdb;
$sql = $wpdb->prepare("SHOW TABLES LIKE %s;", $wpdb->esc_like($table_prefix) . '%');
$result = $wpdb->get_results($sql, OBJECT_K);
if (!empty($result))
{
$ret['result'] = 'failed';
$ret['error'] = 'The table prefix already exists.';
}
}
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function check_filesystem_permissions()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try{
if(!isset($_POST['path']) || empty($_POST['path']) || !is_string($_POST['path']))
{
$ret['result']='failed';
$ret['error']='A site path is required.';
echo wp_json_encode($ret);
die();
}
$path = sanitize_text_field($_POST['path']);
$src_path = untrailingslashit(ABSPATH);
if(isset($_POST['root_dir'])&&$_POST['root_dir']==0)
{
$des_path = untrailingslashit(ABSPATH) . '/' . $path;
}
else if (isset($_POST['root_dir'])&&$_POST['root_dir']==1)
{
$des_path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $path;
}
else
{
$test_dir = 'wpvividstg_testfolder';
$des_path = untrailingslashit($path) . '/' . $test_dir;
}
$mk_res = mkdir($des_path,0755,true);
if (!$mk_res)
{
$ret['result']='failed';
$ret['error']='The directory where the staging site will be installed is not writable. Please set the permissions of the directory to 755 then try it again.';
echo wp_json_encode($ret);
die();
}
$test_file_name = 'wpvividstg_test_file.txt';
$test_file_path = $des_path.DIRECTORY_SEPARATOR.$test_file_name;
$mk_res = fopen($test_file_path, 'wb');
if (!$mk_res)
{
if(file_exists($des_path))
@rmdir($des_path);
$ret['result']='failed';
$ret['error']='The directory where the staging site will be installed is not writable. Please set the permissions of the directory to 755 then try it again.';
echo wp_json_encode($ret);
die();
}
fclose($mk_res);
@wp_delete_file($test_file_path);
if(file_exists($des_path))
@rmdir($des_path);
$ret['result'] = 'success';
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function get_recent_post()
{
//set_prefix
$post_type='post';
$args = array(
'orderby' => 'modified',
'ignore_sticky_posts' => '1',
'page_id' => 0,
'posts_per_page' => 1,
'post_type' => $post_type
);
$loop = new WP_Query( $args );
echo '<ul>';
while( $loop->have_posts())
{
$loop->the_post();
echo '<li><a href="' . esc_url(get_permalink( $loop->post->ID )) . '"> ' .esc_html(get_the_title( $loop->post->ID ) ). '</a> ( '. esc_url(get_the_modified_date()) .') </li>';
}
echo '</ul>';
echo'<input id="wpvivid_update_post" type="button" class="button button-primary" value="Update">';
}
public function get_staging_progress()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$task_id=get_option('wpvivid_current_running_staging_task','');
if(empty($task_id))
{
$list = get_option('wpvivid_staging_task_list',array());
if(!empty($list))
{
foreach ($list as $key => $value)
{
if($value['status']['str'] === 'running' || $value['status']['str'] === 'ready')
{
$task_id = $value['id'];
update_option('wpvivid_current_running_staging_task', $task_id, 'no');
break;
}
}
}
if(empty($task_id))
{
$ret['result']='success';
$ret['log']='';
$ret['continue']=0;
echo wp_json_encode($ret);
die();
}
}
try
{
$task=new WPvivid_Staging_Task($task_id);
$b_delete=false;
if($task->get_status()=='completed')
{
if($task->is_restore()){
$ret['completed_msg'] = 'Pushing the staging site to the live site completed successfully.';
}
else{
$ret['completed_msg'] = 'Updating the staging site completed successfully.';
$db_connect = $task->get_db_connect();
$url = $db_connect['new_site_url'];
$options=array();
$options['timeout']=30;
$response = wp_remote_request( $url,$options);
if(!is_wp_error($response) && ($response['response']['code'] == 200))
{
$this->log->OpenLogFile($task->get_log_file_name());
$this->log->WriteLog('Access staging site successfully.', 'notice');
}
else
{
$this->log->OpenLogFile($task->get_log_file_name());
$this->log->WriteLog('Access staging site failed.', 'notice');
}
}
update_option('wpvivid_current_running_staging_task','','no');
$ret['continue']=0;
$ret['completed']=1;
}
else if($task->get_status()=='ready')
{
$ret['continue']=1;
$ret['need_restart']=1;
}
else if($task->get_status()=='error')
{
update_option('wpvivid_current_running_staging_task','','no');
$ret['continue']=0;
$ret['error']=1;
$ret['error_msg']=$task->get_error();
$b_delete=true;
}
else if($task->get_status()=='cancel')
{
update_option('wpvivid_current_running_staging_task','','no');
$ret['continue']=0;
$ret['need_restart']=0;
$ret['is_cancel']=1;
foreach ($task as $value){
$ret['staging_path']=$value['path']['des_path'];
if($value['db_connect']['des_use_additional_db']){
$ret['staging_additional_db']=1;
$ret['staging_additional_db_user']=$value['db_connect']['des_dbuser'];
$ret['staging_additional_db_pass']=$value['db_connect']['des_dbpassword'];
$ret['staging_additional_db_host']=$value['db_connect']['des_dbhost'];
$ret['staging_additional_db_name']=$value['db_connect']['des_dbname'];
$ret['staging_table_prefix']=$value['db_connect']['new_prefix'];
}
else{
$ret['staging_additional_db']=0;
$ret['staging_additional_db_user']=null;
$ret['staging_additional_db_pass']=null;
$ret['staging_additional_db_host']=null;
$ret['staging_additional_db_name']=null;
$ret['staging_table_prefix']=$value['db_connect']['new_prefix'];
}
}
update_option('wpvivid_staging_task_cancel', false, 'no');
$b_delete=true;
}
else
{
if($task->check_timeout())
{
if($task->get_status()=='ready')
{
$ret['continue']=1;
$ret['need_restart']=1;
}
else
{
update_option('wpvivid_current_running_staging_task','','no');
$ret['continue']=0;
$b_delete=true;
}
}
else
{
$ret['continue']=1;
$ret['need_restart']=0;
}
}
$staging_percent = $task->get_progress();
$file_name=$this->log->GetSaveLogFolder(). $task->get_log_file_name().'_log.txt';
$file =fopen($file_name,'r');
$buffer='';
if(!$file)
{
$buffer='open log file failed';
}
else
{
if(filesize($file_name)<=1*1024*1024)
{
while(!feof($file))
{
$buffer .= fread($file,1024);
}
}
else
{
$pos=-2;
$eof='';
$n=50;
$buffer_array = array();
while($n>0)
{
while($eof!=="\n")
{
if(!fseek($file, $pos, SEEK_END))
{
$eof=fgetc($file);
$pos--;
}
else
{
break;
}
}
$buffer_array[].=fgets($file);
$eof='';
$n--;
}
if(!empty($buffer_array))
{
$buffer_array = array_reverse($buffer_array);
foreach($buffer_array as $value)
{
$buffer.=$value;
}
}
}
fclose($file);
}
if($b_delete)
{
$this->_delete_site($task_id,true);
}
$ret['log']=$buffer;
$ret['percent']=$staging_percent;
$ret['result']='success';
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$ret['result']='failed';
$ret['error']=$error->getMessage();
echo wp_json_encode($ret);
}
die();
}
public function cancel_staging()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$task_id=get_option('wpvivid_current_running_staging_task','');
if(empty($task_id))
{
$ret['result']='success';
$ret['log']='';
$ret['continue']=0;
echo wp_json_encode($ret);
die();
}
try
{
$task=new WPvivid_Staging_Task($task_id);
$task->cancel_staging();
$ret['result']='success';
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$ret['result']='failed';
$ret['error']=$error->getMessage();
echo wp_json_encode($ret);
}
die();
}
public function test_additional_database_connect(){
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_POST['database_info']) && !empty($_POST['database_info']) && is_string($_POST['database_info'])) {
$data = sanitize_text_field($_POST['database_info']);
$data = stripslashes($data);
$json = json_decode($data, true);
$db_user = sanitize_text_field($json['db_user']);
$db_pass = sanitize_text_field($json['db_pass']);
$db_host = sanitize_text_field($json['db_host']);
$db_name = sanitize_text_field($json['db_name']);
$db = new wpdb($db_user, $db_pass, $db_name, $db_host);
// Can not connect to mysql
if (!empty($db->error->errors['db_connect_fail']['0'])) {
$ret['result'] = 'failed';
$ret['error'] = 'Failed to connect to MySQL server. Please try again later.';
echo wp_json_encode($ret);
die();
}
// Can not connect to database
$db->select($db_name);
if (!$db->ready) {
$ret['result'] = 'failed';
$ret['error'] = 'Unable to connect to MySQL database. Please try again later.';
echo wp_json_encode($ret);
die();
}
$ret['result'] = 'success';
echo wp_json_encode($ret);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function update_staging_exclude_extension(){
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (isset($_POST['type']) && !empty($_POST['type']) && is_string($_POST['type']) &&
isset($_POST['exclude_content']) && !empty($_POST['exclude_content']) && is_string($_POST['exclude_content'])) {
$type = sanitize_text_field($_POST['type']);
$value = sanitize_text_field($_POST['exclude_content']);
$staging_option = self::wpvivid_get_staging_history();
if (empty($staging_option)) {
$staging_option = array();
}
if ($type === 'upload') {
$staging_option['upload_extension'] = array();
$str_tmp = explode(',', $value);
for ($index = 0; $index < count($str_tmp); $index++) {
if (!empty($str_tmp[$index])) {
$staging_option['upload_extension'][] = $str_tmp[$index];
}
}
} else if ($type === 'content') {
$staging_option['content_extension'] = array();
$str_tmp = explode(',', $value);
for ($index = 0; $index < count($str_tmp); $index++) {
if (!empty($str_tmp[$index])) {
$staging_option['content_extension'][] = $str_tmp[$index];
}
}
} else if ($type === 'additional_file') {
$staging_option['additional_file_extension'] = array();
$str_tmp = explode(',', $value);
for ($index = 0; $index < count($str_tmp); $index++) {
if (!empty($str_tmp[$index])) {
$staging_option['additional_file_extension'][] = $str_tmp[$index];
}
}
}
self::wpvivid_set_staging_history($staging_option);
$ret['result'] = 'success';
echo wp_json_encode($ret);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function deal_shutdown_error($task_id)
{
if($this->end_shutdown_function===false)
{
$task=false;
$last_error = error_get_last();
if (!empty($last_error) && !in_array($last_error['type'], array(E_NOTICE,E_WARNING,E_USER_NOTICE,E_USER_WARNING,E_DEPRECATED), true))
{
$error = $last_error;
} else {
$error = false;
}
try
{
$task=new WPvivid_Staging_Task($task_id);
if($error==false)
{
$message='Create staging site end with a error.';
}
else
{
$message=$error;
}
$task->finished_task_with_error($message);
$this->log->WriteLog($message,'error');
}
catch (Exception $error)
{
$message = 'An Error has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
error_log($message);
if($task!==false)
$task->finished_task_with_error($message);
$this->log->WriteLog($message,'error');
}
die();
}
}
public function start_staging()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$this->end_shutdown_function=false;
register_shutdown_function(array($this,'deal_staging_shutdown_error'));
$task=false;
try
{
$task_id=get_option('wpvivid_current_running_staging_task','');
if(!empty($task_id))
{
$task=new WPvivid_Staging_Task($task_id);
if($task->get_status()==='running')
{
$this->end_shutdown_function=true;
die();
}
$this->log->OpenLogFile($task->get_log_file_name());
}
else
{
if(isset($_POST['path']) && isset($_POST['table_prefix']) && isset($_POST['custom_dir']) && isset($_POST['additional_db']))
{
$json = sanitize_text_field($_POST['custom_dir']);
$json = stripslashes($json);
$staging_options = json_decode($json, true);
$additional_db_json = sanitize_text_field($_POST['additional_db']);
$additional_db_json = stripslashes($additional_db_json);
$additional_db_options = json_decode($additional_db_json, true);
$option['options'] = $this->set_staging_option();
$src_path = untrailingslashit(ABSPATH);
$path = sanitize_text_field($_POST['path']);
if(isset($_POST['root_dir'])&&$_POST['root_dir']==0)
{
$url_path=$path;
$new_site_url = untrailingslashit($this->get_database_site_url()). '/' . $url_path;
$new_home_url = untrailingslashit($this->get_database_home_url()). '/' . $url_path;
$des_path = untrailingslashit(ABSPATH) . '/' . $path;
}
else
{
$url_path=str_replace(ABSPATH,'',WP_CONTENT_DIR).'/' . $path;
$new_site_url = untrailingslashit($this->get_database_site_url()). '/' . $url_path;
$new_home_url = untrailingslashit($this->get_database_home_url()). '/' . $url_path;
$des_path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $path;
}
$option['data']['path']['src_path'] = $src_path;
$option['data']['path']['des_path'] = $des_path;
$table_prefix = sanitize_text_field($_POST['table_prefix']);
$option['data']['restore'] = false;
$option['data']['copy']=false;
$this->set_create_staging_option($option,$staging_options,$additional_db_options,$new_site_url,$new_home_url,$table_prefix);
$task = new WPvivid_Staging_Task();
$task->setup_task($option);
$task->set_memory_limit();
$task->update_action_time('create_time');
$this->log->CreateLogFile($task->get_log_file_name(), 'no_folder', 'staging');
$this->log->WriteLog('Start creating staging site.', 'notice');
$this->log->WriteLogHander();
}
}
$task_id=$task->get_id();
update_option('wpvivid_current_running_staging_task',$task_id,'no');
register_shutdown_function(array($this,'deal_shutdown_error'),$task_id);
$doing=$task->get_doing_task();
if($doing===false)
{
$doing=$task->get_start_next_task();
}
$task->set_time_limit();
if(!$task->do_task($doing))
{
$task->finished_task_with_error();
$this->end_shutdown_function=true;
die();
}
$doing=$task->get_start_next_task();
if($doing==false)
{
$this->log->WriteLog('Creating staging site is completed.','notice');
$task->finished_task();
}
}
catch (Exception $error)
{
$message = 'An Error has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
error_log($message);
if($task!==false)
$task->finished_task_with_error($message);
$this->log->WriteLog($message,'error');
}
$this->end_shutdown_function=true;
die();
}
public function set_restart_staging_id()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if(isset($_POST['id']))
{
$task_id = sanitize_key($_POST['id']);
update_option('wpvivid_current_running_staging_task', $task_id, 'no');
$ret['result'] = 'success';
echo wp_json_encode($ret);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function set_db_connect_option($new_site_url,$new_home_url,$additional_db_options,$table_prefix,$mu_single_site_id='')
{
global $wpdb;
if(!empty($mu_single_site_id))
{
$prefix=$wpdb->get_blog_prefix($mu_single_site_id);
$db_connect['old_prefix'] = $prefix;
$db_connect['old_site_url'] = get_site_url($mu_single_site_id);
$db_connect['old_home_url'] = get_home_url($mu_single_site_id);
}
else
{
$db_connect['old_prefix'] = $wpdb->base_prefix;
$db_connect['old_site_url'] = untrailingslashit($this->get_database_site_url());
$db_connect['old_home_url'] = untrailingslashit($this->get_database_home_url());
}
$db_connect['new_site_url'] = $new_site_url;
$db_connect['new_home_url'] = $new_home_url;
$db_connect['src_use_additional_db'] = false;
$db_connect['des_use_additional_db'] = false;
$db_connect['new_prefix'] = $table_prefix;
if(isset($additional_db_options['additional_database_check']) && $additional_db_options['additional_database_check'] == '1')
{
/*$option['data']['db_connect']['des_use_additional_db'] = true;
$option['data']['db_connect']['des_dbuser'] = $additional_db_options['additional_database_info']['db_user'];
$option['data']['db_connect']['des_dbpassword'] = $additional_db_options['additional_database_info']['db_pass'];
$option['data']['db_connect']['des_dbname'] = $additional_db_options['additional_database_info']['db_name'];
$option['data']['db_connect']['des_dbhost'] = $additional_db_options['additional_database_info']['db_host'];*/
$db_connect['des_use_additional_db'] = true;
$db_connect['des_dbuser'] = $additional_db_options['additional_database_info']['db_user'];
$db_connect['des_dbpassword'] = $additional_db_options['additional_database_info']['db_pass'];
$db_connect['des_dbname'] = $additional_db_options['additional_database_info']['db_name'];
$db_connect['des_dbhost'] = $additional_db_options['additional_database_info']['db_host'];
}
return $db_connect;
}
public function set_create_staging_option(&$option,$staging_options,$additional_db_options,$new_site_url,$new_home_url,$table_prefix)
{
global $wpdb;
if(isset($_POST['create_new_wp']))
{
$option['data']['core'] = true;
if($staging_options['themes_check'] == '1')
{
$option['data']['theme']['exclude_regex'] = array();
foreach ($staging_options['themes_list'] as $theme)
{
$option['data']['theme']['exclude_regex'][] = '#^'.preg_quote($this -> transfer_path(get_theme_root().DIRECTORY_SEPARATOR.$theme), '/').'$#';
}
}
if($staging_options['plugins_check'] == '1')
{
$option['data']['plugins']['exclude_regex'] = array();
foreach ($staging_options['plugins_list'] as $plugin)
{
$option['data']['plugins']['exclude_regex'][] = '#^'.preg_quote($this -> transfer_path(WP_PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugin), '/').'#';
}
}
$option['data']['db_connect']=$this->set_db_connect_option($new_site_url,$new_home_url,$additional_db_options,$table_prefix);
$option['data']['create_new_wp']=true;
//$option['data']['db']['exclude_tables'] = array();
//$option['data']['db']['exclude_tables'][] = $wpdb->base_prefix.'hw_blocks';
//foreach ($staging_options['database_list'] as $table)
//{
// $option['data']['db']['exclude_tables'][] = $table;
//}
}
else
{
if($staging_options['database_check'] == '1')
{
$option['data']['db_connect']=$this->set_db_connect_option($new_site_url,$new_home_url,$additional_db_options,$table_prefix);
$option['data']['db']['exclude_tables'] = array();
$option['data']['db']['exclude_tables'][] = $wpdb->base_prefix.'hw_blocks';
foreach ($staging_options['database_list'] as $table)
{
$option['data']['db']['exclude_tables'][] = $table;
}
}
$option['data']['theme']['exclude_regex'] = array();
if($staging_options['themes_check'] == '1')
{
foreach ($staging_options['themes_list'] as $key => $value)
{
$option['data']['theme']['exclude_regex'][] = '#^'.preg_quote($this -> transfer_path(get_theme_root().DIRECTORY_SEPARATOR.$key), '/').'#';
}
$option['data']['theme']['exclude_files_regex']=array();
$theme_extension_tmp = array();
if(isset($staging_options['themes_extension']) && !empty($staging_options['themes_extension']))
{
$str_tmp = explode(',', $staging_options['themes_extension']);
for($index=0; $index<count($str_tmp); $index++)
{
if(!empty($str_tmp[$index]))
{
$option['data']['theme']['exclude_files_regex'][] = '#' . '.*\.' . $str_tmp[$index] . '$' . '#';
$theme_extension_tmp[] = $str_tmp[$index];
}
}
$staging_options['themes_extension'] = $theme_extension_tmp;
}
}
$option['data']['plugins']['exclude_regex'] = array();
if($staging_options['plugins_check'] == '1')
{
foreach ($staging_options['plugins_list'] as $key => $value)
{
$option['data']['plugins']['exclude_regex'][] = '#^'.preg_quote($this -> transfer_path(WP_PLUGIN_DIR.DIRECTORY_SEPARATOR.$key), '/').'#';
}
$option['data']['plugins']['exclude_files_regex']=array();
$plugin_extension_tmp = array();
if(isset($staging_options['plugins_extension']) && !empty($staging_options['plugins_extension']))
{
$str_tmp = explode(',', $staging_options['plugins_extension']);
for($index=0; $index<count($str_tmp); $index++)
{
if(!empty($str_tmp[$index]))
{
$option['data']['plugins']['exclude_files_regex'][] = '#' . '.*\.' . $str_tmp[$index] . '$' . '#';
$plugin_extension_tmp[] = $str_tmp[$index];
}
}
$staging_options['plugins_extension'] = $plugin_extension_tmp;
}
}
if($staging_options['uploads_check'] == '1')
{
$upload_dir = wp_upload_dir();
$option['data']['upload']['exclude_regex'] = array();
foreach ($staging_options['uploads_list'] as $key => $value)
{
$option['data']['upload']['exclude_regex'][] = '#^'.preg_quote($this -> transfer_path($upload_dir['basedir'].DIRECTORY_SEPARATOR.$key), '/').'#';
}
$option['data']['upload']['exclude_files_regex']=array();
$upload_extension_tmp = array();
if(isset($staging_options['upload_extension']) && !empty($staging_options['upload_extension']))
{
$str_tmp = explode(',', $staging_options['upload_extension']);
for($index=0; $index<count($str_tmp); $index++)
{
if(!empty($str_tmp[$index]))
{
$option['data']['upload']['exclude_files_regex'][] = '#' . '.*\.' . $str_tmp[$index] . '$' . '#';
$upload_extension_tmp[] = $str_tmp[$index];
}
}
$staging_options['upload_extension'] = $upload_extension_tmp;
}
}
if($staging_options['content_check'] == '1')
{
$option['data']['wp-content']['exclude_regex'] = array();
foreach ($staging_options['content_list'] as $key => $value)
{
$option['data']['wp-content']['exclude_regex'][] = '#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$key), '/').'#';
}
$option['data']['wp-content']['exclude_files_regex']=array();
$content_extension_tmp = array();
if(isset($staging_options['content_extension']) && !empty($staging_options['content_extension']))
{
$str_tmp = explode(',', $staging_options['content_extension']);
for($index=0; $index<count($str_tmp); $index++)
{
if(!empty($str_tmp[$index]))
{
$option['data']['wp-content']['exclude_files_regex'][] = '#' . '.*\.' . $str_tmp[$index] . '$' . '#';
$content_extension_tmp[] = $str_tmp[$index];
}
}
$staging_options['content_extension'] = $content_extension_tmp;
}
}
if($staging_options['core_check'] == '1')
{
$option['data']['core'] = true;
}
if($staging_options['additional_file_check'] == '1')
{
$custom['exclude_regex'] = array();
$custom['exclude_files_regex']=array();
$additional_file_extension_tmp = array();
if(isset($staging_options['additional_file_extension']) && !empty($staging_options['additional_file_extension']))
{
$str_tmp = explode(',', $staging_options['additional_file_extension']);
for($index=0; $index<count($str_tmp); $index++)
{
if(!empty($str_tmp[$index]))
{
$custom['exclude_files_regex'][] = '#' . '.*\.' . $str_tmp[$index] . '$' . '#';
$additional_file_extension_tmp[] = $str_tmp[$index];
}
}
$staging_options['additional_file_extension'] = $additional_file_extension_tmp;
}
foreach ($staging_options['additional_file_list'] as $key => $value)
{
$custom['root'] = $key;
$option['data']['custom'][] = $custom;
}
}
self::wpvivid_set_staging_history($staging_options);
}
}
public function get_table_list($prefix,&$mu_exclude_table,$task=false,$exculude_user=true)
{
global $wpdb;
if($task===false)
{
$db=$wpdb;
}
else
{
$db=$task->get_site_db_instance();
}
$sql=$db->prepare("SHOW TABLES LIKE %s;", $wpdb->esc_like($prefix) . '%');
$result = $db->get_results($sql, OBJECT_K);
foreach ($result as $table_name=>$value)
{
if($prefix==$db->base_prefix)
{
if ( 1 == preg_match('/^' . $db->base_prefix . '\d+_/', $table_name) )
{
}
else
{
if($table_name==$db->base_prefix.'blogs'&&$exculude_user!==false)
continue;
if($exculude_user===false)
{
if($table_name==$db->base_prefix.'users'||$table_name==$db->base_prefix.'usermeta')
continue;
}
$mu_exclude_table[]=$table_name;
}
}
else
{
$mu_exclude_table[]=$table_name;
}
}
}
public function get_upload_exclude_folder($site_id,$des=false,$task=false)
{
if($des)
{
$upload_dir = wp_upload_dir();
$dir = str_replace( ABSPATH, '', $upload_dir['basedir'] );
$src_path=$task->get_site_path();
$upload_basedir=$src_path.DIRECTORY_SEPARATOR.$dir;
if ( defined( 'MULTISITE' ) )
{
$upload_basedir = $upload_basedir.'/sites/' . $site_id;
} else {
$upload_basedir = $upload_basedir.'/' . $site_id;
}
return $upload_basedir;
}
else
{
$upload= $this->get_site_upload_dir($site_id);
return $upload['basedir'];
}
}
public function get_site_upload_dir($site_id, $time = null, $create_dir = true, $refresh_cache = false)
{
static $cache = array(), $tested_paths = array();
$key = sprintf( '%d-%s',$site_id, (string) $time );
if ( $refresh_cache || empty( $cache[ $key ] ) ) {
$cache[ $key ] = $this->_wp_upload_dir( $site_id,$time );
}
/**
* Filters the uploads directory data.
*
* @since 2.0.0
*
* @param array $uploads Array of upload directory data with keys of 'path',
* 'url', 'subdir, 'basedir', and 'error'.
*/
$uploads = apply_filters( 'upload_dir', $cache[ $key ] );
if ( $create_dir ) {
$path = $uploads['path'];
if ( array_key_exists( $path, $tested_paths ) ) {
$uploads['error'] = $tested_paths[ $path ];
} else {
if ( ! wp_mkdir_p( $path ) ) {
if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
$error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
} else {
$error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
}
$uploads['error'] = sprintf(
/* translators: %s: directory path */
__( 'Unable to create directory %s. Is its parent directory writable by the server?', 'wpvivid-backuprestore' ),
esc_html( $error_path )
);
}
$tested_paths[ $path ] = $uploads['error'];
}
}
return $uploads;
}
public function _wp_upload_dir($site_id, $time = null ) {
$siteurl = get_option( 'siteurl' );
$upload_path = trim( get_option( 'upload_path' ) );
if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
$dir = WP_CONTENT_DIR . '/uploads';
} elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
// $dir is absolute, $upload_path is (maybe) relative to ABSPATH
$dir = path_join( ABSPATH, $upload_path );
} else {
$dir = $upload_path;
}
if ( ! $url = get_option( 'upload_url_path' ) ) {
if ( empty( $upload_path ) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) ) {
$url = WP_CONTENT_URL . '/uploads';
} else {
$url = trailingslashit( $siteurl ) . $upload_path;
}
}
/*
* Honor the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
* We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
*/
if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
$dir = ABSPATH . UPLOADS;
$url = trailingslashit( $siteurl ) . UPLOADS;
}
// If multisite (and if not the main site in a post-MU network)
if ( is_multisite() && ! ( is_main_network() && is_main_site($site_id) && defined( 'MULTISITE' ) ) ) {
if ( ! get_site_option( 'ms_files_rewriting' ) ) {
/*
* If ms-files rewriting is disabled (networks created post-3.5), it is fairly
* straightforward: Append sites/%d if we're not on the main site (for post-MU
* networks). (The extra directory prevents a four-digit ID from conflicting with
* a year-based directory for the main site. But if a MU-era network has disabled
* ms-files rewriting manually, they don't need the extra directory, as they never
* had wp-content/uploads for the main site.)
*/
if ( defined( 'MULTISITE' ) ) {
$ms_dir = '/sites/' . $site_id;
} else {
$ms_dir = '/' . $site_id;
}
$dir .= $ms_dir;
$url .= $ms_dir;
} elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
/*
* Handle the old-form ms-files.php rewriting if the network still has that enabled.
* When ms-files rewriting is enabled, then we only listen to UPLOADS when:
* 1) We are not on the main site in a post-MU network, as wp-content/uploads is used
* there, and
* 2) We are not switched, as ms_upload_constants() hardcodes these constants to reflect
* the original blog ID.
*
* Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
* (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
* as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
* rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
*/
if ( defined( 'BLOGUPLOADDIR' ) ) {
$dir = untrailingslashit( BLOGUPLOADDIR );
} else {
$dir = ABSPATH . UPLOADS;
}
$url = trailingslashit( $siteurl ) . 'files';
}
}
$basedir = $dir;
$baseurl = $url;
$subdir = '';
if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
// Generate the yearly and monthly dirs
if ( ! $time ) {
$time = current_time( 'mysql' );
}
$y = substr( $time, 0, 4 );
$m = substr( $time, 5, 2 );
$subdir = "/$y/$m";
}
$dir .= $subdir;
$url .= $subdir;
return array(
'path' => $dir,
'url' => $url,
'subdir' => $subdir,
'basedir' => $basedir,
'baseurl' => $baseurl,
'error' => false,
);
}
public function deal_staging_shutdown_error()
{
if($this->end_shutdown_function===false)
{
$last_error = error_get_last();
if (!empty($last_error) && !in_array($last_error['type'], array(E_NOTICE,E_WARNING,E_USER_NOTICE,E_USER_WARNING,E_DEPRECATED), true))
{
$error = $last_error;
} else {
$error = false;
}
if ($error === false)
{
$error = 'Task interrupted. Please hold on. We are starting a retry.';
} else {
$error = 'type: '. $error['type'] . ', ' . $error['message'] . ' file:' . $error['file'] . ' line:' . $error['line'];
error_log($error);
}
$this->log->WriteLog($error,'error');
$list = get_option('wpvivid_staging_task_list',array());
if(!empty($list))
{
foreach ($list as $key => $value)
{
if($value['status']['str'] === 'running')
{
$list[$key]['status']['str']='ready';
update_option('wpvivid_staging_task_list', $list, 'no');
break;
}
}
}
die();
}
}
public static function wpvivid_set_staging_history($option){
update_option('wpvivid_staging_history', $option, 'no');
}
public static function wpvivid_get_staging_history(){
$options = get_option('wpvivid_staging_history', array());
return $options;
}
public static function wpvivid_get_push_staging_history(){
$options = get_option('wpvivid_push_staging_history', array());
return $options;
}
private function transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode(DIRECTORY_SEPARATOR,$values);
}
public function set_staging_option()
{
$options=get_option('wpvivid_staging_options');
if(isset($options['staging_db_insert_count']))
$option['staging_db_insert_count']=$options['staging_db_insert_count'];
else
$option['staging_db_insert_count']=10000;
if(isset($options['staging_db_replace_count']))
$option['staging_db_replace_count']=$options['staging_db_replace_count'];
else
$option['staging_db_replace_count']=5000;
if(isset($options['staging_memory_limit']))
$option['staging_memory_limit']=$options['staging_memory_limit'];
else
$option['staging_memory_limit']='256M';
if(isset($options['staging_file_copy_count']))
$option['staging_file_copy_count']=$options['staging_file_copy_count'];
else
$option['staging_file_copy_count']=500;
if(isset($options['staging_exclude_file_size'])) {
$option['staging_exclude_file_size'] = $options['staging_exclude_file_size'];
}
else {
$option['staging_exclude_file_size'] = 30;
}
if(isset($options['staging_max_execution_time']))
$option['staging_max_execution_time']=$options['staging_max_execution_time'];
else
$option['staging_max_execution_time']=900;
if(isset($options['staging_resume_count']))
$option['staging_resume_count']=$options['staging_resume_count'];
else
$option['staging_resume_count']=6;
if(isset($options['staging_overwrite_permalink']))
$option['staging_overwrite_permalink']=$options['staging_overwrite_permalink'];
else
$option['staging_overwrite_permalink']=1;
return $option;
}
public function export_setting_addon($json)
{
$default = array();
$wpvivid_staging_history = get_option('wpvivid_staging_history', $default);
$wpvivid_push_staging_history = get_option('wpvivid_push_staging_history', $default);
$json['data']['wpvivid_staging_history'] = $wpvivid_staging_history;
$json['data']['wpvivid_push_staging_history'] = $wpvivid_push_staging_history;
return $json;
}
} includes/staging/class-wpvivid-staging-task-ex.php 0000644 00000111056 15132770567 0016337 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Staging_Task
{
public $task;
public function __construct($task_id=false)
{
if($task_id===false)
{
$this->create_new_task();
}
else
{
$default = array();
$tasks = get_option('wpvivid_staging_task_list', $default);
if(isset($tasks[$task_id]))
{
$this->task=$tasks[$task_id];
}
else
{
$error = 'Staging task not found.';
throw new Exception(esc_html($error));
}
}
}
public function get_id()
{
return $this->task['id'];
}
public function create_new_task()
{
$task_id=uniqid('wpvivid-');
$task['id']=$task_id;
$task['status']['start_time']=time();
$task['status']['run_time']=time();
$task['status']['timeout']=time();
$task['status']['str']='ready';
$task['status']['resume_count']=0;
$task['job']=array();
$task['doing']=false;
$task['timeout_limit']=900;
$task['log_file_name']=$task_id.'_staging';
$log=new WPvivid_Staging_Log_Free();
$log->CreateLogFile($task['log_file_name'],'no_folder','staging');
$log->CloseFile();
$this->task=$task;
$this->update_task();
}
public function get_log_file_name()
{
return $this->task['log_file_name'];
}
public function set_time_limit()
{
$this->get_task();
$this->task['status']['timeout']=time();
if(isset($this->task['options']['staging_max_execution_time'])) {
$this->task['timeout_limit'] = $this->task['options']['staging_max_execution_time'];
}
else{
$this->task['timeout_limit'] = 900;
}
set_time_limit($this->task['timeout_limit']);
$this->update_task();
}
public function update_task($task=false)
{
$default = array();
$tasks = get_option('wpvivid_staging_task_list', $default);
if($task===false)
{
$this->task['status']['run_time']=time();
$tasks[$this->task['id']]=$this->task;
}
else
{
$this->task=$task;
$this->task['status']['run_time']=time();
$tasks[$this->task['id']]=$this->task;
}
update_option('wpvivid_staging_task_list',$tasks,'no');
}
public function get_task()
{
$default = array();
$tasks = get_option('wpvivid_staging_task_list', $default);
$this->task=$tasks[$this->task['id']];
return $this->task;
}
public function get_mu_option()
{
if(isset($this->task['mu']))
{
return $this->task['mu'];
}
else
{
return false;
}
}
public function setup_task($option)
{
global $wpvivid_plugin;
$this->task['options']=$option['options'];
if($option['data']['restore'])
{
$this->task['options']['restore']=true;
$this->task['path']['src_path']=$this->task['site']['path'];
$this->task['path']['des_path']=untrailingslashit(ABSPATH);
global $wpdb;
$this->task['db_connect']['old_prefix']=$this->task['site']['prefix'];
if($this->get_site_mu_single())
{
$this->task['db_connect']['new_prefix']=$wpdb->get_blog_prefix($this->get_site_mu_single_site_id());
}
else
{
$this->task['db_connect']['new_prefix']=$wpdb->base_prefix;
}
$this->task['db_connect']['temp_prefix']=$wpdb->base_prefix.'temp_';
$this->task['db_connect']['old_site_url']=$this->task['site']['site_url'];
$this->task['db_connect']['old_home_url']=$this->task['site']['home_url'];
if($this->get_site_mu_single())
{
$this->task['db_connect']['new_site_url']=get_site_url($this->get_site_mu_single_site_id());
$this->task['db_connect']['new_home_url']=get_home_url($this->get_site_mu_single_site_id());
}
else
{
$this->task['db_connect']['new_site_url']=untrailingslashit($wpvivid_plugin->staging->get_database_site_url());
$this->task['db_connect']['new_home_url']=untrailingslashit($wpvivid_plugin->staging->get_database_home_url());
}
$this->task['db_connect']['src_use_additional_db']=$this->task['site']['db_connect']['use_additional_db'];
if($this->task['db_connect']['src_use_additional_db'])
{
$this->task['db_connect']['src_dbuser']= $this->task['site']['db_connect']['dbuser'];
$this->task['db_connect']['src_dbpassword']= $this->task['site']['db_connect']['dbpassword'];
$this->task['db_connect']['src_dbname']=$this->task['site']['db_connect']['dbname'];
$this->task['db_connect']['src_dbhost']=$this->task['site']['db_connect']['dbhost'];
}
$this->task['db_connect']['des_use_additional_db']=false;
$this->task['permalink_structure'] = get_option( 'permalink_structure','');
if(isset($option['data']['mu']))
{
$this->task['mu']= $option['data']['mu'];
}
}
else
{
$this->task['options']['restore']=false;
if(isset($option['data']['copy'])&&$option['data']['copy'])
{
$this->task['options']['copy']=true;
$this->task['path']['src_path']=untrailingslashit(ABSPATH);
$this->task['path']['des_path']=$this->task['site']['path'];
global $wpdb;
if($this->get_site_mu_single())
{
$prefix=$wpdb->get_blog_prefix($this->get_site_mu_single_site_id());
}
else
{
$prefix=$wpdb->base_prefix;
}
$this->task['db_connect']['old_prefix']=$prefix;
$this->task['db_connect']['new_prefix']=$this->task['site']['prefix'];
if($this->get_site_mu_single())
{
$this->task['db_connect']['old_site_url'] = get_site_url($this->get_site_mu_single_site_id());
$this->task['db_connect']['old_home_url'] = get_home_url($this->get_site_mu_single_site_id());
}
else
{
$this->task['db_connect']['old_site_url']=untrailingslashit($wpvivid_plugin->staging->get_database_site_url());
$this->task['db_connect']['old_home_url']=untrailingslashit($wpvivid_plugin->staging->get_database_home_url());
}
$this->task['db_connect']['new_site_url']=$this->task['site']['site_url'];
$this->task['db_connect']['new_home_url']=$this->task['site']['home_url'];
$this->task['db_connect']['src_use_additional_db']=false;
$this->task['db_connect']['des_use_additional_db']=$this->task['site']['db_connect']['use_additional_db'];
if($this->task['db_connect']['des_use_additional_db'])
{
$this->task['db_connect']['des_dbuser']= $this->task['site']['db_connect']['dbuser'];
$this->task['db_connect']['des_dbpassword']= $this->task['site']['db_connect']['dbpassword'];
$this->task['db_connect']['des_dbname']=$this->task['site']['db_connect']['dbname'];
$this->task['db_connect']['des_dbhost']=$this->task['site']['db_connect']['dbhost'];
}
if(isset($option['data']['mu']))
{
$this->task['mu']= $option['data']['mu'];
}
}
else
{
$this->task['options']['copy']=false;
if(isset($option['data']['db_connect']))
$this->task['db_connect']=$option['data']['db_connect'];
$this->task['path']=$option['data']['path'];
if(isset($option['data']['mu']))
{
$this->task['mu']= $option['data']['mu'];
}
}
$this->task['permalink_structure'] = get_option( 'permalink_structure','');
$this->task['login_url'] = wp_login_url();
}
if(isset($option['data']['core']))
{
$this->task['job']['core']['exclude_files_regex']='#\.htaccess#';
$this->task['job']['core']['finished']=0;
$this->task['job']['core']['start']=0;
$this->task['job']['core']['type']='file';
}
if(isset($option['data']['wp-content']))
{
$this->task['job']['wp-content']['exclude_regex']=$option['data']['wp-content']['exclude_regex'];
$this->task['job']['wp-content']['exclude_files_regex']=$option['data']['wp-content']['exclude_files_regex'];
$this->task['job']['wp-content']['finished']=0;
$this->task['job']['wp-content']['start']=0;
$this->task['job']['wp-content']['type']='file';
}
if(isset($option['data']['plugins']))
{
$this->task['job']['plugins']['exclude_regex']=$option['data']['plugins']['exclude_regex'];
$this->task['job']['plugins']['finished']=0;
$this->task['job']['plugins']['start']=0;
$this->task['job']['plugins']['type']='file';
}
if(isset($option['data']['theme']))
{
$this->task['job']['theme']['exclude_regex']=$option['data']['theme']['exclude_regex'];
$this->task['job']['theme']['finished']=0;
$this->task['job']['theme']['start']=0;
$this->task['job']['theme']['type']='file';
}
if(isset($option['data']['upload']))
{
if(isset($option['data']['upload']['include_regex']))
$this->task['job']['upload']['include_regex']=$option['data']['upload']['include_regex'];
$this->task['job']['upload']['exclude_regex']=$option['data']['upload']['exclude_regex'];
$this->task['job']['upload']['exclude_files_regex']=$option['data']['upload']['exclude_files_regex'];
$this->task['job']['upload']['finished']=0;
$this->task['job']['upload']['start']=0;
$this->task['job']['upload']['type']='file';
}
if(isset($option['data']['custom']))
{
foreach ($option['data']['custom'] as $custom)
{
$this->task['job'][$custom['root']]['root']=$custom['root'];
$this->task['job'][$custom['root']]['exclude_regex']=$custom['exclude_regex'];
$this->task['job'][$custom['root']]['exclude_files_regex']=$custom['exclude_files_regex'];
$this->task['job'][$custom['root']]['finished']=0;
$this->task['job'][$custom['root']]['start']=0;
$this->task['job'][$custom['root']]['type']='file';
}
}
if(isset($option['data']['db']))
{
$this->task['job']['db']['exclude_tables']=$option['data']['db']['exclude_tables'];
$this->task['job']['db']['finished']=0;
$this->task['job']['db']['tables']=array();
$this->task['job']['db']['type']='db';
$this->task['job']['db_replace']['exclude_tables']=$option['data']['db']['exclude_tables'];
$this->task['job']['db_replace']['finished']=0;
$this->task['job']['db_replace']['tables']=array();
$this->task['job']['db_replace']['type']='db_replace';
if($option['data']['restore'])
{
$this->task['job']['db_rename']['exclude_tables']=$option['data']['db']['exclude_tables'];
$this->task['job']['db_rename']['finished']=0;
$this->task['job']['db_rename']['tables']=array();
$this->task['job']['db_rename']['type']='db_rename';
}
}
if(isset($option['data']['mu_single']))
{
$this->task['options']['mu_single']=true;
$this->task['options']['mu_single_upload']=$option['data']['mu_single_upload'];
$this->task['options']['mu_single_site_id']=$option['data']['mu_single_site_id'];
}
if(isset($option['data']['create_new_wp']))
{
$this->task['options']['fresh_install']=true;
$this->task['job']['create_new_wp']['type']='install_wordpress';
$this->task['job']['create_new_wp']['finished']=0;
}
$this->update_task();
}
public function update_action_time($action_type)
{
$this->get_task();
$this->task[$action_type]=time();
$this->update_task();
}
public function is_mu_single()
{
if(isset($this->task['options']['mu_single']))
return true;
else
return false;
}
public function get_mu_single_upload()
{
if(isset($this->task['options']['mu_single_upload']))
return $this->task['options']['mu_single_upload'];
else
return false;
}
public function get_mu_single_site_id()
{
if(isset($this->task['options']['mu_single_site_id']))
return $this->task['options']['mu_single_site_id'];
else
return false;
}
public function get_permalink_structure(){
$this->get_task();
return $this->task['permalink_structure'];
}
public function get_is_overwrite_permalink_structure(){
$this->get_task();
return $this->task['options']['staging_overwrite_permalink'];
}
public function is_tables_exclude($table,$prefix=false)
{
if(isset($this->task['job']['db'])&&isset($this->task['job']['db']['exclude_tables']))
{
$arr=$this->task['job']['db']['exclude_tables'];
if(empty($arr))
return false;
if($prefix===false)
{
return in_array($table, $arr);
}
else
{
$og_table=substr($table, strlen($prefix));
$old_table=$this->get_db_prefix().$og_table;
return in_array($old_table, $arr);
}
}
else
{
return false;
}
}
public function get_doing_task()
{
if($this->get_status()=='error')
return false;
$this->get_task();
$doing=$this->task['doing'];
if(isset($this->task['job'][$doing]))
{
if($this->task['job'][$doing]['finished'])
{
$this->task['doing']=false;
$this->update_task();
return $this->task['doing'];
}
else
{
return $doing;
}
}
else
{
return false;
}
}
public function get_start_next_task()
{
if($this->get_status()=='error')
return false;
$this->get_task();
foreach ($this->task['job'] as $key=>$job)
{
if($job['finished'])
continue;
return $key;
}
return false;
}
public function do_task($key)
{
global $wpvivid_plugin;
$this->get_task();
$wpvivid_plugin->staging->log->WriteLog('Start processing '.$key.'.','notice');
if($key==false)
return true;
$cancel_status = get_option('wpvivid_staging_task_cancel', false);
//if($this->task['status']['str']=='cancel')
if($cancel_status)
{
return false;
}
$job=$this->task['job'][$key];
$this->task['doing']=$key;
$this->task['status']['str']='running';
$this->update_task();
$this->flush();
if($job['type']=='file')
{
$wpvivid_plugin->staging->log->WriteLog('Prepare to copy '.$key.' files.','notice');
$task_id=$this->task['id'];
$file=new WPvivid_Staging_Copy_Files($task_id);
return $file->do_copy_file($key);
}
else if($job['type']=='db')
{
$wpvivid_plugin->staging->log->WriteLog('Prepare to copy database.','notice');
$task_id=$this->task['id'];
$file=new WPvivid_Staging_Copy_DB($task_id);
return $file->do_copy_db();
}
else if($job['type']=='db_replace')
{
$wpvivid_plugin->staging->log->WriteLog('Prepare to replace database.','notice');
$task_id=$this->task['id'];
$file=new WPvivid_Staging_Copy_DB($task_id);
return $file->do_replace_db();
}
else if($job['type']=='db_rename')
{
$wpvivid_plugin->staging->log->WriteLog('Prepare to rename tables.','notice');
$task_id=$this->task['id'];
$file=new WPvivid_Staging_Copy_DB($task_id);
return $file->do_rename_db();
}
else if($job['type']=='install_wordpress')
{
$wpvivid_plugin->staging->log->WriteLog('Prepare to install wordpress.','notice');
$task_id=$this->task['id'];
$install=new WPvivid_Staging_Install_Wordpress_Free($task_id);
return $install->do_install_wordpress();
}
return false;
}
private function flush()
{
$ret['result']='success';
$ret['task_id']=$this->task['id'];
$json=wp_json_encode($ret);
if(!headers_sent())
{
header('Content-Length: '.strlen($json));
header('Connection: close');
header('Content-Encoding: none');
}
if (session_id())
session_write_close();
echo wp_json_encode($ret);
if(function_exists('fastcgi_finish_request'))
{
fastcgi_finish_request();
}
else
{
ob_flush();
flush();
}
}
public function get_start($key)
{
$this->get_task();
if($key=='db'||$key=='db_replace'||$key=='db_rename')
{
foreach ($this->task['job'][$key]['tables'] as $table)
{
if($table['finished']==0)
{
return $table;
}
}
return false;
}
else
{
return $this->task['job'][$key]['start'];
}
}
public function update_start($key,$start)
{
$this->get_task();
$this->task['job'][$key]['start']=$start;
$this->update_task();
}
public function get_path($des=true)
{
$this->get_task();
if($des)
{
return $this->task['path']['des_path'];
}
else
{
return $this->task['path']['src_path'];
}
}
public function get_db_connect()
{
$this->get_task();
return $this->task['db_connect'];
}
public function get_db_prefix($new=false)
{
$this->get_task();
if($new)
{
return $this->task['db_connect']['new_prefix'];
}
else
{
return $this->task['db_connect']['old_prefix'];
}
}
public function get_temp_prefix()
{
$this->get_task();
if($this->is_restore())
return $this->task['db_connect']['temp_prefix'];
else
return $this->task['db_connect']['new_prefix'];
}
public function get_site_url($new=false)
{
$this->get_task();
if($new)
{
return $this->task['db_connect']['new_site_url'];
}
else
{
return $this->task['db_connect']['old_site_url'];
}
}
public function get_home_url($new=false)
{
$this->get_task();
if($new)
{
return $this->task['db_connect']['new_home_url'];
}
else
{
return $this->task['db_connect']['old_home_url'];
}
}
public function get_job_option($key,$option_name)
{
$this->get_task();
if(isset($this->task['job'][$key])&&isset($this->task['job'][$key][$option_name]))
{
return $this->task['job'][$key][$option_name];
}
else
{
return false;
}
}
public function update_job_finished($key)
{
$this->get_task();
$this->task['job'][$key]['finished']=1;
$this->task['status']['str']='ready';
$this->task['status']['resume_count']=0;
$this->task['doing']=false;
$this->update_task();
}
public function get_tables($key)
{
$this->get_task();
return $this->task['job'][$key]['tables'];
}
public function update_tables($key,$tables)
{
$this->get_task();
$this->task['job'][$key]['tables']=$tables;
$this->update_task();
}
public function update_table($key,$table)
{
$this->get_task();
$this->task['job'][$key]['tables'][$table['name']]=$table;
$this->update_task();
}
public function update_table_finished($key,$table)
{
$this->get_task();
$this->task['job'][$key]['tables'][$table['name']]=$table;
$this->task['status']['str']='ready';
$this->update_task();
}
public function finished_task()
{
$this->get_task();
$default = array();
$tasks = get_option('wpvivid_staging_task_list', $default);
$this->task['status']['run_time']=time();
$this->task['status']['str']='completed';
if($this->is_restore()|| $this->task['options']['copy']==true)
{
}
else {
if(isset($this->task['options']['fresh_install']))
{
$this->task['site']['fresh_install']=true;
}
if(isset($this->task['options']['mu_single']))
{
$this->task['site']['mu_single']=true;
$this->task['site']['mu_single_site_id']=$this->task['options']['mu_single_site_id'];
}
$this->task['site']['path']=$this->task['path']['des_path'];
$this->task['site']['site_url']=$this->task['db_connect']['new_site_url'];
$this->task['site']['home_url']=$this->task['db_connect']['new_home_url'];
$this->task['site']['prefix']=$this->task['db_connect']['new_prefix'];
$this->task['site']['db_connect']['use_additional_db']=$this->task['db_connect']['des_use_additional_db'];
if($this->task['site']['db_connect']['use_additional_db'])
{
$this->task['site']['db_connect']['dbuser']=$this->task['db_connect']['des_dbuser'];
$this->task['site']['db_connect']['dbpassword']=$this->task['db_connect']['des_dbpassword'];
$this->task['site']['db_connect']['dbname']=$this->task['db_connect']['des_dbname'];
$this->task['site']['db_connect']['dbhost']=$this->task['db_connect']['des_dbhost'];
}
if(isset($this->task['mu'])&&is_multisite())
{
$this->task['site']['path_current_site']=$this->task['mu']['path_current_site'];
$this->task['site']['main_site_id']=$this->task['mu']['main_site_id'];
}
}
$this->task['job']=array();
$this->task['doing']=false;
$tasks[$this->task['id']]=$this->task;
update_option('wpvivid_staging_task_list',$tasks,'no');
}
public function get_site_mu_single()
{
if(isset($this->task['site']['mu_single']))
return $this->task['site']['mu_single'];
else
return false;
}
public function get_site_mu_single_site_id()
{
if(isset($this->task['site']['mu_single']))
return $this->task['site']['mu_single_site_id'];
else
return false;
}
public function get_site_path()
{
if(isset($this->task['site']))
return $this->task['site']['path'];
else
return false;
}
public function get_site_db_connect()
{
if(isset($this->task['site']))
return $this->task['site']['db_connect'];
else
return false;
}
public function get_site_db_instance()
{
if(isset($this->task['site']))
{
$db=$this->get_site_db_connect();
if($db['use_additional_db']===false)
{
global $wpdb;
return $wpdb;
}
else {
return new wpdb($db['dbuser'],$db['dbpassword'],$db['dbname'],$db['dbhost']);
}
}
else
{
return false;
}
}
public function get_site_prefix()
{
if(isset($this->task['site']))
return $this->task['site']['prefix'];
else
return false;
}
public function finished_task_with_error($error='')
{
global $wpvivid_plugin;
$this->get_task();
if(empty($error))
{
$cancel_status = get_option('wpvivid_staging_task_cancel', false);
//if($this->task['status']['str']=='cancel')
if($cancel_status)
{
$default = array();
$tasks = get_option('wpvivid_staging_task_list', $default);
$this->task['status']['run_time']=time();
$this->task['status']['str']='error';
$this->task['status']['error']='task canceled';
$tasks[$this->task['id']]=$this->task;
update_option('wpvivid_staging_task_list',$tasks,'no');
}
else
{
$default = array();
$error = $this->get_error();
$tasks = get_option('wpvivid_staging_task_list', $default);
$this->task['status']['run_time']=time();
$this->task['status']['str']='error';
$this->task['status']['error']=$error;
$tasks[$this->task['id']]=$this->task;
update_option('wpvivid_staging_task_list',$tasks,'no');
$wpvivid_plugin->staging->log->WriteLog('Error: '.$this->task['status']['error'],'error');
WPvivid_Staging_error_log_free::create_error_log($wpvivid_plugin->staging->log->log_file);
}
}
else
{
$default = array();
$tasks = get_option('wpvivid_staging_task_list', $default);
$this->task['status']['run_time']=time();
$this->task['status']['str']='error';
$this->task['status']['error']=$error;
$tasks[$this->task['id']]=$this->task;
update_option('wpvivid_staging_task_list',$tasks,'no');
$wpvivid_plugin->staging->log->WriteLog('Error: '.$this->task['status']['error'],'error');
WPvivid_Staging_error_log_free::create_error_log($wpvivid_plugin->staging->log->log_file);
}
}
public function set_error($error)
{
$this->get_task();
$this->task['status']['str']='error';
$this->task['status']['error']=$error;
$this->update_task();
}
public function get_error()
{
$this->get_task();
if($this->task['status']['str']=='error')
{
return $this->task['status']['error'];
}
else
{
return '';
}
}
public function get_status()
{
$this->get_task();
$cancel_status = get_option('wpvivid_staging_task_cancel', false);
if($cancel_status)
{
return 'cancel';
}
else {
return $this->task['status']['str'];
}
}
public function check_timeout()
{
$this->get_task();
$time_spend = time() - $this->task['status']['timeout'];
$limit=$this->task['timeout_limit'];
$max_resume_count=$this->task['options']['staging_resume_count'];
if ($time_spend >= $limit)
{
$this->task['status']['resume_count']++;
global $wpvivid_plugin;
$wpvivid_plugin->staging->log->OpenLogFile($this->get_log_file_name());
$wpvivid_plugin->staging->log->WriteLog('Task time out. Resumption times: '.$this->task['status']['resume_count'],'notice');
if($this->task['status']['resume_count']>$max_resume_count)
{
$wpvivid_plugin->staging->log->WriteLog('Task time out.','error');
$this->task['status']['str']='error';
$this->task['status']['error']='task time out.';
}
else
{
$this->task['status']['str']='ready';
}
$this->update_task();
return true;
}
else
{
$no_response_time=time()-$this->task['status']['run_time'];
if($no_response_time>180)
{
$next_timeout_time = $limit-$time_spend;
global $wpvivid_plugin;
$wpvivid_plugin->staging->log->OpenLogFile($this->get_log_file_name());
$wpvivid_plugin->staging->log->WriteLog('Task is not responding and will time out in '.$next_timeout_time,'notice');
$this->task['status']['str']='no_reponse';
$this->update_task();
}
}
return false;
}
public function set_memory_limit()
{
if(isset($this->task['options']['staging_memory_limit']))
$memory_limit=$this->task['options']['staging_memory_limit'];
else
$memory_limit='256M';
@ini_set('memory_limit', $memory_limit);
}
public function get_exclude_file_size()
{
if(isset($this->task['options']['staging_exclude_file_size'])) {
$exclude_file_size = $this->task['options']['staging_exclude_file_size'];
}
else {
$exclude_file_size = 30;
}
return $exclude_file_size;
}
public function get_files_copy_count()
{
if(isset($this->task['options']['staging_file_copy_count']))
$files_copy_count=$this->task['options']['staging_file_copy_count'];
else
$files_copy_count=500;
return $files_copy_count;
}
public function get_db_insert_count()
{
if(isset($this->task['options']['staging_db_insert_count']))
$db_insert_count=$this->task['options']['staging_db_insert_count'];
else
$db_insert_count=10000;
return $db_insert_count;
}
public function get_db_replace_count()
{
if(isset($this->task['options']['staging_db_replace_count']))
$db_replace_count=$this->task['options']['staging_db_replace_count'];
else
$db_replace_count=5000;
return $db_replace_count;
}
public function is_restore()
{
return $this->task['options']['restore'];
}
public function is_copy()
{
return $this->task['options']['copy'];
}
public function cancel_staging()
{
$this->get_task();
//$default = array();
//$tasks = get_option('wpvivid_staging_task_list', $default);
if( $this->task['status']['str']=='running' || $this->task['status']['str']=='ready' )
{
//$this->task['status']['str']='cancel';
update_option('wpvivid_staging_task_cancel', true, 'no');
}
//$tasks[$this->task['id']]=$this->task;
//update_option('wpvivid_staging_task_list',$tasks);
}
public function update_calc_db_size($key)
{
$this->get_task();
$size = 0;
if($key=='db'||$key=='db_replace'||$key=='db_rename')
{
$size = count($this->task['job'][$key]['tables']);
}
$this->task['job'][$key]['copy_size']=$size;
$this->update_task();
}
public function update_calc_db_finish_size($key)
{
$this->get_task();
if($key=='db'||$key=='db_replace'||$key=='db_rename')
{
if(!isset($this->task['job'][$key]['finish_size'])){
$this->task['job'][$key]['finish_size'] = 1;
}
else{
$this->task['job'][$key]['finish_size']++;
}
}
$this->update_task();
}
public function get_progress()
{
$job_count=sizeof($this->task['job']);
if($job_count>0)
{
$job_finished=0;
foreach ($this->task['job'] as $job)
{
if($job['type']=='db'||$job['type']=='db_replace'||$job['type']=='db_rename'){
if(isset($this->task['job'][$job['type']]['finish_size']) && $this->task['job'][$job['type']]['finish_size'] != 0 &&
isset($this->task['job'][$job['type']]['copy_size']) && $this->task['job'][$job['type']]['copy_size'] != 0) {
$percent_db = floatval($this->task['job'][$job['type']]['finish_size'] / $this->task['job'][$job['type']]['copy_size']);
$job_finished = floatval($job_finished + $percent_db);
}
}
else if($job['finished'])
{
$job_finished++;
}
}
$progress=intval(($job_finished/$job_count)*100);
if($progress == 0){
$progress = 5;
}
return $progress;
}
else
{
return 100;
}
}
public function get_mu_sites($args=array())
{
global $wpdb;
$db=$this->get_site_db_connect();
if($db['use_additional_db']===false)
{
$old_prefix=$wpdb->base_prefix;
$wpdb->set_prefix($this->get_site_prefix());
$subsites=get_sites($args);
$wpdb->set_prefix($old_prefix);
}
else
{
$old_wpdb=$wpdb;
$wpdb=new wpdb($db['dbuser'],$db['dbpassword'],$db['dbname'],$db['dbhost']);
$wpdb->set_prefix($this->get_site_prefix());
$subsites=get_sites($args);
$wpdb=$old_wpdb;
}
/*
if($db['use_additional_db']===false)
{
$db_instance=$wpdb;
}
else
{
$db_instance=new wpdb($db['dbuser'],$db['dbpassword'],$db['dbname'],$db['dbhost']);
}
$sql='SELECT * FROM '.$this->get_site_prefix().'blogs';
$subsites=$db_instance->get_results($sql,OBJECT_K);
*/
return $subsites;
}
public function get_mu_path_current_site()
{
if(isset($this->task['site']['path_current_site']))
{
return $this->task['site']['path_current_site'];
}
else
{
return false;
}
}
public function get_mu_main_site_id()
{
if(isset($this->task['site']['main_site_id']))
{
return $this->task['site']['main_site_id'];
}
else
{
return false;
}
}
public function set_push_staging_history($option)
{
global $wpdb;
$site_prefix=$this->get_site_prefix();
foreach ($option['database_list'] as $index => $table)
{
$option['database_list'][$index] = str_replace($site_prefix, $wpdb->base_prefix, $table);
}
$this->task['push_staging_history'] = $option;
}
public function get_push_staging_history()
{
$option = $this->task['push_staging_history'];
return $option;
}
} includes/class-wpvivid-exporter.php 0000644 00000221513 15132770567 0013545 0 ustar 00 <?php
/**
* WPvivid addon: yes
* Addon Name: wpvivid-backup-pro-all-in-one
* Description: Pro
* Version: 1.9.1
*/
if ( ! class_exists( 'WP_List_Table' ) )
{
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class WPvivid_Post_List extends WP_List_Table
{
public $post_ids;
public $page_num;
public function __construct( $args = array() ) {
global $post_type_object, $wpdb;
parent::__construct(
array(
'plural' => 'posts',
'screen' => isset( $args['screen'] ) ? $args['screen'] : null,
)
);
$post_type = $this->screen->post_type;
$post_type_object = get_post_type_object( $post_type );
$exclude_states = get_post_stati(
array(
'show_in_admin_all_list' => false,
)
);
$this->user_posts_count = intval(
$wpdb->get_var(
$wpdb->prepare(
"
SELECT COUNT( 1 )
FROM $wpdb->posts
WHERE post_type = %s
AND post_status NOT IN ( '" . implode( "','", $exclude_states ) . "' )
AND post_author = %d
",
$post_type,
get_current_user_id()
)
)
);
if ( $this->user_posts_count && ! current_user_can( $post_type_object->cap->edit_others_posts ) && empty( $_REQUEST['post_status'] ) && empty( $_REQUEST['all_posts'] ) && empty( $_REQUEST['author'] ) && empty( $_REQUEST['show_sticky'] ) ) {
$_GET['author'] = get_current_user_id();
}
if ( 'post' === $post_type && $sticky_posts = get_option( 'sticky_posts' ) ) {
$sticky_posts = implode( ', ', array_map( 'absint', (array) $sticky_posts ) );
$this->sticky_posts_count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT( 1 ) FROM $wpdb->posts WHERE post_type = %s AND post_status NOT IN ('trash', 'auto-draft') AND ID IN ($sticky_posts)", $post_type ) );
}
}
public function get_columns()
{
$post_type = $this->screen->post_type;
$posts_columns = array();
$posts_columns['cb'] = '<input type="checkbox"/>';
/* translators: manage posts column name */
$posts_columns['wpvivid_id'] = 'ID';
$posts_columns['title'] = _x( 'Title', 'column name', 'wpvivid-backuprestore' );
if ( post_type_supports( $post_type, 'author' ) ) {
$posts_columns['author'] = __( 'Author', 'wpvivid-backuprestore' );
}
$taxonomies = get_object_taxonomies( $post_type, 'objects' );
$taxonomies = wp_filter_object_list( $taxonomies, array( 'show_admin_column' => true ), 'and', 'name' );
/**
* Filters the taxonomy columns in the Posts list table.
*
* The dynamic portion of the hook name, `$post_type`, refers to the post
* type slug.
*
* @since 3.5.0
*
* @param string[] $taxonomies Array of taxonomy names to show columns for.
* @param string $post_type The post type.
*/
$taxonomies = apply_filters( "manage_taxonomies_for_{$post_type}_columns", $taxonomies, $post_type );
$taxonomies = array_filter( $taxonomies, 'taxonomy_exists' );
foreach ( $taxonomies as $taxonomy ) {
if ( 'category' === $taxonomy ) {
$column_key = 'categories';
} elseif ( 'post_tag' === $taxonomy ) {
$column_key = 'tags';
} else {
$column_key = 'taxonomy-' . $taxonomy;
}
$posts_columns[ $column_key ] = get_taxonomy( $taxonomy )->labels->name;
}
$posts_columns['comments'] =__( 'Comments', 'wpvivid-backuprestore' );
$posts_columns['date'] = __( 'Date', 'wpvivid-backuprestore' );
return $posts_columns;
}
function set_post_ids($post_ids,$page_num=1)
{
$this->post_ids=$post_ids;
$this->page_num=$page_num;
}
public function get_pagenum()
{
if($this->page_num=='first')
{
$this->page_num=1;
}
else if($this->page_num=='last')
{
$this->page_num=$this->_pagination_args['total_pages'];
}
$pagenum = $this->page_num ? $this->page_num : 0;
if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
{
$pagenum = $this->_pagination_args['total_pages'];
}
return max( 1, $pagenum );
}
function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$this->_column_headers = array($columns, $hidden, $sortable);
$total_items =sizeof($this->post_ids);
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => 30,
)
);
}
public function has_items()
{
return !empty($this->post_ids);
}
public function column_cb( $post )
{
$checked='';
if($post->checked)
{
$checked='checked';
}
?>
<input id="cb-select-<?php echo esc_attr($post->ID); ?>" type="checkbox" name="post[]" value="<?php echo esc_attr($post->ID); ?>" <?php echo esc_attr($checked) ?>/>
<?php
}
/**
* @since 4.3.0
*
* @param WP_Post $post
* @param string $classes
* @param string $data
* @param string $primary
*/
protected function _column_title( $post, $classes, $data, $primary ) {
echo '<td class="' . esc_attr($classes) . ' page-title" ', esc_attr($data), '>';
echo esc_html($this->column_title( $post ));
echo '</td>';
}
public function column_wpvivid_id( $post )
{
echo '<span>'.esc_attr($post->ID).'</span>';
}
/**
* Handles the title column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_title( $post ) {
echo '<strong>';
$title = $post->post_title;
echo esc_html($title);
echo "</strong>\n";
}
/**
* Handles the post date column output.
*
* @since 4.3.0
*
* @global string $mode List table view mode.
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_date( $post )
{
global $mode;
if ( '0000-00-00 00:00:00' === $post->post_date ) {
$t_time = $h_time = __( 'Unpublished', 'wpvivid-backuprestore' );
$time_diff = 0;
} else {
$t_time = get_the_time( 'Y/m/d g:i:s a' );
$m_time = $post->post_date;
$time = get_post_time( 'G', true, $post );
$time_diff = time() - $time;
if ( $time_diff > 0 && $time_diff < DAY_IN_SECONDS ) {
$h_time = sprintf( '%s ago', human_time_diff( $time ) );
} else {
$h_time = mysql2date( 'Y/m/d', $m_time );
}
}
if ( 'publish' === $post->post_status ) {
$status = __( 'Published', 'wpvivid-backuprestore' );
} elseif ( 'future' === $post->post_status ) {
if ( $time_diff > 0 ) {
$status = '<strong class="error-message">' . __( 'Missed schedule', 'wpvivid-backuprestore' ) . '</strong>';
} else {
$status = __( 'Scheduled', 'wpvivid-backuprestore' );
}
} else {
$status = __( 'Last Modified', 'wpvivid-backuprestore' );
}
/**
* Filters the status text of the post.
*
* @since 4.8.0
*
* @param string $status The status text.
* @param WP_Post $post Post object.
* @param string $column_name The column name.
* @param string $mode The list display mode ('excerpt' or 'list').
*/
$status = apply_filters( 'post_date_column_status', $status, $post, 'date', $mode );
if ( $status ) {
echo esc_html($status) . '<br />';
}
if ( 'excerpt' === $mode ) {
/**
* Filters the published time of the post.
*
* If `$mode` equals 'excerpt', the published time and date are both displayed.
* If `$mode` equals 'list' (default), the publish date is displayed, with the
* time and date together available as an abbreviation definition.
*
* @since 2.5.1
*
* @param string $t_time The published time.
* @param WP_Post $post Post object.
* @param string $column_name The column name.
* @param string $mode The list display mode ('excerpt' or 'list').
*/
echo esc_html(apply_filters( 'post_date_column_time', $t_time, $post, 'date', $mode ));
} else {
/** This filter is documented in wp-admin/includes/class-wp-posts-list-table.php */
echo '<abbr title="' . esc_attr($t_time) . '">' . esc_html(apply_filters( 'post_date_column_time', $h_time, $post, 'date', $mode )) . '</abbr>';
}
}
/**
* Handles the comments column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_comments( $post ) {
?>
<div class="post-com-count-wrapper">
<?php
echo '<span style="text-align:center">'.esc_html(get_comments_number($post->ID)).'</span>'
?>
</div>
<?php
}
/**
* Handles the post author column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
*/
public function column_author( $post ) {
$user_data = get_userdata($post->post_author );
echo '<span>'.esc_html($user_data->display_name).'</span>';
}
/**
* Handles the default column output.
*
* @since 4.3.0
*
* @param WP_Post $post The current WP_Post object.
* @param string $column_name The current column name.
*/
public function column_default( $post, $column_name ) {
if ( 'categories' === $column_name )
{
$taxonomy = 'category';
} elseif ( 'tags' === $column_name )
{
$taxonomy = 'post_tag';
} elseif ( 0 === strpos( $column_name, 'taxonomy-' ) )
{
$taxonomy = substr( $column_name, 9 );
} else {
$taxonomy = false;
}
if ( $taxonomy ) {
$taxonomy_object = get_taxonomy( $taxonomy );
$terms = get_the_terms( $post->ID, $taxonomy );
if ( is_array( $terms ) ) {
$out = array();
foreach ( $terms as $t ) {
$posts_in_term_qv = array();
if ( 'post' != $post->post_type ) {
$posts_in_term_qv['post_type'] = $post->post_type;
}
if ( $taxonomy_object->query_var ) {
$posts_in_term_qv[ $taxonomy_object->query_var ] = $t->slug;
} else {
$posts_in_term_qv['taxonomy'] = $taxonomy;
$posts_in_term_qv['term'] = $t->slug;
}
$label = esc_html( sanitize_term_field( 'name', $t->name, $t->term_id, $taxonomy, 'display' ) );
$out[] = $label;
}
/* translators: used between list items, there is a space after the comma */
echo esc_html(join( ', ', $out ));
} else {
echo '<span aria-hidden="true">—</span><span class="screen-reader-text">' . esc_html($taxonomy_object->labels->no_terms) . '</span>';
}
return;
}
if ( is_post_type_hierarchical( $post->post_type ) ) {
/**
* Fires in each custom column on the Posts list table.
*
* This hook only fires if the current post type is hierarchical,
* such as pages.
*
* @since 2.5.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( 'manage_pages_custom_column', $column_name, $post->ID );
} else {
/**
* Fires in each custom column in the Posts list table.
*
* This hook only fires if the current post type is non-hierarchical,
* such as posts.
*
* @since 1.5.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( 'manage_posts_custom_column', $column_name, $post->ID );
}
/**
* Fires for each custom column of a specific post type in the Posts list table.
*
* The dynamic portion of the hook name, `$post->post_type`, refers to the post type.
*
* @since 3.1.0
*
* @param string $column_name The name of the column to display.
* @param int $post_id The current post ID.
*/
do_action( "manage_{$post->post_type}_posts_custom_column", $column_name, $post->ID );
}
public function display_rows()
{
$this->_display_rows( $this->post_ids );
}
private function _display_rows($post_ids)
{
$page_post_ids=$post_ids;
$page=$this->get_pagenum();
$count=0;
while ( $count<$page )
{
$page_post_ids = array_splice( $post_ids, 0, 30);
$count++;
}
foreach ( $page_post_ids as $post_id)
{
$this->single_row($post_id);
}
}
public function single_row($post_id)
{
$post = get_post($post_id['id']);
$post->checked=$post_id['checked'];
$classes = 'iedit author-' . ( get_current_user_id() == $post->post_author ? 'self' : 'other' );
?>
<tr id="post-<?php echo esc_attr($post->ID); ?>" class="<?php echo esc_attr(implode( ' ', get_post_class( $classes, $post->ID ) )); ?>">
<?php $this->single_row_columns( $post ); ?>
</tr>
<?php
}
protected function pagination( $which ) {
if ( empty( $this->_pagination_args ) ) {
return;
}
$total_items = $this->_pagination_args['total_items'];
$total_pages = $this->_pagination_args['total_pages'];
$infinite_scroll = false;
if ( isset( $this->_pagination_args['infinite_scroll'] ) ) {
$infinite_scroll = $this->_pagination_args['infinite_scroll'];
}
if ( 'top' === $which && $total_pages > 1 ) {
$this->screen->render_screen_reader_content( 'heading_pagination' );
}
$output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items, 'wpvivid-backuprestore' ), number_format_i18n( $total_items ) ) . '</span>';
$current = $this->get_pagenum();
$removable_query_args = wp_removable_query_args();
$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
$current_url = remove_query_arg( $removable_query_args, $current_url );
$page_links = array();
$total_pages_before = '<span class="paging-input">';
$total_pages_after = '</span></span>';
$disable_first = $disable_last = $disable_prev = $disable_next = false;
if ( $current == 1 ) {
$disable_first = true;
$disable_prev = true;
}
if ( $current == 2 ) {
$disable_first = true;
}
if ( $current == $total_pages ) {
$disable_last = true;
$disable_next = true;
}
if ( $current == $total_pages - 1 ) {
$disable_last = true;
}
if ( $disable_first ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>';
} else {
$page_links[] = sprintf(
"<div class='first-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'First page', 'wpvivid-backuprestore' ),
'«'
);
}
if ( $disable_prev ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>';
} else {
$page_links[] = sprintf(
"<div class='prev-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Previous page', 'wpvivid-backuprestore' ),
'‹'
);
}
if ( 'bottom' === $which ) {
$html_current_page = $current;
$total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
} else {
$html_current_page = sprintf(
"%s<input class='current-page' id='current-page-selector-export' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
'<label for="current-page-selector-export" class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</label>',
$current,
strlen( $total_pages )
);
}
$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
$page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging', 'wpvivid-backuprestore' ), $html_current_page, $html_total_pages ) . $total_pages_after;
if ( $disable_next ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>';
} else {
$page_links[] = sprintf(
"<div class='next-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Next page', 'wpvivid-backuprestore' ),
'›'
);
}
if ( $disable_last ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>';
} else {
$page_links[] = sprintf(
"<div class='last-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'Last page', 'wpvivid-backuprestore' ),
'»'
);
}
$pagination_links_class = 'pagination-links';
if ( ! empty( $infinite_scroll ) ) {
$pagination_links_class .= ' hide-if-js';
}
$output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
if ( $total_pages ) {
$page_class = $total_pages < 2 ? ' one-page' : '';
} else {
$page_class = ' no-pages';
}
$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
echo $this->_pagination;
}
/**
* Generate the table navigation above or below the table
*
* @since 3.1.0
* @param string $which
*/
protected function display_tablenav( $which ) {
$css_type = '';
if ( 'top' === $which ) {
wp_nonce_field( 'bulk-' . $this->_args['plural'] );
$css_type = 'margin: 0 0 10px 0';
}
else if( 'bottom' === $which ) {
$css_type = 'margin: 10px 0 0 0';
}
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<div class="alignleft actions bulkactions">
<?php echo '<input class="button-primary" id="wpvivid-post-research-submit" type="submit" name="post" value="' . esc_attr__('Reset Filters', 'wpvivid-backuprestore') .'">'; ?>
</div>
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
}
class WPvivid_Exporter_taskmanager
{
public static function get_task($task_id)
{
$default = array();
$tasks = get_option('wpvivid_exporter_task_list', $default);
if(array_key_exists ($task_id,$tasks))
{
return $tasks[$task_id];
}
else
{
return false;
}
}
public static function update_task($task_id,$task)
{
$default = array();
$options = get_option('wpvivid_exporter_task_list', $default);
$options[$task_id]=$task;
WPvivid_Setting::update_option('wpvivid_exporter_task_list',$options);
}
public static function get_tasks()
{
$default = array();
return $options = get_option('wpvivid_exporter_task_list', $default);
}
public static function get_backup_task_status($task_id)
{
$tasks=self::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task = $tasks[$task_id];
return $task['status'];
}
else
{
return false;
}
}
public static function delete_task($task_id)
{
$options = get_option('wpvivid_exporter_task_list', array());
unset($options[$task_id]);
WPvivid_Setting::update_option('wpvivid_exporter_task_list',$options);
}
public static function update_backup_task_status($task_id,$reset_start_time=false,$status='',$reset_timeout=false,$resume_count=false,$error='')
{
$tasks=self::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task = $tasks[$task_id];
$task['status']['run_time']=time();
if($reset_start_time)
$task['status']['start_time']=time();
if(!empty($status))
{
$task['status']['str']=$status;
}
if($reset_timeout)
$task['status']['timeout']=time();
if($resume_count!==false)
{
$task['status']['resume_count']=$resume_count;
}
if(!empty($error))
{
$task['status']['error']=$error;
}
self::update_task($task_id,$task);
return $task;
}
else
{
return false;
}
}
public static function get_task_options($task_id,$option_names)
{
$tasks=self::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task=$tasks[$task_id];
if(is_array($option_names))
{
$options=array();
foreach ($option_names as $name)
{
$options[$name]=$task['options'][$name];
}
return $options;
}
else
{
return $task['options'][$option_names];
}
}
else
{
return false;
}
}
public static function is_tasks_running()
{
$tasks=self::get_tasks();
foreach ($tasks as $task)
{
if ($task['status']['str']=='running'||$task['status']['str']=='no_responds')
{
return true;
}
}
return false;
}
public static function update_main_task_progress($task_id,$job_name,$progress,$finished,$job_data=array())
{
$task=self::get_task($task_id);
if($task!==false)
{
$task['status']['run_time']=time();
$task['status']['str']='running';
$task['data']['doing']=$job_name;
$task['data'][$job_name]['finished']=$finished;
$task['data'][$job_name]['progress']=$progress;
$task['data'][$job_name]['job_data']=$job_data;
self::update_task($task_id,$task);
}
}
public static function get_backup_tasks_progress($task_id)
{
$tasks=self::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task = $tasks[$task_id];
$current_time=gmdate("Y-m-d H:i:s");
$create_time=gmdate("Y-m-d H:i:s",$task['status']['start_time']);
$time_diff=strtotime($current_time)-strtotime($create_time);
$running_time='';
if(gmdate("G",$time_diff) > 0){
$running_time .= gmdate("G",$time_diff).'hour';
}
if(intval(gmdate("i",$time_diff)) > 0){
$running_time .= intval(gmdate("i",$time_diff)).'min';
}
if(intval(gmdate("s",$time_diff)) > 0){
$running_time .= intval(gmdate("s",$time_diff)).'second';
}
$ret['type']=$task['data']['doing'];
$ret['progress']=$task['data'][$ret['type']]['progress'];
$ret['doing']=$task['data'][$ret['type']]['doing'];
if(isset($task['data'][$ret['type']]['sub_job'][$ret['doing']]['progress']))
$ret['descript']=$task['data'][$ret['type']]['sub_job'][$ret['doing']]['progress'];
else
$ret['descript']='';
if(isset($task['data'][$ret['type']]['sub_job'][$ret['doing']]['upload_data']))
$ret['upload_data']=$task['data'][$ret['type']]['sub_job'][$ret['doing']]['upload_data'];
$task['data'][$ret['type']]['sub_job'][$ret['doing']]['upload_data']=false;
$ret['running_time']=$running_time;
$ret['running_stamp']=$time_diff;
return $ret;
}
else
{
return false;
}
}
}
class WPvivid_Exporter_task
{
private $task;
public function __construct($task_id=false,$task=false)
{
if($task_id!==false)
{
$this->task=WPvivid_Exporter_taskmanager::get_task($task_id);
}
if($task!==false)
{
$this->task=$task;
}
}
public function get_id()
{
return $this->task['id'];
}
public function new_backup_task($options)
{
$id=uniqid('wpvivid-');
$this->task=false;
$this->task['id']=$id;
$this->task['status']['start_time']=time();
$this->task['status']['run_time']=time();
$this->task['status']['timeout']=time();
$this->task['status']['str']='ready';
$this->task['status']['resume_count']=0;
if(isset($options['remote'])) {
if($options['remote']=='1') {
$this->task['options']['remote_options'] = isset($options['remote_options']) ? $options['remote_options'] : WPvivid_Setting::get_remote_options();
}
else {
$this->task['options']['remote_options']=false;
}
}
else {
$this->task['options']['remote_options']=false;
}
$this->task['options']['remote_options'] = apply_filters('wpvivid_set_remote_options', $this->task['options']['remote_options'],$options);
if(isset($options['local'])) {
$this->task['options']['save_local'] = $options['local']=='1' ? 1 : 0;
}
else {
$this->task['options']['save_local']=1;
}
$this->task['options']['post_comment'] = $options['post_comment'];
if(empty($backup_prefix))
$this->task['options']['file_prefix'] = $this->task['id'] . '_' . gmdate('Y-m-d-H-i', $this->task['status']['start_time']);
else
$this->task['options']['file_prefix'] = $backup_prefix . '_' . $this->task['id'] . '_' . gmdate('Y-m-d-H-i', $this->task['status']['start_time']);
$this->task['options']['log_file_name']=$id.'_export';
$log=new WPvivid_Log();
$log->CreateLogFile($this->task['options']['log_file_name'],'no_folder','export');
$this->task['options']['backup_options']['prefix']=$this->task['options']['file_prefix'];
$this->task['options']['backup_options']['compress']=WPvivid_Setting::get_option('wpvivid_compress_setting');
$this->task['options']['backup_options']['dir']=WPvivid_Setting::get_backupdir();
$this->task['options']['backup_options']['post_ids']=$options['post_ids'];
$this->task['options']['backup_options']['post_type']=$options['post_type'];
$export_data['json_info']['post_type']=$options['post_type'];
//$export_data['json_info']['post_ids']=$options['post_ids'];
$export_data['json_info']['post_comment']=$options['post_comment'];
$this->task['options']['backup_options']['backup'][$options['post_type']]=$export_data;
$this->task['data']['doing']='export';
$this->task['data']['export']['doing']='';
$this->task['data']['export']['finished']=0;
$this->task['data']['export']['progress']=0;
if(sizeof($options['post_ids'])>50) {
$this->task['data']['export']['pre_progress']=(50/sizeof($options['post_ids']))*100;
}
else {
$this->task['data']['export']['pre_progress']=100;
}
$this->task['data']['export']['job_data']=array();
$this->task['data']['export']['sub_job']=array();
$this->task['data']['export']['export_info']['post_count']=sizeof($options['post_ids']);
$this->task['data']['upload']['doing']='';
$this->task['data']['upload']['finished']=0;
$this->task['data']['upload']['progress']=0;
$this->task['data']['upload']['job_data']=array();
$this->task['data']['upload']['sub_job']=array();
WPvivid_Exporter_taskmanager::update_task($id,$this->task);
$ret['result']='success';
$ret['task_id']=$this->task['id'];
$log->CloseFile();
return $ret;
}
private function parse_url_all($url)
{
$parse = wp_parse_url($url);
$path=str_replace('/','_',$parse['path']);
return $parse['host'].$path;
}
public function update_sub_task_progress($key,$finished,$progress)
{
$this->task=WPvivid_Exporter_taskmanager::get_task($this->get_id());
$this->task['status']['run_time']=time();
$this->task['status']['str']='running';
$this->task['data']['doing']='export';
$sub_job_name=$key;
$this->task['data']['export']['doing']=$key;
$this->task['data']['export']['sub_job'][$sub_job_name]['finished']=$finished;
$this->task['data']['export']['sub_job'][$sub_job_name]['progress']=$progress;
if(!isset( $this->task['data']['export']['sub_job'][$sub_job_name]['job_data']))
{
$this->task['data']['export']['sub_job'][$sub_job_name]['job_data']=array();
}
WPvivid_Exporter_taskmanager::update_task($this->get_id(),$this->task);
}
public function get_next_posts()
{
asort($this->task['options']['backup_options']['post_ids']);
WPvivid_Exporter_taskmanager::update_task($this->get_id(),$this->task);
$post_ids=$this->task['options']['backup_options']['post_ids'];
if(empty($post_ids))
{
return false;
}
/*if(sizeof($post_ids)>50)
{
$next_post_ids = array_splice( $post_ids, 0, 50 );
}
else
{
$next_post_ids=$post_ids;
}*/
$next_post_ids=$post_ids;
$ret=$this->get_post_contain_attachment_ids($next_post_ids);
$next_post_ids = array_splice( $this->task['options']['backup_options']['post_ids'], 0, $ret['post_count'] );
$ret['next_post_ids']=$next_post_ids;
$post_type = $this->task['options']['backup_options']['post_type'];
$ret['json_info'] = $this->task['options']['backup_options']['backup'][$post_type]['json_info'];
$first=reset($next_post_ids);
$last=end($next_post_ids);
$post_comment = !empty($this->task['options']['post_comment']) ? $this->task['options']['post_comment'].'_' : '';
$ret['file_name']=$post_comment.self::get_id().'_'.gmdate('Y-m-d-H-i', $this->task['status']['start_time']);
$ret['export_type']=$this->task['options']['backup_options']['post_type'];
return $ret;
}
public function update_finished_posts($finished_posts)
{
$this->task=WPvivid_Exporter_taskmanager::get_task( $this->get_id());
array_splice( $this->task['options']['backup_options']['post_ids'], 0, $finished_posts['post_count'] );
$this->task['data']['export']['progress']=$this->task['data']['export']['progress']+$this->task['data']['export']['pre_progress'];
if($this->task['data']['export']['progress']>100)
{
$this->task['data']['export']['progress']=100;
}
WPvivid_Exporter_taskmanager::update_task($this->get_id(),$this->task);
}
public function update_export_files($file_data)
{
$this->task=WPvivid_Exporter_taskmanager::get_task( $this->get_id());
$this->task['data']['file_data'][]=$file_data;
$this->task['data']['export']['export_info']['file_name']=$file_data['file_name'];
$this->task['data']['export']['export_info']['size']=$file_data['size'];
WPvivid_Exporter_taskmanager::update_task($this->get_id(),$this->task);
}
public function get_export_files()
{
$this->task=WPvivid_Exporter_taskmanager::get_task( $this->get_id());
if(isset($this->task['data']['file_data']))
{
$file_data=$this->task['data']['file_data'];
return $file_data;
}
else
{
return array();
}
}
public function get_post_contain_attachment_ids($post_ids)
{
$max_size=1024*1024*100;
$current_size=0;
$count=0;
$sum_attachment_ids=array();
$attachment_added_ids=array();
$files=array();
foreach ($post_ids as $id)
{
$count++;
$attachment_ids=array();
$post = get_post( $id );
if (preg_match_all( '/<img [^>]+>/', $post->post_content, $matches ) )
{
foreach( $matches[0] as $image )
{
if ( preg_match( '/wp-image-([0-9]+)/i', $image, $class_id ) && ( $attachment_id = absint( $class_id[1] ) ) )
{
if(!in_array($attachment_id,$attachment_added_ids))
{
if(!is_null(get_post($attachment_id)))
{
$attachment_ids[] = $attachment_id;
$attachment_added_ids[]=$attachment_id;
}
else
{
$ret_attachment=$this->get_image_from_post_content($image);
$current_size+=$ret_attachment['size'];
$files=array_merge($files,$ret_attachment['files']);
}
}
}
else
{
$ret_attachment=$this->get_image_from_post_content($image);
$current_size+=$ret_attachment['size'];
$files=array_merge($files,$ret_attachment['files']);
}
}
}
$_elementor_meta=get_post_meta($id,'_elementor_data',true);
if($_elementor_meta!=false)
{
if ( is_string( $_elementor_meta ) && ! empty( $_elementor_meta ) )
{
$_elementor_meta = json_decode( $_elementor_meta, true );
}
if ( empty( $_elementor_meta ) )
{
$_elementor_meta = array();
}
$elements_data=$_elementor_meta;
foreach ( $elements_data as $element_data )
{
$element_image=$this->get_element_image($element_data,$attachment_added_ids);
$attachment_ids=array_merge($attachment_ids,$element_image);
}
}
//_thumbnail_id
$_thumbnail_id=get_post_meta($id,'_thumbnail_id',true);
if($_thumbnail_id!=false)
{
if(!in_array($_thumbnail_id,$attachment_added_ids))
{
if(!is_null(get_post($_thumbnail_id)))
{
$attachment_ids[] = $_thumbnail_id;
$attachment_added_ids[]=$_thumbnail_id;
}
}
}
$sum_attachment_ids=array_merge($sum_attachment_ids,$attachment_ids);
foreach ($attachment_ids as $attachment_id)
{
$ret_attachment=$this->get_attachment_size($attachment_id);
$current_size+=$ret_attachment['size'];
$files=array_merge($files,$ret_attachment['files']);
}
if($current_size>$max_size)
{
break;
}
}
$ret['attachment_ids']=$sum_attachment_ids;
$ret['post_count']=$count;
$ret['files']=$files;
return $ret;
}
public function get_image_from_post_content($image)
{
$ret['size']=0;
$ret['files']=array();
if(class_exists('DOMDocument'))
{
$doc = new DOMDocument();
$doc->loadHTML($image);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)");
}
else
{
preg_match('/src="([^"]+)/i',$image, $src);
$src= str_ireplace( 'src="', '', $src[0]);
}
$src=str_replace('https://','',$src);
$src=str_replace('http://','',$src);
$upload=wp_upload_dir();
$upload['baseurl']=str_replace('https://','',$upload['baseurl']);
$upload['baseurl']=str_replace('http://','',$upload['baseurl']);
$path=str_replace($upload['baseurl'],$upload['basedir'],$src);
if(file_exists($path))
{
$ret['size']+=filesize($path);
$ret['files'][]=$path;
}
return $ret;
}
public function get_attachment_size($attachment_id)
{
$files=array();
global $wpdb;
$postmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $attachment_id ) );
foreach ( $postmeta as $meta )
{
$upload_dir = wp_upload_dir();
if ( $upload_dir['error'] !== false )
{
continue;
}
$dir=$upload_dir['basedir'];
if ( apply_filters( 'wxr_export_skip_postmeta', false, $meta->meta_key, $meta ) ) {
continue;
}
if($meta->meta_key=='_wp_attached_file')
{
$bfound=false;
$name=$dir.DIRECTORY_SEPARATOR.$meta->meta_value;
if(!in_array($name,$files)&&file_exists($name))
{
$files[]=$name;
$bfound=true;
}
if($bfound)
{
$attach_meta = wp_get_attachment_metadata( $attachment_id );
if($attach_meta!=false)
{
if(isset($attach_meta['sizes']))
{
foreach ($attach_meta['sizes'] as $key=>$value)
{
$data=image_get_intermediate_size($attachment_id,$key);
$data['path']=ltrim($data['path'], './');
$name=$dir.DIRECTORY_SEPARATOR.$data['path'];
if(!in_array($name,$files)&&file_exists($name))
{
$files[]=$dir.DIRECTORY_SEPARATOR.$data['path'];
}
}
}
else
{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('attach_meta size not found id:'.$attachment_id,'notice');
}
}
}
}
}
$size=0;
if(!empty($files))
{
foreach ($files as $file)
{
$size+=filesize($file);
}
}
$ret['size']=$size;
$ret['files']=$files;
return $ret;
}
public function get_element_image($element_data,&$attachment_added_ids)
{
$element_image=array();
if(!empty($element_data['settings']))
{
$settings=$element_data['settings'];
if(isset($settings['image']))
{
if(!in_array($settings['image']['id'],$attachment_added_ids))
{
$element_image[]=$settings['image']['id'];
$attachment_added_ids[]=$settings['image']['id'];
}
}
}
if(!empty($element_data['elements']))
{
foreach ($element_data['elements'] as $element)
{
$temp=$this->get_element_image($element,$attachment_added_ids);
$element_image=array_merge($element_image,$temp);
}
}
return $element_image;
}
public function add_new_export()
{
$files=$this->get_export_files();
$backup_data=array();
$status=WPvivid_Exporter_taskmanager::get_backup_task_status($this->task['id']);
$backup_data['create_time']=$status['start_time'];
global $wpvivid_plugin;
$backup_data['log']=$wpvivid_plugin->wpvivid_log->log_file;
$backup_data['export']=$files;
$backup_data['id']=$this->task['id'];
$list = get_option('wpvivid_export_list',array());
$list[$this->task['id']]=$backup_data;
WPvivid_Setting::update_option('wpvivid_export_list',$list);
}
}
class WPvivid_Exporter_Item{
private $config;
public function __construct($options){
$this->config=$options;
}
public function get_download_export_files(){
$files = isset($this->config['export']) ? $this->config['export'] : array();
if(empty($files)){
$ret['result'] = WPVIVID_FAILED;
$ret['error']='Failed to get export files.';
}
else{
$ret['result'] = WPVIVID_SUCCESS;
$ret['files']=$files;
}
return $ret;
}
public function get_download_progress($backup_id, $files){
$this->config['local']['path'] = 'wpvividbackups';
foreach ($files as $file){
$need_download = false;
$file_path = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$this->config['local']['path'].DIRECTORY_SEPARATOR.$file;
$download_url = content_url().DIRECTORY_SEPARATOR.$this->config['local']['path'].DIRECTORY_SEPARATOR.$file;
if(file_exists($file_path)){
//need calc file size, then compare is need download
}
else{
$need_download = true;
}
if($need_download){
}
else{
$ret['result'] = WPVIVID_SUCCESS;
$ret['files'][$file]['status'] = 'completed';
$ret['files'][$file]['download_path'] = $file_path;
$ret['files'][$file]['download_url'] = $download_url;
ob_start();
?>
<div style="float:left;margin:10px 10px 10px 0;text-align:center; width:180px;">
<span>Part01</span><br>
<span><a class="wpvivid-download-export" id="trtr" name="<?php echo esc_attr($file); ?>" style="cursor: pointer;">Download</a></span><br>
<div style="width:100%;height:5px; background-color:#dcdcdc;">
<div style="background-color:#0085ba; float:left;width:100%;height:5px;"></div>
</div>
<span>size: </span><span>1K</span>
</div>
<?php
$html = ob_get_clean();
$ret['html']=$html;
}
}
return $ret;
}
}
class WPvivid_Exporter
{
public $task;
//public $config;
public function __construct($task_id=false,$task=false)
{
if($task_id!==false)
{
$this->task=new WPvivid_Exporter_task($task_id);
}
else if($task!==false)
{
$this->task=new WPvivid_Exporter_task(false,$task);
}
else
{
$this->task=new WPvivid_Exporter_task();
}
}
public function init_options($task_id)
{
$this->task=new WPvivid_Exporter_task($task_id);
}
public function export($task_id)
{
$this->init_options($task_id);
global $wpvivid_plugin;
$next=$this->task->get_next_posts();
$ret['result']='success';
WPvivid_Exporter_taskmanager::update_main_task_progress($task_id, 'export', 5, 0);
while($next!==false)
{
@set_time_limit(900);
$wpvivid_plugin->wpvivid_log->WriteLog('Prepare to export post '.$next['file_name'],'notice');
$this->task->update_sub_task_progress($next['file_name'],0,'Start export file '.$next['file_name']);
$ret=$this->export_post_to_xml($next['next_post_ids'], $next['attachment_ids'],$next['file_name'],$next['export_type']);
$wpvivid_plugin->wpvivid_log->WriteLog('Finished to export post '.$next['file_name'],'notice');
if($ret['result']=='success')
{
$wpvivid_plugin->wpvivid_log->WriteLog('Prepare to zip file '.$next['file_name'],'notice');
$next['json_info']['posts_count']=sizeof($next['next_post_ids']);
$ret=$this->zip_media_files($ret['xml_file_name'],$next['files'],$next['file_name'],$next['export_type'],$next['json_info']);
$wpvivid_plugin->wpvivid_log->WriteLog('Finished to zip file '.$next['file_name'],'notice');
if($ret['result']!='success')
{
$wpvivid_plugin->wpvivid_log->WriteLog('Failed to zip post '.$next['file_name'].' '.wp_json_encode($ret),'notice');
return $ret;
}
$this->task->update_sub_task_progress($next['file_name'],1,'Backing up '.$next['file_name'].' finished');
$this->task->update_finished_posts($next);
$this->task->update_export_files($ret['file_data']);
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Failed to export post '.$next['file_name'].' '.wp_json_encode($ret),'notice');
return $ret;
}
$next=$this->task->get_next_posts();
}
WPvivid_Exporter_taskmanager::update_main_task_progress($task_id, 'export', 100, 1);
return $ret;
}
public function export_post_to_xml($posts_ids,$attachment_ids,$file_name,$export_type)
{
$all_ids=array_merge($posts_ids,$attachment_ids);
//$xml_file_name=$file_name.'.xml';
$xml_file_name=$file_name.'_'.$export_type.'.xml';
//$files=array();
$export_folder = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR;
if(!file_exists($export_folder)) {
@mkdir($export_folder);
}
$path=$export_folder.DIRECTORY_SEPARATOR.$xml_file_name;
$ret['xml_file_name']=$path;
if(file_exists($path))
{
@wp_delete_file($path);
}
$this->write_header_to_file($path);
$this->write_authors_list_to_file($path,$all_ids);
$this->write_cat_to_file($path,$posts_ids);
global $wp_query,$wpdb;
// Fake being in the loop.
$wp_query->in_the_loop = true;
$task_id = $this->task->get_id();
while ( $next_posts = array_splice( $posts_ids, 0, 20 ) )
{
$where = 'WHERE ID IN (' . join( ',', $next_posts ) . ')';
$posts = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} $where" );
// Begin Loop.
foreach ( $posts as $post )
{
$this->write_post_to_file($path,$post);
}
}
WPvivid_Exporter_taskmanager::update_main_task_progress($task_id, 'export', 25, 0);
while ( $next_posts = array_splice( $attachment_ids, 0, 20 ) )
{
$where = 'WHERE ID IN (' . join( ',', $next_posts ) . ')';
$posts = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} $where" );
// Begin Loop.
foreach ( $posts as $post )
{
$this->write_media_post_to_file($path,$post);
//$post_files=$this->write_media_post_to_file($path,$post);
//$files=array_merge($post_files,$files);
}
}
WPvivid_Exporter_taskmanager::update_main_task_progress($task_id, 'export', 50, 0);
$this->write_footer_to_file($path);
//$ret['files']=$files;
$ret['result']='success';
return $ret;
}
private function zip_media_files($xml_file,$files,$file_name,$export_type,$json_info=false)
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR.DIRECTORY_SEPARATOR.$file_name.'_export_'.$export_type.'.zip';
$options['compress']['no_compress']=1;
$options['compress']['use_temp_file']=1;
$options['compress']['use_temp_size']=16;
$options['root_flag']=WPVIVID_BACKUP_ROOT_WP_CONTENT;
if(file_exists($path))
@wp_delete_file($path);
$archive = new WPvivid_PclZip($path);
if($json_info!==false) {
$temp_path = dirname($path).DIRECTORY_SEPARATOR.'wpvivid_export_package_info.json';
if(file_exists($temp_path)) {
@wp_delete_file($temp_path);
}
$json_info['create_time']=time();
$json_info['xml_file']=basename($xml_file);
$json_info['media_size']=0;
foreach ($files as $file)
{
$json_info['media_size']+=@filesize($file);
}
file_put_contents($temp_path,print_r(wp_json_encode($json_info),true));
$archive -> add($temp_path,WPVIVID_PCLZIP_OPT_REMOVE_PATH,dirname($temp_path));
@wp_delete_file($temp_path);
}
$ret =$archive -> add($xml_file,WPVIVID_PCLZIP_OPT_REMOVE_PATH,dirname($xml_file));
@wp_delete_file($xml_file);
if(!$ret)
{
return array('result'=>WPVIVID_FAILED,'error'=>$archive->errorInfo(true));
}
if(!empty($files)) {
$ret = $archive->add($files, WPVIVID_PCLZIP_OPT_REMOVE_PATH, WP_CONTENT_DIR, WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD, 16);
}
if(!$ret)
{
return array('result'=>WPVIVID_FAILED,'error'=>$archive->errorInfo(true));
}
$file_data = array();
$file_data['file_name'] = basename($path);
$file_data['size'] = filesize($path);
return array('result'=>WPVIVID_SUCCESS,'file_data'=>$file_data);
}
public function write_header_to_file($file)
{
$wxr_version=1.2;
$line='<?xml version="1.0" encoding="' . get_bloginfo( 'charset' ) . "\" ?>\n";
$line.='<!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your site. -->
<!-- It contains information about your site\'s posts, pages, comments, categories, and other content. -->
<!-- You may use this file to transfer that content from one site to another. -->
<!-- This file is not intended to serve as a complete backup of your site. -->
<!-- To import this information into a WordPress site follow these steps: -->
<!-- 1. Log in to that site as an administrator. -->
<!-- 2. Go to Tools: Import in the WordPress admin panel. -->
<!-- 3. Install the "WordPress" importer from the list. -->
<!-- 4. Activate & Run Importer. -->
<!-- 5. Upload this file using the form provided on that page. -->
<!-- 6. You will first be asked to map the authors in this export file to users -->
<!-- on the site. For each author, you may choose to map to an -->
<!-- existing user on the site or to create a new user. -->
<!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. -->
<!-- contained in this file into your site. -->';
$line.=apply_filters( 'the_generator', get_the_generator( 'export' ), 'export' ) . "\n";
$line.='
<rss version="2.0"
xmlns:excerpt="http://wordpress.org/export/'.$wxr_version.'/excerpt/"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:wp="http://wordpress.org/export/'.$wxr_version.'/"
> ';
$line.='
<channel>
<title>'.apply_filters( 'bloginfo_rss', get_bloginfo_rss( 'name' ), 'name' ).'</title>
<link>'.apply_filters( 'bloginfo_rss', get_bloginfo_rss( 'url' ), 'url' ).'</link>
<description>'.apply_filters( 'bloginfo_rss', get_bloginfo_rss( 'description' ), 'description' ).'</description>
<pubDate>'.gmdate( 'D, d M Y H:i:s +0000' ).'</pubDate>
<language>'.apply_filters( 'bloginfo_rss', get_bloginfo_rss( 'language' ), 'language' ).'</language>
<wp:wxr_version>'.$wxr_version.'</wp:wxr_version>
<wp:base_site_url>'.$this->wxr_site_url().'</wp:base_site_url>
<wp:base_blog_url>'.apply_filters( 'bloginfo_rss', get_bloginfo_rss( 'url' ), 'url' ).'</wp:base_blog_url>
';
file_put_contents($file,$line);
}
public function write_authors_list_to_file($file,$post_ids)
{
$line=$this->wxr_authors_list( $post_ids );
file_put_contents($file,$line,FILE_APPEND);
}
public function write_footer_to_file($file)
{
$line='
</channel>
</rss> ';
file_put_contents($file,$line,FILE_APPEND);
}
public function write_post_header_to_file($file,$post)
{
$is_sticky = is_sticky( $post->ID ) ? 1 : 0;
$post = get_post( $post );
$guid = isset( $post->guid ) ? get_the_guid( $post ) : '';
$id = isset( $post->ID ) ? $post->ID : 0;
$guid= apply_filters( 'the_guid', $guid, $id );
$item_header_line='
<item>
<title>
'.apply_filters( 'the_title_rss', $post->post_title ).'
</title>
<link>'.esc_url( apply_filters( 'the_permalink_rss', get_permalink($post->ID) ) ).'</link>
<pubDate>'.mysql2date( 'D, d M Y H:i:s +0000', get_post_time( 'Y-m-d H:i:s', true,$post ), false ).'</pubDate>
<dc:creator>'.$this->wxr_cdata( get_the_author_meta( 'login' ) ).'</dc:creator>
<guid isPermaLink="false">'.$guid.'</guid>
<description></description>
<content:encoded>'.$this->wxr_cdata( apply_filters( 'the_content_export', $post->post_content ) ).' </content:encoded>
<excerpt:encoded>'.$this->wxr_cdata( apply_filters( 'the_excerpt_export', $post->post_excerpt ) ).'</excerpt:encoded>
<wp:post_id>'.intval( $post->ID ).'</wp:post_id>
<wp:post_date>'.$this->wxr_cdata( $post->post_date ).'</wp:post_date>
<wp:post_date_gmt>'.$this->wxr_cdata( $post->post_date_gmt ).'</wp:post_date_gmt>
<wp:comment_status>'.$this->wxr_cdata( $post->comment_status ).'</wp:comment_status>
<wp:ping_status>'.$this->wxr_cdata( $post->ping_status ).'</wp:ping_status>
<wp:post_name>'.$this->wxr_cdata( $post->post_name ).'</wp:post_name>
<wp:status>'.$this->wxr_cdata( $post->post_status ).'</wp:status>
<wp:post_parent>'.intval( $post->post_parent ).'</wp:post_parent>
<wp:menu_order>'.intval( $post->menu_order ).'</wp:menu_order>
<wp:post_type>'.$this->wxr_cdata( $post->post_type ).'</wp:post_type>
<wp:post_password>'.$this->wxr_cdata( $post->post_password ).'</wp:post_password>
<wp:is_sticky>'.intval( $is_sticky ).'</wp:is_sticky>
';
if ( $post->post_type == 'attachment' )
$item_header_line.='<wp:attachment_url>'.$this->wxr_cdata( wp_get_attachment_url( $post->ID ) ).'</wp:attachment_url>';
file_put_contents($file,$item_header_line,FILE_APPEND);
$line=$this->wxr_post_taxonomy($post);
file_put_contents($file,$line,FILE_APPEND);
}
public function write_media_post_to_file($file,$post)
{
global $wpdb;
$postmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) );
$post_meta_line='';
$added_meta_key=array();
foreach ( $postmeta as $meta )
{
if(in_array($meta->meta_key,$added_meta_key))
continue;
$added_meta_key[]=$meta->meta_key;
$post_meta_line.='
<wp:postmeta>
<wp:meta_key>'.$this->wxr_cdata( $meta->meta_key ).'</wp:meta_key>
<wp:meta_value>'.$this->wxr_cdata( $meta->meta_value ).'</wp:meta_value>
</wp:postmeta>';
}
$this->write_post_header_to_file($file,$post);
file_put_contents($file,$post_meta_line,FILE_APPEND);
$_comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID ) );
$comments = array_map( 'get_comment', $_comments );
$line='';
foreach ( $comments as $c )
{
$line.='
<wp:comment>
<wp:comment_id>'.intval( $c->comment_ID ).'</wp:comment_id>
<wp:comment_author>'.$this->wxr_cdata( $c->comment_author ).'</wp:comment_author>
<wp:comment_author_email>'.$this->wxr_cdata( $c->comment_author_email ).'</wp:comment_author_email>
<wp:comment_author_url>'.esc_url_raw( $c->comment_author_url ).'</wp:comment_author_url>
<wp:comment_author_IP>'.$this->wxr_cdata( $c->comment_author_IP ).'</wp:comment_author_IP>
<wp:comment_date>'.$this->wxr_cdata( $c->comment_date ).'</wp:comment_date>
<wp:comment_date_gmt>'.$this->wxr_cdata( $c->comment_date_gmt ).'</wp:comment_date_gmt>
<wp:comment_content>'.$this->wxr_cdata( $c->comment_content ).'</wp:comment_content>
<wp:comment_approved>'.$this->wxr_cdata( $c->comment_approved ).'</wp:comment_approved>
<wp:comment_type>'.$this->wxr_cdata( $c->comment_type ).'</wp:comment_type>
<wp:comment_parent>'.intval( $c->comment_parent ).'</wp:comment_parent>
<wp:comment_user_id>'.intval( $c->user_id ).'</wp:comment_user_id>';
$c_meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->commentmeta WHERE comment_id = %d", $c->comment_ID ) );
foreach ( $c_meta as $meta )
{
if ( apply_filters( 'wxr_export_skip_commentmeta', false, $meta->meta_key, $meta ) )
{
continue;
}
$line.='
<wp:commentmeta>
<wp:meta_key>'.$this->wxr_cdata( $meta->meta_key ).'</wp:meta_key>
<wp:meta_value>'.$this->wxr_cdata( $meta->meta_value ).'</wp:meta_value>
</wp:commentmeta>';
}
$line.='
</wp:comment>';
}
file_put_contents($file,$line,FILE_APPEND);
$line='
</item>';
file_put_contents($file,$line,FILE_APPEND);
}
public function write_post_to_file($file,$post)
{
global $wpdb;
setup_postdata( $post );
$postmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) );
$post_meta_line='';
$added_meta_key=array();
foreach ( $postmeta as $meta )
{
//if ( apply_filters( 'wxr_export_skip_postmeta', false, $meta->meta_key, $meta ) ) {
// continue;
//}
if(in_array($meta->meta_key,$added_meta_key))
continue;
$added_meta_key[]=$meta->meta_key;
$post_meta_line.='
<wp:postmeta>
<wp:meta_key>'.$this->wxr_cdata( $meta->meta_key ).'</wp:meta_key>
<wp:meta_value>'.$this->wxr_cdata( $meta->meta_value ).'</wp:meta_value>
</wp:postmeta>';
}
$this->write_post_header_to_file($file,$post);
file_put_contents($file,$post_meta_line,FILE_APPEND);
$_comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID ) );
$comments = array_map( 'get_comment', $_comments );
$line='';
foreach ( $comments as $c )
{
$line.='
<wp:comment>
<wp:comment_id>'.intval( $c->comment_ID ).'</wp:comment_id>
<wp:comment_author>'.$this->wxr_cdata( $c->comment_author ).'</wp:comment_author>
<wp:comment_author_email>'.$this->wxr_cdata( $c->comment_author_email ).'</wp:comment_author_email>
<wp:comment_author_url>'.esc_url_raw( $c->comment_author_url ).'</wp:comment_author_url>
<wp:comment_author_IP>'.$this->wxr_cdata( $c->comment_author_IP ).'</wp:comment_author_IP>
<wp:comment_date>'.$this->wxr_cdata( $c->comment_date ).'</wp:comment_date>
<wp:comment_date_gmt>'.$this->wxr_cdata( $c->comment_date_gmt ).'</wp:comment_date_gmt>
<wp:comment_content>'.$this->wxr_cdata( $c->comment_content ).'</wp:comment_content>
<wp:comment_approved>'.$this->wxr_cdata( $c->comment_approved ).'</wp:comment_approved>
<wp:comment_type>'.$this->wxr_cdata( $c->comment_type ).'</wp:comment_type>
<wp:comment_parent>'.intval( $c->comment_parent ).'</wp:comment_parent>
<wp:comment_user_id>'.intval( $c->user_id ).'</wp:comment_user_id>';
$c_meta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->commentmeta WHERE comment_id = %d", $c->comment_ID ) );
foreach ( $c_meta as $meta )
{
if ( apply_filters( 'wxr_export_skip_commentmeta', false, $meta->meta_key, $meta ) )
{
continue;
}
$line.='
<wp:commentmeta>
<wp:meta_key>'.$this->wxr_cdata( $meta->meta_key ).'</wp:meta_key>
<wp:meta_value>'.$this->wxr_cdata( $meta->meta_value ).'</wp:meta_value>
</wp:commentmeta>';
}
$line.='
</wp:comment>';
}
file_put_contents($file,$line,FILE_APPEND);
$line='
</item>';
file_put_contents($file,$line,FILE_APPEND);
return true;
}
public function write_cat_to_file($file,$post_ids)
{
$cats = $tags = $terms = array();
$categories = (array) get_categories( array( 'object_ids' => $post_ids ) );
$tags = (array) get_tags( array( 'object_ids' => $post_ids ) );
$custom_taxonomies = get_taxonomies( array( '_builtin' => false ) );
$custom_terms = (array) get_terms( $custom_taxonomies,array( 'object_ids' => $post_ids ) );
// Put categories in order with no child going before its parent.
while ( $cat = array_shift( $categories ) ) {
if ( $cat->parent == 0 || isset( $cats[ $cat->parent ] ) ) {
$cats[ $cat->term_id ] = $cat;
} else {
$categories[] = $cat;
}
}
// Put terms in order with no child going before its parent.
while ( $t = array_shift( $custom_terms ) ) {
if ( $t->parent == 0 || isset( $terms[ $t->parent ] ) ) {
$terms[ $t->term_id ] = $t;
} else {
$custom_terms[] = $t;
}
}
unset( $categories, $custom_taxonomies, $custom_terms );
$line='';
foreach ($cats as $c)
{
$line.='<wp:category>
<wp:term_id>'.intval( $c->term_id ).'</wp:term_id>
<wp:category_nicename>'.$this->wxr_cdata( $c->slug ).'</wp:category_nicename>
<wp:category_parent>'.$this->wxr_cdata( $c->parent ? $cats[ $c->parent ]->slug : '' ).'</wp:category_parent>
'.$this->wxr_cat_name( $c ).'
'.$this->wxr_category_description( $c ).'
'.$this->wxr_term_meta( $c ).'
</wp:category>';
}
file_put_contents($file,$line,FILE_APPEND);
$line='';
foreach ( $tags as $t )
{
$line.='<wp:tag>
<wp:term_id>'.intval( $t->term_id ).'</wp:term_id>
<wp:tag_slug>'.$this->wxr_cdata( $t->slug ).'</wp:tag_slug>
'.$this->wxr_tag_name( $t ).'
'.$this->wxr_tag_description( $t ).'
'.$this->wxr_term_meta( $t ).'
</wp:tag>';
}
file_put_contents($file,$line,FILE_APPEND);
$line='';
foreach ( $terms as $t)
{
$line.='<wp:term>
<wp:term_id>'.$this->wxr_cdata( $t->term_id ).'</wp:term_id>
<wp:term_taxonomy>'.$this->wxr_cdata( $t->taxonomy ).'</wp:term_taxonomy>
<wp:term_slug>'.$this->wxr_cdata( $t->slug ).'</wp:term_slug>
<wp:term_parent>'.$this->wxr_cdata( $t->parent ? $terms[ $t->parent ]->slug : '' ).'</wp:term_parent>
'.$this->wxr_term_name( $t ).'
'.$this->wxr_term_description( $t ).'
'.$this->wxr_term_meta( $t ).'
</wp:term>';
}
}
private function wxr_cat_name( $category )
{
if ( empty( $category->name ) )
{
return '';
}
return '<wp:cat_name>' . $this->wxr_cdata( $category->name ) . "</wp:cat_name>";
}
private function wxr_category_description( $category ) {
if ( empty( $category->description ) ) {
return '<wp:category_description></wp:category_description>\n';
}
return '<wp:category_description>' . $this->wxr_cdata( $category->description ) . "</wp:category_description>";
}
private function wxr_tag_name( $tag ) {
if ( empty( $tag->name ) ) {
return '';
}
return '<wp:tag_name>' . $this->wxr_cdata( $tag->name ) . "</wp:tag_name>";
}
private function wxr_tag_description( $tag ) {
if ( empty( $tag->description ) ) {
return '';
}
return '<wp:tag_description>' . $this->wxr_cdata( $tag->description ) . "</wp:tag_description>";
}
private function wxr_term_name( $term ) {
if ( empty( $term->name ) ) {
return '';
}
return '<wp:term_name>' . $this->wxr_cdata( $term->name ) . "</wp:term_name>";
}
private function wxr_term_description( $term ) {
if ( empty( $term->description ) ) {
return '';
}
return "\t\t<wp:term_description>" . $this->wxr_cdata( $term->description ) . "</wp:term_description>";
}
private function wxr_term_meta( $term ) {
global $wpdb;
$termmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->termmeta WHERE term_id = %d", $term->term_id ) );
$line='';
foreach ( $termmeta as $meta )
{
/**
* Filters whether to selectively skip term meta used for WXR exports.
*
* Returning a truthy value to the filter will skip the current meta
* object from being exported.
*
* @since 4.6.0
*
* @param bool $skip Whether to skip the current piece of term meta. Default false.
* @param string $meta_key Current meta key.
* @param object $meta Current meta object.
*/
if ( ! apply_filters( 'wxr_export_skip_termmeta', false, $meta->meta_key, $meta ) )
{
$line.="\t\t<wp:termmeta>\n\t\t\t<wp:meta_key>".$this->wxr_cdata( $meta->meta_key )."</wp:meta_key>\n\t\t\t<wp:meta_value>".$this->wxr_cdata( $meta->meta_value )."</wp:meta_value>\n\t\t</wp:termmeta>\n";
}
}
return $line;
}
private function wxr_cdata( $str )
{
if ( ! seems_utf8( $str ) ) {
$str = utf8_encode( $str );
}
// $str = ent2ncr(esc_html($str));
$str = '<![CDATA[' . str_replace( ']]>', ']]]]><![CDATA[>', $str ) . ']]>';
return $str;
}
private function wxr_site_url() {
if ( is_multisite() ) {
// Multisite: the base URL.
return network_home_url();
} else {
// WordPress (single site): the blog URL.
return get_bloginfo_rss( 'url' );
}
}
private function wxr_authors_list( array $post_ids = null )
{
global $wpdb;
if ( ! empty( $post_ids ) ) {
$post_ids = array_map( 'absint', $post_ids );
$and = 'AND ID IN ( ' . implode( ', ', $post_ids ) . ')';
} else {
$and = '';
}
$authors = array();
$results = $wpdb->get_results( "SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_status != 'auto-draft' $and" );
foreach ( (array) $results as $result )
{
$authors[] = get_userdata( $result->post_author );
}
$authors = array_filter( $authors );
$line='';
foreach ( $authors as $author )
{
$line.= "\t<wp:author>";
$line.= '<wp:author_id>' . intval( $author->ID ) . '</wp:author_id>';
$line.= '<wp:author_login>' . $this->wxr_cdata( $author->user_login ) . '</wp:author_login>';
$line.= '<wp:author_email>' . $this->wxr_cdata( $author->user_email ) . '</wp:author_email>';
$line.= '<wp:author_display_name>' . $this->wxr_cdata( $author->display_name ) . '</wp:author_display_name>';
$line.= '<wp:author_first_name>' . $this->wxr_cdata( $author->first_name ) . '</wp:author_first_name>';
$line.= '<wp:author_last_name>' . $this->wxr_cdata( $author->last_name ) . '</wp:author_last_name>';
$line.= "</wp:author>\n";
}
return $line;
}
private function wxr_post_taxonomy($post)
{
$taxonomies = get_object_taxonomies( $post->post_type );
if ( empty( $taxonomies ) ) {
return;
}
$terms = wp_get_object_terms( $post->ID, $taxonomies );
$line='';
foreach ( (array) $terms as $term )
{
$line.= "\t\t<category domain=\"{$term->taxonomy}\" nicename=\"{$term->slug}\">" . $this->wxr_cdata( $term->name ) . "</category>\n";
}
return $line;
}
}
includes/class-wpvivid-crypt.php 0000644 00000014734 15132770567 0013043 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_crypt
{
private $public_key;
private $sym_key;
private $rij;
private $rsa;
public function __construct($public_key)
{
$this->public_key=$public_key;
include_once WPVIVID_PLUGIN_DIR . '/vendor/autoload.php';
$this->rij= new Crypt_Rijndael();
$this->rsa= new Crypt_RSA();
}
public function generate_key()
{
$this->sym_key = crypt_random_string(32);
$this->rij->setKey($this->sym_key);
}
public function encrypt_message($message)
{
$this->generate_key();
$key=$this->encrypt_key();
$len=str_pad(dechex(strlen($key)),3,'0', STR_PAD_LEFT);
$message=$this->rij->encrypt($message);
if($message===false)
return false;
$message_len = str_pad(dechex(strlen($message)), 16, '0', STR_PAD_LEFT);
return $len.$key.$message_len.$message;
}
public function encrypt_key()
{
$this->rsa->loadKey($this->public_key);
return $this->rsa->encrypt($this->sym_key);
}
public function decrypt_message($message)
{
$len = substr($message, 0, 3);
$len = hexdec($len);
$key = substr($message, 3, $len);
$cipherlen = substr($message, ($len + 3), 16);
$cipherlen = hexdec($cipherlen);
$data = substr($message, ($len + 19), $cipherlen);
$rsa = new Crypt_RSA();
$rsa->loadKey($this->public_key);
$key=$rsa->decrypt($key);
$rij = new Crypt_Rijndael();
$rij->setKey($key);
return $rij->decrypt($data);
}
public function encrypt_user_info($user,$pw)
{
$user_info['user']=$user;
$user_info['pw']=$pw;
$info=wp_json_encode($user_info);
$this->rsa->loadKey($this->public_key);
return $this->rsa->encrypt($info);
}
public function encrypt_user_token($user,$token)
{
$user_info['user']=$user;
$user_info['token']=$token;
$info=wp_json_encode($user_info);
$this->rsa->loadKey($this->public_key);
return $this->rsa->encrypt($info);
}
public function encrypt_token($token)
{
$this->rsa->loadKey($this->public_key);
return $this->rsa->encrypt($token);
}
}
class WPvivid_Crypt_File
{
private $key;
private $rij;
public function __construct($key)
{
include_once WPVIVID_PLUGIN_DIR . '/vendor/autoload.php';
$this->rij= new Crypt_Rijndael();
$this->key=$key;
}
public function encrypt($file)
{
$encrypted_path = dirname($file).'/encrypt_'.basename($file).'.tmp';
$data_encrypted = 0;
$buffer_size = 2097152;
$file_size = filesize($file);
$this->rij->setKey($this->key);
$this->rij->disablePadding();
$this->rij->enableContinuousBuffer();
if (file_exists($encrypted_path))
{
@wp_delete_file($encrypted_path);
}
$encrypted_handle = fopen($encrypted_path, 'wb+');
$file_handle = fopen($file, 'rb');
if($file_handle===false)
{
$ret['result']='failed';
$ret['error']=$file.' file not found';
return $ret;
}
while ($data_encrypted < $file_size)
{
$file_part = fread($file_handle, $buffer_size);
$length = strlen($file_part);
if (0 != $length % 16)
{
$pad = 16 - ($length % 16);
$file_part = str_pad($file_part, $length + $pad, chr($pad));
}
$encrypted_data = $this->rij->encrypt($file_part);
fwrite($encrypted_handle, $encrypted_data);
$data_encrypted += $buffer_size;
}
fclose($encrypted_handle);
fclose($file_handle);
$result_path = $file.'.crypt';
@rename($encrypted_path, $result_path);
$ret['result']='success';
$ret['file_path']=$result_path;
return $ret;
}
public function decrypt($file)
{
$file_handle = fopen($file, 'rb');
if($file_handle===false)
{
$ret['result']='failed';
$ret['error']=$file.' file not found';
return $ret;
}
$decrypted_path = dirname($file).'/decrypt_'.basename($file).'.tmp';
$decrypted_handle = fopen($decrypted_path, 'wb+');
$this->rij->setKey($this->key);
$this->rij->disablePadding();
$this->rij->enableContinuousBuffer();
$file_size = filesize($file);
$bytes_decrypted = 0;
$buffer_size =2097152;
while ($bytes_decrypted < $file_size)
{
$file_part = fread($file_handle, $buffer_size);
$length = strlen($file_part);
if (0 != $length % 16) {
$pad = 16 - ($length % 16);
$file_part = str_pad($file_part, $length + $pad, chr($pad));
}
$decrypted_data = $this->rij->decrypt($file_part);
$is_last_block = ($bytes_decrypted + strlen($decrypted_data) >= $file_size);
$write_bytes = min($file_size - $bytes_decrypted, strlen($decrypted_data));
if ($is_last_block)
{
$is_padding = false;
$last_byte = ord(substr($decrypted_data, -1, 1));
if ($last_byte < 16)
{
$is_padding = true;
for ($j = 1; $j<=$last_byte; $j++)
{
if (substr($decrypted_data, -$j, 1) != chr($last_byte))
$is_padding = false;
}
}
if ($is_padding)
{
$write_bytes -= $last_byte;
}
}
fwrite($decrypted_handle, $decrypted_data, $write_bytes);
$bytes_decrypted += $buffer_size;
}
// close the main file handle
fclose($decrypted_handle);
// close original file
fclose($file_handle);
$fullpath_new = preg_replace('/\.crypt$/', '', $file, 1).'.decrypted.zip';
@rename($decrypted_path, $fullpath_new);
$ret['result']='success';
$ret['file_path']=$fullpath_new;
return $ret;
}
} includes/class-wpvivid-function-realize.php 0000644 00000022741 15132770567 0015155 0 ustar 00 <?php
class WPvivid_Function_Realize
{
public function __construct()
{
}
public function _backup_cancel($task_id = '')
{
global $wpvivid_plugin;
try
{
$tasks = WPvivid_taskmanager::get_tasks();
$no_responds=false;
$task_id='';
foreach ($tasks as $task)
{
$task_id = $task['id'];
$backup_task=new WPvivid_Backup_Task_2($task['id']);
$status=$backup_task->get_status();
$file_name=$backup_task->task['options']['file_prefix'];
$path=$backup_task->task['options']['dir'];
$file =$path. DIRECTORY_SEPARATOR . $file_name . '_cancel';
touch($file);
$last_active_time=time()-$status['run_time'];
if($last_active_time>180)
{
$no_responds=true;
}
$timestamp = wp_next_scheduled('wpvivid_task_monitor_event_2', array($task_id));
if ($timestamp === false)
{
$wpvivid_plugin->backup2->add_monitor_event($task_id);
}
}
if($no_responds)
{
$ret['result'] = 'success';
$ret['no_response'] = true;
$ret['task_id'] = $task_id;
$ret['msg'] = __('The backup is not responding for a while, do you want to force cancel it?', 'wpvivid-backuprestore');
}
else
{
$ret['result'] = 'success';
$ret['no_response'] = false;
$ret['task_id'] = $task_id;
$ret['msg'] = __('The backup will be canceled after backing up the current chunk ends.', 'wpvivid-backuprestore');
}
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('result'=>'failed','error'=>$message);
}
/*
try
{
$tasks = WPvivid_taskmanager::get_tasks();
foreach ($tasks as $task)
{
$task_id = $task['id'];
$status=WPvivid_taskmanager::get_backup_task_status($task_id);
$time_spend=$status['run_time']-$status['start_time'];
$options=WPvivid_Setting::get_option('wpvivid_common_setting');
if(isset($options['max_execution_time']))
{
$limit=$options['max_execution_time'];
}
else
{
$limit=WPVIVID_MAX_EXECUTION_TIME;
}
if($time_spend > $limit * 2)
{
$file_name = WPvivid_taskmanager::get_task_options($task_id, 'file_prefix');
$backup_options = WPvivid_taskmanager::get_task_options($task_id, 'backup_options');
$file = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $backup_options['dir'] . DIRECTORY_SEPARATOR . $file_name . '_cancel';
touch($file);
if($wpvivid_plugin->wpvivid_log->log_file_handle==false)
{
$wpvivid_plugin->wpvivid_log->OpenLogFile(WPvivid_taskmanager::get_task_options($task_id,'log_file_name'));
}
$wpvivid_plugin->wpvivid_log->WriteLog('Backup cancelled. Twice the setting time.','notice');
$task=new WPvivid_Backup_Task($task_id);
$task->update_status('cancel');
$wpvivid_plugin->clean_backing_up_data_event($task_id);
WPvivid_Schedule::clear_monitor_schedule($task_id);
WPvivid_taskmanager::delete_task($task_id);
}
else
{
$file_name = WPvivid_taskmanager::get_task_options($task_id, 'file_prefix');
$backup_options = WPvivid_taskmanager::get_task_options($task_id, 'backup_options');
$file = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $backup_options['dir'] . DIRECTORY_SEPARATOR . $file_name . '_cancel';
touch($file);
$timestamp = wp_next_scheduled(WPVIVID_TASK_MONITOR_EVENT, array($task_id));
if ($timestamp === false) {
$wpvivid_plugin->add_monitor_event($task_id, 10);
}
}
$wpvivid_plugin->wpvivid_check_clear_litespeed_rule($task_id);
}
if (WPvivid_taskmanager::get_task($task_id) !== false) {
$file_name = WPvivid_taskmanager::get_task_options($task_id, 'file_prefix');
$backup_options = WPvivid_taskmanager::get_task_options($task_id, 'backup_options');
$file = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $backup_options['dir'] . DIRECTORY_SEPARATOR . $file_name . '_cancel';
touch($file);
}
$timestamp = wp_next_scheduled(WPVIVID_TASK_MONITOR_EVENT, array($task_id));
if ($timestamp === false) {
$wpvivid_plugin->add_monitor_event($task_id, 10);
}
$ret['result'] = 'success';
$ret['msg'] = __('The backup will be canceled after backing up the current chunk ends.', 'wpvivid-backuprestore');
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('result'=>'failed','error'=>$message);
}
catch (Error $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('result'=>'failed','error'=>$message);
}*/
return $ret;
}
public function _get_log_file($read_type, $param){
global $wpvivid_plugin;
$ret['result']='failed';
if($read_type == 'backuplist'){
$backup_id = $param;
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
if(!$backup) {
$ret['result']='failed';
$ret['error']=__('Retrieving the backup information failed while showing log. Please try again later.', 'wpvivid-backuprestore');
return $ret;
}
if(!file_exists($backup['log'])) {
$ret['result']='failed';
$ret['error']=__('The log not found.', 'wpvivid-backuprestore');
return $ret;
}
$ret['result']='success';
$ret['log_file']=$backup['log'];
}
else if($read_type == 'lastlog'){
$option = $param;
$log_file_name= $wpvivid_plugin->wpvivid_log->GetSaveLogFolder().$option.'_log.txt';
if(!file_exists($log_file_name))
{
$information['result']='failed';
$information['error']=__('The log not found.', 'wpvivid-backuprestore');
return $information;
}
$ret['result']='success';
$ret['log_file']=$log_file_name;
}
else if($read_type == 'tasklog'){
$backup_task_id = $param;
$option=WPvivid_taskmanager::get_task_options($backup_task_id,'log_file_name');
if(!$option) {
$information['result']='failed';
$information['error']=__('Retrieving the backup information failed while showing log. Please try again later.', 'wpvivid-backuprestore');
return $information;
}
$log_file_name= $wpvivid_plugin->wpvivid_log->GetSaveLogFolder().$option.'_log.txt';
if(!file_exists($log_file_name)) {
$information['result']='failed';
$information['error']=__('The log not found.', 'wpvivid-backuprestore');
return $information;
}
$ret['result']='success';
$ret['log_file']=$log_file_name;
}
return $ret;
}
public function _set_remote($remote){
WPvivid_Setting::update_option('wpvivid_upload_setting',$remote['upload']);
$history=WPvivid_Setting::get_option('wpvivid_user_history');
$history['remote_selected']=$remote['history']['remote_selected'];
WPvivid_Setting::update_option('wpvivid_user_history',$history);
}
public function _get_default_remote_storage(){
$remote_storage_type = '';
$remoteslist=WPvivid_Setting::get_all_remote_options();
$default_remote_storage='';
foreach ($remoteslist['remote_selected'] as $value) {
$default_remote_storage=$value;
}
foreach ($remoteslist as $key=>$value)
{
if($key === $default_remote_storage)
{
$remote_storage_type=$value['type'];
}
}
return $remote_storage_type;
}
} includes/class-wpvivid-db-method.php 0000644 00000021771 15132770567 0013544 0 ustar 00 <?php
class WPvivid_DB_Method
{
public $db_handle;
public $type;
public function connect_db()
{
$common_setting = WPvivid_Setting::get_setting(false, 'wpvivid_common_setting');
$db_connect_method = isset($common_setting['options']['wpvivid_common_setting']['db_connect_method']) ? $common_setting['options']['wpvivid_common_setting']['db_connect_method'] : 'wpdb';
if($db_connect_method === 'wpdb'){
global $wpdb;
$this->db_handle=$wpdb;
$this->type='wpdb';
return array('result'=>WPVIVID_SUCCESS);
}
else{
if(class_exists('PDO')) {
$extensions=get_loaded_extensions();
if(array_search('pdo_mysql',$extensions)) {
$res = explode(':',DB_HOST);
$db_host = $res[0];
$db_port = empty($res[1])?'':$res[1];
if(!empty($db_port)) {
$dsn='mysql:host=' . $db_host . ';port=' . $db_port . ';dbname=' . DB_NAME;
}
else{
$dsn='mysql:host=' . $db_host . ';dbname=' . DB_NAME;
}
$this->db_handle=new PDO($dsn, DB_USER, DB_PASSWORD);
$this->type='pdo_mysql';
return array('result'=>WPVIVID_SUCCESS);
}
else{
return array('result'=>WPVIVID_FAILED, 'error'=>'The pdo_mysql extension is not detected. Please install the extension first or choose wpdb option for Database connection method.');
}
}
else{
return array('result'=>WPVIVID_FAILED, 'error'=>'The pdo_mysql extension is not detected. Please install the extension first or choose wpdb option for Database connection method.');
}
}
}
public function check_db($fcgi)
{
$ret=$this->connect_db();
if($ret['result']==WPVIVID_FAILED)
{
return $ret;
}
if($this->type=='pdo_mysql')
{
return $this->check_db_pdo($fcgi);
}
else if($this->type=='wpdb')
{
return $this->check_db_wpdb($fcgi);
}
return array('result' => WPVIVID_FAILED,'error' => 'db handle type not found.');
}
public function check_db_pdo($fcgi)
{
$ret['alert_db']=false;
$ret['result']=WPVIVID_SUCCESS;
$ret['big_tables']=array();
$db_info=array();
$sth = $this->db_handle->query('SHOW TABLE STATUS');
$dbSize = 0;
$sum_rows=0;
$rows = $sth->fetchAll();
foreach ($rows as $row)
{
global $wpdb;
if (is_multisite() && !defined('MULTISITE'))
{
$prefix = $wpdb->base_prefix;
} else {
$prefix = $wpdb->get_blog_prefix(0);
}
if(preg_match('/^(?!'.$prefix.')/', $row["Name"]) == 1){
continue;
}
$db_info[$row["Name"]]["Rows"]=$row["Rows"];
$db_info[$row["Name"]]["Data_length"]=size_format($row["Data_length"]+$row["Index_length"],2);
if($row["Rows"]>1000000)
{
$ret['big_tables'][$row["Name"]]['Rows']=$row["Rows"];
$ret['big_tables'][$row["Name"]]['Data_length']=size_format($row["Data_length"]+$row["Index_length"],2);
}
$sum_rows+=$row["Rows"];
$dbSize+=$row["Data_length"]+$row["Index_length"];
}
if($fcgi)
{
$alter_sum_rows=4000000;
}
else
{
$alter_sum_rows=4000000*3;
}
$memory_limit = ini_get('memory_limit');
$ret['memory_limit']=$memory_limit;
$memory_limit = trim($memory_limit);
$memory_limit_int = (int) $memory_limit;
$last = strtolower(substr($memory_limit, -1));
if($last == 'g')
$memory_limit_int = $memory_limit_int*1024*1024*1024;
if($last == 'm')
$memory_limit_int = $memory_limit_int*1024*1024;
if($last == 'k')
$memory_limit_int = $memory_limit_int*1024;
if($dbSize>($memory_limit_int*0.9))
{
$max_rows=0;
}
else
{
$max_rows=(($memory_limit_int*0.9)-$dbSize)/49;
}
$max_rows=max($max_rows,1048576);
if($sum_rows>$alter_sum_rows||$sum_rows>$max_rows)
{
//big db alert
$ret['alert_db']=true;
$ret['sum_rows']=$sum_rows;
$ret['db_size']=size_format($dbSize,2);
if($fcgi)
$ret['alter_fcgi']=true;
}
$ret['db_size']=size_format($dbSize,2);
return $ret;
}
public function check_db_wpdb($fcgi)
{
$ret['alert_db']=false;
$ret['result']=WPVIVID_SUCCESS;
$ret['big_tables']=array();
$db_info=array();
global $wpdb;
$result=$wpdb->get_results('SHOW TABLE STATUS',ARRAY_A);
//$sth = $this->db_handle->query('SHOW TABLE STATUS');
$dbSize = 0;
$sum_rows=0;
//$rows = $sth->fetchAll();
foreach ($result as $row)
{
global $wpdb;
if (is_multisite() && !defined('MULTISITE'))
{
$prefix = $wpdb->base_prefix;
} else {
$prefix = $wpdb->get_blog_prefix(0);
}
if(preg_match('/^(?!'.$prefix.')/', $row["Name"]) == 1){
continue;
}
$db_info[$row["Name"]]["Rows"]=$row["Rows"];
$db_info[$row["Name"]]["Data_length"]=size_format($row["Data_length"]+$row["Index_length"],2);
if($row["Rows"]>1000000)
{
$ret['big_tables'][$row["Name"]]['Rows']=$row["Rows"];
$ret['big_tables'][$row["Name"]]['Data_length']=size_format($row["Data_length"]+$row["Index_length"],2);
}
$sum_rows+=$row["Rows"];
$dbSize+=$row["Data_length"]+$row["Index_length"];
}
if($fcgi)
{
$alter_sum_rows=4000000;
}
else
{
$alter_sum_rows=4000000*3;
}
$memory_limit = ini_get('memory_limit');
$ret['memory_limit']=$memory_limit;
$memory_limit = trim($memory_limit);
$memory_limit_int = (int) $memory_limit;
$last = strtolower(substr($memory_limit, -1));
if($last == 'g')
$memory_limit_int = $memory_limit_int*1024*1024*1024;
if($last == 'm')
$memory_limit_int = $memory_limit_int*1024*1024;
if($last == 'k')
$memory_limit_int = $memory_limit_int*1024;
if($dbSize>($memory_limit_int*0.9))
{
$max_rows=0;
}
else
{
$max_rows=(($memory_limit_int*0.9)-$dbSize)/49;
}
$max_rows=max($max_rows,1048576);
if($sum_rows>$alter_sum_rows||$sum_rows>$max_rows)
{
//big db alert
$ret['alert_db']=true;
$ret['sum_rows']=$sum_rows;
$ret['db_size']=size_format($dbSize,2);
if($fcgi)
$ret['alter_fcgi']=true;
}
$ret['db_size']=size_format($dbSize,2);
return $ret;
}
public function get_sql_mode()
{
try {
$ret['result'] = WPVIVID_SUCCESS;
$ret['mysql_mode'] = '';
global $wpdb;
$result = $wpdb->get_results('SELECT @@SESSION.sql_mode', ARRAY_A);
foreach ($result as $row) {
$ret['mysql_mode'] = $row["@@SESSION.sql_mode"];
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('result'=>'failed','error'=>$message);
}
return $ret;
}
public function get_mysql_version()
{
global $wpdb;
$mysql_version = $wpdb->db_version();
return $mysql_version;
}
public function check_max_allowed_packet()
{
global $wpvivid_plugin,$wpdb;
$max_allowed_packet = (int) $wpdb->get_var("SELECT @@session.max_allowed_packet");
if($max_allowed_packet<1048576)
{
$wpvivid_plugin->wpvivid_log->WriteLog('warning: max_allowed_packet less than 1M :'.size_format($max_allowed_packet,2),'notice');
}
else if($max_allowed_packet<33554432)
{
$wpvivid_plugin->wpvivid_log->WriteLog('max_allowed_packet less than 32M :'.size_format($max_allowed_packet,2),'notice');
}
}
} includes/class-wpvivid-taskmanager.php 0000644 00000055220 15132770567 0014172 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_taskmanager
{
public static function new_backup_task($option,$type,$action='backup')
{
$id=uniqid('wpvivid-');
$task['id']=$id;
$task['action']=$action;
$task['type']=$type;
$task['status']['start_time']=time();
$task['status']['run_time']=time();
$task['status']['timeout']=time();
$task['status']['str']='ready';
$task['status']['resume_count']=0;
$task['options']=$option;
$task['options']['file_prefix']=$task['id'].'_'.gmdate('Y-m-d-H-i',$task['status']['start_time']);
$task['options']['log_file_name']=$id.'_backup';
$log=new WPvivid_Log();
$log->CreateLogFile($task['options']['log_file_name'],'no_folder','backup');
$log->CloseFile();
$task['data']['doing']='backup';
$task['data']['backup']['doing']='';
$task['data']['backup']['finished']=0;
$task['data']['backup']['progress']=0;
$task['data']['backup']['job_data']=array();
$task['data']['backup']['sub_job']=array();
$task['data']['backup']['db_size']='0';
$task['data']['backup']['files_size']['sum']='0';
$task['data']['upload']['doing']='';
$task['data']['upload']['finished']=0;
$task['data']['upload']['progress']=0;
$task['data']['upload']['job_data']=array();
$task['data']['upload']['sub_job']=array();
WPvivid_Setting::update_task($id,$task);
$ret['result']='success';
$ret['task_id']=$task['id'];
return $ret;
}
public static function get_backup_task_prefix($task_id)
{
$tasks=WPvivid_Setting::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task = $tasks[$task_id];
return $task['options']['file_prefix'];
}
else
{
return false;
}
}
public static function new_upload_task($option,$type)
{
$id=uniqid('wpvivid-');
$task['id']=$id;
$task['action']='upload';
$task['type']='Manual';
$task['type']=$type;
$task['status']['start_time']=time();
$task['status']['run_time']=time();
$task['status']['timeout']=time();
$task['status']['str']='ready';
$task['status']['resume_count']=0;
$task['options']=$option;
$task['options']['file_prefix']=$task['id'].'_'.gmdate('Y-m-d-H-i',$task['status']['start_time']);
$task['options']['log_file_name']=$id.'_backup';
$log=new WPvivid_Log();
$log->CreateLogFile($task['options']['log_file_name'],'no_folder','backup');
$log->CloseFile();
$task['data']['doing']='upload';
$task['data']['doing']='backup';
$task['data']['backup']['doing']='';
$task['data']['backup']['finished']=1;
$task['data']['backup']['progress']=100;
$task['data']['backup']['job_data']=array();
$task['data']['backup']['sub_job']=array();
$task['data']['backup']['db_size']='0';
$task['data']['backup']['files_size']['sum']='0';
$task['data']['upload']['doing']='';
$task['data']['upload']['finished']=0;
$task['data']['upload']['progress']=0;
$task['data']['upload']['job_data']=array();
$task['data']['upload']['sub_job']=array();
WPvivid_Setting::update_task($id,$task);
$ret['result']='success';
$ret['task_id']=$task['id'];
return $ret;
}
public static function delete_ready_task()
{
$tasks=WPvivid_Setting::get_tasks();
$delete_ids=array();
if(!empty($tasks))
{
foreach ($tasks as $task)
{
if($task['status']['str']=='ready')
{
$delete_ids[]=$task['id'];
}
}
}
foreach ($delete_ids as $id)
{
unset($tasks[$id]);
}
if(!empty($delete_ids))
WPvivid_Setting::update_option('wpvivid_task_list',$tasks);
}
public static function is_task_canceled($task_id)
{
if(self::get_task($task_id)!==false)
{
$file_name = self::get_task_options($task_id, 'file_prefix');
$backup_options = self::get_task_options($task_id, 'backup_options');
$file = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $backup_options['dir'] . DIRECTORY_SEPARATOR . $file_name . '_cancel';
if (file_exists($file))
{
return true;
}
}
return false;
}
public static function get_backup_tasks_info($action){
$tasks=WPvivid_Setting::get_tasks();
$ret=array();
foreach ($tasks as $task)
{
if($task['action']==$action)
{
$ret[$task['id']]['status']=self::get_backup_tasks_status($task['id']);
$ret[$task['id']]['is_canceled']=self::is_task_canceled($task['id']);
$ret[$task['id']]['size']=self::get_backup_size($task['id']);
$ret[$task['id']]['data']=self::get_backup_tasks_progress($task['id']);
}
}
return $ret;
}
public static function get_backup_tasks_status($task_id){
$tasks=WPvivid_Setting::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task = $tasks[$task_id];
return $task['status'];
}
else
{
return false;
}
}
public static function get_backup_size($task_id){
$tasks=WPvivid_Setting::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task = $tasks[$task_id];
if(array_key_exists('db_size',$task['data']['backup']))
{
$ret['db_size']=$task['data']['backup']['db_size'];
$ret['files_size']=$task['data']['backup']['files_size'];
return $ret;
}
else
{
return false;
}
}
else
{
return false;
}
}
public static function get_backup_tasks_progress($task_id){
$tasks=WPvivid_Setting::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task = $tasks[$task_id];
$current_time=gmdate("Y-m-d H:i:s");
$create_time=gmdate("Y-m-d H:i:s",$task['status']['start_time']);
$time_diff=strtotime($current_time)-strtotime($create_time);
$running_time='';
if(gmdate("G",$time_diff) > 0){
$running_time .= gmdate("G",$time_diff).' hour(s)';
}
if(intval(gmdate("i",$time_diff)) > 0){
$running_time .= intval(gmdate("i",$time_diff)).' min(s)';
}
if(intval(gmdate("s",$time_diff)) > 0){
$running_time .= intval(gmdate("s",$time_diff)).' second(s)';
}
$next_resume_time=WPvivid_Schedule::get_next_resume_time($task['id']);
$ret['type']=$task['data']['doing'];
$ret['progress']=$task['data'][$ret['type']]['progress'];
$ret['doing']=$task['data'][$ret['type']]['doing'];
if(isset($task['data'][$ret['type']]['sub_job'][$ret['doing']]['progress']))
$ret['descript']=$task['data'][$ret['type']]['sub_job'][$ret['doing']]['progress'];
else
$ret['descript']='';
if(isset($task['data'][$ret['type']]['sub_job'][$ret['doing']]['upload_data']))
$ret['upload_data']=$task['data'][$ret['type']]['sub_job'][$ret['doing']]['upload_data'];
$task['data'][$ret['type']]['sub_job'][$ret['doing']]['upload_data']=false;
$ret['running_time']=$running_time;
$ret['running_stamp']=$time_diff;
$ret['next_resume_time']=$next_resume_time;
return $ret;
}
else
{
return false;
}
}
public static function get_backup_task_status($task_id)
{
$tasks=WPvivid_Setting::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task = $tasks[$task_id];
return $task['status'];
}
else
{
return false;
}
}
public static function update_backup_task_status($task_id,$reset_start_time=false,$status='',$reset_timeout=false,$resume_count=false,$error='')
{
$tasks=WPvivid_Setting::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task = $tasks[$task_id];
$task['status']['run_time']=time();
if($reset_start_time)
$task['status']['start_time']=time();
if(!empty($status))
{
$task['status']['str']=$status;
}
if($reset_timeout)
$task['status']['timeout']=time();
if($resume_count!==false)
{
$task['status']['resume_count']=$resume_count;
}
if(!empty($error))
{
$task['status']['error']=$error;
}
WPvivid_Setting::update_task($task_id,$task);
return $task;
}
else
{
return false;
}
}
public static function get_backup_task_error($task_id)
{
$tasks=WPvivid_Setting::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task = $tasks[$task_id];
return $task['status']['error'];
}
else
{
return false;
}
}
public static function get_task_options($task_id,$option_names)
{
$tasks=WPvivid_Setting::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task=$tasks[$task_id];
if(is_array($option_names))
{
$options=array();
foreach ($option_names as $name)
{
$options[$name]=$task['options'][$name];
}
return $options;
}
else
{
return $task['options'][$option_names];
}
}
else
{
return false;
}
}
public static function update_task_options($task_id,$option_name,$option)
{
$tasks=WPvivid_Setting::get_tasks();
if(array_key_exists ($task_id,$tasks))
{
$task=$tasks[$task_id];
$task['options'][$option_name]=$option;
WPvivid_Setting::update_task($task_id,$task);
return true;
}
else
{
return false;
}
}
public static function update_backup_main_task_progress($task_id,$job_name,$progress,$finished,$job_data=array())
{
$task=self::get_task($task_id);
if($task!==false)
{
$task['status']['run_time']=time();
$task['status']['str']='running';
$task['data']['doing']=$job_name;
$task['data'][$job_name]['finished']=$finished;
$task['data'][$job_name]['progress']=$progress;
$task['data'][$job_name]['job_data']=$job_data;
WPvivid_Setting::update_task($task_id,$task);
}
}
public static function update_backup_sub_task_progress($task_id,$job_name,$sub_job_name,$finished,$progress,$job_data=array(),$upload_data=array())
{
$task=self::get_task($task_id);
if($task!==false)
{
$task['status']['run_time']=time();
$task['status']['str']='running';
$task['data']['doing']=$job_name;
if(empty($sub_job_name))
{
$sub_job_name=$task['data'][$job_name]['doing'];
}
$task['data'][$job_name]['doing']=$sub_job_name;
$task['data'][$job_name]['sub_job'][$sub_job_name]['finished']=$finished;
if(!empty($progress))
$task['data'][$job_name]['sub_job'][$sub_job_name]['progress']=$progress;
if(!empty($job_data))
{
$task['data'][$job_name]['sub_job'][$sub_job_name]['job_data']=$job_data;
}
else
{
if(!isset($task['data'][$job_name]['sub_job'][$sub_job_name]['job_data']))
{
$task['data'][$job_name]['sub_job'][$sub_job_name]['job_data']=array();
}
}
if(!empty($upload_data)){
$task['data'][$job_name]['sub_job'][$sub_job_name]['upload_data']=$upload_data;
}
else{
if(!isset($task['data'][$job_name]['sub_job'][$sub_job_name]['upload_data'])){
$task['data'][$job_name]['sub_job'][$sub_job_name]['upload_data']=array();
}
}
WPvivid_Setting::update_task($task_id,$task);
}
}
public static function get_backup_main_task_progress($task_id,$job_name='')
{
$task=self::get_task($task_id);
if(empty($job_name))
{
$job_name=$task['data']['doing'];
return $job_name;
}
if(array_key_exists($job_name,$task['data']))
{
return $task['data'][$job_name];
}
return false;
}
public static function get_backup_sub_task_progress($task_id,$job_name,$sub_job_name)
{
$task=self::get_task($task_id);
if(array_key_exists($job_name,$task['data']))
{
if(array_key_exists($sub_job_name,$task['data'][$job_name]['sub_job']))
{
return $task['data'][$job_name]['sub_job'][$sub_job_name];
}
}
return false;
}
public static function update_backup_db_task_info($task_id,$db_info)
{
$task=self::get_task($task_id);
$task['data']['backup']['sub_job']['backup_db']['db_info']=$db_info;
WPvivid_Setting::update_task($task_id,$task);
}
public static function update_file_and_db_info($task_id,$db_size,$files_size)
{
$task=self::get_task($task_id);
$task['data']['backup']['db_size']=$db_size;
$task['data']['backup']['files_size']=$files_size;
WPvivid_Setting::update_task($task_id,$task);
}
public static function update_download_cache($backup_id,$cache)
{
$default = array();
$options = get_option('wpvivid_download_cache', $default);
$options[$backup_id]['cache']=$cache;
WPvivid_Setting::update_option('wpvivid_download_cache',$options);
}
public static function get_download_cache($backup_id)
{
$default = array();
$options = get_option('wpvivid_download_cache', $default);
if(array_key_exists($backup_id,$options))
{
return $options[$backup_id]['cache'];
}
return false;
}
public static function get_task($id)
{
$tasks=WPvivid_Setting::get_tasks();
if(array_key_exists ($id,$tasks))
{
$task=$tasks[$id];
return $task;
}
else
{
return false;
}
}
public static function get_tasks()
{
$tasks=WPvivid_Setting::get_tasks();
return $tasks;
}
public static function get_tasks_by_action($action)
{
$tasks=WPvivid_Setting::get_tasks();
$ret=array();
foreach ($tasks as $task)
{
if($task['action']==$action)
{
$ret[$task['id']]=$task;
}
}
return $ret;
}
public static function is_tasks_backup_running()
{
$tasks=WPvivid_Setting::get_tasks();
foreach ($tasks as $task)
{
if ($task['status']['str']=='running'||$task['status']['str']=='no_responds')
{
return true;
}
}
return false;
}
public static function get_tasks_backup_running()
{
$tasks=WPvivid_Setting::get_tasks();
$ret=array();
foreach ($tasks as $task)
{
if($task['action']=='backup')
{
if ($task['status']['str']=='running')
{
$ret[$task['id']]=$task;
}
}
}
return $ret;
}
public static function update_task($task)
{
WPvivid_Setting::update_task($task['id'],$task);
}
public static function delete_task($id)
{
WPvivid_Setting::delete_task($id);
}
public static function mark_task($id)
{
$tasks=WPvivid_Setting::get_tasks();
if(array_key_exists ($id,$tasks))
{
$task=$tasks[$id];
$task['marked']=1;
WPvivid_Setting::update_task($id,$task);
return true;
}
else
{
return false;
}
}
public static function delete_marked_task()
{
$has_marked = 0;
$tasks=WPvivid_Setting::get_tasks();
$delete_ids=array();
foreach ($tasks as $task)
{
if(isset($task['marked']))
{
$delete_ids[]=$task['id'];
}
}
foreach ($delete_ids as $id)
{
unset($tasks[$id]);
$has_marked = 1;
}
WPvivid_Setting::update_option('wpvivid_task_list',$tasks);
return $has_marked;
}
public static function delete_out_of_date_finished_task()
{
$tasks=WPvivid_Setting::get_tasks();
$delete_ids=array();
if(!empty($tasks))
{
foreach ($tasks as $task)
{
if($task['status']['str']=='error'||$task['status']['str']=='completed')
{
if(time()-$task['status']['run_time']>60)
{
$delete_ids[]=$task['id'];
}
}
}
}
foreach ($delete_ids as $id)
{
unset($tasks[$id]);
}
WPvivid_Setting::update_option('wpvivid_task_list',$tasks);
}
public static function delete_all_task()
{
WPvivid_Setting::delete_option('wpvivid_task_list');
}
public static function is_backup_task_timeout($task)
{
$current_time=gmdate("Y-m-d H:i:s");
$run_time=gmdate("Y-m-d H:i:s", $task['data']['run_time']);
$running_time=strtotime($current_time)-strtotime($run_time);
if($running_time>$task['data']['options']['max_execution_time'])
{
return true;
}
else
{
return false;
}
}
public static function new_download_task_v2($file_name)
{
$default = array();
wp_cache_delete('notoptions', 'options');
wp_cache_delete('alloptions', 'options');
wp_cache_delete('wpvivid_download_task_v2', 'options');
$options = get_option('wpvivid_download_task_v2', $default);
$task['file_name']=$file_name;
$task['start_time']=time();
$task['run_time']=time();
$task['progress_text']='start download file:'.$file_name;
$task['status']='running';
$task['error']='';
$options[$file_name]=$task;
WPvivid_Setting::update_option('wpvivid_download_task_v2',$options);
return $task;
}
public static function is_download_task_running_v2($file_name)
{
$default = array();
$options = get_option('wpvivid_download_task_v2', $default);
if(empty($options))
{
return false;
}
if(array_key_exists($file_name,$options))
{
$task=$options[$file_name];
if($task['status'] === 'error')
{
return false;
}
if(time()-$task['run_time']>60)
{
return false;
}
else {
return true;
}
}
return false;
}
public static function update_download_task_v2(&$task,$progress_text,$status='',$error='')
{
$default = array();
wp_cache_delete('notoptions', 'options');
wp_cache_delete('alloptions', 'options');
wp_cache_delete('wpvivid_download_task_v2', 'options');
$options = get_option('wpvivid_download_task_v2', $default);
$file_name=$task['file_name'];
$task['run_time']=time();
$task['progress_text']=$progress_text;
if($status!='')
{
$task['status']=$status;
if($error!='')
{
$task['error']=$error;
}
}
$options[$file_name]=$task;
WPvivid_Setting::update_option('wpvivid_download_task_v2',$options);
}
public static function get_download_task_v2($file_name)
{
$default = array();
$options = get_option('wpvivid_download_task_v2', $default);
if(empty($options))
{
return false;
}
if(array_key_exists($file_name,$options))
{
if(time()-$options[$file_name]['run_time']>60)
{
$options[$file_name]['status']='timeout';
$options[$file_name]['error']='time out';
}
return $options[$file_name];
}
return false;
}
public static function delete_download_task_v2($file_name)
{
$default = array();
$options = get_option('wpvivid_download_task_v2', $default);
if(empty($options))
{
return false;
}
if(array_key_exists($file_name,$options))
{
unset($options[$file_name]);
WPvivid_Setting::update_option('wpvivid_download_task_v2',$options);
return true;
}
return false;
}
public static function wpvivid_reset_backup_retry_times($task_id)
{
$task=self::get_task($task_id);
if($task!==false)
{
$task['status']['resume_count']=0;
WPvivid_Setting::update_task($task_id,$task);
}
}
} includes/class-wpvivid-tools.php 0000644 00000011061 15132770567 0013030 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_tools
{
public static function clean_junk_cache(){
$home_url_prefix=get_home_url();
$parse = wp_parse_url($home_url_prefix);
$tmppath='';
if(isset($parse['path'])) {
$tmppath=str_replace('/','_',$parse['path']);
}
$home_url_prefix = $parse['host'].$tmppath;
$path = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
$handler=opendir($path);
if($handler===false)
{
return ;
}
while(($filename=readdir($handler))!==false)
{
/*if(is_dir($path.DIRECTORY_SEPARATOR.$filename) && preg_match('#temp-'.$home_url_prefix.'_'.'#',$filename))
{
WPvivid_tools::deldir($path.DIRECTORY_SEPARATOR.$filename,'',true);
}
if(is_dir($path.DIRECTORY_SEPARATOR.$filename) && preg_match('#temp-'.'#',$filename))
{
WPvivid_tools::deldir($path.DIRECTORY_SEPARATOR.$filename,'',true);
}*/
if(preg_match('#pclzip-.*\.tmp#', $filename)){
@wp_delete_file($path.DIRECTORY_SEPARATOR.$filename);
}
if(preg_match('#pclzip-.*\.gz#', $filename)){
@wp_delete_file($path.DIRECTORY_SEPARATOR.$filename);
}
}
@closedir($handler);
}
public static function deldir($path,$exclude='',$flag = false)
{
if(!is_dir($path))
{
return ;
}
$handler=opendir($path);
if(empty($handler))
return ;
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($path.DIRECTORY_SEPARATOR.$filename)){
if(empty($exclude)||WPvivid_tools::regex_match($exclude['directory'],$path.DIRECTORY_SEPARATOR.$filename ,0)){
self::deldir( $path.DIRECTORY_SEPARATOR.$filename ,$exclude, $flag);
@rmdir( $path.DIRECTORY_SEPARATOR.$filename );
}
}else{
if(empty($exclude)||WPvivid_tools::regex_match($exclude['file'],$path.DIRECTORY_SEPARATOR.$filename ,0)){
@wp_delete_file($path.DIRECTORY_SEPARATOR.$filename);
}
}
}
}
if($handler)
@closedir($handler);
if($flag)
@rmdir($path);
}
public static function regex_match($regex_array,$string,$mode)
{
if(empty($regex_array))
{
return true;
}
if($mode==0)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return false;
}
}
return true;
}
if($mode==1)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return true;
}
}
return false;
}
return true;
}
public static function GetSaveLogFolder()
{
$options = get_option('wpvivid_common_setting',array());
if(!isset($options['log_save_location']))
{
//WPvivid_Setting::set_default_common_option();
$options['log_save_location']=WPVIVID_DEFAULT_LOG_DIR;
update_option('wpvivid_common_setting', $options, 'no');
$options = get_option('wpvivid_common_setting',array());
}
if(!is_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['log_save_location']))
{
@mkdir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['log_save_location'],0777,true);
//@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['log_save_location'].DIRECTORY_SEPARATOR.'index.html', 'x');
$tempfile=@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['log_save_location'].DIRECTORY_SEPARATOR.'.htaccess', 'x');
if($tempfile)
{
//$text="deny from all";
$text="<IfModule mod_rewrite.c>\r\nRewriteEngine On\r\nRewriteRule .* - [F,L]\r\n</IfModule>";
fwrite($tempfile,$text );
}
}
return WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$options['log_save_location'].DIRECTORY_SEPARATOR;
}
} includes/class-wpvivid-backup-uploader.php 0000644 00000130010 15132770567 0014742 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class Wpvivid_BackupUploader
{
public function __construct()
{
add_action('wp_ajax_wpvivid_cancel_upload_backup_free', array($this, 'cancel_upload_backup_free'));
add_action('wp_ajax_wpvivid_is_backup_file_free', array($this, 'is_backup_file_free'));
add_action('wp_ajax_wpvivid_upload_files_finish_free', array($this, 'upload_files_finish_free'));
add_action('wp_ajax_wpvivid_get_file_id',array($this,'get_file_id'));
add_action('wp_ajax_wpvivid_upload_files',array($this,'upload_files'));
add_action('wp_ajax_wpvivid_upload_files_finish',array($this,'upload_files_finish'));
add_action('wp_ajax_wpvivid_delete_upload_incomplete_backup_free', array($this, 'delete_upload_incomplete_backup'));
add_action('wp_ajax_wpvivid_rescan_local_folder',array($this,'rescan_local_folder_set_backup'));
add_action('wp_ajax_wpvivid_get_backup_count',array($this,'get_backup_count'));
add_action('wpvivid_rebuild_backup_list', array($this, 'wpvivid_rebuild_backup_list'), 10);
}
function cancel_upload_backup_free()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try{
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR;
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if (is_dir($path . $filename))
{
continue;
}
else
{
if (preg_match('/.*\.tmp$/', $filename))
{
@wp_delete_file($path . $filename);
}
if (preg_match('/.*\.part$/', $filename))
{
@wp_delete_file($path . $filename);
}
}
}
}
if($handler)
@closedir($handler);
}
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function is_wpvivid_backup($file_name)
{
if (preg_match('/wpvivid-.*_.*_.*\.zip$/', $file_name))
{
return true;
}
else {
return false;
}
}
function is_backup_file_free()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$file_name=sanitize_text_field($_POST['file_name']);
if (isset($file_name))
{
if ($this->is_wpvivid_backup($file_name))
{
$ret['result'] = WPVIVID_SUCCESS;
$backupdir=WPvivid_Setting::get_backupdir();
$filePath = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backupdir.DIRECTORY_SEPARATOR.$file_name;
if(file_exists($filePath))
{
$ret['is_exists']=true;
}
else
{
$ret['is_exists']=false;
}
}
else
{
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = $file_name . ' is not created by WPvivid backup plugin.';
}
}
else
{
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'Failed to post file name.';
}
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
function upload_files_finish_free()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
$ret = $this->_rescan_local_folder_set_backup();
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
function delete_upload_incomplete_backup()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if(isset($_POST['incomplete_backup'])&&!empty($_POST['incomplete_backup']))
{
$json = sanitize_text_field($_POST['incomplete_backup']);
$json = stripslashes($json);
$incomplete_backup = json_decode($json, true);
if(is_array($incomplete_backup) && !empty($incomplete_backup))
{
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR;
foreach ($incomplete_backup as $backup)
{
$backup = basename($backup);
if (preg_match('/wpvivid-.*_.*_.*\.zip$/', $backup))
{
@wp_delete_file($path.$backup);
}
else if(preg_match('/'.apply_filters('wpvivid_white_label_file_prefix', 'wpvivid').'-.*_.*_.*\.zip$/', $backup))
{
@wp_delete_file($path.$backup);
}
}
}
$ret['result']='success';
echo wp_json_encode($ret);
}
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
function get_file_id()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$file_name=sanitize_text_field($_POST['file_name']);
if(isset($file_name))
{
if(preg_match('/wpvivid-.*_.*_.*\.zip$/',$file_name))
{
if(preg_match('/wpvivid-(.*?)_/',$file_name,$matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
if(WPvivid_Backuplist::get_backup_by_id($id)===false)
{
$ret['result']=WPVIVID_SUCCESS;
$ret['id']=$id;
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The uploading backup already exists in Backups list.';
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']=$file_name . ' is not created by WPvivid backup plugin.';
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']=$file_name . ' is not created by WPvivid backup plugin.';
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='Failed to post file name.';
}
echo wp_json_encode($ret);
die();
}
function check_file_is_a_wpvivid_backup($file_name,&$backup_id)
{
if(preg_match('/wpvivid-.*_.*_.*\.zip$/',$file_name))
{
if(preg_match('/wpvivid-(.*?)_/',$file_name,$matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
if(WPvivid_Backuplist::get_backup_by_id($id)===false)
{
$backup_id=$id;
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
function upload_files()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$chunk = isset($_REQUEST["chunk"]) ? intval(sanitize_key($_REQUEST["chunk"])) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval(sanitize_key($_REQUEST["chunks"])) : 0;
$fileName = isset($_REQUEST["name"]) ? sanitize_text_field($_REQUEST["name"]) : $_FILES["file"]["name"];
$validate = wp_check_filetype( $fileName );
if ( $validate['type'] == false )
{
echo wp_json_encode(array('result'=>'failed','error'=>"File type is not allowed."));
die();
}
$backupdir=WPvivid_Setting::get_backupdir();
$filePath = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backupdir.DIRECTORY_SEPARATOR.$fileName;
$out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out)
{
// Read binary input stream and append it to temp file
$options['test_form'] =true;
$options['action'] ='wpvivid_upload_files';
$options['test_type'] = false;
$options['ext'] = 'zip';
$options['type'] = 'application/zip';
add_filter('upload_dir', array($this, 'upload_dir'));
$status = wp_handle_upload($_FILES['async-upload'],$options);
remove_filter('upload_dir', array($this, 'upload_dir'));
$in = @fopen($status['file'], "rb");
if ($in)
{
while ($buff = fread($in, 4096))
fwrite($out, $buff);
}
else
{
echo wp_json_encode(array('result'=>'failed','error'=>"Failed to open tmp file.path:".$status['file']));
die();
}
@fclose($in);
@fclose($out);
@wp_delete_file($status['file']);
}
else
{
echo wp_json_encode(array('result'=>'failed','error'=>"Failed to open input stream.path:{$filePath}.part"));
die();
}
if (!$chunks || $chunk == $chunks - 1)
{
// Strip the temp .part suffix off
rename("{$filePath}.part", $filePath);
}
echo wp_json_encode(array('result' => WPVIVID_SUCCESS));
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
function upload_files_finish()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$ret['html']=false;
if(isset($_POST['files']))
{
$files=sanitize_text_field($_POST['files']);
$files =stripslashes($files);
$files =json_decode($files,true);
if(is_null($files))
{
die();
}
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR;
$backup_data['result']='success';
$backup_data['files']=array();
if(preg_match('/wpvivid-.*_.*_.*\.zip$/',$files[0]['name']))
{
if(preg_match('/wpvivid-(.*?)_/',$files[0]['name'],$matches_id))
{
if(preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}/',$files[0]['name'],$matches))
{
$backup_time=$matches[0];
$time_array=explode('-',$backup_time);
if(sizeof($time_array)>4)
$time=$time_array[0].'-'.$time_array[1].'-'.$time_array[2].' '.$time_array[3].':'.$time_array[4];
else
$time=$backup_time;
$time=strtotime($time);
}
else
{
$time=time();
}
$id= $matches_id[0];
$id=substr($id,0,strlen($id)-1);
$unlinked_file = '';
$check_result=true;
foreach ($files as $file)
{
$res=$this->check_is_a_wpvivid_backup($path.$file['name']);
if($res === true)
{
$add_file['file_name']=$file['name'];
$add_file['size']=filesize($path.$file['name']);
$backup_data['files'][]=$add_file;
}
else
{
$check_result=false;
$unlinked_file .= 'file name: '.$file['name'].', error: '.$res;
}
}
if($check_result === true){
WPvivid_Backuplist::add_new_upload_backup($id,$backup_data,$time,'');
$html = '';
$html = apply_filters('wpvivid_add_backup_list', $html);
$ret['result']=WPVIVID_SUCCESS;
$ret['html'] = $html;
}
else{
foreach ($files as $file) {
$this->clean_tmp_files($path, $file['name']);
@wp_delete_file($path . $file['name']);
}
$ret['result']=WPVIVID_FAILED;
$ret['error']='Upload file failed.';
$ret['unlinked']=$unlinked_file;
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The backup is not created by WPvivid backup plugin.';
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The backup is not created by WPvivid backup plugin.';
}
}
else{
$ret['result']=WPVIVID_FAILED;
$ret['error']='Failed to post file name.';
}
echo wp_json_encode($ret);
die();
}
function clean_tmp_files($path, $filename){
$handler=opendir($path);
if($handler===false)
return;
while(($file=readdir($handler))!==false) {
if (!is_dir($path.$file) && preg_match('/wpvivid-.*_.*_.*\.tmp$/', $file)) {
$iPos = strrpos($file, '_');
$file_temp = substr($file, 0, $iPos);
if($file_temp === $filename) {
@wp_delete_file($path.$file);
}
}
}
@closedir($handler);
}
function wpvivid_check_remove_update_backup($path){
$backup_list = WPvivid_Setting::get_option('wpvivid_backup_list');
$remove_backup_array = array();
$update_backup_array = array();
$tmp_file_array = array();
$remote_backup_list=WPvivid_Backuplist::get_has_remote_backuplist();
foreach ($backup_list as $key => $value){
if(!in_array($key, $remote_backup_list)) {
$need_remove = true;
$need_update = false;
if (is_dir($path)) {
$handler = opendir($path);
if($handler===false)
return true;
while (($filename = readdir($handler)) !== false) {
if ($filename != "." && $filename != "..") {
if (!is_dir($path . $filename)) {
if ($this->check_wpvivid_file_info($filename, $backup_id, $need_update)) {
if ($key === $backup_id) {
$need_remove = false;
}
if ($need_update) {
if ($this->check_is_a_wpvivid_backup($path . $filename) === true) {
if (!in_array($filename, $tmp_file_array)) {
$add_file['file_name'] = $filename;
$add_file['size'] = filesize($path . $filename);
$tmp_file_array[] = $filename;
$update_backup_array[$backup_id]['files'][] = $add_file;
}
}
}
}
}
}
}
if ($handler) {
@closedir($handler);
}
}
if ($need_remove) {
$remove_backup_array[] = $key;
}
}
}
$this->wpvivid_remove_update_local_backup_list($remove_backup_array, $update_backup_array);
return true;
}
function check_wpvivid_file_info($file_name, &$backup_id, &$need_update=false){
if(preg_match('/wpvivid-.*_.*_.*\.zip$/',$file_name))
{
if(preg_match('/wpvivid-(.*?)_/',$file_name,$matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
$backup_id=$id;
if(WPvivid_Backuplist::get_backup_by_id($id)===false)
{
$need_update = false;
return true;
}
else
{
$need_update = true;
return true;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
function wpvivid_remove_update_local_backup_list($remove_backup_array, $update_backup_array){
$backup_list = WPvivid_Setting::get_option('wpvivid_backup_list');
foreach ($remove_backup_array as $remove_backup_id){
unset($backup_list[$remove_backup_id]);
}
foreach ($update_backup_array as $update_backup_id => $data){
$backup_list[$update_backup_id]['backup']['files'] = $data['files'];
}
WPvivid_Setting::update_option('wpvivid_backup_list', $backup_list);
}
function _rescan_local_folder_set_backup(){
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR;
$this->wpvivid_check_remove_update_backup($path);
$backups=array();
$count = 0;
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
$count++;
if (is_dir($path . $filename))
{
continue;
} else {
if($this->check_file_is_a_wpvivid_backup($filename,$backup_id))
{
if($this->zip_check_sum($path . $filename))
{
if($this->check_is_a_wpvivid_backup($path.$filename) === true)
{
$backups[$backup_id]['files'][]=$filename;
}
else
{
$ret['incomplete_backup'][] = $filename;
}
}
}
}
}
}
if($handler)
@closedir($handler);
}
}
else{
$ret['result']=WPVIVID_FAILED;
$ret['error']='Failed to get local storage directory.';
}
if(!empty($backups))
{
foreach ($backups as $backup_id =>$backup)
{
$backup_data['result']='success';
$backup_data['files']=array();
if(empty($backup['files']))
continue;
$time=false;
foreach ($backup['files'] as $file)
{
if($time===false)
{
if(preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}/',$file,$matches))
{
$backup_time=$matches[0];
$time_array=explode('-',$backup_time);
if(sizeof($time_array)>4)
$time=$time_array[0].'-'.$time_array[1].'-'.$time_array[2].' '.$time_array[3].':'.$time_array[4];
else
$time=$backup_time;
$time=strtotime($time);
}
else
{
$time=time();
}
}
$add_file['file_name']=$file;
$add_file['size']=filesize($path.$file);
$backup_data['files'][]=$add_file;
}
WPvivid_Backuplist::add_new_upload_backup($backup_id,$backup_data,$time,'');
}
}
$ret['result']=WPVIVID_SUCCESS;
$html = '';
$tour = true;
$html = apply_filters('wpvivid_add_backup_list', $html, 'wpvivid_backup_list', $tour);
$ret['html'] = $html;
return $ret;
}
function rescan_local_folder_set_backup()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$ret = $this->_rescan_local_folder_set_backup();
echo wp_json_encode($ret);
die();
}
public function wpvivid_rebuild_backup_list(){
$this->_rescan_local_folder_set_backup();
}
static function rescan_local_folder()
{
$backupdir=WPvivid_Setting::get_backupdir();
?>
<div style="padding-top: 10px;">
<span><?php esc_html_e('Tips: Click the button below to scan all uploaded or received backups in directory', 'wpvivid-backuprestore'); ?> <?php echo esc_html(WP_CONTENT_DIR.'/'.$backupdir); ?></span>
</div>
<div style="padding-top: 10px;">
<input type="submit" class="button-primary" value="<?php esc_attr_e('Scan uploaded backup or received backup', 'wpvivid-backuprestore'); ?>" onclick="wpvivid_rescan_local_folder();" />
</div>
<script type="text/javascript">
function wpvivid_rescan_local_folder()
{
var ajax_data = {
'action': 'wpvivid_rescan_local_folder'
};
wpvivid_post_request(ajax_data, function (data)
{
try {
var jsonarray = jQuery.parseJSON(data);
if(typeof jsonarray.incomplete_backup !== 'undefined' && jsonarray.incomplete_backup.length > 0)
{
var incomplete_count = jsonarray.incomplete_backup.length;
alert('Failed to scan '+incomplete_count+' backup zips, the zips can be corrupted during creation or download process. Please check the zips.');
}
if(jsonarray.html !== false)
{
jQuery('#wpvivid_backup_list').html('');
jQuery('#wpvivid_backup_list').append(jsonarray.html);
wpvivid_popup_tour('show');
}
}
catch(err) {
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('scanning backup list', textStatus, errorThrown);
alert(error_message);
});
}
</script>
<?php
}
function get_backup_count()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$backuplist=WPvivid_Backuplist::get_backuplist();
echo esc_attr(sizeof($backuplist));
die();
}
static function upload_meta_box()
{
?>
<div id="wpvivid_plupload-upload-ui" class="hide-if-no-js" style="margin-bottom: 10px;">
<div id="drag-drop-area">
<div class="drag-drop-inside">
<p class="drag-drop-info"><?php esc_html_e('Drop files here', 'wpvivid-backuprestore'); ?></p>
<p><?php esc_html_x('or', 'Uploader: Drop files here - or - Select Files', 'wpvivid-backuprestore'); ?></p>
<p class="drag-drop-buttons"><input id="wpvivid_select_file_button" type="button" value="<?php esc_attr_e('Select Files', 'wpvivid-backuprestore'); ?>" class="button" /></p>
</div>
</div>
</div>
<div id="wpvivid_uploaded_file_list" class="hide-if-no-js" style="margin-bottom: 10px;"></div>
<div id="wpvivid_upload_file_list" class="hide-if-no-js" style="margin-bottom: 10px;"></div>
<div style="margin-bottom: 10px;">
<input type="submit" class="button-primary" id="wpvivid_upload_submit_btn" value="Upload" onclick="wpvivid_submit_upload();" />
<input type="submit" class="button-primary" id="wpvivid_stop_upload_btn" value="Cancel" onclick="wpvivid_cancel_upload();" />
</div>
<div style="clear: both;"></div>
<?php
$chunk_size = min(wp_max_upload_size(), 1048576*2);
$plupload_init = array(
'browse_button' => 'wpvivid_select_file_button',
'container' => 'wpvivid_plupload-upload-ui',
'drop_element' => 'drag-drop-area',
'file_data_name' => 'async-upload',
'max_retries' => 3,
'multiple_queues' => true,
'max_file_size' => '10Gb',
'chunk_size' => $chunk_size.'b',
'url' => admin_url('admin-ajax.php'),
'multipart' => true,
'urlstream_upload' => true,
// additional post data to send to our ajax hook
'multipart_params' => array(
'_ajax_nonce' => wp_create_nonce('wpvivid_ajax'),
'action' => 'wpvivid_upload_files', // the ajax action name
),
);
// we should probably not apply this filter, plugins may expect wp's media uploader...
$plupload_init = apply_filters('plupload_init', $plupload_init);
$upload_file_image = includes_url( '/images/media/archive.png' );
?>
<script type="text/javascript">
var uploader;
function wpvivid_stop_upload()
{
var ajax_data = {
'action': 'wpvivid_cancel_upload_backup_free',
};
wpvivid_post_request(ajax_data, function (data)
{
jQuery("#wpvivid_select_file_button").prop('disabled', false);
jQuery('#wpvivid_upload_file_list').html("");
jQuery('#wpvivid_upload_submit_btn').hide();
jQuery('#wpvivid_stop_upload_btn').hide();
wpvivid_init_upload_list();
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('cancelling upload backups', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_upload_file_list').html("");
jQuery('#wpvivid_upload_submit_btn').hide();
jQuery('#wpvivid_stop_upload_btn').hide();
wpvivid_init_upload_list();
});
}
function wpvivid_check_plupload_added_files(up,files)
{
var repeat_files = '';
var exist_files = '';
var file_count=files.length;
var current_scan=0;
var exist_count=0;
plupload.each(files, function(file)
{
var brepeat=false;
var file_list = jQuery('#wpvivid_upload_file_list span');
file_list.each(function (index, value)
{
if (value.innerHTML === file.name)
{
brepeat=true;
}
});
if(!brepeat)
{
var ajax_data = {
'action': 'wpvivid_is_backup_file_free',
'file_name':file.name
};
wpvivid_post_request(ajax_data, function (data)
{
current_scan++;
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === "success")
{
if(jsonarray.is_exists==true)
{
exist_count++;
if(exist_files === '') {
exist_files += file.name;
}
else {
exist_files += ', ' + file.name;
}
wpvivid_file_uploaded_queued(file);
uploader.removeFile(file);
}
else
{
wpvivid_fileQueued( file );
}
if(file_count === exist_count)
{
alert("The backup already exists in target folder.");
exist_files = '';
}
else if((file_count === current_scan) && (exist_files !== ''))
{
alert(exist_files + " already exist in target folder.");
exist_files = '';
}
}
else if(jsonarray.result === "failed")
{
uploader.removeFile(file);
alert(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
current_scan++;
var error_message = wpvivid_output_ajaxerror('uploading backups', textStatus, errorThrown);
uploader.removeFile(file);
alert(error_message);
});
}
else{
current_scan++;
if(repeat_files === ''){
repeat_files += file.name;
}
else{
repeat_files += ', ' + file.name;
}
}
});
if(repeat_files !== ''){
alert(repeat_files + " already exists in upload list.");
repeat_files = '';
}
}
function wpvivid_fileQueued(file)
{
jQuery('#wpvivid_upload_file_list').append(
'<div id="' + file.id + '" style="width: 100%; height: 36px; background: #fff; margin-bottom: 1px;">' +
'<img src=" <?php echo esc_attr($upload_file_image); ?> " alt="" style="float: left; margin: 2px 10px 0 3px; max-width: 40px; max-height: 32px;">' +
'<div style="line-height: 36px; float: left; margin-left: 5px;"><span>' + file.name + '</span></div>' +
'<div class="fileprogress" style="line-height: 36px; float: right; margin-right: 5px;"></div>' +
'</div>' +
'<div style="clear: both;"></div>'
);
jQuery('#wpvivid_upload_submit_btn').show();
jQuery('#wpvivid_stop_upload_btn').show();
jQuery("#wpvivid_upload_submit_btn").prop('disabled', false);
}
function wpvivid_file_uploaded_queued(file)
{
jQuery('#'+file.id).remove();
}
function wpvivid_delete_incomplete_backups(incomplete_backup)
{
var ajax_data = {
'action': 'wpvivid_delete_upload_incomplete_backup_free',
'incomplete_backup': incomplete_backup
};
wpvivid_post_request(ajax_data, function (data)
{
}, function (XMLHttpRequest, textStatus, errorThrown)
{
});
}
function wpvivid_init_upload_list()
{
uploader = new plupload.Uploader(<?php echo wp_json_encode($plupload_init); ?>);
// checks if browser supports drag and drop upload, makes some css adjustments if necessary
uploader.bind('Init', function(up)
{
var uploaddiv = jQuery('#wpvivid_plupload-upload-ui');
if(up.features.dragdrop){
uploaddiv.addClass('drag-drop');
jQuery('#drag-drop-area')
.bind('dragover.wp-uploader', function(){ uploaddiv.addClass('drag-over'); })
.bind('dragleave.wp-uploader, drop.wp-uploader', function(){ uploaddiv.removeClass('drag-over'); });
}else{
uploaddiv.removeClass('drag-drop');
jQuery('#drag-drop-area').unbind('.wp-uploader');
}
});
uploader.init();
// a file was added in the queue
uploader.bind('FilesAdded', wpvivid_check_plupload_added_files);
uploader.bind('Error', function(up, error)
{
alert('Upload ' + error.file.name +' error, error code: ' + error.code + ', ' + error.message);
wpvivid_stop_upload();
});
uploader.bind('FileUploaded', function(up, file, response)
{
var jsonarray = jQuery.parseJSON(response.response);
if(jsonarray.result == 'failed')
{
alert('upload ' + file.name + ' failed, ' + jsonarray.error);
uploader.stop();
wpvivid_stop_upload();
}
else
{
wpvivid_file_uploaded_queued(file);
}
});
uploader.bind('UploadProgress', function(up, file)
{
jQuery('#' + file.id + " .fileprogress").html(file.percent + "%");
});
uploader.bind('UploadComplete',function(up, files)
{
jQuery('#wpvivid_upload_file_list').html("");
jQuery('#wpvivid_upload_submit_btn').hide();
jQuery('#wpvivid_stop_upload_btn').hide();
jQuery("#wpvivid_select_file_button").prop('disabled', false);
var ajax_data = {
'action': 'wpvivid_upload_files_finish_free'
};
wpvivid_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if(jsonarray.result === 'success')
{
if(typeof jsonarray.incomplete_backup !== 'undefined' && jsonarray.incomplete_backup.length > 0)
{
var incomplete_count = jsonarray.incomplete_backup.length;
var incomplete_backup = JSON.stringify(jsonarray.incomplete_backup);
wpvivid_delete_incomplete_backups(incomplete_backup);
alert('Failed to scan '+incomplete_count+' backup zips, the zips can be corrupted during creation or download process. Please check the zips.');
}
else
{
alert('The upload has completed.');
}
jQuery('#wpvivid_backup_list').html('');
jQuery('#wpvivid_backup_list').append(jsonarray.html);
wpvivid_click_switch_page('backup', 'wpvivid_tab_backup', true);
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page=WPvivid'; ?>';
}
else
{
alert(jsonarray.error);
}
}
catch(err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('refreshing backup list', textStatus, errorThrown);
alert(error_message);
});
plupload.each(files, function(file)
{
if(typeof file === 'undefined')
{
}
else
{
uploader.removeFile(file.id);
}
});
});
uploader.bind('Destroy', function(up, file)
{
wpvivid_stop_upload();
});
}
jQuery(document).ready(function($)
{
// create the uploader and pass the config from above
jQuery('#wpvivid_upload_submit_btn').hide();
jQuery('#wpvivid_stop_upload_btn').hide();
wpvivid_init_upload_list();
});
function wpvivid_submit_upload()
{
jQuery("#wpvivid_upload_submit_btn").prop('disabled', true);
jQuery("#wpvivid_select_file_button").prop('disabled', true);
uploader.refresh();
uploader.start();
}
function wpvivid_cancel_upload()
{
uploader.destroy();
}
</script>
<?php
}
public function upload_dir($uploads)
{
$uploads['path'] = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
return $uploads;
}
private function check_is_a_wpvivid_backup($file_name)
{
$ret=WPvivid_Backup_Item::get_backup_file_info($file_name);
if($ret['result'] === WPVIVID_SUCCESS){
return true;
}
elseif($ret['result'] === WPVIVID_FAILED){
return $ret['error'];
}
}
private function zip_check_sum($file_name)
{
return true;
}
} includes/class-wpvivid-backup-site.php 0000644 00000003235 15132770567 0014103 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
require_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
class WPvivid_Backup_Site
{
private $tools_collection=array();
public function __construct()
{
add_filter('wpvivid_tools_register', array($this, 'init_tools'),10);
$this->tools_collection=apply_filters('wpvivid_tools_register',$this->tools_collection);
$this->load_hooks();
}
public function init_tools($tools_collection){
$tools_collection['zip'][WPVIVID_COMPRESS_ZIPCLASS] = 'WPvivid_ZipClass';
return $tools_collection;
}
public function get_tools($type){
if(array_key_exists($type,$this->tools_collection))
{
foreach ($this -> tools_collection[$type] as $class_name){
if(class_exists($class_name)){
$object = new $class_name();
$last_error = $object -> getLastError();
if(empty($last_error))
return $object;
}
}
}
$class_name = $this -> tools_collection['zip'][WPVIVID_COMPRESS_ZIPCLASS];
$object = new $class_name();
$last_error = $object -> getLastError();
if(empty($last_error)){
return $object;
}else{
return array('result' => WPVIVID_FAILED,'error' => $last_error);
}
}
public function load_hooks(){
foreach ($this -> tools_collection as $compressType){
foreach ($compressType as $className){
$object = new $className();
}
}
}
} includes/class-wpvivid-backuptoremote.php 0000644 00000003616 15132770567 0014723 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-ftpclass.php';
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-sftpclass.php';
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-amazons3-plus.php';
class WPvivid_Backup_Remote
{
public function backup_with_ftp($data = array())
{
$host = $data['options']['host'];
$username = $data['options']['username'];
$password = $data['options']['password'];
$path = $data['options']['path'];
$passive = $data['options']['passive'];
$port = empty($data['options']['port'])?21:$data['options']['port'];
$ftpclass = new WPvivid_FTPClass();
$res = $ftpclass -> upload($host,$username,$password,$path,$data['files'],$data['task_id'],$passive,$port,$data['log']);
return $res;
}
public function backup_with_sftp($data)
{
if(empty($data['port']))
$data['options']['port'] = 22;
$host = $data['options']['host'];
$username = $data['options']['username'];
$password = $data['options']['password'];
$path = $data['options']['path'];
$port = $data['options']['port'];
$scp = $data['options']['scp'];
$sftpclass = new WPvivid_SFTPClass();
$result = $sftpclass -> upload($host,$username,$password,$path,$data['files'],$data['task_id'],$port,$scp,$data['log']);
return $result;
}
public function backup_with_amazonS3($data = array())
{
$files = $data['files'];
$access = $data['options']['access'];
$secret = $data['options']['secret'];
$s3Path = $data['options']['s3Path'];
$region = $data['options']['region'];
$amazonS3 = new WPvivid_AMAZONS3Class();
$amazonS3 ->init($access,$secret,$region);
$res = $amazonS3 -> upload($files,$s3Path,$data['task_id'],$data['log']);
return $res;
}
} includes/class-wpvivid-mail-report.php 0000644 00000200432 15132770567 0014125 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_mail_report
{
public static function send_report_mail($task,$log=false)
{
$option=WPvivid_Setting::get_option('wpvivid_email_setting');
$option=apply_filters('wpvivid_get_mail_option_addon', $option);
if(empty($option))
{
return true;
}
if($option['email_enable'] == 0){
return true;
}
if(empty($option['send_to']))
{
return true;
}
if($task['status']['str']=='completed'&&$option['always']==false)
{
return true;
}
$headers = array('Content-Type: text/html; charset=UTF-8');
$subject = '';
$subject = apply_filters('wpvivid_set_mail_subject', $subject, $task);
$body = '';
$body = apply_filters('wpvivid_set_mail_body', $body, $task);
$task_log=$task['options']['log_file_name'];
if(isset($option['email_attach_log'])){
if($option['email_attach_log'] == '1'){
$attach_log = true;
}
else{
$attach_log = false;
}
}
else{
$attach_log = true;
}
if($attach_log){
$wpvivid_log=new WPvivid_Log();
$log_file_name= $wpvivid_log->GetSaveLogFolder().$task_log.'_log.txt';
$attachments[] = $log_file_name;
}
else{
$attachments = array();
}
foreach ($option['send_to'] as $send_to)
{
if(wp_mail( $send_to, $subject, $body,$headers,$attachments)===false)
{
if($log!==false)
{
$message=get_error_messages('wp_mail_failed');
$log->WriteLog($message,'error');
}
}
}
return true;
}
public static function send_report_mail_ex($task_id,$log=false)
{
$task= new WPvivid_Backup_Task_2($task_id);
$option=WPvivid_Setting::get_option('wpvivid_email_setting');
$option=apply_filters('wpvivid_get_mail_option_addon', $option);
if(empty($option))
{
return true;
}
if($option['email_enable'] == 0){
return true;
}
if(empty($option['send_to']))
{
return true;
}
$status=$task->get_status();
if($status['str']!=='error'&&$option['always']==false)
{
return true;
}
$headers = array('Content-Type: text/html; charset=UTF-8');
//$subject = '';
//$subject = apply_filters('wpvivid_set_mail_subject', $subject, $task);
$subject =self::set_mail_subject($task_id);
//$body = '';
//$body = apply_filters('wpvivid_set_mail_body', $body, $task);
$body = self::set_mail_body($task_id);
$task_log=$task->task['options']['log_file_name'];
if(isset($option['email_attach_log'])){
if($option['email_attach_log'] == '1'){
$attach_log = true;
}
else{
$attach_log = false;
}
}
else{
$attach_log = true;
}
if($attach_log){
$wpvivid_log=new WPvivid_Log();
if($status['str']==='error')
{
$log_file_name= $wpvivid_log->GetSaveLogFolder().'error'.DIRECTORY_SEPARATOR.$task_log.'_log.txt';
}
else
{
$log_file_name= $wpvivid_log->GetSaveLogFolder().$task_log.'_log.txt';
}
$attachments[] = $log_file_name;
}
else{
$attachments = array();
}
foreach ($option['send_to'] as $send_to)
{
if(wp_mail( $send_to, $subject, $body,$headers,$attachments)===false)
{
if($log!==false)
{
$message=get_error_messages('wp_mail_failed');
$log->WriteLog($message,'error');
}
}
}
return true;
}
public static function set_mail_subject($task_id)
{
$task= new WPvivid_Backup_Task_2($task_id);
$task_status=$task->get_status();
if($task_status['str']!=='error')
{
$status='Succeeded';
}
else
{
$status='Failed';
}
$offset=get_option('gmt_offset');
$localtime=gmdate('m-d-Y H:i:s', $task->get_start_time()+$offset*60*60);
$header='[Backup '.$status.']'.$localtime.' - By WPvivid Backup Plugin';
return $header;
}
public static function set_mail_body($task_id)
{
$task= new WPvivid_Backup_Task_2($task_id);
$task_status=$task->get_status();
if($task_status['str']!=='error')
{
$status='Succeeded';
}
else
{
$status='Failed. '.$task_status['error'];
}
$type=$task->task['type'];
if($type === 'Cron')
{
$type = 'Cron-Schedule';
}
$offset=get_option('gmt_offset');
$start_time=gmdate("m-d-Y H:i:s",$task->get_start_time()+$offset*60*60);
$end_time=gmdate("m-d-Y H:i:s",time()+$offset*60*60);
$running_time=($task->get_end_time()-$task->get_start_time()).'s';
$remote_options= $task->task['options']['remote_options'];
if($remote_options!==false)
{
$remote_option=array_shift($remote_options);
$remote=apply_filters('wpvivid_storage_provider_tran', $remote_option['type']);
}
else
{
$remote='Localhost';
}
$content='';
$backup_content=isset($task->task['options']['backup_files'])?$task->task['options']['backup_files']:'';
if($backup_content==='files')
{
$content.='All Files (Exclude Database)';
}
else if($backup_content==='files+db')
{
$content.='Entire Website';
}
else if($backup_content==='db')
{
$content.='Database';
}
else
{
$content='Upload';
}
$body='
<table width="100%" cellpadding="0" cellspacing="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td style="padding-bottom:20px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table align="center" style="border-spacing:0;color:#111111;Margin:0 auto;width:100%;max-width:600px" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="73%" style="border-spacing:0;color:#111111" bgcolor="#F5F7F8">
<tbody>
<tr>
<td style="padding-top:20px;padding-bottom:0px;padding-left:10px;padding-right:40px;width:100%;text-align:center;font-size:32px;color:#2ea3f2;line-height:32px;font-weight:bold;">
<span><img src="https://wpvivid.com/wp-content/uploads/2019/02/wpvivid-logo.png" title="WPvivid.com"></span>
</td>
</tr>
</tbody>
</table>
</td>
<td width="100%" bgcolor="#F5F7F8" style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111" bgcolor="#F5F7F8">
<tbody>
<tr>
<td style="padding-top:10px;padding-bottom:0px;padding-left:10px;padding-right:0px;background-color:#f5f7f8;width:100%;text-align:right">
<p style="Margin-top:0px;margin-bottom:0px;font-size:13px;line-height:16px"><strong><a href="https://twitter.com/wpvividcom" style="text-decoration:none;color:#111111" target="_blank">24/7 Support: <u></u>Twitter<u></u></a></strong></p>
</td>
</tr>
<tr>
<td style="padding-top:0px;padding-bottom:0px;padding-left:10px;padding-right:0px;background-color:#f5f7f8;width:100%;text-align:right">
<p class="m_764812426175198487customerinfo" style="Margin-top:5px;margin-bottom:0px;font-size:13px;line-height:16px">Or <u></u><a href="https://wpvivid.com/contact-us">Email Us</a><u></u></p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#FFFFFF" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:40px;padding-bottom:0px;padding-left:40px;padding-right:40px;background-color:#ffffff;width:100%;text-align:center;font-size:32px;line-height:42px;font-weight:bold;">
<span>Wordpress Backup Report</span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#FFFFFF" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:20px;padding-bottom:0px;padding-left:0px;padding-right:0px;background-color:#ffffff;width:100%;text-align:left">
<p style="margin-top:0px;line-height:0px;margin-bottom:0px;font-size:4px"> </p>
</td>
</tr>
</tbody>
</table>
</td>
<td width="80" style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="80" style="border-spacing:0;color:#111111;border-bottom-color:#ffcca8;border-bottom-width:2px;border-bottom-style:solid">
<tbody>
<tr>
<td style="padding-top:20px;padding-bottom:0px;padding-left:0px;padding-right:0px;background-color:#ffffff;width:100%;text-align:left">
<p style="margin-top:0px;line-height:0px;margin-bottom:0px;font-size:4px"></p>
</td>
</tr>
</tbody>
</table>
</td>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:20px;padding-bottom:0px;padding-left:0px;padding-right:0px;background-color:#ffffff;width:100%;text-align:left">
<p style="margin-top:0px;line-height:0px;margin-bottom:0px;font-size:4px"> </p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#FFFFFF" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:40px;padding-bottom:0px;padding-left:40px;padding-right:40px;background-color:#ffffff;width:100%;text-align:left">
<p style="gdsherpa-regular;margin-top:0px;font-size:14px;line-height:24px;margin-bottom:0px">
You receive this email because you have enabled the email notification feature in WPvivid plugin. Backup Details:
</p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="background-color:#f5f7f8;padding-top:0;padding-right:0;padding-left:0;padding-bottom:0">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#ffffff" width="100%" align="center" border="0" cellspacing="0" cellpadding="0" style="color:#111111;max-width:600px">
<tbody>
<tr>
<td bgcolor="#ffffff" align="left" style="padding-top:10px;padding-bottom:0;padding-right:40px;padding-left:40px;background-color:#ffffff">
<table border="0" cellpadding="0" cellspacing="0" align="left" width="100%">
<tbody>
<tr>
<td style="padding-top:10px;padding-right:0;padding-bottom:0;padding-left:20px">
<table border="0" cellpadding="0" cellspacing="0" align="left">
<tbody>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Backup: </label><label>'.$status.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Backup Type: </label><label>'.$type.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Start Time: </label><label>'.$start_time.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>End Time: </label><label>'.$end_time.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Running Time: </label><label>'.$running_time.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Backed up to: </label><label>'.$remote.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Backup Content: </label><label>'.$content.'</label></p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#FFFFFF" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#757575">
<tbody>
<tr>
<td style="padding-top:20px;padding-bottom:0px;padding-left:40px;padding-right:40px;background-color:#ffffff;width:100%;text-align:left">
<p style="gdsherpa-regular;margin-top:0px;font-size:14px;line-height:24px;margin-bottom:0px">
*WPvivid Backup plugin is a Wordpress plugin that it will help you back up your site to the leading cloud storage providers like Dropbox, Google Drive, Amazon S3, Microsoft OneDrive, FTP and SFTP.
</p>
<p style="gdsherpa-regular;margin-top:0px;font-size:14px;line-height:24px;margin-bottom:0px">
Plugin Page: <a href="https://wordpress.org/plugins/wpvivid-backuprestore/">https://wordpress.org/plugins/wpvivid-backuprestore/</a>
</p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#FFFFFF" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:40px;padding-bottom:0px;padding-left:40px;padding-right:40px;background-color:#ffffff;width:100%;text-align:left">
<p style="margin-top:0px;line-height:0px;margin-bottom:0px;font-size:4px"></p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="background-color:#f5f7f8;padding-top:0;padding-right:0;padding-left:0;padding-bottom:0">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table width="100%" align="center" border="0" cellspacing="0" cellpadding="0" style="color:#111111">
<tbody>
<tr>
<td align="center" style="padding-top:40px;padding-bottom:0;padding-right:0px;padding-left:0px">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" valign="bottom">
<img src="https://wpvivid.com/wp-content/uploads/2019/03/report-background.png" width="270" height="60" style="display:block;width:100%;max-width:270px;min-width:10px;height:60px" class="CToWUd">
</td>
<td width="60" valign="bottom">
<img src="https://wpvivid.com/wp-content/uploads/2019/03/female.png" width="60" height="60" style="display:block" class="CToWUd">
</td>
<td align="right" valign="bottom">
<img src="https://wpvivid.com/wp-content/uploads/2019/03/report-background.png" width="270" height="60" style="display:block;width:100%;max-width:270px;min-width:10px;height:60px" class="CToWUd">
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table bgcolor="#FFFFFF" width="100%" align="left" border="0" cellspacing="0" cellpadding="0" style="color:#111111">
<tbody>
<tr>
<td bgcolor="#FFFFFF" align="left" style="padding-top:20px;padding-bottom:40px;padding-right:40px;padding-left:40px;background-color:#ffffff">
<table border="0" cellpadding="0" cellspacing="0" width="100%" align="center">
<tbody>
<tr>
<td align="center" style="padding-top:0px;padding-bottom:10px;padding-right:0;padding-left:0;text-align:center;font-size:18px;line-height:28px;font-weight:bold;">
<span>We\'re here to help you do your thing.</span>
</td>
</tr>
<tr>
<td align="center" style="padding-top:0px;padding-bottom:0px;padding-right:0;padding-left:0;text-align:center">
<p style="text-align:center;margin-top:0px;margin-bottom:0px;gdsherpa-regular;;font-size:14px;line-height:24px">
<a href="https://wpvivid.com/contact-us">Contact Us</a> or <a href="https://twitter.com/wpvividcom">Twitter</a>
</p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td valign="top" style="font-size:0px;line-height:0px;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<img src="https://wpvivid.com/wp-content/uploads/2019/03/unnamed6.jpg" width="600" height="5" style="display:block;width:100%;max-width:600px;min-width:10px;height:5px">
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#F5F7F8" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:40px;padding-bottom:0px;padding-left:40px;padding-right:40px;background-color:#f5f7f8;width:100%;text-align:left">
<p style="margin-top:0px;line-height:0px;margin-bottom:0px;font-size:4px"> </p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>';
return $body;
}
public static function create_subject($task)
{
$status=$task['status']['str'];
if($status=='completed')
{
$status='Succeeded';
}
else
{
$status='Failed';
}
$offset=get_option('gmt_offset');
$localtime=gmdate('m-d-Y H:i:s', $task['status']['start_time']+$offset*60*60);
$header='[Backup '.$status.']'.$localtime.' - By WPvivid Backup Plugin';
return $header;
}
public static function create_body($task)
{
$status=$task['status']['str'];
if($status=='completed')
{
$status='Succeeded';
}
else
{
$status='Failed. '.$task['status']['error'];
}
$type=$task['type'];
if($type === 'Cron')
{
$type = 'Cron-Schedule';
}
$offset=get_option('gmt_offset');
$start_time=gmdate("m-d-Y H:i:s",$task['status']['start_time']+$offset*60*60);
$end_time=gmdate("m-d-Y H:i:s",time()+$offset*60*60);
$running_time=($task['status']['run_time']-$task['status']['start_time']).'s';
$remote_options= $task['options']['remote_options'];
if($remote_options!==false)
{
$remote_option=array_shift($remote_options);
$remote=apply_filters('wpvivid_storage_provider_tran', $remote_option['type']);
}
else
{
$remote='Localhost';
}
$content='';
$backup_options=$task['options']['backup_options'];
if($backup_options!==false)
{
if(isset($backup_options['backup'][WPVIVID_BACKUP_TYPE_DB])&&isset($backup_options['backup'][WPVIVID_BACKUP_TYPE_THEMES]))
{
$content.='Entire Website';
}
else if(isset($backup_options['backup'][WPVIVID_BACKUP_TYPE_DB]))
{
$content.='Database';
}
else if(isset($backup_options['backup'][WPVIVID_BACKUP_TYPE_THEMES]))
{
$content.='All Files (Exclude Database)';
}
}
else
{
$content='Upload';
}
$body='
<table width="100%" cellpadding="0" cellspacing="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td style="padding-bottom:20px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table align="center" style="border-spacing:0;color:#111111;Margin:0 auto;width:100%;max-width:600px" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="73%" style="border-spacing:0;color:#111111" bgcolor="#F5F7F8">
<tbody>
<tr>
<td style="padding-top:20px;padding-bottom:0px;padding-left:10px;padding-right:40px;width:100%;text-align:center;font-size:32px;color:#2ea3f2;line-height:32px;font-weight:bold;">
<span><img src="https://wpvivid.com/wp-content/uploads/2019/02/wpvivid-logo.png" title="WPvivid.com"></span>
</td>
</tr>
</tbody>
</table>
</td>
<td width="100%" bgcolor="#F5F7F8" style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111" bgcolor="#F5F7F8">
<tbody>
<tr>
<td style="padding-top:10px;padding-bottom:0px;padding-left:10px;padding-right:0px;background-color:#f5f7f8;width:100%;text-align:right">
<p style="Margin-top:0px;margin-bottom:0px;font-size:13px;line-height:16px"><strong><a href="https://twitter.com/wpvividcom" style="text-decoration:none;color:#111111" target="_blank">24/7 Support: <u></u>Twitter<u></u></a></strong></p>
</td>
</tr>
<tr>
<td style="padding-top:0px;padding-bottom:0px;padding-left:10px;padding-right:0px;background-color:#f5f7f8;width:100%;text-align:right">
<p class="m_764812426175198487customerinfo" style="Margin-top:5px;margin-bottom:0px;font-size:13px;line-height:16px">Or <u></u><a href="https://wpvivid.com/contact-us">Email Us</a><u></u></p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#FFFFFF" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:40px;padding-bottom:0px;padding-left:40px;padding-right:40px;background-color:#ffffff;width:100%;text-align:center;font-size:32px;line-height:42px;font-weight:bold;">
<span>Wordpress Backup Report</span>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#FFFFFF" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:20px;padding-bottom:0px;padding-left:0px;padding-right:0px;background-color:#ffffff;width:100%;text-align:left">
<p style="margin-top:0px;line-height:0px;margin-bottom:0px;font-size:4px"> </p>
</td>
</tr>
</tbody>
</table>
</td>
<td width="80" style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="80" style="border-spacing:0;color:#111111;border-bottom-color:#ffcca8;border-bottom-width:2px;border-bottom-style:solid">
<tbody>
<tr>
<td style="padding-top:20px;padding-bottom:0px;padding-left:0px;padding-right:0px;background-color:#ffffff;width:100%;text-align:left">
<p style="margin-top:0px;line-height:0px;margin-bottom:0px;font-size:4px"></p>
</td>
</tr>
</tbody>
</table>
</td>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:20px;padding-bottom:0px;padding-left:0px;padding-right:0px;background-color:#ffffff;width:100%;text-align:left">
<p style="margin-top:0px;line-height:0px;margin-bottom:0px;font-size:4px"> </p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#FFFFFF" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:40px;padding-bottom:0px;padding-left:40px;padding-right:40px;background-color:#ffffff;width:100%;text-align:left">
<p style="gdsherpa-regular;margin-top:0px;font-size:14px;line-height:24px;margin-bottom:0px">
You receive this email because you have enabled the email notification feature in WPvivid plugin. Backup Details:
</p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="background-color:#f5f7f8;padding-top:0;padding-right:0;padding-left:0;padding-bottom:0">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#ffffff" width="100%" align="center" border="0" cellspacing="0" cellpadding="0" style="color:#111111;max-width:600px">
<tbody>
<tr>
<td bgcolor="#ffffff" align="left" style="padding-top:10px;padding-bottom:0;padding-right:40px;padding-left:40px;background-color:#ffffff">
<table border="0" cellpadding="0" cellspacing="0" align="left" width="100%">
<tbody>
<tr>
<td style="padding-top:10px;padding-right:0;padding-bottom:0;padding-left:20px">
<table border="0" cellpadding="0" cellspacing="0" align="left">
<tbody>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Backup: </label><label>'.$status.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Backup Type: </label><label>'.$type.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Start Time: </label><label>'.$start_time.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>End Time: </label><label>'.$end_time.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Running Time: </label><label>'.$running_time.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Backed up to: </label><label>'.$remote.'</label></p>
</td>
</tr>
<tr>
<td valign="top" align="left" style="padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<p style="text-align:left;Margin-top:0px;Margin-bottom:0px;gdsherpa-regular;font-size:14px;line-height:24px"><label>Backup Content: </label><label>'.$content.'</label></p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#FFFFFF" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#757575">
<tbody>
<tr>
<td style="padding-top:20px;padding-bottom:0px;padding-left:40px;padding-right:40px;background-color:#ffffff;width:100%;text-align:left">
<p style="gdsherpa-regular;margin-top:0px;font-size:14px;line-height:24px;margin-bottom:0px">
*WPvivid Backup plugin is a Wordpress plugin that it will help you back up your site to the leading cloud storage providers like Dropbox, Google Drive, Amazon S3, Microsoft OneDrive, FTP and SFTP.
</p>
<p style="gdsherpa-regular;margin-top:0px;font-size:14px;line-height:24px;margin-bottom:0px">
Plugin Page: <a href="https://wordpress.org/plugins/wpvivid-backuprestore/">https://wordpress.org/plugins/wpvivid-backuprestore/</a>
</p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#FFFFFF" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:40px;padding-bottom:0px;padding-left:40px;padding-right:40px;background-color:#ffffff;width:100%;text-align:left">
<p style="margin-top:0px;line-height:0px;margin-bottom:0px;font-size:4px"></p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="background-color:#f5f7f8;padding-top:0;padding-right:0;padding-left:0;padding-bottom:0">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table width="100%" align="center" border="0" cellspacing="0" cellpadding="0" style="color:#111111">
<tbody>
<tr>
<td align="center" style="padding-top:40px;padding-bottom:0;padding-right:0px;padding-left:0px">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td align="left" valign="bottom">
<img src="https://wpvivid.com/wp-content/uploads/2019/03/report-background.png" width="270" height="60" style="display:block;width:100%;max-width:270px;min-width:10px;height:60px" class="CToWUd">
</td>
<td width="60" valign="bottom">
<img src="https://wpvivid.com/wp-content/uploads/2019/03/female.png" width="60" height="60" style="display:block" class="CToWUd">
</td>
<td align="right" valign="bottom">
<img src="https://wpvivid.com/wp-content/uploads/2019/03/report-background.png" width="270" height="60" style="display:block;width:100%;max-width:270px;min-width:10px;height:60px" class="CToWUd">
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table bgcolor="#FFFFFF" width="100%" align="left" border="0" cellspacing="0" cellpadding="0" style="color:#111111">
<tbody>
<tr>
<td bgcolor="#FFFFFF" align="left" style="padding-top:20px;padding-bottom:40px;padding-right:40px;padding-left:40px;background-color:#ffffff">
<table border="0" cellpadding="0" cellspacing="0" width="100%" align="center">
<tbody>
<tr>
<td align="center" style="padding-top:0px;padding-bottom:10px;padding-right:0;padding-left:0;text-align:center;font-size:18px;line-height:28px;font-weight:bold;">
<span>We\'re here to help you do your thing.</span>
</td>
</tr>
<tr>
<td align="center" style="padding-top:0px;padding-bottom:0px;padding-right:0;padding-left:0;text-align:center">
<p style="text-align:center;margin-top:0px;margin-bottom:0px;gdsherpa-regular;;font-size:14px;line-height:24px">
<a href="https://wpvivid.com/contact-us">Contact Us</a> or <a href="https://twitter.com/wpvividcom">Twitter</a>
</p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tbody>
<tr>
<td valign="top" style="font-size:0px;line-height:0px;padding-top:0px;padding-right:0px;padding-bottom:0px;padding-left:0px">
<img src="https://wpvivid.com/wp-content/uploads/2019/03/unnamed6.jpg" width="600" height="5" style="display:block;width:100%;max-width:600px;min-width:10px;height:5px">
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#F5F7F8">
<tbody>
<tr>
<td bgcolor="#F5F7F8" style="padding-top:0px;padding-bottom:0px">
<div style="max-width:600px;margin-top:0;margin-bottom:0;margin-right:auto;margin-left:auto;padding-left:20px;padding-right:20px">
<table bgcolor="#F5F7F8" align="center" style="border-spacing:0;color:#111111;margin:0 auto;width:100%;max-width:600px">
<tbody>
<tr>
<td style="padding-top:0;padding-bottom:0;padding-right:0;padding-left:0">
<table width="100%" style="border-spacing:0;color:#111111">
<tbody>
<tr>
<td style="padding-top:40px;padding-bottom:0px;padding-left:40px;padding-right:40px;background-color:#f5f7f8;width:100%;text-align:left">
<p style="margin-top:0px;line-height:0px;margin-bottom:0px;font-size:4px"> </p>
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>';
return $body;
}
public static function wpvivid_send_debug_info($user_email,$server_type,$host_provider,$comment)
{
$send_to = 'support@wpvivid.com';
$subject = 'Debug Information';
$body = '<div>User\'s email: '.$user_email.'.</div>';
$body .= '<div>Server type: '.$server_type.'.</div>';
$body .= '<div>Host provider: '.$host_provider.'.</div>';
$body .= '<div>Comment: '.$comment.'.</div>';
$headers = array('Content-Type: text/html; charset=UTF-8');
$files=WPvivid_error_log::get_error_log();
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$backup_path=WPvivid_Setting::get_backupdir();
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_path.DIRECTORY_SEPARATOR.'wpvivid_debug.zip';
if(file_exists($path))
{
@wp_delete_file( $path);
}
$archive = new WPvivid_PclZip($path);
if(!empty($files))
{
if(!$archive->add($files,WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH))
{
echo esc_html($archive->errorInfo(true)).' <a href="'.esc_url(admin_url()).'admin.php?page=WPvivid">retry</a>.';
exit;
}
}
global $wpvivid_plugin;
$server_info=wp_json_encode($wpvivid_plugin->get_website_info());
$server_file_path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_path.DIRECTORY_SEPARATOR.'wpvivid_server_info.json';
if(file_exists($server_file_path))
{
@wp_delete_file( $server_file_path);
}
$server_file = fopen($server_file_path, 'x');
fclose($server_file);
file_put_contents($server_file_path,$server_info);
if(!$archive->add($server_file_path,WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH))
{
echo esc_html($archive->errorInfo(true)).' <a href="'.esc_url(admin_url()).'admin.php?page=WPvivid">retry</a>.';
exit;
}
@wp_delete_file( $server_file_path);
$attachments[] = $path;
if(wp_mail( $send_to, $subject, $body,$headers,$attachments)===false)
{
$ret['result']='failed';
$ret['error']=__('Unable to send email. Please check the configuration of email server.', 'wpvivid-backuprestore');
}
else
{
$ret['result']='success';
}
@wp_delete_file($path);
return $ret;
}
} includes/class-wpvivid-mysqldump.php 0000644 00000127337 15132770567 0013741 0 ustar 00 <?php
/**
* Mysqldump File Doc Comment
*
* PHP version 5
*
* @category Library
* @package Ifsnop\Mysqldump
* @author Michael J. Calkins <clouddueling@github.com>
* @author Diego Torres <ifsnop@github.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
* @link https://github.com/ifsnop/mysqldump-php
*
*/
use Exception as Exception;
/**
* Mysqldump Class Doc Comment
*
* @category Library
* @package Ifsnop\Mysqldump
* @author Michael J. Calkins <clouddueling@github.com>
* @author Diego Torres <ifsnop@github.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
* @link https://github.com/ifsnop/mysqldump-php
*
*/
class WPvivid_Mysqldump
{
// Same as mysqldump
const MAXLINESIZE = 1000000;
// Available compression methods as constants
const GZIP = 'Gzip';
const BZIP2 = 'Bzip2';
const NONE = 'None';
// Available connection strings
const UTF8 = 'utf8';
const UTF8MB4 = 'utf8mb4';
/**
* Database username
* @var string
*/
public $user;
/**
* Database password
* @var string
*/
public $pass;
/**
* Destination filename, defaults to stdout
* @var string
*/
public $fileName = 'php://output';
// Internal stuff
private $tables = array();
private $views = array();
private $triggers = array();
private $procedures = array();
private $events = array();
//private $dbHandler = null;
private $dbType;
private $compressManager;
private $typeAdapter;
private $dumpSettings = array();
private $version;
private $tableColumnTypes = array();
public $log=false;
public $task_id='';
/**
* database name, parsed from dsn
* @var string
*/
private $dbName;
/**
* host name, parsed from dsn
* @var string
*/
private $host;
/**
* dsn string parsed as an array
* @var array
*/
private $dsnArray = array();
public $last_query_string='';
public function __construct(
$host = '',
$dbname='',
$user = '',
$pass = '',
$is_additional_db = false,
$dumpSettings = array()
) {
$dumpSettingsDefault = array(
'include-tables' => array(),
'exclude-tables' => array(),
'compress' => WPvivid_Mysqldump::NONE,
'init_commands' => array(),
'no-data' => array(),
'reset-auto-increment' => false,
'add-drop-database' => false,
'add-drop-table' => false,
'add-drop-trigger' => true,
'add-locks' => true,
'complete-insert' => false,
'databases' => false,
'default-character-set' => WPvivid_Mysqldump::UTF8,
'disable-keys' => true,
'extended-insert' => false,
'events' => false,
'hex-blob' => true, /* faster than escaped content */
'net_buffer_length' => self::MAXLINESIZE,
'no-autocommit' => false,
'no-create-info' => false,
'lock-tables' => false,
'routines' => false,
'single-transaction' => true,
'skip-triggers' => false,
'skip-tz-utc' => false,
'skip-comments' => false,
'skip-dump-date' => false,
'where' => '',
/* deprecated */
'disable-foreign-keys-check' => true,
'site_url'=>'',
'home_url'=>'',
'content_url'=>'',
'prefix'=>''
);
if(defined('DB_CHARSET'))
{
$dumpSettingsDefault['default-character-set']=DB_CHARSET;
}
$this->dbType=$this->get_db_type($is_additional_db);
$this->user = $user;
$this->pass = $pass;
$this->host=$host;
$this->dbName=$dbname;
$this->dumpSettings = self::array_replace_recursive($dumpSettingsDefault, $dumpSettings);
$this->dumpSettings['init_commands'][] = "SET NAMES " . WPvivid_Mysqldump::UTF8MB4;
if (false === $this->dumpSettings['skip-tz-utc'])
{
$this->dumpSettings['init_commands'][] = "SET TIME_ZONE='+00:00'";
}
$diff = array_diff(array_keys($this->dumpSettings), array_keys($dumpSettingsDefault));
if (count($diff)>0) {
throw new Exception("Unexpected value in dumpSettings: (" . esc_html(implode(",", $diff)) . ")");
}
if ( !is_array($this->dumpSettings['include-tables']) ||
!is_array($this->dumpSettings['exclude-tables']) ) {
throw new Exception("Include-tables and exclude-tables should be arrays");
}
// Dump the same views as tables, mimic mysqldump behaviour
$this->dumpSettings['include-views'] = $this->dumpSettings['include-tables'];
// Create a new compressManager to manage compressed output
$this->compressManager = WPvividCompressManagerFactory::create($this->dumpSettings['compress']);
}
public function get_db_type($is_additional_db)
{
if($is_additional_db){
return 'mysql';
}
else {
$common_setting = WPvivid_Setting::get_setting(false, 'wpvivid_common_setting');
$db_connect_method = isset($common_setting['options']['wpvivid_common_setting']['db_connect_method']) ? $common_setting['options']['wpvivid_common_setting']['db_connect_method'] : 'wpdb';
if ($db_connect_method === 'wpdb') {
return 'wpdb';
} else {
return 'mysql';
}
}
}
/**
* Destructor of Mysqldump. Unsets dbHandlers and database objects.
*
*/
public function __destruct()
{
//$this->dbHandler = null;
}
/**
* Custom array_replace_recursive to be used if PHP < 5.3
* Replaces elements from passed arrays into the first array recursively
*
* @param array $array1 The array in which elements are replaced
* @param array $array2 The array from which elements will be extracted
*
* @return array Returns an array, or NULL if an error occurs.
*/
public static function array_replace_recursive($array1, $array2)
{
if (function_exists('array_replace_recursive')) {
return array_replace_recursive($array1, $array2);
}
foreach ($array2 as $key => $value) {
if (is_array($value)) {
$array1[$key] = self::array_replace_recursive($array1[$key], $value);
} else {
$array1[$key] = $value;
}
}
return $array1;
}
/**
* Parse DSN string and extract dbname value
* Several examples of a DSN string
* mysql:host=localhost;dbname=testdb
* mysql:host=localhost;port=3307;dbname=testdb
* mysql:unix_socket=/tmp/mysql.sock;dbname=testdb
*
* @param string $dsn dsn string to parse
*/
private function parseDsn($dsn)
{
if (empty($dsn) || (false === ($pos = strpos($dsn, ":")))) {
throw new Exception("Empty DSN string");
}
$this->dsn = $dsn;
$this->dbType = strtolower(substr($dsn, 0, $pos));
if (empty($this->dbType)) {
throw new Exception("Missing database type from DSN string");
}
$dsn = substr($dsn, $pos + 1);
foreach(explode(";", $dsn) as $kvp) {
$kvpArr = explode("=", $kvp);
$this->dsnArray[strtolower($kvpArr[0])] = $kvpArr[1];
}
if (empty($this->dsnArray['host']) &&
empty($this->dsnArray['unix_socket'])) {
throw new Exception("Missing host from DSN string");
}
$this->host = (!empty($this->dsnArray['host'])) ?
$this->dsnArray['host'] :
$this->dsnArray['unix_socket'];
if (empty($this->dsnArray['dbname'])) {
throw new Exception("Missing database name from DSN string");
}
$this->dbName = $this->dsnArray['dbname'];
return true;
}
/**
* Connect with PDO
*
* @return null
*/
private function connect()
{
// Connecting with PDO
/*
try {
switch ($this->dbType) {
case 'sqlite':
$this->dbHandler = @new PDO("sqlite:" . $this->dbName, null, null, $this->pdoSettings);
break;
case 'mysql':
case 'pgsql':
case 'dblib':
$this->dbHandler = @new PDO(
$this->dsn,
$this->user,
$this->pass,
$this->pdoSettings
);
// Execute init commands once connected
foreach($this->dumpSettings['init_commands'] as $stmt) {
$this->dbHandler->exec($stmt);
}
// Store server version
$this->version = $this->dbHandler->getAttribute(PDO::ATTR_SERVER_VERSION);
break;
default:
throw new Exception("Unsupported database type (" . $this->dbType . ")");
}
} catch (PDOException $e) {
throw new Exception(
"Connection to " . $this->dbType . " failed with message: " .
$e->getMessage()
);
}*/
$this->typeAdapter = WPvividTypeAdapterFactory::create($this->dbType, null);
$this->typeAdapter->connect($this->host,$this->dbName,$this->user,$this->pass,$this->dumpSettings['init_commands']);
}
/**
* Main call
*
* @param string $filename Name of file to write sql dump to
* @return null
*/
public function start($filename = '')
{
// Output file can be redefined here
if (!empty($filename)) {
$this->fileName = $filename;
}
// Connect to database
$this->connect();
// Create output file
$this->compressManager->open($this->fileName);
// Write some basic info to output file
$this->compressManager->write($this->getDumpFileHeader());
$this->compressManager->write('/* # site_url: '.$this->dumpSettings['site_url'].' */;'.PHP_EOL);
$this->compressManager->write('/* # home_url: '.$this->dumpSettings['home_url'].' */;'.PHP_EOL);
$this->compressManager->write('/* # content_url: '.$this->dumpSettings['content_url'].' */;'.PHP_EOL);
$upload_dir = wp_upload_dir();
$this->compressManager->write('/* # upload_url: '.$upload_dir['baseurl'].' */;'.PHP_EOL);
$this->compressManager->write('/* # table_prefix: '.$this->dumpSettings['prefix'].' */;'.PHP_EOL.PHP_EOL.PHP_EOL);
// Store server settings and use sanner defaults to dump
$this->compressManager->write(
$this->typeAdapter->backup_parameters($this->dumpSettings)
);
if ($this->dumpSettings['databases']) {
$this->compressManager->write(
$this->typeAdapter->getDatabaseHeader($this->dbName)
);
if ($this->dumpSettings['add-drop-database']) {
$this->compressManager->write(
$this->typeAdapter->add_drop_database($this->dbName)
);
}
}
// Get table, view and trigger structures from database
$this->getDatabaseStructure();
if ($this->dumpSettings['databases']) {
$this->compressManager->write(
$this->typeAdapter->databases($this->dbName)
);
}
// If there still are some tables/views in include-tables array,
// that means that some tables or views weren't found.
// Give proper error and exit.
// This check will be removed once include-tables supports regexps
if (0 < count($this->dumpSettings['include-tables'])) {
$name = implode(",", $this->dumpSettings['include-tables']);
throw new Exception("Table (" . esc_html($name) . ") not found in database");
}
$this->exportTables();
/*
global $wpvivid_plugin;
$this->exportTables();
if($this -> privileges['SHOW VIEW'] == 0){
$wpvivid_plugin->wpvivid_log->WriteLog('The lack of SHOW VIEW privilege, the backup will skip exportViews() to continue.','notice');
}else{
$this->exportViews();
}
if($this -> privileges['TRIGGER'] == 0){
$wpvivid_plugin->wpvivid_log->WriteLog('The lack of TRIGGER privilege, the backup will skip exportTriggers() to continue.','notice');
}else{
$this->exportTriggers();
}
if($this -> privileges['CREATE ROUTINE'] == 0){
$wpvivid_plugin->wpvivid_log->WriteLog('The lack of CREATE ROUTINE privilege, the backup will skip exportProcedures() to continue.','notice');
}else{
$this->exportProcedures();
}
if($this -> privileges['EVENT'] == 0){
$wpvivid_plugin->wpvivid_log->WriteLog('The lack of EVENT privilege, the backup will skip exportEvents() to continue.','notice');
}else{
$this->exportEvents();
}
*/
// Restore saved parameters
$this->compressManager->write(
$this->typeAdapter->restore_parameters($this->dumpSettings)
);
// Write some stats to output file
$this->compressManager->write($this->getDumpFileFooter());
// Close output file
$this->compressManager->close();
}
/**
* Returns header for dump file
*
* @return string
*/
private function getDumpFileHeader()
{
$header = '';
if ( !$this->dumpSettings['skip-comments'] ) {
// Some info about software, source and time
$header = "-- mysqldump-php https://github.com/ifsnop/mysqldump-php" . PHP_EOL .
"--" . PHP_EOL .
"-- Host: {$this->host}\tDatabase: {$this->dbName}" . PHP_EOL .
"-- ------------------------------------------------------" . PHP_EOL;
if ( !empty($this->version) ) {
$header .= "-- Server version \t" . $this->version . PHP_EOL;
}
if ( !$this->dumpSettings['skip-dump-date'] ) {
$header .= "-- Date: " . gmdate('r') . PHP_EOL . PHP_EOL;
}
}
return $header;
}
/**
* Returns footer for dump file
*
* @return string
*/
private function getDumpFileFooter()
{
$footer = '';
if (!$this->dumpSettings['skip-comments']) {
$footer .= '-- Dump completed';
if (!$this->dumpSettings['skip-dump-date']) {
$footer .= ' on: ' . gmdate('r');
}
$footer .= PHP_EOL;
}
return $footer;
}
/**
* Reads table and views names from database.
* Fills $this->tables array so they will be dumped later.
*
* @return null
*/
private function getDatabaseStructure()
{
// Listing all tables from database
if (empty($this->dumpSettings['include-tables'])) {
// include all tables for now, blacklisting happens later
foreach ( $this->query($this->typeAdapter->show_tables($this->dbName)) as $row) {
array_push($this->tables, current($row));
}
} else {
// include only the tables mentioned in include-tables
foreach ($this->query($this->typeAdapter->show_tables($this->dbName)) as $row) {
if (in_array(current($row), $this->dumpSettings['include-tables'], true)) {
array_push($this->tables, current($row));
$elem = array_search(
current($row),
$this->dumpSettings['include-tables']
);
unset($this->dumpSettings['include-tables'][$elem]);
}
}
}
// Listing all views from database
if (empty($this->dumpSettings['include-views'])) {
// include all views for now, blacklisting happens later
foreach ($this->query($this->typeAdapter->show_views($this->dbName)) as $row) {
array_push($this->views, current($row));
}
} else {
// include only the tables mentioned in include-tables
foreach ($this->query($this->typeAdapter->show_views($this->dbName)) as $row) {
if (in_array(current($row), $this->dumpSettings['include-views'], true)) {
array_push($this->views, current($row));
$elem = array_search(
current($row),
$this->dumpSettings['include-views']
);
unset($this->dumpSettings['include-views'][$elem]);
}
}
}
// Listing all triggers from database
if (false === $this->dumpSettings['skip-triggers']) {
foreach ($this->query($this->typeAdapter->show_triggers($this->dbName)) as $row) {
array_push($this->triggers, $row['Trigger']);
}
}
// Listing all procedures from database
if ($this->dumpSettings['routines']) {
foreach ($this->query($this->typeAdapter->show_procedures($this->dbName)) as $row) {
array_push($this->procedures, $row['procedure_name']);
}
}
// Listing all events from database
if ($this->dumpSettings['events']) {
foreach ($this->query($this->typeAdapter->show_events($this->dbName)) as $row) {
array_push($this->events, $row['event_name']);
}
}
}
/**
* Compare if $table name matches with a definition inside $arr
* @param $table string
* @param $arr array with strings or patterns
* @return bool
*/
private function matches($table, $arr) {
$match = false;
foreach ($arr as $pattern) {
if ( '/' != $pattern[0] ) {
continue;
}
if ( 1 == preg_match($pattern, $table) ) {
$match = true;
}
}
return in_array($table, $arr) || $match;
}
/**
* Exports all the tables selected from database
*
* @return null
*/
private function exportTables()
{
// Exporting tables one by one
$i=0;
$i_step=0;
if($this->task_id!=='')
{
$options_name[]='backup_options';
//$options_name[]='ismerge';
$options=WPvivid_taskmanager::get_task_options($this->task_id,$options_name);
if($options['backup_options']['ismerge'])
{
if(isset($options['backup_options']['backup']['backup_type'])) {
$i_step = intval(1 / (sizeof($options['backup_options']['backup']['backup_type']) + 1) * 100);
}
else{
$i_step = intval(1 / (sizeof($options['backup_options']['backup']) + 1) * 100);
}
}
else
{
if(isset($options['backup_options']['backup']['backup_type'])) {
$i_step = intval(1 / sizeof($options['backup_options']['backup']['backup_type']) * 100);
}
else{
$i_step = intval(1 / sizeof($options['backup_options']['backup']) * 100);
}
}
}
foreach ($this->tables as $table)
{
if ( $this->matches($table, $this->dumpSettings['exclude-tables']) )
{
continue;
}
if($this->task_id!=='')
{
$message='Preparing to dump table '.$table;
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog($message,'notice');
WPvivid_taskmanager::update_backup_sub_task_progress($this->task_id,'backup',WPVIVID_BACKUP_TYPE_DB,0,$message);
}
$this->getTableStructure($table);
if($this->tableColumnTypes[$table]===false)
{
global $wpvivid_plugin;
$message='get Table Structure failed. table:'.$table;
$wpvivid_plugin->wpvivid_log->WriteLog($message,'notice');
continue;
}
if ( false === $this->dumpSettings['no-data'] ) { // don't break compatibility with old trigger
$this->listValues($table);
} else if ( true === $this->dumpSettings['no-data']
|| $this->matches($table, $this->dumpSettings['no-data']) ) {
continue;
} else {
$this->listValues($table);
}
$i++;
if($this->task_id!=='')
{
$i_progress=intval($i/sizeof($this->tables)*$i_step);
WPvivid_taskmanager::update_backup_main_task_progress($this->task_id,'backup',$i_progress,0);
}
}
return ;
}
/**
* Exports all the views found in database
*
* @return null
*/
private function exportViews()
{
if (false === $this->dumpSettings['no-create-info']) {
// Exporting views one by one
foreach ($this->views as $view) {
if ( $this->matches($view, $this->dumpSettings['exclude-tables']) ) {
continue;
}
$this->tableColumnTypes[$view] = $this->getTableColumnTypes($view);
$this->getViewStructureTable($view);
}
foreach ($this->views as $view) {
if ( $this->matches($view, $this->dumpSettings['exclude-tables']) ) {
continue;
}
$this->getViewStructureView($view);
}
}
}
/**
* Exports all the triggers found in database
*
* @return null
*/
private function exportTriggers()
{
// Exporting triggers one by one
foreach ($this->triggers as $trigger) {
$this->getTriggerStructure($trigger);
}
}
/**
* Exports all the procedures found in database
*
* @return null
*/
private function exportProcedures()
{
// Exporting triggers one by one
foreach ($this->procedures as $procedure) {
$this->getProcedureStructure($procedure);
}
}
/**
* Exports all the events found in database
*
* @return null
*/
private function exportEvents()
{
// Exporting triggers one by one
foreach ($this->events as $event) {
$this->getEventStructure($event);
}
}
/**
* Table structure extractor
*
* @todo move specific mysql code to typeAdapter
* @param string $tableName Name of table to export
* @return null
*/
private function getTableStructure($tableName)
{
if (!$this->dumpSettings['no-create-info']) {
$ret = '';
if (!$this->dumpSettings['skip-comments']) {
$ret = "--" . PHP_EOL .
"-- Table structure for table `$tableName`" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL;
}
$stmt = $this->typeAdapter->show_create_table($tableName);
foreach ($this->query($stmt) as $r)
{
$this->compressManager->write($ret);
if ($this->dumpSettings['add-drop-table']) {
$this->compressManager->write(
$this->typeAdapter->drop_table($tableName)
);
}
$this->compressManager->write(
$this->typeAdapter->create_table($r, $this->dumpSettings)
);
break;
}
}
$this->tableColumnTypes[$tableName] = $this->getTableColumnTypes($tableName);
return;
}
/**
* Store column types to create data dumps and for Stand-In tables
*
* @param string $tableName Name of table to export
* @return array type column types detailed
*/
private function getTableColumnTypes($tableName) {
$columnTypes = array();
$columns = $this->query(
$this->typeAdapter->show_columns($tableName)
);
if($columns===false)
{
global $wpvivid_plugin;
$error=$this->typeAdapter->errorInfo();
if(isset($error[2])){
$error = 'Error: '.$error[2];
}
else{
$error = '';
}
$message='Show columns failed. '.$error;
$wpvivid_plugin->wpvivid_log->WriteLog($message, 'warning');
$columns = $this->query(
'DESCRIBE '.$tableName
);
if($columns===false)
{
$error=$this->typeAdapter->errorInfo();
if(isset($error[2])){
$error = 'Error: '.$error[2];
}
else{
$error = '';
}
$message='DESCRIBE failed. '.$error;
$wpvivid_plugin->wpvivid_log->WriteLog($message, 'warning');
return false;
}
}
foreach($columns as $key => $col) {
$types = $this->typeAdapter->parseColumnType($col);
$columnTypes[$col['Field']] = array(
'is_numeric'=> $types['is_numeric'],
'is_blob' => $types['is_blob'],
'type' => $types['type'],
'type_sql' => $col['Type'],
'is_virtual' => $types['is_virtual']
);
}
return $columnTypes;
}
/**
* View structure extractor, create table (avoids cyclic references)
*
* @todo move mysql specific code to typeAdapter
* @param string $viewName Name of view to export
* @return null
*/
private function getViewStructureTable($viewName)
{
if (!$this->dumpSettings['skip-comments']) {
$ret = "--" . PHP_EOL .
"-- Stand-In structure for view `${viewName}`" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL;
$this->compressManager->write($ret);
}
$stmt = $this->typeAdapter->show_create_view($viewName);
// create views as tables, to resolve dependencies
foreach ($this->query($stmt) as $r) {
if ($this->dumpSettings['add-drop-table']) {
$this->compressManager->write(
$this->typeAdapter->drop_view($viewName)
);
}
$this->compressManager->write(
$this->createStandInTable($viewName)
);
break;
}
}
/**
* Write a create table statement for the table Stand-In, show create
* table would return a create algorithm when used on a view
*
* @param string $viewName Name of view to export
* @return string create statement
*/
function createStandInTable($viewName) {
$ret = array();
foreach($this->tableColumnTypes[$viewName] as $k => $v) {
$ret[] = "`${k}` ${v['type_sql']}";
}
$ret = implode(PHP_EOL . ",", $ret);
$ret = "CREATE TABLE IF NOT EXISTS `$viewName` (" .
PHP_EOL . $ret . PHP_EOL . ");" . PHP_EOL;
return $ret;
}
/**
* View structure extractor, create view
*
* @todo move mysql specific code to typeAdapter
* @param string $viewName Name of view to export
* @return null
*/
private function getViewStructureView($viewName)
{
if (!$this->dumpSettings['skip-comments']) {
$ret = "--" . PHP_EOL .
"-- View structure for view `${viewName}`" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL;
$this->compressManager->write($ret);
}
$stmt = $this->typeAdapter->show_create_view($viewName);
// create views, to resolve dependencies
// replacing tables with views
foreach ($this->query($stmt) as $r) {
// because we must replace table with view, we should delete it
$this->compressManager->write(
$this->typeAdapter->drop_view($viewName)
);
$this->compressManager->write(
$this->typeAdapter->create_view($r)
);
break;
}
}
/**
* Trigger structure extractor
*
* @param string $triggerName Name of trigger to export
* @return null
*/
private function getTriggerStructure($triggerName)
{
$stmt = $this->typeAdapter->show_create_trigger($triggerName);
foreach ($this->query($stmt) as $r) {
if ($this->dumpSettings['add-drop-trigger']) {
$this->compressManager->write(
$this->typeAdapter->add_drop_trigger($triggerName)
);
}
$this->compressManager->write(
$this->typeAdapter->create_trigger($r)
);
return;
}
}
/**
* Procedure structure extractor
*
* @param string $procedureName Name of procedure to export
* @return null
*/
private function getProcedureStructure($procedureName)
{
if (!$this->dumpSettings['skip-comments']) {
$ret = "--" . PHP_EOL .
"-- Dumping routines for database '" . $this->dbName . "'" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL;
$this->compressManager->write($ret);
}
$stmt = $this->typeAdapter->show_create_procedure($procedureName);
foreach ($this->query($stmt) as $r) {
$this->compressManager->write(
$this->typeAdapter->create_procedure($r, $this->dumpSettings)
);
return;
}
}
/**
* Event structure extractor
*
* @param string $eventName Name of event to export
* @return null
*/
private function getEventStructure($eventName)
{
if (!$this->dumpSettings['skip-comments']) {
$ret = "--" . PHP_EOL .
"-- Dumping events for database '" . $this->dbName . "'" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL;
$this->compressManager->write($ret);
}
$stmt = $this->typeAdapter->show_create_event($eventName);
foreach ($this->query($stmt) as $r) {
$this->compressManager->write(
$this->typeAdapter->create_event($r, $this->dumpSettings)
);
return;
}
}
/**
* Escape values with quotes when needed
*
* @param string $tableName Name of table which contains rows
* @param array $row Associative array of column names and values to be quoted
*
* @return string
*/
private function escape($tableName, $row)
{
$ret = array();
$columnTypes = $this->tableColumnTypes[$tableName];
foreach ($row as $colName => $colValue) {
if (is_null($colValue)) {
$ret[] = "NULL";
} elseif ($this->dumpSettings['hex-blob'] && $columnTypes[$colName]['is_blob']) {
if ($columnTypes[$colName]['type'] == 'bit' || !empty($colValue)) {
$ret[] = "0x${colValue}";
} else {
$ret[] = "''";
}
} elseif ($columnTypes[$colName]['is_numeric']) {
$ret[] = $colValue;
} else {
$ret[] = $this->typeAdapter->quote($colValue);
}
}
return $ret;
}
/**
* Table rows extractor
*
* @param string $tableName Name of table to export
*
* @return null
*/
private function listValues($tableName)
{
$this->prepareListValues($tableName);
$onlyOnce = true;
$lineSize = 0;
$colStmt = $this->getColumnStmt($tableName);
global $wpdb;
$prefix=$wpdb->base_prefix;
if($this->dbType=='wpdb')
{
$start=0;
$limit_count=5000;
$sum =$wpdb->get_var("SELECT COUNT(1) FROM `{$tableName}`");
if(substr($tableName, strlen($prefix))=='options')
{
$stmt = "SELECT " . implode(",", $colStmt) . " FROM `$tableName` WHERE option_name !='wpvivid_task_list'";
}
else
{
$stmt = "SELECT " . implode(",", $colStmt) . " FROM `$tableName`";
}
if ($this->dumpSettings['where']) {
$stmt .= " WHERE {$this->dumpSettings['where']}";
}
$i=0;
$i_check_cancel=0;
$count=0;
while($sum > $start)
{
$limit = " LIMIT {$limit_count} OFFSET {$start}";
$query=$stmt.$limit;
$resultSet = $this->query($query);
if($resultSet===false)
{
global $wpvivid_plugin;
$error=$this->typeAdapter->errorInfo();
if(isset($error[2])){
$error = 'Error: '.$error[2];
}
else{
$error = '';
}
$message='listValues failed. '.$error;
$wpvivid_plugin->wpvivid_log->WriteLog($message, 'warning');
$this->endListValues($tableName);
return ;
}
foreach ($resultSet as $row)
{
$i++;
$vals = $this->escape($tableName, $row);
foreach($vals as $key => $value){
if($value === '\'0000-00-00 00:00:00\'')
$vals[$key] = '\'1999-01-01 00:00:00\'';
}
if ($onlyOnce || !$this->dumpSettings['extended-insert'])
{
if ($this->dumpSettings['complete-insert'])
{
$lineSize += $this->compressManager->write(
"INSERT INTO `$tableName` (" .
implode(", ", $colStmt) .
") VALUES (" . implode(",", $vals) . ")"
);
} else {
$lineSize += $this->compressManager->write(
"INSERT INTO `$tableName` VALUES (" . implode(",", $vals) . ")"
);
}
$onlyOnce = false;
} else {
$lineSize += $this->compressManager->write(",(" . implode(",", $vals) . ")");
}
if (($lineSize > $this->dumpSettings['net_buffer_length']) ||
!$this->dumpSettings['extended-insert']) {
$onlyOnce = true;
$lineSize = $this->compressManager->write(";" . PHP_EOL);
}
if($i>=200000)
{
$count+=$i;
$i=0;
if($this->task_id!=='')
{
$i_check_cancel++;
if($i_check_cancel>5)
{
$i_check_cancel=0;
global $wpvivid_plugin;
$wpvivid_plugin->check_cancel_backup($this->task_id);
}
$message='Dumping table '.$tableName.', rows dumped: '.$count.' rows.';
WPvivid_taskmanager::update_backup_sub_task_progress($this->task_id,'backup',WPVIVID_BACKUP_TYPE_DB,0,$message);
}
}
}
$this->typeAdapter->closeCursor($resultSet);
$start += $limit_count;
}
if (!$onlyOnce) {
$this->compressManager->write(";" . PHP_EOL);
}
$this->endListValues($tableName);
}
else
{
if(substr($tableName, strlen($prefix))=='options')
{
$stmt = "SELECT " . implode(",", $colStmt) . " FROM `$tableName` WHERE option_name !='wpvivid_task_list'";
}
else
{
$stmt = "SELECT " . implode(",", $colStmt) . " FROM `$tableName`";
}
if ($this->dumpSettings['where']) {
$stmt .= " WHERE {$this->dumpSettings['where']}";
}
$resultSet = $this->query($stmt);
if($resultSet===false)
{
global $wpvivid_plugin;
$error=$this->typeAdapter->errorInfo();
if(isset($error[2])){
$error = 'Error: '.$error[2];
}
else{
$error = '';
}
$message='listValues failed. '.$error;
$wpvivid_plugin->wpvivid_log->WriteLog($message, 'warning');
$this->endListValues($tableName);
return ;
}
$i=0;
$i_check_cancel=0;
$count=0;
foreach ($resultSet as $row)
{
$i++;
$vals = $this->escape($tableName, $row);
foreach($vals as $key => $value){
if($value === '\'0000-00-00 00:00:00\'')
$vals[$key] = '\'1999-01-01 00:00:00\'';
}
if ($onlyOnce || !$this->dumpSettings['extended-insert'])
{
if ($this->dumpSettings['complete-insert'])
{
$lineSize += $this->compressManager->write(
"INSERT INTO `$tableName` (" .
implode(", ", $colStmt) .
") VALUES (" . implode(",", $vals) . ")"
);
} else {
$lineSize += $this->compressManager->write(
"INSERT INTO `$tableName` VALUES (" . implode(",", $vals) . ")"
);
}
$onlyOnce = false;
} else {
$lineSize += $this->compressManager->write(",(" . implode(",", $vals) . ")");
}
if (($lineSize > $this->dumpSettings['net_buffer_length']) ||
!$this->dumpSettings['extended-insert']) {
$onlyOnce = true;
$lineSize = $this->compressManager->write(";" . PHP_EOL);
}
if($i>=200000)
{
$count+=$i;
$i=0;
if($this->task_id!=='')
{
$i_check_cancel++;
if($i_check_cancel>5)
{
$i_check_cancel=0;
global $wpvivid_plugin;
$wpvivid_plugin->check_cancel_backup($this->task_id);
}
$message='Dumping table '.$tableName.', rows dumped: '.$count.' rows.';
WPvivid_taskmanager::update_backup_sub_task_progress($this->task_id,'backup',WPVIVID_BACKUP_TYPE_DB,0,$message);
}
}
}
$this->typeAdapter->closeCursor($resultSet);
//$resultSet->closeCursor();
if (!$onlyOnce) {
$this->compressManager->write(";" . PHP_EOL);
}
$this->endListValues($tableName);
}
}
/**
* Table rows extractor, append information prior to dump
*
* @param string $tableName Name of table to export
*
* @return null
*/
function prepareListValues($tableName)
{
if (!$this->dumpSettings['skip-comments']) {
$this->compressManager->write(
"--" . PHP_EOL .
"-- Dumping data for table `$tableName`" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL
);
}
if ($this->dumpSettings['single-transaction']) {
$this->exec($this->typeAdapter->setup_transaction());
$this->exec($this->typeAdapter->start_transaction());
}
if ($this->dumpSettings['lock-tables'])
{
$this->typeAdapter->lock_table($tableName);
//if($this -> privileges['LOCK TABLES'] == 0)
//{
//global $wpvivid_plugin;
// $wpvivid_plugin->wpvivid_log->WriteLog('The lack of LOCK TABLES privilege, the backup will skip lock_tables() to continue.','notice');
//}else{
// $this->typeAdapter->lock_table($tableName);
//}
}
if ($this->dumpSettings['add-locks']) {
$this->compressManager->write(
$this->typeAdapter->start_add_lock_table($tableName)
);
}
if ($this->dumpSettings['disable-keys']) {
$this->compressManager->write(
$this->typeAdapter->start_add_disable_keys($tableName)
);
}
// Disable autocommit for faster reload
if ($this->dumpSettings['no-autocommit']) {
$this->compressManager->write(
$this->typeAdapter->start_disable_autocommit()
);
}
return;
}
/**
* Table rows extractor, close locks and commits after dump
*
* @param string $tableName Name of table to export
*
* @return null
*/
function endListValues($tableName)
{
if ($this->dumpSettings['disable-keys']) {
$this->compressManager->write(
$this->typeAdapter->end_add_disable_keys($tableName)
);
}
if ($this->dumpSettings['add-locks']) {
$this->compressManager->write(
$this->typeAdapter->end_add_lock_table($tableName)
);
}
if ($this->dumpSettings['single-transaction']) {
$this->exec($this->typeAdapter->commit_transaction());
}
if ($this->dumpSettings['lock-tables']) {
$this->typeAdapter->unlock_table($tableName);
}
// Commit to enable autocommit
if ($this->dumpSettings['no-autocommit']) {
$this->compressManager->write(
$this->typeAdapter->end_disable_autocommit()
);
}
$this->compressManager->write(PHP_EOL);
return;
}
/**
* Build SQL List of all columns on current table
*
* @param string $tableName Name of table to get columns
*
* @return string SQL sentence with columns
*/
function getColumnStmt($tableName)
{
$colStmt = array();
foreach($this->tableColumnTypes[$tableName] as $colName => $colType) {
if ($colType['type'] == 'bit' && $this->dumpSettings['hex-blob']) {
$colStmt[] = "LPAD(HEX(`${colName}`),2,'0') AS `${colName}`";
} else if ($colType['is_blob'] && $this->dumpSettings['hex-blob']) {
$colStmt[] = "HEX(`${colName}`) AS `${colName}`";
} else if ($colType['is_virtual']) {
$this->dumpSettings['complete-insert'] = true;
continue;
} else {
$colStmt[] = "`${colName}`";
}
}
return $colStmt;
}
public function query($query_string)
{
$this->last_query_string=$query_string;
return $this->typeAdapter->query($query_string);
}
private function exec($query_string)
{
$this->last_query_string=$query_string;
return $this->typeAdapter->query($query_string);
}
}
includes/class-wpvivid-restore-data.php 0000644 00000003102 15132770567 0014257 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_restore_data
{
public $restore_data_file;
public $restore_log_file;
public $restore_log=false;
public $restore_cache=false;
public function __construct()
{
$dir=WPvivid_Setting::get_backupdir();
$this->restore_data_file= WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.'wpvivid_restoredata';
$this->restore_log_file= WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.'wpvivid_restore_log.txt';
}
public function write_log($message,$type)
{
if($this->restore_log===false)
{
$this->restore_log=new WPvivid_Log();
$this->restore_log->OpenLogFile($this->restore_log_file,'has_folder');
}
clearstatcache();
if(filesize($this->restore_log_file)>4*1024*1024)
{
$this->restore_log->CloseFile();
wp_delete_file($this->restore_log_file);
$this->restore_log=null;
$this->restore_log=new WPvivid_Log();
$this->restore_log->OpenLogFile($this->restore_log_file,'has_folder');
}
$this->restore_log->WriteLog($message,$type);
}
public function get_log_content()
{
$file =fopen($this->restore_log_file,'r');
if(!$file)
{
return '';
}
$buffer='';
while(!feof($file))
{
$buffer .= fread($file,1024);
}
fclose($file);
return $buffer;
}
} includes/class-wpvivid-migrate.php 0000644 00000231012 15132770567 0013320 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Migrate
{
public function __construct()
{
add_filter('wpvivid_add_tab_page', array($this, 'wpvivid_add_migrate_tab_page'));
add_action('wp_ajax_wpvivid_generate_url',array( $this,'generate_url'));
add_action('wp_ajax_wpvivid_generate_url_ex', array($this, 'generate_url_ex'));
add_action('wp_ajax_wpvivid_send_backup_to_site',array( $this,'send_backup_to_site'));
add_action('wp_ajax_wpvivid_migrate_now',array( $this,'migrate_now'));
add_filter('wpvivid_backuppage_load_backuplist', array($this, 'wpvivid_backuppage_load_backuplist'));
add_action('wp_ajax_wpvivid_export_download_backup',array( $this,'export_download_backup'));
add_action('wp_ajax_wpvivid_list_upload_tasks',array( $this,'list_tasks'));
add_action('wp_ajax_wpvivid_test_connect_site',array( $this,'test_connect_site'));
add_action('wp_ajax_wpvivid_delete_transfer_key',array($this, 'delete_transfer_key'));
add_filter('wpvivid_put_transfer_key', array($this, 'wpvivid_put_transfer_key'));
add_action('wpvivid_put_transfer_key_output', array($this, 'wpvivid_put_transfer_key_output'));
add_action('wpvivid_handle_backup_failed',array($this,'wpvivid_handle_backup_failed'),9);
add_action('wpvivid_rescan_backup_list', array($this, 'wpvivid_rescan_backup_list'));
add_action('wpvivid_handle_upload_succeed',array($this,'wpvivid_deal_upload_succeed'),11);
add_action('wpvivid_add_migrate_type_output', array($this, 'wpvivid_add_migrate_type_output'),10,1);
add_filter('wpvivid_add_migrate_type', array($this, 'wpvivid_add_migrate_type'), 11, 2);
add_filter('wpvivid_migrate_descript', array($this, 'wpvivid_migrate_descript'));
add_filter('wpvivid_migrate_part_type', array($this, 'wpvivid_migrate_part_type'));
add_action('wpvivid_migrate_part_exec', array($this, 'wpvivid_migrate_part_exec'));
add_filter('wpvivid_migrate_part_note', array($this, 'wpvivid_migrate_part_note'));
add_filter('wpvivid_migrate_part_tip', array($this, 'wpvivid_migrate_part_tip'));
add_filter('wpvivid_load_migrate_js', array($this, 'wpvivid_load_migrate_js'));
add_action('wpvivid_add_migrate_js', array($this, 'wpvivid_add_migrate_js'));
}
public function wpvivid_add_migrate_tab_page($page_array){
$page_array['migrate'] = array('index' => '3', 'tab_func' => array($this, 'wpvivid_add_tab_migrate'), 'page_func' => array($this, 'wpvivid_add_page_migrate'));
$page_array['key'] = array('index' => '8', 'tab_func' => array($this, 'wpvivid_add_tab_key'), 'page_func' => array($this, 'wpvivid_add_page_key'));
return $page_array;
}
public function wpvivid_add_tab_migrate()
{
?>
<a href="#" id="wpvivid_tab_migrate" class="nav-tab wrap-nav-tab" onclick="switchTabs(event,'migrate-page')"><?php esc_html_e('Auto-Migration', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function wpvivid_add_tab_key()
{
?>
<a href="#" id="wpvivid_tab_key" class="nav-tab wrap-nav-tab" onclick="switchTabs(event,'key-page')"><?php esc_html_e('Key', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function wpvivid_load_migrate_js($html)
{
do_action('wpvivid_add_migrate_js');
return $html;
}
public function wpvivid_add_migrate_js()
{
?>
<script>
var wpvivid_home_url = '<?php
$wpvivid_siteurl = array();
$wpvivid_siteurl=WPvivid_Admin::wpvivid_get_siteurl();
echo esc_url($wpvivid_siteurl['home_url']);
?>';
jQuery('input:radio[option=migrate][name=transfer]').click(function(){
var value = jQuery(this).prop('value');
if(value === 'transfer'){
jQuery('#wpvivid_transfer_btn').show();
jQuery('#wpvivid_export_download_btn').hide();
}
else if(value === 'export'){
jQuery('#wpvivid_transfer_btn').hide();
jQuery('#wpvivid_export_download_btn').show();
}
});
//wpvivid_edit_url_button
jQuery('#wpvivid_add_remote_site_url').show();
jQuery('#wpvivid_upload_backup_percent').hide();
var wpvivid_transfer_id = '';
function wpvivid_control_transfer_lock(){
jQuery('#wpvivid_quickbackup_btn').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#wpvivid_transfer_btn').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery("#wpvivid_delete_key_button").css({'pointer-events': 'none', 'opacity': '0.4'});
}
function wpvivid_control_transfer_unlock(){
jQuery('#wpvivid_quickbackup_btn').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#wpvivid_transfer_btn').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery("#wpvivid_delete_key_button").css({'pointer-events': 'auto', 'opacity': '1'});
}
function wpvivid_click_export_backup()
{
var option_data = wpvivid_ajax_data_transfer('migrate');
var ajax_data = {
'action': 'wpvivid_export_download_backup',
'backup_options':option_data
};
migrate_task_need_update=true;
jQuery('#wpvivid_export_download_btn').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function (data)
{
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('test generate url', textStatus, errorThrown);
alert(error_message);
});
}
var wpvivid_display_get_key = false;
function wpvivid_transfer_cancel_flow()
{
jQuery('#wpvivid_transfer_cancel_btn').click(function(){
wpvivid_cancel_transfer();
});
}
function wpvivid_cancel_transfer()
{
var ajax_data= {
'action': 'wpvivid_backup_cancel',
'task_id': wpvivid_transfer_id
};
jQuery('#wpvivid_transfer_cancel_btn').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if(jsonarray.no_response)
{
var ret = confirm(jsonarray.msg);
if(ret === true)
{
wpvivid_termination_backup_task_ex(jsonarray.task_id);
}
}
else
{
jQuery('#wpvivid_current_doing').html(jsonarray.msg);
}
}
catch(err)
{
alert(err);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#wpvivid_transfer_cancel_btn').css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = wpvivid_output_ajaxerror('cancelling the backup', textStatus, errorThrown);
wpvivid_add_notice('Backup', 'Error', error_message);
});
}
function wpvivid_termination_backup_task_ex(task_id)
{
var ajax_data= {
'action': 'wpvivid_shutdown_backup',
'task_id': task_id
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
}
catch(err)
{
alert(err);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('terminationing the backup', textStatus, errorThrown);
wpvivid_add_notice('Backup', 'Error', error_message);
});
}
var migrate_task_need_update=true;
var task_recheck_times=0;
function wpvivid_check_upload_runningtask()
{
var ajax_data = {
'action': 'wpvivid_list_upload_tasks',
};
if(wpvivid_restoring === false) {
wpvivid_post_request(ajax_data, function (data) {
setTimeout(function () {
wpvivid_manage_upload_task();
}, 3000);
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.transfer_succeed_notice != false) {
jQuery('#wpvivid_backup_notice').show();
jQuery('#wpvivid_backup_notice').append(jsonarray.transfer_succeed_notice);
}
if (jsonarray.transfer_error_notice != false) {
jQuery('#wpvivid_backup_notice').show();
jQuery.each(jsonarray.transfer_error_notice, function (index, value) {
jQuery('#wpvivid_backup_notice').append(value.error_msg);
});
}
var b_need_show = false;
if (jsonarray.transfer.data.length !== 0) {
b_need_show = true;
task_recheck_times = 0;
if (jsonarray.transfer.result === 'success') {
jQuery.each(jsonarray.transfer.data, function (index, value) {
if (value.status.str === 'ready') {
wpvivid_control_transfer_lock();
jQuery('#wpvivid_upload_backup_percent').show();
jQuery('#wpvivid_upload_backup_percent').html(value.progress_html);
migrate_task_need_update = true;
}
else if (value.status.str === 'running') {
wpvivid_control_transfer_lock();
jQuery('#wpvivid_upload_backup_percent').show();
jQuery('#wpvivid_upload_backup_percent').html(value.progress_html);
migrate_task_need_update = true;
}
else if (value.status.str === 'wait_resume') {
wpvivid_control_transfer_lock();
jQuery('#wpvivid_upload_backup_percent').show();
jQuery('#wpvivid_upload_backup_percent').html(value.progress_html);
if (value.data.next_resume_time !== 'get next resume time failed.') {
wpvivid_resume_transfer(index, value.data.next_resume_time);
}
else {
wpvivid_delete_backup_task(index);
}
}
else if (value.status.str === 'no_responds') {
wpvivid_control_transfer_lock();
jQuery('#wpvivid_upload_backup_percent').show();
jQuery('#wpvivid_upload_backup_percent').html(value.progress_html);
migrate_task_need_update = true;
}
else if (value.status.str === 'completed') {
wpvivid_control_transfer_unlock();
jQuery('#wpvivid_upload_backup_percent').html(value.progress_html);
jQuery('#wpvivid_upload_backup_percent').hide();
migrate_task_need_update = true;
alert('Transfer succeeded. Please scan the backup list on the destination site to display the backup, then restore the backup.');
}
else if (value.status.str === 'error') {
wpvivid_control_transfer_unlock();
jQuery('#wpvivid_upload_backup_percent').html(value.progress_html);
jQuery('#wpvivid_upload_backup_percent').hide();
migrate_task_need_update = true;
}
});
}
wpvivid_transfer_cancel_flow();
}
else{
if(wpvivid_transfer_id != '') {
jQuery('#wpvivid_transfer_cancel_btn').css({'pointer-events': 'auto', 'opacity': '1'});
wpvivid_control_transfer_unlock();
jQuery('#wpvivid_upload_backup_percent').hide();
wpvivid_transfer_id = '';
}
}
}
catch (err) {
alert(err);
}
if (!b_need_show) {
task_recheck_times++;
if (task_recheck_times < 5) {
migrate_task_need_update = true;
}
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
migrate_task_need_update = true;
setTimeout(function () {
wpvivid_manage_upload_task();
}, 3000);
});
}
}
function wpvivid_resume_transfer(backup_id, next_resume_time){
if(next_resume_time < 0){
next_resume_time = 0;
}
next_resume_time = next_resume_time * 1000;
setTimeout("wpvivid_activate_migrate_cron()", next_resume_time);
setTimeout(function(){
task_recheck_times = 0;
migrate_task_need_update=true;
}, next_resume_time);
}
function wpvivid_manage_upload_task()
{
if(migrate_task_need_update){
migrate_task_need_update=false;
wpvivid_check_upload_runningtask();
}
else {
setTimeout(function () {
wpvivid_manage_upload_task();
}, 3000);
}
}
function wpvivid_activate_migrate_cron(){
var next_get_time = 3 * 60 * 1000;
jQuery.get(wpvivid_home_url+'/wp-cron.php');
setTimeout("wpvivid_activate_migrate_cron()", next_get_time);
setTimeout(function(){
migrate_task_need_update=true;
}, 10000);
}
function switchmigrateTabs(evt,contentName,storage_page_id) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="table-list-content" and hide them
tabcontent = document.getElementsByClassName("migrate-tab-content");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="table-nav-tab" and remove the class "nav-tab-active"
tablinks = document.getElementsByClassName("migrate-nav-tab");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" nav-tab-active", "");
}
// Show the current tab, and add an "storage-menu-active" class to the button that opened the tab
document.getElementById(contentName).style.display = "block";
evt.currentTarget.className += " nav-tab-active";
var top = jQuery('#'+storage_page_id).offset().top-jQuery('#'+storage_page_id).height();
jQuery('html, body').animate({scrollTop:top}, 'slow');
}
jQuery(document).ready(function ()
{
<?php
$default_task_type = array();
$default_task_type = apply_filters('wpvivid_get_task_type', $default_task_type);
if(empty($default_task_type)){
?>
//wpvivid_activate_migrate_cron();
//wpvivid_manage_upload_task();
<?php
}
?>
});
</script>
<?php
}
public function wpvivid_add_page_migrate(){
$migrate_descript = '';
$migrate_key = '';
$migrate_part_type = '';
$migrate_part_exec = '';
$migrate_part_note = '';
$migrate_part_tip = '';
?>
<div id="migrate-page" class="wrap-tab-content wpvivid_tab_migrate" name="tab-migrate" style="display: none;">
<div class="postbox wpvivid-element-space-bottom" style="padding: 10px;">
<?php
echo '<div style="padding: 0 0 10px 0;">
'.esc_html__('The feature can help you transfer a Wordpress site to a new domain(site). It would be a convenient way to migrate your WP site from dev environment to live server or from old server to the new.', 'wpvivid-backuprestore').'
</div>';
do_action('wpvivid_put_transfer_key_output');
?>
</div>
<div class="postbox wpvivid-element-space-bottom" id="wpvivid_upload_backup_percent" style="display: none;">
<div class="action-progress-bar" id="wpvivid_upload_progress_bar">
<div class="action-progress-bar-percent" id="wpvivid_upload_progress_bar_percent" style="height:24px;width:0"></div>
</div>
<div style="margin-left:10px; float: left; width:100%;"><p id="wpvivid_upload_current_doing"></p></div>
<div style="clear: both;"></div>
<div>
<div id="wpvivid_transfer_cancel" class="backup-log-btn"><input class="button-primary" id="wpvivid_transfer_cancel_btn" type="submit" value="<?php esc_attr_e( 'Cancel', 'wpvivid-backuprestore' ); ?>" /></div>
</div>
</div>
<div style="padding: 0 0 10px 0;">
<?php
$migrate_type = '';
$type_name = 'transfer_type';
echo '<div class="postbox quicktransfer">
<div class="wpvivid-element-space-bottom">
<h2 style="padding: 0;"><span>'.esc_html__( 'Choose the content you want to transfer', 'wpvivid-backuprestore').'</span></h2>
</div>
<div class="quickstart-archive-block">
<fieldset>
<legend class="screen-reader-text"><span>input type="radio"</span></legend>
';
do_action('wpvivid_add_migrate_type_output', $type_name);
echo '
</fieldset>
</div>
</div>';
?>
<p><?php echo esc_html__('Note: ', 'wpvivid-backuprestore'); ?></p>
<p>1. In order to successfully complete the migration, you'd better deactivate <a href="https://wpvivid.com/best-redirect-plugins.html" target="_blank" style="text-decoration: none;">301 redirect plugin</a>, <a href="https://wpvivid.com/8-best-wordpress-firewall-plugins.html" target="_blank" style="text-decoration: none;">firewall and security plugin</a>, and <a href="https://wpvivid.com/best-free-wordpress-caching-plugins.html" target="_blank" style="text-decoration: none;">caching plugin</a> (if they exist) before transferring website.</p>
<p>2. Please migrate website with the manual way when using <strong>Local by Flywheel</strong> environment.</p>
<div style="padding: 0 0 10px 0;">
<?php do_action('wpvivid_migrate_part_exec'); ?>
</div>
<div style="clear: both;"></div>
<div style="padding: 10px 0 10px 0;">
<?php
$backupdir=WPvivid_Setting::get_backupdir();
echo '<p><strong>Tips: </strong>Some web hosts may restrict the connection between the two sites, so you may get a 403 error or unstable connection issue when performing auto migration. In that case, it is recommended to manually transfer the site</p>
<p><strong>'.esc_html__('How to migrate Wordpress site manually to a new domain(site) with WPvivid backup plugin?', 'wpvivid-backuprestore').'</strong></p>
<p>'.esc_html__('1. Download a backup in backups list to your computer.', 'wpvivid-backuprestore').'</p>
<p>'.esc_html__('2. Upload the backup to destination site. There are two ways available to use:', 'wpvivid-backuprestore').'</p>
<p style="margin-left: 20px;">'.esc_html__('2.1 Upload the backup to the upload section of WPvivid backup plugin in destination site.', 'wpvivid-backuprestore').'</p>
<p style="margin-left: 20px;">'.sprintf('2.2 Upload the backup with FTP client to backup directory %s in destination site, then click <strong>Scan uploaded backup or received backup</strong> button.', esc_html(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backupdir)).'</p>
<p>'.esc_html__('3. Once done, the backup appears in backups list. Then, restore the backup.', 'wpvivid-backuprestore').'</p>';
?>
</div>
</div>
</div>
<?php
$js = '';
apply_filters('wpvivid_load_migrate_js', $js);
?>
<?php
}
public function wpvivid_add_page_key(){
?>
<div id="key-page" class="wrap-tab-content wpvivid_tab_key" name="tab-key" style="display: none;">
<div style="padding: 0 0 0 10px">
<div style="padding: 0 0 10px 0">
<span><?php esc_html_e('In order to allow another site to send a backup to this site, please generate a key below. Once the key is generated, this site is ready to receive a backup from another site. Then, please copy and paste the key in sending site and save it.', 'wpvivid-backuprestore'); ?></span>
</div>
<strong><?php esc_html_e('The key will expire in ', 'wpvivid-backuprestore'); ?></strong>
<select id="wpvivid_generate_url_expires" style="margin-bottom: 2px;">
<option value="2 hour"><?php esc_html_e('2 hours', 'wpvivid-backuprestore'); ?></option>
<option selected="selected" value="8 hour"><?php esc_html_e('8 hours', 'wpvivid-backuprestore'); ?></option>
<option value="24 hour"><?php esc_html_e('24 hours', 'wpvivid-backuprestore'); ?></option>
<!--<option value="Never">Never</option>-->
</select>
<p><?php esc_html_e('Tips: For security reason, please choose an appropriate expiration time for the key.', 'wpvivid-backuprestore'); ?></p>
<div>
<input class="button-primary" id="wpvivid_generate_url" type="submit" value="<?php esc_attr_e( 'Generate', 'wpvivid-backuprestore' ); ?>" onclick="wpvivid_click_generate_url();" />
</div>
<div id="wpvivid_test_generate_url" style="padding-top: 10px;">
<textarea id="wpvivid_test_remote_site_url_text" style="width: 100%; height: 140px;"></textarea>
</div>
</div>
</div>
<script>
jQuery("#wpvivid_test_remote_site_url_text").focus(function() {
jQuery(this).select();
jQuery(this).mouseup(function() {
jQuery(this).unbind("mouseup");
return false;
});
});
function wpvivid_click_generate_url()
{
var expires=jQuery('#wpvivid_generate_url_expires').val();
var ajax_data = {
'action': 'wpvivid_generate_url_ex',
'expires':expires
};
wpvivid_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_test_remote_site_url_text').val(jsonarray.url);
}
else
{
alert('Failed to generating key.');
}
}
catch (err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('generating key', textStatus, errorThrown);
alert(error_message);
});
}
</script>
<?php
}
public function test_connect_site()
{
if(isset($_POST['url']))
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$url=strtok(sanitize_url($_POST['url']),'?');
if (filter_var($url, FILTER_VALIDATE_URL) === FALSE)
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The key is invalid.';
echo wp_json_encode($ret);
die();
}
if($url==home_url())
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The key generated by this site cannot be added into this site.';
echo wp_json_encode($ret);
die();
}
$query=wp_parse_url (sanitize_url($_POST['url']),PHP_URL_QUERY);
if($query===null)
{
$query=strtok('?');
}
parse_str($query,$query_arr);
$token=$query_arr['token'];
$expires=$query_arr['expires'];
$domain=$query_arr['domain'];
if ($expires != 0 && time() > $expires) {
$ret['result'] = 'failed';
$ret['error'] = 'The key has expired.';
echo wp_json_encode($ret);
die();
}
$json['test_connect']=1;
$json=wp_json_encode($json);
$crypt=new WPvivid_crypt(base64_decode($token));
$data=$crypt->encrypt_message($json);
if($data===false)
{
$ret['result'] = 'failed';
$ret['error'] = 'Data encryption failed.';
echo wp_json_encode($ret);
die();
}
$data=base64_encode($data);
$args['body']=array('wpvivid_content'=>$data,'wpvivid_action'=>'send_to_site_connect');
$args['timeout']=30;
$response=wp_remote_post($url,$args);
if ( is_wp_error( $response ) )
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $response->get_error_message();
}
else
{
if($response['response']['code']==200)
{
$res=json_decode($response['body'],1);
if($res!=null)
{
if($res['result']==WPVIVID_SUCCESS)
{
$ret['result']=WPVIVID_SUCCESS;
$options=WPvivid_Setting::get_option('wpvivid_saved_api_token');
$options[$url]['token']=$token;
$options[$url]['url']=$url;
$options[$url]['expires']=$expires;
$options[$url]['domain']=$domain;
delete_option('wpvivid_saved_api_token');
WPvivid_Setting::update_option('wpvivid_saved_api_token',$options);
$html='';
$i=0;
foreach ($options as $key=>$site)
{
$check_status='';
if($key==$url)
{
$check_status='checked';
}
if($site['expires']>time())
{
$date=gmdate("l, F d, Y H:i", $site['expires']);
}
else
{
$date='Token has expired';
}
$i++;
$html = apply_filters('wpvivid_put_transfer_key', $html);
}
$ret['html']= $html;
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $res['error'];
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $response['body'];
//$ret['error']= 'failed to parse returned data. Unable to retrieve the correct authorization data via HTTP request.';
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'upload error '.$response['response']['code'].' '.$response['body'];
//$response['body']
}
}
echo wp_json_encode($ret);
}
die();
}
public function delete_transfer_key()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$ret['result']=WPVIVID_SUCCESS;
delete_option('wpvivid_saved_api_token');
$html='';
$html = apply_filters('wpvivid_put_transfer_key', $html);
$ret['html']=$html;
echo wp_json_encode($ret);
die();
}
public function send_backup_to_site()
{
try {
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$options = WPvivid_Setting::get_option('wpvivid_saved_api_token');
if (empty($options)) {
$ret['result'] = 'failed';
$ret['error'] = __('A key is required.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$url = '';
foreach ($options as $key => $value) {
$url = $value['url'];
}
if ($url === '') {
$ret['result'] = 'failed';
$ret['error'] = __('The key is invalid.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
if ($options[$url]['expires'] != 0 && $options[$url]['expires'] < time()) {
$ret['result'] = 'failed';
$ret['error'] = __('The key has expired.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$json['test_connect']=1;
$json=wp_json_encode($json);
$crypt=new WPvivid_crypt(base64_decode($options[$url]['token']));
$data=$crypt->encrypt_message($json);
$data=base64_encode($data);
$args['body']=array('wpvivid_content'=>$data,'wpvivid_action'=>'send_to_site_connect');
$response=wp_remote_post($url,$args);
if ( is_wp_error( $response ) )
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $response->get_error_message();
echo wp_json_encode($ret);
die();
}
else
{
if($response['response']['code']==200) {
$res=json_decode($response['body'],1);
if($res!=null) {
if($res['result']==WPVIVID_SUCCESS) {
}
else {
$ret['result']=WPVIVID_FAILED;
$ret['error']= $res['error'];
echo wp_json_encode($ret);
die();
}
}
else {
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'failed to parse returned data, unable to establish connection with the target site.';
$ret['response']=$response;
echo wp_json_encode($ret);
die();
}
}
else {
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'upload error '.$response['response']['code'].' '.$response['body'];
echo wp_json_encode($ret);
die();
}
}
if (WPvivid_taskmanager::is_tasks_backup_running()) {
$ret['result'] = 'failed';
$ret['error'] = __('A task is already running. Please wait until the running task is complete, and try again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$remote_option['url'] = $options[$url]['url'];
$remote_option['token'] = $options[$url]['token'];
$remote_option['type'] = WPVIVID_REMOTE_SEND_TO_SITE;
$remote_options['temp'] = $remote_option;
$backup_options = stripslashes(sanitize_text_field($_POST['backup_options']));
$backup_options = json_decode($backup_options, true);
$backup['backup_files'] = $backup_options['transfer_type'];
$backup['local'] = 0;
$backup['remote'] = 1;
$backup['ismerge'] = 1;
$backup['lock'] = 0;
$backup['remote_options'] = $remote_options;
$backup_task = new WPvivid_Backup_Task();
$ret = $backup_task->new_backup_task($backup, 'Manual', 'transfer');
$task_id = $ret['task_id'];
global $wpvivid_plugin;
$wpvivid_plugin->check_backup($task_id, $backup);
echo wp_json_encode($ret);
die();
}
catch (Exception $e){
$ret['result'] = 'failed';
$ret['error'] = $e->getMessage();
echo wp_json_encode($ret);
die();
}
}
public function migrate_now()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if (!isset($_POST['task_id'])||empty($_POST['task_id'])||!is_string($_POST['task_id']))
{
$ret['result']='failed';
$ret['error']=__('Error occurred while parsing the request data. Please try to run backup again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$task_id=sanitize_key($_POST['task_id']);
//flush buffer
$wpvivid_plugin->flush($task_id);
$wpvivid_plugin->backup($task_id);
die();
}
function export_download_backup()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$schedule_options=WPvivid_Schedule::get_schedule();
if(empty($schedule_options))
{
die();
}
$backup_options = stripslashes(sanitize_text_field($_POST['backup_options']));
$backup_options = json_decode($backup_options, true);
$backup['backup_files']= $backup_options['transfer_type'];
$backup['local']=1;
$backup['remote']=0;
$backup['ismerge']=1;
$backup['lock']=0;
//$backup['remote_options']='';
$backup_task=new WPvivid_Backup_Task();
$task=$backup_task->new_backup_task($backup,'Manual', 'export');
$task_id=$task['task_id'];
//add_action('wpvivid_handle_upload_succeed',array($this,'wpvivid_deal_upload_succeed'),11);
$wpvivid_plugin->check_backup($task_id,$backup['backup_files']);
$wpvivid_plugin->flush($task_id);
$wpvivid_plugin->backup($task_id);
//}
die();
}
function wpvivid_handle_backup_failed($task)
{
global $wpvivid_plugin;
if($task['action'] === 'transfer') {
$backup_error_array = WPvivid_Setting::get_option('wpvivid_transfer_error_array');
if (empty($backup_error_array)) {
$backup_error_array = array();
}
if (!array_key_exists($task['id'], $backup_error_array['bu_error'])) {
$backup_error_array['bu_error']['task_id'] = $task['id'];
$backup_error_array['bu_error']['error_msg'] = $task['status']['error'];
WPvivid_Setting::update_option('wpvivid_transfer_error_array', $backup_error_array);
}
$backup=new WPvivid_Backup($task['id']);
$backup->clean_backup();
$wpvivid_plugin->wpvivid_log->WriteLog('Upload failed. Delete task '.$task['id'], 'notice');
WPvivid_Backuplist::delete_backup($task['id']);
}
}
public function wpvivid_deal_upload_succeed($task)
{
global $wpvivid_plugin;
if($task['action'] === 'transfer')
{
$backup_success_count = WPvivid_Setting::get_option('wpvivid_transfer_success_count');
if (empty($backup_success_count))
{
$backup_success_count = 0;
}
$backup_success_count++;
WPvivid_Setting::update_option('wpvivid_transfer_success_count', $backup_success_count);
$wpvivid_plugin->wpvivid_log->WriteLog('Upload finished. Delete task '.$task['id'], 'notice');
WPvivid_Backuplist::delete_backup($task['id']);
}
}
public function generate_url()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
include_once WPVIVID_PLUGIN_DIR . '/vendor/autoload.php';
$expires=time()+3600;
if(isset($_POST['expires']))
{
$expires_display=sanitize_text_field($_POST['expires']);
if($expires_display=='1 month')
{
$expires=time()+2592000;
}
else if($expires_display=='1 day')
{
$expires=time()+86400;
}
else if($expires_display=='2 hour')
{
$expires=time()+7200;
}
else if($expires_display=='8 hour')
{
$expires=time()+28800;
}
else if($expires_display=='24 hour')
{
$expires=time()+86400;
}
else if($expires_display=='Never')
{
$expires=0;
}
}
$key_size = 2048;
$rsa = new Crypt_RSA();
$keys = $rsa->createKey($key_size);
$options['public_key']=base64_encode($keys['publickey']);
$options['private_key']=base64_encode($keys['privatekey']);
$options['expires']=$expires;
$options['domain']=home_url();
WPvivid_Setting::update_option('wpvivid_api_token',$options);
$url= $options['domain'];
$url=$url.'?domain='.$options['domain'].'&token='.$options['public_key'].'&expires='.$expires;
echo $url;
die();
}
public function generate_url_ex()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
include_once WPVIVID_PLUGIN_DIR . '/vendor/autoload.php';
$expires=time()+3600;
if(isset($_POST['expires']))
{
$expires_display=sanitize_text_field($_POST['expires']);
if($expires_display=='1 month')
{
$expires=time()+2592000;
}
else if($expires_display=='1 day')
{
$expires=time()+86400;
}
else if($expires_display=='2 hour')
{
$expires=time()+7200;
}
else if($expires_display=='8 hour')
{
$expires=time()+28800;
}
else if($expires_display=='24 hour')
{
$expires=time()+86400;
}
else if($expires_display=='Never')
{
$expires=0;
}
}
$key_size = 2048;
$rsa = new Crypt_RSA();
$keys = $rsa->createKey($key_size);
$options['public_key']=base64_encode($keys['publickey']);
$options['private_key']=base64_encode($keys['privatekey']);
$options['expires']=$expires;
$options['domain']=home_url();
WPvivid_Setting::update_option('wpvivid_api_token',$options);
$url= $options['domain'];
$url=$url.'?domain='.$options['domain'].'&token='.$options['public_key'].'&expires='.$expires;
$ret['result']='success';
$ret['url']=$url;
echo wp_json_encode($ret);
die();
}
public function wpvivid_put_transfer_key_output()
{
echo '<div id="wpvivid_transfer_key">';
$options=WPvivid_Setting::get_option('wpvivid_saved_api_token');
if(empty($options))
{
echo '<div style="padding: 0 0 10px 0;"><strong>'.esc_html__('Please paste the key below.', 'wpvivid-backuprestore').'</strong><a href="#" style="margin-left: 5px; text-decoration: none;" onclick="wpvivid_click_how_to_get_key();">'.esc_html__('How to get a site key?', 'wpvivid-backuprestore').'</a></div>
<div id="wpvivid_how_to_get_key"></div>
<div class="wpvivid-element-space-bottom"><textarea type="text" id="wpvivid_transfer_key_text" onKeyUp="wpvivid_check_key(this.value)" style="width: 100%; height: 140px;"/></textarea></div>
<div><input class="button-primary" id="wpvivid_save_url_button" type="submit" value="'.esc_attr__( 'Save', 'wpvivid-backuprestore' ).'" onclick="wpvivid_click_save_site_url();" /></div>';
}
else{
foreach ($options as $key => $value)
{
$token = $value['token'];
$source_dir=home_url();
$target_dir=$value['domain'];
$expires=$value['expires'];
if ($expires != 0 && time() > $expires) {
$key_status='The key has expired. Please delete it first and generate a new one.';
}
else{
$time_diff = $expires - time();
$key_status = 'The key will expire in: '.gmdate("H:i:s",$time_diff).'. Once the key expires, you need to generate a new key.';
}
}
echo '<div style="padding: 0 0 10px 0;">
<span>Key:</span>
<input type="text" id="wpvivid_send_remote_site_url_text" value="'.esc_attr($token).'" readonly="readonly" />
<input class="button-primary" id="wpvivid_delete_key_button" type="submit" value="'.esc_attr__( 'Delete', 'wpvivid-backuprestore' ).'" onclick="wpvivid_click_delete_transfer_key();" />
</div>
<div class="wpvivid-element-space-bottom">'.esc_html($key_status).'</div>
<div>The connection is ok. Now you can transfer the site <strong>'.esc_html($source_dir).'</strong> to the site <strong>'.esc_html($target_dir).'</strong></div>';
}
?>
</div>
<script>
var source_site = "<?php echo esc_url(admin_url('admin-ajax.php'))?>";
function wpvivid_check_key(value){
var pos = value.indexOf("?");
var site_url = value.substring(0, pos);
if(site_url == source_site){
alert("The key generated by this site cannot be added into this site.");
jQuery('#wpvivid_save_url_button').prop('disabled', true);
}
else{
jQuery("#wpvivid_save_url_button").prop('disabled', false);
}
}
function wpvivid_click_save_site_url()
{
var url= jQuery('#wpvivid_transfer_key_text').val();
var ajax_data = {
'action': 'wpvivid_test_connect_site',
'url':url
};
jQuery("#wpvivid_save_url_button").prop('disabled', true);
wpvivid_post_request(ajax_data, function (data)
{
jQuery("#wpvivid_save_url_button").prop('disabled', false);
try
{
var jsonarray = jQuery.parseJSON(data);
if(jsonarray.result==='success')
{
jQuery('#wpvivid_transfer_key').html(jsonarray.html);
}
else
{
alert(jsonarray.error);
}
}
catch(err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery("#wpvivid_save_url_button").prop('disabled', false);
var error_message = wpvivid_output_ajaxerror('saving key', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_click_delete_transfer_key()
{
var ajax_data = {
'action': 'wpvivid_delete_transfer_key'
};
jQuery("#wpvivid_delete_key_button").css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function (data)
{
jQuery("#wpvivid_delete_key_button").css({'pointer-events': 'none', 'opacity': '0.4'});
try
{
var jsonarray = jQuery.parseJSON(data);
if(jsonarray.result==='success')
{
jQuery('#wpvivid_transfer_key').html(jsonarray.html);
}
}
catch(err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery("#wpvivid_delete_key_button").css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = wpvivid_output_ajaxerror('deleting key', textStatus, errorThrown);
alert(error_message);
});
}
function click_dismiss_key_notice(obj){
wpvivid_display_get_key = false;
jQuery(obj).parent().remove();
}
function wpvivid_click_how_to_get_key(){
if(!wpvivid_display_get_key) {
wpvivid_display_get_key = true;
var div = "<div class='notice notice-info is-dismissible inline'>" +
"<p>" + wpvividlion.get_key_step1 + "</p>" +
"<p>" + wpvividlion.get_key_step2 + "</p>" +
"<p>" + wpvividlion.get_key_step3 + "</p>" +
"<button type='button' class='notice-dismiss' onclick='click_dismiss_key_notice(this);'>" +
"<span class='screen-reader-text'>Dismiss this notice.</span>" +
"</button>" +
"</div>";
jQuery('#wpvivid_how_to_get_key').append(div);
}
}
</script>
<?php
}
public function wpvivid_put_transfer_key($html){
$html='<div id="wpvivid_transfer_key">';
$options=WPvivid_Setting::get_option('wpvivid_saved_api_token');
if(empty($options)){
$html .= '<div style="padding: 0 0 10px 0;"><strong>'.__('Please paste the key below.', 'wpvivid-backuprestore').'</strong><a href="#" style="margin-left: 5px; text-decoration: none;" onclick="wpvivid_click_how_to_get_key();">'.__('How to get a site key?', 'wpvivid-backuprestore').'</a></div>
<div id="wpvivid_how_to_get_key"></div>
<div class="wpvivid-element-space-bottom"><textarea type="text" id="wpvivid_transfer_key_text" onKeyUp="wpvivid_check_key(this.value)" style="width: 100%; height: 140px;"/></textarea></div>
<div><input class="button-primary" id="wpvivid_save_url_button" type="submit" value="'.esc_attr__( 'Save', 'wpvivid-backuprestore' ).'" onclick="wpvivid_click_save_site_url();" /></div>';
}
else{
foreach ($options as $key => $value)
{
$token = $value['token'];
$source_dir=home_url();
$target_dir=$value['domain'];
$expires=$value['expires'];
if ($expires != 0 && time() > $expires) {
$key_status='The key has expired. Please delete it first and generate a new one.';
}
else{
$time_diff = $expires - time();
$key_status = 'The key will expire in: '.gmdate("H:i:s",$time_diff).'. Once the key expires, you need to generate a new key.';
}
}
$html .= '<div style="padding: 0 0 10px 0;">
<span>Key:</span>
<input type="text" id="wpvivid_send_remote_site_url_text" value="'.$token.'" readonly="readonly" />
<input class="button-primary" id="wpvivid_delete_key_button" type="submit" value="'.esc_attr__( 'Delete', 'wpvivid-backuprestore' ).'" onclick="wpvivid_click_delete_transfer_key();" />
</div>
<div class="wpvivid-element-space-bottom">'.$key_status.'</div>
<div>The connection is ok. Now you can transfer the site <strong>'.$source_dir.'</strong> to the site <strong>'.$target_dir.'</strong></div>';
}
$html.='</div>
<script>
var source_site = \''.admin_url('admin-ajax.php').'\';
function wpvivid_check_key(value){
var pos = value.indexOf(\'?\');
var site_url = value.substring(0, pos);
if(site_url == source_site){
alert(\'The key generated by this site cannot be added into this site.\');
jQuery(\'#wpvivid_save_url_button\').prop(\'disabled\', true);
}
else{
jQuery("#wpvivid_save_url_button").prop(\'disabled\', false);
}
}
function wpvivid_click_save_site_url()
{
var url= jQuery(\'#wpvivid_transfer_key_text\').val();
var ajax_data = {
\'action\': \'wpvivid_test_connect_site\',
\'url\':url
};
jQuery("#wpvivid_save_url_button").prop(\'disabled\', true);
wpvivid_post_request(ajax_data, function (data)
{
jQuery("#wpvivid_save_url_button").prop(\'disabled\', false);
try
{
var jsonarray = jQuery.parseJSON(data);
if(jsonarray.result===\'success\')
{
jQuery(\'#wpvivid_transfer_key\').html(jsonarray.html);
}
else
{
alert(jsonarray.error);
}
}
catch(err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery("#wpvivid_save_url_button").prop(\'disabled\', false);
var error_message = wpvivid_output_ajaxerror(\'saving key\', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_click_delete_transfer_key()
{
var ajax_data = {
\'action\': \'wpvivid_delete_transfer_key\'
};
jQuery("#wpvivid_delete_key_button").css({\'pointer-events\': \'none\', \'opacity\': \'0.4\'});
wpvivid_post_request(ajax_data, function (data)
{
jQuery("#wpvivid_delete_key_button").css({\'pointer-events\': \'none\', \'opacity\': \'0.4\'});
try
{
var jsonarray = jQuery.parseJSON(data);
if(jsonarray.result===\'success\')
{
jQuery(\'#wpvivid_transfer_key\').html(jsonarray.html);
}
}
catch(err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery("#wpvivid_delete_key_button").css({\'pointer-events\': \'auto\', \'opacity\': \'1\'});
var error_message = wpvivid_output_ajaxerror(\'deleting key\', textStatus, errorThrown);
alert(error_message);
});
}
function click_dismiss_key_notice(obj){
wpvivid_display_get_key = false;
jQuery(obj).parent().remove();
}
function wpvivid_click_how_to_get_key(){
if(!wpvivid_display_get_key) {
wpvivid_display_get_key = true;
var div = "<div class=\'notice notice-info is-dismissible inline\'>" +
"<p>" + wpvividlion.get_key_step1 + "</p>" +
"<p>" + wpvividlion.get_key_step2 + "</p>" +
"<p>" + wpvividlion.get_key_step3 + "</p>" +
"<button type=\'button\' class=\'notice-dismiss\' onclick=\'click_dismiss_key_notice(this);\'>" +
"<span class=\'screen-reader-text\'>Dismiss this notice.</span>" +
"</button>" +
"</div>";
jQuery(\'#wpvivid_how_to_get_key\').append(div);
}
}
</script>';
return $html;
}
public function wpvivid_migrate_descript($html){
$html .= '<div style="padding: 0 0 10px 0;">
'.__('The feature can help you transfer a Wordpress site to a new domain(site). It would be a convenient way to migrate your WP site from dev environment to live server or from old server to the new.', 'wpvivid-backuprestore').'
</div>';
return $html;
}
public function wpvivid_migrate_part_type($html){
$migrate_type = '';
$type_name = 'transfer_type';
$html = '<div class="postbox quicktransfer">
<div class="wpvivid-element-space-bottom">
<h2 style="padding: 0;"><span>'.__( 'Choose the content you want to transfer', 'wpvivid-backuprestore').'</span></h2>
</div>
<div class="quickstart-archive-block">
<fieldset>
<legend class="screen-reader-text"><span>input type="radio"</span></legend>
'.apply_filters('wpvivid_add_migrate_type', $migrate_type, $type_name).'
</fieldset>
</div>
</div>';
return $html;
}
public function wpvivid_migrate_part_exec($html)
{
?>
<div id="wpvivid_transfer_btn" style="float: left;">
<input class="button-primary quicktransfer-btn" type="submit" value="<?php esc_attr_e( 'Clone then Transfer', 'wpvivid-backuprestore'); ?>" onclick="wpvivid_click_send_backup();" />
</div>
<script>
function wpvivid_click_send_backup()
{
//send_to_remote
var option_data = wpvivid_ajax_data_transfer('migrate');
var ajax_data = {
'action': 'wpvivid_send_backup_to_site_2',
'backup_options':option_data
};
migrate_task_need_update=true;
wpvivid_clear_notice('wpvivid_backup_notice');
wpvivid_control_transfer_lock();
wpvivid_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if(jsonarray.result==='failed')
{
wpvivid_delete_transfer_ready_task(jsonarray.error);
}
else{
wpvivid_transfer_id = jsonarray.task_id;
wpvivid_migrate_now(jsonarray.task_id);
}
}
catch(err)
{
wpvivid_delete_transfer_ready_task(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('trying to establish communication with your server', textStatus, errorThrown);
wpvivid_delete_transfer_ready_task(error_message);
});
}
function wpvivid_migrate_now(task_id)
{
var ajax_data = {
'action': 'wpvivid_migrate_now_2',
'task_id': task_id
};
task_recheck_times = 0;
m_need_update_2=true;
wpvivid_post_request(ajax_data, function(data){
}, function(XMLHttpRequest, textStatus, errorThrown) {
});
}
function wpvivid_delete_transfer_ready_task(error){
var ajax_data={
'action': 'wpvivid_delete_ready_task'
};
wpvivid_post_request(ajax_data, function (data) {
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
wpvivid_add_notice('Backup', 'Error', error);
wpvivid_control_transfer_unlock();
jQuery('#wpvivid_upload_backup_percent').hide();
}
}
catch(err){
wpvivid_add_notice('Backup', 'Error', err);
wpvivid_control_transfer_unlock();
jQuery('#wpvivid_upload_backup_percent').hide();
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
setTimeout(function () {
wpvivid_delete_transfer_ready_task(error);
}, 3000);
});
}
</script>
<?php
}
public function wpvivid_migrate_part_note($html){
$html .= '<p>'.__('Note: ', 'wpvivid-backuprestore').'</p>
<p>'.__('1. In order to successfully complete the migration, you\'d better deactivate <a href="https://wpvivid.com/best-redirect-plugins.html" target="_blank" style="text-decoration: none;">301 redirect plugin</a>, <a href="https://wpvivid.com/8-best-wordpress-firewall-plugins.html" target="_blank" style="text-decoration: none;">firewall and security plugin</a>, and <a href="https://wpvivid.com/best-free-wordpress-caching-plugins.html" target="_blank" style="text-decoration: none;">caching plugin</a> (if they exist) before transferring website.', 'wpvivid-backuprestore').'</p>
<p>'.__('2. Please migrate website with the manual way when using <strong>Local by Flywheel</strong> environment.', 'wpvivid-backuprestore').'</p>';
return $html;
}
public function wpvivid_migrate_part_tip($html){
$backupdir=WPvivid_Setting::get_backupdir();
$html .= '<p>'.__('<strong>Tips: </strong>Some web hosts may restrict the connection between the two sites, so you may get a 403 error or unstable connection issue when performing auto migration. In that case, it is recommended to manually transfer the site.', 'wpvivid-backuprestore').'</p>
<p><strong>'.__('How to migrate Wordpress site manually to a new domain(site) with WPvivid backup plugin?', 'wpvivid-backuprestore').'</strong></p>
<p>'.__('1. Download a backup in backups list to your computer.', 'wpvivid-backuprestore').'</p>
<p>'.__('2. Upload the backup to destination site. There are two ways available to use:', 'wpvivid-backuprestore').'</p>
<p style="margin-left: 20px;">'.__('2.1 Upload the backup to the upload section of WPvivid backup plugin in destination site.', 'wpvivid-backuprestore').'</p>
<p style="margin-left: 20px;">'.sprintf('2.2 Upload the backup with FTP client to backup directory %s in destination site, then click <strong>Scan uploaded backup or received backup</strong> button.', WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backupdir).'</p>
<p>'.__('3. Once done, the backup appears in backups list. Then, restore the backup.', 'wpvivid-backuprestore').'</p>';
return $html;
}
public function wpvivid_add_migrate_type_output($name_type)
{
echo '<label>
<input type="radio" option="migrate" name="'.esc_attr($name_type).'" value="files+db" checked />
<span>'.esc_html__( 'Database + Files (WordPress Files)', 'wpvivid-backuprestore' ).'</span>
</label><br>
<label>
<input type="radio" option="migrate" name="'.esc_attr($name_type).'" value="files" />
<span>'.esc_html__( 'WordPress Files (Exclude Database)', 'wpvivid-backuprestore' ).'</span>
</label><br>
<label>
<input type="radio" option="migrate" name="'.esc_attr($name_type).'" value="db" />
<span>'.esc_html__( 'Only Database', 'wpvivid-backuprestore' ).'</span>
</label><br>
<label>
<div style="float: left;">
<input type="radio" disabled />
<span class="wpvivid-element-space-right" style="color: #ddd;">'.esc_html__('Choose what to migrate', 'wpvivid-backuprestore').'</span>
</div>
<span class="wpvivid-feature-pro">
<a href="https://docs.wpvivid.com/custom-migration-overview.html" style="text-decoration: none;">'.esc_html__('Pro feature: learn more', 'wpvivid-backuprestore').'</a>
</span>
</label><br>';
}
public function wpvivid_add_migrate_type($html, $name_type){
$html .= '<label>
<input type="radio" option="migrate" name="'.$name_type.'" value="files+db" checked />
<span>'.__( 'Database + Files (WordPress Files)', 'wpvivid-backuprestore' ).'</span>
</label><br>
<label>
<input type="radio" option="migrate" name="'.$name_type.'" value="files" />
<span>'.__( 'WordPress Files (Exclude Database)', 'wpvivid-backuprestore' ).'</span>
</label><br>
<label>
<input type="radio" option="migrate" name="'.$name_type.'" value="db" />
<span>'.__( 'Only Database', 'wpvivid-backuprestore' ).'</span>
</label><br>
<label>
<div style="float: left;">
<input type="radio" disabled />
<span class="wpvivid-element-space-right" style="color: #ddd;">'.__('Choose what to migrate', 'wpvivid-backuprestore').'</span>
</div>
<span class="wpvivid-feature-pro">
<a href="https://docs.wpvivid.com/custom-migration-overview.html" style="text-decoration: none;">'.__('Pro feature: learn more', 'wpvivid-backuprestore').'</a>
</span>
</label><br>';
return $html;
}
public function list_tasks()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$tasks=WPvivid_Setting::get_tasks();
$ret=array();
$list_tasks=array();
foreach ($tasks as $task)
{
if($task['action']=='transfer')
{
$backup=new WPvivid_Backup_Task($task['id']);
$list_tasks[$task['id']]=$backup->get_backup_task_info($task['id']);
if($list_tasks[$task['id']]['task_info']['need_next_schedule']===true){
$timestamp = wp_next_scheduled(WPVIVID_TASK_MONITOR_EVENT,array($task['id']));
if($timestamp===false)
{
$wpvivid_plugin->add_monitor_event($task['id'],20);
}
}
if($list_tasks[$task['id']]['task_info']['need_update_last_task']===true){
$task_msg = WPvivid_taskmanager::get_task($task['id']);
$wpvivid_plugin->update_last_backup_task($task_msg);
}
//<div id="wpvivid_estimate_backup_info" style="float:left;">
// <div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Database Size:', 'wpvivid-backuprestore') . '</span><span>' . $list_tasks[$task['id']]['task_info']['db_size'] . '</span></div>
// <div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('File Size:', 'wpvivid-backuprestore') . '</span><span>' . $list_tasks[$task['id']]['task_info']['file_size'] . '</span></div>
// </div>
$list_tasks[$task['id']]['progress_html'] = '<div class="action-progress-bar" id="wpvivid_upload_progress_bar">
<div class="action-progress-bar-percent" id="wpvivid_upload_progress_bar_percent" style="height:24px;width:' . $list_tasks[$task['id']]['task_info']['backup_percent'] . '"></div>
</div>
<div id="wpvivid_estimate_upload_info" style="float: left;">
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Total Size:', 'wpvivid-backuprestore') . '</span><span>' . $list_tasks[$task['id']]['task_info']['total'] . '</span></div>
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Uploaded:', 'wpvivid-backuprestore') . '</span><span>' . $list_tasks[$task['id']]['task_info']['upload'] . '</span></div>
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Speed:', 'wpvivid-backuprestore') . '</span><span>' . $list_tasks[$task['id']]['task_info']['speed'] . '</span></div>
</div>
<div style="float: left;">
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Network Connection:', 'wpvivid-backuprestore') . '</span><span>' . $list_tasks[$task['id']]['task_info']['network_connection'] . '</span></div>
</div>
<div style="clear:both;"></div>
<div style="margin-left:10px; float: left; width:100%;"><p id="wpvivid_upload_current_doing">' . $list_tasks[$task['id']]['task_info']['descript'] . '</p></div>
<div style="clear: both;"></div>
<div>
<div id="wpvivid_transfer_cancel" class="backup-log-btn"><input class="button-primary" id="wpvivid_transfer_cancel_btn" type="submit" value="'.esc_attr__( 'Cancel', 'wpvivid-backuprestore' ).'" /></div>
</div>';
}
}
WPvivid_taskmanager::delete_marked_task();
$backup_success_count=WPvivid_Setting::get_option('wpvivid_transfer_success_count');
if(!empty($backup_success_count)){
$notice_msg = __('Transfer succeeded. Please scan the backup list on the destination site to display the backup, then restore the backup.', 'wpvivid-backuprestore');
$success_notice_html='<div class="notice notice-success is-dismissible inline"><p>'.$notice_msg.'</p>
<button type="button" class="notice-dismiss" onclick="click_dismiss_notice(this);">
<span class="screen-reader-text">Dismiss this notice.</span>
</button>
</div>';
WPvivid_Setting::delete_option('wpvivid_transfer_success_count');
}
else {
$success_notice_html = false;
}
$ret['transfer_succeed_notice'] = $success_notice_html;
$backup_error_array=WPvivid_Setting::get_option('wpvivid_transfer_error_array');
if(!empty($backup_error_array)){
$error_notice_html = array();
foreach ($backup_error_array as $key => $value){
$notice_msg = 'Transfer failed, '.$value['error_msg'];
$error_notice_html['bu_error']['task_id']=$value['task_id'];
$error_notice_html['bu_error']['error_msg']='<div class="notice notice-error inline"><p>'.$notice_msg.'</p></div>';
}
WPvivid_Setting::delete_option('wpvivid_transfer_error_array');
}
else{
$error_notice_html = false;
}
$ret['transfer_error_notice'] = $error_notice_html;
$ret['transfer']['result']='success';
$ret['transfer']['data']=$list_tasks;
if(!empty($task_ids))
{
foreach ($task_ids as $id)
{
WPvivid_Setting::delete_task($id);
}
}
echo wp_json_encode($ret);
die();
}
function wpvivid_rescan_backup_list(){
?>
<div style="padding: 0 0 10px 0;">
<?php
Wpvivid_BackupUploader::rescan_local_folder();
?>
</div>
<?php
}
public function wpvivid_backuppage_load_backuplist($backuplist_array){
$backuplist_array['list_upload'] = array('index' => '2', 'tab_func' => array($this, 'wpvivid_add_tab_upload'), 'page_func' => array($this, 'wpvivid_add_page_upload'));
return $backuplist_array;
}
function wpvivid_add_tab_upload(){
?>
<a href="#" id="wpvivid_tab_upload" class="nav-tab backup-nav-tab" onclick="switchrestoreTabs(event,'page-upload')"><?php esc_html_e('Upload', 'wpvivid-backuprestore'); ?></a>
<?php
}
function wpvivid_add_page_upload(){
$backupdir=WPvivid_Setting::get_backupdir();
?>
<div class="backup-tab-content wpvivid_tab_upload" id="page-upload" style="display:none;">
<div style="padding: 10px 0 10px 0;">
<div style="padding-bottom: 10px;">
<span><?php echo esc_html(sprintf('The backups will be uploaded to %s directory.', WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backupdir)); ?></span>
</div>
<div style="padding-bottom: 10px;">
<span><?php esc_html_e('Note: The files you want to upload must be a backup created by WPvivid backup plugin. Make sure that uploading every part of a backup to the directory if the backup is split into many parts', 'wpvivid-backuprestore'); ?></span>
</div>
<?php
Wpvivid_BackupUploader::upload_meta_box();
?>
</div>
</div>
<?php
}
} includes/class-wpvivid-upload.php 0000644 00000013757 15132770567 0013172 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Upload
{
public $task_id;
public function upload($task_id,$remote_option=null)
{
global $wpvivid_plugin;
$this->task_id=$task_id;
$task=new WPvivid_Backup_Task($task_id);
$files=$task->get_backup_files();
WPvivid_taskmanager::update_backup_main_task_progress($this->task_id,'upload',0,0);
if(is_null($remote_option))
{
$remote_options=WPvivid_taskmanager::get_task_options($this->task_id,'remote_options');
if(sizeof($remote_options)>1)
{
$result=array('result' => WPVIVID_FAILED , 'error' => 'not support multi remote storage');
$result= apply_filters('wpvivid_upload_files_to_multi_remote',$result,$task_id);
if($result['result']==WPVIVID_SUCCESS)
{
WPvivid_taskmanager::update_backup_main_task_progress($this->task_id,'upload',100,1);
WPvivid_taskmanager::update_backup_task_status($task_id,false,'completed');
return array('result' => WPVIVID_SUCCESS);
}
else
{
WPvivid_taskmanager::update_backup_task_status($this->task_id,false,'error',false,false,$result['error']);
return array('result' => WPVIVID_FAILED , 'error' => $result['error']);
}
}
else
{
$remote_option=array_shift($remote_options);
if(is_null($remote_option))
{
return array('result' => WPVIVID_FAILED , 'error' => 'not select remote storage');
}
if(!class_exists('WPvivid_Remote_collection'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-remote-collection.php';
$wpvivid_plugin->remote_collection=new WPvivid_Remote_collection();
}
$remote=$wpvivid_plugin->remote_collection->get_remote($remote_option);
$result=$remote->upload($this->task_id,$files,array($this,'upload_callback'));
if($result['result']==WPVIVID_SUCCESS)
{
WPvivid_taskmanager::update_backup_main_task_progress($this->task_id,'upload',100,1);
WPvivid_taskmanager::update_backup_task_status($task_id,false,'completed');
return array('result' => WPVIVID_SUCCESS);
}
else
{
$remote ->cleanup($files);
WPvivid_taskmanager::update_backup_task_status($this->task_id,false,'error',false,false,$result['error']);
return array('result' => WPVIVID_FAILED , 'error' => $result['error']);
}
}
}
else
{
if(!class_exists('WPvivid_Remote_collection'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-remote-collection.php';
$wpvivid_plugin->remote_collection=new WPvivid_Remote_collection();
}
$remote=$wpvivid_plugin->remote_collection->get_remote($remote_option);
$result=$remote->upload($this->task_id,$files,array($this,'upload_callback'));
if($result['result']==WPVIVID_SUCCESS)
{
WPvivid_taskmanager::update_backup_main_task_progress($this->task_id,'upload',100,1);
WPvivid_taskmanager::update_backup_task_status($task_id,false,'completed');
return array('result' => WPVIVID_SUCCESS);
}
else
{
$remote ->cleanup($files);
WPvivid_taskmanager::update_backup_task_status($this->task_id,false,'error',false,false,$result['error']);
return array('result' => WPVIVID_FAILED , 'error' => $result['error']);
}
}
}
public function upload_callback($offset,$current_name,$current_size,$last_time,$last_size)
{
$job_data=array();
$upload_data=array();
$upload_data['offset']=$offset;
$upload_data['current_name']=$current_name;
$upload_data['current_size']=$current_size;
$upload_data['last_time']=$last_time;
$upload_data['last_size']=$last_size;
$upload_data['descript']='Uploading '.$current_name;
$v =( $offset - $last_size ) / (time() - $last_time);
$v /= 1000;
$v=round($v,2);
global $wpvivid_plugin;
$wpvivid_plugin->check_cancel_backup($this->task_id);
$message='Uploading '.$current_name.' Total size: '.size_format($current_size,2).' Uploaded: '.size_format($offset,2).' speed:'.$v.'kb/s';
$wpvivid_plugin->wpvivid_log->WriteLog($message,'notice');
$progress=intval(($offset/$current_size)*100);
WPvivid_taskmanager::update_backup_main_task_progress($this->task_id,'upload',$progress,0);
WPvivid_taskmanager::update_backup_sub_task_progress($this->task_id,'upload','',WPVIVID_UPLOAD_UNDO,$message, $job_data, $upload_data);
}
public function get_backup_files($backup)
{
$backup_item=new WPvivid_Backup_Item($backup);
return $backup_item->get_files();
}
public function clean_remote_backup($remotes,$files)
{
$remote_option=array_shift($remotes);
if(!is_null($remote_option))
{
global $wpvivid_plugin;
if(!class_exists('WPvivid_Remote_collection'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-remote-collection.php';
$wpvivid_plugin->remote_collection=new WPvivid_Remote_collection();
}
$remote=$wpvivid_plugin->remote_collection->get_remote($remote_option);
$remote ->cleanup($files);
}
}
} includes/class-wpvivid-compress-default.php 0000644 00000004773 15132770567 0015161 0 ustar 00 <?php
abstract class Wpvivid_Compress_Default{
public $last_error = '';
abstract public function compress($data);
abstract public function extract($files,$path = '');
abstract public function extract_by_files($files,$zip,$path = '');
abstract public function get_include_zip($files,$allpackages);
abstract public function listcontent($path);
abstract public function listnum($path , $includeFolder = false);
public function getLastError(){
return $this -> last_error;
}
public function getBasename($basename){
$basename = basename($basename);
$arr = explode('.',$basename);
return $arr[0];
}
public function _in_array($file,$lists){
foreach ($lists as $item){
if(strstr($file,$item)){
return true;
}
}
return false;
}
public function filesplit($max_size,$files){
$packages = array();
if($max_size == 0 || $max_size === '0M' || empty($max_size)){
$packages[] = $files;
}else{
$sizenum = 0;
$max_size = str_replace('M', '', $max_size);
$size = $max_size * 1024 * 1024;
$package = array();
$flag = false;
usort($files, function ($a, $b)
{
$a_size=filesize($a);
$b_size=filesize($b);
if ($a_size == $b_size)
return 0;
if ($a_size < $b_size)
return 1;
else
return -1;
});
foreach ($files as $file)
{
$sizenum += filesize($file);
if($sizenum > $size)
{
if(empty($package))
{
$package[] = $file;
$packages[] = $package;
$package = array();
$sizenum = 0;
}
else
{
$packages[] = $package;
$package = array();
$package[] = $file;
$sizenum = filesize($file);
}
}else{
$package[] = $file;
}
}
if(!empty($package))
$packages[] = $package;
}
return $packages;
}
} includes/customclass/class-wpvivid-base-dropbox.php 0000644 00000031321 15132770567 0016616 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class Dropbox_Base{
const API_URL_V2 = 'https://api.dropboxapi.com/';
const CONTENT_URL_V2 = 'https://content.dropboxapi.com/2/';
const API_ID = 'cwn4z5jg8wy7b4u';
private $access_token;
private $created;
private $expires_in;
private $refresh_token;
private $option;
public function __construct($option)
{
$this -> option = $option;
$this -> access_token = $option['access_token'];
$this -> created = $option['created'];
$this -> expires_in = $option['expires_in'];
$this -> refresh_token = $option['refresh_token'];
}
public function check_token()
{
if(!isset($this->option['refresh_token']))
{
return array('result' => WPVIVID_FAILED,'error' => 'Invalid or expired token. Please remove '.$this -> option['name'].' from the storage list and re-authenticate it.');
}
$now=time()-10;
if ($now>$this->option['created']+$this->option['expires_in'])
{
$result=$this->getRefreshToken();
if($result['result']=='failed')
{
return array('result' => WPVIVID_FAILED,'error' => $result['error']);
}
else
{
$remote_options=WPvivid_Setting::get_remote_option($this->option['id']);
if($remote_options!==false)
{
$remote_options['access_token']= base64_encode($result['data']['access_token']);
if(!isset($remote_options['is_encrypt']))
{
$remote_options['refresh_token']=base64_encode($remote_options['refresh_token']);
$this -> refresh_token = base64_encode($this->option['refresh_token']);
}
else
{
$this -> refresh_token = $this->option['refresh_token'];
}
$remote_options['expires_in'] = $result['data']['expires_in'];
$remote_options['created'] = time();
$remote_options['is_encrypt']=1;
WPvivid_Setting::update_remote_option($this->option['id'],$remote_options);
$this -> access_token = $remote_options['access_token'];
$this -> created = $remote_options['created'];
$this -> expires_in = $remote_options['expires_in'];
$this -> option['is_encrypt']=1;
$ret['result']='success';
return $ret;
}
else
{
return array('result' => WPVIVID_FAILED,'error'=>'get refresh token failed');
}
}
}
else
{
$ret['result']='success';
return $ret;
}
}
public function upload($target_path, $file_data, $mode = "add")
{
$endpoint = self::CONTENT_URL_V2."files/upload";
$headers = array(
"Content-Type: application/octet-stream",
"Dropbox-API-Arg: {\"path\": \"$target_path\", \"mode\": \"$mode\"}"
);
if (file_exists($file_data))
$postdata = file_get_contents($file_data);
else
$postdata = $file_data;
$returnData = $this ->postRequest($endpoint, $headers, $postdata);
if(isset($returnData['error_summary']) && preg_match( "/Invalid or expired token. Please remove .* from the storage list and re-authenticate it/", $returnData['error_summary'], $matches ))
{
$ret=$this->check_token();
if($ret['result']=='failed')
{
return $returnData;
}
else
{
$returnData = $this ->postRequest($endpoint, $headers, $postdata);
}
}
return $returnData;
}
public function upload_session_start()
{
$endpoint = self::CONTENT_URL_V2."files/upload_session/start";
$headers = array(
"Content-Type: application/octet-stream",
"Dropbox-API-Arg: {\"close\": false}"
);
$returnData = $this ->postRequest($endpoint, $headers,null);
if(isset($returnData['error_summary']) && preg_match( "/Invalid or expired token. Please remove .* from the storage list and re-authenticate it/", $returnData['error_summary'], $matches ))
{
$ret=$this->check_token();
if($ret['result']=='failed')
{
return $returnData;
}
else
{
$returnData = $this ->postRequest($endpoint, $headers,null);
}
}
return $returnData;
}
public function upload_session_append_v2($session_id, $offset, $postdata)
{
$endpoint = self::CONTENT_URL_V2."files/upload_session/append_v2";
$headers = array(
"Content-Type: application/octet-stream",
"Dropbox-API-Arg: {\"cursor\": {\"session_id\": \"$session_id\",\"offset\": $offset},\"close\": false}"
);
$returnData = $this ->postRequest($endpoint, $headers, $postdata);
if(isset($returnData['error_summary']) && preg_match( "/Invalid or expired token. Please remove .* from the storage list and re-authenticate it/", $returnData['error_summary'], $matches ))
{
$ret=$this->check_token();
if($ret['result']=='failed')
{
return $returnData;
}
else
{
$returnData = $this ->postRequest($endpoint, $headers,null);
}
}
return $returnData;
}
public function upload_session_finish($session_id, $filesize, $path, $mode = 'add') {
$endpoint = self::CONTENT_URL_V2."files/upload_session/finish";
$entry = array(
'cursor' => array(
'session_id' => $session_id,
'offset' => $filesize,
),
'commit' => array(
'path' => $path,
'mode' => $mode,
),
);
$headers = array(
"Content-Type: application/octet-stream",
"Dropbox-API-Arg: " . wp_json_encode($entry),
);
$returnData = $this ->postRequest($endpoint, $headers,null);
return $returnData;
}
public function download($path,$header = array()) {
$endpoint = "https://content.dropboxapi.com/2/files/download";
$headers = array(
"Content-Type: text/plain; charset=utf-8",
"Dropbox-API-Arg: {\"path\": \"$path\"}"
);
$headers = array_merge ($headers,$header);
$data = $this ->postRequest($endpoint, $headers,null,false);
return $data;
}
public function delete($path) {
$endpoint = self::API_URL_V2."2/files/delete";
$headers = array(
"Content-Type: application/json"
);
$postdata = wp_json_encode(array( "path" => $path ));
$returnData = $this -> postRequest($endpoint, $headers, $postdata);
return $returnData;
}
public function revoke() {
$endpoint = self::API_URL_V2."2/auth/token/revoke";
$headers = array();
$this -> postRequest($endpoint, $headers);
}
public function getUsage(){
$endpoint = self::API_URL_V2."2/users/get_space_usage";
$headers = array(
"Content-Type: application/json"
);
$postdata = "null";
$returnData = $this -> postRequest($endpoint, $headers,$postdata);
return $returnData;
}
public static function getUrl($url,$state = '')
{
$params = array(
'client_id' => self::API_ID,
'response_type' => 'code',
'redirect_uri' => $url,
'token_access_type'=>'offline',
'state' => $state,
);
$url = 'https://www.dropbox.com/oauth2/authorize?';
$url .= http_build_query($params,'','&');
return $url;
}
public function postRequest($endpoint, $headers, $data = null,$returnjson = true) {
if(isset($this->option['is_encrypt']) && $this->option['is_encrypt'] == 1) {
$access_token=base64_decode($this -> access_token);
}
else{
$access_token=$this -> access_token;
}
$ch = curl_init($endpoint);
array_push($headers, "Authorization: Bearer " . $access_token);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//todo delete this code
// curl_setopt($ch,CURLOPT_PROXY, '127.0.0.1:1080');
$r = curl_exec($ch);
$chinfo = curl_getinfo($ch);
$error = curl_error($ch);
curl_close($ch);
if($r === false){
$r['error_summary'] = $error;
}else{
if($chinfo['http_code'] === 401)
{
$ret=$this->check_token();
if($ret['result']=='success')
{
$ch = curl_init($endpoint);
array_push($headers, "Authorization: Bearer " . $access_token);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$r = curl_exec($ch);
$chinfo = curl_getinfo($ch);
$error = curl_error($ch);
curl_close($ch);
if($r === false)
{
$r['error_summary'] = $error;
}
else
{
if($chinfo['http_code'] === 401)
{
$r = array();
$r['error_summary'] = 'Invalid or expired token. Please remove '.$this -> option['name'].' from the storage list and re-authenticate it.';
}
elseif($chinfo['http_code'] !== 200 && $chinfo['http_code'] !== 206)
{
$r = json_decode($r,true);
}
}
}
else
{
$r = array();
$r['error_summary'] = 'Invalid or expired token. Please remove '.$this -> option['name'].' from the storage list and re-authenticate it.';
}
}elseif($chinfo['http_code'] !== 200 && $chinfo['http_code'] !== 206){
$r = json_decode($r,true);
}
}
if($returnjson && !is_array($r))
$r = json_decode($r,true);
return $r;
}
public function setAccessToken($access_token){
$this -> access_token = $access_token;
}
public function getRefreshToken()
{
if(isset($this->option['is_encrypt']) && $this->option['is_encrypt'] == 1) {
$refresh_token=base64_decode($this -> refresh_token);
}
else{
$refresh_token=$this -> refresh_token;
}
$options=array();
$options['timeout']=30;
$options['sslverify']=FALSE;
$params = array(
'client_id' => self::API_ID,
'refresh_token' => $refresh_token,
'version'=>1
);
$url = 'https://auth.wpvivid.com/dropbox_v3/?';
$url .= http_build_query($params,'','&');
$request = wp_remote_request( $url,$options);
if(!is_wp_error($request) && ($request['response']['code'] == 200))
{
$json= wp_remote_retrieve_body($request);
$body=json_decode($json,true);
if(is_null($body))
{
$ret['result']='failed';
$ret['error']='Get refresh token failed';
return $ret;
}
if($body['result']=='success')
{
return $body;
}
else
{
return $body;
}
}
else
{
$ret['result']='failed';
$ret['error']='Get refresh token failed';
return $ret;
}
}
} includes/customclass/class-wpvivid-one-drive.php 0000644 00000203305 15132770567 0016124 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-remote.php';
if(!defined('WPVIVID_REMOTE_ONEDRIVE'))
{
define('WPVIVID_REMOTE_ONEDRIVE','onedrive');
}
if(!defined('WPVIVID_ONEDRIVE_DEFAULT_FOLDER'))
{
define('WPVIVID_ONEDRIVE_DEFAULT_FOLDER','wpvivid_backup');
}
if(!defined('WPVIVID_ONEDRIVE_UPLOAD_SIZE'))
{
define('WPVIVID_ONEDRIVE_UPLOAD_SIZE',1024*1024*2);
}
if(!defined('WPVIVID_ONEDRIVE_DOWNLOAD_SIZE'))
{
define('WPVIVID_ONEDRIVE_DOWNLOAD_SIZE',1024*1024*2);
}
if(!defined('WPVIVID_ONEDRIVE_RETRY_TIMES'))
{
define('WPVIVID_ONEDRIVE_RETRY_TIMES','3');
}
class WPvivid_one_drive extends WPvivid_Remote
{
public $options;
public $callback;
public $add_remote;
public function __construct($options=array())
{
if(empty($options))
{
if(!defined('WPVIVID_INIT_STORAGE_TAB_ONE_DRIVE'))
{
add_action('init', array($this, 'handle_auth_actions'));
//wpvivid_one_drive_add_remote
add_action('wp_ajax_wpvivid_one_drive_add_remote',array( $this,'finish_add_remote'));
add_action('wpvivid_add_storage_tab',array($this,'wpvivid_add_storage_tab_one_drive'), 12);
add_action('wpvivid_add_storage_page',array($this,'wpvivid_add_storage_page_one_drive'), 12);
add_action('wpvivid_edit_remote_page',array($this,'wpvivid_edit_storage_page_one_drive'), 12);
add_filter('wpvivid_remote_pic',array($this,'wpvivid_remote_pic_one_drive'),10);
add_filter('wpvivid_get_out_of_date_remote',array($this,'wpvivid_get_out_of_date_one_drive'),10,2);
add_filter('wpvivid_storage_provider_tran',array($this,'wpvivid_storage_provider_one_drive'),10);
add_filter('wpvivid_get_root_path',array($this,'wpvivid_get_root_path_one_drive'),10);
add_filter('wpvivid_pre_add_remote',array($this, 'pre_add_remote'),10,2);
define('WPVIVID_INIT_STORAGE_TAB_ONE_DRIVE',1);
}
}
else
{
$this->options=$options;
}
$this->add_remote=false;
}
public function pre_add_remote($remote,$id)
{
if($remote['type']==WPVIVID_REMOTE_ONEDRIVE)
{
$remote['id']=$id;
}
return $remote;
}
public function handle_auth_actions()
{
if (isset($_GET['action']) && isset($_GET['page']))
{
if($_GET['page'] === 'WPvivid')
{
if($_GET['action']=='wpvivid_one_drive_auth')
{
$check=current_user_can('manage_options');
if(!$check)
{
return;
}
try {
$rand_id = substr(md5(time().rand()), 0,13);
$auth_id = 'wpvivid-auth-'.$rand_id;
$remote_options['auth_id']=$auth_id;
set_transient('onedrive_auth_id', $remote_options, 900);
$url = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'
. '?client_id=' . urlencode('37668be9-b55f-458f-b6a3-97e6f8aa10c9')
. '&scope=' . urlencode('offline_access files.readwrite.all')
. '&response_type=code'
. '&redirect_uri=' . urlencode('https://auth.wpvivid.com/onedrive_v2/')
. '&state=' . urlencode(admin_url() . 'admin.php?page=WPvivid' . '&action=wpvivid_one_drive_finish_auth&main_tab=storage&sub_tab=one_drive&sub_page=storage_account_one_drive&auth_id='.$auth_id)
. '&display=popup'
. '&locale=en';
header('Location: ' . esc_url_raw($url));
}
catch (Exception $e){
echo '<div class="notice notice-error"><p>'.esc_html($e->getMessage()).'</p></div>';
}
}
else if($_GET['action']=='wpvivid_one_drive_finish_auth')
{
$tmp_options = get_transient('onedrive_auth_id');
if($tmp_options === false)
{
return;
}
else if($tmp_options['auth_id'] !== $_GET['auth_id'])
{
delete_transient('onedrive_auth_id');
return;
}
try
{
if (isset($_GET['auth_error']))
{
$error = urldecode($_GET['auth_error']);
header('Location: ' . admin_url() . 'admin.php?page=' . WPVIVID_PLUGIN_SLUG . '&action=wpvivid_one_drive&result=error&resp_msg=' . $error);
return;
}
$remoteslist = WPvivid_Setting::get_all_remote_options();
foreach ($remoteslist as $key => $value)
{
if (isset($value['auth_id']) && isset($_GET['auth_id']) && $value['auth_id'] == sanitize_text_field($_GET['auth_id']))
{
echo '<div class="notice notice-success is-dismissible"><p>';
esc_html_e('You have authenticated the Microsoft OneDrive account as your remote storage.', 'wpvivid-backuprestore');
echo '</p></div>';
return;
}
}
if(empty($_POST['refresh_token']))
{
if(empty($tmp_options['token']['refresh_token']))
{
$err = 'No refresh token was received from OneDrive, which means that you entered client secret incorrectly, or that you did not re-authenticated yet after you corrected it. Please authenticate again.';
header('Location: ' . admin_url() . 'admin.php?page=' . WPVIVID_PLUGIN_SLUG . '&action=wpvivid_one_drive&result=error&resp_msg='.$err);
return;
}
}
else
{
$tmp_options['type'] = WPVIVID_REMOTE_ONEDRIVE;
$tmp_options['token']['access_token']=base64_encode(sanitize_text_field($_POST['access_token']));
$tmp_options['token']['refresh_token']=base64_encode(sanitize_text_field($_POST['refresh_token']));
$tmp_options['token']['expires']=time()+$_POST['expires_in'];
$tmp_options['is_encrypt'] = 1;
set_transient('onedrive_auth_id', $tmp_options, 900);
}
$this->add_remote=true;
}
catch (Exception $e){
echo '<div class="notice notice-error"><p>'.esc_html($e->getMessage()).'</p></div>';
}
}
else if($_GET['action']=='wpvivid_one_drive')
{
try {
if (isset($_GET['result'])) {
if ($_GET['result'] == 'success') {
add_action('show_notice', array($this, 'wpvivid_show_notice_add_onedrive_success'));
} else if ($_GET['result'] == 'error') {
add_action('show_notice', array($this, 'wpvivid_show_notice_add_onedrive_error'));
}
}
}
catch (Exception $e){
echo '<div class="notice notice-error"><p>'.esc_html($e->getMessage()).'</p></div>';
}
}
}
}
}
public function wpvivid_show_notice_add_onedrive_success(){
echo '<div class="notice notice-success is-dismissible"><p>';
esc_html_e('You have authenticated the Microsoft OneDrive account as your remote storage.', 'wpvivid-backuprestore');
echo '</p></div>';
}
public function wpvivid_show_notice_add_onedrive_error(){
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_handle_remote_storage_error($_GET['resp_msg'], 'Add OneDrive Remote');
echo '<div class="notice notice-error"><p>'.esc_html($_GET['resp_msg']).'</p></div>';
}
public function wpvivid_add_storage_tab_one_drive()
{
?>
<div class="storage-providers" remote_type="one_drive" onclick="select_remote_storage(event, 'storage_account_one_drive');">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/storage-microsoft-onedrive.png'); ?>" style="vertical-align:middle;"/><?php esc_html_e('Microsoft OneDrive', 'wpvivid-backuprestore'); ?>
</div>
<?php
}
public function wpvivid_add_storage_page_one_drive()
{
global $wpvivid_plugin;
$root_path=apply_filters('wpvivid_get_root_path', WPVIVID_REMOTE_ONEDRIVE);
if($this->add_remote)
{
?>
<div id="storage_account_one_drive" class="storage-account-page" style="display:none;">
<div style="background-color:#f1f1f1; padding: 10px;">
Please read <a target="_blank" href="https://wpvivid.com/privacy-policy" style="text-decoration: none;">this privacy policy</a> for use of our Microsoft OneDrive authorization app (none of your backup data is sent to us).
</div>
<div style="color:#8bc34a; padding: 10px 10px 10px 0;">
<strong><?php esc_html_e('Authentication is done, please continue to enter the storage information, then click \'Add Now\' button to save it.', 'wpvivid-backuprestore'); ?></strong>
</div>
<div style="padding: 10px 10px 10px 0;">
<strong><?php esc_html_e('Enter Your Microsoft OneDrive Information', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="one_drive" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. OneDrive-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="one_drive" name="path" value="<?php echo esc_attr($root_path.WPVIVID_ONEDRIVE_DEFAULT_FOLDER); ?>" readonly="readonly" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('All backups will be uploaded to this directory.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" value="mywebsite01" readonly="readonly" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<a href="https://docs.wpvivid.com/wpvivid-backup-pro-microsoft-onedrive-custom-folder-name.html"><?php esc_html_e('Pro feature: Create a directory for storing the backups of the site', 'wpvivid-backuprestore'); ?></a>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="one_drive" name="default" checked /><?php esc_html_e('Set as the default remote storage.', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Once checked, all this sites backups sent to a remote storage destination will be uploaded to this storage by default.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input id="wpvivid_one_drive_auth" class="button-primary" type="submit" value="<?php esc_attr_e('Add Now', 'wpvivid-backuprestore'); ?>">
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to add the storage.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script>
function wpvivid_check_onedrive_storage_alias(storage_alias)
{
var find = 1;
jQuery('#wpvivid_remote_storage_list tr').each(function (i) {
jQuery(this).children('td').each(function (j) {
if (j == 3) {
if (jQuery(this).text() == storage_alias) {
find = -1;
return false;
}
}
});
});
return find;
}
jQuery('#wpvivid_one_drive_auth').click(function()
{
wpvivid_one_drive_auth();
});
function wpvivid_one_drive_auth()
{
wpvivid_settings_changed = false;
var name='';
var path='';
jQuery('input:text[option=one_drive]').each(function()
{
var key = jQuery(this).prop('name');
if(key==='name')
{
name = jQuery(this).val();
}
});
var remote_default='0';
jQuery('input:checkbox[option=one_drive]').each(function()
{
if(jQuery(this).prop('checked')) {
remote_default='1';
}
else {
remote_default='0';
}
});
if(name == ''){
alert(wpvividlion.remotealias);
}
else if(wpvivid_check_onedrive_storage_alias(name) === -1){
alert(wpvividlion.remoteexist);
}
else {
var ajax_data;
var remote_from = wpvivid_ajax_data_transfer('one_drive');
ajax_data = {
'action': 'wpvivid_one_drive_add_remote',
'remote': remote_from
};
jQuery('#wpvivid_one_drive_auth').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#wpvivid_remote_notice').html('');
wpvivid_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_one_drive_auth').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('input:text[option=one_drive]').each(function(){
jQuery(this).val('');
});
jQuery('input:password[option=one_drive]').each(function(){
jQuery(this).val('');
});
wpvivid_handle_remote_storage_data(data);
location.href='admin.php?page=WPvivid&action=wpvivid_one_drive&main_tab=storage&sub_tab=one_drive&sub_page=storage_account_one_drive&result=success';
}
else if (jsonarray.result === 'failed')
{
jQuery('#wpvivid_remote_notice').html(jsonarray.notice);
jQuery('input[option=add-remote]').css({'pointer-events': 'auto', 'opacity': '1'});
}
}
catch (err)
{
alert(err);
jQuery('input[option=add-remote]').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('adding the remote storage', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_one_drive_auth').css({'pointer-events': 'auto', 'opacity': '1'});
});
}
}
</script>
<?php
}
else
{
?>
<div id="storage_account_one_drive" class="storage-account-page" style="display:none;">
<div style="background-color:#f1f1f1; padding: 10px;">
Please read <a target="_blank" href="https://wpvivid.com/privacy-policy" style="text-decoration: none;">this privacy policy</a> for use of our Microsoft OneDrive authorization app (none of your backup data is sent to us).
</div>
<div style="padding: 10px 10px 10px 0;">
<strong><?php esc_html_e('To add OneDrive, please get Microsoft authentication first. Once authenticated, you will be redirected to this page, then you can add storage information and save it', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input onclick="wpvivid_one_drive_auth();" class="button-primary" type="submit" value="<?php esc_attr_e('Authenticate with Microsoft OneDrive', 'wpvivid-backuprestore'); ?>">
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click to get Microsoft authentication.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
<div style="padding: 10px 0 0 0;">
<span>Tip: Get a 404 or 403 error after authorization? Please read this <a href="https://docs.wpvivid.com/http-403-error-authorizing-cloud-storage.html">doc</a>.</span>
</div>
</div>
<script>
function wpvivid_one_drive_auth()
{
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page=WPvivid' . '&action=wpvivid_one_drive_auth'?>';
}
</script>
<?php
}
}
public function wpvivid_edit_storage_page_one_drive()
{
?>
<div id="remote_storage_edit_onedrive" class="postbox storage-account-block remote-storage-edit" style="display:none;">
<div style="padding: 0 10px 10px 0;">
<strong><?php esc_html_e('Enter Your Microsoft OneDrive Information', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-onedrive" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. OneDrive-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" type="submit" option="edit-remote" value="<?php esc_attr_e('Save Changes', 'wpvivid-backuprestore'); ?>">
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to save the changes.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script>
function wpvivid_one_drive_update_auth()
{
var name='';
jQuery('input:text[option=edit-onedrive]').each(function()
{
var key = jQuery(this).prop('name');
if(key==='name')
{
name = jQuery(this).val();
}
});
if(name == ''){
alert(wpvividlion.remotealias);
}
else if(wpvivid_check_onedrive_storage_alias(name) === -1){
alert(wpvividlion.remoteexist);
}
else {
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page=WPvivid' . '&action=wpvivid_one_drive_update_auth&name='?>' + name + '&id=' + wpvivid_editing_storage_id;
}
}
</script>
<?php
}
public function sanitize_options($skip_name='')
{
$ret['result']=WPVIVID_SUCCESS;
if(!isset($this->options['name']))
{
$ret['error']="Warning: An alias for remote storage is required.";
return $ret;
}
$ret['options']=$this->options;
return $ret;
}
public function test_connect()
{
return array('result' => WPVIVID_SUCCESS);
}
public function upload($task_id, $files, $callback = '')
{
global $wpvivid_plugin;
if($this->need_refresh())
{
$wpvivid_plugin->wpvivid_log->WriteLog('The token expired and will go to the server to refresh the token.','notice');
$ret=$this->refresh_token();
if($ret['result']===WPVIVID_FAILED)
{
return $ret;
}
}
$path=$this->options['path'];
$wpvivid_plugin->wpvivid_log->WriteLog('Check upload folder '.$path,'notice');
$ret=$this->check_folder($path);
if($ret['result']===WPVIVID_FAILED)
{
return $ret;
}
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_ONEDRIVE);
if(empty($upload_job))
{
$job_data=array();
foreach ($files as $file)
{
$file_data['size']=filesize($file);
$file_data['uploaded']=0;
$file_data['uploadUrl']='';
$job_data[basename($file)]=$file_data;
}
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_ONEDRIVE,WPVIVID_UPLOAD_UNDO,'Start uploading',$job_data);
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_ONEDRIVE);
}
foreach ($files as $file)
{
if(is_array($upload_job['job_data'])&&array_key_exists(basename($file),$upload_job['job_data']))
{
if($upload_job['job_data'][basename($file)]['uploaded']==1)
continue;
}
$this -> last_time = time();
$this -> last_size = 0;
if(!file_exists($file))
return array('result' =>WPVIVID_FAILED,'error' =>$file.' not found. The file might has been moved, renamed or deleted. Please reload the list and verify the file exists.');
$wpvivid_plugin->wpvivid_log->WriteLog('Start uploading '.basename($file),'notice');
$wpvivid_plugin->set_time_limit($task_id);
$result=$this->_upload($task_id, $file,$callback);
if($result['result'] !==WPVIVID_SUCCESS)
{
return $result;
}
else
{
WPvivid_taskmanager::wpvivid_reset_backup_retry_times($task_id);
}
if($this->need_refresh())
{
$wpvivid_plugin->wpvivid_log->WriteLog('The token expired and will go to the server to refresh the token.','notice');
$ret=$this->refresh_token();
if($ret['result']===WPVIVID_FAILED)
{
return $ret;
}
}
}
return array('result' =>WPVIVID_SUCCESS);
}
public function cleanup($files)
{
@set_time_limit(120);
$path=$this->options['path'];
if($this->need_refresh())
{
$ret=$this->refresh_token();
if($ret['result']===WPVIVID_FAILED)
{
return $ret;
}
}
$ret=$this->get_files_id($files,$path);
if($ret['result']==WPVIVID_SUCCESS)
{
$ids=$ret['ids'];
foreach ($ids as $id)
{
$this->delete_file($id);
}
}
else
{
return $ret;
}
return array('result' =>WPVIVID_SUCCESS);
}
public function set_token()
{
$remote_options=WPvivid_Setting::get_remote_option($this->options['id']);
if($remote_options!==false)
{
$this->options['token']=$remote_options['token'];
if(isset($remote_options['is_encrypt']))
{
$this->options['is_encrypt']=$remote_options['is_encrypt'];
}
}
}
public function download($file, $local_path, $callback = '')
{
try {
$this->current_file_name = $file['file_name'];
$this->current_file_size = $file['size'];
$this->callback=$callback;
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_download_log->WriteLog('Remote type: OneDrive.','notice');
$this->set_token();
if ($this->need_refresh()) {
$ret = $this->refresh_token();
if ($ret['result'] === WPVIVID_FAILED) {
return $ret;
}
}
$path = $this->options['path'];
$ret = $this->check_file($file['file_name'], $path);
if ($ret['result'] === WPVIVID_FAILED) {
return $ret;
}
$file_path = $local_path . $file['file_name'];
$wpvivid_plugin->wpvivid_download_log->WriteLog('Create local file.','notice');
$fh = fopen($file_path, 'a');
$wpvivid_plugin->wpvivid_download_log->WriteLog('Downloading file ' . $file['file_name'] . ', Size: ' . $file['size'] ,'notice');
$downloaded_start = filesize($file_path);
$url = 'https://graph.microsoft.com/v1.0/me/drive/root:/' . $this->options['path'] . '/' . $file['file_name'] . ':/content';
$download_size = WPVIVID_ONEDRIVE_DOWNLOAD_SIZE;
$size = $file['size'];
while ($downloaded_start < $size) {
$ret = $this->download_loop($url, $downloaded_start, $download_size, $size);
if ($ret['result'] != WPVIVID_SUCCESS) {
return $ret;
}
fwrite($fh, $ret['body']);
}
fclose($fh);
return array('result' => WPVIVID_SUCCESS);
}
catch (Exception $error){
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('result'=>WPVIVID_FAILED, 'error'=>$message);
}
}
private function download_loop($url,&$downloaded_start,$download_size,$file_size,$retry_count=0)
{
global $wpvivid_plugin;
$downloaded_end=min($downloaded_start+$download_size-1,$file_size-1);
$response=$this->remote_get_download_backup($url,$downloaded_start,$downloaded_end,false,30);
if ((time() - $this->last_time) > 3) {
if (is_callable($this->callback)) {
call_user_func_array($this->callback, array($downloaded_start, $this->current_file_name,
$this->current_file_size, $this->last_time, $this->last_size));
}
$this->last_size = $downloaded_start;
$this->last_time = time();
}
if($response['result']==WPVIVID_SUCCESS)
{
$downloaded_start=$downloaded_end+1;
$ret['result']=WPVIVID_SUCCESS;
$ret['body']=$response['body'];
return $ret;
}
else
{
if($retry_count<WPVIVID_ONEDRIVE_RETRY_TIMES)
{
$retry_count++;
return $this->download_loop($url,$downloaded_start,$download_size,$file_size,$retry_count);
}
else
{
return $response;
}
}
}
public function remote_get_download_backup($url,$downloaded_start,$downloaded_end,$decode=true,$timeout=30,$except_code=array())
{
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$access_token=base64_decode($this->options['token']['access_token']);
}
else{
$access_token=$this->options['token']['access_token'];
}
if(empty($except_code))
{
$except_code=array(200,201,202,204,206);
}
$curl = curl_init();
$curl_options = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer ' . $access_token,
'Range: '."bytes=$downloaded_start-$downloaded_end"
),
CURLOPT_CONNECTTIMEOUT => $timeout,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_SSL_VERIFYPEER => true
);
$curl_options[CURLOPT_CAINFO] = WPVIVID_PLUGIN_DIR.'/vendor/guzzle/guzzle/src/Guzzle/Http/Resources/cacert.pem';
$curl_options[CURLOPT_FOLLOWLOCATION] = true;
curl_setopt_array($curl, $curl_options);
$result = curl_exec($curl);
$http_info = curl_getinfo($curl);
$http_code = array_key_exists('http_code', $http_info) ? (int) $http_info['http_code'] : null;
if($result !== false)
{
curl_close($curl);
if($http_code==401)
{
$this->refresh_token();
$ret=$this->remote_get_download_backup($url,$downloaded_start,$downloaded_end,$decode,$timeout,$except_code);
return $ret;
}
else
{
if(in_array($http_code,$except_code))
{
$ret['result']=WPVIVID_SUCCESS;
if($decode)
$ret['body']=json_decode($result,1);
else
$ret['body']=$result;
return $ret;
}
else
{
$ret['result']='failed';
$ret['error']='Download files failed, error code: '.$http_code;
return $ret;
}
}
}
else
{
$ret['result']='failed';
$ret['error']=curl_error($curl);
curl_close($curl);
return $ret;
}
}
private function need_refresh()
{
if(time()-120> $this->options['token']['expires'])
{
return true;
}
else
{
return false;
}
}
private function refresh_token()
{
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$refresh_token=base64_decode($this->options['token']['refresh_token']);
}
else{
$refresh_token=$this->options['token']['refresh_token'];
}
$args['method']='POST';
$args['wpvivid_refresh_token']=1;
$args['timeout']=15;
$args['sslverify']=FALSE;
$args['body']=array( 'wpvivid_refresh_token' => '1', 'refresh_token' => $refresh_token);
$response=wp_remote_post('https://auth.wpvivid.com/onedrive_v2/',$args);
if(!is_wp_error($response) && ($response['response']['code'] == 200))
{
$json =stripslashes($response['body']);
$json_ret =json_decode($json,true);
if($json_ret['result']=='success')
{
$remote_options=WPvivid_Setting::get_remote_option($this->options['id']);
$json_ret['token']['access_token']=base64_encode($json_ret['token']['access_token']);
$json_ret['token']['refresh_token']=base64_encode($json_ret['token']['refresh_token']);
$this->options['token']=$json_ret['token'];
$this->options['is_encrypt']=1;
$this->options['token']['expires']=time()+ $json_ret['token']['expires_in'];
if($remote_options!==false)
{
$remote_options['is_encrypt']=1;
$remote_options['token']=$json_ret['token'];
$remote_options['token']['expires']=time()+ $json_ret['token']['expires_in'];
WPvivid_Setting::update_remote_option($this->options['id'],$remote_options);
}
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
else{
$ret['result']=WPVIVID_FAILED;
$ret['error']=$json_ret['error'];
return $ret;
}
}
else
{
$ret['result']=WPVIVID_FAILED;
if ( is_wp_error( $response ) )
{
$ret['error']= $response->get_error_message();
}
else
{
$ret['error']=$response['response']['message'];
}
return $ret;
}
}
private function check_folder($folder)
{
$url='https://graph.microsoft.com/v1.0/me/drive/root:/'.$folder.'?$select=id,name,folder';
$response=$this->remote_get($url);
if($response['result']==WPVIVID_SUCCESS)
{
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
else
{
if(isset($response['code'])&&$response['code'] ==404)
{
$body=array( 'name' => $folder, 'folder' => array("childCount" => '0'));
$body=wp_json_encode($body);
$url='https://graph.microsoft.com/v1.0/me/drive/root/children';
$response=$this->remote_post($url,array(),$body);
if($response['result']==WPVIVID_SUCCESS)
{
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
else
{
return $response;
}
}
else
{
return $response;
}
}
}
private function check_file($file,$folder)
{
$url='https://graph.microsoft.com/v1.0/me/drive/root:/'.$folder.'/'.$file.'?$select=id,name,size';
$response=$this->remote_get($url);
if($response['result']==WPVIVID_SUCCESS)
{
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
else
{
return $response;
}
}
private function _upload($task_id,$local_file,$callback)
{
global $wpvivid_plugin;
$this -> current_file_size = filesize($local_file);
$this -> current_file_name = basename($local_file);
$wpvivid_plugin->wpvivid_log->WriteLog('Check if the server already has the same name file.','notice');
$this->delete_file_by_name($this->options['path'],basename($local_file));
$file_size=filesize($local_file);
//small file
if($file_size<1024*1024*4)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Uploaded files are less than 4M.','notice');
$ret=$this->upload_small_file($local_file,$task_id);
return $ret;
}
else
{
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_ONEDRIVE);
if(empty( $upload_job['job_data'][basename($local_file)]['uploadUrl']))
{
$wpvivid_plugin->wpvivid_log->WriteLog('Creating upload session.','notice');
//big file
$ret=$this->create_upload_session(basename($local_file));
if($ret['result']===WPVIVID_FAILED)
{
return $ret;
}
$upload_job['job_data'][basename($local_file)]['uploadUrl']=$ret['session_url'];
$session_url=$ret['session_url'];
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_ONEDRIVE,WPVIVID_UPLOAD_UNDO,'Created upload session',$upload_job['job_data']);
}
else
{
$session_url=$upload_job['job_data'][basename($local_file)]['uploadUrl'];
}
$wpvivid_plugin->wpvivid_log->WriteLog('Ready to start uploading files.','notice');
$ret=$this->upload_resume($session_url,$local_file,$task_id,$callback);
return $ret;
}
}
private function upload_small_file($file,$task_id)
{
global $wpvivid_plugin;
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_ONEDRIVE);
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$access_token=base64_decode($this->options['token']['access_token']);
}
else{
$access_token=$this->options['token']['access_token'];
}
$path=$this->options['path'].'/'.basename($file);
$args['method']='PUT';
$args['headers']=array( 'Authorization' => 'bearer '.$access_token,'content-type' => 'application/zip');
$args['timeout']=15;
$data=file_get_contents($file);
$args['body']=$data;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_ONEDRIVE,WPVIVID_UPLOAD_UNDO,'Start uploading '.basename($file).'.',$upload_job['job_data']);
$response=wp_remote_post('https://graph.microsoft.com/v1.0/me/drive/root:/'.$path.':/content',$args);
if(!is_wp_error($response) && ($response['response']['code'] == 200||$response['response']['code'] == 201))
{
$upload_job['job_data'][basename($file)]['uploaded']=1;
$wpvivid_plugin->wpvivid_log->WriteLog('Finished uploading '.basename($file),'notice');
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_ONEDRIVE,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file).' completed.',$upload_job['job_data']);
return array('result' =>WPVIVID_SUCCESS);
}
else
{
$ret['result']=WPVIVID_FAILED;
if ( is_wp_error( $response ) )
{
$ret['error']= $response->get_error_message();
}
else
{
$error=json_decode($response['body'],1);
$ret['error']=$error['error']['message'];
}
return $ret;
}
}
private function upload_resume($session_url,$file,$task_id,$callback)
{
global $wpvivid_plugin;
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_ONEDRIVE);
$ret=$this->get_upload_offset($session_url);
if($ret['result']=='failed')
{
return $ret;
}
$offset=$ret['offset'];
$wpvivid_plugin->wpvivid_log->WriteLog('offset '.$offset,'notice');
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_ONEDRIVE,WPVIVID_UPLOAD_UNDO,'Start uploading '.basename($file).'.',$upload_job['job_data']);
$file_size=filesize($file);
$handle=fopen($file,'rb');
$upload_size=WPVIVID_ONEDRIVE_UPLOAD_SIZE;
$upload_end=min($offset+$upload_size-1,$file_size-1);
while(true)
{
$ret=$this->upload_loop($session_url,$handle,$offset,$upload_end,$upload_size,$file_size,$task_id,$callback);
if($ret['result']==WPVIVID_SUCCESS)
{
if((time() - $this -> last_time) >3)
{
if(is_callable($callback))
{
call_user_func_array($callback,array($offset,$this -> current_file_name,
$this->current_file_size,$this -> last_time,$this -> last_size));
}
$this -> last_size = $offset;
$this -> last_time = time();
}
if($ret['op']=='continue')
{
continue;
}
else
{
break;
}
}
else
{
return $ret;
}
}
fclose($handle);
$upload_job['job_data'][basename($file)]['uploaded']=1;
$wpvivid_plugin->wpvivid_log->WriteLog('Finished uploading '.basename($file),'notice');
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_ONEDRIVE,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file).' completed.',$upload_job['job_data']);
return array('result' =>WPVIVID_SUCCESS);
}
private function get_upload_offset($uploadUrl)
{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('uploadUrl: '.$uploadUrl,'notice');
$url=$uploadUrl;
$response=$this->remote_get_ex($url);
if($response['result']==WPVIVID_SUCCESS)
{
if($response['code']==200)
{
$ranges=$response['body']['nextExpectedRanges'];
if (is_array($ranges))
{
$range = $ranges[0];
} else {
$range=$ranges;
}
if (preg_match('/^(\d+)/', $range, $matches))
{
$uploaded = $matches[1];
$ret['result']='success';
$ret['offset']=$uploaded;
return $ret;
}
else
{
$ret['result']='failed';
$ret['error']='get offset failed';
return $ret;
}
}
else
{
$ret['result']='failed';
$ret['error']='get offset failed';
return $ret;
}
}
else
{
return $response;
}
}
private function create_upload_session($file)
{
$path=$this->options['path'].'/'.basename($file);
$url='https://graph.microsoft.com/v1.0/me/drive/root:/'.$path.':/createUploadSession';
$response=$this->remote_post($url);
if($response['result']==WPVIVID_SUCCESS)
{
$upload_session=$response['body']['uploadUrl'];
$ret['result']=WPVIVID_SUCCESS;
$ret['session_url']=$upload_session;
return $ret;
}
else
{
return $response;
}
}
private function upload_loop($url,$file_handle,&$uploaded,&$upload_end,$upload_size,$file_size,$task_id,$callback,$retry_count=0)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
curl_setopt($curl, CURLOPT_TIMEOUT, 60);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$upload_size=min($upload_size,$file_size-$uploaded);
if ($uploaded)
fseek($file_handle, $uploaded);
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$access_token=base64_decode($this->options['token']['access_token']);
}
else{
$access_token=$this->options['token']['access_token'];
}
$headers = array(
"Content-Length: $upload_size",
"Content-Range: bytes $uploaded-$upload_end/".$file_size,
);
//$headers[] = 'Authorization: Bearer ' . $access_token;
$options = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_PUT => true,
CURLOPT_INFILE => $file_handle,
CURLOPT_INFILESIZE => $upload_size,
CURLOPT_RETURNTRANSFER=>true,
);
curl_setopt_array($curl, $options);
global $wpvivid_plugin;
$response=curl_exec($curl);
$http_code = curl_getinfo($curl,CURLINFO_HTTP_CODE);
if($response!=false)
{
curl_close($curl);
if($http_code==202)
{
$json=json_decode($response,1);
$ranges=$json['nextExpectedRanges'];
if (is_array($ranges))
{
$range = $ranges[0];
} else {
$range=$ranges;
}
if (preg_match('/^(\d+)/', $range, $matches))
{
$uploaded = $matches[1];
$upload_end=min($uploaded+$upload_size-1,$file_size-1);
}
$ret['result']=WPVIVID_SUCCESS;
$ret['op']='continue';
return $ret;
}
else if($http_code==200||$http_code==201)
{
$ret['result']=WPVIVID_SUCCESS;
$ret['op']='finished';
return $ret;
}
else
{
if($retry_count<WPVIVID_ONEDRIVE_RETRY_TIMES)
{
$error=json_decode($response,1);
$wpvivid_plugin->wpvivid_log->WriteLog('http code is not 200, start retry. http code :'.$http_code.', error: '.wp_json_encode($error),'notice');
$ret=$this->get_upload_offset($url);
if($ret['result']=='failed')
{
return $ret;
}
$uploaded=$ret['offset'];
$upload_end=min($uploaded+$upload_size-1,$file_size-1);
$wpvivid_plugin->wpvivid_log->WriteLog('offset '.$uploaded,'notice');
$retry_count++;
return $this->upload_loop($url,$file_handle,$uploaded,$upload_end,$upload_size,$file_size,$task_id,$callback,$retry_count);
}
else
{
$ret['result']=WPVIVID_FAILED;
$error=json_decode($response,1);
$ret['error']=$error['error']['message'];
return $ret;
}
}
}
else
{
if($retry_count<WPVIVID_ONEDRIVE_RETRY_TIMES)
{
$wpvivid_plugin->wpvivid_log->WriteLog('http no response, start retry. http code :'.$http_code,'notice');
$ret=$this->get_upload_offset($url);
if($ret['result']=='failed')
{
return $ret;
}
$uploaded=$ret['offset'];
$upload_end=min($uploaded+$upload_size-1,$file_size-1);
$wpvivid_plugin->wpvivid_log->WriteLog('offset '.$uploaded,'notice');
if($http_code === 202)
{
WPvivid_taskmanager::wpvivid_reset_backup_retry_times($task_id);
$retry_count=0;
if(is_callable($callback))
{
call_user_func_array($callback,array($uploaded,$this -> current_file_name,
$this->current_file_size,$this -> last_time,$this -> last_size));
}
$this -> last_size = $uploaded;
$this -> last_time = time();
}
else
{
$retry_count++;
}
return $this->upload_loop($url,$file_handle,$uploaded,$upload_end,$upload_size,$file_size,$task_id,$callback,$retry_count);
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('retry times: '.$retry_count.', http code :'.$http_code,'notice');
$ret['result']=WPVIVID_FAILED;
$ret['error']=curl_error($curl);
curl_close($curl);
return $ret;
}
}
}
private function get_files_id($files,$path)
{
$ret['ids']=array();
foreach ($files as $file)
{
$url='https://graph.microsoft.com/v1.0/me/drive/root:/'.$path.'/'.$file.'?$select=id';
$response=$this->remote_get($url);
if($response['result']==WPVIVID_SUCCESS)
{
if($response['code']==200)
{
$ret['ids'][]=$response['body']['id'];
}
}
else
{
continue;
}
}
if(sizeof($ret['ids'])==0)
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='file not found';
}
else
{
$ret['result']=WPVIVID_SUCCESS;
}
return $ret;
}
private function delete_file($id)
{
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$access_token=base64_decode($this->options['token']['access_token']);
}
else{
$access_token=$this->options['token']['access_token'];
}
$args['method']='DELETE';
$args['headers']=array( 'Authorization' => 'bearer '.$access_token);
$args['timeout']=15;
$response = wp_remote_request( 'https://graph.microsoft.com/v1.0/me/drive/items/'.$id,$args);
if(!is_wp_error($response) && ($response['response']['code'] == 204))
{
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
else
{
$ret['result']=WPVIVID_FAILED;
if ( is_wp_error( $response ) )
{
$ret['error']= $response->get_error_message();
}
else
{
$ret['error']= $response['body'];
}
return $ret;
}
}
private function remote_get($url,$header=array(),$decode=true,$timeout=15,$except_code=array())
{
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$access_token=base64_decode($this->options['token']['access_token']);
}
else{
$access_token=$this->options['token']['access_token'];
}
if(empty($except_code))
{
$except_code=array(200,201,202,204,206);
}
$args['timeout']=$timeout;
$args['headers']['Authorization']= 'bearer '.$access_token;
$args['headers']= $args['headers']+$header;
$response=wp_remote_get($url,$args);
if(!is_wp_error($response))
{
$ret['code']=$response['response']['code'];
if(in_array($response['response']['code'],$except_code))
{
$ret['result']=WPVIVID_SUCCESS;
if($decode)
$ret['body']=json_decode($response['body'],1);
else
$ret['body']=$response['body'];
}
else
{
$ret['result']=WPVIVID_FAILED;
$error=json_decode($response['body'],1);
$ret['error']=$error['error']['message'].' http code:'.$response['response']['code'];
}
return $ret;
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']=$response->get_error_message();
return $ret;
}
}
public function remote_get_ex($url,$header=array(),$decode=true,$timeout=30,$except_code=array())
{
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$access_token=base64_decode($this->options['token']['access_token']);
}
else{
$access_token=$this->options['token']['access_token'];
}
if(empty($except_code))
{
$except_code=array(200,201,202,204,206);
}
$args['timeout']=$timeout;
$args['headers']=$header;
$response=wp_remote_get($url,$args);
if(!is_wp_error($response))
{
if($response['response']['code']==401)
{
$this->refresh_token();
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$access_token=base64_decode($this->options['token']['access_token']);
}
else{
$access_token=$this->options['token']['access_token'];
}
$args=array();
$args['timeout']=$timeout;
$args['headers']['Authorization']= 'bearer '.$access_token;
$args['headers']= $args['headers']+$header;
$response=wp_remote_get($url,$args);
}
$ret['code']=$response['response']['code'];
if(in_array($response['response']['code'],$except_code))
{
$ret['result']=WPVIVID_SUCCESS;
if($decode)
$ret['body']=json_decode($response['body'],1);
else
$ret['body']=$response['body'];
}
else
{
$ret['result']=WPVIVID_FAILED;
$error=json_decode($response['body'],1);
$ret['error']=$error['error']['message'].' http code:'.$response['response']['code'];
}
return $ret;
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']=$response->get_error_message();
return $ret;
}
}
private function remote_post($url,$header=array(),$body=null,$except_code=array())
{
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$access_token=base64_decode($this->options['token']['access_token']);
}
else{
$access_token=$this->options['token']['access_token'];
}
if(empty($except_code))
{
$except_code=array(200,201,202,204,206);
}
$args['method']='POST';
$args['headers']=array( 'Authorization' => 'bearer '.$access_token,'content-type' => 'application/json');
$args['headers']=$args['headers']+$header;
if(!is_null($body))
{
$args['body']=$body;
}
$args['timeout']=15;
$response=wp_remote_post($url,$args);
if(!is_wp_error($response))
{
$ret['code']=$response['response']['code'];
if(in_array($response['response']['code'],$except_code))
{
$ret['result']=WPVIVID_SUCCESS;
$ret['body']=json_decode($response['body'],1);
}
else
{
$ret['result']=WPVIVID_FAILED;
$error=json_decode($response['body'],1);
$ret['error']=$error['error']['message'];
}
return $ret;
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']=$response->get_error_message();
return $ret;
}
}
private function delete_file_by_name($folder,$file_name)
{
$files[]=$file_name;
$ret=$this->get_files_id($files,$folder);
if($ret['result']==WPVIVID_SUCCESS)
{
$ids=$ret['ids'];
foreach ($ids as $id)
{
$ret=$this->delete_file($id);
if($ret['result']==WPVIVID_FAILED)
{
return $ret;
}
}
}
else
{
return $ret;
}
return array('result' =>WPVIVID_SUCCESS);
}
public function wpvivid_remote_pic_one_drive($remote)
{
$remote['onedrive']['default_pic'] = '/admin/partials/images/storage-microsoft-onedrive(gray).png';
$remote['onedrive']['selected_pic'] = '/admin/partials/images/storage-microsoft-onedrive.png';
$remote['onedrive']['title'] = 'Microsoft OneDrive';
return $remote;
}
public function wpvivid_get_out_of_date_one_drive($out_of_date_remote, $remote)
{
if($remote['type'] == WPVIVID_REMOTE_ONEDRIVE){
$root_path=apply_filters('wpvivid_get_root_path', $remote['type']);
$out_of_date_remote = $root_path.$remote['path'];
}
return $out_of_date_remote;
}
public function wpvivid_storage_provider_one_drive($storage_type)
{
if($storage_type == WPVIVID_REMOTE_ONEDRIVE){
$storage_type = 'Microsoft OneDrive';
}
return $storage_type;
}
public function wpvivid_get_root_path_one_drive($storage_type){
if($storage_type == WPVIVID_REMOTE_ONEDRIVE){
$storage_type = 'root/';
}
return $storage_type;
}
public function finish_add_remote()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (empty($_POST) || !isset($_POST['remote']) || !is_string($_POST['remote'])) {
die();
}
$tmp_remote_options = get_transient('onedrive_auth_id');
if($tmp_remote_options === false)
{
die();
}
delete_transient('onedrive_auth_id');
if(empty($tmp_remote_options)||$tmp_remote_options['type']!==WPVIVID_REMOTE_ONEDRIVE)
{
die();
}
$json = sanitize_text_field($_POST['remote']);
$json = stripslashes($json);
$remote_options = json_decode($json, true);
if (is_null($remote_options)) {
die();
}
$remote_options['path'] = WPVIVID_ONEDRIVE_DEFAULT_FOLDER;
$remote_options=array_merge($remote_options,$tmp_remote_options);
if(!class_exists('WPvivid_Remote_collection'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-remote-collection.php';
$wpvivid_plugin->remote_collection=new WPvivid_Remote_collection();
}
$ret = $wpvivid_plugin->remote_collection->add_remote($remote_options);
if ($ret['result'] == 'success') {
$html = '';
$html = apply_filters('wpvivid_add_remote_storage_list', $html);
$ret['html'] = $html;
$pic = '';
$pic = apply_filters('wpvivid_schedule_add_remote_pic', $pic);
$ret['pic'] = $pic;
$dir = '';
$dir = apply_filters('wpvivid_get_remote_directory', $dir);
$ret['dir'] = $dir;
$schedule_local_remote = '';
$schedule_local_remote = apply_filters('wpvivid_schedule_local_remote', $schedule_local_remote);
$ret['local_remote'] = $schedule_local_remote;
$remote_storage = '';
$remote_storage = apply_filters('wpvivid_remote_storage', $remote_storage);
$ret['remote_storage'] = $remote_storage;
$remote_select_part = '';
$remote_select_part = apply_filters('wpvivid_remote_storage_select_part', $remote_select_part);
$ret['remote_select_part'] = $remote_select_part;
$default = array();
$remote_array = apply_filters('wpvivid_archieve_remote_array', $default);
$ret['remote_array'] = $remote_array;
$success_msg = __('You have successfully added a remote storage.', 'wpvivid-backuprestore');
$ret['notice'] = apply_filters('wpvivid_add_remote_notice', true, $success_msg);
}
else{
$ret['notice'] = apply_filters('wpvivid_add_remote_notice', false, $ret['error']);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
} includes/customclass/class-wpvivid-base-s3.php 0000644 00000026310 15132770567 0015470 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
include_once 'class-wpvivid-s3.php';
class WPvivid_Base_S3 extends Wpvivid_S3{
var $signVer = 'v2';
/**
* Set Signature Version
*
* @param string $version
* @return void
*/
public function setSignatureVersion($version = 'v2') {
$this->signVer = $version;
}
public function setServerSideEncryption($value = self::SSE_AES256) {
$this->_serverSideEncryption = $value;
}
public function setStorageClass($value = self::STORAGE_CLASS_STANDARD_IA){
$this -> _storageClass = $value;
}
public function initiateMultipartUpload ($bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self::STORAGE_CLASS_STANDARD) {
$rest = new WPvivid_S3Request('POST', $bucket, $uri, $this->endpoint, $this);
$rest->setParameter('uploads','');
if (is_array($requestHeaders) && !empty($requestHeaders))
foreach ($requestHeaders as $h => $v) $rest->setHeader($h, $v);
if(is_array($metaHeaders) && !empty($metaHeaders))
foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
if ($this -> _storageClass !== self::STORAGE_CLASS_STANDARD) // Storage class
$rest->setAmzHeader('x-amz-storage-class', $this -> _storageClass);
if ($this -> _serverSideEncryption !== self::SSE_NONE) // Server-side encryption
$rest->setAmzHeader('x-amz-server-side-encryption', $this -> _serverSideEncryption);
$rest->setAmzHeader('x-amz-acl', $acl);
$rest->getResponse();
if (false === $rest->response->error && 200 !== $rest->response->code) {
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
}
if (false !== $rest->response->error) {
$this->__triggerError(sprintf("WPvivid_S3::initiateMultipartUpload(): [%s] %s",
$rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__);
return false;
} elseif (isset($rest->response->body)) {
if (is_a($rest->response->body, 'SimpleXMLElement')) {
$body = $rest->response->body;
} else {
$body = new SimpleXMLElement($rest->response->body);
}
return (string) $body->UploadId;
}
return false;
}
public function uploadPart ($bucket, $uri, $uploadId, $filePath, $partNumber, $partSize = 5242880) {
$rest = new WPvivid_S3Request('PUT', $bucket, $uri, $this->endpoint, $this);
$rest->setParameter('partNumber', $partNumber);
$rest->setParameter('uploadId', $uploadId);
$fileOffset = ($partNumber - 1 ) * $partSize;
$fileBytes = min(filesize($filePath) - $fileOffset, $partSize);
if ($fileBytes < 0) $fileBytes = 0;
$rest->setHeader('Content-Type', 'application/octet-stream');
$rest->data = "";
if ($handle = fopen($filePath, "rb")) {
if ($fileOffset >0) fseek($handle, $fileOffset);
$bytes_read = 0;
while ($fileBytes>0 && $read = fread($handle, max($fileBytes, 131072))) { //128kb
$fileBytes = $fileBytes - strlen($read);
$bytes_read += strlen($read);
$rest->data = $rest->data . $read;
}
fclose($handle);
} else {
return false;
}
$rest->setHeader('Content-MD5', base64_encode(md5($rest->data, true)));
$rest->size = $bytes_read;
$rest = $rest->getResponse();
if (false === $rest->error && 200 !== $rest->code) {
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
}
if (false !== $rest->error) {
$this->__triggerError(sprintf("S3::uploadPart(): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return $rest->headers['hash'];
}
public function completeMultipartUpload ($bucket, $uri, $uploadId, $parts) {
$rest = new WPvivid_S3Request('POST', $bucket, $uri, $this->endpoint, $this);
$rest->setParameter('uploadId', $uploadId);
$xml = "<CompleteMultipartUpload>\n";
$partno = 1;
foreach ($parts as $etag) {
$xml .= "<Part><PartNumber>$partno</PartNumber><ETag>$etag</ETag></Part>\n";
$partno++;
}
$xml .= "</CompleteMultipartUpload>";
$rest->data = $xml;
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
$rest = $rest->getResponse();
if (false === $rest->error && 200 !== $rest->code) {
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
}
if (false !== $rest->error) {
if ('InternalError' == $rest->error['code'] && 'This multipart completion is already in progress' == $rest->error['message']) {
return true;
}
$this->__triggerError(sprintf("S3::completeMultipartUpload(): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
public function abortMultipartUpload ($bucket, $uri, $uploadId) {
$rest = new WPvivid_S3Request('DELETE', $bucket, $uri, $this->endpoint, $this);
$rest->setParameter('uploadId', $uploadId);
$rest = $rest->getResponse();
if (false === $rest->error && 204 !== $rest->code) {
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
}
if (false !== $rest->error) {
$this->__triggerError(sprintf("S3::abortMultipartUpload(): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
public function getObject($bucket, $uri, $saveTo = false, $resume = false) {
$rest = new WPvivid_S3Request('GET', $bucket, $uri, $this->endpoint, $this);
if (false !== $saveTo) {
if (is_resource($saveTo)) {
$rest->fp = $saveTo;
if (!is_bool($resume)) $rest->setHeader('Range', $resume);
} else {
if ($resume && file_exists($saveTo)) {
if (false !== ($rest->fp = @fopen($saveTo, 'ab'))) {
$rest->setHeader('Range', "bytes=".filesize($saveTo).'-');
$rest->file = realpath($saveTo);
} else {
$rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
}
} else {
if (false !== ($rest->fp = @fopen($saveTo, 'wb')))
$rest->file = realpath($saveTo);
else
$rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
}
}
}
if (false === $rest->response->error) $rest->getResponse();
if (false === $rest->response->error && ( !$resume && 200 != $rest->response->code) || ( $resume && 206 != $rest->response->code && 200 != $rest->response->code))
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if (false !== $rest->response->error) {
$this->__triggerError(sprintf("WPvivid_S3::getObject({$bucket}, {$uri}): [%s] %s",
$rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__);
return false;
}
return $rest->response;
}
/*public function listObject($bucket, $path)
{
$rest = new WPvivid_S3Request('GET', $bucket, '', $this->endpoint, $this);
$rest->setParameter('list-type', 2);
//$rest->setParameter('max-keys', 2000);
$rest->setParameter('prefix', $path);
$rest->setParameter('start-after', 'wpvividbackuppro/pestcontrolcanberraarea_com_au\/2020_08_03_to_2020_08_10/pestcontrolcanberraarea.com.au_wpvivid-5f28895122706_2020-08-04-08-00_incremental_backup_all.zip');
//$rest->setParameter('delimiter', $path);
$response = $rest->getResponse();
if ($response->error === false && $response->code !== 200)
{
//$response->error = array('code' => $response->code, 'message' => 'Unexpected HTTP status');
$ret['result']='failed';
$ret['error']=$response['message'].' '.$response->code;
return $ret;
}
if ($response->error !== false)
{
$ret['result']='failed';
$ret['error']=sprintf("S3::getBucket(): [%s] %s", $response->error['code'], $response->error['message']);
return $ret;
}
$results = array();
if (isset($response->body, $response->body->Contents))
{
foreach ($response->body->Contents as $c)
{
$results[] = array(
'name' => (string)$c->Key,
'size' => (int)$c->Size,
);
}
}
$ret['result']='success';
$ret['data']=$results;
return $ret;
}*/
public function listObject($bucket, $path)
{
$ret['result']='success';
$results = array();
$bcheck = true;
$bcontinue = false;
$continue_token = '';
$start_after = '';
$rest = new WPvivid_S3Request('GET', $bucket, '', $this->endpoint, $this);
while($bcheck){
$rest->unsetParameter($bucket);
$rest->setParameter('list-type', 2);
if($bcontinue) {
$rest->setParameter('start-after', $start_after);
}
else{
$rest->setParameter('prefix', $path);
}
$response = $rest->getResponse();
if ($response->error === false && $response->code !== 200)
{
$ret['result']='failed';
$ret['error']=$response['message'].' '.$response->code;
return $ret;
}
if ($response->error !== false)
{
$ret['result']='failed';
$ret['error']=sprintf("S3::getBucket(): [%s] %s", $response->error['code'], $response->error['message']);
return $ret;
}
if (isset($response->body, $response->body->Contents))
{
foreach ($response->body->Contents as $c)
{
$results[] = array(
'name' => (string)$c->Key,
'size' => (int)$c->Size,
);
$start_after = (string)$c->Key;
}
}
if(isset($response->body->NextContinuationToken)){
$bcontinue = true;
$continue_token = $response->body->NextContinuationToken;
$start_after = $start_after;
$bcheck = true;
}
else{
$bcontinue = false;
$continue_token = '';
$bcheck = false;
}
$ret['result']='success';
$ret['data']=$results;
if(!$bcheck){
break;
}
}
return $ret;
}
} includes/customclass/class-wpvivid-send-to-site.php 0000644 00000121242 15132770567 0016546 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
if(!defined('WPVIVID_REMOTE_SEND_TO_SITE'))
define('WPVIVID_REMOTE_SEND_TO_SITE','send_to_site');
include_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-remote.php';
if(!defined('WPVIVID_SEND_TO_SITE_UPLOAD_SIZE'))
define('WPVIVID_SEND_TO_SITE_UPLOAD_SIZE', 2);
class WPvivid_Send_to_site extends WPvivid_Remote
{
public $options;
public function __construct($options=array())
{
if(empty($options))
{
if(!defined('WPVIVID_INIT_SEND_TO_SITE'))
{
add_action('plugins_loaded', array($this, 'plugins_loaded'));
define('WPVIVID_INIT_SEND_TO_SITE',1);
}
}
else
{
$this->options=$options;
}
}
public function plugins_loaded()
{
if (!empty($_POST) &&isset($_POST['wpvivid_action']))
{
@ini_set( 'display_errors', 0 );
if($_POST['wpvivid_action']=='send_to_site_connect')
{
$this->send_to_site_connect();
}
else if($_POST['wpvivid_action']=='send_to_site_finish')
{
$this->send_to_site_finish();
}
else if($_POST['wpvivid_action']=='send_to_site')
{
$this->send_to_site();
}
else if($_POST['wpvivid_action']=='send_to_site_file_status')
{
$this->send_to_site_file_status();
}
else if($_POST['wpvivid_action']=='clear_backup_cache')
{
$this->clear_backup_cache();
}
die();
}
}
public function init_remotes($remote_collection)
{
$remote_collection[WPVIVID_REMOTE_SEND_TO_SITE] = 'WPvivid_Send_to_site';
return $remote_collection;
}
public function test_connect()
{
return array('result' => WPVIVID_SUCCESS,'test'=>$this->options['url']);
}
public function upload($task_id, $files, $callback = '')
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-crypt.php';
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Connect site ','notice');
$ret=$this->connect_site($task_id);
if($ret['result']==WPVIVID_FAILED)
{
if($ret['error']=='The uploading backup already exists in Backups list.')
{
return array('result' =>WPVIVID_SUCCESS);
}
else
{
return $ret;
}
}
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SEND_TO_SITE);
if(empty($upload_job))
{
$job_data=array();
foreach ($files as $file)
{
$file_data['size']=filesize($file);
$file_data['uploaded']=0;
$job_data[basename($file)]=$file_data;
}
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SEND_TO_SITE,WPVIVID_UPLOAD_UNDO,'Start uploading',$job_data);
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SEND_TO_SITE);
}
foreach ($files as $file)
{
$wpvivid_plugin->set_time_limit($task_id);
if(array_key_exists(basename($file),$upload_job['job_data']))
{
if($upload_job['job_data'][basename($file)]['uploaded']==1)
continue;
}
$this -> last_time = time();
$this -> last_size = 0;
if(!file_exists($file))
return array('result' =>WPVIVID_FAILED,'error' =>$file.' not found. The file might has been moved, renamed or deleted. Please reload the list and verify the file exists.');
$result=$this->_upload($task_id, $file,$callback);
if($result['result'] !==WPVIVID_SUCCESS)
{
$this->wpvivid_clear_backup_cache($task_id);
return $result;
}
}
$result=$this->upload_finish($task_id);
return $result;
//return array('result' =>WPVIVID_SUCCESS);
}
public function _upload($task_id, $file,$callback)
{
$this -> current_file_size = filesize($file);
$this -> current_file_name = basename($file);
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SEND_TO_SITE);
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Start uploading '.basename($file),'notice');
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SEND_TO_SITE,WPVIVID_UPLOAD_UNDO,'Start uploading '.basename($file).'.',$upload_job['job_data']);
$file_size=filesize($file);
$md5=md5_file($file);
$handle=fopen($file,'rb');
$ret=$this->get_file_status($task_id,basename($file),$file_size,$md5);
$wpvivid_plugin->wpvivid_log->WriteLog(wp_json_encode($ret),'notice');
if($ret['result']==WPVIVID_SUCCESS)
{
if($ret['file_status']['status']=='finished')
{
$wpvivid_plugin->wpvivid_log->WriteLog('upload finished','notice');
fclose($handle);
$upload_job['job_data'][basename($file)]['uploaded']=1;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SEND_TO_SITE,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file).' completed.',$upload_job['job_data']);
return array('result' =>WPVIVID_SUCCESS);
}
else if($ret['file_status']['status']=='continue')
{
$offset=$ret['file_status']['offset'];
}
else
{
$offset=0;
}
}
else
{
return $ret;
}
$retry_count=0;
while (!feof($handle))
{
$general_setting=WPvivid_Setting::get_setting(true, "");
if(!isset($general_setting['options']['wpvivid_common_setting']['migrate_size']) || empty($general_setting['options']['wpvivid_common_setting']['migrate_size'])){
$general_setting['options']['wpvivid_common_setting']['migrate_size']=WPVIVID_SEND_TO_SITE_UPLOAD_SIZE;
}
$upload_size = $general_setting['options']['wpvivid_common_setting']['migrate_size'];
$upload_size = intval($upload_size) * 1024;
$ret=$this->send_chunk($task_id,$handle,basename($file),$offset,$upload_size,$file_size,$md5);
if($ret['result']==WPVIVID_SUCCESS)
{
$status = WPvivid_taskmanager::get_backup_task_status($task_id);
$status['resume_count']=0;
WPvivid_taskmanager::update_backup_task_status($task_id, false, 'running', false, $status['resume_count']);
if((time() - $this -> last_time) >3)
{
if(is_callable($callback))
{
call_user_func_array($callback,array($offset,$this -> current_file_name,
$this->current_file_size,$this -> last_time,$this -> last_size));
}
$this -> last_size = $offset;
$this -> last_time = time();
}
if($ret['op']=='continue')
{
continue;
}
else
{
break;
}
}
else
{
if($retry_count>3)
{
if(isset($ret['http_code']))
{
if($ret['http_code']==413)
{
$ret['error']='Site migration failed. The receiving site can\'t receive the oversized data chunk. Please set the value of Chunk size to 512 KB in plugin settings. Then try again.';
}
}
return $ret;
}
else
{
if(isset($ret['http_code']))
{
if($ret['http_code']==413)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Site migration failed. The receiving site can\'t receive the oversized data chunk. Please set the value of Chunk size to 512 KB in plugin settings. Then try again. Chunk size: '.size_format($offset),'warning');
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('upload file error offset:'.size_format($offset).' http error:'.$ret['http_code'],'warning');
}
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('upload file error offset:'.size_format($offset).' error:'.$ret['error'],'warning');
}
$retry_count++;
}
}
}
$wpvivid_plugin->wpvivid_log->WriteLog('upload finished','notice');
fclose($handle);
$upload_job['job_data'][basename($file)]['uploaded']=1;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SEND_TO_SITE,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file).' completed.',$upload_job['job_data']);
return array('result' =>WPVIVID_SUCCESS);
}
public function wpvivid_clear_backup_cache($task_id)
{
global $wpvivid_plugin;
$json=array();
$json['backup_id']=$task_id;
$json=wp_json_encode($json);
$crypt=new WPvivid_crypt(base64_decode($this->options['token']));
$data=$crypt->encrypt_message($json);
$data=base64_encode($data);
$wpvivid_plugin->wpvivid_log->WriteLog('Failed upload backup, clear backup cache.','notice');
global $wp_version;
$args['user-agent'] ='WordPress/' . $wp_version . '; ' . get_bloginfo('url');
$args['body']=array('wpvivid_content'=>$data,'wpvivid_action'=>'clear_backup_cache');
$args['timeout']=30;
$response=wp_remote_post($this->options['url'],$args);
if ( is_wp_error( $response ) )
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $response->get_error_message();
$wpvivid_plugin->wpvivid_log->WriteLog( $ret['error'],'notice');
}
else
{
if($response['response']['code']==200)
{
$res=json_decode($response['body'],1);
if($res!=null)
{
if($res['result']==WPVIVID_SUCCESS)
{
$ret['result']=WPVIVID_SUCCESS;
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $res['error'];
$wpvivid_plugin->wpvivid_log->WriteLog( $ret['error'],'notice');
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'Failed to parse returned data, unable to clear target site backup cache.';
$wpvivid_plugin->wpvivid_log->WriteLog( $ret['error'],'notice');
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'Clear backup cache error '.$response['response']['code'].' '.$response['body'];
$wpvivid_plugin->wpvivid_log->WriteLog( $ret['error'],'notice');
}
}
return $ret;
}
public function connect_site($task_id)
{
$json=array();
$json['backup_id']=$task_id;
$json=wp_json_encode($json);
$crypt=new WPvivid_crypt(base64_decode($this->options['token']));
$data=$crypt->encrypt_message($json);
$data=base64_encode($data);
global $wp_version;
$args['user-agent'] ='WordPress/' . $wp_version . '; ' . get_bloginfo('url');
$args['body']=array('wpvivid_content'=>$data,'wpvivid_action'=>'send_to_site_connect');
$args['timeout']=30;
$response=wp_remote_post($this->options['url'],$args);
if ( is_wp_error( $response ) )
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $response->get_error_message();
}
else
{
if($response['response']['code']==200)
{
global $wpvivid_plugin;
$res=json_decode($response['body'],1);
if($res!=null)
{
if($res['result']==WPVIVID_SUCCESS)
{
$ret['result']=WPVIVID_SUCCESS;
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $res['error'];
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'Failed to parse returned data, unable to establish connection with the target site.';
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'Upload error '.$response['response']['code'].' '.$response['body'];
}
}
return $ret;
}
public function send_chunk($task_id,$file_handle,$file_name,&$offset,$size,$file_size,$md5)
{
$upload_size=min($size,$file_size-$offset);
if ($offset)
fseek($file_handle, $offset);
$data=fread($file_handle,$upload_size);
if($data===false)
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='Read file error at:'.$offset;
return $ret;
}
$json['backup_id']=$task_id;
$json['name']=$file_name;
$json['offset']=$offset;
$json['size']=$upload_size;
$json['file_size']=$file_size;
$json['md5']=$md5;
$json['data']=base64_encode($data);
$json=wp_json_encode($json);
$crypt=new WPvivid_crypt(base64_decode($this->options['token']));
$data=$crypt->encrypt_message($json);
$data=base64_encode($data);
global $wp_version;
$args['user-agent'] ='WordPress/' . $wp_version . '; ' . get_bloginfo('url');
$args['body']=array('wpvivid_content'=>$data,'wpvivid_action'=>'send_to_site');
$args['timeout']=30;
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('send chunk '.basename($file_name).' offset '.$offset,'notice');
$response=wp_remote_post($this->options['url'],$args);
$wpvivid_plugin->wpvivid_log->WriteLog('finished send chunk','notice');
if ( is_wp_error( $response ) )
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $response->get_error_message();
}
else
{
if($response['response']['code']==200)
{
$res=json_decode($response['body'],1);
if($res!=null)
{
if($res['result']==WPVIVID_SUCCESS)
{
$offset=$offset+$upload_size;
$ret['result']=WPVIVID_SUCCESS;
$ret['op']=$res['op'];
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $res['error'];
$wpvivid_plugin->wpvivid_log->WriteLog( $ret['error'],'notice');
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'Failed to parse returned data, chunk transfer failed.';
$wpvivid_plugin->wpvivid_log->WriteLog('error send chunk failed','notice');
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['http_code']=$response['response']['code'];
$ret['error']= 'http error, error code:'.$response['response']['code'];
}
}
return $ret;
}
public function upload_finish($task_id)
{
$task= new WPvivid_Backup_Task_2($task_id);
$task->update_backup_result();
$task=WPvivid_taskmanager::get_task($task_id);
$json=array();
$json['backup']=$task;
$json['backup_id']=$task_id;
$json=wp_json_encode($json);
$crypt=new WPvivid_crypt(base64_decode($this->options['token']));
$data=$crypt->encrypt_message($json);
$data=base64_encode($data);
global $wp_version;
$args['user-agent'] ='WordPress/' . $wp_version . '; ' . get_bloginfo('url');
$args['body']=array('wpvivid_content'=>$data,'wpvivid_action'=>'send_to_site_finish');
$args['timeout']=30;
$response=wp_remote_post($this->options['url'],$args);
if ( is_wp_error( $response ) )
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $response->get_error_message();
}
else
{
if($response['response']['code']==200)
{
$res=json_decode($response['body'],1);
if($res!=null)
{
if($res['result']==WPVIVID_SUCCESS)
{
$ret['result']=WPVIVID_SUCCESS;
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $res['error'];
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'Failed to parse returned data, uploading backup chunks failed.';
}
}
else
{
$ret['result']=WPVIVID_FAILED;
//$ret['error']= 'Upload error '.$response['response']['code'].' '.$response['body'];
$ret['error']= 'Upload error '.$response['response']['code'];
}
}
return $ret;
}
public function send_to_site_connect()
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-crypt.php';
try {
if (isset($_POST['wpvivid_content'])) {
$default = array();
$option = get_option('wpvivid_api_token', $default);
if (empty($option)) {
die();
}
if ($option['expires'] != 0 && $option['expires'] < time()) {
die();
}
$crypt = new WPvivid_crypt(base64_decode($option['private_key']));
$body = base64_decode($_POST['wpvivid_content']);
$data = $crypt->decrypt_message($body);
if (!is_string($data)) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'Data decryption failed.';
echo wp_json_encode($ret);
die();
}
$params = json_decode($data, 1);
if (is_null($params)) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'Data decode failed.';
echo wp_json_encode($ret);
die();
}
if (isset($params['backup_id'])) {
if (WPvivid_Backuplist::get_backup_by_id($params['backup_id']) !== false) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'The uploading backup already exists in Backups list.';
echo wp_json_encode($ret);
} else {
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log = new WPvivid_Log();
if (!file_exists($wpvivid_plugin->wpvivid_log->GetSaveLogFolder() . $params['backup_id'] . '_backup_log.txt')) {
$wpvivid_plugin->wpvivid_log->CreateLogFile($params['backup_id'] . '_backup', 'no_folder', 'transfer');
$wpvivid_plugin->wpvivid_log->WriteLogHander();
} else {
$wpvivid_plugin->wpvivid_log->OpenLogFile($params['backup_id'] . '_backup', 'no_folder');
}
$wpvivid_plugin->wpvivid_log->WriteLog('Connect site success', 'notice');
$ret['result'] = WPVIVID_SUCCESS;
echo wp_json_encode($ret);
}
} else {
$ret['result'] = WPVIVID_SUCCESS;
echo wp_json_encode($ret);
}
}
}
catch (Exception $e) {
$ret['result']=WPVIVID_FAILED;
$ret['error']=$e->getMessage();
echo wp_json_encode($ret);
die();
}
die();
}
public function send_to_site()
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-crypt.php';
$test_log=new WPvivid_Log();
$test_log->CreateLogFile('test_backup','no_folder','transfer');
$test_log->WriteLog('test upload.','notice');
try
{
if(isset($_POST['wpvivid_content']))
{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log=new WPvivid_Log();
$default=array();
$option=get_option('wpvivid_api_token',$default);
if(empty($option))
{
die();
}
if($option['expires'] !=0 && $option['expires']<time())
{
die();
}
$crypt=new WPvivid_crypt(base64_decode($option['private_key']));
$body=base64_decode($_POST['wpvivid_content']);
$data=$crypt->decrypt_message($body);
if (!is_string($data))
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The key is invalid.';
echo wp_json_encode($ret);
die();
}
$params=json_decode($data,1);
if(is_null($params))
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The key is invalid.';
echo wp_json_encode($ret);
die();
}
$wpvivid_plugin->wpvivid_log->OpenLogFile($params['backup_id'].'_backup','no_folder','backup');
$wpvivid_plugin->wpvivid_log->WriteLog('start upload.','notice');
$dir=WPvivid_Setting::get_backupdir();
$file_path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.str_replace('wpvivid','wpvivid_temp',$params['name']);
if(!file_exists($file_path))
{
$handle=fopen($file_path,'w');
fclose($handle);
}
$handle=fopen($file_path,'rb+');
$offset=$params['offset'];
$wpvivid_plugin->wpvivid_log->WriteLog('Write file:'.$file_path.' offset:'.size_format($offset),'notice');
if($offset)
{
if(fseek($handle, $offset)===-1)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Seek file offset failed:'.size_format($offset),'notice');
}
}
if (fwrite($handle,base64_decode($params['data'])) === FALSE)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Write file :'.$file_path.' failed size:'.filesize($file_path),'notice');
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Write file:'.$file_path.' success size:'.filesize($file_path),'notice');
}
fclose($handle);
if(filesize($file_path)>=$params['file_size'])
{
if (md5_file($file_path) == $params['md5'])
{
$wpvivid_plugin->wpvivid_log->WriteLog('rename temp file:'.$file_path.' to new name:'.WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.$params['name'],'notice');
rename($file_path,WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR.$params['name']);
$ret['result']=WPVIVID_SUCCESS;
$ret['op']='finished';
} else {
$wpvivid_plugin->wpvivid_log->WriteLog('file md5 not match','notice');
$ret['result']=WPVIVID_FAILED;
$ret['error']='File md5 is not matched.';
}
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('continue size:'.filesize($file_path).' size1:'.$params['file_size'],'notice');
$ret['result']=WPVIVID_SUCCESS;
$ret['op']='continue';
//
}
echo wp_json_encode($ret);
}
}
catch (Exception $e)
{
$ret['result']=WPVIVID_FAILED;
$ret['error']=$e->getMessage();
//$wpvivid_plugin->wpvivid_log->WriteLog($e->getMessage(),'error');
echo wp_json_encode($ret);
die();
}
die();
}
public function send_to_site_finish()
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-crypt.php';
try {
if (isset($_POST['wpvivid_content'])) {
$default = array();
$option = get_option('wpvivid_api_token', $default);
if (empty($option)) {
die();
}
if ($option['expires'] != 0 && $option['expires'] < time()) {
die();
}
$crypt = new WPvivid_crypt(base64_decode($option['private_key']));
$body = base64_decode($_POST['wpvivid_content']);
$data = $crypt->decrypt_message($body);
if (!is_string($data)) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'The key is invalid.';
echo wp_json_encode($ret);
die();
}
$params = json_decode($data, 1);
if (is_null($params)) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'The key is invalid.';
echo wp_json_encode($ret);
die();
}
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log = new WPvivid_Log();
$wpvivid_plugin->wpvivid_log->OpenLogFile($params['backup_id'] . '_backup', 'no_folder', 'backup');
$wpvivid_plugin->wpvivid_log->WriteLog('upload finished', 'notice');
if (isset($params['backup']) && isset($params['backup_id']))
{
$list = WPvivid_Setting::get_option('wpvivid_backup_list');
$backup_data = $this->get_backup_data_by_task($params['backup']);
$list[$params['backup_id']] = $backup_data;
WPvivid_Setting::update_option('wpvivid_backup_list', $list);
}
$ret['result'] = WPVIVID_SUCCESS;
echo wp_json_encode($ret);
}
}
catch (Exception $e) {
$ret['result']=WPVIVID_FAILED;
$ret['error']=$e->getMessage();
echo wp_json_encode($ret);
die();
}
die();
}
public function get_backup_data_by_task($task)
{
global $wpvivid_plugin;
$backup_data=array();
$backup_data['type']='Migration';
$backup_data['create_time']=$task['status']['start_time'];
$backup_data['manual_delete']=0;
$backup_data['local']['path']=WPvivid_Setting::get_backupdir();
$backup_data['compress']['compress_type']=$task['options']['backup_options']['compress']['compress_type'];
$backup_data['save_local']=$task['options']['save_local'];
$backup_data['log']=$wpvivid_plugin->wpvivid_log->log_file;
$backup_data['backup']=$this->get_backup_result_by_task($task);
$backup_data['remote']=array();
$backup_data['lock']=0;
$backup_data=apply_filters('wpvivid_get_backup_data_by_task',$backup_data,$task);
return $backup_data;
}
public function get_backup_result_by_task($task)
{
$ret['result']=WPVIVID_SUCCESS;
$ret['files']=array();
foreach ($task['options']['backup_options']['backup'] as $backup_data)
{
if($task['options']['backup_options']['ismerge']==1)
{
if (!defined('WPVIVID_BACKUP_TYPE_MERGE'))
define('WPVIVID_BACKUP_TYPE_MERGE','backup_merge');
if(WPVIVID_BACKUP_TYPE_MERGE==$backup_data['key'])
{
$ret=$backup_data['result'];
if($ret['result']!==WPVIVID_SUCCESS)
{
return $ret;
}
}
}
else
{
$ret['files']=array_merge($ret['files'],$backup_data['result']['files']);
}
}
return $ret;
}
public function cleanup($files)
{
return array('result' => WPVIVID_SUCCESS);
}
public function download($file, $local_path, $callback = '')
{
return array('result' => WPVIVID_SUCCESS);
}
public function get_file_status($task_id,$file,$file_size,$md5)
{
$json=array();
$json['backup_id']=$task_id;
$json['name']=$file;
$json['file_size']=$file_size;
$json['md5']=$md5;
$json=wp_json_encode($json);
$crypt=new WPvivid_crypt(base64_decode($this->options['token']));
$data=$crypt->encrypt_message($json);
$data=base64_encode($data);
global $wp_version;
$args['user-agent'] ='WordPress/' . $wp_version . '; ' . get_bloginfo('url');
$args['body']=array('wpvivid_content'=>$data,'wpvivid_action'=>'send_to_site_file_status');
$args['timeout']=30;
$response=wp_remote_post($this->options['url'],$args);
if ( is_wp_error( $response ) )
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $response->get_error_message();
}
else
{
if($response['response']['code']==200)
{
global $wpvivid_plugin;
$res=json_decode($response['body'],1);
if($res!=null)
{
if($res['result']==WPVIVID_SUCCESS)
{
$ret['result']=WPVIVID_SUCCESS;
$ret['file_status']=$res['file_status'];
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $res['error'];
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'Failed to parse returned data, unable to retrieve file status of target site.';
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'Upload error '.$response['response']['code'].' '.$response['body'];
}
}
return $ret;
}
public function send_to_site_file_status()
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-crypt.php';
try {
if (isset($_POST['wpvivid_content'])) {
$default = array();
$option = get_option('wpvivid_api_token', $default);
if (empty($option)) {
die();
}
if ($option['expires'] != 0 && $option['expires'] < time()) {
die();
}
$crypt = new WPvivid_crypt(base64_decode($option['private_key']));
$body = base64_decode($_POST['wpvivid_content']);
$data = $crypt->decrypt_message($body);
if (!is_string($data)) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'The key is invalid.';
echo wp_json_encode($ret);
die();
}
$params = json_decode($data, 1);
if (is_null($params)) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'The key is invalid.';
echo wp_json_encode($ret);
die();
}
$dir = WPvivid_Setting::get_backupdir();
$file_path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . str_replace('wpvivid', 'wpvivid_temp', $params['name']);
$rename = true;
if (!file_exists($file_path))
{
$file_path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $params['name'];
$rename = false;
$offset=false;
}
else
{
$offset = filesize($file_path);
}
if (!$offset) {
$ret['result'] = WPVIVID_SUCCESS;
$ret['file_status']['status'] = 'start';
echo wp_json_encode($ret);
die();
}
if (filesize($file_path) >= $params['file_size']) {
if (md5_file($file_path) == $params['md5']) {
if ($rename)
rename($file_path, WP_CONTENT_DIR . DIRECTORY_SEPARATOR . $dir . DIRECTORY_SEPARATOR . $params['name']);
$ret['result'] = WPVIVID_SUCCESS;
$ret['file_status']['status'] = 'finished';
} else {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'File md5 is not matched.';
}
} else {
$ret['result'] = WPVIVID_SUCCESS;
$ret['file_status']['status'] = 'continue';
$ret['file_status']['offset'] = filesize($file_path);
}
echo wp_json_encode($ret);
}
}
catch (Exception $e) {
$ret['result']=WPVIVID_FAILED;
$ret['error']=$e->getMessage();
echo wp_json_encode($ret);
die();
}
die();
}
public function clear_backup_cache()
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-crypt.php';
try {
if (isset($_POST['wpvivid_content'])) {
$default = array();
$option = get_option('wpvivid_api_token', $default);
if (empty($option)) {
die();
}
if ($option['expires'] != 0 && $option['expires'] < time()) {
die();
}
$crypt = new WPvivid_crypt(base64_decode($option['private_key']));
$body = base64_decode($_POST['wpvivid_content']);
$data = $crypt->decrypt_message($body);
if (!is_string($data)) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'The key is invalid.';
echo wp_json_encode($ret);
die();
}
$params = json_decode($data, 1);
if (is_null($params)) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'The key is invalid.';
echo wp_json_encode($ret);
die();
}
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log = new WPvivid_Log();
$wpvivid_plugin->wpvivid_log->OpenLogFile($params['backup_id'] . '_backup', 'no_folder', 'backup');
$dir=WPvivid_Setting::get_backupdir();
$backup_path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir.DIRECTORY_SEPARATOR;
if(is_dir($backup_path))
{
$handler = opendir($backup_path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if (is_dir($backup_path . $filename))
{
continue;
}
else {
if (self::is_wpvivid_backup($filename))
{
if ($id =self::get_wpvivid_backup_id($filename))
{
$white_label_id = str_replace(apply_filters('wpvivid_white_label_file_prefix', 'wpvivid'), 'wpvivid', $id);
if(isset($params['backup_id']))
{
$clear_backup_id = sanitize_text_field($params['backup_id']);
if($id === $clear_backup_id || $white_label_id === $clear_backup_id)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Clear backup file: '.$backup_path.$filename, 'notice');
@wp_delete_file($backup_path.$filename);
}
}
}
}
}
}
}
if($handler)
@closedir($handler);
}
$ret['result'] = WPVIVID_SUCCESS;
}
else{
$ret['result']='failed';
$ret['error']='Failed to get local storage directory.';
}
echo wp_json_encode($ret);
}
}
catch (Exception $e) {
$ret['result']=WPVIVID_FAILED;
$ret['error']=$e->getMessage();
echo wp_json_encode($ret);
die();
}
die();
}
public static function is_wpvivid_backup($file_name)
{
if (preg_match('/wpvivid-.*_.*_.*\.zip$/', $file_name))
{
return true;
}
else {
return false;
}
}
public static function get_wpvivid_backup_id($file_name)
{
if (preg_match('/wpvivid-(.*?)_/', $file_name, $matches))
{
$id = $matches[0];
$id = substr($id, 0, strlen($id) - 1);
return $id;
}
else {
return false;
}
}
} includes/customclass/class-wpvivid-ftpclass.php 0000644 00000101377 15132770567 0016061 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
if(!defined('WPVIVID_REMOTE_FTP'))
define('WPVIVID_REMOTE_FTP','ftp');
require_once WPVIVID_PLUGIN_DIR .'/includes/customclass/class-wpvivid-remote.php';
class WPvivid_FTPClass extends WPvivid_Remote{
private $time_out = 20;
private $callback;
private $options=array();
public function __construct($options=array())
{
if(empty($options))
{
add_action('wpvivid_add_storage_tab',array($this,'wpvivid_add_storage_tab_ftp'), 15);
add_action('wpvivid_add_storage_page',array($this,'wpvivid_add_storage_page_ftp'), 15);
add_action('wpvivid_edit_remote_page',array($this,'wpvivid_edit_storage_page_ftp'), 15);
add_filter('wpvivid_remote_pic',array($this,'wpvivid_remote_pic_ftp'),9);
add_filter('wpvivid_get_out_of_date_remote',array($this,'wpvivid_get_out_of_date_ftp'),10,2);
add_filter('wpvivid_storage_provider_tran',array($this,'wpvivid_storage_provider_ftp'),10);
}else{
$this->options = $options;
}
}
public function wpvivid_add_storage_tab_ftp()
{
?>
<div class="storage-providers" remote_type="ftp" onclick="select_remote_storage(event, 'storage_account_ftp');">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/storage-ftp.png'); ?>" style="vertical-align:middle;"/><?php esc_html_e('FTP', 'wpvivid-backuprestore'); ?>
</div>
<?php
}
public function wpvivid_add_storage_page_ftp()
{
?>
<div id="storage_account_ftp" class="storage-account-page" style="display:none;">
<div style="padding: 0 10px 10px 0;"><strong><?php esc_html_e('Enter Your FTP Account', 'wpvivid-backuprestore'); ?></strong></div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" autocomplete="off" option="ftp" name="name" placeholder="<?php esc_attr_e('Enter an unique alias: e.g. FTP-001', 'wpvivid-backuprestore'); ?>" class="regular-text" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" autocomplete="off" option="ftp" name="server" placeholder="<?php esc_attr_e('FTP server (server\'s port 21)','wpvivid-backuprestore'); ?>" class="regular-text"/>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i style="margin-right: 10px;"><?php esc_html_e('Enter the FTP server.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" autocomplete="off" class="regular-text" value="21" readonly="readonly" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<a href="https://docs.wpvivid.com/wpvivid-backup-pro-ftp-change-ftp-default-port.html"><?php esc_html_e('Pro feature: Change the FTP default port number', 'wpvivid-backuprestore'); ?></a>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="ftp" name="username" placeholder="<?php esc_attr_e('FTP login', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter your FTP server user name.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="password" class="regular-text" autocomplete="new-password" option="ftp" name="password" placeholder="<?php esc_attr_e('FTP password', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the FTP server password.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" autocomplete="off" option="ftp" name="path" placeholder="<?php esc_attr_e('Absolute path must exist(e.g. /home/username)', 'wpvivid-backuprestore'); ?>" class="regular-text"/>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter an absolute path and a custom subdirectory (optional) for holding the backups of current website. For example, /home/username/customfolder', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="ftp" name="default" checked /><?php esc_html_e('Set as the default remote storage.', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Once checked, all this sites backups sent to a remote storage destination will be uploaded to this storage by default.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="ftp" name="passive" checked /><?php esc_html_e('Uncheck this to enable FTP active mode.', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Uncheck the option to use FTP active mode when transferring files. Make sure the FTP server you are configuring supports the active FTP mode.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" type="submit" option="add-remote" value="<?php esc_attr_e('Test and Add', 'wpvivid-backuprestore'); ?>">
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to connect to FTP server and add it to the storage list below.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<?php
}
public function wpvivid_edit_storage_page_ftp()
{
?>
<div id="remote_storage_edit_ftp" class="postbox storage-account-block remote-storage-edit" style="display:none;">
<div style="padding: 0 10px 10px 0;"><strong><?php esc_html_e('Enter Your FTP Account', 'wpvivid-backuprestore'); ?></strong></div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" autocomplete="off" option="edit-ftp" name="name" placeholder="<?php esc_attr_e('Enter an unique alias: e.g. FTP-001', 'wpvivid-backuprestore'); ?>" class="regular-text" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" autocomplete="off" option="edit-ftp" name="server" placeholder="<?php esc_attr_e('FTP server (server\'s port 21)', 'wpvivid-backuprestore'); ?>" class="regular-text"/>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i style="margin-right: 10px;"><?php esc_html_e('Enter the FTP server.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-ftp" name="username" placeholder="<?php esc_attr_e('FTP login', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter your FTP server user name.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="password" class="regular-text" autocomplete="new-password" option="edit-ftp" name="password" placeholder="<?php esc_attr_e('FTP password', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the FTP server password.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" autocomplete="off" option="edit-ftp" name="path" placeholder="<?php esc_attr_e('Absolute path must exist(e.g. /home/username)', 'wpvivid-backuprestore'); ?>" class="regular-text"/>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter an absolute path and a custom subdirectory (optional) for holding the backups of current website. For example, /home/username/customfolder', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="edit-ftp" name="passive" checked /><?php esc_html_e('Uncheck this to enable FTP active mode.', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Uncheck the option to use FTP active mode when transferring files. Make sure the FTP server you are configuring supports the active FTP mode.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" type="submit" option="edit-remote" value="<?php esc_attr_e('Save Changes', 'wpvivid-backuprestore'); ?>">
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to save the changes.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<?php
}
public function wpvivid_remote_pic_ftp($remote){
$remote['ftp']['default_pic'] = '/admin/partials/images/storage-ftp(gray).png';
$remote['ftp']['selected_pic'] = '/admin/partials/images/storage-ftp.png';
$remote['ftp']['title'] = 'FTP';
return $remote;
}
public function test_connect()
{
$passive =$this->options['passive'];
$host = $this->options['host'];
$username = $this->options['username'];
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1){
$password = base64_decode($this->options['password']);
}
else {
$password = $this->options['password'];
}
$path = $this->options['path'];
$port = empty($this->options['port'])?21:$this->options['port'];
$conn = $this -> do_connect($host,$username,$password,$port);
if(is_array($conn) && array_key_exists('result',$conn))
return $conn;
ftp_pasv($conn,$passive);
return $this->do_chdir($conn,$path);
}
public function sanitize_options($skip_name='')
{
$ret['result']=WPVIVID_FAILED;
if(!isset($this->options['name']))
{
$ret['error']=__('Warning: An alias for remote storage is required.','wpvivid-backuprestore');
return $ret;
}
$this->options['name']=sanitize_text_field($this->options['name']);
if(empty($this->options['name']))
{
$ret['error']=__('Warning: An alias for remote storage is required.','wpvivid-backuprestore');
return $ret;
}
$remoteslist=WPvivid_Setting::get_all_remote_options();
foreach ($remoteslist as $key=>$value)
{
if(isset($value['name'])&&$value['name'] == $this->options['name']&&$skip_name!=$value['name'])
{
$ret['error']="Warning: The alias already exists in storage list.";
return $ret;
}
}
$this->options['server']=sanitize_text_field($this->options['server']);
if(empty($this->options['server']))
{
$ret['error']="Warning: The FTP server is required.";
return $ret;
}
$res = explode(':',$this -> options['server']);
if(sizeof($res) > 1){
$this ->options['host'] = $res[0];
if($res[1] != 21){
$ret['error']='Currently, only port 21 is supported.';
return $ret;
}
}else{
$this -> options['host'] = $res[0];
}
if(!isset($this->options['username']))
{
$ret['error']="Warning: The FTP login is required.";
return $ret;
}
$this->options['username']=sanitize_text_field($this->options['username']);
if(empty($this->options['username']))
{
$ret['error']="Warning: The FTP login is required.";
return $ret;
}
if(!isset($this->options['password'])||empty($this->options['password']))
{
$ret['error']="Warning: The FTP password is required.";
return $ret;
}
$this->options['password']=sanitize_text_field($this->options['password']);
if(empty($this->options['password']))
{
$ret['error']="Warning: The FTP password is required.";
return $ret;
}
$this->options['password'] = base64_encode($this->options['password']);
$this->options['is_encrypt'] = 1;
if(!isset($this->options['path'])||empty($this->options['path']))
{
$ret['error']="Warning: The storage path is required.";
return $ret;
}
$this->options['path']=sanitize_text_field($this->options['path']);
if(empty($this->options['path']))
{
$ret['error']="Warning: The storage path is required.";
return $ret;
}
if($this->options['path']=='/')
{
$ret['error']= __('Warning: Root directory is forbidden to set to \'/\'.', 'wpvivid-backuprestore');
return $ret;
}
$ret['result']=WPVIVID_SUCCESS;
$ret['options']=$this->options;
return $ret;
}
public function do_connect($server,$username,$password,$port = 21)
{
$conn = ftp_connect( $server, $port, $this ->time_out );
if($conn)
{
if(ftp_login($conn,$username,$password))
{
return $conn;
}
else
{
return array('result'=>WPVIVID_FAILED,'error'=>'Login failed. You have entered the incorrect credential(s). Please try again.');
}
}
else{
return array('result'=>WPVIVID_FAILED,'error'=>'Login failed. The connection has timed out. Please try again later.');
}
}
public function do_chdir($conn,$path){
@ftp_chdir($conn,'/');
if(!@ftp_chdir($conn,$path))
{
$parts = explode('/',$path);
foreach($parts as $part){
if($part !== '') {
if (!@ftp_chdir($conn, $part)) {
if (!ftp_mkdir($conn, $part)) {
return array('result' => WPVIVID_FAILED, 'error' => 'Failed to create a backup. Make sure you have sufficient privileges to perform the operation.');
}
if (!@ftp_chdir($conn, $part)) {
return array('result' => WPVIVID_FAILED, 'error' => 'Failed to create a backup. Make sure you have sufficient privileges to perform the operation.');
}
}
}
}
/*if ( ! ftp_mkdir( $conn, $path ) )
{
return array('result'=>WPVIVID_FAILED,'error'=>'Failed to create a backup. Make sure you have sufficient privileges to perform the operation.');
}
if (!@ftp_chdir($conn,$path))
{
return array('result'=>WPVIVID_FAILED,'error'=>'Failed to create a backup. Make sure you have sufficient privileges to perform the operation.');
}*/
}
$temp_file = md5(wp_rand());
$temp_path = trailingslashit(WP_CONTENT_DIR).WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.$temp_file;
file_put_contents($temp_path,print_r($temp_file,true));
if(! ftp_put($conn,trailingslashit($path).$temp_file,$temp_path,FTP_BINARY)){
return array('result'=>WPVIVID_FAILED,'error'=>'Failed to add FTP storage. It can be because the FTP folder permissions are insufficient, or calling PHP ftp_put function of your web server failed. Please make sure the folder has write permission and the ftp_put function works properly.');
}
@wp_delete_file($temp_path);
@ftp_delete($conn,trailingslashit($path).$temp_file);
return array('result'=>WPVIVID_SUCCESS);
}
public function upload($task_id,$files,$callback = '')
{
global $wpvivid_plugin;
$this -> callback = $callback;
$passive =$this->options['passive'];
$host = $this->options['host'];
$username = $this->options['username'];
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1){
$password = base64_decode($this->options['password']);
}
else {
$password = $this->options['password'];
}
$path = $this->options['path'];
$port = empty($this->options['port'])?21:$this->options['port'];
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_FTP);
if(empty($upload_job))
{
$job_data=array();
foreach ($files as $file)
{
if(!file_exists($file))
return array('result'=>WPVIVID_FAILED,'error'=>$file.' not found. The file might has been moved, renamed or deleted. Please back it up again.');
$file_data['size']=filesize($file);
$file_data['uploaded']=0;
$job_data[basename($file)]=$file_data;
}
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_FTP,WPVIVID_UPLOAD_UNDO,'Start uploading.',$job_data);
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_FTP);
}
$wpvivid_plugin->wpvivid_log->WriteLog('Connecting to server '.$host,'notice');
$conn = $this -> do_connect($host,$username,$password,$port);
if(is_array($conn) && array_key_exists('result',$conn))
return $conn;
ftp_pasv($conn,$passive);
$wpvivid_plugin->wpvivid_log->WriteLog('chdir '.$path,'notice');
$str = $this -> do_chdir($conn , $path);
if($str['result'] !== WPVIVID_SUCCESS)
return $str;
$flag = true;
$error = '';
foreach ($files as $key => $file)
{
if(is_array($upload_job['job_data']) && array_key_exists(basename($file),$upload_job['job_data']))
{
if($upload_job['job_data'][basename($file)]['uploaded']==1)
continue;
}
$this ->last_time = time();
$this -> last_size = 0;
$wpvivid_plugin->wpvivid_log->WriteLog('Start uploading '.basename($file),'notice');
$remote_file = trailingslashit($path).basename($file);
if(!file_exists($file))
return array('result'=>WPVIVID_FAILED,'error'=>$file.' not found. The file might has been moved, renamed or deleted. Please back it up again.');
$wpvivid_plugin->set_time_limit($task_id);
for($i =0;$i <WPVIVID_REMOTE_CONNECT_RETRY_TIMES;$i ++)
{
$this -> current_file_name = basename($file);
$this -> current_file_size = filesize($file);
$this -> last_time = time();
$this -> last_size = 0;
$local_handle = fopen($file,'rb');
if(!$local_handle)
{
return array('result'=>WPVIVID_FAILED,'error'=>'Failed to open '.$this->current_file_name.'.');
}
$status = ftp_nb_fput($conn,$remote_file,$local_handle,FTP_BINARY,0);
while ($status == FTP_MOREDATA)
{
$status = ftp_nb_continue($conn);
if((time() - $this -> last_time) >3)
{
if(is_callable($callback)){
call_user_func_array($callback,array(ftell($local_handle),$this -> current_file_name,
$this->current_file_size,$this -> last_time,$this -> last_size));
}
$this -> last_size = ftell($local_handle);
$this -> last_time = time();
}
}
if ($status != FTP_FINISHED)
{
return array('result'=>WPVIVID_FAILED,'error'=>'Uploading '.$remote_file.' to FTP server failed. '.$remote_file.' might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.');
}
if($status == FTP_FINISHED)
{
WPvivid_taskmanager::wpvivid_reset_backup_retry_times($task_id);
$wpvivid_plugin->wpvivid_log->WriteLog('Finished uploading '.basename($file),'notice');
$upload_job['job_data'][basename($file)]['uploaded']=1;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_FTP,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file).' completed.',$upload_job['job_data']);
break;
}
if($status != FTP_FINISHED && $i == (WPVIVID_REMOTE_CONNECT_RETRY_TIMES - 1))
{
$flag = false;
$error = 'Uploading '.basename($file).' to FTP server failed. '.basename($file).' might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.';
break 2;
}
sleep(WPVIVID_REMOTE_CONNECT_RETRY_INTERVAL);
}
}
if($flag){
return array('result'=>WPVIVID_SUCCESS);
}else{
return array('result'=>WPVIVID_FAILED,'error'=>$error);
}
}
public function download($file,$local_path,$callback = '')
{
try {
global $wpvivid_plugin;
$passive = $this->options['passive'];
$host = $this->options['host'];
$username = $this->options['username'];
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1){
$password = base64_decode($this->options['password']);
}
else {
$password = $this->options['password'];
}
$path = $this->options['path'];
$port = empty($this->options['port']) ? 21 : $this->options['port'];
$local_path = trailingslashit($local_path) . $file['file_name'];
$remote_file = trailingslashit($path) . $file['file_name'];
$this->current_file_name = $file['file_name'];
$this->current_file_size = $file['size'];
$wpvivid_plugin->wpvivid_download_log->WriteLog('Connecting FTP server.','notice');
$conn = $this->do_connect($host, $username, $password, $port);
if (is_array($conn) && array_key_exists('result', $conn)) {
return $conn;
}
ftp_pasv($conn, $passive);
$wpvivid_plugin->wpvivid_download_log->WriteLog('Create local file.','notice');
$local_handle = fopen($local_path, 'ab');
if (!$local_handle) {
return array('result' => WPVIVID_FAILED, 'error' => 'Unable to create the local file. Please make sure the folder is writable and try again.');
}
$stat = fstat($local_handle);
$offset = $stat['size'];
$wpvivid_plugin->wpvivid_download_log->WriteLog('Downloading file ' . $file['file_name'] . ', Size: ' . $file['size'] ,'notice');
$status = ftp_nb_fget($conn, $local_handle, $remote_file, FTP_BINARY, $offset);
while ($status == FTP_MOREDATA) {
$status = ftp_nb_continue($conn);
if ((time() - $this->last_time) > 3) {
if (is_callable($callback)) {
call_user_func_array($callback, array(ftell($local_handle), $this->current_file_name,
$this->current_file_size, $this->last_time, $this->last_size));
}
$this->last_size = ftell($local_handle);
$this->last_time = time();
}
}
if(filesize($local_path) == $file['size']){
if($wpvivid_plugin->wpvivid_check_zip_valid()) {
$res = TRUE;
}
else{
$res = FALSE;
}
}
else{
$res = FALSE;
}
if ($status != FTP_FINISHED || $res !== TRUE) {
@wp_delete_file($local_path);
return array('result' => WPVIVID_FAILED, 'error' => 'Downloading ' . $remote_file . ' failed. ' . $remote_file . ' might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.');
}
ftp_close($conn);
fclose($local_handle);
return array('result' => WPVIVID_SUCCESS);
}
catch (Exception $error){
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('result'=>WPVIVID_FAILED, 'error'=>$message);
}
}
public function cleanup($file){
$host = $this->options['host'];
$username = $this->options['username'];
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1){
$password = base64_decode($this->options['password']);
}
else {
$password = $this->options['password'];
}
$path = $this->options['path'];
$port = empty($this->options['port'])?21:$this->options['port'];
$conn = $this -> do_connect($host,$username,$password,$port);
if(is_array($conn) && array_key_exists('result',$conn))
return $conn;
foreach ($file as $value){
@ftp_delete($conn,trailingslashit($path).$value);
}
return array('result'=>WPVIVID_SUCCESS);
}
public function init_remotes($remote_collection){
$remote_collection[WPVIVID_REMOTE_FTP] = 'WPvivid_FTPClass';
return $remote_collection;
}
public function wpvivid_get_out_of_date_ftp($out_of_date_remote, $remote)
{
if($remote['type'] == WPVIVID_REMOTE_FTP){
$out_of_date_remote = $remote['path'];
}
return $out_of_date_remote;
}
public function wpvivid_storage_provider_ftp($storage_type)
{
if($storage_type == WPVIVID_REMOTE_FTP){
$storage_type = 'FTP';
}
return $storage_type;
}
} includes/customclass/class-wpvivid-dropbox.php 0000644 00000126303 15132770567 0015713 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
if(!defined('WPVIVID_REMOTE_DROPBOX')){
define('WPVIVID_REMOTE_DROPBOX','dropbox');
}
if(!defined('WPVIVID_DROPBOX_DEFAULT_FOLDER'))
define('WPVIVID_DROPBOX_DEFAULT_FOLDER','/');
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-base-dropbox.php';
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-remote.php';
class WPvivid_Dropbox extends WPvivid_Remote
{
private $options;
private $upload_chunk_size = 2097152;
private $download_chunk_size = 2097152;
private $redirect_url = 'https://auth.wpvivid.com/dropbox_v3/';
public $add_remote;
public function __construct($options = array())
{
if(empty($options))
{
if(!defined('WPVIVID_INIT_STORAGE_TAB_DROPBOX'))
{
add_action('init', array($this, 'handle_auth_actions'));
//wpvivid_dropbox_add_remote
add_action('wp_ajax_wpvivid_dropbox_add_remote',array( $this,'finish_add_remote'));
add_action('wpvivid_delete_remote_token',array($this,'revoke'));
add_filter('wpvivid_remote_register', array($this, 'init_remotes'),10);
add_action('wpvivid_add_storage_tab',array($this,'wpvivid_add_storage_tab_dropbox'), 11);
add_action('wpvivid_add_storage_page',array($this,'wpvivid_add_storage_page_dropbox'), 11);
add_action('wpvivid_edit_remote_page',array($this,'wpvivid_edit_storage_page_dropbox'), 11);
add_filter('wpvivid_remote_pic',array($this,'wpvivid_remote_pic_dropbox'),10);
add_filter('wpvivid_get_out_of_date_remote',array($this,'wpvivid_get_out_of_date_dropbox'),10,2);
add_filter('wpvivid_storage_provider_tran',array($this,'wpvivid_storage_provider_dropbox'),10);
add_filter('wpvivid_get_root_path',array($this,'wpvivid_get_root_path_dropbox'),10);
add_filter('wpvivid_pre_add_remote',array($this, 'pre_add_remote'),10,2);
define('WPVIVID_INIT_STORAGE_TAB_DROPBOX',1);
}
}else{
$this -> options = $options;
}
$this->add_remote=false;
}
public function pre_add_remote($remote,$id)
{
if($remote['type']==WPVIVID_REMOTE_DROPBOX)
{
$remote['id']=$id;
}
return $remote;
}
public function test_connect()
{
return array('result' => WPVIVID_SUCCESS);
}
public function sanitize_options($skip_name='')
{
$ret['result']=WPVIVID_SUCCESS;
if(!isset($this->options['name']))
{
$ret['error']="Warning: An alias for remote storage is required.";
return $ret;
}
$this->options['name']=sanitize_text_field($this->options['name']);
if(empty($this->options['name']))
{
$ret['error']="Warning: An alias for remote storage is required.";
return $ret;
}
$remoteslist=WPvivid_Setting::get_all_remote_options();
foreach ($remoteslist as $key=>$value)
{
if(isset($value['name'])&&$value['name'] == $this->options['name']&&$skip_name!=$value['name'])
{
$ret['error']="Warning: The alias already exists in storage list.";
return $ret;
}
}
$ret['options']=$this->options;
return $ret;
}
public function upload($task_id, $files, $callback = '')
{
global $wpvivid_plugin;
$options = $this -> options;
$dropbox = new Dropbox_Base($options);
$ret=$dropbox->check_token();
if($ret['result']=='failed')
{
return $ret;
}
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_DROPBOX);
if(empty($upload_job))
{
$job_data=array();
foreach ($files as $file)
{
$file_data['size']=filesize($file);
$file_data['uploaded']=0;
$file_data['session_id']='';
$file_data['offset']=0;
$job_data[basename($file)]=$file_data;
}
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_DROPBOX,WPVIVID_UPLOAD_UNDO,'Start uploading',$job_data);
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_DROPBOX);
}
foreach ($files as $file)
{
if(is_array($upload_job['job_data']) &&array_key_exists(basename($file),$upload_job['job_data']))
{
if($upload_job['job_data'][basename($file)]['uploaded']==1)
continue;
}
$ret=$dropbox->check_token();
if($ret['result']=='failed')
{
return $ret;
}
$this -> last_time = time();
$this -> last_size = 0;
$wpvivid_plugin->wpvivid_log->WriteLog('Start uploading '.basename($file),'notice');
$wpvivid_plugin->set_time_limit($task_id);
if(!file_exists($file))
return array('result' =>WPVIVID_FAILED,'error' =>$file.' not found. The file might has been moved, renamed or deleted. Please reload the list and verify the file exists.');
$result = $this -> _put($task_id,$dropbox,$file,$callback);
if($result['result'] !==WPVIVID_SUCCESS){
$wpvivid_plugin->wpvivid_log->WriteLog('Uploading '.basename($file).' failed.','notice');
return $result;
}
else
{
WPvivid_taskmanager::wpvivid_reset_backup_retry_times($task_id);
}
$wpvivid_plugin->wpvivid_log->WriteLog('Finished uploading '.basename($file),'notice');
$upload_job['job_data'][basename($file)]['uploaded'] = 1;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id, 'upload', WPVIVID_REMOTE_DROPBOX, WPVIVID_UPLOAD_SUCCESS, 'Uploading ' . basename($file) . ' completed.', $upload_job['job_data']);
}
return array('result' =>WPVIVID_SUCCESS);
}
private function _put($task_id,$dropbox,$file,$callback){
global $wpvivid_plugin;
$options = $this -> options;
$path = trailingslashit($options['path']).basename($file);
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_DROPBOX);
$this -> current_file_size = filesize($file);
$this -> current_file_name = basename($file);
if($this -> current_file_size > $this -> upload_chunk_size)
{
if(empty($upload_job['job_data'][basename($file)]['session_id']))
{
$wpvivid_plugin->wpvivid_log->WriteLog('Creating upload session.','notice');
//WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_DROPBOX,WPVIVID_UPLOAD_UNDO,'Start uploading '.basename($file).'.',$upload_job['job_data']);
$result = $dropbox -> upload_session_start();
if(isset($result['error_summary']))
{
return array('result'=>WPVIVID_FAILED,'error'=>$result['error_summary']);
}
$upload_job['job_data'][basename($file)]['session_id']= $result['session_id'];
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_DROPBOX,WPVIVID_UPLOAD_UNDO,'Start uploading '.basename($file).'.',$upload_job['job_data']);
$build_id = $result['session_id'];
}
else
{
$build_id = $upload_job['job_data'][basename($file)]['session_id'];
}
$result = $this -> large_file_upload($task_id,$build_id,$file,$dropbox,$callback);
}else{
$wpvivid_plugin->wpvivid_log->WriteLog('Uploaded files are less than 2M.','notice');
$result = $dropbox -> upload($path,$file);
if(isset($result['error_summary'])){
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_DROPBOX,WPVIVID_UPLOAD_FAILED,'Uploading '.basename($file).' failed.',$upload_job['job_data']);
$result = array('result' => WPVIVID_FAILED,'error' => $result['error_summary']);
}else{
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_DROPBOX,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file).' completed.',$upload_job['job_data']);
$result = array('result'=> WPVIVID_SUCCESS);
}
}
return $result;
}
public function large_file_upload($task_id,$session_id,$file,$dropbox,$callback)
{
global $wpvivid_plugin;
$fh = fopen($file,'rb');
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_DROPBOX);
$offset = $upload_job['job_data'][basename($file)]['offset'];
$wpvivid_plugin->wpvivid_log->WriteLog('offset:'.size_format($offset,2),'notice');
if ($offset > 0)
{
fseek($fh, $offset);
}
while($data =fread($fh,$this -> upload_chunk_size))
{
$ret = $this -> _upload_loop($session_id,$offset,$data,$dropbox);
if($ret['result'] !== WPVIVID_SUCCESS)
{
return $ret;
}
if((time() - $this -> last_time) >3)
{
if(is_callable($callback))
{
call_user_func_array($callback,array(min($offset + $this -> upload_chunk_size,$this -> current_file_size),$this -> current_file_name,
$this->current_file_size,$this -> last_time,$this -> last_size));
}
$this -> last_size = $offset;
$this -> last_time = time();
}
if(isset($ret['correct_offset']))
{
$offset = $ret['correct_offset'];
fseek($fh, $offset);
$wpvivid_plugin->wpvivid_log->WriteLog('correct_offset:'.size_format($offset,2),'notice');
}
else
{
$offset = ftell($fh);
}
$upload_job['job_data'][basename($file)]['offset']=$offset;
$wpvivid_plugin->wpvivid_log->WriteLog('offset:'.size_format($offset,2),'notice');
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_DROPBOX,WPVIVID_UPLOAD_UNDO,'Uploading '.basename($file),$upload_job['job_data']);
}
$options = $this -> options;
$path = trailingslashit($options['path']).basename($file);
$result = $dropbox -> upload_session_finish($session_id,$offset,$path);
if(isset($result['error_summary']))
{
$wpvivid_plugin->wpvivid_log->WriteLog('offset:'.$offset,'notice');
$wpvivid_plugin->wpvivid_log->WriteLog('result:'.wp_json_encode($result),'notice');
$ret = array('result' => WPVIVID_FAILED,'error' => $result['error_summary']);
}else{
$ret = array('result'=> WPVIVID_SUCCESS);
}
fclose($fh);
return $ret;
}
public function _upload_loop($session_id,$offset,$data,$dropbox)
{
$result['result']=WPVIVID_SUCCESS;
for($i =0;$i <WPVIVID_REMOTE_CONNECT_RETRY_TIMES; $i ++)
{
$result = $dropbox -> upload_session_append_v2($session_id,$offset,$data);
if(isset($result['error_summary']))
{
if(strstr($result['error_summary'],'incorrect_offset'))
{
$result['result']=WPVIVID_SUCCESS;
$result['correct_offset']=$result['error']['correct_offset'];
return $result;
}
else
{
$result = array('result' => WPVIVID_FAILED,'error' => 'Uploading '.$this -> current_file_name.' to Dropbox server failed. '.$result['error_summary']);
}
}
else
{
return array('result' => WPVIVID_SUCCESS);
}
}
return $result;
}
public function download($file, $local_path, $callback = '')
{
try {
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_download_log->WriteLog('Remote type: Dropbox.','notice');
$this->current_file_name = $file['file_name'];
$this->current_file_size = $file['size'];
$options = $this->options;
$dropbox = new Dropbox_Base($options);
$ret=$dropbox->check_token();
if($ret['result']=='failed')
{
return $ret;
}
$file_path = trailingslashit($local_path) . $this->current_file_name;
$start_offset = file_exists($file_path) ? filesize($file_path) : 0;
$wpvivid_plugin->wpvivid_download_log->WriteLog('Create local file.','notice');
$fh = fopen($file_path, 'a');
$wpvivid_plugin->wpvivid_download_log->WriteLog('Downloading file ' . $file['file_name'] . ', Size: ' . $file['size'] ,'notice');
while ($start_offset < $this->current_file_size) {
$last_byte = min($start_offset + $this->download_chunk_size - 1, $this->current_file_size - 1);
$headers = array("Range: bytes=$start_offset-$last_byte");
$response = $dropbox->download(trailingslashit($options['path']) . $this->current_file_name, $headers);
if (isset($response['error_summary'])) {
return array('result' => WPVIVID_FAILED, 'error' => 'Downloading ' . trailingslashit($options['path']) . $this->current_file_name . ' failed.' . $response['error_summary']);
}
if (!fwrite($fh, $response)) {
return array('result' => WPVIVID_FAILED, 'error' => 'Downloading ' . trailingslashit($options['path']) . $this->current_file_name . ' failed.');
}
clearstatcache();
$state = stat($file_path);
$start_offset = $state['size'];
if ((time() - $this->last_time) > 3) {
if (is_callable($callback)) {
call_user_func_array($callback, array($start_offset, $this->current_file_name,
$this->current_file_size, $this->last_time, $this->last_size));
}
$this->last_size = $start_offset;
$this->last_time = time();
}
}
@fclose($fh);
if(filesize($file_path) == $file['size']){
if($wpvivid_plugin->wpvivid_check_zip_valid()) {
$res = TRUE;
}
else{
$res = FALSE;
}
}
else{
$res = FALSE;
}
if ($res !== TRUE) {
@wp_delete_file($file_path);
return array('result' => WPVIVID_FAILED, 'error' => 'Downloading ' . $file['file_name'] . ' failed. ' . $file['file_name'] . ' might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.');
}
return array('result' => WPVIVID_SUCCESS);
}
catch (Exception $error){
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('result'=>WPVIVID_FAILED, 'error'=>$message);
}
}
public function cleanup($files)
{
$options = $this -> options;
$dropbox = new Dropbox_Base($options);
$ret=$dropbox->check_token();
if($ret['result']=='failed')
{
return $ret;
}
foreach ($files as $file){
$dropbox -> delete(trailingslashit($options['path']).$file);
}
return array('result'=>WPVIVID_SUCCESS);
}
public function init_remotes($remote_collection){
$remote_collection[WPVIVID_REMOTE_DROPBOX] = 'WPvivid_Dropbox';
return $remote_collection;
}
public function handle_auth_actions()
{
if(isset($_GET['action']) && isset($_GET['page']))
{
if($_GET['page'] === 'WPvivid')
{
if($_GET['action'] === 'wpvivid_dropbox_auth')
{
$check=current_user_can('manage_options');
if(!$check)
{
return;
}
try {
$rand_id = substr(md5(time().rand()), 0,13);
$auth_id = 'wpvivid-auth-'.$rand_id;
$state = admin_url() . 'admin.php?page=WPvivid' . '&action=wpvivid_dropbox_finish_auth&main_tab=storage&sub_tab=dropbox&sub_page=storage_account_dropbox&auth_id='.$auth_id;
$remote_options['auth_id']=$auth_id;
set_transient('dropbox_auth_id', $remote_options, 900);
$url = Dropbox_Base::getUrl($this->redirect_url, $state);
header('Location: ' . filter_var($url, FILTER_SANITIZE_URL));
}
catch (Exception $e){
echo '<div class="notice notice-error"><p>'.esc_html($e->getMessage()).'</p></div>';
}
}
else if($_GET['action'] === 'wpvivid_dropbox_finish_auth')
{
$tmp_options = get_transient('dropbox_auth_id');
if($tmp_options === false)
{
return;
}
else if($tmp_options['auth_id'] !== $_GET['auth_id'])
{
delete_transient('dropbox_auth_id');
return;
}
try {
$remoteslist = WPvivid_Setting::get_all_remote_options();
foreach ($remoteslist as $key => $value)
{
if (isset($value['auth_id']) && isset($_GET['auth_id']) && $value['auth_id'] == sanitize_text_field($_GET['auth_id']))
{
echo '<div class="notice notice-success is-dismissible"><p>';
esc_html_e('You have authenticated the Dropbox account as your remote storage.', 'wpvivid-backuprestore');
echo '</p></div>';
return;
}
}
if(empty($_POST['code']))
{
if(empty($tmp_options['access_token']))
{
header('Location: ' . admin_url() . 'admin.php?page=' . WPVIVID_PLUGIN_SLUG . '&action=wpvivid_dropbox_drive&result=error&resp_msg=' . 'Get Dropbox token failed.');
return;
}
}
else
{
$tmp_options['type'] = WPVIVID_REMOTE_DROPBOX;
$tmp_options['access_token']= base64_encode(sanitize_text_field($_POST['code']));
$tmp_options['expires_in'] = sanitize_text_field($_POST['expires_in']);
$tmp_options['refresh_token'] = base64_encode(sanitize_text_field($_POST['refresh_token']));
$tmp_options['is_encrypt'] = 1;
set_transient('dropbox_auth_id', $tmp_options, 900);
}
$this->add_remote=true;
}
catch (Exception $e){
echo '<div class="notice notice-error"><p>'.esc_html($e->getMessage()).'</p></div>';
}
}
else if($_GET['action']=='wpvivid_dropbox_drive')
{
try {
if (isset($_GET['result'])) {
if ($_GET['result'] == 'success') {
add_action('show_notice', array($this, 'wpvivid_show_notice_add_dropbox_success'));
} else if ($_GET['result'] == 'error') {
add_action('show_notice', array($this, 'wpvivid_show_notice_add_dropbox_error'));
}
}
}
catch (Exception $e){
echo '<div class="notice notice-error"><p>'.esc_html($e->getMessage()).'</p></div>';
}
}
}
}
}
public function wpvivid_show_notice_add_dropbox_success(){
echo '<div class="notice notice-success is-dismissible"><p>';
esc_html_e('You have authenticated the Dropbox account as your remote storage.', 'wpvivid-backuprestore');
echo '</p></div>';
}
public function wpvivid_show_notice_add_dropbox_error(){
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_handle_remote_storage_error($_GET['resp_msg'], 'Add Dropbox Remote');
echo '<div class="notice notice-error"><p>'.esc_html($_GET['resp_msg']).'</p></div>';
}
public function wpvivid_add_storage_tab_dropbox(){
?>
<div class="storage-providers" remote_type="dropbox" onclick="select_remote_storage(event, 'storage_account_dropbox');">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/storage-dropbox.png'); ?>" style="vertical-align:middle;"/><?php esc_html_e('Dropbox', 'wpvivid-backuprestore'); ?>
</div>
<?php
}
public function wpvivid_add_storage_page_dropbox(){
global $wpvivid_plugin;
$root_path=apply_filters('wpvivid_get_root_path', WPVIVID_REMOTE_DROPBOX);
$remote = get_option('wpvivid_upload_setting');
if($this->add_remote)
{
?>
<div id="storage_account_dropbox" class="storage-account-page" style="display:none;">
<div style="background-color:#f1f1f1; padding: 10px;">
Please read<a target="_blank" href="https://wpvivid.com/privacy-policy" style="text-decoration: none;">this privacy policy</a> for use of our Dropbox authorization app (none of your backup data is sent to us).
</div>
<div style="color:#8bc34a; padding: 10px 10px 10px 0;">
<strong><?php esc_html_e('Authentication is done, please continue to enter the storage information, then click \'Add Now\' button to save it.', 'wpvivid-backuprestore'); ?></strong>
</div>
<div style="padding: 10px 10px 10px 0;">
<strong><?php esc_html_e('Enter Your Dropbox Information', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="dropbox" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. Dropbox-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="dropbox" name="path" value="<?php echo esc_attr($root_path.WPVIVID_DROPBOX_DEFAULT_FOLDER); ?>" readonly="readonly" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('All backups will be uploaded to this directory.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" value="mywebsite01" readonly="readonly" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<a href="https://docs.wpvivid.com/wpvivid-backup-pro-dropbox-custom-folder-name.html"><?php esc_html_e('Pro feature: Create a directory for storing the backups of the site', 'wpvivid-backuprestore'); ?></a>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="dropbox" name="default" checked /><?php esc_html_e('Set as the default remote storage.', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Once checked, all this sites backups sent to a remote storage destination will be uploaded to this storage by default.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input id="wpvivid_dropbox_auth" class="button-primary" type="submit" value="<?php esc_attr_e('Add Now', 'wpvivid-backuprestore'); ?>">
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to add the storage.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script>
function wpvivid_check_dropbox_storage_alias(storage_alias)
{
var find = 1;
jQuery('#wpvivid_remote_storage_list tr').each(function (i) {
jQuery(this).children('td').each(function (j) {
if (j == 3) {
if (jQuery(this).text() == storage_alias) {
find = -1;
return false;
}
}
});
});
return find;
}
jQuery('#wpvivid_dropbox_auth').click(function()
{
wpvivid_dropbox_auth();
});
function wpvivid_dropbox_auth()
{
wpvivid_settings_changed = false;
var name='';
var path = '';
var bdefault = '0';
jQuery("input:checkbox[option=dropbox]").each(function(){
var key = jQuery(this).prop('name');
if(jQuery(this).prop('checked')) {
bdefault = '1';
}
else {
bdefault = '0';
}
});
jQuery('input:text[option=dropbox]').each(function()
{
var type = jQuery(this).prop('name');
if(type == 'name'){
name = jQuery(this).val();
}
});
if(name == ''){
alert(wpvividlion.remotealias);
}
else if(wpvivid_check_dropbox_storage_alias(name) === -1){
alert(wpvividlion.remoteexist);
}
else{
var ajax_data;
var remote_from = wpvivid_ajax_data_transfer('dropbox');
ajax_data = {
'action': 'wpvivid_dropbox_add_remote',
'remote': remote_from
};
jQuery('#wpvivid_dropbox_auth').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#wpvivid_remote_notice').html('');
wpvivid_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_dropbox_auth').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('input:text[option=dropbox]').each(function(){
jQuery(this).val('');
});
jQuery('input:password[option=dropbox]').each(function(){
jQuery(this).val('');
});
wpvivid_handle_remote_storage_data(data);
location.href='admin.php?page=WPvivid&action=wpvivid_dropbox_drive&main_tab=storage&sub_tab=dropbox&sub_page=storage_account_dropbox&result=success';
}
else if (jsonarray.result === 'failed')
{
jQuery('#wpvivid_remote_notice').html(jsonarray.notice);
jQuery('input[option=add-remote]').css({'pointer-events': 'auto', 'opacity': '1'});
}
}
catch (err)
{
alert(err);
jQuery('input[option=add-remote]').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('adding the remote storage', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_dropbox_auth').css({'pointer-events': 'auto', 'opacity': '1'});
});
}
}
</script>
<?php
}
else
{
?>
<div id="storage_account_dropbox" class="storage-account-page" style="display:none;">
<div style="background-color:#f1f1f1; padding: 10px;">
Please read <a target="_blank" href="https://wpvivid.com/privacy-policy" style="text-decoration: none;">this privacy policy</a> for use of our Dropbox authorization app (none of your backup data is sent to us).
</div>
<div style="padding: 10px 10px 10px 0;">
<strong><?php esc_html_e('To add Dropbox, please get Dropbox authentication first. Once authenticated, you will be redirected to this page, then you can add storage information and save it.', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input onclick="wpvivid_dropbox_auth();" class="button-primary" type="submit" value="<?php esc_attr_e('Authenticate with Dropbox', 'wpvivid-backuprestore'); ?>">
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click to get Dropbox authentication.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
<div style="padding: 10px 0 0 0;">
<span>Tip: Get a 404 or 403 error after authorization? Please read this <a href="https://docs.wpvivid.com/http-403-error-authorizing-cloud-storage.html">doc</a>.</span>
</div>
</div>
<script>
function wpvivid_dropbox_auth()
{
location.href ='<?php echo esc_url(admin_url()).'admin.php?page=WPvivid'.'&action=wpvivid_dropbox_auth'?>';
}
</script>
<?php
}
}
public function wpvivid_edit_storage_page_dropbox()
{
do_action('wpvivid_remote_storage_js');
?>
<div id="remote_storage_edit_dropbox" class="postbox storage-account-block remote-storage-edit" style="display:none;">
<div style="padding: 0 10px 10px 0;">
<strong><?php esc_html_e('To add Dropbox, please get Dropbox authentication first. Once authenticated, you will be redirected to this page, then you can add storage information and save it', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-dropbox" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. Dropbox-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" type="submit" option="edit-remote" value="<?php esc_attr_e('Save Changes', 'wpvivid-backuprestore'); ?>">
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to save the changes.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script>
function wpvivid_dropbox_update_auth()
{
var name='';
jQuery('input:text[option=edit-dropbox]').each(function()
{
var key = jQuery(this).prop('name');
if(key==='name')
{
name = jQuery(this).val();
}
});
if(name == ''){
alert(wpvividlion.remotealias);
}
else if(wpvivid_check_onedrive_storage_alias(name) === -1){
alert(wpvividlion.remoteexist);
}
else {
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page=WPvivid' . '&action=wpvivid_dropbox_update_auth&name='?>' + name + '&id=' + wpvivid_editing_storage_id;
}
}
</script>
<?php
}
public function wpvivid_remote_pic_dropbox($remote)
{
$remote['dropbox']['default_pic'] = '/admin/partials/images/storage-dropbox(gray).png';
$remote['dropbox']['selected_pic'] = '/admin/partials/images/storage-dropbox.png';
$remote['dropbox']['title'] = 'Dropbox';
return $remote;
}
public function revoke($id){
$upload_options = WPvivid_Setting::get_option('wpvivid_upload_setting');
if(array_key_exists($id,$upload_options) && $upload_options[$id] == WPVIVID_REMOTE_DROPBOX){
$dropbox = new Dropbox_Base($upload_options);
$dropbox -> revoke();
}
}
public function wpvivid_get_out_of_date_dropbox($out_of_date_remote, $remote)
{
if($remote['type'] == WPVIVID_REMOTE_DROPBOX){
$root_path=apply_filters('wpvivid_get_root_path', $remote['type']);
$out_of_date_remote = $root_path.$remote['path'];
}
return $out_of_date_remote;
}
public function wpvivid_storage_provider_dropbox($storage_type)
{
if($storage_type == WPVIVID_REMOTE_DROPBOX){
$storage_type = 'Dropbox';
}
return $storage_type;
}
public function wpvivid_get_root_path_dropbox($storage_type){
if($storage_type == WPVIVID_REMOTE_DROPBOX){
$storage_type = 'apps/Wpvivid backup restore';
}
return $storage_type;
}
public function finish_add_remote()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (empty($_POST) || !isset($_POST['remote']) || !is_string($_POST['remote'])) {
die();
}
$tmp_remote_options = get_transient('dropbox_auth_id');
if($tmp_remote_options === false)
{
die();
}
delete_transient('dropbox_auth_id');
if(empty($tmp_remote_options)||$tmp_remote_options['type']!==WPVIVID_REMOTE_DROPBOX)
{
die();
}
$json = sanitize_text_field($_POST['remote']);
$json = stripslashes($json);
$remote_options = json_decode($json, true);
if (is_null($remote_options)) {
die();
}
$remote_options['created']=time();
$remote_options['path'] = WPVIVID_DROPBOX_DEFAULT_FOLDER;
$remote_options=array_merge($remote_options,$tmp_remote_options);
if(!class_exists('WPvivid_Remote_collection'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-remote-collection.php';
$wpvivid_plugin->remote_collection=new WPvivid_Remote_collection();
}
$ret = $wpvivid_plugin->remote_collection->add_remote($remote_options);
if ($ret['result'] == 'success') {
$html = '';
$html = apply_filters('wpvivid_add_remote_storage_list', $html);
$ret['html'] = $html;
$pic = '';
$pic = apply_filters('wpvivid_schedule_add_remote_pic', $pic);
$ret['pic'] = $pic;
$dir = '';
$dir = apply_filters('wpvivid_get_remote_directory', $dir);
$ret['dir'] = $dir;
$schedule_local_remote = '';
$schedule_local_remote = apply_filters('wpvivid_schedule_local_remote', $schedule_local_remote);
$ret['local_remote'] = $schedule_local_remote;
$remote_storage = '';
$remote_storage = apply_filters('wpvivid_remote_storage', $remote_storage);
$ret['remote_storage'] = $remote_storage;
$remote_select_part = '';
$remote_select_part = apply_filters('wpvivid_remote_storage_select_part', $remote_select_part);
$ret['remote_select_part'] = $remote_select_part;
$default = array();
$remote_array = apply_filters('wpvivid_archieve_remote_array', $default);
$ret['remote_array'] = $remote_array;
$success_msg = __('You have successfully added a remote storage.', 'wpvivid-backuprestore');
$ret['notice'] = apply_filters('wpvivid_add_remote_notice', true, $success_msg);
}
else{
$ret['notice'] = apply_filters('wpvivid_add_remote_notice', false, $ret['error']);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
} includes/customclass/class-wpvivid-remote-default.php 0000644 00000002015 15132770567 0017144 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
if(!defined('WPVIVID_UPLOAD_SUCCESS'))
{
define('WPVIVID_UPLOAD_SUCCESS',1);
}
if(!defined('WPVIVID_UPLOAD_FAILED'))
{
define('WPVIVID_UPLOAD_FAILED',2);
}
if(!defined('WPVIVID_UPLOAD_UNDO'))
{
define('WPVIVID_UPLOAD_UNDO',0);
}
require_once WPVIVID_PLUGIN_DIR .'/includes/customclass/class-wpvivid-remote.php';
class WPvivid_Remote_Defult extends WPvivid_Remote{
public function test_connect()
{
return array('result' => WPVIVID_FAILED,'error'=> 'Type incorrect.');
}
public function upload($task_id, $files, $callback = '')
{
return array('result' => WPVIVID_FAILED,'error'=> 'Type incorrect.');
}
public function download( $file, $local_path, $callback = '')
{
return array('result' => WPVIVID_FAILED,'error'=> 'Type incorrect.');
}
public function cleanup($files)
{
return array('result' => WPVIVID_FAILED,'error'=> 'Type incorrect.');
}
} includes/customclass/class-wpvivid-amazons3-plus.php 0000644 00000116423 15132770567 0016754 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
if(!defined('WPVIVID_REMOTE_AMAZONS3'))
define('WPVIVID_REMOTE_AMAZONS3','amazons3');
if(!defined('WPVIVID_AMAZONS3_DEFAULT_FOLDER'))
define('WPVIVID_AMAZONS3_DEFAULT_FOLDER','/wpvivid_backup');
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-remote.php';
require_once 'class-wpvivid-base-s3.php';
class WPvivid_AMAZONS3Class extends WPvivid_Remote{
public $options;
public $bucket='';
private $upload_chunk_size = 5242880;
private $download_chunk_size = 5242880;
public $current_file_size;
public $current_file_name;
public function __construct($options=array())
{
if(empty($options))
{
add_action('wpvivid_add_storage_tab',array($this,'wpvivid_add_storage_tab_amazons3'), 13);
add_action('wpvivid_add_storage_page',array($this,'wpvivid_add_storage_page_amazons3'), 13);
add_action('wpvivid_edit_remote_page',array($this,'wpvivid_edit_storage_page_amazons3'), 13);
add_filter('wpvivid_remote_pic',array($this,'wpvivid_remote_pic_amazons3'),11);
add_filter('wpvivid_get_out_of_date_remote',array($this,'wpvivid_get_out_of_date_amazons3'),10,2);
add_filter('wpvivid_storage_provider_tran',array($this,'wpvivid_storage_provider_amazons3'),10);
}
else
{
$this->options=$options;
}
}
public function wpvivid_add_storage_tab_amazons3()
{
?>
<div class="storage-providers" remote_type="amazons3" onclick="select_remote_storage(event, 'storage_account_amazons3');">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/storage-amazon-s3.png'); ?>" style="vertical-align:middle;"/><?php esc_html_e('Amazon S3', 'wpvivid-backuprestore'); ?>
</div>
<?php
}
public function wpvivid_add_storage_page_amazons3()
{
if(!function_exists('simplexml_load_string')){
$need_extension = true;
$add_btn_style = 'pointer-events: none; opacity: 0.4;';
}
else{
$need_extension = false;
$add_btn_style = 'pointer-events: auto; opacity: 1;';
}
?>
<div id="storage_account_amazons3" class="storage-account-page" style="display:none;">
<div style="padding: 0 10px 10px 0;">
<strong><?php esc_html_e('Enter Your Amazon S3 Account', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="amazons3" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. Amazon S3-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="amazons3" name="access" placeholder="<?php esc_attr_e('Amazon S3 access key', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter your Amazon S3 access key.', 'wpvivid-backuprestore'); ?></i><a href="https://wpvivid.com/get-amazon-access-secret-key.html" target="_blank"> <?php esc_html_e('How to get an AmazonS3 access key.', 'wpvivid-backuprestore'); ?></a>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="password" class="regular-text" autocomplete="new-password" option="amazons3" name="secret" placeholder="<?php esc_attr_e('Amazon S3 secret key', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter your Amazon S3 secret key.', 'wpvivid-backuprestore'); ?></i><a href="https://wpvivid.com/get-amazon-access-secret-key.html" target="_blank"> <?php esc_html_e('How to get an Amazon S3 secret key.', 'wpvivid-backuprestore'); ?></a>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="amazons3" name="bucket" placeholder="<?php esc_attr_e('Amazon S3 Bucket Name(e.g. test)', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><span><?php esc_html_e('Enter an existed Bucket to create a custom backup storage directory.', 'wpvivid-backuprestore'); ?></span></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="amazons3" name="path" placeholder="<?php esc_attr_e('Custom Path', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><span><?php esc_html_e('Customize the directory where you want to store backups within the Bucket.', 'wpvivid-backuprestore'); ?></span></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="amazons3" name="default" checked /><?php esc_html_e('Set as the default remote storage.', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Once checked, all this sites backups sent to a remote storage destination will be uploaded to this storage by default.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="amazons3" name="classMode" checked /><?php esc_html_e('Storage class: Standard (infrequent access).', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Check the option to use Amazon S3 Standard-Infrequent Access (S3 Standard-IA) storage class for data transfer.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="amazons3" name="sse" checked /><?php esc_html_e('Server-side encryption.', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Check the option to use Amazon S3 server-side encryption to protect data.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" option="add-remote" type="submit" value="<?php esc_attr_e('Test and Add', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to connect to Amazon S3 storage and add it to the storage list below.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
<?php
if($need_extension){
?>
<p style="padding-left: 10px;"><?php esc_html_e('The simplexml extension is not detected. Please install the extension first.', 'wpvivid-backuprestore'); ?></p>
<?php
}
?>
</div>
<?php
}
public function wpvivid_edit_storage_page_amazons3()
{
?>
<div id="remote_storage_edit_amazons3" class="postbox storage-account-block remote-storage-edit" style="display:none;">
<div style="padding: 0 10px 10px 0;">
<strong><?php esc_html_e('Enter Your Amazon S3 Account', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-amazons3" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. Amazon S3-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-amazons3" name="access" placeholder="<?php esc_attr_e('Amazon S3 access key', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter your Amazon S3 access key.', 'wpvivid-backuprestore'); ?></i><a href="https://wpvivid.com/get-amazon-access-secret-key.html" target="_blank"> <?php esc_html_e('How to get an AmazonS3 access key.', 'wpvivid-backuprestore'); ?></a>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="password" class="regular-text" autocomplete="new-password" option="edit-amazons3" name="secret" placeholder="<?php esc_attr_e('Amazon S3 secret key', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter your Amazon S3 secret key.', 'wpvivid-backuprestore'); ?></i><a href="https://wpvivid.com/get-amazon-access-secret-key.html" target="_blank"> <?php esc_html_e('How to get an Amazon S3 secret key.', 'wpvivid-backuprestore'); ?></a>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-amazons3" name="bucket" placeholder="<?php esc_attr_e('Amazon S3 Bucket Name(e.g. test)', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><span><?php esc_html_e('Enter an existed Bucket to create a custom backup storage directory.', 'wpvivid-backuprestore'); ?></span></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-amazons3" name="path" placeholder="<?php esc_attr_e('Custom Path', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><span><?php esc_html_e('Customize the directory where you want to store backups within the Bucket.', 'wpvivid-backuprestore'); ?></span></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="edit-amazons3" name="classMode" /><?php esc_html_e('Storage class: Standard (infrequent access).', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Check the option to use Amazon S3 Standard-Infrequent Access (S3 Standard-IA) storage class for data transfer.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="edit-amazons3" name="sse" /><?php esc_html_e('Server-side encryption.', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Check the option to use Amazon S3 server-side encryption to protect data.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" option="edit-remote" type="submit" value="<?php esc_attr_e('Save Changes', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to save the changes.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<?php
}
public function wpvivid_remote_pic_amazons3($remote){
$remote['amazons3']['default_pic'] = '/admin/partials/images/storage-amazon-s3(gray).png';
$remote['amazons3']['selected_pic'] = '/admin/partials/images/storage-amazon-s3.png';
$remote['amazons3']['title'] = 'Amazon S3';
return $remote;
}
public function test_connect()
{
$amazons3 = $this -> getS3();
if(is_array($amazons3) && $amazons3['result'] === WPVIVID_FAILED)
return $amazons3;
$temp_file = md5(wp_rand());
try
{
if(isset($this->options['s3Path']))
{
$url=$this->options['s3Path'].$temp_file;
}
else
{
$url=$this->options['path'].'/'.$temp_file;
}
if(!$amazons3 -> putObjectString($temp_file,$this -> bucket,$url))
{
return array('result'=>WPVIVID_FAILED,'error'=>'We successfully accessed the bucket, but create test file failed.');
}
if(!$amazons3 -> deleteObject($this -> bucket,$url))
{
return array('result'=>WPVIVID_FAILED,'error'=>'We successfully accessed the bucket, and create test file succeed, but delete test file failed.');
}
}catch(Exception $e){
return array('result'=>WPVIVID_FAILED,'error'=>$e -> getMessage());
}
return array('result'=>WPVIVID_SUCCESS);
}
public function sanitize_options($skip_name='')
{
$ret['result']=WPVIVID_FAILED;
if(!isset($this->options['name']))
{
$ret['error']="Warning: An alias for remote storage is required.";
return $ret;
}
$this->options['name']=sanitize_text_field($this->options['name']);
if(empty($this->options['name']))
{
$ret['error']="Warning: An alias for remote storage is required.";
return $ret;
}
$remoteslist=WPvivid_Setting::get_all_remote_options();
foreach ($remoteslist as $key=>$value)
{
if(isset($value['name'])&&$value['name'] == $this->options['name']&&$skip_name!=$value['name'])
{
$ret['error']="Warning: The alias already exists in storage list.";
return $ret;
}
}
if(!isset($this->options['access']))
{
$ret['error']="Warning: The access key for Amazon S3 is required.";
return $ret;
}
$this->options['access']=sanitize_text_field($this->options['access']);
if(empty($this->options['access']))
{
$ret['error']="Warning: The access key for Amazon S3 is required.";
return $ret;
}
if(!isset($this->options['secret']))
{
$ret['error']="Warning: The storage secret key is required.";
return $ret;
}
$this->options['secret']=sanitize_text_field($this->options['secret']);
if(empty($this->options['secret']))
{
$ret['error']="Warning: The storage secret key is required.";
return $ret;
}
$this->options['secret'] = base64_encode($this->options['secret']);
$this->options['is_encrypt'] = 1;
if(!isset($this->options['bucket']))
{
$ret['error']="Warning: A Bucket name is required.";
return $ret;
}
$this->options['bucket']=sanitize_text_field($this->options['bucket']);
if(empty($this->options['bucket']))
{
$ret['error']="Warning: A Bucket name is required.";
return $ret;
}
if(!isset($this->options['path']))
{
$ret['error']="Warning: A directory name is required.";
return $ret;
}
$this->options['path']=sanitize_text_field($this->options['path']);
if(empty($this->options['path'])){
$ret['error']="Warning: A directory name is required.";
return $ret;
}
$ret['result']=WPVIVID_SUCCESS;
$ret['options']=$this->options;
return $ret;
}
public function upload($task_id,$files,$callback='')
{
global $wpvivid_plugin;
$amazons3 = $this -> getS3();
if(is_array($amazons3) && $amazons3['result'] == WPVIVID_FAILED)
return $amazons3;
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_AMAZONS3);
if(empty($upload_job))
{
$job_data=array();
foreach ($files as $file)
{
$file_data['size']=filesize($file);
$file_data['uploaded']=0;
$job_data[basename($file)]=$file_data;
}
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_AMAZONS3,WPVIVID_UPLOAD_UNDO,'Start uploading',$job_data);
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_AMAZONS3);
}
foreach ($files as $file){
if(is_array($upload_job['job_data']) &&array_key_exists(basename($file),$upload_job['job_data']))
{
if($upload_job['job_data'][basename($file)]['uploaded']==1)
continue;
}
$this -> last_time = time();
$this -> last_size = 0;
$wpvivid_plugin->wpvivid_log->WriteLog('Start uploading '.basename($file),'notice');
$wpvivid_plugin->set_time_limit($task_id);
if(!file_exists($file))
return array('result' =>WPVIVID_FAILED,'error' =>$file.' not found. The file might has been moved, renamed or deleted. Please reload the list and verify the file exists.');
$result = $this -> _put($task_id,$amazons3,$file,$callback);
if($result['result'] !==WPVIVID_SUCCESS){
$wpvivid_plugin->wpvivid_log->WriteLog('Uploading '.basename($file).' failed.','notice');
return $result;
}
else
{
WPvivid_taskmanager::wpvivid_reset_backup_retry_times($task_id);
}
$wpvivid_plugin->wpvivid_log->WriteLog('Finished uploading '.basename($file),'notice');
$upload_job['job_data'][basename($file)]['uploaded']=1;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_AMAZONS3,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file).' completed.',$upload_job['job_data']);
}
return array('result' =>WPVIVID_SUCCESS);
}
private function _put($task_id,$amazons3,$file,$callback)
{
global $wpvivid_plugin;
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_AMAZONS3);
$this -> current_file_size = filesize($file);
$this -> current_file_name = basename($file);
if(isset($this->options['s3Path']))
{
$url=$this->options['s3Path'].$this -> current_file_name;
}
else
{
$url=$this->options['path'].'/'.$this -> current_file_name;
}
$wpvivid_plugin->wpvivid_log->WriteLog($url,'notice');
$chunk_num = floor($this -> current_file_size / $this -> upload_chunk_size);
if($this -> current_file_size % $this -> upload_chunk_size > 0) $chunk_num ++;
for($i =0;$i <WPVIVID_REMOTE_CONNECT_RETRY_TIMES;$i ++)
{
try
{
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_AMAZONS3,WPVIVID_UPLOAD_UNDO,'Start uploading '.basename($file).'.',$upload_job['job_data']);
if(true)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Creating Multipart Upload.','notice');
if(!empty($upload_job['job_data'][basename($file)]['upload_id']))
{
$build_id = $upload_job['job_data'][basename($file)]['upload_id'];
}else{
$build_id = $amazons3 -> initiateMultipartUpload($this -> bucket,$url);
$upload_job['job_data'][basename($file)]['upload_id'] = $build_id;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_AMAZONS3,WPVIVID_UPLOAD_UNDO,'InitiateMultipartUpload, created build id of '.basename($file).'.',$upload_job['job_data']);
}
if(!empty($upload_job['job_data'][basename($file)]['upload_chunks']))
{
$chunks = $upload_job['job_data'][basename($file)]['upload_chunks'];
}else{
$chunks = array();
$upload_job['job_data'][basename($file)]['upload_chunks'] = $chunks;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_AMAZONS3,WPVIVID_UPLOAD_UNDO,'Start multipartupload of '.basename($file).'.',$upload_job['job_data']);
}
for($i =sizeof($chunks);$i <$chunk_num;$i ++)
{
$chunk_id = $amazons3 -> uploadPart($this -> bucket,$url,$build_id,$file,$i+1,$this ->upload_chunk_size);
if(!$chunk_id){
$chunks = array();
$upload_job['job_data'][basename($file)]['upload_chunks'] = $chunks;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_AMAZONS3,WPVIVID_UPLOAD_UNDO,'Start multipartupload of '.basename($file).'.',$upload_job['job_data']);
return array('result' => WPVIVID_FAILED,'error' => 'upload '.$file.' failed.');
}
$chunks[] = $chunk_id;
$upload_job['job_data'][basename($file)]['upload_chunks'] = $chunks;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_AMAZONS3,WPVIVID_UPLOAD_UNDO,'Uploading '.basename($file).'.',$upload_job['job_data']);
$offset = (($i + 1) * $this -> upload_chunk_size) > $this -> current_file_size ? $this -> current_file_size : (($i + 1) * $this -> upload_chunk_size);
if((time() - $this -> last_time) >3)
{
if(is_callable($callback))
{
call_user_func_array($callback,array($offset,$this -> current_file_name,
$this->current_file_size,$this -> last_time,$this -> last_size));
}
$this -> last_size = $offset;
$this -> last_time = time();
}
}
$result = $amazons3 -> completeMultipartUpload($this -> bucket,$url,$build_id,$chunks);
}else{
$wpvivid_plugin->wpvivid_log->WriteLog('Uploaded files are less than 5M.','notice');
$input = $amazons3 -> inputFile($file);
$wpvivid_plugin->wpvivid_log->WriteLog('putObject input:'.wp_json_encode($input).' bucket:'.$this->bucket.' url:'.$url,'notice');
$result = $amazons3 -> putObject($input,$this ->bucket,$url);
$wpvivid_plugin->wpvivid_log->WriteLog('putObject end:'.$result,'notice');
}
}catch(Exception $e)
{
if(strstr($e -> getMessage(), 'upload ID may be invalid'))
{
$upload_job['job_data'][basename($file)]['upload_id'] = '';
$upload_job['job_data'][basename($file)]['upload_chunks'] = '';
continue;
}
return array('result' => WPVIVID_FAILED,'error'=>$e -> getMessage());
}
if($result){
$upload_job['job_data'][basename($file)]['uploaded']=1;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_AMAZONS3,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file).' completed.',$upload_job['job_data']);
break;
}
if(!$result && $i == (WPVIVID_REMOTE_CONNECT_RETRY_TIMES - 1))
{
return array('result'=>WPVIVID_FAILED,'error'=>'Uploading '.$file.' to Amazon S3 server failed. '.$file.' might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.');
}
sleep(WPVIVID_REMOTE_CONNECT_RETRY_INTERVAL);
}
return array('result' =>WPVIVID_SUCCESS);
}
public function download($file,$local_path,$callback = '')
{
try {
global $wpvivid_plugin;
$this->current_file_name = $file['file_name'];
$this->current_file_size = $file['size'];
$wpvivid_plugin->wpvivid_download_log->WriteLog('Get amazons3 client.','notice');
$amazons3 = $this->getS3();
if (is_array($amazons3) && $amazons3['result'] === WPVIVID_FAILED) {
return $amazons3;
}
if(isset($this->options['s3Path']))
{
$url=$this->options['s3Path']. $this -> current_file_name;
}
else
{
$url=$this->options['path'].'/'. $this -> current_file_name;
}
$file_path = trailingslashit($local_path) . $this->current_file_name;
$start_offset = file_exists($file_path) ? filesize($file_path) : 0;
$wpvivid_plugin->wpvivid_download_log->WriteLog('Create local file.','notice');
$fh = fopen($file_path, 'a');
$wpvivid_plugin->wpvivid_download_log->WriteLog('Downloading file ' . $file['file_name'] . ', Size: ' . $file['size'] ,'notice');
while ($start_offset < $this->current_file_size) {
$last_byte = min($start_offset + $this->download_chunk_size - 1, $this->current_file_size - 1);
$headers['Range'] = "bytes=$start_offset-$last_byte";
$response = $amazons3->getObject($this->bucket,$url, $fh, $headers['Range']);
if (!$response)
return array('result' => WPVIVID_FAILED, 'error' => 'download ' . $url. ' failed.');
clearstatcache();
$state = stat($file_path);
$start_offset = $state['size'];
if ((time() - $this->last_time) > 3) {
if (is_callable($callback)) {
call_user_func_array($callback, array($start_offset, $this->current_file_name,
$this->current_file_size, $this->last_time, $this->last_size));
}
$this->last_size = $start_offset;
$this->last_time = time();
}
}
@fclose($fh);
if(filesize($file_path) == $file['size']){
if($wpvivid_plugin->wpvivid_check_zip_valid()) {
$res = TRUE;
}
else{
$res = FALSE;
}
}
else{
$res = FALSE;
}
if ($res !== TRUE) {
@wp_delete_file($file_path);
return array('result' => WPVIVID_FAILED, 'error' => 'Downloading ' . $file['file_name'] . ' failed. ' . $file['file_name'] . ' might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.');
}
return array('result' => WPVIVID_SUCCESS);
}
catch (Exception $error){
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('result'=>WPVIVID_FAILED, 'error'=>$message);
}
}
public function cleanup($files)
{
$amazons3 = $this -> getS3();
if(is_array($amazons3) && $amazons3['result'] === WPVIVID_FAILED)
return $amazons3;
foreach ($files as $file){
if(isset($this->options['s3Path']))
{
$url=$this->options['s3Path'].$file;
}
else
{
$url=$this->options['path'].'/'.$file;
}
$amazons3 -> deleteObject($this -> bucket , $url);
}
return array('result' => WPVIVID_SUCCESS);
}
private function getS3()
{
if(isset($this->options['s3Path']))
{
$path_temp = str_replace('s3://','',$this->options['s3Path']);
if (preg_match("#^/*([^/]+)/(.*)$#", $path_temp, $bmatches))
{
$this->bucket = $bmatches[1];
if(empty($bmatches[2])){
$this->options['s3Path'] = '';
}else{
$this->options['s3Path'] = trailingslashit($bmatches[2]);
}
} else {
$this->bucket = $path_temp;
$this->options['s3Path'] = '';
}
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1){
$secret = base64_decode($this->options['secret']);
}
else {
$secret = $this->options['secret'];
}
$amazons3 = new WPvivid_Base_S3($this->options['access'],$secret);
$amazons3 -> setExceptions();
if($this->options['classMode'])
$amazons3 -> setStorageClass();
if($this->options['sse'])
$amazons3 -> setServerSideEncryption();
try{
$region = $amazons3 -> getBucketLocation($this->bucket);
}catch(Exception $e){
return array('result' => WPVIVID_FAILED,'error' => $e -> getMessage());
}
$endpoint = $this -> getEndpoint($region);
if(!empty($endpoint))
$amazons3 -> setEndpoint($endpoint);
return $amazons3;
}
else
{
$this->bucket= $this->options['bucket'];
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1){
$secret = base64_decode($this->options['secret']);
}
else {
$secret = $this->options['secret'];
}
$amazons3 = new WPvivid_Base_S3($this->options['access'],$secret);
$amazons3 -> setExceptions();
if($this->options['classMode'])
$amazons3 -> setStorageClass();
if($this->options['sse'])
$amazons3 -> setServerSideEncryption();
try{
$region = $amazons3 -> getBucketLocation($this->bucket);
}catch(Exception $e){
return array('result' => WPVIVID_FAILED,'error' => $e -> getMessage());
}
$amazons3->setSignatureVersion('v4');
$amazons3->setRegion($region);
$endpoint = $this -> getEndpoint($region);
if(!empty($endpoint))
$amazons3 -> setEndpoint($endpoint);
return $amazons3;
}
}
private function getEndpoint($region){
switch ($region) {
case 'EU':
case 'eu-west-1':
$endpoint = 's3-eu-west-1.amazonaws.com';
break;
case 'US':
case 'us-east-1':
$endpoint = 's3.amazonaws.com';
break;
case 'us-west-1':
case 'us-east-2':
case 'us-west-2':
case 'eu-west-2':
case 'eu-west-3':
case 'ap-southeast-1':
case 'ap-southeast-2':
case 'ap-northeast-2':
case 'sa-east-1':
case 'ca-central-1':
case 'us-gov-west-1':
case 'eu-north-1':
case 'eu-central-1':
$endpoint = 's3-'.$region.'.amazonaws.com';
break;
case 'ap-northeast-1':
$endpoint = 's3.'.$region.'.amazonaws.com';
break;
case 'ap-south-1':
$endpoint = 's3.'.$region.'.amazonaws.com';
break;
case 'cn-north-1':
$endpoint = 's3.'.$region.'.amazonaws.com.cn';
break;
case 'af-south-1':
$endpoint = 's3.'.$region.'.amazonaws.com';
break;
default:
$endpoint = 's3.amazonaws.com';
break;
}
return $endpoint;
}
public function wpvivid_get_out_of_date_amazons3($out_of_date_remote, $remote)
{
if($remote['type'] == WPVIVID_REMOTE_AMAZONS3)
{
if(isset($remote['s3Path']))
$out_of_date_remote = $remote['s3Path'];
else
$out_of_date_remote = $remote['path'];
}
return $out_of_date_remote;
}
public function wpvivid_storage_provider_amazons3($storage_type)
{
if($storage_type == WPVIVID_REMOTE_AMAZONS3){
$storage_type = 'Amazon S3';
}
return $storage_type;
}
} includes/customclass/class-wpvivid-s3compat.php 0000644 00000105275 15132770567 0015774 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
if(!defined('WPVIVID_REMOTE_S3COMPAT')){
define('WPVIVID_REMOTE_S3COMPAT','s3compat');
}
if(!defined('WPVIVID_S3COMPAT_DEFAULT_FOLDER'))
define('WPVIVID_S3COMPAT_DEFAULT_FOLDER','/wpvivid_backup');
if(!defined('WPVIVID_S3COMPAT_NEED_PHP_VERSION'))
define('WPVIVID_S3COMPAT_NEED_PHP_VERSION','5.3.9');
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-remote.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
class Wpvivid_S3Compat extends WPvivid_Remote{
private $options;
private $bucket;
private $region;
private $upload_chunk_size = 5242880; // All parts except the last part must be no smaller than 5MB
private $download_chunk_size = 2097152;
public function __construct($options = array())
{
if(empty($options)){
add_action('wpvivid_add_storage_tab',array($this,'wpvivid_add_storage_tab_s3compat'), 14);
add_action('wpvivid_add_storage_page',array($this,'wpvivid_add_storage_page_s3compat'), 14);
add_action('wpvivid_edit_remote_page',array($this,'wpvivid_edit_storage_page_s3compat'), 14);
add_filter('wpvivid_remote_pic',array($this,'wpvivid_remote_pic_s3compat'),11);
add_filter('wpvivid_get_out_of_date_remote',array($this,'wpvivid_get_out_of_date_s3compat'),10,2);
add_filter('wpvivid_storage_provider_tran',array($this,'wpvivid_storage_provider_s3compat'),10);
}else{
$this -> options = $options;
}
}
public function getClient(){
$res = $this -> compare_php_version();
if($res['result'] == WPVIVID_FAILED)
return $res;
if(isset($this->options['s3directory']))
{
$path_temp = str_replace('s3generic://','',$this->options['s3directory'].$this -> options['path']);
if (preg_match("#^/*([^/]+)/(.*)$#", $path_temp, $bmatches))
{
$this->bucket = $bmatches[1];
} else {
$this->bucket = $path_temp;
}
$this->options['path']=ltrim($this -> options['path'],'/');
$endpoint_temp = str_replace('https://','',$this->options['endpoint']);
$explodes = explode('.',$endpoint_temp);
$this -> region = $explodes[0];
$this -> options['endpoint'] = 'https://'.trailingslashit($endpoint_temp);
}
else
{
$endpoint_temp = str_replace('https://','',$this->options['endpoint']);
$explodes = explode('.',$endpoint_temp);
$this -> region = $explodes[0];
$this -> options['endpoint'] = 'https://'.trailingslashit($endpoint_temp);
$this -> bucket=$this->options['bucket'];
}
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1){
$secret = base64_decode($this->options['secret']);
}
else {
$secret = $this->options['secret'];
}
include_once WPVIVID_PLUGIN_DIR.'/vendor/autoload.php';
$s3compat = S3Client::factory(
array(
'credentials' => array(
'key' => $this -> options['access'],
'secret' => $secret,
),
'version' => 'latest',
'region' => $this -> region,
'endpoint' => $this -> options['endpoint'],
)
);
return $s3compat;
}
public function test_connect()
{
$s3compat = $this -> getClient();
if(is_array($s3compat) && $s3compat['result'] == WPVIVID_FAILED)
{
return $s3compat;
}
$temp_file = md5(wp_rand());
try
{
$result = $s3compat->putObject(
array(
'Bucket'=>$this->bucket,
'Key' => $this->options['path'].'/'.$temp_file,
'Body' => $temp_file,
)
);
$etag = $result->get('ETag');
if(!isset($etag))
{
return array('result'=>WPVIVID_FAILED,'error'=>'We successfully accessed the bucket, but create test file failed.');
}
$result = $s3compat->deleteObject(array(
'Bucket' => $this -> bucket,
'Key' => $this -> options['path'].'/'.$temp_file,
));
if(empty($result))
{
return array('result'=>WPVIVID_FAILED,'error'=>'We successfully accessed the bucket, and create test file succeed, but delete test file failed.');
}
}
catch(S3Exception $e)
{
return array('result' => WPVIVID_FAILED,'error' => $e -> getAwsErrorCode().$e -> getMessage());
}
catch(Exception $e)
{
return array('result' => WPVIVID_FAILED,'error' => $e -> getMessage());
}
return array('result' => WPVIVID_SUCCESS);
}
public function upload($task_id, $files, $callback = '')
{
global $wpvivid_plugin;
$s3compat = $this -> getClient();
if(is_array($s3compat) && $s3compat['result'] == WPVIVID_FAILED)
{
return $s3compat;
}
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_S3COMPAT);
if(empty($upload_job))
{
$job_data=array();
foreach ($files as $file)
{
$file_data['size']=filesize($file);
$file_data['uploaded']=0;
$job_data[basename($file)]=$file_data;
}
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_S3COMPAT,WPVIVID_UPLOAD_UNDO,'Start uploading',$job_data);
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_S3COMPAT);
}
foreach ($files as $file)
{
if(is_array($upload_job['job_data'])&&array_key_exists(basename($file),$upload_job['job_data']))
{
if($upload_job['job_data'][basename($file)]['uploaded']==1)
continue;
}
$this->last_time = time();
$this->last_size = 0;
$wpvivid_plugin->wpvivid_log->WriteLog('Start uploading '.basename($file),'notice');
$wpvivid_plugin->set_time_limit($task_id);
if(!file_exists($file)){
$wpvivid_plugin->wpvivid_log->WriteLog('Uploading '.basename($file).' failed.','notice');
return array('result' =>WPVIVID_FAILED,'error' =>$file.' not found. The file might has been moved, renamed or deleted. Please reload the list and verify the file exists.');
}
$result = $this->_put($task_id,$s3compat,$file,$callback);
if($result['result'] !==WPVIVID_SUCCESS)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Uploading '.basename($file).' failed.','notice');
return $result;
}
else
{
WPvivid_taskmanager::wpvivid_reset_backup_retry_times($task_id);
}
$upload_job['job_data'][basename($file)]['uploaded']=1;
$wpvivid_plugin->wpvivid_log->WriteLog('Finished uploading '.basename($file),'notice');
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_S3COMPAT,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file).' completed.',$upload_job['job_data']);
}
return array('result' => WPVIVID_SUCCESS);
}
public function _put($task_id,$s3compat,$file,$callback){
$path = $this->options['path'].'/'.basename($file);
$this->current_file_size = filesize($file);
$this->current_file_name = basename($file);
try
{
if($this->current_file_size > $this->upload_chunk_size)
{
$result = $s3compat ->createMultipartUpload(array(
'Bucket' => $this -> bucket,
'Key' => $path,
));
if(!isset($result['UploadId']))
return array('result' => WPVIVID_FAILED, 'error' => 'Creating upload task failed. Please try again.');
$uploadId = $result['UploadId'];
$fh = fopen($file,'rb');
$partNumber = 1;
$parts = array();
$offset = 0;
while(!feof($fh))
{
$data = fread($fh,$this -> upload_chunk_size);
$result = $this -> _upload_loop($s3compat,$uploadId,$path,$data,$partNumber,$parts);
if($result['result'] === WPVIVID_FAILED)
break;
$partNumber ++;
$offset += $this -> upload_chunk_size;
if((time() - $this -> last_time) >3)
{
if(is_callable($callback))
{
call_user_func_array($callback,array(min($offset,$this -> current_file_size),$this -> current_file_name,
$this->current_file_size,$this -> last_time,$this -> last_size));
}
$this -> last_size = $offset;
$this -> last_time = time();
}
}
fclose($fh);
if($result['result'] === WPVIVID_SUCCESS)
{
$ret = $s3compat ->completeMultipartUpload
(
array(
'Bucket' => $this -> bucket,
'Key' => $path,
'Parts' => $parts,
'UploadId' => $uploadId,
)
);
if(!isset($ret['Location']))
{
$result = array('result' => WPVIVID_FAILED, 'error' => 'Merging multipart failed. File name: '.$this -> current_file_name);
}
}
}
else {
$res = $s3compat ->putObject(
array(
'Bucket'=>$this -> bucket,
'Key' => $path,
'SourceFile' => $file,
)
);
$etag = $res -> get('ETag');
if(isset($etag))
{
$result = array('result' => WPVIVID_SUCCESS);
}else {
$result = array('result' => WPVIVID_FAILED , 'error' => 'upload '.$this -> current_file_name.' failed.');
}
}
}
catch(S3Exception $e)
{
return array('result' => WPVIVID_FAILED,'error' => $e -> getAwsErrorCode().$e -> getMessage());
}
catch(Exception $e)
{
return array('result' => WPVIVID_FAILED,'error' => $e -> getMessage());
}
return $result;
}
public function _upload_loop($s3compat,$uploadId,$path,$data,$partNumber,&$parts){
for($i =0;$i <WPVIVID_REMOTE_CONNECT_RETRY_TIMES;$i ++)
{
$ret = $s3compat ->uploadPart(array(
'Bucket' => $this ->bucket,
'Key' => $path,
'UploadId' => $uploadId,
'PartNumber' => $partNumber,
'Body' => $data,
));
if(isset($ret['ETag']))
{
$parts[] = array(
'ETag' => $ret['ETag'],
'PartNumber' => $partNumber,
);
return array('result' => WPVIVID_SUCCESS);
}
}
return array('result' => WPVIVID_FAILED,'error' =>'Multipart upload failed. File name: '.$this -> current_file_name);
}
public function download($file, $local_path, $callback = '')
{
try {
global $wpvivid_plugin;
$this->current_file_name = $file['file_name'];
$this->current_file_size = $file['size'];
$file_path = trailingslashit($local_path) . $this->current_file_name;
$wpvivid_plugin->wpvivid_download_log->WriteLog('Get s3compat client.','notice');
$s3compat = $this->getClient();
if (is_array($s3compat) && $s3compat['result'] == WPVIVID_FAILED) {
return $s3compat;
}
$start_offset = file_exists($file_path) ? filesize($file_path) : 0;
$wpvivid_plugin->wpvivid_download_log->WriteLog('Create local file.','notice');
$fh = fopen($file_path, 'a');
$wpvivid_plugin->wpvivid_download_log->WriteLog('Downloading file ' . $file['file_name'] . ', Size: ' . $file['size'] ,'notice');
while ($start_offset < $this->current_file_size)
{
$last_byte = min($start_offset + $this->download_chunk_size - 1, $this->current_file_size - 1);
$range = "bytes=$start_offset-$last_byte";
$response = $this->_download_loop($s3compat, $range, $fh);
if ($response['result'] === WPVIVID_FAILED)
{
return $response;
}
clearstatcache();
$state = stat($file_path);
$start_offset = $state['size'];
if ((time() - $this->last_time) > 3)
{
if (is_callable($callback)) {
call_user_func_array($callback, array($start_offset, $this->current_file_name,
$this->current_file_size, $this->last_time, $this->last_size));
}
$this->last_size = $start_offset;
$this->last_time = time();
}
}
@fclose($fh);
if(filesize($file_path) == $file['size'])
{
if($wpvivid_plugin->wpvivid_check_zip_valid())
{
$res = TRUE;
}
else{
$res = FALSE;
}
}
else{
$res = FALSE;
}
if ($res !== TRUE) {
@wp_delete_file($file_path);
return array('result' => WPVIVID_FAILED, 'error' => 'Downloading ' . $file['file_name'] . ' failed. ' . $file['file_name'] . ' might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.');
}
return array('result' => WPVIVID_SUCCESS);
}
catch (S3Exception $e) {
return array('result' => WPVIVID_FAILED, 'error' => $e->getAwsErrorCode() . $e->getMessage());
}
catch (Exception $error){
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('result'=>WPVIVID_FAILED, 'error'=>$message);
}
}
public function _download_loop($s3compat,$range,$fh){
try{
for($i =0;$i <WPVIVID_REMOTE_CONNECT_RETRY_TIMES;$i ++){
$response = $s3compat -> getObject(array(
'Bucket' => $this -> bucket,
'Key' => $this -> options['path'].'/'.$this -> current_file_name,
'Range' => $range
));
if(isset($response['Body']) && fwrite($fh,$response['Body'])) {
return array('result' => WPVIVID_SUCCESS);
}
}
return array('result'=>WPVIVID_FAILED, 'error' => 'download '.$this -> current_file_name.' failed.');
}catch(S3Exception $e){
return array('result' => WPVIVID_FAILED,'error' => $e -> getAwsErrorCode().$e -> getMessage());
}catch(Exception $e){
return array('result' => WPVIVID_FAILED,'error' => $e -> getMessage());
}
}
public function cleanup($files)
{
$s3compat = $this -> getClient();
if(is_array($s3compat) && $s3compat['result'] == WPVIVID_FAILED){
return $s3compat;
}
$keys = array();
foreach ($files as $file){
$keys[] = array('Key' => $this -> options['path'].'/'.basename($file));
}
try{
$result = $s3compat -> deleteObjects(array(
// Bucket is required
'Bucket' => $this -> bucket,
// Objects is required
'Objects' => $keys
));
}catch (S3Exception $e){}catch (Exception $e){}
return array('result'=>WPVIVID_SUCCESS);
}
public function wpvivid_add_storage_tab_s3compat(){
?>
<div class="storage-providers" remote_type="s3compat" onclick="select_remote_storage(event, 'storage_account_s3compat');">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/storage-digitalocean.png'); ?>" style="vertical-align:middle;"/><?php esc_html_e('DigitalOcean Spaces', 'wpvivid-backuprestore'); ?>
</div>
<?php
}
public function wpvivid_add_storage_page_s3compat(){
?>
<div id="storage_account_s3compat" class="storage-account-page" style="display:none;">
<div style="padding: 0 10px 10px 0;">
<strong><?php esc_html_e('Enter Your DigitalOcean Spaces Account', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="s3compat" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. DOS-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="s3compat" name="access" placeholder="<?php esc_attr_e('DigitalOcean Spaces access key', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter your DigitalOcean Spaces access key', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="password" class="regular-text" autocomplete="new-password" option="s3compat" name="secret" placeholder="<?php esc_attr_e('DigitalOcean Spaces secret key', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter your DigitalOcean Spaces secret key', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="s3compat" name="bucket" placeholder="<?php esc_attr_e('Space Name(e.g. test)', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><span><?php esc_html_e('Enter an existed Space to create a custom backup storage directory.', 'wpvivid-backuprestore'); ?></span></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="s3compat" name="path" placeholder="<?php esc_attr_e('Custom Path', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><span><?php esc_html_e('Customize the directory where you want to store backups within the Space.', 'wpvivid-backuprestore'); ?></span></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="s3compat" name="endpoint" placeholder="<?php esc_attr_e('region.digitaloceanspaces.com', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the DigitalOcean Endpoint for the storage', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="s3compat" name="default" checked /><?php esc_html_e('Set as the default remote storage.', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Once checked, all this sites backups sent to a remote storage destination will be uploaded to this storage by default.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" option="add-remote" type="submit" value="<?php esc_attr_e('Test and Add', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to connect to DigitalOcean Spaces storage and add it to the storage list below.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<?php
}
public function wpvivid_edit_storage_page_s3compat()
{
?>
<div id="remote_storage_edit_s3compat" class="postbox storage-account-block remote-storage-edit" style="display:none;">
<div style="padding: 0 10px 10px 0;">
<strong><?php esc_html_e('Enter Your DigitalOcean Spaces Account', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-s3compat" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. DOS-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-s3compat" name="access" placeholder="<?php esc_attr_e('DigitalOcean Spaces access key', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter your DigitalOcean Spaces access key', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="password" class="regular-text" autocomplete="new-password" option="edit-s3compat" name="secret" placeholder="<?php esc_attr_e('DigitalOcean Spaces secret key', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter your DigitalOcean Spaces secret key', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-s3compat" name="bucket" placeholder="<?php esc_attr_e('Space Name(e.g. test)', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><span><?php esc_html_e('Enter an existed Space to create a custom backup storage directory.', 'wpvivid-backuprestore'); ?></span></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-s3compat" name="path" placeholder="<?php esc_attr_e('Custom Path', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><span><?php esc_html_e('Customize the directory where you want to store backups within the Space.', 'wpvivid-backuprestore'); ?></span></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-s3compat" name="endpoint" placeholder="<?php esc_attr_e('region.digitaloceanspaces.com', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the DigitalOcean Endpoint for the storage', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" option="edit-remote" type="submit" value="<?php esc_attr_e('Save Changes', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to save the changes.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script>
jQuery("input:text[option=edit-s3compat][name=s3directory]").keyup(function(){
var value = jQuery(this).val();
if(value == ''){
value = '*';
}
value = value + '/wpvivid_backup';
jQuery('#wpvivid_edit_dos_root_path').html(value);
});
</script>
<?php
}
public function wpvivid_remote_pic_s3compat($remote){
$remote['s3compat']['default_pic'] = '/admin/partials/images/storage-digitalocean(gray).png';
$remote['s3compat']['selected_pic'] = '/admin/partials/images/storage-digitalocean.png';
$remote['s3compat']['title'] = 'DigitalOcean Spaces';
return $remote;
}
public function sanitize_options($skip_name='')
{
$ret['result']=WPVIVID_FAILED;
if(!isset($this->options['name']))
{
$ret['error']="Warning: An alias for remote storage is required.";
return $ret;
}
$this->options['name']=sanitize_text_field($this->options['name']);
if(empty($this->options['name']))
{
$ret['error']="Warning: An alias for remote storage is required.";
return $ret;
}
$remoteslist=WPvivid_Setting::get_all_remote_options();
foreach ($remoteslist as $key=>$value)
{
if(isset($value['name'])&&$value['name'] == $this->options['name']&&$skip_name!=$value['name'])
{
$ret['error']="Warning: The alias already exists in storage list.";
return $ret;
}
}
if(!isset($this->options['access']))
{
$ret['error']="Warning: The access key for S3-Compatible is required.";
return $ret;
}
$this->options['access']=sanitize_text_field($this->options['access']);
if(empty($this->options['access']))
{
$ret['error']="Warning: The access key for S3-Compatible is required.";
return $ret;
}
if(!isset($this->options['secret']))
{
$ret['error']="Warning: The storage secret key is required.";
return $ret;
}
$this->options['secret']=sanitize_text_field($this->options['secret']);
if(empty($this->options['secret']))
{
$ret['error']="Warning: The storage secret key is required.";
return $ret;
}
$this->options['secret'] = base64_encode($this->options['secret']);
$this->options['is_encrypt'] = 1;
if(empty($this->options['bucket']))
{
$ret['error']="Warning: A Digital Space is required.";
return $ret;
}
if(!isset($this->options['path']))
{
$ret['error']="Warning: A directory name is required.";
return $ret;
}
$this->options['path']=sanitize_text_field($this->options['path']);
if(empty($this->options['path'])){
$ret['error']="Warning: A directory name is required.";
return $ret;
}
if(!isset($this->options['endpoint']))
{
$ret['error']="Warning: The end-point is required.";
return $ret;
}
$this->options['endpoint']=sanitize_text_field($this->options['endpoint']);
$ret['result']=WPVIVID_SUCCESS;
$ret['options']=$this->options;
return $ret;
}
public function wpvivid_get_out_of_date_s3compat($out_of_date_remote, $remote)
{
if($remote['type'] == WPVIVID_REMOTE_S3COMPAT)
{
if(isset($remote['s3directory']))
$out_of_date_remote = $remote['s3directory'].$remote['path'];
else
$out_of_date_remote = $remote['path'];
}
return $out_of_date_remote;
}
public function wpvivid_storage_provider_s3compat($storage_type)
{
if($storage_type == WPVIVID_REMOTE_S3COMPAT){
$storage_type = 'DigitalOcean Spaces';
}
return $storage_type;
}
private function compare_php_version(){
if(version_compare(WPVIVID_GOOGLE_NEED_PHP_VERSION,phpversion()) > 0){
return array('result' => WPVIVID_FAILED,'error' => 'The required PHP version is higher than '.WPVIVID_S3COMPAT_NEED_PHP_VERSION.'. After updating your PHP version, please try again.');
}
return array('result' => WPVIVID_SUCCESS);
}
} includes/customclass/class-wpvivid-remote.php 0000644 00000001715 15132770567 0015530 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
abstract class WPvivid_Remote{
public $current_file_name = '';
public $current_file_size = '';
public $last_time = 0;
public $last_size = 0;
public $object;
public $remote;
abstract public function test_connect();
abstract public function upload($task_id,$files,$callback = ''); // $files = array();
abstract public function download($file,$local_path,$callback = ''); // $file = array('file_name' => ,'size' =>,'md5' =>)
abstract public function cleanup($files); // $files = array();
public function formatBytes($bytes, $precision = 2)
{
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . '' . $units[$pow];
}
} includes/customclass/class-wpvivid-extend-sftp.php 0000644 00000010702 15132770567 0016472 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
include_once WPVIVID_PLUGIN_DIR.'/vendor/autoload.php';
class WPvivid_Net_SFTP extends Net_SFTP
{
function get($remote_file, $local_file = false, $offset = 0, $length = -1, $callback = null)
{
if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
return false;
}
$remote_file = $this->_realpath($remote_file);
if ($remote_file === false) {
return false;
}
$packet = pack('Na*N2', strlen($remote_file), $remote_file, NET_SFTP_OPEN_READ, 0);
if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) {
return false;
}
$response = $this->_get_sftp_packet();
switch ($this->packet_type) {
case NET_SFTP_HANDLE:
$handle = substr($response, 4);
break;
case NET_SFTP_STATUS:
$this->_logError($response);
return false;
default:
user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS');
return false;
}
if (is_resource($local_file)) {
$fp = $local_file;
$stat = fstat($fp);
$res_offset = $stat['size'];
} else {
$res_offset = 0;
if ($local_file !== false) {
$fp = fopen($local_file, 'wb');
if (!$fp) {
return false;
}
} else {
$content = '';
}
}
$fclose_check = $local_file !== false && !is_resource($local_file);
$start = $offset;
$read = 0;
while (true) {
$i = 0;
while ($i < NET_SFTP_QUEUE_SIZE && ($length < 0 || $read < $length)) {
$tempoffset = $start + $read;
$packet_size = $length > 0 ? min($this->max_sftp_packet, $length - $read) : $this->max_sftp_packet;
$packet = pack('Na*N3', strlen($handle), $handle, $tempoffset / 4294967296, $tempoffset, $packet_size);
if (!$this->_send_sftp_packet(NET_SFTP_READ, $packet)) {
if ($fclose_check) {
fclose($fp);
}
return false;
}
$packet = null;
$read+= $packet_size;
$i++;
}
if (!$i) {
break;
}
$clear_responses = false;
while ($i > 0) {
$i--;
if ($clear_responses) {
$this->_get_sftp_packet();
continue;
} else {
$response = $this->_get_sftp_packet();
}
switch ($this->packet_type) {
case NET_SFTP_DATA:
$temp = substr($response, 4);
$offset+= strlen($temp);
if ($local_file === false) {
$content.= $temp;
} else {
fputs($fp, $temp);
}
if( is_callable($callback)){
call_user_func_array($callback,array($offset));
}
$temp = null;
break;
case NET_SFTP_STATUS:
$this->_logError($response);
$clear_responses = true;
break;
default:
if ($fclose_check) {
fclose($fp);
}
user_error('Expected SSH_FX_DATA or SSH_FXP_STATUS');
}
$response = null;
}
if ($clear_responses) {
break;
}
}
if ($length > 0 && $length <= $offset - $start) {
if ($local_file === false) {
$content = substr($content, 0, $length);
} else {
ftruncate($fp, $length + $res_offset);
}
}
if ($fclose_check) {
fclose($fp);
}
if (!$this->_close_handle($handle)) {
return false;
}
return isset($content) ? $content : true;
}
} includes/customclass/class-wpvivid-s3.php 0000644 00000255367 15132770567 0014600 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
/**
* $Id$
*
* Copyright (c) 2013, Donovan Schönknecht. All rights reserved.
* Portions copyright (c) 2012-2022, David Anderson (https://david.dw-perspective.org.uk). All rights reserved
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Amazon S3 is a trademark of Amazon.com, Inc. or its affiliates.
*/
/**
* Amazon S3 PHP class
*
* @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class
* @version 0.5.1
*/
class WPvivid_S3
{
// ACL flags
const ACL_PRIVATE = 'private';
const ACL_PUBLIC_READ = 'public-read';
const ACL_PUBLIC_READ_WRITE = 'public-read-write';
const ACL_AUTHENTICATED_READ = 'authenticated-read';
const STORAGE_CLASS_STANDARD = 'STANDARD';
const STORAGE_CLASS_RRS = 'REDUCED_REDUNDANCY';
const STORAGE_CLASS_STANDARD_IA = 'STANDARD_IA';
const SSE_NONE = '';
const SSE_AES256 = 'AES256';
/**
* The AWS Access key
*
* @var string
* @access private
* @static
*/
private $__accessKey = null;
/**
* AWS Secret Key
*
* @var string
* @access private
* @static
*/
private $__secretKey = null;
/**
* SSL Client key
*
* @var string
* @access private
* @static
*/
private $__sslKey = null;
/**
* Default delimiter to be used, for example while getBucket().
* @var string
* @access public
* @
*/
public $defDelimiter = null;
/**
* AWS URI
*
* @var string
* @acess public
* @static
*/
public $endpoint = 's3.amazonaws.com';
/**
* Proxy information
*
* @var null|array
* @access public
* @static
*/
public $proxy = null;
/**
* Connect using SSL?
*
* @var bool
* @access public
* @static
*/
public $useSSL = false;
/**
* Use SSL validation?
*
* @var bool
* @access public
* @static
*/
public $useSSLValidation = true;
/**
* Use SSL version
*
* @var const
* @access public
* @static
*/
public $useSSLVersion = CURL_SSLVERSION_TLSv1;
/**
* Use PHP exceptions?
*
* @var bool
* @access public
* @static
*/
public $useExceptions = false;
/**
* Time offset applied to time()
* @access private
* @static
*/
private $__timeOffset = 0;
/**
* SSL client key
*
* @var bool
* @access public
* @static
*/
public $sslKey = null;
/**
* SSL client certfificate
*
* @var string
* @acess public
* @static
*/
public $sslCert = null;
/**
* SSL CA cert (only required if you are having problems with your system CA cert)
*
* @var string
* @access public
* @static
*/
public $sslCACert = null;
/**
* AWS Key Pair ID
*
* @var string
* @access private
* @static
*/
private $__signingKeyPairId = null;
/**
* Key resource, freeSigningKey() must be called to clear it from memory
*
* @var bool
* @access private
* @
*/
private $__signingKeyResource = false;
var $_serverSideEncryption = self::SSE_NONE;
var $_storageClass = self::STORAGE_CLASS_STANDARD;
/**
* Constructor - if you're not using the class statically
*
* @param string $accessKey Access key
* @param string $secretKey Secret key
* @param boolean $useSSL Enable SSL
* @param string $endpoint Amazon URI
* @return void
*/
var $region;
public function __construct($accessKey = null, $secretKey = null, $useSSL = false, $endpoint = 's3.amazonaws.com')
{
if ($accessKey !== null && $secretKey !== null)
$this -> setAuth($accessKey, $secretKey);
$this -> useSSL = $useSSL;
$this -> endpoint = $endpoint;
$this->region = 'us-east-1';
}
/**
* Set the service endpoint
*
* @param string $host Hostname
* @return void
*/
public function setEndpoint($host)
{
$this -> endpoint = $host;
}
/**
* Set the service region
*
* @param string $region Region
* @return void
*/
public function setRegion($region) {
$this->region = $region;
}
/**
* Get the service region
* Note: Region calculation will be done in methods/s3.php file
*
* @return string Region
*/
public function getRegion() {
return $this->region;
}
/**
* Set AWS access key and secret key
*
* @param string $accessKey Access key
* @param string $secretKey Secret key
* @return void
*/
public function setAuth($accessKey, $secretKey)
{
$this -> __accessKey = $accessKey;
$this -> __secretKey = $secretKey;
}
/**
* Check if AWS keys have been set
*
* @return boolean
*/
public function hasAuth() {
return ($this -> __accessKey !== null && $this -> __secretKey !== null);
}
/**
* Set SSL on or off
*
* @param boolean $enabled SSL enabled
* @param boolean $validate SSL certificate validation
* @return void
*/
public function setSSL($enabled, $validate = true)
{
$this -> useSSL = $enabled;
$this -> useSSLValidation = $validate;
}
/**
* Set SSL client certificates (experimental)
*
* @param string $sslCert SSL client certificate
* @param string $sslKey SSL client key
* @param string $sslCACert SSL CA cert (only required if you are having problems with your system CA cert)
* @return void
*/
public function setSSLAuth($sslCert = null, $sslKey = null, $sslCACert = null)
{
$this -> sslCert = $sslCert;
$this -> sslKey = $sslKey;
$this -> sslCACert = $sslCACert;
}
/**
* Set proxy information
*
* @param string $host Proxy hostname and port (localhost:1234)
* @param string $user Proxy username
* @param string $pass Proxy password
* @param constant $type CURL proxy type
* @return void
*/
public function setProxy($host, $user = null, $pass = null, $type = CURLPROXY_SOCKS5)
{
$this -> proxy = array('host' => $host, 'type' => $type, 'user' => $user, 'pass' => $pass);
}
/**
* Set the error mode to exceptions
*
* @param boolean $enabled Enable exceptions
* @return void
*/
public function setExceptions($enabled = true)
{
$this -> useExceptions = $enabled;
}
/**
* Set AWS time correction offset (use carefully)
*
* This can be used when an inaccurate system time is generating
* invalid request signatures. It should only be used as a last
* resort when the system time cannot be changed.
*
* @param string $offset Time offset (set to zero to use AWS server time)
* @return void
*/
public function setTimeCorrectionOffset($offset = 0)
{
if ($offset == 0)
{
$rest = new WPvivid_S3Request('HEAD','','',$this -> endpoint,$this);
$rest = $rest->getResponse();
$awstime = $rest->headers['date'];
$systime = time();
$offset = $systime > $awstime ? -($systime - $awstime) : ($awstime - $systime);
}
$this -> __timeOffset = $offset;
}
/**
* Set signing key
*
* @param string $keyPairId AWS Key Pair ID
* @param string $signingKey Private Key
* @param boolean $isFile Load private key from file, set to false to load string
* @return boolean
*/
public function setSigningKey($keyPairId, $signingKey, $isFile = true)
{
$this -> __signingKeyPairId = $keyPairId;
if (($this -> __signingKeyResource = openssl_pkey_get_private($isFile ?
file_get_contents($signingKey) : $signingKey)) !== false) return true;
$this -> __triggerError('S3::setSigningKey(): Unable to open load private key: '.$signingKey, __FILE__, __LINE__);
return false;
}
/**
* Free signing key from memory, MUST be called if you are using setSigningKey()
*
* @return void
*/
public function freeSigningKey()
{
if ($this -> __signingKeyResource !== false)
openssl_free_key($this -> __signingKeyResource);
}
/**
* Internal error handler
*
* @internal Internal error handler
* @param string $message Error message
* @param string $file Filename
* @param integer $line Line number
* @param integer $code Error code
* @return void
*/
function __triggerError($message, $file, $line, $code = 0)
{
if ($this -> useExceptions)
throw new WPvivid_S3Exception(esc_html($message), esc_attr($file), esc_attr($line), esc_attr($code));
else
trigger_error(esc_html($message), E_USER_WARNING);
}
/**
* Get a list of buckets
*
* @param boolean $detailed Returns detailed bucket list when true
* @return array | false
*/
public function listBuckets($detailed = false)
{
$rest = new WPvivid_S3Request('GET', '', '', $this -> endpoint,$this);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::listBuckets(): [%s] %s", $rest->error['code'],
$rest->error['message']), __FILE__, __LINE__);
return false;
}
$results = array();
if (!isset($rest->body->Buckets)) return $results;
if ($detailed)
{
if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName))
$results['owner'] = array(
'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName
);
$results['buckets'] = array();
foreach ($rest->body->Buckets->Bucket as $b)
$results['buckets'][] = array(
'name' => (string)$b->Name, 'time' => strtotime((string)$b->CreationDate)
);
} else
foreach ($rest->body->Buckets->Bucket as $b) $results[] = (string)$b->Name;
return $results;
}
/**
* Get contents for a bucket
*
* If maxKeys is null this method will loop through truncated result sets
*
* @param string $bucket Bucket name
* @param string $prefix Prefix
* @param string $marker Marker (last file listed)
* @param string $maxKeys Max keys (maximum number of keys to return)
* @param string $delimiter Delimiter
* @param boolean $returnCommonPrefixes Set to true to return CommonPrefixes
* @return array | false
*/
public function getBucket($bucket, $prefix = null, $marker = null, $maxKeys = null, $delimiter = null, $returnCommonPrefixes = false)
{
$rest = new WPvivid_S3Request('GET', $bucket, '', $this -> endpoint,$this);
if ($maxKeys == 0) $maxKeys = null;
if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix);
if ($marker !== null && $marker !== '') $rest->setParameter('marker', $marker);
if ($maxKeys !== null && $maxKeys !== '') $rest->setParameter('max-keys', $maxKeys);
if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter);
else if (!empty($this -> defDelimiter)) $rest->setParameter('delimiter', $this -> defDelimiter);
$response = $rest->getResponse();
if ($response->error === false && $response->code !== 200)
$response->error = array('code' => $response->code, 'message' => 'Unexpected HTTP status');
if ($response->error !== false)
{
$this -> __triggerError(sprintf("S3::getBucket(): [%s] %s",
$response->error['code'], $response->error['message']), __FILE__, __LINE__);
return false;
}
$results = array();
$nextMarker = null;
if (isset($response->body, $response->body->Contents))
foreach ($response->body->Contents as $c)
{
$results[(string)$c->Key] = array(
'name' => (string)$c->Key,
'time' => strtotime((string)$c->LastModified),
'size' => (int)$c->Size,
'hash' => substr((string)$c->ETag, 1, -1)
);
$nextMarker = (string)$c->Key;
}
if ($returnCommonPrefixes && isset($response->body, $response->body->CommonPrefixes))
foreach ($response->body->CommonPrefixes as $c)
$results[(string)$c->Prefix] = array('prefix' => (string)$c->Prefix);
if (isset($response->body, $response->body->IsTruncated) &&
(string)$response->body->IsTruncated == 'false') return $results;
if (isset($response->body, $response->body->NextMarker))
$nextMarker = (string)$response->body->NextMarker;
// Loop through truncated results if maxKeys isn't specified
if ($maxKeys == null && $nextMarker !== null && (string)$response->body->IsTruncated == 'true')
do
{
$rest = new WPvivid_S3Request('GET', $bucket, '', $this -> endpoint,$this);
if ($prefix !== null && $prefix !== '') $rest->setParameter('prefix', $prefix);
$rest->setParameter('marker', $nextMarker);
if ($delimiter !== null && $delimiter !== '') $rest->setParameter('delimiter', $delimiter);
if (($response = $rest->getResponse()) == false || $response->code !== 200) break;
if (isset($response->body, $response->body->Contents))
foreach ($response->body->Contents as $c)
{
$results[(string)$c->Key] = array(
'name' => (string)$c->Key,
'time' => strtotime((string)$c->LastModified),
'size' => (int)$c->Size,
'hash' => substr((string)$c->ETag, 1, -1)
);
$nextMarker = (string)$c->Key;
}
if ($returnCommonPrefixes && isset($response->body, $response->body->CommonPrefixes))
foreach ($response->body->CommonPrefixes as $c)
$results[(string)$c->Prefix] = array('prefix' => (string)$c->Prefix);
if (isset($response->body, $response->body->NextMarker))
$nextMarker = (string)$response->body->NextMarker;
} while ($response !== false && (string)$response->body->IsTruncated == 'true');
return $results;
}
/**
* Put a bucket
*
* @param string $bucket Bucket name
* @param constant $acl ACL flag
* @param string $location Set as "EU" to create buckets hosted in Europe
* @return boolean
*/
public function putBucket($bucket, $acl = self::ACL_PRIVATE, $location = false)
{
$rest = new WPvivid_S3Request('PUT', $bucket, '', $this -> endpoint,$this);
$rest->setAmzHeader('x-amz-acl', $acl);
if ($location !== false)
{
$dom = new DOMDocument;
$createBucketConfiguration = $dom->createElement('CreateBucketConfiguration');
$locationConstraint = $dom->createElement('LocationConstraint', $location);
$createBucketConfiguration->appendChild($locationConstraint);
$dom->appendChild($createBucketConfiguration);
$rest->data = $dom->saveXML();
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
}
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::putBucket({$bucket}, {$acl}, {$location}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
/**
* Delete an empty bucket
*
* @param string $bucket Bucket name
* @return boolean
*/
public function deleteBucket($bucket)
{
$rest = new WPvivid_S3Request('DELETE', $bucket, '', $this -> endpoint,$this);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 204)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::deleteBucket({$bucket}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
/**
* Create input info array for putObject()
*
* @param string $file Input file
* @param mixed $md5sum Use MD5 hash (supply a string if you want to use your own)
* @return array | false
*/
public function inputFile($file, $md5sum = true)
{
if (!file_exists($file) || !is_file($file) || !is_readable($file))
{
$this -> __triggerError('S3::inputFile(): Unable to open input file: '.$file, __FILE__, __LINE__);
return false;
}
clearstatcache(false, $file);
return array('file' => $file, 'size' => filesize($file), 'md5sum' => $md5sum !== false ?
(is_string($md5sum) ? $md5sum : base64_encode(md5_file($file, true))) : '');
}
/**
* Create input array info for putObject() with a resource
*
* @param string $resource Input resource to read from
* @param integer $bufferSize Input byte size
* @param string $md5sum MD5 hash to send (optional)
* @return array | false
*/
public function inputResource(&$resource, $bufferSize = false, $md5sum = '')
{
if (!is_resource($resource) || (int)$bufferSize < 0)
{
$this -> __triggerError('S3::inputResource(): Invalid resource or buffer size', __FILE__, __LINE__);
return false;
}
// Try to figure out the bytesize
if ($bufferSize === false)
{
if (fseek($resource, 0, SEEK_END) < 0 || ($bufferSize = ftell($resource)) === false)
{
$this -> __triggerError('S3::inputResource(): Unable to obtain resource size', __FILE__, __LINE__);
return false;
}
fseek($resource, 0);
}
$input = array('size' => $bufferSize, 'md5sum' => $md5sum);
$input['fp'] =& $resource;
return $input;
}
/**
* Put an object
*
* @param mixed $input Input data
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param constant $acl ACL constant
* @param array $metaHeaders Array of x-amz-meta-* headers
* @param array $requestHeaders Array of request headers or content type as a string
* @param constant $storageClass Storage class constant
* @param constant $serverSideEncryption Server-side encryption
* @return boolean
*/
public function putObject($input, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self::STORAGE_CLASS_STANDARD, $serverSideEncryption = self::SSE_NONE)
{
if ($input === false) return false;
$rest = new WPvivid_S3Request('PUT', $bucket, $uri, $this -> endpoint,$this);
if (!is_array($input)) $input = array(
'data' => $input, 'size' => strlen($input),
'md5sum' => base64_encode(md5($input, true))
);
// Data
if (isset($input['fp']))
$rest->fp =& $input['fp'];
elseif (isset($input['file']))
$rest->fp = @fopen($input['file'], 'rb');
elseif (isset($input['data']))
$rest->data = $input['data'];
// Content-Length (required)
if (isset($input['size']) && $input['size'] >= 0)
$rest->size = $input['size'];
else {
if (isset($input['file'])) {
clearstatcache(false, $input['file']);
$rest->size = filesize($input['file']);
}
elseif (isset($input['data']))
$rest->size = strlen($input['data']);
}
// Custom request headers (Content-Type, Content-Disposition, Content-Encoding)
if (is_array($requestHeaders))
foreach ($requestHeaders as $h => $v)
strpos($h, 'x-amz-') === 0 ? $rest->setAmzHeader($h, $v) : $rest->setHeader($h, $v);
elseif (is_string($requestHeaders)) // Support for legacy contentType parameter
$input['type'] = $requestHeaders;
// Content-Type
if (!isset($input['type']))
{
if (isset($requestHeaders['Content-Type']))
$input['type'] =& $requestHeaders['Content-Type'];
elseif (isset($input['file']))
$input['type'] = $this -> __getMIMEType($input['file']);
else
$input['type'] = 'application/octet-stream';
}
if ($this -> _storageClass !== self::STORAGE_CLASS_STANDARD) // Storage class
$rest->setAmzHeader('x-amz-storage-class', $this -> _storageClass);
if ($this -> _serverSideEncryption !== self::SSE_NONE) // Server-side encryption
$rest->setAmzHeader('x-amz-server-side-encryption', $this -> _serverSideEncryption);
// We need to post with Content-Length and Content-Type, MD5 is optional
if ($rest->size >= 0 && ($rest->fp !== false || $rest->data !== false))
{
$rest->setHeader('Content-Type', $input['type']);
if (isset($input['md5sum'])) $rest->setHeader('Content-MD5', $input['md5sum']);
$rest->setAmzHeader('x-amz-acl', $acl);
foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
$rest->getResponse();
} else
$rest->response->error = array('code' => 0, 'message' => 'Missing input parameters');
if ($rest->response->error === false && $rest->response->code !== 200)
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if ($rest->response->error !== false)
{
$this -> __triggerError(sprintf("S3::putObject(): [%s] %s",
$rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
/**
* Put an object from a file (legacy function)
*
* @param string $file Input file path
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param constant $acl ACL constant
* @param array $metaHeaders Array of x-amz-meta-* headers
* @param string $contentType Content type
* @return boolean
*/
public function putObjectFile($file, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = null)
{
return $this -> putObject($this -> inputFile($file), $bucket, $uri, $acl, $metaHeaders, $contentType);
}
/**
* Put an object from a string (legacy function)
*
* @param string $string Input data
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param constant $acl ACL constant
* @param array $metaHeaders Array of x-amz-meta-* headers
* @param string $contentType Content type
* @return boolean
*/
public function putObjectString($string, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $contentType = 'text/plain')
{
return $this -> putObject($string, $bucket, $uri, $acl, $metaHeaders, $contentType);
}
/**
* Get an object
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param mixed $saveTo Filename or resource to write to
* @return mixed
*/
public function getObject($bucket, $uri, $saveTo = false)
{
$rest = new WPvivid_S3Request('GET', $bucket, $uri, $this -> endpoint,$this);
if ($saveTo !== false)
{
if (is_resource($saveTo))
$rest->fp =& $saveTo;
else
if (($rest->fp = @fopen($saveTo, 'wb')) !== false)
$rest->file = realpath($saveTo);
else
$rest->response->error = array('code' => 0, 'message' => 'Unable to open save file for writing: '.$saveTo);
}
if ($rest->response->error === false) $rest->getResponse();
if ($rest->response->error === false && $rest->response->code !== 200)
$rest->response->error = array('code' => $rest->response->code, 'message' => 'Unexpected HTTP status');
if ($rest->response->error !== false)
{
$this -> __triggerError(sprintf("S3::getObject({$bucket}, {$uri}): [%s] %s",
$rest->response->error['code'], $rest->response->error['message']), __FILE__, __LINE__);
return false;
}
return $rest->response;
}
/**
* Get object information
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param boolean $returnInfo Return response information
* @return mixed | false
*/
public function getObjectInfo($bucket, $uri, $returnInfo = true)
{
$rest = new WPvivid_S3Request('HEAD', $bucket, $uri, $this -> endpoint,$this);
$rest = $rest->getResponse();
if ($rest->error === false && ($rest->code !== 200 && $rest->code !== 404))
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::getObjectInfo({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return $rest->code == 200 ? $returnInfo ? $rest->headers : true : false;
}
/**
* Copy an object
*
* @param string $srcBucket Source bucket name
* @param string $srcUri Source object URI
* @param string $bucket Destination bucket name
* @param string $uri Destination object URI
* @param constant $acl ACL constant
* @param array $metaHeaders Optional array of x-amz-meta-* headers
* @param array $requestHeaders Optional array of request headers (content type, disposition, etc.)
* @param constant $storageClass Storage class constant
* @return mixed | false
*/
public function copyObject($srcBucket, $srcUri, $bucket, $uri, $acl = self::ACL_PRIVATE, $metaHeaders = array(), $requestHeaders = array(), $storageClass = self::STORAGE_CLASS_STANDARD)
{
$rest = new WPvivid_S3Request('PUT', $bucket, $uri, $this -> endpoint,$this);
$rest->setHeader('Content-Length', 0);
foreach ($requestHeaders as $h => $v)
strpos($h, 'x-amz-') === 0 ? $rest->setAmzHeader($h, $v) : $rest->setHeader($h, $v);
foreach ($metaHeaders as $h => $v) $rest->setAmzHeader('x-amz-meta-'.$h, $v);
if ($storageClass !== self::STORAGE_CLASS_STANDARD) // Storage class
$rest->setAmzHeader('x-amz-storage-class', $storageClass);
$rest->setAmzHeader('x-amz-acl', $acl);
$rest->setAmzHeader('x-amz-copy-source', sprintf('/%s/%s', $srcBucket, rawurlencode($srcUri)));
if (sizeof($requestHeaders) > 0 || sizeof($metaHeaders) > 0)
$rest->setAmzHeader('x-amz-metadata-directive', 'REPLACE');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::copyObject({$srcBucket}, {$srcUri}, {$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return isset($rest->body->LastModified, $rest->body->ETag) ? array(
'time' => strtotime((string)$rest->body->LastModified),
'hash' => substr((string)$rest->body->ETag, 1, -1)
) : false;
}
/**
* Set up a bucket redirection
*
* @param string $bucket Bucket name
* @param string $location Target host name
* @return boolean
*/
public function setBucketRedirect($bucket = NULL, $location = NULL)
{
$rest = new WPvivid_S3Request('PUT', $bucket, '', $this -> endpoint,$this);
if( empty($bucket) || empty($location) ) {
$this -> __triggerError("S3::setBucketRedirect({$bucket}, {$location}): Empty parameter.", __FILE__, __LINE__);
return false;
}
$dom = new DOMDocument;
$websiteConfiguration = $dom->createElement('WebsiteConfiguration');
$redirectAllRequestsTo = $dom->createElement('RedirectAllRequestsTo');
$hostName = $dom->createElement('HostName', $location);
$redirectAllRequestsTo->appendChild($hostName);
$websiteConfiguration->appendChild($redirectAllRequestsTo);
$dom->appendChild($websiteConfiguration);
$rest->setParameter('website', null);
$rest->data = $dom->saveXML();
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::setBucketRedirect({$bucket}, {$location}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
/**
* Set logging for a bucket
*
* @param string $bucket Bucket name
* @param string $targetBucket Target bucket (where logs are stored)
* @param string $targetPrefix Log prefix (e,g; domain.com-)
* @return boolean
*/
public function setBucketLogging($bucket, $targetBucket, $targetPrefix = null)
{
// The S3 log delivery group has to be added to the target bucket's ACP
if ($targetBucket !== null && ($acp = $this -> getAccessControlPolicy($targetBucket, '')) !== false)
{
// Only add permissions to the target bucket when they do not exist
$aclWriteSet = false;
$aclReadSet = false;
foreach ($acp['acl'] as $acl)
if ($acl['type'] == 'Group' && $acl['uri'] == 'http://acs.amazonaws.com/groups/s3/LogDelivery')
{
if ($acl['permission'] == 'WRITE') $aclWriteSet = true;
elseif ($acl['permission'] == 'READ_ACP') $aclReadSet = true;
}
if (!$aclWriteSet) $acp['acl'][] = array(
'type' => 'Group', 'uri' => 'http://acs.amazonaws.com/groups/s3/LogDelivery', 'permission' => 'WRITE'
);
if (!$aclReadSet) $acp['acl'][] = array(
'type' => 'Group', 'uri' => 'http://acs.amazonaws.com/groups/s3/LogDelivery', 'permission' => 'READ_ACP'
);
if (!$aclReadSet || !$aclWriteSet) $this -> setAccessControlPolicy($targetBucket, '', $acp);
}
$dom = new DOMDocument;
$bucketLoggingStatus = $dom->createElement('BucketLoggingStatus');
$bucketLoggingStatus->setAttribute('xmlns', 'http://s3.amazonaws.com/doc/2006-03-01/');
if ($targetBucket !== null)
{
if ($targetPrefix == null) $targetPrefix = $bucket . '-';
$loggingEnabled = $dom->createElement('LoggingEnabled');
$loggingEnabled->appendChild($dom->createElement('TargetBucket', $targetBucket));
$loggingEnabled->appendChild($dom->createElement('TargetPrefix', $targetPrefix));
// TODO: Add TargetGrants?
$bucketLoggingStatus->appendChild($loggingEnabled);
}
$dom->appendChild($bucketLoggingStatus);
$rest = new WPvivid_S3Request('PUT', $bucket, '', $this -> endpoint,$this);
$rest->setParameter('logging', null);
$rest->data = $dom->saveXML();
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::setBucketLogging({$bucket}, {$targetBucket}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
/**
* Get logging status for a bucket
*
* This will return false if logging is not enabled.
* Note: To enable logging, you also need to grant write access to the log group
*
* @param string $bucket Bucket name
* @return array | false
*/
public function getBucketLogging($bucket)
{
$rest = new WPvivid_S3Request('GET', $bucket, '', $this -> endpoint,$this);
$rest->setParameter('logging', null);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::getBucketLogging({$bucket}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
if (!isset($rest->body->LoggingEnabled)) return false; // No logging
return array(
'targetBucket' => (string)$rest->body->LoggingEnabled->TargetBucket,
'targetPrefix' => (string)$rest->body->LoggingEnabled->TargetPrefix,
);
}
/**
* Disable bucket logging
*
* @param string $bucket Bucket name
* @return boolean
*/
public function disableBucketLogging($bucket)
{
return $this -> setBucketLogging($bucket, null);
}
/**
* Get a bucket's location
*
* @param string $bucket Bucket name
* @return string | false
*/
public function getBucketLocation($bucket)
{
$rest = new WPvivid_S3Request('GET', $bucket, '', $this -> endpoint,$this);
$rest->setParameter('location', null);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::getBucketLocation({$bucket}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return (isset($rest->body[0]) && (string)$rest->body[0] !== '') ? (string)$rest->body[0] : 'us-east-1';
}
/**
* Set object or bucket Access Control Policy
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param array $acp Access Control Policy Data (same as the data returned from getAccessControlPolicy)
* @return boolean
*/
public function setAccessControlPolicy($bucket, $uri = '', $acp = array())
{
$dom = new DOMDocument;
$dom->formatOutput = true;
$accessControlPolicy = $dom->createElement('AccessControlPolicy');
$accessControlList = $dom->createElement('AccessControlList');
// It seems the owner has to be passed along too
$owner = $dom->createElement('Owner');
$owner->appendChild($dom->createElement('ID', $acp['owner']['id']));
$owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name']));
$accessControlPolicy->appendChild($owner);
foreach ($acp['acl'] as $g)
{
$grant = $dom->createElement('Grant');
$grantee = $dom->createElement('Grantee');
$grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
if (isset($g['id']))
{ // CanonicalUser (DisplayName is omitted)
$grantee->setAttribute('xsi:type', 'CanonicalUser');
$grantee->appendChild($dom->createElement('ID', $g['id']));
}
elseif (isset($g['email']))
{ // AmazonCustomerByEmail
$grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail');
$grantee->appendChild($dom->createElement('EmailAddress', $g['email']));
}
elseif ($g['type'] == 'Group')
{ // Group
$grantee->setAttribute('xsi:type', 'Group');
$grantee->appendChild($dom->createElement('URI', $g['uri']));
}
$grant->appendChild($grantee);
$grant->appendChild($dom->createElement('Permission', $g['permission']));
$accessControlList->appendChild($grant);
}
$accessControlPolicy->appendChild($accessControlList);
$dom->appendChild($accessControlPolicy);
$rest = new WPvivid_S3Request('PUT', $bucket, $uri, $this -> endpoint,$this);
$rest->setParameter('acl', null);
$rest->data = $dom->saveXML();
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
/**
* Get object or bucket Access Control Policy
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @return mixed | false
*/
public function getAccessControlPolicy($bucket, $uri = '')
{
$rest = new WPvivid_S3Request('GET', $bucket, $uri, $this -> endpoint,$this);
$rest->setParameter('acl', null);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::getAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
$acp = array();
if (isset($rest->body->Owner, $rest->body->Owner->ID, $rest->body->Owner->DisplayName))
$acp['owner'] = array(
'id' => (string)$rest->body->Owner->ID, 'name' => (string)$rest->body->Owner->DisplayName
);
if (isset($rest->body->AccessControlList))
{
$acp['acl'] = array();
foreach ($rest->body->AccessControlList->Grant as $grant)
{
foreach ($grant->Grantee as $grantee)
{
if (isset($grantee->ID, $grantee->DisplayName)) // CanonicalUser
$acp['acl'][] = array(
'type' => 'CanonicalUser',
'id' => (string)$grantee->ID,
'name' => (string)$grantee->DisplayName,
'permission' => (string)$grant->Permission
);
elseif (isset($grantee->EmailAddress)) // AmazonCustomerByEmail
$acp['acl'][] = array(
'type' => 'AmazonCustomerByEmail',
'email' => (string)$grantee->EmailAddress,
'permission' => (string)$grant->Permission
);
elseif (isset($grantee->URI)) // Group
$acp['acl'][] = array(
'type' => 'Group',
'uri' => (string)$grantee->URI,
'permission' => (string)$grant->Permission
);
else continue;
}
}
}
return $acp;
}
/**
* Delete an object
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @return boolean
*/
public function deleteObject($bucket, $uri)
{
$rest = new WPvivid_S3Request('DELETE', $bucket, $uri, $this -> endpoint,$this);
$rest = $rest->getResponse();
if ($rest->error === false && $rest->code !== 204)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::deleteObject(): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
/**
* Get a query string authenticated URL
*
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param integer $lifetime Lifetime in seconds
* @param boolean $hostBucket Use the bucket name as the hostname
* @param boolean $https Use HTTPS ($hostBucket should be false for SSL verification)
* @return string
*/
public function getAuthenticatedURL($bucket, $uri, $lifetime, $hostBucket = false, $https = false)
{
$expires = $this -> __getTime() + $lifetime;
$uri = str_replace(array('%2F', '%2B'), array('/', '+'), rawurlencode($uri));
return sprintf(($https ? 'https' : 'http').'://%s/%s?AWSAccessKeyId=%s&Expires=%u&Signature=%s',
// $hostBucket ? $bucket : $bucket.'.s3.amazonaws.com', $uri, self::$__accessKey, $expires,
$hostBucket ? $bucket : $this -> endpoint.'/'.$bucket, $uri, $this -> __accessKey, $expires,
urlencode($this -> __getHash("GET\n\n\n{$expires}\n/{$bucket}/{$uri}")));
}
/**
* Get a CloudFront signed policy URL
*
* @param array $policy Policy
* @return string
*/
public function getSignedPolicyURL($policy)
{
$data = wp_json_encode($policy);
$signature = '';
if (!openssl_sign($data, $signature, $this -> __signingKeyResource)) return false;
$encoded = str_replace(array('+', '='), array('-', '_', '~'), base64_encode($data));
$signature = str_replace(array('+', '='), array('-', '_', '~'), base64_encode($signature));
$url = $policy['Statement'][0]['Resource'] . '?';
foreach (array('Policy' => $encoded, 'Signature' => $signature, 'Key-Pair-Id' => $this -> __signingKeyPairId) as $k => $v)
$url .= $k.'='.str_replace('%2F', '/', rawurlencode($v)).'&';
return substr($url, 0, -1);
}
/**
* Get a CloudFront canned policy URL
*
* @param string $url URL to sign
* @param integer $lifetime URL lifetime
* @return string
*/
public function getSignedCannedURL($url, $lifetime)
{
return $this -> getSignedPolicyURL(array(
'Statement' => array(
array('Resource' => $url, 'Condition' => array(
'DateLessThan' => array('AWS:EpochTime' => $this -> __getTime() + $lifetime)
))
)
));
}
/**
* Get upload POST parameters for form uploads
*
* @param string $bucket Bucket name
* @param string $uriPrefix Object URI prefix
* @param constant $acl ACL constant
* @param integer $lifetime Lifetime in seconds
* @param integer $maxFileSize Maximum filesize in bytes (default 5MB)
* @param string $successRedirect Redirect URL or 200 / 201 status code
* @param array $amzHeaders Array of x-amz-meta-* headers
* @param array $headers Array of request headers or content type as a string
* @param boolean $flashVars Includes additional "Filename" variable posted by Flash
* @return object
*/
public function getHttpUploadPostParams($bucket, $uriPrefix = '', $acl = self::ACL_PRIVATE, $lifetime = 3600,
$maxFileSize = 5242880, $successRedirect = "201", $amzHeaders = array(), $headers = array(), $flashVars = false)
{
// Create policy object
$policy = new stdClass;
$policy->expiration = gmdate('Y-m-d\TH:i:s\Z', ($this -> __getTime() + $lifetime));
$policy->conditions = array();
$obj = new stdClass; $obj->bucket = $bucket; array_push($policy->conditions, $obj);
$obj = new stdClass; $obj->acl = $acl; array_push($policy->conditions, $obj);
$obj = new stdClass; // 200 for non-redirect uploads
if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
$obj->success_action_status = (string)$successRedirect;
else // URL
$obj->success_action_redirect = $successRedirect;
array_push($policy->conditions, $obj);
if ($acl !== self::ACL_PUBLIC_READ)
array_push($policy->conditions, array('eq', '$acl', $acl));
array_push($policy->conditions, array('starts-with', '$key', $uriPrefix));
if ($flashVars) array_push($policy->conditions, array('starts-with', '$Filename', ''));
foreach (array_keys($headers) as $headerKey)
array_push($policy->conditions, array('starts-with', '$'.$headerKey, ''));
foreach ($amzHeaders as $headerKey => $headerVal)
{
$obj = new stdClass;
$obj->{$headerKey} = (string)$headerVal;
array_push($policy->conditions, $obj);
}
array_push($policy->conditions, array('content-length-range', 0, $maxFileSize));
$policy = base64_encode(str_replace('\/', '/', wp_json_encode($policy)));
// Create parameters
$params = new stdClass;
$params->AWSAccessKeyId = $this -> __accessKey;
$params->key = $uriPrefix.'${filename}';
$params->acl = $acl;
$params->policy = $policy; unset($policy);
$params->signature = $this -> __getHash($params->policy);
if (is_numeric($successRedirect) && in_array((int)$successRedirect, array(200, 201)))
$params->success_action_status = (string)$successRedirect;
else
$params->success_action_redirect = $successRedirect;
foreach ($headers as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
foreach ($amzHeaders as $headerKey => $headerVal) $params->{$headerKey} = (string)$headerVal;
return $params;
}
/**
* Create a CloudFront distribution
*
* @param string $bucket Bucket name
* @param boolean $enabled Enabled (true/false)
* @param array $cnames Array containing CNAME aliases
* @param string $comment Use the bucket name as the hostname
* @param string $defaultRootObject Default root object
* @param string $originAccessIdentity Origin access identity
* @param array $trustedSigners Array of trusted signers
* @return array | false
*/
public function createDistribution($bucket, $enabled = true, $cnames = array(), $comment = null, $defaultRootObject = null, $originAccessIdentity = null, $trustedSigners = array())
{
if (!extension_loaded('openssl'))
{
$this -> __triggerError(sprintf("S3::createDistribution({$bucket}, ".(int)$enabled.", [], '$comment'): %s",
"CloudFront functionality requires SSL"), __FILE__, __LINE__);
return false;
}
$useSSL = $this -> useSSL;
$this -> useSSL = true; // CloudFront requires SSL
$rest = new WPvivid_S3Request('POST', '', '2010-11-01/distribution', 'cloudfront.amazonaws.com',$this);
$rest->data = $this -> __getCloudFrontDistributionConfigXML(
$bucket.'.s3.amazonaws.com',
$enabled,
(string)$comment,
(string)microtime(true),
$cnames,
$defaultRootObject,
$originAccessIdentity,
$trustedSigners
);
$rest->size = strlen($rest->data);
$rest->setHeader('Content-Type', 'application/xml');
$rest = $this -> __getCloudFrontResponse($rest);
$this -> useSSL = $useSSL;
if ($rest->error === false && $rest->code !== 201)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::createDistribution({$bucket}, ".(int)$enabled.", [], '$comment'): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
} elseif ($rest->body instanceof SimpleXMLElement)
return $this -> __parseCloudFrontDistributionConfig($rest->body);
return false;
}
/**
* Get CloudFront distribution info
*
* @param string $distributionId Distribution ID from listDistributions()
* @return array | false
*/
public function getDistribution($distributionId)
{
if (!extension_loaded('openssl'))
{
$this -> __triggerError(sprintf("S3::getDistribution($distributionId): %s",
"CloudFront functionality requires SSL"), __FILE__, __LINE__);
return false;
}
$useSSL = $this -> useSSL;
$this -> useSSL = true; // CloudFront requires SSL
$rest = new WPvivid_S3Request('GET', '', '2010-11-01/distribution/'.$distributionId, 'cloudfront.amazonaws.com',$this);
$rest = $this -> __getCloudFrontResponse($rest);
$this -> useSSL = $useSSL;
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::getDistribution($distributionId): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
elseif ($rest->body instanceof SimpleXMLElement)
{
$dist = $this -> __parseCloudFrontDistributionConfig($rest->body);
$dist['hash'] = $rest->headers['hash'];
$dist['id'] = $distributionId;
return $dist;
}
return false;
}
/**
* Update a CloudFront distribution
*
* @param array $dist Distribution array info identical to output of getDistribution()
* @return array | false
*/
public function updateDistribution($dist)
{
if (!extension_loaded('openssl'))
{
$this -> __triggerError(sprintf("S3::updateDistribution({$dist['id']}): %s",
"CloudFront functionality requires SSL"), __FILE__, __LINE__);
return false;
}
$useSSL = $this -> useSSL;
$this -> useSSL = true; // CloudFront requires SSL
$rest = new WPvivid_S3Request('PUT', '', '2010-11-01/distribution/'.$dist['id'].'/config', 'cloudfront.amazonaws.com',$this);
$rest->data = $this -> __getCloudFrontDistributionConfigXML(
$dist['origin'],
$dist['enabled'],
$dist['comment'],
$dist['callerReference'],
$dist['cnames'],
$dist['defaultRootObject'],
$dist['originAccessIdentity'],
$dist['trustedSigners']
);
$rest->size = strlen($rest->data);
$rest->setHeader('If-Match', $dist['hash']);
$rest = $this -> __getCloudFrontResponse($rest);
$this -> useSSL = $useSSL;
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::updateDistribution({$dist['id']}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
} else {
$dist = $this -> __parseCloudFrontDistributionConfig($rest->body);
$dist['hash'] = $rest->headers['hash'];
return $dist;
}
return false;
}
/**
* Delete a CloudFront distribution
*
* @param array $dist Distribution array info identical to output of getDistribution()
* @return boolean
*/
public function deleteDistribution($dist)
{
if (!extension_loaded('openssl'))
{
$this -> __triggerError(sprintf("S3::deleteDistribution({$dist['id']}): %s",
"CloudFront functionality requires SSL"), __FILE__, __LINE__);
return false;
}
$useSSL = $this -> useSSL;
$this -> useSSL = true; // CloudFront requires SSL
$rest = new WPvivid_S3Request('DELETE', '', '2008-06-30/distribution/'.$dist['id'], 'cloudfront.amazonaws.com',$this);
$rest->setHeader('If-Match', $dist['hash']);
$rest = $this -> __getCloudFrontResponse($rest);
$this -> useSSL = $useSSL;
if ($rest->error === false && $rest->code !== 204)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::deleteDistribution({$dist['id']}): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
return true;
}
/**
* Get a list of CloudFront distributions
*
* @return array
*/
public function listDistributions()
{
if (!extension_loaded('openssl'))
{
$this -> __triggerError(sprintf("S3::listDistributions(): [%s] %s",
"CloudFront functionality requires SSL"), __FILE__, __LINE__);
return false;
}
$useSSL =$this -> useSSL;
$this -> useSSL = true; // CloudFront requires SSL
$rest = new WPvivid_S3Request('GET', '', '2010-11-01/distribution', 'cloudfront.amazonaws.com',$this);
$rest = self::__getCloudFrontResponse($rest);
$this -> useSSL = $useSSL;
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
$this -> __triggerError(sprintf("S3::listDistributions(): [%s] %s",
$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
return false;
}
elseif ($rest->body instanceof SimpleXMLElement && isset($rest->body->DistributionSummary))
{
$list = array();
if (isset($rest->body->Marker, $rest->body->MaxItems, $rest->body->IsTruncated))
{
//$info['marker'] = (string)$rest->body->Marker;
//$info['maxItems'] = (int)$rest->body->MaxItems;
//$info['isTruncated'] = (string)$rest->body->IsTruncated == 'true' ? true : false;
}
foreach ($rest->body->DistributionSummary as $summary)
$list[(string)$summary->Id] = self::__parseCloudFrontDistributionConfig($summary);
return $list;
}
return array();
}
/**
* List CloudFront Origin Access Identities
*
* @return array
*/
public function listOriginAccessIdentities()
{
if (!extension_loaded('openssl'))
{
$this -> __triggerError(sprintf("S3::listOriginAccessIdentities(): [%s] %s",
"CloudFront functionality requires SSL"), __FILE__, __LINE__);
return false;
}
$this -> useSSL = true; // CloudFront requires SSL
$rest = new WPvivid_S3Request('GET', '', '2010-11-01/origin-access-identity/cloudfront', 'cloudfront.amazonaws.com',$this);
$rest = self::__getCloudFrontResponse($rest);
$useSSL = $this -> useSSL;
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
trigger_error(sprintf("S3::listOriginAccessIdentities(): [%s] %s",
esc_attr($rest->error['code']), esc_html($rest->error['message'])), E_USER_WARNING);
return false;
}
if (isset($rest->body->CloudFrontOriginAccessIdentitySummary))
{
$identities = array();
foreach ($rest->body->CloudFrontOriginAccessIdentitySummary as $identity)
if (isset($identity->S3CanonicalUserId))
$identities[(string)$identity->Id] = array('id' => (string)$identity->Id, 's3CanonicalUserId' => (string)$identity->S3CanonicalUserId);
return $identities;
}
return false;
}
/**
* Invalidate objects in a CloudFront distribution
*
* Thanks to Martin Lindkvist for S3::invalidateDistribution()
*
* @param string $distributionId Distribution ID from listDistributions()
* @param array $paths Array of object paths to invalidate
* @return boolean
*/
public function invalidateDistribution($distributionId, $paths)
{
if (!extension_loaded('openssl'))
{
$this -> __triggerError(sprintf("S3::invalidateDistribution(): [%s] %s",
"CloudFront functionality requires SSL"), __FILE__, __LINE__);
return false;
}
$useSSL = $this -> useSSL;
$this -> useSSL = true; // CloudFront requires SSL
$rest = new WPvivid_S3Request('POST', '', '2010-08-01/distribution/'.$distributionId.'/invalidation', 'cloudfront.amazonaws.com',$this);
$rest->data = self::__getCloudFrontInvalidationBatchXML($paths, (string)microtime(true));
$rest->size = strlen($rest->data);
$rest = self::__getCloudFrontResponse($rest);
$this -> useSSL = $useSSL;
if ($rest->error === false && $rest->code !== 201)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
trigger_error(esc_html(sprintf("S3::invalidate('{$distributionId}',{$paths}): [%s] %s",
$rest->error['code'], $rest->error['message'])), E_USER_WARNING);
return false;
}
return true;
}
/**
* Get a InvalidationBatch DOMDocument
*
* @internal Used to create XML in invalidateDistribution()
* @param array $paths Paths to objects to invalidateDistribution
* @param int $callerReference
* @return string
*/
private function __getCloudFrontInvalidationBatchXML($paths, $callerReference = '0')
{
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$invalidationBatch = $dom->createElement('InvalidationBatch');
foreach ($paths as $path)
$invalidationBatch->appendChild($dom->createElement('Path', $path));
$invalidationBatch->appendChild($dom->createElement('CallerReference', $callerReference));
$dom->appendChild($invalidationBatch);
return $dom->saveXML();
}
/**
* List your invalidation batches for invalidateDistribution() in a CloudFront distribution
*
* http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/ListInvalidation.html
* returned array looks like this:
* Array
* (
* [I31TWB0CN9V6XD] => InProgress
* [IT3TFE31M0IHZ] => Completed
* [I12HK7MPO1UQDA] => Completed
* [I1IA7R6JKTC3L2] => Completed
* )
*
* @param string $distributionId Distribution ID from listDistributions()
* @return array
*/
public function getDistributionInvalidationList($distributionId)
{
if (!extension_loaded('openssl'))
{
$this -> __triggerError(sprintf("S3::getDistributionInvalidationList(): [%s] %s",
"CloudFront functionality requires SSL"), __FILE__, __LINE__);
return false;
}
$useSSL = $this -> useSSL;
$this -> useSSL = true; // CloudFront requires SSL
$rest = new WPvivid_S3Request('GET', '', '2010-11-01/distribution/'.$distributionId.'/invalidation', 'cloudfront.amazonaws.com',$this);
$rest = $this -> __getCloudFrontResponse($rest);
$this -> useSSL = $useSSL;
if ($rest->error === false && $rest->code !== 200)
$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
if ($rest->error !== false)
{
trigger_error(esc_html(sprintf("S3::getDistributionInvalidationList('{$distributionId}'): [%s]",
$rest->error['code'], $rest->error['message'])), E_USER_WARNING);
return false;
}
elseif ($rest->body instanceof SimpleXMLElement && isset($rest->body->InvalidationSummary))
{
$list = array();
foreach ($rest->body->InvalidationSummary as $summary)
$list[(string)$summary->Id] = (string)$summary->Status;
return $list;
}
return array();
}
/**
* Get a DistributionConfig DOMDocument
*
* http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/index.html?PutConfig.html
*
* @internal Used to create XML in createDistribution() and updateDistribution()
* @param string $bucket S3 Origin bucket
* @param boolean $enabled Enabled (true/false)
* @param string $comment Comment to append
* @param string $callerReference Caller reference
* @param array $cnames Array of CNAME aliases
* @param string $defaultRootObject Default root object
* @param string $originAccessIdentity Origin access identity
* @param array $trustedSigners Array of trusted signers
* @return string
*/
private function __getCloudFrontDistributionConfigXML($bucket, $enabled, $comment, $callerReference = '0', $cnames = array(), $defaultRootObject = null, $originAccessIdentity = null, $trustedSigners = array())
{
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$distributionConfig = $dom->createElement('DistributionConfig');
$distributionConfig->setAttribute('xmlns', 'http://cloudfront.amazonaws.com/doc/2010-11-01/');
$origin = $dom->createElement('S3Origin');
$origin->appendChild($dom->createElement('DNSName', $bucket));
if ($originAccessIdentity !== null) $origin->appendChild($dom->createElement('OriginAccessIdentity', $originAccessIdentity));
$distributionConfig->appendChild($origin);
if ($defaultRootObject !== null) $distributionConfig->appendChild($dom->createElement('DefaultRootObject', $defaultRootObject));
$distributionConfig->appendChild($dom->createElement('CallerReference', $callerReference));
foreach ($cnames as $cname)
$distributionConfig->appendChild($dom->createElement('CNAME', $cname));
if ($comment !== '') $distributionConfig->appendChild($dom->createElement('Comment', $comment));
$distributionConfig->appendChild($dom->createElement('Enabled', $enabled ? 'true' : 'false'));
$trusted = $dom->createElement('TrustedSigners');
foreach ($trustedSigners as $id => $type)
$trusted->appendChild($id !== '' ? $dom->createElement($type, $id) : $dom->createElement($type));
$distributionConfig->appendChild($trusted);
$dom->appendChild($distributionConfig);
//var_dump($dom->saveXML());
return $dom->saveXML();
}
/**
* Parse a CloudFront distribution config
*
* See http://docs.amazonwebservices.com/AmazonCloudFront/latest/APIReference/index.html?GetDistribution.html
*
* @internal Used to parse the CloudFront DistributionConfig node to an array
* @param object &$node DOMNode
* @return array
*/
private function __parseCloudFrontDistributionConfig(&$node)
{
if (isset($node->DistributionConfig))
return $this -> __parseCloudFrontDistributionConfig($node->DistributionConfig);
$dist = array();
if (isset($node->Id, $node->Status, $node->LastModifiedTime, $node->DomainName))
{
$dist['id'] = (string)$node->Id;
$dist['status'] = (string)$node->Status;
$dist['time'] = strtotime((string)$node->LastModifiedTime);
$dist['domain'] = (string)$node->DomainName;
}
if (isset($node->CallerReference))
$dist['callerReference'] = (string)$node->CallerReference;
if (isset($node->Enabled))
$dist['enabled'] = (string)$node->Enabled == 'true' ? true : false;
if (isset($node->S3Origin))
{
if (isset($node->S3Origin->DNSName))
$dist['origin'] = (string)$node->S3Origin->DNSName;
$dist['originAccessIdentity'] = isset($node->S3Origin->OriginAccessIdentity) ?
(string)$node->S3Origin->OriginAccessIdentity : null;
}
$dist['defaultRootObject'] = isset($node->DefaultRootObject) ? (string)$node->DefaultRootObject : null;
$dist['cnames'] = array();
if (isset($node->CNAME))
foreach ($node->CNAME as $cname)
$dist['cnames'][(string)$cname] = (string)$cname;
$dist['trustedSigners'] = array();
if (isset($node->TrustedSigners))
foreach ($node->TrustedSigners as $signer)
{
if (isset($signer->Self))
$dist['trustedSigners'][''] = 'Self';
elseif (isset($signer->KeyPairId))
$dist['trustedSigners'][(string)$signer->KeyPairId] = 'KeyPairId';
elseif (isset($signer->AwsAccountNumber))
$dist['trustedSigners'][(string)$signer->AwsAccountNumber] = 'AwsAccountNumber';
}
$dist['comment'] = isset($node->Comment) ? (string)$node->Comment : null;
return $dist;
}
/**
* Grab CloudFront response
*
* @internal Used to parse the CloudFront WPvivid_S3Request::getResponse() output
* @param object &$rest WPvivid_S3Request instance
* @return object
*/
private function __getCloudFrontResponse(&$rest)
{
$rest->getResponse();
if ($rest->response->error === false && isset($rest->response->body) &&
is_string($rest->response->body) && substr($rest->response->body, 0, 5) == '<?xml')
{
$rest->response->body = simplexml_load_string($rest->response->body);
// Grab CloudFront errors
if (isset($rest->response->body->Error, $rest->response->body->Error->Code,
$rest->response->body->Error->Message))
{
$rest->response->error = array(
'code' => (string)$rest->response->body->Error->Code,
'message' => (string)$rest->response->body->Error->Message
);
unset($rest->response->body);
}
}
return $rest->response;
}
/**
* Get MIME type for file
*
* To override the putObject() Content-Type, add it to $requestHeaders
*
* To use fileinfo, ensure the MAGIC environment variable is set
*
* @internal Used to get mime types
* @param string &$file File path
* @return string
*/
private function __getMIMEType(&$file)
{
$exts = array(
'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif',
'png' => 'image/png', 'ico' => 'image/x-icon', 'pdf' => 'application/pdf',
'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'svg' => 'image/svg+xml',
'svgz' => 'image/svg+xml', 'swf' => 'application/x-shockwave-flash',
'zip' => 'application/zip', 'gz' => 'application/x-gzip',
'tar' => 'application/x-tar', 'bz' => 'application/x-bzip',
'bz2' => 'application/x-bzip2', 'rar' => 'application/x-rar-compressed',
'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload',
'cab' => 'application/vnd.ms-cab-compressed', 'txt' => 'text/plain',
'asc' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html',
'css' => 'text/css', 'js' => 'text/javascript',
'xml' => 'text/xml', 'xsl' => 'application/xsl+xml',
'ogg' => 'application/ogg', 'mp3' => 'audio/mpeg', 'wav' => 'audio/x-wav',
'avi' => 'video/x-msvideo', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg',
'mov' => 'video/quicktime', 'flv' => 'video/x-flv', 'php' => 'text/x-php'
);
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if (isset($exts[$ext])) return $exts[$ext];
// Use fileinfo if available
if (extension_loaded('fileinfo') && isset($_ENV['MAGIC']) &&
($finfo = finfo_open(FILEINFO_MIME, $_ENV['MAGIC'])) !== false)
{
if (($type = finfo_file($finfo, $file)) !== false)
{
// Remove the charset and grab the last content-type
$type = explode(' ', str_replace('; charset=', ';charset=', $type));
$type = array_pop($type);
$type = explode(';', $type);
$type = trim(array_shift($type));
}
finfo_close($finfo);
if ($type !== false && strlen($type) > 0) return $type;
}
return 'application/octet-stream';
}
/**
* Get the current time
*
* @internal Used to apply offsets to sytem time
* @return integer
*/
public function __getTime()
{
return time() + $this -> __timeOffset;
}
/**
* Generate the auth string: "AWS AccessKey:Signature"
*
* @internal Used by WPvivid_S3Request::getResponse()
* @param string $string String to sign
* @return string
*/
public function __getSignature($string)
{
return 'AWS '.$this -> __accessKey.':'.$this -> __getHash($string);
}
/**
* Creates a HMAC-SHA1 hash
*
* This uses the hash extension if loaded
*
* @internal Used by __getSignature()
* @param string $string String to sign
* @return string
*/
private function __getHash($string)
{
return base64_encode(extension_loaded('hash') ?
hash_hmac('sha1', $string, $this -> __secretKey, true) : pack('H*', sha1(
(str_pad($this -> __secretKey, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
pack('H*', sha1((str_pad($this -> __secretKey, 64, chr(0x00)) ^
(str_repeat(chr(0x36), 64))) . $string)))));
}
/**
* Generate the headers for AWS Signature V4
*
* @internal Used by UpdraftPlus_S3Request::getResponse()
* @param array $aHeaders amzHeaders
* @param array $headers
* @param string $method
* @param string $uri
* @param string $data
*
* @return array $headers
*/
public function __getSignatureV4($aHeaders, $headers, $method = 'GET', $uri = '', $data = '') {// phpcs:ignore PHPCompatibility.FunctionNameRestrictions.ReservedFunctionNames.MethodDoubleUnderscore -- Method name "UpdraftPlus_S3Request::__responseHeaderCallback" is discouraged; PHP has reserved all method names with a double underscore prefix for future use.
$service = 's3';
$region = $this->getRegion();
$algorithm = 'AWS4-HMAC-SHA256';
$amzHeaders = array();
$amzRequests = array();
$amzDate = gmdate('Ymd\THis\Z');
$amzDateStamp = gmdate('Ymd');
// amz-date ISO8601 format? for aws request
$amzHeaders['x-amz-date'] = $amzDate;
// CanonicalHeaders
foreach ($headers as $k => $v) {
$amzHeaders[strtolower($k)] = trim($v);
}
foreach ($aHeaders as $k => $v) {
$amzHeaders[strtolower($k)] = trim($v);
}
uksort($amzHeaders, 'strcmp');
// payload
$payloadHash = isset($amzHeaders['x-amz-content-sha256']) ? $amzHeaders['x-amz-content-sha256'] : hash('sha256', $data);
// parameters
$parameters = array();
if (strpos($uri, '?')) {
list($uri, $query_str) = @explode('?', $uri);
parse_str($query_str, $parameters);
}
// Canonical Requests
$amzRequests[] = $method;
$uriQmPos = strpos($uri, '?');
$amzRequests[] = (false === $uriQmPos ? $uri : substr($uri, 0, $uriQmPos));
$amzRequests[] = http_build_query($parameters);
// add headers as string to requests
foreach ($amzHeaders as $k => $v) {
$amzRequests[] = $k . ':' . $v;
}
// add a blank entry so we end up with an extra line break
$amzRequests[] = '';
// SignedHeaders
$amzRequests[] = implode(';', array_keys($amzHeaders));
// payload hash
$amzRequests[] = $payloadHash;
// request as string
$amzRequestStr = implode("\n", $amzRequests);
// CredentialScope
$credentialScope = array();
$credentialScope[] = $amzDateStamp;
$credentialScope[] = $region;
$credentialScope[] = $service;
$credentialScope[] = 'aws4_request';
// stringToSign
$stringToSign = array();
$stringToSign[] = $algorithm;
$stringToSign[] = $amzDate;
$stringToSign[] = implode('/', $credentialScope);
$stringToSign[] = hash('sha256', $amzRequestStr);
// as string
$stringToSignStr = implode("\n", $stringToSign);
// Make Signature
$kSecret = 'AWS4' . $this->__secretKey;
$kDate = hash_hmac('sha256', $amzDateStamp, $kSecret, true);
$kRegion = hash_hmac('sha256', $region, $kDate, true);
$kService = hash_hmac('sha256', $service, $kRegion, true);
$kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);
$signature = hash_hmac('sha256', $stringToSignStr, $kSigning);
$authorization = array(
'Credential=' . $this->__accessKey . '/' . implode('/', $credentialScope),
'SignedHeaders=' . implode(';', array_keys($amzHeaders)),
'Signature=' . $signature,
);
$authorizationStr = $algorithm . ' ' . implode(',', $authorization);
$resultHeaders = array(
'X-AMZ-DATE' => $amzDate,
'Authorization' => $authorizationStr
);
if (!isset($aHeaders['x-amz-content-sha256'])) {
$resultHeaders['x-amz-content-sha256'] = $payloadHash;
}
return $resultHeaders;
}
}
/**
* S3 Request class
*
* @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class
* @version 0.5.0-dev
*/
final class WPvivid_S3Request
{
/**
* AWS URI
*
* @var string
* @access private
*/
private $endpoint;
/**
* Verb
*
* @var string
* @access private
*/
private $verb;
/**
* S3 bucket name
*
* @var string
* @access private
*/
private $bucket;
/**
* Object URI
*
* @var string
* @access private
*/
private $uri;
/**
* Final object URI
*
* @var string
* @access private
*/
private $resource = '';
/**
* Additional request parameters
*
* @var array
* @access private
*/
private $parameters = array();
/**
* Amazon specific request headers
*
* @var array
* @access private
*/
private $amzHeaders = array();
/**
* HTTP request headers
*
* @var array
* @access private
*/
private $headers = array(
'Host' => '', 'Date' => '', 'Content-MD5' => '', 'Content-Type' => ''
);
/**
* Use HTTP PUT?
*
* @var bool
* @access public
*/
public $fp = false;
/**
* PUT file size
*
* @var int
* @access public
*/
public $size = 0;
/**
* PUT post fields
*
* @var array
* @access public
*/
public $data = false;
/**
* S3 request respone
*
* @var object
* @access public
*/
public $response;
private $s3;
/**
* Constructor
*
* @param string $verb Verb
* @param string $bucket Bucket name
* @param string $uri Object URI
* @param string $endpoint AWS endpoint URI
* @return mixed
*/
function __construct($verb, $bucket = '', $uri = '', $endpoint = 's3.amazonaws.com', $s3 = null)
{
$this->endpoint = $endpoint;
$this->verb = $verb;
$this->bucket = $bucket;
$this->uri = $uri !== '' ? '/'.str_replace('%2F', '/', rawurlencode($uri)) : '/';
$this -> s3 = $s3;
if ($this->bucket !== '')
{
$this->headers['Host'] = $this->endpoint;
$this->uri = $this->uri;
if ($this->bucket !== '') $this->uri = '/'.$this->bucket.$this->uri;
$this->bucket = '';
$this->resource = $this->uri;
}
else
{
$this->headers['Host'] = $this->endpoint;
$this->resource = $this->uri;
}
$this->headers['Date'] = gmdate('D, d M Y H:i:s T');
$this->response = new STDClass;
$this->response->error = false;
$this->response->body = null;
$this->response->headers = array();
}
/**
* Set request parameter
*
* @param string $key Key
* @param string $value Value
* @return void
*/
public function setParameter($key, $value)
{
$this->parameters[$key] = $value;
}
public function unsetParameter($bucket)
{
if (sizeof($this->parameters) > 0) {
foreach ($this->parameters as $key => $value){
unset($this->parameters[$key]);
}
}
$this->uri = '/';
if ($bucket !== '')
{
$this->uri = '/'.$bucket.$this->uri;
}
}
/**
* Set request header
*
* @param string $key Key
* @param string $value Value
* @return void
*/
public function setHeader($key, $value)
{
$this->headers[$key] = $value;
}
/**
* Set x-amz-meta-* header
*
* @param string $key Key
* @param string $value Value
* @return void
*/
public function setAmzHeader($key, $value)
{
$this->amzHeaders[$key] = $value;
}
/**
* Get the S3 response
*
* @return object | false
*/
/*public function getResponse() {
$query = '';
if (sizeof($this->parameters) > 0) {
$query = ('?' !== substr($this->uri, -1)) ? '?' : '&';
foreach ($this->parameters as $var => $value)
if (null == $value || '' == $value) $query .= $var.'&';
else $query .= $var.'='.rawurlencode($value).'&';
$query = substr($query, 0, -1);
$this->uri .= $query;
if (array_key_exists('acl', $this->parameters) ||
array_key_exists('location', $this->parameters) ||
array_key_exists('torrent', $this->parameters) ||
array_key_exists('logging', $this->parameters) ||
array_key_exists('partNumber', $this->parameters) ||
array_key_exists('uploads', $this->parameters) ||
array_key_exists('uploadId', $this->parameters))
$this->resource .= $query;
}
$url = ($this->s3->useSSL ? 'https://' : 'http://') . ('' !== $this->headers['Host'] ? $this->headers['Host'] : $this->endpoint) . $this->uri;
//var_dump('bucket: ' . $this->bucket, 'uri: ' . $this->uri, 'resource: ' . $this->resource, 'url: ' . $url);
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php');
if ($this->s3->useSSL) {
// SSL Validation can now be optional for those with broken OpenSSL installations
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->s3->useSSLValidation ? 2 : 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->s3->useSSLValidation ? 1 : 0);
if (null !== $this->s3->sslKey) curl_setopt($curl, CURLOPT_SSLKEY, $this->s3->sslKey);
if (null !== $this->s3->sslCert) curl_setopt($curl, CURLOPT_SSLCERT, $this->s3->sslCert);
if (null !== $this->s3->sslCACert) curl_setopt($curl, CURLOPT_CAINFO, $this->s3->sslCACert);
}
curl_setopt($curl, CURLOPT_URL, $url);
// Headers
$headers = array(); $amz = array();
foreach ($this->amzHeaders as $header => $value)
if (strlen($value) > 0) $headers[] = $header.': '.$value;
foreach ($this->headers as $header => $value)
if (strlen($value) > 0) $headers[] = $header . ': ' . $value;
// Collect AMZ headers for signature
foreach ($this->amzHeaders as $header => $value)
if (strlen($value) > 0) $amz[] = strtolower($header).':'.$value;
// AMZ headers must be sorted
if (sizeof($amz) > 0) {
//sort($amz);
usort($amz, array(&$this, '__sortMetaHeadersCmp'));
$amz = "\n".implode("\n", $amz);
} else {
$amz = '';
}
if ($this->s3->hasAuth()) {
// Authorization string (CloudFront stringToSign should only contain a date)
if ('cloudfront.amazonaws.com' == $this->headers['Host']) {
$headers[] = 'Authorization: ' . $this->s3->__getSignature($this->headers['Date']);
} else {
if ('v2' === $this->s3->signVer) {
$headers[] = 'Authorization: ' . $this->s3->__getSignature(
$this->verb."\n".
$this->headers['Content-MD5']."\n".
$this->headers['Content-Type']."\n".
$this->headers['Date'].$amz."\n".
$this->resource
);
} else {
$amzHeaders = $this->s3->__getSignatureV4(
$this->amzHeaders,
$this->headers,
$this->verb,
$this->uri,
$this->data
);
foreach ($amzHeaders as $k => $v) {
$headers[] = $k . ': ' . $v;
}
}
}
}
// if (false !== $this->s3->port) curl_setopt($curl, CURLOPT_PORT, $this->s3->port);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback'));
curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback'));
@curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Request types
switch ($this->verb) {
case 'GET': break;
case 'PUT': case 'POST':
if (false !== $this->fp) {
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_INFILE, $this->fp);
if ($this->size >= 0) {
curl_setopt($curl, CURLOPT_INFILESIZE, $this->size);
}
} elseif (false !== $this->data) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb);
curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
curl_setopt($curl, CURLOPT_INFILESIZE, strlen($this->data));
} else {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb);
}
break;
case 'HEAD':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
curl_setopt($curl, CURLOPT_NOBODY, true);
break;
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
default: break;
}
// Execute, grab errors
if (curl_exec($curl))
$this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
else
$this->response->error = array(
'code' => curl_errno($curl),
'message' => curl_error($curl),
'resource' => $this->resource
);
@curl_close($curl);
// Parse body into XML
// The case in which there is not application/xml content-type header is to support a DreamObjects case seen, April 2018
if (false === $this->response->error && isset($this->response->body) && ((isset($this->response->headers['type']) && 'application/xml' == $this->response->headers['type']) || (!isset($this->response->headers['type']) && 0 === strpos($this->response->body, '<?xml')))) {
$this->response->body = simplexml_load_string($this->response->body);
// Grab S3 errors
if (!in_array($this->response->code, array(200, 204, 206)) &&
isset($this->response->body->Code)) {
$this->response->error = array(
'code' => (string)$this->response->body->Code,
);
$this->response->error['message'] = isset($this->response->body->Message) ? $this->response->body->Message : '';
if (isset($this->response->body->Resource))
$this->response->error['resource'] = (string)$this->response->body->Resource;
unset($this->response->body);
}
}
// Clean up file resources
// if (false !== $this->fp && is_resource($this->fp)) fclose($this->fp);
return $this->response;
}*/
public function getResponse() {
$query = '';
if (sizeof($this->parameters) > 0) {
$query = ('?' !== substr($this->uri, -1)) ? '?' : '&';
foreach ($this->parameters as $var => $value)
if (null == $value || '' == $value) $query .= $var.'&';
else if($var !== 'continuation-token'){
$query .= $var.'='.rawurlencode($value).'&';
}
else{
$query .= $var.'='.rawurlencode($value).'&';
//$query .= $var.'='.$value.'&';
}
$query = substr($query, 0, -1);
$this->uri .= $query;
if (array_key_exists('acl', $this->parameters) ||
array_key_exists('location', $this->parameters) ||
array_key_exists('torrent', $this->parameters) ||
array_key_exists('logging', $this->parameters) ||
array_key_exists('partNumber', $this->parameters) ||
array_key_exists('uploads', $this->parameters) ||
array_key_exists('uploadId', $this->parameters))
$this->resource .= $query;
}
$url = ($this->s3->useSSL ? 'https://' : 'http://') . ('' !== $this->headers['Host'] ? $this->headers['Host'] : $this->endpoint) . $this->uri;
//var_dump('bucket: ' . $this->bucket, 'uri: ' . $this->uri, 'resource: ' . $this->resource, 'url: ' . $url);
$curl = curl_init();
curl_setopt($curl, CURLOPT_USERAGENT, 'S3/php');
if ($this->s3->useSSL) {
// SSL Validation can now be optional for those with broken OpenSSL installations
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, $this->s3->useSSLValidation ? 2 : 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->s3->useSSLValidation ? 1 : 0);
if (null !== $this->s3->sslKey) curl_setopt($curl, CURLOPT_SSLKEY, $this->s3->sslKey);
if (null !== $this->s3->sslCert) curl_setopt($curl, CURLOPT_SSLCERT, $this->s3->sslCert);
if (null !== $this->s3->sslCACert) curl_setopt($curl, CURLOPT_CAINFO, $this->s3->sslCACert);
}
curl_setopt($curl, CURLOPT_URL, $url);
// Headers
$headers = array(); $amz = array();
foreach ($this->amzHeaders as $header => $value)
if (strlen($value) > 0) $headers[] = $header.': '.$value;
foreach ($this->headers as $header => $value)
if (strlen($value) > 0) $headers[] = $header . ': ' . $value;
// Collect AMZ headers for signature
foreach ($this->amzHeaders as $header => $value)
if (strlen($value) > 0) $amz[] = strtolower($header).':'.$value;
// AMZ headers must be sorted
if (sizeof($amz) > 0) {
//sort($amz);
usort($amz, array(&$this, '__sortMetaHeadersCmp'));
$amz = "\n".implode("\n", $amz);
} else {
$amz = '';
}
if ($this->s3->hasAuth()) {
// Authorization string (CloudFront stringToSign should only contain a date)
if ('cloudfront.amazonaws.com' == $this->headers['Host']) {
$headers[] = 'Authorization: ' . $this->s3->__getSignature($this->headers['Date']);
} else {
if ('v2' === $this->s3->signVer) {
$headers[] = 'Authorization: ' . $this->s3->__getSignature(
$this->verb."\n".
$this->headers['Content-MD5']."\n".
$this->headers['Content-Type']."\n".
$this->headers['Date'].$amz."\n".
$this->resource
);
} else {
$amzHeaders = $this->s3->__getSignatureV4(
$this->amzHeaders,
$this->headers,
$this->verb,
$this->uri,
$this->data
);
foreach ($amzHeaders as $k => $v) {
$headers[] = $k . ': ' . $v;
}
}
}
}
// if (false !== $this->s3->port) curl_setopt($curl, CURLOPT_PORT, $this->s3->port);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, false);
curl_setopt($curl, CURLOPT_WRITEFUNCTION, array(&$this, '__responseWriteCallback'));
curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this, '__responseHeaderCallback'));
@curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
// Request types
switch ($this->verb) {
case 'GET': break;
case 'PUT': case 'POST':
if (false !== $this->fp) {
curl_setopt($curl, CURLOPT_PUT, true);
curl_setopt($curl, CURLOPT_INFILE, $this->fp);
if ($this->size >= 0) {
curl_setopt($curl, CURLOPT_INFILESIZE, $this->size);
}
} elseif (false !== $this->data) {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb);
curl_setopt($curl, CURLOPT_POSTFIELDS, $this->data);
curl_setopt($curl, CURLOPT_INFILESIZE, strlen($this->data));
} else {
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $this->verb);
}
break;
case 'HEAD':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'HEAD');
curl_setopt($curl, CURLOPT_NOBODY, true);
break;
case 'DELETE':
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
default: break;
}
// Execute, grab errors
if (curl_exec($curl))
$this->response->code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
else
$this->response->error = array(
'code' => curl_errno($curl),
'message' => curl_error($curl),
'resource' => $this->resource
);
@curl_close($curl);
// Parse body into XML
// The case in which there is not application/xml content-type header is to support a DreamObjects case seen, April 2018
if (false === $this->response->error && isset($this->response->body) && ((isset($this->response->headers['type']) && 'application/xml' == $this->response->headers['type']) || (!isset($this->response->headers['type']) && 0 === strpos($this->response->body, '<?xml')))) {
$this->response->body = simplexml_load_string($this->response->body);
// Grab S3 errors
if (!in_array($this->response->code, array(200, 204, 206)) &&
isset($this->response->body->Code)) {
$this->response->error = array(
'code' => (string)$this->response->body->Code,
);
$this->response->error['message'] = isset($this->response->body->Message) ? $this->response->body->Message : '';
if (isset($this->response->body->Resource))
$this->response->error['resource'] = (string)$this->response->body->Resource;
unset($this->response->body);
}
}
// Clean up file resources
// if (false !== $this->fp && is_resource($this->fp)) fclose($this->fp);
return $this->response;
}
/**
* Sort compare for meta headers
*
* @internal Used to sort x-amz meta headers
* @param string $a String A
* @param string $b String B
* @return integer
*/
private function __sortMetaHeadersCmp($a, $b)
{
$lenA = strpos($a, ':');
$lenB = strpos($b, ':');
$minLen = min($lenA, $lenB);
$ncmp = strncmp($a, $b, $minLen);
if ($lenA == $lenB) return $ncmp;
if (0 == $ncmp) return $lenA < $lenB ? -1 : 1;
return $ncmp;
}
/**
* CURL write callback
*
* @param resource &$curl CURL resource
* @param string &$data Data
* @return integer
*/
private function __responseWriteCallback($curl, $data)
{
if (in_array($this->response->code, array(200, 206)) && $this->fp !== false)
return fwrite($this->fp, $data);
else
$this->response->body .= $data;
return strlen($data);
}
// /**
// * Check DNS conformity
// *
// * @param string $bucket Bucket name
// * @return boolean
// */
// private function __dnsBucketName($bucket)
// {
// if (strlen($bucket) > 63 || preg_match("/[^a-z0-9\.-]/", $bucket)) return false;
// if ($this -> s3 -> useSSL && strstr($bucket, '.') !== false) return false;
// if (strstr($bucket, '-.') !== false) return false;
// if (strstr($bucket, '..') !== false) return false;
// if (!preg_match("/^[0-9a-z]/", $bucket)) return false;
// if (!preg_match("/[0-9a-z]$/", $bucket)) return false;
// return true;
// }
/**
* CURL header callback
*
* @param resource $curl CURL resource
* @param string $data Data
* @return integer
*/
private function __responseHeaderCallback($curl, $data)
{
if (($strlen = strlen($data)) <= 2) return $strlen;
if (substr($data, 0, 4) == 'HTTP')
$this->response->code = (int)substr($data, 9, 3);
else
{
$data = trim($data);
if (strpos($data, ': ') === false) return $strlen;
list($header, $value) = explode(': ', $data, 2);
if ($header == 'Last-Modified')
$this->response->headers['time'] = strtotime($value);
elseif ($header == 'Date')
$this->response->headers['date'] = strtotime($value);
elseif ($header == 'Content-Length')
$this->response->headers['size'] = (int)$value;
elseif ($header == 'Content-Type')
$this->response->headers['type'] = $value;
elseif ($header == 'ETag')
$this->response->headers['hash'] = $value[0] == '"' ? substr($value, 1, -1) : $value;
elseif (preg_match('/^x-amz-meta-.*$/', $header))
$this->response->headers[$header] = $value;
}
return $strlen;
}
}
/**
* S3 exception class
*
* @link http://undesigned.org.za/2007/10/22/amazon-s3-php-class
* @version 0.5.0-dev
*/
class WPvivid_S3Exception extends Exception {
/**
* Class constructor
*
* @param string $message Exception message
* @param string $file File in which exception was created
* @param string $line Line number on which exception was created
* @param int $code Exception code
*/
function __construct($message, $file, $line, $code = 0)
{
parent::__construct($message, $code);
$this->file = $file;
$this->line = $line;
}
}
includes/customclass/class-wpvivid-google-drive.php 0000644 00000170243 15132770567 0016623 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
require_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-remote.php';
if(!defined('WPVIVID_REMOTE_GOOGLEDRIVE'))
define('WPVIVID_REMOTE_GOOGLEDRIVE','googledrive');
if(!defined('WPVIVID_GOOGLEDRIVE_DEFAULT_FOLDER'))
define('WPVIVID_GOOGLEDRIVE_DEFAULT_FOLDER','wpvivid_backup');
if(!defined('WPVIVID_GOOGLEDRIVE_UPLOAD_SIZE'))
define('WPVIVID_GOOGLEDRIVE_UPLOAD_SIZE',1024*1024*2);
if(!defined('WPVIVID_GOOGLE_NEED_PHP_VERSION'))
define('WPVIVID_GOOGLE_NEED_PHP_VERSION','5.5');
class Wpvivid_Google_drive extends WPvivid_Remote
{
public $options;
public $google_drive_secrets;
public $add_remote;
public function __construct($options=array())
{
if(empty($options))
{
if(!defined('WPVIVID_INIT_STORAGE_TAB_GOOGLE_DRIVE'))
{
add_action('init', array($this, 'handle_auth_actions'));
//wpvivid_google_drive_add_remote
add_action('wp_ajax_wpvivid_google_drive_add_remote',array( $this,'finish_add_remote'));
add_action('wpvivid_add_storage_tab',array($this,'wpvivid_add_storage_tab_google_drive'), 10);
add_action('wpvivid_add_storage_page',array($this,'wpvivid_add_storage_page_google_drive'), 10);
add_filter('wpvivid_pre_add_remote',array($this, 'pre_add_remote'),10,2);
add_action('wpvivid_edit_remote_page',array($this,'wpvivid_edit_storage_page_google_drive'), 10);
add_filter('wpvivid_remote_pic',array($this,'wpvivid_remote_pic_google_drive'),10);
add_filter('wpvivid_get_out_of_date_remote',array($this,'wpvivid_get_out_of_date_google_drive'),10,2);
add_filter('wpvivid_storage_provider_tran',array($this,'wpvivid_storage_provider_google_drive'),10);
add_filter('wpvivid_get_root_path',array($this,'wpvivid_get_root_path_google_drive'),10);
define('WPVIVID_INIT_STORAGE_TAB_GOOGLE_DRIVE',1);
}
}
else
{
$this->options=$options;
}
$this->add_remote=false;
$this->google_drive_secrets = array("web"=>array(
"client_id"=>"134809148507-32crusepgace4h6g47ota99jjrvf4j1u.apps.googleusercontent.com",
"project_id"=>"wpvivid-auth",
"auth_uri"=>"https://accounts.google.com/o/oauth2/auth",
"token_uri"=>"https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url"=>"https://www.googleapis.com/oauth2/v1/certs",
"client_secret"=>"",
"redirect_uris"=>array("https://auth.wpvivid.com/google_drive_v2/")
));
}
public function pre_add_remote($remote,$id)
{
if($remote['type']==WPVIVID_REMOTE_GOOGLEDRIVE)
{
$remote['id']=$id;
}
return $remote;
}
public function handle_auth_actions()
{
if(isset($_GET['action']) && isset($_GET['page']))
{
if($_GET['page'] === 'WPvivid')
{
if($_GET['action']=='wpvivid_google_drive_auth')
{
$check=current_user_can('manage_options');
if(!$check)
{
return;
}
$rand_id = substr(md5(time().rand()), 0,13);
$auth_id = 'wpvivid-auth-'.$rand_id;
$res = $this -> compare_php_version();
if($res['result'] == WPVIVID_FAILED){
echo '<div class="notice notice-warning is-dismissible"><p>'.esc_html($res['error']).'</p></div>';
return ;
}
try {
include_once WPVIVID_PLUGIN_DIR . '/vendor/autoload.php';
$client = new WPvivid_Google_Client();
$client->setAuthConfig($this->google_drive_secrets);
$client->setApprovalPrompt('force');
$client->addScope(WPvivid_Google_Service_Drive::DRIVE_FILE);
$client->setAccessType('offline');
$client->setState(admin_url() . 'admin.php?page=WPvivid' . '&action=wpvivid_google_drive_finish_auth&main_tab=storage&sub_tab=googledrive&sub_page=storage_account_google_drive&auth_id='.$auth_id);
$auth_url = $client->createAuthUrl();
$remote_options['auth_id']=$auth_id;
set_transient('google_drive_auth_id', $remote_options, 900);
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}
catch (Exception $e){
if($e->getMessage() === 'file does not exist'){
$error_msg = __('Authentication failed, the client_secrets.json file is missing. Please make sure the client_secrets.json file is in wpvivid-backuprestore\includes\customclass directory.', 'wpvivid-backuprestore');
echo '<div class="notice notice-error"><p>'.esc_html($error_msg).'</p></div>';
}
else if($e->getMessage() === 'invalid json for auth config'){
$error_msg = __('Authentication failed, the format of the client_secrets.json file is incorrect. Please delete and re-install the plugin to recreate the file.', 'wpvivid-backuprestore');
echo '<div class="notice notice-error"><p>'.esc_html($error_msg).'</p></div>';
}
else{
echo '<div class="notice notice-error"><p>'.esc_html($e->getMessage()).'</p></div>';
}
}
}
else if($_GET['action']=='wpvivid_google_drive_finish_auth')
{
$tmp_options = get_transient('google_drive_auth_id');
if($tmp_options === false)
{
return;
}
else if($tmp_options['auth_id'] !== $_GET['auth_id'])
{
delete_transient('google_drive_auth_id');
return;
}
try
{
if(isset($_GET['error']))
{
header('Location: '.admin_url().'admin.php?page='.WPVIVID_PLUGIN_SLUG.'&action=wpvivid_google_drive&main_tab=storage&sub_tab=googledrive&sub_page=storage_account_google_drive&result=error&resp_msg='.sanitize_text_field($_GET['error']));
return;
}
$remoteslist = WPvivid_Setting::get_all_remote_options();
foreach ($remoteslist as $key => $value)
{
if (isset($value['auth_id']) && isset($_GET['auth_id']) && $value['auth_id'] == sanitize_text_field($_GET['auth_id']))
{
echo '<div class="notice notice-success is-dismissible"><p>';
esc_html_e('You have authenticated the Google Drive account as your remote storage.', 'wpvivid-backuprestore');
echo '</p></div>';
return;
}
}
if(empty($_POST['refresh_token']))
{
if(empty($tmp_options['token']['refresh_token']))
{
$err = 'No refresh token was received from Google, which means that you entered client secret incorrectly, or that you did not re-authenticated yet after you corrected it. Please authenticate again.';
header('Location: '.admin_url().'admin.php?page='.WPVIVID_PLUGIN_SLUG.'&action=wpvivid_google_drive&main_tab=storage&sub_tab=googledrive&sub_page=storage_account_google_drive&result=error&resp_msg='.$err);
return;
}
}
else
{
$tmp_options['type'] = WPVIVID_REMOTE_GOOGLEDRIVE;
$tmp_options['token']['access_token'] = base64_encode(sanitize_text_field($_POST['access_token']));
$tmp_options['token']['expires_in'] = sanitize_text_field($_POST['expires_in']);
$tmp_options['token']['refresh_token'] = base64_encode(sanitize_text_field($_POST['refresh_token']));
$tmp_options['token']['scope'] = sanitize_text_field($_POST['scope']);
$tmp_options['token']['token_type'] = sanitize_text_field($_POST['token_type']);
$tmp_options['token']['created'] = sanitize_text_field($_POST['created']);
$tmp_options['is_encrypt'] = 1;
set_transient('google_drive_auth_id', $tmp_options, 900);
}
$this->add_remote=true;
}
catch (Exception $e){
echo '<div class="notice notice-error"><p>'.esc_html($e->getMessage()).'</p></div>';
}
}
else if($_GET['action']=='wpvivid_google_drive')
{
try {
if (isset($_GET['result'])) {
if ($_GET['result'] == 'success') {
add_action('show_notice', array($this, 'wpvivid_show_notice_add_google_drive_success'));
} else if ($_GET['result'] == 'error') {
add_action('show_notice', array($this, 'wpvivid_show_notice_add_google_drive_error'));
}
}
}
catch (Exception $e){
echo '<div class="notice notice-error"><p>'.esc_html($e->getMessage()).'</p></div>';
}
}
}
}
}
public function wpvivid_show_notice_add_google_drive_success(){
echo '<div class="notice notice-success is-dismissible"><p>';
esc_html_e('You have authenticated the Google Drive account as your remote storage.', 'wpvivid-backuprestore');
echo '</p></div>';
}
public function wpvivid_show_notice_add_google_drive_error(){
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_handle_remote_storage_error($_GET['resp_msg'], 'Add Google Drive Remote');
echo '<div class="notice notice-error"><p>'.esc_html($_GET['resp_msg']).'</p></div>';
}
public function wpvivid_add_storage_tab_google_drive()
{
?>
<div class="storage-providers storage-providers-active" remote_type="googledrive" onclick="select_remote_storage(event, 'storage_account_google_drive');">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/stroage-google-drive.png'); ?>" style="vertical-align:middle;"/><?php esc_html_e('Google Drive', 'wpvivid-backuprestore'); ?>
</div>
<?php
}
public function wpvivid_add_storage_page_google_drive()
{
global $wpvivid_plugin;
$root_path=apply_filters('wpvivid_get_root_path', WPVIVID_REMOTE_GOOGLEDRIVE);
if($this->add_remote)
{
?>
<div id="storage_account_google_drive" class="storage-account-page">
<div style="background-color:#f1f1f1; padding: 10px;">
Please read <a target="_blank" href="https://wpvivid.com/privacy-policy" style="text-decoration: none;">this privacy policy</a> for use of our Google Drive authorization app (none of your backup data is sent to us).
</div>
<div style="color:#8bc34a; padding: 10px 10px 10px 0;">
<strong>Authentication is done, please continue to enter the storage information, then click 'Add Now' button to save it.</strong>
</div>
<div style="padding: 10px 10px 10px 0;">
<strong><?php esc_html_e('Enter Your Google Drive Information', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="googledrive" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. Google Drive-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" name="path" value="<?php echo esc_attr($root_path.WPVIVID_GOOGLEDRIVE_DEFAULT_FOLDER); ?>" readonly="readonly" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('All backups will be uploaded to this directory.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" value="mywebsite01" readonly="readonly" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<a href="https://docs.wpvivid.com/wpvivid-backup-pro-google-drive-custom-folder-name.html"><?php esc_html_e('Pro feature: Create a directory for storing the backups of the site', 'wpvivid-backuprestore'); ?></a>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="googledrive" name="default" checked /><?php esc_html_e('Set as the default remote storage.', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Once checked, all this sites backups sent to a remote storage destination will be uploaded to this storage by default.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input id="wpvivid_google_drive_auth" class="button-primary" type="submit" value="<?php esc_attr_e('Add Now', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to add the storage.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script>
function wpvivid_check_google_drive_storage_alias(storage_alias){
var find = 1;
jQuery('#wpvivid_remote_storage_list tr').each(function (i) {
jQuery(this).children('td').each(function (j) {
if (j == 3) {
if (jQuery(this).text() == storage_alias) {
find = -1;
return false;
}
}
});
});
return find;
}
jQuery('#wpvivid_google_drive_auth').click(function()
{
wpvivid_google_drive_auth();
});
function wpvivid_google_drive_auth()
{
wpvivid_settings_changed = false;
var name='';
var path='';
jQuery('input:text[option=googledrive]').each(function()
{
var key = jQuery(this).prop('name');
if(key==='name')
{
name = jQuery(this).val();
}
});
var remote_default='0';
jQuery('input:checkbox[option=googledrive]').each(function()
{
if(jQuery(this).prop('checked')) {
remote_default='1';
}
else {
remote_default='0';
}
});
if(name == ''){
alert(wpvividlion.remotealias);
}
else if(wpvivid_check_google_drive_storage_alias(name) === -1)
{
alert(wpvividlion.remoteexist);
}
else
{
var ajax_data;
var remote_from = wpvivid_ajax_data_transfer('googledrive');
ajax_data = {
'action': 'wpvivid_google_drive_add_remote',
'remote': remote_from
};
jQuery('#wpvivid_google_drive_auth').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#wpvivid_remote_notice').html('');
wpvivid_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_google_drive_auth').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('input:text[option=googledrive]').each(function(){
jQuery(this).val('');
});
jQuery('input:password[option=googledrive]').each(function(){
jQuery(this).val('');
});
wpvivid_handle_remote_storage_data(data);
location.href='admin.php?page=WPvivid&action=wpvivid_google_drive&main_tab=storage&sub_tab=googledrive&sub_page=storage_account_google_drive&result=success';
}
else if (jsonarray.result === 'failed')
{
jQuery('#wpvivid_remote_notice').html(jsonarray.notice);
jQuery('input[option=add-remote]').css({'pointer-events': 'auto', 'opacity': '1'});
}
}
catch (err)
{
alert(err);
jQuery('input[option=add-remote]').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('adding the remote storage', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_google_drive_auth').css({'pointer-events': 'auto', 'opacity': '1'});
});
}
}
</script>
<?php
}
else
{
?>
<div id="storage_account_google_drive" class="storage-account-page">
<div style="background-color:#f1f1f1; padding: 10px;">
Please read <a target="_blank" href="https://wpvivid.com/privacy-policy" style="text-decoration: none;">this privacy policy</a> for use of our Google Drive authorization app (none of your backup data is sent to us).
</div>
<div style="padding: 10px 10px 10px 0;">
<strong><?php esc_html_e('To add Google Drive, please get Google authentication first. Once authenticated, you will be redirected to this page, then you can add storage information and save it', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input onclick="wpvivid_google_drive_auth();" class="button-primary" type="submit" value="<?php esc_attr_e('Authenticate with Google Drive', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click to get Google authentication.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
<div style="padding: 10px 0 0 0;">
<span>Tip: Get a 404 or 403 error after authorization? Please read this <a href="https://docs.wpvivid.com/http-403-error-authorizing-cloud-storage.html">doc</a>.</span>
</div>
</div>
<script>
function wpvivid_google_drive_auth()
{
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page=WPvivid' . '&action=wpvivid_google_drive_auth'?>';
}
</script>
<?php
}
}
public function wpvivid_edit_storage_page_google_drive()
{
?>
<div id="remote_storage_edit_googledrive" class="postbox storage-account-block remote-storage-edit" style="display:none;">
<div style="padding: 0 10px 10px 0;">
<strong><?php esc_html_e('Enter Your Google Drive Information', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-googledrive" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. Google Drive-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" type="submit" option="edit-remote" value="<?php esc_attr_e('Save Changes', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to save the changes.', 'wpvivid-backuprestore');?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<script>
function wpvivid_google_drive_update_auth()
{
var name='';
jQuery('input:text[option=edit-googledrive]').each(function()
{
var key = jQuery(this).prop('name');
if(key==='name')
{
name = jQuery(this).val();
}
});
if(name == ''){
alert(wpvividlion.remotealias);
}
else if(wpvivid_check_onedrive_storage_alias(name) === -1){
alert(wpvividlion.remoteexist);
}
else {
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page=WPvivid' . '&action=wpvivid_google_drive_update_auth&name='?>' + name + '&id=' + wpvivid_editing_storage_id;
}
}
</script>
<?php
}
public function wpvivid_remote_pic_google_drive($remote)
{
$remote['googledrive']['default_pic'] = '/admin/partials/images/stroage-google-drive(gray).png';
$remote['googledrive']['selected_pic'] = '/admin/partials/images/stroage-google-drive.png';
$remote['googledrive']['title'] = 'Google Drive';
return $remote;
}
public function sanitize_options($skip_name='')
{
$ret['result']=WPVIVID_SUCCESS;
if(!isset($this->options['name']))
{
$ret['error']="Warning: An alias for remote storage is required.";
return $ret;
}
$this->options['name']=sanitize_text_field($this->options['name']);
if(empty($this->options['name']))
{
$ret['error']="Warning: An alias for remote storage is required.";
return $ret;
}
$remoteslist=WPvivid_Setting::get_all_remote_options();
foreach ($remoteslist as $key=>$value)
{
if(isset($value['name'])&&$value['name'] == $this->options['name']&&$skip_name!=$value['name'])
{
$ret['error']="Warning: The alias already exists in storage list.";
return $ret;
}
}
$ret['options']=$this->options;
return $ret;
}
public function test_connect()
{
return array('result' => WPVIVID_SUCCESS);
}
public function upload($task_id, $files, $callback = '')
{
global $wpvivid_plugin;
$client=$this->get_client();
if($client['result'] == WPVIVID_FAILED){
return $client;
}
$client = $client['data'];
if($client===false)
{
return array('result' => WPVIVID_FAILED,'error'=> 'Token refresh failed.');
}
$service = new WPvivid_Google_Service_Drive($client);
$path=$this->options['path'];
$wpvivid_plugin->wpvivid_log->WriteLog('Check upload folder '.$path,'notice');
$folder_id=$this->get_folder($service,$path);
if($folder_id==false)
{
return array('result' => WPVIVID_FAILED,'error'=> 'Unable to create the local file. Please make sure the folder is writable and try again.');
}
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_GOOGLEDRIVE);
if(empty($upload_job))
{
$job_data=array();
foreach ($files as $file)
{
$file_data['size']=filesize($file);
$file_data['uploaded']=0;
$file_data['resumeUri']=false;
$file_data['progress']=false;
$job_data[basename($file)]=$file_data;
}
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_GOOGLEDRIVE,WPVIVID_UPLOAD_UNDO,'Start uploading',$job_data);
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_GOOGLEDRIVE);
}
foreach ($files as $file)
{
if(is_array($upload_job['job_data'])&&array_key_exists(basename($file),$upload_job['job_data']))
{
if($upload_job['job_data'][basename($file)]['uploaded']==1)
continue;
}
$this -> last_time = time();
$this -> last_size = 0;
if(!file_exists($file))
return array('result' =>WPVIVID_FAILED,'error' =>$file.' not found. The file might has been moved, renamed or deleted. Please reload the list and verify the file exists.');
$wpvivid_plugin->wpvivid_log->WriteLog('Start uploading '.basename($file),'notice');
$wpvivid_plugin->set_time_limit($task_id);
$result=$this->_upload($task_id, $file,$client,$service,$folder_id, $callback);
if($result['result'] !==WPVIVID_SUCCESS){
return $result;
}
else
{
WPvivid_taskmanager::wpvivid_reset_backup_retry_times($task_id);
}
$ref=$this->check_token($client, $service);
if($ref['result']=!WPVIVID_SUCCESS)
{
return $ref;
}
}
return array('result' =>WPVIVID_SUCCESS);
}
public function check_token(&$client, &$service)
{
if ($client->isAccessTokenExpired())
{
// Refresh the token if possible, else fetch a new one.
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Refresh the token.','notice');
if ($client->getRefreshToken())
{
$tmp_refresh_token = $client->getRefreshToken();
/*
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$token=$client->getAccessToken();
*/
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$tmp_refresh_token = base64_decode($tmp_refresh_token);
}
$args = array(
'refresh_token' => $tmp_refresh_token
);
$result = wp_remote_post("https://auth.wpvivid.com/google_drive_v2/", array(
'timeout' => 60,
'body' => $args
));
if (is_wp_error($result))
{
return array('result' => WPVIVID_SUCCESS,'data' => false);
}
else
{
$token = wp_remote_retrieve_body($result);
$token = json_decode($token, true);
if(!is_null($token))
{
$client->setAccessToken($token);
}
else
{
return array('result' => WPVIVID_SUCCESS,'data' => false);
}
}
$remote_options=WPvivid_Setting::get_remote_option($this->options['id']);
$this->options['token']=json_decode(wp_json_encode($token),1);
$this->options['token']['access_token']=base64_encode($this->options['token']['access_token']);
$this->options['is_encrypt']=1;
if($remote_options!==false)
{
if(!isset($this->options['token']['refresh_token'])){
$this->options['token']['refresh_token'] = base64_encode($tmp_refresh_token);
}
else{
$this->options['token']['refresh_token']=base64_encode($this->options['token']['refresh_token']);
}
$remote_options['token']=$this->options['token'];
$remote_options['is_encrypt']=1;
WPvivid_Setting::update_remote_option($this->options['id'],$remote_options);
$client=$this->get_client();
if($client['result'] == WPVIVID_FAILED){
return $client;
}
$client = $client['data'];
if($client===false)
{
return array('result' => WPVIVID_FAILED,'error'=> 'Token refresh failed.');
}
$service = new WPvivid_Google_Service_Drive($client);
}
return array('result' => WPVIVID_SUCCESS);
}
else
{
return array('result' => WPVIVID_FAILED,'error'=>'get refresh token failed');
}
}
else
{
return array('result' => WPVIVID_SUCCESS);
}
}
public function _upload($task_id, $file,$client,$service,$folder_id, $callback = '', $retry_times=0)
{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Check if the server already has the same name file.','notice');
try{
if(!$this->delete_exist_file($folder_id,basename($file),$service))
{
return array('result' =>WPVIVID_FAILED,'error'=>'Uploading '.$file.' to Google Drive server failed. '.$file.' might be deleted or network doesn\'t work properly . Please verify the file and confirm the network connection and try again later.');
}
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_GOOGLEDRIVE);
$this -> current_file_size = filesize($file);
$this -> current_file_name = basename($file);
$fileMetadata = new WPvivid_Google_Service_Drive_DriveFile(array(
'name' => basename($file),
'parents' => array($folder_id)));
$chunk_size = 1 * 1024 * 1024;
$client->setDefer(true);
$request = $service->files->create($fileMetadata);
$media = new WPvivid_Google_Http_MediaFileUpload(
$client,
$request,
'text/plain',
null,
true,
$chunk_size
);
$media->setFileSize(filesize($file));
$status = false;
$handle = fopen($file, "rb");
if(!empty($upload_job['job_data'][basename($file)]['resumeUri']))
{
$media->resume( $upload_job['job_data'][basename($file)]['resumeUri'] );
$media->setResumeUri($upload_job['job_data'][basename($file)]['resumeUri'] );
$media->setProgress($upload_job['job_data'][basename($file)]['progress'] );
$wpvivid_plugin->wpvivid_log->WriteLog('Resume uploading '.basename($file).'.','notice');
$wpvivid_plugin->wpvivid_log->WriteLog('resumeUri:'.$media->getResumeUri().'.','notice');
$wpvivid_plugin->wpvivid_log->WriteLog('progress:'.$media->getProgress().'.','notice');
$offset = $upload_job['job_data'][basename($file)]['progress'];
fseek($handle, $offset);
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_GOOGLEDRIVE,WPVIVID_UPLOAD_UNDO,'Resume uploading '.basename($file).'.',$upload_job['job_data']);
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Initiate a resumable upload session.','notice');
$offset=0;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_GOOGLEDRIVE,WPVIVID_UPLOAD_UNDO,'Start uploading '.basename($file).'.',$upload_job['job_data']);
}
while (!$status && !feof($handle))
{
$chunk = fread($handle, $chunk_size);
$status = $media->nextChunk($chunk);
$offset+=strlen($chunk);
$retry_times=0;
if((time() - $this -> last_time) >3)
{
if(is_callable($callback))
{
call_user_func_array($callback,array($offset,$this -> current_file_name,
$this->current_file_size,$this -> last_time,$this -> last_size));
}
$this -> last_size = $offset;
$this -> last_time = time();
}
$upload_job['job_data'][basename($file)]['resumeUri']=$media->getResumeUri();
$upload_job['job_data'][basename($file)]['progress']=$media->getProgress();
//$wpvivid_plugin->wpvivid_log->WriteLog('resumeUri:'.$media->getResumeUri().'.','notice');
$wpvivid_plugin->wpvivid_log->WriteLog('progress:'.$media->getProgress().'.','notice');
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_GOOGLEDRIVE,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file),$upload_job['job_data']);
}
fclose($handle);
$client->setDefer(false);
if ($status != false)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Finished uploading '.basename($file),'notice');
$upload_job['job_data'][basename($file)]['uploaded']=1;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_GOOGLEDRIVE,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file).' completed.',$upload_job['job_data']);
$wpvivid_plugin->wpvivid_log->WriteLog('Upload success.','notice');
return array('result' =>WPVIVID_SUCCESS);
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Upload failed.','notice');
return array('result' =>WPVIVID_FAILED,'error'=>'Uploading '.$file.' to Google Drive server failed. '.$file.' might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.');
}
}
catch (WPvivid_Google_Service_Exception $e)
{
$retry_times++;
fclose($handle);
$client->setDefer(false);
$message = 'A exception ('.get_class($e).') occurred '.esc_html($e->getMessage()).' (Code: '.$e->getCode().', line '.$e->getLine().' in '.$e->getFile().') ';
if($retry_times < 15)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Upload Google_Service_Exception, '.$message.', retry times: '.$retry_times,'notice');
return $this->_upload($task_id, $file,$client,$service,$folder_id, $callback, $retry_times);
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Upload Google_Service_Exception, retry times: '.$retry_times,'notice');
return array('result' =>WPVIVID_FAILED,'error'=>$message);
}
}
catch (InvalidArgumentException $e)
{
//need refresh token
$retry_times++;
$message = 'A exception ('.get_class($e).') occurred '.esc_html($e->getMessage()).' (Code: '.$e->getCode().', line '.$e->getLine().' in '.$e->getFile().') ';
$wpvivid_plugin->wpvivid_log->WriteLog('Upload InvalidArgumentException, '.$message.', refresh token','notice');
$ref=$this->check_token($client, $service);
if($ref['result']=!WPVIVID_SUCCESS)
{
$wpvivid_plugin->wpvivid_log->WriteLog('refresh token failed, error: '.json_encode($ref),'notice');
return $ref;
}
fclose($handle);
$client->setDefer(false);
if($retry_times < 15)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Refresh token completed, continue upload.','notice');
return $this->_upload($task_id, $file,$client,$service,$folder_id, $callback, $retry_times);
}
else
{
return array('result' =>WPVIVID_FAILED,'error'=>$message);
}
}
}
public function get_client()
{
$res = $this -> compare_php_version();
if($res['result'] == WPVIVID_FAILED){
return $res;
}
$token=$this->options['token'];
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$token['access_token'] = base64_decode($this->options['token']['access_token']);
}
include_once WPVIVID_PLUGIN_DIR.'/vendor/autoload.php';
$client = new WPvivid_Google_Client();
$client->setConfig('access_type','offline');
$client->setAuthConfig($this->google_drive_secrets);
$client->addScope(WPvivid_Google_Service_Drive::DRIVE_FILE);//
$client->setAccessToken($token);
if ($client->isAccessTokenExpired())
{
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken())
{
$tmp_refresh_token = $client->getRefreshToken();
/*
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$token=$client->getAccessToken();
*/
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1) {
$tmp_refresh_token = base64_decode($tmp_refresh_token);
}
$args = array(
'refresh_token' => $tmp_refresh_token
);
$result = wp_remote_post("https://auth.wpvivid.com/google_drive_v2/", array(
'timeout' => 60,
'body' => $args
));
if (is_wp_error($result))
{
return array('result' => WPVIVID_SUCCESS,'data' => false);
}
else
{
$token = wp_remote_retrieve_body($result);
$token = json_decode($token, true);
if(!is_null($token))
{
$client->setAccessToken($token);
}
else
{
return array('result' => WPVIVID_SUCCESS,'data' => false);
}
}
$this->options['token']=json_decode(wp_json_encode($token),1);
$this->options['token']['access_token']=base64_encode($this->options['token']['access_token']);
$this->options['is_encrypt']=1;
if(!isset($this->options['token']['refresh_token'])){
$this->options['token']['refresh_token'] = base64_encode($tmp_refresh_token);
}
else{
$this->options['token']['refresh_token']=base64_encode($this->options['token']['refresh_token']);
}
WPvivid_Setting::update_remote_option($this->options['id'],$this->options);
return array('result' => WPVIVID_SUCCESS,'data' => $client);
}
else
{
return array('result' => WPVIVID_SUCCESS,'data' => false);
}
}
else
{
return array('result' => WPVIVID_SUCCESS,'data' => $client);
}
}
private function get_folder($service,$path)
{
$response = $service->files->listFiles(array(
'q' => "name ='".$path."' and 'root' in parents and mimeType = 'application/vnd.google-apps.folder'",
'fields' => 'nextPageToken, files(id, name,mimeType)',
));
if(sizeof($response->getFiles())==0)
{
$fileMetadata = new WPvivid_Google_Service_Drive_DriveFile(array(
'name' => $path,
'mimeType' => 'application/vnd.google-apps.folder'));
$file = $service->files->create($fileMetadata, array(
'fields' => 'id'));
return $file->id;
}
else
{
foreach ($response->getFiles() as $file)
{
return $file->getId();
}
}
return false;
}
public function set_token()
{
$remote_options=WPvivid_Setting::get_remote_option($this->options['id']);
if($remote_options!==false)
{
$this->options['token']=$remote_options['token'];
if(isset($remote_options['is_encrypt']))
{
$this->options['is_encrypt']=$remote_options['is_encrypt'];
}
}
}
public function download( $file, $local_path, $callback = '')
{
try
{
global $wpvivid_plugin;
$this -> current_file_name = $file['file_name'];
$this -> current_file_size = $file['size'];
$this->set_token();
$wpvivid_plugin->wpvivid_download_log->WriteLog('Google Drive get client.','notice');
$client=$this->get_client();
if($client['result'] == WPVIVID_FAILED) {
return $client;
}
$client = $client['data'];
if($client===false)
{
return array('result' => WPVIVID_FAILED,'error'=> 'Token refresh failed.');
}
$service = new WPvivid_Google_Service_Drive($client);
$path=$this->options['path'];
$wpvivid_plugin->wpvivid_download_log->WriteLog('Create local file.','notice');
$folder_id=$this->get_folder($service,$path);
if($folder_id==false)
{
return array('result' => WPVIVID_FAILED,'error'=> 'Unable to create the local file. Please make sure the folder is writable and try again.');
}
$response = $service->files->listFiles(array(
'q' => "name='".$file['file_name']."' and '".$folder_id."' in parents",
'fields' => 'files(id,size,webContentLink)'
));
if(sizeof($response->getFiles())==0)
{
return array('result' => WPVIVID_FAILED,'error'=> 'Downloading file failed. The file might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.');
}
else
{
$fileSize=$file['size'];
$file_id='';
foreach ($response->getFiles() as $file)
{
$file_id=$file->getId();
break;
}
$wpvivid_plugin->wpvivid_download_log->WriteLog('Get download url.','notice');
$download_url=$this->get_download_url($client,$file_id);
if(!empty($file_id)||!empty($download_url))
{
$file_path = trailingslashit($local_path).$this -> current_file_name;
if(file_exists($file_path))
{
$offset = filesize($file_path);
}
else
{
$offset=0;
}
$fh = fopen($file_path, 'a');
$upload_size = WPVIVID_GOOGLEDRIVE_UPLOAD_SIZE;
$http = $client->authorize();
$wpvivid_plugin->wpvivid_download_log->WriteLog('Downloading file ' . $file['file_name'] . ', Size: ' . $file['size'] ,'notice');
while ($offset < $fileSize)
{
$upload_end=min($offset+$upload_size-1,$fileSize-1);
if ($offset > 0)
{
$options['headers']['Range']='bytes='.$offset.'-'.$upload_end;
} else {
$options['headers']['Range']='bytes=0-'.$upload_end;
}
$request = new WPvividGuzzleHttp\Psr7\Request('GET', $download_url,$options['headers']);
$http_request = $http->send($request);
$http_response=$http_request->getStatusCode();
if (200 == $http_response || 206 == $http_response)
{
fwrite($fh, $http_request->getBody()->getContents(),$upload_size);
$offset=$upload_end + 1;
}
else
{
throw new Exception('Failed to obtain any new data at size: '.$offset.' http code:'.$http_response);
}
if((time() - $this -> last_time) >3)
{
if(is_callable($callback))
{
call_user_func_array($callback,array($offset,$this -> current_file_name,
$this->current_file_size,$this -> last_time,$this -> last_size));
}
$this -> last_size = $offset;
$this -> last_time = time();
}
}
fclose($fh);
}
else
{
return array('result' => WPVIVID_FAILED,'error'=> 'Downloading file failed. The file might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.');
}
}
}catch(Exception $e)
{
return array('result' => WPVIVID_FAILED,'error' => $e -> getMessage());
}
return array('result' => WPVIVID_SUCCESS);
}
public function get_download_url($client,$file_id)
{
$http = $client->authorize();
$url='https://www.googleapis.com/drive/v2/files/'.$file_id;
$request = new WPvividGuzzleHttp\Psr7\Request('GET', $url);
$http_request = $http->send($request);
$http_response=$http_request->getStatusCode();
if (200 == $http_response)
{
$json=$http_request->getBody()->getContents();
$json=json_decode($json,1);
$download_url=$json['downloadUrl'];
return $download_url;
}
else
{
throw new Exception('Failed to use v2 api');
}
}
public function delete_exist_file($folder_id,$file,$service)
{
global $wpvivid_plugin;
$client=$this->get_client();
if($client['result'] == WPVIVID_FAILED)
return false;
$client = $client['data'];
if($client===false)
{
return false;
}
try{
$delete_files = $service->files->listFiles(array(
'q' => "name='".$file."' and '".$folder_id."' in parents",
'fields' => 'nextPageToken, files(id, name,mimeType)',
));
if(sizeof($delete_files->getFiles())==0)
{
return true;
}
else
{
foreach ($delete_files->getFiles() as $file_google_drive)
{
$file_id=$file_google_drive->getId();
$service->files->delete($file_id);
return true;
}
}
}
catch(Exception $error)
{
$wpvivid_plugin->wpvivid_log->WriteLog('listFiles exception.','notice');
return true;
}
return false;
}
public function cleanup($files)
{
$client=$this->get_client();
if($client['result'] == WPVIVID_FAILED)
return $client;
$client = $client['data'];
if($client===false)
{
return array('result' => WPVIVID_FAILED,'error'=> 'Token refresh failed.');
}
$service = new WPvivid_Google_Service_Drive($client);
$path=$this->options['path'];
$folder_id=$this->get_folder($service,$path);
if($folder_id==false)
{
return array('result' => WPVIVID_FAILED,'error'=> 'Unable to create the local file. Please make sure the folder is writable and try again.');
}
foreach ($files as $file)
{
$delete_files = $service->files->listFiles(array(
'q' => "name='".$file."' and '".$folder_id."' in parents",
'fields' => 'nextPageToken, files(id, name,mimeType)',
));
if(sizeof($delete_files->getFiles())==0)
{
continue;
}
else
{
foreach ($delete_files->getFiles() as $file_google_drive)
{
$file_id=$file_google_drive->getId();
$service->files->delete($file_id);
}
}
}
return array('result' =>WPVIVID_SUCCESS);
}
public function wpvivid_get_out_of_date_google_drive($out_of_date_remote, $remote)
{
if($remote['type'] == WPVIVID_REMOTE_GOOGLEDRIVE){
$root_path=apply_filters('wpvivid_get_root_path', $remote['type']);
$out_of_date_remote = $root_path.$remote['path'];
}
return $out_of_date_remote;
}
public function wpvivid_storage_provider_google_drive($storage_type)
{
if($storage_type == WPVIVID_REMOTE_GOOGLEDRIVE){
$storage_type = 'Google Drive';
}
return $storage_type;
}
public function wpvivid_get_root_path_google_drive($storage_type){
if($storage_type == WPVIVID_REMOTE_GOOGLEDRIVE){
$storage_type = 'root/';
}
return $storage_type;
}
private function compare_php_version(){
if(version_compare(WPVIVID_GOOGLE_NEED_PHP_VERSION,phpversion()) > 0){
return array('result' => WPVIVID_FAILED,error => 'The required PHP version is higher than '.WPVIVID_GOOGLE_NEED_PHP_VERSION.'. After updating your PHP version, please try again.');
}
return array('result' => WPVIVID_SUCCESS);
}
public function finish_add_remote()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try {
if (empty($_POST) || !isset($_POST['remote']) || !is_string($_POST['remote'])) {
die();
}
$tmp_remote_options = get_transient('google_drive_auth_id');
if($tmp_remote_options === false)
{
die();
}
delete_transient('google_drive_auth_id');
if(empty($tmp_remote_options)||$tmp_remote_options['type']!==WPVIVID_REMOTE_GOOGLEDRIVE)
{
die();
}
$json = sanitize_text_field($_POST['remote']);
$json = stripslashes($json);
$remote_options = json_decode($json, true);
if (is_null($remote_options)) {
die();
}
$remote_options['path'] = WPVIVID_GOOGLEDRIVE_DEFAULT_FOLDER;
$remote_options=array_merge($remote_options,$tmp_remote_options);
if(!class_exists('WPvivid_Remote_collection'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-remote-collection.php';
$wpvivid_plugin->remote_collection=new WPvivid_Remote_collection();
}
$ret = $wpvivid_plugin->remote_collection->add_remote($remote_options);
if ($ret['result'] == 'success') {
$html = '';
$html = apply_filters('wpvivid_add_remote_storage_list', $html);
$ret['html'] = $html;
$pic = '';
$pic = apply_filters('wpvivid_schedule_add_remote_pic', $pic);
$ret['pic'] = $pic;
$dir = '';
$dir = apply_filters('wpvivid_get_remote_directory', $dir);
$ret['dir'] = $dir;
$schedule_local_remote = '';
$schedule_local_remote = apply_filters('wpvivid_schedule_local_remote', $schedule_local_remote);
$ret['local_remote'] = $schedule_local_remote;
$remote_storage = '';
$remote_storage = apply_filters('wpvivid_remote_storage', $remote_storage);
$ret['remote_storage'] = $remote_storage;
$remote_select_part = '';
$remote_select_part = apply_filters('wpvivid_remote_storage_select_part', $remote_select_part);
$ret['remote_select_part'] = $remote_select_part;
$default = array();
$remote_array = apply_filters('wpvivid_archieve_remote_array', $default);
$ret['remote_array'] = $remote_array;
$success_msg = __('You have successfully added a remote storage.', 'wpvivid-backuprestore');
$ret['notice'] = apply_filters('wpvivid_add_remote_notice', true, $success_msg);
}
else{
$ret['notice'] = apply_filters('wpvivid_add_remote_notice', false, $ret['error']);
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
echo wp_json_encode($ret);
die();
}
} includes/customclass/class-wpvivid-sftpclass.php 0000644 00000073040 15132770567 0016237 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
if(!defined('WPVIVID_REMOTE_SFTP'))
define('WPVIVID_REMOTE_SFTP','sftp');
require_once WPVIVID_PLUGIN_DIR .'/includes/customclass/class-wpvivid-remote.php';
class WPvivid_SFTPClass extends WPvivid_Remote{
private $package_size = 10;
private $timeout = 20;
private $error_str=false;
private $callback;
private $options=array();
public function __construct($options=array())
{
if(empty($options))
{
add_action('wpvivid_add_storage_tab',array($this,'wpvivid_add_storage_tab_sftp'), 16);
add_action('wpvivid_add_storage_page',array($this,'wpvivid_add_storage_page_sftp'), 16);
add_action('wpvivid_edit_remote_page',array($this,'wpvivid_edit_storage_page_sftp'), 16);
add_filter('wpvivid_remote_pic',array($this,'wpvivid_remote_pic_sftp'),10);
add_filter('wpvivid_get_out_of_date_remote',array($this,'wpvivid_get_out_of_date_sftp'),10,2);
add_filter('wpvivid_storage_provider_tran',array($this,'wpvivid_storage_provider_sftp'),10);
}
else
{
$this->options=$options;
}
}
public function wpvivid_add_storage_tab_sftp()
{
?>
<div class="storage-providers" remote_type="sftp" onclick="select_remote_storage(event, 'storage_account_sftp');">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/storage-sftp.png'); ?>" style="vertical-align:middle;"/><?php esc_html_e('SFTP', 'wpvivid-backuprestore'); ?>
</div>
<?php
}
public function wpvivid_add_storage_page_sftp()
{
?>
<div id="storage_account_sftp" class="storage-account-page" style="display:none;">
<div style="padding: 0 10px 10px 0;">
<strong><?php esc_html_e('Enter Your SFTP Account', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="sftp" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. SFTP-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="sftp" name="host" placeholder="<?php esc_attr_e('Server Address', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the server address.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="sftp" name="username" placeholder="<?php esc_attr_e('User Name', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the user name.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="password" class="regular-text" autocomplete="new-password" option="sftp" name="password" placeholder="<?php esc_attr_e('User Password', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the user password.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="sftp" name="port" placeholder="<?php esc_attr_e('Port', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/\D/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the server port.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="sftp" name="path" placeholder="<?php esc_attr_e('Absolute path must exist(e.g. /var)', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter an absolute path and a custom subdirectory (optional) for holding the backups of current website. For example, /var/customfolder/', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-select">
<label>
<input type="checkbox" option="sftp" name="default" checked /><?php esc_html_e('Set as the default remote storage.', 'wpvivid-backuprestore'); ?>
</label>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Once checked, all this sites backups sent to a remote storage destination will be uploaded to this storage by default.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" option="add-remote" type="submit" value="<?php esc_attr_e('Test and Add', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to connect to SFTP server and add it to the storage list below.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<?php
}
public function wpvivid_edit_storage_page_sftp()
{
?>
<div id="remote_storage_edit_sftp" class="postbox storage-account-block remote-storage-edit" style="display:none;">
<div style="padding: 0 10px 10px 0;">
<strong><?php esc_html_e('Enter Your SFTP Account', 'wpvivid-backuprestore'); ?></strong>
</div>
<table class="wp-list-table widefat plugins" style="width:100%;">
<tbody>
<form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-sftp" name="name" placeholder="<?php esc_attr_e('Enter a unique alias: e.g. SFTP-001', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/[^a-zA-Z0-9\-_]/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('A name to help you identify the storage if you have multiple remote storage connected.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-sftp" name="host" placeholder="<?php esc_attr_e('Server Address', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the server address.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-sftp" name="username" placeholder="<?php esc_attr_e('User Name', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the user name.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="password" class="regular-text" autocomplete="new-password" option="edit-sftp" name="password" placeholder="<?php esc_attr_e('User Password', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the user password.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-sftp" name="port" placeholder="<?php esc_attr_e('Port', 'wpvivid-backuprestore'); ?>" onkeyup="value=value.replace(/\D/g,'')" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter the server port.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" autocomplete="off" option="edit-sftp" name="path" placeholder="<?php esc_attr_e('Absolute path must exist(e.g. /var)', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Enter an absolute path and a custom subdirectory (optional) for holding the backups of current website. For example, /var/customfolder/', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</form>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" option="edit-remote" type="submit" value="<?php esc_attr_e('Save Changes', 'wpvivid-backuprestore'); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i><?php esc_html_e('Click the button to save the changes.', 'wpvivid-backuprestore'); ?></i>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<?php
}
public function wpvivid_remote_pic_sftp($remote)
{
$remote['sftp']['default_pic'] = '/admin/partials/images/storage-sftp(gray).png';
$remote['sftp']['selected_pic'] = '/admin/partials/images/storage-sftp.png';
$remote['sftp']['title'] = 'SFTP';
return $remote;
}
public function test_connect()
{
$host = $this->options['host'];
$username = $this->options['username'];
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1){
$password = base64_decode($this->options['password']);
}
else {
$password = $this->options['password'];
}
$path = $this->options['path'];
$port = empty($this->options['port'])?22:$this->options['port'];
$conn = $this->do_connect($host,$username,$password,$port);
if(!is_subclass_of($conn,'Net_SSH2'))
{
return $conn;
}
$str = $this->do_chdir($conn,$path);
if($str['result'] == WPVIVID_SUCCESS)
{
if($conn->put(trailingslashit($path) . 'testfile', 'test data', NET_SFTP_STRING))
{
$this -> _delete($conn ,trailingslashit($path) . 'testfile');
return array('result'=>WPVIVID_SUCCESS);
}
return array('result'=>WPVIVID_FAILED,'error'=>'Failed to create a test file. Please try again later.');
}else{
return $str;
}
}
public function sanitize_options($skip_name='')
{
$ret['result']=WPVIVID_FAILED;
if(!isset($this->options['name']))
{
$ret['error']="Warning: An alias for remote storage is required.";
return $ret;
}
$this->options['name']=sanitize_text_field($this->options['name']);
if(empty($this->options['name']))
{
$ret['error']="Warning: An alias for remote storage is required.";
return $ret;
}
$remoteslist=WPvivid_Setting::get_all_remote_options();
foreach ($remoteslist as $key=>$value)
{
if(isset($value['name'])&&$value['name'] == $this->options['name']&&$skip_name!=$value['name'])
{
$ret['error']="Warning: The alias already exists in storage list.";
return $ret;
}
}
if(!isset($this->options['host']))
{
$ret['error']="Warning: The IP Address is required.";
return $ret;
}
$this->options['host']=sanitize_text_field($this->options['host']);
if(empty($this->options['host']))
{
$ret['error']="Warning: The IP Address is required.";
return $ret;
}
if(!isset($this->options['username']))
{
$ret['error']="Warning: The username is required.";
return $ret;
}
$this->options['username']=sanitize_text_field($this->options['username']);
if(empty($this->options['username']))
{
$ret['error']="Warning: The username is required.";
return $ret;
}
if(!isset($this->options['password'])||empty($this->options['password']))
{
$ret['error']="Warning: The password is required.";
return $ret;
}
//$this->options['password']=sanitize_text_field($this->options['password']);
if(empty($this->options['password']))
{
$ret['error']="Warning: The password is required.";
return $ret;
}
$this->options['password'] = base64_encode($this->options['password']);
$this->options['is_encrypt'] = 1;
if(!isset($this->options['port']))
{
$ret['error']="Warning: The port number is required.";
return $ret;
}
$this->options['port']=sanitize_text_field($this->options['port']);
if(empty($this->options['port']))
{
$ret['error']="Warning: The port number is required.";
return $ret;
}
if(!isset($this->options['path'])||empty($this->options['path']))
{
$ret['error']="Warning: The storage path is required.";
return $ret;
}
$this->options['path']=sanitize_text_field($this->options['path']);
if(empty($this->options['path']))
{
$ret['error']="Warning: The storage path is required.";
return $ret;
}
$ret['result']=WPVIVID_SUCCESS;
$ret['options']=$this->options;
return $ret;
}
function do_connect($host,$username,$password,$port)
{
include_once WPVIVID_PLUGIN_DIR . '/includes/customclass/class-wpvivid-extend-sftp.php';
$conn = new WPvivid_Net_SFTP($host,$port,$this -> timeout);
$conn -> setTimeout($this->timeout);
$ret = $conn->login($username,$password);
if(!$ret)
{
return array('result'=>WPVIVID_FAILED,'error'=>'The connection failed because of incorrect credentials or server connection timeout. Please try again.');
}
return $conn;
}
function do_chdir($conn,$path)
{
@$conn->mkdir($path);
// See if the directory now exists
if (!$conn->chdir($path))
{
@$conn->disconnect();
return array('result'=>WPVIVID_FAILED,'error'=>'Failed to create a backup. Make sure you have sufficient privileges to perform the operation.');
}
return array('result'=>WPVIVID_SUCCESS);
}
function _delete($conn , $file)
{
$result = $conn ->delete($file , true);
return $result;
}
public function upload($task_id,$files,$callback='')
{
global $wpvivid_plugin;
$this -> callback = $callback;
if(empty($this->options['port']))
$this->options['port'] = 22;
$host = $this->options['host'];
$username = $this->options['username'];
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1){
$password = base64_decode($this->options['password']);
}
else {
$password = $this->options['password'];
}
$path = $this->options['path'];
$port = $this->options['port'];
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SFTP);
if(empty($upload_job))
{
$job_data=array();
foreach ($files as $file)
{
$file_data['size']=filesize($file);
$file_data['uploaded']=0;
$job_data[basename($file)]=$file_data;
}
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SFTP,WPVIVID_UPLOAD_UNDO,'Start uploading',$job_data);
$upload_job=WPvivid_taskmanager::get_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SFTP);
}
$wpvivid_plugin->wpvivid_log->WriteLog('Connecting to server '.$host,'notice');
$conn = $this->do_connect($host,$username,$password,$port);
if(is_array($conn) && $conn['result'] ==WPVIVID_FAILED)
{
return $conn;
}
$wpvivid_plugin->wpvivid_log->WriteLog('chdir '.$path,'notice');
$str = $this->do_chdir($conn,$path);
if($str['result'] == WPVIVID_FAILED)
return $str;
foreach ($files as $key => $file)
{
if(is_array($upload_job['job_data']) &&array_key_exists(basename($file),$upload_job['job_data']))
{
if($upload_job['job_data'][basename($file)]['uploaded']==1)
continue;
}
$wpvivid_plugin->wpvivid_log->WriteLog('Start uploading '.basename($file),'notice');
$this -> last_time = time();
$this -> last_size = 0;
if(!file_exists($file))
return array('result'=>WPVIVID_FAILED,'error'=>$file.' not found. The file might has been moved, renamed or deleted. Please back it up again.');
$wpvivid_plugin->set_time_limit($task_id);
for($i =0;$i <WPVIVID_REMOTE_CONNECT_RETRY_TIMES;$i ++)
{
$this -> last_time = time();
$this->current_file_name=basename($file);
$this -> current_file_size = filesize($file);
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SFTP,WPVIVID_UPLOAD_UNDO,'Start uploading '.basename($file).'.',$upload_job['job_data']);
$result = $conn->put(trailingslashit($path) . basename($file), $file, NET_SFTP_LOCAL_FILE| NET_SFTP_RESUME_START, -1, -1, array($this , 'upload_callback'));
if($result)
{
WPvivid_taskmanager::wpvivid_reset_backup_retry_times($task_id);
$wpvivid_plugin->wpvivid_log->WriteLog('Finished uploading '.basename($file),'notice');
$upload_job['job_data'][basename($file)]['uploaded']=1;
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',WPVIVID_REMOTE_SFTP,WPVIVID_UPLOAD_SUCCESS,'Uploading '.basename($file).' completed.',$upload_job['job_data']);
break;
}
if(!$result && $i == (WPVIVID_REMOTE_CONNECT_RETRY_TIMES - 1))
{
$conn -> disconnect();
return array('result'=>WPVIVID_FAILED,'error'=>'Uploading '.$file.' to SFTP server failed. '.$file.' might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.');
}
sleep(WPVIVID_REMOTE_CONNECT_RETRY_INTERVAL);
}
}
$conn -> disconnect();
return array('result'=>WPVIVID_SUCCESS);
}
public function download($file,$local_path,$callback = '')
{
try {
global $wpvivid_plugin;
$this->callback = $callback;
$this->current_file_name = $file['file_name'];
$this->current_file_size = $file['size'];
$host = $this->options['host'];
$username = $this->options['username'];
if(isset($this->options['is_encrypt']) && $this->options['is_encrypt'] == 1){
$password = base64_decode($this->options['password']);
}
else {
$password = $this->options['password'];
}
$path = $this->options['path'];
$port = empty($this->options['port']) ? 22 : $this->options['port'];
$local_path = trailingslashit($local_path) . $file['file_name'];
$file_size = $file['size'];
$remote_file_name = trailingslashit($path) . $file['file_name'];
$wpvivid_plugin->wpvivid_download_log->WriteLog('Connecting SFTP server.','notice');
$conn = $this->do_connect($host, $username, $password, $port);
$progress = 0;
if (!is_subclass_of($conn, 'Net_SSH2')) {
return $conn;
}
$wpvivid_plugin->wpvivid_download_log->WriteLog('Create local file.','notice');
$local_file = fopen($local_path, 'ab');
if (!$local_file) {
return array('result' => WPVIVID_FAILED, 'error' => 'Unable to create the local file. Please make sure the folder is writable and try again.');
}
$stat = fstat($local_file);
$offset = $stat['size'];
$progress = floor(($offset / $file_size) * 100);
$wpvivid_plugin->wpvivid_download_log->WriteLog('Downloading file ' . $file['file_name'] . ', Size: ' . $file['size'] ,'notice');
$result = $conn->get($remote_file_name, $local_file, $offset, -1, array($this, 'download_callback'));
@fclose($local_file);
if(filesize($local_path) == $file['size']){
if($wpvivid_plugin->wpvivid_check_zip_valid()) {
$res = TRUE;
}
else{
$res = FALSE;
}
}
else{
$res = FALSE;
}
if ($result && $res) {
return array('result' => WPVIVID_SUCCESS);
} else {
return array('result' => WPVIVID_FAILED, 'error' => 'Downloading ' . $remote_file_name . ' failed. ' . $remote_file_name . ' might be deleted or network doesn\'t work properly. Please verify the file and confirm the network connection and try again later.');
}
}
catch (Exception $error){
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('result'=>WPVIVID_FAILED, 'error'=>$message);
}
}
public function delete($remote,$files){
$host = $remote['options']['host'];
$username = $remote['options']['username'];
if(isset($remote['options']['is_encrypt']) && $remote['options']['is_encrypt'] == 1){
$password = base64_decode($remote['options']['password']);
}
else {
$password = $remote['options']['password'];
}
$path = $remote['options']['path'];
$port = empty($remote['options']['port'])?22:$remote['options']['port'];
$conn = $this->do_connect($host,$username,$password,$port);
if(!is_subclass_of($conn,'Net_SSH2')){
return $conn;
}
foreach ($files as $file)
{
$file=trailingslashit($path).$file;
$this -> _delete($conn , $file);
}
return array('result'=>WPVIVID_SUCCESS);
}
public function get_last_error()
{
if($this->error_str===false)
{
$this->error_str='connection time out.';
}
return $this->error_str;
}
public function upload_callback($offset){
if((time() - $this -> last_time) >3)
{
if(is_callable($this -> callback)){
call_user_func_array($this -> callback,array($offset,$this -> current_file_name,
$this->current_file_size,$this -> last_time,$this -> last_size));
}
$this -> last_size = $offset;
$this -> last_time = time();
}
}
public function download_callback($offset){
if((time() - $this -> last_time) >3){
if(is_callable($this -> callback)){
call_user_func_array($this -> callback,array($offset,$this -> current_file_name,
$this->current_file_size,$this -> last_time,$this -> last_size));
}
$this -> last_size = $offset;
$this -> last_time = time();
}
}
public function cleanup($files)
{
$remote['options'] = $this -> options;
return $this -> delete($remote,$files);
}
public function wpvivid_get_out_of_date_sftp($out_of_date_remote, $remote)
{
if($remote['type'] == WPVIVID_REMOTE_SFTP){
$out_of_date_remote = $remote['path'];
}
return $out_of_date_remote;
}
public function wpvivid_storage_provider_sftp($storage_type)
{
if($storage_type == WPVIVID_REMOTE_SFTP){
$storage_type = 'SFTP';
}
return $storage_type;
}
} includes/class-wpvivid-importer.php 0000644 00000306350 15132770567 0013541 0 ustar 00 <?php
/**
* WPvivid addon: yes
* Addon Name: wpvivid-backup-pro-all-in-one
* Description: Pro
* Version: 1.9.1
* Need_init: yes
* Interface Name: WPvivid_media_importer
*/
if ( ! class_exists( 'WP_List_Table' ) )
{
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class WPvivid_Export_List extends WP_List_Table
{
public $list;
public $page_num;
public $parent;
public function __construct( $args = array() )
{
global $wpdb;
parent::__construct(
array(
'plural' => 'import',
'screen' => 'import',
)
);
}
public function set_parent($parent)
{
$this->parent=$parent;
}
public function set_list($list, $page_num=1)
{
$this->list=$list;
$this->page_num=$page_num;
}
public function get_columns()
{
$posts_columns = array();
$posts_columns['file_name'] = __( 'File Name', 'wpvivid-backuprestore' );
$posts_columns['export_type'] = __( 'Post Types', 'wpvivid-backuprestore' );
$posts_columns['posts_count'] = __( 'Count', 'wpvivid-backuprestore' );
$posts_columns['media_size'] = __( 'Media Files Size', 'wpvivid-backuprestore' );
$posts_columns['import'] = __( 'Action', 'wpvivid-backuprestore' );
return $posts_columns;
}
protected function display_tablenav( $which ) {
$total_items =sizeof($this->list);
if($total_items > 10) {
if ('top' === $which) {
wp_nonce_field('bulk-' . $this->_args['plural']);
}
?>
<div class="tablenav <?php echo esc_attr($which); ?>">
<?php if ($this->has_items()) : ?>
<div class="alignleft actions bulkactions">
<?php $this->bulk_actions($which); ?>
</div>
<?php
endif;
$this->extra_tablenav($which);
$this->pagination($which);
?>
<br class="clear"/>
</div>
<?php
}
}
function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$this->_column_headers = array($columns, $hidden, $sortable);
$total_items =sizeof($this->list);
if($total_items > 10) {
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => 10,
)
);
}
}
public function has_items()
{
return !empty($this->list);
}
public function column_cb( $item )
{
?>
<input id="cb-select-<?php echo esc_attr($item['id']); ?>" type="checkbox" name="export[]" value="<?php echo esc_attr($item['id']); ?>"/>
<?php
}
public function _column_file_name( $item, $classes, $data, $primary )
{
echo '<td>
<div>
'.esc_html($item['file_name']).'
</div>
<div style="padding-bottom: 5px;">
<div class="backuptime">Data Modified: ' .esc_html(gmdate('M-d-Y H:i', $item['time'])) . '</div>
</div>
</td>';
}
public function _column_export_type( $item, $classes, $data, $primary )
{
$export = $item['export_type'] === 'page' ? 'Page' : 'Post';
echo '<td style="color: #000;">
<div>
<div style="float:left;padding:10px 10px 10px 0;">';
esc_html_e('Type: ', 'wpvivid-backuprestore');
echo esc_html($export).'</div>
</div>
</td>';
}
public function _column_posts_count( $item, $classes, $data, $primary )
{
echo '<td style="min-width:100px;">
<div style="float:left;padding:10px 10px 10px 0;">
'.esc_html($item['posts_count']).'
</div>
</td>';
}
public function _column_media_size( $item, $classes, $data, $primary )
{
echo '<td style="min-width:100px;">
<div style="float:left;padding:10px 10px 10px 0;">
'.esc_html($item['media_size']).'
</div>
</td>';
}
public function _column_import( $item )
{
echo '<td style="min-width:100px;">
<div class="export-list-import" style="cursor:pointer;padding:10px 0 10px 0;">
<img src="' . esc_url(WPVIVID_PLUGIN_URL . '/admin/partials/images/Restore.png') . '" style="vertical-align:middle;" /><span>' ; esc_html_e('Import', 'wpvivid-backuprestore') ;
echo '</span>
</div>
</td>';
}
public function display_rows()
{
$this->_display_rows( $this->list );
}
private function _display_rows($lists)
{
$page_lists=$lists;
$page=$this->get_pagenum();
$count=0;
while ( $count<$page )
{
$page_lists = array_splice( $lists, 0, 10);
$count++;
}
foreach ( $page_lists as $key=>$item )
{
$item['id']=$key;
$this->single_row($item);
}
?>
<?php
}
public function get_pagenum()
{
if($this->page_num=='first')
{
$this->page_num=1;
}
else if($this->page_num=='last')
{
$this->page_num=$this->_pagination_args['total_pages'];
}
$pagenum = $this->page_num ? $this->page_num : 0;
if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
{
$pagenum = $this->_pagination_args['total_pages'];
}
return max( 1, $pagenum );
}
public function single_row($item)
{
?>
<tr id="<?php echo esc_attr($item['id']) ?>" class="wpvivid-export-list-item">
<?php $this->single_row_columns( $item ); ?>
</tr>
<?php
}
protected function pagination( $which ) {
if ( empty( $this->_pagination_args ) ) {
return;
}
$total_items = $this->_pagination_args['total_items'];
$total_pages = $this->_pagination_args['total_pages'];
$infinite_scroll = false;
if ( isset( $this->_pagination_args['infinite_scroll'] ) ) {
$infinite_scroll = $this->_pagination_args['infinite_scroll'];
}
if ( 'top' === $which && $total_pages > 1 ) {
$this->screen->render_screen_reader_content( 'heading_pagination' );
}
$output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items, 'wpvivid-backuprestore' ), number_format_i18n( $total_items ) ) . '</span>';
$current = $this->get_pagenum();
$removable_query_args = wp_removable_query_args();
$current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
$current_url = remove_query_arg( $removable_query_args, $current_url );
$page_links = array();
$total_pages_before = '<span class="paging-input">';
$total_pages_after = '</span></span>';
$disable_first = $disable_last = $disable_prev = $disable_next = false;
if ( $current == 1 ) {
$disable_first = true;
$disable_prev = true;
}
if ( $current == 2 ) {
$disable_first = true;
}
if ( $current == $total_pages ) {
$disable_last = true;
$disable_next = true;
}
if ( $current == $total_pages - 1 ) {
$disable_last = true;
}
if ( $disable_first ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>';
} else {
$page_links[] = sprintf(
"<div class='first-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'First page', 'wpvivid-backuprestore' ),
'«'
);
}
if ( $disable_prev ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>';
} else {
$page_links[] = sprintf(
"<div class='prev-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Previous page', 'wpvivid-backuprestore' ),
'‹'
);
}
if ( 'bottom' === $which ) {
$html_current_page = $current;
$total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
} else {
$html_current_page = sprintf(
"%s<input class='current-page' id='current-page-selector-import' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
'<label for="current-page-selector-import" class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</label>',
$current,
strlen( $total_pages )
);
}
$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
$page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging', 'wpvivid-backuprestore' ), $html_current_page, $html_total_pages ) . $total_pages_after;
if ( $disable_next ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>';
} else {
$page_links[] = sprintf(
"<div class='next-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Next page', 'wpvivid-backuprestore' ),
'›'
);
}
if ( $disable_last ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>';
} else {
$page_links[] = sprintf(
"<div class='last-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'Last page', 'wpvivid-backuprestore' ),
'»'
);
}
$pagination_links_class = 'pagination-links';
if ( ! empty( $infinite_scroll ) ) {
$pagination_links_class .= ' hide-if-js';
}
$output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
if ( $total_pages ) {
$page_class = $total_pages < 2 ? ' one-page' : '';
} else {
$page_class = ' no-pages';
}
$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
echo $this->_pagination;
}
}
class WPvivid_Impoter_taskmanager
{
public static function new_task($task_id,$files,$options)
{
$task['id']=$task_id;
$task['status']['start_time']=time();
$task['status']['run_time']=time();
$task['status']['timeout']=time();
$task['status']['str']='ready';
$task['status']['resume_count']=0;
$task['options']=$options;
$task['data']['files']=$files;
self::update_task($task_id,$task);
}
public static function get_files($task_id)
{
$task=self::get_task($task_id);
return $task['data']['files'];
}
public static function get_options($task_id)
{
$task=self::get_task($task_id);
return $task['options'];
}
public static function get_tasks(){
$default = array();
return $options = get_option('wpvivid_importer_task_list', $default);
}
public static function get_task($task_id)
{
$default = array();
$tasks = get_option('wpvivid_importer_task_list', $default);
if(array_key_exists ($task_id, $tasks)) {
return $tasks[$task_id];
}
else {
return false;
}
}
public static function update_task($task_id, $task)
{
$default = array();
$options = get_option('wpvivid_importer_task_list', $default);
$options[$task_id]=$task;
WPvivid_Setting::update_option('wpvivid_importer_task_list', $options);
}
public static function delete_task($task_id){
$options = get_option('wpvivid_importer_task_list', array());
unset($options[$task_id]);
WPvivid_Setting::update_option('wpvivid_importer_task_list', $options);
}
public static function get_import_task_status($task_id){
$tasks=self::get_tasks();
if(array_key_exists ($task_id, $tasks)) {
$task = $tasks[$task_id];
return $task['status']['str'];
}
else {
return false;
}
}
public static function update_import_task_status($task_id, $status, $reset_start_time=false, $reset_timeout=false, $resume_count=false, $error=''){
$tasks=self::get_tasks();
if(array_key_exists ($task_id, $tasks))
{
$task = $tasks[$task_id];
$task['status']['run_time']=time();
if($reset_start_time)
$task['status']['start_time']=time();
if(!empty($status)) {
$task['status']['str']=$status;
}
if($reset_timeout)
$task['status']['timeout']=time();
if($resume_count!==false) {
$task['status']['resume_count']=$resume_count;
}
if(!empty($error)) {
$task['status']['error']=$error;
}
self::update_task($task_id, $task);
return $task;
}
else {
return false;
}
}
}
class WPvivid_import_data
{
public $import_log = false;
public $import_log_file;
public function __construct()
{
$this->import_log_file = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR.DIRECTORY_SEPARATOR.'wpvivid_import_log.txt';
}
public function wpvivid_create_import_log()
{
$this->import_log=new WPvivid_Log();
$this->import_log->CreateLogFile($this->import_log_file, 'has_folder', 'import');
}
public function wpvivid_write_import_log($message, $type)
{
if($this->import_log===false)
{
$this->import_log=new WPvivid_Log();
$this->import_log->OpenLogFile($this->import_log_file,'has_folder');
}
clearstatcache();
if(filesize($this->import_log_file)>4*1024*1024)
{
$this->import_log->CloseFile();
wp_delete_file($this->import_log_file);
$this->import_log=null;
$this->import_log=new WPvivid_Log();
$this->import_log->OpenLogFile($this->import_log_file,'has_folder');
}
$this->import_log->WriteLog($message, $type);
}
public function get_log_content()
{
$buffer = '';
if(file_exists($this->import_log_file)){
$file = fopen($this->import_log_file, 'r');
if (!$file) {
return '';
}
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
}
return $buffer;
}
}
global $xml_file_name;
class WPvivid_media_importer
{
var $max_wxr_version = 1.2; // max. supported WXR version
var $id; // WXR attachment ID
var $default_user;
// information to import from WXR file
var $version;
var $authors = array();
var $posts = array();
var $terms = array();
var $categories = array();
var $tags = array();
var $base_url = '';
var $new_site_url='';
// mappings from old information to new
var $processed_authors = array();
var $author_mapping = array();
var $processed_terms = array();
var $processed_posts = array();
var $post_orphans = array();
var $processed_menu_items = array();
var $menu_item_orphans = array();
var $missing_menu_items = array();
var $fetch_attachments = false;
var $url_remap = array();
var $featured_images = array();
public $import_log;
public function __construct()
{
}
public function import($id)
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$this->import_log = new WPvivid_import_data();
@set_time_limit(900);
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR;
$files=WPvivid_Impoter_taskmanager::get_files($id);
define(PCLZIP_TEMPORARY_DIR,dirname($path));
global $xml_file_name;
foreach ($files as $file)
{
$file_path=$path.DIRECTORY_SEPARATOR.$file;
$this->import_log->wpvivid_write_import_log('Prepare to retrieve file info, file name: '.$file_path, 'notice');
$archive = new WPvivid_PclZip($file_path);
$ret=$this->get_file_info($file_path);
if($ret['result']=='failed')
{
$this->import_log->wpvivid_write_import_log('Failed to retrieve file info, error: '.$ret['error'], 'notice');
WPvivid_Impoter_taskmanager::update_import_task_status($id, 'error', true, false, false, $ret['error']);
return $ret;
}
$this->import_log->wpvivid_write_import_log('Retrieving file info is completed.', 'notice');
$xml_file=$ret['json_data']['xml_file'];
$xml_file_name = $ret['json_data']['xml_file'];
$this->import_log->wpvivid_write_import_log('Prepare to extract, file name: '.$xml_file, 'notice');
$zip_ret = $archive->extract(WPVIVID_PCLZIP_OPT_BY_NAME,basename($xml_file),WPVIVID_PCLZIP_OPT_PATH,$path,WPVIVID_PCLZIP_OPT_REPLACE_NEWER,WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,16);
if(!$zip_ret)
{
$this->import_log->wpvivid_write_import_log('Failed to extract, error: '.$archive->errorInfo(true), 'notice');
WPvivid_Impoter_taskmanager::update_import_task_status($id, 'error', true, false, false, $archive->errorInfo(true));
$ret['result']='failed';
$ret['error'] = $archive->errorInfo(true);
return $ret;
}
$this->import_log->wpvivid_write_import_log('The file extracton is completed, file name: '.$xml_file, 'notice');
$this->import_log->wpvivid_write_import_log('Prepare to extract, file name: '.$file_path, 'notice');
$zip_ret = $archive->extract(WPVIVID_PCLZIP_OPT_PATH, WP_CONTENT_DIR, WPVIVID_PCLZIP_OPT_REPLACE_NEWER, WPVIVID_PCLZIP_CB_PRE_EXTRACT, 'wpvivid_function_pre_extract_import_callback', WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,16);
if(!$zip_ret)
{
$this->import_log->wpvivid_write_import_log('Failed to extract, error: '.$archive->errorInfo(true), 'notice');
WPvivid_Impoter_taskmanager::update_import_task_status($id, 'error', true, false, false, $archive->errorInfo(true));
$ret['result']='failed';
$ret['error'] = $archive->errorInfo(true);
return $ret;
}
$this->import_log->wpvivid_write_import_log('The file extracton is completed, file name: '.$file_path, 'notice');
@set_time_limit(900);
$file_path=$path.DIRECTORY_SEPARATOR.$xml_file;
$this->import_log->wpvivid_write_import_log('Prepare import, file name: '.$file_path, 'notice');
$ret=$this->_import($file_path, WPvivid_Impoter_taskmanager::get_options($id));
if($ret['result']=='failed')
{
$this->import_log->wpvivid_write_import_log('Failed to import, error: '.$ret['error'], 'notice');
WPvivid_Impoter_taskmanager::update_import_task_status($id, 'error', true, false, false, $ret['error']);
return $ret;
}
$this->import_log->wpvivid_write_import_log('Import task is completed, file name: '.$file_path, 'notice');
@wp_delete_file($file_path);
}
$this->replace_domain();
$ret['result']='success';
$ret['files']=$files;
$this->import_log->wpvivid_write_import_log('Import task succeeded.', 'notice');
WPvivid_Impoter_taskmanager::update_import_task_status($id, 'completed', false);
return $ret;
}
public function get_file_info($file_name)
{
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
$ret=$zip->get_json_data($file_name, 'export');
if($ret['result'] === WPVIVID_SUCCESS)
{
$json=$ret['json_data'];
$json = json_decode($json, 1);
if (is_null($json))
{
return array('result'=>WPVIVID_FAILED,'error'=>'Failed to decode json');
} else {
return array('result'=>WPVIVID_SUCCESS,'json_data'=>$json);
}
}
else {
return $ret;
}
}
public function _import($file,$options)
{
if(isset($options['user']))
{
$this->default_user=$options['user'];
}
else
{
$this->default_user=get_current_user_id();
}
if(isset($options['update_exist']))
{
$update_exist=$options['update_exist'];
}
else
{
$update_exist=false;
}
$ret=$this->import_start( $file );
if($ret['result']=='failed')
{
return $ret;
}
$ret=$this->get_author_mapping();
if($ret['result']=='failed')
{
return $ret;
}
wp_suspend_cache_invalidation( true );
$ret=$this->process_categories();
if($ret['result']=='failed')
{
return $ret;
}
$ret=$this->process_tags();
if($ret['result']=='failed')
{
return $ret;
}
$ret=$this->process_terms();
if($ret['result']=='failed')
{
return $ret;
}
$ret=$this->process_posts_ex($update_exist);
if($ret['result']=='failed')
{
return $ret;
}
wp_suspend_cache_invalidation( false );
$ret=$this->import_end();
return $ret;
}
private function import_start( $file )
{
$this->import_log->wpvivid_write_import_log('Analyze the imported file, file name: '.$file, 'notice');
$import_data = $this->parse( $file );
if( is_wp_error( $import_data ) )
{
$this->import_log->wpvivid_write_import_log('Failed to analyze a file, file name: '.$file, 'notice');
$ret['result']='failed';
$ret['error']=$import_data->get_error_message();
return $ret;
}
$this->version = $import_data['version'];
$this->get_authors_from_import( $import_data );
$this->posts = $import_data['posts'];
$this->terms = $import_data['terms'];
$this->categories = $import_data['categories'];
$this->tags = $import_data['tags'];
$this->base_url = esc_url( $import_data['base_url'] );
$this->import_log->wpvivid_write_import_log('The file analysis is completed, file name: '.$file, 'notice');
$ret['result']='success';
return $ret;
}
private function get_author_mapping()
{
$ret['result']='success';
return $ret;
/*
$create_users = false;
foreach ( (array) $_POST['imported_authors'] as $i => $old_login )
{
// Multisite adds strtolower to sanitize_user. Need to sanitize here to stop breakage in process_posts.
$santized_old_login = sanitize_user( $old_login, true );
$old_id = isset( $this->authors[$old_login]['author_id'] ) ? intval($this->authors[$old_login]['author_id']) : false;
if ( ! empty( $_POST['user_map'][$i] ) )
{
$user = get_userdata( intval($_POST['user_map'][$i]) );
if ( isset( $user->ID ) ) {
if ( $old_id )
$this->processed_authors[$old_id] = $user->ID;
$this->author_mapping[$santized_old_login] = $user->ID;
}
} else if ( $create_users )
{
if ( ! empty($_POST['user_new'][$i]) )
{
$user_id = wp_create_user( $_POST['user_new'][$i], wp_generate_password() );
} else if ( $this->version != '1.0' )
{
$user_data = array(
'user_login' => $old_login,
'user_pass' => wp_generate_password(),
'user_email' => isset( $this->authors[$old_login]['author_email'] ) ? $this->authors[$old_login]['author_email'] : '',
'display_name' => $this->authors[$old_login]['author_display_name'],
'first_name' => isset( $this->authors[$old_login]['author_first_name'] ) ? $this->authors[$old_login]['author_first_name'] : '',
'last_name' => isset( $this->authors[$old_login]['author_last_name'] ) ? $this->authors[$old_login]['author_last_name'] : '',
);
$user_id = wp_insert_user( $user_data );
}
if ( ! is_wp_error( $user_id ) )
{
if ( $old_id )
$this->processed_authors[$old_id] = $user_id;
$this->author_mapping[$santized_old_login] = $user_id;
} else {
printf( __( 'Failed to create new user for %s. Their posts will be attributed to the current user.', 'wordpress-importer' ), esc_html($this->authors[$old_login]['author_display_name']) );
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
echo ' ' . $user_id->get_error_message();
echo '<br />';
}
}
// failsafe: if the user_id was invalid, default to the current user
if ( ! isset( $this->author_mapping[$santized_old_login] ) )
{
if ( $old_id )
$this->processed_authors[$old_id] = (int) get_current_user_id();
$this->author_mapping[$santized_old_login] = (int) get_current_user_id();
}
}
*/
}
private function process_categories()
{
$ret['result']='success';
$this->categories = apply_filters( 'wp_import_categories', $this->categories );
$this->import_log->wpvivid_write_import_log('Start importing categories.', 'notice');
if ( empty( $this->categories ) ) {
$this->import_log->wpvivid_write_import_log('Categories import is completed.', 'notice');
return $ret;
}
foreach ( $this->categories as $cat )
{
// if the category already exists leave it alone
$term_id = term_exists( $cat['category_nicename'], 'category' );
if ( $term_id )
{
if ( is_array($term_id) ) $term_id = $term_id['term_id'];
if ( isset($cat['term_id']) )
$this->processed_terms[intval($cat['term_id'])] = (int) $term_id;
continue;
}
$category_parent = empty( $cat['category_parent'] ) ? 0 : category_exists( $cat['category_parent'] );
$category_description = isset( $cat['category_description'] ) ? $cat['category_description'] : '';
$catarr = array(
'category_nicename' => $cat['category_nicename'],
'category_parent' => $category_parent,
'cat_name' => $cat['cat_name'],
'category_description' => $category_description
);
$catarr = wp_slash( $catarr );
$id = wp_insert_category( $catarr );
if ( ! is_wp_error( $id ) )
{
if ( isset($cat['term_id']) )
$this->processed_terms[intval($cat['term_id'])] = $id;
} else {
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
{
$this->import_log->wpvivid_write_import_log('Failed to import categories, error: '.$id->get_error_message(), 'notice');
$ret['result']='failed';
$ret['error']='Failed to import category '.$cat['category_nicename'].' '.$id->get_error_message();
return $ret;
}
continue;
}
$this->process_termmeta( $cat, $id['term_id'] );
}
unset( $this->categories );
$this->import_log->wpvivid_write_import_log('Categories import is completed.', 'notice');
return $ret;
}
private function process_termmeta( $term, $term_id )
{
if ( ! isset( $term['termmeta'] ) )
{
$term['termmeta'] = array();
}
$term['termmeta'] = apply_filters( 'wp_import_term_meta', $term['termmeta'], $term_id, $term );
if ( empty( $term['termmeta'] ) ) {
return;
}
foreach ( $term['termmeta'] as $meta )
{
$key = apply_filters( 'import_term_meta_key', $meta['key'], $term_id, $term );
if ( ! $key ) {
continue;
}
// Export gets meta straight from the DB so could have a serialized string
$value = maybe_unserialize( $meta['value'] );
add_term_meta( $term_id, $key, $value );
do_action( 'import_term_meta', $term_id, $key, $value );
}
}
private function process_tags()
{
$ret['result']='success';
$this->tags = apply_filters( 'wp_import_tags', $this->tags );
$this->import_log->wpvivid_write_import_log('Start importing tags.', 'notice');
if ( empty( $this->tags ) ){
$this->import_log->wpvivid_write_import_log('Tags import is completed.', 'notice');
return $ret;
}
foreach ( $this->tags as $tag )
{
$term_id = term_exists( $tag['tag_slug'], 'post_tag' );
if ( $term_id )
{
if ( is_array($term_id) ) $term_id = $term_id['term_id'];
if ( isset($tag['term_id']) )
$this->processed_terms[intval($tag['term_id'])] = (int) $term_id;
continue;
}
$tag = wp_slash( $tag );
$tag_desc = isset( $tag['tag_description'] ) ? $tag['tag_description'] : '';
$tagarr = array( 'slug' => $tag['tag_slug'], 'description' => $tag_desc );
$id = wp_insert_term( $tag['tag_name'], 'post_tag', $tagarr );
if ( ! is_wp_error( $id ) )
{
if ( isset($tag['term_id']) )
$this->processed_terms[intval($tag['term_id'])] = $id['term_id'];
} else {
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
{
$this->import_log->wpvivid_write_import_log('Failed to import tags, error: '.$id->get_error_message(), 'notice');
$ret['result']='failed';
$ret['error']='Failed to import post tag '.$tag['tag_name'].' '.$id->get_error_message();
return $ret;
}
continue;
}
$this->process_termmeta( $tag, $id['term_id'] );
}
unset( $this->tags );
$this->import_log->wpvivid_write_import_log('Tags import is completed.', 'notice');
return $ret;
}
private function process_terms()
{
$ret['result']='success';
$this->terms = apply_filters( 'wp_import_terms', $this->terms );
$this->import_log->wpvivid_write_import_log('Start importing terms.', 'notice');
if ( empty( $this->terms ) ) {
$this->import_log->wpvivid_write_import_log('Terms import is completed.', 'notice');
return $ret;
}
foreach ( $this->terms as $term )
{
// if the term already exists in the correct taxonomy leave it alone
$term_id = term_exists( $term['slug'], $term['term_taxonomy'] );
if ( $term_id ) {
if ( is_array($term_id) ) $term_id = $term_id['term_id'];
if ( isset($term['term_id']) )
$this->processed_terms[intval($term['term_id'])] = (int) $term_id;
continue;
}
if ( empty( $term['term_parent'] ) ) {
$parent = 0;
} else {
$parent = term_exists( $term['term_parent'], $term['term_taxonomy'] );
if ( is_array( $parent ) ) $parent = $parent['term_id'];
}
$term = wp_slash( $term );
$description = isset( $term['term_description'] ) ? $term['term_description'] : '';
$termarr = array( 'slug' => $term['slug'], 'description' => $description, 'parent' => intval($parent) );
$id = wp_insert_term( $term['term_name'], $term['term_taxonomy'], $termarr );
if ( ! is_wp_error( $id ) ) {
if ( isset($term['term_id']) )
$this->processed_terms[intval($term['term_id'])] = $id['term_id'];
} else {
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
{
$this->import_log->wpvivid_write_import_log('Failed to import terms, error: '.$id->get_error_message(), 'notice');
$ret['result']='failed';
$ret['error']='Failed to import '.$term['term_taxonomy'].' '.$term['term_name'].' '.$id->get_error_message();
return $ret;
}
continue;
}
$this->process_termmeta( $term, $id['term_id'] );
}
unset( $this->terms );
$this->import_log->wpvivid_write_import_log('Terms import is completed.', 'notice');
return $ret;
}
private function process_posts_ex($update_exist=false)
{
$this->import_log->wpvivid_write_import_log('Start importing posts.', 'notice');
$ret['result']='success';
$this->posts = apply_filters( 'wp_import_posts', $this->posts );
foreach ( $this->posts as $post )
{
$this->import_log->wpvivid_write_import_log('Post id: '.$post['post_id'], 'notice');
$post = apply_filters( 'wp_import_post_data_raw', $post );
$post_type_object = get_post_type_object( $post['post_type'] );
$post_exists = post_exists( $post['post_title'], '', $post['post_date'] );
$post_exists = apply_filters( 'wp_import_existing_post', $post_exists, $post );
if ( $post_exists && get_post_type( $post_exists ) == $post['post_type'] )
{
$this->import_log->wpvivid_write_import_log('The post already exists.', 'notice');
$comment_post_ID=$post_id = $post_exists;
$this->processed_posts[ intval( $post['post_id'] ) ] = intval( $post_exists );
if($update_exist)
{
$post_parent = (int) $post['post_parent'];
if ( $post_parent )
{
// if we already know the parent, map it to the new local ID
if ( isset( $this->processed_posts[$post_parent] ) )
{
$post_parent = $this->processed_posts[$post_parent];
// otherwise record the parent for later
} else {
$this->post_orphans[intval($post['post_id'])] = $post_parent;
$post_parent = 0;
}
}
$author = sanitize_user( $post['post_author'], true );
if ( isset( $this->author_mapping[$author] ) ) {
$author = $this->author_mapping[$author];
}
else {
$author = (int)$this->default_user;
}
$postdata = array(
'ID' => $post['post_id'], 'post_author' => $author, 'post_date' => $post['post_date'],
'post_date_gmt' => $post['post_date_gmt'], 'post_content' => $post['post_content'],
'post_excerpt' => $post['post_excerpt'], 'post_title' => $post['post_title'],
'post_status' => $post['status'], 'post_name' => $post['post_name'],
'comment_status' => $post['comment_status'], 'ping_status' => $post['ping_status'],
'guid' => $post['guid'], 'post_parent' => $post_parent, 'menu_order' => $post['menu_order'],
'post_type' => $post['post_type'], 'post_password' => $post['post_password']
);
wp_update_post($postdata);
if ( ! empty( $post['postmeta'] ) )
{
foreach ( $post['postmeta'] as $meta )
{
$key = apply_filters( 'import_post_meta_key', $meta['key'], $post_id, $post );
$value = false;
if ( '_edit_last' == $key )
{
if ( isset( $this->processed_authors[intval($meta['value'])] ) )
$value = $this->processed_authors[intval($meta['value'])];
else
$key = false;
}
if ( $key )
{
// export gets meta straight from the DB so could have a serialized string
if ( ! $value )
$value = maybe_unserialize( $meta['value'] );
if(metadata_exists('post', $post_id, $key))
{
//update_post_meta($post_id,$key,$value);
update_post_meta($post_id, wp_slash( $key ), wp_slash_strings_only( $value ));
}
else
{
//add_post_meta( $post_id, $key, $value );
add_post_meta( $post_id, wp_slash( $key ), wp_slash_strings_only( $value ) );
}
do_action( 'import_post_meta', $post_id, $key, $value );
// if the post has a featured image, take note of this in case of remap
if ( '_thumbnail_id' == $key )
$this->featured_images[$post_id] = (int) $value;
}
}
}
}
} else {
$post_parent = (int) $post['post_parent'];
if ( $post_parent )
{
// if we already know the parent, map it to the new local ID
if ( isset( $this->processed_posts[$post_parent] ) )
{
$post_parent = $this->processed_posts[$post_parent];
// otherwise record the parent for later
} else {
$this->post_orphans[intval($post['post_id'])] = $post_parent;
$post_parent = 0;
}
}
// map the post author
$author = sanitize_user( $post['post_author'], true );
if ( isset( $this->author_mapping[$author] ) ) {
$author = $this->author_mapping[$author];
}
else {
$author = (int)$this->default_user;
}
$postdata = array(
'import_id' => $post['post_id'], 'post_author' => $author, 'post_date' => $post['post_date'],
'post_date_gmt' => $post['post_date_gmt'], 'post_content' => $post['post_content'],
'post_excerpt' => $post['post_excerpt'], 'post_title' => $post['post_title'],
'post_status' => $post['status'], 'post_name' => $post['post_name'],
'comment_status' => $post['comment_status'], 'ping_status' => $post['ping_status'],
'guid' => $post['guid'], 'post_parent' => $post_parent, 'menu_order' => $post['menu_order'],
'post_type' => $post['post_type'], 'post_password' => $post['post_password']
);
$original_post_ID = $post['post_id'];
$postdata = apply_filters( 'wp_import_post_data_processed', $postdata, $post );
$postdata = wp_slash( $postdata );
if ( 'attachment' == $postdata['post_type'] )
{
$remote_url = ! empty($post['attachment_url']) ? $post['attachment_url'] : $post['guid'];
// try to use _wp_attached file for upload folder placement to ensure the same location as the export site
// e.g. location is 2003/05/image.jpg but the attachment post_date is 2010/09, see media_handle_upload()
$postdata['upload_date'] = $post['post_date'];
if ( isset( $post['postmeta'] ) )
{
foreach( $post['postmeta'] as $meta )
{
if ( $meta['key'] == '_wp_attached_file' ) {
if ( preg_match( '%^[0-9]{4}/[0-9]{2}%', $meta['value'], $matches ) )
$postdata['upload_date'] = $matches[0];
break;
}
}
$postmeta=$post['postmeta'];
}
else
{
$postmeta=false;
}
$comment_post_ID = $post_id = $this->process_attachment_ex( $postdata, $remote_url ,$postmeta);
} else {
$comment_post_ID =$post_id = wp_insert_post( $postdata, true );
do_action( 'wp_import_insert_post', $post_id, $original_post_ID, $postdata, $post );
}
if ( is_wp_error( $post_id ) )
{
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
{
$ret['result']='failed';
$ret['error']='Failed to import '.$post_type_object->labels->singular_name.' '.$post['post_title'].' '.$post_id->get_error_message();
return $ret;
}
continue;
}
if ( $post['is_sticky'] == 1 )
stick_post( $post_id );
// map pre-import ID to local ID
$this->processed_posts[intval($post['post_id'])] = (int) $post_id;
}
if($post_exists)
continue;
if ( ! isset( $post['terms'] ) )
$post['terms'] = array();
$post['terms'] = apply_filters( 'wp_import_post_terms', $post['terms'], $post_id, $post );
// add categories, tags and other terms
if ( ! empty( $post['terms'] ) )
{
$terms_to_set = array();
foreach ( $post['terms'] as $term )
{
// back compat with WXR 1.0 map 'tag' to 'post_tag'
$taxonomy = ( 'tag' == $term['domain'] ) ? 'post_tag' : $term['domain'];
$term_exists = term_exists( $term['slug'], $taxonomy );
$term_id = is_array( $term_exists ) ? $term_exists['term_id'] : $term_exists;
if ( ! $term_id )
{
$t = wp_insert_term( $term['name'], $taxonomy, array( 'slug' => $term['slug'] ) );
if ( ! is_wp_error( $t ) )
{
$term_id = $t['term_id'];
do_action( 'wp_import_insert_term', $t, $term, $post_id, $post );
} else {
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
{
$this->import_log->wpvivid_write_import_log('Failed to import post, error: '.$post_id->get_error_message(), 'notice');
$ret['result']='failed';
$ret['error']='Failed to import '.esc_html($taxonomy).' '.esc_html($term['name']).' '.$post_id->get_error_message();
return $ret;
}
continue;
}
}
$terms_to_set[$taxonomy][] = intval( $term_id );
}
foreach ( $terms_to_set as $tax => $ids )
{
$tt_ids = wp_set_post_terms( $post_id, $ids, $tax );
do_action( 'wp_import_set_post_terms', $tt_ids, $ids, $tax, $post_id, $post );
}
unset( $post['terms'], $terms_to_set );
}
if ( ! isset( $post['comments'] ) )
$post['comments'] = array();
$post['comments'] = apply_filters( 'wp_import_post_comments', $post['comments'], $post_id, $post );
// add/update comments
if ( ! empty( $post['comments'] ) )
{
$num_comments = 0;
$inserted_comments = array();
foreach ( $post['comments'] as $comment )
{
$comment_id = $comment['comment_id'];
$newcomments[$comment_id]['comment_post_ID'] = $comment_post_ID;
$newcomments[$comment_id]['comment_author'] = $comment['comment_author'];
$newcomments[$comment_id]['comment_author_email'] = $comment['comment_author_email'];
$newcomments[$comment_id]['comment_author_IP'] = $comment['comment_author_IP'];
$newcomments[$comment_id]['comment_author_url'] = $comment['comment_author_url'];
$newcomments[$comment_id]['comment_date'] = $comment['comment_date'];
$newcomments[$comment_id]['comment_date_gmt'] = $comment['comment_date_gmt'];
$newcomments[$comment_id]['comment_content'] = $comment['comment_content'];
$newcomments[$comment_id]['comment_approved'] = $comment['comment_approved'];
$newcomments[$comment_id]['comment_type'] = $comment['comment_type'];
$newcomments[$comment_id]['comment_parent'] = $comment['comment_parent'];
$newcomments[$comment_id]['commentmeta'] = isset( $comment['commentmeta'] ) ? $comment['commentmeta'] : array();
if ( isset( $this->processed_authors[$comment['comment_user_id']] ) )
$newcomments[$comment_id]['user_id'] = $this->processed_authors[$comment['comment_user_id']];
}
ksort( $newcomments );
foreach ( $newcomments as $key => $comment )
{
// if this is a new post we can skip the comment_exists() check
if ( ! $post_exists || ! comment_exists( $comment['comment_author'], $comment['comment_date'] ) )
{
if ( isset( $inserted_comments[$comment['comment_parent']] ) )
$comment['comment_parent'] = $inserted_comments[$comment['comment_parent']];
$comment = wp_slash( $comment );
$comment = wp_filter_comment( $comment );
$inserted_comments[$key] = wp_insert_comment( $comment );
do_action( 'wp_import_insert_comment', $inserted_comments[$key], $comment, $comment_post_ID, $post );
foreach( $comment['commentmeta'] as $meta ) {
$value = maybe_unserialize( $meta['value'] );
add_comment_meta( $inserted_comments[$key], $meta['key'], $value );
}
$num_comments++;
}
}
unset( $newcomments, $inserted_comments, $post['comments'] );
}
if ( ! isset( $post['postmeta'] ) )
$post['postmeta'] = array();
$post['postmeta'] = apply_filters( 'wp_import_post_meta', $post['postmeta'], $post_id, $post );
// add/update post meta
if ( ! empty( $post['postmeta'] ) )
{
foreach ( $post['postmeta'] as $meta )
{
$key = apply_filters( 'import_post_meta_key', $meta['key'], $post_id, $post );
$value = false;
if ( '_edit_last' == $key )
{
if ( isset( $this->processed_authors[intval($meta['value'])] ) )
$value = $this->processed_authors[intval($meta['value'])];
else
$key = false;
}
if ( $key )
{
// export gets meta straight from the DB so could have a serialized string
if ( ! $value )
$value = maybe_unserialize( $meta['value'] );
if(metadata_exists('post', $post_id, $key))
{
//update_post_meta($post_id,$key,$value);
update_post_meta($post_id, wp_slash( $key ), wp_slash_strings_only( $value ));
}
else
{
//add_post_meta( $post_id, $key, $value );
add_post_meta( $post_id, wp_slash( $key ), wp_slash_strings_only( $value ) );
}
do_action( 'import_post_meta', $post_id, $key, $value );
// if the post has a featured image, take note of this in case of remap
if ( '_thumbnail_id' == $key )
$this->featured_images[$post_id] = (int) $value;
}
}
}
}
unset( $this->posts );
$this->import_log->wpvivid_write_import_log('Posts import is completed.', 'notice');
return $ret;
}
public function replace_domain()
{
$this->new_site_url= untrailingslashit(site_url());
$this->import_log->wpvivid_write_import_log('The original domain name: '.$this->base_url, 'notice');
$this->import_log->wpvivid_write_import_log('The current domain name: '.$this->new_site_url, 'notice');
if(empty($this->base_url))
{
$this->import_log->wpvivid_write_import_log('Failed to retrieve the original domain name: '.$this->base_url, 'notice');
return ;
}
if(empty($this->processed_posts))
{
$this->import_log->wpvivid_write_import_log('The unimported posts', 'notice');
return ;
}
if($this->base_url===$this->new_site_url)
{
$this->import_log->wpvivid_write_import_log('Replacing domain name is not required.', 'notice');
return ;
}
global $wp_query,$wpdb;
$this->import_log->wpvivid_write_import_log('Start replacing domain name.', 'notice');
$wp_query->in_the_loop = true;
while ( $next_posts = array_splice( $this->processed_posts, 0, 20 ) )
{
$where = 'WHERE ID IN (' . join(',', $next_posts) . ')';
$posts = $wpdb->get_results("SELECT * FROM {$wpdb->posts} $where");
foreach ( $posts as $post )
{
$old_data=$post->post_content;
$new_data=$this->replace_row_data($old_data);
if($new_data==$old_data)
{
$this->import_log->wpvivid_write_import_log('Post ID '.$post->ID.' is not changed.', 'notice');
continue;
}
else
{
$this->import_log->wpvivid_write_import_log('Post ID '.$post->ID.' is changed.', 'notice');
}
$post->post_content=$new_data;
wp_update_post($post);
}
}
}
private function replace_row_data($old_data)
{
$unserialize_data = @unserialize($old_data, array('allowed_classes' => false));
if($unserialize_data===false)
{
$old_data=$this->replace_string($old_data);
}
else
{
$old_data=$this->replace_serialize_data($unserialize_data);
$old_data=serialize($old_data);
/*if(is_array($unserialize_data))
{
$temp_data = array();
foreach ($unserialize_data as $key => $value)
{
$temp_data[$key]=$this->replace_string($value);
}
$old_data = $temp_data;
unset($temp_data);
$old_data=$this->replace_serialize_data($unserialize_data);
$old_data=serialize($old_data);
}
else if(is_object($unserialize_data))
{
$temp_data = $unserialize_data;
$props = get_object_vars($unserialize_data);
foreach ($props as $key => $value)
{
$temp_data->$key =$this->replace_string($value);
}
$old_data = $temp_data;
unset($temp_data);
$old_data=serialize($old_data);
}*/
}
return $old_data;
}
private function replace_serialize_data($data)
{
if(is_string($data))
{
$serialize_data =@unserialize($data, array('allowed_classes' => false));
if($serialize_data===false)
{
$data=$this->replace_string($data);
}
else
{
$data=serialize($this->replace_serialize_data($serialize_data));
}
}
else if(is_array($data))
{
foreach ($data as $key => $value)
{
if(is_string($value))
{
$data[$key]=$this->replace_string($value);
}
else if(is_array($value))
{
$data[$key]=$this->replace_serialize_data($value);
}
else if(is_object($value))
{
if (is_a($value, '__PHP_Incomplete_Class'))
{
//
}
else
{
$data[$key]=$this->replace_serialize_data($value);
}
}
}
}
else if(is_object($data))
{
$temp = $data; // new $data_class();
if (is_a($data, '__PHP_Incomplete_Class'))
{
}
else
{
$props = get_object_vars($data);
foreach ($props as $key => $value)
{
if(is_string($value))
{
$temp->$key =$this->replace_string($value);
}
else if(is_array($value))
{
$temp->$key=$this->replace_serialize_data($value);
}
else if(is_object($value))
{
$temp->$key=$this->replace_serialize_data($value);
}
}
}
$data = $temp;
unset($temp);
}
return $data;
}
private function replace_string($old_string)
{
if(!is_string($old_string))
{
return $old_string;
}
if($this->base_url!=$this->new_site_url)
{
$remove_http_link=$this->get_remove_http_link($this->base_url);
$new_remove_http_link=$this->get_remove_http_link($this->new_site_url);
if(strpos($new_remove_http_link,$remove_http_link)!==false)
{
return $this->replace_string_ex($old_string);
}
}
if($this->base_url!=$this->new_site_url)
{
$old_string=str_replace($this->base_url,$this->new_site_url,$old_string);
$old_mix_link=$this->get_mix_link($this->base_url);
if($old_mix_link!==false)
{
$old_string=str_replace($old_mix_link,$this->new_site_url,$old_string);
}
$remove_http_link=$this->get_remove_http_link($this->base_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link($this->new_site_url);
$old_string=str_replace($remove_http_link,$new_remove_http_link,$old_string);
}
$remove_http_link=$this->get_remove_http_link_ex($this->base_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link_ex($this->new_site_url);
$old_string=str_replace($remove_http_link,$new_remove_http_link,$old_string);
}
}
return $old_string;
}
private function replace_string_ex($old_string)
{
if(!is_string($old_string))
{
return $old_string;
}
if($this->base_url!=$this->new_site_url)
{
$remove_http_link=$this->get_remove_http_link($this->base_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link($this->new_site_url);
$old_string=str_replace($remove_http_link,$new_remove_http_link,$old_string);
}
$new_mix_link=$this->get_mix_link($this->new_site_url);
if($new_mix_link!==false)
{
$old_string=str_replace($new_mix_link,$this->new_site_url,$old_string);
}
$remove_http_link=$this->get_remove_http_link_ex($this->base_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link_ex($this->new_site_url);
$old_string=str_replace($remove_http_link,$new_remove_http_link,$old_string);
}
}
return $old_string;
}
private function get_remove_http_link($url)
{
if (0 === stripos($url, 'https://'))
{
$mix_link = '//'.substr($url, 8);
} elseif (0 === stripos($url, 'http://')) {
$mix_link = '//'.substr($url, 7);
}
else
{
$mix_link=false;
}
return $mix_link;
}
private function get_remove_http_link_ex($url)
{
if (0 === stripos($url, 'https://'))
{
$mix_link = '\/\/'.substr($url, 8);
} elseif (0 === stripos($url, 'http://')) {
$mix_link = '\/\/'.substr($url, 7);
}
else
{
$mix_link=false;
}
return $mix_link;
}
private function get_mix_link($url)
{
if (0 === stripos($url, 'https://'))
{
$mix_link = 'http://'.substr($url, 8);
} elseif (0 === stripos($url, 'http://')) {
$mix_link = 'https://'.substr($url, 7);
}
else
{
$mix_link=false;
}
return $mix_link;
}
function process_attachment_ex( $post, $url,$postmeta )
{
// if the URL is absolute, but does not contain address, then upload it assuming base_site_url
if ( preg_match( '|^/[\w\W]+$|', $url ) )
$url = rtrim( $this->base_url, '/' ) . $url;
$upload = $this->fetch_local_file_ex( $url, $post ,$postmeta);
if ( is_wp_error( $upload ) )
return $upload;
$post['post_mime_type']=$upload['type'];
$post['guid'] = $upload['url'];
// as per wp-admin/includes/upload.php
$post_id = wp_insert_attachment( $post, $upload['file'] );
if ( is_wp_error( $post_id ) )
{
return $post_id;
}
if ( preg_match( '!^image/!',$upload['type'] ) )
{
$parts = pathinfo( $url );
$name = basename( $parts['basename'], ".{$parts['extension']}" ); // PATHINFO_FILENAME in PHP 5.2
$parts_new = pathinfo( $upload['url'] );
$name_new = basename( $parts_new['basename'], ".{$parts_new['extension']}" );
$this->url_remap[$parts['dirname'] . '/' . $name] = $parts_new['dirname'] . '/' . $name_new;
}
return $post_id;
}
function fetch_local_file_ex($url,$post,$postmeta)
{
$file_name = basename( $url );
$upload = wp_upload_dir( $post['upload_date'] );
$new_file='';
if($postmeta!==false)
{
foreach( $postmeta as $meta )
{
if ( $meta['key'] == '_wp_attached_file' )
{
$new_file=$upload['basedir'].'/'.$meta['meta_value'];
$url = $upload['baseurl'].'/'.$meta['meta_value'];
}
}
}
if(empty($new_file))
{
$new_file = $upload['path'] . "/$file_name";
$url = $upload['url'] . "/$file_name";
}
if(!file_exists($new_file))
{
return new WP_Error( 'import_file_error', 'File not exist, file:'.$new_file );
}
$wp_filetype = wp_check_filetype( $file_name );
if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )
{
return new WP_Error( 'import_file_error', __( 'Sorry, this file type is not permitted for security reasons.', 'wpvivid-backuprestore' ) );
}
return apply_filters(
'wp_handle_upload',
array(
'file' => $new_file,
'url' => $url,
'type' => $wp_filetype['type'],
'error' => false,
),
'sideload'
);
}
function parse( $file ) {
$parser = new WPvivid_WXR_Parser();
return $parser->parse( $file );
}
function get_authors_from_import( $import_data )
{
if ( ! empty( $import_data['authors'] ) )
{
$this->authors = $import_data['authors'];
// no author information, grab it from the posts
} else {
foreach ( $import_data['posts'] as $post )
{
$login = sanitize_user( $post['post_author'], true );
if ( empty( $login ) )
{
continue;
}
if ( ! isset($this->authors[$login]) )
$this->authors[$login] = array(
'author_login' => $login,
'author_display_name' => $post['post_author']
);
}
}
}
function process_attachment( $post, $url )
{
if ( ! $this->fetch_attachments )
return new WP_Error( 'attachment_processing_error',
__( 'Fetching attachments is not enabled', 'wpvivid-backuprestore' ) );
// if the URL is absolute, but does not contain address, then upload it assuming base_site_url
if ( preg_match( '|^/[\w\W]+$|', $url ) )
$url = rtrim( $this->base_url, '/' ) . $url;
$upload = $this->fetch_local_file( $url, $post );
if ( is_wp_error( $upload ) )
return $upload;
if ( $info = wp_check_filetype( $upload['file'] ) )
$post['post_mime_type'] = $info['type'];
else
return new WP_Error( 'attachment_processing_error', __('Invalid file type', 'wpvivid-backuprestore') );
$post['guid'] = $upload['url'];
// as per wp-admin/includes/upload.php
$post_id = wp_insert_attachment( $post, $upload['file'] );
if ( is_wp_error( $post_id ) )
{
echo 'error file:'.esc_html($upload['file']);
}
//$metadata=wp_generate_attachment_metadata( $post_id, $upload['file'] );
//wp_update_attachment_metadata( $post_id,$metadata );
// remap resized image URLs, works by stripping the extension and remapping the URL stub.
if ( preg_match( '!^image/!', $info['type'] ) ) {
$parts = pathinfo( $url );
$name = basename( $parts['basename'], ".{$parts['extension']}" ); // PATHINFO_FILENAME in PHP 5.2
$parts_new = pathinfo( $upload['url'] );
$name_new = basename( $parts_new['basename'], ".{$parts_new['extension']}" );
$this->url_remap[$parts['dirname'] . '/' . $name] = $parts_new['dirname'] . '/' . $name_new;
}
return $post_id;
}
function fetch_local_file($url,$post)
{
$file_name = basename( $url );
$upload = wp_upload_dir( $post['upload_date'] );
$new_file = $upload['path'] . "/$file_name";
$url = $upload['url'] . "/$file_name";
$wp_filetype = wp_check_filetype( $file_name );
if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) ) {
return array( 'error' => __( 'Sorry, this file type is not permitted for security reasons.', 'wpvivid-backuprestore' ) );
}
if(!file_exists($new_file))
{
return new WP_Error( 'import_file_error', 'File not exist, file:'.$new_file );
}
return apply_filters(
'wp_handle_upload',
array(
'file' => $new_file,
'url' => $url,
'type' => $wp_filetype['type'],
'error' => false,
),
'sideload'
);
}
/**
* Performs post-import cleanup of files and the cache
*/
function import_end()
{
wp_import_cleanup( $this->id );
wp_cache_flush();
foreach ( get_taxonomies() as $tax ) {
delete_option( "{$tax}_children" );
_get_term_hierarchy( $tax );
}
wp_defer_term_counting( false );
wp_defer_comment_counting( false );
$ret['result']='success';
do_action( 'import_end' );
return $ret;
}
}
function wpvivid_function_pre_extract_import_callback($p_event, &$p_header)
{
global $xml_file_name;
if(strpos($p_header['filename'],$xml_file_name)!==false)
{
return 0;
}
if(strpos($p_header['filename'],'wpvivid_export_package_info.json')!==false)
{
return 0;
}
return 1;
}
/**
* WordPress Importer class for managing parsing of WXR files.
*/
class WPvivid_WXR_Parser
{
function parse( $file )
{
// Attempt to use proper XML parsers first
if ( extension_loaded( 'simplexml' ) )
{
$parser = new WPvivid_WXR_Parser_SimpleXML;
$result = $parser->parse( $file );
// If SimpleXML succeeds or this is an invalid WXR file then return the results
if ( ! is_wp_error( $result ) || 'SimpleXML_parse_error' != $result->get_error_code() )
return $result;
}
else if ( extension_loaded( 'xml' ) )
{
$parser = new WPvivid_WXR_Parser_XML;
$result = $parser->parse( $file );
// If XMLParser succeeds or this is an invalid WXR file then return the results
if ( ! is_wp_error( $result ) || 'XML_parse_error' != $result->get_error_code() )
return $result;
}
// We have a malformed XML file, so display the error and fallthrough to regex
if ( isset($result) && defined('IMPORT_DEBUG') && IMPORT_DEBUG )
{
$msg='';
if ( 'SimpleXML_parse_error' == $result->get_error_code() )
{
foreach ( $result->get_error_data() as $error )
$msg.= $error->line . ':' . $error->column . ' ' . esc_html( $error->message ) . "\n";
} else if ( 'XML_parse_error' == $result->get_error_code() )
{
$error = $result->get_error_data();
$msg.= $error[0] . ':' . $error[1] . ' ' . esc_html( $error[2] );
}
$msg.=__( 'There was an error when reading this WXR file', 'wpvivid-backuprestore' ) ;
$msg.=__( 'Details are shown above. The importer will now try again with a different parser...', 'wpvivid-backuprestore' );
return new WP_Error( 'WXR_Parser_error', $msg,'' );
}
// use regular expressions if nothing else available or this is bad XML
$parser = new WPvivid_WXR_Parser_Regex;
return $parser->parse( $file );
}
}
/**
* WXR Parser that makes use of the SimpleXML PHP extension.
*/
class WPvivid_WXR_Parser_SimpleXML
{
function parse( $file )
{
$authors = $posts = $categories = $tags = $terms = array();
$internal_errors = libxml_use_internal_errors(true);
$dom = new DOMDocument;
$old_value = null;
if ( function_exists( 'libxml_disable_entity_loader' ) ) {
$old_value = libxml_disable_entity_loader( true );
}
//$success = $dom->loadXML( file_get_contents( $file ), LIBXML_PARSEHUGE );
$success = $dom->loadXML( file_get_contents( $file ) );
if ( ! is_null( $old_value ) )
{
libxml_disable_entity_loader( $old_value );
}
if ( ! $success || isset( $dom->doctype ) )
{
return new WP_Error( 'SimpleXML_parse_error', __( 'There was an error when reading this WXR file', 'wpvivid-backuprestore' ), libxml_get_errors() );
}
$xml = simplexml_import_dom( $dom );
unset( $dom );
// halt if loading produces an error
if ( ! $xml )
return new WP_Error( 'SimpleXML_parse_error', __( 'There was an error when reading this WXR file', 'wpvivid-backuprestore' ), libxml_get_errors() );
$wxr_version = $xml->xpath('/rss/channel/wp:wxr_version');
if ( ! $wxr_version )
return new WP_Error( 'WXR_parse_error', __( 'This does not appear to be a WXR file, missing/invalid WXR version number', 'wpvivid-backuprestore' ) );
$wxr_version = (string) trim( $wxr_version[0] );
// confirm that we are dealing with the correct file format
if ( ! preg_match( '/^\d+\.\d+$/', $wxr_version ) )
return new WP_Error( 'WXR_parse_error', __( 'This does not appear to be a WXR file, missing/invalid WXR version number', 'wpvivid-backuprestore' ) );
$base_url = $xml->xpath('/rss/channel/wp:base_site_url');
$base_url = (string) trim( $base_url[0] );
$namespaces = $xml->getDocNamespaces();
if ( ! isset( $namespaces['wp'] ) )
$namespaces['wp'] = 'http://wordpress.org/export/1.1/';
if ( ! isset( $namespaces['excerpt'] ) )
$namespaces['excerpt'] = 'http://wordpress.org/export/1.1/excerpt/';
// grab authors
foreach ( $xml->xpath('/rss/channel/wp:author') as $author_arr )
{
$a = $author_arr->children( $namespaces['wp'] );
$login = (string) $a->author_login;
$authors[$login] = array(
'author_id' => (int) $a->author_id,
'author_login' => $login,
'author_email' => (string) $a->author_email,
'author_display_name' => (string) $a->author_display_name,
'author_first_name' => (string) $a->author_first_name,
'author_last_name' => (string) $a->author_last_name
);
}
// grab cats, tags and terms
foreach ( $xml->xpath('/rss/channel/wp:category') as $term_arr )
{
$t = $term_arr->children( $namespaces['wp'] );
$category = array(
'term_id' => (int) $t->term_id,
'category_nicename' => (string) $t->category_nicename,
'category_parent' => (string) $t->category_parent,
'cat_name' => (string) $t->cat_name,
'category_description' => (string) $t->category_description
);
foreach ( $t->termmeta as $meta ) {
$category['termmeta'][] = array(
'key' => (string) $meta->meta_key,
'value' => (string) $meta->meta_value
);
}
$categories[] = $category;
}
foreach ( $xml->xpath('/rss/channel/wp:tag') as $term_arr )
{
$t = $term_arr->children( $namespaces['wp'] );
$tag = array(
'term_id' => (int) $t->term_id,
'tag_slug' => (string) $t->tag_slug,
'tag_name' => (string) $t->tag_name,
'tag_description' => (string) $t->tag_description
);
foreach ( $t->termmeta as $meta ) {
$tag['termmeta'][] = array(
'key' => (string) $meta->meta_key,
'value' => (string) $meta->meta_value
);
}
$tags[] = $tag;
}
foreach ( $xml->xpath('/rss/channel/wp:term') as $term_arr )
{
$t = $term_arr->children( $namespaces['wp'] );
$term = array(
'term_id' => (int) $t->term_id,
'term_taxonomy' => (string) $t->term_taxonomy,
'slug' => (string) $t->term_slug,
'term_parent' => (string) $t->term_parent,
'term_name' => (string) $t->term_name,
'term_description' => (string) $t->term_description
);
foreach ( $t->termmeta as $meta ) {
$term['termmeta'][] = array(
'key' => (string) $meta->meta_key,
'value' => (string) $meta->meta_value
);
}
$terms[] = $term;
}
// grab posts
foreach ( $xml->channel->item as $item )
{
$post = array(
'post_title' => (string) $item->title,
'guid' => (string) $item->guid,
);
$dc = $item->children( 'http://purl.org/dc/elements/1.1/' );
$post['post_author'] = (string) $dc->creator;
$content = $item->children( 'http://purl.org/rss/1.0/modules/content/' );
$excerpt = $item->children( $namespaces['excerpt'] );
$post['post_content'] = (string) $content->encoded;
$post['post_excerpt'] = (string) $excerpt->encoded;
$wp = $item->children( $namespaces['wp'] );
$post['post_id'] = (int) $wp->post_id;
$post['post_date'] = (string) $wp->post_date;
$post['post_date_gmt'] = (string) $wp->post_date_gmt;
$post['comment_status'] = (string) $wp->comment_status;
$post['ping_status'] = (string) $wp->ping_status;
$post['post_name'] = (string) $wp->post_name;
$post['status'] = (string) $wp->status;
$post['post_parent'] = (int) $wp->post_parent;
$post['menu_order'] = (int) $wp->menu_order;
$post['post_type'] = (string) $wp->post_type;
$post['post_password'] = (string) $wp->post_password;
$post['is_sticky'] = (int) $wp->is_sticky;
if ( isset($wp->attachment_url) )
$post['attachment_url'] = (string) $wp->attachment_url;
foreach ( $item->category as $c )
{
$att = $c->attributes();
if ( isset( $att['nicename'] ) )
$post['terms'][] = array(
'name' => (string) $c,
'slug' => (string) $att['nicename'],
'domain' => (string) $att['domain']
);
}
foreach ( $wp->postmeta as $meta )
{
$post['postmeta'][] = array(
'key' => (string) $meta->meta_key,
'value' => (string) $meta->meta_value
);
}
foreach ( $wp->comment as $comment )
{
$meta = array();
if ( isset( $comment->commentmeta ) ) {
foreach ( $comment->commentmeta as $m ) {
$meta[] = array(
'key' => (string) $m->meta_key,
'value' => (string) $m->meta_value
);
}
}
$post['comments'][] = array(
'comment_id' => (int) $comment->comment_id,
'comment_author' => (string) $comment->comment_author,
'comment_author_email' => (string) $comment->comment_author_email,
'comment_author_IP' => (string) $comment->comment_author_IP,
'comment_author_url' => (string) $comment->comment_author_url,
'comment_date' => (string) $comment->comment_date,
'comment_date_gmt' => (string) $comment->comment_date_gmt,
'comment_content' => (string) $comment->comment_content,
'comment_approved' => (string) $comment->comment_approved,
'comment_type' => (string) $comment->comment_type,
'comment_parent' => (string) $comment->comment_parent,
'comment_user_id' => (int) $comment->comment_user_id,
'commentmeta' => $meta,
);
}
$posts[] = $post;
}
return array(
'authors' => $authors,
'posts' => $posts,
'categories' => $categories,
'tags' => $tags,
'terms' => $terms,
'base_url' => $base_url,
'version' => $wxr_version
);
}
}
/**
* WXR Parser that makes use of the XML Parser PHP extension.
*/
class WPvivid_WXR_Parser_XML {
var $wp_tags = array(
'wp:post_id', 'wp:post_date', 'wp:post_date_gmt', 'wp:comment_status', 'wp:ping_status', 'wp:attachment_url',
'wp:status', 'wp:post_name', 'wp:post_parent', 'wp:menu_order', 'wp:post_type', 'wp:post_password',
'wp:is_sticky', 'wp:term_id', 'wp:category_nicename', 'wp:category_parent', 'wp:cat_name', 'wp:category_description',
'wp:tag_slug', 'wp:tag_name', 'wp:tag_description', 'wp:term_taxonomy', 'wp:term_parent',
'wp:term_name', 'wp:term_description', 'wp:author_id', 'wp:author_login', 'wp:author_email', 'wp:author_display_name',
'wp:author_first_name', 'wp:author_last_name',
);
var $wp_sub_tags = array(
'wp:comment_id', 'wp:comment_author', 'wp:comment_author_email', 'wp:comment_author_url',
'wp:comment_author_IP', 'wp:comment_date', 'wp:comment_date_gmt', 'wp:comment_content',
'wp:comment_approved', 'wp:comment_type', 'wp:comment_parent', 'wp:comment_user_id',
);
function parse( $file ) {
$this->wxr_version = $this->in_post = $this->cdata = $this->data = $this->sub_data = $this->in_tag = $this->in_sub_tag = false;
$this->authors = $this->posts = $this->term = $this->category = $this->tag = array();
$xml = xml_parser_create( 'UTF-8' );
xml_parser_set_option( $xml, XML_OPTION_SKIP_WHITE, 1 );
xml_parser_set_option( $xml, XML_OPTION_CASE_FOLDING, 0 );
xml_set_object( $xml, $this );
xml_set_character_data_handler( $xml, 'cdata' );
xml_set_element_handler( $xml, 'tag_open', 'tag_close' );
if ( ! xml_parse( $xml, file_get_contents( $file ), true ) ) {
$current_line = xml_get_current_line_number( $xml );
$current_column = xml_get_current_column_number( $xml );
$error_code = xml_get_error_code( $xml );
$error_string = xml_error_string( $error_code );
return new WP_Error( 'XML_parse_error', 'There was an error when reading this WXR file', array( $current_line, $current_column, $error_string ) );
}
xml_parser_free( $xml );
if ( ! preg_match( '/^\d+\.\d+$/', $this->wxr_version ) )
return new WP_Error( 'WXR_parse_error', __( 'This does not appear to be a WXR file, missing/invalid WXR version number', 'wpvivid-backuprestore' ) );
return array(
'authors' => $this->authors,
'posts' => $this->posts,
'categories' => $this->category,
'tags' => $this->tag,
'terms' => $this->term,
'base_url' => $this->base_url,
'version' => $this->wxr_version
);
}
function tag_open( $parse, $tag, $attr ) {
if ( in_array( $tag, $this->wp_tags ) ) {
$this->in_tag = substr( $tag, 3 );
return;
}
if ( in_array( $tag, $this->wp_sub_tags ) ) {
$this->in_sub_tag = substr( $tag, 3 );
return;
}
switch ( $tag ) {
case 'category':
if ( isset($attr['domain'], $attr['nicename']) ) {
$this->sub_data['domain'] = $attr['domain'];
$this->sub_data['slug'] = $attr['nicename'];
}
break;
case 'item': $this->in_post = true;
case 'title': if ( $this->in_post ) $this->in_tag = 'post_title'; break;
case 'guid': $this->in_tag = 'guid'; break;
case 'dc:creator': $this->in_tag = 'post_author'; break;
case 'content:encoded': $this->in_tag = 'post_content'; break;
case 'excerpt:encoded': $this->in_tag = 'post_excerpt'; break;
case 'wp:term_slug': $this->in_tag = 'slug'; break;
case 'wp:meta_key': $this->in_sub_tag = 'key'; break;
case 'wp:meta_value': $this->in_sub_tag = 'value'; break;
}
}
function cdata( $parser, $cdata ) {
if ( ! trim( $cdata ) )
return;
if ( false !== $this->in_tag || false !== $this->in_sub_tag ) {
$this->cdata .= $cdata;
} else {
$this->cdata .= trim( $cdata );
}
}
function tag_close( $parser, $tag ) {
switch ( $tag ) {
case 'wp:comment':
unset( $this->sub_data['key'], $this->sub_data['value'] ); // remove meta sub_data
if ( ! empty( $this->sub_data ) )
$this->data['comments'][] = $this->sub_data;
$this->sub_data = false;
break;
case 'wp:commentmeta':
$this->sub_data['commentmeta'][] = array(
'key' => $this->sub_data['key'],
'value' => $this->sub_data['value']
);
break;
case 'category':
if ( ! empty( $this->sub_data ) ) {
$this->sub_data['name'] = $this->cdata;
$this->data['terms'][] = $this->sub_data;
}
$this->sub_data = false;
break;
case 'wp:postmeta':
if ( ! empty( $this->sub_data ) )
$this->data['postmeta'][] = $this->sub_data;
$this->sub_data = false;
break;
case 'item':
$this->posts[] = $this->data;
$this->data = false;
break;
case 'wp:category':
case 'wp:tag':
case 'wp:term':
$n = substr( $tag, 3 );
array_push( $this->$n, $this->data );
$this->data = false;
break;
case 'wp:author':
if ( ! empty($this->data['author_login']) )
$this->authors[$this->data['author_login']] = $this->data;
$this->data = false;
break;
case 'wp:base_site_url':
$this->base_url = $this->cdata;
break;
case 'wp:wxr_version':
$this->wxr_version = $this->cdata;
break;
default:
if ( $this->in_sub_tag ) {
$this->sub_data[$this->in_sub_tag] = ! empty( $this->cdata ) ? $this->cdata : '';
$this->in_sub_tag = false;
} else if ( $this->in_tag ) {
$this->data[$this->in_tag] = ! empty( $this->cdata ) ? $this->cdata : '';
$this->in_tag = false;
}
}
$this->cdata = false;
}
}
/**
* WXR Parser that uses regular expressions. Fallback for installs without an XML parser.
*/
class WPvivid_WXR_Parser_Regex {
var $authors = array();
var $posts = array();
var $categories = array();
var $tags = array();
var $terms = array();
var $base_url = '';
function __construct() {
$this->has_gzip = is_callable( 'gzopen' );
}
function parse( $file ) {
$wxr_version = $in_multiline = false;
$multiline_content = '';
$multiline_tags = array(
'item' => array( 'posts', array( $this, 'process_post' ) ),
'wp:category' => array( 'categories', array( $this, 'process_category' ) ),
'wp:tag' => array( 'tags', array( $this, 'process_tag' ) ),
'wp:term' => array( 'terms', array( $this, 'process_term' ) ),
);
$fp = $this->fopen( $file, 'r' );
if ( $fp ) {
while ( ! $this->feof( $fp ) ) {
$importline = rtrim( $this->fgets( $fp ) );
if ( ! $wxr_version && preg_match( '|<wp:wxr_version>(\d+\.\d+)</wp:wxr_version>|', $importline, $version ) )
$wxr_version = $version[1];
if ( false !== strpos( $importline, '<wp:base_site_url>' ) ) {
preg_match( '|<wp:base_site_url>(.*?)</wp:base_site_url>|is', $importline, $url );
$this->base_url = $url[1];
continue;
}
if ( false !== strpos( $importline, '<wp:author>' ) ) {
preg_match( '|<wp:author>(.*?)</wp:author>|is', $importline, $author );
$a = $this->process_author( $author[1] );
$this->authors[$a['author_login']] = $a;
continue;
}
foreach ( $multiline_tags as $tag => $handler ) {
// Handle multi-line tags on a singular line
if ( preg_match( '|<' . $tag . '>(.*?)</' . $tag . '>|is', $importline, $matches ) ) {
$this->{$handler[0]}[] = call_user_func( $handler[1], $matches[1] );
} elseif ( false !== ( $pos = strpos( $importline, "<$tag>" ) ) ) {
// Take note of any content after the opening tag
$multiline_content = trim( substr( $importline, $pos + strlen( $tag ) + 2 ) );
// We don't want to have this line added to `$is_multiline` below.
$importline = '';
$in_multiline = $tag;
} elseif ( false !== ( $pos = strpos( $importline, "</$tag>" ) ) ) {
$in_multiline = false;
$multiline_content .= trim( substr( $importline, 0, $pos ) );
$this->{$handler[0]}[] = call_user_func( $handler[1], $multiline_content );
}
}
if ( $in_multiline && $importline ) {
$multiline_content .= $importline . "\n";
}
}
$this->fclose($fp);
}
if ( ! $wxr_version )
return new WP_Error( 'WXR_parse_error', __( 'This does not appear to be a WXR file, missing/invalid WXR version number', 'wpvivid-backuprestore' ) );
return array(
'authors' => $this->authors,
'posts' => $this->posts,
'categories' => $this->categories,
'tags' => $this->tags,
'terms' => $this->terms,
'base_url' => $this->base_url,
'version' => $wxr_version
);
}
function get_tag( $string, $tag ) {
preg_match( "|<$tag.*?>(.*?)</$tag>|is", $string, $return );
if ( isset( $return[1] ) ) {
if ( substr( $return[1], 0, 9 ) == '<![CDATA[' ) {
if ( strpos( $return[1], ']]]]><![CDATA[>' ) !== false ) {
preg_match_all( '|<!\[CDATA\[(.*?)\]\]>|s', $return[1], $matches );
$return = '';
foreach( $matches[1] as $match )
$return .= $match;
} else {
$return = preg_replace( '|^<!\[CDATA\[(.*)\]\]>$|s', '$1', $return[1] );
}
} else {
$return = $return[1];
}
} else {
$return = '';
}
return $return;
}
function process_category( $c ) {
return array(
'term_id' => $this->get_tag( $c, 'wp:term_id' ),
'cat_name' => $this->get_tag( $c, 'wp:cat_name' ),
'category_nicename' => $this->get_tag( $c, 'wp:category_nicename' ),
'category_parent' => $this->get_tag( $c, 'wp:category_parent' ),
'category_description' => $this->get_tag( $c, 'wp:category_description' ),
);
}
function process_tag( $t ) {
return array(
'term_id' => $this->get_tag( $t, 'wp:term_id' ),
'tag_name' => $this->get_tag( $t, 'wp:tag_name' ),
'tag_slug' => $this->get_tag( $t, 'wp:tag_slug' ),
'tag_description' => $this->get_tag( $t, 'wp:tag_description' ),
);
}
function process_term( $t ) {
return array(
'term_id' => $this->get_tag( $t, 'wp:term_id' ),
'term_taxonomy' => $this->get_tag( $t, 'wp:term_taxonomy' ),
'slug' => $this->get_tag( $t, 'wp:term_slug' ),
'term_parent' => $this->get_tag( $t, 'wp:term_parent' ),
'term_name' => $this->get_tag( $t, 'wp:term_name' ),
'term_description' => $this->get_tag( $t, 'wp:term_description' ),
);
}
function process_author( $a ) {
return array(
'author_id' => $this->get_tag( $a, 'wp:author_id' ),
'author_login' => $this->get_tag( $a, 'wp:author_login' ),
'author_email' => $this->get_tag( $a, 'wp:author_email' ),
'author_display_name' => $this->get_tag( $a, 'wp:author_display_name' ),
'author_first_name' => $this->get_tag( $a, 'wp:author_first_name' ),
'author_last_name' => $this->get_tag( $a, 'wp:author_last_name' ),
);
}
function process_post( $post ) {
$post_id = $this->get_tag( $post, 'wp:post_id' );
$post_title = $this->get_tag( $post, 'title' );
$post_date = $this->get_tag( $post, 'wp:post_date' );
$post_date_gmt = $this->get_tag( $post, 'wp:post_date_gmt' );
$comment_status = $this->get_tag( $post, 'wp:comment_status' );
$ping_status = $this->get_tag( $post, 'wp:ping_status' );
$status = $this->get_tag( $post, 'wp:status' );
$post_name = $this->get_tag( $post, 'wp:post_name' );
$post_parent = $this->get_tag( $post, 'wp:post_parent' );
$menu_order = $this->get_tag( $post, 'wp:menu_order' );
$post_type = $this->get_tag( $post, 'wp:post_type' );
$post_password = $this->get_tag( $post, 'wp:post_password' );
$is_sticky = $this->get_tag( $post, 'wp:is_sticky' );
$guid = $this->get_tag( $post, 'guid' );
$post_author = $this->get_tag( $post, 'dc:creator' );
$post_excerpt = $this->get_tag( $post, 'excerpt:encoded' );
$post_excerpt = preg_replace_callback( '|<(/?[A-Z]+)|', array( &$this, '_normalize_tag' ), $post_excerpt );
$post_excerpt = str_replace( '<br>', '<br />', $post_excerpt );
$post_excerpt = str_replace( '<hr>', '<hr />', $post_excerpt );
$post_content = $this->get_tag( $post, 'content:encoded' );
$post_content = preg_replace_callback( '|<(/?[A-Z]+)|', array( &$this, '_normalize_tag' ), $post_content );
$post_content = str_replace( '<br>', '<br />', $post_content );
$post_content = str_replace( '<hr>', '<hr />', $post_content );
$postdata = compact( 'post_id', 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_excerpt',
'post_title', 'status', 'post_name', 'comment_status', 'ping_status', 'guid', 'post_parent',
'menu_order', 'post_type', 'post_password', 'is_sticky'
);
$attachment_url = $this->get_tag( $post, 'wp:attachment_url' );
if ( $attachment_url )
$postdata['attachment_url'] = $attachment_url;
preg_match_all( '|<category domain="([^"]+?)" nicename="([^"]+?)">(.+?)</category>|is', $post, $terms, PREG_SET_ORDER );
foreach ( $terms as $t ) {
$post_terms[] = array(
'slug' => $t[2],
'domain' => $t[1],
'name' => str_replace( array( '<![CDATA[', ']]>' ), '', $t[3] ),
);
}
if ( ! empty( $post_terms ) ) $postdata['terms'] = $post_terms;
preg_match_all( '|<wp:comment>(.+?)</wp:comment>|is', $post, $comments );
$comments = $comments[1];
if ( $comments ) {
foreach ( $comments as $comment ) {
preg_match_all( '|<wp:commentmeta>(.+?)</wp:commentmeta>|is', $comment, $commentmeta );
$commentmeta = $commentmeta[1];
$c_meta = array();
foreach ( $commentmeta as $m ) {
$c_meta[] = array(
'key' => $this->get_tag( $m, 'wp:meta_key' ),
'value' => $this->get_tag( $m, 'wp:meta_value' ),
);
}
$post_comments[] = array(
'comment_id' => $this->get_tag( $comment, 'wp:comment_id' ),
'comment_author' => $this->get_tag( $comment, 'wp:comment_author' ),
'comment_author_email' => $this->get_tag( $comment, 'wp:comment_author_email' ),
'comment_author_IP' => $this->get_tag( $comment, 'wp:comment_author_IP' ),
'comment_author_url' => $this->get_tag( $comment, 'wp:comment_author_url' ),
'comment_date' => $this->get_tag( $comment, 'wp:comment_date' ),
'comment_date_gmt' => $this->get_tag( $comment, 'wp:comment_date_gmt' ),
'comment_content' => $this->get_tag( $comment, 'wp:comment_content' ),
'comment_approved' => $this->get_tag( $comment, 'wp:comment_approved' ),
'comment_type' => $this->get_tag( $comment, 'wp:comment_type' ),
'comment_parent' => $this->get_tag( $comment, 'wp:comment_parent' ),
'comment_user_id' => $this->get_tag( $comment, 'wp:comment_user_id' ),
'commentmeta' => $c_meta,
);
}
}
if ( ! empty( $post_comments ) ) $postdata['comments'] = $post_comments;
preg_match_all( '|<wp:postmeta>(.+?)</wp:postmeta>|is', $post, $postmeta );
$postmeta = $postmeta[1];
if ( $postmeta ) {
foreach ( $postmeta as $p ) {
$post_postmeta[] = array(
'key' => $this->get_tag( $p, 'wp:meta_key' ),
'value' => $this->get_tag( $p, 'wp:meta_value' ),
);
}
}
if ( ! empty( $post_postmeta ) ) $postdata['postmeta'] = $post_postmeta;
return $postdata;
}
function _normalize_tag( $matches ) {
return '<' . strtolower( $matches[1] );
}
function fopen( $filename, $mode = 'r' ) {
if ( $this->has_gzip )
return gzopen( $filename, $mode );
return fopen( $filename, $mode );
}
function feof( $fp ) {
if ( $this->has_gzip )
return gzeof( $fp );
return feof( $fp );
}
function fgets( $fp, $len = 8192 ) {
if ( $this->has_gzip )
return gzgets( $fp, $len );
return fgets( $fp, $len );
}
function fclose( $fp ) {
if ( $this->has_gzip )
return gzclose( $fp );
return fclose( $fp );
}
} includes/class-wpvivid-setting.php 0000644 00000056406 15132770567 0013361 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_Setting
{
public static function init_option()
{
$ret=self::get_option('wpvivid_email_setting');
if(empty($ret))
{
self::set_default_email_option();
}
$ret=self::get_option('wpvivid_compress_setting');
if(empty($ret))
{
self::set_default_compress_option();
}
$ret=self::get_option('wpvivid_local_setting');
if(empty($ret))
{
self::set_default_local_option();
}
$ret=self::get_option('wpvivid_upload_setting');
if(empty($ret))
{
self::set_default_upload_option();
}
$ret=self::get_option('wpvivid_common_setting');
if(empty($ret))
{
self::set_default_common_option();
}
}
public static function get_default_option($option_name)
{
$options=array();
switch ($option_name)
{
case 'wpvivid_compress_setting':
$options=self::set_default_compress_option();
break;
case 'wpvivid_local_setting':
$options=self::set_default_local_option();
break;
case 'wpvivid_upload_setting':
$options=self::set_default_upload_option();
break;
case 'wpvivid_common_setting':
$options=self::set_default_common_option();
break;
}
return $options;
}
public static function set_default_option()
{
self::set_default_compress_option();
self::set_default_local_option();
self::set_default_upload_option();
self::set_default_common_option();
}
public static function set_default_compress_option()
{
$compress_option['compress_type']=WPVIVID_DEFAULT_COMPRESS_TYPE;
$compress_option['max_file_size']=WPVIVID_DEFAULT_MAX_FILE_SIZE;
$compress_option['no_compress']=WPVIVID_DEFAULT_NO_COMPRESS;
$compress_option['use_temp_file']=WPVIVID_DEFAULT_USE_TEMP;
$compress_option['use_temp_size']=WPVIVID_DEFAULT_USE_TEMP_SIZE;
$compress_option['exclude_file_size']=WPVIVID_DEFAULT_EXCLUDE_FILE_SIZE;
$compress_option['subpackage_plugin_upload']=WPVIVID_DEFAULT_SUBPACKAGE_PLUGIN_UPLOAD;
self::update_option('wpvivid_compress_setting',$compress_option);
return $compress_option;
}
public static function set_default_local_option()
{
$local_option['path']=WPVIVID_DEFAULT_BACKUP_DIR;
$local_option['save_local']=1;
self::update_option('wpvivid_local_setting',$local_option);
return $local_option;
}
public static function set_default_upload_option()
{
$upload_option=array();
self::update_option('wpvivid_upload_setting',$upload_option);
return $upload_option;
}
public static function set_default_email_option()
{
$email_option['send_to']=array();
$email_option['always']=true;
$email_option['email_enable']=false;
self::update_option('wpvivid_email_setting',$email_option);
return $email_option;
}
public static function set_default_common_option()
{
$sapi_type=php_sapi_name();
if($sapi_type=='cgi-fcgi'||$sapi_type==' fpm-fcgi')
{
$common_option['max_execution_time']=WPVIVID_MAX_EXECUTION_TIME_FCGI;
}
else
{
$common_option['max_execution_time']=WPVIVID_MAX_EXECUTION_TIME;
}
$common_option['log_save_location']=WPVIVID_DEFAULT_LOG_DIR;
$common_option['max_backup_count']=WPVIVID_DEFAULT_BACKUP_COUNT;
$common_option['show_admin_bar']=WPVIVID_DEFAULT_ADMIN_BAR;
//$common_option['show_tab_menu']=WPVIVID_DEFAULT_TAB_MENU;
$common_option['domain_include']=WPVIVID_DEFAULT_DOMAIN_INCLUDE;
$common_option['estimate_backup']=WPVIVID_DEFAULT_ESTIMATE_BACKUP;
$common_option['max_resume_count']=WPVIVID_RESUME_RETRY_TIMES;
$common_option['memory_limit']=WPVIVID_MEMORY_LIMIT;
$common_option['restore_memory_limit']=WPVIVID_RESTORE_MEMORY_LIMIT;
$common_option['migrate_size']=WPVIVID_MIGRATE_SIZE;
self::update_option('wpvivid_common_setting',$common_option);
return $common_option;
}
public static function get_option($option_name, $default = array())
{
$ret = get_option($option_name, $default);
if(empty($ret))
{
self::get_default_option($option_name);
}
return $ret;
}
public static function get_last_backup_message($option_name, $default = array()){
$message = self::get_option($option_name, $default);
$ret = array();
if(!empty($message['id'])) {
$ret['id'] = $message['id'];
$ret['status'] = $message['status'];
$ret['status']['start_time'] = gmdate("M d, Y H:i", $ret['status']['start_time']);
$ret['status']['run_time'] = gmdate("M d, Y H:i", $ret['status']['run_time']);
$ret['status']['timeout'] = gmdate("M d, Y H:i", $ret['status']['timeout']);
if(isset($message['options']['log_file_name']))
$ret['log_file_name'] = $message['options']['log_file_name'];
else
$ret['log_file_name'] ='';
}
return $ret;
}
public static function get_backupdir()
{
$dir=self::get_option('wpvivid_local_setting');
if(!isset($dir['path']))
{
$dir=self::set_default_local_option();
}
if(!is_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir['path']))
{
@mkdir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir['path'],0777,true);
//@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir['path'].DIRECTORY_SEPARATOR.'index.html', 'x');
$tempfile=@fopen(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir['path'].DIRECTORY_SEPARATOR.'.htaccess', 'x');
if($tempfile)
{
//$text="deny from all";
$text="<IfModule mod_rewrite.c>\r\nRewriteEngine On\r\nRewriteRule .* - [F,L]\r\n</IfModule>";
fwrite($tempfile,$text );
fclose($tempfile);
}
else
{
return false;
}
}
return $dir['path'];
}
public static function wpvivid_remove_directory($directory)
{
if(file_exists($directory))
{
if($dir_handle=@opendir($directory))
{
while($filename=readdir($dir_handle))
{
if($filename!='.' && $filename!='..')
{
$subFile=$directory."/".$filename;
if(is_dir($subFile))
{
self::wpvivid_remove_directory($subFile);
}
if(is_file($subFile))
{
wp_delete_file($subFile);
}
}
}
closedir($dir_handle);
rmdir($directory);
}
}
}
public static function wpvivid_write_htaccess_rule($wpvivid_backup_dir_htaccess)
{
$tempfile=@fopen($wpvivid_backup_dir_htaccess, 'x');
if($tempfile)
{
$text="<IfModule mod_rewrite.c>\r\nRewriteEngine On\r\nRewriteRule .* - [F,L]\r\n</IfModule>";
fwrite($tempfile,$text );
fclose($tempfile);
}
}
public static function get_save_local()
{
$local=self::get_option('wpvivid_local_setting');
if(!isset($local['save_local']))
{
$local=self::set_default_local_option();
}
return $local['save_local'];
}
public static function update_option($option_name,$options)
{
update_option($option_name,$options,'no');
}
public static function delete_option($option_name)
{
delete_option($option_name);
}
public static function get_tasks()
{
$default = array();
return $options = get_option('wpvivid_task_list', $default);
}
public static function update_task($id,$task)
{
$default = array();
$options = get_option('wpvivid_task_list', $default);
$options[$id]=$task;
self::update_option('wpvivid_task_list',$options);
}
public static function delete_task($id)
{
$default = array();
$options = get_option('wpvivid_task_list', $default);
unset($options[$id]);
self::update_option('wpvivid_task_list',$options);
}
public static function check_compress_options()
{
$options =self::get_option('wpvivid_compress_setting');
if(!isset($options['compress_type'])||!isset($options['max_file_size'])||
!isset($options['no_compress'])||!isset($options['exclude_file_size'])||
!isset($options['use_temp_file'])||!isset($options['use_temp_size']))
{
self::set_default_compress_option();
}
}
public static function check_local_options()
{
$options =self::get_option('wpvivid_local_setting');
if(!isset($options['path'])||!isset($options['save_local']))
{
self::set_default_local_option();
}
return true;
}
/*public static function get_backup_options($post)
{
self::check_compress_options();
self::check_local_options();
if($post=='files+db')
{
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_DB]=0;
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_THEMES]=0;
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_PLUGIN]=0;
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_UPLOADS]=0;
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_CONTENT]=0;
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_CORE]=0;
}
else if($post=='files')
{
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_THEMES]=0;
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_PLUGIN]=0;
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_UPLOADS]=0;
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_CONTENT]=0;
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_CORE]=0;
}
else if($post=='db')
{
$backup_options['backup']['backup_type'][WPVIVID_BACKUP_TYPE_DB]=0;
}
else
{
//return false;
}
$backup_options['compress']=self::get_option('wpvivid_compress_setting');
$backup_options['dir']=self::get_backupdir();
return $backup_options;
}*/
public static function get_remote_option($id)
{
$upload_options=self::get_option('wpvivid_upload_setting');
if(array_key_exists($id,$upload_options))
{
return $upload_options[$id];
}
else
{
return false;
}
}
public static function get_remote_options($remote_ids=array())
{
if(empty($remote_ids))
{
$remote_ids=WPvivid_Setting::get_user_history('remote_selected');
}
if(empty($remote_ids))
{
return false;
}
$options=array();
$upload_options=WPvivid_Setting::get_option('wpvivid_upload_setting');
foreach ($remote_ids as $id)
{
if(array_key_exists($id,$upload_options))
{
$options[$id]=$upload_options[$id];
}
}
if(empty($options))
return false;
else
return $options;
}
public static function get_all_remote_options()
{
$upload_options=self::get_option('wpvivid_upload_setting');
$upload_options['remote_selected']=WPvivid_Setting::get_user_history('remote_selected');
return $upload_options;
}
public static function add_remote_options($remote)
{
$upload_options=self::get_option('wpvivid_upload_setting');
$id=uniqid('wpvivid-remote-');
$remote=apply_filters('wpvivid_pre_add_remote',$remote,$id);
$upload_options[$id]=$remote;
self::update_option('wpvivid_upload_setting',$upload_options);
return $id;
}
public static function delete_remote_option($id)
{
do_action('wpvivid_delete_remote_token',$id);
$upload_options=self::get_option('wpvivid_upload_setting');
if(array_key_exists($id,$upload_options))
{
unset( $upload_options[$id]);
self::update_option('wpvivid_upload_setting',$upload_options);
return true;
}
else
{
return false;
}
}
public static function update_remote_option($remote_id,$remote)
{
$upload_options=self::get_option('wpvivid_upload_setting');
if(array_key_exists($remote_id,$upload_options))
{
$remote=apply_filters('wpvivid_pre_add_remote',$remote,$remote_id);
$upload_options[$remote_id]=$remote;
self::update_option('wpvivid_upload_setting',$upload_options);
return true;
}
else
{
return false;
}
}
public static function get_setting($all,$options_name)
{
$get_options=array();
if($all==true)
{
$get_options[]='wpvivid_email_setting';
$get_options[]='wpvivid_compress_setting';
$get_options[]='wpvivid_local_setting';
$get_options[]='wpvivid_common_setting';
$get_options = apply_filters('wpvivid_get_setting_addon', $get_options);
}
else
{
$get_options[]=$options_name;
}
$ret['result']='success';
$ret['options']=array();
foreach ($get_options as $option_name)
{
$ret['options'][$option_name]=self::get_option($option_name);
}
return $ret;
}
public static function update_setting($options)
{
foreach ($options as $option_name=>$option)
{
self::update_option($option_name,$option);
}
$ret['result']='success';
return $ret;
}
public static function export_setting_to_json($setting=true,$history=true,$review=true,$backup_list=true)
{
global $wpvivid_plugin;
$json['plugin']=$wpvivid_plugin->get_plugin_name();
$json['version']=WPVIVID_PLUGIN_VERSION;
$json['setting']=$setting;
$json['history']=$history;
$json['data']['wpvivid_init']=self::get_option('wpvivid_init');
if($setting)
{
$json['data']['wpvivid_schedule_setting']=self::get_option('wpvivid_schedule_setting');
if(!empty( $json['data']['wpvivid_schedule_setting']))
{
if(isset($json['data']['wpvivid_schedule_setting']['backup']['backup_files']))
$json['data']['wpvivid_schedule_setting']['backup_type']=$json['data']['wpvivid_schedule_setting']['backup']['backup_files'];
if(isset($json['data']['wpvivid_schedule_setting']['backup']['local']))
{
if($json['data']['wpvivid_schedule_setting']['backup']['local'] == 1){
$json['data']['wpvivid_schedule_setting']['save_local_remote']='local';
}
else{
$json['data']['wpvivid_schedule_setting']['save_local_remote']='remote';
}
}
$json['data']['wpvivid_schedule_setting']['lock']=0;
if(wp_get_schedule(WPVIVID_MAIN_SCHEDULE_EVENT))
{
$recurrence = wp_get_schedule(WPVIVID_MAIN_SCHEDULE_EVENT);
$timestamp = wp_next_scheduled(WPVIVID_MAIN_SCHEDULE_EVENT);
$json['data']['wpvivid_schedule_setting']['recurrence']=$recurrence;
$json['data']['wpvivid_schedule_setting']['next_start']=$timestamp;
}
}
else
{
$json['data']['wpvivid_schedule_setting']=array();
}
$json['data']['wpvivid_compress_setting']=self::get_option('wpvivid_compress_setting');
$json['data']['wpvivid_local_setting']=self::get_option('wpvivid_local_setting');
$json['data']['wpvivid_upload_setting']=self::get_option('wpvivid_upload_setting');
$json['data']['wpvivid_common_setting']=self::get_option('wpvivid_common_setting');
$json['data']['wpvivid_email_setting']=self::get_option('wpvivid_email_setting');
$json['data']['wpvivid_saved_api_token']=self::get_option('wpvivid_saved_api_token');
$json = apply_filters('wpvivid_export_setting_addon', $json);
/*if(isset($json['data']['wpvivid_local_setting']['path'])){
unset($json['data']['wpvivid_local_setting']['path']);
}*/
if(isset($json['data']['wpvivid_common_setting']['log_save_location'])){
unset($json['data']['wpvivid_common_setting']['log_save_location']);
}
if(isset($json['data']['wpvivid_common_setting']['backup_prefix'])){
unset($json['data']['wpvivid_common_setting']['backup_prefix']);
}
}
if($history)
{
$json['data']['wpvivid_task_list']=self::get_option('wpvivid_task_list');
$json['data']['wpvivid_last_msg']=self::get_option('wpvivid_last_msg');
$json['data']['wpvivid_user_history']=self::get_option('wpvivid_user_history');
$json = apply_filters('wpvivid_history_addon', $json);
}
if($backup_list){
$json['data']['wpvivid_backup_list']=self::get_option('wpvivid_backup_list');
$json = apply_filters('wpvivid_backup_list_addon', $json);
}
else{
if(isset($json['data']['wpvivid_new_remote_list']))
{
unset($json['data']['wpvivid_new_remote_list']);
}
}
if($review)
{
$json['data']['wpvivid_need_review']=self::get_option('wpvivid_need_review');
$json['data']['cron_backup_count']=self::get_option('cron_backup_count');
$json['data']['wpvivid_review_msg']=self::get_option('wpvivid_review_msg');
$json['data']['wpvivid_review_time']=self::get_option('wpvivid_review_time', false);
$json['data']['wpvivid_review_type']=self::get_option('wpvivid_review_type', false);
$json = apply_filters('wpvivid_review_addon', $json);
}
return $json;
}
public static function import_json_to_setting($json)
{
wp_cache_delete('notoptions', 'options');
wp_cache_delete('alloptions', 'options');
foreach ($json['data'] as $option_name=>$option)
{
wp_cache_delete($option_name, 'options');
delete_option($option_name);
self::update_option($option_name,$option);
}
}
public static function set_max_backup_count($count)
{
$options=self::get_option('wpvivid_common_setting');
$options['max_backup_count']=$count;
self::update_option('wpvivid_common_setting',$options);
}
public static function get_max_backup_count()
{
$options=self::get_option('wpvivid_common_setting');
if(isset($options['max_backup_count']))
{
return $options['max_backup_count'];
}
else
{
return WPVIVID_MAX_BACKUP_COUNT;
}
}
public static function get_mail_setting()
{
return self::get_option('wpvivid_email_setting');
}
public static function get_admin_bar_setting(){
$options=self::get_option('wpvivid_common_setting');
if(isset($options['show_admin_bar']))
{
if($options['show_admin_bar']){
return true;
}
else{
return false;
}
}
else
{
return true;
}
}
public static function update_user_history($action,$value)
{
$options=self::get_option('wpvivid_user_history');
$options[$action]=$value;
self::update_option('wpvivid_user_history',$options);
}
public static function get_user_history($action)
{
$options=self::get_option('wpvivid_user_history');
if(array_key_exists($action,$options))
{
return $options[$action];
}
else
{
return array();
}
}
public static function get_retain_local_status()
{
$options=self::get_option('wpvivid_common_setting');
if(isset($options['retain_local']))
{
if($options['retain_local']){
return true;
}
else{
return false;
}
}
else
{
return false;
}
}
public static function get_sync_data()
{
$data['setting']['wpvivid_compress_setting']=self::get_option('wpvivid_compress_setting');
$data['setting']['wpvivid_local_setting']=self::get_option('wpvivid_local_setting');
$data['setting']['wpvivid_common_setting']=self::get_option('wpvivid_common_setting');
$data['setting']['wpvivid_email_setting']=self::get_option('wpvivid_email_setting');
$data['setting']['cron_backup_count']=self::get_option('cron_backup_count');
$data['schedule']=self::get_option('wpvivid_schedule_setting');
$data['remote']['upload']=self::get_option('wpvivid_upload_setting');
$data['remote']['history']=self::get_option('wpvivid_user_history');
$data['last_backup_report'] = get_option('wpvivid_backup_reports');
$data['setting_addon'] = $data['setting'];
$data['setting_addon']['wpvivid_staging_options']=array();
$data['backup_custom_setting']=array();
$data['menu_capability']=array();
$data['white_label_setting']=array();
$data['incremental_backup_setting']=array();
$data['schedule_addon']=array();
$data['time_zone']=false;
$data['is_pro']=false;
$data['is_install']=false;
$data['is_login']=false;
$data['latest_version']='';
$data['current_version']='';
$data['dashboard_version'] = '';
$data['addons_info'] = array();
$data=apply_filters('wpvivid_get_wpvivid_info_addon_mainwp_ex', $data);
return $data;
}
} includes/upload-cleaner/class-wpvivid-upload-cleaner-setting.php 0000644 00000114566 15132770567 0021147 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
if ( ! class_exists( 'WP_List_Table' ) )
{
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class WPvivid_Exclude_Files_List extends WP_List_Table
{
public $list;
public $type;
public $page_num;
public $parent;
public function __construct( $args = array() )
{
global $wpdb;
parent::__construct(
array(
'plural' => 'upload_files',
'screen' => 'upload_files',
)
);
}
public function set_parent($parent)
{
$this->parent=$parent;
}
public function set_list($list,$page_num=1)
{
$this->list=$list;
$this->page_num=$page_num;
}
protected function get_table_classes()
{
return array( 'widefat striped' );
}
public function get_columns()
{
$sites_columns = array(
'cb' => ' ',
'file_regex' => __( 'File Regex', 'wpvivid-backuprestore' )
);
return $sites_columns;
}
public function get_pagenum()
{
if($this->page_num=='first')
{
$this->page_num=1;
}
else if($this->page_num=='last')
{
$this->page_num=$this->_pagination_args['total_pages'];
}
$pagenum = $this->page_num ? $this->page_num : 0;
if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
{
$pagenum = $this->_pagination_args['total_pages'];
}
return max( 1, $pagenum );
}
public function column_cb( $item )
{
echo '<input type="checkbox" name="regex_list" />';
}
public function column_file_regex( $item )
{
echo esc_html($item);
}
public function has_items()
{
return !empty($this->list);
}
public function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$this->_column_headers = array($columns, $hidden, $sortable);
$total_items =sizeof($this->list);
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => 10,
)
);
}
public function display_rows()
{
$this->_display_rows( $this->list );
}
private function _display_rows( $list )
{
$page=$this->get_pagenum();
$page_list=$list;
$temp_page_list=array();
$count=0;
while ( $count<$page )
{
$temp_page_list = array_splice( $page_list, 0, 10);
$count++;
}
foreach ( $temp_page_list as $key=>$item)
{
$this->single_row($item);
}
}
public function single_row($item)
{
?>
<tr file_regex="<?php echo esc_attr($item)?>">
<?php $this->single_row_columns( $item ); ?>
</tr>
<?php
}
protected function pagination( $which )
{
if ( empty( $this->_pagination_args ) )
{
return;
}
$total_items = $this->_pagination_args['total_items'];
$total_pages = $this->_pagination_args['total_pages'];
$infinite_scroll = false;
if ( isset( $this->_pagination_args['infinite_scroll'] ) )
{
$infinite_scroll = $this->_pagination_args['infinite_scroll'];
}
if ( 'top' === $which && $total_pages > 1 )
{
$this->screen->render_screen_reader_content( 'heading_pagination' );
}
$output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items, 'wpvivid-backuprestore' ), number_format_i18n( $total_items ) ) . '</span>';
$current = $this->get_pagenum();
$page_links = array();
$total_pages_before = '<span class="paging-input">';
$total_pages_after = '</span></span>';
$disable_first = $disable_last = $disable_prev = $disable_next = false;
if ( $current == 1 ) {
$disable_first = true;
$disable_prev = true;
}
if ( $current == 2 ) {
$disable_first = true;
}
if ( $current == $total_pages ) {
$disable_last = true;
$disable_next = true;
}
if ( $current == $total_pages - 1 ) {
$disable_last = true;
}
if ( $disable_first ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>';
} else {
$page_links[] = sprintf(
"<div class='first-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'First page', 'wpvivid-backuprestore' ),
'«'
);
}
if ( $disable_prev ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>';
} else {
$page_links[] = sprintf(
"<div class='prev-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Previous page', 'wpvivid-backuprestore' ),
'‹'
);
}
if ( 'bottom' === $which ) {
$html_current_page = $current;
$total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
} else {
$html_current_page = sprintf(
"%s<input class='current-page' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
'<label class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</label>',
$current,
strlen( $total_pages )
);
}
$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
$page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging', 'wpvivid-backuprestore' ), $html_current_page, $html_total_pages ) . $total_pages_after;
if ( $disable_next ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>';
} else {
$page_links[] = sprintf(
"<div class='next-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Next page', 'wpvivid-backuprestore' ),
'›'
);
}
if ( $disable_last ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>';
} else {
$page_links[] = sprintf(
"<div class='last-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'Last page', 'wpvivid-backuprestore' ),
'»'
);
}
$pagination_links_class = 'pagination-links';
if ( ! empty( $infinite_scroll ) ) {
$pagination_links_class .= ' hide-if-js';
}
$output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
if ( $total_pages ) {
$page_class = $total_pages < 2 ? ' one-page' : '';
} else {
$page_class = ' no-pages';
}
$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
echo $this->_pagination;
}
protected function display_tablenav( $which ) {
$css_type = '';
if ( 'top' === $which ) {
wp_nonce_field( 'bulk-' . $this->_args['plural'] );
$css_type = 'margin: 0 0 10px 0';
}
else if( 'bottom' === $which ) {
$css_type = 'margin: 10px 0 0 0';
}
$total_pages = $this->_pagination_args['total_pages'];
if ( $total_pages >1)
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<div class="alignleft actions bulkactions">
<label for="wpvivid_uc_exclude_regex_bulk_action" class="screen-reader-text">Select bulk action</label>
<select name="action" id="wpvivid_uc_exclude_regex_bulk_action">
<option value="remove_exclude_regex">Remove</option>
</select>
<input type="submit" class="button action" value="Apply">
</div>
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
else
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<div class="alignleft actions bulkactions">
<label for="wpvivid_uc_exclude_regex_bulk_action" class="screen-reader-text">Select bulk action</label>
<select name="action" id="wpvivid_uc_exclude_regex_bulk_action">
<option value="remove_exclude_regex">Remove</option>
</select>
<input type="submit" class="button action" value="Apply">
</div>
<br class="clear" />
</div>
<?php
}
}
public function display()
{
$singular = $this->_args['singular'];
$this->display_tablenav( 'top' );
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<table class="wp-list-table <?php echo esc_attr(implode( ' ', $this->get_table_classes() )); ?>" >
<thead>
<tr>
<?php $this->print_column_headers(); ?>
</tr>
</thead>
<tbody id="the-list"
<?php
if ( $singular ) {
echo esc_attr(" data-wp-lists='list:$singular'");
}
?>
>
<?php $this->display_rows_or_placeholder(); ?>
</tbody>
<tfoot>
<tr>
<?php $this->print_column_headers( false ); ?>
</tr>
</tfoot>
</table>
<?php
}
}
class WPvivid_Post_Type_List extends WP_List_Table
{
public $list;
public $type;
public $page_num;
public $parent;
public function __construct( $args = array() )
{
global $wpdb;
parent::__construct(
array(
'plural' => 'upload_files',
'screen' => 'upload_files',
)
);
}
public function set_parent($parent)
{
$this->parent=$parent;
}
public function set_list($list,$page_num=1)
{
$this->list=$list;
$this->page_num=$page_num;
}
protected function get_table_classes()
{
return array( 'widefat striped' );
}
public function get_columns()
{
$sites_columns = array(
'cb' => ' ',
'post_type' => __( 'Post Type', 'wpvivid-backuprestore' )
);
return $sites_columns;
}
public function get_pagenum()
{
if($this->page_num=='first')
{
$this->page_num=1;
}
else if($this->page_num=='last')
{
$this->page_num=$this->_pagination_args['total_pages'];
}
$pagenum = $this->page_num ? $this->page_num : 0;
if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
{
$pagenum = $this->_pagination_args['total_pages'];
}
return max( 1, $pagenum );
}
public function column_cb( $item )
{
echo '<input type="checkbox" name="post_type" />';
}
public function column_post_type( $item )
{
echo esc_attr($item);
}
public function has_items()
{
return !empty($this->list);
}
public function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$this->_column_headers = array($columns, $hidden, $sortable);
$total_items =sizeof($this->list);
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => 10,
)
);
}
public function display_rows()
{
$this->_display_rows( $this->list );
}
private function _display_rows( $list )
{
$page=$this->get_pagenum();
$page_list=$list;
$temp_page_list=array();
$count=0;
while ( $count<$page )
{
$temp_page_list = array_splice( $page_list, 0, 10);
$count++;
}
foreach ( $temp_page_list as $key=>$item)
{
$this->single_row($item);
}
}
public function single_row($item)
{
?>
<tr post_type="<?php echo esc_attr($item)?>">
<?php $this->single_row_columns( $item ); ?>
</tr>
<?php
}
protected function pagination( $which )
{
if ( empty( $this->_pagination_args ) )
{
return;
}
$total_items = $this->_pagination_args['total_items'];
$total_pages = $this->_pagination_args['total_pages'];
$infinite_scroll = false;
if ( isset( $this->_pagination_args['infinite_scroll'] ) )
{
$infinite_scroll = $this->_pagination_args['infinite_scroll'];
}
if ( 'top' === $which && $total_pages > 1 )
{
$this->screen->render_screen_reader_content( 'heading_pagination' );
}
$output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items, 'wpvivid-backuprestore' ), number_format_i18n( $total_items ) ) . '</span>';
$current = $this->get_pagenum();
$page_links = array();
$total_pages_before = '<span class="paging-input">';
$total_pages_after = '</span></span>';
$disable_first = $disable_last = $disable_prev = $disable_next = false;
if ( $current == 1 ) {
$disable_first = true;
$disable_prev = true;
}
if ( $current == 2 ) {
$disable_first = true;
}
if ( $current == $total_pages ) {
$disable_last = true;
$disable_next = true;
}
if ( $current == $total_pages - 1 ) {
$disable_last = true;
}
if ( $disable_first ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>';
} else {
$page_links[] = sprintf(
"<div class='first-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'First page', 'wpvivid-backuprestore' ),
'«'
);
}
if ( $disable_prev ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>';
} else {
$page_links[] = sprintf(
"<div class='prev-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Previous page', 'wpvivid-backuprestore' ),
'‹'
);
}
if ( 'bottom' === $which ) {
$html_current_page = $current;
$total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
} else {
$html_current_page = sprintf(
"%s<input class='current-page' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
'<label class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</label>',
$current,
strlen( $total_pages )
);
}
$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
$page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging', 'wpvivid-backuprestore' ), $html_current_page, $html_total_pages ) . $total_pages_after;
if ( $disable_next ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>';
} else {
$page_links[] = sprintf(
"<div class='next-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Next page', 'wpvivid-backuprestore' ),
'›'
);
}
if ( $disable_last ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>';
} else {
$page_links[] = sprintf(
"<div class='last-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'Last page', 'wpvivid-backuprestore' ),
'»'
);
}
$pagination_links_class = 'pagination-links';
if ( ! empty( $infinite_scroll ) ) {
$pagination_links_class .= ' hide-if-js';
}
$output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
if ( $total_pages ) {
$page_class = $total_pages < 2 ? ' one-page' : '';
} else {
$page_class = ' no-pages';
}
$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
echo $this->_pagination;
}
protected function display_tablenav( $which ) {
$css_type = '';
if ( 'top' === $which ) {
wp_nonce_field( 'bulk-' . $this->_args['plural'] );
$css_type = 'margin: 0 0 10px 0';
}
else if( 'bottom' === $which ) {
$css_type = 'margin: 10px 0 0 0';
}
$total_pages = $this->_pagination_args['total_pages'];
if ( $total_pages >1)
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<div class="alignleft actions bulkactions">
<label for="wpvivid_uc_post_type_bulk_action" class="screen-reader-text">Select bulk action</label>
<select name="action" id="wpvivid_uc_post_type_bulk_action">
<option value="remove_post_type">Remove</option>
</select>
<input type="submit" class="button action" value="Apply">
</div>
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
else
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<div class="alignleft actions bulkactions">
<label for="wpvivid_uc_post_type_bulk_action" class="screen-reader-text">Select bulk action</label>
<select name="action" id="wpvivid_uc_post_type_bulk_action">
<option value="remove_post_type">Remove</option>
</select>
<input type="submit" class="button action" value="Apply">
</div>
<br class="clear" />
</div>
<?php
}
}
public function display()
{
$singular = $this->_args['singular'];
$this->display_tablenav( 'top' );
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<table class="wp-list-table <?php echo esc_attr(implode( ' ', $this->get_table_classes() )); ?>" >
<thead>
<tr>
<?php $this->print_column_headers(); ?>
</tr>
</thead>
<tbody id="the-list"
<?php
if ( $singular ) {
echo esc_attr(" data-wp-lists='list:$singular'");
}
?>
>
<?php $this->display_rows_or_placeholder(); ?>
</tbody>
<tfoot>
<tr>
<?php $this->print_column_headers( false ); ?>
</tr>
</tfoot>
</table>
<?php
}
}
class WPvivid_Uploads_Cleaner_Setting
{
public function __construct()
{
add_filter('wpvivid_add_setting_tab_page', array($this, 'add_setting_tab_page'), 10);
add_action('wpvivid_setting_add_uc_cell',array($this, 'add_uc_cell'),13);
add_filter('wpvivid_set_general_setting', array($this, 'set_general_setting'), 11, 3);
add_filter('wpvivid_pro_setting_tab', array($this, 'setting_tab'), 13);
add_action('wp_ajax_wpvivid_get_exclude_files_list',array($this, 'get_exclude_files_list'));
add_action('wp_ajax_wpvivid_delete_exclude_files',array($this, 'delete_exclude_files'));
add_action('wp_ajax_wpvivid_get_post_type_list',array($this, 'get_post_type_list'));
add_action('wp_ajax_wpvivid_delete_post_type',array($this, 'delete_post_type'));
}
public function setting_tab($tabs)
{
if(current_user_can('manage_options'))
{
$tab['title']='Media Cleaner Settings';
$tab['slug']='upload_cleaner';
$tab['callback']= array($this, 'output_setting');
$args['is_parent_tab']=0;
$args['transparency']=1;
$tab['args']=$args;
$tabs[]=$tab;
}
return $tabs;
}
public function set_general_setting($setting_data, $setting, $options)
{
if(isset($setting['wpvivid_uc_scan_limit']))
$setting_data['wpvivid_uc_scan_limit'] = intval($setting['wpvivid_uc_scan_limit']);
if(isset($setting['wpvivid_uc_files_limit']))
$setting_data['wpvivid_uc_files_limit'] = intval($setting['wpvivid_uc_files_limit']);
if(isset($setting['wpvivid_uc_scan_file_types'])&&is_array($setting['wpvivid_uc_scan_file_types']))
$setting_data['wpvivid_uc_scan_file_types'] = $setting['wpvivid_uc_scan_file_types'];
if(isset($setting['wpvivid_uc_post_types'])&&is_array($setting['wpvivid_uc_post_types']))
$setting_data['wpvivid_uc_post_types'] = $setting['wpvivid_uc_post_types'];
if(isset($setting['wpvivid_uc_quick_scan']))
$setting_data['wpvivid_uc_quick_scan'] = boolval($setting['wpvivid_uc_quick_scan']);
if(isset($setting['wpvivid_uc_delete_media_when_delete_file']))
$setting_data['wpvivid_uc_delete_media_when_delete_file'] = boolval($setting['wpvivid_uc_delete_media_when_delete_file']);
if(isset($setting['wpvivid_uc_exclude_files_regex']))
$setting_data['wpvivid_uc_exclude_files_regex'] = $setting['wpvivid_uc_exclude_files_regex'];
return $setting_data;
}
public function add_setting_tab_page($setting_array)
{
$setting_array['uc_setting'] = array('index' => '3', 'tab_func' => array($this, 'wpvivid_settingpage_add_tab_uc'), 'page_func' => array($this, 'wpvivid_settingpage_add_page_uc'));
return $setting_array;
}
public function wpvivid_settingpage_add_tab_uc()
{
?>
<a href="#" id="wpvivid_tab_uc_setting" class="nav-tab setting-nav-tab" onclick="switchsettingTabs(event,'page-uc-setting')"><?php esc_html_e('Media Cleaner Settings', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function wpvivid_settingpage_add_page_uc()
{
?>
<div class="setting-tab-content wpvivid_tab_uc_setting" id="page-uc-setting" style="margin-top: 10px; display: none;">
<?php do_action('wpvivid_setting_add_uc_cell'); ?>
</div>
<?php
}
public function output_setting()
{
?>
<div style="margin-top: 10px;">
<?php
$this->add_uc_cell();
?>
<div><input class="button-primary wpvivid_setting_general_save" type="submit" value="<?php esc_attr_e( 'Save Changes', 'wpvivid-backuprestore' ); ?>" /></div>
</div>
<?php
}
public function add_uc_cell()
{
$scan_limit=get_option('wpvivid_uc_scan_limit',20);
$files_limit=get_option('wpvivid_uc_files_limit',100);
$default_file_types=array();
$default_file_types[]='png';
$default_file_types[]='jpg';
$default_file_types[]='jpeg';
$scan_file_types=get_option('wpvivid_uc_scan_file_types',$default_file_types);
$quick_scan=get_option('wpvivid_uc_quick_scan',false);
if($quick_scan)
{
$quick_scan='checked';
}
else
{
$quick_scan='';
}
//$default_post_types=array();
//$default_post_types[]='attachment';
//$default_post_types[]='revision';
//$default_post_types[]='auto-draft';
//$default_post_types[]='nav_menu_item';
//$default_post_types[]='shop_order';
//$default_post_types[]='shop_order_refund';
//$default_post_types[]='oembed_cache';
//$post_types=get_option('wpvivid_uc_post_types',$default_post_types);
$delete_media_when_delete_file=get_option('wpvivid_uc_delete_media_when_delete_file',true);
if($delete_media_when_delete_file)
{
$delete_media_when_delete_file='checked';
}
else
{
$delete_media_when_delete_file='';
}
$exclude_path=get_option('wpvivid_uc_exclude_files_regex', '');
?>
<div class="postbox schedule-tab-block setting-page-content">
<div class="wpvivid-element-space-bottom">
<label for="wpvivid_uc_scan_file_types">
<input style="margin: 4px;" id="wpvivid_uc_quick_scan" type="checkbox" option="setting" name="wpvivid_uc_quick_scan" <?php echo esc_attr($quick_scan); ?> />
<span><strong><?php esc_html_e('Enable Quick Scan', 'wpvivid-backuprestore'); ?></strong></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<span><?php esc_html_e('Checking this option will speed up your scans but may produce lower accuracy.', 'wpvivid-backuprestore'); ?></span>
</div>
<div class="wpvivid-element-space-bottom">
<label for="wpvivid_uc_delete_media_when_delete_file">
<input style="margin: 4px;" id="wpvivid_uc_delete_media_when_delete_file" style="margin-right: 4px;" type="checkbox" option="setting" name="wpvivid_uc_delete_media_when_delete_file" <?php echo esc_attr($delete_media_when_delete_file); ?> />
<span><strong><?php esc_html_e('Delete Image URL', 'wpvivid-backuprestore'); ?></strong></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<span><?php esc_html_e('With this option checked, when the image is deleted, the corresponding image url in the database that is not used anywhere on your website will also be deleted.', 'wpvivid-backuprestore'); ?></span>
</div>
</div>
<div class="postbox schedule-tab-block setting-page-content">
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('Posts Quantity Processed Per Request', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input style="margin: 0px;" type="text" placeholder="20" option="setting" name="wpvivid_uc_scan_limit" id="wpvivid_uc_scan_limit" class="all-options" value="<?php echo esc_attr($scan_limit); ?>" onkeyup="value=value.replace(/\D/g,'')" />
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'Set how many posts to process per request. The value should be set depending on your server performance and the recommended value is 20.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('Media Files Quantity Processed Per Request', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<input style="margin: 0px;" type="text" placeholder="100" option="setting" name="wpvivid_uc_files_limit" id="wpvivid_uc_files_limit" class="all-options" value="<?php echo esc_attr($files_limit); ?>" onkeyup="value=value.replace(/\D/g,'')" />
</div>
<div class="wpvivid-element-space-bottom">
<?php esc_html_e( 'Set how many media files to process per request. The value should be set depending on your server performance and the recommended value is 100.', 'wpvivid-backuprestore' ); ?>
</div>
<div class="wpvivid-element-space-bottom"><strong><?php esc_html_e('Exclude images by folder path', 'wpvivid-backuprestore'); ?></strong></div>
<div class="wpvivid-element-space-bottom">
<textarea placeholder="Example: /wp-content/uploads/19/03/ /wp-content/uploads/19/04/" option="setting" name="wpvivid_uc_exclude_files_regex" style="width:100%; height:200px; overflow-x:auto;"><?php echo esc_html($exclude_path); ?></textarea>
</div>
</div>
<?php
}
public function get_exclude_files_list()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$file_exclude=array_map( 'sanitize_text_field', $_POST['file_exclude']);
if(isset($file_exclude)&&!empty($file_exclude))
{
$white_list=get_option('wpvivid_uc_exclude_files_regex',array());
$white_list[]=$file_exclude;
update_option('wpvivid_uc_exclude_files_regex',$white_list,'no');
}
$white_list=get_option('wpvivid_uc_exclude_files_regex',array());
$list=new WPvivid_Exclude_Files_List();
if(isset($_POST['page']))
{
$list->set_list($white_list,sanitize_text_field($_POST['page']));
}
else
{
$list->set_list($white_list);
}
$list->prepare_items();
ob_start();
$list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function delete_exclude_files()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$json = sanitize_text_field($_POST['selected']);
$json = stripslashes($json);
$json = json_decode($json, true);
$files=$json['selected'];
$white_list=get_option('wpvivid_uc_exclude_files_regex',array());
$white_list = array_diff($white_list, $files);
update_option('wpvivid_uc_exclude_files_regex',$white_list,'no');
$white_list=get_option('wpvivid_uc_exclude_files_regex',array());
$list=new WPvivid_Exclude_Files_List();
if(isset($_POST['page']))
{
$list->set_list($white_list,sanitize_key($_POST['page']));
}
else
{
$list->set_list($white_list);
}
$list->prepare_items();
ob_start();
$list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function get_post_type_list()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$default_post_types=array();
$default_post_types[]='attachment';
$default_post_types[]='revision';
$default_post_types[]='auto-draft';
$default_post_types[]='nav_menu_item';
$default_post_types[]='shop_order';
$default_post_types[]='shop_order_refund';
$default_post_types[]='oembed_cache';
$post_type=sanitize_text_field($_POST['post_type']);
if(isset($post_type)&&!empty($post_type))
{
$file_exclude=$post_type;
$post_types=get_option('wpvivid_uc_post_types',$default_post_types);
$post_types[]=$file_exclude;
update_option('wpvivid_uc_post_types',$post_types,'no');
}
$post_types=get_option('wpvivid_uc_post_types',array());
$list=new WPvivid_Post_Type_List();
if(isset($_POST['page']))
{
$list->set_list($post_types,sanitize_key($_POST['page']));
}
else
{
$list->set_list($post_types);
}
$list->prepare_items();
ob_start();
$list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function delete_post_type()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$default_post_types=array();
$default_post_types[]='attachment';
$default_post_types[]='revision';
$default_post_types[]='auto-draft';
$default_post_types[]='nav_menu_item';
$default_post_types[]='shop_order';
$default_post_types[]='shop_order_refund';
$default_post_types[]='oembed_cache';
$json = sanitize_text_field($_POST['selected']);
$json = stripslashes($json);
$json = json_decode($json, true);
$files=$json['selected'];
$post_types=get_option('wpvivid_uc_post_types',$default_post_types);
$post_types = array_diff($post_types, $files);
update_option('wpvivid_uc_post_types',$post_types,'no');
$post_types=get_option('wpvivid_uc_post_types',$default_post_types);
$list=new WPvivid_Post_Type_List();
if(isset($_POST['page']))
{
$list->set_list($post_types,sanitize_key($_POST['page']));
}
else
{
$list->set_list($post_types);
}
$list->prepare_items();
ob_start();
$list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
} includes/upload-cleaner/class-wpvivid-uploads-scanner.php 0000644 00000234706 15132770567 0017676 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Uploads_Scanner
{
public $upload_url;
public $upload_base_url;
public $file_found_cache;
public function __construct()
{
$upload_dir=wp_upload_dir();
$this->upload_url=$upload_dir['baseurl'];
$this->upload_base_url = substr($upload_dir['baseurl'],1+strlen(get_site_url()));
$this->file_found_cache=array();
}
public function init_scan_task()
{
$this->check_table();
$task['start_time']=time();
$task['running_time']=time();
$task['status']='running';
$task['progress']=0;
$task['offset']=0;
update_option('scan_unused_files_task',$task,'no');
}
public function check_table_exist()
{
global $wpdb;
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . "wpvivid_scan_result";
if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name)
{
$sql = "CREATE TABLE $table_name (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
path text NOT NULL,
from_post INT NOT NULL,
PRIMARY KEY (id)
) ". $charset_collate . ";";
//reference to upgrade.php file
dbDelta( $sql );
}
}
public function check_unused_uploads_files_table_exist()
{
global $wpdb;
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . "wpvivid_unused_uploads_files";
if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name)
{
$sql = "CREATE TABLE $table_name (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
path text NOT NULL,
folder text NOT NULL,
PRIMARY KEY (id)
)". $charset_collate . ";";
//reference to upgrade.php file
dbDelta( $sql );
}
}
public function check_table()
{
global $wpdb;
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . "wpvivid_scan_result";
if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name)
{
$sql = "CREATE TABLE $table_name (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
path text NOT NULL,
from_post INT NOT NULL,
PRIMARY KEY (id)
) ". $charset_collate . ";";
//reference to upgrade.php file
dbDelta( $sql );
}
$wpdb->query("TRUNCATE TABLE $table_name");
}
public function init_unused_uploads_task($folders)
{
$this->check_unused_uploads_files_table();
update_option('unused_uploads_task',array(),'no');
$task['start_time']=time();
$task['running_time']=time();
$task['status']='running';
$task['progress']=0;
$task['size']=0;
$upload_folder = wp_upload_dir();
$root_path =$upload_folder['basedir'];
foreach ($folders as $folder)
{
$task['folder'][$folder]['finished']=0;
$task['folder'][$folder]['offset']=0;
if($folder=='.')
{
$task['folder'][$folder]['total']=0;
}
else
{
$path=$root_path.DIRECTORY_SEPARATOR.$folder;
if(file_exists($path))
{
$fi = new FilesystemIterator($path, FilesystemIterator::SKIP_DOTS);
$task['folder'][$folder]['total']=iterator_count($fi);
}
else {
$task['folder'][$folder]['total']=0;
}
}
}
update_option('unused_uploads_task',$task,'no');
}
public function check_unused_uploads_files_table()
{
global $wpdb;
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . "wpvivid_unused_uploads_files";
if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name)
{
$sql = "CREATE TABLE $table_name (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
path text NOT NULL,
folder text NOT NULL,
PRIMARY KEY (id)
)". $charset_collate . ";";
//reference to upgrade.php file
dbDelta( $sql );
}
$wpdb->query("TRUNCATE TABLE $table_name");
}
public function scan_sidebars_widgets()
{
global $wp_registered_widgets;
$syswidgets = $wp_registered_widgets;
$active_widgets = get_option( 'sidebars_widgets' );
$files=array();
foreach ( $active_widgets as $sidebar_name => $widgets )
{
if ( $sidebar_name != 'wp_inactive_widgets' && !empty( $widgets ) && is_array( $widgets ) )
{
foreach ( $widgets as $key => $widget )
{
$files=array_merge($files,$this->get_images_from_widget($syswidgets[$widget]));
//do_action( 'wpmc_scan_widget', $syswidgets[$widget] );
//$acfwidget = $syswidgets[$widget]['callback'][0]->id;
//if ( strlen($acfwidget)>11 && substr($acfwidget,0,11)=='acf_widget_' )
//{
//$this->get_images_from_acfwidgets ( $acfwidget );
//}
}
}
}
return $files;
}
public function scan_divi_options()
{
$files=array();
$options=get_option('et_divi',false);
if($options!==false)
{
if(isset($options['divi_logo']))
{
$files[]=$this->get_src($options['divi_logo']);
}
}
$options=get_option('widget_text',false);
if($options!==false)
{
foreach ($options as $option)
{
if(isset($option['title']))
{
$this->get_img_from_divi($option['title'],$files);
}
if(isset($option['text']))
{
$this->get_img_from_divi($option['text'],$files);
}
}
}
$options=get_option('theme_mods_Divi',false);
if($options!==false)
{
if(isset($options['background_image']))
{
$files[]=$this->get_src($options['background_image']);
}
}
return $files;
}
public function get_images_from_widget($widget)
{
$widget_class = $widget['callback'][0]->option_name;
$instance_id = $widget['params'][0]['number'];
$widget_data = get_option( $widget_class );
$files=array();
$ids=array();
if ( !empty( $widget_data[$instance_id]['text'] ) )
{
$html = $widget_data[$instance_id]['text']; // mm change
$media=$this->get_media_from_html($html);
if(!empty($media))
{
$files=$media;
}
}
if ( !empty( $widget_data[$instance_id]['attachment_id'] ) )
{
$id = $widget_data[$instance_id]['attachment_id'];
array_push( $ids, $id );
}
if ( !empty( $widget_data[$instance_id]['url'] ) )
{
$url = $widget_data[$instance_id]['url'];
if ( $this->is_url( $url ) )
{
$src=$this->get_src($url);
array_push( $files, $src );
}
}
if ( !empty( $widget_data[$instance_id]['ids'] ) )
{
$newIds = $widget_data[$instance_id]['ids'];
if(is_array($newIds))
{
$ids = array_merge( $ids, $newIds );
}
else
{
$ids = array_merge( $ids, array($newIds) );
}
}
// Recent Blog Posts
if ( !empty( $widget_data[$instance_id]['thumbnail'] ) )
{
$id = $widget_data[$instance_id]['thumbnail'];
array_push( $ids, $id );
}
foreach ($ids as $id)
{
$files=array_merge($files,$this->get_img_from_id($id));
}
return $files;
}
public function scan_termmeta_thumbnail()
{
global $wpdb;
$query = "SELECT meta_value FROM $wpdb->termmeta WHERE meta_key LIKE '%thumbnail_id%'";
$metas = $wpdb->get_col( $query );
$files=array();
if(count($metas)>0)
{
$ids=array();
foreach ( $metas as $id )
{
if ( is_numeric( $id ) && $id > 0 )
$ids[]=$id;
}
foreach ($ids as $id)
{
$files=array_merge($files,$this->get_img_from_id($id));
}
}
$placeholder_id = get_option( 'woocommerce_placeholder_image', null, true );
if ( !empty( $placeholder_id ) )
$files=array_merge($files,$this->get_img_from_id($placeholder_id));
return $files;
}
public function array_to_file($exploded)
{
$file='';
foreach ($exploded as $key=>$value)
{
$file=$value;
}
return $file;
}
public function scan_image_from_nextend()
{
global $wpdb;
$file_array=array();
if($wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->prefix."nextend2_image_storage" ) ) !== null)
{
$query = "SELECT image FROM ".$wpdb->prefix."nextend2_image_storage";
$metas = $wpdb->get_col( $query );
$upload_dir = wp_upload_dir();
$upload_path = $upload_dir['basedir'];
foreach ($metas as $meta)
{
$exploded = explode( ',', $meta );
if ( is_array( $exploded ) )
{
$file_tmp = $this->array_to_file($exploded);
$file = str_replace('$upload$', $upload_path, $file_tmp);
if(file_exists($file))
{
$file_array[] = str_replace('$upload$'.'/', '', $file_tmp);
}
continue;
}
}
}
return $file_array;
}
/*
public function get_images_from_acfwidgets( $widget)
{
global $wpdb;
$result=array();
// $widget starts with: acf_widget_ and looks like this: acf_widget_15011-2
$LikeKey = 'widget_' . $widget . '_%'; // Example: option_name starts with widget_acf_widget_15216-3_
$q = "SELECT option_name, option_value FROM {$wpdb->options} where option_name like %s;";
$OptionRows = $wpdb->get_results( $wpdb->prepare( $q, $LikeKey ) , ARRAY_N );
if ( $wpdb->last_error )
{
$result['result']='failed';
$result['error']=$wpdb->last_error;
return $result;
}
if ( count( $OptionRows ) > 0 )
{
$ACFWidget_ids = array();
$ACFWidget_urls = array();
foreach( $OptionRows as $row )
{
//$row[0] = option_name from wp_options
//$row[1] = option_value from wp_options
// Three if statements in priority order (image ids, link fields, text fields)
// *** An image field containing a post id for the image or is it???
if ( strpos($row[0], 'image') || strpos($row[0], 'icon') !== false )
{
if ( is_numeric( $row[1] ) ) {
array_push( $ACFWidget_ids, $row[1] );
}
}
// No else here because sometimes image or icon is present in the option_name and link is also present
// Example: widget_acf_widget_15011-2_link_1_link_icon
// Example: widget_acf_widget_15216-3_widget_image_link
// *** A link field may contain a link or be empty
if ( strpos( $row[0], 'link' ) || strpos( $row[0], 'url' ) !== false )
{
if ( $this->is_url($row[1]) ) {
$url = $this->clean_url($row[1]);
if (!empty($url)) {
array_push($ACFWidget_urls, $url);
}
}
}
// *** A text field may contain HTML
if (strpos($row[0], 'text') || strpos($row[0], 'html') !== false)
{
if (!empty($row[1])) {
$ACFWidget_urls = array_merge($ACFWidget_urls, $this->get_urls_from_html($row[1])); // mm change
}
}
}
}
}
*/
public function get_post_count()
{
global $wpdb;
$post_types=apply_filters('wpvivid_scan_post_types', array());
$post_types="post_type NOT IN ('".implode("','",$post_types)."')";
$post_status="post_status NOT IN ('inherit', 'trash', 'auto-draft')";
$query="SELECT COUNT(*) FROM $wpdb->posts WHERE $post_types AND $post_status";
$result=$wpdb->get_results($query,ARRAY_N);
if($result && sizeof($result)>0)
{
$count = $result[0][0];
}
else
{
$count=0;
}
return $count;
}
public function get_posts($start,$limit)
{
global $wpdb;
$post_types=apply_filters('wpvivid_scan_post_types', array());
$post_types="post_type NOT IN ('".implode("','",$post_types)."')";
$post_status="post_status NOT IN ('inherit', 'trash', 'auto-draft')";
$query=$wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE $post_types AND $post_status LIMIT %d, %d",$start,$limit);
$posts = $wpdb->get_col( $query );
return $posts;
}
public function get_media_from_html($html)
{
$html = mb_convert_encoding( $html, 'HTML-ENTITIES', 'UTF-8' );
$html = do_shortcode( $html );
$html = wp_filter_content_tags( $html );
if ( !class_exists("DOMDocument") )
{
echo 'The DOM extension for PHP is not installed.';
return array();
}
libxml_use_internal_errors(true);
$dom = new DOMDocument();
@$dom->loadHTML( $html );
libxml_clear_errors();
$results = array();
$this->get_img_from_tag_img($dom,$results);
$this->get_img_from_meta($dom,$results);
$this->get_img_from_tag_a($dom,$results);
$this->get_img_from_tag_a($dom,$results,'link');
$this->get_img_from_bk($html,$results);
$this->get_img_from_wp_image($html,$results);
return $results;
}
public function get_media_from_post_content($post)
{
$html = get_post_field( 'post_content', $post );
$html = mb_convert_encoding( $html, 'HTML-ENTITIES', 'UTF-8' );
ob_start();
$html = do_shortcode( $html );
ob_clean();
ob_end_flush();
$html = wp_filter_content_tags( $html );
if ( !class_exists("DOMDocument") )
{
echo 'The DOM extension for PHP is not installed.';
return array();
}
if(empty($html))
{
return array();
}
libxml_use_internal_errors(true);
$dom = new DOMDocument();
@$dom->loadHTML( $html );
libxml_clear_errors();
$results = array();
$this->get_img_from_tag_img($dom,$results);
$this->get_img_from_meta($dom,$results);
$this->get_img_from_tag_a($dom,$results);
$this->get_img_from_tag_a($dom,$results,'link');
$this->get_img_from_bk($html,$results);
$this->get_img_from_wp_image($html,$results);
$this->get_img_from_divi($html,$results);
$galleries = get_post_galleries_images( $post );
foreach ( $galleries as $gallery )
{
foreach ( $gallery as $image )
{
$src=$this->get_src($image);
if($src!==false)
{
array_push( $results, $src );
}
}
}
return $results;
}
public function get_img_from_tag_img($dom,&$results)
{
$imgs = $dom->getElementsByTagName( 'img' );
foreach ( $imgs as $img )
{
$url = $img->getAttribute('src');
$src=$this->get_src($url);
if($src!==false)
{
array_push( $results, $src );
}
$srcset = $img->getAttribute('srcset');
if ( !empty( $srcset ) )
{
$setImgs = explode( ',', trim( $srcset ) );
foreach ( $setImgs as $setImg )
{
$urls = explode( ' ', trim( $setImg ) );
if ( is_array( $urls ) )
{
$src=$this->get_src($urls[0]);
if($src!==false)
{
array_push( $results, $src );
}
}
}
}
}
}
public function get_img_from_meta($dom,&$results)
{
$metas = $dom->getElementsByTagName( 'meta' );
foreach ( $metas as $meta )
{
$property = $meta->getAttribute( 'property' );
if ( $property == 'og:image' || $property == 'og:image:secure_url' || $property == 'twitter:image' )
{
$url = $meta->getAttribute( 'content' );
$src=$this->get_src($url);
if($src!==false)
{
array_push( $results, $src );
}
}
}
}
public function get_img_from_tag_a($dom,&$results,$tag='a')
{
$urls = $dom->getElementsByTagName($tag);
foreach ( $urls as $url )
{
$url_href = $url->getAttribute('href'); // mm change
$src=$this->get_src($url_href);
if($src!==false)
{
if ( !empty( $src ) )
{
array_push( $results, $src );
}
}
}
}
public function get_img_from_bk($html,&$results)
{
preg_match_all( "/url\(\'?\"?((https?:\/\/)?[^\\&\#\[\] \"\?]+\.(jpe?g|gif|png))\'?\"?/", $html, $res );
if ( !empty( $res ) && isset( $res[1] ) && count( $res[1] ) > 0 )
{
foreach ( $res[1] as $url )
{
$src=$this->get_src($url);
if($src!==false)
{
array_push( $results, $src );
}
}
}
}
public function get_img_from_wp_image($html,&$results)
{
$posts_images_ids=array();
preg_match_all( "/wp-image-([0-9]+)/", $html, $res );
if ( !empty( $res ) && isset( $res[1] ) && count( $res[1] ) > 0 )
{
$posts_images_ids = array_merge( $posts_images_ids, $res[1] );
}
preg_match_all('/\[gallery.*ids=.(.*).\]/', $html, $res );
if ( !empty( $res ) && isset( $res[1] ) && count( $res[1] ) > 0 )
{
foreach ( $res[1] as $id )
{
$ids = explode( ',', $id );
$posts_images_ids = array_merge( $posts_images_ids, $ids );
}
}
if(!empty($posts_images_ids))
{
foreach ($posts_images_ids as $id)
{
$files=$this->get_attachment_size($id);
if(!empty($files))
{
$results=array_merge( $results, $files );
}
}
}
}
public function get_img_from_divi( $html, &$results )
{
$galleries_images_et = array();
// Single Image
preg_match_all( "/src=\"((https?:\/\/)?[^\\&\#\[\] \"\?]+\.(jpe?g|gif|png|ico|tif?f|bmp))\"/", $html, $res );
if ( !empty( $res ) && isset( $res[1] ) && count( $res[1] ) > 0 )
{
foreach ( $res[1] as $url )
{
$src=$this->get_src($url);
if($src!==false)
{
array_push( $results, $src );
}
}
}
preg_match_all( "/image=\"((https?:\/\/)?[^\\&\#\[\] \"\?]+\.(jpe?g|gif|png|ico|tif?f|bmp))\"/", $html, $res );
if ( !empty( $res ) && isset( $res[1] ) && count( $res[1] ) > 0 )
{
foreach ( $res[1] as $url )
{
$src=$this->get_src($url);
if($src!==false)
{
array_push( $results, $src );
}
}
}
// Background Image
preg_match_all( "/background_image=\"((https?:\/\/)?[^\\&\#\[\] \"\?]+\.(jpe?g|gif|png|ico|tif?f|bmp))\"/", $html, $res );
if ( !empty( $res ) && isset( $res[1] ) && count( $res[1] ) > 0 )
{
foreach ( $res[1] as $url )
{
$src=$this->get_src($url);
if($src!==false)
{
array_push( $results, $src );
}
}
}
// Modules with URL (like the Person module)
preg_match_all( "/url=\"((https?:\/\/)?[^\\&\#\[\] \"\?]+\.(jpe?g|gif|png|ico|tif?f|bmp))\"/", $html, $res );
if ( !empty( $res ) && isset( $res[1] ) )
{
foreach ( $res[1] as $url )
{
$src=$this->get_src($url);
if($src!==false)
{
array_push( $results, $src );
}
}
}
// Galleries
preg_match_all( "/gallery_ids=\"([0-9,]+)/", $html, $res );
if ( !empty( $res ) && isset( $res[1] ) )
{
foreach ( $res[1] as $r )
{
$ids = explode( ',', $r );
$galleries_images_et = array_merge( $galleries_images_et, $ids );
}
}
foreach ($galleries_images_et as $id)
{
$results=array_merge($results,$this->get_img_from_id($id));
}
}
public function get_attachment_size($attachment_id)
{
$files=array();
global $wpdb;
$meta_key="(meta_key = '_wp_attached_file')";
$postmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d AND $meta_key", $attachment_id ) );
foreach ( $postmeta as $meta )
{
if($meta->meta_key=='_wp_attached_file')
{
$files[]=$meta->meta_value;
$attach_meta = wp_get_attachment_metadata( $attachment_id );
if($attach_meta!=false)
{
if(isset($attach_meta['sizes']))
{
foreach ($attach_meta['sizes'] as $key=>$value)
{
$data=image_get_intermediate_size($attachment_id,$key);
$files[]=$data['path'];
}
}
}
}
}
return $files;
}
public function get_media_from_post_meta($post)
{
global $wpdb;
$meta_key="(meta_key = '_thumbnail_id')";
$query=$wpdb->prepare("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND $meta_key",$post);
$metas = $wpdb->get_col($query);
$postmeta_images_ids = array();
$postmeta_images_urls = array();
foreach ($metas as $meta)
{
if ( is_numeric( $meta ) )
{
if ( $meta > 0 )
array_push( $postmeta_images_ids, $meta );
continue;
}
else if ( is_serialized( $meta ) )
{
$decoded = @unserialize( $meta, array('allowed_classes' => false) );
if ( is_array( $decoded ) )
{
$this->array_to_ids_or_urls( $decoded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
else {
$exploded = explode( ',', $meta );
if ( is_array( $exploded ) )
{
$this->array_to_ids_or_urls( $exploded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
}
//
$meta_key="(meta_key = '_product_image_gallery')";
$query=$wpdb->prepare("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND $meta_key",$post);
$metas = $wpdb->get_col($query);
foreach ($metas as $meta)
{
if ( is_numeric( $meta ) )
{
if ( $meta > 0 )
array_push( $postmeta_images_ids, $meta );
continue;
}
else if ( is_serialized( $meta ) )
{
$decoded = @unserialize( $meta, array('allowed_classes' => false) );
if ( is_array( $decoded ) )
{
$this->array_to_ids_or_urls( $decoded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
else {
$exploded = explode( ',', $meta );
if ( is_array( $exploded ) )
{
$this->array_to_ids_or_urls( $exploded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
}
//
//
$meta_key="(meta_key = 'image')";
$query=$wpdb->prepare("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND $meta_key",$post);
$metas = $wpdb->get_col($query);
foreach ($metas as $meta)
{
if ( is_numeric( $meta ) )
{
if ( $meta > 0 )
array_push( $postmeta_images_ids, $meta );
continue;
}
else if ( is_serialized( $meta ) )
{
$decoded = @unserialize( $meta, array('allowed_classes' => false) );
if ( is_array( $decoded ) )
{
$this->array_to_ids_or_urls( $decoded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
else {
$exploded = explode( ',', $meta );
if ( is_array( $exploded ) )
{
$this->array_to_ids_or_urls( $exploded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
}
$meta_key="(meta_key = 'imagem')";
$query=$wpdb->prepare("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND $meta_key",$post);
$metas = $wpdb->get_col($query);
foreach ($metas as $meta)
{
if ( is_numeric( $meta ) )
{
if ( $meta > 0 )
array_push( $postmeta_images_ids, $meta );
continue;
}
else if ( is_serialized( $meta ) )
{
$decoded = @unserialize( $meta, array('allowed_classes' => false) );
if ( is_array( $decoded ) )
{
$this->array_to_ids_or_urls( $decoded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
else {
$exploded = explode( ',', $meta );
if ( is_array( $exploded ) )
{
$this->array_to_ids_or_urls( $exploded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
}
$meta_key="(meta_key = 'bild1')";
$query=$wpdb->prepare("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND $meta_key",$post);
$metas = $wpdb->get_col($query);
foreach ($metas as $meta)
{
if ( is_numeric( $meta ) )
{
if ( $meta > 0 )
array_push( $postmeta_images_ids, $meta );
continue;
}
else if ( is_serialized( $meta ) )
{
$decoded = @unserialize( $meta, array('allowed_classes' => false) );
if ( is_array( $decoded ) )
{
$this->array_to_ids_or_urls( $decoded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
else {
$exploded = explode( ',', $meta );
if ( is_array( $exploded ) )
{
$this->array_to_ids_or_urls( $exploded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
}
$meta_key="(meta_key = 'bild2')";
$query=$wpdb->prepare("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND $meta_key",$post);
$metas = $wpdb->get_col($query);
foreach ($metas as $meta)
{
if ( is_numeric( $meta ) )
{
if ( $meta > 0 )
array_push( $postmeta_images_ids, $meta );
continue;
}
else if ( is_serialized( $meta ) )
{
$decoded = @unserialize( $meta, array('allowed_classes' => false) );
if ( is_array( $decoded ) )
{
$this->array_to_ids_or_urls( $decoded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
else {
$exploded = explode( ',', $meta );
if ( is_array( $exploded ) )
{
$this->array_to_ids_or_urls( $exploded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
}
$meta_key="(meta_key = 'bild3')";
$query=$wpdb->prepare("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND $meta_key",$post);
$metas = $wpdb->get_col($query);
foreach ($metas as $meta)
{
if ( is_numeric( $meta ) )
{
if ( $meta > 0 )
array_push( $postmeta_images_ids, $meta );
continue;
}
else if ( is_serialized( $meta ) )
{
$decoded = @unserialize( $meta, array('allowed_classes' => false) );
if ( is_array( $decoded ) )
{
$this->array_to_ids_or_urls( $decoded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
else {
$exploded = explode( ',', $meta );
if ( is_array( $exploded ) )
{
$this->array_to_ids_or_urls( $exploded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
}
$meta_key="(meta_key = 'bild4')";
$query=$wpdb->prepare("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND $meta_key",$post);
$metas = $wpdb->get_col($query);
foreach ($metas as $meta)
{
if ( is_numeric( $meta ) )
{
if ( $meta > 0 )
array_push( $postmeta_images_ids, $meta );
continue;
}
else if ( is_serialized( $meta ) )
{
$decoded = @unserialize( $meta,array('allowed_classes' => false) );
if ( is_array( $decoded ) )
{
$this->array_to_ids_or_urls( $decoded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
else {
$exploded = explode( ',', $meta );
if ( is_array( $exploded ) )
{
$this->array_to_ids_or_urls( $exploded, $postmeta_images_ids, $postmeta_images_urls );
continue;
}
}
}
//
$files=array();
foreach ($postmeta_images_ids as $id)
{
$files=array_merge($files,$this->get_img_from_id($id));
}
return $files;
}
public function get_media_from_post_meta_elementor( $post )
{
$postmeta_images_ids = array();
$files=array();
$_elementor_meta = get_post_meta( $post, '_elementor_data',true);
if($_elementor_meta!=false)
{
if ( is_string( $_elementor_meta ) && ! empty( $_elementor_meta ) )
{
$_elementor_meta = json_decode( $_elementor_meta, true );
}
if ( empty( $_elementor_meta ) )
{
$_elementor_meta = array();
}
$elements_data=$_elementor_meta;
foreach ( $elements_data as $element_data )
{
$element_image=$this->get_element_image($element_data,$postmeta_images_ids);
$postmeta_images_ids=array_merge($postmeta_images_ids,$element_image);
}
foreach ($postmeta_images_ids as $id)
{
$files=array_merge($files,$this->get_img_from_id($id));
}
}
return $files;
}
public function get_media_from_post_custom_meta( $post )
{
$custom_fields=get_post_custom($post);
$files=array();
if($custom_fields!=false)
{
if(isset($custom_fields['essb_cached_image']))
{
if ( is_string( $custom_fields['essb_cached_image'] ) && ! empty( $custom_fields['essb_cached_image'] ) )
{
$files[]=$this->get_src($custom_fields['essb_cached_image']);
}
else if(is_array( $custom_fields['essb_cached_image'] )&& ! empty( $custom_fields['essb_cached_image'] ))
{
foreach ($custom_fields['essb_cached_image'] as $essb_cached_image)
{
$files[]=$this->get_src($essb_cached_image);
}
}
}
if(isset($custom_fields['picture']))
{
if ( is_string( $custom_fields['picture'] ) && ! empty( $custom_fields['picture'] ) )
{
$id=$custom_fields['picture'];
$files=array_merge($files,$this->get_img_from_id($id));
}
else if(is_array( $custom_fields['picture'] )&& ! empty( $custom_fields['picture'] ))
{
foreach ($custom_fields['picture'] as $id)
{
$files=array_merge($files,$this->get_img_from_id($id));
}
}
}
}
return $files;
}
public function get_media_from_wpresidence( $post )
{
$files=array();
$image_to_attach = get_post_meta( $post, 'image_to_attach',true);
$image_to_attach_array = explode(",", $image_to_attach);
if(!empty($image_to_attach_array))
{
foreach ($image_to_attach_array as $image_post_id)
{
if(!empty($image_post_id))
{
$_wp_attachment_metadata = get_post_meta( $image_post_id, '_wp_attachment_metadata',true);
if(isset($_wp_attachment_metadata['file']))
{
$files[] = $_wp_attachment_metadata['file'];
$iPos = strripos($_wp_attachment_metadata['file'], '/');
$relative_path = substr($_wp_attachment_metadata['file'], 0, $iPos+1);
if(isset($_wp_attachment_metadata['original_image']))
{
$files[] = $relative_path.$_wp_attachment_metadata['original_image'];
}
if(isset($_wp_attachment_metadata['sizes']))
{
foreach ($_wp_attachment_metadata['sizes'] as $type)
{
if(isset($type['file']))
{
$files[] = $relative_path.$type['file'];
}
}
}
}
}
}
}
return $files;
}
public function get_media_from_breakdance( $post )
{
$files=array();
$array_key='tree_json_string';
$image_to_attach=get_post_meta( $post, 'breakdance_data',true);
if (is_string($image_to_attach))
{
$decoded_value = json_decode($image_to_attach, true);
if ($decoded_value !== null)
{
if (is_array($decoded_value) && array_key_exists($array_key, $decoded_value))
{
if(isset($decoded_value[$array_key]))
{
$tree = json_decode($decoded_value[$array_key], true);
if(isset($tree['root']['children']))
{
foreach ($tree['root']['children'] as $info)
{
if(isset($info['children']))
{
foreach ($info['children'] as $info1)
{
if(isset($info1['children']))
{
foreach ($info1['children'] as $info2)
{
if(isset($info2['children']))
{
foreach ($info2['children'] as $info3)
{
if(isset($info3['data']['properties']['content']['content']['image']['id']))
{
$image_post_id=$info3['data']['properties']['content']['content']['image']['id'];
$_wp_attachment_metadata = get_post_meta( $image_post_id, '_wp_attachment_metadata',true);
if(isset($_wp_attachment_metadata['file']))
{
$files[] = $_wp_attachment_metadata['file'];
$iPos = strripos($_wp_attachment_metadata['file'], '/');
$relative_path = substr($_wp_attachment_metadata['file'], 0, $iPos+1);
if(isset($_wp_attachment_metadata['original_image']))
{
$files[] = $relative_path.$_wp_attachment_metadata['original_image'];
}
if(isset($_wp_attachment_metadata['sizes']))
{
foreach ($_wp_attachment_metadata['sizes'] as $type)
{
if(isset($type['file']))
{
$files[] = $relative_path.$type['file'];
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return $files;
}
public function get_media_from_oxygen( $post )
{
$files=array();
$image_post_id_array=array();
$image_to_attach=get_post_meta( $post, '_ct_builder_json',true);
if (is_string($image_to_attach))
{
$metadata_array = json_decode($image_to_attach, true);
if(isset( $metadata_array['children'] ) && is_array( $metadata_array['children'] ) && count( $metadata_array['children'] ) > 0 )
{
foreach($metadata_array['children'] as $index=>$value)
{
if(isset($value['children']))
{
foreach ($value['children'] as $index1 => $value1)
{
if(isset($value1['options']['original']['image_ids']))
{
$tmp_array = explode(',', $value1['options']['original']['image_ids']);
foreach ($tmp_array as $image_post_id)
{
$image_post_id_array[]=$image_post_id;
}
}
if(isset($value1['options']['original']['src']))
{
$src=$this->get_src($value1['options']['original']['src']);
array_push( $files, $src );
}
if(isset($value1['options']['original']['background-image']))
{
$src=$this->get_src($value1['options']['original']['background-image']);
array_push( $files, $src );
}
if(isset($value1['children']))
{
foreach ($value1['children'] as $index2 => $value2)
{
if(isset($value2['options']['original']['image_ids']))
{
$tmp_array = explode(',', $value2['options']['original']['image_ids']);
foreach ($tmp_array as $image_post_id)
{
$image_post_id_array[]=$image_post_id;
}
}
if(isset($value2['options']['original']['src']))
{
$src=$this->get_src($value2['options']['original']['src']);
array_push( $files, $src );
}
if(isset($value2['options']['original']['background-image']))
{
$src=$this->get_src($value2['options']['original']['background-image']);
array_push( $files, $src );
}
if(isset($value2['children']))
{
foreach ($value2['children'] as $index3 => $value3)
{
if(isset($value3['options']['original']['image_ids']))
{
$tmp_array = explode(',', $value3['options']['original']['image_ids']);
foreach ($tmp_array as $image_post_id)
{
$image_post_id_array[]=$image_post_id;
}
}
if(isset($value3['options']['original']['src']))
{
$src=$this->get_src($value3['options']['original']['src']);
array_push( $files, $src );
}
if(isset($value3['options']['original']['background-image']))
{
$src=$this->get_src($value3['options']['original']['background-image']);
array_push( $files, $src );
}
}
}
}
}
}
}
}
}
}
if(!empty($image_post_id_array))
{
foreach ($image_post_id_array as $image_post_id)
{
$_wp_attachment_metadata = get_post_meta( $image_post_id, '_wp_attachment_metadata',true);
if(isset($_wp_attachment_metadata['file']))
{
$files[] = $_wp_attachment_metadata['file'];
$iPos = strripos($_wp_attachment_metadata['file'], '/');
$relative_path = substr($_wp_attachment_metadata['file'], 0, $iPos+1);
if(isset($_wp_attachment_metadata['original_image']))
{
$files[] = $relative_path.$_wp_attachment_metadata['original_image'];
}
if(isset($_wp_attachment_metadata['sizes']))
{
foreach ($_wp_attachment_metadata['sizes'] as $type)
{
if(isset($type['file']))
{
$files[] = $relative_path.$type['file'];
}
}
}
}
}
}
return $files;
}
public function get_element_image($element_data,&$attachment_added_ids)
{
$element_image=array();
if(!empty($element_data['settings']))
{
$settings=$element_data['settings'];
if(isset($settings['image']))
{
if(isset($settings['image']['id']))
{
if(!in_array($settings['image']['id'],$attachment_added_ids))
{
$element_image[]=$settings['image']['id'];
$attachment_added_ids[]=$settings['image']['id'];
}
}
}
if(isset($settings['logo_items']))
{
foreach ($settings['logo_items'] as $item)
{
if(isset($item['logo_image']))
{
if(!in_array($item['logo_image']['id'],$attachment_added_ids))
{
$element_image[]=$item['logo_image']['id'];
$attachment_added_ids[]=$item['logo_image']['id'];
}
}
}
}
if(isset($settings['gallery']))
{
foreach ($settings['gallery'] as $item)
{
if(isset($item['id']))
{
if(!in_array($item['id'],$attachment_added_ids))
{
$element_image[]=$item['id'];
$attachment_added_ids[]=$item['id'];
}
}
}
}
if(isset($settings['background_image']))
{
if(isset($settings['background_image']['id']))
{
if(!in_array($settings['background_image']['id'],$attachment_added_ids))
{
$element_image[]=$settings['background_image']['id'];
$attachment_added_ids[]=$settings['background_image']['id'];
}
}
}
if(isset($settings['background_a_image']))
{
if(isset($settings['background_a_image']['id']))
{
if(!in_array($settings['background_a_image']['id'],$attachment_added_ids))
{
$element_image[]=$settings['background_a_image']['id'];
$attachment_added_ids[]=$settings['background_a_image']['id'];
}
}
}
if(isset($settings['carousel']) && !empty($settings['carousel']))
{
foreach ($settings['carousel'] as $item)
{
if(isset($item['id']))
{
if(!in_array($item['id'],$attachment_added_ids))
{
$element_image[]=$item['id'];
$attachment_added_ids[]=$item['id'];
}
}
}
}
if(isset($settings['slides']) && !empty($settings['slides']))
{
foreach ($settings['slides'] as $item)
{
if(isset($item['image']['id']))
{
if(!in_array($item['image']['id'],$attachment_added_ids))
{
$element_image[]=$item['image']['id'];
$attachment_added_ids[]=$item['image']['id'];
}
}
}
}
if(isset($settings['poster']) && !empty($settings['poster']))
{
if(isset($settings['poster']['id']))
{
if(!in_array($settings['poster']['id'],$attachment_added_ids))
{
$element_image[]=$settings['poster']['id'];
$attachment_added_ids[]=$settings['poster']['id'];
}
}
}
if(isset($settings['image_overlay']) && !empty($settings['image_overlay']))
{
if(isset($settings['image_overlay']['id']))
{
if(!in_array($settings['image_overlay']['id'],$attachment_added_ids))
{
$element_image[]=$settings['image_overlay']['id'];
$attachment_added_ids[]=$settings['image_overlay']['id'];
}
}
}
if(isset($settings['background_video_fallback']))
{
if(isset($settings['background_video_fallback']['id']))
{
if(!in_array($settings['background_video_fallback']['id'],$attachment_added_ids))
{
$element_image[]=$settings['background_video_fallback']['id'];
$attachment_added_ids[]=$settings['background_video_fallback']['id'];
}
}
}
if(isset($settings['background_slideshow_gallery']) && !empty($settings['background_slideshow_gallery']))
{
foreach ($settings['background_slideshow_gallery'] as $item)
{
if(isset($item['id']))
{
if(!in_array($item['id'],$attachment_added_ids))
{
$element_image[]=$item['id'];
$attachment_added_ids[]=$item['id'];
}
}
}
}
if(isset($settings['column_bg_image_new']) && !empty($settings['column_bg_image_new']))
{
if(isset($settings['column_bg_image_new']['id']))
{
if(!in_array($settings['column_bg_image_new']['id'],$attachment_added_ids))
{
$element_image[]=$settings['column_bg_image_new']['id'];
$attachment_added_ids[]=$settings['column_bg_image_new']['id'];
}
}
}
}
if(!empty($element_data['elements']))
{
foreach ($element_data['elements'] as $element)
{
$temp=$this->get_element_image($element,$attachment_added_ids);
$element_image=array_merge($element_image,$temp);
}
}
return $element_image;
}
public function get_from_meta( $meta, $lookFor, &$ids, &$urls )
{
foreach ( $meta as $key => $value ) {
if ( is_object( $value ) || is_array( $value ) )
$this->get_from_meta( $value, $lookFor, $ids, $urls );
else if ( in_array( $key, $lookFor ) ) {
if ( empty( $value ) )
continue;
else if ( is_numeric( $value ) ) {
// It this an ID?
array_push( $ids, $value );
}
else {
if ( $this->is_url( $value ) ) {
// Is this an URL?
array_push( $urls, $this->clean_url( $value ) );
}
else {
// Is this an array of IDs, encoded as a string? (like "20,13")
$pieces = explode( ',', $value );
foreach ( $pieces as $pval ) {
if ( is_numeric( $pval ) ) {
array_push( $ids, $pval );
}
}
}
}
}
}
}
public function get_img_from_id($attachment_id)
{
$files=array();
$attach_meta = wp_get_attachment_metadata( $attachment_id );
if($attach_meta!=false)
{
if(isset($attach_meta['sizes']))
{
foreach ($attach_meta['sizes'] as $key=>$value)
{
$data=image_get_intermediate_size($attachment_id,$key);
$data['path']=ltrim($data['path'], './');
$name=$data['path'];
if(!in_array($name,$files))
{
$files[]=$name;
}
}
}
if(isset($attach_meta['file'])&&is_string($attach_meta['file']))
{
if(!in_array($attach_meta['file'],$files))
{
$files[]=$attach_meta['file'];
}
}
}
return $files;
}
public function get_src($url)
{
if(empty($url)||!is_string( $url ))
{
return false;
}
if(strlen($url)>4&&strtolower( substr( $url, 0, 4) ) == 'http')
{
$tmp_url = str_replace('https://', '', $url);
$tmp_url = str_replace('http://', '', $tmp_url);
$tmp_upload_url = str_replace('https://', '', $this->upload_url);
$tmp_upload_url = str_replace('http://', '', $tmp_upload_url);
$ipos = strpos( $tmp_url, $tmp_upload_url );
if ($ipos === false)
{
return false;
}
$str=substr( $tmp_url, 1 + strlen( $tmp_upload_url ) + $ipos );
return $str;
}
else if($url[0] == '/')
{
$ipos = strpos( $url, $this->upload_base_url );
if ($ipos === false)
return false;
return substr( $url, 1 + strlen( $this->upload_base_url ) + $ipos );
}
else
{
return false;
}
}
function is_url( $url ) {
return ( (
!empty( $url ) ) &&
is_string( $url ) &&
strlen( $url ) > 4 && (
strtolower( substr( $url, 0, 4) ) == 'http' || $url[0] == '/'
)
);
}
function array_to_ids_or_urls( &$meta, &$ids, &$urls )
{
$regex_file = '/[A-Za-z0-9-_,.\(\)\s]+[.]{1}(jpg|jpeg|jpe|gif|png|tiff|bmp|csv|pdf|xls|xlsx|doc|docx|odt|wpd|rtf|tiff|mp3|mp4|wav|lua)/';
foreach ( $meta as $k => $m )
{
if ( is_numeric( $m ) ) {
// Probably a Media ID
if ( $m > 0 )
array_push( $ids, $m );
}
else if ( is_array( $m ) )
{
// If it's an array with a width, probably that the index is the Media ID
if ( isset( $m['width'] ) && is_numeric( $k ) ) {
if ( $k > 0 )
array_push( $ids, $k );
}
}
else if ( !empty( $m ) )
{
// If it's a string, maybe it's a file (with an extension)
if ( preg_match( $regex_file, $m ) )
array_push( $urls, $m );
}
}
}
private function transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode(DIRECTORY_SEPARATOR,$values);
}
public function get_folders()
{
$upload_folder = wp_upload_dir();
$root_path =$upload_folder['basedir'];
$regex=apply_filters('wpvivid_uc_scan_include_files_regex',array());
$exclude_regex=apply_filters('wpvivid_uc_scan_exclude_files_regex',array());
$result=$this->get_folder_list($root_path,$regex,$exclude_regex);
return $result;
}
public function get_files($folder)
{
$upload_folder = wp_upload_dir();
$root_path =$upload_folder['basedir'];
$files =array();
$regex=apply_filters('wpvivid_uc_scan_include_files_regex',array());
$exclude_regex=apply_filters('wpvivid_uc_scan_exclude_files_regex',array());
if($folder === '.')
{
$this->scan_root_uploaded_files($files, $root_path.DIRECTORY_SEPARATOR.$folder,$root_path,$regex,$exclude_regex);
}
else
{
$this->scan_list_uploaded_files($files, $root_path.DIRECTORY_SEPARATOR.$folder,$root_path,$regex,$exclude_regex);
}
return $files;
}
private function regex_match($regex_array,$string,$mode)
{
if(empty($regex_array))
{
return true;
}
if($mode==0)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return false;
}
}
return true;
}
if($mode==1)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return true;
}
}
return false;
}
return true;
}
private function get_folder_list($root_path,$regex=array(),$exclude_regex=array())
{
$result['folders']=array();
$result['files']=array();
$result['size']=0;
$handler = opendir($root_path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if(empty($exclude_regex) || (!empty($exclude_regex) && $this->regex_match($exclude_regex,$this -> transfer_path($root_path . DIRECTORY_SEPARATOR . $filename),0)))
{
if (is_dir($root_path . DIRECTORY_SEPARATOR . $filename))
{
if(preg_match('#^\d{4}$#',$filename) ||
preg_match('/listing-uploads/', $filename)) //add listing-uploads\gallery
{
$result['folders']=array_merge( $result['folders'],$this->get_sub_folder($root_path . DIRECTORY_SEPARATOR . $filename,$filename,$exclude_regex));
}
else
{
$result['folders'][]=$filename;
}
}
else
{
if ($this->regex_match($exclude_regex, $filename, 0))
{
if($this->regex_match($regex, $filename, 1))
{
$result['files'][] = $filename;
$result['size']+=filesize($root_path . DIRECTORY_SEPARATOR . $filename);
}
}
}
}
}
}
if($handler)
@closedir($handler);
}
$result['folders'][]='.';
return $result;
}
function get_sub_folder($path,$root,$exclude_regex=array())
{
$folders=array();
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if(empty($exclude_regex) || (!empty($exclude_regex) && $this->regex_match($exclude_regex,$this -> transfer_path($path . DIRECTORY_SEPARATOR . $filename),0)))
{
if (is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
$folders[]=$root.DIRECTORY_SEPARATOR.$filename;
}
}
}
}
if($handler)
@closedir($handler);
}
return $folders;
}
function scan_root_uploaded_files( &$files,$path,$root,$regex=array(),$exclude_regex=array())
{
$count = 0;
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
$count++;
if ($this->regex_match($exclude_regex, $this -> transfer_path($root . DIRECTORY_SEPARATOR . $filename), 0))
{
if($this->regex_match($regex, $filename, 1))
{
$result['files'][] = $filename;
$files[] = str_replace($path . DIRECTORY_SEPARATOR,'',$path . DIRECTORY_SEPARATOR . $filename);
}
}
}
}
if($handler)
@closedir($handler);
}
}
return $files;
}
function scan_list_uploaded_files( &$files,$path,$root,$regex=array(),$exclude_regex=array())
{
$count = 0;
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
$count++;
if (is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
$this->scan_list_uploaded_files($files, $path . DIRECTORY_SEPARATOR . $filename,$root,$regex);
}
else
{
if ($this->regex_match($exclude_regex, $this -> transfer_path($path . DIRECTORY_SEPARATOR . $filename), 0))
{
if($this->regex_match($regex, $filename, 1))
{
$result['files'][] = $filename;
$files[] = str_replace($root . DIRECTORY_SEPARATOR,'',$path . DIRECTORY_SEPARATOR . $filename);
}
}
}
}
}
if($handler)
@closedir($handler);
}
}
return $files;
}
public function update_scan_task($uploads_files,$offset,$status='running',$progress=0)
{
$task=get_option('scan_unused_files_task',array());
$task['running_time']=time();
$task['status']=$status;
$task['progress']=$progress;
$task['offset']=$offset;
$this->insert_scan_result($uploads_files);
update_option('scan_unused_files_task',$task,'no');
}
public function update_unused_uploads_task($uploads_files,$folder,$finished,$offset,$status='running',$progress=0,$size=0)
{
$task=get_option('unused_uploads_task',array());
$task['running_time']=time();
$task['status']=$status;
$task['progress']=$progress;
$task['size']+=$size;
$task['folder'][$folder]['finished']=$finished;
$task['folder'][$folder]['offset']=$offset;
if(!empty($uploads_files))
$this->insert_unused_uploads_files($folder,$uploads_files);
update_option('unused_uploads_task',$task,'no');
}
public function get_unused_uploads_progress()
{
$task=get_option('unused_uploads_task',array());
if(isset($task['folder']))
{
$i=0;
foreach ($task['folder'] as $folder=>$item)
{
if($item['finished'])
$i++;
}
$progress=intval(($i/sizeof($task['folder']))*100);
$ret['percent']=$progress;
$ret['total_folders']=sizeof($task['folder']);
$ret['scanned_folders']=$i;
return $ret;
}
else
{
$ret['percent']=0;
$ret['total_folders']=0;
$ret['scanned_folders']=0;
return $ret;
}
}
public function get_unfinished_folder()
{
$task=get_option('unused_uploads_task',array());
foreach ($task['folder'] as $folder=>$data)
{
if(!$data['finished'])
{
$result['folder']=$folder;
$result['offset']=$data['offset'];
$result['total']=$data['total'];
return $result;
}
}
return false;
}
public function insert_scan_result($uploads_files)
{
global $wpdb;
$table_name = $wpdb->prefix . "wpvivid_scan_result";
$query = "INSERT INTO $table_name (id,path,from_post) VALUES ";
$values = array();
$place_holders=array();
foreach ( $uploads_files as $id=>$files )
{
if(empty($files))
continue;
foreach ($files as $path)
{
array_push( $values, $path );
array_push( $values, $id );
$place_holders[] = "(NULL,'%s',%d)";
}
}
if ( !empty( $values ) )
{
$query .= implode( ', ', $place_holders );
$prepared = $wpdb->prepare( "$query ", $values );
$wpdb->query( $prepared );
}
}
public function insert_unused_uploads_files($folder,$uploads_files)
{
global $wpdb;
$table_name = $wpdb->prefix . "wpvivid_unused_uploads_files";
$query = "INSERT INTO $table_name (id,path,folder) VALUES ";
$values = array();
$place_holders=array();
foreach ( $uploads_files as $path )
{
array_push( $values, $path );
array_push( $values, $folder );
$place_holders[] = "(NULL,'%s','%s')";
}
if ( !empty( $values ) )
{
$query .= implode( ', ', $place_holders );
$prepared = $wpdb->prepare( "$query ", $values );
$wpdb->query( $prepared );
}
}
public function is_uploads_files_exist($file)
{
global $wpdb;
$file=str_replace('\\','/',$file);
$table = $wpdb->prefix . "wpvivid_scan_result";
$row = $wpdb->get_row( "SELECT * FROM $table WHERE path = '$file'" );
if (empty($row))
{
$quick_scan=get_option('wpvivid_uc_quick_scan',false);
if(!$quick_scan)
{
$attachment_id=$this->find_media_id_from_file($file);
if($attachment_id)
{
if(isset($this->file_found_cache[$attachment_id]))
{
if($this->file_found_cache[$attachment_id])
{
return true;
}
else
{
return false;
}
}
$files=$this->get_img_from_id($attachment_id);
if(!empty($files))
{
$files = implode("','",$files);
$sql= "SELECT * FROM $table WHERE path IN ('$files')";
$row = $wpdb->get_row($sql);
if (!empty($row))
{
$this->file_found_cache[$attachment_id]=1;
return true;
}
else
{
$this->file_found_cache[$attachment_id]=0;
}
}
}
}
return false;
}
return true;
}
public function find_media_id_from_file( $file )
{
global $wpdb;
$file=basename($file);
$sql = "SELECT post_id
FROM {$wpdb->postmeta}
WHERE meta_key = '_wp_attachment_metadata'
AND meta_value LIKE '%$file%'";
$ret = $wpdb->get_var( $sql );
if(!$ret)
{
$sql = $wpdb->prepare( "SELECT post_id
FROM {$wpdb->postmeta}
WHERE meta_key = '_wp_attached_file'
AND meta_value = %s", $file
);
$ret = $wpdb->get_var( $sql );
}
return $ret;
}
public function get_scan_result($search,$folder)
{
global $wpdb;
$where='';
if(!empty($search)||!empty($folder))
{
$where='WHERE ';
if(!empty($search))
{
$where.="`path` LIKE '%$search%'";
}
if(!empty($search)&&!empty($folder))
{
$where.=' AND ';
}
if(!empty($folder))
{
$where.="`folder` = '$folder'";
}
}
$table = $wpdb->prefix . "wpvivid_unused_uploads_files";
$sql="SELECT * FROM `$table` ".$where;
return $wpdb->get_results($sql,ARRAY_A);
}
public function get_scan_result_count()
{
global $wpdb;
$table = $wpdb->prefix . "wpvivid_unused_uploads_files";
$sql="SELECT COUNT(*) FROM $table";
$result=$wpdb->get_results($sql,ARRAY_N);
if($result)
{
return $count=$result[0][0];
}
else
{
return false;
}
}
public function get_scan_result_size()
{
$task=get_option('unused_uploads_task',array());
if(empty($task))
{
return false;
}
else if(isset($task['size']))
{
return size_format($task['size'],2);
}
else
{
return false;
}
}
public function get_all_folder()
{
global $wpdb;
$table = $wpdb->prefix . "wpvivid_unused_uploads_files";
$sql="SELECT * FROM $table GROUP BY `folder`";
$result=$wpdb->get_results($sql,ARRAY_A);
if($result)
{
$folders=array();
foreach ($result as $item)
{
if($item['folder']=='.')
{
$folders[]='root';
}
else
{
$folders[]=$item['folder'];
}
}
return $folders;
}
else
{
return false;
}
}
public function get_selected_files_list($selected_list)
{
global $wpdb;
$ids=implode(",",$selected_list);
$table = $wpdb->prefix . "wpvivid_unused_uploads_files";
$sql="SELECT * FROM $table WHERE `id` IN ($ids)";
$result=$wpdb->get_results($sql,ARRAY_A);
if($result)
{
$files=array();
foreach ($result as $item)
{
$files[]=$item['path'];
}
return $files;
}
else
{
return false;
}
}
public function delete_selected_files_list($selected_list)
{
global $wpdb;
$table = $wpdb->prefix . "wpvivid_unused_uploads_files";
$ids=implode(",",$selected_list);
$sql="DELETE FROM $table WHERE `id` IN ($ids)";
$result=$wpdb->query($sql);
if($result)
{
return true;
}
else
{
return false;
}
}
public function get_all_files_list($search,$folder,$offset,$count)
{
global $wpdb;
$where='';
if(!empty($search)||!empty($folder))
{
$where='WHERE ';
if(!empty($search))
{
$where.="`path` LIKE '%$search%'";
}
if(!empty($search)&&!empty($folder))
{
$where.=' AND ';
}
if(!empty($folder))
{
$where.="`folder` = '$folder'";
}
}
$where.=" LIMIT $offset,$count";
//LIMIT
$table = $wpdb->prefix . "wpvivid_unused_uploads_files";
$sql="SELECT * FROM $table ".$where;
$result=$wpdb->get_results($sql,ARRAY_A);
if($result)
{
$files=array();
foreach ($result as $item)
{
$files[]=$item['path'];
}
return $files;
}
else
{
return false;
}
}
public function delete_all_files_list($search,$folder,$count)
{
global $wpdb;
$where='';
if(!empty($search)||!empty($folder))
{
$where='WHERE ';
if(!empty($search))
{
$where.="`path` LIKE '%$search%'";
}
if(!empty($search)&&!empty($folder))
{
$where.=' AND ';
}
if(!empty($folder))
{
$where.="`folder` = '$folder'";
}
}
$where.=" LIMIT $count";
//LIMIT
$table = $wpdb->prefix . "wpvivid_unused_uploads_files";
$sql="DELETE FROM $table ".$where;
$result=$wpdb->query($sql);
if($result)
{
return true;
}
else
{
return false;
}
}
} includes/upload-cleaner/class-wpvivid-uploads-cleaner.php 0000644 00000420466 15132770567 0017656 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
define('WPVIVID_UPLOADS_ISO_DIR','wpvivid_uploads'.DIRECTORY_SEPARATOR.'Isolate');
if ( ! class_exists( 'WP_List_Table' ) )
{
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class WPvivid_Unused_Upload_Files_List extends WP_List_Table
{
public $list;
public $type;
public $page_num;
public $parent;
public function __construct( $args = array() )
{
global $wpdb;
parent::__construct(
array(
'plural' => 'upload_files',
'screen' => 'upload_files',
)
);
}
public function set_parent($parent)
{
$this->parent=$parent;
}
public function set_list($list,$page_num=1)
{
$this->list=$list;
$this->page_num=$page_num;
}
protected function get_table_classes()
{
return array( 'widefat striped' );
}
public function get_columns()
{
$sites_columns = array(
'cb' => ' ',
'thumb' =>__( 'Thumbnail', 'wpvivid-backuprestore' ),
'path' => __( 'Path', 'wpvivid-backuprestore' ),
//'folder' => __( 'Folder', 'wpvivid-backuprestore' ),
'size'=>__( 'Size', 'wpvivid-backuprestore' )
);
return $sites_columns;
}
public function get_pagenum()
{
if($this->page_num=='first')
{
$this->page_num=1;
}
else if($this->page_num=='last')
{
$this->page_num=$this->_pagination_args['total_pages'];
}
$pagenum = $this->page_num ? $this->page_num : 0;
if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
{
$pagenum = $this->_pagination_args['total_pages'];
}
return max( 1, $pagenum );
}
public function column_cb( $item )
{
echo '<input type="checkbox" name="uploads" value="'.esc_attr($item['id']).'" />';
}
public function column_thumb($item)
{
$supported_image = array(
'gif',
'jpg',
'jpeg',
'png'
);
$item['path'] = str_replace('\\', '/', $item['path']);
$upload_dir=wp_upload_dir();
$path=$upload_dir['basedir'].DIRECTORY_SEPARATOR.$item['path'];
$ext = strtolower(pathinfo($item['path'], PATHINFO_EXTENSION));
if (in_array($ext, $supported_image)&&file_exists( $path ))
{
echo "<a target='_blank' href='" . esc_url($upload_dir['baseurl'].'/'.$item['path'] ).
"'><img style='max-width: 48px; max-height: 48px;' src='" .
esc_url($upload_dir['baseurl'].'/'.$item['path']) . "' />";
}
else {
echo '<span class="dashicons dashicons-no-alt"></span>';
}
}
public function column_path( $item )
{
$item['path']=esc_html($item['path']);
echo esc_html('...\uploads\\'.$item['path']);
}
public function column_folder( $item )
{
if($item['folder']=='.')
{
echo 'Uploads root';
}
else
{
echo esc_html($item['folder']);
}
}
public function column_size( $item )
{
$upload_dir=wp_upload_dir();
$file_name=$upload_dir['basedir'].DIRECTORY_SEPARATOR.$item['path'];
if(file_exists($file_name))
{
echo esc_html(size_format(filesize($file_name),2));
}
else
{
echo 'file not found';
}
}
public function has_items()
{
return !empty($this->list);
}
/*
public function no_items()
{
_e( '<a class="wpvivid-no-item" style="cursor:pointer">No items found. Click here to reset</a>' );
}*/
public function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$this->_column_headers = array($columns, $hidden, $sortable);
$total_items =sizeof($this->list);
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => 20,
)
);
}
public function display_rows()
{
$this->_display_rows( $this->list );
}
private function _display_rows( $list )
{
$page=$this->get_pagenum();
$page_list=$list;
$temp_page_list=array();
$count=0;
while ( $count<$page )
{
$temp_page_list = array_splice( $page_list, 0, 20);
$count++;
}
foreach ( $temp_page_list as $key=>$item)
{
$this->single_row($item);
}
}
public function single_row($item)
{
?>
<tr>
<?php $this->single_row_columns( $item ); ?>
</tr>
<?php
}
protected function pagination( $which )
{
if ( empty( $this->_pagination_args ) )
{
return;
}
$total_items = $this->_pagination_args['total_items'];
$total_pages = $this->_pagination_args['total_pages'];
$infinite_scroll = false;
if ( isset( $this->_pagination_args['infinite_scroll'] ) )
{
$infinite_scroll = $this->_pagination_args['infinite_scroll'];
}
if ( 'top' === $which && $total_pages > 1 )
{
$this->screen->render_screen_reader_content( 'heading_pagination' );
}
$output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items, 'wpvivid-backuprestore' ), number_format_i18n( $total_items ) ) . '</span>';
$current = $this->get_pagenum();
$page_links = array();
$total_pages_before = '<span class="paging-input">';
$total_pages_after = '</span></span>';
$disable_first = $disable_last = $disable_prev = $disable_next = false;
if ( $current == 1 ) {
$disable_first = true;
$disable_prev = true;
}
if ( $current == 2 ) {
$disable_first = true;
}
if ( $current == $total_pages ) {
$disable_last = true;
$disable_next = true;
}
if ( $current == $total_pages - 1 ) {
$disable_last = true;
}
if ( $disable_first ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>';
} else {
$page_links[] = sprintf(
"<div class='first-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'First page', 'wpvivid-backuprestore' ),
'«'
);
}
if ( $disable_prev ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>';
} else {
$page_links[] = sprintf(
"<div class='prev-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Previous page', 'wpvivid-backuprestore' ),
'‹'
);
}
if ( 'bottom' === $which ) {
$html_current_page = $current;
$total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
} else {
$html_current_page = sprintf(
"%s<input class='current-page' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
'<label class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</label>',
$current,
strlen( $total_pages )
);
}
$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
$page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging', 'wpvivid-backuprestore' ), $html_current_page, $html_total_pages ) . $total_pages_after;
if ( $disable_next ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>';
} else {
$page_links[] = sprintf(
"<div class='next-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Next page', 'wpvivid-backuprestore' ),
'›'
);
}
if ( $disable_last ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>';
} else {
$page_links[] = sprintf(
"<div class='last-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'Last page', 'wpvivid-backuprestore' ),
'»'
);
}
$pagination_links_class = 'pagination-links';
if ( ! empty( $infinite_scroll ) ) {
$pagination_links_class .= ' hide-if-js';
}
$output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
if ( $total_pages ) {
$page_class = $total_pages < 2 ? ' one-page' : '';
} else {
$page_class = ' no-pages';
}
$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
echo $this->_pagination;
}
protected function display_tablenav( $which ) {
$css_type = '';
if ( 'top' === $which ) {
wp_nonce_field( 'bulk-' . $this->_args['plural'] );
$css_type = 'margin: 0 0 10px 0';
}
else if( 'bottom' === $which ) {
$css_type = 'margin: 10px 0 0 0';
}
$total_pages = $this->_pagination_args['total_pages'];
if ( $total_pages >1)
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<div class="alignleft actions bulkactions">
<label for="wpvivid_uc_bulk_action" class="screen-reader-text"><?php esc_html_e( 'Select bulk action', 'wpvivid-backuprestore' ); ?></label>
<select name="action" id="wpvivid_uc_bulk_action">
<option value="-1"><?php esc_html_e( 'Bulk Actions', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_isolate_selected_image"><?php esc_html_e( 'Isolate selected images', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_isolate_list_image"><?php esc_html_e( 'Isolate all images', 'wpvivid-backuprestore' ); ?></option>
</select>
<input type="submit" class="button action" value="<?php esc_attr_e( 'Apply', 'wpvivid-backuprestore' ); ?>">
</div>
<div id="wpvivid_isolate_progress" style="margin-top: 4px; display: none;">
<div class="spinner is-active" style="margin: 0 5px 10px 0; float: left;"></div>
<div style="float: left; margin-top: 2px;"><?php esc_html_e( 'Isolating images...', 'wpvivid-backuprestore' ); ?></div>
<div style="clear: both;"></div>
</div>
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
else
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<div class="alignleft actions bulkactions">
<label for="wpvivid_uc_bulk_action" class="screen-reader-text"><?php esc_html_e( 'Select bulk action', 'wpvivid-backuprestore' ); ?></label>
<select name="action" id="wpvivid_uc_bulk_action">
<option value="-1"><?php esc_html_e( 'Bulk Actions', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_isolate_selected_image"><?php esc_html_e( 'Isolate selected images', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_isolate_list_image"><?php esc_html_e( 'Isolate all images', 'wpvivid-backuprestore' ); ?></option>
</select>
<input type="submit" class="button action" value="<?php esc_attr_e( 'Apply', 'wpvivid-backuprestore' ); ?>">
</div>
<div id="wpvivid_isolate_progress" style="margin-top: 4px; display: none;">
<div class="spinner is-active" style="margin: 0 5px 10px 0; float: left;"></div>
<div style="float: left; margin-top: 2px;"><?php esc_html_e( 'Isolating images...', 'wpvivid-backuprestore' ); ?></div>
<div style="clear: both;"></div>
</div>
<br class="clear" />
</div>
<?php
}
}
public function display() {
$singular = $this->_args['singular'];
$this->display_tablenav( 'top' );
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<table class="wp-list-table <?php echo esc_attr(implode( ' ', $this->get_table_classes() )); ?>" >
<thead>
<tr>
<?php $this->print_column_headers(); ?>
</tr>
</thead>
<tbody id="the-list"
<?php
if ( $singular ) {
echo esc_attr(" data-wp-lists='list:$singular'");
}
?>
>
<?php $this->display_rows_or_placeholder(); ?>
</tbody>
<tfoot>
<tr>
<?php $this->print_column_headers( false ); ?>
</tr>
</tfoot>
</table>
<?php
}
}
class WPvivid_Isolate_Files_List extends WP_List_Table
{
public $list;
public $type;
public $page_num;
public $parent;
public function __construct( $args = array() )
{
global $wpdb;
parent::__construct(
array(
'plural' => 'upload_files',
'screen' => 'upload_files',
)
);
}
public function set_parent($parent)
{
$this->parent=$parent;
}
public function set_list($list,$page_num=1)
{
$this->list=$list;
$this->page_num=$page_num;
}
protected function get_table_classes()
{
return array( 'widefat striped' );
}
public function get_columns()
{
$sites_columns = array(
'cb' => ' ',
'thumb' =>__( 'Thumbnail', 'wpvivid-backuprestore' ),
'path' => __( 'Path', 'wpvivid-backuprestore' ),
//'folder' => __( 'Folder', 'wpvivid-backuprestore' ),
'size'=>__( 'Size', 'wpvivid-backuprestore' )
);
return $sites_columns;
}
public function get_pagenum()
{
if($this->page_num=='first')
{
$this->page_num=1;
}
else if($this->page_num=='last')
{
$this->page_num=$this->_pagination_args['total_pages'];
}
$pagenum = $this->page_num ? $this->page_num : 0;
if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
{
$pagenum = $this->_pagination_args['total_pages'];
}
return max( 1, $pagenum );
}
public function column_cb( $item )
{
echo '<input type="checkbox" name="uploads" />';
}
public function column_thumb($item)
{
$supported_image = array(
'gif',
'jpg',
'jpeg',
'png'
);
$item['path'] = str_replace('\\', '/', $item['path']);
$wpvivid_uploads_iso_dir = str_replace('\\', '/', WPVIVID_UPLOADS_ISO_DIR);
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR.DIRECTORY_SEPARATOR.$item['path'];
$ext = strtolower(pathinfo($item['path'], PATHINFO_EXTENSION));
if (in_array($ext, $supported_image)&&file_exists( $path ))
{
echo "<a target='_blank' href='" . esc_url(WP_CONTENT_URL.'/'.$wpvivid_uploads_iso_dir.'/'.$item['path']) .
"'><img style='max-width: 48px; max-height: 48px;' src='" .
esc_url(WP_CONTENT_URL.'/'.$wpvivid_uploads_iso_dir.'/'.$item['path'] ). "' />";
}
else {
echo '<span class="dashicons dashicons-no-alt"></span>';
}
}
public function column_path( $item )
{
$item['path']=esc_html($item['path']);
echo esc_html('...\uploads\\'.$item['path']);
}
public function column_folder( $item )
{
if($item['folder']=='.')
{
echo 'Uploads root';
}
else
{
echo esc_html($item['folder']);
}
}
public function column_size( $item )
{
$file_name=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR.DIRECTORY_SEPARATOR.$item['path'];
if(file_exists($file_name))
{
echo esc_html(size_format(filesize($file_name),2));
}
else
{
echo 'file not found';
}
}
public function has_items()
{
return !empty($this->list);
}
/*
public function no_items()
{
_e( '<a class="wpvivid-no-item" style="cursor:pointer">No items found. Click here to reset</a>' );
}
*/
public function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$this->_column_headers = array($columns, $hidden, $sortable);
$total_items =sizeof($this->list);
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => 20,
)
);
}
public function display_rows()
{
$this->_display_rows( $this->list );
}
private function _display_rows( $list )
{
$page=$this->get_pagenum();
$page_list=$list;
$temp_page_list=array();
$count=0;
while ( $count<$page )
{
$temp_page_list = array_splice( $page_list, 0, 20);
$count++;
}
foreach ( $temp_page_list as $key=>$item)
{
$this->single_row($item);
}
}
public function single_row($item)
{
?>
<tr path="<?php echo esc_attr($item['path'])?>">
<?php $this->single_row_columns( $item ); ?>
</tr>
<?php
}
protected function pagination( $which )
{
if ( empty( $this->_pagination_args ) )
{
return;
}
$total_items = $this->_pagination_args['total_items'];
$total_pages = $this->_pagination_args['total_pages'];
$infinite_scroll = false;
if ( isset( $this->_pagination_args['infinite_scroll'] ) )
{
$infinite_scroll = $this->_pagination_args['infinite_scroll'];
}
if ( 'top' === $which && $total_pages > 1 )
{
$this->screen->render_screen_reader_content( 'heading_pagination' );
}
$output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items, 'wpvivid-backuprestore' ), number_format_i18n( $total_items ) ) . '</span>';
$current = $this->get_pagenum();
$page_links = array();
$total_pages_before = '<span class="paging-input">';
$total_pages_after = '</span></span>';
$disable_first = $disable_last = $disable_prev = $disable_next = false;
if ( $current == 1 ) {
$disable_first = true;
$disable_prev = true;
}
if ( $current == 2 ) {
$disable_first = true;
}
if ( $current == $total_pages ) {
$disable_last = true;
$disable_next = true;
}
if ( $current == $total_pages - 1 ) {
$disable_last = true;
}
if ( $disable_first ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>';
} else {
$page_links[] = sprintf(
"<div class='first-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'First page', 'wpvivid-backuprestore' ),
'«'
);
}
if ( $disable_prev ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>';
} else {
$page_links[] = sprintf(
"<div class='prev-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Previous page', 'wpvivid-backuprestore' ),
'‹'
);
}
if ( 'bottom' === $which ) {
$html_current_page = $current;
$total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
} else {
$html_current_page = sprintf(
"%s<input class='current-page' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
'<label class="screen-reader-text">' . __( 'Current Page', 'wpvivid-backuprestore' ) . '</label>',
$current,
strlen( $total_pages )
);
}
$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
$page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging', 'wpvivid-backuprestore' ), $html_current_page, $html_total_pages ) . $total_pages_after;
if ( $disable_next ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>';
} else {
$page_links[] = sprintf(
"<div class='next-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Next page', 'wpvivid-backuprestore' ),
'›'
);
}
if ( $disable_last ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>';
} else {
$page_links[] = sprintf(
"<div class='last-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'Last page', 'wpvivid-backuprestore' ),
'»'
);
}
$pagination_links_class = 'pagination-links';
if ( ! empty( $infinite_scroll ) ) {
$pagination_links_class .= ' hide-if-js';
}
$output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
if ( $total_pages ) {
$page_class = $total_pages < 2 ? ' one-page' : '';
} else {
$page_class = ' no-pages';
}
$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
echo $this->_pagination;
}
protected function display_tablenav( $which ) {
$css_type = '';
if ( 'top' === $which ) {
wp_nonce_field( 'bulk-' . $this->_args['plural'] );
$css_type = 'margin: 0 0 10px 0';
}
else if( 'bottom' === $which ) {
$css_type = 'margin: 10px 0 0 0';
}
$total_pages = $this->_pagination_args['total_pages'];
$admin_url = apply_filters('wpvivid_get_admin_url', '');
if ( $total_pages >1)
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<div class="alignleft actions bulkactions">
<label for="wpvivid_uc_iso_bulk_action" class="screen-reader-text"><?php esc_html_e( 'Select bulk action', 'wpvivid-backuprestore' ); ?></label>
<select name="action" id="wpvivid_uc_iso_bulk_action">
<option value="-1"><?php esc_html_e( 'Bulk Actions', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_restore_selected_image"><?php esc_html_e( 'Restore selected images', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_restore_list_image"><?php esc_html_e( 'Restore all images', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_delete_selected_image"><?php esc_html_e( 'Delete selected images', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_delete_list_image"><?php esc_html_e( 'Delete all images', 'wpvivid-backuprestore' ); ?></option>
</select>
<input type="submit" class="button action" value="<?php esc_attr_e( 'Apply', 'wpvivid-backuprestore' ); ?>">
</div>
<div id="wpvivid_restore_delete_progress" style="margin-top: 4px; display: none;">
<div class="spinner is-active" style="margin: 0 5px 10px 0; float: left;"></div>
<div id="wpvivid_restore_delete_text" style="float: left; margin-top: 2px;"><?php esc_html_e( 'Restoring images...', 'wpvivid-backuprestore' ); ?></div>
<div style="clear: both;"></div>
</div>
<div class="wpvivid-backup-tips" style="background: #fff; border: 1px solid #f1f1f1; border-radius: 6px; margin-top: 10px;margin-bottom: 10px">
<div style="float: left;">
<div style="padding: 10px;">
<strong><?php esc_html_e('Note: ', 'wpvivid-backuprestore'); ?></strong>
<?php echo sprintf('Once deleted, images will be lost permanently. The action cannot be undone, unless you have %1$sa backup%2$s in place.', '<a href="'. esc_url($admin_url) . 'admin.php?page=WPvivid'.'">', '</a>'); ?>
</div>
</div>
<div style="clear: both;"></div>
</div>
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
else
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<div class="alignleft actions bulkactions">
<label for="wpvivid_uc_iso_bulk_action" class="screen-reader-text"><?php esc_html_e( 'Select bulk action', 'wpvivid-backuprestore' ); ?></label>
<select name="action" id="wpvivid_uc_iso_bulk_action">
<option value="-1"><?php esc_html_e( 'Bulk Actions', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_restore_selected_image"><?php esc_html_e( 'Restore selected images', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_restore_list_image"><?php esc_html_e( 'Restore all images', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_delete_selected_image"><?php esc_html_e( 'Delete selected images', 'wpvivid-backuprestore' ); ?></option>
<option value="wpvivid_delete_list_image"><?php esc_html_e( 'Delete all images', 'wpvivid-backuprestore' ); ?></option>
</select>
<input type="submit" class="button action" value="<?php esc_attr_e( 'Apply', 'wpvivid-backuprestore' ); ?>">
</div>
<div id="wpvivid_restore_delete_progress" style="margin-top: 4px; display: none;">
<div class="spinner is-active" style="margin: 0 5px 10px 0; float: left;"></div>
<div id="wpvivid_restore_delete_text" style="float: left; margin-top: 2px;"><?php esc_html_e( 'Restoring images...', 'wpvivid-backuprestore' ); ?></div>
<div style="clear: both;"></div>
</div>
<div class="wpvivid-backup-tips" style="background: #fff; border: 1px solid #f1f1f1; border-radius: 6px; margin-top: 10px;margin-bottom: 10px">
<div style="float: left;">
<div style="padding: 10px;">
<strong><?php esc_html_e('Note: ', 'wpvivid-backuprestore'); ?></strong>
<?php echo sprintf('Once deleted, images will be lost permanently. The action cannot be undone, unless you have %1$sa backup%2$s in place.', '<a href="'. esc_url($admin_url) . 'admin.php?page=WPvivid'.'">', '</a>'); ?>
</div>
</div>
<div style="clear: both;"></div>
</div>
<br class="clear" />
</div>
<?php
}
}
public function display() {
$singular = $this->_args['singular'];
$this->display_tablenav( 'top' );
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<table class="wp-list-table <?php echo esc_attr(implode( ' ', $this->get_table_classes() )); ?>" >
<thead>
<tr>
<?php $this->print_column_headers(); ?>
</tr>
</thead>
<tbody id="the-list"
<?php
if ( $singular ) {
echo esc_attr(" data-wp-lists='list:$singular'");
}
?>
>
<?php $this->display_rows_or_placeholder(); ?>
</tbody>
<tfoot>
<tr>
<?php $this->print_column_headers( false ); ?>
</tr>
</tfoot>
</table>
<?php
}
}
class WPvivid_Uploads_Cleaner
{
public $main_tab;
//public $screen_ids;
//public $version;
//public $plugin_name;
public function __construct()
{
//$this->version = WPVIVID_UPLOADS_CLEANER_VERSION;
//$this->plugin_name = WPVIVID_UPLOADS_CLEANER_SLUG;
//$this->screen_ids=array();
//$this->screen_ids[]='toplevel_page_'. $this->plugin_name;
//add_action('admin_enqueue_scripts',array( $this,'enqueue_styles'));
//add_action('admin_enqueue_scripts',array( $this,'enqueue_scripts'));
//add_action('admin_menu',array( $this,'add_plugin_admin_menu'));
//$plugin_basename = plugin_basename( plugin_dir_path( __DIR__ ) . 'wpvivid-uploads-cleaner.php' );
//add_filter('plugin_action_links_' . $plugin_basename, array( $this,'add_action_links'));
add_filter('wpvivid_scan_post_types',array($this,'scan_post_types'),10);
add_action('wp_ajax_wpvivid_start_scan_uploads_files_task', array($this, 'start_scan_uploads_files_task'));
add_action('wp_ajax_wpvivid_scan_uploads_files_from_post',array($this, 'scan_uploads_files_from_post'));
add_action('wp_ajax_wpvivid_start_unused_files_task',array($this, 'start_unused_files_task'));
add_action('wp_ajax_wpvivid_unused_files_task',array($this, 'unused_files_task'));
add_action('wp_ajax_wpvivid_get_result_list',array($this, 'get_result_list'));
add_action('wp_ajax_wpvivid_isolate_selected_image',array($this, 'isolate_selected_image'));
add_action('wp_ajax_wpvivid_start_isolate_all_image',array($this, 'start_isolate_all_image'));
add_action('wp_ajax_wpvivid_isolate_all_image',array($this, 'isolate_all_image'));
//
add_action('wp_ajax_wpvivid_get_iso_list',array($this, 'get_iso_list'));
add_action('wp_ajax_wpvivid_delete_selected_image',array($this, 'delete_selected_image'));
add_action('wp_ajax_wpvivid_start_delete_all_image',array($this, 'delete_all_image'));
add_action('wp_ajax_wpvivid_delete_all_image',array($this, 'delete_all_image'));
add_action('wp_ajax_wpvivid_restore_selected_image',array($this, 'restore_selected_image'));
add_action('wp_ajax_wpvivid_start_restore_all_image',array($this, 'restore_all_image'));
add_action('wp_ajax_wpvivid_restore_all_image',array($this, 'restore_all_image'));
add_action('wp_ajax_wpvivid_uc_add_exclude_files',array($this, 'add_exclude_files'));
//
add_filter('wpvivid_uc_scan_include_files_regex',array($this,'scan_include_files_regex'),10);
add_filter('wpvivid_uc_scan_exclude_files_regex',array($this,'scan_exclude_files_regex'),10);
include_once WPVIVID_PLUGIN_DIR . '/includes/upload-cleaner/class-wpvivid-uploads-scanner.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/upload-cleaner/class-wpvivid-isolate-files.php';
include_once WPVIVID_PLUGIN_DIR. '/includes/upload-cleaner/class-wpvivid-upload-cleaner-setting.php';
$iso=new WPvivid_Isolate_Files();
$iso->check_folder();
$setting=new WPvivid_Uploads_Cleaner_Setting();
add_filter('wpvivid_get_toolbar_menus',array($this,'get_toolbar_menus'),22);
add_filter('wpvivid_get_admin_menus',array($this,'get_admin_menus'),22);
add_filter('wpvivid_get_screen_ids',array($this,'get_screen_ids'),12);
}
public function get_screen_ids($screen_ids)
{
$screen_ids[]=apply_filters('wpvivid_white_label_screen_id', 'wpvivid-backup_page_wpvivid-cleaner');
return $screen_ids;
}
public function get_toolbar_menus($toolbar_menus)
{
$admin_url = apply_filters('wpvivid_get_admin_url', '');
$menu['id']='wpvivid_admin_menu_cleaner';
$menu['parent']='wpvivid_admin_menu';
$menu['title']=__('Image Cleaner', 'wpvivid-backuprestore');
$menu['tab']= 'admin.php?page='.apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-cleaner');
$menu['href']=$admin_url . 'admin.php?page='.apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-cleaner');
$menu['capability']='administrator';
$menu['index']=4;
$toolbar_menus[$menu['parent']]['child'][$menu['id']]=$menu;
return $toolbar_menus;
}
public function get_admin_menus($submenus)
{
$submenu['parent_slug']=apply_filters('wpvivid_white_label_slug', WPVIVID_PLUGIN_SLUG);
$submenu['page_title']= apply_filters('wpvivid_white_label_display', 'WPvivid Backup');
$submenu['menu_title']=__('Image Cleaner', 'wpvivid-backuprestore');
$submenu['capability']='administrator';
$submenu['menu_slug']=strtolower(sprintf('%s-cleaner', apply_filters('wpvivid_white_label_slug', 'wpvivid')));
$submenu['index']=4;
$submenu['function']=array($this, 'display');
$submenus[$submenu['menu_slug']]=$submenu;
return $submenus;
}
private function transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode(DIRECTORY_SEPARATOR,$values);
}
public function wpvivid_check_jet_engine()
{
if (!function_exists('get_plugins'))
{
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$active_plugins = get_option('active_plugins');
$plugins=get_plugins();
$jet_engine_slug='jet-engine/jet-engine.php';
if(!empty($plugins))
{
if(isset($plugins[$jet_engine_slug]))
{
if(in_array($jet_engine_slug, $active_plugins))
{
echo '<div class="notice notice-warning inline" style="margin: 10px 0 0 0;"><p><strong>Warning:</strong> We detected that you use Jet Engine plugin on this site,
it may have compatibility issues with our plugin, which can result in an inaccuracy of the scan result,
so we recommend not using this feature yet.
</p></div>';
}
}
}
}
public function display()
{
$scan=new WPvivid_Uploads_Scanner();
$scan->check_table_exist();
$scan->check_unused_uploads_files_table_exist();
$upload_dir=wp_upload_dir();
$path=$this->transfer_path($upload_dir['basedir']);
$path1=$this->transfer_path(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'uploads');
if($path!==$path1)
{
echo '<div class="notice notice-error inline"><p>The current version does not support custom uploads directory</p></div>';
return;
}
?>
<div class="wrap" style="max-width:1720px;">
<h1>
<?php
esc_html_e('WPvivid Image Cleaner', 'wpvivid-backuprestore');
?>
</h1>
<?php $this->wpvivid_check_jet_engine(); ?>
<?php
if(!class_exists('WPvivid_Tab_Page_Container'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-tab-page-container.php';
$args['is_parent_tab']=1;
$this->main_tab=new WPvivid_Tab_Page_Container();
$this->main_tab->add_tab(__('Scan Media', 'wpvivid-backuprestore'),'scan',array($this, 'output_scan'), $args);
$this->main_tab->add_tab(__('Isolated Media', 'wpvivid-backuprestore'),'isolate',array($this, 'output_isolate'), $args);
//$this->main_tab->add_tab('Database','database',array($this, 'output_database'), $args);
$this->main_tab->display();
if (isset($_GET['tab']))
{
$tab=esc_html($_GET['tab']);
?>
<script>
jQuery(document).ready(function($)
{
jQuery( document ).trigger( '<?php echo esc_attr($this->main_tab->container_id); ?>-show','<?php echo esc_attr($tab); ?>');
});
</script>
<?php
}
?>
</div>
<?php
}
public function output_scan()
{
$scanner=new WPvivid_Uploads_Scanner();
$count=$scanner->get_scan_result_count();
$size=$scanner->get_scan_result_size();
$upload_dir=wp_upload_dir();
$path=$this->transfer_path($upload_dir['basedir']);
$abs=$this->transfer_path(ABSPATH);
$path=str_replace($abs,'...'.DIRECTORY_SEPARATOR,$path);
$folders=$scanner->get_all_folder();
$admin_url = apply_filters('wpvivid_get_admin_url', '');
//Before running a scan, it is recommended to <a style="cursor:pointer;" href="<?php echo $admin_url . 'admin.php?page=WPvivid';">[make a full website backup]</a> to avoid losing images.
$progress_bar='<div class="action-progress-bar"><div class="action-progress-bar-percent" style="height:24px;width:0%"></div></div> <div style="clear:both;"></div><div style="margin-left:10px; float: left; width:100%;"><p>Ready to scan</p></div> <div style="clear: both;"></div><div><div class="backup-log-btn"><input class="button-primary" id="wpvivid_uc_cancel" type="submit" value="Cancel" /></div></div><div style="clear: both;"></div>';
?>
<div class="postbox quickbackup-addon">
<div style="margin-top: 10px;margin-bottom: 10px;">
<?php esc_html_e('In the tab, you can scan your media folder (uploads) to find unused images and isolate specific or all unused images.', 'wpvivid-backuprestore'); ?>
</div>
<div id="wpvivid_uc_scan">
<div style="margin-top: 10px;margin-bottom: 10px;">
<?php esc_html_e('Media path: ', 'wpvivid-backuprestore'); ?><a><?php echo esc_html($path)?></a>
</div>
<input class="button-primary" style="width: 200px; height: 50px; font-size: 20px;" id="wpvivid_start_scan" type="submit" value="<?php esc_attr_e('Scan', 'wpvivid-backuprestore'); ?>">
<div style="clear: both;"></div>
<div style="margin-top: 10px">
<span>
<?php esc_html_e('Clicking the \'Scan\' button to find unused images in your media folder. Currently it only scans JPG and PNG images.', 'wpvivid-backuprestore'); ?>
</span>
</div>
<?php
if($count===false)
{
}
else
{
echo "<p style=\"margin-top: 10px; margin-bottom: 0px;\">Last Scan: Unused media file(s) found: <strong>".esc_html($count)."</strong>. ";
if($size!==false)
{
echo 'Total size: '.esc_html($size).' .';
}
echo "</p>";
}
?>
<div class="wpvivid-backup-tips" style="background: #fff; border: 1px solid #f1f1f1; border-radius: 6px; margin-top: 10px;">
<div style="float: left;">
<div style="padding: 10px;">
<strong><?php esc_html_e('Note: ', 'wpvivid-backuprestore'); ?></strong>
<?php esc_html_e('Please don\'t refresh the page while running a scan.', 'wpvivid-backuprestore'); ?>
</div>
</div>
<div style="clear: both;"></div>
</div>
</div>
<div id="wpvivid_uc_progress" style="display: none;">
<?php
echo '<div class="action-progress-bar"><div class="action-progress-bar-percent" style="height:24px;width:0%"></div></div> <div style="clear:both;"></div><div style="margin-left:10px; float: left; width:100%;"><p>Ready to scan</p></div> <div style="clear: both;"></div><div><div class="backup-log-btn"><input class="button-primary" id="wpvivid_uc_cancel" type="submit" value="Cancel" /></div></div><div style="clear: both;"></div>';
?>
</div>
<br/>
</div>
<div class="postbox quickbackup-addon">
<p>
<input id="wpvivid_result_list_search" type="search" name="s" value="" placeholder="<?php esc_attr_e('Search', 'wpvivid-backuprestore'); ?>">
<select id="wpvivid_result_list_folder" style="margin-top: -5px;">
<option selected="selected" value="0"><?php esc_html_e('All Folders', 'wpvivid-backuprestore'); ?></option>
<?php
if(!empty($folders))
{
asort($folders);
foreach ($folders as $folder)
{
echo "<option value='".esc_attr($folder)."'>".esc_html($folder)."</option>";
}
}
?>
</select>
<input id="wpvivid_result_list_search_btn" type="submit" class="button" value="<?php esc_attr_e('Search', 'wpvivid-backuprestore'); ?>">
</p>
</div>
<div class="postbox">
<div id="wpvivid_scan_result_list" style="margin: 10px;">
<?php
$result=$scanner->get_scan_result('','');
$list = new WPvivid_Unused_Upload_Files_List();
$list->set_list($result);
$list->prepare_items();
$list ->display();
?>
</div>
</div>
<script>
var wpvivid_result_list_search='';
var wpvivid_result_list_folder='';
jQuery('#wpvivid_result_list_search_btn').click(function()
{
wpvivid_result_list_search=jQuery('#wpvivid_result_list_search').val();
wpvivid_result_list_folder=jQuery('#wpvivid_result_list_folder').val();
if(wpvivid_result_list_folder=='0')
{
wpvivid_result_list_folder='';
}
if(wpvivid_result_list_folder=='root')
{
wpvivid_result_list_folder='.';
}
wpvivid_get_result_list('first');
});
function wpvivid_get_result_list(page)
{
var ajax_data = {
'action': 'wpvivid_get_result_list',
'page':page,
'search':wpvivid_result_list_search,
'folder':wpvivid_result_list_folder
};
wpvivid_post_request(ajax_data, function (data)
{
//var old_html= jQuery('#wpvivid_scan_result_list').html();
//jQuery('#wpvivid_scan_result_list').html('');
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.empty)
{
jQuery('#wpvivid_result_list_search').val('');
wpvivid_result_list_search='';
alert('No items found.');
//jQuery('#wpvivid_scan_result_list').html(old_html);
}
else
{
jQuery('#wpvivid_scan_result_list').html(jsonarray.html);
}
}
else
{
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('get list', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#wpvivid_scan_result_list').on("click",'.wpvivid-no-item',function()
{
wpvivid_result_list_search='';
jQuery('#wpvivid_result_list_search').val('');
wpvivid_get_result_list('first');
});
jQuery('#wpvivid_scan_result_list').on("click",'.first-page',function()
{
wpvivid_get_result_list('first');
});
jQuery('#wpvivid_scan_result_list').on("click",'.prev-page',function()
{
var page=parseInt(jQuery(this).attr('value'));
wpvivid_get_result_list(page-1);
});
jQuery('#wpvivid_scan_result_list').on("click",'.next-page',function()
{
var page=parseInt(jQuery(this).attr('value'));
wpvivid_get_result_list(page+1);
});
jQuery('#wpvivid_scan_result_list').on("click",'.last-page',function()
{
wpvivid_get_result_list('last');
});
jQuery('#wpvivid_scan_result_list').on("keypress", '.current-page', function()
{
if(event.keyCode === 13){
var page = jQuery(this).val();
wpvivid_get_result_list(page);
}
});
jQuery('#wpvivid_scan_result_list').on("click",'.action',function()
{
var selected=jQuery('#wpvivid_uc_bulk_action').val();
if(selected=='wpvivid_isolate_selected_image')
{
wpvivid_isolate_selected_image();
}
else if(selected=='wpvivid_isolate_list_image')
{
wpvivid_start_isolate_all_image();
}
else if(selected=='wpvivid_ignore_selected_image')
{
wpvivid_ignore_selected_image();
}
});
function wpvivid_ignore_selected_image()
{
var json = {};
json['selected']=Array();
jQuery('input[name=uploads][type=checkbox]').each(function(index, value)
{
if(jQuery(value).prop('checked'))
{
json['selected'].push(jQuery(value).val())
}
});
var selected= JSON.stringify(json);
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', true);
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', true);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', true);
var ajax_data = {
'action': 'wpvivid_uc_add_exclude_files',
'selected':selected,
'search':wpvivid_result_list_search,
'folder':wpvivid_result_list_folder
};
wpvivid_post_request(ajax_data, function (data)
{
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', false);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', false);
jQuery('#wpvivid_scan_result_list').html('');
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_scan_result_list').html(jsonarray.html);
}
else
{
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', false);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', false);
var error_message = wpvivid_output_ajaxerror('add options', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_isolate_selected_image()
{
var json = {};
json['selected']=Array();
jQuery('input[name=uploads][type=checkbox]').each(function(index, value)
{
if(jQuery(value).prop('checked'))
{
json['selected'].push(jQuery(value).val())
}
});
var selected= JSON.stringify(json);
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', true);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', true);
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', true);
var ajax_data = {
'action': 'wpvivid_isolate_selected_image',
'selected':selected,
'search':wpvivid_result_list_search,
'folder':wpvivid_result_list_folder
};
jQuery('#wpvivid_isolate_progress').show();
wpvivid_post_request(ajax_data, function (data)
{
jQuery('#wpvivid_isolate_progress').hide();
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', false);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', false);
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', false);
jQuery('#wpvivid_scan_result_list').html('');
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_scan_result_list').html(jsonarray.html);
jQuery('#wpvivid_iso_files_list').html(jsonarray.iso);
}
else
{
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#wpvivid_isolate_progress').hide();
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', false);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', false);
var error_message = wpvivid_output_ajaxerror('add isolate files', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_start_isolate_all_image()
{
var ajax_data = {
'action': 'wpvivid_start_isolate_all_image',
'search':wpvivid_result_list_search,
'folder':wpvivid_result_list_folder
};
jQuery('#wpvivid_isolate_progress').show();
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', true);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', true);
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', true);
wpvivid_post_request(ajax_data, function (data)
{
jQuery('#wpvivid_isolate_progress').hide();
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.continue)
{
wpvivid_isolate_all_image();
}
else
{
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page='.esc_html(apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-cleaner'));?>';
}
}
else if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', false);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', false);
}
}
catch(err)
{
alert(err);
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', false);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', false);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#wpvivid_isolate_progress').hide();
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', false);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', false);
var error_message = wpvivid_output_ajaxerror('add isolate files', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_isolate_all_image()
{
var ajax_data = {
'action': 'wpvivid_isolate_all_image',
'search':wpvivid_result_list_search,
'folder':wpvivid_result_list_folder
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.continue)
{
wpvivid_isolate_all_image();
}
else
{
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page='.esc_html(apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-cleaner'));?>';
}
}
else if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', false);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', false);
}
}
catch(err)
{
alert(err);
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', false);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', false);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('add isolate files', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_scan_result_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_isolate_selected_image').prop('disabled', false);
//jQuery('#wpvivid_isolate_list_image').prop('disabled', false);
});
}
jQuery('#wpvivid_rescan').click(function()
{
jQuery( document ).trigger( '<?php echo esc_attr($this->main_tab->container_id) ?>-show','scan');
});
</script>
<script>
var wpvivid_cancel=false;
jQuery('#wpvivid_start_scan').click(function()
{
wpvivid_start_scan();
//wpvivid_start_unused_files_task();
});
jQuery('#wpvivid_uc_progress').on("click",'#wpvivid_uc_cancel',function()
{
wpvivid_cancel_scan();
});
function wpvivid_cancel_scan()
{
wpvivid_cancel=true;
jQuery('#wpvivid_uc_cancel').prop('disabled', true);
}
function wpvivid_start_scan()
{
jQuery('#wpvivid_uc_progress').show();
jQuery('#wpvivid_uc_progress').html('<?php echo '<div class="action-progress-bar"><div class="action-progress-bar-percent" style="height:24px;width:0%"></div></div> <div style="clear:both;"></div><div style="margin-left:10px; float: left; width:100%;"><p>Ready to scan</p></div> <div style="clear: both;"></div><div><div class="backup-log-btn"><input class="button-primary" id="wpvivid_uc_cancel" type="submit" value="Cancel" /></div></div><div style="clear: both;"></div>';?>');
jQuery('#wpvivid_uc_scan').hide();
jQuery('#wpvivid_uc_cancel').prop('disabled', false);
wpvivid_cancel=false;
var ajax_data = {
'action': 'wpvivid_start_scan_uploads_files_task'
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_uc_progress').html(jsonarray.progress_html);
if(jsonarray.continue)
{
scan_uploads_files(jsonarray.start);
}
else
{
wpvivid_start_unused_files_task();
}
}
else if (jsonarray.result === 'failed')
{
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
}
}
catch(err)
{
alert(err);
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('scan files', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
});
}
function scan_uploads_files(start)
{
if(wpvivid_cancel)
{
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
jQuery('#wpvivid_uc_cancel').prop('disabled', false);
return;
}
var ajax_data = {
'action': 'wpvivid_scan_uploads_files_from_post',
'start':start
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_uc_progress').html(jsonarray.progress_html);
if(jsonarray.continue)
{
scan_uploads_files(jsonarray.start);
}
else
{
wpvivid_start_unused_files_task();
}
}
else if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
}
}
catch(err)
{
alert(err);
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('scan files', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
});
}
function wpvivid_start_unused_files_task()
{
if(wpvivid_cancel)
{
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
jQuery('#wpvivid_uc_cancel').prop('disabled', false);
return;
}
var ajax_data = {
'action': 'wpvivid_start_unused_files_task'
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_uc_progress').html(jsonarray.progress_html);
if(jsonarray.continue)
{
wpvivid_unused_files_task();
}
else
{
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page='.esc_html(apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-cleaner'));?>';
}
}
else if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
}
}
catch(err)
{
alert(err);
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('scan files', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
});
}
function wpvivid_unused_files_task()
{
if(wpvivid_cancel)
{
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
jQuery('#wpvivid_uc_cancel').prop('disabled', false);
jQuery('#wpvivid_uc_scan_log').html("");
return;
}
var ajax_data = {
'action': 'wpvivid_unused_files_task'
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_uc_progress').html(jsonarray.progress_html);
if(jsonarray.continue)
{
wpvivid_unused_files_task();
}
else
{
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page='.esc_html(apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-cleaner'));?>';
}
}
else if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
}
}
catch(err)
{
alert(err);
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('scan files', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_uc_progress').hide();
jQuery('#wpvivid_uc_scan').show();
});
}
jQuery(document).ready(function($)
{
jQuery('#wpvivid_uc_scan').show();
jQuery('#wpvivid_uc_progress').hide();
});
</script>
<?php
}
public function output_isolate()
{
$iso=new WPvivid_Isolate_Files();
$path=$this->transfer_path(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR);
$abs=$this->transfer_path(ABSPATH);
$path=str_replace($abs,'...'.DIRECTORY_SEPARATOR,$path);
$result=$iso->get_isolate_folder();
?>
<div class="postbox quickbackup-addon">
<div style="margin-top: 10px;margin-bottom: 10px;">
<?php esc_html_e('This tab displays the isolated images and their locations. You can choose to restore or delete specific isolated images.', 'wpvivid-backuprestore'); ?>
</div>
<div style="margin-top: 10px;margin-bottom: 10px;">
<?php esc_html_e('lsolated Folder Path: ', 'wpvivid-backuprestore'); ?><a><?php echo esc_html($path)?></a>
</div>
</div>
<div class="postbox quickbackup-addon">
<p>
<input id="wpvivid_iso_list_search" type="search" name="s" value="" placeholder="<?php esc_attr_e('Search', 'wpvivid-backuprestore'); ?>">
<select id="wpvivid_iso_list_folder" style="margin-top: -5px;">
<option selected="selected" value="0"><?php esc_html_e('All Folders', 'wpvivid-backuprestore'); ?></option>
<?php
asort($result['folders']);
foreach ($result['folders'] as $folder)
{
echo "<option value='".esc_attr($folder)."'>".esc_html($folder)."</option>";
}
?>
</select>
<input id="wpvivid_iso_list_search_btn" type="submit" class="button" value="<?php esc_attr_e('Search', 'wpvivid-backuprestore'); ?>">
</p>
</div>
<div class="postbox">
<div id="wpvivid_iso_files_list" style="margin: 10px;">
<?php
$files=$iso->get_isolate_files();
$list = new WPvivid_Isolate_Files_List();
$list->set_list($files);
$list->prepare_items();
$list ->display();
?>
</div>
</div>
<script>
var wpvivid_iso_list_search='';
var wpvivid_iso_list_folder='';
jQuery('#wpvivid_iso_list_search_btn').click(function()
{
wpvivid_iso_list_search=jQuery('#wpvivid_iso_list_search').val();
wpvivid_iso_list_folder=jQuery('#wpvivid_iso_list_folder').val();
if(wpvivid_iso_list_folder=='0')
{
wpvivid_iso_list_folder='';
}
if(wpvivid_iso_list_folder=='root')
{
wpvivid_iso_list_folder='.';
}
wpvivid_get_iso_list('first');
});
function wpvivid_get_iso_list(page)
{
var ajax_data = {
'action': 'wpvivid_get_iso_list',
'page':page,
'search':wpvivid_iso_list_search,
'folder':wpvivid_iso_list_folder
};
wpvivid_post_request(ajax_data, function (data)
{
//jQuery('#wpvivid_iso_files_list').html('');
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.empty)
{
jQuery('#wpvivid_iso_list_search').val('');
wpvivid_iso_list_search='';
alert('No items found.');
}
else
{
jQuery('#wpvivid_iso_files_list').html(jsonarray.html);
}
}
else
{
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('get list', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#wpvivid_iso_files_list').on("click",'.first-page',function()
{
wpvivid_get_iso_list('first');
});
jQuery('#wpvivid_iso_files_list').on("click",'.wpvivid-no-item',function()
{
wpvivid_iso_list_search='';
jQuery('#wpvivid_iso_files_list').val('');
wpvivid_get_iso_list('first');
});
jQuery('#wpvivid_iso_files_list').on("click",'.prev-page',function()
{
var page=parseInt(jQuery(this).attr('value'));
wpvivid_get_iso_list(page-1);
});
jQuery('#wpvivid_iso_files_list').on("click",'.next-page',function()
{
var page=parseInt(jQuery(this).attr('value'));
wpvivid_get_iso_list(page+1);
});
jQuery('#wpvivid_iso_files_list').on("click",'.last-page',function()
{
wpvivid_get_iso_list('last');
});
jQuery('#wpvivid_iso_files_list').on("keypress", '.current-page', function()
{
if(event.keyCode === 13){
var page = jQuery(this).val();
wpvivid_get_iso_list(page);
}
});
jQuery('#wpvivid_iso_files_list').on("click",'.action',function()
{
var selected=jQuery('#wpvivid_uc_iso_bulk_action').val();
if(selected=='wpvivid_delete_selected_image')
{
wpvivid_delete_selected_image();
}
else if(selected=='wpvivid_delete_list_image')
{
wpvivid_start_delete_all_image();
}
else if(selected=='wpvivid_restore_selected_image')
{
wpvivid_restore_selected_image();
}
else if(selected=='wpvivid_restore_list_image')
{
wpvivid_start_restore_all_image();
}
});
function wpvivid_delete_selected_image()
{
var json = {};
json['selected']=Array();
jQuery('input[name=uploads][type=checkbox]').each(function(index, value)
{
if(jQuery(value).prop('checked'))
{
jQuery(value).closest('tr');
var path = jQuery(this).closest('tr').attr('path');
json['selected'].push(path)
}
});
var selected= JSON.stringify(json);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', true);
var ajax_data = {
'action': 'wpvivid_delete_selected_image',
'selected':selected,
'search':wpvivid_iso_list_search,
'folder':wpvivid_iso_list_folder
};
jQuery('#wpvivid_restore_delete_progress').show();
jQuery('#wpvivid_restore_delete_text').html('Deleting images...');
wpvivid_post_request(ajax_data, function (data)
{
jQuery('#wpvivid_restore_delete_progress').hide();
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
jQuery('#wpvivid_iso_files_list').html('');
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_iso_files_list').html(jsonarray.html);
}
else
{
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#wpvivid_restore_delete_progress').hide();
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_delete_selected_image').prop('disabled', false);
//jQuery('#wpvivid_delete_list_image').prop('disabled', false);
//jQuery('#wpvivid_restore_selected_image').prop('disabled', false);
//jQuery('#wpvivid_restore_list_image').prop('disabled', false);
var error_message = wpvivid_output_ajaxerror('delete files', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_start_delete_all_image()
{
var ajax_data = {
'action': 'wpvivid_start_delete_all_image',
'search':wpvivid_iso_list_search,
'folder':wpvivid_iso_list_folder
};
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', true);
jQuery('#wpvivid_restore_delete_progress').show();
jQuery('#wpvivid_restore_delete_text').html('Deleting images...');
wpvivid_post_request(ajax_data, function (data)
{
jQuery('#wpvivid_restore_delete_progress').hide();
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.continue)
{
wpvivid_delete_all_image();
}
else
{
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page=' .esc_html(apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-cleaner')). '&tab=isolate'?>';
}
}
else if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
}
}
catch(err)
{
alert(err);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_delete_selected_image').prop('disabled', false);
//jQuery('#wpvivid_delete_list_image').prop('disabled', false);
//jQuery('#wpvivid_restore_selected_image').prop('disabled', false);
//jQuery('#wpvivid_restore_list_image').prop('disabled', false);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#wpvivid_restore_delete_progress').hide();
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_delete_selected_image').prop('disabled', false);
//jQuery('#wpvivid_delete_list_image').prop('disabled', false);
//jQuery('#wpvivid_restore_selected_image').prop('disabled', false);
//jQuery('#wpvivid_restore_list_image').prop('disabled', false);
var error_message = wpvivid_output_ajaxerror('delete files', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_delete_all_image()
{
var ajax_data = {
'action': 'wpvivid_delete_all_image',
'search':wpvivid_iso_list_search,
'folder':wpvivid_iso_list_folder
};
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', true);
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.continue)
{
wpvivid_delete_all_image();
}
else
{
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page=' .esc_html(apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-cleaner')). '&tab=isolate'?>';
}
}
else if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
}
}
catch(err)
{
alert(err);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('delete files', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
});
}
function wpvivid_restore_selected_image()
{
var json = {};
json['selected']=Array();
jQuery('input[name=uploads][type=checkbox]').each(function(index, value)
{
if(jQuery(value).prop('checked'))
{
jQuery(value).closest('tr');
var path = jQuery(this).closest('tr').attr('path');
json['selected'].push(path)
}
});
var selected= JSON.stringify(json);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', true);
var ajax_data = {
'action': 'wpvivid_restore_selected_image',
'selected':selected,
'search':wpvivid_iso_list_search,
'folder':wpvivid_iso_list_folder
};
jQuery('#wpvivid_restore_delete_progress').show();
jQuery('#wpvivid_restore_delete_text').html('Restoring images...');
wpvivid_post_request(ajax_data, function (data)
{
jQuery('#wpvivid_restore_delete_progress').hide();
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
jQuery('#wpvivid_iso_files_list').html('');
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_iso_files_list').html(jsonarray.html);
}
else
{
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#wpvivid_restore_delete_progress').hide();
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_delete_selected_image').prop('disabled', false);
//jQuery('#wpvivid_delete_list_image').prop('disabled', false);
//jQuery('#wpvivid_restore_selected_image').prop('disabled', false);
//jQuery('#wpvivid_restore_list_image').prop('disabled', false);
var error_message = wpvivid_output_ajaxerror('restore files', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_start_restore_all_image()
{
var ajax_data = {
'action': 'wpvivid_start_restore_all_image',
'search':wpvivid_iso_list_search,
'folder':wpvivid_iso_list_folder
};
jQuery('#wpvivid_restore_delete_progress').show();
jQuery('#wpvivid_restore_delete_text').html('Restoring images...');
wpvivid_post_request(ajax_data, function (data)
{
jQuery('#wpvivid_restore_delete_progress').hide();
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.continue)
{
wpvivid_restore_all_image();
}
else
{
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page=' .esc_html(apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-cleaner')). '&tab=isolate'?>';
}
}
else if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
}
}
catch(err)
{
alert(err);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_delete_selected_image').prop('disabled', false);
//jQuery('#wpvivid_delete_list_image').prop('disabled', false);
//jQuery('#wpvivid_restore_selected_image').prop('disabled', false);
//jQuery('#wpvivid_restore_list_image').prop('disabled', false);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#wpvivid_restore_delete_progress').hide();
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_delete_selected_image').prop('disabled', false);
//jQuery('#wpvivid_delete_list_image').prop('disabled', false);
//jQuery('#wpvivid_restore_selected_image').prop('disabled', false);
//jQuery('#wpvivid_restore_list_image').prop('disabled', false);
var error_message = wpvivid_output_ajaxerror('restore files', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_restore_all_image()
{
var ajax_data = {
'action': 'wpvivid_restore_all_image',
'search':wpvivid_iso_list_search,
'folder':wpvivid_iso_list_folder
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.continue)
{
wpvivid_restore_all_image();
}
else
{
location.href = '<?php echo esc_url(admin_url()) . 'admin.php?page=' .esc_html(apply_filters('wpvivid_white_label_plugin_name', 'wpvivid-cleaner')). '&tab=isolate'?>';
}
}
else if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_delete_selected_image').prop('disabled', false);
//jQuery('#wpvivid_delete_list_image').prop('disabled', false);
//jQuery('#wpvivid_restore_selected_image').prop('disabled', false);
//jQuery('#wpvivid_restore_list_image').prop('disabled', false);
}
}
catch(err)
{
alert(err);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('restore files', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_iso_files_list').find('.action').prop('disabled', false);
//jQuery('#wpvivid_delete_selected_image').prop('disabled', false);
//jQuery('#wpvivid_delete_list_image').prop('disabled', false);
//jQuery('#wpvivid_restore_selected_image').prop('disabled', false);
//jQuery('#wpvivid_restore_list_image').prop('disabled', false);
});
}
</script>
<?php
}
public function output_database()
{
?>
<div class="postbox quickbackup-addon">
<h1>Coming soon</h1>
</div>
<?php
}
public function start_scan_uploads_files_task()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
set_time_limit(30);
$uploads_scanner=new WPvivid_Uploads_Scanner();
$uploads_scanner->init_scan_task();
$uploads_files=array();
$uploads_files[0]=$uploads_scanner->scan_sidebars_widgets();
$files=$uploads_scanner->scan_termmeta_thumbnail();
$uploads_files[0]=array_merge($uploads_files[0],$files);
$files=$uploads_scanner->scan_divi_options();
$uploads_files[0]=array_merge($uploads_files[0],$files);
$site_icon_id = (int) get_option( 'site_icon' );
if($site_icon_id)
{
$files=$uploads_scanner->get_attachment_size($site_icon_id);
$uploads_files[0]=array_merge($uploads_files[0],$files);
}
$site_logo_id = get_option( 'site_logo' );
if($site_logo_id)
{
$files=$uploads_scanner->get_attachment_size($site_logo_id);
$uploads_files[0]=array_merge($uploads_files[0],$files);
}
$count=$uploads_scanner->get_post_count();
$start=0;
$limit=min(get_option('wpvivid_uc_scan_limit',20),$count);
$posts=$uploads_scanner->get_posts($start,$limit);
foreach ($posts as $post)
{
$media=$uploads_scanner->get_media_from_post_content($post);
//$uploads_files['post_id']=$post;
//$uploads_files['uploads_files']=$media;
//$uploads_files=array_merge($uploads_files,$media);
if(!empty($media))
{
$uploads_files[$post]=$media;
}
$media=$uploads_scanner->get_media_from_post_meta($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
$media=$uploads_scanner->get_media_from_post_meta_elementor($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
//$uploads_ids=array_merge($uploads_ids,$media);
$media=$uploads_scanner->get_media_from_post_custom_meta($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
//fix theme WpResidence
$media=$uploads_scanner->get_media_from_wpresidence($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
//fix breakdance page builder
$media=$uploads_scanner->get_media_from_breakdance($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
//oxygen images
$media=$uploads_scanner->get_media_from_oxygen($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
}
$start+=$limit;
$result['result']='success';
if($count == 0){
$result['percent']=0;
}
else{
$result['percent']=intval(($start/$count)*100);
}
$result['total_posts']=$start;
$result['scanned_posts']=$count;
$result['descript']='Scanning files from posts';
$result['progress_html']='
<div class="action-progress-bar">
<div class="action-progress-bar-percent" style="height:24px;width:' . $result['percent'] . '%"></div>
</div>
<div style="float:left;">
<div class="backup-basic-info">
<span class="wpvivid-element-space-right">' . __('Total Posts:', 'wpvivid-backuprestore') . '</span>
<span>' . $result['total_posts'] . '</span>
</div>
<div class="backup-basic-info">
<span class="wpvivid-element-space-right">' . __('Scanned:', 'wpvivid-backuprestore') . '</span>
<span>' . $result['scanned_posts'] . '</span>
</div>
</div>
<div style="clear:both;"></div>
<div style="margin-left:10px; float: left; width:100%;">
<p>' . $result['descript'] . '</p>
</div>
<div style="clear: both;"></div>
<div>
<div class="backup-log-btn">
<input class="button-primary" id="wpvivid_uc_cancel" type="submit" value="' . esc_attr('Cancel', 'wpvivid-backuprestore') . '" />
</div>
</div>
<div style="clear: both;"></div>';
if($start>=$count)
{
$uploads_scanner->update_scan_task($uploads_files,$start,'finished',100);
$result['start']=$start;
$result['status']='finished';
$result['continue']=0;
$result['log']='scan upload files finished'.PHP_EOL;
}
else
{
$uploads_scanner->update_scan_task($uploads_files,$start,'running');
$result['start']=$start;
$result['status']='running';
$result['continue']=1;
$result['log']='scanned posts:'.$start.PHP_EOL.'total posts:'.$count.PHP_EOL;
}
//$uploads_files=$uploads_scanner->get_files();
//$result['count']=$count;
//$result['files']=$uploads_files;
echo wp_json_encode($result);
die();
}
public function scan_uploads_files_from_post()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(!isset($_POST['start']))
{
die();
}
$start=intval($_POST['start']);
if(!is_int($start))
{
die();
}
set_time_limit(30);
$uploads_scanner=new WPvivid_Uploads_Scanner();
$count=$uploads_scanner->get_post_count();
$limit=min(get_option('wpvivid_uc_scan_limit',20),$count);
$posts=$uploads_scanner->get_posts($start,$limit);
$uploads_files=array();
foreach ($posts as $post)
{
$media=$uploads_scanner->get_media_from_post_content($post);
//$uploads_files['post_id']=$post;
//$uploads_files['uploads_files']=$media;
//$uploads_files=array_merge($uploads_files,$media);
if(!empty($media))
{
$uploads_files[$post]=$media;
}
$media=$uploads_scanner->get_media_from_post_meta($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
$media=$uploads_scanner->get_media_from_post_meta_elementor($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
$media=$uploads_scanner->get_media_from_post_custom_meta($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
//fix theme WpResidence
$media=$uploads_scanner->get_media_from_wpresidence($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
//fix breakdance page builder
$media=$uploads_scanner->get_media_from_breakdance($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
//oxygen images
$media=$uploads_scanner->get_media_from_oxygen($post);
if(!empty($media))
{
if(isset($uploads_files[$post]))
$uploads_files[$post]=array_merge($uploads_files[$post],$media);
else
$uploads_files[$post]=$media;
}
}
$start+=$limit;
$result['result']='success';
$result['percent']=intval(($start/$count)*100);
$result['total_posts']=$start;
$result['scanned_posts']=$count;
$result['descript']='Scanning files from posts';
$result['progress_html']='
<div class="action-progress-bar">
<div class="action-progress-bar-percent" style="height:24px;width:' . $result['percent'] . '%"></div>
</div>
<div style="float:left;">
<div class="backup-basic-info">
<span class="wpvivid-element-space-right">' . __('Total Posts:', 'wpvivid-backuprestore') . '</span>
<span>' . $result['total_posts'] . '</span>
</div>
<div class="backup-basic-info">
<span class="wpvivid-element-space-right">' . __('Scanned:', 'wpvivid-backuprestore') . '</span>
<span>' . $result['scanned_posts'] . '</span>
</div>
</div>
<div style="clear:both;"></div>
<div style="margin-left:10px; float: left; width:100%;">
<p>' . $result['descript'] . '</p>
</div>
<div style="clear: both;"></div>
<div>
<div class="backup-log-btn">
<input class="button-primary" id="wpvivid_uc_cancel" type="submit" value="' . esc_attr('Cancel', 'wpvivid-backuprestore') . '" />
</div>
</div>
<div style="clear: both;"></div>';
if($start>=$count)
{
$uploads_scanner->update_scan_task($uploads_files,$start,'finished',100);
$result['start']=$start;
$result['status']='finished';
$result['continue']=0;
$result['log']='scan upload files finished'.PHP_EOL;
}
else
{
$uploads_scanner->update_scan_task($uploads_files,$start,'running');
$result['start']=$start;
$result['status']='running';
$result['continue']=1;
$result['log']='scanned posts:'.$start.PHP_EOL.'total posts:'.$count.PHP_EOL;
}
$ret=$uploads_scanner->get_unused_uploads_progress();
$result['total_folders']=$ret['total_folders'];
$result['scanned_folders']=$ret['scanned_folders'];
$result['percent']=$ret['percent'];
echo wp_json_encode($result);
die();
}
public function start_unused_files_task()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
set_time_limit(30);
$uploads_scanner=new WPvivid_Uploads_Scanner();
$result=$uploads_scanner->get_folders();
$uploads_scanner->init_unused_uploads_task($result['folders']);
$files=array();
foreach ($result['files'] as $file)
{
if(!$uploads_scanner->is_uploads_files_exist($file))
{
$files[]=$file;
}
}
$uploads_scanner->update_unused_uploads_task($files,'.',1,0,'running',0,$result['size']);
$result['result']='success';
$result['status']='running';
$result['continue']=1;
$result['log']='scanning files'.PHP_EOL;
$ret=$uploads_scanner->get_unused_uploads_progress();
$result['total_folders']=$ret['total_folders'];
$result['scanned_folders']=$ret['scanned_folders'];
$result['percent']=$ret['percent'];
$result['descript']='Scanning upload folder.';
$result['progress_html']='
<div class="action-progress-bar">
<div class="action-progress-bar-percent" style="height:24px;width:' . $result['percent'] . '%"></div>
</div>
<div style="float:left;">
<div class="backup-basic-info">
<span class="wpvivid-element-space-right">' . __('Total Folders:', 'wpvivid-backuprestore') . '</span>
<span>' . $result['total_folders'] . '</span>
</div>
<div class="backup-basic-info">
<span class="wpvivid-element-space-right">' . __('Scanned:', 'wpvivid-backuprestore') . '</span>
<span>' . $result['scanned_folders'] . '</span>
</div>
</div>
<div style="clear:both;"></div>
<div style="margin-left:10px; float: left; width:100%;">
<p>' . $result['descript'] . '</p>
</div>
<div style="clear: both;"></div>
<div>
<div class="backup-log-btn">
<input class="button-primary" id="wpvivid_uc_cancel" type="submit" value="' . esc_attr('Cancel', 'wpvivid-backuprestore') . '" />
</div>
</div>
<div style="clear: both;"></div>';
$result['.']=$files;
echo wp_json_encode($result);
die();
}
public function unused_files_task()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
set_time_limit(30);
$uploads_scanner=new WPvivid_Uploads_Scanner();
$ret=$uploads_scanner->get_unfinished_folder();
if($ret===false)
{
$uploads_scanner->update_unused_uploads_task(array(),'.',1,0,'finished',100);
$result['result']='success';
$result['status']='finished';
$result['log']='scanning files finished'.PHP_EOL;
$result['percent']=100;
$result['continue']=0;
}
else
{
$size=0;
$folder=$ret['folder'];
$offset=$ret['offset'];
$total=$ret['total'];
$files=$uploads_scanner->get_files($folder);
$upload_folder = wp_upload_dir();
$root_path =$upload_folder['basedir'];
$start=0;
$count=0;
$limit=get_option('wpvivid_uc_files_limit',100);
$unused_files=array();
foreach ($files as $file)
{
if($count>$limit)
{
$uploads_scanner->update_unused_uploads_task($unused_files,$folder,0,$start,'running',0,$size);
$result['result']='success';
$result['status']='running';
$result['continue']=1;
$task=get_option('unused_uploads_task',array());
$result['task']=$task;
$result[$folder]=$unused_files;
$result['log']='scanning folder '.$folder.PHP_EOL.'scanned files:'.$start.PHP_EOL;
$ret=$uploads_scanner->get_unused_uploads_progress();
$result['total_folders']=$ret['total_folders'];
$result['scanned_folders']=$ret['scanned_folders'];
$result['percent']=$ret['percent'];
$result['descript']='Scanning upload folder:'.$folder.'<br>'.$start.' files have been scanned in '.$total.' files';
$result['progress_html']='
<div class="action-progress-bar">
<div class="action-progress-bar-percent" style="height:24px;width:' . $result['percent'] . '%"></div>
</div>
<div style="float:left;">
<div class="backup-basic-info">
<span class="wpvivid-element-space-right">' . __('Total Folders:', 'wpvivid-backuprestore') . '</span>
<span>' . $result['total_folders'] . '</span>
</div>
<div class="backup-basic-info">
<span class="wpvivid-element-space-right">' . __('Scanned:', 'wpvivid-backuprestore') . '</span>
<span>' . $result['scanned_folders'] . '</span>
</div>
</div>
<div style="clear:both;"></div>
<div style="margin-left:10px; float: left; width:100%;">
<p>' . $result['descript'] . '</p>
</div>
<div style="clear: both;"></div>
<div>
<div class="backup-log-btn">
<input class="button-primary" id="wpvivid_uc_cancel" type="submit" value="' . esc_attr('Cancel', 'wpvivid-backuprestore') . '" />
</div>
</div>
<div style="clear: both;"></div>';
echo wp_json_encode($result);
die();
}
if($start>=$offset)
{
if(!$uploads_scanner->is_uploads_files_exist($file))
{
$unused_files[]=$file;
$size+=filesize($root_path.DIRECTORY_SEPARATOR . $file);
}
$count++;
}
$start++;
}
$uploads_scanner->update_unused_uploads_task($unused_files,$folder,1,0,'running',0,$size);
$result['result']='success';
$result['status']='running';
$result['continue']=1;
$result[$folder]=$unused_files;
$result['log']='scanning folder '.$folder.PHP_EOL.'scanned files:'.$start.PHP_EOL;
$ret=$uploads_scanner->get_unused_uploads_progress();
$result['total_folders']=$ret['total_folders'];
$result['scanned_folders']=$ret['scanned_folders'];
$result['percent']=$ret['percent'];
$upload_folder = wp_upload_dir();
$result['descript']='Scanning upload folder:'.$folder.'<br>'.$start.' files have been scanned in '.$total.' files';
$result['progress_html']='
<div class="action-progress-bar">
<div class="action-progress-bar-percent" style="height:24px;width:' . $result['percent'] . '%"></div>
</div>
<div style="float:left;">
<div class="backup-basic-info">
<span class="wpvivid-element-space-right">' . __('Total Folders:', 'wpvivid-backuprestore') . '</span>
<span>' . $result['total_folders'] . '</span>
</div>
<div class="backup-basic-info">
<span class="wpvivid-element-space-right">' . __('Scanned:', 'wpvivid-backuprestore') . '</span>
<span>' . $result['scanned_folders'] . '</span>
</div>
</div>
<div style="clear:both;"></div>
<div style="margin-left:10px; float: left; width:100%;">
<p>' . $result['descript'] . '</p>
</div>
<div style="clear: both;"></div>
<div>
<div class="backup-log-btn">
<input class="button-primary" id="wpvivid_uc_cancel" type="submit" value="' . esc_attr('Cancel', 'wpvivid-backuprestore') . '" />
</div>
</div>
<div style="clear: both;"></div>';
}
echo wp_json_encode($result);
die();
}
public function scan_post_types($post_types)
{
$default_post_types=array();
$default_post_types[]='attachment';
$default_post_types[]='revision';
$default_post_types[]='auto-draft';
$default_post_types[]='nav_menu_item';
$default_post_types[]='shop_order';
$default_post_types[]='shop_order_refund';
$default_post_types[]='oembed_cache';
$post_types=get_option('wpvivid_uc_post_types',$default_post_types);
return $post_types;
}
public function scan_exclude_files_regex($regex)
{
$files=get_option('wpvivid_uc_exclude_files_regex','');
if(empty($files))
{
return $regex;
}
$files=explode("\n", $files);
foreach ($files as $item)
{
if(!empty($item))
{
$item=rtrim($item, '/');
$regex[]='#'.preg_quote($this -> transfer_path($item), '/').'#';
}
}
/*foreach ($files as $file)
{
$regex[]='#'.$file.'$#';
}*/
$regex[]='#webp$#';
return $regex;
}
public function scan_include_files_regex($regex)
{
$default_file_types=array();
$default_file_types[]='png';
$default_file_types[]='jpg';
$default_file_types[]='jpeg';
$scan_file_types=get_option('wpvivid_uc_scan_file_types',$default_file_types);
$regex=array();
foreach ($scan_file_types as $scan_file_type)
{
$regex[]='#.*\.'.$scan_file_type.'#';
}
return $regex;
}
public function add_exclude_files()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$json = $_POST['selected'];
$json = stripslashes($json);
$json = json_decode($json, true);
$selected_list=$json['selected'];
$sanitize_list=array();
foreach ($selected_list as $item)
{
$sanitize_list[]=intval($item);
}
$scanner=new WPvivid_Uploads_Scanner();
$files=$scanner->get_selected_files_list($sanitize_list);
$list=new WPvivid_Unused_Upload_Files_List();
if($files===false||empty($files))
{
}
else
{
$options=get_option('wpvivid_uc_exclude_files_regex',array());
$options=array_merge($files,$options);
update_option('wpvivid_uc_exclude_files_regex',$options,'no');
$scanner->delete_selected_files_list($sanitize_list);
}
$search='';
if(isset($_POST['search']))
{
$search=$_POST['search'];
}
$folder='';
if(isset($_POST['folder']))
{
$folder=$_POST['folder'];
}
$result=$scanner->get_scan_result($search,$folder);
$list->set_list($result);
$list->prepare_items();
ob_start();
$list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
echo wp_json_encode($ret);
die();
}
public function get_result_list()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$search='';
if(isset($_POST['search']))
{
$search=$_POST['search'];
}
$folder='';
if(isset($_POST['folder']))
{
$folder=$_POST['folder'];
}
$list=new WPvivid_Unused_Upload_Files_List();
$scanner=new WPvivid_Uploads_Scanner();
$result=$scanner->get_scan_result($search,$folder);
if(isset($_POST['page']))
{
$list->set_list($result,$_POST['page']);
}
else
{
$list->set_list($result);
}
$list->prepare_items();
ob_start();
$list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
if(empty($result))
{
$ret['empty']=1;
}
else
{
$ret['empty']=0;
}
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function isolate_selected_image()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$json = $_POST['selected'];
$json = stripslashes($json);
$json = json_decode($json, true);
$selected_list=$json['selected'];
$sanitize_list=array();
foreach ($selected_list as $item)
{
$sanitize_list[]=intval($item);
}
$scanner=new WPvivid_Uploads_Scanner();
$files=$scanner->get_selected_files_list($sanitize_list);
if($files===false||empty($files))
{
}
else
{
$iso=new WPvivid_Isolate_Files();
$result=$iso->isolate_files($files);
if($result['result']=='success')
{
$scanner->delete_selected_files_list($selected_list);
}
else
{
echo wp_json_encode($result);
die();
}
}
$search='';
if(isset($_POST['search']))
{
$search=$_POST['search'];
}
$folder='';
if(isset($_POST['folder']))
{
$folder=$_POST['folder'];
}
$list=new WPvivid_Unused_Upload_Files_List();
$scanner=new WPvivid_Uploads_Scanner();
$result=$scanner->get_scan_result($search,$folder);
$list->set_list($result);
$list->prepare_items();
ob_start();
$list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
$list=new WPvivid_Isolate_Files_List();
$iso=new WPvivid_Isolate_Files();
$result=$iso->get_isolate_files($search,'');
if(isset($_POST['page']))
{
$list->set_list($result,$_POST['page']);
}
else
{
$list->set_list($result);
}
$list->prepare_items();
ob_start();
$list->display();
$iso = ob_get_clean();
$ret['iso']=$iso;
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function start_isolate_all_image()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$search='';
if(isset($_POST['search']))
{
$search=$_POST['search'];
}
$folder='';
if(isset($_POST['folder']))
{
$folder=$_POST['folder'];
}
$iso=new WPvivid_Isolate_Files();
$scanner=new WPvivid_Uploads_Scanner();
$offset=0;
$count=100;
$iso->init_isolate_task();
$files=$scanner->get_all_files_list($search,$folder,$offset,$count);
if($files===false||empty($files))
{
$iso->update_isolate_task(0,'finished',100);
$result['result']='success';
$result['status']='finished';
$result['continue']=0;
echo wp_json_encode($result);
die();
}
else
{
$offset+=$count;
$result=$iso->isolate_files($files);
$scanner->delete_all_files_list($search,$folder,$count);
if($result['result']=='success')
{
$iso->update_isolate_task($offset);
}
else
{
echo wp_json_encode($result);
die();
}
}
$ret['result']='success';
$ret['status']='running';
$ret['continue']=1;
echo wp_json_encode($ret);
die();
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function isolate_all_image()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$search='';
if(isset($_POST['search']))
{
$search=$_POST['search'];
}
$folder='';
if(isset($_POST['folder']))
{
$folder=$_POST['folder'];
}
$iso=new WPvivid_Isolate_Files();
$scanner=new WPvivid_Uploads_Scanner();
$offset=$iso->get_isolate_task_offset();
if($offset===false)
{
$result['result']='success';
$result['status']='finished';
$result['continue']=0;
echo wp_json_encode($result);
die();
}
$start=0;
$count=100;
$files=$scanner->get_all_files_list($search,$folder,$start,$count);
if($files===false||empty($files))
{
$iso->update_isolate_task(0,'finished',100);
$result['result']='success';
$result['status']='finished';
$result['continue']=0;
echo wp_json_encode($result);
die();
}
else
{
$offset+=$count;
$result=$iso->isolate_files($files);
$scanner->delete_all_files_list($search,$folder,$count);
if($result['result']=='success')
{
$iso->update_isolate_task($offset);
}
else
{
echo wp_json_encode($result);
die();
}
}
$ret['result']='success';
$ret['status']='running';
$ret['continue']=1;
echo wp_json_encode($ret);
die();
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function get_iso_list()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$search='';
if(isset($_POST['search']))
{
$search=$_POST['search'];
}
$folder='';
if(isset($_POST['folder']))
{
$folder=$_POST['folder'];
}
$folder = str_replace('\\\\', '\\', $folder);
$list=new WPvivid_Isolate_Files_List();
$iso=new WPvivid_Isolate_Files();
$result=$iso->get_isolate_files($search,$folder);
if(isset($_POST['page']))
{
$list->set_list($result,$_POST['page']);
}
else
{
$list->set_list($result);
}
$list->prepare_items();
ob_start();
$list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
if(empty($result))
{
$ret['empty']=1;
}
else
{
$ret['empty']=0;
}
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function delete_selected_image()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$json = $_POST['selected'];
$json = stripslashes($json);
$json = json_decode($json, true);
$files=array_map( 'sanitize_text_field', $json['selected']);
$iso=new WPvivid_Isolate_Files();
$iso->delete_files($files);
$search='';
if(isset($_POST['search']))
{
$search=sanitize_text_field($_POST['search']);
}
$folder='';
if(isset($_POST['folder']))
{
$folder=sanitize_text_field($_POST['folder']);
}
$folder = str_replace('\\\\', '\\', $folder);
$list=new WPvivid_Isolate_Files_List();
$iso=new WPvivid_Isolate_Files();
$result=$iso->get_isolate_files($search,$folder);
if(isset($_POST['page']))
{
$list->set_list($result,$_POST['page']);
}
else
{
$list->set_list($result);
}
$list->prepare_items();
ob_start();
$list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function delete_all_image()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$search='';
if(isset($_POST['search']))
{
$search=$_POST['search'];
}
$folder='';
if(isset($_POST['folder']))
{
$folder=$_POST['folder'];
}
$iso=new WPvivid_Isolate_Files();
$count=1000;
$files=$iso->get_isolate_files($search,$folder,$count);
if($files===false||empty($files))
{
$result['result']='success';
$result['status']='finished';
$result['continue']=0;
echo wp_json_encode($result);
die();
}
else
{
$iso->delete_files_ex($files);
}
$ret['result']='success';
$ret['status']='running';
$ret['continue']=1;
echo wp_json_encode($ret);
die();
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
//restore_selected_image
public function restore_selected_image()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$json = $_POST['selected'];
$json = stripslashes($json);
$json = json_decode($json, true);
$files=$json['selected'];
$iso=new WPvivid_Isolate_Files();
$iso->restore_files($files);
$search='';
if(isset($_POST['search']))
{
$search=$_POST['search'];
}
$folder='';
if(isset($_POST['folder']))
{
$folder=$_POST['folder'];
}
$folder = str_replace('\\\\', '\\', $folder);
$list=new WPvivid_Isolate_Files_List();
$iso=new WPvivid_Isolate_Files();
$result=$iso->get_isolate_files($search,$folder);
if(isset($_POST['page']))
{
$list->set_list($result,$_POST['page']);
}
else
{
$list->set_list($result);
}
$list->prepare_items();
ob_start();
$list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
public function restore_all_image()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$search='';
if(isset($_POST['search']))
{
$search=$_POST['search'];
}
$folder='';
if(isset($_POST['folder']))
{
$folder=$_POST['folder'];
}
$iso=new WPvivid_Isolate_Files();
$count=100;
$files=$iso->get_isolate_files($search,$folder,$count);
if($files===false||empty($files))
{
$result['result']='success';
$result['status']='finished';
$result['continue']=0;
echo wp_json_encode($result);
die();
}
else
{
$iso->restore_files_ex($files);
}
$ret['result']='success';
$ret['status']='running';
$ret['continue']=1;
echo wp_json_encode($ret);
die();
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
}
die();
}
} includes/upload-cleaner/class-wpvivid-isolate-files.php 0000644 00000026632 15132770567 0017335 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Isolate_Files
{
public function __construct()
{
}
public function check_folder()
{
if(!is_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR))
{
@mkdir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR,0777,true);
}
}
public function isolate_files($files)
{
$upload_dir=wp_upload_dir();
$root_path=$upload_dir['basedir'].DIRECTORY_SEPARATOR;
if(!is_dir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR))
{
@mkdir(WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR,0777,true);
}
$iso_dir=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR.DIRECTORY_SEPARATOR;
foreach ($files as $file)
{
$from=$root_path.$file;
$to=$iso_dir.$file;
if(file_exists($from))
{
if (!is_dir(dirname($to)))
{
mkdir(dirname($to), 0777, true);
}
@rename($from,$to);
}
}
$ret['result']='success';
return $ret;
}
public function init_isolate_task()
{
$task['start_time']=time();
$task['running_time']=time();
$task['status']='running';
$task['progress']=0;
$task['offset']=0;
update_option('init_isolate_task',$task,'no');
}
public function get_isolate_task_offset()
{
$task=get_option('scan_unused_files_task',array());
if(empty($task))
{
return false;
}
if($task['status']=='finished')
{
return false;
}
return $task['offset'];
}
public function update_isolate_task($offset,$status='running',$progress=0)
{
$task=get_option('scan_unused_files_task',array());
$task['running_time']=time();
$task['status']=$status;
$task['progress']=$progress;
$task['offset']=$offset;
update_option('scan_unused_files_task',$task,'no');
}
public function get_isolate_folder()
{
$root=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR;
$ret=$this->get_folder_list($root);
return $ret;
}
public function get_isolate_files($search='',$folder_ex='',$count=0)
{
$root=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR;
$ret=$this->get_folder_list($root,$search);
if(empty($folder_ex))
{
$result=$ret['files'];
foreach ($ret['folders'] as $folder)
{
$files=array();
$this->scan_list_uploaded_files($files,$root.DIRECTORY_SEPARATOR.$folder,$root,$folder,$search);
$result=array_merge($result,$files);
}
}
else if($folder_ex=='.')
{
$result=$ret['files'];
if($count>0&&sizeof($result)>$count)
{
$result=array_slice($result, 0, $count);
}
return $result;
}
else
{
$files=array();
$this->scan_list_uploaded_files($files,$root.DIRECTORY_SEPARATOR.$folder_ex,$root,$folder_ex,$search);
$result=$files;
}
if($count>0&&sizeof($result)>$count)
{
$result=array_slice($result, 0, $count);
}
return $result;
}
private function get_folder_list($root_path,$search='')
{
$result['folders']=array();
$result['folders'][]='root';
$result['files']=array();
if(!file_exists($root_path)){
@mkdir($root_path, 0755, true);
}
$handler = opendir($root_path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if (is_dir($root_path . DIRECTORY_SEPARATOR . $filename))
{
if(preg_match('#^\d{4}$#',$filename))
{
$result['folders']=array_merge( $result['folders'],$this->get_sub_folder($root_path . DIRECTORY_SEPARATOR . $filename,$filename));
}
else
{
$ret=scandir($root_path . DIRECTORY_SEPARATOR . $filename);
if($ret!==false&&count($ret)!=2)
{
$result['folders'][]=$filename;
}
}
} else {
if($filename=='.htaccess'||$filename=='index.php')
{
continue;
}
if(empty($search))
{
$file['path']=$filename;
$file['folder']='.';
$result['files'][] = $file;
}
else if(preg_match('#'.$search.'#',$filename))
{
$file['path']=$filename;
$file['folder']='.';
$result['files'][] = $file;
}
}
}
}
if($handler)
@closedir($handler);
}
return $result;
}
private function get_sub_folder($path,$root)
{
$folders=array();
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if (is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
$ret=scandir($path . DIRECTORY_SEPARATOR . $filename);
if($ret!==false&&count($ret)!=2)
{
$folders[]=$root.DIRECTORY_SEPARATOR.$filename;
}
}
}
}
if($handler)
@closedir($handler);
}
return $folders;
}
private function scan_list_uploaded_files( &$files,$path,$root,$folder,$search='')
{
$count = 0;
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
$count++;
if (is_dir($path . DIRECTORY_SEPARATOR . $filename))
{
$this->scan_list_uploaded_files($files, $path . DIRECTORY_SEPARATOR . $filename,$root,$folder,$search);
} else {
if(empty($search))
{
$file['path']=str_replace($root . DIRECTORY_SEPARATOR,'',$path . DIRECTORY_SEPARATOR . $filename);
$file['folder']=$folder;
$files[] = $file;
}
else if(preg_match('#'.$search.'#',$filename))
{
$file['path']=str_replace($root . DIRECTORY_SEPARATOR,'',$path . DIRECTORY_SEPARATOR . $filename);
$file['folder']=$folder;
$files[] = $file;
}
}
}
}
if($handler)
@closedir($handler);
}
}
return $files;
}
public function delete_files($files)
{
$root=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR;
$delete_media_when_delete_file=get_option('wpvivid_uc_delete_media_when_delete_file',true);
foreach ($files as $file)
{
@wp_delete_file($root.DIRECTORY_SEPARATOR.$file);
if($delete_media_when_delete_file)
{
$attachment_id=$this->find_media_id_from_file($file);
if($attachment_id)
{
wp_delete_attachment( $attachment_id, true );
}
}
}
}
public function delete_files_ex($files)
{
$root=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR;
$delete_media_when_delete_file=get_option('wpvivid_uc_delete_media_when_delete_file',true);
foreach ($files as $file)
{
@wp_delete_file($root.DIRECTORY_SEPARATOR.$file['path']);
if($delete_media_when_delete_file)
{
$attachment_id=$this->find_media_id_from_file($file['path']);
if($attachment_id)
{
wp_delete_attachment( $attachment_id, true );
}
}
}
}
public function find_media_id_from_file( $file )
{
global $wpdb;
$file=basename($file);
$sql = "SELECT post_id
FROM {$wpdb->postmeta}
WHERE meta_key = '_wp_attachment_metadata'
AND meta_value LIKE '%$file%'";
$ret = $wpdb->get_var( $sql );
if(!$ret)
{
$sql = $wpdb->prepare( "SELECT post_id
FROM {$wpdb->postmeta}
WHERE meta_key = '_wp_attached_file'
AND meta_value = %s", $file
);
$ret = $wpdb->get_var( $sql );
}
return $ret;
}
public function restore_files($files)
{
$upload_dir=wp_upload_dir();
$root_path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR.DIRECTORY_SEPARATOR;
$upload_path=$upload_dir['basedir'].DIRECTORY_SEPARATOR;
foreach ($files as $file)
{
$from=$root_path.$file;
$to=$upload_path.$file;
if(file_exists($from))
{
if (!is_dir(dirname($to)))
{
mkdir(dirname($to), 0777, true);
}
@rename($from,$to);
}
}
$ret['result']='success';
return $ret;
}
public function restore_files_ex($files)
{
$upload_dir=wp_upload_dir();
$root_path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPVIVID_UPLOADS_ISO_DIR.DIRECTORY_SEPARATOR;
$upload_path=$upload_dir['basedir'].DIRECTORY_SEPARATOR;
foreach ($files as $file)
{
$from=$root_path.$file['path'];
$to=$upload_path.$file['path'];
if(file_exists($from))
{
if (!is_dir(dirname($to)))
{
mkdir(dirname($to), 0777, true);
}
@rename($from,$to);
}
}
$ret['result']='success';
return $ret;
}
} includes/snapshot/class-wpvivid-tab-page-container-ex.php 0000644 00000023665 15132770567 0017616 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
if(!class_exists('WPvivid_Tab_Page_Container'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-tab-page-container.php';
}
class WPvivid_Tab_Page_Container_Ex extends WPvivid_Tab_Page_Container
{
public $is_transparency=0;
public function add_tab($title,$slug,$callback,$args=array())
{
$new_tab['title']=$title;
$new_tab['slug']=$slug;
$new_tab['page']=$callback;
foreach ($args as $key=>$arg)
{
$new_tab[$key]=$arg;
if($key === 'is_parent_tab') {
$this->is_parent_tab = $arg;
}
if($key === 'transparency'){
$this->is_transparency = $arg;
}
}
$this->tabs[]=$new_tab;
}
public function display()
{
$class = '';
if($this->is_transparency){
$class .= ' wpvivid-intab-addon';
}
?>
<div class="wpvivid-one-coloum" id="<?php echo esc_attr($this->container_id); ?>">
<h2 class="nav-tab-wrapper wpvivid-nav-tab-wrapper">
<?php
$this->display_tabs();
?>
</h2>
</div>
<?php
if($this->is_parent_tab){
?>
<div style="margin: 10px 0 0 2px;">
<div id="poststuff" style="padding-top: 0;">
<div id="post-body" class="metabox-holder columns-2">
<div id="post-body-content">
<div class="inside" style="margin-top:0;">
<div>
<?php
$this->display_page();
?>
</div>
</div>
</div>
<div id="postbox-container-1" class="postbox-container">
<div class="meta-box-sortables">
</div>
</div>
</div>
<br class="clear">
</div>
</div>
<?php
}
else{
?>
<?php
$this->display_page();
?>
<?php
}
?>
<script>
jQuery('#<?php echo esc_js($this->container_id)?>').on("click",".<?php echo esc_js($this->container_id)?>-tab",function()
{
jQuery('#<?php echo esc_js($this->container_id)?>').find( '.<?php echo esc_js($this->container_id)?>-tab' ).each(function()
{
jQuery(this).removeClass( "nav-tab-active wpvivid-nav-tab-active" );
});
jQuery('.<?php echo esc_js($this->container_id)?>-content').each(function()
{
jQuery(this).hide();
});
var id=jQuery(this).attr('id');
id= id.substr(12);
jQuery("#wpvivid_page_"+id).show();
jQuery(this).addClass( "nav-tab-active wpvivid-nav-tab-active" );
var top = jQuery(this).offset().top-jQuery(this).height();
jQuery('html, body').animate({scrollTop:top}, 'slow');
});
jQuery('#<?php echo esc_js($this->container_id)?>').on("click",".nav-tab-delete-img-addon",function(event)
{
event.stopPropagation();
var redirect=jQuery(this).attr('redirect');
jQuery(this).parent().hide();
jQuery('#<?php echo esc_js($this->container_id)?>').find( '.<?php echo esc_js($this->container_id)?>-tab' ).each(function()
{
jQuery(this).removeClass( "nav-tab-active wpvivid-nav-tab-active" );
});
jQuery('.<?php echo esc_js($this->container_id)?>-content').each(function()
{
jQuery(this).hide();
});
jQuery("#wpvivid_page_"+redirect).show();
jQuery("#wpvivid_tab_"+redirect).addClass( "nav-tab-active wpvivid-nav-tab-active" );
//jQuery(this).addClass( "nav-tab-active wpvivid-nav-tab-active" );
});
jQuery(document).ready(function($)
{
jQuery(document).on('<?php echo esc_js($this->container_id)?>-show', function(event,id,redirect)
{
jQuery('#<?php echo esc_js($this->container_id)?>').find( '.<?php echo esc_js($this->container_id)?>-tab' ).each(function()
{
jQuery(this).removeClass( "nav-tab-active wpvivid-nav-tab-active" );
});
jQuery('.<?php echo esc_js($this->container_id); ?>-content').each(function()
{
jQuery(this).hide();
});
jQuery("#wpvivid_page_"+id).show();
jQuery("#wpvivid_tab_"+id).show();
jQuery("#wpvivid_tab_"+id).find( '.nav-tab-delete-img-addon' ).each(function()
{
jQuery(this).attr('redirect',redirect);
});
jQuery("#wpvivid_tab_"+id).addClass( "nav-tab-active wpvivid-nav-tab-active" );
var top = jQuery("#wpvivid_tab_"+id).offset().top-jQuery("#wpvivid_tab_"+id).height();
jQuery('html, body').animate({scrollTop:top}, 'slow');
});
jQuery(document).on('<?php echo esc_js($this->container_id)?>-delete', function(event,id,redirect)
{
jQuery('#<?php echo esc_js($this->container_id)?>').find( '.<?php echo esc_js($this->container_id)?>-tab' ).each(function()
{
jQuery(this).removeClass( "nav-tab-active wpvivid-nav-tab-active" );
});
jQuery('#<?php echo esc_js($this->container_id)?>').find( '.<?php echo esc_js($this->container_id)?>-content' ).each(function()
{
jQuery(this).hide();
});
jQuery("#wpvivid_page_"+id).hide();
jQuery("#wpvivid_tab_"+id).hide();
jQuery("#wpvivid_page_"+redirect).show();
jQuery("#wpvivid_tab_"+redirect).addClass( "nav-tab-active wpvivid-nav-tab-active" );
});
});
</script>
<?php
}
public function display_tabs()
{
$first=true;
foreach ($this->tabs as $tab)
{
$class='nav-tab wpvivid-nav-tab '.$this->container_id.'-tab';
$span_class='';
$span_style='';
if($first)
{
$class.=' nav-tab-active wpvivid-nav-tab-active';
$first=false;
}
$style='cursor:pointer;';
if(isset($tab['hide']))
{
$style.=' display: none';
}
if(isset($tab['span_class']))
{
$span_class.=$tab['span_class'];
}
if(isset($tab['span_style']))
{
$span_style.=$tab['span_style'];
}
if(isset($tab['can_delete']))
{
$class.=' delete';
}
if(isset($tab['transparency']))
{
$class.=' wpvivid-transparency-tab';
}
echo '<a id="wpvivid_tab_'.esc_attr($tab['slug']).'" class="'.esc_attr($class).'" style="'.esc_attr($style).'">';
if(isset($tab['can_delete']))
{
echo '<span class="'.esc_attr($span_class).'" style="'.esc_attr($span_style).'"></span><span style="padding-right: 1em;">'.esc_attr($tab['title']).'</span>';
if(isset($tab['redirect']))
{
echo '<div class="nav-tab-delete-img-addon" redirect="'.esc_attr($tab['redirect']).'">
<span class="dashicons dashicons-no-alt wpvivid-dashicons-grey" style="width: 15px; height: 15px; font-size: 15px; padding-top: 0.4em;">
</div>';
}
else
{
echo '<div class="nav-tab-delete-img-addon">
<span class="dashicons dashicons-no-alt wpvivid-dashicons-grey" style="width: 15px; height: 15px; font-size: 15px; padding-top: 0.4em;">
</div>';
}
}
else
{
echo '<span class="'.esc_attr($span_class).'" style="'.esc_attr($span_style).'"></span><span>'.esc_attr($tab['title']).'</span>';
}
echo '</a>';
}
}
public function display_page()
{
$first=true;
foreach ($this->tabs as $tab)
{
//delete
/*$style='display: none;';
if($first)
{
if(isset($tab['hide']))
{
}
else
{
$style='';
$first=false;
}
}*/
if(isset($tab['div_style']))
{
$style = $tab['div_style'];
}
else{
$style='display: none;';
}
$class='wpvivid-one-coloum wpvivid-tabcontent ';
$class.=$this->container_id.'-content';
echo '<div id="wpvivid_page_'.esc_attr($tab['slug']).'" class="'.esc_attr($class).'" style="'.esc_attr($style).'">';
call_user_func($tab['page']);
echo '</div>';
}
}
} includes/snapshot/class-wpvivid-snapshots-list.php 0000644 00000031631 15132770567 0016527 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
if ( ! class_exists( 'WP_List_Table' ) )
{
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
if ( ! class_exists( 'WPvivid_Snapshots_List_Ex' ) )
{
class WPvivid_Snapshots_List_Ex extends WP_List_Table
{
public $page_num;
public $Snapshots_list;
public function __construct( $args = array() )
{
parent::__construct(
array(
'plural' => 'snapshots',
'screen' => 'snapshots'
)
);
}
protected function get_table_classes()
{
return array( 'widefat striped' );
}
public function get_columns()
{
$columns = array();
$columns['cb'] = __( 'cb', 'wpvivid-snapshot-database' );
$columns['wpvivid_time'] = __( 'Time', 'wpvivid-snapshot-database' );
$columns['wpvivid_type'] = __( 'Type', 'wpvivid-snapshot-database' );
$columns['wpvivid_prefix'] = __( 'Prefix', 'wpvivid-snapshot-database' );
$columns['wpvivid_comment'] = __( 'Comment', 'wpvivid-snapshot-database' );
$columns['wpvivid_actions'] = __( 'Actions', 'wpvivid-snapshot-database' );
return $columns;
}
public function column_cb( $data )
{
echo '<input type="checkbox"/>';
}
public function _column_wpvivid_time( $data )
{
$time = gmdate('M-d-Y H:i', $data['time']);
echo '<td>' . esc_html( $time ) . '</td>';
}
public function _column_wpvivid_type( $data )
{
echo '<td>' . esc_html( $data['type'] ) . '</td>';
}
public function _column_wpvivid_prefix( $data )
{
echo '<td>' . esc_html( $data['id'] ) . '</td>';
}
public function _column_wpvivid_comment( $data )
{
echo '<td>' . esc_html($data['comment'] ) . '</td>';
}
public function _column_wpvivid_actions( $data )
{
echo '<td>
<div style="cursor:pointer;float:left;">
<span class="dashicons dashicons-update wpvivid-dashicons-green wpvivid-snapshot-restore"></span>
<span class="wpvivid-snapshot-restore">Restore</span>
<span style="width:1rem;">|</span>
<span class="dashicons dashicons-trash wpvivid-dashicons-grey wpvivid-snapshot-delete"></span>
<span class="wpvivid-snapshot-delete">Delete</span>
</div>
</td>';
}
public function set_list($Snapshots_list,$page_num=1)
{
$this->Snapshots_list=$Snapshots_list;
$this->page_num=$page_num;
}
public function get_pagenum()
{
if($this->page_num=='first')
{
$this->page_num=1;
}
else if($this->page_num=='last')
{
$this->page_num=$this->_pagination_args['total_pages'];
}
$pagenum = $this->page_num ? $this->page_num : 0;
if ( isset( $this->_pagination_args['total_pages'] ) && $pagenum > $this->_pagination_args['total_pages'] )
{
$pagenum = $this->_pagination_args['total_pages'];
}
return max( 1, $pagenum );
}
public function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = array();
$this->_column_headers = array($columns, $hidden, $sortable);
$total_items =sizeof($this->Snapshots_list);
$this->set_pagination_args(
array(
'total_items' => $total_items,
'per_page' => 10,
)
);
}
public function has_items()
{
return !empty($this->Snapshots_list);
}
public function display_rows()
{
$this->_display_rows($this->Snapshots_list);
}
private function _display_rows($Snapshots_list)
{
$page=$this->get_pagenum();
$page_file_list=array();
$count=0;
while ( $count<$page )
{
$page_file_list = array_splice( $Snapshots_list, 0, 10);
$count++;
}
foreach ( $page_file_list as $data)
{
$this->single_row($data);
}
}
public function single_row($data)
{
?>
<tr class='wpvivid-snapshot-row' slug="<?php echo esc_attr($data['id']);?>">
<?php $this->single_row_columns( $data ); ?>
</tr>
<?php
}
protected function pagination( $which )
{
if ( empty( $this->_pagination_args ) )
{
return;
}
$total_items = $this->_pagination_args['total_items'];
$total_pages = $this->_pagination_args['total_pages'];
$infinite_scroll = false;
if ( isset( $this->_pagination_args['infinite_scroll'] ) )
{
$infinite_scroll = $this->_pagination_args['infinite_scroll'];
}
if ( 'top' === $which && $total_pages > 1 )
{
$this->screen->render_screen_reader_content( 'heading_pagination' );
}
$output = '<span class="displaying-num">' . sprintf( _n( '%s item', '%s items', $total_items ), number_format_i18n( $total_items ) ) . '</span>';
$current = $this->get_pagenum();
$page_links = array();
$total_pages_before = '<span class="paging-input">';
$total_pages_after = '</span></span>';
$disable_first = $disable_last = $disable_prev = $disable_next = false;
if ( $current == 1 ) {
$disable_first = true;
$disable_prev = true;
}
if ( $current == 2 ) {
$disable_first = true;
}
if ( $current == $total_pages ) {
$disable_last = true;
$disable_next = true;
}
if ( $current == $total_pages - 1 ) {
$disable_last = true;
}
if ( $disable_first ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">«</span>';
} else {
$page_links[] = sprintf(
"<div class='first-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'First page' ),
'«'
);
}
if ( $disable_prev ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">‹</span>';
} else {
$page_links[] = sprintf(
"<div class='prev-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Previous page' ),
'‹'
);
}
if ( 'bottom' === $which ) {
$html_current_page = $current;
$total_pages_before = '<span class="screen-reader-text">' . __( 'Current Page' ) . '</span><span id="table-paging" class="paging-input"><span class="tablenav-paging-text">';
} else {
$html_current_page = sprintf(
"%s<input class='current-page' id='current-page-selector-filelist' type='text' name='paged' value='%s' size='%d' aria-describedby='table-paging' /><span class='tablenav-paging-text'>",
'<label for="current-page-selector-filelist" class="screen-reader-text">' . __( 'Current Page' ) . '</label>',
$current,
strlen( $total_pages )
);
}
$html_total_pages = sprintf( "<span class='total-pages'>%s</span>", number_format_i18n( $total_pages ) );
$page_links[] = $total_pages_before . sprintf( _x( '%1$s of %2$s', 'paging' ), $html_current_page, $html_total_pages ) . $total_pages_after;
if ( $disable_next ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">›</span>';
} else {
$page_links[] = sprintf(
"<div class='next-page button' value='%s'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
$current,
__( 'Next page' ),
'›'
);
}
if ( $disable_last ) {
$page_links[] = '<span class="tablenav-pages-navspan button disabled" aria-hidden="true">»</span>';
} else {
$page_links[] = sprintf(
"<div class='last-page button'><span class='screen-reader-text'>%s</span><span aria-hidden='true'>%s</span></div>",
__( 'Last page' ),
'»'
);
}
$pagination_links_class = 'pagination-links';
if ( ! empty( $infinite_scroll ) ) {
$pagination_links_class .= ' hide-if-js';
}
$output .= "\n<span class='$pagination_links_class'>" . join( "\n", $page_links ) . '</span>';
if ( $total_pages ) {
$page_class = $total_pages < 2 ? ' one-page' : '';
} else {
$page_class = ' no-pages';
}
$this->_pagination = "<div class='tablenav-pages{$page_class}'>$output</div>";
echo $this->_pagination;
}
protected function display_tablenav( $which ) {
$css_type = '';
if ( 'top' === $which ) {
wp_nonce_field( 'bulk-' . $this->_args['plural'] );
$css_type = 'margin: 0 0 10px 0';
}
else if( 'bottom' === $which ) {
$css_type = 'margin: 10px 0 0 0';
}
$total_pages = $this->_pagination_args['total_pages'];
if ( $total_pages >1 && 'top' === $which)
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<input type="submit" id="wpvivid_delete_snapshots_action" class="button action" value="Delete the selected snapshots">
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
else if($total_pages >1)
{
?>
<div class="tablenav <?php echo esc_attr( $which ); ?>" style="<?php echo esc_attr($css_type); ?>">
<?php
$this->extra_tablenav( $which );
$this->pagination( $which );
?>
<br class="clear" />
</div>
<?php
}
else if($total_pages <=1 && 'top' === $which)
{
?>
<input type="submit" id="wpvivid_delete_snapshots_action" class="button action" value="Delete the selected snapshots">
<p></p>
<?php
}
}
public function display()
{
$singular = $this->_args['singular'];
$this->display_tablenav( 'top' );
$this->screen->render_screen_reader_content( 'heading_list' );
?>
<table class="wp-list-table <?php echo esc_attr(implode( ' ', $this->get_table_classes() )); ?>">
<thead>
<tr>
<?php $this->print_column_headers(); ?>
</tr>
</thead>
<tbody id="the-list"
<?php
if ( $singular ) {
echo esc_attr(" data-wp-lists='list:$singular'");
}
?>
>
<?php $this->display_rows_or_placeholder(); ?>
</tbody>
</table>
<?php
$this->display_tablenav( 'bottom' );
}
}
}
includes/snapshot/class-wpvivid-snapshot-options.php 0000644 00000004504 15132770567 0017063 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Snapshot_Option_Ex
{
public $options_table;
public function __construct()
{
global $wpdb;
$this->options_table = $wpdb->base_prefix."wpvivid_options";
//$this->check_tables();
}
public function check_tables()
{
global $wpdb;
if($wpdb->get_var("SHOW TABLES LIKE '$this->options_table'") != $this->options_table)
{
$sql = "CREATE TABLE IF NOT EXISTS $this->options_table (
`option_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`option_name` varchar(191) NOT NULL DEFAULT '',
`option_value` longtext NOT NULL,
PRIMARY KEY (`option_id`),
UNIQUE KEY `option_name` (`option_name`)
);";
$wpdb->query($sql);
}
}
public function get_option($option_name)
{
global $wpdb;
if($wpdb->get_var("SHOW TABLES LIKE '$this->options_table'") != $this->options_table)
{
return false;
}
else
{
global $wpdb;
$query =$wpdb->prepare('select option_value from '.$this->options_table .' where option_name = %s', $option_name);
$result =$wpdb->get_var($query);
if(empty($result))
{
return false;
}
else
{
return maybe_unserialize($result);
}
}
}
public function update_option($option_name,$value)
{
global $wpdb;
if($this->is_exists_option($option_name))
{
$option_value = maybe_serialize($value);
return $wpdb->update($this->options_table, compact('option_name', 'option_value'), compact('option_name'));
}
else
{
$option_value = maybe_serialize($value);
return $wpdb->insert($this->options_table, compact('option_name', 'option_value'));
}
}
public function is_exists_option($option_name)
{
global $wpdb;
$query = $wpdb->prepare('select option_value from '.$this->options_table.' where option_name = %s', $option_name);
$result =$wpdb->get_row($query);
return !empty($result);
}
} includes/snapshot/class-wpvivid-snapshot-function.php 0000644 00000055251 15132770567 0017222 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Snapshot_Function_Ex
{
public $options;
public function __construct()
{
$this->options=new WPvivid_Snapshot_Option_Ex();
}
public function check_manual_snapshot()
{
$snapshots=$this->options->get_option('wpvivid_snapshot');
$manual_snapshots=array();
if($snapshots !== false)
{
foreach ($snapshots as $snapshot)
{
if($snapshot['type']=='manual')
{
$manual_snapshots[]=$snapshot;
}
}
}
$setting=$this->options->get_option('wpvivid_snapshot_setting');
$count=isset($setting['snapshot_retention'])?$setting['snapshot_retention']:6;
if(empty($count))
{
$count=6;
}
usort($manual_snapshots, function ($a, $b)
{
if ($a['time'] == $b['time'])
return 0;
if ($a['time'] > $b['time'])
return 1;
else
return -1;
});
while(count($manual_snapshots)>=$count)
{
$manual_snapshot=array_shift($manual_snapshots);
$this->remove_snapshot($manual_snapshot['id']);
}
}
public function create_merge_snapshot($comment='')
{
global $wpdb;
$snapshot_id = 'wp'.$this->create_snapshot_uid();
$tables = $wpdb->get_results('SHOW TABLE STATUS');
$exclude_tables[]=$wpdb->prefix.'wpvivid_log';
$exclude_tables[]=$wpdb->base_prefix."wpvivid_increment_big_ids";
$exclude_tables[]=$wpdb->prefix.'wpvivid_merge_db';
$exclude_tables[]=$wpdb->prefix.'wpvivid_options';
$exclude_tables[]=$wpdb->base_prefix."wpvivid_record_task";
$exclude_tables=apply_filters('wpvivid_create_snapshot_exclude_tables',$exclude_tables);
$snapshot_tables=array();
foreach ($tables as $table)
{
if (0 !== stripos($table->Name, $wpdb->prefix))
{
continue;
}
if (empty($table->Engine))
{
continue;
}
if(in_array($table->Name,$exclude_tables))
{
continue;
}
$snapshot_table['Name']=$table->Name;
$snapshot_table['finished']=0;
$snapshot_tables[$table->Name]=$snapshot_table;
}
if (!empty($snapshot_tables))
{
foreach ($snapshot_tables as $table_name=>$snapshot_table)
{
$new_table=$this->str_replace_first($wpdb->prefix,$snapshot_id,$table_name);
$wpdb->query("OPTIMIZE TABLE {$table_name}");
$wpdb->query("CREATE TABLE `{$new_table}` LIKE `{$table_name}`");
$wpdb->query("INSERT `{$new_table}` SELECT * FROM `{$table_name}`");
}
}
else
{
$ret['result']='failed';
$ret['error']='create snapshot failed';
return $ret;
}
$this->update_snapshot($snapshot_id,'merge',$comment);
$ret['result']='success';
$ret['finished']=1;
$ret['snapshot_id']=$snapshot_id;
return $ret;
}
public function check_dev_snapshot()
{
$snapshots=$this->options->get_option('wpvivid_snapshot');
$dev_snapshots=array();
foreach ($snapshots as $snapshot)
{
if($snapshot['type']=='dev')
{
$dev_snapshots[]=$snapshot;
}
}
$setting=$this->options->get_option('wpvivid_merge_setting');
$count=isset($setting['snapshot_retention'])?$setting['snapshot_retention']:6;
if(empty($count))
{
$count=6;
}
while(count($dev_snapshots)>=$count)
{
usort($dev_snapshots, function ($a, $b)
{
if ($a['time'] == $b['time'])
return 0;
if ($a['time'] > $b['time'])
return 1;
else
return -1;
});
$dev_snapshot=array_shift($dev_snapshots);
$this->remove_snapshot($dev_snapshot['id']);
}
}
public function create_dev_snapshot($task_data)
{
global $wpdb;
$snapshot_id = 'wp'.$this->create_snapshot_uid();
$tables = $wpdb->get_results('SHOW TABLE STATUS');
//$exclude_tables[]=$wpdb->prefix.'wpvivid_log';
//$exclude_tables[]=$wpdb->prefix.'wpvivid_merge_db';
$exclude_tables[]=$wpdb->prefix.'wpvivid_options';
$exclude_tables[]=$wpdb->base_prefix."wpvivid_record_task";
$exclude_tables=apply_filters('wpvivid_create_snapshot_exclude_tables',$exclude_tables);
$start_time=time();
$snapshot_tables=array();
foreach ($tables as $table)
{
if (0 !== stripos($table->Name, $wpdb->prefix))
{
continue;
}
if (empty($table->Engine))
{
continue;
}
if(in_array($table->Name,$exclude_tables))
{
continue;
}
$snapshot_table['Name']=$table->Name;
$snapshot_table['finished']=0;
$snapshot_tables[$table->Name]=$snapshot_table;
}
$this->init_task($snapshot_id,$snapshot_tables,'dev',$task_data['comment']);
if (!empty($snapshot_tables))
{
foreach ($snapshot_tables as $table_name=>$snapshot_table)
{
if($snapshot_table['finished']==1)
continue;
$new_table=$this->str_replace_first($wpdb->prefix,$snapshot_id,$table_name);
$wpdb->query("OPTIMIZE TABLE {$table_name}");
$wpdb->query("CREATE TABLE `{$new_table}` LIKE `{$table_name}`");
$wpdb->query("INSERT `{$new_table}` SELECT * FROM `{$table_name}`");
$snapshot_tables[$table_name]['finished']=1;
$this->update_task($snapshot_id,$snapshot_tables);
if($this->is_time_limit_exceeded($start_time))
{
$ret['result']='success';
$ret['finished']=0;
$ret['snapshot_id']=$snapshot_id;
$ret['snapshot_tables']=$snapshot_tables;
return $ret;
}
}
}
else
{
$ret['result']='failed';
$ret['error']='create snapshot failed';
return $ret;
}
$this->update_snapshot($snapshot_id,'dev',$task_data['comment']);
$ret['result']='success';
$ret['finished']=1;
$ret['snapshot_id']=$snapshot_id;
return $ret;
}
public function create_snapshot($type='',$comment='')
{
global $wpdb;
$snapshot_id=$this->create_snapshot_uid();
$snapshot_id = 'wp'.$snapshot_id;
$tables = $wpdb->get_results('SHOW TABLE STATUS');
$exclude_tables[]=$wpdb->prefix.'wpvivid_log';
$exclude_tables[]=$wpdb->base_prefix."wpvivid_increment_big_ids";
$exclude_tables[]=$wpdb->prefix.'wpvivid_merge_db';
$exclude_tables[]=$wpdb->prefix.'wpvivid_options';
$exclude_tables[]=$wpdb->base_prefix."wpvivid_record_task";
$exclude_tables=apply_filters('wpvivid_create_snapshot_exclude_tables',$exclude_tables);
$start_time=time();
$snapshot_tables=array();
foreach ($tables as $table)
{
if (0 !== stripos($table->Name, $wpdb->prefix))
{
continue;
}
if (empty($table->Engine))
{
continue;
}
if(in_array($table->Name,$exclude_tables))
{
continue;
}
$snapshot_table['Name']=$table->Name;
$snapshot_table['finished']=0;
$snapshot_tables[$table->Name]=$snapshot_table;
}
if(empty($type))
{
$type='manual';
}
$this->init_task($snapshot_id,$snapshot_tables,$type,$comment);
if (!empty($snapshot_tables))
{
foreach ($snapshot_tables as $table_name=>$snapshot_table)
{
if($snapshot_table['finished']==1)
continue;
$new_table=$this->str_replace_first($wpdb->prefix,$snapshot_id,$table_name);
$wpdb->query("OPTIMIZE TABLE {$table_name}");
$wpdb->query("DROP TABLE IF EXISTS `{$new_table}`");
$wpdb->query("CREATE TABLE `{$new_table}` LIKE `{$table_name}`");
$wpdb->query("INSERT `{$new_table}` SELECT * FROM `{$table_name}`");
$snapshot_tables[$table_name]['finished']=1;
$this->update_task($snapshot_id,$snapshot_tables);
if($this->is_time_limit_exceeded($start_time))
{
$ret['result']='success';
$ret['finished']=0;
$ret['snapshot_id']=$snapshot_id;
$ret['snapshot_tables']=$snapshot_tables;
return $ret;
}
}
}
else
{
$ret['result']='failed';
$ret['error']='Creating the snapshot failed.';
return $ret;
}
$this->update_task($snapshot_id,$snapshot_tables);
$this->update_snapshot($snapshot_id,$type,$comment);
$ret['result']='success';
$ret['finished']=1;
$ret['snapshot_id']=$snapshot_id;
return $ret;
}
public function resume_create_snapshot()
{
global $wpdb;
$start_time=time();
$ret=$this->get_task_data();
if($ret['result']=='failed')
{
return $ret;
}
$snapshot_id=$ret['snapshot_id'];
$snapshot_tables=$ret['snapshot_tables'];
$type=$ret['type'];
$comment=$ret['comment'];
if (!empty($snapshot_tables))
{
foreach ($snapshot_tables as $table_name=>$snapshot_table)
{
if($snapshot_table['finished']==1)
continue;
$new_table=$this->str_replace_first($wpdb->prefix,$snapshot_id,$table_name);
$wpdb->query("OPTIMIZE TABLE {$table_name}");
$wpdb->query("DROP TABLE IF EXISTS `{$new_table}`");
$wpdb->query("CREATE TABLE `{$new_table}` LIKE `{$table_name}`");
$wpdb->query("INSERT `{$new_table}` SELECT * FROM `{$table_name}`");
$snapshot_tables[$table_name]['finished']=1;
$this->update_task($snapshot_id,$snapshot_tables);
if($this->is_time_limit_exceeded($start_time))
{
$ret['result']='success';
$ret['finished']=0;
$ret['snapshot_id']=$snapshot_id;
$ret['snapshot_tables']=$snapshot_tables;
$this->update_task($snapshot_id,$snapshot_tables);
return $ret;
}
}
}
else
{
$ret['result']='failed';
$ret['error']='Creating the snapshot failed.';
return $ret;
}
$this->update_task($snapshot_id,$snapshot_tables);
$this->update_snapshot($snapshot_id,$type,$comment);
$ret['result']='success';
$ret['finished']=1;
$ret['snapshot_id']=$snapshot_id;
return $ret;
}
public function init_task($snapshot_id,$snapshot_tables,$type,$comment)
{
$snapshot_task=$this->options->get_option('wpvivid_snapshot_task');
if(empty($snapshot_task))
{
$snapshot_task=array();
}
$snapshot_task['snapshot_id']=$snapshot_id;
$snapshot_task['snapshot_tables']=$snapshot_tables;
$snapshot_task['type']=$type;
$snapshot_task['comment']=$comment;
$this->options->update_option('wpvivid_snapshot_task',$snapshot_task);
}
public function get_progress()
{
$snapshot_task=$this->options->get_option('wpvivid_snapshot_task');
if(empty($snapshot_task))
{
$progress['main_percent']='0%';
$progress['doing']="Creating a snapshot.";
}
$snapshot_tables=$snapshot_task['snapshot_tables'];
$i_sum=count($snapshot_tables);
$i_finished=0;
$b_finished=true;
foreach ($snapshot_tables as $table_name=>$snapshot_table)
{
if($snapshot_table['finished']==1)
{
$i_finished++;
}
else
{
$b_finished=false;
}
}
$i_progress=intval(($i_finished/$i_sum)*100);
$progress['main_percent']=$i_progress.'%';
if($b_finished)
{
$progress['doing']="Create snapshot completed.";
}
else
{
$progress['doing']="Creating a snapshot.";
}
return $progress;
}
public function update_task($snapshot_id,$snapshot_tables)
{
$snapshot_task=$this->options->get_option('wpvivid_snapshot_task');
if(empty($snapshot_task))
{
$snapshot_task=array();
}
$snapshot_task['snapshot_id']=$snapshot_id;
$snapshot_task['snapshot_tables']=$snapshot_tables;
$this->options->update_option('wpvivid_snapshot_task',$snapshot_task);
}
public function get_task_data()
{
$snapshot_task=$this->options->get_option('wpvivid_snapshot_task');
if(empty($snapshot_task))
{
$ret['result']='failed';
$ret['error']='Creating snapshot task not found.';
return $ret;
}
if(empty($snapshot_task['snapshot_id'])||empty($snapshot_task['snapshot_tables']))
{
$ret['result']='failed';
$ret['error']='Creating snapshot task not found.';
return $ret;
}
$ret['result']='success';
$ret['snapshot_id']=$snapshot_task['snapshot_id'];
$ret['snapshot_tables']=$snapshot_task['snapshot_tables'];
$ret['type']=$snapshot_task['type'];
$ret['comment']=$snapshot_task['comment'];
return $ret;
}
public function get_snapshots($type='')
{
$snapshot_data=$this->options->get_option('wpvivid_snapshot');
if(empty($snapshot_data))
{
$snapshot_data=array();
}
if(empty($type))
{
return $snapshot_data;
}
else
{
$get_snapshot_data=array();
foreach ($snapshot_data as $data)
{
if($data['type']==$type)
{
$get_snapshot_data[]=$data;
}
}
return $snapshot_data;
}
}
public function restore_snapshot($snapshot_id)
{
global $wpdb;
$tables = $wpdb->get_results('SHOW TABLE STATUS');
//$exclude_tables[]=$wpdb->prefix.'wpvivid_log';
//$exclude_tables[]=$wpdb->base_prefix."wpvivid_increment_big_ids";
//$exclude_tables[]=$wpdb->prefix.'wpvivid_merge_db';
$exclude_tables[]=$wpdb->prefix.'wpvivid_options';
$exclude_tables=apply_filters('wpvivid_create_snapshot_exclude_tables',$exclude_tables);
add_filter('wpvivid_merge_query_lock', array($this,'query_lock'), 9999);
$new_tables = array();
if (is_array($tables))
{
foreach ($tables as $table)
{
if (0 !== stripos($table->Name, $snapshot_id))
{
continue;
}
if (empty($table->Engine))
{
continue;
}
if(in_array($table->Name,$exclude_tables))
{
continue;
}
$new_table['Name']=$table->Name;
$new_table['finished']=0;
$new_tables[$table->Name] =$new_table;
}
}
else
{
$ret['result']='failed';
$ret['error']='Failed to retrieve list of database tables.';
return $ret;
}
$this->init_restore_task($snapshot_id,$new_tables);
/*
foreach ($tables as $table)
{
if (0 !== stripos($table->Name, $wpdb->prefix))
{
continue;
}
if (empty($table->Engine))
{
continue;
}
if(in_array($table->Name,$exclude_tables))
{
continue;
}
$wpdb->query('DROP TABLE ' . $table->Name);
}*/
foreach ($new_tables as $table_name=>$table)
{
$new_table=$this->str_replace_first($snapshot_id,$wpdb->prefix,$table_name);
$wpdb->query('DROP TABLE ' . $new_table);
$wpdb->query("CREATE TABLE `{$new_table}` LIKE `{$table_name}`");
$wpdb->query("INSERT `{$new_table}` SELECT * FROM `{$table_name}`");
$new_tables[$table_name]['finished']=1;
$this->update_restore_task($snapshot_id,$new_tables);
}
$ret['result']='success';
return $ret;
}
public function init_restore_task($snapshot_id,$snapshot_tables)
{
$snapshot_task=$this->options->get_option('wpvivid_restore_snapshot_task');
if(empty($snapshot_task))
{
$snapshot_task=array();
}
$snapshot_task['snapshot_id']=$snapshot_id;
$snapshot_task['snapshot_tables']=$snapshot_tables;
$this->options->update_option('wpvivid_restore_snapshot_task',$snapshot_task);
}
public function update_restore_task($snapshot_id,$snapshot_tables)
{
$snapshot_task=$this->options->get_option('wpvivid_restore_snapshot_task');
if(empty($snapshot_task))
{
$snapshot_task=array();
}
$snapshot_task['snapshot_id']=$snapshot_id;
$snapshot_task['snapshot_tables']=$snapshot_tables;
$this->options->update_option('wpvivid_restore_snapshot_task',$snapshot_task);
}
public function get_restore_task_data()
{
$snapshot_task=$this->options->get_option('wpvivid_restore_snapshot_task');
if(empty($snapshot_task))
{
$ret['result']='failed';
$ret['error']='Restoring snapshot task not found.';
return $ret;
}
if(empty($snapshot_task['snapshot_id'])||empty($snapshot_task['snapshot_tables']))
{
$ret['result']='failed';
$ret['error']='Restoring snapshot task not found.';
return $ret;
}
$ret['result']='success';
$ret['snapshot_id']=$snapshot_task['snapshot_id'];
$ret['snapshot_tables']=$snapshot_task['snapshot_tables'];
return $ret;
}
public function remove_snapshot($snapshot_id)
{
global $wpdb;
$tables = $wpdb->get_col($wpdb->prepare('SHOW TABLES LIKE %s', array($snapshot_id . '%')));
foreach ($tables as $table)
{
$wpdb->query('DROP TABLE IF EXISTS `' . $table.'`');
}
$snapshot_data=$this->options->get_option('wpvivid_snapshot');
unset($snapshot_data[$snapshot_id]);
$this->options->update_option('wpvivid_snapshot',$snapshot_data);
$ret['result']='success';
return $ret;
}
public function str_replace_first($from, $to, $content)
{
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
public function create_snapshot_uid()
{
global $wpdb;
$count = 0;
do
{
$count++;
$uid = sprintf('%06x', wp_rand(0, 0xFFFFFF));
$verify_db = $wpdb->get_col($wpdb->prepare('SHOW TABLES LIKE %s', array('%' . $uid . '%')));
} while (!empty($verify_db) && $count < 10);
if ($count == 10)
{
$uid = false;
}
return $uid;
}
public function update_snapshot($snapshot_id,$type,$comment)
{
$snapshot_data=$this->options->get_option('wpvivid_snapshot');
if(empty($snapshot_data))
{
$snapshot_data=array();
}
$snapshot_data[$snapshot_id]['id']=$snapshot_id;
$snapshot_data[$snapshot_id]['type']=$type;
$snapshot_data[$snapshot_id]['time']=time();
$snapshot_data[$snapshot_id]['comment']=$comment;
$this->options->update_option('wpvivid_snapshot',$snapshot_data);
}
public function is_time_limit_exceeded($start_time)
{
$time_limit =20;
$time_taken = microtime(true) -$start_time;
if($time_taken >= $time_limit)
{
return true;
}
return false;
}
public function get_dev_progress()
{
$snapshot_task=$this->options->get_option('wpvivid_snapshot_task');
if(empty($snapshot_task))
{
$progress['main_percent']='0%';
$progress['text']="creating snapshot for dev site.";
}
$snapshot_tables=$snapshot_task['snapshot_tables'];
$i_sum=count($snapshot_tables);
$i_finished=0;
$b_finished=true;
foreach ($snapshot_tables as $table_name=>$snapshot_table)
{
if($snapshot_table['finished']==1)
{
$i_finished++;
}
else
{
$b_finished=false;
}
}
$i_progress=intval(($i_finished/$i_sum)*100);
$progress['main_percent']=$i_progress.'%';
if($b_finished)
{
$progress['text']="creating snapshot for dev site completed.";
}
else
{
$progress['text']="creating snapshot for dev site - $i_finished/$i_sum tables";
}
return $progress;
}
public function query_lock($lock)
{
return true;
}
} includes/snapshot/class-wpvivid-snapshot.php 0000644 00000216104 15132770567 0015373 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Snapshot_Ex
{
public $options;
public $main_tab;
public function __construct()
{
include_once WPVIVID_PLUGIN_DIR . '/includes/snapshot/class-wpvivid-snapshot-function.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/snapshot/class-wpvivid-snapshot-options.php';
if(is_admin())
{
include_once WPVIVID_PLUGIN_DIR . '/includes/snapshot/class-wpvivid-snapshots-list.php';
add_filter('wpvivid_get_dashboard_menu', array($this, 'get_dashboard_menu'), 20, 2);
add_filter('wpvivid_get_dashboard_screens', array($this, 'get_dashboard_screens'), 20);
add_filter('wpvivid_snapshot_get_main_admin_menus',array($this,'get_main_admin_menus'),9999);
$this->options=new WPvivid_Snapshot_Option_Ex();
/*
if (is_multisite())
{
add_action('network_admin_menu',array( $this,'add_admin_menu'));
}
else
{
add_action('admin_menu',array( $this,'add_admin_menu'));
}
add_filter('wpvivid_snapshot_get_screen_ids', array($this,'get_screen_ids'), 9999);
*/
add_filter('wpvivid_get_admin_menus',array($this,'get_admin_menus'),22);
add_filter('wpvivid_get_screen_ids',array($this,'get_screen_ids'),12);
add_action('admin_enqueue_scripts', array($this, 'enqueue_styles'), 11);
add_action('admin_enqueue_scripts', array($this, 'enqueue_scripts'), 11);
add_action('wp_ajax_wpvivid_create_snapshot',array( $this,'create_snapshot'));
add_action('wp_ajax_wpvivid_get_snapshot_progress',array( $this,'get_snapshot_progress'));
//
add_action('wp_ajax_wpvivid_resume_create_snapshot',array( $this,'resume_create_snapshot'));
add_action('wp_ajax_wpvivid_restore_snapshot',array( $this,'restore_snapshot'));
add_action('wp_ajax_wpvivid_get_restore_snapshot_status',array( $this,'get_restore_snapshot_status'));
add_action('wp_ajax_wpvivid_delete_snapshot',array( $this,'delete_snapshot'));
add_filter('wpvivid_check_create_snapshot',array($this,'check_create_snapshot'));
add_action('wpvivid_create_snapshot',array($this,'create_snapshot_ex'),10,1);
add_action('wp_ajax_wpvivid_set_snapshot_setting',array( $this,'set_setting'));
//
add_action('wpvivid_snapshot_add_sidebar',array( $this,'add_sidebar'));
add_action('wpvivid_snapshot_add_sidebar_free', array( $this, 'add_sidebar_free' ));
$snapshot_setting=$this->options->get_option('wpvivid_snapshot_setting');
$quick_snapshot=isset($snapshot_setting['quick_snapshot'])?$snapshot_setting['quick_snapshot']:false;
if($quick_snapshot)
{
add_action('admin_bar_menu',array( $this,'add_toolbar_items'),100);
add_action('admin_footer',array( $this,'quick_snapshot'));
}
}
}
public function get_admin_menus($submenus)
{
$submenu['parent_slug']=apply_filters('wpvivid_white_label_slug', WPVIVID_PLUGIN_SLUG);
$submenu['page_title']= apply_filters('wpvivid_white_label_display', 'WPvivid Backup');
$submenu['menu_title']=__('Database Snapshots', 'wpvivid-backuprestore');
$submenu['capability']='administrator';
$submenu['menu_slug']=strtolower(sprintf('%s-snapshot-ex', apply_filters('wpvivid_white_label_slug', 'wpvivid')));
$submenu['index']=2;
$submenu['function']=array($this, 'init_page');
$submenus[$submenu['menu_slug']]=$submenu;
return $submenus;
}
public function get_screen_ids($screen_ids)
{
$screen_ids[]=apply_filters('wpvivid_white_label_screen_id', 'wpvivid-backup_page_wpvivid-snapshot-ex');
return $screen_ids;
}
public function add_toolbar_items($wp_admin_bar)
{
$wp_admin_bar->add_menu(array(
'id' => 'wpvivid_snapshot_admin_menu',
'title' => '<span class="dashicons-camera-alt ab-icon"></span>'.'Quick Snapshot',
'meta' =>array(
'class' => 'wpvivid-quick-create-snapshot',
)
));
}
public function add_admin_menu()
{
$page_title=apply_filters('wpvivid_white_label_display', 'WPvivid Snapshot');
$menu_title=apply_filters('wpvivid_white_label_display', 'WPvivid Snapshot');
$capability = 'administrator';
$menu_slug ='wpvivid-snapshot';
$function=array($this, 'init_page');
$icon_url='dashicons-camera-alt';
$position=100;
$menu['page_title']= $page_title;
$menu['menu_title']= $menu_title;
$menu['capability']='administrator';
$menu['menu_slug']=$menu_slug;
$menu['function']=array($this, 'init_page');
$menu['icon_url']=$icon_url;
$menu['position']=100;
$menu=apply_filters('wpvivid_snapshot_get_main_admin_menus', $menu);
if($menu!=false)
add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position);
}
public function get_dashboard_menu($submenus,$parent_slug)
{
$display = apply_filters('wpvivid_get_menu_capability_addon', 'menu_database_snapshot');
if($display)
{
$submenu['menu_slug'] = strtolower(sprintf('%s-snapshot', apply_filters('wpvivid_white_label_slug', 'wpvivid')));
if(isset($submenus[$submenu['menu_slug']]))
{
unset($submenus[$submenu['menu_slug']]);
}
$submenu['parent_slug'] = $parent_slug;
$submenu['page_title'] = apply_filters('wpvivid_white_label_display', 'Database Snapshots');
$submenu['menu_title'] = 'Database Snapshots';
$submenu['capability'] = 'administrator';
$submenu['index'] = 11;//10;
$submenu['function'] = array($this, 'init_page_pro');
$submenus[$submenu['menu_slug']] = $submenu;
}
return $submenus;
}
public function get_dashboard_screens($screens)
{
$screen['menu_slug']='wpvivid-snapshot';
$screen['screen_id']='wpvivid-plugin_page_wpvivid-snapshot';
$screen['is_top']=false;
$screens[]=$screen;
return $screens;
}
public function get_main_admin_menus($menu)
{
if(class_exists('WPvivid_backup_pro'))
return false;
else
return $menu;
}
/*
public function get_screen_ids($screen_ids)
{
$screen_ids=array();
$screen['menu_slug']='wpvivid-snapshot';
$screen['screen_id']='toplevel_page_wpvivid-snapshot';
$screen['is_top']=true;
$screens[]=$screen;
foreach ($screens as $screen)
{
$screen_ids[]=$screen['screen_id'];
if(is_multisite())
{
if(substr($screen['screen_id'],-8)=='-network')
continue;
$screen_ids[]=$screen['screen_id'].'-network';
}
else
{
$screen_ids[]=$screen['screen_id'];
}
}
return $screen_ids;
}
*/
public function enqueue_styles()
{
$screen_ids=array();
$screen_ids=apply_filters('wpvivid_get_screen_ids',$screen_ids);
if(in_array(get_current_screen()->id,$screen_ids))
{
wp_enqueue_style('wpvivid_snapshot_ex', WPVIVID_PLUGIN_DIR_URL . 'css/wpvivid-snapshot-style.css', array(), WPVIVID_PLUGIN_VERSION, 'all');
}
}
public function enqueue_scripts()
{
$snapshot_setting=$this->options->get_option('wpvivid_snapshot_setting');
$quick_snapshot=isset($snapshot_setting['quick_snapshot'])?$snapshot_setting['quick_snapshot']:false;
if($quick_snapshot)
{
wp_enqueue_style('wpvivid_quick_snapshot_ex', WPVIVID_PLUGIN_DIR_URL . 'css/wpvivid-quick-snapshot-style.css', array(), WPVIVID_PLUGIN_VERSION, 'all');
wp_enqueue_style ( 'wp-jquery-ui-dialog');
wp_enqueue_script( 'jquery-ui-dialog' );
wp_enqueue_script ( 'wpvivid_qucick_snapshot_ex_js' , // handle
WPVIVID_PLUGIN_DIR_URL . 'js/wpvivid-quick-snapshot.js' , // source
array('jquery-ui-dialog'),
WPVIVID_PLUGIN_VERSION, false
);
wp_localize_script('wpvivid_qucick_snapshot_ex_js', 'wpvivid_quick_snapshot_ajax_object', array('ajax_url' => admin_url('admin-ajax.php'),'ajax_nonce'=>wp_create_nonce('wpvivid_ajax')));
}
}
public function added_quick_snapshot($added)
{
return true;
}
public function quick_snapshot()
{
if(apply_filters('wpvivid_added_quick_snapshot',false))
{
return;
}
add_filter('wpvivid_added_quick_snapshot',array( $this,'added_quick_snapshot'));
$current_url = $_SERVER['REQUEST_URI'];
if (preg_match('/post.php?/', $current_url))
{
return;
}
?>
<div id="wpvivid_quick_snapshot_dialog">
<span id="wpvivid_quick_snapshot_close" class="dashicons dashicons-no" style="float:right;cursor: pointer"></span>
<div id="wpvivid_quick_snapshot_message_box" style="padding:20px 0;">
<p style="text-align:center;font-size:24px;">
<span id="wpvivid_quick_snapshot_message">Are you sure you want to create a snapshot now?</span>
<span id="wpvivid_quick_snapshot_loading"><img src="<?php echo esc_url(admin_url()).'/images/loading.gif'; ?>"></span>
</p>
<p style="text-align:center;" id="wpvivid_quick_create_snapshot_comment_box">
<span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-green" style="margin-top:0.2em;"></span>
<span><strong>Comment the snapshot</strong>(optional): </span>
<input id="wpvivid_quick_create_snapshot_comment" type="text" placeholder="e.g. mysnapshot">
</p>
</div>
<div id="wpvivid_quick_snapshot_progress" style="display: none">
<p>
<span class="wpvivid-span-progress">
<span class="wpvivid-span-processed-progress">0% completed</span>
</span>
</p>
<p><span>Action: </span><span></span><span></span></p>
</div>
<div style="padding:0 0 10px 0">
<p style="text-align:center;">
<input class="button-primary" style="width: 150px; height: 40px; font-size: 16px; margin-bottom: 10px; pointer-events: auto; opacity: 1;" id="wpvivid_quick_create_snapshot" type="submit" value="Create Now">
</p>
</div>
</div>
<script>
var b_quick_end_create_progress=false;
var b_quick_need_update=false;
jQuery('.wpvivid-quick-create-snapshot').click(function()
{
jQuery("#wpvivid_quick_snapshot_message_box").show();
//
jQuery("#wpvivid_quick_snapshot_loading").hide();
jQuery("#wpvivid_quick_create_snapshot_comment_box").show();
jQuery("#wpvivid_quick_snapshot_progress").hide();
//
jQuery("#wpvivid_quick_snapshot_message").html("Are you sure you want to create a snapshot now?");
jQuery("#wpvivid_quick_snapshot_dialog").dialog("widget").find(".ui-dialog-titlebar").hide();
jQuery("#wpvivid_quick_snapshot_dialog").dialog("open");
return false;
});
//wpvivid_quick_snapshot_close
jQuery('#wpvivid_quick_snapshot_close').click(function()
{
jQuery("#wpvivid_quick_snapshot_dialog").dialog('close');
});
jQuery('#wpvivid_quick_create_snapshot').click(function()
{
wpvivid_quick_create_snapshot();
});
function wpvivid_quick_simulate_create_progress()
{
var MaxProgess = 30,
currentProgess = 0,
steps = 1,
time_steps=1000;
var timer = setInterval(function ()
{
if(currentProgess>100)
{
currentProgess=100;
}
else
{
currentProgess += steps;
}
if(b_quick_end_create_progress)
{
clearInterval(timer);
return;
}
var progress_html='<p><span class="wpvivid-span-progress">' +
'<span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width: '+currentProgess+'%">' +
currentProgess+'% completed</span></span></p><p>' +
'<span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span>' +
'<span>Creating the snapshot.</span></p>';
jQuery("#wpvivid_quick_snapshot_progress").html(progress_html);
if (currentProgess >= MaxProgess)
{
clearInterval(timer);
}
}, time_steps);
}
function wpvivid_quick_create_snapshot()
{
var comment=jQuery('#wpvivid_quick_create_snapshot_comment').val();
var ajax_data= {
'action': 'wpvivid_create_snapshot',
'comment':comment,
};
var default_progress='<p><span class="wpvivid-span-progress"><span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width: 0%">0% completed</span></span></p><p><span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span><span>Creating a snapshot.</span></p>';
jQuery('#wpvivid_quick_snapshot_progress').show();
jQuery('#wpvivid_quick_snapshot_progress').html(default_progress);
jQuery("#wpvivid_quick_snapshot_loading").show();
jQuery("#wpvivid_quick_create_snapshot_comment_box").hide();
jQuery("#wpvivid_quick_snapshot_message").html("Creating the snapshot...");
b_quick_need_update=true;
b_quick_end_create_progress=false;
wpvivid_quick_simulate_create_progress();
setTimeout(function(){
wpvivid_quick_get_snapshot_progress();
}, 3000);
jQuery('#wpvivid_quick_create_snapshot').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request_quick(ajax_data, function(data)
{
b_quick_end_create_progress=true;
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_quick_snapshot_progress').html(jsonarray.progress);
if(jsonarray.finished==1)
{
jQuery("#wpvivid_quick_snapshot_dialog").dialog('close');
b_quick_need_update=false;
jQuery('#wpvivid_quick_snapshot_progress').hide();
jQuery('#wpvivid_quick_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery("#wpvivid_quick_snapshot_loading").hide();
jQuery("#wpvivid_quick_create_snapshot_comment_box").show();
jQuery("#wpvivid_quick_snapshot_message").html("Are you sure you want to create a snapshot now?");
alert("Creating a snapshot completed successfully.");
}
else
{
wpvivid_quick_resume_create_snapshot();
}
}
else
{
alert(jsonarray.error);
b_quick_need_update=false;
jQuery('#wpvivid_quick_snapshot_progress').hide();
jQuery('#wpvivid_quick_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery("#wpvivid_quick_snapshot_loading").hide();
jQuery("#wpvivid_quick_create_snapshot_comment_box").show();
jQuery("#wpvivid_quick_snapshot_message").html("Are you sure you want to create a snapshot now?");
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function(){
wpvivid_quick_resume_create_snapshot(0);
}, 15000);
});
}
function wpvivid_quick_get_snapshot_progress()
{
var ajax_data= {
'action': 'wpvivid_get_snapshot_progress',
};
wpvivid_post_request_quick(ajax_data, function(data)
{
var jsonarray = jQuery.parseJSON(data);
b_quick_end_create_progress=true;
jQuery('#wpvivid_quick_snapshot_progress').html(jsonarray.progress);
if(b_quick_need_update)
{
setTimeout(function(){
wpvivid_quick_get_snapshot_progress();
}, 1000);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
if(b_quick_need_update)
{
setTimeout(function(){
wpvivid_quick_get_snapshot_progress();
}, 1000);
}
});
}
function wpvivid_quick_resume_create_snapshot(resume)
{
if(resume>6)
{
alert('Creating the snapshot timed out.');
b_quick_need_update=false;
jQuery("#wpvivid_quick_snapshot_message_box").show();
jQuery('#wpvivid_quick_snapshot_progress').hide();
jQuery('#wpvivid_quick_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery("#wpvivid_quick_snapshot_loading").hide();
jQuery("#wpvivid_quick_create_snapshot_comment_box").show();
jQuery("#wpvivid_quick_snapshot_message").html("Are you sure you want to create a snapshot now?");
return;
}
var ajax_data= {
'action': 'wpvivid_resume_create_snapshot'
};
wpvivid_post_request_quick(ajax_data, function(data)
{
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_quick_snapshot_progress').html(jsonarray.progress);
if(jsonarray.finished==1)
{
b_quick_need_update=false;
jQuery("#wpvivid_quick_snapshot_dialog").dialog('close');
jQuery("#wpvivid_quick_snapshot_message_box").show();
jQuery('#wpvivid_quick_snapshot_progress').hide();
jQuery('#wpvivid_quick_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery("#wpvivid_quick_snapshot_loading").hide();
jQuery("#wpvivid_quick_create_snapshot_comment_box").show();
jQuery("#wpvivid_quick_snapshot_message").html("Are you sure you want to create a snapshot now?");
alert("Creating a snapshot completed successfully.");
}
else
{
wpvivid_quick_resume_create_snapshot();
}
}
else
{
b_quick_need_update=false;
jQuery("#wpvivid_quick_snapshot_message_box").show();
alert(jsonarray.error);
jQuery('#wpvivid_quick_snapshot_progress').hide();
jQuery('#wpvivid_quick_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery("#wpvivid_quick_snapshot_loading").hide();
jQuery("#wpvivid_quick_create_snapshot_comment_box").show();
jQuery("#wpvivid_quick_snapshot_message").html("Are you sure you want to create a snapshot now?");
}
}
catch (e)
{
resume+=1;
setTimeout(function(){
wpvivid_quick_resume_create_snapshot(resume);
}, 15000);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
resume+=1;
setTimeout(function(){
wpvivid_quick_resume_create_snapshot(resume);
}, 15000);
});
}
jQuery(document).ready(function ()
{
jQuery(function($)
{
jQuery("#wpvivid_quick_snapshot_dialog").dialog({
'dialogClass' : 'noTitleStuff',
'modal' : true,
'autoOpen' : false,
'closeOnEscape' : true,
'width': '600px',
'minWidth' : "260px"
});
});
});
</script>
<?php
}
public function init_page()
{
$this->options->check_tables();
?>
<div class="wrap" style="max-width:1720px;">
<h1><?php echo esc_html( apply_filters('wpvivid_white_label_display', 'WPvivid').' Plugins - Snapshots'); ?></h1>
<?php
if(!class_exists('WPvivid_Tab_Page_Container'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-tab-page-container.php';
$args['is_parent_tab']=1;
$this->main_tab=new WPvivid_Tab_Page_Container();
$this->main_tab->add_tab('Snapshots','snapshots',array($this, 'output_snapshots'), $args);
$this->main_tab->add_tab('Setting','snapshots_setting',array($this, 'output_snapshots_setting'), $args);
$this->main_tab->display();
?>
</div>
<?php
}
public function init_page_pro()
{
$this->options->check_tables();
?>
<div class="wrap wpvivid-canvas">
<div class="icon32"></div>
<h1><?php echo esc_html( apply_filters('wpvivid_white_label_display', 'WPvivid').' Plugins - Snapshots' ); ?></h1>
<div id="wpvivid_backup_notice"></div>
<div id="poststuff">
<div id="post-body" class="metabox-holder columns-2">
<div id="post-body-content">
<div class="meta-box-sortables ui-sortable">
<div class="wpvivid-backup">
<?php $this->welcome_bar();?>
<div class="wpvivid-canvas wpvivid-clear-float">
<!--- backup progress --->
<?php
if(!class_exists('WPvivid_Tab_Page_Container_Ex'))
include_once WPVIVID_PLUGIN_DIR . '/includes/snapshot/class-wpvivid-tab-page-container-ex.php';
$this->main_tab=new WPvivid_Tab_Page_Container_Ex();
$args['is_parent_tab']=0;
$args['div_style']='padding-top:0;display:block;';
$args['span_class']='dashicons dashicons-camera';
$args['span_style']='color:#007cba; padding-right:0.5em;margin-top:0.2em;';
//
$tabs['merge']['title']='Snapshots';
$tabs['merge']['slug']='snapshots';
$tabs['merge']['callback']=array($this, 'output_snapshots');
$tabs['merge']['args']=$args;
$args['div_style']='padding-top:0;';
$args['span_class']='dashicons dashicons-admin-generic';
$args['span_style']='color:grey;padding-right:0.5em;margin-top:0.1em;';
$tabs['snapshot']['title']='Setting';
$tabs['snapshot']['slug']='snapshots_setting';
$tabs['snapshot']['callback']=array($this, 'output_snapshots_setting');
$tabs['snapshot']['args']=$args;
foreach ($tabs as $key=>$tab)
{
$this->main_tab->add_tab($tab['title'],$tab['slug'],$tab['callback'], $tab['args']);
}
$this->main_tab->display();
?>
</div>
</div>
</div>
</div>
<?php
do_action( 'wpvivid_snapshot_add_sidebar');
?>
</div>
</div>
</div>
<?php
}
public function welcome_bar()
{
?>
<div class="wpvivid-welcome-bar wpvivid-clear-float">
<div class="wpvivid-welcome-bar-left">
<p><span class="dashicons dashicons-camera-alt wpvivid-dashicons-large wpvivid-dashicons-green"></span><span class="wpvivid-page-title">Database Snapshots</span></p>
<p><span class="about-description">Create snapshots of the website database and restore the database from a snapshot.</span></p>
</div>
<div class="wpvivid-welcome-bar-right">
<p></p>
<div style="float:right;">
<span>Local Time:</span>
<span>
<a href="<?php echo esc_attr(apply_filters('wpvivid_get_admin_url', '').'options-general.php'); ?>">
<?php
$offset=get_option('gmt_offset');
echo esc_html(gmdate("l, F-d-Y H:i",time()+$offset*60*60));
?>
</a>
</span>
<span class="dashicons dashicons-editor-help wpvivid-dashicons-editor-help wpvivid-tooltip">
<div class="wpvivid-left">
<p>Clicking the date and time will redirect you to the WordPress General Settings page where you can change your timezone settings.</p>
<i></i> <!-- do not delete this line -->
</div>
</span>
</div>
</div>
</div>
<?php
}
public function output_snapshots()
{
$snapshot=new WPvivid_Snapshot_Function_Ex();
$snapshot_data=$snapshot->get_snapshots();
?>
<div class="postbox quicksnapshot">
<div id="wpvivid_snapshot_progress" style="display: none">
<p>
<span class="wpvivid-span-progress">
<span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress">0% completed</span>
</span>
</p>
<p><span>Action: </span><span></span><span class="wpvivid-animate-flicker"></span></p>
</div>
<div>
<input class="button-primary" style="width: 200px; height: 50px; font-size: 20px; margin-bottom: 10px; pointer-events: auto; opacity: 1;" id="wpvivid_create_snapshot" type="submit" value="Create a snapshot">
</div>
<div>
<p>
<span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-green" style="margin-top:0.2em;"></span>
<span><strong>Comment the snapshot</strong>(optional): </span>
<input id="wpvivid_create_snapshot_comment" type="text" placeholder="e.g. mysnapshot">
</p>
</div>
<div id="wpvivid_snapshots_list">
<?php
$Snapshots_list = new WPvivid_Snapshots_List_Ex();
$Snapshots_list->set_list($snapshot_data);
$Snapshots_list->prepare_items();
$Snapshots_list->display();
?>
</div>
</div>
<script>
var b_need_update=false;
var b_restore_finished=false;
var b_end_create_progress=false;
jQuery('#wpvivid_create_snapshot').click(function()
{
wpvivid_create_snapshot();
});
function wpvivid_simulate_restore_progress()
{
var MaxProgess = 95,
currentProgess = 0,
steps = 1,
time_steps=1000;
var timer = setInterval(function ()
{
if(b_restore_finished)
{
currentProgess=100;
}
else
{
currentProgess += steps;
}
var progress_html='<p><span class="wpvivid-span-progress">' +
'<span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width: '+currentProgess+'%">' +
currentProgess+'% completed</span></span></p><p>' +
'<span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span>' +
'<span>Restoring the snapshot.</span></p>';
jQuery("#wpvivid_snapshot_progress").html(progress_html);
if (currentProgess >= MaxProgess)
{
clearInterval(timer);
}
}, time_steps);
}
function wpvivid_simulate_create_progress()
{
var MaxProgess = 30,
currentProgess = 0,
steps = 1,
time_steps=1000;
var timer = setInterval(function ()
{
if(currentProgess>100)
{
currentProgess=100;
}
else
{
currentProgess += steps;
}
if(b_end_create_progress)
{
clearInterval(timer);
return;
}
var progress_html='<p><span class="wpvivid-span-progress">' +
'<span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width: '+currentProgess+'%">' +
currentProgess+'% completed</span></span></p><p>' +
'<span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span>' +
'<span>Creating the snapshot.</span></p>';
jQuery("#wpvivid_snapshot_progress").html(progress_html);
if (currentProgess >= MaxProgess)
{
clearInterval(timer);
}
}, time_steps);
}
function wpvivid_create_snapshot()
{
var comment=jQuery('#wpvivid_create_snapshot_comment').val();
var ajax_data= {
'action': 'wpvivid_create_snapshot',
'comment':comment,
};
var default_progress='<p><span class="wpvivid-span-progress"><span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width: 0%">0% completed</span></span></p><p><span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span><span>Creating a snapshot.</span></p>';
jQuery('#wpvivid_snapshot_progress').show();
jQuery('#wpvivid_snapshot_progress').html(default_progress);
b_need_update=true;
b_end_create_progress=false;
wpvivid_simulate_create_progress();
setTimeout(function(){
wpvivid_get_snapshot_progress();
}, 3000);
jQuery('#wpvivid_create_snapshot').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function(data)
{
b_end_create_progress=true;
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_snapshot_progress').html(jsonarray.progress);
if(jsonarray.finished==1)
{
b_need_update=false;
alert('Creating a snapshot completed successfully.');
location.reload();
}
else
{
wpvivid_resume_create_snapshot();
}
}
else
{
b_need_update=false;
alert(jsonarray.error);
jQuery('#wpvivid_snapshot_progress').hide();
jQuery('#wpvivid_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function(){
wpvivid_resume_create_snapshot(0);
}, 15000);
});
}
function wpvivid_get_snapshot_progress()
{
var ajax_data= {
'action': 'wpvivid_get_snapshot_progress',
};
wpvivid_post_request(ajax_data, function(data)
{
var jsonarray = jQuery.parseJSON(data);
b_end_create_progress=true;
jQuery('#wpvivid_snapshot_progress').html(jsonarray.progress);
if(b_need_update)
{
setTimeout(function(){
wpvivid_get_snapshot_progress();
}, 1000);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
if(b_need_update)
{
setTimeout(function(){
wpvivid_get_snapshot_progress();
}, 1000);
}
});
}
function wpvivid_resume_create_snapshot(resume)
{
if(resume>6)
{
b_need_update=false;
alert('Creating the snapshot timed out.');
jQuery('#wpvivid_snapshot_progress').hide();
jQuery('#wpvivid_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
return;
}
var ajax_data= {
'action': 'wpvivid_resume_create_snapshot'
};
wpvivid_post_request(ajax_data, function(data)
{
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_snapshot_progress').html(jsonarray.progress);
if(jsonarray.finished==1)
{
b_need_update=false;
alert('Creating a snapshot completed successfully.');
location.reload();
}
else
{
wpvivid_resume_create_snapshot();
}
}
else
{
b_need_update=false;
alert(jsonarray.error);
jQuery('#wpvivid_snapshot_progress').hide();
jQuery('#wpvivid_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
}
}
catch (e)
{
resume+=1;
setTimeout(function(){
wpvivid_resume_create_snapshot(resume);
}, 15000);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
resume+=1;
setTimeout(function(){
wpvivid_resume_create_snapshot(resume);
}, 15000);
});
}
jQuery('#wpvivid_snapshots_list').on("click",'.wpvivid-snapshot-restore',function()
{
var Obj=jQuery(this);
var snapshot_id=Obj.closest('tr').attr('slug');
var descript = '<?php esc_html_e('Are you sure you want to restore this snapshot?', 'wpvivid'); ?>';
var ret = confirm(descript);
if (ret === true)
{
var ajax_data= {
'action': 'wpvivid_restore_snapshot',
'id':snapshot_id
};
jQuery('#wpvivid_create_snapshot').css({'pointer-events': 'none', 'opacity': '0.4'});
var default_progress='<p><span class="wpvivid-span-progress"><span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width: 0%">0% completed</span></span></p><p><span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span><span>Restoring the snapshot.</span></p>';
jQuery('#wpvivid_snapshot_progress').show();
jQuery('#wpvivid_snapshot_progress').html(default_progress);
b_restore_finished=false;
wpvivid_simulate_restore_progress();
wpvivid_post_request(ajax_data, function(data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
b_restore_finished=true;
jQuery('#wpvivid_snapshot_progress').html(jsonarray.progress);
alert('Restoring the snapshot completed successfully.');
location.reload(); }
else
{
b_restore_finished=true;
jQuery('#wpvivid_snapshot_progress').hide();
alert(jsonarray.error);
jQuery('#wpvivid_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function(){
wpvivid_get_restore_snapshot_status();
}, 1000);
});
}
});
function wpvivid_get_restore_snapshot_status()
{
var ajax_data= {
'action': 'wpvivid_get_restore_snapshot_status',
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
if(jsonarray.finished==1)
{
jQuery('#wpvivid_snapshot_progress').html(jsonarray.progress);
b_restore_finished=true;
alert('Restoring the snapshot completed successfully.');
location.reload();
}
else
{
setTimeout(function(){
wpvivid_get_restore_snapshot_status();
}, 1000);
}
}
else
{
b_restore_finished=true;
jQuery('#wpvivid_snapshot_progress').hide();
alert(jsonarray.error);
jQuery('#wpvivid_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
}
}
catch (err)
{
setTimeout(function(){
wpvivid_get_restore_snapshot_status();
}, 1000);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
setTimeout(function(){
wpvivid_get_restore_snapshot_status();
}, 1000);
});
}
jQuery('#wpvivid_snapshots_list').on("click",'.wpvivid-snapshot-delete',function()
{
var Obj=jQuery(this);
var snapshot_id=Obj.closest('tr').attr('slug');
var descript = '<?php esc_html_e('Are you sure you want to delete this snapshot?', 'wpvivid'); ?>';
var ret = confirm(descript);
if (ret === true)
{
var ajax_data= {
'action': 'wpvivid_delete_snapshot',
'id':snapshot_id
};
jQuery('#wpvivid_create_snapshot').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function(data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
alert('The snapshot has been deleted successfully.');
jQuery('#wpvivid_snapshots_list').html(jsonarray.html);
jQuery('#wpvivid_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
}
else
{
alert(jsonarray.error);
jQuery('#wpvivid_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
jQuery('#wpvivid_create_snapshot').css({'pointer-events': 'auto', 'opacity': '1'});
alert("Deleting the snapshot(s) failed.");
});
}
});
jQuery('#wpvivid_snapshots_list').on("click",'#wpvivid_delete_snapshots_action',function()
{
var delete_snapshots_array = new Array();
var count = 0;
jQuery('#wpvivid_snapshots_list .wpvivid-snapshot-row input').each(function (i)
{
if(jQuery(this).prop('checked'))
{
delete_snapshots_array[count] =jQuery(this).closest('tr').attr('slug');
count++;
}
});
if( count === 0 )
{
alert('<?php esc_html_e('Please select at least one item.','wpvivid'); ?>');
}
else
{
var descript = '<?php esc_html_e('Are you sure to delete the selected snapshots? These snapshots will be deleted permanently.', 'wpvivid'); ?>';
var ret = confirm(descript);
if (ret === true)
{
jQuery('#wpvivid_delete_snapshots_action').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_delete_snapshot_array(delete_snapshots_array,0);
}
}
});
function wpvivid_delete_snapshot_array(delete_snapshots_array,index)
{
if(index >= delete_snapshots_array.length)
{
alert('The snapshot has been deleted successfully.');
jQuery('#wpvivid_delete_snapshots_action').css({'pointer-events': 'auto', 'opacity': '1'});
return;
}
const snapshot_id = delete_snapshots_array[index];
var ajax_data= {
'action': 'wpvivid_delete_snapshot',
'id':snapshot_id
};
wpvivid_post_request(ajax_data, function(data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_snapshots_list').html(jsonarray.html);
index++;
wpvivid_delete_snapshot_array(delete_snapshots_array,index);
}
else
{
alert(jsonarray.error);
jQuery('#wpvivid_delete_snapshots_action').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Deleting the snapshot(s) failed.');
jQuery('#wpvivid_delete_snapshots_action').css({'pointer-events': 'auto', 'opacity': '1'});
});
}
</script>
<?php
}
public function output_snapshots_setting()
{
$setting=$this->options->get_option('wpvivid_snapshot_setting');
if(empty($setting))
{
$setting=array();
}
$snapshot_retention=isset($setting['snapshot_retention'])?$setting['snapshot_retention']:6;
$quick_snapshot=isset($setting['quick_snapshot'])?$setting['quick_snapshot']:false;
if($quick_snapshot)
{
$quick_snapshot='checked';
}
else
{
$quick_snapshot='';
}
?>
<div class="postbox quicksnapshot">
<table class="widefat" style="border-left:none;border-top:none;border-right:none;">
<tr>
<td class="row-title" style="min-width:200px;">
<label for="tablecell">Snapshot Retention</label>
</td>
<td>
<p>
<span>Up to </span>
<span>
<select id="wpvivid_snapshot_retention" option="setting" name="snapshot_retention">
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6" selected>6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</span>
<span>snapshots retained</span></p>
<p>It is not recommended to create too many snapshots.</p>
</td>
</tr>
<tr>
<td class="row-title" style="min-width:200px;">
<label for="tablecell">Quick Snapshot</label>
</td>
<td>
<p>
<label class="wpvivid-checkbox">
<span>Enable Quick Snapshot</span>
<input type="checkbox" option="setting" name="quick_snapshot" <?php echo esc_attr($quick_snapshot); ?> />
<span class="wpvivid-checkbox-checkmark"></span>
</label>
</p>
<p><code>Show a menu in top admin bar for quickly creating a snapshot.</code></p>
</td>
</tr>
</table>
<div style="padding:1em 1em 0 0;"><input class="button-primary wpvivid-snapshot-setting-save" type="submit" value="Save Changes"></div>
</div>
<script>
jQuery('.wpvivid-snapshot-setting-save').click(function()
{
wpvivid_snapshot_setting_save();
});
function wpvivid_ajax_snapshot_data_transfer(data_type){
var json = {};
jQuery('input:checkbox[option='+data_type+']').each(function() {
var value = '0';
var key = jQuery(this).prop('name');
if(jQuery(this).prop('checked')) {
value = '1';
}
else {
value = '0';
}
json[key]=value;
});
jQuery('input:radio[option='+data_type+']').each(function() {
if(jQuery(this).prop('checked'))
{
var key = jQuery(this).prop('name');
var value = jQuery(this).prop('value');
json[key]=value;
}
});
jQuery('input:text[option='+data_type+']').each(function(){
var obj = {};
var key = jQuery(this).prop('name');
var value = jQuery(this).val();
json[key]=value;
});
jQuery('input:password[option='+data_type+']').each(function(){
var obj = {};
var key = jQuery(this).prop('name');
var value = jQuery(this).val();
json[key]=value;
});
jQuery('select[option='+data_type+']').each(function(){
var obj = {};
var key = jQuery(this).prop('name');
var value = jQuery(this).val();
json[key]=value;
});
return JSON.stringify(json);
}
function wpvivid_snapshot_setting_save()
{
var setting_data = wpvivid_ajax_snapshot_data_transfer('setting');
var json = JSON.parse(setting_data);
setting_data=JSON.stringify(json);
var ajax_data = {
'action': 'wpvivid_set_snapshot_setting',
'setting': setting_data,
};
jQuery('.wpvivid-snapshot-setting-save').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
jQuery('.wpvivid-snapshot-setting-save').css({'pointer-events': 'auto', 'opacity': '1'});
if (jsonarray.result === 'success')
{
location.reload();
}
else
{
alert(jsonarray.error);
}
}
catch (err)
{
alert(err);
jQuery('.wpvivid-snapshot-setting-save').css({'pointer-events': 'auto', 'opacity': '1'});
}
},function (XMLHttpRequest, textStatus, errorThrown)
{
var error_msg = "request: "+ textStatus + "(" + errorThrown + "): an error occurred when changing snapshot settings. " +
"This error may be request not reaching or server not responding. Please try again later.";
alert(error_msg);
});
}
jQuery(document).ready(function ()
{
jQuery('#wpvivid_snapshot_retention').val("<?php echo esc_attr($snapshot_retention)?>").change();
});
</script>
<?php
}
public function create_snapshot()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(isset($_POST['comment'])&&!empty($_POST['comment']))
{
$comment=sanitize_text_field($_POST['comment']);
}
else
{
$comment='';
}
set_time_limit(300);
$snapshot=new WPvivid_Snapshot_Function_Ex();
$snapshot->check_manual_snapshot();
$ret=$snapshot->create_snapshot('manual',$comment);
if($ret['result']=='success')
{
if($ret['finished']==1)
{
$ret['progress'] = '<p><span class="wpvivid-span-progress"><span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width:100%">100% completed</span></span></p>
<p><span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span><span>Create snapshot completed.</span></p>';
}
else
{
$progress=$snapshot->get_progress();
$ret['progress'] = '<p><span class="wpvivid-span-progress"><span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width:'.$progress['main_percent'].'">'.$progress['main_percent'].' completed</span></span></p>
<p><span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span><span>'.$progress['doing'].'</span></p>';
}
}
echo wp_json_encode($ret);
die();
}
public function get_snapshot_progress()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
set_time_limit(300);
$snapshot=new WPvivid_Snapshot_Function_Ex();
$progress=$snapshot->get_progress();
$ret['progress'] = '<p><span class="wpvivid-span-progress"><span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width:'.$progress['main_percent'].'">'.$progress['main_percent'].' completed</span></span></p>
<p><span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span><span>'.$progress['doing'].'</span></p>';
echo wp_json_encode($ret);
die();
}
public function resume_create_snapshot()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
set_time_limit(300);
$snapshot=new WPvivid_Snapshot_Function_Ex();
$ret=$snapshot->resume_create_snapshot();
if($ret['result']=='success')
{
if($ret['finished']==1)
{
$ret['progress'] = '<p><span class="wpvivid-span-progress"><span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width:100%">100% completed</span></span></p>
<p><span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span><span>Create snapshot completed.</span></p>';
}
else
{
$progress=$snapshot->get_progress();
$ret['progress'] = '<p><span class="wpvivid-span-progress"><span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width:'.$progress['main_percent'].'">'.$progress['main_percent'].' completed</span></span></p>
<p><span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span><span>'.$progress['doing'].'</span></p>';
}
}
echo wp_json_encode($ret);
die();
}
public function restore_snapshot()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(isset($_POST['id']))
{
$snapshot_id=sanitize_text_field($_POST['id']);
set_time_limit(300);
$snapshot=new WPvivid_Snapshot_Function_Ex();
$ret=$snapshot->restore_snapshot($snapshot_id);
if($ret['result']=='success')
{
$ret['progress'] = '<p><span class="wpvivid-span-progress"><span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width:100%">100% completed</span></span></p>
<p><span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span><span>Restoring the snapshot completed.</span></p>';
}
echo wp_json_encode($ret);
}
die();
}
public function get_restore_snapshot_status()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
set_time_limit(300);
$snapshot=new WPvivid_Snapshot_Function_Ex();
$ret=$snapshot->get_restore_task_data();
if($ret['result']!='failed')
{
$finished=true;
$i_sum=count($ret['snapshot_tables']);
$i_finished=0;
foreach ($ret['snapshot_tables'] as $table)
{
if($table['finished']==0)
{
$finished=false;
}
else
{
$i_finished++;
}
}
$i_progress=intval(($i_finished/$i_sum)*100);
$progress['main_percent']=$i_progress.'%';
$progress['doing']="Restoring the snapshot.";
$ret['progress'] = '<p><span class="wpvivid-span-progress"><span class="wpvivid-span-processed-progress wpvivid-span-processed-percent-progress" style="width:'.$progress['main_percent'].'">'.$progress['main_percent'].' completed</span></span></p>
<p><span class="dashicons dashicons-welcome-write-blog wpvivid-dashicons-grey"></span><span>Action:</span><span>'.$progress['doing'].'</span></p>';
$ret['finished']=$finished;
}
echo wp_json_encode($ret);
die();
}
public function delete_snapshot()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(isset($_POST['id']))
{
$snapshot_id=sanitize_text_field($_POST['id']);
set_time_limit(300);
$snapshot=new WPvivid_Snapshot_Function_Ex();
$ret=$snapshot->remove_snapshot($snapshot_id);
if($ret['result']=='success')
{
$snapshot_data=$snapshot->get_snapshots();
$Snapshots_list = new WPvivid_Snapshots_List_Ex();
$Snapshots_list->set_list($snapshot_data);
$Snapshots_list->prepare_items();
ob_start();
$Snapshots_list->display();
$html = ob_get_clean();
$ret['html']=$html;
}
echo wp_json_encode($ret);
}
die();
}
public function check_create_snapshot($check)
{
return true;
}
public function create_snapshot_ex($comment)
{
set_time_limit(300);
$snapshot=new WPvivid_Snapshot_Function_Ex();
$snapshot->create_snapshot('manual',$comment);
}
public function set_setting()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(isset($_POST['setting'])&&!empty($_POST['setting']))
{
$json_setting = sanitize_text_field($_POST['setting']);
$json_setting = stripslashes($json_setting);
$setting = json_decode($json_setting, true);
if (is_null($setting))
{
$ret['result']='failed';
$ret['error']='json decode failed';
echo wp_json_encode($ret);
die();
}
$old_setting=$this->options->get_option('wpvivid_snapshot_setting');
if(empty($setting))
{
$setting=array();
}
if(isset($setting['snapshot_retention']))
{
$old_setting['snapshot_retention']=intval($setting['snapshot_retention']);
}
if(isset($setting['quick_snapshot']))
{
$old_setting['quick_snapshot']=intval($setting['quick_snapshot']);
}
$this->options->update_option('wpvivid_snapshot_setting',$old_setting);
}
$ret['result']='success';
echo wp_json_encode($ret);
die();
}
public function add_sidebar_free()
{
if(defined('WPVIVID_SNAPSHOT_VERSION'))
{
$wpvivid_snapshot_version = WPVIVID_SNAPSHOT_VERSION;
}
else
{
$wpvivid_snapshot_version = WPVIVID_PLUGIN_VERSION;
}
?>
<div class="postbox">
<h2>
<div style="float: left; margin-right: 5px;"><span style="margin: 0; padding: 0"><?php esc_html_e('Current Version: ', 'wpvivid-backuprestore'); ?><?php echo esc_html($wpvivid_snapshot_version); ?></span></div>
<div style="float: left; margin-right: 5px;"><span style="margin: 0; padding: 0">|</span></div>
<div style="float: left; margin-left: 0;">
<span style="margin: 0; padding: 0"><a href="https://wordpress.org/plugins/wpvivid-snapshot-database/#developers" target="_blank" style="text-decoration: none;"><?php esc_html_e('ChangeLog', 'wpvivid-backuprestore'); ?></a></span>
</div>
<div style="clear: both;"></div>
</h2>
</div>
<div id="wpvivid_backup_schedule_part"></div>
<div class="postbox">
<h2><span><?php esc_html_e('Troubleshooting', 'wpvivid-backuprestore'); ?></span></h2>
<div class="inside">
<table class="widefat" cellpadding="0">
<tbody>
<tr class="alternate">
<td class="row-title"><a href="https://docs.wpvivid.com/wpvivid-database-snapshots-create-database-snapshots-wordpress.html" target="_blank"><?php esc_html_e('Create Database Snapshots', 'wpvivid-backuprestore'); ?></a></td>
</tr>
<tr>
<td class="row-title"><a href="https://docs.wpvivid.com/wpvivid-database-snapshots-restore-database-snapshots-wordpress.html" target="_blank"><?php esc_html_e('Restore Database Snapshots', 'wpvivid-backuprestore'); ?></a></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="postbox">
<h2><span><?php esc_html_e('Support', 'wpvivid-backuprestore'); ?></span></h2>
<div class="inside">
<table class="widefat" cellpadding="0">
<tbody>
<tr class="alternate"><td class="row-title"><a href="https://wordpress.org/support/plugin/wpvivid-snapshot-database" target="_blank"><?php esc_html_e('Get Support on Forum', 'wpvivid-backuprestore'); ?></a></td></tr>
</tbody>
</table>
</div>
</div>
<?php
}
public function add_sidebar()
{
if(apply_filters('wpvivid_show_sidebar',true))
{
?>
<div id="postbox-container-1" class="postbox-container">
<div class="meta-box-sortables ui-sortable">
<div class="postbox wpvivid-sidebar">
<h2 style="margin-top:0.5em;">
<span class="dashicons dashicons-book-alt wpvivid-dashicons-orange" ></span>
<span><?php esc_attr_e(
'Documentation', 'WpAdminStyle'
); ?></span></h2>
<div class="inside" style="padding-top:0;">
<ul class="" >
<li>
<span class="dashicons dashicons-camera-alt wpvivid-dashicons-grey"></span>
<a href="https://docs.wpvivid.com/wpvivid-database-snapshots-create-database-snapshots-wordpress.html"><b><?php esc_html_e('Create Database Snapshots', 'wpvivid'); ?></b></a>
<small><span style="float: right;"><a href="#" style="text-decoration: none;"><span class="dashicons dashicons-migrate wpvivid-dashicons-grey"></span></a></span></small><br>
</li>
<li>
<span class="dashicons dashicons-camera-alt wpvivid-dashicons-grey"></span>
<a href="https://docs.wpvivid.com/wpvivid-database-snapshots-restore-database-snapshots-wordpress.html"><b><?php esc_html_e('Restore Database Snapshots', 'wpvivid'); ?></b></a>
<small><span style="float: right;"><a href="#" style="text-decoration: none;"><span class="dashicons dashicons-migrate wpvivid-dashicons-grey"></span></a></span></small><br>
</li>
</ul>
</div>
<h2><span class="dashicons dashicons-businesswoman wpvivid-dashicons-green"></span>
<span><?php esc_attr_e(
'Support', 'WpAdminStyle'
); ?></span></h2>
<div class="inside">
<ul class="">
<li><span class="dashicons dashicons-admin-comments wpvivid-dashicons-green"></span>
<a href="https://wordpress.org/support/plugin/snapshot-database/"><b><?php esc_html_e('Get Support on Forum', 'wpvivid'); ?></b></a>
<br>
<?php esc_html_e('If you need any help with our plugin, start a thread on the plugin support forum and we will respond shortly.', 'wpvivid'); ?>
</li>
</ul>
</div>
</div>
</div>
</div>
<?php
}
}
} includes/class-wpvivid-additional-db-method.php 0000644 00000021357 15132770567 0015652 0 ustar 00 <?php
class WPvivid_Additional_DB_Method
{
private $dbuser;
private $dbpass;
private $dbhost;
private $use_mysqli = false;
private $dbh;
private $has_connected = false;
public $charset;
public $collate;
public function __construct($dbuser, $dbpass, $dbhost){
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->dbhost = $dbhost;
if ( function_exists( 'mysqli_connect' ) ) {
$this->use_mysqli = true;
if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
$this->use_mysqli = ! WP_USE_EXT_MYSQL;
}
}
}
public function wpvivid_parse_db_host( $host ) {
$port = null;
$socket = null;
$is_ipv6 = false;
// First peel off the socket parameter from the right, if it exists.
$socket_pos = strpos( $host, ':/' );
if ( $socket_pos !== false ) {
$socket = substr( $host, $socket_pos + 1 );
$host = substr( $host, 0, $socket_pos );
}
// We need to check for an IPv6 address first.
// An IPv6 address will always contain at least two colons.
if ( substr_count( $host, ':' ) > 1 ) {
$pattern = '#^(?:\[)?(?P<host>[0-9a-fA-F:]+)(?:\]:(?P<port>[\d]+))?#';
$is_ipv6 = true;
} else {
// We seem to be dealing with an IPv4 address.
$pattern = '#^(?P<host>[^:/]*)(?::(?P<port>[\d]+))?#';
}
$matches = array();
$result = preg_match( $pattern, $host, $matches );
if ( 1 !== $result ) {
// Couldn't parse the address, bail.
return false;
}
$host = '';
foreach ( array( 'host', 'port' ) as $component ) {
if ( ! empty( $matches[ $component ] ) ) {
$$component = $matches[ $component ];
}
}
return array( $host, $port, $socket, $is_ipv6 );
}
public function db_version() {
if ( $this->use_mysqli ) {
$server_info = mysqli_get_server_info( $this->dbh );
} else {
$server_info = mysql_get_server_info( $this->dbh );
}
return preg_replace( '/[^0-9.].*/', '', $server_info );
}
public function has_cap( $db_cap ) {
$version = $this->db_version();
switch ( strtolower( $db_cap ) ) {
case 'collation': // @since 2.5.0
case 'group_concat': // @since 2.7.0
case 'subqueries': // @since 2.7.0
return version_compare( $version, '4.1', '>=' );
case 'set_charset':
return version_compare( $version, '5.0.7', '>=' );
case 'utf8mb4': // @since 4.1.0
if ( version_compare( $version, '5.5.3', '<' ) ) {
return false;
}
if ( $this->use_mysqli ) {
$client_version = mysqli_get_client_info();
} else {
$client_version = mysql_get_client_info();
}
/*
* libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
* mysqlnd has supported utf8mb4 since 5.0.9.
*/
if ( false !== strpos( $client_version, 'mysqlnd' ) ) {
$client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
return version_compare( $client_version, '5.0.9', '>=' );
} else {
return version_compare( $client_version, '5.5.3', '>=' );
}
case 'utf8mb4_520': // @since 4.6.0
return version_compare( $version, '5.6', '>=' );
}
return false;
}
public function determine_charset( $charset, $collate ) {
if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
return compact( 'charset', 'collate' );
}
if ( 'utf8' === $charset && $this->has_cap( 'utf8mb4' ) ) {
$charset = 'utf8mb4';
}
if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
$charset = 'utf8';
$collate = str_replace( 'utf8mb4_', 'utf8_', $collate );
}
if ( 'utf8mb4' === $charset ) {
// _general_ is outdated, so we can upgrade it to _unicode_, instead.
if ( ! $collate || 'utf8_general_ci' === $collate ) {
$collate = 'utf8mb4_unicode_ci';
} else {
$collate = str_replace( 'utf8_', 'utf8mb4_', $collate );
}
}
// _unicode_520_ is a better collation, we should use that when it's available.
if ( $this->has_cap( 'utf8mb4_520' ) && 'utf8mb4_unicode_ci' === $collate ) {
$collate = 'utf8mb4_unicode_520_ci';
}
return compact( 'charset', 'collate' );
}
public function init_charset() {
$charset = '';
$collate = '';
if ( function_exists( 'is_multisite' ) && is_multisite() ) {
$charset = 'utf8';
if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
$collate = DB_COLLATE;
} else {
$collate = 'utf8_general_ci';
}
} elseif ( defined( 'DB_COLLATE' ) ) {
$collate = DB_COLLATE;
}
if ( defined( 'DB_CHARSET' ) ) {
$charset = DB_CHARSET;
}
$charset_collate = $this->determine_charset( $charset, $collate );
$this->charset = $charset_collate['charset'];
$this->collate = $charset_collate['collate'];
}
public function wpvivid_do_connect($allow_bail = true){
$new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
$client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
$error_code = '';
$error = 'Unknown Error.';
if ( $this->use_mysqli ) {
$this->dbh = mysqli_init();
$host = $this->dbhost;
$port = null;
$socket = null;
$is_ipv6 = false;
if ( $host_data = $this->wpvivid_parse_db_host( $this->dbhost ) ) {
list( $host, $port, $socket, $is_ipv6 ) = $host_data;
}
if ( $is_ipv6 && extension_loaded( 'mysqlnd' ) ) {
$host = "[$host]";
}
@mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpass, null, $port, $socket, $client_flags );
if ( $this->dbh->connect_errno ) {
$error_code = $this->dbh->connect_errno;
$error = $this->dbh->connect_error;
$this->dbh = null;
$attempt_fallback = true;
if ( $this->has_connected ) {
$attempt_fallback = false;
} elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
$attempt_fallback = false;
} elseif ( ! function_exists( 'mysql_connect' ) ) {
$attempt_fallback = false;
}
if ( $attempt_fallback ) {
$this->use_mysqli = false;
return $this->wpvivid_do_connect( $allow_bail );
}
}
}
else{
$this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpass, $new_link, $client_flags );
}
if($this->dbh){
$this->has_connected = true;
$ret['result'] = WPVIVID_SUCCESS;
}
else{
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = $error_code.': '.$error;
}
return $ret;
}
public function wpvivid_show_additional_databases(){
$query = 'SHOW DATABASES;';
$result = '';
if ( ! empty( $this->dbh ) && $this->use_mysqli ) {
$result = mysqli_query( $this->dbh, $query );
} elseif ( ! empty( $this->dbh ) ) {
$result = mysql_query( $query, $this->dbh );
}
if ( $this->use_mysqli && $result instanceof mysqli_result ) {
while ( $row = mysqli_fetch_object( $result ) ) {
$database_array[] = $row;
}
} elseif ( is_resource( $result ) ) {
while ( $row = mysql_fetch_object( $result ) ) {
$database_array[] = $row;
}
}
if(!empty($database_array)){
foreach ($database_array as $key => $value){
$last_result[] = $value->Database;
}
}
return $last_result;
}
} includes/mu-plugins/a-wpvivid-restore-mu-plugin-check.php 0000644 00000002661 15132770567 0017562 0 ustar 00 <?php
/**
* Plugin Name: WPvivid Restore Must use plugin checker
* Plugin URI: https://wpvivid.com/
* Description:
* Author: WPvivid
*/
// If this file is called directly, abort.
if ( ! defined( "WPINC" ) ) die;
// Load and include
register_shutdown_function('wpvivid_deal_restore_shut_down_error');
// Run
function wpvivid_transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode(DIRECTORY_SEPARATOR,$values);
}
function wpvivid_deal_restore_shut_down_error()
{
$error = error_get_last();
if (!is_null($error)&&($error['type']==E_ERROR||$error['type']==E_COMPILE_ERROR))
{
if(preg_match('/Failed opening required.*$/', $error['message']))
{
$error_file_path=$error['file'];
$error_file_path=wpvivid_transfer_path($error_file_path);
$mu_path = wpvivid_transfer_path(WPMU_PLUGIN_DIR);
if(strpos($error_file_path,$mu_path)!==false)
{
@wp_delete_file($error_file_path);
$restore_task=get_option('wpvivid_restore_task',array());
$restore_task['status']='error';
$restore_task['error']=$error['message'];
$restore_task['error_mu_require_file']=$error['file'];
update_option('wpvivid_restore_task',$restore_task,'no');
}
}
}
die();
}
includes/class-wpvivid-error-log.php 0000644 00000014352 15132770567 0013606 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_error_log
{
public static function create_error_log($log_file_name)
{
$dir=dirname($log_file_name);
$file=basename($log_file_name);
if(!is_dir($dir.DIRECTORY_SEPARATOR.'error'))
{
@mkdir($dir.DIRECTORY_SEPARATOR.'error',0777,true);
//@fopen($dir.DIRECTORY_SEPARATOR.'error'.'/index.html', 'x');
$tempfile=@fopen($dir.DIRECTORY_SEPARATOR.'error'.'/.htaccess', 'x');
if($tempfile)
{
//$text="deny from all";
$text="<IfModule mod_rewrite.c>\r\nRewriteEngine On\r\nRewriteRule .* - [F,L]\r\n</IfModule>";
fwrite($tempfile,$text );
@fclose($tempfile);
}
}
if(!file_exists($log_file_name))
{
return ;
}
if(file_exists($dir.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file))
{
@wp_delete_file($dir.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file);
}
@rename($log_file_name,$dir.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file);
//self::delete_oldest_error_log();
}
public static function create_restore_error_log($log_file_name)
{
$dir=dirname($log_file_name);
if(!is_dir($dir.DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'error'))
{
@mkdir($dir.DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'error',0777,true);
//@fopen($dir.DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'error'.'/index.html', 'x');
$tempfile=@fopen($dir.DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'error'.'/.htaccess', 'x');
if($tempfile)
{
//$text="deny from all";
$text="<IfModule mod_rewrite.c>\r\nRewriteEngine On\r\nRewriteRule .* - [F,L]\r\n</IfModule>";
fwrite($tempfile,$text );
@fclose($tempfile);
}
}
$id = uniqid('wpvivid-');
$file=$id.'_restore_log.txt';
if(file_exists($dir.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file))
{
@wp_delete_file($dir.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file);
}
@copy($log_file_name,$dir.DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'error'.DIRECTORY_SEPARATOR.$file);
//self::delete_oldest_error_log();
}
public static function delete_oldest_error_log()
{
$files=array();
$log=new WPvivid_Log();
$dir=$log->GetSaveLogFolder();
$dir=$dir.'error';
@$handler=opendir($dir);
if($handler===false)
return;
$regex='#^wpvivid.*_log.txt#';
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.DIRECTORY_SEPARATOR.$filename))
{
continue;
}else{
if(preg_match($regex,$filename))
{
$files[$filename] = $dir.DIRECTORY_SEPARATOR.$filename;
}
}
}
}
if($handler)
@closedir($handler);
$oldest=0;
$oldest_filename='';
$max_count=5;
if(sizeof($files)>$max_count)
{
foreach ($files as $file)
{
if($oldest==0)
{
$oldest=filemtime($file);
$oldest_filename=$file;
}
else
{
if($oldest>filemtime($file))
{
$oldest=filemtime($file);
$oldest_filename=$file;
}
}
}
if($oldest_filename!='')
{
@wp_delete_file($oldest_filename);
}
}
}
public static function get_error_log()
{
$log=new WPvivid_Log();
$dir=$log->GetSaveLogFolder();
$dir=$dir.'error';
$files=array();
$handler=opendir($dir);
if($handler === false){
return $files;
}
$regex='#^wpvivid.*_log.txt#';
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.$filename))
{
continue;
}
else{
if(preg_match($regex,$filename))
{
$files[] = $dir.DIRECTORY_SEPARATOR.$filename;
}
}
}
}
if($handler)
@closedir($handler);
return $files;
}
public static function get_staging_error_log()
{
if(!class_exists('WPvivid_Staging_Log_Free'))
include_once WPVIVID_PLUGIN_DIR . '/includes/staging/class-wpvivid-staging-log.php';
$log=new WPvivid_Staging_Log_Free();
$dir=$log->GetSaveLogFolder();
$dir=$dir.'error';
$files=array();
if(is_dir($dir) && file_exists($dir))
{
$handler=opendir($dir);
if($handler === false){
return $files;
}
$regex='#^wpvivid.*_log.txt#';
while(($filename=readdir($handler))!==false)
{
if($filename != "." && $filename != "..")
{
if(is_dir($dir.$filename))
{
continue;
}
else{
if(preg_match($regex,$filename))
{
$files[] = $dir.DIRECTORY_SEPARATOR.$filename;
}
}
}
}
if($handler)
@closedir($handler);
return $files;
}
else
{
return $files;
}
}
} includes/class-wpvivid-interface-mainwp.php 0000644 00000065073 15132770567 0015135 0 ustar 00 <?php
class WPvivid_Interface_MainWP
{
public function __construct(){
$this->load_wpvivid_mainwp_backup_filter();
$this->load_wpvivid_mainwp_side_bar_filter();
$this->load_wpvivid_mainwp_backup_list_filter();
$this->load_wpvivid_mainwp_schedule_filter();
$this->load_wpvivid_mainwp_setting_filter();
$this->load_wpvivid_mainwp_remote_filter();
}
public function load_wpvivid_mainwp_backup_filter(){
add_filter('wpvivid_get_status_mainwp', array($this, 'wpvivid_get_status_mainwp'));
add_filter('wpvivid_get_backup_list_mainwp', array($this, 'wpvivid_get_backup_list_mainwp'));
add_filter('wpvivid_get_backup_schedule_mainwp', array($this, 'wpvivid_get_backup_schedule_mainwp'));
add_filter('wpvivid_get_default_remote_mainwp', array($this, 'wpvivid_get_default_remote_mainwp'));
add_filter('wpvivid_prepare_backup_mainwp', array($this, 'wpvivid_prepare_backup_mainwp'));
add_filter('wpvivid_backup_now_mainwp', array($this, 'wpvivid_backup_now_mainwp'));
add_filter('wpvivid_view_backup_task_log_mainwp', array($this, 'wpvivid_view_backup_task_log_mainwp'));
add_filter('wpvivid_backup_cancel_mainwp', array($this, 'wpvivid_backup_cancel_mainwp'));
add_filter('wpvivid_set_backup_report_addon_mainwp', array($this, 'wpvivid_set_backup_report_addon_mainwp'));
}
public function load_wpvivid_mainwp_side_bar_filter(){
add_filter('wpvivid_read_last_backup_log_mainwp', array($this, 'wpvivid_read_last_backup_log_mainwp'));
}
public function load_wpvivid_mainwp_backup_list_filter(){
add_filter('wpvivid_set_security_lock_mainwp', array($this, 'wpvivid_set_security_lock_mainwp'));
add_filter('wpvivid_view_log_mainwp', array($this, 'wpvivid_view_log_mainwp'));
add_filter('wpvivid_init_download_page_mainwp', array($this, 'wpvivid_init_download_page_mainwp'));
add_filter('wpvivid_prepare_download_backup_mainwp', array($this, 'wpvivid_prepare_download_backup_mainwp'));
add_filter('wpvivid_get_download_task_mainwp', array($this, 'wpvivid_get_download_task_mainwp'));
add_filter('wpvivid_download_backup_mainwp', array($this, 'wpvivid_download_backup_mainwp'));
add_filter('wpvivid_delete_backup_mainwp', array($this, 'wpvivid_delete_backup_mainwp'));
add_filter('wpvivid_delete_backup_array_mainwp', array($this, 'wpvivid_delete_backup_array_mainwp'));
}
public function load_wpvivid_mainwp_schedule_filter(){
add_filter('wpvivid_set_schedule_mainwp', array($this, 'wpvivid_set_schedule_mainwp'));
}
public function load_wpvivid_mainwp_setting_filter(){
add_filter('wpvivid_set_general_setting_mainwp', array($this, 'wpvivid_set_general_setting_mainwp'));
}
public function load_wpvivid_mainwp_remote_filter(){
add_filter('wpvivid_set_remote_mainwp', array($this, 'wpvivid_set_remote_mainwp'));
}
public function wpvivid_get_status_mainwp($data){
$ret['result']='success';
$list_tasks=array();
$tasks=WPvivid_Setting::get_tasks();
foreach ($tasks as $task)
{
$backup = new WPvivid_Backup_Task($task['id']);
$list_tasks[$task['id']]=$backup->get_backup_task_info($task['id']);
if($list_tasks[$task['id']]['task_info']['need_update_last_task']===true){
$task_msg = WPvivid_taskmanager::get_task($task['id']);
WPvivid_Setting::update_option('wpvivid_last_msg',$task_msg);
apply_filters('wpvivid_set_backup_report_addon_mainwp', $task_msg);
}
}
$ret['wpvivid']['task']=$list_tasks;
$backuplist=WPvivid_Backuplist::get_backuplist();
$schedule=WPvivid_Schedule::get_schedule();
$ret['wpvivid']['backup_list']=$backuplist;
$ret['wpvivid']['schedule']=$schedule;
$ret['wpvivid']['schedule']['last_message']=WPvivid_Setting::get_last_backup_message('wpvivid_last_msg');
WPvivid_taskmanager::delete_marked_task();
return $ret;
}
public function wpvivid_get_backup_list_mainwp($data){
$backuplist=WPvivid_Backuplist::get_backuplist();
$ret['result']='success';
$ret['wpvivid']['backup_list']=$backuplist;
return $ret;
}
public function wpvivid_get_backup_schedule_mainwp($data){
$schedule=WPvivid_Schedule::get_schedule();
$ret['result']='success';
$ret['wpvivid']['schedule']=$schedule;
$ret['wpvivid']['schedule']['last_message']=WPvivid_Setting::get_last_backup_message('wpvivid_last_msg');
return $ret;
}
public function wpvivid_get_default_remote_mainwp($data){
global $wpvivid_plugin;
$ret['result']='success';
$ret['remote_storage_type']=$wpvivid_plugin->function_realize->_get_default_remote_storage();
return $ret;
}
public function wpvivid_prepare_backup_mainwp($data){
$backup_options = $data['backup'];
global $wpvivid_plugin;
if(isset($backup_options)&&!empty($backup_options))
{
if (is_null($backup_options))
{
$ret['error']='Invalid parameter param:'.$backup_options;
return $ret;
}
if(!isset($backup_options['type']))
{
$backup_options['type']='Manual';
}
if(!isset($backup_options['backup_files'])||empty($backup_options['backup_files']))
{
$ret['result']='failed';
$ret['error']=__('A backup type is required.', 'wpvivid-backuprestore');
return $ret;
}
if(!isset($backup_options['local'])||!isset($backup_options['remote']))
{
$ret['result']='failed';
$ret['error']=__('Choose at least one storage location for backups.', 'wpvivid-backuprestore');
return $ret;
}
if(empty($backup_options['local']) && empty($backup_options['remote']))
{
$ret['result']='failed';
$ret['error']=__('Choose at least one storage location for backups.', 'wpvivid-backuprestore');
return $ret;
}
if ($backup_options['remote'] === '1')
{
$remote_storage = WPvivid_Setting::get_remote_options();
if ($remote_storage == false)
{
$ret['result']='failed';
$ret['error'] = __('There is no default remote storage configured. Please set it up first.', 'wpvivid-backuprestore');
return $ret;
}
}
if(apply_filters('wpvivid_need_clean_oldest_backup',true,$backup_options))
{
$wpvivid_plugin->clean_oldest_backup();
}
do_action('wpvivid_clean_oldest_backup',$backup_options);
if($wpvivid_plugin->backup2->is_tasks_backup_running())
{
$ret['result']='failed';
$ret['error']=__('A task is already running. Please wait until the running task is complete, and try again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$settings=$wpvivid_plugin->backup2->get_backup_settings($backup_options);
$backup=new WPvivid_Backup_Task_2();
$ret=$backup->new_backup_task($backup_options,$settings);
}
else{
$ret['error']='Error occurred while parsing the request data. Please try to run backup again.';
return $ret;
}
return $ret;
}
public function wpvivid_backup_now_mainwp($data){
global $wpvivid_plugin;
try{
$task_id = $data['task_id'];
$task_id=sanitize_key($task_id);
if (!isset($task_id)||empty($task_id)||!is_string($task_id))
{
$ret['result'] = 'failed';
$ret['error']=__('Error occurred while parsing the request data. Please try to run backup again.', 'wpvivid-backuprestore');
return $ret;
}
if ($wpvivid_plugin->backup2->is_tasks_backup_running($task_id))
{
$ret['result'] = 'failed';
$ret['error'] = __('We detected that there is already a running backup task. Please wait until it completes then try again.', 'wpvivid-backuprestore');
return $ret;
}
$wpvivid_plugin->backup2->update_backup_task_status($task_id,true,'running');
$wpvivid_plugin->flush($task_id, true);
$wpvivid_plugin->backup2->add_monitor_event($task_id);
$wpvivid_plugin->backup2->task=new WPvivid_Backup_Task_2($task_id);
$wpvivid_plugin->backup2->task->set_memory_limit();
$wpvivid_plugin->backup2->task->set_time_limit();
$wpvivid_plugin->wpvivid_log->OpenLogFile($wpvivid_plugin->backup2->task->task['options']['log_file_name']);
$wpvivid_plugin->wpvivid_log->WriteLog('Start backing up.','notice');
$wpvivid_plugin->wpvivid_log->WriteLogHander();
if(!$wpvivid_plugin->backup2->task->is_backup_finished())
{
$ret=$wpvivid_plugin->backup2->backup();
$wpvivid_plugin->backup2->task->clear_cache();
if($ret['result']!='success')
{
$wpvivid_plugin->wpvivid_log->WriteLog('Backup the file ends with an error '. $ret['error'],'error');
$wpvivid_plugin->backup2->task->update_backup_task_status(false,'error',false,false,$ret['error']);
do_action('wpvivid_handle_backup_2_failed', $task_id);
$wpvivid_plugin->backup2->clear_monitor_schedule($task_id);
$ret['result'] = 'failed';
$ret['error']='Backup the file ends with an error '. $ret['error'];
return $ret;
}
}
if($wpvivid_plugin->backup2->task->need_upload())
{
$ret=$wpvivid_plugin->backup2->upload($task_id);
if($ret['result'] == WPVIVID_SUCCESS)
{
do_action('wpvivid_handle_backup_2_succeed',$task_id);
$wpvivid_plugin->backup2->update_backup_task_status($task_id,false,'completed');
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Uploading the file ends with an error '. $ret['error'], 'error');
do_action('wpvivid_handle_backup_2_failed',$task_id);
}
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Backup completed.','notice');
do_action('wpvivid_handle_backup_2_succeed', $task_id);
$wpvivid_plugin->backup2->update_backup_task_status($task_id,false,'completed');
}
$wpvivid_plugin->backup2->clear_monitor_schedule($task_id);
$ret['result']='success';
return $ret;
}
catch (Exception $error)
{
//catch error and stop task recording history
$message = 'An exception has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
error_log($message);
WPvivid_taskmanager::update_backup_task_status($task_id,false,'error',false,false,$message);
$wpvivid_plugin->wpvivid_log->WriteLog($message,'error');
do_action('wpvivid_handle_backup_2_failed',$task_id);
$ret['result'] = 'failed';
$ret['error']=$message;
return $ret;
}
}
public function wpvivid_view_backup_task_log_mainwp($data){
$backup_task_id = $data['id'];
global $wpvivid_plugin;
if (!isset($backup_task_id)||empty($backup_task_id)||!is_string($backup_task_id)){
$ret['error']='Reading the log failed. Please try again.';
return $ret;
}
$backup_task_id = sanitize_key($backup_task_id);
$ret=$wpvivid_plugin->function_realize->_get_log_file('tasklog', $backup_task_id);
if($ret['result'] == 'success') {
$file = fopen($ret['log_file'], 'r');
if (!$file) {
$ret['result'] = 'failed';
$ret['error'] = __('Unable to open the log file.', 'wpvivid-backuprestore');
return $ret;
}
$buffer = '';
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
$ret['result'] = 'success';
$ret['data'] = $buffer;
}
else{
$ret['error']='Unknown error';
}
return $ret;
}
public function wpvivid_backup_cancel_mainwp($data){
global $wpvivid_plugin;
$ret=$wpvivid_plugin->function_realize->_backup_cancel();
return $ret;
}
public function wpvivid_set_backup_report_addon_mainwp($data){
if(isset($data['id']))
{
$task_id = $data['id'];
$option = array();
$option[$task_id]['task_id'] = $task_id;
$option[$task_id]['backup_time'] = $data['status']['start_time'];
if($data['status']['str'] == 'completed'){
$option[$task_id]['status'] = 'Succeeded';
}
elseif($data['status']['str'] == 'error'){
$option[$task_id]['status'] = 'Failed, '.$data['status']['error'];
}
elseif($data['status']['str'] == 'cancel'){
$option[$task_id]['status'] = 'Canceled';
}
else{
$option[$task_id]['status'] = 'The last backup message not found.';
}
$backup_reports = get_option('wpvivid_backup_reports', array());
if(!empty($backup_reports)){
foreach ($option as $key => $value){
$backup_reports[$key] = $value;
update_option('wpvivid_backup_reports', $backup_reports, 'no');
}
}
else{
update_option('wpvivid_backup_reports', $option, 'no');
}
}
}
public function wpvivid_read_last_backup_log_mainwp($data){
$log_file_name = $data['log_file_name'];
global $wpvivid_plugin;
if(!isset($log_file_name)||empty($log_file_name)||!is_string($log_file_name))
{
$ret['result']='failed';
$ret['error']=__('Reading the log failed. Please try again.', 'wpvivid-backuprestore');
return $ret;
}
$log_file_name=sanitize_text_field($log_file_name);
$ret=$wpvivid_plugin->function_realize->_get_log_file('lastlog', $log_file_name);
if($ret['result'] == 'success') {
$file = fopen($ret['log_file'], 'r');
if (!$file) {
$ret['result'] = 'failed';
$ret['error'] = __('Unable to open the log file.', 'wpvivid-backuprestore');
return $ret;
}
$buffer = '';
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
$ret['result'] = 'success';
$ret['data'] = $buffer;
}
else{
$ret['error']='Unknown error';
}
return $ret;
}
public function wpvivid_set_security_lock_mainwp($data){
$backup_id = $data['backup_id'];
$lock = $data['lock'];
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id)){
$ret['error']='Backup id not found';
return $ret;
}
if(!isset($lock)){
$ret['error']='Invalid parameter param: lock';
return $ret;
}
$backup_id=sanitize_key($backup_id);
if($lock==0||$lock==1) {
}
else {
$lock=0;
}
WPvivid_Backuplist::set_security_lock($backup_id,$lock);
$backuplist=WPvivid_Backuplist::get_backuplist();
$ret['wpvivid']['backup_list']=$backuplist;
return $ret;
}
public function wpvivid_view_log_mainwp($data){
$backup_id = $data['id'];
global $wpvivid_plugin;
if (!isset($backup_id)||empty($backup_id)||!is_string($backup_id)){
$ret['error']='Backup id not found';
return $ret;
}
$backup_id=sanitize_key($backup_id);
$ret=$wpvivid_plugin->function_realize->_get_log_file('backuplist', $backup_id);
if($ret['result'] == 'success') {
$file = fopen($ret['log_file'], 'r');
if (!$file) {
$ret['result'] = 'failed';
$ret['error'] = __('Unable to open the log file.', 'wpvivid-backuprestore');
return $ret;
}
$buffer = '';
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
$ret['data'] = $buffer;
}
else{
$ret['error']='Unknown error';
}
return $ret;
}
public function wpvivid_init_download_page_mainwp($data){
$backup_id = $data['backup_id'];
global $wpvivid_plugin;
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id)) {
$ret['error']='Invalid parameter param:'.$backup_id;
return $ret;
}
else {
$backup_id=sanitize_key($backup_id);
return $wpvivid_plugin->init_download($backup_id);
}
}
public function wpvivid_prepare_download_backup_mainwp($data){
$backup_id = $data['backup_id'];
$file_name = $data['file_name'];
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id))
{
$ret['error']='Invalid parameter param:'.$backup_id;
return $ret;
}
if(!isset($file_name)||empty($file_name)||!is_string($file_name))
{
$ret['error']='Invalid parameter param:'.$file_name;
return $ret;
}
$download_info=array();
$download_info['backup_id']=sanitize_key($backup_id);
$download_info['file_name'] = $file_name;
@set_time_limit(600);
if (session_id())
session_write_close();
try
{
$downloader=new WPvivid_downloader();
$downloader->ready_download($download_info);
}
catch (Exception $e)
{
$message = 'A exception ('.get_class($e).') occurred '.$e->getMessage().' (Code: '.$e->getCode().', line '.$e->getLine().' in '.$e->getFile().')';
error_log($message);
return array('error'=>$message);
}
catch (Error $e)
{
$message = 'A error ('.get_class($e).') has occurred: '.$e->getMessage().' (Code: '.$e->getCode().', line '.$e->getLine().' in '.$e->getFile().')';
error_log($message);
return array('error'=>$message);
}
$ret['result']='success';
return $ret;
}
public function wpvivid_get_download_task_mainwp($data){
$backup_id = $data['backup_id'];
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id)) {
$ret['error']='Invalid parameter param:'.$backup_id;
return $ret;
}
else {
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
if ($backup === false) {
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'backup id not found';
return $ret;
}
$backup_item = new WPvivid_Backup_Item($backup);
$ret = $backup_item->update_download_page($backup_id);
return $ret;
}
}
public function wpvivid_download_backup_mainwp($data){
$backup_id = $data['backup_id'];
$file_name = $data['file_name'];
global $wpvivid_plugin;
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id)) {
$ret['error']='Invalid parameter param: backup_id';
return $ret;
}
if(!isset($file_name)||empty($file_name)||!is_string($file_name)) {
$ret['error']='Invalid parameter param: file_name';
return $ret;
}
$backup_id=sanitize_key($backup_id);
$cache=WPvivid_taskmanager::get_download_cache($backup_id);
if($cache===false) {
$wpvivid_plugin->init_download($backup_id);
$cache=WPvivid_taskmanager::get_download_cache($backup_id);
}
$path=false;
if(array_key_exists($file_name,$cache['files'])) {
if($cache['files'][$file_name]['status']=='completed') {
$path=$cache['files'][$file_name]['download_path'];
$download_url = $cache['files'][$file_name]['download_url'];
}
}
if($path!==false) {
if (file_exists($path)) {
$ret['download_url'] = $download_url;
$ret['size'] = filesize($path);
}
}
return $ret;
}
public function wpvivid_delete_backup_mainwp($data){
$backup_id = $data['backup_id'];
$force_del = $data['force'];
global $wpvivid_plugin;
if(!isset($backup_id)||empty($backup_id)||!is_string($backup_id)) {
$ret['error']='Invalid parameter param: backup_id.';
return $ret;
}
if(!isset($force_del)){
$ret['error']='Invalid parameter param: force.';
return $ret;
}
if($force_del==0||$force_del==1) {
}
else {
$force_del=0;
}
$backup_id=sanitize_key($backup_id);
$ret=$wpvivid_plugin->delete_backup_by_id($backup_id, $force_del);
$backuplist=WPvivid_Backuplist::get_backuplist();
$ret['wpvivid']['backup_list']=$backuplist;
return $ret;
}
public function wpvivid_delete_backup_array_mainwp($data){
$backup_id_array = $data['backup_id'];
global $wpvivid_plugin;
if(!isset($backup_id_array)||empty($backup_id_array)||!is_array($backup_id_array)) {
$ret['error']='Invalid parameter param: backup_id';
return $ret;
}
$ret=array();
foreach($backup_id_array as $backup_id)
{
$backup_id=sanitize_key($backup_id);
$ret=$wpvivid_plugin->delete_backup_by_id($backup_id);
}
$backuplist=WPvivid_Backuplist::get_backuplist();
$ret['wpvivid']['backup_list']=$backuplist;
return $ret;
}
public function wpvivid_set_schedule_mainwp($data){
$schedule = $data['schedule'];
$ret=array();
try {
if(isset($schedule)&&!empty($schedule)) {
$json = $schedule;
$json = stripslashes($json);
$schedule = json_decode($json, true);
if (is_null($schedule)) {
$ret['error']='bad parameter';
return $ret;
}
$ret=WPvivid_Schedule::set_schedule_ex($schedule);
if($ret['result']!='success') {
return $ret;
}
}
$ret['result']='success';
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('error'=>$message);
}
return $ret;
}
public function wpvivid_set_general_setting_mainwp($data){
$setting = $data['setting'];
$ret=array();
try {
if(isset($setting)&&!empty($setting)) {
$json_setting = $setting;
$json_setting = stripslashes($json_setting);
$setting = json_decode($json_setting, true);
if (is_null($setting)) {
$ret['error']='bad parameter';
return $ret;
}
if(isset($setting['wpvivid_compress_setting']['max_file_size']))
{
$setting['wpvivid_common_setting']['max_file_size'] = str_replace('M', '', $setting['wpvivid_compress_setting']['max_file_size']);
}
if(isset($setting['wpvivid_compress_setting']['exclude_file_size']))
{
$setting['wpvivid_common_setting']['exclude_file_size'] = $setting['wpvivid_compress_setting']['exclude_file_size'];
}
WPvivid_Setting::update_setting($setting);
}
$ret['result']='success';
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('error'=>$message);
}
return $ret;
}
public function wpvivid_set_remote_mainwp($data){
$remote = $data['remote'];
global $wpvivid_plugin;
$ret=array();
try {
if(isset($remote)&&!empty($remote)) {
$json = $remote;
$json = stripslashes($json);
$remote = json_decode($json, true);
if (is_null($remote)) {
$ret['error']='bad parameter';
return $ret;
}
$wpvivid_plugin->function_realize->_set_remote($remote);
}
$ret['result']='success';
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
return array('error'=>$message);
}
return $ret;
}
} includes/zip/class-wpvivid-pclzip.php 0000644 00000615546 15132770567 0014015 0 ustar 00 <?php
// --------------------------------------------------------------------------------
// PhpConcept Library - Zip Module 2.8.2
// --------------------------------------------------------------------------------
// License GNU/LGPL - Vincent Blavet - August 2009
// http://www.phpconcept.net
// --------------------------------------------------------------------------------
//
// Presentation :
// PclZip is a PHP library that manage ZIP archives.
// So far tests show that archives generated by PclZip are readable by
// WinZip application and other tools.
//
// Description :
// See readme.txt and http://www.phpconcept.net
//
// Warning :
// This library and the associated files are non commercial, non professional
// work.
// It should not have unexpected results. However if any damage is caused by
// this software the author can not be responsible.
// The use of this software is at the risk of the user.
//
// --------------------------------------------------------------------------------
// $Id: pclzip.lib.php,v 1.60 2009/09/30 21:01:04 vblavet Exp $
// --------------------------------------------------------------------------------
// ----- Constants
if (!defined('PCLZIP_READ_BLOCK_SIZE')) {
define( 'PCLZIP_READ_BLOCK_SIZE', 2048 );
}
// ----- File list separator
// In version 1.x of PclZip, the separator for file list is a space
// (which is not a very smart choice, specifically for windows paths !).
// A better separator should be a comma (,). This constant gives you the
// ability to change that.
// However notice that changing this value, may have impact on existing
// scripts, using space separated filenames.
// Recommended values for compatibility with older versions :
//define( 'PCLZIP_SEPARATOR', ' ' );
// Recommended values for smart separation of filenames.
if (!defined('PCLZIP_SEPARATOR')) {
define( 'PCLZIP_SEPARATOR', ',' );
}
// ----- Error configuration
// 0 : PclZip Class integrated error handling
// 1 : PclError external library error handling. By enabling this
// you must ensure that you have included PclError library.
// [2,...] : reserved for futur use
if (!defined('PCLZIP_ERROR_EXTERNAL')) {
define( 'PCLZIP_ERROR_EXTERNAL', 0 );
}
// ----- Optional static temporary directory
// By default temporary files are generated in the script current
// path.
// If defined :
// - MUST BE terminated by a '/'.
// - MUST be a valid, already created directory
// Samples :
// define( 'PCLZIP_TEMPORARY_DIR', '/temp/' );
// define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' );
if (!defined('PCLZIP_TEMPORARY_DIR')) {
define( 'PCLZIP_TEMPORARY_DIR', '' );
}
// ----- Optional threshold ratio for use of temporary files
// Pclzip sense the size of the file to add/extract and decide to
// use or not temporary file. The algorithm is looking for
// memory_limit of PHP and apply a ratio.
// threshold = memory_limit * ratio.
// Recommended values are under 0.5. Default 0.47.
// Samples :
// define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.5 );
if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) {
define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.47 );
}
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED *****
// --------------------------------------------------------------------------------
// ----- Global variables
$g_pclzip_version = "2.8.2";
// ----- Error codes
// -1 : Unable to open file in binary write mode
// -2 : Unable to open file in binary read mode
// -3 : Invalid parameters
// -4 : File does not exist
// -5 : Filename is too long (max. 255)
// -6 : Not a valid zip file
// -7 : Invalid extracted file size
// -8 : Unable to create directory
// -9 : Invalid archive extension
// -10 : Invalid archive format
// -11 : Unable to delete file (wp_delete_file)
// -12 : Unable to rename file (rename)
// -13 : Invalid header checksum
// -14 : Invalid archive size
define( 'WPVIVID_PCLZIP_ERR_USER_ABORTED', 2 );
define( 'WPVIVID_PCLZIP_ERR_NO_ERROR', 0 );
define( 'WPVIVID_PCLZIP_ERR_WRITE_OPEN_FAIL', -1 );
define( 'WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL', -2 );
define( 'WPVIVID_PCLZIP_ERR_INVALID_PARAMETER', -3 );
define( 'WPVIVID_PCLZIP_ERR_MISSING_FILE', -4 );
define( 'WPVIVID_PCLZIP_ERR_FILENAME_TOO_LONG', -5 );
define( 'WPVIVID_PCLZIP_ERR_INVALID_ZIP', -6 );
define( 'WPVIVID_PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 );
define( 'WPVIVID_PCLZIP_ERR_DIR_CREATE_FAIL', -8 );
define( 'WPVIVID_PCLZIP_ERR_BAD_EXTENSION', -9 );
define( 'WPVIVID_PCLZIP_ERR_BAD_FORMAT', -10 );
define( 'WPVIVID_PCLZIP_ERR_DELETE_FILE_FAIL', -11 );
define( 'WPVIVID_PCLZIP_ERR_RENAME_FILE_FAIL', -12 );
define( 'WPVIVID_PCLZIP_ERR_BAD_CHECKSUM', -13 );
define( 'WPVIVID_PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 );
define( 'WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE', -15 );
define( 'WPVIVID_PCLZIP_ERR_INVALID_OPTION_VALUE', -16 );
define( 'WPVIVID_PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 );
define( 'WPVIVID_PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 );
define( 'WPVIVID_PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 );
define( 'WPVIVID_PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20 );
define( 'WPVIVID_PCLZIP_ERR_DIRECTORY_RESTRICTION', -21 );
// ----- Options values
define( 'WPVIVID_PCLZIP_OPT_PATH', 77001 );
define( 'WPVIVID_PCLZIP_OPT_ADD_PATH', 77002 );
define( 'WPVIVID_PCLZIP_OPT_REMOVE_PATH', 77003 );
define( 'WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH', 77004 );
define( 'WPVIVID_PCLZIP_OPT_SET_CHMOD', 77005 );
define( 'WPVIVID_PCLZIP_OPT_EXTRACT_AS_STRING', 77006 );
define( 'WPVIVID_PCLZIP_OPT_NO_COMPRESSION', 77007 );
define( 'WPVIVID_PCLZIP_OPT_BY_NAME', 77008 );
define( 'WPVIVID_PCLZIP_OPT_BY_INDEX', 77009 );
define( 'WPVIVID_PCLZIP_OPT_BY_EREG', 77010 );
define( 'WPVIVID_PCLZIP_OPT_BY_PREG', 77011 );
define( 'WPVIVID_PCLZIP_OPT_COMMENT', 77012 );
define( 'WPVIVID_PCLZIP_OPT_ADD_COMMENT', 77013 );
define( 'WPVIVID_PCLZIP_OPT_PREPEND_COMMENT', 77014 );
define( 'WPVIVID_PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 );
define( 'WPVIVID_PCLZIP_OPT_REPLACE_NEWER', 77016 );
define( 'WPVIVID_PCLZIP_OPT_STOP_ON_ERROR', 77017 );
// Having big trouble with crypt. Need to multiply 2 long int
// which is not correctly supported by PHP ...
//define( 'PCLZIP_OPT_CRYPT', 77018 );
define( 'WPVIVID_PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019 );
define( 'WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020 );
define( 'WPVIVID_PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020 ); // alias
define( 'WPVIVID_PCLZIP_OPT_TEMP_FILE_ON', 77021 );
define( 'WPVIVID_PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021 ); // alias
define( 'WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF', 77022 );
define( 'WPVIVID_PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022 ); // alias
// ----- File description attributes
define( 'WPVIVID_PCLZIP_ATT_FILE_NAME', 79001 );
define( 'WPVIVID_PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002 );
define( 'WPVIVID_PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003 );
define( 'WPVIVID_PCLZIP_ATT_FILE_MTIME', 79004 );
define( 'WPVIVID_PCLZIP_ATT_FILE_CONTENT', 79005 );
define( 'WPVIVID_PCLZIP_ATT_FILE_COMMENT', 79006 );
// ----- Call backs values
define( 'WPVIVID_PCLZIP_CB_PRE_EXTRACT', 78001 );
define( 'WPVIVID_PCLZIP_CB_POST_EXTRACT', 78002 );
define( 'WPVIVID_PCLZIP_CB_PRE_ADD', 78003 );
define( 'WPVIVID_PCLZIP_CB_POST_ADD', 78004 );
/* For futur use
define( 'PCLZIP_CB_PRE_LIST', 78005 );
define( 'PCLZIP_CB_POST_LIST', 78006 );
define( 'PCLZIP_CB_PRE_DELETE', 78007 );
define( 'PCLZIP_CB_POST_DELETE', 78008 );
*/
// --------------------------------------------------------------------------------
// Class : PclZip
// Description :
// PclZip is the class that represent a Zip archive.
// The public methods allow the manipulation of the archive.
// Attributes :
// Attributes must not be accessed directly.
// Methods :
// PclZip() : Object creator
// create() : Creates the Zip archive
// listContent() : List the content of the Zip archive
// extract() : Extract the content of the archive
// properties() : List the properties of the archive
// --------------------------------------------------------------------------------
class WPvivid_PclZip
{
// ----- Filename of the zip file
var $zipname = '';
// ----- File descriptor of the zip file
var $zip_fd = 0;
// ----- Internal error handling
var $error_code = 1;
var $error_string = '';
// ----- Current status of the magic_quotes_runtime
// This value store the php configuration for magic_quotes
// The class can then disable the magic_quotes and reset it after
var $magic_quotes_status;
// --------------------------------------------------------------------------------
// Function : PclZip()
// Description :
// Creates a PclZip object and set the name of the associated Zip archive
// filename.
// Note that no real action is taken, if the archive does not exist it is not
// created. Use create() for that.
// --------------------------------------------------------------------------------
function __construct($p_zipname)
{
// ----- Tests the zlib
if (!function_exists('gzopen'))
{
die('Abort '.basename(__FILE__).' : Missing zlib extensions');
}
// ----- Set the attributes
$this->zipname = $p_zipname;
$this->zip_fd = 0;
$this->magic_quotes_status = -1;
// ----- Return
return;
}
public function PclZip($p_zipname) {
self::__construct($p_zipname);
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// create($p_filelist, $p_add_dir="", $p_remove_dir="")
// create($p_filelist, $p_option, $p_option_value, ...)
// Description :
// This method supports two different synopsis. The first one is historical.
// This method creates a Zip Archive. The Zip file is created in the
// filesystem. The files and directories indicated in $p_filelist
// are added in the archive. See the parameters description for the
// supported format of $p_filelist.
// When a directory is in the list, the directory and its content is added
// in the archive.
// In this synopsis, the function takes an optional variable list of
// options. See below the supported options.
// Parameters :
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or one directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_add_dir : A path to add before the real path of the archived file,
// in order to have it memorized in the archive.
// $p_remove_dir : A path to remove from the real path of the file to archive,
// in order to have a shorter path memorized in the archive.
// When $p_add_dir and $p_remove_dir are set, $p_remove_dir
// is removed first, before $p_add_dir is added.
// Options :
// WPVIVID_PCLZIP_OPT_ADD_PATH :
// WPVIVID_PCLZIP_OPT_REMOVE_PATH :
// WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH :
// WPVIVID_PCLZIP_OPT_COMMENT :
// WPVIVID_PCLZIP_CB_PRE_ADD :
// WPVIVID_PCLZIP_CB_POST_ADD :
// Return Values :
// 0 on failure,
// The list of the added files, with a status of the add action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function create($p_filelist)
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Set default values
$v_options = array();
$v_options[WPVIVID_PCLZIP_OPT_NO_COMPRESSION] = FALSE;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove from the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (WPVIVID_PCLZIP_OPT_REMOVE_PATH => 'optional',
WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
WPVIVID_PCLZIP_OPT_ADD_PATH => 'optional',
WPVIVID_PCLZIP_CB_PRE_ADD => 'optional',
WPVIVID_PCLZIP_CB_POST_ADD => 'optional',
WPVIVID_PCLZIP_OPT_NO_COMPRESSION => 'optional',
WPVIVID_PCLZIP_OPT_COMMENT => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_ON => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
//, PCLZIP_OPT_CRYPT => 'optional'
));
if ($v_result != 1) {
return 0;
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_options[WPVIVID_PCLZIP_OPT_ADD_PATH] = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_options[WPVIVID_PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
}
else if ($v_size > 2) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER,
"Invalid number / type of arguments");
return 0;
}
}
}
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Init
$v_string_list = array();
$v_att_list = array();
$v_filedescr_list = array();
$p_result_list = array();
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Look if the first element is also an array
// This will mean that this is a file description entry
if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
$v_att_list = $p_filelist;
}
// ----- The list is a list of string names
else {
$v_string_list = $p_filelist;
}
}
// ----- Look if the $p_filelist is a string
else if (is_string($p_filelist)) {
// ----- Create a list from the string
$v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
}
// ----- Invalid variable type for $p_filelist
else {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist");
return 0;
}
// ----- Reformat the string list
if (sizeof($v_string_list) != 0) {
foreach ($v_string_list as $v_string) {
if ($v_string != '') {
$v_att_list[][WPVIVID_PCLZIP_ATT_FILE_NAME] = $v_string;
}
else {
}
}
}
// ----- For each file in the list check the attributes
$v_supported_attributes
= array ( WPVIVID_PCLZIP_ATT_FILE_NAME => 'mandatory'
,WPVIVID_PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
,WPVIVID_PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
,WPVIVID_PCLZIP_ATT_FILE_MTIME => 'optional'
,WPVIVID_PCLZIP_ATT_FILE_CONTENT => 'optional'
,WPVIVID_PCLZIP_ATT_FILE_COMMENT => 'optional'
);
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
$v_options,
$v_supported_attributes);
if ($v_result != 1) {
return 0;
}
}
// ----- Expand the filelist (expand directories)
$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Call the create fct
$v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Return
return $p_result_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// add($p_filelist, $p_add_dir="", $p_remove_dir="")
// add($p_filelist, $p_option, $p_option_value, ...)
// Description :
// This method supports two synopsis. The first one is historical.
// This methods add the list of files in an existing archive.
// If a file with the same name already exists, it is added at the end of the
// archive, the first one is still present.
// If the archive does not exist, it is created.
// Parameters :
// $p_filelist : An array containing file or directory names, or
// a string containing one filename or one directory name, or
// a string containing a list of filenames and/or directory
// names separated by spaces.
// $p_add_dir : A path to add before the real path of the archived file,
// in order to have it memorized in the archive.
// $p_remove_dir : A path to remove from the real path of the file to archive,
// in order to have a shorter path memorized in the archive.
// When $p_add_dir and $p_remove_dir are set, $p_remove_dir
// is removed first, before $p_add_dir is added.
// Options :
// WPVIVID_PCLZIP_OPT_ADD_PATH :
// WPVIVID_PCLZIP_OPT_REMOVE_PATH :
// WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH :
// WPVIVID_PCLZIP_OPT_COMMENT :
// WPVIVID_PCLZIP_OPT_ADD_COMMENT :
// WPVIVID_PCLZIP_OPT_PREPEND_COMMENT :
// WPVIVID_PCLZIP_CB_PRE_ADD :
// WPVIVID_PCLZIP_CB_POST_ADD :
// Return Values :
// 0 on failure,
// The list of the added files, with a status of the add action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function add($p_filelist)
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Set default values
$v_options = array();
$v_options[WPVIVID_PCLZIP_OPT_NO_COMPRESSION] = FALSE;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove form the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (WPVIVID_PCLZIP_OPT_REMOVE_PATH => 'optional',
WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
WPVIVID_PCLZIP_OPT_ADD_PATH => 'optional',
WPVIVID_PCLZIP_CB_PRE_ADD => 'optional',
WPVIVID_PCLZIP_CB_POST_ADD => 'optional',
WPVIVID_PCLZIP_OPT_NO_COMPRESSION => 'optional',
WPVIVID_PCLZIP_OPT_COMMENT => 'optional',
WPVIVID_PCLZIP_OPT_ADD_COMMENT => 'optional',
WPVIVID_PCLZIP_OPT_PREPEND_COMMENT => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_ON => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
//, PCLZIP_OPT_CRYPT => 'optional'
));
if ($v_result != 1) {
return 0;
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_options[WPVIVID_PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_options[WPVIVID_PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
return 0;
}
}
}
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Init
$v_string_list = array();
$v_att_list = array();
$v_filedescr_list = array();
$p_result_list = array();
// ----- Look if the $p_filelist is really an array
if (is_array($p_filelist)) {
// ----- Look if the first element is also an array
// This will mean that this is a file description entry
if (isset($p_filelist[0]) && is_array($p_filelist[0])) {
$v_att_list = $p_filelist;
}
// ----- The list is a list of string names
else {
$v_string_list = $p_filelist;
}
}
// ----- Look if the $p_filelist is a string
else if (is_string($p_filelist)) {
// ----- Create a list from the string
$v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist);
}
// ----- Invalid variable type for $p_filelist
else {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist");
return 0;
}
// ----- Reformat the string list
if (sizeof($v_string_list) != 0) {
foreach ($v_string_list as $v_string) {
$v_att_list[][WPVIVID_PCLZIP_ATT_FILE_NAME] = $v_string;
}
}
// ----- For each file in the list check the attributes
$v_supported_attributes
= array ( WPVIVID_PCLZIP_ATT_FILE_NAME => 'mandatory'
,WPVIVID_PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional'
,WPVIVID_PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional'
,WPVIVID_PCLZIP_ATT_FILE_MTIME => 'optional'
,WPVIVID_PCLZIP_ATT_FILE_CONTENT => 'optional'
,WPVIVID_PCLZIP_ATT_FILE_COMMENT => 'optional'
);
foreach ($v_att_list as $v_entry) {
$v_result = $this->privFileDescrParseAtt($v_entry,
$v_filedescr_list[],
$v_options,
$v_supported_attributes);
if ($v_result != 1) {
return 0;
}
}
// ----- Expand the filelist (expand directories)
$v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Call the create fct
$v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options);
if ($v_result != 1) {
return 0;
}
// ----- Return
return $p_result_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : listContent()
// Description :
// This public method, gives the list of the files and directories, with their
// properties.
// The properties of each entries in the list are (used also in other functions) :
// filename : Name of the file. For a create or add action it is the filename
// given by the user. For an extract function it is the filename
// of the extracted file.
// stored_filename : Name of the file / directory stored in the archive.
// size : Size of the stored file.
// compressed_size : Size of the file's data compressed in the archive
// (without the headers overhead)
// mtime : Last known modification date of the file (UNIX timestamp)
// comment : Comment associated with the file
// folder : true | false
// index : index of the file in the archive
// status : status of the action (depending of the action) :
// Values are :
// ok : OK !
// filtered : the file / dir is not extracted (filtered by user)
// already_a_directory : the file can not be extracted because a
// directory with the same name already exists
// write_protected : the file can not be extracted because a file
// with the same name already exists and is
// write protected
// newer_exist : the file was not extracted because a newer file exists
// path_creation_fail : the file is not extracted because the folder
// does not exist and can not be created
// write_error : the file was not extracted because there was a
// error while writing the file
// read_error : the file was not extracted because there was a error
// while reading the file
// invalid_header : the file was not extracted because of an archive
// format error (bad file header)
// Note that each time a method can continue operating when there
// is an action error on a file, the error is only logged in the file status.
// Return Values :
// 0 on an unrecoverable failure,
// The list of the files in the archive.
// --------------------------------------------------------------------------------
function listContent()
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Call the extracting fct
$p_list = array();
if (($v_result = $this->privList($p_list)) != 1)
{
unset($p_list);
return(0);
}
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// extract($p_path="./", $p_remove_path="")
// extract([$p_option, $p_option_value, ...])
// Description :
// This method supports two synopsis. The first one is historical.
// This method extract all the files / directories from the archive to the
// folder indicated in $p_path.
// If you want to ignore the 'root' part of path of the memorized files
// you can indicate this in the optional $p_remove_path parameter.
// By default, if a newer file with the same name already exists, the
// file is not extracted.
//
// If both WPVIVID_PCLZIP_OPT_PATH and WPVIVID_PCLZIP_OPT_ADD_PATH options
// are used, the path indicated in WPVIVID_PCLZIP_OPT_ADD_PATH is append
// at the end of the path value of WPVIVID_PCLZIP_OPT_PATH.
// Parameters :
// $p_path : Path where the files and directories are to be extracted
// $p_remove_path : First part ('root' part) of the memorized path
// (if any similar) to remove while extracting.
// Options :
// WPVIVID_PCLZIP_OPT_PATH :
// WPVIVID_PCLZIP_OPT_ADD_PATH :
// WPVIVID_PCLZIP_OPT_REMOVE_PATH :
// WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH :
// WPVIVID_PCLZIP_CB_PRE_EXTRACT :
// WPVIVID_PCLZIP_CB_POST_EXTRACT :
// Return Values :
// 0 or a negative value on failure,
// The list of the extracted files, with a status of the action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function extract()
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Set default values
$v_options = array();
// $v_path = "./";
$v_path = '';
$v_remove_path = "";
$v_remove_all_path = false;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Default values for option
$v_options[WPVIVID_PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
// ----- Look for arguments
if ($v_size > 0) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (WPVIVID_PCLZIP_OPT_PATH => 'optional',
WPVIVID_PCLZIP_OPT_REMOVE_PATH => 'optional',
WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
WPVIVID_PCLZIP_OPT_ADD_PATH => 'optional',
WPVIVID_PCLZIP_CB_PRE_EXTRACT => 'optional',
WPVIVID_PCLZIP_CB_POST_EXTRACT => 'optional',
WPVIVID_PCLZIP_OPT_SET_CHMOD => 'optional',
WPVIVID_PCLZIP_OPT_BY_NAME => 'optional',
WPVIVID_PCLZIP_OPT_BY_EREG => 'optional',
WPVIVID_PCLZIP_OPT_BY_PREG => 'optional',
WPVIVID_PCLZIP_OPT_BY_INDEX => 'optional',
WPVIVID_PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
WPVIVID_PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional',
WPVIVID_PCLZIP_OPT_REPLACE_NEWER => 'optional'
,WPVIVID_PCLZIP_OPT_STOP_ON_ERROR => 'optional'
,WPVIVID_PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_ON => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
));
if ($v_result != 1) {
return 0;
}
// ----- Set the arguments
if (isset($v_options[WPVIVID_PCLZIP_OPT_PATH])) {
$v_path = $v_options[WPVIVID_PCLZIP_OPT_PATH];
}
if (isset($v_options[WPVIVID_PCLZIP_OPT_REMOVE_PATH])) {
$v_remove_path = $v_options[WPVIVID_PCLZIP_OPT_REMOVE_PATH];
}
if (isset($v_options[WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH])) {
$v_remove_all_path = $v_options[WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH];
}
if (isset($v_options[WPVIVID_PCLZIP_OPT_ADD_PATH])) {
// ----- Check for '/' in last path char
if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
$v_path .= '/';
}
$v_path .= $v_options[WPVIVID_PCLZIP_OPT_ADD_PATH];
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_remove_path = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
return 0;
}
}
}
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Trace
// ----- Call the extracting fct
$p_list = array();
$v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path,
$v_remove_all_path, $v_options);
if ($v_result < 1) {
unset($p_list);
return(0);
}
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// extractByIndex($p_index, $p_path="./", $p_remove_path="")
// extractByIndex($p_index, [$p_option, $p_option_value, ...])
// Description :
// This method supports two synopsis. The first one is historical.
// This method is doing a partial extract of the archive.
// The extracted files or folders are identified by their index in the
// archive (from 0 to n).
// Note that if the index identify a folder, only the folder entry is
// extracted, not all the files included in the archive.
// Parameters :
// $p_index : A single index (integer) or a string of indexes of files to
// extract. The form of the string is "0,4-6,8-12" with only numbers
// and '-' for range or ',' to separate ranges. No spaces or ';'
// are allowed.
// $p_path : Path where the files and directories are to be extracted
// $p_remove_path : First part ('root' part) of the memorized path
// (if any similar) to remove while extracting.
// Options :
// WPVIVID_PCLZIP_OPT_PATH :
// WPVIVID_PCLZIP_OPT_ADD_PATH :
// WPVIVID_PCLZIP_OPT_REMOVE_PATH :
// WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH :
// WPVIVID_PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and
// not as files.
// The resulting content is in a new field 'content' in the file
// structure.
// This option must be used alone (any other options are ignored).
// WPVIVID_PCLZIP_CB_PRE_EXTRACT :
// WPVIVID_PCLZIP_CB_POST_EXTRACT :
// Return Values :
// 0 on failure,
// The list of the extracted files, with a status of the action.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
//function extractByIndex($p_index, options...)
function extractByIndex($p_index)
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Set default values
$v_options = array();
// $v_path = "./";
$v_path = '';
$v_remove_path = "";
$v_remove_all_path = false;
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Default values for option
$v_options[WPVIVID_PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
// ----- Look for arguments
if ($v_size > 1) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Remove form the options list the first argument
array_shift($v_arg_list);
$v_size--;
// ----- Look for first arg
if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) {
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (WPVIVID_PCLZIP_OPT_PATH => 'optional',
WPVIVID_PCLZIP_OPT_REMOVE_PATH => 'optional',
WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH => 'optional',
WPVIVID_PCLZIP_OPT_EXTRACT_AS_STRING => 'optional',
WPVIVID_PCLZIP_OPT_ADD_PATH => 'optional',
WPVIVID_PCLZIP_CB_PRE_EXTRACT => 'optional',
WPVIVID_PCLZIP_CB_POST_EXTRACT => 'optional',
WPVIVID_PCLZIP_OPT_SET_CHMOD => 'optional',
WPVIVID_PCLZIP_OPT_REPLACE_NEWER => 'optional'
,WPVIVID_PCLZIP_OPT_STOP_ON_ERROR => 'optional'
,WPVIVID_PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_ON => 'optional',
WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF => 'optional'
));
if ($v_result != 1) {
return 0;
}
// ----- Set the arguments
if (isset($v_options[WPVIVID_PCLZIP_OPT_PATH])) {
$v_path = $v_options[WPVIVID_PCLZIP_OPT_PATH];
}
if (isset($v_options[WPVIVID_PCLZIP_OPT_REMOVE_PATH])) {
$v_remove_path = $v_options[WPVIVID_PCLZIP_OPT_REMOVE_PATH];
}
if (isset($v_options[WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH])) {
$v_remove_all_path = $v_options[WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH];
}
if (isset($v_options[WPVIVID_PCLZIP_OPT_ADD_PATH])) {
// ----- Check for '/' in last path char
if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) {
$v_path .= '/';
}
$v_path .= $v_options[WPVIVID_PCLZIP_OPT_ADD_PATH];
}
if (!isset($v_options[WPVIVID_PCLZIP_OPT_EXTRACT_AS_STRING])) {
$v_options[WPVIVID_PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE;
}
else {
}
}
// ----- Look for 2 args
// Here we need to support the first historic synopsis of the
// method.
else {
// ----- Get the first argument
$v_path = $v_arg_list[0];
// ----- Look for the optional second argument
if ($v_size == 2) {
$v_remove_path = $v_arg_list[1];
}
else if ($v_size > 2) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments");
// ----- Return
return 0;
}
}
}
// ----- Trace
// ----- Trick
// Here I want to reuse extractByRule(), so I need to parse the $p_index
// with privParseOptions()
$v_arg_trick = array (WPVIVID_PCLZIP_OPT_BY_INDEX, $p_index);
$v_options_trick = array();
$v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick,
array (WPVIVID_PCLZIP_OPT_BY_INDEX => 'optional' ));
if ($v_result != 1) {
return 0;
}
$v_options[WPVIVID_PCLZIP_OPT_BY_INDEX] = $v_options_trick[WPVIVID_PCLZIP_OPT_BY_INDEX];
// ----- Look for default option values
$this->privOptionDefaultThreshold($v_options);
// ----- Call the extracting fct
if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) {
return(0);
}
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function :
// delete([$p_option, $p_option_value, ...])
// Description :
// This method removes files from the archive.
// If no parameters are given, then all the archive is emptied.
// Parameters :
// None or optional arguments.
// Options :
// WPVIVID_PCLZIP_OPT_BY_INDEX :
// WPVIVID_PCLZIP_OPT_BY_NAME :
// WPVIVID_PCLZIP_OPT_BY_EREG :
// WPVIVID_PCLZIP_OPT_BY_PREG :
// Return Values :
// 0 on failure,
// The list of the files which are still present in the archive.
// (see PclZip::listContent() for list entry format)
// --------------------------------------------------------------------------------
function delete()
{
$v_result=1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Set default values
$v_options = array();
// ----- Look for variable options arguments
$v_size = func_num_args();
// ----- Look for arguments
if ($v_size > 0) {
// ----- Get the arguments
$v_arg_list = func_get_args();
// ----- Parse the options
$v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options,
array (WPVIVID_PCLZIP_OPT_BY_NAME => 'optional',
WPVIVID_PCLZIP_OPT_BY_EREG => 'optional',
WPVIVID_PCLZIP_OPT_BY_PREG => 'optional',
WPVIVID_PCLZIP_OPT_BY_INDEX => 'optional' ));
if ($v_result != 1) {
return 0;
}
}
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Call the delete fct
$v_list = array();
if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) {
$this->privSwapBackMagicQuotes();
unset($v_list);
return(0);
}
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : deleteByIndex()
// Description :
// ***** Deprecated *****
// delete(WPVIVID_PCLZIP_OPT_BY_INDEX, $p_index) should be preferred.
// --------------------------------------------------------------------------------
function deleteByIndex($p_index)
{
$p_list = $this->delete(WPVIVID_PCLZIP_OPT_BY_INDEX, $p_index);
// ----- Return
return $p_list;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : properties()
// Description :
// This method gives the properties of the archive.
// The properties are :
// nb : Number of files in the archive
// comment : Comment associated with the archive file
// status : not_exist, ok
// Parameters :
// None
// Return Values :
// 0 on failure,
// An array with the archive properties.
// --------------------------------------------------------------------------------
function properties()
{
// ----- Reset the error handler
$this->privErrorReset();
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Check archive
if (!$this->privCheckFormat()) {
$this->privSwapBackMagicQuotes();
return(0);
}
// ----- Default properties
$v_prop = array();
$v_prop['comment'] = '';
$v_prop['nb'] = 0;
$v_prop['status'] = 'not_exist';
// ----- Look if file exists
if (@is_file($this->zipname))
{
// ----- Open the zip file
if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
{
$this->privSwapBackMagicQuotes();
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
// ----- Return
return 0;
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privSwapBackMagicQuotes();
return 0;
}
// ----- Close the zip file
$this->privCloseFd();
// ----- Set the user attributes
$v_prop['comment'] = $v_central_dir['comment'];
$v_prop['nb'] = $v_central_dir['entries'];
$v_prop['status'] = 'ok';
}
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_prop;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : duplicate()
// Description :
// This method creates an archive by copying the content of an other one. If
// the archive already exist, it is replaced by the new one without any warning.
// Parameters :
// $p_archive : The filename of a valid archive, or
// a valid PclZip object.
// Return Values :
// 1 on success.
// 0 or a negative value on error (error code).
// --------------------------------------------------------------------------------
function duplicate($p_archive)
{
$v_result = 1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Look if the $p_archive is a PclZip object
if (is_object($p_archive) && $p_archive instanceof pclzip)
{
// ----- Duplicate the archive
$v_result = $this->privDuplicate($p_archive->zipname);
}
// ----- Look if the $p_archive is a string (so a filename)
else if (is_string($p_archive))
{
// ----- Check that $p_archive is a valid zip file
// TBC : Should also check the archive format
if (!is_file($p_archive)) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'");
$v_result = WPVIVID_PCLZIP_ERR_MISSING_FILE;
}
else {
// ----- Duplicate the archive
$v_result = $this->privDuplicate($p_archive);
}
}
// ----- Invalid variable
else
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
$v_result = WPVIVID_PCLZIP_ERR_INVALID_PARAMETER;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : merge()
// Description :
// This method merge the $p_archive_to_add archive at the end of the current
// one ($this).
// If the archive ($this) does not exist, the merge becomes a duplicate.
// If the $p_archive_to_add archive does not exist, the merge is a success.
// Parameters :
// $p_archive_to_add : It can be directly the filename of a valid zip archive,
// or a PclZip object archive.
// Return Values :
// 1 on success,
// 0 or negative values on error (see below).
// --------------------------------------------------------------------------------
function merge($p_archive_to_add)
{
$v_result = 1;
// ----- Reset the error handler
$this->privErrorReset();
// ----- Check archive
if (!$this->privCheckFormat()) {
return(0);
}
// ----- Look if the $p_archive_to_add is a PclZip object
if (is_object($p_archive_to_add) && $p_archive_to_add instanceof pclzip)
{
// ----- Merge the archive
$v_result = $this->privMerge($p_archive_to_add);
}
// ----- Look if the $p_archive_to_add is a string (so a filename)
else if (is_string($p_archive_to_add))
{
// ----- Create a temporary archive
$v_object_archive = new WPvivid_PclZip($p_archive_to_add);
// ----- Merge the archive
$v_result = $this->privMerge($v_object_archive);
}
// ----- Invalid variable
else
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add");
$v_result = WPVIVID_PCLZIP_ERR_INVALID_PARAMETER;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorCode()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorCode()
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
return(PclErrorCode());
}
else {
return($this->error_code);
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorName()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorName($p_with_code=false)
{
$v_name = array ( WPVIVID_PCLZIP_ERR_NO_ERROR => 'WPVIVID_PCLZIP_ERR_NO_ERROR',
WPVIVID_PCLZIP_ERR_WRITE_OPEN_FAIL => 'WPVIVID_PCLZIP_ERR_WRITE_OPEN_FAIL',
WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL => 'WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL',
WPVIVID_PCLZIP_ERR_INVALID_PARAMETER => 'WPVIVID_PCLZIP_ERR_INVALID_PARAMETER',
WPVIVID_PCLZIP_ERR_MISSING_FILE => 'WPVIVID_PCLZIP_ERR_MISSING_FILE',
WPVIVID_PCLZIP_ERR_FILENAME_TOO_LONG => 'WPVIVID_PCLZIP_ERR_FILENAME_TOO_LONG',
WPVIVID_PCLZIP_ERR_INVALID_ZIP => 'WPVIVID_PCLZIP_ERR_INVALID_ZIP',
WPVIVID_PCLZIP_ERR_BAD_EXTRACTED_FILE => 'WPVIVID_PCLZIP_ERR_BAD_EXTRACTED_FILE',
WPVIVID_PCLZIP_ERR_DIR_CREATE_FAIL => 'WPVIVID_PCLZIP_ERR_DIR_CREATE_FAIL',
WPVIVID_PCLZIP_ERR_BAD_EXTENSION => 'WPVIVID_PCLZIP_ERR_BAD_EXTENSION',
WPVIVID_PCLZIP_ERR_BAD_FORMAT => 'WPVIVID_PCLZIP_ERR_BAD_FORMAT',
WPVIVID_PCLZIP_ERR_DELETE_FILE_FAIL => 'WPVIVID_PCLZIP_ERR_DELETE_FILE_FAIL',
WPVIVID_PCLZIP_ERR_RENAME_FILE_FAIL => 'WPVIVID_PCLZIP_ERR_RENAME_FILE_FAIL',
WPVIVID_PCLZIP_ERR_BAD_CHECKSUM => 'WPVIVID_PCLZIP_ERR_BAD_CHECKSUM',
WPVIVID_PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'WPVIVID_PCLZIP_ERR_INVALID_ARCHIVE_ZIP',
WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE => 'WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE',
WPVIVID_PCLZIP_ERR_INVALID_OPTION_VALUE => 'WPVIVID_PCLZIP_ERR_INVALID_OPTION_VALUE',
WPVIVID_PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'WPVIVID_PCLZIP_ERR_UNSUPPORTED_COMPRESSION',
WPVIVID_PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'WPVIVID_PCLZIP_ERR_UNSUPPORTED_ENCRYPTION'
,WPVIVID_PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'WPVIVID_PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE'
,WPVIVID_PCLZIP_ERR_DIRECTORY_RESTRICTION => 'WPVIVID_PCLZIP_ERR_DIRECTORY_RESTRICTION'
);
if (isset($v_name[$this->error_code])) {
$v_value = $v_name[$this->error_code];
}
else {
$v_value = 'NoName';
}
if ($p_with_code) {
return($v_value.' ('.$this->error_code.')');
}
else {
return($v_value);
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : errorInfo()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function errorInfo($p_full=false)
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
return(PclErrorString());
}
else {
if ($p_full) {
return($this->errorName(true)." : ".$this->error_string);
}
else {
return($this->error_string." [code ".$this->error_code."]");
}
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS *****
// ***** *****
// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY *****
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCheckFormat()
// Description :
// This method check that the archive exists and is a valid zip archive.
// Several level of check exists. (futur)
// Parameters :
// $p_level : Level of check. Default 0.
// 0 : Check the first bytes (magic codes) (default value))
// 1 : 0 + Check the central directory (futur)
// 2 : 1 + Check each file header (futur)
// Return Values :
// true on success,
// false on error, the error code is set.
// --------------------------------------------------------------------------------
function privCheckFormat($p_level=0)
{
$v_result = true;
// ----- Reset the file system cache
clearstatcache();
// ----- Reset the error handler
$this->privErrorReset();
// ----- Look if the file exits
if (!is_file($this->zipname)) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'");
return(false);
}
// ----- Check that the file is readable
if (!is_readable($this->zipname)) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'");
return(false);
}
// ----- Check the magic code
// TBC
// ----- Check the central header
// TBC
// ----- Check each file header
// TBC
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privParseOptions()
// Description :
// This internal methods reads the variable list of arguments ($p_options_list,
// $p_size) and generate an array with the options and values ($v_result_list).
// $v_requested_options contains the options that can be present and those that
// must be present.
// $v_requested_options is an array, with the option value as key, and 'optional',
// or 'mandatory' as value.
// Parameters :
// See above.
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false)
{
$v_result=1;
// ----- Read the options
$i=0;
while ($i<$p_size) {
// ----- Check if the option is supported
if (!isset($v_requested_options[$p_options_list[$i]])) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Look for next option
switch ($p_options_list[$i]) {
// ----- Look for options that request a path value
case WPVIVID_PCLZIP_OPT_PATH :
case WPVIVID_PCLZIP_OPT_REMOVE_PATH :
case WPVIVID_PCLZIP_OPT_ADD_PATH :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Get the value
$v_result_list[$p_options_list[$i]] = WPvivid_PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
$i++;
break;
case WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
return WPvivid_PclZip::errorCode();
}
// ----- Check for incompatible options
if (isset($v_result_list[WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF])) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF'");
return WPvivid_PclZip::errorCode();
}
// ----- Check the value
$v_value = $p_options_list[$i+1];
if ((!is_integer($v_value)) || ($v_value<0)) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
return WPvivid_PclZip::errorCode();
}
// ----- Get the value (and convert it in bytes)
$v_result_list[$p_options_list[$i]] = $v_value*1048576;
$i++;
break;
case WPVIVID_PCLZIP_OPT_TEMP_FILE_ON :
// ----- Check for incompatible options
if (isset($v_result_list[WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF])) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF'");
return WPvivid_PclZip::errorCode();
}
$v_result_list[$p_options_list[$i]] = true;
break;
case WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF :
// ----- Check for incompatible options
if (isset($v_result_list[WPVIVID_PCLZIP_OPT_TEMP_FILE_ON])) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'WPVIVID_PCLZIP_OPT_TEMP_FILE_ON'");
return WPvivid_PclZip::errorCode();
}
// ----- Check for incompatible options
if (isset($v_result_list[WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD'");
return WPvivid_PclZip::errorCode();
}
$v_result_list[$p_options_list[$i]] = true;
break;
case WPVIVID_PCLZIP_OPT_EXTRACT_DIR_RESTRICTION :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Get the value
if ( is_string($p_options_list[$i+1])
&& ($p_options_list[$i+1] != '')) {
$v_result_list[$p_options_list[$i]] = WPvivid_PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE);
$i++;
}
else {
}
break;
// ----- Look for options that request an array of string for value
case WPVIVID_PCLZIP_OPT_BY_NAME :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1];
}
else if (is_array($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
$i++;
break;
// ----- Look for options that request an EREG or PREG expression
case WPVIVID_PCLZIP_OPT_BY_EREG :
// ereg() is deprecated starting with PHP 5.3. Move WPVIVID_PCLZIP_OPT_BY_EREG
// to WPVIVID_PCLZIP_OPT_BY_PREG
$p_options_list[$i] = WPVIVID_PCLZIP_OPT_BY_PREG;
case WPVIVID_PCLZIP_OPT_BY_PREG :
//case PCLZIP_OPT_CRYPT :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
$i++;
break;
// ----- Look for options that takes a string
case WPVIVID_PCLZIP_OPT_COMMENT :
case WPVIVID_PCLZIP_OPT_ADD_COMMENT :
case WPVIVID_PCLZIP_OPT_PREPEND_COMMENT :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE,
"Missing parameter value for option '"
.WPvivid_PclZipUtilOptionText($p_options_list[$i])
."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Get the value
if (is_string($p_options_list[$i+1])) {
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
}
else {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_OPTION_VALUE,
"Wrong parameter value for option '"
.WPvivid_PclZipUtilOptionText($p_options_list[$i])
."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
$i++;
break;
// ----- Look for options that request an array of index
case WPVIVID_PCLZIP_OPT_BY_INDEX :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Get the value
$v_work_list = array();
if (is_string($p_options_list[$i+1])) {
// ----- Remove spaces
$p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', '');
// ----- Parse items
$v_work_list = explode(",", $p_options_list[$i+1]);
}
else if (is_integer($p_options_list[$i+1])) {
$v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1];
}
else if (is_array($p_options_list[$i+1])) {
$v_work_list = $p_options_list[$i+1];
}
else {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Reduce the index list
// each index item in the list must be a couple with a start and
// an end value : [0,3], [5-5], [8-10], ...
// ----- Check the format of each item
$v_sort_flag=false;
$v_sort_value=0;
for ($j=0; $j<sizeof($v_work_list); $j++) {
// ----- Explode the item
$v_item_list = explode("-", $v_work_list[$j]);
$v_size_item_list = sizeof($v_item_list);
// ----- TBC : Here we might check that each item is a
// real integer ...
// ----- Look for single value
if ($v_size_item_list == 1) {
// ----- Set the option value
$v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
$v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0];
}
elseif ($v_size_item_list == 2) {
// ----- Set the option value
$v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0];
$v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1];
}
else {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Look for list sort
if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) {
$v_sort_flag=true;
// ----- TBC : An automatic sort should be written ...
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
$v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start'];
}
// ----- Sort the items
if ($v_sort_flag) {
// TBC : To Be Completed
}
// ----- Next option
$i++;
break;
// ----- Look for options that request no value
case WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH :
case WPVIVID_PCLZIP_OPT_EXTRACT_AS_STRING :
case WPVIVID_PCLZIP_OPT_NO_COMPRESSION :
case WPVIVID_PCLZIP_OPT_EXTRACT_IN_OUTPUT :
case WPVIVID_PCLZIP_OPT_REPLACE_NEWER :
case WPVIVID_PCLZIP_OPT_STOP_ON_ERROR :
$v_result_list[$p_options_list[$i]] = true;
break;
// ----- Look for options that request an octal value
case WPVIVID_PCLZIP_OPT_SET_CHMOD :
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Get the value
$v_result_list[$p_options_list[$i]] = $p_options_list[$i+1];
$i++;
break;
// ----- Look for options that request a call-back
case WPVIVID_PCLZIP_CB_PRE_EXTRACT :
case WPVIVID_PCLZIP_CB_POST_EXTRACT :
case WPVIVID_PCLZIP_CB_PRE_ADD :
case WPVIVID_PCLZIP_CB_POST_ADD :
/* for futur use
case PCLZIP_CB_PRE_DELETE :
case PCLZIP_CB_POST_DELETE :
case PCLZIP_CB_PRE_LIST :
case PCLZIP_CB_POST_LIST :
*/
// ----- Check the number of parameters
if (($i+1) >= $p_size) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Get the value
$v_function_name = $p_options_list[$i+1];
// ----- Check that the value is a valid existing function
if (!function_exists($v_function_name)) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".WPvivid_PclZipUtilOptionText($p_options_list[$i])."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Set the attribute
$v_result_list[$p_options_list[$i]] = $v_function_name;
$i++;
break;
default :
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER,
"Unknown parameter '"
.$p_options_list[$i]."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Next options
$i++;
}
// ----- Look for mandatory options
if ($v_requested_options !== false) {
for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
// ----- Look for mandatory option
if ($v_requested_options[$key] == 'mandatory') {
// ----- Look if present
if (!isset($v_result_list[$key])) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".WPvivid_PclZipUtilOptionText($key)."(".$key.")");
// ----- Return
return WPvivid_PclZip::errorCode();
}
}
}
}
// ----- Look for default values
if (!isset($v_result_list[WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD])) {
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privOptionDefaultThreshold()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privOptionDefaultThreshold(&$p_options)
{
$v_result=1;
if (isset($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD])
|| isset($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF])) {
return $v_result;
}
// ----- Get 'memory_limit' configuration value
$v_memory_limit = ini_get('memory_limit');
$v_memory_limit = trim($v_memory_limit);
$v_memory_limit_int = (int) $v_memory_limit;
$last = strtolower(substr($v_memory_limit, -1));
if($last == 'g')
//$v_memory_limit_int = $v_memory_limit_int*1024*1024*1024;
$v_memory_limit_int = $v_memory_limit_int*1073741824;
if($last == 'm')
//$v_memory_limit_int = $v_memory_limit_int*1024*1024;
$v_memory_limit_int = $v_memory_limit_int*1048576;
if($last == 'k')
$v_memory_limit_int = $v_memory_limit_int*1024;
$p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit_int*PCLZIP_TEMPORARY_FILE_RATIO);
// ----- Sanity check : No threshold if value lower than 1M
if ($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) {
unset($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD]);
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privFileDescrParseAtt()
// Description :
// Parameters :
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false)
{
$v_result=1;
// ----- For each file in the list check the attributes
foreach ($p_file_list as $v_key => $v_value) {
// ----- Check if the option is supported
if (!isset($v_requested_options[$v_key])) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Look for attribute
switch ($v_key) {
case WPVIVID_PCLZIP_ATT_FILE_NAME :
if (!is_string($v_value)) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".WPvivid_PclZipUtilOptionText($v_key)."'");
return WPvivid_PclZip::errorCode();
}
$p_filedescr['filename'] = WPvivid_PclZipUtilPathReduction($v_value);
if ($p_filedescr['filename'] == '') {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".WPvivid_PclZipUtilOptionText($v_key)."'");
return WPvivid_PclZip::errorCode();
}
break;
case WPVIVID_PCLZIP_ATT_FILE_NEW_SHORT_NAME :
if (!is_string($v_value)) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".WPvivid_PclZipUtilOptionText($v_key)."'");
return WPvivid_PclZip::errorCode();
}
$p_filedescr['new_short_name'] = WPvivid_PclZipUtilPathReduction($v_value);
if ($p_filedescr['new_short_name'] == '') {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".WPvivid_PclZipUtilOptionText($v_key)."'");
return WPvivid_PclZip::errorCode();
}
break;
case WPVIVID_PCLZIP_ATT_FILE_NEW_FULL_NAME :
if (!is_string($v_value)) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".WPvivid_PclZipUtilOptionText($v_key)."'");
return WPvivid_PclZip::errorCode();
}
$p_filedescr['new_full_name'] = WPvivid_PclZipUtilPathReduction($v_value);
if ($p_filedescr['new_full_name'] == '') {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".WPvivid_PclZipUtilOptionText($v_key)."'");
return WPvivid_PclZip::errorCode();
}
break;
// ----- Look for options that takes a string
case WPVIVID_PCLZIP_ATT_FILE_COMMENT :
if (!is_string($v_value)) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".WPvivid_PclZipUtilOptionText($v_key)."'");
return WPvivid_PclZip::errorCode();
}
$p_filedescr['comment'] = $v_value;
break;
case WPVIVID_PCLZIP_ATT_FILE_MTIME :
if (!is_integer($v_value)) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".WPvivid_PclZipUtilOptionText($v_key)."'");
return WPvivid_PclZip::errorCode();
}
$p_filedescr['mtime'] = $v_value;
break;
case WPVIVID_PCLZIP_ATT_FILE_CONTENT :
$p_filedescr['content'] = $v_value;
break;
default :
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER,
"Unknown parameter '".$v_key."'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Look for mandatory options
if ($v_requested_options !== false) {
for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) {
// ----- Look for mandatory option
if ($v_requested_options[$key] == 'mandatory') {
// ----- Look if present
if (!isset($p_file_list[$key])) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".WPvivid_PclZipUtilOptionText($key)."(".$key.")");
return WPvivid_PclZip::errorCode();
}
}
}
}
// end foreach
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privFileDescrExpand()
// Description :
// This method look for each item of the list to see if its a file, a folder
// or a string to be added as file. For any other type of files (link, other)
// just ignore the item.
// Then prepare the information that will be stored for that file.
// When its a folder, expand the folder with all the files that are in that
// folder (recursively).
// Parameters :
// Return Values :
// 1 on success.
// 0 on failure.
// --------------------------------------------------------------------------------
function privFileDescrExpand(&$p_filedescr_list, &$p_options)
{
$v_result=1;
// ----- Create a result list
$v_result_list = array();
// ----- Look each entry
for ($i=0; $i<sizeof($p_filedescr_list); $i++) {
// ----- Get filedescr
$v_descr = $p_filedescr_list[$i];
// ----- Reduce the filename
$v_descr['filename'] = WPvivid_PclZipUtilTranslateWinPath($v_descr['filename'], false);
$v_descr['filename'] = WPvivid_PclZipUtilPathReduction($v_descr['filename']);
// ----- Look for real file or folder
if (file_exists($v_descr['filename'])) {
if (@is_file($v_descr['filename'])) {
$v_descr['type'] = 'file';
}
else if (@is_dir($v_descr['filename'])) {
$v_descr['type'] = 'folder';
}
else if (@is_link($v_descr['filename'])) {
// skip
continue;
}
else {
// skip
continue;
}
}
// ----- Look for string added as file
else if (isset($v_descr['content'])) {
$v_descr['type'] = 'virtual_file';
}
// ----- Missing file
else {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_FILE, "File '".$v_descr['filename']."' does not exist");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Calculate the stored filename
$this->privCalculateStoredFilename($v_descr, $p_options);
// ----- Add the descriptor in result list
$v_result_list[sizeof($v_result_list)] = $v_descr;
// ----- Look for folder
if ($v_descr['type'] == 'folder') {
// ----- List of items in folder
$v_dirlist_descr = array();
$v_dirlist_nb = 0;
if ($v_folder_handler = @opendir($v_descr['filename'])) {
while (($v_item_handler = @readdir($v_folder_handler)) !== false) {
// ----- Skip '.' and '..'
if (($v_item_handler == '.') || ($v_item_handler == '..')) {
continue;
}
// ----- Compose the full filename
$v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler;
// ----- Look for different stored filename
// Because the name of the folder was changed, the name of the
// files/sub-folders also change
if (($v_descr['stored_filename'] != $v_descr['filename'])
&& (!isset($p_options[WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH]))) {
if ($v_descr['stored_filename'] != '') {
$v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler;
}
else {
$v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler;
}
}
$v_dirlist_nb++;
}
@closedir($v_folder_handler);
}
else {
// TBC : unable to open folder in read mode
}
// ----- Expand each element of the list
if ($v_dirlist_nb != 0) {
// ----- Expand
if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) {
return $v_result;
}
// ----- Concat the resulting list
$v_result_list = array_merge($v_result_list, $v_dirlist_descr);
}
else {
}
// ----- Free local array
unset($v_dirlist_descr);
}
}
// ----- Get the result list
$p_filedescr_list = $v_result_list;
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCreate()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privCreate($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
$v_list_detail = array();
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the file in write mode
if (($v_result = $this->privOpenFd('wb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Add the list of files
$v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options);
// ----- Close
$this->privCloseFd();
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAdd()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privAdd($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
$v_list_detail = array();
// ----- Look if the archive exists or is empty
if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0))
{
// ----- Do a create
$v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options);
// ----- Return
return $v_result;
}
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the zip file
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Go to beginning of File
@rewind($this->zip_fd);
// ----- Creates a temporary file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Open the temporary file in write mode
if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0)
{
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = $v_central_dir['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Swap the file descriptor
// Here is a trick : I swap the temporary fd with the zip fd, in order to use
// the following methods on the temporary fil and not the real archive
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Add the files
$v_header_list = array();
if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1)
{
fclose($v_zip_temp_fd);
$this->privCloseFd();
@wp_delete_file($v_zip_temp_name);
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($this->zip_fd);
// ----- Copy the block of file headers from the old archive
$v_size = $v_central_dir['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($v_zip_temp_fd, $v_read_size);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Create the Central Dir files header
for ($i=0, $v_count=0; $i<sizeof($v_header_list); $i++)
{
// ----- Create the file header
if ($v_header_list[$i]['status'] == 'ok') {
if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
fclose($v_zip_temp_fd);
$this->privCloseFd();
@wp_delete_file($v_zip_temp_name);
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
$v_count++;
}
// ----- Transform the header to a 'usable' info
$this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
// ----- Zip file comment
$v_comment = $v_central_dir['comment'];
if (isset($p_options[WPVIVID_PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[WPVIVID_PCLZIP_OPT_COMMENT];
}
if (isset($p_options[WPVIVID_PCLZIP_OPT_ADD_COMMENT])) {
$v_comment = $v_comment.$p_options[WPVIVID_PCLZIP_OPT_ADD_COMMENT];
}
if (isset($p_options[WPVIVID_PCLZIP_OPT_PREPEND_COMMENT])) {
$v_comment = $p_options[WPVIVID_PCLZIP_OPT_PREPEND_COMMENT].$v_comment;
}
// ----- Calculate the size of the central header
$v_size = @ftell($this->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1)
{
// ----- Reset the file list
unset($v_header_list);
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// ----- Swap back the file descriptor
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Close
$this->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Delete the zip file
// TBC : I should test the result ...
@wp_delete_file($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
WPvivid_PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privOpenFd()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privOpenFd($p_mode)
{
$v_result=1;
// ----- Look if already open
if ($this->zip_fd != 0)
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Open the zip file
if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0)
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCloseFd()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privCloseFd()
{
$v_result=1;
if ($this->zip_fd != 0)
@fclose($this->zip_fd);
$this->zip_fd = 0;
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddList()
// Description :
// $p_add_dir and $p_remove_dir will give the ability to memorize a path which is
// different from the real path of the file. This is useful if you want to have PclTar
// running in any directory, and memorize relative path from an other directory.
// Parameters :
// $p_list : An array containing the file or directory names to add in the tar
// $p_result_list : list of added files with their properties (specially the status field)
// $p_add_dir : Path to add in the filename path archived
// $p_remove_dir : Path to remove in the filename path archived
// Return Values :
// --------------------------------------------------------------------------------
// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options)
function privAddList($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
// ----- Add the files
$v_header_list = array();
if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1)
{
// ----- Return
return $v_result;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($this->zip_fd);
// ----- Create the Central Dir files header
for ($i=0,$v_count=0; $i<sizeof($v_header_list); $i++)
{
// ----- Create the file header
if ($v_header_list[$i]['status'] == 'ok') {
if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
// ----- Return
return $v_result;
}
$v_count++;
}
// ----- Transform the header to a 'usable' info
$this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
// ----- Zip file comment
$v_comment = '';
if (isset($p_options[WPVIVID_PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[WPVIVID_PCLZIP_OPT_COMMENT];
}
// ----- Calculate the size of the central header
$v_size = @ftell($this->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1)
{
// ----- Reset the file list
unset($v_header_list);
// ----- Return
return $v_result;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddFileList()
// Description :
// Parameters :
// $p_filedescr_list : An array containing the file description
// or directory names to add in the zip
// $p_result_list : list of added files with their properties (specially the status field)
// Return Values :
// --------------------------------------------------------------------------------
function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result=1;
$v_header = array();
// ----- Recuperate the current number of elt in list
$v_nb = sizeof($p_result_list);
// ----- Loop on the files
for ($j=0; ($j<sizeof($p_filedescr_list)) && ($v_result==1); $j++) {
// ----- Format the filename
$p_filedescr_list[$j]['filename']
= WPvivid_PclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false);
// ----- Skip empty file names
// TBC : Can this be possible ? not checked in DescrParseAtt ?
if ($p_filedescr_list[$j]['filename'] == "") {
continue;
}
// ----- Check the filename
if ( ($p_filedescr_list[$j]['type'] != 'virtual_file')
&& (!file_exists($p_filedescr_list[$j]['filename']))) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_MISSING_FILE, "File '".$p_filedescr_list[$j]['filename']."' does not exist");
return WPvivid_PclZip::errorCode();
}
// ----- Look if it is a file or a dir with no all path remove option
// or a dir with all its path removed
// if ( (is_file($p_filedescr_list[$j]['filename']))
// || ( is_dir($p_filedescr_list[$j]['filename'])
if ( ($p_filedescr_list[$j]['type'] == 'file')
|| ($p_filedescr_list[$j]['type'] == 'virtual_file')
|| ( ($p_filedescr_list[$j]['type'] == 'folder')
&& ( !isset($p_options[WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH])
|| !$p_options[WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH]))
) {
// ----- Add the file
$v_result = $this->privAddFile($p_filedescr_list[$j], $v_header,
$p_options);
if ($v_result != 1) {
return $v_result;
}
// ----- Store the file infos
$p_result_list[$v_nb++] = $v_header;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privAddFile($p_filedescr, &$p_header, &$p_options)
{
$v_result=1;
// ----- Working variable
$p_filename = $p_filedescr['filename'];
// TBC : Already done in the fileAtt check ... ?
if ($p_filename == "") {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Look for a stored different filename
/* TBC : Removed
if (isset($p_filedescr['stored_filename'])) {
$v_stored_filename = $p_filedescr['stored_filename'];
}
else {
$v_stored_filename = $p_filedescr['stored_filename'];
}
*/
// ----- Set the file properties
clearstatcache();
$p_header['version'] = 20;
$p_header['version_extracted'] = 10;
$p_header['flag'] = 0;
$p_header['compression'] = 0;
$p_header['crc'] = 0;
$p_header['compressed_size'] = 0;
$p_header['filename_len'] = strlen($p_filename);
$p_header['extra_len'] = 0;
$p_header['disk'] = 0;
$p_header['internal'] = 0;
$p_header['offset'] = 0;
$p_header['filename'] = $p_filename;
// TBC : Removed $p_header['stored_filename'] = $v_stored_filename;
$p_header['stored_filename'] = $p_filedescr['stored_filename'];
$p_header['extra'] = '';
$p_header['status'] = 'ok';
$p_header['index'] = -1;
// ----- Look for regular file
if ($p_filedescr['type']=='file') {
$p_header['external'] = 0x00000000;
$p_header['size'] = filesize($p_filename);
}
// ----- Look for regular folder
else if ($p_filedescr['type']=='folder') {
$p_header['external'] = 0x00000010;
$p_header['mtime'] = filemtime($p_filename);
$p_header['size'] = filesize($p_filename);
}
// ----- Look for virtual file
else if ($p_filedescr['type'] == 'virtual_file') {
$p_header['external'] = 0x00000000;
$p_header['size'] = strlen($p_filedescr['content']);
}
// ----- Look for filetime
if (isset($p_filedescr['mtime'])) {
$p_header['mtime'] = $p_filedescr['mtime'];
}
else if ($p_filedescr['type'] == 'virtual_file') {
$p_header['mtime'] = time();
}
else {
$p_header['mtime'] = filemtime($p_filename);
}
// ------ Look for file comment
if (isset($p_filedescr['comment'])) {
$p_header['comment_len'] = strlen($p_filedescr['comment']);
$p_header['comment'] = $p_filedescr['comment'];
}
else {
$p_header['comment_len'] = 0;
$p_header['comment'] = '';
}
// ----- Look for pre-add callback
if (isset($p_options[WPVIVID_PCLZIP_CB_PRE_ADD])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_header, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[WPVIVID_PCLZIP_CB_PRE_ADD](WPVIVID_PCLZIP_CB_PRE_ADD, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_header['status'] = "skipped";
$v_result = 1;
}
// ----- Update the information
// Only some fields can be modified
if ($p_header['stored_filename'] != $v_local_header['stored_filename']) {
$p_header['stored_filename'] = WPvivid_PclZipUtilPathReduction($v_local_header['stored_filename']);
}
}
// ----- Look for empty stored filename
if ($p_header['stored_filename'] == "") {
$p_header['status'] = "filtered";
}
// ----- Check the path length
if (strlen($p_header['stored_filename']) > 0xFF) {
$p_header['status'] = 'filename_too_long';
}
// ----- Look if no error, or file not skipped
if ($p_header['status'] == 'ok') {
// ----- Look for a file
if ($p_filedescr['type'] == 'file') {
// ----- Look for using temporary file to zip
if ( (!isset($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF]))
&& (isset($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_ON])
|| (isset($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD])
&& ($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) {
$v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options);
if ($v_result < WPVIVID_PCLZIP_ERR_NO_ERROR) {
return $v_result;
}
}
// ----- Use "in memory" zip algo
else {
// ----- Open the source file
if (($v_file = @fopen($p_filename, "rb")) == 0) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
return WPvivid_PclZip::errorCode();
}
// ----- Read the file content
if($p_header['size']==0)
{
$v_content='';
}
else
{
$v_content = @fread($v_file, $p_header['size']);
}
// ----- Close the file
@fclose($v_file);
// ----- Calculate the CRC
$p_header['crc'] = @crc32($v_content);
// ----- Look for no compression
if ($p_options[WPVIVID_PCLZIP_OPT_NO_COMPRESSION]) {
// ----- Set header parameters
$p_header['compressed_size'] = $p_header['size'];
$p_header['compression'] = 0;
}
// ----- Look for normal compression
else {
// ----- Compress the content
$v_content = @gzdeflate($v_content);
// ----- Set header parameters
$p_header['compressed_size'] = strlen($v_content);
$p_header['compression'] = 8;
}
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
@fclose($v_file);
return $v_result;
}
// ----- Write the compressed (or not) content
@fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
}
}
// ----- Look for a virtual file (a file from string)
else if ($p_filedescr['type'] == 'virtual_file') {
$v_content = $p_filedescr['content'];
// ----- Calculate the CRC
$p_header['crc'] = @crc32($v_content);
// ----- Look for no compression
if ($p_options[WPVIVID_PCLZIP_OPT_NO_COMPRESSION]) {
// ----- Set header parameters
$p_header['compressed_size'] = $p_header['size'];
$p_header['compression'] = 0;
}
// ----- Look for normal compression
else {
// ----- Compress the content
$v_content = @gzdeflate($v_content);
// ----- Set header parameters
$p_header['compressed_size'] = strlen($v_content);
$p_header['compression'] = 8;
}
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
@fclose($v_file);
return $v_result;
}
// ----- Write the compressed (or not) content
@fwrite($this->zip_fd, $v_content, $p_header['compressed_size']);
}
// ----- Look for a directory
else if ($p_filedescr['type'] == 'folder') {
// ----- Look for directory last '/'
if (@substr($p_header['stored_filename'], -1) != '/') {
$p_header['stored_filename'] .= '/';
}
// ----- Set the file properties
$p_header['size'] = 0;
//$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked
$p_header['external'] = 0x00000010; // Value for a folder : to be checked
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1)
{
return $v_result;
}
}
}
// ----- Look for post-add callback
if (isset($p_options[WPVIVID_PCLZIP_CB_POST_ADD])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_header, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[WPVIVID_PCLZIP_CB_POST_ADD](WPVIVID_PCLZIP_CB_POST_ADD, $v_local_header);
if ($v_result == 0) {
// ----- Ignored
$v_result = 1;
}
// ----- Update the information
// Nothing can be modified
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privAddFileUsingTempFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options)
{
$v_result=WPVIVID_PCLZIP_ERR_NO_ERROR;
// ----- Working variable
$p_filename = $p_filedescr['filename'];
// ----- Open the source file
if (($v_file = @fopen($p_filename, "rb")) == 0) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode");
return WPvivid_PclZip::errorCode();
}
// ----- Creates a compressed temporary file
$v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz';
if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) {
fclose($v_file);
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode');
return WPvivid_PclZip::errorCode();
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = filesize($p_filename);
while ($v_size != 0) {
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($v_file, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@gzputs($v_file_compressed, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Close the file
@fclose($v_file);
@gzclose($v_file_compressed);
// ----- Check the minimum file size
if (filesize($v_gzip_temp_name) < 18) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes');
return WPvivid_PclZip::errorCode();
}
// ----- Extract the compressed attributes
if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
return WPvivid_PclZip::errorCode();
}
// ----- Read the gzip file header
$v_binary_data = @fread($v_file_compressed, 10);
$v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data);
// ----- Check some parameters
$v_data_header['os'] = bin2hex($v_data_header['os']);
// ----- Read the gzip file footer
@fseek($v_file_compressed, filesize($v_gzip_temp_name)-8);
$v_binary_data = @fread($v_file_compressed, 8);
$v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data);
// ----- Set the attributes
$p_header['compression'] = ord($v_data_header['cm']);
//$p_header['mtime'] = $v_data_header['mtime'];
$p_header['crc'] = $v_data_footer['crc'];
$p_header['compressed_size'] = filesize($v_gzip_temp_name)-18;
// ----- Close the file
@fclose($v_file_compressed);
// ----- Call the header generation
if (($v_result = $this->privWriteFileHeader($p_header)) != 1) {
return $v_result;
}
// ----- Add the compressed data
if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0)
{
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
return WPvivid_PclZip::errorCode();
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
fseek($v_file_compressed, 10);
$v_size = $p_header['compressed_size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($v_file_compressed, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Close the file
@fclose($v_file_compressed);
// ----- Unlink the temporary file
@wp_delete_file($v_gzip_temp_name);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCalculateStoredFilename()
// Description :
// Based on file descriptor properties and global options, this method
// calculate the filename that will be stored in the archive.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privCalculateStoredFilename(&$p_filedescr, &$p_options)
{
$v_result=1;
// ----- Working variables
$p_filename = $p_filedescr['filename'];
if (isset($p_options[WPVIVID_PCLZIP_OPT_ADD_PATH])) {
$p_add_dir = $p_options[WPVIVID_PCLZIP_OPT_ADD_PATH];
}
else {
$p_add_dir = '';
}
if (isset($p_options[WPVIVID_PCLZIP_OPT_REMOVE_PATH])) {
$p_remove_dir = $p_options[WPVIVID_PCLZIP_OPT_REMOVE_PATH];
}
else {
$p_remove_dir = '';
}
if (isset($p_options[WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH])) {
$p_remove_all_dir = $p_options[WPVIVID_PCLZIP_OPT_REMOVE_ALL_PATH];
}
else {
$p_remove_all_dir = 0;
}
// ----- Look for full name change
if (isset($p_filedescr['new_full_name'])) {
// ----- Remove drive letter if any
$v_stored_filename = WPvivid_PclZipUtilTranslateWinPath($p_filedescr['new_full_name']);
}
// ----- Look for path and/or short name change
else {
// ----- Look for short name change
// Its when we change just the filename but not the path
if (isset($p_filedescr['new_short_name'])) {
$v_path_info = pathinfo($p_filename);
$v_dir = '';
if ($v_path_info['dirname'] != '') {
$v_dir = $v_path_info['dirname'].'/';
}
$v_stored_filename = $v_dir.$p_filedescr['new_short_name'];
}
else {
// ----- Calculate the stored filename
$v_stored_filename = $p_filename;
}
// ----- Look for all path to remove
if ($p_remove_all_dir) {
$v_stored_filename = basename($p_filename);
}
// ----- Look for partial path remove
else if ($p_remove_dir != "") {
if (substr($p_remove_dir, -1) != '/')
$p_remove_dir .= "/";
if ( (substr($p_filename, 0, 2) == "./")
|| (substr($p_remove_dir, 0, 2) == "./")) {
if ( (substr($p_filename, 0, 2) == "./")
&& (substr($p_remove_dir, 0, 2) != "./")) {
$p_remove_dir = "./".$p_remove_dir;
}
if ( (substr($p_filename, 0, 2) != "./")
&& (substr($p_remove_dir, 0, 2) == "./")) {
$p_remove_dir = substr($p_remove_dir, 2);
}
}
$v_compare = WPvivid_PclZipUtilPathInclusion($p_remove_dir,
$v_stored_filename);
if ($v_compare > 0) {
if ($v_compare == 2) {
$v_stored_filename = "";
}
else {
$v_stored_filename = substr($v_stored_filename,
strlen($p_remove_dir));
}
}
}
// ----- Remove drive letter if any
$v_stored_filename = WPvivid_PclZipUtilTranslateWinPath($v_stored_filename);
// ----- Look for path to add
if ($p_add_dir != "") {
if (substr($p_add_dir, -1) == "/")
$v_stored_filename = $p_add_dir.$v_stored_filename;
else
$v_stored_filename = $p_add_dir."/".$v_stored_filename;
}
}
// ----- Filename (reduce the path of stored name)
$v_stored_filename = WPvivid_PclZipUtilPathReduction($v_stored_filename);
$p_filedescr['stored_filename'] = $v_stored_filename;
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteFileHeader(&$p_header)
{
$v_result=1;
// ----- Store the offset position of the file
$p_header['offset'] = ftell($this->zip_fd);
// ----- Transform UNIX mtime to DOS format mdate/mtime
$v_date = getdate($p_header['mtime']);
$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
// ----- Packed data
$v_binary_data = pack("VvvvvvVVVvv", 0x04034b50,
$p_header['version_extracted'], $p_header['flag'],
$p_header['compression'], $v_mtime, $v_mdate,
$p_header['crc'], $p_header['compressed_size'],
$p_header['size'],
strlen($p_header['stored_filename']),
$p_header['extra_len']);
// ----- Write the first 148 bytes of the header in the archive
fputs($this->zip_fd, $v_binary_data, 30);
// ----- Write the variable fields
if (strlen($p_header['stored_filename']) != 0)
{
fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
}
if ($p_header['extra_len'] != 0)
{
fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteCentralFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteCentralFileHeader(&$p_header)
{
$v_result=1;
// TBC
//for(reset($p_header); $key = key($p_header); next($p_header)) {
//}
// ----- Transform UNIX mtime to DOS format mdate/mtime
$v_date = getdate($p_header['mtime']);
$v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2;
$v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday'];
// ----- Packed data
$v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50,
$p_header['version'], $p_header['version_extracted'],
$p_header['flag'], $p_header['compression'],
$v_mtime, $v_mdate, $p_header['crc'],
$p_header['compressed_size'], $p_header['size'],
strlen($p_header['stored_filename']),
$p_header['extra_len'], $p_header['comment_len'],
$p_header['disk'], $p_header['internal'],
$p_header['external'], $p_header['offset']);
// ----- Write the 42 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 46);
// ----- Write the variable fields
if (strlen($p_header['stored_filename']) != 0)
{
fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename']));
}
if ($p_header['extra_len'] != 0)
{
fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']);
}
if ($p_header['comment_len'] != 0)
{
fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']);
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privWriteCentralHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment)
{
$v_result=1;
// ----- Packed data
$v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries,
$p_nb_entries, $p_size,
$p_offset, strlen($p_comment));
// ----- Write the 22 bytes of the header in the zip file
fputs($this->zip_fd, $v_binary_data, 22);
// ----- Write the variable fields
if (strlen($p_comment) != 0)
{
fputs($this->zip_fd, $p_comment, strlen($p_comment));
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privList()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privList(&$p_list)
{
$v_result=1;
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Open the zip file
if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0)
{
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Go to beginning of Central Dir
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_central_dir['offset']))
{
$this->privSwapBackMagicQuotes();
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Read each entry
for ($i=0; $i<$v_central_dir['entries']; $i++)
{
// ----- Read the file header
if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
{
$this->privSwapBackMagicQuotes();
return $v_result;
}
$v_header['index'] = $i;
// ----- Get the only interesting attributes
$this->privConvertHeader2FileInfo($v_header, $p_list[$i]);
unset($v_header);
}
// ----- Close the zip file
$this->privCloseFd();
// ----- Magic quotes trick
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privConvertHeader2FileInfo()
// Description :
// This function takes the file information from the central directory
// entries and extract the interesting parameters that will be given back.
// The resulting file infos are set in the array $p_info
// $p_info['filename'] : Filename with full path. Given by user (add),
// extracted in the filesystem (extract).
// $p_info['stored_filename'] : Stored filename in the archive.
// $p_info['size'] = Size of the file.
// $p_info['compressed_size'] = Compressed size of the file.
// $p_info['mtime'] = Last modification date of the file.
// $p_info['comment'] = Comment associated with the file.
// $p_info['folder'] = true/false : indicates if the entry is a folder or not.
// $p_info['status'] = status of the action on the file.
// $p_info['crc'] = CRC of the file content.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privConvertHeader2FileInfo($p_header, &$p_info)
{
$v_result=1;
// ----- Get the interesting attributes
$v_temp_path = WPvivid_PclZipUtilPathReduction($p_header['filename']);
$p_info['filename'] = $v_temp_path;
$v_temp_path = WPvivid_PclZipUtilPathReduction($p_header['stored_filename']);
$p_info['stored_filename'] = $v_temp_path;
$p_info['size'] = $p_header['size'];
$p_info['compressed_size'] = $p_header['compressed_size'];
$p_info['mtime'] = $p_header['mtime'];
$p_info['comment'] = $p_header['comment'];
$p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010);
$p_info['index'] = $p_header['index'];
$p_info['status'] = $p_header['status'];
$p_info['crc'] = $p_header['crc'];
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractByRule()
// Description :
// Extract a file or directory depending of rules (by index, by name, ...)
// Parameters :
// $p_file_list : An array where will be placed the properties of each
// extracted file
// $p_path : Path to add while writing the extracted files
// $p_remove_path : Path to remove (from the file memorized path) while writing the
// extracted files. If the path does not match the file path,
// the file is extracted with its memorized path.
// $p_remove_path does not apply to 'list' mode.
// $p_path and $p_remove_path are commulative.
// Return Values :
// 1 on success,0 or less on error (see error code list)
// --------------------------------------------------------------------------------
function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
{
$v_result=1;
// ----- Magic quotes trick
$this->privDisableMagicQuotes();
// ----- Check the path
if ( ($p_path == "")
|| ( (substr($p_path, 0, 1) != "/")
&& (substr($p_path, 0, 3) != "../")
&& (substr($p_path,1,2)!=":/")))
$p_path = "./".$p_path;
// ----- Reduce the path last (and duplicated) '/'
if (($p_path != "./") && ($p_path != "/"))
{
// ----- Look for the path end '/'
while (substr($p_path, -1) == "/")
{
$p_path = substr($p_path, 0, strlen($p_path)-1);
}
}
// ----- Look for path to remove format (should end by /)
if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/'))
{
$p_remove_path .= '/';
}
$p_remove_path_size = strlen($p_remove_path);
// ----- Open the zip file
if (($v_result = $this->privOpenFd('rb')) != 1)
{
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Start at beginning of Central Dir
$v_pos_entry = $v_central_dir['offset'];
// ----- Read each entry
$j_start = 0;
for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++)
{
// ----- Read next Central dir entry
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_pos_entry))
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Read the file header
$v_header = array();
if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Store the index
$v_header['index'] = $i;
// ----- Store the file position
$v_pos_entry = ftell($this->zip_fd);
// ----- Look for the specific extract rules
$v_extract = false;
// ----- Look for extract by name rule
if ( (isset($p_options[WPVIVID_PCLZIP_OPT_BY_NAME]))
&& ($p_options[WPVIVID_PCLZIP_OPT_BY_NAME] != 0)) {
// ----- Look if the filename is in the list
for ($j=0; ($j<sizeof($p_options[WPVIVID_PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) {
// ----- Look for a directory
if (substr($p_options[WPVIVID_PCLZIP_OPT_BY_NAME][$j], -1) == "/") {
// ----- Look if the directory is in the filename path
if ( (strlen($v_header['stored_filename']) > strlen($p_options[WPVIVID_PCLZIP_OPT_BY_NAME][$j]))
&& (substr($v_header['stored_filename'], 0, strlen($p_options[WPVIVID_PCLZIP_OPT_BY_NAME][$j])) == $p_options[WPVIVID_PCLZIP_OPT_BY_NAME][$j])) {
$v_extract = true;
}
}
// ----- Look for a filename
elseif ($v_header['stored_filename'] == $p_options[WPVIVID_PCLZIP_OPT_BY_NAME][$j]) {
$v_extract = true;
}
}
}
// ----- Look for extract by ereg rule
// ereg() is deprecated with PHP 5.3
/*
else if ( (isset($p_options[WPVIVID_PCLZIP_OPT_BY_EREG]))
&& ($p_options[WPVIVID_PCLZIP_OPT_BY_EREG] != "")) {
if (ereg($p_options[WPVIVID_PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) {
$v_extract = true;
}
}
*/
// ----- Look for extract by preg rule
else if ( (isset($p_options[WPVIVID_PCLZIP_OPT_BY_PREG]))
&& ($p_options[WPVIVID_PCLZIP_OPT_BY_PREG] != "")) {
if (preg_match($p_options[WPVIVID_PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) {
$v_extract = true;
}
}
// ----- Look for extract by index rule
else if ( (isset($p_options[WPVIVID_PCLZIP_OPT_BY_INDEX]))
&& ($p_options[WPVIVID_PCLZIP_OPT_BY_INDEX] != 0)) {
// ----- Look if the index is in the list
for ($j=$j_start; ($j<sizeof($p_options[WPVIVID_PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) {
if (($i>=$p_options[WPVIVID_PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[WPVIVID_PCLZIP_OPT_BY_INDEX][$j]['end'])) {
$v_extract = true;
}
if ($i>=$p_options[WPVIVID_PCLZIP_OPT_BY_INDEX][$j]['end']) {
$j_start = $j+1;
}
if ($p_options[WPVIVID_PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
break;
}
}
}
// ----- Look for no rule, which means extract all the archive
else {
$v_extract = true;
}
// ----- Check compression method
if ( ($v_extract)
&& ( ($v_header['compression'] != 8)
&& ($v_header['compression'] != 0))) {
$v_header['status'] = 'unsupported_compression';
// ----- Look for WPVIVID_PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[WPVIVID_PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[WPVIVID_PCLZIP_OPT_STOP_ON_ERROR]===true)) {
$this->privSwapBackMagicQuotes();
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_UNSUPPORTED_COMPRESSION,
"Filename '".$v_header['stored_filename']."' is "
."compressed by an unsupported compression "
."method (".$v_header['compression'].") ");
return WPvivid_PclZip::errorCode();
}
}
// ----- Check encrypted files
if (($v_extract) && (($v_header['flag'] & 1) == 1)) {
$v_header['status'] = 'unsupported_encryption';
// ----- Look for WPVIVID_PCLZIP_OPT_STOP_ON_ERROR
if ( (isset($p_options[WPVIVID_PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[WPVIVID_PCLZIP_OPT_STOP_ON_ERROR]===true)) {
$this->privSwapBackMagicQuotes();
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_UNSUPPORTED_ENCRYPTION,
"Unsupported encryption for "
." filename '".$v_header['stored_filename']
."'");
return WPvivid_PclZip::errorCode();
}
}
// ----- Look for real extraction
if (($v_extract) && ($v_header['status'] != 'ok')) {
$v_result = $this->privConvertHeader2FileInfo($v_header,
$p_file_list[$v_nb_extracted++]);
if ($v_result != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
$v_extract = false;
}
// ----- Look for real extraction
if ($v_extract)
{
// ----- Go to the file position
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_header['offset']))
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Look for extraction as string
if ($p_options[WPVIVID_PCLZIP_OPT_EXTRACT_AS_STRING]) {
$v_string = '';
// ----- Extracting the file
$v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Set the file content
$p_file_list[$v_nb_extracted]['content'] = $v_string;
// ----- Next extracted file
$v_nb_extracted++;
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
// ----- Look for extraction in standard output
elseif ( (isset($p_options[WPVIVID_PCLZIP_OPT_EXTRACT_IN_OUTPUT]))
&& ($p_options[WPVIVID_PCLZIP_OPT_EXTRACT_IN_OUTPUT])) {
// ----- Extracting the file in standard output
$v_result1 = $this->privExtractFileInOutput($v_header, $p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
// ----- Look for normal extraction
else {
// ----- Extracting the file
$v_result1 = $this->privExtractFile($v_header,
$p_path, $p_remove_path,
$p_remove_all_path,
$p_options);
if ($v_result1 < 1) {
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result1;
}
// ----- Get the only interesting attributes
if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Look for user callback abort
if ($v_result1 == 2) {
break;
}
}
}
}
// ----- Close the zip file
$this->privCloseFd();
$this->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFile()
// Description :
// Parameters :
// Return Values :
//
// 1 : ... ?
// WPVIVID_PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback
// --------------------------------------------------------------------------------
function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
{
$v_result=1;
// ----- Read the file header
if (($v_result = $this->privReadFileHeader($v_header)) != 1)
{
// ----- Return
return $v_result;
}
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for all path to remove
if ($p_remove_all_path == true) {
// ----- Look for folder entry that not need to be extracted
if (($p_entry['external']&0x00000010)==0x00000010) {
$p_entry['status'] = "filtered";
return $v_result;
}
// ----- Get the basename of the path
$p_entry['filename'] = basename($p_entry['filename']);
}
// ----- Look for path to remove
else if ($p_remove_path != "")
{
if (WPvivid_PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2)
{
// ----- Change the file status
$p_entry['status'] = "filtered";
// ----- Return
return $v_result;
}
$p_remove_path_size = strlen($p_remove_path);
if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path)
{
// ----- Remove the path
$p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size);
}
}
// ----- Add the path
if ($p_path != '') {
$p_entry['filename'] = $p_path."/".$p_entry['filename'];
}
// ----- Check a base_dir_restriction
if (isset($p_options[WPVIVID_PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) {
$v_inclusion
= WPvivid_PclZipUtilPathInclusion($p_options[WPVIVID_PCLZIP_OPT_EXTRACT_DIR_RESTRICTION],
$p_entry['filename']);
if ($v_inclusion == 0) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_DIRECTORY_RESTRICTION,
"Filename '".$p_entry['filename']."' is "
."outside WPVIVID_PCLZIP_OPT_EXTRACT_DIR_RESTRICTION");
return WPvivid_PclZip::errorCode();
}
}
// ----- Look for pre-extract callback
if (isset($p_options[WPVIVID_PCLZIP_CB_PRE_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[WPVIVID_PCLZIP_CB_PRE_EXTRACT](WPVIVID_PCLZIP_CB_PRE_EXTRACT, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = WPVIVID_PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the information
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
}
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Look for specific actions while the file exist
if (file_exists($p_entry['filename']))
{
// ----- Look if file is a directory
if (is_dir($p_entry['filename']))
{
// ----- Change the file status
$p_entry['status'] = "already_a_directory";
// ----- Look for WPVIVID_PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[WPVIVID_PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[WPVIVID_PCLZIP_OPT_STOP_ON_ERROR]===true)) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_ALREADY_A_DIRECTORY,
"Filename '".$p_entry['filename']."' is "
."already used by an existing directory");
return WPvivid_PclZip::errorCode();
}
}
// ----- Look if file is write protected
else if (!is_writeable($p_entry['filename']))
{
// ----- Change the file status
$p_entry['status'] = "write_protected";
// ----- Look for WPVIVID_PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[WPVIVID_PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[WPVIVID_PCLZIP_OPT_STOP_ON_ERROR]===true)) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_WRITE_OPEN_FAIL,
"Filename '".$p_entry['filename']."' exists "
."and is write protected");
return WPvivid_PclZip::errorCode();
}
}
// ----- Look if the extracted file is older
else if (filemtime($p_entry['filename']) > $p_entry['mtime'])
{
// ----- Change the file status
if ( (isset($p_options[WPVIVID_PCLZIP_OPT_REPLACE_NEWER]))
&& ($p_options[WPVIVID_PCLZIP_OPT_REPLACE_NEWER]===true)) {
}
else {
$p_entry['status'] = "newer_exist";
// ----- Look for WPVIVID_PCLZIP_OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if ( (isset($p_options[WPVIVID_PCLZIP_OPT_STOP_ON_ERROR]))
&& ($p_options[WPVIVID_PCLZIP_OPT_STOP_ON_ERROR]===true)) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_WRITE_OPEN_FAIL,
"Newer version of '".$p_entry['filename']."' exists "
."and option WPVIVID_PCLZIP_OPT_REPLACE_NEWER is not selected");
return WPvivid_PclZip::errorCode();
}
}
}
else {
}
}
// ----- Check the directory availability and create it if necessary
else {
if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/'))
$v_dir_to_check = $p_entry['filename'];
else if (!strstr($p_entry['filename'], "/"))
$v_dir_to_check = "";
else
$v_dir_to_check = dirname($p_entry['filename']);
if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) {
// ----- Change the file status
$p_entry['status'] = "path_creation_fail";
// ----- Return
//return $v_result;
$v_result = 1;
}
}
}
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010))
{
// ----- Look for not compressed file
if ($p_entry['compression'] == 0) {
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0)
{
// ----- Change the file status
$p_entry['status'] = "write_error";
// ----- Return
return $v_result;
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = $p_entry['compressed_size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($this->zip_fd, $v_read_size);
/* Try to speed up the code
$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($v_dest_file, $v_binary_data, $v_read_size);
*/
@fwrite($v_dest_file, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Closing the destination file
fclose($v_dest_file);
// ----- Change the file mtime
touch($p_entry['filename'], $p_entry['mtime']);
}
else {
// ----- TBC
// Need to be finished
if (($p_entry['flag'] & 1) == 1) {
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.');
return WPvivid_PclZip::errorCode();
}
// ----- Look for using temporary file to unzip
if ( (!isset($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_OFF]))
&& (isset($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_ON])
|| (isset($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD])
&& ($p_options[WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) {
$v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options);
if ($v_result < WPVIVID_PCLZIP_ERR_NO_ERROR) {
return $v_result;
}
}
// ----- Look for extract in memory
else {
// ----- Read the compressed file in a buffer (one shot)
if ( $p_entry['compressed_size'] > 0 ) {
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
$v_buffer = false;
}
// ----- Decompress the file
$v_file_content = @gzinflate($v_buffer);
unset($v_buffer);
if ($v_file_content === FALSE) {
// ----- Change the file status
// TBC
$p_entry['status'] = "error";
return $v_result;
}
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
// ----- Change the file status
$p_entry['status'] = "write_error";
return $v_result;
}
// ----- Write the uncompressed data
@fwrite($v_dest_file, $v_file_content, $p_entry['size']);
unset($v_file_content);
// ----- Closing the destination file
@fclose($v_dest_file);
}
// ----- Change the file mtime
@touch($p_entry['filename'], $p_entry['mtime']);
}
// ----- Look for chmod option
if (isset($p_options[WPVIVID_PCLZIP_OPT_SET_CHMOD])) {
// ----- Change the mode of the file
@chmod($p_entry['filename'], $p_options[WPVIVID_PCLZIP_OPT_SET_CHMOD]);
}
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[WPVIVID_PCLZIP_CB_POST_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[WPVIVID_PCLZIP_CB_POST_EXTRACT](WPVIVID_PCLZIP_CB_POST_EXTRACT, $v_local_header);
// ----- Look for abort result
if ($v_result == 2) {
$v_result = WPVIVID_PCLZIP_ERR_USER_ABORTED;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileUsingTempFile()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileUsingTempFile(&$p_entry, &$p_options)
{
$v_result=1;
// ----- Creates a temporary file
$v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz';
if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) {
fclose($v_file);
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode');
return WPvivid_PclZip::errorCode();
}
// ----- Write gz file format header
$v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3));
@fwrite($v_dest_file, $v_binary_data, 10);
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = $p_entry['compressed_size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($this->zip_fd, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($v_dest_file, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Write gz file format footer
$v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']);
@fwrite($v_dest_file, $v_binary_data, 8);
// ----- Close the temporary file
@fclose($v_dest_file);
// ----- Opening destination file
if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) {
$p_entry['status'] = "write_error";
return $v_result;
}
// ----- Open the temporary gz file
if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) {
@fclose($v_dest_file);
$p_entry['status'] = "read_error";
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode');
return WPvivid_PclZip::errorCode();
}
// ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks
$v_size = $p_entry['size'];
while ($v_size != 0) {
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @gzread($v_src_file, $v_read_size);
//$v_binary_data = pack('a'.$v_read_size, $v_buffer);
@fwrite($v_dest_file, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
@fclose($v_dest_file);
@gzclose($v_src_file);
// ----- Delete the temporary file
@wp_delete_file($v_gzip_temp_name);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileInOutput()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileInOutput(&$p_entry, &$p_options)
{
$v_result=1;
// ----- Read the file header
if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
return $v_result;
}
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for pre-extract callback
if (isset($p_options[WPVIVID_PCLZIP_CB_PRE_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
// eval('$v_result = '.$p_options[WPVIVID_PCLZIP_CB_PRE_EXTRACT].'(WPVIVID_PCLZIP_CB_PRE_EXTRACT, $v_local_header);');
$v_result = $p_options[WPVIVID_PCLZIP_CB_PRE_EXTRACT](WPVIVID_PCLZIP_CB_PRE_EXTRACT, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = WPVIVID_PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the information
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
}
// ----- Trace
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010)) {
// ----- Look for not compressed file
if ($p_entry['compressed_size'] == $p_entry['size']) {
// ----- Read the file in a buffer (one shot)
if ( $p_entry['compressed_size'] > 0 ) {
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
$v_buffer = false;
}
// ----- Send the file to the output
echo $v_buffer;
unset($v_buffer);
}
else {
// ----- Read the compressed file in a buffer (one shot)
if ( $p_entry['compressed_size'] > 0 ) {
$v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
$v_buffer = false;
}
// ----- Decompress the file
$v_file_content = gzinflate($v_buffer);
unset($v_buffer);
// ----- Send the file to the output
echo $v_file_content;
unset($v_file_content);
}
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[WPVIVID_PCLZIP_CB_POST_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[WPVIVID_PCLZIP_CB_POST_EXTRACT](WPVIVID_PCLZIP_CB_POST_EXTRACT, $v_local_header);
// ----- Look for abort result
if ($v_result == 2) {
$v_result = WPVIVID_PCLZIP_ERR_USER_ABORTED;
}
}
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privExtractFileAsString()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privExtractFileAsString(&$p_entry, &$p_string, &$p_options)
{
$v_result=1;
// ----- Read the file header
$v_header = array();
if (($v_result = $this->privReadFileHeader($v_header)) != 1)
{
// ----- Return
return $v_result;
}
// ----- Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// ----- Look for pre-extract callback
if (isset($p_options[WPVIVID_PCLZIP_CB_PRE_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[WPVIVID_PCLZIP_CB_PRE_EXTRACT](WPVIVID_PCLZIP_CB_PRE_EXTRACT, $v_local_header);
if ($v_result == 0) {
// ----- Change the file status
$p_entry['status'] = "skipped";
$v_result = 1;
}
// ----- Look for abort result
if ($v_result == 2) {
// ----- This status is internal and will be changed in 'skipped'
$p_entry['status'] = "aborted";
$v_result = WPVIVID_PCLZIP_ERR_USER_ABORTED;
}
// ----- Update the information
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
}
// ----- Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// ----- Do the extraction (if not a folder)
if (!(($p_entry['external']&0x00000010)==0x00000010)) {
// ----- Look for not compressed file
// if ($p_entry['compressed_size'] == $p_entry['size'])
if ($p_entry['compression'] == 0) {
// ----- Reading the file
if ( $p_entry['compressed_size'] > 0 ) {
$p_string = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
$p_string = false;
}
}
else {
// ----- Reading the file
if ( $p_entry['compressed_size'] > 0 ) {
$v_data = @fread($this->zip_fd, $p_entry['compressed_size']);
}
else {
$v_data = false;
}
// ----- Decompress the file
if (($p_string = @gzinflate($v_data)) === FALSE) {
// TBC
}
}
// ----- Trace
}
else {
// TBC : error : can not extract a folder in a string
}
}
// ----- Change abort status
if ($p_entry['status'] == "aborted") {
$p_entry['status'] = "skipped";
}
// ----- Look for post-extract callback
elseif (isset($p_options[WPVIVID_PCLZIP_CB_POST_EXTRACT])) {
// ----- Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// ----- Swap the content to header
$v_local_header['content'] = $p_string;
$p_string = '';
// ----- Call the callback
// Here I do not use call_user_func() because I need to send a reference to the
// header.
$v_result = $p_options[WPVIVID_PCLZIP_CB_POST_EXTRACT](WPVIVID_PCLZIP_CB_POST_EXTRACT, $v_local_header);
// ----- Swap back the content to header
$p_string = $v_local_header['content'];
unset($v_local_header['content']);
// ----- Look for abort result
if ($v_result == 2) {
$v_result = WPVIVID_PCLZIP_ERR_USER_ABORTED;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadFileHeader(&$p_header)
{
$v_result=1;
// ----- Read the 4 bytes signature
$v_binary_data = @fread($this->zip_fd, 4);
$v_data = unpack('Vid', $v_binary_data);
// ----- Check signature
if ($v_data['id'] != 0x04034b50)
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Read the first 42 bytes of the header
$v_binary_data = fread($this->zip_fd, 26);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 26)
{
$p_header['filename'] = "";
$p_header['status'] = "invalid_header";
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Extract the values
$v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data);
// ----- Get filename
$p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']);
// ----- Get extra_fields
if ($v_data['extra_len'] != 0) {
$p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']);
}
else {
$p_header['extra'] = '';
}
// ----- Extract properties
$p_header['version_extracted'] = $v_data['version'];
$p_header['compression'] = $v_data['compression'];
$p_header['size'] = $v_data['size'];
$p_header['compressed_size'] = $v_data['compressed_size'];
$p_header['crc'] = $v_data['crc'];
$p_header['flag'] = $v_data['flag'];
$p_header['filename_len'] = $v_data['filename_len'];
// ----- Recuperate date in UNIX format
$p_header['mdate'] = $v_data['mdate'];
$p_header['mtime'] = $v_data['mtime'];
if ($p_header['mdate'] && $p_header['mtime'])
{
// ----- Extract time
$v_hour = ($p_header['mtime'] & 0xF800) >> 11;
$v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
$v_seconde = ($p_header['mtime'] & 0x001F)*2;
// ----- Extract date
$v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
$v_month = ($p_header['mdate'] & 0x01E0) >> 5;
$v_day = $p_header['mdate'] & 0x001F;
// ----- Get UNIX date format
$p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
}
else
{
$p_header['mtime'] = time();
}
// TBC
//for(reset($v_data); $key = key($v_data); next($v_data)) {
//}
// ----- Set the stored filename
$p_header['stored_filename'] = $p_header['filename'];
// ----- Set the status field
$p_header['status'] = "ok";
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadCentralFileHeader()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadCentralFileHeader(&$p_header)
{
$v_result=1;
// ----- Read the 4 bytes signature
$v_binary_data = @fread($this->zip_fd, 4);
$v_data = unpack('Vid', $v_binary_data);
// ----- Check signature
if ($v_data['id'] != 0x02014b50)
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Read the first 42 bytes of the header
$v_binary_data = fread($this->zip_fd, 42);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 42)
{
$p_header['filename'] = "";
$p_header['status'] = "invalid_header";
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data));
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Extract the values
$p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data);
// ----- Get filename
if ($p_header['filename_len'] != 0)
$p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']);
else
$p_header['filename'] = '';
// ----- Get extra
if ($p_header['extra_len'] != 0)
$p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']);
else
$p_header['extra'] = '';
// ----- Get comment
if ($p_header['comment_len'] != 0)
$p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']);
else
$p_header['comment'] = '';
// ----- Extract properties
// ----- Recuperate date in UNIX format
//if ($p_header['mdate'] && $p_header['mtime'])
// TBC : bug : this was ignoring time with 0/0/0
if (1)
{
// ----- Extract time
$v_hour = ($p_header['mtime'] & 0xF800) >> 11;
$v_minute = ($p_header['mtime'] & 0x07E0) >> 5;
$v_seconde = ($p_header['mtime'] & 0x001F)*2;
// ----- Extract date
$v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980;
$v_month = ($p_header['mdate'] & 0x01E0) >> 5;
$v_day = $p_header['mdate'] & 0x001F;
// ----- Get UNIX date format
$p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year);
}
else
{
$p_header['mtime'] = time();
}
// ----- Set the stored filename
$p_header['stored_filename'] = $p_header['filename'];
// ----- Set default status to ok
$p_header['status'] = 'ok';
// ----- Look if it is a directory
if (substr($p_header['filename'], -1) == '/') {
//$p_header['external'] = 0x41FF0010;
$p_header['external'] = 0x00000010;
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privCheckFileHeaders()
// Description :
// Parameters :
// Return Values :
// 1 on success,
// 0 on error;
// --------------------------------------------------------------------------------
function privCheckFileHeaders(&$p_local_header, &$p_central_header)
{
$v_result=1;
// ----- Check the static values
// TBC
if ($p_local_header['filename'] != $p_central_header['filename']) {
}
if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) {
}
if ($p_local_header['flag'] != $p_central_header['flag']) {
}
if ($p_local_header['compression'] != $p_central_header['compression']) {
}
if ($p_local_header['mtime'] != $p_central_header['mtime']) {
}
if ($p_local_header['filename_len'] != $p_central_header['filename_len']) {
}
// ----- Look for flag bit 3
if (($p_local_header['flag'] & 8) == 8) {
$p_local_header['size'] = $p_central_header['size'];
$p_local_header['compressed_size'] = $p_central_header['compressed_size'];
$p_local_header['crc'] = $p_central_header['crc'];
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privReadEndCentralDir()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privReadEndCentralDir(&$p_central_dir)
{
$v_result=1;
// ----- Go to the end of the zip file
$v_size = filesize($this->zipname);
@fseek($this->zip_fd, $v_size);
if (@ftell($this->zip_fd) != $v_size)
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\'');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- First try : look if this is an archive with no commentaries (most of the time)
// in this case the end of central dir is at 22 bytes of the file end
$v_found = 0;
if ($v_size > 26) {
@fseek($this->zip_fd, $v_size-22);
if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22))
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Read for bytes
$v_binary_data = @fread($this->zip_fd, 4);
$v_data = @unpack('Vid', $v_binary_data);
// ----- Check signature
if ($v_data['id'] == 0x06054b50) {
$v_found = 1;
}
$v_pos = ftell($this->zip_fd);
}
// ----- Go back to the maximum possible size of the Central Dir End Record
if (!$v_found) {
$v_maximum_size = 65557; // 0xFFFF + 22;
if ($v_maximum_size > $v_size)
$v_maximum_size = $v_size;
@fseek($this->zip_fd, $v_size-$v_maximum_size);
if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size))
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\'');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Read byte per byte in order to find the signature
$v_pos = ftell($this->zip_fd);
$v_bytes = 0x00000000;
while ($v_pos < $v_size)
{
// ----- Read a byte
$v_byte = @fread($this->zip_fd, 1);
// ----- Add the byte
//$v_bytes = ($v_bytes << 8) | Ord($v_byte);
// Note we mask the old value down such that once shifted we can never end up with more than a 32bit number
// Otherwise on systems where we have 64bit integers the check below for the magic number will fail.
$v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte);
// ----- Compare the bytes
if ($v_bytes == 0x504b0506)
{
$v_pos++;
break;
}
$v_pos++;
}
// ----- Look if not found end of central dir
if ($v_pos == $v_size)
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature");
// ----- Return
return WPvivid_PclZip::errorCode();
}
}
// ----- Read the first 18 bytes of the header
$v_binary_data = fread($this->zip_fd, 18);
// ----- Look for invalid block size
if (strlen($v_binary_data) != 18)
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data));
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Extract the values
$v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data);
// ----- Check the global size
if (($v_pos + $v_data['comment_size'] + 18) != $v_size) {
// ----- Removed in release 2.2 see readme file
// The check of the file size is a little too strict.
// Some bugs where found when a zip is encrypted/decrypted with 'crypt'.
// While decrypted, zip has training 0 bytes
if (0) {
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_BAD_FORMAT,
'The central dir is not at the end of the archive.'
.' Some trailing bytes exists after the archive.');
// ----- Return
return WPvivid_PclZip::errorCode();
}
}
// ----- Get comment
if ($v_data['comment_size'] != 0) {
$p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']);
}
else
$p_central_dir['comment'] = '';
$p_central_dir['entries'] = $v_data['entries'];
$p_central_dir['disk_entries'] = $v_data['disk_entries'];
$p_central_dir['offset'] = $v_data['offset'];
$p_central_dir['size'] = $v_data['size'];
$p_central_dir['disk'] = $v_data['disk'];
$p_central_dir['disk_start'] = $v_data['disk_start'];
// TBC
//for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) {
//}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDeleteByRule()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDeleteByRule(&$p_result_list, &$p_options)
{
$v_result=1;
$v_list_detail = array();
// ----- Open the zip file
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
return $v_result;
}
// ----- Go to beginning of File
@rewind($this->zip_fd);
// ----- Scan all the files
// ----- Start at beginning of Central Dir
$v_pos_entry = $v_central_dir['offset'];
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_pos_entry))
{
// ----- Close the zip file
$this->privCloseFd();
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Read each entry
$v_header_list = array();
$j_start = 0;
for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++)
{
// ----- Read the file header
$v_header_list[$v_nb_extracted] = array();
if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1)
{
// ----- Close the zip file
$this->privCloseFd();
return $v_result;
}
// ----- Store the index
$v_header_list[$v_nb_extracted]['index'] = $i;
// ----- Look for the specific extract rules
$v_found = false;
// ----- Look for extract by name rule
if ( (isset($p_options[WPVIVID_PCLZIP_OPT_BY_NAME]))
&& ($p_options[WPVIVID_PCLZIP_OPT_BY_NAME] != 0)) {
// ----- Look if the filename is in the list
for ($j=0; ($j<sizeof($p_options[WPVIVID_PCLZIP_OPT_BY_NAME])) && (!$v_found); $j++) {
// ----- Look for a directory
if (substr($p_options[WPVIVID_PCLZIP_OPT_BY_NAME][$j], -1) == "/") {
// ----- Look if the directory is in the filename path
if ( (strlen($v_header_list[$v_nb_extracted]['stored_filename']) > strlen($p_options[WPVIVID_PCLZIP_OPT_BY_NAME][$j]))
&& (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[WPVIVID_PCLZIP_OPT_BY_NAME][$j])) == $p_options[WPVIVID_PCLZIP_OPT_BY_NAME][$j])) {
$v_found = true;
}
elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */
&& ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[WPVIVID_PCLZIP_OPT_BY_NAME][$j])) {
$v_found = true;
}
}
// ----- Look for a filename
elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[WPVIVID_PCLZIP_OPT_BY_NAME][$j]) {
$v_found = true;
}
}
}
// ----- Look for extract by ereg rule
// ereg() is deprecated with PHP 5.3
/*
else if ( (isset($p_options[WPVIVID_PCLZIP_OPT_BY_EREG]))
&& ($p_options[WPVIVID_PCLZIP_OPT_BY_EREG] != "")) {
if (ereg($p_options[WPVIVID_PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
$v_found = true;
}
}
*/
// ----- Look for extract by preg rule
else if ( (isset($p_options[WPVIVID_PCLZIP_OPT_BY_PREG]))
&& ($p_options[WPVIVID_PCLZIP_OPT_BY_PREG] != "")) {
if (preg_match($p_options[WPVIVID_PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) {
$v_found = true;
}
}
// ----- Look for extract by index rule
else if ( (isset($p_options[WPVIVID_PCLZIP_OPT_BY_INDEX]))
&& ($p_options[WPVIVID_PCLZIP_OPT_BY_INDEX] != 0)) {
// ----- Look if the index is in the list
for ($j=$j_start; ($j<sizeof($p_options[WPVIVID_PCLZIP_OPT_BY_INDEX])) && (!$v_found); $j++) {
if (($i>=$p_options[WPVIVID_PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[WPVIVID_PCLZIP_OPT_BY_INDEX][$j]['end'])) {
$v_found = true;
}
if ($i>=$p_options[WPVIVID_PCLZIP_OPT_BY_INDEX][$j]['end']) {
$j_start = $j+1;
}
if ($p_options[WPVIVID_PCLZIP_OPT_BY_INDEX][$j]['start']>$i) {
break;
}
}
}
else {
$v_found = true;
}
// ----- Look for deletion
if ($v_found)
{
unset($v_header_list[$v_nb_extracted]);
}
else
{
$v_nb_extracted++;
}
}
// ----- Look if something need to be deleted
if ($v_nb_extracted > 0) {
// ----- Creates a temporary file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Creates a temporary zip archive
$v_temp_zip = new WPvivid_PclZip($v_zip_temp_name);
// ----- Open the temporary zip file in write mode
if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) {
$this->privCloseFd();
// ----- Return
return $v_result;
}
// ----- Look which file need to be kept
for ($i=0; $i<sizeof($v_header_list); $i++) {
// ----- Calculate the position of the header
@rewind($this->zip_fd);
if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@wp_delete_file($v_zip_temp_name);
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Read the file header
$v_local_header = array();
if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@wp_delete_file($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Check that local file header is same as central file header
if ($this->privCheckFileHeaders($v_local_header,
$v_header_list[$i]) != 1) {
// TBC
}
unset($v_local_header);
// ----- Write the file header
if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@wp_delete_file($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Read/write the data block
if (($v_result = WPvivid_PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) {
// ----- Close the zip file
$this->privCloseFd();
$v_temp_zip->privCloseFd();
@wp_delete_file($v_zip_temp_name);
// ----- Return
return $v_result;
}
}
// ----- Store the offset of the central dir
$v_offset = @ftell($v_temp_zip->zip_fd);
// ----- Re-Create the Central Dir files header
for ($i=0; $i<sizeof($v_header_list); $i++) {
// ----- Create the file header
if (($v_result = $v_temp_zip->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
$v_temp_zip->privCloseFd();
$this->privCloseFd();
@wp_delete_file($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Transform the header to a 'usable' info
$v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]);
}
// ----- Zip file comment
$v_comment = '';
if (isset($p_options[WPVIVID_PCLZIP_OPT_COMMENT])) {
$v_comment = $p_options[WPVIVID_PCLZIP_OPT_COMMENT];
}
// ----- Calculate the size of the central header
$v_size = @ftell($v_temp_zip->zip_fd)-$v_offset;
// ----- Create the central dir footer
if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) {
// ----- Reset the file list
unset($v_header_list);
$v_temp_zip->privCloseFd();
$this->privCloseFd();
@wp_delete_file($v_zip_temp_name);
// ----- Return
return $v_result;
}
// ----- Close
$v_temp_zip->privCloseFd();
$this->privCloseFd();
// ----- Delete the zip file
// TBC : I should test the result ...
@wp_delete_file($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
WPvivid_PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Destroy the temporary archive
unset($v_temp_zip);
}
// ----- Remove every files : reset the file
else if ($v_central_dir['entries'] != 0) {
$this->privCloseFd();
if (($v_result = $this->privOpenFd('wb')) != 1) {
return $v_result;
}
if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) {
return $v_result;
}
$this->privCloseFd();
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDirCheck()
// Description :
// Check if a directory exists, if not it creates it and all the parents directory
// which may be useful.
// Parameters :
// $p_dir : Directory path to check.
// Return Values :
// 1 : OK
// -1 : Unable to create directory
// --------------------------------------------------------------------------------
function privDirCheck($p_dir, $p_is_dir=false)
{
$v_result = 1;
// ----- Remove the final '/'
if (($p_is_dir) && (substr($p_dir, -1)=='/'))
{
$p_dir = substr($p_dir, 0, strlen($p_dir)-1);
}
// ----- Check the directory availability
if ((is_dir($p_dir)) || ($p_dir == ""))
{
return 1;
}
// ----- Extract parent directory
$p_parent_dir = dirname($p_dir);
// ----- Just a check
if ($p_parent_dir != $p_dir)
{
// ----- Look for parent directory
if ($p_parent_dir != "")
{
if (($v_result = $this->privDirCheck($p_parent_dir)) != 1)
{
return $v_result;
}
}
}
// ----- Create the directory
if (!@mkdir($p_dir, 0777))
{
// ----- Error log
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'");
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privMerge()
// Description :
// If $p_archive_to_add does not exist, the function exit with a success result.
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privMerge(&$p_archive_to_add)
{
$v_result=1;
// ----- Look if the archive_to_add exists
if (!is_file($p_archive_to_add->zipname))
{
// ----- Nothing to merge, so merge is a success
$v_result = 1;
// ----- Return
return $v_result;
}
// ----- Look if the archive exists
if (!is_file($this->zipname))
{
// ----- Do a duplicate
$v_result = $this->privDuplicate($p_archive_to_add->zipname);
// ----- Return
return $v_result;
}
// ----- Open the zip file
if (($v_result=$this->privOpenFd('rb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Read the central directory information
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1)
{
$this->privCloseFd();
return $v_result;
}
// ----- Go to beginning of File
@rewind($this->zip_fd);
// ----- Open the archive_to_add file
if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1)
{
$this->privCloseFd();
// ----- Return
return $v_result;
}
// ----- Read the central directory information
$v_central_dir_to_add = array();
if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
return $v_result;
}
// ----- Go to beginning of File
@rewind($p_archive_to_add->zip_fd);
// ----- Creates a temporary file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
// ----- Open the temporary file in write mode
if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
// ----- Return
return WPvivid_PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = $v_central_dir['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Copy the files from the archive_to_add into the temporary file
$v_size = $v_central_dir_to_add['offset'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($v_zip_temp_fd);
// ----- Copy the block of file headers from the old archive
$v_size = $v_central_dir['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Copy the block of file headers from the archive_to_add
$v_size = $v_central_dir_to_add['size'];
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Merge the file comments
$v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment'];
// ----- Calculate the size of the (new) central header
$v_size = @ftell($v_zip_temp_fd)-$v_offset;
// ----- Swap the file descriptor
// Here is a trick : I swap the temporary fd with the zip fd, in order to use
// the following methods on the temporary fil and not the real archive fd
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Create the central dir footer
if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1)
{
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
@fclose($v_zip_temp_fd);
$this->zip_fd = null;
// ----- Reset the file list
unset($v_header_list);
// ----- Return
return $v_result;
}
// ----- Swap back the file descriptor
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
// ----- Close
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Delete the zip file
// TBC : I should test the result ...
@wp_delete_file($this->zipname);
// ----- Rename the temporary file
// TBC : I should test the result ...
//@rename($v_zip_temp_name, $this->zipname);
WPvivid_PclZipUtilRename($v_zip_temp_name, $this->zipname);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDuplicate()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDuplicate($p_archive_filename)
{
$v_result=1;
// ----- Look if the $p_archive_filename exists
if (!is_file($p_archive_filename))
{
// ----- Nothing to duplicate, so duplicate is a success.
$v_result = 1;
// ----- Return
return $v_result;
}
// ----- Open the zip file
if (($v_result=$this->privOpenFd('wb')) != 1)
{
// ----- Return
return $v_result;
}
// ----- Open the temporary file in write mode
if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0)
{
$this->privCloseFd();
WPvivid_PclZip::privErrorLog(WPVIVID_PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode');
// ----- ReturnR
return WPvivid_PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = filesize($p_archive_filename);
while ($v_size != 0)
{
$v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = fread($v_zip_temp_fd, $v_read_size);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Close
$this->privCloseFd();
// ----- Close the temporary file
@fclose($v_zip_temp_fd);
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privErrorLog()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privErrorLog($p_error_code=0, $p_error_string='')
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
PclError($p_error_code, $p_error_string);
}
else {
$this->error_code = $p_error_code;
$this->error_string = $p_error_string;
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privErrorReset()
// Description :
// Parameters :
// --------------------------------------------------------------------------------
function privErrorReset()
{
if (PCLZIP_ERROR_EXTERNAL == 1) {
PclErrorReset();
}
else {
$this->error_code = 0;
$this->error_string = '';
}
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privDisableMagicQuotes()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privDisableMagicQuotes()
{
$v_result=1;
// EDIT for WordPress 5.3.0
// magic_quote functions are deprecated in PHP 7.4, now assuming it's always off.
/*
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
|| (!function_exists("set_magic_quotes_runtime"))) {
return $v_result;
}
// ----- Look if already done
if ($this->magic_quotes_status != -1) {
return $v_result;
}
// ----- Get and memorize the magic_quote value
$this->magic_quotes_status = @get_magic_quotes_runtime();
// ----- Disable magic_quotes
if ($this->magic_quotes_status == 1) {
@set_magic_quotes_runtime(0);
}
*/
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : privSwapBackMagicQuotes()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function privSwapBackMagicQuotes()
{
$v_result=1;
// EDIT for WordPress 5.3.0
// magic_quote functions are deprecated in PHP 7.4, now assuming it's always off.
/*
// ----- Look if function exists
if ( (!function_exists("get_magic_quotes_runtime"))
|| (!function_exists("set_magic_quotes_runtime"))) {
return $v_result;
}
// ----- Look if something to do
if ($this->magic_quotes_status != -1) {
return $v_result;
}
// ----- Swap back magic_quotes
if ($this->magic_quotes_status == 1) {
@set_magic_quotes_runtime($this->magic_quotes_status);
}
*/
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
}
// End of class
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : WPvivid_PclZipUtilPathReduction()
// Description :
// Parameters :
// Return Values :
// --------------------------------------------------------------------------------
function WPvivid_PclZipUtilPathReduction($p_dir)
{
$v_result = "";
// ----- Look for not empty path
if ($p_dir != "") {
// ----- Explode path by directory names
$v_list = explode("/", $p_dir);
// ----- Study directories from last to first
$v_skip = 0;
for ($i=sizeof($v_list)-1; $i>=0; $i--) {
// ----- Look for current path
if ($v_list[$i] == ".") {
// ----- Ignore this directory
// Should be the first $i=0, but no check is done
}
else if ($v_list[$i] == "..") {
$v_skip++;
}
else if ($v_list[$i] == "") {
// ----- First '/' i.e. root slash
if ($i == 0) {
$v_result = "/".$v_result;
if ($v_skip > 0) {
// ----- It is an invalid path, so the path is not modified
// TBC
$v_result = $p_dir;
$v_skip = 0;
}
}
// ----- Last '/' i.e. indicates a directory
else if ($i == (sizeof($v_list)-1)) {
$v_result = $v_list[$i];
}
// ----- Double '/' inside the path
else {
// ----- Ignore only the double '//' in path,
// but not the first and last '/'
}
}
else {
// ----- Look for item to skip
if ($v_skip > 0) {
$v_skip--;
}
else {
$v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:"");
}
}
}
// ----- Look for skip
if ($v_skip > 0) {
while ($v_skip > 0) {
$v_result = '../'.$v_result;
$v_skip--;
}
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : WPvivid_PclZipUtilPathInclusion()
// Description :
// This function indicates if the path $p_path is under the $p_dir tree. Or,
// said in an other way, if the file or sub-dir $p_path is inside the dir
// $p_dir.
// The function indicates also if the path is exactly the same as the dir.
// This function supports path with duplicated '/' like '//', but does not
// support '.' or '..' statements.
// Parameters :
// Return Values :
// 0 if $p_path is not inside directory $p_dir
// 1 if $p_path is inside directory $p_dir
// 2 if $p_path is exactly the same as $p_dir
// --------------------------------------------------------------------------------
function WPvivid_PclZipUtilPathInclusion($p_dir, $p_path)
{
$v_result = 1;
// ----- Look for path beginning by ./
if ( ($p_dir == '.')
|| ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) {
$p_dir = WPvivid_PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1);
}
if ( ($p_path == '.')
|| ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) {
$p_path = WPvivid_PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1);
}
// ----- Explode dir and path by directory separator
$v_list_dir = explode("/", $p_dir);
$v_list_dir_size = sizeof($v_list_dir);
$v_list_path = explode("/", $p_path);
$v_list_path_size = sizeof($v_list_path);
// ----- Study directories paths
$i = 0;
$j = 0;
while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) {
// ----- Look for empty dir (path reduction)
if ($v_list_dir[$i] == '') {
$i++;
continue;
}
if ($v_list_path[$j] == '') {
$j++;
continue;
}
// ----- Compare the items
if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) {
$v_result = 0;
}
// ----- Next items
$i++;
$j++;
}
// ----- Look if everything seems to be the same
if ($v_result) {
// ----- Skip all the empty items
while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++;
while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++;
if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) {
// ----- There are exactly the same
$v_result = 2;
}
else if ($i < $v_list_dir_size) {
// ----- The path is shorter than the dir
$v_result = 0;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : WPvivid_PclZipUtilCopyBlock()
// Description :
// Parameters :
// $p_mode : read/write compression mode
// 0 : src & dest normal
// 1 : src gzip, dest normal
// 2 : src normal, dest gzip
// 3 : src & dest gzip
// Return Values :
// --------------------------------------------------------------------------------
function WPvivid_PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0)
{
$v_result = 1;
if ($p_mode==0)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($p_src, $v_read_size);
@fwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
else if ($p_mode==1)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @gzread($p_src, $v_read_size);
@fwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
else if ($p_mode==2)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @fread($p_src, $v_read_size);
@gzwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
else if ($p_mode==3)
{
while ($p_size != 0)
{
$v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE);
$v_buffer = @gzread($p_src, $v_read_size);
@gzwrite($p_dest, $v_buffer, $v_read_size);
$p_size -= $v_read_size;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : WPvivid_PclZipUtilRename()
// Description :
// This function tries to do a simple rename() function. If it fails, it
// tries to copy the $p_src file in a new $p_dest file and then unlink the
// first one.
// Parameters :
// $p_src : Old filename
// $p_dest : New filename
// Return Values :
// 1 on success, 0 on failure.
// --------------------------------------------------------------------------------
function WPvivid_PclZipUtilRename($p_src, $p_dest)
{
$v_result = 1;
// ----- Try to rename the files
if (!@rename($p_src, $p_dest)) {
// ----- Try to copy & unlink the src
if (!@copy($p_src, $p_dest)) {
$v_result = 0;
}
else if (!@wp_delete_file($p_src)) {
$v_result = 0;
}
}
// ----- Return
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : WPvivid_PclZipUtilOptionText()
// Description :
// Translate option value in text. Mainly for debug purpose.
// Parameters :
// $p_option : the option value.
// Return Values :
// The option text value.
// --------------------------------------------------------------------------------
function WPvivid_PclZipUtilOptionText($p_option)
{
$v_list = get_defined_constants();
for (reset($v_list); $v_key = key($v_list); next($v_list)) {
$v_prefix = substr($v_key, 0, 10);
if (( ($v_prefix == 'PCLZIP_OPT')
|| ($v_prefix == 'PCLZIP_CB_')
|| ($v_prefix == 'PCLZIP_ATT'))
&& ($v_list[$v_key] == $p_option)) {
return $v_key;
}
}
$v_result = 'Unknown';
return $v_result;
}
// --------------------------------------------------------------------------------
// --------------------------------------------------------------------------------
// Function : WPvivid_PclZipUtilTranslateWinPath()
// Description :
// Translate windows path by replacing '\' by '/' and optionally removing
// drive letter.
// Parameters :
// $p_path : path to translate.
// $p_remove_disk_letter : true | false
// Return Values :
// The path translated.
// --------------------------------------------------------------------------------
function WPvivid_PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true)
{
if (function_exists('php_uname') && strpos(ini_get('disable_functions'), 'php_uname') === false)
{
if (stristr(php_uname(), 'windows')) {
// ----- Look for potential disk letter
if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) {
$p_path = substr($p_path, $v_position+1);
}
// ----- Change potential windows directory separator
if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
$p_path = strtr($p_path, '\\', '/');
}
}
}
else
{
if(DIRECTORY_SEPARATOR === '\\' && PHP_SHLIB_SUFFIX === 'dll' && PATH_SEPARATOR === ';')
{
// ----- Look for potential disk letter
if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) {
$p_path = substr($p_path, $v_position+1);
}
// ----- Change potential windows directory separator
if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
$p_path = strtr($p_path, '\\', '/');
}
}
}
return $p_path;
}
// --------------------------------------------------------------------------------
?>
includes/class-wpvivid-downloader.php 0000644 00000015036 15132770567 0014034 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_downloader
{
private $task;
public function ready_download($download_info)
{
$backup=WPvivid_Backuplist::get_backup_by_id($download_info['backup_id']);
if(!$backup)
{
return false;
}
$file_info=false;
if(isset($backup['backup']['files']))
{
foreach ($backup['backup']['files'] as $file)
{
if ($file['file_name'] == $download_info['file_name'])
{
$file_info= $file;
break;
}
}
}
else if ($backup['backup']['ismerge'] == 1)
{
$backup_files = $backup['backup']['data']['meta']['files'];
foreach ($backup_files as $file)
{
if ($file['file_name'] == $download_info['file_name'])
{
$file_info = $file;
break;
}
}
} else {
foreach ($backup['backup']['data']['type'] as $type)
{
$backup_files = $type['files'];
foreach ($backup_files as $file) {
if ($file['file_name'] == $download_info['file_name'])
{
$file_info = $file;
break;
}
}
}
}
if($file_info==false)
{
return false;
}
$backup_dir = WPvivid_Setting::get_backupdir();
$local_path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup_dir.DIRECTORY_SEPARATOR;
//$local_path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$backup['local']['path'].DIRECTORY_SEPARATOR;
$need_download_files=array();
$local_file=$local_path.$file_info['file_name'];
if(file_exists($local_file))
{
if(filesize($local_file)!=$file_info['size'])
{
if(filesize($local_file)>$file_info['size'])
{
@wp_delete_file($local_file);
}
$need_download_files[$file_info['file_name']]=$file_info;
}
}
else {
$need_download_files[$file_info['file_name']]=$file_info;
}
if(empty($need_download_files))
{
delete_option('wpvivid_download_cache');
}
else
{
if(WPvivid_taskmanager::is_download_task_running_v2($download_info['file_name']))
{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('has a downloading task,exit download.','test');
return false;
}
else
{
WPvivid_taskmanager::delete_download_task_v2($download_info['file_name']);
$task=WPvivid_taskmanager::new_download_task_v2($download_info['file_name']);
}
}
foreach ($need_download_files as $file)
{
$ret=$this->download_ex($task,$backup['remote'],$file,$local_path);
if($ret['result']==WPVIVID_FAILED)
{
return false;
}
}
return true;
}
public function download_ex(&$task,$remotes,$file,$local_path)
{
$this->task=$task;
$remote_option=array_shift($remotes);
if(is_null($remote_option))
{
return array('result' => WPVIVID_FAILED ,'error'=>'Retrieving the cloud storage information failed while downloading backups. Please try again later.');
}
global $wpvivid_plugin;
if(!class_exists('WPvivid_Remote_collection'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-remote-collection.php';
$wpvivid_plugin->remote_collection=new WPvivid_Remote_collection();
}
$remote=$wpvivid_plugin->remote_collection->get_remote($remote_option);
$ret=$remote->download($file,$local_path,array($this,'download_callback_v2'));
if($ret['result']==WPVIVID_SUCCESS)
{
$progress=100;
$wpvivid_plugin->wpvivid_download_log->WriteLog('Download completed.', 'notice');
WPvivid_taskmanager::update_download_task_v2( $task,$progress,'completed');
return $ret;
}
else
{
$progress=0;
$message=$ret['error'];
if($wpvivid_plugin->wpvivid_download_log)
{
$wpvivid_plugin->wpvivid_download_log->WriteLog('Download failed, ' . $message ,'error');
$wpvivid_plugin->wpvivid_download_log->CloseFile();
WPvivid_error_log::create_error_log($wpvivid_plugin->wpvivid_download_log->log_file);
}
else {
$id = uniqid('wpvivid-');
$log_file_name = $id . '_download';
$log = new WPvivid_Log();
$log->CreateLogFile($log_file_name, 'no_folder', 'download');
$log->WriteLog($message, 'notice');
$log->CloseFile();
WPvivid_error_log::create_error_log($log->log_file);
}
WPvivid_taskmanager::update_download_task_v2($task,$progress,'error',$message);
return $ret;
}
}
public function download_callback_v2($offset,$current_name,$current_size,$last_time,$last_size)
{
global $wpvivid_plugin;
$progress= floor(($offset/$current_size)* 100) ;
$text='Total size:'.size_format($current_size,2).' downloaded:'.size_format($offset,2);
$this->task['download_descript']=$text;
$wpvivid_plugin->wpvivid_download_log->WriteLog('Total Size: '.$current_size.', Downloaded Size: '.$offset ,'notice');
WPvivid_taskmanager::update_download_task_v2( $this->task,$progress,'running');
}
public static function delete($remote , $files)
{
global $wpvivid_plugin;
@set_time_limit(60);
if(!class_exists('WPvivid_Remote_collection'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-remote-collection.php';
$wpvivid_plugin->remote_collection=new WPvivid_Remote_collection();
}
$remote=$wpvivid_plugin->remote_collection->get_remote($remote);
$result =$remote->cleanup($files);
return $result;
}
} includes/class-wpvivid-export-import.php 0000644 00000367017 15132770567 0014540 0 ustar 00 <?php
define('WPVIVID_IMPORT_EXPORT_DIR', 'ImportandExport');
class WPvivid_Export_Import
{
public $main_tab;
public $sub_tab;
public $end_shutdown_function;
public function __construct()
{
add_action('wp_ajax_wpvivid_export_post_step2', array($this, 'export_post_step2'));
add_action('wp_ajax_wpvivid_export_post_step3', array($this, 'export_post_step3'));
add_filter('wpvivid_get_toolbar_menus',array($this,'get_toolbar_menus'),21);
add_filter('wpvivid_get_admin_menus',array($this,'get_admin_menus'),21);
add_action('wp_ajax_wpvivid_export_now', array($this, 'export_now'));
add_action('wp_ajax_wpvivid_prepare_export_post', array($this, 'prepare_export_post'));
add_action('wp_ajax_wpvivid_export_list_tasks', array($this, 'list_tasks'));
add_action('wp_ajax_wpvivid_get_post_list', array($this, 'get_list'));
add_action('wp_ajax_wpvivid_get_post_list_page', array($this, 'get_list_page'));
add_action('wp_ajax_wpvivid_get_import_list_page', array($this, 'get_import_list_page'));
add_action('wp_ajax_wpvivid_get_export_list',array($this, 'get_export_list'));
add_action('admin_head', array($this, 'my_admin_custom_styles'));
add_action('wpvivid_handle_export_success',array($this,'handle_export_success'),10);
add_action('wpvivid_handle_export_failed',array($this,'handle_export_failed'),10, 2);
add_action('wp_ajax_wpvivid_delete_export_list',array($this,'delete_export_list'),10);
add_filter('wpvivid_get_screen_ids',array($this,'get_screen_ids'),12);
add_action('wp_ajax_wpvivid_start_import', array($this, 'start_import'));
add_action('wp_ajax_wpvivid_download_export_backup', array($this, 'wpvivid_download_export_backup'));
add_action('wp_ajax_wpvivid_check_import_file', array($this, 'check_import_file'));
add_action('wp_ajax_wpvivid_upload_import_files',array($this,'upload_import_files'));
add_action('wp_ajax_wpvivid_upload_import_file_complete', array($this, 'upload_import_file_complete'));
add_action('wp_ajax_wpvivid_get_import_progress', array($this, 'get_import_progress'));
add_action('wp_ajax_wpvivid_scan_import_folder', array($this, 'wpvivid_scan_import_folder'));
add_action('wp_ajax_wpvivid_calc_import_folder_size', array($this, 'calc_import_folder_size'));
add_action('wp_ajax_wpvivid_clean_import_folder', array($this, 'clean_import_folder'));
//
$this->end_shutdown_function = false;
}
public function get_screen_ids($screen_ids)
{
$screen_ids[]='wpvivid-backup_page_wpvivid-export-import';
return $screen_ids;
}
public function get_toolbar_menus($toolbar_menus)
{
$admin_url = apply_filters('wpvivid_get_admin_url', '');
$menu['id']='wpvivid_admin_menu_export_import';
$menu['parent']='wpvivid_admin_menu';
$menu['title']=__('Export & Import', 'wpvivid-backuprestore');
$menu['tab']= 'admin.php?page=wpvivid-export-import';
$menu['href']=$admin_url . 'admin.php?page=wpvivid-export-import';
$menu['capability']='administrator';
$menu['index']=4;
$toolbar_menus[$menu['parent']]['child'][$menu['id']]=$menu;
return $toolbar_menus;
}
public function get_admin_menus($submenus)
{
$submenu['parent_slug']=WPVIVID_PLUGIN_SLUG;
$submenu['page_title']= 'WPvivid Backup';
$submenu['menu_title']=__('Export & Import', 'wpvivid-backuprestore');
$submenu['capability']='administrator';
$submenu['menu_slug']='wpvivid-export-import';
$submenu['index']=4;
$submenu['function']=array($this, 'init_page');
$submenus[$submenu['menu_slug']]=$submenu;
return $submenus;
}
public function init_page()
{
?>
<div class="wrap" style="max-width:1720px;">
<h1><?php
$plugin_display_name = 'WPvivid Backup Plugin';
$plugin_display_name = apply_filters('wpvivid_display_pro_name', $plugin_display_name);
esc_html_e('WPvivid Backup Plugin', 'wpvivid-backuprestore');
?></h1>
<div id="wpvivid_export_notice"></div>
<?php
$args['is_parent_tab']=1;
$this->main_tab=new WPvivid_Tab_Page_Container();
$this->main_tab->add_tab('Export','export',array($this, 'output_export'), $args);
$this->main_tab->add_tab('Import','import',array($this, 'output_import'), $args);
$this->main_tab->display();
?>
</div>
<?php
}
//export
public function output_export()
{
$export_dir = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR;
?>
<div class="postbox export-import-block">
<div>
<div class="wpvivid-element-space-bottom wpvivid-element-space-right" style="float: left;">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_IMAGES_URL.'export-import.png'); ?>" style="width:50px;height:50px;">
</div>
<div style="box-sizing: border-box;">
<div class="wpvivid-text-space-bottom"><?php esc_html_e('Export posts or pages with images in bulk.', 'wpvivid-backuprestore'); ?>
<span class="wpvivid-feature-pro">
<a href="https://docs.wpvivid.com/export-content.html" target="_blank" style="text-decoration: none;"><?php esc_html_e('Learn more', 'wpvivid-backuprestore'); ?></a>
</span>
</div>
<div class="wpvivid-text-space-bottom"><?php esc_html_e('This will contain all of your posts, pages, comments, terms and images (original images, featured images and thumbnails).', 'wpvivid-backuprestore'); ?></div>
<div class="wpvivid-text-space-bottom"><strong><?php esc_html_e('Note:', 'wpvivid-backuprestore'); ?></strong> <?php esc_html_e('Try to select fewer items when you are facing a shortage of server resources (typically presented as a timeout error).', 'wpvivid-backuprestore'); ?></div>
<div style="clear: both;"></div>
</div>
<div style="clear: both;"></div>
</div>
<div style="clear: both;"></div>
<div style="background: #fff; border: 1px solid #e5e5e5; border-radius: 6px; margin-bottom: 10px; padding: 10px;">
<div>
<?php
echo esc_html(sprintf('Exported files will be temporarily stored in %s directory', $export_dir));
?>
</div>
</div>
<div style="width:100%; border:1px solid #f1f1f1; float:left; box-sizing: border-box;margin-bottom:10px;">
<div style="box-sizing: border-box; margin: 1px; background-color: #f1f1f1;"><h2><?php esc_html_e('Choose post type', 'wpvivid-backuprestore'); ?></h2></div>
</div>
<div style="clear: both;"></div>
<div class="postbox wpvivid-element-space-bottom">
<div class="wpvivid-export-type-provider wpvivid-export-type-post wpvivid-export-type-provider-active" onclick="wpvivid_select_export_type('post');">
<?php esc_html_e('Post', 'wpvivid-backuprestore'); ?>
</div>
<div class="wpvivid-export-type-provider wpvivid-export-type-page" onclick="wpvivid_select_export_type('page');">
<?php esc_html_e('Page', 'wpvivid-backuprestore'); ?>
</div>
<div class="wpvivid-export-type-provider">
<?php esc_html_e('More post types coming soon...', 'wpvivid-backuprestore'); ?>
</div>
</div>
<div id="wpvivid_export_page">
<input class="button-primary wpvivid-button-export-archieve" type="submit" name="post" value="<?php esc_attr_e('Next Step', 'wpvivid-backuprestore'); ?>" />
</div>
<div class="postbox" id="wpvivid_export_task_progress" style="display: none; margin-top: 10px; margin-bottom: 0;">
<div class="action-progress-bar" id="wpvivid_export_bar_percent">
<div class="action-progress-bar-percent" style="width:0; height:24px;"></div>
</div>
<div style="clear: both;"></div>
<div style="margin-left:10px; float: left; width:100%;"><p id="wpvivid_export_current_doing"></p></div>
<div style="clear: both;"></div>
</div>
<div class="postbox" id="wpvivid_export_summary" style="display: none; margin-top: 10px; margin-bottom: 0; padding: 10px;"></div>
</div>
<script>
var export_task_id='';
var retry_count=0;
var current_export_type = 'post';
function wpvivid_select_export_type(export_type){
jQuery('.wpvivid-export-type-provider').removeClass('wpvivid-export-type-provider-active');
jQuery('.wpvivid-export-type-'+export_type).addClass('wpvivid-export-type-provider-active');
if(current_export_type !== export_type){
current_export_type = export_type;
var button_html = '<input class="button-primary wpvivid-button-export-archieve" type="submit" name="'+export_type+'" value="<?php esc_attr_e('Next Step', 'wpvivid-backuprestore'); ?>" />';
jQuery('#wpvivid_export_page').html(button_html);
jQuery('#wpvivid_export_summary').hide();
}
}
function wpvivid_archieve_export_info(post_type, is_running){
var ajax_data = {
'action':'wpvivid_export_post_step2',
'post_type': post_type
};
wpvivid_post_request(ajax_data, function(data) {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
jQuery('#wpvivid_export_page').html(jsonarray.html);
if(is_running){
jQuery('#wpvivid_export_custom').hide();
}
}
else if (jsonarray.result === 'failed') {
alert(jsonarray.error);
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('export the previously-exported settings', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_import_lock_unlock(action){
var css_pointer_event = '';
var css_opacity = '';
if(action === 'lock'){
css_pointer_event = 'none';
css_opacity = '0.4';
}
else{
css_pointer_event = 'auto';
css_opacity = '1';
}
jQuery('.wpvivid-export-type-provider').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_export_page .wpvivid-button-export-archieve').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_export_page #wpvivid-post-query-submit').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_export_page #wpvivid-post-research-submit').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('input:radio[name=contain]').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_export_page #wpvivid_start_export').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_tab_export').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_tab_import').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_empty_import_folder').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_select_import_file_button').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_upload_file_list').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('.export-list-import').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_start_import').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_rechoose_import_file').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
}
function wpvivid_export_lock_unlock(action){
var css_pointer_event = '';
var css_opacity = '';
if(action === 'lock'){
css_pointer_event = 'none';
css_opacity = '0.4';
}
else{
css_pointer_event = 'auto';
css_opacity = '1';
}
jQuery('.wpvivid-export-type-provider').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_export_page .wpvivid-button-export-archieve').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_export_page #wpvivid-post-query-submit').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_export_page #wpvivid-post-research-submit').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('input:radio[name=contain]').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
jQuery('#wpvivid_export_page #wpvivid_start_export').css({'pointer-events': css_pointer_event, 'opacity': css_opacity});
}
jQuery('#wpvivid_export_page').on("click", ".wpvivid-button-export-archieve", function(){
var post_type = jQuery(this).attr('name');
wpvivid_archieve_export_info(post_type, false);
});
jQuery('#wpvivid_export_page').on("click", "#wpvivid-post-research-submit",function()
{
jQuery('#wpvivid_post_selector').show();
jQuery('#wpvivid_post_list').hide();
});
jQuery('#wpvivid_export_page').on("click", "#wpvivid-post-query-submit",function()
{
var post_type = jQuery('#wpvivid-post-query-submit').attr('name');
var cat=jQuery('select[name=cat]').val();
var authors=jQuery('select[name=post_author]').val();
var post_start_date=jQuery('select[name=post_start_date]').val();
var post_end_date=jQuery('select[name=post_end_date]').val();
var post_ids=jQuery('input[name=post-id]').val();
var post_title=jQuery('input[name=post-title]').val();
var ajax_data = {
'action':'wpvivid_get_post_list',
'post_type': post_type,
'cat':cat,
'authors':authors,
'post_start_date':post_start_date,
'post_end_date':post_end_date,
'post_ids':post_ids,
'post_title':post_title
};
wpvivid_post_request(ajax_data, function(data) {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
jQuery('#wpvivid_post_selector').hide();
jQuery('#wpvivid_bottom_step2').show();
jQuery('#wpvivid_post_list').show();
jQuery('#wpvivid_post_list').html(jsonarray.rows);
}
else if (jsonarray.result === 'failed') {
alert(jsonarray.error);
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('export the previously-exported settings', textStatus, errorThrown);
alert(error_message);
});
});
jQuery('#wpvivid_export_page').on("click", 'input:radio[name=contain]',function() {
if(jQuery(this).val()==='list') {
jQuery('#wpvivid_export_custom').show();
}
else {
jQuery('#wpvivid_export_custom').hide();
}
});
jQuery('#wpvivid_export_page').on("keyup", '#wpvivid_set_post_comment', function(){
var post_comment = jQuery('#wpvivid_set_post_comment').val();
if(post_comment === ''){
post_comment = '*';
jQuery('#wpvivid_post_comment').html(post_comment);
}
else{
var reg = RegExp(/wpvivid/, 'i');
if (post_comment.match(reg)) {
jQuery('#wpvivid_set_post_comment').val('');
jQuery('#wpvivid_post_comment').html('*');
alert('<?php esc_html_e('You can not use word \'wpvivid\' to comment the post.', 'wpvivid-backuprestore'); ?>');
}
else{
jQuery('#wpvivid_post_comment').html(post_comment);
}
}
});
function wpvivid_check_export_status(){
var check_status = false;
jQuery('input[name="post[]"]').each(function (i) {
var id=jQuery(this).val();
if(jQuery(this).prop('checked')) {
check_status = true;
return;
}
});
return check_status;
}
jQuery('#wpvivid_export_page').on("click", '#cb-select-all-1', function() {
if(jQuery(this).prop('checked')) {
jQuery('#wpvivid_start_export').css({'pointer-events': 'auto', 'opacity': '1'});
}
else{
jQuery('#wpvivid_start_export').css({'pointer-events': 'none', 'opacity': '0.4'});
}
});
jQuery('#wpvivid_export_page').on("click", '#cb-select-all-2', function() {
if(jQuery(this).prop('checked')) {
jQuery('#wpvivid_start_export').css({'pointer-events': 'auto', 'opacity': '1'});
}
else{
jQuery('#wpvivid_start_export').css({'pointer-events': 'none', 'opacity': '0.4'});
}
});
jQuery('#wpvivid_export_page').on("click", 'input[name="post[]"]', function() {
var check_status = wpvivid_check_export_status();
if(check_status){
jQuery('#wpvivid_start_export').css({'pointer-events': 'auto', 'opacity': '1'});
}
else{
jQuery('#wpvivid_start_export').css({'pointer-events': 'none', 'opacity': '0.4'});
}
});
jQuery('#wpvivid_export_page').on("click", '#wpvivid_start_export', function(){
wpvivid_clear_notice('wpvivid_export_notice');
jQuery('#wpvivid_export_summary').hide();
var post_type = jQuery('#wpvivid_start_export').attr('name');
var select_type='all';
jQuery('input:radio[name=contain]').each(function() {
if(jQuery(this).prop('checked')) {
select_type=jQuery(this).val();
}
});
var has_item = false;
var post_ids = {};
jQuery('input[name="post[]"]').each(function (i) {
var id=jQuery(this).val();
if(jQuery(this).prop('checked')) {
post_ids[id]=1;
has_item = true;
}
else {
post_ids[id]=0;
}
});
if(select_type === 'list' && !has_item){
alert('<?php esc_html_e('Please select at least one item.', 'wpvivid-backuprestore'); ?>');
}
else{
var post_ids_json = {
'post_ids': post_ids
};
jQuery('#wpvivid_export_custom').hide();
var export_data = wpvivid_ajax_data_transfer('export');
export_data = JSON.parse(export_data);
jQuery.extend(export_data, post_ids_json);
export_data = JSON.stringify(export_data);
var ajax_data = {
'action': 'wpvivid_prepare_export_post',
'post_type': post_type,
'export_data': export_data
};
wpvivid_export_lock_unlock('lock');
wpvivid_post_request(ajax_data, function(data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
export_task_id=jsonarray.task_id;
var ajax_data = {
'action':'wpvivid_export_now',
'task_id':export_task_id
};
wpvivid_export_progpress();
wpvivid_post_request(ajax_data, function(data) {
},function(XMLHttpRequest, textStatus, errorThrown) {
});
}
else if (jsonarray.result === 'failed') {
wpvivid_export_lock_unlock('unlock');
alert(jsonarray.error);
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
wpvivid_export_lock_unlock('unlock');
var error_message = wpvivid_output_ajaxerror('export the previously-exported settings', textStatus, errorThrown);
alert(error_message);
});
}
});
jQuery('#wpvivid_export_page').on("click",'.first-page',function() {
wpvivid_change_page('first');
});
jQuery('#wpvivid_export_page').on("click",'.prev-page',function() {
var page=parseInt(jQuery(this).attr('value'));
wpvivid_change_page(page-1);
});
jQuery('#wpvivid_export_page').on("click",'.next-page',function() {
var page=parseInt(jQuery(this).attr('value'));
wpvivid_change_page(page+1);
});
jQuery('#wpvivid_export_page').on("click",'.last-page',function() {
wpvivid_change_page('last');
});
jQuery('#wpvivid_export_page').on("keypress", '.current-page', function(){
if(event.keyCode === 13){
var page = jQuery(this).val();
wpvivid_change_page(page);
}
});
function wpvivid_change_page(page) {
var post_type='post';
jQuery('input:radio[name=post_type]').each(function() {
if(jQuery(this).prop('checked'))
{
post_type=jQuery(this).val();
}
});
var post_ids = {};
jQuery('input[name="post[]"]').each(function (i) {
var id=jQuery(this).val();
if(jQuery(this).prop('checked'))
{
post_ids[id]=1;
}
else
{
post_ids[id]=0;
}
});
var ajax_data = {
'action':'wpvivid_get_post_list_page',
'post_type': post_type,
'page': page,
'post_ids':post_ids
};
wpvivid_post_request(ajax_data, function(data) {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
jQuery('#wpvivid_post_list').html(jsonarray.rows);
}
else if (jsonarray.result === 'failed') {
alert(jsonarray.error);
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('export the previously-exported settings', textStatus, errorThrown);
alert(error_message);
});
}
function wpvivid_export_progpress() {
var ajax_data = {
'action': 'wpvivid_export_list_tasks',
'task_id': export_task_id
};
jQuery('#wpvivid_export_task_progress').show();
wpvivid_post_request(ajax_data, function(data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
retry_count=0;
export_task_id=jsonarray.task_id;
if(jsonarray.show)
{
jQuery('#wpvivid_export_task_progress').show();
jQuery('#wpvivid_export_summary').hide();
jQuery('#wpvivid_export_bar_percent').html(jsonarray.percent);
jQuery('#wpvivid_export_current_doing').html(jsonarray.doing);
}
else
{
jQuery('#wpvivid_export_task_progress').hide();
}
if(jsonarray.completed)
{
wpvivid_export_lock_unlock('unlock');
//jQuery('#wpvivid_export_notice').show();
//jQuery('#wpvivid_export_notice').append(jsonarray.doing);
jQuery('#wpvivid_export_summary').show();
jQuery('#wpvivid_export_summary').html(jsonarray.doing);
jQuery('html, body').animate({scrollTop: jQuery("#wpvivid_export_notice").offset().top}, 'slow');
wpvivid_download_export(jsonarray.file_name, jsonarray.file_size);
}
if(jsonarray.continue)
{
wpvivid_export_lock_unlock('lock');
setTimeout(function ()
{
wpvivid_export_progpress();
}, 3000);
}
if(jsonarray.error){
wpvivid_export_lock_unlock('unlock');
jQuery('#wpvivid_export_notice').show();
jQuery('#wpvivid_export_notice').append(jsonarray.doing);
jQuery('html, body').animate({scrollTop: jQuery("#wpvivid_export_notice").offset().top}, 'slow');
}
}
else
{
alert(jsonarray.error);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
retry_count++;
if(retry_count<3)
{
setTimeout(function () {
wpvivid_export_progpress();
}, 3000);
}
});
}
function wpvivid_download_export(file_name, file_size){
location.href =ajaxurl+'?_wpnonce='+wpvivid_ajax_object.ajax_nonce+'&action=wpvivid_download_export_backup&file_name='+file_name+'&file_size='+file_size;
}
jQuery(document).ready(function (){
<?php
$task_id = false;
$post_type = false;
$tasks=WPvivid_Exporter_taskmanager::get_tasks();
foreach ($tasks as $task){
$task_id = $task['id'];
$post_type = $task['options']['backup_options']['post_type'];
break;
}
?>
var task_id = '<?php echo esc_attr($task_id); ?>';
if(task_id != false){
export_task_id = task_id;
wpvivid_export_lock_unlock('lock');
wpvivid_export_progpress();
}
});
</script>
<?php
}
public function export_post_step2()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(isset($_POST['post_type']))
{
global $wpdb;
$post_type = sanitize_text_field($_POST['post_type']);
$descript_type = $post_type === 'post' ? 'posts' : 'pages';
$btn_text = $post_type === 'post' ? __('Show Posts', 'wpvivid-backuprestore') : __('Show Pages', 'wpvivid-backuprestore');
ob_start();
?>
<div style="width:100%; border:1px solid #f1f1f1; float:left; box-sizing: border-box;margin-bottom:10px;">
<div style="box-sizing: border-box; margin: 1px; background-color: #f1f1f1;"><h2><?php esc_html_e('Choose what to export', 'wpvivid-backuprestore'); ?></h2></div>
</div>
<div style="clear: both;"></div>
<div style="width:100%; border:1px solid #f1f1f1; float:left; padding:10px 10px 0 10px;margin-bottom:10px; box-sizing: border-box;">
<fieldset>
<legend class="screen-reader-text"><span>input type="radio"</span></legend>
<div class="wpvivid-element-space-bottom wpvivid-element-space-right" style="float: left;">
<label>
<input type="radio" option="export" name="contain" value="list" checked/><?php esc_html_e('Filter Posts/Pages', 'wpvivid-backuprestore'); ?>
</label>
</div>
<div style="clear: both;"></div>
</fieldset>
<div id="wpvivid_export_custom" style="margin-bottom: 10px;">
<table id="wpvivid_post_selector" class="wp-list-table widefat plugins" style="width:100%; border:1px solid #f1f1f1;">
<tbody>
<?php
if($post_type !== 'page') {
?>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form regular-text">
<?php
wp_dropdown_categories(
array(
'class' => 'regular-text',
'show_option_all' => __('All Categories', 'wpvivid-backuprestore')
)
);
?>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i>
<?php
echo esc_html(sprintf('Export %s of all categories or a specific category.', $descript_type));
?>
</i>
</div>
</td>
</tr>
<?php
}
?>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form regular-text">
<?php
$authors = $wpdb->get_col( "SELECT DISTINCT post_author FROM {$wpdb->posts} WHERE post_type = '$post_type'" );
wp_dropdown_users(
array(
'class' => 'regular-text',
'include' => $authors,
'name' => 'post_author',
'multi' => true,
'show_option_all' => __( 'All Authors', 'wpvivid-backuprestore' ),
'show' => 'display_name_with_login',
)
);
?>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i>
<?php
echo esc_html(sprintf('Export %s of all authors or a specific author.', $descript_type));
?>
</i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form regular-text">
<label for="post-start-date" class="label-responsive" style="display: block;"></label>
<select class="regular-text" name="post_start_date" id="post-start-date">
<option value="0"><?php esc_html_e( '— Select —', 'wpvivid-backuprestore' ); ?></option>
<?php $this->export_date_options($post_type); ?>
</select>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i>
<?php
echo esc_html(sprintf('Export %s published after this date.', $descript_type));
?>
</i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form regular-text">
<label for="post-end-date" class="label-responsive" style="display: block;"></label>
<select class="regular-text" name="post_end_date" id="post-end-date">
<option value="0"><?php esc_html_e( '— Select —', 'wpvivid-backuprestore' ); ?></option>
<?php $this->export_date_options($post_type); ?>
</select>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i>
<?php
echo esc_html(sprintf('Export %s published before this date.', $descript_type));
?>
</i>
</div>
</td>
</tr>
<tr style="display: none;">
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" id="post-search-id-input" name="post-id" autocomplete="off" value=""/>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i>Enter a <?php echo esc_html($post_type); ?> ID.(optional)</i>
</div>
</td>
</tr>
<tr style="display: none;">
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input type="text" class="regular-text" id="post-search-title-input" name="post-title" autocomplete="off" value=""/>
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i>Enter a <?php echo esc_html($post_type); ?> title.(optional)</i>
</div>
</td>
</tr>
<tr>
<td class="plugin-title column-primary">
<div class="wpvivid-storage-form">
<input class="button-primary" id="wpvivid-post-query-submit" type="submit" name="<?php echo esc_attr($post_type); ?>" value="<?php echo esc_attr($btn_text); ?>" />
</div>
</td>
<td class="column-description desc">
<div class="wpvivid-storage-form-desc">
<i>
<?php
echo esc_html(sprintf('Search for %s according to the above rules.', $post_type));
?>
</i>
</div>
</td>
</tr>
</tbody>
</table>
<div id="wpvivid_post_list"></div>
</div>
</div>
<div style="width:100%; border:1px solid #f1f1f1; float:left; box-sizing: border-box;margin-bottom:10px;">
<div style="box-sizing: border-box; margin: 1px; background-color: #f1f1f1;"><h2><?php esc_html_e('Comment the export (optional)', 'wpvivid-backuprestore'); ?></h2></div>
</div>
<div style="clear: both;"></div>
<div style="width:100%; border:1px solid #f1f1f1; float:left; padding:10px 10px 0 10px;margin-bottom:10px; box-sizing: border-box;">
<div>
<div class="wpvivid-element-space-bottom wpvivid-text-space-right" style="float: left; padding-top: 6px;"><?php esc_html_e('Comment the export: ', 'wpvivid-backuprestore'); ?></div>
<div class="wpvivid-element-space-bottom wpvivid-text-space-right" style="float: left;">
<input type="text" option="export" name="post_comment" id="wpvivid_set_post_comment" onkeyup="value=value.replace(/[^a-zA-Z0-9]/g,'')" onpaste="value=value.replace(/[^\a-\z\A-\Z0-9]/g,'')" />
</div>
<div class="wpvivid-element-space-bottom wpvivid-text-space-right" style="float: left; padding-top: 6px;"><?php esc_html_e('Only letters (except for wpvivid) and numbers are allowed.', 'wpvivid-backuprestore'); ?></div>
<div style="clear: both;"></div>
</div>
<div>
<div class="wpvivid-element-space-bottom wpvivid-text-space-right" style="float: left;"><?php esc_html_e('Sample:', 'wpvivid-backuprestore'); ?></div>
<div class="wpvivid-element-space-bottom" style="float: left;">
<div class="wpvivid-element-space-bottom" style="display: inline;" id="wpvivid_post_comment">*</div><div class="wpvivid-element-space-bottom" style="display: inline;">_wpvivid-5dbf8d6a5f133_2019-11-08-03-15_export_<?php echo esc_html($post_type); ?>.zip</div>
</div>
<div style="clear: both;"></div>
</div>
</div>
<div>
<input class="button-primary" id="wpvivid_start_export" type="submit" name="<?php echo esc_attr($post_type); ?>" value="<?php esc_attr_e('Export and Download', 'wpvivid-backuprestore'); ?>" style="pointer-events: none; opacity: 0.4;">
</div>
<?php
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
}
else
{
$ret['result']='failed';
$ret['error']='not set post type';
}
echo wp_json_encode($ret);
die();
}
public function export_post_step3()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$post_type=sanitize_text_field($_POST['post_type']);
$post_all=sanitize_text_field($_POST['all']);
if(isset($post_type)&&isset($post_all))
{
$old_post_ids=array();
if(isset($_POST['post_ids']))
{
$old_post_ids=$_POST['post_ids'];
$old_post_ids = array_map( 'sanitize_key', $old_post_ids );
$old_post_ids=(int)$old_post_ids;
}
$list_cache=get_option('wpvivid_list_cache',array());
foreach ($old_post_ids as $id=>$checked)
{
if(isset($list_cache[$id]))
{
$list_cache[$id]['checked']=$checked;
}
}
WPvivid_Setting::update_option('wpvivid_list_cache',$list_cache);
$post_count=0;
if($post_all=='all')
{
global $wpdb;
$where = $wpdb->prepare( "post_type =%s", $post_type);
$posts_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} WHERE $where" );
$post_count=sizeof($posts_ids);
}
else
{
foreach ($list_cache as $id=>$item)
{
if($item['checked'])
$post_count++;
}
}
ob_start();
?>
<h2>Export post type:<strong><?php echo esc_html($post_type)?></strong></h2>
<p>
Selected post(s):<?php echo esc_html($post_count)?>
</p>
<p class="submit">
<input type="button" class="button button-primary wpvivid-export-step3-prev" value="Prev step">
<input type="button" class="button button-primary" id="wpvivid_start_export" value="Start Export">
</p>
<?php
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
}
else
{
$ret['result']='failed';
$ret['error']='not set post type';
}
echo wp_json_encode($ret);
die();
}
public function my_admin_custom_styles()
{
echo '<style type="text/css">
.column-file_name { width:25% }
.column-export_type { width:8% }
.column-posts_count { width:8% }
.column-media_size { width:8% }
.column-import { width:8% }
</style>';
}
public function get_list()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(!isset($_POST['post_type'])&&!isset($_POST['cat'])&&!isset($_POST['authors'])&&!isset($_POST['post_start_date'])&&!isset($_POST['post_end_date']))
{
die();
}
if(isset($_POST['post_ids'])&&!empty($_POST['post_ids']))
{
$select_post_id=$_POST['post_ids'];
$select_post_id = array_map( 'sanitize_key', $select_post_id );
$select_post_id=(int)$select_post_id;
}
else
{
$select_post_id=0;
}
if(isset($_POST['post_title'])&&!empty($_POST['post_title']))
{
$post_title=sanitize_text_field($_POST['post_title']);
}
else
{
$post_title='';
}
//
$post_type=sanitize_text_field($_POST['post_type']);
if(isset($_POST['cat'])) {
$cat = (int)sanitize_key($_POST['cat']);
}
$author=(int)sanitize_key($_POST['authors']);
$post_start_date=sanitize_text_field($_POST['post_start_date']);
$post_end_date=sanitize_text_field($_POST['post_end_date']);
global $wpdb;
$where = $wpdb->prepare( "post_type =%s", $post_type);
$join = '';
if(isset($_POST['cat'])) {
if ($term = term_exists($cat, 'category')) {
$join = "INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)";
$where .= $wpdb->prepare(" AND {$wpdb->term_relationships}.term_taxonomy_id = %d", $term['term_taxonomy_id']);
}
}
if ( $author )
{
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_author = %d", $author );
}
if ( $post_start_date )
{
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date >= %s", gmdate( 'Y-m-d', strtotime( $post_start_date ) ) );
}
if ( $post_end_date )
{
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_date < %s", gmdate( 'Y-m-d', strtotime( '+1 month', strtotime( $post_end_date ) ) ) );
}
if($select_post_id)
{
$where .= $wpdb->prepare( " AND {$wpdb->posts}.ID = %d", $select_post_id );
}
if($post_title)
{
$where .= $wpdb->prepare( " AND {$wpdb->posts}.post_title LIKE %s", '%' . $wpdb->esc_like($post_title) . '%' );
}
$posts_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} $join WHERE $where" );
asort($posts_ids);
$list_cache=array();
foreach ($posts_ids as $id)
{
$post_id['id']=$id;
$post_id['checked']=0;
$list_cache[$id]=$post_id;
}
WPvivid_Setting::update_option('wpvivid_list_cache',$list_cache);
$page=1;
$arg['screen']=$post_type;
$myListTable = new WPvivid_Post_List($arg);
$myListTable->set_post_ids($list_cache,$page);
$myListTable->prepare_items();
ob_start();
$myListTable->display();
$rows = ob_get_clean();
$ret['result']='success';
$ret['rows']=$rows;
echo wp_json_encode($ret);
die();
}
public function get_export_list()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$list = get_option('wpvivid_export_list',array());
$display_list=new WPvivid_Export_List();
$display_list->set_parent('wpvivid_import_list');
$display_list->set_list($list);
$display_list->prepare_items();
ob_start();
$display_list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['html']=$html;
echo wp_json_encode($ret);
die();
}
public function get_list_page()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(!isset($_POST['post_type'])&&!isset($_POST['page']))
{
die();
}
$list_cache=get_option('wpvivid_list_cache',array());
WPvivid_Setting::update_option('wpvivid_list_cache',$list_cache);
$page=sanitize_key($_POST['page']);
$post_type=sanitize_text_field($_POST['post_type']);
$arg['screen']=$post_type;
$myListTable = new WPvivid_Post_List($arg);
$myListTable->set_post_ids($list_cache,$page);
$myListTable->prepare_items();
ob_start();
$myListTable->display();
$rows = ob_get_clean();
$ret['result']='success';
$ret['rows']=$rows;
echo wp_json_encode($ret);
die();
}
public function export_date_options($post_type = 'post')
{
global $wpdb, $wp_locale;
$months = $wpdb->get_results(
$wpdb->prepare(
"
SELECT DISTINCT YEAR( post_date ) AS year, MONTH( post_date ) AS month
FROM $wpdb->posts
WHERE post_type = %s AND post_status != 'auto-draft'
ORDER BY post_date DESC
",
$post_type
)
);
$month_count = count( $months );
if ( ! $month_count || ( 1 == $month_count && 0 == $months[0]->month ) ) {
return;
}
foreach ( $months as $date ) {
if ( 0 == $date->year ) {
continue;
}
$month = zeroise( $date->month, 2 );
echo '<option value="' . esc_attr($date->year) . '-' . esc_attr($month) . '">' . esc_html($wp_locale->get_month( $month ) . ' ' . $date->year) . '</option>';
}
}
public function prepare_export_post()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(isset($_POST['post_type'])&&isset($_POST['export_data']))
{
$post_type = sanitize_text_field($_POST['post_type']);
$json_export = sanitize_text_field($_POST['export_data']);
$json_export = stripslashes($json_export);
$export_data = json_decode($json_export, true);
$post_ids=array();
$posts_ids=array();
if(isset($export_data['post_ids']) && !empty($export_data['post_ids']))
{
$post_ids=$export_data['post_ids'];
}
foreach ($post_ids as $id=>$checked)
{
if($checked)
{
$posts_ids[]=$id;
}
}
if(empty($posts_ids))
{
$ret['result']='failed';
$ret['error']=__('Empty post id', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
if(WPvivid_Exporter_taskmanager::is_tasks_running())
{
$ret['result']='failed';
$ret['error']=__('A task is already running. Please wait until the running task is complete, and try again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$export_task=new WPvivid_Exporter_task();
$options['post_ids']=$posts_ids;
$options['post_type']=$post_type;
$options['post_comment']=$export_data['post_comment'];
$ret=$export_task->new_backup_task($options);
echo wp_json_encode($ret);
}
die();
}
public function export_now()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
if (!isset($_POST['task_id']) || empty($_POST['task_id']) || !is_string($_POST['task_id']))
{
$ret['result'] = 'failed';
$ret['error'] = __('Error occurred while parsing the request data. Please try to run export task again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$task_id = sanitize_key($_POST['task_id']);
if(WPvivid_Exporter_taskmanager::is_tasks_running())
{
$ret['result'] = 'failed';
$ret['error'] = __('A task is already running. Please wait until the running task is complete, and try again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$this->export_post($task_id);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function export_post($task_id)
{
$this->end_shutdown_function = false;
register_shutdown_function(array($this,'deal_shutdown_error'),$task_id);
@ignore_user_abort(true);
WPvivid_Exporter_taskmanager::update_backup_task_status($task_id,true,'running');
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->OpenLogFile(WPvivid_Exporter_taskmanager::get_task_options($task_id,'log_file_name'));
$wpvivid_plugin->wpvivid_log->WriteLog('Start export posts.','notice');
$wpvivid_plugin->wpvivid_log->WriteLogHander();
$this->flush($task_id);
$export=new WPvivid_Exporter();
@set_time_limit(900);
try
{
$ret = $export->export($task_id);
if($ret['result']=='success')
{
do_action('wpvivid_handle_export_success', $task_id, true);
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog($ret['error'],'error');
WPvivid_Exporter_taskmanager::update_backup_task_status($task_id, false, 'error', false, false, $ret['error']);
do_action('wpvivid_handle_export_failed', $task_id, true);
}
}
catch (Exception $error)
{
$message = 'An error has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
error_log($message);
WPvivid_Exporter_taskmanager::update_backup_task_status($task_id,false,'error',false,false,$message);
$wpvivid_plugin->wpvivid_log->WriteLog($message,'error');
$this->end_shutdown_function=true;
die();
}
echo wp_json_encode($ret);
$this->end_shutdown_function=true;
die();
}
public function deal_shutdown_error($task_id)
{
if($this->end_shutdown_function===false)
{
global $wpvivid_plugin;
$last_error = error_get_last();
if (!empty($last_error) && !in_array($last_error['type'], array(E_NOTICE,E_WARNING,E_USER_NOTICE,E_USER_WARNING,E_DEPRECATED), true))
{
$error = $last_error;
} else {
$error = false;
}
if (WPvivid_Exporter_taskmanager::get_task($task_id) !== false)
{
if ($wpvivid_plugin->wpvivid_log->log_file_handle == false)
{
$wpvivid_plugin->wpvivid_log->OpenLogFile(WPvivid_Exporter_taskmanager::get_task_options($task_id, 'log_file_name'));
}
$status = WPvivid_Exporter_taskmanager::get_backup_task_status($task_id);
$message='in shutdown';
if ($error !== false)
{
$message= 'type: '. $error['type'] . ', ' . $error['message'] . ' file:' . $error['file'] . ' line:' . $error['line'];
}
WPvivid_Exporter_taskmanager::update_backup_task_status($task_id, false, 'error', false, $status['resume_count'], $message);
if ($wpvivid_plugin->wpvivid_log)
$wpvivid_plugin->wpvivid_log->WriteLog($message, 'error');
}
die();
}
}
public function handle_export_success($task_id)
{
global $wpvivid_plugin;
WPvivid_Exporter_taskmanager::update_backup_task_status($task_id,false,'completed');
$wpvivid_plugin->wpvivid_log->WriteLog('Finished to export post','notice');
}
public function handle_export_failed($task_id)
{
}
public function list_tasks()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$ret['result']='success';
$ret['show']=false;
$tasks=WPvivid_Exporter_taskmanager::get_tasks();
foreach ($tasks as $task)
{
$this->task_monitor($task['id']);
$task=WPvivid_Exporter_taskmanager::get_task($task['id']);
$status=WPvivid_Exporter_taskmanager::get_backup_task_status($task['id']);
$ret['show']=true;
$ret['completed']=false;
$ret['error']=false;
if($status['str']=='running'||$status['str']=='no_responds'||$status['str']=='ready')
{
$ret['continue']=1;
}
else
{
$ret['continue']=0;
$ret['show']=false;
}
$progress=WPvivid_Exporter_taskmanager::get_backup_tasks_progress($task['id']);
$ret['percent']='<div class="action-progress-bar-percent" style="height:24px;width:'.(int)$progress['progress'].'%;"></div>';
$ret['doing']=$task['data']['doing']='export';
if($status['str']=='ready')
{
$ret['doing']=__('Ready to export. Progress: 0%, running time: 0second.','wpvivid-backuprestore');
}
else if($status['str']=='running')
{
$ret['doing']= ' '.__('Progress: ', 'wpvivid-backuprestore') . $progress['descript'] . ', '.__('running time: ', 'wpvivid-backuprestore') . $progress['running_time'];
}
else if($status['str']=='wait_resume')
{
$ret['doing']='Task '.$task['id'].' timed out, the export task will retry in '.$task['data']['next_resume_time'].' seconds, retry times: '.$task['status']['resume_count'].'.';
}
else if($status['str']=='no_responds')
{
$ret['doing']=__('The export task is not responding.','wpvivid-backuprestore');
}
else if($status['str']=='completed')
{
$file_name = $task['data']['export']['export_info']['file_name'];
$file_size = $task['data']['export']['export_info']['size'];
if($task['options']['backup_options']['post_type'] === 'post'){
$post_type = 'posts';
}
else{
$post_type = 'pages';
}
$msg = '<div style="margin-bottom: 10px;">The export task is completed and the automatic download starts. If the automatic download didn\'t run, please click <a style="cursor:pointer;" onclick="wpvivid_download_export(\''.$file_name.'\', \''.$file_size.'\');">here</a> to download.</div>';
$msg .= '<div style="margin-bottom: 10px;">The count of exported '.$post_type.': '.$task['data']['export']['export_info']['post_count'].'.</div>';
$msg .= '<div style="margin-bottom: 10px;">File name: '.$file_name.'.</div>';
$msg .= '<div>File size: '.size_format($file_size, 2).'.</div>';
$ret['completed']=true;
$ret['file_name'] = $file_name;
$ret['file_size'] = $file_size;
$ret['doing']=$msg;
}
else if($status['str']=='error')
{
$ret['doing']='Export error: '.$task['status']['error'];
$ret['doing']='<div class="notice notice-error is-dismissible inline"><p>'.__('Export error:', 'wpvivid-backuprestore').' '.$task['status']['error'].'</p></div>';
$ret['error']=true;
}
if($ret['completed']||$ret['error'])
{
WPvivid_Exporter_taskmanager::delete_task($task['id']);
}
}
echo wp_json_encode($ret);
die();
}
public function task_monitor($task_id)
{
global $wpvivid_plugin;
if(WPvivid_Exporter_taskmanager::get_task($task_id)!==false)
{
if($wpvivid_plugin->wpvivid_log->log_file_handle==false)
{
$wpvivid_plugin->wpvivid_log->OpenLogFile(WPvivid_Exporter_taskmanager::get_task_options($task_id,'log_file_name'));
}
$status=WPvivid_Exporter_taskmanager::get_backup_task_status($task_id);
if($status['str']=='running'||$status['str']=='error'||$status['str']=='no_responds')
{
$limit=900;
$time_spend=time()-$status['timeout'];
if($time_spend>=$limit)
{
//time out
$message=__('Task time out.', 'wpvivid-backuprestore');
WPvivid_Exporter_taskmanager::update_backup_task_status($task_id,false,'error',false,$status['resume_count'],$message);
if($wpvivid_plugin->wpvivid_log)
$wpvivid_plugin->wpvivid_log->WriteLog($message,'error');
$wpvivid_plugin->wpvivid_log->CloseFile();
WPvivid_error_log::create_error_log($wpvivid_plugin->wpvivid_log->log_file);
}
else {
$time_spend=time()-$status['run_time'];
if($time_spend>180)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Not responding for a long time.','notice');
WPvivid_Exporter_taskmanager::update_backup_task_status($task_id,false,'no_responds',false,$status['resume_count']);
}
}
}
}
}
public function delete_export_list()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(isset($_POST['export_id']))
{
$id=sanitize_key($_POST['export_id']);
$list = get_option('wpvivid_import_list_cache',array());
if(empty($list))
{
$ret['result']='success';
}
else
{
if(isset($list[$id]))
{
$item=$list[$id];
if(isset($item['export']))
{
foreach ($item['export'] as $file)
{
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR.DIRECTORY_SEPARATOR.$file['file_name'];
@wp_delete_file($path);
}
}
unset($list[$id]);
WPvivid_Setting::update_option('wpvivid_import_list_cache',$list);
$ret['result']='success';
}
else
{
$ret['result']='success';
}
}
echo wp_json_encode($ret);
}
die();
}
public function wpvivid_download_export_backup()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try{
if(isset($_REQUEST['file_name']) && !empty($_REQUEST['file_name']) && is_string($_REQUEST['file_name']) &&
isset($_REQUEST['file_size']) && !empty($_REQUEST['file_size']) && is_string($_REQUEST['file_size'])){
$file_name = sanitize_text_field($_REQUEST['file_name']);
$file_size = intval(sanitize_key($_REQUEST['file_size']));
$file_name = basename($file_name);
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR.DIRECTORY_SEPARATOR.$file_name;
if (file_exists($path)) {
if (session_id()) {
session_write_close();
}
$size = filesize($path);
if($size === $file_size) {
if (!headers_sent()) {
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . basename($path) . '"');
header('Cache-Control: must-revalidate');
header('Content-Length: ' . $size);
header('Content-Transfer-Encoding: binary');
}
if ($size < 1024 * 1024 * 60) {
ob_end_clean();
readfile($path);
exit;
} else {
ob_end_clean();
$download_rate = 1024 * 10;
$file = fopen($path, "r");
while (!feof($file)) {
@set_time_limit(20);
// send the current file part to the browser
print fread($file, round($download_rate * 1024));
// flush the content to the browser
flush();
// sleep one second
sleep(1);
}
fclose($file);
exit;
}
}
else{
$admin_url = admin_url();
echo '<a href="'.esc_url($admin_url).'admin.php?page=wpvivid-export-import">';
esc_html_e('File size not match. please retry again.', 'wpvivid-backuprestore');
echo '</a>';
die();
}
}
$admin_url = admin_url();
echo '<a href="'.esc_url($admin_url).'admin.php?page=wpvivid-export-import">';
esc_html_e('File not found. Please retry again.', 'wpvivid-backuprestore');
echo '</a>';
die();
}
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
}
//import
public function output_import()
{
$import_dir = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR;
WPvivid_Setting::update_option('wpvivid_import_list_cache',array());
WPvivid_Setting::update_option('wpvivid_importer_task_list', array());
?>
<div class="postbox export-import-block">
<div>
<div class="wpvivid-element-space-bottom wpvivid-element-space-right" style="float: left;">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_IMAGES_URL.'export-import.png'); ?>" style="width:50px;height:50px;">
</div>
<div style="box-sizing: border-box;">
<div class="wpvivid-element-space-bottom wpvivid-element-space-right"><?php esc_html_e('Import posts or pages with images in bulk.', 'wpvivid-backuprestore'); ?>
<span class="wpvivid-feature-pro">
<a href="https://wpvivid.com/import-content" target="_blank" style="text-decoration: none;"><?php esc_html_e('Learn more', 'wpvivid-backuprestore'); ?></a>
</span>
</div>
<div class="wpvivid-element-space-bottom wpvivid-element-space-right"><strong><?php esc_html_e('Note:', 'wpvivid-backuprestore'); ?></strong>
<?php esc_html_e('To properly display the imported content, please make sure that the importing and exporting sites have the same environment, for example, same theme or pages built with the same page builder.', 'wpvivid-backuprestore'); ?>
</div>
<div style="clear: both;"></div>
</div>
<div style="clear: both;"></div>
</div>
<div style="clear: both;"></div>
<div style="background: #fff; border: 1px solid #e5e5e5; border-radius: 6px; margin-bottom: 10px; padding: 10px;">
<div style="margin-right: 10px; float: left; height: 28px; line-height: 28px;"><?php echo esc_html(sprintf('Imported files will be temporarily stored in %s directory', $import_dir)) ?></div>
<div style="float: left;"><input class="button" type="submit" id="wpvivid_empty_import_folder" value="<?php esc_attr_e('Delete Exported Files In Folder', 'wpvivid-backuprestore'); ?>" onclick="wpvivid_clean_import_folder();" /></div>
<div style="clear: both;"></div>
</div>
<div id="wpvivid_import_step1">
<p><?php esc_html_e('Choose an export from your computer to import: ', 'wpvivid-backuprestore'); ?></p>
<input class="button button-primary" type="button" id="wpvivid_select_import_file_button" value="<?php esc_attr_e('Upload and Import', 'wpvivid-backuprestore'); ?>" />
<div id="wpvivid_upload_file_list" class="hide-if-no-js" style="margin-top: 10px; display: none;"></div>
<br>
<p><?php echo esc_html(sprintf('Or you can use ftp to upload the export to the directory %s. Then click the button below to scan the file to import.', $import_dir)); ?></p>
<input class="button button-primary" type="button" value="<?php esc_attr_e('Scan Uploaded Exports', 'wpvivid-backuprestore'); ?>" onclick="wpvivid_refresh_import_list();" />
<div class="wpvivid-export-import-block" id="wpvivid_import_list" style="margin-top: 10px; display: none;"></div>
</div>
<div id="wpvivid_import_step2" style="display: none;">
<h3><?php esc_html_e('The importing file info', 'wpvivid-backuprestore'); ?></h3>
<div id="wpvivid_import_file_data">
</div>
<h3><?php esc_html_e('Assign author', 'wpvivid-backuprestore'); ?></h3>
<div>
<?php esc_html_e('Select an existing author:', 'wpvivid-backuprestore'); ?>
<?php wp_dropdown_users( array( 'name' => "user_map", 'multi' => true, 'show_option_all' => __( '- Select -', 'wpvivid-backuprestore' ) ) );?>
</div>
<h3><?php esc_html_e('Import Setting', 'wpvivid-backuprestore'); ?></h3>
<div style="margin-bottom: 10px;">
<label>
<input type="checkbox" id="wpvivid_overwrite_existing" />
<span><strong id="wpvivid_import_type"><?php esc_html_e('Overwrite existing pages', 'wpvivid-backuprestore'); ?></strong></span>
</label>
</div>
<div style="margin-bottom: 10px;">
<span><?php esc_html_e('With this option checked, Pages/posts already existing will be overwritten with the updated ones in an import.', 'wpvivid-backuprestore'); ?></span>
</div>
<input class="button button-primary" type="button" id="wpvivid_start_import" value="<?php esc_attr_e('Import', 'wpvivid-backuprestore'); ?>" />
<input class="button button-primary" type="button" id="wpvivid_rechoose_import_file" value="<?php esc_attr_e('Back', 'wpvivid-backuprestore'); ?>" />
</div>
<div id="wpvivid_import_step3" style="display: none;">
<div class="postbox wpvivid-import-log" id="wpvivid_import_log" style="margin-top: 10px; margin-bottom: 0;"></div>
</div>
</div>
<?php
$chunk_size = min(wp_max_upload_size()-1024, 1048576*2);
$plupload_init = array(
'runtimes' => 'html5,silverlight,flash,html4',
'browse_button' => 'wpvivid_select_import_file_button',
'file_data_name' => 'async-upload',
'max_retries' => 3,
'multiple_queues' => true,
'max_file_size' => '10Gb',
'chunk_size' => $chunk_size.'b',
'url' => admin_url('admin-ajax.php'),
'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
'multipart' => true,
'urlstream_upload' => true,
'multi_selection' => false,
// additional post data to send to our ajax hook
'multipart_params' => array(
'_ajax_nonce' => wp_create_nonce('wpvivid_ajax'),
'action' => 'wpvivid_upload_import_files', // the ajax action name
),
);
if (is_file(ABSPATH.WPINC.'/js/plupload/Moxie.swf')) {
$plupload_init['flash_swf_url'] = includes_url('js/plupload/Moxie.swf');
} else {
$plupload_init['flash_swf_url'] = includes_url('js/plupload/plupload.flash.swf');
}
if (is_file(ABSPATH.WPINC.'/js/plupload/Moxie.xap')) {
$plupload_init['silverlight_xap_url'] = includes_url('js/plupload/Moxie.xap');
} else {
$plupload_init['silverlight_xap_url'] = includes_url('js/plupload/plupload.silverlight.swf');
}
// we should probably not apply this filter, plugins may expect wp's media uploader...
$plupload_init = apply_filters('plupload_init', $plupload_init);
$upload_file_image = includes_url( '/images/media/archive.png' );
?>
<script type="text/javascript">
var uploader;
var import_file_name='';
jQuery(document).ready(function($)
{
// create the uploader and pass the config from above
jQuery('#wpvivid_upload_submit_btn').hide();
uploader = new plupload.Uploader(<?php echo wp_json_encode($plupload_init); ?>);
// checks if browser supports drag and drop upload, makes some css adjustments if necessary
uploader.bind('Init', function(up)
{
var uploaddiv = $('#wpvivid_plupload-upload-ui');
if(up.features.dragdrop){
uploaddiv.addClass('drag-drop');
$('#drag-drop-area')
.bind('dragover.wp-uploader', function(){ uploaddiv.addClass('drag-over'); })
.bind('dragleave.wp-uploader, drop.wp-uploader', function(){ uploaddiv.removeClass('drag-over'); });
}else{
uploaddiv.removeClass('drag-drop');
$('#drag-drop-area').unbind('.wp-uploader');
}
});
uploader.init();
function wpvivid_check_plupload_added_files(up, files)
{
jQuery('#wpvivid_import_list').hide();
var file=files[0];
var ajax_data = {
'action': 'wpvivid_check_import_file',
'file_name':file.name
};
wpvivid_post_request(ajax_data, function (data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === "success")
{
jQuery('#wpvivid_select_import_file_button').css({'pointer-events': 'none', 'opacity': '0.4'});
var repeat_files = '';
plupload.each(files, function(file)
{
var brepeat=false;
var file_list = jQuery('#wpvivid_upload_file_list span');
file_list.each(function (index, value) {
if (value.innerHTML === file.name) {
brepeat=true;
}
});
if(!brepeat) {
jQuery('#wpvivid_upload_file_list').append(
'<div id="' + file.id + '" style="width: 100%; height: 36px; background: #f1f1f1; margin-bottom: 1px;">' +
'<img src=" <?php echo esc_attr($upload_file_image); ?> " alt="" style="float: left; margin: 2px 10px 0 3px; max-width: 40px; max-height: 32px;">' +
'<div style="line-height: 36px; float: left; margin-left: 5px;"><span>' + file.name + '</span></div>' +
'<div class="fileprogress" style="line-height: 36px; float: right; margin-right: 5px;"></div>' +
'</div>' +
'<div style="clear: both;"></div>'
);
jQuery('#wpvivid_upload_file_list').show();
uploader.refresh();
uploader.start();
}
else{
if(repeat_files === ''){
repeat_files += file.name;
}
else{
repeat_files += ', ' + file.name;
}
}
});
if(repeat_files !== ''){
alert(repeat_files + " already exists in upload list.");
repeat_files = '';
}
}
else if(jsonarray.result === "failed")
{
uploader.removeFile(file);
alert(jsonarray.error);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('uploading backups', textStatus, errorThrown);
uploader.removeFile(file);
alert(error_message);
});
}
uploader.bind('FilesAdded', wpvivid_check_plupload_added_files);
uploader.bind('Error', function(up, error)
{
alert('Upload ' + error.file.name +' error, error code: ' + error.code + ', ' + error.message);
console.log(error);
});
uploader.bind('FileUploaded', function(up, file, response)
{
var jsonarray = jQuery.parseJSON(response.response);
if(jsonarray.result == 'failed'){
alert('upload ' + file.name + ' failed, ' + jsonarray.error);
}
});
uploader.bind('UploadProgress', function(up, file)
{
jQuery('#' + file.id + " .fileprogress").html(file.percent + "%");
});
uploader.bind('UploadComplete',function(up, files)
{
jQuery('#wpvivid_select_import_file_button').css({'pointer-events': 'auto', 'opacity': '1'});
var ajax_data = {
'action': 'wpvivid_upload_import_file_complete',
'files':JSON.stringify(files)
};
wpvivid_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if(jsonarray.result === 'success')
{
jQuery('#wpvivid_upload_file_list').html("");
jQuery('#wpvivid_upload_file_list').hide();
wpvivid_import_step2(jsonarray.data);
}
else if(jsonarray.result === 'failed')
{
jQuery('#wpvivid_upload_file_list').html("");
jQuery('#wpvivid_upload_file_list').hide();
alert(jsonarray.error);
}
}
catch(err)
{
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('refreshing backup list', textStatus, errorThrown);
alert(error_message);
});
plupload.each(files, function(file)
{
if(typeof file === 'undefined')
{
}
else
{
uploader.removeFile(file.id);
}
});
})
});
function wpvivid_clean_import_folder()
{
var descript = '<?php esc_html_e('Are you sure you want to delete all the exported files in the /ImportandExport folder? All the export files in the folder will be permanently deleted.', 'wpvivid-backuprestore'); ?>';
var ret = confirm(descript);
if(ret === true){
var ajax_data = {
'action': 'wpvivid_clean_import_folder'
};
wpvivid_post_request(ajax_data, function (data)
{
try {
var jsonarray = jQuery.parseJSON(data);
if(jsonarray.html !== false) {
jQuery('#wpvivid_import_list').html(jsonarray.html);
jQuery('#wpvivid_empty_import_folder').val('<?php esc_attr_e('Delete Exported Files In Folder', 'wpvivid-backuprestore'); ?> ('+jsonarray.size+')');
}
}
catch(err) {
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('scanning import folder', textStatus, errorThrown);
alert(error_message);
});
}
}
function wpvivid_import_step2(data)
{
jQuery('#wpvivid_import_file_data').html('');
var import_type = 'pages';
jQuery.each(data, function (index, value)
{
import_type = value['export_type'];
import_file_name=value['file_name'];
var list = "";
var myDate = new Date(value['time']*1000);
list += "<li>File name: " + value['file_name'] + "</li>";
list += "<li>Post type: " + value['export_type'] + "</li>";
list += "<li>Posts: " + value['posts_count'] + "</li>";
list += "<li>Media files size: " + value['media_size'] + "</li>";
list += "<li>Export time: " + myDate.toLocaleString('en-us') + "</li>";
jQuery("#wpvivid_import_file_data").append("<ul>"+ list +"</ul>");
});
jQuery('#wpvivid_import_type').html('Overwrite existing '+import_type+'s');
jQuery('#wpvivid_import_step1').hide();
jQuery('#wpvivid_import_step2').show();
jQuery('#wpvivid_import_step3').hide();
}
function wpvivid_import_step3()
{
jQuery('#wpvivid_import_step1').hide();
jQuery('#wpvivid_import_step2').hide();
jQuery('#wpvivid_import_step3').show();
}
function wpvivid_return_import_page(){
jQuery('#wpvivid_import_step1').show();
jQuery('#wpvivid_import_step2').hide();
jQuery('#wpvivid_import_step3').hide();
}
function wpvivid_monitor_import_task()
{
var ajax_data = {
'action': 'wpvivid_get_import_progress',
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (typeof jsonarray === 'object')
{
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_import_log').html("");
while (jsonarray.log.indexOf('\n') >= 0)
{
var iLength = jsonarray.log.indexOf('\n');
var log = jsonarray.log.substring(0, iLength);
jsonarray.log = jsonarray.log.substring(iLength + 1);
var insert_log = "<div style=\"clear:both;\">" + log + "</div>";
jQuery('#wpvivid_import_log').append(insert_log);
var div = jQuery('#wpvivid_import_log');
div[0].scrollTop = div[0].scrollHeight;
}
if (jsonarray.status === 'wait')
{
setTimeout(function () {
wpvivid_monitor_import_task();
}, 1000);
}
else if (jsonarray.status === 'completed')
{
var insert_log = "<div style=\"clear:both;\"><a style='cursor: pointer;' onclick='wpvivid_return_import_page();'>Return import page</a></div>";
jQuery('#wpvivid_import_log').append(insert_log);
var div = jQuery('#wpvivid_import_log');
div[0].scrollTop = div[0].scrollHeight;
setTimeout(function () {
alert("<?php esc_html_e('Import completed successfully.', 'wpvivid-backuprestore'); ?>");
}, 1000);
wpvivid_import_lock_unlock('unlock');
}
else if (jsonarray.status === 'error')
{
alert("<?php esc_html_e('Import failed.', 'wpvivid-backuprestore'); ?>");
wpvivid_import_lock_unlock('unlock');
}
else
{
setTimeout(function ()
{
wpvivid_monitor_import_task();
}, 1000);
}
}
else {
setTimeout(function () {
wpvivid_monitor_import_task();
}, 1000);
}
}
else{
setTimeout(function () {
wpvivid_monitor_import_task();
}, 1000);
}
}
catch (err) {
setTimeout(function () {
wpvivid_monitor_import_task();
}, 1000);
}
},function(XMLHttpRequest, textStatus, errorThrown) {
setTimeout(function () {
wpvivid_monitor_import_task();
}, 1000);
});
}
jQuery('#wpvivid_start_import').click(function()
{
if(import_file_name!=='')
{
var descript = '';
var user=jQuery('select[name="user_map"]').val();
if(user !== '0'){
wpvivid_start_import(import_file_name, user);
}
else{
alert('<?php esc_html_e('Please select an existing author to start importing.', 'wpvivid-backuprestore'); ?>');
}
}
});
jQuery('#wpvivid_rechoose_import_file').click(function(){
jQuery('#wpvivid_import_step1').show();
jQuery('#wpvivid_import_step2').hide();
jQuery('#wpvivid_import_step3').hide();
});
function wpvivid_start_import (file_name, user)
{
if(jQuery('#wpvivid_overwrite_existing').prop('checked')){
var overwrite_existing = 1;
}
else{
var overwrite_existing = 0;
}
wpvivid_import_lock_unlock('lock');
wpvivid_monitor_import_task();
wpvivid_import_step3();
var ajax_data = {
'action':'wpvivid_start_import',
'file_name':file_name,
'user':user,
'update_exist':overwrite_existing
};
wpvivid_post_request(ajax_data, function(data)
{
}, function(XMLHttpRequest, textStatus, errorThrown)
{
});
}
var wpvivid_scan_data={};
function wpvivid_refresh_import_list()
{
var ajax_data = {
'action': 'wpvivid_scan_import_folder'
};
wpvivid_post_request(ajax_data, function (data)
{
try {
var jsonarray = jQuery.parseJSON(data);
if(jsonarray.html !== false)
{
wpvivid_scan_data=jsonarray.data;
jQuery('#wpvivid_import_list').show();
jQuery('#wpvivid_import_list').html(jsonarray.html);
}
}
catch(err) {
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('scanning import folder', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#wpvivid_import_list').on("click",'.first-page',function()
{
wpvivid_change_import_page('first');
});
jQuery('#wpvivid_import_list').on("click",'.prev-page',function()
{
var page=parseInt(jQuery(this).attr('value'));
wpvivid_change_import_page(page-1);
});
jQuery('#wpvivid_import_list').on("click",'.next-page',function()
{
var page=parseInt(jQuery(this).attr('value'));
wpvivid_change_import_page(page+1);
});
jQuery('#wpvivid_import_list').on("click",'.last-page',function()
{
wpvivid_change_import_page('last');
});
jQuery('#wpvivid_import_list').on("keypress", '.current-page', function(){
if(event.keyCode === 13){
var page = jQuery(this).val();
wpvivid_change_import_page(page);
}
});
function wpvivid_change_import_page(page)
{
var post_ids = {};
jQuery('input[name="export[]"]').each(function (i)
{
var id=jQuery(this).val();
if(jQuery(this).prop('checked'))
{
post_ids[id]=1;
}
else
{
post_ids[id]=0;
}
});
var ajax_data = {
'action':'wpvivid_get_import_list_page',
'page': page,
'post_ids':post_ids
};
wpvivid_post_request(ajax_data, function(data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_import_list').html(jsonarray.rows);
}
else if (jsonarray.result === 'failed')
{
alert(jsonarray.error);
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('export the previously-exported settings', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#wpvivid_import_list').on("click",".wpvivid-export-list-item td",function()
{
var id = jQuery(this).parent().attr('id');
if(jQuery(this).find('div.export-list-import').length !== 0)
{
var data={};
data[id]=wpvivid_scan_data[id];
console.log(data[id]);
wpvivid_import_step2(data);
jQuery('#wpvivid_import_list').hide();
}
});
function wpvivid_calc_import_folder_size(){
var ajax_data = {
'action': 'wpvivid_calc_import_folder_size'
};
wpvivid_post_request(ajax_data, function(data)
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('#wpvivid_empty_import_folder').val('<?php esc_attr_e('Delete Exported Files In Folder', 'wpvivid-backuprestore'); ?> ('+jsonarray.size+')');
}
}, function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('calc import folder size', textStatus, errorThrown);
alert(error_message);
});
}
jQuery(document).ready(function (){
wpvivid_calc_import_folder_size();
});
</script>
<?php
}
public function wpvivid_check_import_file_name($file_name){
if(preg_match('/wpvivid-.*_.*_export_.*\.zip$/', $file_name))
{
if(preg_match('/wpvivid-(.*?)_/',$file_name,$matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
$ret['result']=WPVIVID_SUCCESS;
$ret['id']=$id;
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']=$file_name.' is not the file exported by WPvivid backup plugin.';
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']=$file_name.' is not the file exported by WPvivid backup plugin.';
}
return $ret;
}
public function check_import_file()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$file_name = sanitize_text_field($_POST['file_name']);
if(isset($file_name))
{
$ret = $this->wpvivid_check_import_file_name($file_name);
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='Failed to post file name.';
}
echo wp_json_encode($ret);
die();
}
public function upload_import_dir($uploads)
{
$uploads['path'] = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR;
return $uploads;
}
public function upload_import_files()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$options['test_form'] =true;
$options['action'] ='wpvivid_upload_import_files';
$options['test_type'] = false;
$options['ext'] = 'zip';
$options['type'] = 'application/zip';
add_filter('upload_dir', array($this, 'upload_import_dir'));
$status = wp_handle_upload($_FILES['async-upload'],$options);
remove_filter('upload_dir', array($this, 'upload_import_dir'));
if (isset($status['error']))
{
echo wp_json_encode(array('result'=>WPVIVID_FAILED, 'error' => $status['error']));
exit;
}
$file_name=basename(sanitize_text_field($_POST['name']));
if (isset($_POST['chunks']) && isset($_POST['chunk']))
{
$chunks=sanitize_key($_POST['chunks']);
$chunk=sanitize_key($_POST['chunk']);
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR.DIRECTORY_SEPARATOR;
rename($status['file'],$path.$file_name.'_'.$chunk.'.tmp');
$status['file'] = $path.$file_name.'_'.$chunk.'.tmp';
if($chunk == $chunks-1)
{
$file_handle = fopen($path.$file_name, 'wb');
if ($file_handle)
{
for ($i=0; $i<$chunks; $i++)
{
$chunks_handle=fopen($path.$file_name.'_'.$i.'.tmp','rb');
if($chunks_handle)
{
while ($line = fread($chunks_handle, 1048576*2))
{
fwrite($file_handle, $line);
}
fclose($chunks_handle);
@wp_delete_file($path.$file_name.'_'.$i.'.tmp');
}
}
fclose($file_handle);
}
}
}
echo wp_json_encode(array('result'=>WPVIVID_SUCCESS));
die();
}
public function get_import_progress()
{
try
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$tasks=WPvivid_Impoter_taskmanager::get_tasks();
foreach ($tasks as $task)
{
WPvivid_Impoter_taskmanager::get_task($task['id']);
$import_log = new WPvivid_import_data();
$ret['result'] = 'success';
$ret['status'] = WPvivid_Impoter_taskmanager::get_import_task_status($task['id']);
if ($ret['status'] === 'error')
{
WPvivid_Impoter_taskmanager::delete_task($task['id']);
}
if($ret['status'] === 'completed')
{
WPvivid_Impoter_taskmanager::delete_task($task['id']);
}
$ret['log'] = $import_log->get_log_content();
echo wp_json_encode($ret);
die();
}
$ret['result'] = 'success';
$ret['status'] ='wait';
$ret['log']='';
echo wp_json_encode($ret);
die();
}
catch (Exception $error) {
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
}
public function upload_import_file_complete()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$ret['html']=false;
if(isset($_POST['files']))
{
$files =sanitize_text_field($_POST['files']);
$files =stripslashes($files);
$files =json_decode($files,true);
if(is_null($files))
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'Failed to decode files.';
echo wp_json_encode($ret);
die();
}
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR.DIRECTORY_SEPARATOR;
//if(preg_match('/wpvivid-.*_.*_to_.*\.zip$/',$files[0]['name']))
//{
$data=array();
$check_result=true;
foreach ($files as $file)
{
$res=$this->check_is_import_file($path.$file['name']);
if($res['result'] =='success')
{
$add_file['file_name']=$file['name'];
$add_file['size']=filesize($path.$file['name']);
$add_file['export_type']=$res['export_type'];
$add_file['export_comment']=$res['export_comment'];
$add_file['posts_count']=$res['posts_count'];
$add_file['media_size']=size_format($res['media_size'],2);
$add_file['time']=$res['time'];
$data[]=$add_file;
}
else
{
$check_result=false;
}
}
if($check_result === true)
{
$ret['result']=WPVIVID_SUCCESS;
$ret['data']=$data;
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='Upload file failed.';
foreach ($files as $file)
{
$this->clean_tmp_files($path, $file['name']);
@wp_delete_file($path . $file['name']);
}
}
/*}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The file is not created by WPvivid backup plugin.';
}*/
}
else {
$ret['result']=WPVIVID_FAILED;
$ret['error']='Failed to post file name.';
}
echo wp_json_encode($ret);
die();
}
public function check_is_import_file($file_name)
{
$ret=$this->get_backup_file_info($file_name);
if($ret['result'] === WPVIVID_SUCCESS)
{
$export_type_support_array = array('post', 'page');
if(isset($ret['json_data']['post_type']) && in_array($ret['json_data']['post_type'], $export_type_support_array))
{
$ret['export_type']=$ret['json_data']['post_type'];
$ret['export_comment']=isset($ret['json_data']['post_comment']) ? $ret['json_data']['post_comment'] : 'N/A';
$ret['export_time']=isset($ret['json_data']['create_time']) ? $ret['json_data']['create_time'] : '';
$ret['posts_count']=isset($ret['json_data']['posts_count']) ? $ret['json_data']['posts_count'] : 0;
$ret['media_size']=isset($ret['json_data']['media_size']) ? $ret['json_data']['media_size'] : 0;
$ret['time']=isset($ret['json_data']['create_time']) ? $ret['json_data']['create_time'] : time();
return $ret;
}
else{
$ret['result'] = WPVIVID_FAILED;
$ret['error'] = 'The backup is not an import file.';
return $ret;
}
}
else
{
return $ret;
}
}
public function get_backup_file_info($file_name)
{
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
$ret=$zip->get_json_data($file_name, 'export');
if($ret['result'] === WPVIVID_SUCCESS)
{
$json=$ret['json_data'];
$json = json_decode($json, 1);
if (is_null($json))
{
return array('result'=>WPVIVID_FAILED,'error'=>'Failed to decode json');
} else {
return array('result'=>WPVIVID_SUCCESS,'json_data'=>$json);
}
}
else {
return $ret;
}
}
function clean_tmp_files($path, $filename){
$handler=opendir($path);
if($handler===false)
return;
while(($file=readdir($handler))!==false) {
if (!is_dir($path.$file) && preg_match('/wpvivid-.*_.*_.*\.tmp$/', $file)) {
$iPos = strrpos($file, '_');
$file_temp = substr($file, 0, $iPos);
if($file_temp === $filename) {
@wp_delete_file($path.$file);
}
}
}
@closedir($handler);
}
function wpvivid_write_upload_log($message, $id = ''){
if($id === ''){
$id=uniqid('wpvivid-');
}
global $wpvivid_plugin;
$wpvivid_plugin->upload_log=new WPvivid_Log();
$wpvivid_plugin->upload_log->CreateLogFile($id.'_upload','no_folder','upload');
$wpvivid_plugin->upload_log->WriteLogHander();
$wpvivid_plugin->upload_log->WriteLog($message,'notice');
}
public function wpvivid_check_is_import_file_ex($file_name, &$backup_id){
if(preg_match('/wpvivid-.*_.*_to_.*\.zip$/', $file_name))
{
if(preg_match('/wpvivid-(.*?)_/', $file_name, $matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
$backup_id=$id;
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public function calc_import_folder_size()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$path = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR.DIRECTORY_SEPARATOR;
$bytes_total = 0;
$path = realpath($path);
if($path!==false && $path!='' && file_exists($path))
{
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object){
$bytes_total += $object->getSize();
}
}
$ret['result'] = WPVIVID_SUCCESS;
$ret['size'] = $wpvivid_plugin->formatBytes($bytes_total);
echo wp_json_encode($ret);
die();
}
public function clean_import_folder(){
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$path = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR.DIRECTORY_SEPARATOR;
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false){
if ($filename != "." && $filename != ".."){
if (is_dir($path . $filename)) {
continue;
}
else{
$res=$this->check_is_import_file($path.$filename);
if($res['result'] =='success'){
@wp_delete_file($path.$filename);
}
}
}
}
}
}
$data = array();
WPvivid_Setting::update_option('wpvivid_import_list_cache', $data);
$page=1;
$display_list=new WPvivid_Export_List();
$display_list->set_parent('wpvivid_import_list');
$display_list->set_list($data, $page);
$display_list->prepare_items();
ob_start();
$display_list->display();
$html = ob_get_clean();
$ret['html']=$html;
$ret['data']=$data;
$ret['result']=WPVIVID_SUCCESS;
global $wpvivid_plugin;
$bytes_total = 0;
$path = realpath($path);
if($path!==false && $path!='' && file_exists($path))
{
foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS)) as $object)
{
$bytes_total += $object->getSize();
}
}
$ret['size'] = $wpvivid_plugin->formatBytes($bytes_total);
echo wp_json_encode($ret);
die();
}
public function wpvivid_scan_import_folder()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR.WPVIVID_IMPORT_EXPORT_DIR.DIRECTORY_SEPARATOR;
$data=array();
$count = 0;
if(is_dir($path))
{
$handler = opendir($path);
if($handler!==false)
{
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
$count++;
if (is_dir($path . $filename))
{
continue;
}
else {
$res=$this->check_is_import_file($path.$filename);
if($res['result'] =='success')
{
$add_file['file_name']=$filename;
$add_file['size']=filesize($path.$filename);
$add_file['export_type']=$res['export_type'];
$add_file['export_comment']=$res['export_comment'];
$add_file['posts_count']=$res['posts_count'];
$add_file['media_size']=size_format($res['media_size'],2);
$add_file['time']=$res['time'];
$data[$this->get_file_id($filename)]=$add_file;
}
}
}
}
if($handler)
@closedir($handler);
}
}
else{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log=new WPvivid_Log();
$id=uniqid('wpvivid-');
$wpvivid_plugin->wpvivid_log->CreateLogFile($id.'_scan','no_folder','scan');
$wpvivid_plugin->wpvivid_log->WriteLogHander();
$wpvivid_plugin->wpvivid_log->WriteLog('Failed to get local storage directory.','notice');
$ret['result']=WPVIVID_FAILED;
$ret['error']='Failed to get local storage directory.';
}
WPvivid_Setting::update_option('wpvivid_import_list_cache', $data);
$page=1;
$display_list=new WPvivid_Export_List();
$display_list->set_parent('wpvivid_import_list');
$display_list->set_list($data, $page);
$display_list->prepare_items();
ob_start();
$display_list->display();
$html = ob_get_clean();
$ret['html']=$html;
$ret['data']=$data;
$ret['result']=WPVIVID_SUCCESS;
echo wp_json_encode($ret);
die();
}
public function get_import_list_page(){
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(!isset($_POST['page']))
{
die();
}
$page=sanitize_key($_POST['page']);
$backups = get_option('wpvivid_import_list_cache');
$display_list=new WPvivid_Export_List();
$display_list->set_parent('wpvivid_import_list');
$display_list->set_list($backups, $page);
$display_list->prepare_items();
ob_start();
$display_list->display();
$html = ob_get_clean();
$ret['result']='success';
$ret['rows']=$html;
echo wp_json_encode($ret);
die();
}
public function deal_import_shutdown_error()
{
if($this->end_shutdown_function===false){
$last_error = error_get_last();
if (!empty($last_error) && !in_array($last_error['type'], array(E_NOTICE,E_WARNING,E_USER_NOTICE,E_USER_WARNING,E_DEPRECATED), true)) {
$error = $last_error;
} else {
$error = false;
}
$ret['result'] = 'failed';
if ($error === false) {
$ret['error'] = 'unknown Error';
} else {
$ret['error'] = 'type: '. $error['type'] . ', ' . $error['message'] . ' file:' . $error['file'] . ' line:' . $error['line'];
error_log($ret['error']);
}
$id = uniqid('wpvivid-');
$log_file_name = $id . '_import';
$log = new WPvivid_Log();
$log->CreateLogFile($log_file_name, 'no_folder', 'import');
$log->WriteLog($ret['error'], 'notice');
$log->CloseFile();
WPvivid_error_log::create_error_log($log->log_file);
echo wp_json_encode($ret);
die();
}
}
private function flush($task_id)
{
$ret['result']='success';
$ret['task_id']=$task_id;
$json=wp_json_encode($ret);
if(!headers_sent())
{
header('Content-Length: '.strlen($json));
header('Connection: close');
header('Content-Encoding: none');
}
if (session_id())
session_write_close();
echo wp_json_encode($ret);
if(function_exists('fastcgi_finish_request'))
{
fastcgi_finish_request();
}
else
{
ob_flush();
flush();
}
}
public function start_import()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$this->end_shutdown_function = false;
register_shutdown_function(array($this,'deal_import_shutdown_error'));
try
{
$file_name=sanitize_text_field($_POST['file_name']);
if (isset($file_name) && !empty($file_name) && is_string($file_name))
{
$files=array();
$options=array();
$files[]=$file_name;
$options['user']=0;
if(isset($_POST['user']))
{
$options['user']=sanitize_text_field($_POST['user']);
}
$options['update_exist']=0;
if(isset($_POST['update_exist']))
{
$options['update_exist']=sanitize_text_field($_POST['update_exist']);
}
$task_id=$this->get_file_id($file_name);
WPvivid_Impoter_taskmanager::new_task($task_id, $files,$options);
$import_log = new WPvivid_import_data();
$import_log->wpvivid_create_import_log();
$import_log->wpvivid_write_import_log('Start importing', 'notice');
$this->flush($task_id);
WPvivid_Impoter_taskmanager::update_import_task_status($task_id, 'running', true);
$importer = new WPvivid_media_importer();
$ret = $importer->import($task_id);
echo wp_json_encode($ret);
}
}
catch (Exception $error)
{
$message = 'An error has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
error_log($message);
WPvivid_Exporter_taskmanager::update_backup_task_status($task_id,false,'error',false,false,$message);
$wpvivid_plugin->wpvivid_log->WriteLog($message,'error');
$this->end_shutdown_function=true;
die();
}
$this->end_shutdown_function=true;
die();
}
public function get_file_id($file_name)
{
if(preg_match('/wpvivid-.*_.*_to_.*\.zip$/',$file_name))
{
if(preg_match('/wpvivid-(.*?)_/',$file_name,$matches))
{
$id= $matches[0];
$id=substr($id,0,strlen($id)-1);
return $id;
}
else
{
$id=uniqid('wpvivid-');
return $id;
}
}
else
{
$id=uniqid('wpvivid-');
return $id;
}
}
} includes/new_backup/class-wpvivid-mysqldump2.php 0000644 00000101330 15132770567 0016122 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
use Exception as Exception;
class CompressTest_2
{
private $fileHandler = null;
/**
* @param string $filename
*/
public function open($filename)
{
$this->fileHandler = fopen($filename, "wb");
if (false === $this->fileHandler) {
throw new Exception("Output file is not writable");
}
return true;
}
public function write($str)
{
if (false === ($bytesWritten = fwrite($this->fileHandler, $str))) {
throw new Exception("Writting to file failed! Probably, there is no more free space left?");
}
return $bytesWritten;
}
public function close()
{
return fclose($this->fileHandler);
}
public function get_size()
{
$fstat = fstat($this->fileHandler);
return $fstat['size'];
}
}
class WPvivid_Mysqldump2
{
// Same as mysqldump
const MAXLINESIZE = 1000000;
// Available compression methods as constants
const GZIP = 'Gzip';
const BZIP2 = 'Bzip2';
const NONE = 'None';
// Available connection strings
const UTF8 = 'utf8';
const UTF8MB4 = 'utf8mb4';
/**
* Database username
* @var string
*/
public $user;
/**
* Database password
* @var string
*/
public $pass;
/**
* Destination filename, defaults to stdout
* @var string
*/
public $fileName = 'php://output';
// Internal stuff
private $tables = array();
//private $dbHandler = null;
private $dbType;
private $compressManager;
private $typeAdapter;
private $dumpSettings = array();
private $version;
private $tableColumnTypes = array();
public $log=false;
public $task_id='';
/**
* database name, parsed from dsn
* @var string
*/
private $dbName;
/**
* host name, parsed from dsn
* @var string
*/
private $host;
public $last_query_string='';
public $task = false;
public $file_index=1;
public $tmp_file_name='';
public $current_size=0;
public $files=array();
public $backup_tables;
public $find_zero_date=false;
public function __construct($task,$dump_setting)
{
if(is_a($task, 'WPvivid_Backup_Task_2'))
{
$this->task=$task;
}
else
{
throw new Exception('not as wpvivid task type');
}
$dumpSettingsDefault = array(
'include-tables' => array(),
'exclude-tables' => array(),
'compress' => WPvivid_Mysqldump2::NONE,
'init_commands' => array(),
'no-data' => array(),
'reset-auto-increment' => false,
'add-drop-database' => false,
'add-drop-table' => true,
'add-drop-trigger' => true,
'add-locks' => true,
'complete-insert' => false,
'default-character-set' => WPvivid_Mysqldump2::UTF8,
'disable-keys' => true,
'extended-insert' => false,
'events' => false,
'hex-blob' => true, /* faster than escaped content */
'net_buffer_length' => self::MAXLINESIZE,
'no-autocommit' => false,
'no-create-info' => false,
'lock-tables' => false,
'routines' => false,
'single-transaction' => true,
'skip-triggers' => false,
'skip-tz-utc' => false,
'skip-comments' => false,
'skip-dump-date' => false,
'where' => '',
);
if(defined('DB_CHARSET'))
{
$dumpSettingsDefault['default-character-set']=DB_CHARSET;
}
$this->dumpSettings = $this->array_replace_recursive($dumpSettingsDefault, $dump_setting);
$this->dumpSettings['init_commands'][] = "SET NAMES " . WPvivid_Mysqldump2::UTF8MB4;
if (false === $this->dumpSettings['skip-tz-utc'])
{
$this->dumpSettings['init_commands'][] = "SET TIME_ZONE='+00:00'";
}
// Create a new compressManager to manage compressed output
$this->compressManager = new CompressTest_2();
$this->backup_tables=0;
}
public function connect()
{
$dbType=$this->dumpSettings['db_connect_method'];
$host=$this->dumpSettings['host'];
$user=$this->dumpSettings['user'];
$pass=$this->dumpSettings['pass'];
$database=$this->dumpSettings['database'];
$this->typeAdapter = WPvividTypeAdapterFactory::create($dbType, null);
$this->typeAdapter->connect($host,$database,$user,$pass,$this->dumpSettings['init_commands']);
}
public function write_header()
{
// Write some basic info to output file
$upload_dir = wp_upload_dir();
$site_url=$this->dumpSettings['site_url'];
$home_url=$this->dumpSettings['home_url'];
$content_url=$this->dumpSettings['content_url'];
$upload_url=$upload_dir['baseurl'];
$this->compressManager->write('/* # site_url: '.$site_url.' */;'.PHP_EOL);
$this->compressManager->write('/* # home_url: '.$home_url.' */;'.PHP_EOL);
$this->compressManager->write('/* # content_url: '.$content_url.' */;'.PHP_EOL);
$this->compressManager->write('/* # upload_url: '.$upload_url.' */;'.PHP_EOL);
if(isset($this->dumpSettings['prefix']))
{
$table_prefix=$this->dumpSettings['prefix'];
$this->compressManager->write('/* # table_prefix: '.$table_prefix.' */;'.PHP_EOL.PHP_EOL.PHP_EOL);
}
// Store server settings and use sanner defaults to dump
$this->compressManager->write(
$this->typeAdapter->backup_parameters($this->dumpSettings)
);
}
public function write_footer()
{
// Restore saved parameters
$this->compressManager->write(
$this->typeAdapter->restore_parameters($this->dumpSettings)
);
}
public function init_job()
{
$tables=$this->list_tables();
if(empty($tables))
{
return false;
}
usort($tables, function ($a, $b)
{
if ($a['size'] == $b['size'])
return 0;
if ($a['size'] > $b['size'])
return 1;
else
return -1;
});
$jobs=array();
foreach ($tables as $table)
{
$jobs[$table['name']]['index']=0;
$jobs[$table['name']]['finished']=0;
$jobs[$table['name']]['created']=0;
$jobs[$table['name']]['name']=$table['name'];
$jobs[$table['name']]['size']=$table['size'];
$jobs[$table['name']]['rows']=$table['rows'];
}
$this->task->update_current_sub_job($jobs);
return $jobs;
}
public function start_jobs()
{
$this->tables= $this->task->get_current_sub_job();
return $this->exportTables();
}
public function list_tables()
{
$tables=array();
$views=array();
global $wpdb;
$resultSet=$wpdb->get_results('SHOW TABLE STATUS', ARRAY_A);
$resultViews=$wpdb->get_results('SHOW FULL TABLES WHERE table_type = \'VIEW\'', ARRAY_A);
if(!is_null($resultViews))
{
foreach ($resultViews as $view)
{
$name = 'Tables_in_'.DB_NAME;
$views[] = $view[$name];
}
}
if (is_null($resultSet))
{
return $tables;
}
if(isset($this->dumpSettings['prefix'])&&!empty($this->dumpSettings['prefix']))
{
$exclude = array('/^(?!' . $this->dumpSettings['prefix'] . ')/i');
}
else
{
$exclude=array();
}
foreach ($resultSet as $row)
{
if(isset($row['Comment']) && $row['Comment'] === 'VIEW')
{
continue;
}
if ( $this->matches($row['Name'], $this->dumpSettings['include-tables']) )
{
$table['name']=$row['Name'];
$table['size']= ($row["Data_length"] + $row["Index_length"]);
$table['rows']=$row['Rows'];
$tables[]=$table;
continue;
}
if(!empty($exclude))
{
if ( $this->matches($row['Name'], $exclude) )
{
continue;
}
}
if ( $this->matches($row['Name'], $this->dumpSettings['exclude-tables']) )
{
continue;
}
if(!empty($views))
{
if ( $this->matches($row['Name'], $views) )
{
continue;
}
}
$table['name']=$row['Name'];
$table['size']= ($row["Data_length"] + $row["Index_length"]);
$table['rows']=$row['Rows'];
$tables[]=$table;
}
return $tables;
}
/**
* Compare if $table name matches with a definition inside $arr
* @param $table string
* @param $arr array with strings or patterns
* @return bool
*/
private function matches($table, $arr) {
$match = false;
if(empty($arr))
{
return false;
}
foreach ($arr as $pattern) {
if ( '/' != $pattern[0] ) {
continue;
}
if ( 1 == preg_match($pattern, $table) ) {
$match = true;
}
}
return in_array($table, $arr) || $match;
}
public function check_tmp_file()
{
$max_file_size=$this->dumpSettings['max_file_size'];
$max_backup_tables=5000;
if($max_file_size==0)
return;
$this->current_size=$this->compressManager->get_size();
$path=$this->dumpSettings['path'];
if( $this->current_size>$max_file_size||$this->backup_tables>=$max_backup_tables)
{
$this->current_size=0;
$this->backup_tables=0;
$this->close_tmp_file();
$name_file_name=$this->dumpSettings['file_prefix'].'.part'.sprintf('%03d',($this->file_index)).'.sql';
$this->file_index++;
rename($this->tmp_file_name,$path.DIRECTORY_SEPARATOR.$name_file_name);
$this->task->update_current_sub_job($this->tables);
$this->task->add_mysql_dump_files($name_file_name);
$this->open_tmp_file();
}
}
public function open_tmp_file($b_delete=false)
{
if($b_delete)
@wp_delete_file( $this->tmp_file_name);
$this->compressManager->open($this->tmp_file_name);
}
public function close_tmp_file()
{
$this->compressManager->close();
}
private function exportTables()
{
global $wpvivid_plugin;
//tmp_file_name
$path=$this->dumpSettings['path'];
$this->tmp_file_name=$path.DIRECTORY_SEPARATOR.$this->dumpSettings['file_prefix'].'_tmp.sql';
$this->open_tmp_file();
$this->write_header();
/*
if(file_exists($this->tmp_file_name))
{
$this->open_tmp_file();
}
else
{
$this->open_tmp_file();
$this->write_header();
}*/
// Exporting tables one by one
$this->file_index=$this->task->get_current_mysql_file_index();
$this->current_size=0;
$tables=$this->tables;
$i=0;
$i_step=0;
$this->backup_tables=0;
if($this->task->task_id!=='')
{
$size = $this->task->get_backup_jobs();
if(sizeof($size) > 0)
{
$i_step = intval(1 / (sizeof($size)) * 100);
}
}
foreach ($tables as $name=>$table)
{
if($this->task->check_cancel_backup())
{
die();
}
if($table['finished']==1)
{
continue;
}
$index=$table['index'];
$table_name=$table['name'];
$message='Preparing to dump table '.$table_name;
$wpvivid_plugin->wpvivid_log->WriteLog($message,'notice');
$this->task->update_sub_task_progress($message);
if($table['created']==0)
{
$this->getTableStructure($table_name);
$this->tables[$name]['created']=1;
//$this->task->update_current_sub_job($this->tables);
}
$this->tableColumnTypes[$table_name] = $this->getTableColumnTypes($table_name);
if($this->tableColumnTypes[$table_name]===false)
{
continue;
}
$this->listValues($table_name,$index);
$this->check_tmp_file();
$this->tables[$name]['finished']=1;
$this->backup_tables++;
//$this->task->update_current_sub_job($this->tables);
$i++;
if($this->task->task_id!=='')
{
$i_progress=intval($i/sizeof($this->tables)*$i_step);
$this->task->update_database_progress($i_progress);
}
}
$this->current_size=$this->compressManager->get_size();
if($this->current_size>0)
{
$this->close_tmp_file();
$name_file_name=$this->dumpSettings['file_prefix'].'.part'.sprintf('%03d',($this->file_index)).'.sql';
$this->file_index++;
rename($this->tmp_file_name,$path.DIRECTORY_SEPARATOR.$name_file_name);
$this->task->add_mysql_dump_files($name_file_name);
}
else
{
$this->close_tmp_file();
}
$ret['result']='success';
return $ret;
}
/**
* Table structure extractor
*
* @param string $tableName Name of table to export
* @return null
*/
private function getTableStructure($tableName)
{
if (!$this->dumpSettings['no-create-info']) {
$ret = '';
if (!$this->dumpSettings['skip-comments']) {
$ret = "--" . PHP_EOL .
"-- Table structure for table `$tableName`" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL;
}
$stmt = $this->typeAdapter->show_create_table($tableName);
foreach ($this->query($stmt) as $r)
{
$this->compressManager->write($ret);
if ($this->dumpSettings['add-drop-table']) {
$this->compressManager->write(
$this->typeAdapter->drop_table($tableName)
);
}
$this->compressManager->write(
$this->typeAdapter->create_table($r, $this->dumpSettings)
);
break;
}
}
return;
}
/**
* Store column types to create data dumps and for Stand-In tables
*
* @param string $tableName Name of table to export
* @return array type column types detailed
*/
private function getTableColumnTypes($tableName) {
$columnTypes = array();
$columns = $this->query(
$this->typeAdapter->show_columns($tableName)
);
if($columns===false)
{
$error=$this->typeAdapter->errorInfo();
if(isset($error[2])){
$error = 'Error: '.$error[2];
}
else{
$error = '';
}
$columns = $this->query(
'DESCRIBE '.$tableName
);
if($columns===false)
{
$error=$this->typeAdapter->errorInfo();
if(isset($error[2])){
$error = 'Error: '.$error[2];
}
else{
$error = '';
}
return false;
}
}
foreach($columns as $key => $col) {
$types = $this->typeAdapter->parseColumnType($col);
$columnTypes[$col['Field']] = array(
'is_numeric'=> $types['is_numeric'],
'is_blob' => $types['is_blob'],
'type' => $types['type'],
'type_sql' => $col['Type'],
'is_virtual' => $types['is_virtual']
);
}
return $columnTypes;
}
/**
* Escape values with quotes when needed
*
* @param string $tableName Name of table which contains rows
* @param array $row Associative array of column names and values to be quoted
*
* @return array
*/
private function escape($tableName, $row)
{
$ret = array();
$columnTypes = $this->tableColumnTypes[$tableName];
foreach ($row as $colName => $colValue) {
if (is_null($colValue)) {
$ret[] = "NULL";
} elseif ($this->dumpSettings['hex-blob'] && $columnTypes[$colName]['is_blob']) {
if ($columnTypes[$colName]['type'] == 'bit' || !empty($colValue)) {
$ret[] = "0x{$colValue}";
} else {
$ret[] = "''";
}
} elseif ($columnTypes[$colName]['is_numeric']) {
$ret[] = $colValue;
} else {
$ret[] = $this->typeAdapter->quote($colValue);
}
}
return $ret;
}
private function listValues($tableName,$index)
{
global $wpvivid_plugin;
$this->prepareListValues($tableName);
$onlyOnce = true;
$lineSize = 0;
$colStmt = $this->getColumnStmt($tableName);
global $wpdb;
$prefix=$wpdb->base_prefix;
$dbType=$this->dumpSettings['db_connect_method'];
$start=$index;
$limit_count=5000;
//$sum =$wpdb->get_var("SELECT COUNT(1) FROM `{$tableName}`");
$sum=0;
$resultSet = $this->query("SELECT COUNT(1) FROM `{$tableName}`");
foreach ($resultSet as $row)
{
$sum=$row['COUNT(1)'];
}
$this->typeAdapter->closeCursor($resultSet);
if($dbType=='wpdb')
{
$b_options=false;
if(substr($tableName, strlen($prefix))=='options')
{
$b_options=true;
}
$stmt = "SELECT " . implode(",", $colStmt) . " FROM `$tableName`";
if ($this->dumpSettings['where']) {
$stmt .= " WHERE {$this->dumpSettings['where']}";
}
$i=0;
$i_check_cancel=0;
$count=0;
while($sum > $start)
{
$limit = " LIMIT {$limit_count} OFFSET {$start}";
$query=$stmt.$limit;
$resultSet = $this->query($query);
if($resultSet===false)
{
$error=$this->typeAdapter->errorInfo();
if(isset($error[2])){
$error = 'Error: '.$error[2];
}
else{
$error = '';
}
$this->endListValues($tableName);
return ;
}
foreach ($resultSet as $row)
{
$i++;
$skip=false;
$vals = $this->escape($tableName, $row);
foreach($vals as $key => $value)
{
if($value === '\'0000-00-00 00:00:00\'')
{
//$vals[$key] = '\'1999-01-01 00:00:00\'';
$this->find_zero_date=true;
}
if($b_options)
{
if($value=="'wpvivid_task_list'")
{
$skip=true;
}
}
}
if($skip)
continue;
if ($onlyOnce || !$this->dumpSettings['extended-insert'])
{
if ($this->dumpSettings['complete-insert'])
{
$lineSize += $this->compressManager->write(
"INSERT INTO `$tableName` (" .
implode(", ", $colStmt) .
") VALUES (" . implode(",", $vals) . ")"
);
} else {
$lineSize += $this->compressManager->write(
"INSERT INTO `$tableName` VALUES (" . implode(",", $vals) . ")"
);
}
$onlyOnce = false;
}
else {
$lineSize += $this->compressManager->write(",(" . implode(",", $vals) . ")");
}
if (($lineSize > $this->dumpSettings['net_buffer_length']) ||
!$this->dumpSettings['extended-insert']) {
$onlyOnce = true;
$lineSize = $this->compressManager->write(";" . PHP_EOL);
}
if($i>=200000)
{
$count+=$i;
$i=0;
if($this->task->task_id!=='')
{
$i_check_cancel++;
if($i_check_cancel>5)
{
$i_check_cancel=0;
$this->task->check_cancel_backup();
}
$message='Dumping table '.$tableName.', rows dumped: '.$count.' rows.';
$this->task->update_sub_task_progress($message);
}
}
}
$this->typeAdapter->closeCursor($resultSet);
$start += $limit_count;
$this->tables[$tableName]['index']=$start;
//$this->task->update_current_sub_job($this->tables);
$this->check_tmp_file();
}
if (!$onlyOnce) {
$this->compressManager->write(";" . PHP_EOL);
}
$this->endListValues($tableName);
}
else
{
$b_options=false;
if(substr($tableName, strlen($prefix))=='options')
{
$b_options=true;
}
$stmt = "SELECT " . implode(",", $colStmt) . " FROM `$tableName`";
if ($this->dumpSettings['where']) {
$stmt .= " WHERE {$this->dumpSettings['where']}";
}
$i=0;
$i_check_cancel=0;
$count=0;
while($sum > $start)
{
$limit = " LIMIT {$limit_count} OFFSET {$start}";
$query=$stmt.$limit;
$resultSet = $this->query($query);
if($resultSet===false)
{
$error=$this->typeAdapter->errorInfo();
if(isset($error[2])){
$error = 'Error: '.$error[2];
}
else{
$error = '';
}
$this->endListValues($tableName);
return ;
}
foreach ($resultSet as $row)
{
$skip=false;
$vals = $this->escape($tableName, $row);
foreach($vals as $key => $value)
{
if($value === '\'0000-00-00 00:00:00\'')
{
//$vals[$key] = '\'1999-01-01 00:00:00\'';
$this->find_zero_date=true;
}
if($b_options)
{
if($value=="'wpvivid_task_list'")
{
$skip=true;
}
}
}
if($skip)
continue;
if ($onlyOnce || !$this->dumpSettings['extended-insert'])
{
if ($this->dumpSettings['complete-insert'])
{
var_dump('test1');
$lineSize += $this->compressManager->write(
"INSERT INTO `$tableName` (" .
implode(", ", $colStmt) .
") VALUES (" . implode(",", $vals) . ")"
);
} else {
$lineSize += $this->compressManager->write(
"INSERT INTO `$tableName` VALUES (" . implode(",", $vals) . ")"
);
}
$onlyOnce = false;
}
else {
$lineSize += $this->compressManager->write(",(" . implode(",", $vals) . ")");
}
if (($lineSize > $this->dumpSettings['net_buffer_length']) ||
!$this->dumpSettings['extended-insert']) {
$onlyOnce = true;
$lineSize = $this->compressManager->write(";" . PHP_EOL);
}
if($i>=200000)
{
$count+=$i;
$i=0;
if($this->task->task_id!=='')
{
$i_check_cancel++;
if($i_check_cancel>5)
{
$i_check_cancel=0;
$this->task->check_cancel_backup();
}
$message='Dumping table '.$tableName.', rows dumped: '.$count.' rows.';
$this->task->update_sub_task_progress($message);
}
}
}
$this->typeAdapter->closeCursor($resultSet);
$start += $limit_count;
$this->tables[$tableName]['index']=$start;
//$this->task->update_current_sub_job($this->tables);
$this->check_tmp_file();
}
if (!$onlyOnce) {
$this->compressManager->write(";" . PHP_EOL);
}
$this->endListValues($tableName);
}
//$this->current_size+=$table['size'];
}
/**
* Table rows extractor, append information prior to dump
*
* @param string $tableName Name of table to export
*
* @return null
*/
function prepareListValues($tableName)
{
if (!$this->dumpSettings['skip-comments']) {
$this->compressManager->write(
"--" . PHP_EOL .
"-- Dumping data for table `$tableName`" . PHP_EOL .
"--" . PHP_EOL . PHP_EOL
);
}
if ($this->dumpSettings['single-transaction']) {
$this->exec($this->typeAdapter->setup_transaction());
$this->exec($this->typeAdapter->start_transaction());
}
if ($this->dumpSettings['lock-tables'])
{
$this->typeAdapter->lock_table($tableName);
//if($this -> privileges['LOCK TABLES'] == 0)
//{
//global $wpvivid_plugin;
// $wpvivid_plugin->wpvivid_log->WriteLog('The lack of LOCK TABLES privilege, the backup will skip lock_tables() to continue.','notice');
//}else{
// $this->typeAdapter->lock_table($tableName);
//}
}
if ($this->dumpSettings['add-locks']) {
$this->compressManager->write(
$this->typeAdapter->start_add_lock_table($tableName)
);
}
if ($this->dumpSettings['disable-keys']) {
$this->compressManager->write(
$this->typeAdapter->start_add_disable_keys($tableName)
);
}
// Disable autocommit for faster reload
if ($this->dumpSettings['no-autocommit']) {
$this->compressManager->write(
$this->typeAdapter->start_disable_autocommit()
);
}
return;
}
/**
* Table rows extractor, close locks and commits after dump
*
* @param string $tableName Name of table to export
*
* @return null
*/
function endListValues($tableName)
{
if ($this->dumpSettings['disable-keys']) {
$this->compressManager->write(
$this->typeAdapter->end_add_disable_keys($tableName)
);
}
if ($this->dumpSettings['add-locks']) {
$this->compressManager->write(
$this->typeAdapter->end_add_lock_table($tableName)
);
}
if ($this->dumpSettings['single-transaction']) {
$this->exec($this->typeAdapter->commit_transaction());
}
if ($this->dumpSettings['lock-tables']) {
$this->typeAdapter->unlock_table($tableName);
}
// Commit to enable autocommit
if ($this->dumpSettings['no-autocommit']) {
$this->compressManager->write(
$this->typeAdapter->end_disable_autocommit()
);
}
$this->compressManager->write(PHP_EOL);
return;
}
/**
* Build SQL List of all columns on current table
*
* @param string $tableName Name of table to get columns
*
* @return string SQL sentence with columns
*/
function getColumnStmt($tableName)
{
$colStmt = array();
foreach($this->tableColumnTypes[$tableName] as $colName => $colType) {
if ($colType['type'] == 'bit' && $this->dumpSettings['hex-blob']) {
$colStmt[] = "LPAD(HEX(`{$colName}`),2,'0') AS `{$colName}`";
} else if ($colType['is_blob'] && $this->dumpSettings['hex-blob']) {
$colStmt[] = "HEX(`{$colName}`) AS `{$colName}`";
} else if ($colType['is_virtual']) {
$this->dumpSettings['complete-insert'] = true;
continue;
} else {
$colStmt[] = "`{$colName}`";
}
}
return $colStmt;
}
/**
* Custom array_replace_recursive to be used if PHP < 5.3
* Replaces elements from passed arrays into the first array recursively
*
* @param array $array1 The array in which elements are replaced
* @param array $array2 The array from which elements will be extracted
*
* @return array Returns an array, or NULL if an error occurs.
*/
public function array_replace_recursive($array1, $array2)
{
if (function_exists('array_replace_recursive')) {
return array_replace_recursive($array1, $array2);
}
foreach ($array2 as $key => $value) {
if (is_array($value)) {
$array1[$key] = $this->array_replace_recursive($array1[$key], $value);
} else {
$array1[$key] = $value;
}
}
return $array1;
}
public function query($query_string)
{
$this->last_query_string=$query_string;
return $this->typeAdapter->query($query_string);
}
private function exec($query_string)
{
$this->last_query_string=$query_string;
return $this->typeAdapter->query($query_string);
}
public function is_has_zero_date()
{
if($this->find_zero_date)
{
return true;
}
else
{
return false;
}
}
} includes/new_backup/class-wpvivid-zip.php 0000644 00000023735 15132770567 0014623 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Zip
{
public $zip_object;
public function __construct($zip_method='')
{
$this->check_available_zip_object($zip_method);
}
public function add_files($zip_file,$root_path,$files,$create=false,$json=false)
{
if($create)
{
if(file_exists($zip_file))
@wp_delete_file($zip_file);
}
if($json!==false)
{
$this->add_json_file($zip_file,$json,$create);
}
if(file_exists($zip_file))
{
$this->zip_object->open($zip_file);
clearstatcache();
}
else
{
$create_code = (version_compare(PHP_VERSION, '5.2.12', '>') && defined('ZIPARCHIVE::CREATE')) ? ZIPARCHIVE::CREATE : 1;
$this->zip_object->open($zip_file, $create_code);
}
if(is_a($this->zip_object,'WPvivid_PclZip_2'))
$this->zip_object->set_replace_path($root_path);
foreach ($files as $file)
{
$new_file=str_replace($root_path,'',$file);
if(file_exists($file))
{
$this->zip_object->addFile($file,$new_file);
}
}
if($this->zip_object->close()===false)
{
$ret['result']='failed';
$ret['error']='Failed to add zip files.';
if(is_a($this->zip_object,'WPvivid_PclZip_2'))
{
$ret['error'].=' last error:'.$this->zip_object->last_error;
}
else if(is_a($this->zip_object,'ZipArchive'))
{
$ret['error'].=' status string:'.$this->zip_object->getStatusString();
}
return $ret;
}
$ret['result']='success';
return $ret;
}
public function add_file($zip_file,$file,$add_as,$replace_path)
{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Prepare to zip file. file: '.basename($file),'notice');
if(file_exists($zip_file))
{
$this->zip_object->open($zip_file);
clearstatcache();
}
else
{
$create_code = (version_compare(PHP_VERSION, '5.2.12', '>') && defined('ZIPARCHIVE::CREATE')) ? ZIPARCHIVE::CREATE : 1;
$this->zip_object->open($zip_file, $create_code);
}
if(is_a($this->zip_object,'WPvivid_PclZip_2'))
$this->zip_object->set_replace_path($replace_path);
if($this->zip_object->addFile($file,$add_as)===false)
{
$ret['result']='failed';
$ret['error']='Failed to add zip file '.$file;
if(is_a($this->zip_object,'WPvivid_PclZip_2'))
{
$ret['error'].=' last error:'.$this->zip_object->last_error;
}
else if(is_a($this->zip_object,'ZipArchive'))
{
$ret['error'].=' status string:'.$this->zip_object->getStatusString();
}
return $ret;
}
if($this->zip_object->close()===false)
{
$ret['result']='failed';
$ret['error']='Failed to add zip files.';
if(is_a($this->zip_object,'WPvivid_PclZip_2'))
{
$ret['error'].=' last error:'.$this->zip_object->last_error;
}
else if(is_a($this->zip_object,'ZipArchive'))
{
$ret['error'].=' status string:'.$this->zip_object->getStatusString();
}
return $ret;
}
$ret['result']='success';
$wpvivid_plugin->wpvivid_log->WriteLog('Adding zip files completed.'.basename($zip_file).', filesize: '.size_format(filesize($zip_file),2),'notice');
return $ret;
}
public function add_json_file($zip_file,$json,$create=false)
{
if($create)
{
if(file_exists($zip_file))
@wp_delete_file($zip_file);
}
$json['file']=basename($zip_file);
$string=wp_json_encode($json);
if(file_exists($zip_file))
{
$this->zip_object->open($zip_file);
clearstatcache();
}
else
{
$create_code = (version_compare(PHP_VERSION, '5.2.12', '>') && defined('ZIPARCHIVE::CREATE')) ? ZIPARCHIVE::CREATE : 1;
$this->zip_object->open($zip_file, $create_code);
}
if($this->zip_object->addFromString('wpvivid_package_info.json',$string)===false)
{
$ret['result']='failed';
$ret['error']='Failed to add zip file';
return $ret;
}
if(is_a($this->zip_object,'WPvivid_PclZip_2'))
{
}
else
{
if($this->zip_object->close()===false)
{
$ret['result']='failed';
$ret['error']='Failed to add zip file';
return $ret;
}
}
$ret['result']='success';
return $ret;
}
public function check_available_zip_object($zip_method)
{
if($zip_method=='ziparchive'||empty($zip_method))
{
if($this->check_ziparchive_available())
{
$this->zip_object=new ZipArchive();
}
else
{
$this->zip_object=new WPvivid_PclZip_2();
}
}
else
{
$this->zip_object=new WPvivid_PclZip_2();
}
}
public function check_ziparchive_available()
{
if(class_exists('ZipArchive'))
{
if(method_exists('ZipArchive', 'addFile'))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
public function addEmptyDir($zip_file,$folders)
{
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR;
if(file_exists($path.$zip_file))
{
$this->zip_object->open($path.$zip_file);
}
else
{
$create_code = (version_compare(PHP_VERSION, '5.2.12', '>') && defined('ZIPARCHIVE::CREATE')) ? ZIPARCHIVE::CREATE : 1;
$this->zip_object->open($path.$zip_file, $create_code);
}
foreach ($folders as $folder)
{
$this->zip_object->addEmptyDir($folder);
}
$this->zip_object->close();
$ret['result']='success';
return $ret;
}
}
class WPvivid_PclZip_2
{
public $addfiles;
public $adddirs;
public $path;
public $pclzip;
public $last_error;
public $replace_path;
public function __construct()
{
$this->addfiles = array();
$this->adddirs = array();
if(!defined('PCLZIP_TEMPORARY_DIR'))
{
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR;
$temp_dir =$path.'wpvivid-pclzip-temp'.DIRECTORY_SEPARATOR;
define(PCLZIP_TEMPORARY_DIR,$temp_dir);
}
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
}
public function open($path, $flags = 0)
{
$ziparchive_create_match = (version_compare(PHP_VERSION, '5.2.12', '>') && defined('ZIPARCHIVE::CREATE')) ? ZIPARCHIVE::CREATE : 1;
if ($flags == $ziparchive_create_match && file_exists($path))
@wp_delete_file($path);
$this->pclzip = new WPvivid_PclZip($path);
if (empty($this->pclzip))
{
return false;
}
$this->path = $path;
return true;
}
public function set_replace_path($replace_path)
{
$this->replace_path=$replace_path;
}
public function addFile($file, $add_as)
{
$this->addfiles[] = $file;
return true;
}
public function addEmptyDir($dir)
{
$this->adddirs[] = $dir;
}
public function close()
{
if (empty($this->pclzip))
{
return false;
}
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR;
foreach ($this->adddirs as $dir)
{
$ret=$this->pclzip->add($path.'emptydir', WPVIVID_PCLZIP_OPT_REMOVE_PATH, $path.'emptydir', WPVIVID_PCLZIP_OPT_ADD_PATH, $dir);
if (!$ret)
{
$this->last_error = $this->pclzip->errorInfo(true);
return false;
}
}
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$ret = $this->pclzip -> add($this->addfiles,WPVIVID_PCLZIP_OPT_REMOVE_PATH,$this->replace_path,WPVIVID_PCLZIP_CB_PRE_ADD,'wpvivid_function_per_add_callback',WPVIVID_PCLZIP_OPT_NO_COMPRESSION,WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,16);
if (!$ret)
{
$this->last_error = $this->pclzip->errorInfo(true);
return false;
}
$this->pclzip = false;
$this->addfiles = array();
$this->adddirs = array();
clearstatcache();
return true;
}
public function addFromString($file_name,$string)
{
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR;
$temp_path = $path.$file_name;
if(file_exists($temp_path))
{
@wp_delete_file($temp_path);
}
file_put_contents($temp_path,$string);
$this->pclzip -> add($temp_path,WPVIVID_PCLZIP_OPT_REMOVE_PATH,dirname($temp_path));
@wp_delete_file($temp_path);
return true;
}
} includes/new_backup/class-wpvivid-backup-task_2.php 0000644 00000344703 15132770567 0016450 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Backup_Task_2
{
public $task;
public $task_id;
public $current_job;
public $current_db;
public function __construct($task_id=false,$task=array())
{
$this->task_id=false;
$this->current_job=false;
if(empty($task))
{
if(!empty($task_id))
{
$default = array();
$options = get_option('wpvivid_task_list', $default);
if(isset($options[$task_id]))
{
$this->task=$options[$task_id];
$this->task_id=$task_id;
}
}
}
else
{
$this->task_id=$task_id;
$this->task=$task;
}
}
public function get_new_id()
{
$rand_id = substr(md5(time().rand()), 0,13);
return 'wpvivid-'.$rand_id;
}
public function new_backup_task($options,$settings)
{
$this->task=array();
$id=$this->get_new_id();
$this->task['id']=$id;
$this->task['type']=isset($options['type'])?$options['type']:'';
if(isset($options['lock']))
{
$this->task['options']['lock']=$options['lock'];
}
else
{
$this->task['options']['lock']=0;
}
$this->task['status']['task_start_time']=time();
$this->task['status']['task_end_time']=time();
$this->task['status']['start_time']=time();
$this->task['status']['run_time']=time();
$this->task['status']['timeout']=time();
$this->task['status']['str']='ready';
$this->task['status']['resume_count']=0;
$options['save_local']=isset($settings['save_local'])?$settings['save_local']:false;
$this->set_backup_option($options);
if(isset($options['remote']))
{
if($options['remote']=='1')
{
if(isset($options['remote_options']))
{
$this->task['options']['remote_options']=$options['remote_options'];
}
else
{
$this->task['options']['remote_options']=WPvivid_Setting::get_remote_options();
}
}
else {
$this->task['options']['remote_options']=false;
}
}
else
{
$this->task['options']['remote_options']=false;
}
$this->task['setting']=$settings;
$this->task['data']['doing']='backup';
$this->task['data']['backup']['doing']='';
$this->task['data']['backup']['progress']=0;
$this->task['data']['backup']['sub_job']=array();
$this->task['data']['upload']['doing']='';
$this->task['data']['upload']['finished']=0;
$this->task['data']['upload']['progress']=0;
$this->task['data']['upload']['job_data']=array();
$this->task['data']['upload']['sub_job']=array();
$this->init_backup_job($options['backup_files']);
$this->task['options']['backup_files']=$options['backup_files'];
delete_option('wpvivid_task_list');
WPvivid_Setting::update_task($id,$this->task);
$ret['result']='success';
$ret['task']=$this->task;
$ret['task_id']=$this->task['id'];
return $ret;
}
public function get_start_time()
{
return $this->task['status']['task_start_time'];
}
public function get_end_time()
{
return $this->task['status']['task_end_time'];
}
public function update_end_time()
{
$this->task['status']['task_end_time']=time();
$this->update_task();
}
public function set_backup_option($options)
{
$offset=get_option('gmt_offset');
$this->task['options']=$options;
$general_setting=WPvivid_Setting::get_setting(true, "");
if(isset($options['backup_prefix']) && !empty($options['backup_prefix']))
{
$this->task['options']['backup_prefix']=$options['backup_prefix'];
}
else
{
if(isset($general_setting['options']['wpvivid_common_setting']['domain_include'])&&$general_setting['options']['wpvivid_common_setting']['domain_include'])
{
$check_addon = apply_filters('wpvivid_check_setting_addon', 'not_addon');
if (isset($general_setting['options']['wpvivid_common_setting']['backup_prefix']) && $check_addon == 'addon')
{
$this->task['options']['backup_prefix'] = $general_setting['options']['wpvivid_common_setting']['backup_prefix'];
}
else {
$home_url_prefix = get_home_url();
$home_url_prefix = $this->parse_url_all($home_url_prefix);
$this->task['options']['backup_prefix'] = $home_url_prefix;
}
}
else
{
$this->task['options']['backup_prefix']='';
}
}
if(empty($this->task['options']['backup_prefix']))
{
$this->task['options']['file_prefix'] = $this->task['id'] . '_' . gmdate('Y-m-d-H-i', time()+$offset*60*60);
}
else
{
$this->task['options']['file_prefix'] = $this->task['options']['backup_prefix'] . '_' . $this->task['id'] . '_' . gmdate('Y-m-d-H-i', time()+$offset*60*60);
}
$this->task['options']['file_prefix'] = apply_filters('wpvivid_backup_file_prefix',$this->task['options']['file_prefix'],$this->task['options']['backup_prefix'],$this->task['id'],$this->task['status']['start_time']);
$this->task['options']['log_file_name']=$this->task['id'].'_backup';
$log=new WPvivid_Log();
$log->CreateLogFile($this->task['options']['log_file_name'],'no_folder','backup');
$this->task['options']['log_file_path']=$log->log_file;
$this->task['options']['prefix']=$this->task['options']['file_prefix'];
$this->task['options']['dir']=WP_CONTENT_DIR.'/'.WPvivid_Setting::get_backupdir();
$this->task['options']['backup_dir']=WPvivid_Setting::get_backupdir();
$exclude_files=isset($options['exclude_files'])?$options['exclude_files']:array();
$exclude_files=apply_filters('wpvivid_default_exclude_folders',$exclude_files);
$this->task['options']['exclude-tables']=isset($options['exclude-tables'])?$options['exclude-tables']:array();
$this->task['options']['exclude-tables']=$this->default_exclude_table($this->task['options']['exclude-tables']);
$this->task['options']['include-tables']=isset($options['include-tables'])?$options['include-tables']:array();
$this->task['options']['exclude_files']=$this->get_exclude_files($exclude_files);
$this->task['options']['include_files']=$this->get_include_files();
$this->task['options']['include_plugins']=isset($options['include_plugins'])?$options['include_plugins']:array();
$this->task['options']['include_themes']=isset($options['include_themes'])?$options['include_themes']:array();
if(isset($options['local']))
{
if($options['local']=='1')
{
$this->task['options']['save_local']=1;
}
else
{
//$this->task['options']['save_local']=0;
$this->task['options']['save_local'] =isset($options['save_local'])?$options['save_local']:false;
}
}
else
{
$this->task['options']['save_local']=1;
}
$this->task['options']['backup_options']['compress']['compress_type']='zip';
$log->CloseFile();
//$this->task['options']['remote_options'] = apply_filters('wpvivid_set_remote_options', $this->task['options']['remote_options'],$this->task['options']);
}
public function default_exclude_table($exclude_tables)
{
global $wpdb;
$exclude_tables[]=$wpdb->base_prefix."wpvivid_log";
$exclude_tables[]=$wpdb->base_prefix."wpvivid_increment_big_ids";
$exclude_tables[]=$wpdb->base_prefix."wpvivid_options";
$exclude_tables[]=$wpdb->base_prefix."wpvivid_record_task";
$exclude_tables[]=$wpdb->base_prefix."wpvivid_merge_db";
$exclude_tables[]=$wpdb->base_prefix."wpvivid_merge_ids";
return $exclude_tables;
}
public function parse_url_all($url)
{
$parse = wp_parse_url($url);
//$path=str_replace('/','_',$parse['path']);
$path = '';
if(isset($parse['path'])) {
$parse['path'] = str_replace('/', '_', $parse['path']);
$path = $parse['path'];
}
return $parse['host'].$path;
}
public function init_backup_job($backup_content)
{
$index=0;
$this->task['jobs']=array();
if($backup_content==='files')
{
$this->task['jobs'][$index]['backup_type']='backup_themes';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['index']=0;
$index++;
$this->task['jobs'][$index]['backup_type']='backup_plugin';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['index']=0;
$index++;
$this->task['jobs'][$index]['backup_type']='backup_uploads';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['index']=0;
$index++;
$this->task['jobs'][$index]['backup_type']='backup_content';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['index']=0;
$index++;
$this->task['jobs'][$index]['backup_type']='backup_core';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['index']=0;
$index++;
}
else if($backup_content==='files+db')
{
$this->task['jobs'][$index]['backup_type']='backup_db';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['mysql_file_index']=1;
$index++;
$this->task['jobs'][$index]['backup_type']='backup_themes';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['index']=0;
$index++;
$this->task['jobs'][$index]['backup_type']='backup_plugin';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['index']=0;
$index++;
$this->task['jobs'][$index]['backup_type']='backup_uploads';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['index']=0;
$index++;
$this->task['jobs'][$index]['backup_type']='backup_content';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['index']=0;
$index++;
$this->task['jobs'][$index]['backup_type']='backup_core';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['index']=0;
$index++;
}
else if($backup_content==='db')
{
$this->task['jobs'][$index]['backup_type']='backup_db';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['mysql_file_index']=1;
$index++;
}
$is_merge=$this->task['setting']['is_merge'];
if(count($this->task['jobs'])==1)
{
$is_merge=false;
}
if($is_merge)
{
$this->task['jobs'][$index]['backup_type']='backup_merge';
$this->task['jobs'][$index]['finished']=0;
$this->task['jobs'][$index]['progress']=0;
$this->task['jobs'][$index]['file_index']=1;
$this->task['jobs'][$index]['child_file']=array();
$this->task['jobs'][$index]['index']=0;
}
}
public function get_exclude_files($exclude_files=array())
{
$exclude_plugins=array();
$exclude_plugins=apply_filters('wpvivid_exclude_plugins',$exclude_plugins);
$exclude_regex=array();
foreach ($exclude_plugins as $exclude_plugin)
{
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_PLUGIN_DIR.'/'.$exclude_plugin), '/').'#';
}
foreach ($exclude_files as $exclude_file)
{
if($exclude_file['type']=='file'||$exclude_file['type']=='folder')
{
if(file_exists($exclude_file['path']))
{
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($exclude_file['path']), '/').'#';
}
else
{
$path=WP_CONTENT_DIR.'/'.$exclude_file['path'];
if(file_exists($path))
{
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($path), '/').'#';
}
}
}
else if($exclude_file['type']=='ext')
{
$exclude_regex[]='#^.*\.'.$exclude_file['path'].'$#';
}
}
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).'/'.'wpvivid', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).'/'.WPvivid_Setting::get_backupdir(), '/').'#';
if(defined('WPVIVID_UPLOADS_ISO_DIR'))
{
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).'/'.WPVIVID_UPLOADS_ISO_DIR, '/').'#';
}
return $exclude_regex;
}
public function get_backup_type_exclude_files($backup_type)
{
$exclude_regex=array();
if($backup_type=='backup_content')
{
$upload_dir = wp_upload_dir();
$exclude_regex[]='#^'.preg_quote($this -> transfer_path(WP_CONTENT_DIR).'/'.'plugins', '/').'#';
$exclude_regex[]='#^'.preg_quote($this -> transfer_path($upload_dir['basedir']), '/').'$#';
$exclude_regex[]='#^'.preg_quote($this->transfer_path(get_theme_root()), '/').'#';
}
return $exclude_regex;
}
public function get_include_files()
{
$include_regex[]='#^'.preg_quote($this -> transfer_path(ABSPATH.'wp-admin'), '/').'#';
$include_regex[]='#^'.preg_quote($this->transfer_path(ABSPATH.'wp-includes'), '/').'#';
$include_regex[]='#^'.preg_quote($this->transfer_path(ABSPATH.'lotties'), '/').'#';
return $include_regex;
}
public function set_memory_limit()
{
$memory_limit=isset($this->task['setting']['memory_limit'])?$this->task['setting']['memory_limit']:WPVIVID_MEMORY_LIMIT;
@ini_set('memory_limit', $memory_limit);
}
public function is_backup_finished()
{
$finished=true;
foreach ($this->task['jobs'] as $job)
{
if($job['finished']==0)
{
$finished=false;
break;
}
}
return $finished;
}
public function update_sub_task_progress($progress)
{
$this->task['status']['run_time']=time();
$this->task['status']['str']='running';
$this->task['data']['doing']='backup';
$sub_job_name=$this->task['jobs'][$this->current_job]['backup_type'];
$this->task['data']['backup']['doing']=$sub_job_name;
$this->task['data']['backup']['sub_job'][$sub_job_name]['progress']=$progress;
if(!isset( $this->task['data']['backup']['sub_job'][$sub_job_name]['job_data']))
{
$this->task['data']['backup']['sub_job'][$sub_job_name]['job_data']=array();
}
$this->update_task();
}
public function get_next_job()
{
$job_key=false;
foreach ($this->task['jobs'] as $key=>$job)
{
if($job['finished']==0)
{
$job_key=$key;
break;
}
}
return $job_key;
}
public function do_backup_job($key)
{
if(!isset($this->task['jobs'][$key]))
{
$ret['result']='failed';
$ret['error']='not found job';
return $ret;
}
//backup_type
$this->current_job=$key;
$job=$this->task['jobs'][$key];
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Prepare to backup '.$job['backup_type'].' files.','notice');
$this->update_sub_task_progress(sprintf('Start backing up %s.',$job['backup_type']));
if($job['backup_type']=='backup_db')
{
$ret=$this->do_backup_db();
if($ret['result']!='success')
{
return $ret;
}
else
{
$this->rename_backup_files($key);
}
}
else if($job['backup_type']=='backup_merge')
{
$ret=$this->do_backup_merge();
if($ret['result']!='success')
{
return $ret;
}
else
{
$this->rename_backup_files($key);
}
}
else
{
$ret=$this->do_backup_files($job['backup_type']);
if($ret['result']!='success')
{
return $ret;
}
else
{
$this->rename_backup_files($key);
}
}
$wpvivid_plugin->wpvivid_log->WriteLog('Backing up '.$job['backup_type'].' completed.','notice');
$this->task['jobs'][$key]['finished']=1;
$this->task['status']['resume_count']=0;
$this->update_sub_task_progress(sprintf('Backing up %s finished.',$job['backup_type']));
$this->update_main_progress();
$ret['result']='success';
return $ret;
}
public function rename_backup_files($key)
{
if(isset($this->task['jobs'][$key]['zip_file']))
{
if(count($this->task['jobs'][$key]['zip_file'])==1)
{
$backup_type=$this->task['jobs'][$key]['backup_type'];
$file_prefix=$this->task['options']['file_prefix'];
$old_file=array_shift($this->task['jobs'][$key]['zip_file']);
if($backup_type=='backup_merge')
{
$backup_type='backup_all';
}
$filename=$file_prefix.'_'.$backup_type.'.zip';
$zip['filename']=$filename;
$zip['finished']=1;
$this->task['jobs'][$key]['zip_file']=array();
$this->task['jobs'][$key]['zip_file'][$filename]=$zip;
$path=$this->task['options']['dir'].'/';
rename($path.$old_file['filename'],$path.$filename);
$this->update_task();
}
}
}
public function update_main_progress()
{
$i_finished_backup_count=0;
$i_sum=count($this->task['jobs']);
foreach ($this->task['jobs'] as $job)
{
if($job['finished']==1)
{
$i_finished_backup_count++;
}
}
$i_progress=intval(($i_finished_backup_count/$i_sum)*100);
$this->task['data']['backup']['progress']=$i_progress;
$this->update_task();
}
public function update_database_progress($i_progress)
{
$this->task['data']['backup']['progress']=$i_progress;
$this->update_task();
}
public function delete_canceled_backup_files($task_id)
{
$path = $this->task['options']['dir'];
$handler=opendir($path);
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if(preg_match('#'.$task_id.'#',$filename) || preg_match('#'.apply_filters('wpvivid_fix_wpvivid_free', $task_id).'#',$filename))
{
@wp_delete_file($path.'/'.$filename);
}
}
@closedir($handler);
}
}
public function update_task()
{
wp_cache_flush();
$default = array();
$tasks = get_option('wpvivid_task_list', $default);
if(array_key_exists ($this->task_id, $tasks))
{
$this->task['status']['run_time']=time();
WPvivid_Setting::update_task($this->task_id,$this->task);
}
else
{
$this->delete_canceled_backup_files($this->task_id);
}
}
public function do_backup_merge()
{
$root_path=$this->get_backup_root('backup_merge');
$files=$this->get_merge_files($root_path);
if(empty($files))
{
$ret['result']='success';
return $ret;
}
$max_zip_file_size= $this->task['setting']['max_file_size']*1024*1024;
$path=$this->task['options']['dir'].'/';
$zip_method=isset($this->task['setting']['zip_method'])?$this->task['setting']['zip_method']:'ziparchive';
$zip=new WPvivid_Zip($zip_method);
$zip_file_name=$path.$this->get_zip_file('backup_merge');
$numItems = count($files);
$i = 0;
$index=$this->get_zipped_file_index();
foreach ($files as $file)
{
if($this->check_cancel_backup())
{
die();
}
if($i<$index)
{
$i++;
continue;
}
if($max_zip_file_size==0)
$max_zip_file_size = 4 * 1024 * 1024 * 1024;
if(!file_exists($zip_file_name) || filesize($zip_file_name) == 0)
{
$zip->add_file($zip_file_name,$file,basename($file),dirname($file));
$i++;
$child_json=$this->get_file_json($file);
$this->update_merge_zipped_file_index($i,basename($file),$child_json);
if($i === $numItems)
{
continue;
}
if((filesize($zip_file_name)>$max_zip_file_size) || ($i >= 55000))
{
$json=array();
$json=$this->get_json_info('backup_merge',$json);
$this->update_zip_file(basename($zip_file_name),1,$json);
$zip_file_name=$path.$this->add_zip_file('backup_merge');
}
}
else if(((filesize($zip_file_name) + filesize($file)) < $max_zip_file_size) && $i < 55000)
{
$zip->add_file($zip_file_name,$file,basename($file),dirname($file));
$i++;
$child_json=$this->get_file_json($file);
$this->update_merge_zipped_file_index($i,basename($file),$child_json);
if($i === $numItems)
{
continue;
}
}
else
{
$json=array();
$json=$this->get_json_info('backup_merge',$json);
$this->update_zip_file(basename($zip_file_name),1,$json);
$zip_file_name=$path.$this->add_zip_file('backup_merge');
$zip->add_file($zip_file_name,$file,basename($file),dirname($file));
$i++;
$child_json=$this->get_file_json($file);
$this->update_merge_zipped_file_index($i,basename($file),$child_json);
if($i === $numItems)
{
continue;
}
}
/*if(filesize($zip_file_name)>$max_zip_file_size)
{
$json=array();
$json=$this->get_json_info('backup_merge',$json);
$this->update_zip_file(basename($zip_file_name),1,$json);
$zip_file_name=$path.$this->add_zip_file('backup_merge');
}*/
}
$json=array();
$json=$this->get_json_info('backup_merge',$json);
$this->update_zip_file(basename($zip_file_name),1,$json);
foreach ($files as $file)
{
@wp_delete_file($file);
}
$ret['result']='success';
return $ret;
}
public function do_backup_files($backup_type)
{
$root_path=$this->get_backup_root($backup_type);
$exclude_files=$this->get_backup_type_exclude_files($backup_type);
$backup_symlink_folder=$this->task['setting']['backup_symlink_folder'];
if($root_path===false)
{
$ret['result']='failed';
$ret['error']='backup type not found';
return $ret;
}
$compress_file_use_cache= $this->task['setting']['compress_file_use_cache'];
$replace_path=$this->get_replace_path($backup_type);
if($compress_file_use_cache)
{
if(!$this->check_cache_files())
{
$this->clean_zip_files();
if($backup_type=='backup_core')
{
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files,$this->task['options']['include_files']);
}
else if($backup_type=='backup_plugin')
{
if(!empty($this->task['options']['include_plugins']))
{
$include_regex=array();
foreach ($this->task['options']['include_plugins'] as $plugins)
{
$include_regex[]='#^'.preg_quote($this -> transfer_path(WP_PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugins), '/').'#';
}
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files,$include_regex);
}
else
{
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files);
}
}
else if($backup_type=='backup_themes')
{
if(!empty($this->task['options']['include_themes']))
{
$include_regex=array();
foreach ($this->task['options']['include_themes'] as $themes)
{
$include_regex[]='#^'.preg_quote($this -> transfer_path(get_theme_root().DIRECTORY_SEPARATOR.$themes), '/').'#';
}
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files,$include_regex);
}
else
{
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files);
}
}
else
{
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files);
}
$cache_file_prefix=WP_CONTENT_DIR.'/'.WPvivid_Setting::get_backupdir().'/'.$this->task['options']['file_prefix'].'_'.$backup_type.'_';
if($backup_type=='backup_core')
{
$ret=$this->create_cache_files($cache_file_prefix,$root_path,$backup_symlink_folder,$exclude_files,$this->task['options']['include_files']);
}
else if($backup_type=='backup_custom_other')
{
$ret=$this->create_custom_other_cache_files($cache_file_prefix,$this->task['options']['custom_other_root'],$backup_symlink_folder,$exclude_files,$this->task['options']['custom_other_include_files']);
}
else if($backup_type=='backup_plugin')
{
if(!empty($this->task['options']['include_plugins']))
{
$include_regex=array();
foreach ($this->task['options']['include_plugins'] as $plugins)
{
$include_regex[]='#^'.preg_quote($this -> transfer_path(WP_PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugins), '/').'#';
}
$ret=$this->create_cache_files($cache_file_prefix,$root_path,$backup_symlink_folder,$exclude_files,$include_regex);
}
else
{
$ret=$this->create_cache_files($cache_file_prefix,$root_path,$backup_symlink_folder,$exclude_files);
}
}
else if($backup_type=='backup_themes')
{
if(!empty($this->task['options']['include_themes']))
{
$include_regex=array();
foreach ($this->task['options']['include_themes'] as $themes)
{
$include_regex[]='#^'.preg_quote($this -> transfer_path(get_theme_root().DIRECTORY_SEPARATOR.$themes), '/').'#';
}
$ret=$this->create_cache_files($cache_file_prefix,$root_path,$backup_symlink_folder,$exclude_files,$include_regex);
}
else
{
$ret=$this->create_cache_files($cache_file_prefix,$root_path,$backup_symlink_folder,$exclude_files);
}
}
else
{
$ret=$this->create_cache_files($cache_file_prefix,$root_path,$backup_symlink_folder,$exclude_files);
}
if($ret['is_empty']===true)
{
$ret['result']='success';
$this->clean_tmp_files();
return $ret;
}
$ret=$this->_backup_empty_folder($folders,$backup_type);
if($ret['result']!='success')
{
return $ret;
}
}
$ret=$this->_backup_files_use_cache($backup_type,$replace_path);
}
else
{
if($backup_type=='backup_core')
{
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files,$this->task['options']['include_files']);
}
else if($backup_type=='backup_plugin')
{
if(!empty($this->task['options']['include_plugins']))
{
$include_regex=array();
foreach ($this->task['options']['include_plugins'] as $plugins)
{
$include_regex[]='#^'.preg_quote($this -> transfer_path(WP_PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugins), '/').'#';
}
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files,$include_regex);
}
else
{
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files);
}
}
else if($backup_type=='backup_themes')
{
if(!empty($this->task['options']['include_themes']))
{
$include_regex=array();
foreach ($this->task['options']['include_themes'] as $themes)
{
$include_regex[]='#^'.preg_quote($this -> transfer_path(get_theme_root().DIRECTORY_SEPARATOR.$themes), '/').'#';
}
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files,$include_regex);
}
else
{
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files);
}
}
else
{
$folders=$this->get_empty_folders($root_path,$replace_path,$backup_symlink_folder,$exclude_files);
}
if($backup_type=='backup_core')
{
$files=$this->get_files($root_path,$backup_symlink_folder,$exclude_files,$this->task['options']['include_files']);
}
else if($backup_type=='backup_plugin')
{
if(!empty($this->task['options']['include_plugins']))
{
$include_regex=array();
foreach ($this->task['options']['include_plugins'] as $plugins)
{
$include_regex[]='#^'.preg_quote($this -> transfer_path(WP_PLUGIN_DIR.DIRECTORY_SEPARATOR.$plugins), '/').'#';
}
$files=$this->get_files($root_path,$backup_symlink_folder,$exclude_files,$include_regex);
}
else
{
$files=$this->get_files($root_path,$backup_symlink_folder,$exclude_files);
}
}
else if($backup_type=='backup_themes')
{
if(!empty($this->task['options']['include_themes']))
{
$include_regex=array();
foreach ($this->task['options']['include_themes'] as $themes)
{
$include_regex[]='#^'.preg_quote($this -> transfer_path(get_theme_root().DIRECTORY_SEPARATOR.$themes), '/').'#';
}
$files=$this->get_files($root_path,$backup_symlink_folder,$exclude_files,$include_regex);
}
else
{
$files=$this->get_files($root_path,$backup_symlink_folder,$exclude_files);
}
}
else
{
$files=$this->get_files($root_path,$backup_symlink_folder,$exclude_files);
}
$replace_path=$this->get_replace_path($backup_type);
if(empty($files))
{
$ret['result']='success';
return $ret;
}
else
{
$ret=$this->_backup_empty_folder($folders,$backup_type);
if($ret['result']!='success')
{
return $ret;
}
$ret=$this->_backup_files($files,$replace_path,$backup_type);
}
}
return $ret;
}
public function transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode('/',$values);
}
public function get_backup_root($backup_type)
{
if($backup_type=='backup_themes')
{
return $this->transfer_path(get_theme_root());
}
else if($backup_type=='backup_plugin')
{
return $this->transfer_path(WP_PLUGIN_DIR);
}
else if($backup_type=='backup_uploads')
{
$upload_dir = wp_upload_dir();
return $this -> transfer_path($upload_dir['basedir']);
}
else if($backup_type=='backup_content')
{
return $this -> transfer_path(WP_CONTENT_DIR);
}
else if($backup_type=='backup_core')
{
return $this -> transfer_path(ABSPATH);
}
else if($backup_type=='backup_merge')
{
return $this -> transfer_path(WP_CONTENT_DIR.'/'.WPvivid_Setting::get_backupdir());
}
else
{
return false;
}
}
public function get_replace_path($backup_type)
{
if($backup_type=='backup_themes')
{
return $this->transfer_path(WP_CONTENT_DIR.'/');
}
else if($backup_type=='backup_plugin')
{
return $this->transfer_path(WP_CONTENT_DIR.'/');
}
else if($backup_type=='backup_uploads')
{
return $this->transfer_path(WP_CONTENT_DIR.'/');
}
else if($backup_type=='backup_content')
{
return $this->transfer_path(WP_CONTENT_DIR.'/');
}
else if($backup_type=='backup_core')
{
return $this -> transfer_path(ABSPATH);
}
else
{
return false;
}
}
public function check_cache_files()
{
if($this->current_job!==false)
{
if(isset($this->task['jobs'][$this->current_job]['cache_files']))
{
return true;
}
}
return false;
}
public function clean_tmp_files()
{
if($this->current_job!==false)
{
if(isset($this->task['jobs'][$this->current_job]['cache_files']))
{
foreach ($this->task['jobs'][$this->current_job]['cache_files'] as $cache_file)
{
@wp_delete_file($cache_file['name']);
}
}
if(isset($this->task['jobs'][$this->current_job]['mysql_dump_files']))
{
$files=$this->task['jobs'][$this->current_job]['mysql_dump_files'];
if(count($files)==1)
{
$path=$this->task['options']['dir'].'/';
$new_file=$this->task['options']['file_prefix'].'_backup_db.sql';
@wp_delete_file($path.$new_file);
}
else
{
$path=$this->task['options']['dir'].'/';
foreach ($files as $file)
{
@wp_delete_file($path.$file);
}
}
}
}
}
public function get_empty_folders($root_path,$replace_path,$backup_symlink_folder=false,$exclude_files=array(),$include_files=array())
{
$folder=array();
$exclude_regex=array_merge($this->task['options']['exclude_files'],$exclude_files);
$root_path=untrailingslashit($root_path);
$this->_get_folders($root_path,$replace_path,$folder,$backup_symlink_folder,$exclude_regex,$include_files);
return $folder;
}
public function _get_folders($path,$replace_path,&$folders,$backup_symlink_folder=false,$exclude_regex=array(),$include_regex=array())
{
$handler = opendir($path);
if($handler===false)
return;
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if (is_dir($path . '/' . $filename))
{
if($backup_symlink_folder == 1 || ($backup_symlink_folder == 0 && !@is_link($path . '/' . $filename)))
{
if($this->regex_match($exclude_regex, $this->transfer_path($path . '/' . $filename), 0))
{
if ($this->regex_match($include_regex, $path . '/' . $filename, 1))
{
$folders[]=str_replace($replace_path,'',$this->transfer_path($path . '/' . $filename));
$this->_get_folders($path . '/' . $filename,$replace_path,$folders,$backup_symlink_folder,$exclude_regex,$include_regex);
}
}
}
}
}
}
if($handler)
@closedir($handler);
return;
}
public function _backup_empty_folder($folders,$backup_type)
{
$file_prefix=$this->task['options']['file_prefix'];
$file_index=$this->get_file_index();
$zip_file_name=$file_prefix.'_'.$backup_type.'.part'.sprintf('%03d',($file_index)).'.zip';
$zip_method=isset($this->task['setting']['zip_method'])?$this->task['setting']['zip_method']:'ziparchive';
$zip=new WPvivid_Zip($zip_method);
return $zip->addEmptyDir($zip_file_name,$folders);
}
public function create_cache_files($file_prefix,$root_path,$backup_symlink_folder=false,$exclude_files=array(),$include_files=array())
{
$number=1;
$cache_file_handle=false;
$max_cache_file_size=16*1024*1024;
$exclude_regex=array_merge($this->task['options']['exclude_files'],$exclude_files);
$exclude_file_size=$this->task['setting']['exclude_file_size'];
$root_path=untrailingslashit($root_path);
$skip_files_time=0;
$files=$this->get_file_cache($root_path,$file_prefix,$cache_file_handle,$max_cache_file_size,$number,$backup_symlink_folder,$exclude_regex,$include_files,$exclude_file_size,$skip_files_time);
if($this->current_job!==false)
{
foreach ($files as $file)
{
$file_data['name']=$file;
$file_data['index']=0;
$file_data['finished']=0;
$this->task['jobs'][$this->current_job]['cache_files'][$file_data['name']]=$file_data;
}
$this->update_task();
}
$ret['result']='success';
$ret['is_empty']=$this->is_cache_empty($files);
return $ret;
}
public function is_cache_empty($files)
{
$empty=true;
foreach ($files as $file)
{
if(filesize($file)>0)
{
$empty=false;
break;
}
}
return $empty;
}
public function create_custom_other_cache_files($file_prefix,$custom_other_root,$backup_symlink_folder=false,$exclude_files=array(),$include_files=array())
{
$number=1;
$cache_file_handle=false;
$max_cache_file_size=16*1024*1024;
$exclude_regex=array_merge($this->task['options']['exclude_files'],$exclude_files);
$exclude_file_size=$this->task['setting']['exclude_file_size'];
if(isset($this->task['options']['incremental_options']))
{
$skip_files_time=$this->task['options']['incremental_options']['versions']['skip_files_time'];
}
else
{
$skip_files_time=0;
}
$files=array();
foreach ($custom_other_root as $root_path)
{
$files1=$this->get_file_cache($root_path,$file_prefix,$cache_file_handle,$max_cache_file_size,$number,$backup_symlink_folder,$exclude_regex,$include_files,$exclude_file_size,$skip_files_time);
$files=array_merge($files,$files1);
}
if($this->current_job!==false)
{
foreach ($files as $file)
{
$file_data['name']=$file;
$file_data['index']=0;
$file_data['finished']=0;
$this->task['jobs'][$this->current_job]['cache_files'][$file_data['name']]=$file_data;
}
$this->update_task();
}
$ret['result']='success';
$ret['is_empty']=$this->is_cache_empty($files);
return $ret;
}
public function update_files_cache($file_data)
{
if($this->current_job!==false)
{
$this->task['jobs'][$this->current_job]['cache_files'][$file_data['name']]=$file_data;
$this->task['status']['resume_count']=0;
$this->update_task();
}
}
public function get_files_cache_list()
{
if($this->current_job!==false)
{
return $this->task['jobs'][$this->current_job]['cache_files'];
}
else
{
return array();
}
}
public function get_files_from_cache($cache_file,$index,$max_count)
{
$files=array();
$file = new SplFileObject($cache_file);
$file->seek($index);
$file->setFlags( \SplFileObject::SKIP_EMPTY | \SplFileObject::READ_AHEAD );
$count=0;
while(!$file->eof())
{
$src = $file->fgets();
$src=trim($src,PHP_EOL);
if(empty($src))
continue;
if(!file_exists($src))
{
continue;
}
$files[$src]=$src;
$count++;
if($count>$max_count)
{
break;
}
}
$ret['eof']=$file->eof();
$ret['files']=$files;
return $ret;
}
public function get_files_from_cache_by_size($cache_file,$index,$max_zip_file_size,$use_pclzip)
{
$files=array();
$file = new SplFileObject($cache_file);
//$file->seek($index);
if (version_compare(PHP_VERSION, '8.0.1', '>=') || $index == 0) {
$file->seek($index);
} else {
if( $index == 1 ){
$file->rewind(); // Ensure to go at first row before exit
$file->fgets(); // Read line 0. Cursor remains now at line 1
} else {
$file->seek($index-1);
}
}
$file->setFlags( \SplFileObject::SKIP_EMPTY | \SplFileObject::READ_AHEAD );
$current_size=0;
$current=$index;
$current_file_index = 0;
while(!$file->eof())
{
$src = $file->fgets();
$src=trim($src,PHP_EOL);
if(empty($src))
{
continue;
}
if(!file_exists($src))
{
continue;
}
if($max_zip_file_size==0)
$max_zip_file_size = 4 * 1024 * 1024 * 1024;
if($current_size > 0)
{
$current_size+=filesize($src);
}
if($current_size == 0)
{
$current++;
$current_file_index++;
$files[$src]=$src;
$current_size+=filesize($src);
}
else if(($current_size>$max_zip_file_size) || ($use_pclzip && ($current_file_index >= 55000)))
{
break;
}
else
{
$current++;
$current_file_index++;
$files[$src]=$src;
}
}
$ret['eof']=$file->eof();
$ret['index']=$current;
$ret['files']=$files;
return $ret;
}
public function get_files_count($files,$index,$add_files_count)
{
$add_files = array_slice($files,$index,$add_files_count);
if($index+$add_files_count>count($files))
{
$eof=true;
}
else
{
$eof=false;
}
$ret['eof']=$eof;
$ret['files']=$add_files;
return $ret;
}
public function get_files_size($files,$index,$max_zip_file_size,$use_pclzip)
{
$current=0;
$current_file_index = 0;
$current_size=0;
$add_files=array();
foreach ($files as $file)
{
if($current<$index)
{
$current++;
continue;
}
if($max_zip_file_size==0)
$max_zip_file_size = 4 * 1024 * 1024 * 1024;
if($current_size > 0)
{
$current_size+=filesize($file);
}
if($current_size == 0)
{
$current++;
$current_file_index++;
$add_files[]=$file;
$current_size+=filesize($file);
}
else if(($current_size>$max_zip_file_size) || ($use_pclzip && ($current_file_index >= 55000)))
{
break;
}
else
{
$current++;
$current_file_index++;
$add_files[]=$file;
}
}
if($current>=count($files))
{
$eof=true;
}
else
{
$eof=false;
}
$ret['eof']=$eof;
$ret['index']=$current;
$ret['files']=$add_files;
return $ret;
}
public function get_file_cache($path,$cache_prefix,&$cache_file_handle,$max_cache_file_size,&$number,$backup_symlink_folder,$exclude_files,$include_files,$exclude_file_size,$skip_files_time)
{
$files=array();
if(!$cache_file_handle)
{
$cache_file=$cache_prefix.$number.'.cache';
$cache_file_handle=fopen($cache_file,'a');
$files[] = $cache_file;
}
$handler = opendir($path);
if($handler===false)
return $files;
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if (is_dir($path . '/' . $filename))
{
if($backup_symlink_folder == 1 || ($backup_symlink_folder == 0 && !@is_link($path . '/' . $filename)))
{
if($this->regex_match($exclude_files, $this->transfer_path($path . '/' . $filename), 0))
{
if ($this->regex_match($include_files, $path . '/' . $filename, 1))
{
$files2=$this->get_file_cache($path . '/' . $filename,$cache_prefix,$cache_file_handle,$max_cache_file_size,$number,$backup_symlink_folder,$exclude_files,$include_files,$exclude_file_size,$skip_files_time);
$files=array_merge($files,$files2);
}
}
}
}
else
{
if($this->regex_match($exclude_files, $this->transfer_path($path . '/' . $filename), 0))
{
if(is_readable($path . '/' . $filename))
{
if($backup_symlink_folder == 1 || ($backup_symlink_folder == 0 && !@is_link($path . '/' . $filename)))
{
if ($exclude_file_size != 0)
{
if (filesize($path . '/' . $filename) < $exclude_file_size * 1024 * 1024)
{
$add=true;
}
else
{
$add=false;
}
}
else
{
$add=true;
}
if($add)
{
if($skip_files_time>0)
{
$file_time=filemtime($path . '/' . $filename);
if($file_time>0&&$file_time>$skip_files_time)
{
$line = $this->transfer_path($path . '/' . $filename).PHP_EOL;
fwrite($cache_file_handle, $line);
}
}
else
{
$line = $this->transfer_path($path . '/' . $filename).PHP_EOL;
fwrite($cache_file_handle, $line);
}
}
}
}
}
}
}
}
if($handler)
@closedir($handler);
return $files;
}
public function get_zip_file($backup_type)
{
if($this->current_job!==false)
{
if(!isset($this->task['jobs'][$this->current_job]['zip_file']))
{
$file_prefix=$this->task['options']['file_prefix'];
if($backup_type=='backup_merge')
{
$backup_type='backup_all';
}
$filename=$file_prefix.'_'.$backup_type.'.part'.sprintf('%03d',($this->task['jobs'][$this->current_job]['file_index'])).'.zip';
$zip['filename']=$filename;
$zip['finished']=0;
$this->task['jobs'][$this->current_job]['zip_file'][$filename]=$zip;
$this->update_task();
return $filename;
}
else
{
foreach ($this->task['jobs'][$this->current_job]['zip_file'] as $zip)
{
if( $zip['finished']==0)
{
return $zip['filename'];
}
}
return false;
}
}
else
{
return false;
}
}
public function add_zip_file($backup_type)
{
if($this->current_job!==false)
{
$this->task['jobs'][$this->current_job]['file_index']++;
$file_prefix=$this->task['options']['file_prefix'];
if($backup_type=='backup_merge')
{
$backup_type='backup_all';
$this->task['jobs'][$this->current_job]['child_file']=array();
}
$filename=$file_prefix.'_'.$backup_type.'.part'.sprintf('%03d',($this->task['jobs'][$this->current_job]['file_index'])).'.zip';
$zip['filename']=$filename;
$zip['finished']=0;
$this->task['jobs'][$this->current_job]['zip_file'][$filename]=$zip;
$this->task['status']['resume_count']=0;
$this->update_task();
$this->set_time_limit();
return $filename;
}
else
{
return false;
}
}
public function update_zip_file($zip_name,$finished,$json=array())
{
if($this->current_job!==false)
{
if($json!==false)
$this->add_json_file($zip_name,$json);
$this->task['jobs'][$this->current_job]['zip_file'][$zip_name]['finished']=$finished;
$this->task['jobs'][$this->current_job]['zip_file'][$zip_name]['json']=$json;
$this->update_task();
}
}
public function add_json_file($zip_name,$json)
{
$zip_method=isset($this->task['setting']['zip_method'])?$this->task['setting']['zip_method']:'ziparchive';
$zip=new WPvivid_Zip($zip_method);
$path=WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir().DIRECTORY_SEPARATOR;
return $zip->add_json_file($path.$zip_name,$json);
}
public function _backup_files_use_cache($backup_type,$replace_path)
{
global $wpvivid_plugin;
$max_zip_file_size= $this->task['setting']['max_file_size']*1024*1024;
$add_files_count=$this->task['setting']['compress_file_count'];
$path=$this->task['options']['dir'].'/';
$files_cache_list=$this->get_files_cache_list();
$zip_method=isset($this->task['setting']['zip_method'])?$this->task['setting']['zip_method']:'ziparchive';
$zip=new WPvivid_Zip($zip_method);
if($zip_method=='ziparchive')
{
if($zip->check_ziparchive_available())
{
$use_pclzip=false;
}
else
{
$use_pclzip=true;
}
}
else
{
$use_pclzip=true;
}
$zip_file_name=$path.$this->get_zip_file($backup_type);
$json=array();
$json=$this->get_json_info($backup_type,$json);
$numItems = count($files_cache_list);
$i = 0;
foreach ($files_cache_list as $cache_file)
{
$i++;
if($cache_file['finished']==1)
continue;
$eof=false;
while(!$eof)
{
if ($this->check_cancel_backup())
{
die();
}
if ($use_pclzip)
{
$files_cache = $this->get_files_from_cache_by_size($cache_file['name'], $cache_file['index'], $max_zip_file_size, $use_pclzip);
$eof = $files_cache['eof'];
$files = $files_cache['files'];
$cache_file['index'] = $files_cache['index'];
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing zip file:' . basename($zip_file_name) . ' index:' . $cache_file['index'], 'notice');
$zip->add_files($zip_file_name, $replace_path, $files, true, $json);
//$cache_file['index'] += $add_files_count;
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing zip file:' . basename($zip_file_name) . ' success. index:' . $cache_file['index'] . ' file size:' . size_format(filesize($zip_file_name), 2), 'notice');
$this->update_zip_file(basename($zip_file_name), 1, false);
$this->update_files_cache($cache_file);
if ($i === $numItems && $eof)
{
continue;
}
$zip_file_name = $path . $this->add_zip_file($backup_type);
}
else
{
//$files_cache = $this->get_files_from_cache($cache_file['name'], $cache_file['index'], $add_files_count);
$files_cache = $this->get_files_from_cache_by_size($cache_file['name'], $cache_file['index'], $max_zip_file_size, $use_pclzip);
$eof = $files_cache['eof'];
$files = $files_cache['files'];
$cache_file['index'] = $files_cache['index'];
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing zip file:' . basename($zip_file_name) . ' index:' . $cache_file['index'], 'notice');
$zip->add_files($zip_file_name, $replace_path, $files);
//$cache_file['index'] += $add_files_count;
$this->update_files_cache($cache_file);
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing zip file:' . basename($zip_file_name) . ' success. index:' . $cache_file['index'] . ' file size:' . size_format(filesize($zip_file_name), 2), 'notice');
if ($i === $numItems && $eof)
{
continue;
}
$this->update_zip_file(basename($zip_file_name), 1, $json);
$zip_file_name = $path . $this->add_zip_file($backup_type);
/*if ($max_zip_file_size !== 0 && (filesize($zip_file_name) > $max_zip_file_size))
{
$this->update_zip_file(basename($zip_file_name), 1, $json);
$zip_file_name = $path . $this->add_zip_file($backup_type);
}*/
}
}
$cache_file['finished']=1;
$this->update_files_cache($cache_file);
}
if(!$use_pclzip)
{
$this->update_zip_file(basename($zip_file_name),1,$json);
}
$this->clean_tmp_files();
$ret['result']='success';
return $ret;
}
public function get_json_info($backup_type,$json)
{
global $wpdb;
if($backup_type=='backup_themes')
{
$json['file_type']='themes';
$json['root_flag']='wp-content';
$json['php_version']=phpversion();
$json['mysql_version']=$wpdb->db_version();
$json['wp_version'] = get_bloginfo( 'version' );
$json['themes']=$this->get_themes_list();
}
else if($backup_type=='backup_plugin')
{
$json['file_type']='plugin';
$json['root_flag']='wp-content';
$json['php_version']=phpversion();
$json['mysql_version']=$wpdb->db_version();
$json['wp_version'] = get_bloginfo( 'version' );
$json['plugin']=$this->get_plugins_list();
}
else if($backup_type=='backup_uploads')
{
$json['file_type']='upload';
$json['root_flag']='wp-content';
$json['php_version']=phpversion();
$json['mysql_version']=$wpdb->db_version();
$json['wp_version'] = get_bloginfo( 'version' );
}
else if($backup_type=='backup_content')
{
$json['file_type']='wp-content';
$json['root_flag']='wp-content';
$json['php_version']=phpversion();
$json['mysql_version']=$wpdb->db_version();
$json['wp_version'] = get_bloginfo( 'version' );
}
else if($backup_type=='backup_core')
{
$json['file_type']='wp-core';
$json['include_path'][]='wp-includes';
$json['include_path'][]='wp-admin';
$json['wp_core']=1;
$json['root_flag']='root';
$json['home_url']=home_url();
}
else if($backup_type=='backup_db')
{
global $wpdb;
$json['dump_db']=1;
$json['file_type']='databases';
if(isset($this->task['options']['site_id']))
{
$json['site_id']=$this->task['options']['site_id'];
global $wpdb;
$site_prefix= $wpdb->get_blog_prefix($this->task['options']['site_id']);
$json['home_url']=get_home_url($this->task['options']['site_id']);
$json['site_url']=get_site_url($this->task['options']['site_id']);
$json['blog_prefix']=$site_prefix;
$json['mu_migrate']=1;
$json['base_prefix']=$wpdb->get_blog_prefix(0);
}
else
{
$json['home_url']=home_url();
}
$json['root_flag']='custom';
$json['php_version']=phpversion();
$json['mysql_version']=$wpdb->db_version();
$json['wp_version'] = get_bloginfo( 'version' );
if(is_multisite())
{
$json['is_mu']=1;
}
//encrypt_db
if(isset($this->task['options']['encrypt_db'])&&$this->task['options']['encrypt_db'])
{
$json['is_crypt']=1;
}
}
else if($backup_type=='backup_merge')
{
$json['has_child']=1;
$json['home_url']=home_url();
$json['root_flag']='custom';
$json['php_version']=phpversion();
$json['mysql_version']=$wpdb->db_version();
$json['wp_version'] = get_bloginfo( 'version' );
$json['child_file']=array();
foreach ($this->task['jobs'][$this->current_job]['child_file'] as $file=>$child_json)
{
$json['child_file'][$file]=$child_json;
}
}
return $json;
}
public function get_themes_list()
{
$themes_list=array();
$list=wp_get_themes();
foreach ($list as $key=>$item)
{
$path=$this -> transfer_path(get_theme_root().'/'.$key);
if($this->regex_match($this->task['options']['exclude_files'],$path, 0))
{
$themes_list[$key]['slug']=$key;
}
}
return $themes_list;
}
public function get_plugins_list()
{
$plugins_list=array();
if(!function_exists('get_plugins'))
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
$list=get_plugins();
foreach ($list as $key=>$item)
{
if(dirname($key)=='.')
continue;
$path=$this -> transfer_path(WP_PLUGIN_DIR.'/'.$key);
if($this->regex_match($this->task['options']['exclude_files'],$path, 0))
{
$plugins_list[dirname($key)]['slug']=dirname($key);
}
}
return $plugins_list;
}
public function get_files($root_path,$backup_symlink_folder=false,$exclude_files=array(),$include_files=array())
{
$files=array();
$exclude_regex=array_merge($this->task['options']['exclude_files'],$exclude_files);
$exclude_file_size=$this->task['setting']['exclude_file_size'];
$root_path=untrailingslashit($root_path);
if(isset($this->task['options']['incremental_options']))
{
$skip_files_time=$this->task['options']['incremental_options']['versions']['skip_files_time'];
}
else
{
$skip_files_time=0;
}
$this->_get_files($root_path,$files,$backup_symlink_folder,$exclude_regex,$include_files,$exclude_file_size,$skip_files_time);
return $files;
}
public function _get_files($path,&$files,$backup_symlink_folder,$exclude_regex,$include_regex,$exclude_file_size,$skip_files_time)
{
$handler = opendir($path);
if($handler===false)
return;
while (($filename = readdir($handler)) !== false)
{
if ($filename != "." && $filename != "..")
{
if (is_dir($path . '/' . $filename))
{
if($backup_symlink_folder == 1 || ($backup_symlink_folder == 0 && !@is_link($path . '/' . $filename)))
{
if($this->regex_match($exclude_regex, $this->transfer_path($path . '/' . $filename), 0))
{
if ($this->regex_match($include_regex, $path . '/' . $filename, 1))
{
$this->_get_files($path . '/' . $filename,$files,$backup_symlink_folder,$exclude_regex,$include_regex,$exclude_file_size,$skip_files_time);
}
}
}
}
else
{
if(is_readable($path . '/' . $filename))
{
if($backup_symlink_folder == 1 || ($backup_symlink_folder == 0 && !@is_link($path . '/' . $filename)))
{
if($skip_files_time>0)
{
$file_time=filemtime($path . '/' . $filename);
if($file_time>0&&$file_time>$skip_files_time)
{
if ($exclude_file_size == 0)
{
if($this->regex_match($exclude_regex, $this->transfer_path($path . '/' . $filename), 0))
{
$files[]=$this->transfer_path($path . '/' . $filename);
}
}
else
{
if($this->regex_match($exclude_regex, $this->transfer_path($path . '/' . $filename), 0))
{
if (filesize($path . '/' . $filename) < $exclude_file_size * 1024 * 1024)
{
$files[]=$this->transfer_path($path . '/' . $filename);
}
}
}
}
}
else
{
if ($exclude_file_size == 0)
{
if($this->regex_match($exclude_regex, $this->transfer_path($path . '/' . $filename), 0))
{
$files[]=$this->transfer_path($path . '/' . $filename);
}
}
else
{
if($this->regex_match($exclude_regex, $this->transfer_path($path . '/' . $filename), 0))
{
if (filesize($path . '/' . $filename) < $exclude_file_size * 1024 * 1024)
{
$files[]=$this->transfer_path($path . '/' . $filename);
}
}
}
}
}
}
}
}
}
if($handler)
@closedir($handler);
return;
}
public function get_merge_files($root_path)
{
$files=array();
foreach ($this->task['jobs'] as $job)
{
if($job['backup_type']=='backup_merge')
continue;
if(isset($job['zip_file']))
{
foreach ($job['zip_file'] as $zip)
{
if( $zip['finished']!=0)
{
$files[]=$root_path.'/'.$zip['filename'];
}
}
}
}
return $files;
}
private function regex_match($regex_array,$string,$mode)
{
if(empty($regex_array))
{
return true;
}
if($mode==0)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return false;
}
}
return true;
}
if($mode==1)
{
foreach ($regex_array as $regex)
{
if(preg_match($regex,$string))
{
return true;
}
}
return false;
}
return true;
}
public function _backup_files($files,$replace_path,$backup_type)
{
global $wpvivid_plugin;
$max_zip_file_size= $this->task['setting']['max_file_size']*1024*1024;
$add_files_count=$this->task['setting']['compress_file_count'];
$path=$this->task['options']['dir'].'/';
$zip_method=isset($this->task['setting']['zip_method'])?$this->task['setting']['zip_method']:'ziparchive';
$zip=new WPvivid_Zip($zip_method);
if($zip_method=='ziparchive')
{
if($zip->check_ziparchive_available())
{
$use_pclzip=false;
}
else
{
$use_pclzip=true;
}
}
else
{
$use_pclzip=true;
}
$zip_file_name=$path.$this->get_zip_file($backup_type);
$json=array();
$json=$this->get_json_info($backup_type,$json);
$eof=false;
$index=$this->get_zipped_file_index();
while(!$eof)
{
if($this->check_cancel_backup())
{
die();
}
if($use_pclzip)
{
$files_count=$this->get_files_size($files,$index,$max_zip_file_size,$use_pclzip);
$eof=$files_count['eof'];
$index=$files_count['index'];
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing zip file:'.basename($zip_file_name).' index:'.$index,'notice');
$ret=$zip->add_files($zip_file_name,$replace_path,$files_count['files'],true,$json);
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing zip file:'.basename($zip_file_name).' success. index:'.$index.' file size:'.size_format(filesize($zip_file_name),2),'notice');
if($ret['result']!='success')
{
return $ret;
}
$this->update_zip_file(basename($zip_file_name),1,false);
$this->update_zipped_file_index($index);
if($eof)
{
continue;
}
$zip_file_name=$path.$this->add_zip_file($backup_type);
}
else
{
//$files_count=$this->get_files_count($files,$index,$add_files_count);
$files_count=$this->get_files_size($files,$index,$max_zip_file_size,$use_pclzip);
$eof=$files_count['eof'];
//$index+=$add_files_count;
$index=$files_count['index'];
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing zip file:'.basename($zip_file_name).' index:'.$index,'notice');
$ret=$zip->add_files($zip_file_name,$replace_path,$files_count['files']);
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing zip file:'.basename($zip_file_name).' success. index:'.$index.' file size:'.size_format(filesize($zip_file_name),2),'notice');
if($ret['result']!='success')
{
return $ret;
}
$this->update_zipped_file_index($index);
if($eof)
{
continue;
}
$this->update_zip_file(basename($zip_file_name),1,$json);
$zip_file_name=$path.$this->add_zip_file($backup_type);
}
}
if(!$use_pclzip)
$this->update_zip_file(basename($zip_file_name),1,$json);
$ret['result']='success';
return $ret;
}
public function do_backup_db()
{
if(!class_exists('WPvividTypeAdapterFactory'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-mysqldump-method.php';
}
$this->task['dump_setting']=$this->init_db_backup_setting();
$dump = new WPvivid_Mysqldump2($this,$this->task['dump_setting']);
$dump->connect();
if(!isset($this->task['jobs'][$this->current_job]['sub_jobs']))
{
$ret=$dump->init_job();
if($ret===false)
{
$ret['result']='failed';
$ret['error']='tables not found.';
return $ret;
}
}
if($this->check_cancel_backup())
{
die();
}
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Start exporting database.','notice');
$ret= $dump->start_jobs();
if($ret['result']=='success')
{
$wpvivid_plugin->wpvivid_log->WriteLog('Exporting database finished.','notice');
$files=$this->get_mysql_dump_files();
$jobs=$this->get_current_sub_job();
$tables=array();
foreach ( $jobs as $job)
{
$table['name']=$job['name'];
$table['size']=$job['size'];
$table['rows']=$job['rows'];
$tables[]=$table;
}
$wpvivid_plugin->wpvivid_log->WriteLog('Start compressing database','notice');
$find_zero_date=$dump->is_has_zero_date();
$ret=$this->zip_mysql_dump_files($files,$tables,$find_zero_date);
$wpvivid_plugin->wpvivid_log->WriteLog('Compressing database completed','notice');
}
$this->clean_tmp_files();
return $ret;
}
public function get_current_mysql_file_index()
{
if($this->current_job!==false)
{
return $this->task['jobs'][$this->current_job]['mysql_file_index'];
}
else
{
return 1;
}
}
public function reset_mysql_file_index()
{
$this->task['jobs'][$this->current_job]['mysql_file_index']=1;
$this->update_task();
}
public function get_mysql_dump_files()
{
if($this->current_job!==false)
{
$files=$this->task['jobs'][$this->current_job]['mysql_dump_files'];
if(count($files)==1)
{
$path=$this->task['options']['dir'].'/';
$file=array_shift($files);
if($this->task['jobs'][$this->current_job]['backup_type']=='backup_additional_db')
{
$new_file=$this->task['options']['file_prefix'].'_backup_additional_db.sql';
}
else
{
$new_file=$this->task['options']['file_prefix'].'_backup_db.sql';
}
rename($path.$file,$path.$new_file);
$dump_files=array();
$dump_files[]=$path.$new_file;
}
else
{
$dump_files=array();
$path=$this->task['options']['dir'].'/';
foreach ($files as $file)
{
$dump_files[]=$path.$file;
}
}
return $dump_files;
}
else
{
return array();
}
}
public function add_mysql_dump_files($name_file_name)
{
if($this->current_job!==false)
{
$this->task['jobs'][$this->current_job]['mysql_dump_files'][]=$name_file_name;
$this->task['jobs'][$this->current_job]['mysql_file_index']++;
$this->update_task();
}
}
public function get_file_index()
{
if($this->current_job!==false)
{
return $this->task['jobs'][$this->current_job]['file_index'];
}
else
{
return 1;
}
}
public function get_zipped_file_index()
{
if($this->current_job!==false)
{
return $this->task['jobs'][$this->current_job]['index'];
}
else
{
return 0;
}
}
public function update_zipped_file_index($index)
{
if($this->current_job!==false)
{
$this->task['jobs'][$this->current_job]['index']=$index;
$this->task['status']['resume_count']=0;
$this->update_task();
}
}
public function update_merge_zipped_file_index($index,$file,$json)
{
if($this->current_job!==false)
{
$this->task['jobs'][$this->current_job]['index']=$index;
$this->task['status']['resume_count']=0;
$this->task['jobs'][$this->current_job]['child_file'][$file]=$json;
$this->update_task();
}
}
public function zip_mysql_dump_files($files,$tables,$find_zero_date=false)
{
foreach ($files as $file)
{
$json['files'][]=basename($file);
}
$json['tables']=$tables;
$json=$this->get_json_info('backup_db',$json);
$max_zip_file_size= $this->task['setting']['max_file_size']*1024*1024;
$path=$this->task['options']['dir'].'/';
$zip_method=isset($this->task['setting']['zip_method'])?$this->task['setting']['zip_method']:'ziparchive';
$zip=new WPvivid_Zip($zip_method);
$zip_file_name=$path.$this->get_zip_file('backup_db');
$numItems = count($files);
$i = 0;
foreach ($files as $file)
{
$ret=$zip->add_file($zip_file_name,$file,basename($file),dirname($file));
if($ret['result']!='success')
{
return $ret;
}
if(++$i === $numItems)
{
continue;
}
if($max_zip_file_size !== 0 && (filesize($zip_file_name)>$max_zip_file_size))
{
$this->update_zip_file(basename($zip_file_name),1,$json);
$zip_file_name=$path.$this->add_zip_file('backup_db');
}
}
if($find_zero_date)
{
$json['find_zero_date']=1;
}
$this->update_zip_file(basename($zip_file_name),1,$json);
$ret['result']='success';
return $ret;
}
public function update_current_sub_job($jobs)
{
if($this->current_job!==false)
{
$this->task['jobs'][$this->current_job]['sub_jobs']=$jobs;
$this->update_task();
}
}
public function get_current_sub_job()
{
if($this->current_job!==false)
{
return $this->task['jobs'][$this->current_job]['sub_jobs'];
}
else
{
return false;
}
}
public function init_db_backup_setting()
{
global $wpdb;
$dump_setting['database'] = DB_NAME;
$dump_setting['host'] = DB_HOST;
$dump_setting['user'] = DB_USER;
$dump_setting['pass'] = DB_PASSWORD;
$dump_setting['site_url']=get_site_url();
$dump_setting['home_url']=get_home_url();
$dump_setting['content_url']=content_url();
$dump_setting['prefix'] = $wpdb->get_blog_prefix(0);
$db_connect_method = isset($this->task['setting']['db_connect_method']) ? $this->task['setting']['db_connect_method'] : 'wpdb';
if ($db_connect_method === 'wpdb')
{
$dump_setting['db_connect_method']='wpdb';
}
else
{
$dump_setting['db_connect_method']='mysql';
}
$dump_setting['file_prefix']=$this->task['options']['file_prefix'];
$dump_setting['path']=$this->task['options']['dir'];
$dump_setting['max_file_size']=$this->task['setting']['max_sql_file_size']*1024*1024;
$dump_setting['exclude-tables']=isset($this->task['options']['exclude-tables'])?$this->task['options']['exclude-tables']:array();
$dump_setting['include-tables']=isset($this->task['options']['include-tables'])?$this->task['options']['include-tables']:array();
return $dump_setting;
}
public function update_status($status)
{
$this->task['status']['str']=$status;
$this->task['status']['run_time']=time();
WPvivid_Setting::update_task($this->task_id,$this->task);
}
public function get_status()
{
return $this->task['status'];
}
public function set_time_limit()
{
//max_execution_time
@set_time_limit( $this->task['setting']['max_execution_time']);
$this->task['status']['timeout']=time();
$this->update_task();
}
public function get_time_limit()
{
return $this->task['setting']['max_execution_time'];
}
public function get_max_resume_count()
{
return $this->task['setting']['max_resume_count'];
}
public function update_backup_task_status($reset_start_time=false,$status='',$reset_timeout=false,$resume_count=false,$error='')
{
$this->task['status']['run_time']=time();
if($reset_start_time)
$this->task['status']['start_time']=time();
if(!empty($status))
{
$this->task['status']['str']=$status;
}
if($reset_timeout)
$this->task['status']['timeout']=time();
if($resume_count!==false)
{
$this->task['status']['resume_count']=$resume_count;
}
if(!empty($error))
{
$this->task['status']['error']=$error;
}
$this->update_task();
}
public function get_setting()
{
return $this->task['setting'];
}
public function get_unfinished_job()
{
$job=false;
if(!$this->is_backup_finished())
{
$job_key=$this->get_next_job();
if($job_key!==false)
{
$job=$this->task['jobs'][$job_key];
}
}
return $job;
}
public function clean_zip_files()
{
if($this->current_job!==false)
{
if(isset($this->task['jobs'][$this->current_job]['zip_file']))
{
$path=$this->task['options']['dir'].'/';
foreach ($this->task['jobs'][$this->current_job]['zip_file'] as $zip)
{
@wp_delete_file($path.$zip['filename']);
}
unset($this->task['jobs'][$this->current_job]['zip_file']);
$this->task['jobs'][$this->current_job]['file_index']=1;
$this->update_task();
}
}
}
public function need_upload()
{
//remote_options
if($this->task['options']['remote_options']===false)
{
return false;
}
else
{
return true;
}
}
public function is_upload_finished()
{
$b_finished=true;
if(array_key_exists('upload',$this->task['data']))
{
foreach ($this->task['data']['upload']['sub_job'] as $upload_job)
{
if($upload_job['finished']!=1)
{
$b_finished=false;
break;
}
}
}
else
{
$b_finished=false;
}
return $b_finished;
}
public function get_remote_options()
{
return $this->task['options']['remote_options'];
}
public function get_backup_files()
{
$files=array();
$root_path=$this -> transfer_path(WP_CONTENT_DIR.'/'.WPvivid_Setting::get_backupdir());
foreach ($this->task['jobs'] as $job)
{
if($job['backup_type']=='backup_merge')
{
$files=array();
if(isset($job['zip_file']))
{
foreach ($job['zip_file'] as $zip)
{
$files[]=$root_path.'/'.$zip['filename'];
}
}
break;
}
if(isset($job['zip_file']))
{
foreach ($job['zip_file'] as $zip)
{
$files[]=$root_path.'/'.$zip['filename'];
}
}
}
return $files;
}
public function update_backup_result()
{
$files=$this->get_backup_files();
$backup_result['result']['result']='success';
if(!empty($files))
{
foreach ($files as $file)
{
$file_data['file_name'] = basename($file);
$file_data['size'] = filesize($file);
$backup_result['result']['files'][] =$file_data;
}
}
$is_merge=$this->task['setting']['is_merge'];
if($is_merge==1)
{
$backup_result['key']='backup_merge';
}
$this->task['options']['backup_options']['ismerge']=$is_merge;
$this->task['options']['backup_options']['backup'][]=$backup_result;
$this->update_task();
}
public function add_new_backup()
{
$files=$this->get_backup_files();
if(empty($files))
{
return;
}
$backup_data=array();
$backup_data['type']=$this->task['type'];
$backup_data['create_time']=$this->task['status']['start_time'];
$backup_data['manual_delete']=0;
$backup_data['local']['path']=$this->task['options']['backup_dir'];
$backup_data['compress']['compress_type']='zip';
$backup_data['save_local']=$this->task['options']['save_local'];
if(isset($this->task['options']['backup_prefix']))
{
$backup_data['backup_prefix'] = $this->task['options']['backup_prefix'];
}
$backup_data['log']=$this->task['options']['log_file_path'];
$backup_result['result']='success';
foreach ($files as $file)
{
$file_data['file_name'] = basename($file);
$file_data['size'] = filesize($file);
$backup_result['files'][] =$file_data;
}
$backup_data['backup']=$backup_result;
$backup_data['remote']=array();
if(isset($this->task['options']['lock']))
{
$backup_data['lock'] = $this->task['options']['lock'];
}
$backup_list='wpvivid_backup_list';
$backup_list=apply_filters('get_wpvivid_backup_list_name',$backup_list,$this->task['id']);
$list = WPvivid_Setting::get_option($backup_list);
$list[$this->task['id']]=$backup_data;
WPvivid_Setting::update_option($backup_list,$list);
}
public function set_remote_lock()
{
$backup_lock=get_option('wpvivid_remote_backups_lock');
$backup_id = $this->task['id'];
if(isset($this->task['options']['lock']))
{
$lock = $this->task['options']['lock'];
}
else
{
$lock = 0;
}
if($lock)
{
$backup_lock[$backup_id]=1;
}
else {
unset($backup_lock[$backup_id]);
}
update_option('wpvivid_remote_backups_lock',$backup_lock,'no');
}
public function add_exist_backup($backup_id,$type='Common')
{
$files=$this->get_backup_files();
if(empty($files))
{
return;
}
$backup=WPvivid_Backuplist::get_backup_by_id($backup_id);
$backup_result['files']=array();
foreach ($files as $file)
{
$file_data['file_name'] = basename($file);
$file_data['size'] = filesize($file);
$backup_result['files'][] =$file_data;
}
$backup['backup']['files']=array_merge($backup['backup']['files'],$backup_result['files']);
WPvivid_Backuplist::update_backup($backup_id,'backup', $backup['backup']);
}
public function clean_backup()
{
if(empty($this->task_id))
{
return;
}
$path = $this->task['options']['dir'];
$handler=opendir($path);
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if(preg_match('#'.$this->task_id.'#',$filename) || preg_match('#'.apply_filters('wpvivid_fix_wpvivid_free', $this->task_id).'#',$filename))
{
@wp_delete_file($path.'/'.$filename);
}
}
@closedir($handler);
}
}
public function get_backup_task_info()
{
$list_tasks['status']=$this->task['status'];
$list_tasks['is_canceled']=$this->is_task_canceled();
$list_tasks['data']=$this->get_backup_tasks_progress();
//
$list_tasks['task_info']['need_next_schedule']=false;
if($list_tasks['status']['str']=='running'||$list_tasks['status']['str']=='no_responds')
{
if($list_tasks['data']['running_stamp']>180)
{
$list_tasks['task_info']['need_next_schedule'] = true;
}
else{
$list_tasks['task_info']['need_next_schedule'] = false;
}
}
$list_tasks['task_info']['display_estimate_backup'] = '';
$list_tasks['task_info']['backup_percent']=$list_tasks['data']['progress'].'%';
//
$list_tasks['task_info']['db_size']=0;
$list_tasks['task_info']['file_size']=0;
$list_tasks['task_info']['descript']='';
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['total'] = 'N/A';
$list_tasks['task_info']['upload'] = 'N/A';
$list_tasks['task_info']['speed'] = 'N/A';
$list_tasks['task_info']['network_connection'] = 'N/A';
$list_tasks['task_info']['need_update_last_task']=false;
if($list_tasks['status']['str']=='ready')
{
$list_tasks['task_info']['descript']=__('Ready to backup. Progress: 0%, running time: 0second.','wpvivid-backuprestore');
$list_tasks['task_info']['css_btn_cancel']='pointer-events: none; opacity: 0.4;';
$list_tasks['task_info']['css_btn_log']='pointer-events: none; opacity: 0.4;';
}
else if($list_tasks['status']['str']=='running')
{
if($list_tasks['is_canceled'] == false)
{
if($list_tasks['data']['type'] == 'upload')
{
if(isset($list_tasks['data']['upload_data']) && !empty($list_tasks['data']['upload_data']))
{
$descript = $list_tasks['data']['upload_data']['descript'];
$offset = $list_tasks['data']['upload_data']['offset'];
$current_size = $list_tasks['data']['upload_data']['current_size'];
$last_time = $list_tasks['data']['upload_data']['last_time'];
$last_size = $list_tasks['data']['upload_data']['last_size'];
$speed = ($offset - $last_size) / (time() - $last_time);
$speed /= 1000;
$speed = round($speed, 2);
$speed .= 'kb/s';
if(!empty($current_size)) {
$list_tasks['task_info']['total'] = size_format($current_size,2);
}
if(!empty($offset)) {
$list_tasks['task_info']['upload'] = size_format($offset, 2);
}
}
else{
$descript = 'Start uploading.';
$speed = '0kb/s';
$list_tasks['task_info']['total'] = 'N/A';
$list_tasks['task_info']['upload'] = 'N/A';
}
$list_tasks['task_info']['speed'] = $speed;
$list_tasks['task_info']['descript'] = $descript.' '.__('Progress: ', 'wpvivid-backuprestore') . $list_tasks['task_info']['backup_percent'] . ', ' . __('running time: ', 'wpvivid-backuprestore') . $list_tasks['data']['running_time'];
$time_spend=time()-$list_tasks['status']['run_time'];
if($time_spend>30)
{
$list_tasks['task_info']['network_connection']='Retrying';
}
else
{
$list_tasks['task_info']['network_connection']='OK';
}
}
else {
$list_tasks['task_info']['descript'] = $list_tasks['data']['descript'] . ' '. __('Progress: ', 'wpvivid-backuprestore') . $list_tasks['task_info']['backup_percent'] . ', '. __('running time: ', 'wpvivid-backuprestore') . $list_tasks['data']['running_time'];
}
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
}
else{
$list_tasks['task_info']['descript']=__('The backup will be canceled after backing up the current chunk ends.','wpvivid-backuprestore');
$list_tasks['task_info']['css_btn_cancel']='pointer-events: none; opacity: 0.4;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
}
}
else if($list_tasks['status']['str']=='wait_resume')
{
$list_tasks['task_info']['descript']='Task '.$this->task_id.' timed out, backup task will retry in '.$list_tasks['data']['next_resume_time'].' seconds, retry times: '.$list_tasks['status']['resume_count'].'.';
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
}
else if($list_tasks['status']['str']=='no_responds')
{
if($list_tasks['is_canceled'] == false)
{
$list_tasks['task_info']['descript']='Task , '.$list_tasks['data']['doing'].' is not responding. Progress: '.$list_tasks['task_info']['backup_percent'].', running time: '.$list_tasks['data']['running_time'];
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
}
else{
$list_tasks['task_info']['descript']=__('The backup will be canceled after backing up the current chunk ends.','wpvivid-backuprestore');
$list_tasks['task_info']['css_btn_cancel']='pointer-events: none; opacity: 0.4;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
}
}
else if($list_tasks['status']['str']=='completed')
{
$list_tasks['task_info']['descript']='Task '.$this->task_id.' completed.';
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['need_update_last_task']=true;
}
else if($list_tasks['status']['str']=='error')
{
$list_tasks['task_info']['descript']='Backup error: '.$list_tasks['status']['error'];
$list_tasks['task_info']['css_btn_cancel']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['css_btn_log']='pointer-events: auto; opacity: 1;';
$list_tasks['task_info']['need_update_last_task']=true;
}
return $list_tasks;
}
public function is_task_canceled()
{
$file_name=$this->task['options']['file_prefix'];
$file =$this->task['options']['dir'].'/'. $file_name . '_cancel';
if (file_exists($file))
{
return true;
}
return false;
}
public function check_cancel_backup()
{
if($this->is_task_canceled())
{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Backup cancelled.','notice');
$this->update_status('cancel');
$this->clean_tmp_files();
$tasks=WPvivid_Setting::get_option('wpvivid_clean_task_2');
$tasks[$this->task_id]=$this->task;
WPvivid_Setting::update_option('wpvivid_clean_task_2',$tasks);
$resume_time=time()+60;
$b=wp_schedule_single_event($resume_time,'wpvivid_clean_backup_data_event_2',array($this->task_id));
if($b===false)
{
$timestamp = wp_next_scheduled('wpvivid_clean_backup_data_event_2',array($this->task_id));
if($timestamp!==false)
{
$resume_time=max($resume_time,$timestamp+10*60+10);
wp_schedule_single_event($resume_time,'wpvivid_clean_backup_data_event_2',array($this->task_id));
}
}
$timestamp =wp_next_scheduled('wpvivid_task_monitor_event',array($this->task_id));
if($timestamp!==false)
{
wp_unschedule_event($timestamp,'wpvivid_task_monitor_event',array($this->task_id));
}
wp_cache_flush();
WPvivid_taskmanager::delete_task($this->task_id);
wp_cache_flush();
$this->wpvivid_check_clear_litespeed_rule();
return true;
}
else
{
return false;
}
}
public function get_backup_tasks_progress()
{
$current_time=gmdate("Y-m-d H:i:s");
$create_time=gmdate("Y-m-d H:i:s",$this->task['status']['start_time']);
$time_diff=strtotime($current_time)-strtotime($create_time);
$running_time='';
if(gmdate("G",$time_diff) > 0){
$running_time .= gmdate("G",$time_diff).' hour(s)';
}
if(intval(gmdate("i",$time_diff)) > 0){
$running_time .= intval(gmdate("i",$time_diff)).' min(s)';
}
if(intval(gmdate("s",$time_diff)) > 0){
$running_time .= intval(gmdate("s",$time_diff)).' second(s)';
}
$next_resume_time=$this->get_next_resume_time();
$ret['type']=$this->task['data']['doing'];
$ret['progress']=$this->task['data'][$ret['type']]['progress'];
$ret['doing']=$this->task['data'][$ret['type']]['doing'];
if(isset($this->task['data'][$ret['type']]['sub_job'][$ret['doing']]['progress']))
{
$ret['descript']=$this->task['data'][$ret['type']]['sub_job'][$ret['doing']]['progress'];
}
else
{
$ret['descript']='';
}
if(isset($this->task['data'][$ret['type']]['sub_job'][$ret['doing']]['upload_data']))
$ret['upload_data']=$this->task['data'][$ret['type']]['sub_job'][$ret['doing']]['upload_data'];
$this->task['data'][$ret['type']]['sub_job'][$ret['doing']]['upload_data']=false;
$ret['running_time']=$running_time;
$ret['running_stamp']=$time_diff;
$ret['next_resume_time']=$next_resume_time;
return $ret;
}
public function get_next_resume_time()
{
$timestamp=wp_next_scheduled(WPVIVID_RESUME_SCHEDULE_EVENT,array($this->task_id));
if($timestamp!==false)
{
return $timestamp-time();
}
else
{
return false;
}
}
public function clear_cache()
{
$path = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
$handler=opendir($path);
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if(preg_match('#pclzip-.*\.tmp#', $filename)){
@wp_delete_file($path.DIRECTORY_SEPARATOR.$filename);
}
if(preg_match('#pclzip-.*\.gz#', $filename)){
@wp_delete_file($path.DIRECTORY_SEPARATOR.$filename);
}
}
@closedir($handler);
}
}
public function is_save_local()
{
return isset($this->task['options']['save_local'])?$this->task['options']['save_local']:false;
}
public function clean_local_files()
{
$path = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.WPvivid_Setting::get_backupdir();
$handler=opendir($path);
if($handler!==false)
{
while(($filename=readdir($handler))!==false)
{
if(preg_match('#'.$this->task_id.'#',$filename) || preg_match('#'.apply_filters('wpvivid_fix_wpvivid_free', $this->task_id).'#',$filename))
{
@wp_delete_file($path.DIRECTORY_SEPARATOR.$filename);
}
}
@closedir($handler);
}
}
public function get_backup_jobs()
{
return $this->task['jobs'];
}
public function get_file_json($file)
{
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
$ret=$zip->get_json_data($file);
if($ret['result'] === WPVIVID_SUCCESS)
{
$json=$ret['json_data'];
$json = json_decode($json, 1);
if (is_null($json))
{
return false;
} else {
return $json;
}
}
else
{
return array();
}
}
//adaptive settings
public function check_memory_limit()
{
$current_memory_limit=$this->task['setting']['memory_limit'];
$current_memory_int = (int) filter_var($current_memory_limit, FILTER_SANITIZE_NUMBER_INT);
if($current_memory_int<512)
{
$this->task['setting']['memory_limit']='512M';
$this->update_task();
return true;
}
else if($current_memory_int<1024)
{
$this->task['setting']['memory_limit']=($current_memory_int+100).'M';
$this->update_task();
return true;
}
else
{
return false;
}
}
public function check_timeout()
{
$job=$this->get_unfinished_job();
if($job!==false)
{
if($job['backup_type']=='backup_db'||$job['backup_type']=='backup_additional_db')
{
if($this->task['setting']['max_sql_file_size']>200)
{
$this->task['setting']['max_sql_file_size']=200;
}
else
{
$this->task['setting']['max_sql_file_size']=max(10,$this->task['setting']['max_sql_file_size']-50);
}
$this->update_task();
}
else
{
//if($this->task['setting']['compress_file_use_cache']==false)
//{
// $this->task['setting']['compress_file_use_cache']=true;
//}
if($this->task['setting']['compress_file_count']>=1000)
{
$this->task['setting']['compress_file_count']=800;
}
else if($this->task['setting']['compress_file_count']>=800)
{
$this->task['setting']['compress_file_count']=500;
}
else if($this->task['setting']['compress_file_count']>=500)
{
$this->task['setting']['compress_file_count']=300;
}
else
{
$this->task['setting']['compress_file_count']=100;
}
if($this->task['setting']['max_file_size']>200)
{
$this->task['setting']['max_file_size']=200;
}
if($this->task['setting']['exclude_file_size']==0)
{
$this->task['setting']['exclude_file_size']=200;
}
$this->update_task();
}
}
}
public function check_execution_time()
{
$this->task['setting']['max_execution_time']=$this->task['setting']['max_execution_time']+120;
$this->update_task();
}
public function check_timeout_backup_failed()
{
//$job=$this->get_unfinished_job();
//if($job!==false)
//{
//if($job['backup_type']=='backup_merge')
//{
//$this->task['setting']['is_merge']=false;
//}
//}
$max_resume_count=$this->get_max_resume_count();
$status=$this->get_status();
$status['resume_count']++;
if($status['resume_count']>$max_resume_count)
{
$this->task['setting']['max_resume_count']=max(20,$this->task['setting']['max_resume_count']+3);
$this->update_task();
}
}
public function update_schedule_last_backup_time()
{
}
public function wpvivid_check_add_litespeed_server()
{
$litespeed=false;
if ( isset( $_SERVER['HTTP_X_LSCACHE'] ) && $_SERVER['HTTP_X_LSCACHE'] )
{
$litespeed=true;
}
elseif ( isset( $_SERVER['LSWS_EDITION'] ) && strpos( $_SERVER['LSWS_EDITION'], 'Openlitespeed' ) === 0 ) {
$litespeed=true;
}
elseif ( isset( $_SERVER['SERVER_SOFTWARE'] ) && $_SERVER['SERVER_SOFTWARE'] == 'LiteSpeed' ) {
$litespeed=true;
}
if($litespeed)
{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('LiteSpeed Server.','notice');
if ( ! function_exists( 'got_mod_rewrite' ) )
{
require_once ABSPATH . 'wp-admin/includes/misc.php';
}
if(function_exists('insert_with_markers'))
{
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
$home_path = get_home_path();
$htaccess_file = $home_path . '.htaccess';
if ( ( ! file_exists( $htaccess_file ) && is_writable( $home_path ) ) || is_writable( $htaccess_file ) )
{
if ( got_mod_rewrite() )
{
$line[]='<IfModule Litespeed>';
$line[]='RewriteEngine On';
$line[]='RewriteRule .* - [E=noabort:1, E=noconntimeout:1]';
$line[]='</IfModule>';
insert_with_markers($htaccess_file,'WPvivid Rewrite Rule for LiteSpeed',$line);
$wpvivid_plugin->wpvivid_log->WriteLog('Add LiteSpeed Rule','notice');
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('mod_rewrite not found.','notice');
}
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('.htaccess file not exists or not writable.','notice');
}
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('insert_with_markers function not exists.','notice');
}
}
}
public function wpvivid_check_clear_litespeed_rule()
{
$litespeed=false;
if ( isset( $_SERVER['HTTP_X_LSCACHE'] ) && $_SERVER['HTTP_X_LSCACHE'] )
{
$litespeed=true;
}
elseif ( isset( $_SERVER['LSWS_EDITION'] ) && strpos( $_SERVER['LSWS_EDITION'], 'Openlitespeed' ) === 0 ) {
$litespeed=true;
}
elseif ( isset( $_SERVER['SERVER_SOFTWARE'] ) && $_SERVER['SERVER_SOFTWARE'] == 'LiteSpeed' ) {
$litespeed=true;
}
if($litespeed)
{
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('LiteSpeed Server.','notice');
if ( ! function_exists( 'got_mod_rewrite' ) )
{
require_once ABSPATH . 'wp-admin/includes/misc.php';
}
if(function_exists('insert_with_markers'))
{
if(!function_exists('get_home_path'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
$home_path = get_home_path();
$htaccess_file = $home_path . '.htaccess';
if ( ( ! file_exists( $htaccess_file ) && is_writable( $home_path ) ) || is_writable( $htaccess_file ) )
{
if ( got_mod_rewrite() )
{
insert_with_markers($htaccess_file,'WPvivid Rewrite Rule for LiteSpeed','');
$wpvivid_plugin->wpvivid_log->WriteLog('Clear LiteSpeed Rule','notice');
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('mod_rewrite not found.','notice');
}
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('.htaccess file not exists or not writable.','notice');
}
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('insert_with_markers function not exists.','notice');
}
}
}
public function wpvivid_disable_litespeed_cache_for_backup()
{
if (defined('LSCWP_V'))
{
do_action( 'litespeed_disable_all', 'stop for backup' );
}
}
} includes/new_backup/class-wpvivid-restore2.php 0000644 00000217524 15132770567 0015567 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Restore_2
{
public $log;
public $end_shutdown_function;
public function __construct()
{
$this->log=false;
$this->end_shutdown_function=false;
add_action('wp_ajax_wpvivid_init_restore_task_2',array($this,'init_restore_task'));
add_action('wp_ajax_wpvivid_do_restore_2',array($this,'do_restore'));
add_action('wp_ajax_nopriv_wpvivid_do_restore_2',array( $this,'do_restore'));
add_action('wp_ajax_wpvivid_get_restore_progress_2',array( $this,'get_restore_progress'));
add_action('wp_ajax_nopriv_wpvivid_get_restore_progress_2',array( $this,'get_restore_progress'));
add_action('wp_ajax_wpvivid_finish_restore_2',array( $this,'finish_restore'));
add_action('wp_ajax_nopriv_wpvivid_finish_restore_2',array( $this,'finish_restore'));
add_action('wp_ajax_wpvivid_restore_failed_2',array( $this,'restore_failed'));
add_action('wp_ajax_nopriv_wpvivid_restore_failed_2',array( $this,'restore_failed'));
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-restore-file-2.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-restore-db-2.php';
}
public function init_restore_task()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if(!isset($_POST['backup_id'])||empty($_POST['backup_id'])||!is_string($_POST['backup_id']))
{
die();
}
$backup_id=sanitize_key($_POST['backup_id']);
$restore_options=array();
if(isset($_POST['restore_options']))
{
foreach ($_POST['restore_options'] as $key=>$option)
{
$restore_options[$key]=sanitize_text_field($option);
}
}
if(isset($restore_options['restore_version']))
{
$restore_version=$restore_options['restore_version'];
}
else
{
$restore_version=0;
}
$restore_options['restore_detail_options']=array();
$ret=$this->create_restore_task($backup_id,$restore_options,$restore_version);
$this->write_litespeed_rule();
$this->deactivate_plugins();
if(!file_exists(WPMU_PLUGIN_DIR.'/a-wpvivid-restore-mu-plugin-check.php'))
{
if(file_exists(WPMU_PLUGIN_DIR))
copy(WPVIVID_PLUGIN_DIR . '/includes/mu-plugins/a-wpvivid-restore-mu-plugin-check.php',WPMU_PLUGIN_DIR.'/a-wpvivid-restore-mu-plugin-check.php');
}
echo wp_json_encode($ret);
die();
}
public function create_restore_task($backup_id,$restore_options,$restore_version)
{
$restore_task=array();
$restore_task['backup_id']=$backup_id;
$restore_task['restore_options']=$restore_options;
$restore_task['update_time']=time();
$restore_task['restore_timeout_count']=0;
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
if($backup===false)
{
$ret['result']='failed';
$ret['error']='backup not found';
return $ret;
}
$backup_item = new WPvivid_Backup_Item($backup);
$backup_file_info=$this->get_restore_files_info($backup_item,$restore_version,true);
$sub_tasks=array();
$b_reset_plugin=false;
foreach ($backup_file_info as $key=>$files_info)
{
$task['type']=$key;
if(isset($restore_options[$key]))
$task['options']=$restore_options[$key];
else
$task['options']=array();
$task['options']['restore_reset']=true;
if($key=='themes')
{
$task['priority']=1;
$task['unzip_file']['files']=$files_info['files'];
$task['unzip_file']['unzip_finished']=0;
$task['unzip_file']['last_action']='waiting...';
$task['unzip_file']['last_unzip_file']='';
$task['unzip_file']['last_unzip_file_index']=0;
}
else if($key=='plugin')
{
$task['priority']=2;
$task['unzip_file']['files']=$files_info['files'];
$task['unzip_file']['unzip_finished']=0;
$task['unzip_file']['last_action']='waiting...';
$task['unzip_file']['last_unzip_file']='';
$task['unzip_file']['last_unzip_file_index']=0;
$b_reset_plugin=isset($restore_options['restore_detail_options']['restore_reset'])?$restore_options['restore_detail_options']['restore_reset']:false;;
}
else if($key=='wp-content')
{
$task['priority']=3;
$task['unzip_file']['files']=$files_info['files'];
$task['unzip_file']['unzip_finished']=0;
$task['unzip_file']['last_action']='waiting...';
$task['unzip_file']['last_unzip_file']='';
$task['unzip_file']['last_unzip_file_index']=0;
}
else if($key=='upload')
{
$task['priority']=4;
$task['unzip_file']['files']=$files_info['files'];
$task['unzip_file']['unzip_finished']=0;
$task['unzip_file']['last_action']='waiting...';
$task['unzip_file']['last_unzip_file']='';
$task['unzip_file']['last_unzip_file_index']=0;
}
else if($key=='wp-core')
{
$task['priority']=5;
$task['unzip_file']['files']=$files_info['files'];
$task['unzip_file']['unzip_finished']=0;
$task['unzip_file']['last_action']='waiting...';
$task['unzip_file']['last_unzip_file']='';
$task['unzip_file']['last_unzip_file_index']=0;
}
else if($key=='custom')
{
$task['priority']=6;
$task['unzip_file']['files']=$files_info['files'];
$task['unzip_file']['unzip_finished']=0;
$task['unzip_file']['last_action']='waiting...';
$task['unzip_file']['last_unzip_file']='';
$task['unzip_file']['last_unzip_file_index']=0;
}
else if($key=='db'||$key=='databases')
{
$task['type']='databases';
$task['unzip_file']['files']=$files_info['files'];
$task['options']=array_merge($task['options'],$task['unzip_file']['files'][0]['options']);
$task['unzip_file']['unzip_finished']=0;
$task['unzip_file']['last_action']='waiting...';
$task['unzip_file']['last_unzip_file']='';
$task['exec_sql']['init_sql_finished']=0;
$task['exec_sql']['create_snapshot_finished']=0;
$task['exec_sql']['exec_sql_finished']=0;
$task['exec_sql']['replace_rows_finished']=0;
$task['exec_sql']['current_table']='';
$task['exec_sql']['current_old_table']='';
$task['exec_sql']['replace_tables']=array();
//$task['exec_sql']['current_replace_table_finish']=false;
//$task['exec_sql']['current_need_replace_table']=false;
//$task['exec_sql']['current_replace_row']=0;
$task['exec_sql']['last_action']='waiting...';
$task['exec_sql']['last_query']='';
$uid=$this->create_db_uid();
if($uid===false)
{
$ret['result']='failed';
$ret['error']='create db uid failed';
return $ret;
}
$task['exec_sql']['db_id']=$uid;
$task['exec_sql']['sql_files']=array();
$task['priority']=8;
$restore_task['restore_db']=1;
}
else
{
$task['priority']=7;
$task['unzip_file']['files']=$files_info['files'];
$task['unzip_file']['unzip_finished']=0;
$task['unzip_file']['last_action']='waiting...';
$task['unzip_file']['last_unzip_file']='';
$task['unzip_file']['last_unzip_file_index']=0;
}
$restore_reset=isset($restore_options['restore_detail_options']['restore_reset'])?$restore_options['restore_detail_options']['restore_reset']:false;
$task['finished']=0;
$task['last_msg']='waiting...';
if($restore_reset)
{
$task['restore_reset']=true;
$task['restore_reset_finished']=false;
}
else
{
$task['restore_reset']=false;
}
$restore_htaccess=isset($restore_options['restore_detail_options']['restore_htaccess'])?$restore_options['restore_detail_options']['restore_htaccess']:false;
if($restore_htaccess)
{
$task['options']['restore_htaccess']=true;
}
else
{
$task['options']['restore_htaccess']=false;
}
$sub_tasks[]=$task;
}
usort($sub_tasks, function ($a, $b)
{
if ($a['priority'] == $b['priority'])
return 0;
if ($a['priority'] > $b['priority'])
return 1;
else
return -1;
});
$restore_task['is_migrate'] = $backup_item->check_migrate_file();
$restore_task['sub_tasks']=$sub_tasks;
$restore_task['do_sub_task']=false;
$restore_task['restore_detail_options']=$this->get_default_restore_options($restore_options['restore_detail_options']);
$id=uniqid('wpvivid-');
$log_file_name=$id.'_restore_log.txt';
$this->log=new WPvivid_Log();
$log_file=$this->log->GetSaveLogFolder().$log_file_name;
$restore_task['log']=$log_file;
$restore_task['last_log']='Init restore task completed.';
$this->log->WriteLog($restore_task['last_log'],'notice');
$restore_task['status']='ready';
update_option('wpvivid_restore_task',$restore_task,'no');
$ret['result']='success';
$ret['reset_plugin']=$b_reset_plugin;
$ret['task']=$restore_task;
return $ret;
}
public function write_litespeed_rule($open=true)
{
$litespeed=false;
if ( isset( $_SERVER['HTTP_X_LSCACHE'] ) && $_SERVER['HTTP_X_LSCACHE'] )
{
$litespeed=true;
}
elseif ( isset( $_SERVER['LSWS_EDITION'] ) && strpos( $_SERVER['LSWS_EDITION'], 'Openlitespeed' ) === 0 ) {
$litespeed=true;
}
elseif ( isset( $_SERVER['SERVER_SOFTWARE'] ) && $_SERVER['SERVER_SOFTWARE'] == 'LiteSpeed' ) {
$litespeed=true;
}
if($litespeed)
{
if (function_exists('insert_with_markers'))
{
$home_path = get_home_path();
$htaccess_file = $home_path . '.htaccess';
if ( ( ! file_exists( $htaccess_file ) && is_writable( $home_path ) ) || is_writable( $htaccess_file ) )
{
if ( got_mod_rewrite() )
{
if($open)
{
$line=array();
$line[]='<IfModule Litespeed>';
$line[]='RewriteEngine On';
$line[]='RewriteRule .* - [E=noabort:1, E=noconntimeout:1]';
$line[]='</IfModule>';
insert_with_markers($htaccess_file,'WPvivid_Restore',$line);
}
else
{
insert_with_markers($htaccess_file,'WPvivid_Restore','');
}
}
}
}
}
}
public function deactivate_plugins()
{
if(is_multisite())
{
$current = get_site_option( 'active_sitewide_plugins' );
update_option( 'wpvivid_save_active_plugins', $current, 'no');
$wpvivid_backup='wpvivid-backuprestore/wpvivid-backuprestore.php';
if (array_key_exists($wpvivid_backup, $current) !== false)
{
unset($current[$wpvivid_backup]);
}
deactivate_plugins($current, true, true);
}
else
{
$current = get_option( 'active_plugins', array() );
update_option( 'wpvivid_save_active_plugins', $current, 'no');
$wpvivid_backup='wpvivid-backuprestore/wpvivid-backuprestore.php';
if (($key = array_search($wpvivid_backup, $current)) !== false)
{
unset($current[$key]);
}
deactivate_plugins($current, true, false);
}
}
public function get_default_restore_options($restore_detail_options)
{
$setting=get_option('wpvivid_common_setting',array());
$restore_detail_options['max_allowed_packet']=32;
$restore_detail_options['replace_rows_pre_request']=isset($setting['replace_rows_pre_request'])?$setting['replace_rows_pre_request']:10000;
$restore_detail_options['restore_max_execution_time']=isset($setting['restore_max_execution_time'])?$setting['restore_max_execution_time']:WPVIVID_RESTORE_MAX_EXECUTION_TIME;
$restore_detail_options['restore_memory_limit']=isset($setting['restore_memory_limit'])?$setting['restore_memory_limit']:WPVIVID_RESTORE_MEMORY_LIMIT;
$restore_detail_options['sql_file_buffer_pre_request']=isset($setting['sql_file_buffer_pre_request'])?$setting['sql_file_buffer_pre_request']:'5';
$restore_detail_options['use_index']=isset($setting['use_index'])?$setting['use_index']:1;
$restore_detail_options['unzip_files_pre_request']=isset($setting['unzip_files_pre_request'])?$setting['unzip_files_pre_request']:1000;
$restore_detail_options['db_connect_method']=isset($setting['db_connect_method'])?$setting['db_connect_method']:'wpdb';
$restore_detail_options['restore_db_reset']=false;
return $restore_detail_options;
}
public function create_db_uid()
{
global $wpdb;
$count = 0;
do
{
$count++;
$uid = sprintf('%06x', wp_rand(0, 0xFFFFFF));
$verify_db = $wpdb->get_col($wpdb->prepare('SHOW TABLES LIKE %s', array('%' . $uid . '%')));
} while (!empty($verify_db) && $count < 10);
if ($count == 10)
{
$uid = false;
}
return $uid;
}
public function get_restore_files_info($backup_item,$restore_version=0,$use_index=0)
{
$files=$backup_item->get_files(false);
$files_info=array();
foreach ($files as $file)
{
$files_info[$file]=$backup_item->get_file_info($file);
}
$info=array();
$added_files=array();
foreach ($files_info as $file_name=>$file_info)
{
if(isset($file_info['has_child']))
{
$info=$this->get_has_child_file_info($info,$file_name,$file_info,$added_files,$restore_version,$use_index);
}
else
{
if(isset($file_info['file_type']))
{
if(isset($file_info['version']))
{
if($restore_version===false)
{
if (!in_array($file_name, $added_files))
{
$file_data['file_name']=$file_name;
$file_data['version']=$file_info['version'];
$file_data['has_version']=true;
$file_data['finished']=0;
if($use_index)
{
$file_data['index']=0;
}
$file_data['options']=$file_info;
$info[$file_info['file_type']]['files'][]= $file_data;
$added_files[]=$file_name;
}
}
else
{
$version=$restore_version;
if($version>=$file_info['version'])
{
if (!in_array($file_name, $added_files))
{
$file_data['file_name']=$file_name;
$file_data['version']=$version;
$file_data['has_version']=true;
$file_data['finished']=0;
if($use_index)
{
$file_data['index']=0;
}
$file_data['options']=$file_info;
$info[$file_info['file_type']]['files'][]= $file_data;
$added_files[]=$file_name;
}
}
}
}
else
{
if (!in_array($file_name, $added_files))
{
$file_data['file_name']=$file_name;
$file_data['version']=0;
$file_data['finished']=0;
if($use_index)
{
$file_data['index']=0;
}
$file_data['options']=$file_info;
$info[$file_info['file_type']]['files'][]= $file_data;
$added_files[]=$file_name;
}
}
}
}
}
return $info;
}
public function get_has_child_file_info($info,$file_name,$file_info,&$added_files,$restore_version=0,$use_index=0)
{
foreach ($file_info['child_file'] as $child_file_name=>$child_file_info)
{
if(isset($child_file_info['file_type']))
{
if(isset($child_file_info['version']))
{
$info=$this->get_file_version_info($info,$file_name,$file_info,$child_file_name,$child_file_info,$restore_version,$added_files,$use_index);
}
else
{
if (!in_array($child_file_name, $added_files))
{
$file_data['file_name']=$child_file_name;
$file_data['version']=0;
$file_data['parent_file']=$file_name;
$file_data['has_child']=1;
$file_data['extract_child_finished']=0;
$file_data['finished']=0;
if($use_index)
{
$file_data['index']=0;
}
$file_data['options']=$file_info['child_file'][$child_file_name];
$info[$child_file_info['file_type']]['files'][]=$file_data;
$added_files[]=$child_file_name;
}
}
}
}
return $info;
}
public function get_file_version_info($info,$file_name,$file_info,$child_file_name,$child_file_info,$restore_version,&$added_files,$use_index)
{
if($restore_version===false||$restore_version>=$child_file_info['version'])
{
if (!in_array($child_file_name, $added_files))
{
$file_data['file_name']=$child_file_name;
$file_data['version']=$child_file_info['version'];
$file_data['has_version']=true;
$file_data['parent_file']=$file_name;
$file_data['has_child']=1;
$file_data['finished']=0;
if($use_index)
{
$file_data['index']=0;
}
$file_data['options']=$file_info['child_file'][$child_file_name];
$info[$child_file_info['file_type']]['files'][]=$file_data;
$added_files[]=$child_file_name;
}
}
return $info;
}
public function deal_restore_shutdown_error()
{
$error = error_get_last();
if (!is_null($error))
{
if(preg_match('/Allowed memory size of.*$/', $error['message']))
{
$restore_task=get_option('wpvivid_restore_task',array());
$restore_detail_options=$restore_task['restore_detail_options'];
$db_connect_method=$restore_detail_options['db_connect_method'];
if($db_connect_method === 'wpdb')
{
$key=$restore_task['do_sub_task'];
if($key!==false)
{
if($restore_task['sub_tasks'][$key]['type']==='databases')
{
global $wpdb;
$wpdb->get_results('COMMIT');
}
}
}
$restore_task['status']='error';
$restore_task['error']=$error['message'];
$restore_task['error_memory_limit']=true;
update_option('wpvivid_restore_task',$restore_task,'no');
}
}
die();
}
public function do_restore()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
if(!$check)
{
die();
}
ini_set('display_errors', false);
error_reporting(-1);
register_shutdown_function(array($this,'deal_restore_shutdown_error'));
try
{
if($this->check_restore_task()==false)
{
$ret['result']='failed';
$ret['error']='restore task has error';
echo wp_json_encode($ret);
$this->end_shutdown_function=true;
die();
}
$this->_enable_maintenance_mode();
$this->set_restore_environment();
//$this->flush();
$ret=$this->_do_restore();
$this->_disable_maintenance_mode();
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$restore_task=get_option('wpvivid_restore_task',array());
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
$this->_disable_maintenance_mode();
$ret['result']='failed';
$ret['error']=$message;
$restore_task['status']='error';
$restore_task['error']=$ret['error'];
update_option('wpvivid_restore_task',$restore_task,'no');
echo wp_json_encode($ret);
}
die();
}
public function _do_restore()
{
$ret['result']='success';
$restore_task=get_option('wpvivid_restore_task',array());
$this->log=new WPvivid_Log();
$this->log->OpenLogFile( $restore_task['log'],'has_folder');
if(empty($restore_task))
{
$ret['result']='failed';
$ret['error']='task empty';
return $ret;
}
$restore_task['do_sub_task']=false;
foreach ($restore_task['sub_tasks'] as $key=>$sub_task)
{
if($sub_task['finished']==1)
{
continue;
}
else
{
$restore_task['do_sub_task']=$key;
break;
}
}
if($restore_task['do_sub_task']===false)
{
$ret['result']='failed';
$ret['error']='no sub task';
$restore_task['status']='error';
$restore_task['error']=$ret['error'];
update_option('wpvivid_restore_task',$restore_task,'no');
return $ret;
}
else
{
$restore_task['status']='doing sub task';
$restore_task['update_time']=time();
update_option('wpvivid_restore_task',$restore_task,'no');
return $this->do_sub_task();
}
}
public function do_sub_task()
{
$restore_task=get_option('wpvivid_restore_task',array());
$key=$restore_task['do_sub_task'];
$sub_task=$restore_task['sub_tasks'][$key];
if($sub_task['type']=='databases')
{
$this->log->WriteLog('Start restoring '.$sub_task['type'].'.','notice');
$restore_db=new WPvivid_Restore_DB_2($this->log);
$ret=$restore_db->restore($sub_task,$restore_task['backup_id']);
if($ret['result']=='success')
{
$this->log->WriteLog('End restore '.$sub_task['type'].'.','notice');
$restore_task=get_option('wpvivid_restore_task',array());
$restore_task['sub_tasks'][$key]=$ret['sub_task'];
$restore_task['status']='sub task finished';
$restore_task['update_time']=time();
update_option('wpvivid_restore_task',$restore_task,'no');
}
else
{
$restore_task=get_option('wpvivid_restore_task',array());
$restore_task['status']='error';
$restore_task['error']=$ret['error'];
wp_cache_flush();
update_option('wpvivid_restore_task',$restore_task,'no');
}
}
else
{
$this->log->WriteLog('Start restoring '.$sub_task['type'].'.','notice');
$restore_file=new WPvivid_Restore_File_2($this->log);
$ret=$restore_file->restore($sub_task,$restore_task['backup_id']);
if($ret['result']=='success')
{
$this->log->WriteLog('End restore '.$sub_task['type'].'.','notice');
$restore_task=get_option('wpvivid_restore_task',array());
$restore_task['sub_tasks'][$key]=$ret['sub_task'];
$restore_task['status']='sub task finished';
$restore_task['update_time']=time();
update_option('wpvivid_restore_task',$restore_task,'no');
}
else
{
$restore_task=get_option('wpvivid_restore_task',array());
$restore_task['status']='error';
$restore_task['error']=$ret['error'];
$this->log->WriteLog('End restore '.$sub_task['type'].' error:'.$ret['error'],'notice');
update_option('wpvivid_restore_task',$restore_task,'no');
}
}
return $ret;
}
public function check_restore_task()
{
$restore_task=get_option('wpvivid_restore_task',array());
if(empty($restore_task))
{
return false;
}
$backup_id=$restore_task['backup_id'];
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
if($backup===false)
{
return false;
}
if(empty($restore_task['sub_tasks']))
{
return false;
}
if($restore_task['do_sub_task']===false)
{
return true;
}
else
{
$sub_task_key=$restore_task['do_sub_task'];
if(isset($restore_task['sub_tasks'][$sub_task_key]))
{
return true;
}
else
{
return false;
}
}
}
public function _enable_maintenance_mode()
{
//enable maintenance mode by create the .maintenance file.
//If your wordpress version is greater than 4.6, use the enable_maintenance_mode filter to make our ajax request pass
$this->init_filesystem();
global $wp_filesystem;
$file = $wp_filesystem->abspath() . '.maintenance';
$maintenance_string = '<?php $upgrading = ' . (time()+1200) . ';';
$maintenance_string.='global $wp_version;';
$maintenance_string.='$version_check=version_compare($wp_version,4.6,\'>\' );';
$maintenance_string.='if($version_check)';
$maintenance_string.='{';
$maintenance_string.='if(!function_exists(\'enable_maintenance_mode_filter\'))';
$maintenance_string.='{';
$maintenance_string.='function enable_maintenance_mode_filter($enable_checks,$upgrading)';
$maintenance_string.='{';
$maintenance_string.='if(is_admin()&&isset($_POST[\'wpvivid_restore\']))';
$maintenance_string.='{';
$maintenance_string.='return false;';
$maintenance_string.='}';
$maintenance_string.='return $enable_checks;';
$maintenance_string.='}';
$maintenance_string.='}';
$maintenance_string.='add_filter( \'enable_maintenance_mode\',\'enable_maintenance_mode_filter\',10, 2 );';
$maintenance_string.='}';
$maintenance_string.='else';
$maintenance_string.='{';
$maintenance_string.='if(is_admin()&&isset($_POST[\'wpvivid_restore\']))';
$maintenance_string.='{';
$maintenance_string.='global $upgrading;';
$maintenance_string.='$upgrading=0;';
$maintenance_string.='return 1;';
$maintenance_string.='}';
$maintenance_string.='}';
if ($wp_filesystem->exists( $file ) )
{
$wp_filesystem->delete($file);
}
$wp_filesystem->put_contents($file, $maintenance_string, FS_CHMOD_FILE);
}
public function _disable_maintenance_mode()
{
$this->init_filesystem();
global $wp_filesystem;
$file = $wp_filesystem->abspath() . '.maintenance';
if ($wp_filesystem->exists( $file ))
{
$wp_filesystem->delete($file);
}
}
public function init_filesystem()
{
$credentials = request_filesystem_credentials(wp_nonce_url(admin_url('admin.php')."?page=WPvivid", 'wpvivid-nonce'));
if ( ! WP_Filesystem($credentials) )
{
return false;
}
return true;
}
public function set_restore_environment()
{
$restore_task=get_option('wpvivid_restore_task',array());
$restore_detail_options=$restore_task['restore_detail_options'];
$memory_limit = $restore_detail_options['restore_memory_limit'];
$restore_max_execution_time= $restore_detail_options['restore_max_execution_time'];
@set_time_limit($restore_max_execution_time);
@ini_set('memory_limit', $memory_limit);
}
public function flush()
{
$ret['result'] = 'success';
$txt = wp_json_encode($ret);
if(!headers_sent()){
header('Content-Length: '.( ( ! empty( $txt ) ) ? strlen( $txt ) : '0' ));
header('Connection: close');
header('Content-Encoding: none');
}
if (session_id())
session_write_close();
echo wp_json_encode($ret);
if(function_exists('fastcgi_finish_request'))
{
fastcgi_finish_request();
}
else
{
if(ob_get_level()>0)
ob_flush();
flush();
}
}
public function get_restore_progress()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
if(!$check)
{
die();
}
$restore_task=get_option('wpvivid_restore_task',array());
if($this->check_restore_task()==false)
{
$ret['result']='failed';
$ret['error']='restore task has error';
$ret['test']=$restore_task;
echo wp_json_encode($ret);
die();
}
$ret['test']=$restore_task;
if($restore_task['status']=='error')
{
$ret['result']='failed';
$ret['error']=$restore_task['error'];
echo wp_json_encode($ret);
die();
}
$key=$restore_task['do_sub_task'];
if($key===false)
{
$ret['result']='success';
$ret['do_sub_task']=false;
$ret['status']='ready';
}
else
{
if(isset($restore_task['sub_tasks'][$key]))
{
$sub_task=$restore_task['sub_tasks'][$key];
$do_sub_task=$sub_task['type'];
if($sub_task['finished']==1)
{
$ret['result']='success';
$ret['do_sub_task']=$do_sub_task;
if($this->check_task_finished())
{
$ret['status']='task finished';
}
else
{
$ret['status']='sub task finished';
}
}
else
{
$ret['result']='success';
$ret['do_sub_task']=$do_sub_task;
if($restore_task['status']=='sub task finished')
{
$ret['status']='sub task finished';
}
else
{
$common_setting = WPvivid_Setting::get_option('wpvivid_common_setting');
if(isset($common_setting['restore_max_execution_time']))
{
$setting_restore_max_execution_time = intval($common_setting['restore_max_execution_time']);
}
else{
$setting_restore_max_execution_time = WPVIVID_RESTORE_MAX_EXECUTION_TIME;
}
$restore_detail_options=$restore_task['restore_detail_options'];
$restore_max_execution_time= isset($restore_detail_options['restore_max_execution_time'])?$restore_detail_options['restore_max_execution_time']:$setting_restore_max_execution_time;
if(time()-$restore_task['update_time']>$restore_max_execution_time)
{
$restore_task['restore_timeout_count']++;
update_option('wpvivid_restore_task',$restore_task,'no');
if($restore_task['restore_timeout_count']>6)
{
$ret['result']='failed';
$ret['error']='restore timeout';
}
else
{
$ret['status']='sub task finished';
}
}
else if(time()-$restore_task['update_time']>180)
{
$ret['status']='no response';
}
else
{
$ret['status']='doing sub task';
}
}
}
if($ret['result']=='success')
{
$ret['main_msg']='doing restore '.$sub_task['type'];
$finished=0;
$total=count($restore_task['sub_tasks']);
$sub_tasks_progress=array();
$sub_tasks_progress_detail=array();
if($total==0)
{
$main_progress=0;
}
else
{
$sub_progress=0;
foreach ($restore_task['sub_tasks'] as $key=>$sub_task)
{
if($sub_task['type']=='themes')
{
$sub_progress_id='wpvivid_restore_themes_progress';
$sub_progress_detail_id='wpvivid_restore_themes_progress_detail';
}
else if($sub_task['type']=='plugin')
{
$sub_progress_id='wpvivid_restore_plugin_progress';
$sub_progress_detail_id='wpvivid_restore_plugin_progress_detail';
}
else if($sub_task['type']=='wp-content')
{
$sub_progress_id='wpvivid_restore_wp_content_progress';
$sub_progress_detail_id='wpvivid_restore_wp_content_progress_detail';
}
else if($sub_task['type']=='upload')
{
$sub_progress_id='wpvivid_restore_upload_progress';
$sub_progress_detail_id='wpvivid_restore_upload_progress_detail';
}
else if($sub_task['type']=='wp-core')
{
$sub_progress_id='wpvivid_restore_core_progress';
$sub_progress_detail_id='wpvivid_restore_core_progress_detail';
}
else if($sub_task['type']=='custom')
{
$sub_progress_id='wpvivid_restore_custom_progress';
$sub_progress_detail_id='wpvivid_restore_custom_progress_detail';
}
else if($sub_task['type']=='db'||$sub_task['type']=='databases')
{
$sub_progress_id='wpvivid_restore_databases_progress';
$sub_progress_detail_id='wpvivid_restore_databases_progress_detail';
}
else if($sub_task['type']=='additional_databases')
{
$sub_progress_id='wpvivid_restore_additional_db_progress';
$sub_progress_detail_id='wpvivid_restore_additional_db_progress_detail';
}
else
{
$sub_progress_id='';
$sub_progress_detail_id='';
}
if($sub_task['finished']==1)
{
$finished++;
$sub_progress+=100;
$sub_task_progress='Completed - 100%<span class="dashicons dashicons-yes" style="color:#8bc34a;"></span>';
}
else
{
if($sub_task['unzip_file']['last_action']=='waiting...')
{
$sub_task_progress='waiting...';
}
else if($sub_task['type']=='databases')
{
if($sub_task['unzip_file']['unzip_finished']==0)
{
$sub_task_progress= $sub_task['unzip_file']['last_action'].' - 0%';
}
else
{
if($restore_task['is_migrate'])
{
$file_size=0;
$read_size=0;
foreach ($sub_task['exec_sql']['sql_files'] as $sql_file)
{
$file_size+=$sql_file['sql_file_size'];
$read_size+=$sql_file['sql_offset'];
}
$progress1=intval(($read_size/ $file_size)*50);
$progress2=0;
if(!empty($sub_task['exec_sql']['replace_tables']))
{
$need_replace_table = sizeof($sub_task['exec_sql']['replace_tables']);
$replaced_tables=0;
foreach ($sub_task['exec_sql']['replace_tables'] as $replace_table)
{
if ($replace_table['finished'] == 1)
{
$replaced_tables++;
}
}
$progress2=intval(($replaced_tables/ $need_replace_table)*50);
}
$progress=$progress1+$progress2;
$sub_progress+=$progress;
$sub_task_progress= $sub_task['exec_sql']['last_action'].' - '.$progress.'%';
}
else
{
$file_size=0;
$read_size=0;
foreach ($sub_task['exec_sql']['sql_files'] as $sql_file)
{
$file_size+=$sql_file['sql_file_size'];
$read_size+=$sql_file['sql_offset'];
}
$progress=intval(($read_size/ $file_size)*100);
$sub_progress+=$progress;
$sub_task_progress= $sub_task['exec_sql']['last_action'].' - '.$progress.'%';
}
}
}
else
{
$files=$sub_task['unzip_file']['files'];
$files_finished=0;
$files_total=count($sub_task['unzip_file']['files']);
foreach ($files as $index=>$file)
{
if ($file['finished'] == 1)
{
$files_finished++;
}
}
if(isset($sub_task['unzip_file']['sum'])&&$sub_task['unzip_file']['start'])
{
$sum=$sub_task['unzip_file']['sum'];
$start=$sub_task['unzip_file']['start'];
if($sum>0)
{
$file_progress=intval((($start/$sum)*100)/$files_total);
}
else
{
$file_progress=0;
}
}
else
{
$file_progress=0;
}
$progress=intval(($files_finished/ $files_total)*100)+$file_progress;
$progress=min(100,$progress);
$sub_progress+=$progress;
$sub_task_progress= $sub_task['unzip_file']['last_action'].' - '.$progress.'%';
}
}
if(!empty($sub_progress_id))
{
$sub_tasks_progress[$sub_progress_id]=$sub_task_progress;
}
if(!empty($sub_progress_id))
{
$sub_tasks_progress_detail[$sub_progress_detail_id]['html']=$sub_task['last_msg'];
if($do_sub_task==$sub_task['type'])
{
$sub_tasks_progress_detail[$sub_progress_detail_id]['show']=true;
}
else
{
$sub_tasks_progress_detail[$sub_progress_detail_id]['show']=false;
}
}
}
$main_progress=intval($sub_progress/$total);
//$main_progress=intval(($finished/$total)*100);
$main_progress=min($main_progress,100);
}
$ret['sub_tasks_progress']=$sub_tasks_progress;
$ret['sub_tasks_progress_detail']=$sub_tasks_progress_detail;
$ret['main_task_progress_total']=$total;
$ret['main_task_progress_finished']=$finished;
$ret['main_progress']='<span class="action-progress-bar-percent wpvivid-span-processed-restore-percent-progress" style="width: '.$main_progress.'%; display:block; height:1.5em; border-radius:0; padding-left:0.5em;">'.$main_progress.'% completed</span>';
$buffer = '';
if(file_exists($restore_task['log']))
{
$file = fopen($restore_task['log'], 'r');
if ($file)
{
while (!feof($file)) {
$buffer .= fread($file, 1024);
}
fclose($file);
}
}
$ret['log'] = $buffer;
if(strlen($ret['log']) > 100*1024)
{
$ret['log']=substr($ret['log'], -100*1024);
}
}
}
else
{
$ret['result']='failed';
$ret['error']='sub task not found';
}
}
echo wp_json_encode($ret);
die();
}
public function check_task_finished()
{
$restore_task=get_option('wpvivid_restore_task',array());
$finished=false;
foreach ($restore_task['sub_tasks'] as $sub_task)
{
if($sub_task['finished']==1)
{
$finished=true;
}
else
{
$finished=false;
break;
}
}
return $finished;
}
public function finish_restore()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
if(!$check)
{
die();
}
register_shutdown_function(array($this,'deal_restore_finish_shutdown_error'));
ini_set('display_errors', 0);
echo '<p style="font-size:1.5em;"><span>The restoration has been successfully completed.</span></p>';
$this->_disable_maintenance_mode();
$this->write_litespeed_rule(false);
if(file_exists(WPMU_PLUGIN_DIR.'/a-wpvivid-restore-mu-plugin-check.php'))
{
@wp_delete_file(WPMU_PLUGIN_DIR.'/a-wpvivid-restore-mu-plugin-check.php');
}
$plugins= get_option( 'wpvivid_save_active_plugins', array() );
$ret=$this->check_restore_db();
$this->delete_temp_files();
delete_transient( 'wp_core_block_css_files' );
$restore_task=get_option('wpvivid_restore_task',array());
if($restore_task['is_migrate'])
{
$this->check_force_ssl();
$this->check_admin_plugins();
$this->flush_elementor_cache();
$this->regenerate_css_files();
if(!is_multisite())
{
if (function_exists('save_mod_rewrite_rules'))
{
if(isset($restore_task['restore_options']['restore_detail_options']['restore_htaccess'])&&$restore_task['restore_options']['restore_detail_options']['restore_htaccess'])
{
//
}
else
{
if (file_exists(get_home_path() . '.htaccess'))
{
$htaccess_data = file_get_contents(get_home_path() . '.htaccess');
$line = '';
if (preg_match('#AddHandler application/x-httpd-php.*#', $htaccess_data, $matcher))
{
$line = PHP_EOL . $matcher[0];
if (preg_match('#<IfModule mod_suphp.c>#', $htaccess_data, $matcher)) {
$line .= PHP_EOL . '<IfModule mod_suphp.c>';
if (preg_match('#suPHP_ConfigPath .*#', $htaccess_data, $matcher)) {
$line .= PHP_EOL . $matcher[0];
}
$line .= PHP_EOL . '</IfModule>';
}
}
else if (preg_match('#AddHandler application/x-httpd-ea-php.*#', $htaccess_data, $matcher))
{
$line_temp = PHP_EOL . $matcher[0];
if (preg_match('#<IfModule mime_module>#', $htaccess_data, $matcher))
{
$line .= PHP_EOL . '<IfModule mime_module>';
$line .= $line_temp.PHP_EOL;
$line .= PHP_EOL . '</IfModule>';
}
}
@rename(get_home_path() . '.htaccess', get_home_path() . '.htaccess_old');
save_mod_rewrite_rules();
if (!empty($line))
file_put_contents(get_home_path() . '.htaccess', $line, FILE_APPEND);
}
else
{
save_mod_rewrite_rules();
}
}
if(file_exists(get_home_path() . '.user.ini'))
{
@rename(get_home_path() . '.user.ini', get_home_path() . '.user.ini_old');
save_mod_rewrite_rules();
}
}
}
//Migration notice
$need_review=WPvivid_Setting::get_option('wpvivid_need_review');
if($need_review=='not')
{
$review_time=WPvivid_Setting::get_option('wpvivid_review_time', false);
if($review_time === false || time() >= $review_time)
{
WPvivid_Setting::update_option('wpvivid_need_review','show');
$msg = 'Migration complete! We\'d love it if you could leave WPvivid Backup Plugin a 5-star rating. It really motivates us to keep improving!';
WPvivid_Setting::update_option('wpvivid_review_msg',$msg);
WPvivid_Setting::update_option('wpvivid_review_type', 'migration');
}
}
}
if($ret['has_db'])
{
$this->active_plugins();
}
else
{
$this->active_plugins($plugins);
}
if($restore_task['is_migrate'])
{
//$html.='<p style="font-size:1.5em;"><span>Save permalinks structure:</span><span><a href="'.admin_url('options-permalink.php').'" target="_blank">click here</a></span></p>';
if($this->check_oxygen())
{
echo '<p style="font-size:1.5em;"><span>The restoration is almost complete, but there is a little bit job to do.</span></p>';
echo '<p style="font-size:1.5em;"><span>We found that your website is using the Oxygen page builder. In order to restore this backup perfectly, please follow</span><span><a href="https://oxygenbuilder.com/documentation/other/importing-exporting/#resigning" target="_blank"> the guide </a>to regenerate the css.</span></p>';
}
if($this->check_divi())
{
$this->clean_divi_cache();
echo '<p style="font-size:1.5em;"><span>The restoration is almost complete, but there is a little bit job to do.</span></p>';
echo '<p style="font-size:1.5em;"><span>We found that your website is using the Divi theme. In order to restore this backup perfectly,</span><span>please follow<a href="https://divitheme.net/clear-divi-cache/" target="_blank"> the guide </a>to clean up the Divi cache</span></p>';
}
}
if(isset( $restore_task['restore_options']['delete_local'])&& $restore_task['restore_options']['delete_local'])
{
$backup_id=$restore_task['backup_id'];
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
if($backup!==false)
{
$backup_item = new WPvivid_Backup_Item($backup);
if($backup_item->get_remote()!==false)
{
$files=$backup_item->get_files(true);
foreach ($files as $file)
{
@wp_delete_file($file);
}
}
}
}
$siteurl = get_option( 'siteurl' );
echo '<p style="font-size:1.5em;"><span><a href="'.esc_url($siteurl).'" target="_blank">Visit Site</a></span></p>';
delete_option('wpvivid_restore_task');
wp_cache_flush();
die();
}
public function check_restore_db()
{
$has_db=false;
$restore_task=get_option('wpvivid_restore_task',array());
$this->log=new WPvivid_Log();
$this->log->OpenLogFile( $restore_task['log'],'has_folder');
foreach ($restore_task['sub_tasks'] as $sub_task)
{
if($sub_task['type']=='databases')
{
$has_db=true;
$restore_db=new WPvivid_Restore_DB_2($this->log);
$current_setting = WPvivid_Setting::export_setting_to_json();
$ret=$restore_db->rename_db($sub_task);
WPvivid_Setting::import_json_to_setting($current_setting);
do_action('wpvivid_reset_schedule');
do_action('wpvivid_do_after_restore_db');
if($restore_task['is_migrate'] == '1')
{
$option_name = 'wpvivid_staging_task_list';
global $wpdb;
$result = $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->options} WHERE option_name = %s", $option_name));
if(!$result)
{
$this->log->WriteLog('Delete migration option failed.', 'notice');
}
}
if($ret['result']!='success')
{
$this->log->WriteLog('Restore database failed:'.$ret['error'],'notice');
$restore_db->remove_tmp_table($sub_task);
return $ret;
}
break;
}
}
$ret['result']='success';
$ret['has_db']=$has_db;
return $ret;
}
public function delete_temp_files()
{
$restore_task=get_option('wpvivid_restore_task',array());
$this->log=new WPvivid_Log();
$this->log->OpenLogFile( $restore_task['log'],'has_folder');
$this->log->WriteLog('Deleting temp files.','notice');
$backup_id=$restore_task['backup_id'];
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
$backup_item=new WPvivid_Backup_Item($backup);
foreach($restore_task['sub_tasks'] as $key => $task)
{
foreach ($task['unzip_file']['files'] as $file)
{
if(isset($file['has_child']))
{
$path= $backup_item->get_local_path().$file['file_name'];
//$this->log->WriteLog('clean file:'.$path,'notice');
if(file_exists($path))
{
@wp_delete_file($path);
}
}
}
}
}
public function restore_failed()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
if(!$check)
{
die();
}
register_shutdown_function(array($this,'deal_restore_finish_shutdown_error'));
//echo '<p style="font-size:1.5em;"><span>Please adjust the advanced settings before restoring and retry.</span></p>';
$this->_disable_maintenance_mode();
$this->write_litespeed_rule(false);
if(file_exists(WPMU_PLUGIN_DIR.'/a-wpvivid-restore-mu-plugin-check.php'))
{
@wp_delete_file(WPMU_PLUGIN_DIR.'/a-wpvivid-restore-mu-plugin-check.php');
}
$plugins= get_option( 'wpvivid_save_active_plugins', array() );
$this->delete_temp_tables();
$this->delete_temp_files();
$this->active_plugins($plugins);
$restore_task=get_option('wpvivid_restore_task',array());
//$restore_detail_options=$restore_task['restore_detail_options'];
//$unzip_files_pre_request=$restore_detail_options['unzip_files_pre_request'];
echo 'Restore failed. ';
if($restore_task['status']=='error')
{
echo 'Error:'.esc_html($restore_task['error']).' ';
if(isset($restore_task['error_memory_limit']))
{
echo 'Memory exhausted during restoring..';
}
else if(isset($restore_task['error_mu_require_file']))
{
echo 'Restore must-use plugin '.esc_html($restore_task['error_mu_require_file']).' error.Plugin require file not found..';
}
}
else
{
$key=$restore_task['do_sub_task'];
if($key!==false)
{
if(isset($restore_task['sub_tasks'][$key]))
{
//$error_msg='restore sub task '.$restore_task['sub_tasks'][$key]['type'].' timeout.';
if($restore_task['sub_tasks'][$key]['type']==='databases'||$restore_task['sub_tasks'][$key]['type']==='additional_databases')
{
echo 'Sql file importing time out.';
//$error_msg.='<p style="font-size:1.5em;">Pleases try to increase your max_allowed_packet(recommend 32M)</p>';
//$error_msg.='<p style="font-size:1.5em;">or reduce SQL buffer will be processed every PHP request(recommend 5M)</p>';
//$error_msg.='<p style="font-size:1.5em;">or reduce maximum rows of data in MYSQL table will be imported every time when restoring(recommend 10000)</p>';
}
else
{
echo 'File extracting time out.';
//$error_msg.='<p style="font-size:1.5em;">Pleases try to check user unzip files using index,and set files are unzipped every PHP request(recommend 1000)</p>';
//$error_msg.='<p style="font-size:1.5em;">and increase your PHP - max execution time(900s)</p>';
}
}
else
{
//$error_msg='';
echo 'Restoring time out.';
}
}
}
delete_option('wpvivid_restore_task');
wp_cache_flush();
die();
}
public function deal_restore_finish_shutdown_error()
{
$error = error_get_last();
if (!is_null($error))
{
if (empty($error) || !in_array($error['type'], array(E_ERROR,E_RECOVERABLE_ERROR,E_CORE_ERROR,E_COMPILE_ERROR), true))
{
$error = false;
}
if ($error !== false)
{
$message = 'type: '. $error['type'] . ', ' . $error['message'];
echo '<p style="font-size:1.5em;">Error Info:'.esc_html($message).'</p>';;
}
}
die();
}
public function delete_temp_tables()
{
$restore_task=get_option('wpvivid_restore_task',array());
$this->log=new WPvivid_Log();
$this->log->OpenLogFile( $restore_task['log'],'has_folder');
foreach ($restore_task['sub_tasks'] as $sub_task)
{
if($sub_task['type']=='databases')
{
$restore_db=new WPvivid_Restore_DB_2($this->log);
$restore_db->remove_tmp_table($sub_task);
}
}
$ret['result']='success';
return $ret;
}
public function check_force_ssl()
{
$plugins=array();
if ( ! is_ssl() )
{
$plugins[]='really-simple-ssl/rlrsssl-really-simple-ssl.php';
$plugins[]='wordpress-https/wordpress-https.php';
$plugins[]='wp-force-ssl/wp-force-ssl.php';
$plugins[]='force-https-littlebizzy/force-https.php';
$current = get_option( 'active_plugins', array() );
foreach ( $plugins as $plugin )
{
if ( ( $key = array_search( $plugin, $current ) ) !== false )
{
unset( $current[ $key ] );
}
}
update_option( 'active_plugins', $current );
if ( get_option( 'woocommerce_force_ssl_checkout' ) )
{
update_option( 'woocommerce_force_ssl_checkout', 'no' );
}
}
}
public function check_admin_plugins()
{
$plugins=array();
$plugins[]='wps-hide-login/wps-hide-login.php';
$plugins[]='lockdown-wp-admin/lockdown-wp-admin.php';
$plugins[]='rename-wp-login/rename-wp-login.php';
$plugins[]='change-wp-admin-login/change-wp-admin-login.php';
$plugins[]='hide-my-wp/index.php';
$plugins[]='hide-login-page/hide-login-page.php';
$plugins[]='wp-hide-security-enhancer/wp-hide.php';
//
$current = get_option( 'active_plugins', array() );
foreach ( $plugins as $plugin )
{
if ( ( $key = array_search( $plugin, $current ) ) !== false )
{
unset( $current[ $key ] );
}
}
update_option( 'active_plugins', $current );
}
public function flush_elementor_cache()
{
$wp_upload_dir=wp_upload_dir( null, false );
$path = $wp_upload_dir['basedir'] . '/elementor/css/' . '*';
foreach ( glob( $path ) as $file_path ) {
wp_delete_file( $file_path );
}
delete_post_meta_by_key( '_elementor_css' );
delete_option( '_elementor_global_css' );
delete_option( 'elementor-custom-breakpoints-files' );
delete_option( '_elementor_assets_data' );
delete_post_meta_by_key( '_elementor_inline_svg' );
}
public function regenerate_css_files()
{
delete_option( 'generateblocks_dynamic_css_posts' );
}
public function active_plugins($plugins=array())
{
wp_cache_flush();
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
$current = get_option( 'active_plugins', array() );
$plugin_list=array();
$plugin_list[]='wpvivid-backuprestore/wpvivid-backuprestore.php';
$plugin_list=apply_filters('wpvivid_enable_plugins_list',$plugin_list);
$current=array_merge($plugin_list,$current);
// Add plugins
if(!empty($plugins))
{
foreach ( $plugins as $plugin )
{
if ( ! in_array( $plugin, $current ) && ! is_wp_error( validate_plugin( $plugin ) ) ) {
$current[] = $plugin;
}
}
}
activate_plugins($current,'',false,true);
}
public function check_oxygen()
{
if (!function_exists('get_plugins'))
{
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
if ( ( $plugins = get_plugins() ) )
{
foreach ( $plugins as $key => $plugin )
{
if ( $key === 'oxygen/functions.php' )
{
return true;
}
}
}
return false;
}
public function check_divi()
{
$themes=wp_get_themes();
foreach ($themes as $key=>$theme)
{
if ( $key === 'Divi' )
{
return true;
}
}
return false;
}
public function clean_divi_cache()
{
$_post_id = '*';
$_owner = '*';
$_slug = '*';
$cache_dir= WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'et-cache';
$files = array_merge(
// Remove any CSS files missing a parent folder.
(array) glob( "{$cache_dir}/et-{$_owner}-*" ),
// Remove CSS files for individual posts or all posts if $post_id set to 'all'.
(array) glob( "{$cache_dir}/{$_post_id}/et-{$_owner}-{$_slug}*" ),
// Remove CSS files that contain theme builder template CSS.
// Multiple directories need to be searched through since * doesn't match / in the glob pattern.
(array) glob( "{$cache_dir}/*/et-{$_owner}-{$_slug}-*tb-{$_post_id}*" ),
(array) glob( "{$cache_dir}/*/*/et-{$_owner}-{$_slug}-*tb-{$_post_id}*" ),
(array) glob( "{$cache_dir}/*/*/*/et-{$_owner}-{$_slug}-*tb-{$_post_id}*" ),
(array) glob( "{$cache_dir}/*/et-{$_owner}-{$_slug}-*tb-for-{$_post_id}*" ),
(array) glob( "{$cache_dir}/*/*/et-{$_owner}-{$_slug}-*tb-for-{$_post_id}*" ),
(array) glob( "{$cache_dir}/*/*/*/et-{$_owner}-{$_slug}-*tb-for-{$_post_id}*" ),
// Remove Dynamic CSS files for categories, tags, authors, archives, homepage post feed and search results.
(array) glob( "{$cache_dir}/taxonomy/*/*/et-{$_owner}-dynamic*" ),
(array) glob( "{$cache_dir}/author/*/et-{$_owner}-dynamic*" ),
(array) glob( "{$cache_dir}/archive/et-{$_owner}-dynamic*" ),
(array) glob( "{$cache_dir}/search/et-{$_owner}-dynamic*" ),
(array) glob( "{$cache_dir}/notfound/et-{$_owner}-dynamic*" ),
(array) glob( "{$cache_dir}/home/et-{$_owner}-dynamic*" )
);
$this->_remove_files_in_directory( $files, $cache_dir );
$this->remove_empty_directories($cache_dir );
delete_option( '_et_builder_global_feature_cache' );
$post_meta_caches = array(
'et_enqueued_post_fonts',
'_et_dynamic_cached_shortcodes',
'_et_dynamic_cached_attributes',
'_et_builder_module_features_cache',
);
// Clear post meta caches.
foreach ( $post_meta_caches as $post_meta_cache ) {
if ( ! empty( $post_id ) ) {
delete_post_meta( $post_id, $post_meta_cache );
} else {
delete_post_meta_by_key( $post_meta_cache );
}
}
}
public function remove_empty_directories( $path ) {
$path = realpath( $path );
if ( empty( $path ) ) {
// $path doesn't exist
return;
}
$path = $this->normalize_path( $path );
$content_dir = $this->normalize_path( WP_CONTENT_DIR );
if ( 0 !== strpos( $path, $content_dir ) || $content_dir === $path ) {
return;
}
$this->_remove_empty_directories($path);
}
public function _remove_empty_directories($path)
{
if ( ! is_dir( $path ) ) {
return false;
}
$empty = true;
$directory_contents = glob( untrailingslashit( $path ) . '/*' );
foreach ( (array) $directory_contents as $item ) {
if ( ! $this->_remove_empty_directories( $item ) ) {
$empty = false;
}
}
return $empty ? @rmdir( $path ) : false;
}
public function _remove_files_in_directory( $files, $cache_dir )
{
$cache_dir=$this->normalize_path( $cache_dir );
foreach ( $files as $file )
{
$file =$this->normalize_path( $file );
if ( ! $this->starts_with( $file, $cache_dir ) ) {
// File is not located inside cache directory so skip it.
continue;
}
if ( is_file( $file ) )
{
@wp_delete_file($file);
}
}
}
public function starts_with( $string, $substring ) {
return 0 === strpos( $string, $substring );
}
public function normalize_path( $path = '' )
{
$path = (string) $path;
$path = str_replace( '..', '', $path );
if ( function_exists( 'wp_normalize_path' ) ) {
return wp_normalize_path( $path );
}
return str_replace( '\\', '/', $path );
}
} includes/new_backup/class-wpvivid-restore-db-method-2.php 0000644 00000045065 15132770567 0017504 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Restore_DB_WPDB_Method_2
{
public $max_allow_packet;
public $skip_query=0;
public $last_error='';
public $last_log='';
public function connect_db()
{
global $wpdb;
$wpdb->get_results('SET NAMES utf8mb4', ARRAY_A);
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
public function get_last_error()
{
return $this->last_error;
}
public function get_last_log()
{
return $this->last_log;
}
public function test_db()
{
global $wpdb;
$test_table_new=uniqid('wpvivid_test_tables_');
$columns='(test_id int primary key)';
$test_table = $wpdb->get_results("CREATE TABLE IF NOT EXISTS $test_table_new $columns",ARRAY_A);
if ($test_table!==false)
{
$this->last_log='The test to create table succeeds.';
$test_table = $wpdb->get_results("INSERT INTO $test_table_new (`test_id`) VALUES ('123')",ARRAY_A);
if($test_table!==false)
{
$this->last_log='The test to insert into table succeeds.';
$test_table = $wpdb->get_results("DROP TABLE IF EXISTS $test_table_new",ARRAY_A);
if($test_table!==false)
{
$this->last_log='The test to drop table succeeds.';
return true;
}
else
{
$this->last_error='Unable to drop table. The reason is '.$wpdb->last_error;
return false;
}
}
else
{
$this->last_error='Unable to insert into table. The reason is '.$wpdb->last_error;
return false;
}
}
else {
$this->last_error='Unable to create table. The reason is '.$wpdb->last_error;
return false;
}
}
public function check_max_allow_packet($log)
{
$restore_task=get_option('wpvivid_restore_task',array());
$restore_detail_options=$restore_task['restore_detail_options'];
$max_allowed_packet=$restore_detail_options['max_allowed_packet'];
$set_max_allowed_packet=$max_allowed_packet*1024*1024;
global $wpdb;
$max_allowed_packet =$wpdb->get_var("SELECT @@session.max_allowed_packet");
if($max_allowed_packet!==null)
{
if($max_allowed_packet<$set_max_allowed_packet)
{
$query='set global max_allowed_packet='.$set_max_allowed_packet;
$test=$wpdb->get_results($query);
var_dump($test);
$wpdb->db_connect();
$max_allowed_packet =$wpdb->get_var("SELECT @@session.max_allowed_packet");
$this->max_allow_packet=$max_allowed_packet;
}
else
{
$this->max_allow_packet=$max_allowed_packet;
}
}
else
{
$this->last_log='get max_allowed_packet failed.';
$this->max_allow_packet=1048576;
}
}
public function get_max_allow_packet()
{
return $this->max_allow_packet;
}
public function init_sql_mode()
{
global $wpdb;
$res = $wpdb->get_var('SELECT @@SESSION.sql_mode');
if($res===null)
{
$this->last_error='get sql_mode failed';
return false;
}
else
{
$sql_mod = $res;
$temp_sql_mode = str_replace('NO_ENGINE_SUBSTITUTION','',$sql_mod);
$temp_sql_mode = 'ALLOW_INVALID_DATES,NO_AUTO_VALUE_ON_ZERO,'.$temp_sql_mode;
$wpdb->get_results('SET SESSION sql_mode = "'.$temp_sql_mode.'"',ARRAY_A);
return true;
}
}
public function set_skip_query($count)
{
$this->skip_query=$count;
}
public function execute_sql($query)
{
if(preg_match('#SET TIME_ZONE=@OLD_TIME_ZONE#', $query))
{
return true;
}
if(preg_match('#SET SQL_MODE=@OLD_SQL_MODE#', $query))
{
return true;
}
if(preg_match('#SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS#', $query))
{
return true;
}
if(preg_match('#SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS#', $query))
{
return true;
}
if(preg_match('#SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT#', $query))
{
return true;
}
if(preg_match('#SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS#', $query))
{
return true;
}
if(preg_match('#SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION#', $query))
{
return true;
}
if(preg_match('#SET SQL_NOTES=@OLD_SQL_NOTES#', $query))
{
return true;
}
global $wpdb;
if ($wpdb->get_results($query)===false)
{
$this->last_error=$wpdb->last_error;
return false;
}
else
{
return true;
}
}
public function query($sql,$output)
{
global $wpdb;
return $wpdb->get_results($sql,$output);
}
public function errorInfo()
{
global $wpdb;
return $wpdb->last_error;
}
}
class WPvivid_Restore_DB_PDO_Mysql_Method_2
{
private $db;
public $max_allow_packet;
public $skip_query=0;
public $last_error='';
public $last_log='';
public function get_last_error()
{
return $this->last_error;
}
public function get_last_log()
{
return $this->last_log;
}
public function connect_db()
{
try
{
$res = explode(':',DB_HOST);
$db_host = $res[0];
$db_port = empty($res[1])?'':$res[1];
if(!empty($db_port)) {
$dsn='mysql:host=' . $db_host . ';port=' . $db_port . ';dbname=' . DB_NAME;
}
else{
$dsn='mysql:host=' . $db_host . ';dbname=' . DB_NAME;
}
$this->db = null;
$this->db=new PDO($dsn, DB_USER, DB_PASSWORD);
$this->db->exec('SET NAMES utf8mb4');
if(empty($this->db) || !$this->db)
{
if(class_exists('PDO'))
{
$extensions=get_loaded_extensions();
if(array_search('pdo_mysql',$extensions))
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The error establishing a database connection. Please check wp-config.php file and make sure the information is correct.';
}
else{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The pdo_mysql extension is not detected. Please install the extension first or choose wpdb option for Database connection method.';
}
}
else{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The pdo_mysql extension is not detected. Please install the extension first or choose wpdb option for Database connection method.';
}
}
else
{
$ret['result']=WPVIVID_SUCCESS;
}
}
catch (Exception $e)
{
if(empty($this->db) || !$this->db)
{
if(class_exists('PDO'))
{
$extensions=get_loaded_extensions();
if(array_search('pdo_mysql',$extensions))
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The error establishing a database connection. Please check wp-config.php file and make sure the information is correct.';
}
else{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The pdo_mysql extension is not detected. Please install the extension first or choose wpdb option for Database connection method.';
}
}
else{
$ret['result']=WPVIVID_FAILED;
$ret['error']='The pdo_mysql extension is not detected. Please install the extension first or choose wpdb option for Database connection method.';
}
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']=$e->getMessage();
}
}
return $ret;
}
public function test_db()
{
$test_table_new=uniqid('wpvivid_test_tables_');
$columns='(test_id int primary key)';
$test_table = $this->db->exec("CREATE TABLE IF NOT EXISTS $test_table_new $columns");
if ($test_table!==false)
{
$this->last_log='The test to create table succeeds.';
$test_table = $this->db->exec("INSERT INTO $test_table_new (`test_id`) VALUES ('123')");
if($test_table!==false)
{
$this->last_log='The test to insert into table succeeds.';
$test_table = $this->db->exec("DROP TABLE IF EXISTS $test_table_new");
if($test_table!==false)
{
$this->last_log='The test to drop table succeeds.';
return true;
}
else
{
$error=$this->db->errorInfo();
$this->last_error='Unable to drop table. The reason is '.$error[2];
return false;
}
}
else
{
$error=$this->db->errorInfo();
$this->last_error='Unable to insert into table. The reason is '.$error[2];
return false;
}
}
else {
$error=$this->db->errorInfo();
$this->last_error='Unable to create table. The reason is '.$error[2];
return false;
}
}
public function check_max_allow_packet($log)
{
$restore_task=get_option('wpvivid_restore_task',array());
$restore_detail_options=$restore_task['restore_detail_options'];
$max_allowed_packet=$restore_detail_options['max_allowed_packet'];
$set_max_allowed_packet=$max_allowed_packet*1024*1024;
try{
$max_allowed_packet = $this->db->query("SELECT @@session.max_allowed_packet;");
if($max_allowed_packet)
{
$max_allowed_packet = $max_allowed_packet -> fetchAll();
if(is_array($max_allowed_packet)&&isset($max_allowed_packet[0])&&isset($max_allowed_packet[0][0]))
{
if($max_allowed_packet[0][0]<$set_max_allowed_packet)
{
$query='set global max_allowed_packet='.$set_max_allowed_packet;
$this->db->exec($query);
$this->connect_db();
$max_allowed_packet = $this->db->query("SELECT @@session.max_allowed_packet;");
$max_allowed_packet = $max_allowed_packet -> fetchAll();
if(is_array($max_allowed_packet)&&isset($max_allowed_packet[0])&&isset($max_allowed_packet[0][0]))
{
$this->max_allow_packet=$max_allowed_packet[0][0];
}
else
{
$this->max_allow_packet=1048576;
}
}
else
{
$this->max_allow_packet=$max_allowed_packet[0][0];
}
}
else
{
$this->last_log='get max_allowed_packet failed.';
$this->max_allow_packet=1048576;
}
}
else
{
$this->last_log='get max_allowed_packet failed.';
$this->max_allow_packet=1048576;
}
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
$log->WriteLog($message, 'warning');
}
}
public function get_max_allow_packet()
{
return $this->max_allow_packet;
}
public function init_sql_mode()
{
$res = $this->db->query('SELECT @@SESSION.sql_mode') -> fetchAll();
$sql_mod = $res[0][0];
$modes = explode( ',', $sql_mod );
$modes = array_change_key_case( $modes, CASE_UPPER );
$incompatible_modes = array(
'NO_ZERO_DATE',
'ONLY_FULL_GROUP_BY',
'STRICT_TRANS_TABLES',
'STRICT_ALL_TABLES',
'TRADITIONAL',
);
$incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $incompatible_modes );
foreach ( $modes as $i => $mode ) {
if ( in_array( $mode, $incompatible_modes ) ) {
unset( $modes[ $i ] );
}
}
$sql_mod = implode( ',', $modes );
//$temp_sql_mode = str_replace('NO_ENGINE_SUBSTITUTION','',$sql_mod);
//$temp_sql_mode = 'NO_AUTO_VALUE_ON_ZERO,'.$temp_sql_mode;
$this->db->query('SET SESSION sql_mode = "'.$sql_mod.'"');
return true;
}
public function set_skip_query($count)
{
$this->skip_query=$count;
}
public function execute_sql($query)
{
if($this->skip_query>10)
{
if(strlen($query)>$this->max_allow_packet)
{
$this->last_log='skip query size:'.size_format(strlen($query));
return true;
}
}
if(preg_match('#SET TIME_ZONE=@OLD_TIME_ZONE#', $query))
{
return true;
}
if(preg_match('#SET SQL_MODE=@OLD_SQL_MODE#', $query))
{
return true;
}
if(preg_match('#SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS#', $query))
{
return true;
}
if(preg_match('#SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS#', $query))
{
return true;
}
if(preg_match('#SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT#', $query))
{
return true;
}
if(preg_match('#SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS#', $query))
{
return true;
}
if(preg_match('#SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION#', $query))
{
return true;
}
if(preg_match('#SET SQL_NOTES=@OLD_SQL_NOTES#', $query))
{
return true;
}
if ($this->db->exec($query)===false)
{
$info=$this->db->errorInfo();
if($info[1] == 2006)
{
if(strlen($query)>$this->max_allow_packet)
{
$this->skip_query++;
$this->last_error='max_allow_packet too small:'.size_format($this->max_allow_packet).' query size:'.size_format(strlen($query));
}
else
{
$this->last_error='execute sql failed. The reason is '.$info[2];
}
$ret=$this->connect_db();
if($ret['result']==WPVIVID_FAILED)
{
$this->last_log='reconnect failed';
}
else {
$this->last_log='reconnect succeed';
}
}
else
{
$this->last_error='execute sql failed. The reason is '.$info[2];
}
return false;
}
else
{
return true;
}
}
public function query($sql,$output)
{
$ret=$this->db->query($sql);
if($ret===false)
{
$error=$this->db->errorInfo();
$this->last_error=$error[1].' - '.$error[2];
return false;
}
else
{
return $ret -> fetchAll();
}
}
public function errorInfo()
{
return $this->db->errorInfo();
}
}
class WPvivid_Restore_DB_Method_2
{
private $db;
private $type;
public function __construct()
{
$restore_task=get_option('wpvivid_restore_task',array());
$restore_detail_options=$restore_task['restore_detail_options'];
$db_connect_method=$restore_detail_options['db_connect_method'];
if($db_connect_method === 'wpdb')
{
$this->db =new WPvivid_Restore_DB_WPDB_Method_2();
$this->type='wpdb';
}
else{
$this->db =new WPvivid_Restore_DB_PDO_Mysql_Method_2();
$this->type='pdo_mysql';
}
}
public function get_last_error()
{
return $this->db->last_error;
}
public function get_last_log()
{
return $this->db->last_log;
}
public function get_type()
{
return $this->type;
}
public function connect_db()
{
return $this->db->connect_db();
}
public function test_db()
{
return $this->db->test_db();
}
public function check_max_allow_packet($log)
{
$this->db->check_max_allow_packet($log);
}
public function get_max_allow_packet()
{
return $this->db->get_max_allow_packet();
}
public function init_sql_mode()
{
$this->db->init_sql_mode();
}
public function set_skip_query($count)
{
$this->db->set_skip_query($count);
}
public function execute_sql($query)
{
return $this->db->execute_sql($query);
}
public function query($sql,$output=ARRAY_A)
{
return $this->db->query($sql,$output);
}
public function errorInfo()
{
return $this->db->errorInfo();
}
} includes/new_backup/class-wpvivid-restore-db-2.php 0000644 00000422703 15132770567 0016224 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Restore_DB_2
{
public $log;
public $db_method;
public $support_engines;
public $support_charsets;
public $support_collates;
public $default_engines;
public $default_charsets;
public $default_collates;
public $old_prefix;
public $old_base_prefix;
public $new_prefix;
public $temp_new_prefix;
public $old_site_url;
public $old_home_url;
public $old_content_url;
public $old_upload_url;
public $old_mu_single_site_upload_url;
public $old_mu_single_home_upload_url;
public $new_site_url;
public $new_home_url;
public $new_content_url;
public $new_upload_url;
public $is_migrate;
public $replacing_table;
public $is_mu;
public $skip_table;
public $sum;
public $offset;
public $replace_table_character_set;
public function __construct($log=false)
{
$this->log=$log;
}
public function restore($sub_task,$backup_id)
{
add_filter('wpvivid_restore_db_skip_replace_tables', array($this, 'skip_tables'),10,2);
add_filter('wpvivid_restore_db_skip_replace_rows', array($this, 'skip_rows'),10,3);
add_filter('wpvivid_restore_db_skip_create_tables', array($this, 'skip_create_tables'),10,3);
$files=$sub_task['unzip_file']['files'];
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
$backup_item = new WPvivid_Backup_Item($backup);
$local_path=$backup_item->get_local_path();
if($sub_task['unzip_file']['unzip_finished']==0)
{
foreach ($files as $index=>$file)
{
if($file['finished']==1)
{
continue;
}
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['unzip_file']['last_unzip_file']=$file['file_name'];
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['file_name'].'</span>';
$this->update_sub_task($sub_task);
if(isset($file['has_child']))
{
if(!file_exists($local_path))
{
@mkdir($local_path);
}
$this->log->WriteLog('Extracting file:'.$file['parent_file'],'notice');
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['parent_file'].'</span>';
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['unzip_file']['last_unzip_file']=$file['parent_file'];
$this->update_sub_task($sub_task);
$extract_files[]=$file['file_name'];
$ret=$this->extract_ex($local_path.$file['parent_file'],$extract_files,untrailingslashit($local_path));
if($ret['result']!='success')
{
return $ret;
}
$this->log->WriteLog('Extracting file:'.$file['parent_file'].' finished.','notice');
$file_name=$local_path.$file['file_name'];
}
else
{
$file_name=$local_path.$file['file_name'];
}
$root_path = $this->transfer_path(WP_CONTENT_DIR . DIRECTORY_SEPARATOR . WPvivid_Setting::get_backupdir());
$root_path = rtrim($root_path, '/');
$root_path = rtrim($root_path, DIRECTORY_SEPARATOR);
$this->log->WriteLog('Extracting file:'.$file_name,'notice');
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file_name.'</span>';
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['unzip_file']['last_unzip_file']=$file['file_name'];
$this->update_sub_task($sub_task);
$ret=$this->extract($file_name,untrailingslashit($root_path));
if($ret['result']!='success')
{
return $ret;
}
$this->log->WriteLog('Extracting file:'.$file_name.' finished.','notice');
$sub_task['unzip_file']['files'][$index]['finished']=1;
}
$is_crypt = false;
if($files[0]['options']['dump_db'] == 1 && $files[0]['options']['file_type'] == 'databases')
{
$temp_sql_file=$backup_item->get_backup_path($files[0]['file_name']);
$sql_files=$this->get_sql_file($temp_sql_file);
foreach ($sql_files as $tmp_sql_file)
{
$sql_file_name = $tmp_sql_file['file_name'];
if(preg_match('/.*\.crypt$/', $sql_file_name))
{
$is_crypt = true;
break;
}
}
}
if(isset($files[0]['options']['is_crypt'])&&$files[0]['options']['is_crypt']=='1' || $is_crypt === true)
{
$ret['result']='failed';
$ret['error']='The free version of WPvivid Backup Plugin does not support restoration of encrypted database backups. You can consider upgrading to the pro version as needed.';
return $ret;
}
else
{
foreach ($files as $file)
{
$sql_file_path=$backup_item->get_backup_path($file['file_name']);
$sql_files=$this->get_sql_file($sql_file_path);
foreach ($sql_files as $tmp_sql_file)
{
$sql_file['sql_file_name']=$tmp_sql_file['file_name'];
$sql_file['sql_file_size']=filesize($local_path.$tmp_sql_file['file_name']);
$sql_file['sql_offset']=0;
$sql_file['finished']=0;
$sub_task['exec_sql']['sql_files'][$sql_file['sql_file_name']]= $sql_file;
}
}
}
$sub_task['unzip_file']['unzip_finished']=1;
$ret['result']='success';
$ret['sub_task']=$sub_task;
$this->update_sub_task($sub_task);
return $ret;
}
if(!empty($sub_task['exec_sql']['sql_files']))
{
$sql_files=$sub_task['exec_sql']['sql_files'];
}
else
{
foreach ($files as $file)
{
$sql_file_path=$backup_item->get_backup_path($file['file_name']);
$sql_files=$this->get_sql_file($sql_file_path);
foreach ($sql_files as $tmp_sql_file)
{
$sql_file['sql_file_name']=$tmp_sql_file['file_name'];
$sql_file['sql_file_size']=filesize($local_path.$tmp_sql_file['file_name']);
$sql_file['sql_offset']=0;
$sql_file['finished']=0;
$sub_task['exec_sql']['sql_files'][$sql_file['sql_file_name']]= $sql_file;
}
}
$this->update_sub_task($sub_task);
$sql_files=$sub_task['exec_sql']['sql_files'];
}
if(empty($sql_files))
{
$ret['result']='failed';
$ret['error']='Sql file not found.';
return $ret;
}
ksort($sql_files);
$ret=$this->restore_db($sql_files,$local_path,$sub_task);
return $ret;
}
public function get_sql_file($path)
{
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
$zip=new WPvivid_ZipClass();
return $zip->list_file($path);
}
public function update_sub_task($sub_task=false)
{
$restore_task=get_option('wpvivid_restore_task',array());
if($restore_task['do_sub_task']!==false)
{
$key=$restore_task['do_sub_task'];
$restore_task['update_time']=time();
if($sub_task!==false)
$restore_task['sub_tasks'][$key]=$sub_task;
update_option('wpvivid_restore_task',$restore_task,'no');
}
}
public function extract($file_name,$root_path)
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
if(!defined('PCLZIP_TEMPORARY_DIR'))
define(PCLZIP_TEMPORARY_DIR,dirname($root_path));
$archive = new WPvivid_PclZip($file_name);
$zip_ret = $archive->extract(WPVIVID_PCLZIP_OPT_PATH, $root_path,WPVIVID_PCLZIP_OPT_REPLACE_NEWER,WPVIVID_PCLZIP_CB_PRE_EXTRACT,'wpvivid_function_pre_extract_callback',WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,16);
if(!$zip_ret)
{
$ret['result']='failed';
$ret['error'] = $archive->errorInfo(true);
$this->log->WriteLog('Extracting failed. Error:'.$archive->errorInfo(true),'notice');
}
else
{
$ret['result']='success';
}
return $ret;
}
public function extract_ex($file_name,$extract_files,$root_path)
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
if(!class_exists('WPvivid_ZipClass'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-zipclass.php';
if(!defined('PCLZIP_TEMPORARY_DIR'))
define(PCLZIP_TEMPORARY_DIR,dirname($root_path));
$archive = new WPvivid_PclZip($file_name);
$zip_ret = $archive->extract(WPVIVID_PCLZIP_OPT_BY_NAME,$extract_files,WPVIVID_PCLZIP_OPT_PATH, $root_path,WPVIVID_PCLZIP_OPT_REPLACE_NEWER,WPVIVID_PCLZIP_CB_PRE_EXTRACT,'wpvivid_function_pre_extract_callback',WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,16);
if(!$zip_ret)
{
$ret['result']='failed';
$ret['error'] = $archive->errorInfo(true);
$this->log->WriteLog('Extracting failed. Error:'.$archive->errorInfo(true),'notice');
}
else
{
$ret['result']='success';
}
return $ret;
}
private function transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode(DIRECTORY_SEPARATOR,$values);
}
public function restore_db($sql_files,$local_path,$sub_task)
{
$ret['result']='success';
$ret['sub_task']=$sub_task;
foreach ($sql_files as $sql_file_name=>$sql_file)
{
if($sql_file['finished']==1)
{
continue;
}
$this->log->WriteLog('Start restoring sql file offset:'.$sql_file['sql_offset'],'notice');
$sub_task['exec_sql']['last_action']='Importing';
$this->sum=filesize($local_path.$sql_file_name);
$this->offset=($sql_file['sql_offset']);
$ret=$this->exec_sql($sql_file_name,$local_path,$sub_task);
if($ret['result']=='success')
{
$sub_task=$ret['sub_task'];
break;
}
else
{
$this->log->WriteLog('Restoring sql failed:'.$ret['error'],'notice');
$this->remove_tmp_table($sub_task);
return $ret;
}
}
$exec_sql_finished=true;
foreach ($sub_task['exec_sql']['sql_files'] as $sql_file_name=>$sql_file)
{
if($sql_file['finished']==0)
{
$exec_sql_finished=false;
break;
}
}
$sub_task['exec_sql']['exec_sql_finished']=$exec_sql_finished;
if($sub_task['exec_sql']['exec_sql_finished']==1)
{
$ret=$this->replace_tables_rows($sub_task);
if($ret['result']=='success')
{
$sub_task=$ret['sub_task'];
}
else
{
$this->log->WriteLog('Restoring failed:'.$ret['error'],'notice');
$this->remove_tmp_table($sub_task);
return $ret;
}
}
if($sub_task['exec_sql']['replace_rows_finished']==1)
{
$ret=$this->finish_restore_db($sql_files,$local_path,$sub_task);
if($ret['result']!='success')
{
return $ret;
}
$this->log->WriteLog('Restore db success','notice');
}
return $ret;
}
public function str_replace_first($from, $to, $content)
{
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
public function remove_tmp_table($sub_task)
{
global $wpdb;
$temp_new_prefix='tmp'.$sub_task['exec_sql']['db_id'].'_';
$tables = $wpdb->get_col($wpdb->prepare('SHOW TABLES LIKE %s', array($temp_new_prefix . '%')));
foreach ($tables as $table)
{
$wpdb->query('DROP TABLE IF EXISTS `' . $table.'`');
}
$ret['result']='success';
return $ret;
}
public function exec_sql($sql_file_name,$local_path,$sub_task)
{
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-restore-db-method-2.php';
$this->db_method=new WPvivid_Restore_DB_Method_2();
$this->db_method->set_skip_query(0);
$this->skip_table=false;
$sql_file=$local_path.$sql_file_name;
if(!file_exists($sql_file))
{
return array('result'=>'failed','error'=>'Database\'s .sql file not found. Please switch the database access method from WPDB to PDO in the plugin\'s Advanced Settings and try it again.');
}
$ret=$this->db_method->connect_db();
if($ret['result']=='failed')
{
return $ret;
}
if($this->db_method->test_db()===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
$ret['result']='failed';
$ret['error']=$this->db_method->get_last_error();
return $ret;
}
$this->db_method->check_max_allow_packet($this->log);
$this->log->WriteLog($this->db_method->get_last_log(),'notice');
$this->db_method->init_sql_mode();
global $wpdb;
$wpdb->query('SET FOREIGN_KEY_CHECKS=0;');
$this->is_mu=false;
if(isset($sub_task['options']['is_mu']))
{
$this->is_mu=true;
}
else
{
$this->is_mu=false;
}
if($sub_task['exec_sql']['init_sql_finished']!=1)
{
$ret=$this->init_restore_db($sql_file,$sub_task);
$sub_task=$ret['sub_task'];
$sub_task['exec_sql']['init_sql_finished']=1;
$this->update_sub_task($sub_task);
}
else
{
$this->default_engines= $sub_task['db_info']['default_engine'];
$this->default_charsets=$sub_task['db_info']['default_charsets'];
$this->default_collates=$sub_task['db_info']['default_collates'];
$this->old_base_prefix=$sub_task['db_info']['base_prefix'];
$this->new_prefix=$sub_task['db_info']['new_prefix'];
$this->temp_new_prefix=$sub_task['db_info']['temp_new_prefix'];
$this->new_site_url= $sub_task['db_info']['new_site_url'];
$this->new_home_url=$sub_task['db_info']['new_home_url'];
$this->new_content_url=$sub_task['db_info']['new_content_url'];
$this->new_upload_url=$sub_task['db_info']['new_upload_url'];
$this->is_migrate=$sub_task['db_info']['is_migrate'];
$this->old_site_url = $sub_task['db_info']['old_site_url'];
$this->old_home_url =$sub_task['db_info']['old_home_url'];
$this->old_content_url =$sub_task['db_info']['old_content_url'];
$this->old_upload_url = $sub_task['db_info']['old_upload_url'];
$this->old_prefix =$sub_task['db_info']['old_prefix'];
if(isset($sub_task['db_info']['old_mu_single_site_upload_url']))
{
$this->old_mu_single_site_upload_url=$sub_task['db_info']['old_mu_single_site_upload_url'];
}
else
{
$this->old_mu_single_site_upload_url='';
}
if(isset($sub_task['db_info']['old_mu_single_home_upload_url']))
{
$this->old_mu_single_home_upload_url=$sub_task['db_info']['old_mu_single_home_upload_url'];
}
else
{
$this->old_mu_single_home_upload_url='';
}
$result = $wpdb->get_results("SHOW ENGINES", OBJECT_K);
foreach ($result as $key=>$value)
{
$this->support_engines[]=$key;
}
$result = $wpdb->get_results("SHOW CHARACTER SET", OBJECT_K);
foreach ($result as $key=>$value)
{
$this->support_charsets[]=$key;
}
$result = $wpdb->get_results("SHOW COLLATION", OBJECT_K);
foreach ($result as $key=>$value)
{
$this->support_collates[$key]=$value;
}
}
$sql_handle = fopen($sql_file,'r');
if($sql_handle===false)
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='file not found. file name:'.$sql_file;
return $ret;
}
fseek($sql_handle,$sub_task['exec_sql']['sql_files'][$sql_file_name]['sql_offset']);
$line_num = 0;
$query='';
$restore_task=get_option('wpvivid_restore_task',array());
$restore_detail_options=$restore_task['restore_detail_options'];
$sql_file_buffer_pre_request=$restore_detail_options['sql_file_buffer_pre_request'];
$max_buffer_size=$sql_file_buffer_pre_request*1024*1024;
$this->replace_table_character_set=isset($restore_detail_options['replace_table_character_set'])?$restore_detail_options['replace_table_character_set']:false;
$current_offset=$sub_task['exec_sql']['sql_files'][$sql_file_name]['sql_offset'];
if(!empty($sub_task['exec_sql']['current_table']))
{
if(apply_filters('wpvivid_restore_db_skip_create_tables',false,$sub_task['exec_sql']['current_table'],$sub_task['options']))
{
$this->log->WriteLog('Skipping table '.$sub_task['exec_sql']['current_table'],'notice');
$this->skip_table=$sub_task['exec_sql']['current_table'];
}
/*if($sub_task['exec_sql']['current_need_replace_table'])
{
$this->execute_sql('START TRANSACTION',$sub_task);
$ret_replace_row=$this->do_replace_row($sql_file_name,$sub_task);
$sub_task=$ret_replace_row['sub_task'];
if(!$ret_replace_row['finished'])
{
$this->execute_sql('COMMIT',$sub_task);
$sub_task['exec_sql']['sql_files'][$sql_file_name]['finished']=0;
$ret['result']='success';
$ret['sub_task']=$ret_replace_row['sub_task'];
//sub_task
$this->update_sub_task($sub_task);
return $ret;
}
}*/
$sub_task['last_msg']='Importing sql file:'.$sql_file_name.' table: '.$sub_task['exec_sql']['current_table'].' '.size_format($this->offset,2).'/'.size_format($this->sum,2);
$this->update_sub_task($sub_task);
}
else
{
$sub_task['last_msg']='Importing sql file:'.$sql_file_name.size_format($this->offset,2).'/'.size_format($this->sum,2);
$this->update_sub_task($sub_task);
}
$this->execute_sql('START TRANSACTION',$sub_task);
$progress_offset=$current_offset;
while(!feof($sql_handle))
{
if(empty($query))
{
$sub_task['exec_sql']['sql_files'][$sql_file_name]['sql_offset']=ftell($sql_handle);
$sub_task['exec_sql']['last_action']='Importing';
if(!empty($sub_task['exec_sql']['current_table']))
{
$sub_task['last_msg']='Importing sql file:'.$sql_file_name.' table: '.$sub_task['exec_sql']['current_table'].' '.size_format($sub_task['exec_sql']['sql_files'][$sql_file_name]['sql_offset'],2).'/'.size_format($this->sum,2);
}
else
{
$sub_task['last_msg']='Importing sql file:'.$sql_file_name.size_format($sub_task['exec_sql']['sql_files'][$sql_file_name]['sql_offset'],2).'/'.size_format($this->sum,2);
}
$read_offset=$sub_task['exec_sql']['sql_files'][$sql_file_name]['sql_offset']-$current_offset;
if($read_offset>$max_buffer_size)
{
fclose($sql_handle);
$this->execute_sql('COMMIT',$sub_task);
$this->log->WriteLog('Reading sql file completed offset:'.$sub_task['exec_sql']['sql_files'][$sql_file_name]['sql_offset'],'notice');
$sub_task['exec_sql']['sql_files'][$sql_file_name]['finished']=0;
$ret['result']='success';
$ret['sub_task']=$sub_task;
return $ret;
}
else
{
if($sub_task['exec_sql']['sql_files'][$sql_file_name]['sql_offset']-$progress_offset>1024*100)
{
$progress_offset=$sub_task['exec_sql']['sql_files'][$sql_file_name]['sql_offset'];
$this->update_sub_task($sub_task);
}
}
}
$line = fgets($sql_handle);
$line_num ++;
$startWith = substr(trim($line), 0 ,2);
$startWithEx = substr(trim($line), 0 ,3);
$endWith = substr(trim($line), -1 ,1);
$line = rtrim($line);
if (empty($line) || $startWith == '--' || ($startWith == '/*'&&$startWithEx!='/*!') || $startWith == '//')
{
continue;
}
$query = $query . $line;
if ($endWith == ';')
{
if (preg_match('#^\\s*CREATE TABLE#', $query))
{
/*if (preg_match('/TYPE=/', $query))
{
$query = str_replace('TYPE=', 'ENGINE=', $query);
}*/
$this->skip_table=false;
$sub_task['exec_sql']['current_table']=$this->create_table($query,$sub_task['exec_sql']['current_old_table'],$sub_task);
if(apply_filters('wpvivid_restore_db_skip_create_tables',false,$sub_task['exec_sql']['current_table'],$sub_task['options']))
{
$this->log->WriteLog('Skipping table '.$sub_task['exec_sql']['current_table'],'notice');
$this->skip_table=$sub_task['exec_sql']['current_table'];
}
else
{
$this->log->WriteLog('Creating table '.$sub_task['exec_sql']['current_table'],'notice');
}
//$sub_task['exec_sql']['current_replace_table_finish']=false;
//$sub_task['exec_sql']['current_need_replace_table']=false;
$sub_task['exec_sql']['current_replace_row']=0;
$this->update_sub_task($sub_task);
}
else if(preg_match('#^\\s*LOCK TABLES#',$query))
{
//$this->lock_table($query);
}
else if(preg_match('#^\\s*INSERT INTO#', $query))
{
if($this->skip_table!==false&&$this->skip_table==$sub_task['exec_sql']['current_table'])
{
$query = '';
continue;
}
$this->insert($query,$sub_task);
}
else if(preg_match('#^\\s*DROP TABLE #', $query))
{
if($this->skip_table!==false&&$this->skip_table==$sub_task['exec_sql']['current_table'])
{
}
else
{
if($this->is_migrate&&!empty($sub_task['exec_sql']['current_table']))
{
$replace_tables['current_table']=$sub_task['exec_sql']['current_table'];
$replace_tables['current_old_table']=$sub_task['exec_sql']['current_old_table'];
$replace_tables['finished']=0;
$replace_tables['offset']=0;
$sub_task['exec_sql']['replace_tables'][$sub_task['exec_sql']['current_table']]=$replace_tables;
$this->update_sub_task($sub_task);
/*if($this->is_og_table($sub_task['exec_sql']['current_old_table']))
{
$sub_task['exec_sql']['current_need_replace_table']=true;
$ret_replace_row=$this->do_replace_row($sql_file_name,$sub_task);
$sub_task=$ret_replace_row['sub_task'];
if(!$ret_replace_row['finished'])
{
$this->execute_sql('COMMIT',$sub_task);
$sub_task['exec_sql']['sql_files'][$sql_file_name]['finished']=0;
$ret['result']='success';
$ret['sub_task']=$sub_task;
$this->update_sub_task($sub_task);
return $ret;
}
}*/
}
}
$this->drop_table($query,$sub_task);
}
else if(preg_match('#\/*!#', $query))
{
if($this->skip_table!==false&&$this->skip_table==$sub_task['exec_sql']['current_table'])
{
$query = '';
continue;
}
if ($this->replace_table_execute_sql($query,$sub_task['exec_sql']['current_old_table'],$sub_task)===false)
{
$query = '';
continue;
}
}
else
{
if($this->skip_table!==false&&$this->skip_table==$sub_task['exec_sql']['current_table'])
{
$query = '';
continue;
}
if ( $this->execute_sql($query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
$query = '';
continue;
}
}
$query = '';
}
}
$this->execute_sql('COMMIT',$sub_task);
$sub_task['exec_sql']['sql_files'][$sql_file_name]['sql_offset']=ftell($sql_handle);
$sub_task['exec_sql']['sql_files'][$sql_file_name]['finished']=1;
$replace_tables['current_table']=$sub_task['exec_sql']['current_table'];
$replace_tables['current_old_table']=$sub_task['exec_sql']['current_old_table'];
$replace_tables['finished']=0;
$replace_tables['offset']=0;
$sub_task['exec_sql']['replace_tables'][$sub_task['exec_sql']['current_table']]=$replace_tables;
$this->update_sub_task($sub_task);
/*if($this->skip_table!==false&&$this->skip_table==$sub_task['exec_sql']['current_table'])
{
$sub_task['exec_sql']['sql_files'][$sql_file_name]['finished']=1;
$sub_task['exec_sql']['current_replace_table_finish']=false;
}
else
{
$ret_replace_row=$this->do_replace_row($sql_file_name,$sub_task);
$sub_task=$ret_replace_row['sub_task'];
if($ret_replace_row['finished'])
{
$sub_task['exec_sql']['sql_files'][$sql_file_name]['finished']=1;
$sub_task['exec_sql']['current_replace_table_finish']=false;
}
else
{
$sub_task['exec_sql']['sql_files'][$sql_file_name]['finished']=0;
}
}*/
fclose($sql_handle);
$sub_task['exec_sql']['last_action']='Importing';
$this->update_sub_task($sub_task);
$ret['result']='success';
$ret['sub_task']=$sub_task;
return $ret;
}
private function init_db($sub_task)
{
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-restore-db-method-2.php';
$this->db_method=new WPvivid_Restore_DB_Method_2();
$this->db_method->set_skip_query(0);
$this->skip_table=false;
$ret=$this->db_method->connect_db();
if($ret['result']=='failed')
{
return $ret;
}
$this->db_method->check_max_allow_packet($this->log);
$this->log->WriteLog($this->db_method->get_last_log(),'notice');
$this->db_method->init_sql_mode();
$this->default_engines= $sub_task['db_info']['default_engine'];
$this->default_charsets=$sub_task['db_info']['default_charsets'];
$this->default_collates=$sub_task['db_info']['default_collates'];
$this->old_base_prefix=$sub_task['db_info']['base_prefix'];
$this->new_prefix=$sub_task['db_info']['new_prefix'];
$this->temp_new_prefix=$sub_task['db_info']['temp_new_prefix'];
$this->new_site_url= $sub_task['db_info']['new_site_url'];
$this->new_home_url=$sub_task['db_info']['new_home_url'];
$this->new_content_url=$sub_task['db_info']['new_content_url'];
$this->new_upload_url=$sub_task['db_info']['new_upload_url'];
$this->is_migrate=$sub_task['db_info']['is_migrate'];
$this->old_site_url = $sub_task['db_info']['old_site_url'];
$this->old_home_url =$sub_task['db_info']['old_home_url'];
$this->old_content_url =$sub_task['db_info']['old_content_url'];
$this->old_upload_url = $sub_task['db_info']['old_upload_url'];
$this->old_prefix =$sub_task['db_info']['old_prefix'];
if(isset($sub_task['db_info']['old_mu_single_site_upload_url']))
{
$this->old_mu_single_site_upload_url=$sub_task['db_info']['old_mu_single_site_upload_url'];
}
else
{
$this->old_mu_single_site_upload_url='';
}
if(isset($sub_task['db_info']['old_mu_single_home_upload_url']))
{
$this->old_mu_single_home_upload_url=$sub_task['db_info']['old_mu_single_home_upload_url'];
}
else
{
$this->old_mu_single_home_upload_url='';
}
$ret['result']='success';
return $ret;
}
public function do_replace_row($sql_file_name,$sub_task)
{
if($this->is_migrate&&!empty($sub_task['exec_sql']['current_table']))
{
if($this->is_og_table($sub_task['exec_sql']['current_old_table']))
{
if($sub_task['exec_sql']['current_replace_table_finish'])
{
$ret['finished']=1;
}
else
{
$sub_task['exec_sql']['last_action']='Importing';
$this->update_sub_task($sub_task);
$restore_task=get_option('wpvivid_restore_task',array());
$restore_detail_options=$restore_task['restore_detail_options'];
$replace_rows_pre_request=$restore_detail_options['replace_rows_pre_request'];
$ret=$this->replace_row($sql_file_name,$sub_task,$replace_rows_pre_request);
$sub_task['exec_sql']['current_replace_row']=$ret['replace_row'];
$sub_task['exec_sql']['current_replace_table_finish']=$ret['current_replace_table_finish'];
if($ret['current_replace_table_finish']==false)
{
$ret['finished']=0;
}
else
{
$ret['finished']=1;
}
}
}
else
{
$ret['finished']=1;
}
}
else
{
$ret['finished']=1;
}
$ret['result']='success';
$ret['sub_task']=$sub_task;
return $ret;
}
public function do_replace_row_ex($table_name,$replace_table_data,$sub_task)
{
$this->init_db($sub_task);
if($this->is_migrate&&!empty($replace_table_data['current_table']))
{
$tmp_option=$sub_task['options'];
if($this->is_mu&&isset($tmp_option['site_id']))
{
if($this->is_mu_single_og_table($replace_table_data['current_old_table']))
{
$sub_task['exec_sql']['last_action']='Importing';
$this->update_sub_task($sub_task);
$restore_task=get_option('wpvivid_restore_task',array());
$restore_detail_options=$restore_task['restore_detail_options'];
$replace_rows_pre_request=$restore_detail_options['replace_rows_pre_request'];
$this->execute_sql('START TRANSACTION',$sub_task);
$ret=$this->replace_row_ex($table_name,$replace_table_data,$sub_task,$replace_rows_pre_request);
$this->execute_sql('COMMIT',$sub_task);
$sub_task['exec_sql']['replace_tables'][$table_name]['offset']=$ret['replace_row'];
$sub_task['exec_sql']['replace_tables'][$table_name]['finished']=$ret['current_replace_table_finish'];
if($ret['current_replace_table_finish']==false)
{
$ret['finished']=0;
}
else
{
$ret['finished']=1;
}
}
}
else if($this->is_og_table($replace_table_data['current_old_table']))
{
$sub_task['exec_sql']['last_action']='Importing';
$this->update_sub_task($sub_task);
$restore_task=get_option('wpvivid_restore_task',array());
$restore_detail_options=$restore_task['restore_detail_options'];
$replace_rows_pre_request=$restore_detail_options['replace_rows_pre_request'];
$this->execute_sql('START TRANSACTION',$sub_task);
$ret=$this->replace_row_ex($table_name,$replace_table_data,$sub_task,$replace_rows_pre_request);
$this->execute_sql('COMMIT',$sub_task);
$sub_task['exec_sql']['replace_tables'][$table_name]['offset']=$ret['replace_row'];
$sub_task['exec_sql']['replace_tables'][$table_name]['finished']=$ret['current_replace_table_finish'];
$sub_task['last_msg']=$ret['last_msg'];
if($ret['current_replace_table_finish']==false)
{
$ret['finished']=0;
}
else
{
$ret['finished']=1;
}
}
else
{
$sub_task['exec_sql']['replace_tables'][$table_name]['finished']=1;
$ret['finished']=1;
}
}
else
{
$sub_task['exec_sql']['replace_tables'][$table_name]['finished']=1;
$ret['finished']=1;
}
$ret['result']='success';
$ret['sub_task']=$sub_task;
return $ret;
}
public function replace_tables_rows($sub_task)
{
$this->is_mu=false;
if(isset($sub_task['options']['is_mu']))
{
$this->is_mu=true;
}
else
{
$this->is_mu=false;
}
if(empty($sub_task['exec_sql']['replace_tables']))
{
$sub_task['exec_sql']['replace_rows_finished']=1;
$this->update_sub_task($sub_task);
$ret['result']='success';
$ret['sub_task']=$sub_task;
return $ret;
}
else
{
foreach ($sub_task['exec_sql']['replace_tables'] as $table_name=>$replace_table_data)
{
if($replace_table_data['finished']==1)
{
continue;
}
$this->log->WriteLog('Start replacing table '.$table_name.' offset:'.$replace_table_data['offset'],'notice');
$sub_task['exec_sql']['last_action']='Importing';
$ret=$this->do_replace_row_ex($table_name,$replace_table_data,$sub_task);
if($ret['result']=='success')
{
$sub_task=$ret['sub_task'];
break;
}
else
{
$this->log->WriteLog('Restoring failed:'.$ret['error'],'notice');
$this->remove_tmp_table($sub_task);
return $ret;
}
}
$replace_rows_finished=true;
foreach ($sub_task['exec_sql']['replace_tables'] as $table_name=>$replace_table_data)
{
if($replace_table_data['finished']==0)
{
$replace_rows_finished=false;
break;
}
}
$sub_task['exec_sql']['replace_rows_finished']=$replace_rows_finished;
$this->update_sub_task($sub_task);
$ret['result']='success';
$ret['sub_task']=$sub_task;
return $ret;
}
}
public function init_restore_db($sql_file,$sub_task)
{
global $wpdb;
$option=$sub_task['options'];
$this->support_engines=array();
$this->support_charsets=array();
$this->support_collates=array();
$this->default_engines=array();
$this->default_charsets=array();
$this->default_collates=array();
if(isset($option['default_engine']))
{
$sub_task['db_info']['default_engine']=$this->default_engines=$option['default_engine'];
}
else
{
$sub_task['db_info']['default_engine'][]=$this->default_engines[]='MyISAM';
}
if(isset($option['default_charsets']))
{
$sub_task['db_info']['default_charsets']=$this->default_charsets=$option['default_charsets'];
}
else
{
$sub_task['db_info']['default_charsets'][]=$this->default_charsets[]=DB_CHARSET;
}
if(isset($option['default_collations']))
{
$sub_task['db_info']['default_collates']=$this->default_collates=$option['default_collations'];
}
else
{
$sub_task['db_info']['default_collates'][]=$this->default_collates[]=DB_COLLATE;
}
if($this->is_mu&&isset($option['site_id']))
{
$sub_task['db_info']['base_prefix']=$this->old_base_prefix=$option['base_prefix'];
$sub_task['db_info']['old_prefix']=$this->old_prefix=$option['blog_prefix'];
$sub_task['db_info']['site_url']=$this->old_site_url=$option['site_url'];
$sub_task['db_info']['home_url']=$this->old_home_url=$option['home_url'];
$this->old_content_url='';
$this->old_upload_url='';
$sub_task['db_info']['old_mu_single_site_upload_url']=$this->old_mu_single_site_upload_url=trailingslashit($option['site_url']).'wp-content/uploads/sites/'.$option['site_id'];
$sub_task['db_info']['old_mu_single_home_upload_url']=$this->old_mu_single_home_upload_url=trailingslashit($option['home_url']).'wp-content/uploads/sites/'.$option['site_id'];
if($option['overwrite'])
{
$sub_task['db_info']['new_prefix']=$this->new_prefix=$wpdb->get_blog_prefix($option['overwrite_site']);
$sub_task['db_info']['new_site_url']=$this->new_site_url= untrailingslashit(get_site_url($option['overwrite_site']));
$sub_task['db_info']['new_home_url']=$this->new_home_url=untrailingslashit(get_home_url($option['overwrite_site']));
$sub_task['db_info']['new_content_url']=$this->new_content_url=untrailingslashit(content_url());
$upload_dir = wp_upload_dir();
$sub_task['db_info']['new_upload_url']=$this->new_upload_url=untrailingslashit($upload_dir['baseurl']);
}
else
{
$sub_task['db_info']['new_prefix']=$this->new_prefix=$wpdb->get_blog_prefix($option['site_id']);
$sub_task['db_info']['new_site_url']=$this->new_site_url= untrailingslashit(get_site_url($option['site_id']));
$sub_task['db_info']['new_home_url']=$this->new_home_url=untrailingslashit(get_home_url($option['site_id']));
$sub_task['db_info']['new_content_url']=$this->new_content_url=untrailingslashit(content_url());
$upload_dir = wp_upload_dir();
$sub_task['db_info']['new_upload_url']=$this->new_upload_url=untrailingslashit($upload_dir['baseurl']);
}
$sub_task['db_info']['temp_new_prefix']=$this->temp_new_prefix='tmp'.$sub_task['exec_sql']['db_id'].'_';
}
else
{
$this->old_prefix='';
$this->old_base_prefix='';
$this->old_mu_single_site_upload_url='';
$this->old_mu_single_home_upload_url='';
if(isset($option['mu_migrate']))
{
$sub_task['db_info']['base_prefix']=$this->old_base_prefix=$option['base_prefix'];
}
else
{
$sub_task['db_info']['base_prefix']=$this->old_base_prefix;
}
$sub_task['db_info']['new_prefix']=$this->new_prefix=$wpdb->base_prefix;
$sub_task['db_info']['temp_new_prefix']=$this->temp_new_prefix='tmp'.$sub_task['exec_sql']['db_id'].'_';
$sub_task['db_info']['new_site_url']= $this->new_site_url= untrailingslashit(site_url());
$sub_task['db_info']['new_home_url']=$this->new_home_url=untrailingslashit(home_url());
$sub_task['db_info']['new_content_url']=$this->new_content_url=untrailingslashit(content_url());
$upload_dir = wp_upload_dir();
$sub_task['db_info']['new_upload_url']=$this->new_upload_url=untrailingslashit($upload_dir['baseurl']);
}
$wpdb->query('SET FOREIGN_KEY_CHECKS=0;');
$result = $wpdb->get_results("SHOW ENGINES", OBJECT_K);
foreach ($result as $key=>$value)
{
$this->support_engines[]=$key;
}
$result = $wpdb->get_results("SHOW CHARACTER SET", OBJECT_K);
foreach ($result as $key=>$value)
{
$this->support_charsets[]=$key;
}
$result = $wpdb->get_results("SHOW COLLATION", OBJECT_K);
foreach ($result as $key=>$value)
{
$this->support_collates[$key]=$value;
}
$sql_handle = fopen($sql_file,'r');
if($sql_handle===false)
{
$ret['result']=WPVIVID_FAILED;
$ret['error']='file not found. file name:'.$sql_file;
return $ret;
}
$this->old_site_url='';
$this->old_home_url='';
$this->old_content_url='';
$this->old_upload_url='';
$line_num = 0;
while(!feof($sql_handle))
{
if($line_num>50)
break;
$line = fgets($sql_handle);
$line_num ++;
$startWith = substr(trim($line), 0 ,2);
$startWithEx = substr(trim($line), 0 ,3);
$endWith = substr(trim($line), -1 ,1);
$line = rtrim($line);
if (empty($line) || $startWith == '--' || ($startWith == '/*'&&$startWithEx!='/*!') || $startWith == '//')
{
if ($endWith == ';' && preg_match('- # -',$line))
{
$matcher = array();
if(empty($this -> site_url) && preg_match('# site_url: (.*?) #',$line,$matcher))
{
if(empty( $this->old_site_url))
{
$sub_task['db_info']['old_site_url']=$this->old_site_url = $matcher[1];
}
}
if(empty($this -> home_url) && preg_match('# home_url: (.*?) #',$line,$matcher))
{
if(empty( $this->old_home_url))
{
$sub_task['db_info']['old_home_url']=$this->old_home_url = $matcher[1];
}
}
if(empty($this -> content_url) && preg_match('# content_url: (.*?) #',$line,$matcher))
{
if(empty( $this->old_content_url))
{
$sub_task['db_info']['old_content_url']= $this->old_content_url = $matcher[1];
}
}
if(empty($this -> upload_url) && preg_match('# upload_url: (.*?) #',$line,$matcher))
{
if(empty( $this->old_upload_url))
{
$sub_task['db_info']['old_upload_url']=$this->old_upload_url = $matcher[1];
}
}
if(empty($this -> table_prefix) && preg_match('# table_prefix: (.*?) #',$line,$matcher))
{
if(empty( $this->old_prefix))
{
$sub_task['db_info']['old_prefix']= $this->old_prefix = $matcher[1];
}
}
}
continue;
}
}
if($this->old_prefix!=$this->new_prefix||(!empty($this->old_site_url)&&$this->old_site_url!=$this->new_site_url))
{
$sub_task['db_info']['is_migrate']=$this->is_migrate=true;
}
else
{
$sub_task['db_info']['is_migrate']=false;
}
fclose($sql_handle);
$ret['result']='success';
$ret['sub_task']=$sub_task;
return $ret;
}
private function create_table($query,&$current_old_table,$sub_task)
{
$table_name='';
if (preg_match('/^\s*CREATE TABLE +\`?([^\`]*)\`?/i', $query, $matches))
{
$table_name = $matches[1];
$current_old_table=$table_name;
}
$tmp_option=$sub_task['options'];
if($this->is_mu&&isset($tmp_option['site_id']))
{
if($this->is_mu_single_og_table($table_name))
{
if(substr($table_name,strlen($this->old_base_prefix))=='users'||substr($table_name,strlen($this->old_base_prefix))=='usermeta')
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_base_prefix));
}
else
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_prefix));
}
}
else
{
$new_table_name=$current_old_table;
}
}
else if($this->is_og_table($table_name))
{
if(!empty($this->old_base_prefix)&&(substr($table_name,strlen($this->old_base_prefix))=='users'||substr($table_name,strlen($this->old_base_prefix))=='usermeta'))
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_base_prefix));
}
else
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_prefix));
}
}
else
{
$new_table_name=$current_old_table;
}
if($this->old_prefix !== '')
{
$query=str_replace($table_name,$new_table_name,$query);
}
else
{
$query=preg_replace('/'.$table_name.'/',$new_table_name,$query, 1);
}
$table_name=$new_table_name;
if(apply_filters('wpvivid_restore_db_skip_create_tables',false,$table_name,$sub_task['options']))
{
return $table_name;
}
if($this->replace_table_character_set)
{
if (preg_match('/ENGINE=([^\s;]+)/', $query, $matches))
{
$engine = $matches[1];
$replace_engine=true;
foreach ($this->support_engines as $support_engine)
{
if(strtolower($engine)==strtolower($support_engine))
{
$replace_engine=false;
break;
}
}
if($replace_engine!==false)
{
if(!empty($this->default_engines))
$replace_engine=$this->default_engines[0];
}
if($replace_engine!==false)
{
$this->log->WriteLog('Create table replace engine:'.$engine.' to :'.$replace_engine,'notice');
$query=str_replace("ENGINE=$engine", "ENGINE=$replace_engine", $query);
}
}
if (preg_match('/CHARSET ([^\s;]+)/', $query, $matches)||preg_match('/CHARSET=([^\s;]+)/', $query, $matches))
{
$charset = $matches[1];
$replace_charset=true;
foreach ($this->support_charsets as $support_charset)
{
if(strtolower($charset)==strtolower($support_charset))
{
$replace_charset=false;
break;
}
}
if($replace_charset)
{
$replace_charset=$this->default_charsets[0];
}
if($replace_charset!==false)
{
$this->log->WriteLog('Create table replace charset:'.$charset.' to :'.$replace_charset,'notice');
$query=str_replace("CHARSET=$charset", "CHARSET=$replace_charset", $query);
$query=str_replace("CHARSET $charset", "CHARSET=$replace_charset", $query);
$charset=$replace_charset;
}
$collate='';
if (preg_match('/ COLLATE ([a-zA-Z0-9._-]+)/i', $query, $matches))
{
$collate = $matches[1];
}
else if(preg_match('/ COLLATE=([a-zA-Z0-9._-]+)/i', $query, $matches))
{
$collate = $matches[1];
}
if(!empty($collate))
{
$replace_collate=true;
foreach ($this->support_collates as $key=>$support_collate)
{
if(strtolower($charset)==strtolower($support_collate->Charset)&&strtolower($collate)==strtolower($key))
{
$replace_collate=false;
break;
}
}
if($replace_collate)
{
$replace_collate=false;
foreach ($this->support_collates as $key=>$support_collate)
{
if(strtolower($charset)==strtolower($support_collate->Charset))
{
if($support_collate->Default=='Yes')
{
$replace_collate=$key;
}
}
}
if($replace_collate==false)
{
foreach ($this->support_collates as $key=>$support_collate)
{
if(strtolower($charset)==strtolower($support_collate->Charset))
{
$replace_collate=$key;
break;
}
}
}
}
if($replace_collate!==false)
{
$this->log->WriteLog('Create table replace collate:'.$collate.' to :'.$replace_collate.' '.$charset,'notice');
$query=str_replace("COLLATE $collate", "COLLATE $replace_collate", $query);
$query=str_replace("COLLATE=$collate", "COLLATE=$replace_collate", $query);
}
}
}
else
{
if (preg_match('/ COLLATE ([a-zA-Z0-9._-]+)/i', $query, $matches))
{
$collate = $matches[1];
}
else if(preg_match('/ COLLATE=([a-zA-Z0-9._-]+)/i', $query, $matches))
{
$collate = $matches[1];
}
if(!empty($collate))
{
$replace_collate=true;
foreach ($this->support_collates as $key=>$support_collate)
{
if(strtolower($collate)==strtolower($key))
{
$replace_collate=false;
break;
}
}
if($replace_collate)
{
$replace_collate=false;
foreach ($this->support_collates as $key=>$support_collate)
{
if(strtolower($this->default_charsets[0])==strtolower($support_collate->Charset))
{
if($support_collate->Default=='Yes')
{
$replace_collate=$key;
}
}
}
if($replace_collate==false)
{
foreach ($this->support_collates as $key=>$support_collate)
{
if(strtolower($this->default_charsets[0])==strtolower($support_collate->Charset))
{
$replace_collate=$key;
break;
}
}
}
}
if($replace_collate!==false)
{
$this->log->WriteLog('Create table replace collate:'.$collate.' to :'.$replace_collate,'notice');
$query=str_replace("COLLATE $collate", "COLLATE $replace_collate", $query);
$query=str_replace("COLLATE=$collate", "COLLATE=$replace_collate", $query);
}
}
}
if(preg_match('/\/\*!.*\*\//', $query, $matches))
{
$annotation_content = $matches[0];
$query = str_replace($annotation_content, '', $query);
}
}
$constraints = array();
if (preg_match_all('/CONSTRAINT ([\a-zA-Z0-9_\']+) FOREIGN KEY \([a-zA-z0-9_\', ]+\) REFERENCES \'?([a-zA-z0-9_]+)\'? /i', $query, $constraint_matches))
{
$constraints = $constraint_matches;
}
else if (preg_match_all('/ FOREIGN KEY \([a-zA-z0-9_\', ]+\) REFERENCES \'?([a-zA-z0-9_]+)\'? /i', $query, $constraint_matches))
{
$constraints = $constraint_matches;
}
if (!empty($constraints) && $this->old_prefix != $this->new_prefix)
{
foreach ($constraints[0] as $constraint)
{
$updated_constraint = str_replace($this->old_prefix, $this->new_prefix, $constraint);
$query = str_replace($constraint, $updated_constraint, $query);
}
$this->log->WriteLog('replace foreign key.','notice');
}
if($this->execute_sql($query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
return $table_name;
}
private function lock_table($query,$sub_task)
{
if (preg_match('/^\s*LOCK TABLES +\`?([^\`]*)\`?/i', $query, $matches))
{
$table_name = $matches[1];
$tmp_option=$sub_task['options'];
if($this->is_mu&&isset($tmp_option['site_id']))
{
if($this->is_mu_single_og_table($table_name))
{
if(substr($table_name,strlen($this->old_base_prefix))=='users'||substr($table_name,strlen($this->old_base_prefix))=='usermeta')
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_base_prefix));
}
else
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_prefix));
}
}
else
{
$new_table_name=$table_name;
}
}
else if($this->is_og_table($table_name))
{
if(!empty($this->old_base_prefix)&&(substr($table_name,strlen($this->old_base_prefix))=='users'||substr($table_name,strlen($this->old_base_prefix))=='usermeta'))
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_base_prefix));
}
else
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_prefix));
}
}
else
{
$new_table_name=$table_name;
}
$this->log->WriteLog('lock replace table:'.$table_name.' to :'.$new_table_name,'notice');
$query=str_replace($table_name,$new_table_name,$query);
}
if($this->execute_sql($query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
private function replace_table_execute_sql($query,$table_name,$sub_task)
{
$tmp_option=$sub_task['options'];
if($this->is_mu&&isset($tmp_option['site_id']))
{
if($this->is_mu_single_og_table($table_name))
{
if(!empty($table_name))
{
if(substr($table_name,strlen($this->old_base_prefix))=='users'||substr($table_name,strlen($this->old_base_prefix))=='usermeta')
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_base_prefix));
}
else
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_prefix));
}
if($this->old_prefix !== '')
{
$query=str_replace($table_name,$new_table_name,$query);
}
else
{
$query=preg_replace('/'.$table_name.'/',$new_table_name,$query, 1);
}
}
}
else
{
$new_table_name=$table_name;
$query=str_replace($table_name,$new_table_name,$query);
}
}
else if($this->is_og_table($table_name))
{
if(!empty($table_name))
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_prefix));
$query=str_replace($table_name,$new_table_name,$query);
}
}
else
{
$new_table_name=$table_name;
$query=str_replace($table_name,$new_table_name,$query);
}
if($this->execute_sql($query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
private function insert($query,$sub_task)
{
if (preg_match('/^\s*INSERT INTO +\`?([^\`]*)\`?/i', $query, $matches))
{
$table_name = $matches[1];
$tmp_option=$sub_task['options'];
if($this->is_mu&&isset($tmp_option['site_id']))
{
if($this->is_mu_single_og_table($table_name))
{
if(substr($table_name,strlen($this->old_base_prefix))=='users'||substr($table_name,strlen($this->old_base_prefix))=='usermeta')
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_base_prefix));
}
else
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_prefix));
}
}
else
{
$new_table_name=$table_name;
}
}
else if($this->is_og_table($table_name))
{
if(!empty($this->old_base_prefix)&&(substr($table_name,strlen($this->old_base_prefix))=='users'||substr($table_name,strlen($this->old_base_prefix))=='usermeta'))
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_base_prefix));
}
else
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_prefix));
}
}
else
{
$new_table_name=$table_name;
}
if($this->old_prefix !== '')
{
$query=str_replace($table_name,$new_table_name,$query);
}
else
{
$query=preg_replace('/'.$table_name.'/',$new_table_name,$query, 1);
}
}
if($this->execute_sql($query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
/*
$pos=strpos($query,'mainwp_child_');
if($pos!==false)
{
$this->log->WriteLog('skip insert item: '.$query,'notice');
}
else{
if($this->execute_sql($query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}*/
}
private function drop_table($query,$sub_task)
{
if (preg_match('/^\s*DROP TABLE IF EXISTS +\`?([^\`]*)\`?\s*;/i', $query, $matches))
{
$table_name = $matches[1];
$tmp_option=$sub_task['options'];
if($this->is_mu&&isset($tmp_option['site_id']))
{
if($this->is_mu_single_og_table($table_name))
{
if(substr($table_name,strlen($this->old_base_prefix))=='users'||substr($table_name,strlen($this->old_base_prefix))=='usermeta')
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_base_prefix));
}
else
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_prefix));
}
}
else
{
$new_table_name=$table_name;
}
}
else if($this->is_og_table($table_name))
{
if(!empty($this->old_base_prefix)&&(substr($table_name,strlen($this->old_base_prefix))=='users'||substr($table_name,strlen($this->old_base_prefix))=='usermeta'))
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_base_prefix));
}
else
{
$new_table_name=$this->temp_new_prefix.substr($table_name,strlen($this->old_prefix));
}
}
else
{
$new_table_name=$table_name;
}
$query=str_replace($table_name,$new_table_name,$query);
$this->log->WriteLog('Drop table if exist '.$new_table_name,'notice');
}
if($this->execute_sql($query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
private function replace_row_ex($table_name,$replace_table_data,$sub_task,$max_replace_row=100000)
{
global $wpdb;
$max_replace_row=max(100,$max_replace_row);
$row=$replace_table_data['offset'];
$this->replacing_table=$table_name;
$replace_current_table_finish=false;
if(substr($table_name, strlen($this->temp_new_prefix))=='options')
{
if($this->old_prefix!=$this->new_prefix)
{
$update_query ='UPDATE '.$table_name.' SET option_name="'.$this->new_prefix.'user_roles" WHERE option_name="'.$this->old_prefix.'user_roles";';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
}
if(substr($table_name, strlen($this->temp_new_prefix))=='usermeta')
{
$tmp_option=$sub_task['options'];
if($this->is_mu&&isset($tmp_option['site_id']))
{
$update_query ='UPDATE '.$table_name.' SET meta_key=REPLACE(meta_key,"'.$this->old_prefix.'","'.$this->new_prefix.'") WHERE meta_key LIKE "'.str_replace('_','\_',$this->old_prefix).'%";';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%capabilities%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.'capabilities\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%user_level%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.'user_level\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
$ret['last_msg']=$sub_task['last_msg'];
return $ret;
}
else
{
if($this->old_prefix!=$this->new_prefix)
{
if($this->old_prefix!=='')
{
$update_query ='UPDATE '.$table_name.' SET meta_key=REPLACE(meta_key,"'.$this->old_prefix.'","'.$this->new_prefix.'") WHERE meta_key LIKE "'.str_replace('_','\_',$this->old_prefix).'%";';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
else
{
if(is_multisite())
{
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%_capabilities%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.$item['meta_key'].'\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%_user_level%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.$item['meta_key'].'\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'capabilities" WHERE meta_key="' . $this->old_prefix . 'capabilities";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user_level" WHERE meta_key="' . $this->old_prefix . 'user_level";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user-settings" WHERE meta_key="' . $this->old_prefix . 'user-settings";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user-settings-time" WHERE meta_key="' . $this->old_prefix . 'user-settings-time";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'dashboard_quick_press_last_post_id" WHERE meta_key="' . $this->old_prefix . 'dashboard_quick_press_last_post_id";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
}
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
$ret['last_msg']=$sub_task['last_msg'];
return $ret;
}
}
}
if(!empty($this->old_base_prefix)&&substr($table_name,strlen($this->temp_new_prefix))=='usermeta')
{
$tmp_option=$sub_task['options'];
if($this->is_mu&&isset($tmp_option['site_id']))
{
$update_query ='UPDATE '.$table_name.' SET meta_key=REPLACE(meta_key,"'.$this->old_base_prefix.'","'.$this->new_prefix.'") WHERE meta_key LIKE "'.str_replace('_','\_',$this->old_base_prefix).'%";';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%_capabilities%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.'capabilities\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%_user_level%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.'user_level\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
$ret['last_msg']=$sub_task['last_msg'];
return $ret;
}
else
{
if($this->old_base_prefix!=$this->new_prefix)
{
if($this->old_base_prefix!=='')
{
$update_query ='UPDATE '.$table_name.' SET meta_key=REPLACE(meta_key,"'.$this->old_base_prefix.'","'.$this->new_prefix.'") WHERE meta_key LIKE "'.str_replace('_','\_',$this->old_base_prefix).'%";';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
else
{
if(is_multisite())
{
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%_capabilities%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.$item['meta_key'].'\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%_user_level%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.$item['meta_key'].'\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'capabilities" WHERE meta_key="' . $this->old_base_prefix . 'capabilities";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user_level" WHERE meta_key="' . $this->old_base_prefix . 'user_level";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user-settings" WHERE meta_key="' . $this->old_base_prefix . 'user-settings";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user-settings-time" WHERE meta_key="' . $this->old_base_prefix . 'user-settings-time";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'dashboard_quick_press_last_post_id" WHERE meta_key="' . $this->old_base_prefix . 'dashboard_quick_press_last_post_id";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
}
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
$ret['last_msg']=$sub_task['last_msg'];
return $ret;
}
}
}
if($this->old_site_url==$this->new_site_url)
{
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
$ret['last_msg']=$sub_task['last_msg'];
return $ret;
}
if($this->is_mu)
{
if(substr($table_name, strlen($this->temp_new_prefix))=='blogs')
{
$this->log->WriteLog('Update mu blogs table', 'notice');
if((preg_match('#^https?://([^/]+)#i', $this->new_home_url, $matches) || preg_match('#^https?://([^/]+)#i', $this->new_site_url, $matches)) && (preg_match('#^https?://([^/]+)#i', $this->old_home_url, $old_matches) || preg_match('#^https?://([^/]+)#i', $this->old_site_url, $old_matches)))
{
$new_string = strtolower($matches[1]);
$old_string = strtolower($old_matches[1]);
$new_path='';
$old_path='';
if(defined( 'PATH_CURRENT_SITE' ))
{
$new_path=PATH_CURRENT_SITE;
}
$query = 'SELECT * FROM `'.$table_name.'`';
$result=$this->db_method->query($query,ARRAY_A);
if($result && sizeof($result)>0)
{
$rows = $result;
foreach ($rows as $row)
{
$update=array();
$where=array();
if($row['blog_id']==1)
{
$old_path=$row['path'];
}
$old_domain_data = $row['domain'];
$new_domain_data=str_replace($old_string,$new_string,$old_domain_data);
$temp_where='`blog_id` = "' . $row['blog_id'] . '"';
if (is_callable(array($wpdb, 'remove_placeholder_escape')))
$temp_where = $wpdb->remove_placeholder_escape($temp_where);
$where[] = $temp_where;
$update[] = '`domain` = "' . $new_domain_data . '"';
if(!empty($old_path)&&!empty($new_path))
{
$old_path_data= $row['path'];
$new_path_data=$this->str_replace_first($old_path,$new_path,$old_path_data);
$update[] = '`path` = "' . $new_path_data . '"';
}
if(!empty($update)&&!empty($where))
{
$update_query = 'UPDATE `'.$table_name.'` SET '.implode(', ', $update).' WHERE '.implode(' AND ', array_filter($where)).';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
}
}
}
}
}
$skip_table=false;
if(apply_filters('wpvivid_restore_db_skip_replace_tables',$skip_table,$table_name))
{
$this->log->WriteLog('Skipping table '.$table_name, 'Warning');
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
$ret['last_msg']=$sub_task['last_msg'];
return $ret;
}
$query = 'SELECT COUNT(*) FROM `'.$table_name.'`';
$current_row=0;
$result=$this->db_method->query($query,ARRAY_N);
if($result && sizeof($result)>0)
{
$count=$result[0][0];
$this->log->WriteLog('Counting of rows in '.$table_name.': '.$count, 'notice');
if($count==0)
{
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
$ret['last_msg']=$sub_task['last_msg'];
return $ret;
}
$query='DESCRIBE `'.$table_name.'`';
$result=$this->db_method->query($query,ARRAY_A);
$columns=array();
foreach ($result as $data)
{
$column['Field']=$data['Field'];
if($data['Key']=='PRI')
$column['PRI']=1;
else
$column['PRI']=0;
if($data['Type']=='mediumblob')
{
$column['skip']=1;
}
$columns[]=$column;
}
$page=min(5000,$max_replace_row);
$update_query='';
$start_row=$row;
$replace_row=0;
for ($current_row = $start_row; $current_row < $count; $current_row += $page)
{
$this->log->WriteLog('Replacing the row in '.$current_row. ' line.', 'notice');
$sub_task['last_msg']='Importing sql file table: '.$table_name.' Replaced row: '.$current_row.'/'.$count.';';
$this->update_sub_task($sub_task);
$query = 'SELECT * FROM `'.$table_name.'` LIMIT '.$current_row.', '.$page;
$replace_row+=$page;
$result=$this->db_method->query($query,ARRAY_A);
if($result && sizeof($result)>0)
{
$rows = $result;
foreach ($rows as $row)
{
$update=array();
$where=array();
foreach ($columns as $column)
{
if(isset($column['skip']))
{
//$this->log->WriteLog('Skipping mediumblob type data', 'notice');
continue;
}
$old_data = $row[$column['Field']];
if($column['PRI']==1)
{
$wpdb->escape_by_ref($old_data);
$temp_where='`'.$column['Field'].'` = "' . $old_data . '"';
if (is_callable(array($wpdb, 'remove_placeholder_escape')))
$temp_where = $wpdb->remove_placeholder_escape($temp_where);
$where[] = $temp_where;
}
$skip_row=false;
if(apply_filters('wpvivid_restore_db_skip_replace_rows',$skip_row,$table_name,$column['Field']))
{
continue;
}
if (!is_null($old_data))
{
if(preg_match('/WP_HTML_Token/', $old_data, $matches))
{
$this->log->WriteLog('Skip WP_HTML_Token.', 'notice');
continue;
}
}
$new_data=$this->replace_row_data($old_data);
if($new_data==$old_data)
continue;
$wpdb->escape_by_ref($new_data);
if (is_callable(array($wpdb, 'remove_placeholder_escape')))
$new_data = $wpdb->remove_placeholder_escape($new_data);
$update[] = '`'.$column['Field'].'` = "' . $new_data . '"';
}
if(!empty($update)&&!empty($where))
{
$temp_query = 'UPDATE `'.$table_name.'` SET '.implode(', ', $update).' WHERE '.implode(' AND ', array_filter($where)).';';
$type=$this->db_method->get_type();
if($type=='pdo_mysql')
{
if($update_query=='')
{
$update_query=$temp_query;
if(strlen($update_query)>$this->db_method->get_max_allow_packet())
{
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
$update_query='';
}
}
else if(strlen($temp_query)+strlen($update_query)>$this->db_method->get_max_allow_packet())
{
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
$update_query=$temp_query;
}
else
{
$update_query.=$temp_query;
}
}
else
{
$update_query=$temp_query;
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
$update_query='';
}
}
//return;
}
}
if($replace_row>$max_replace_row)
{
$current_row+= $page;
break;
}
}
if(!empty($update_query))
{
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
if($current_row >= $count)
{
$replace_current_table_finish=true;
}
}
else
{
$replace_current_table_finish=true;
$current_row=0;
}
$this->log->WriteLog('Replacing row completed. Current row:'.$current_row, 'notice');
$ret['result']='success';
$ret['replace_row']=$current_row;
$ret['max_replace_row']=$max_replace_row;
$ret['current_replace_table_finish']=$replace_current_table_finish;
$ret['last_msg']=$sub_task['last_msg'];
$this->log->WriteLog(json_encode($ret), 'notice');
return $ret;
}
private function replace_row($sql_file_name,$sub_task,$max_replace_row=100000)
{
global $wpdb;
$max_replace_row=max(100,$max_replace_row);
$table_name=$sub_task['exec_sql']['current_table'];
$row=$sub_task['exec_sql']['current_replace_row'];
$this->replacing_table=$table_name;
$replace_current_table_finish=false;
$this->log->WriteLog('Dumping table '.$table_name.' is complete. Start replacing row(s).', 'notice');
if(substr($table_name, strlen($this->temp_new_prefix))=='options')
{
if($this->old_prefix!=$this->new_prefix)
{
$update_query ='UPDATE '.$table_name.' SET option_name="'.$this->new_prefix.'user_roles" WHERE option_name="'.$this->old_prefix.'user_roles";';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
}
if(substr($table_name, strlen($this->temp_new_prefix))=='usermeta')
{
if($this->old_prefix!=$this->new_prefix)
{
if($this->old_prefix!=='')
{
$update_query ='UPDATE '.$table_name.' SET meta_key=REPLACE(meta_key,"'.$this->old_prefix.'","'.$this->new_prefix.'") WHERE meta_key LIKE "'.str_replace('_','\_',$this->old_prefix).'%";';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
else
{
if(is_multisite())
{
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%_capabilities%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.$item['meta_key'].'\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%_user_level%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.$item['meta_key'].'\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'capabilities" WHERE meta_key="' . $this->old_prefix . 'capabilities";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user_level" WHERE meta_key="' . $this->old_prefix . 'user_level";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user-settings" WHERE meta_key="' . $this->old_prefix . 'user-settings";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user-settings-time" WHERE meta_key="' . $this->old_prefix . 'user-settings-time";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'dashboard_quick_press_last_post_id" WHERE meta_key="' . $this->old_prefix . 'dashboard_quick_press_last_post_id";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
}
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
return $ret;
}
}
if(!empty($this->old_base_prefix)&&substr($table_name,strlen($this->temp_new_prefix))=='usermeta')
{
if($this->old_base_prefix!=$this->new_prefix)
{
if($this->old_base_prefix!=='')
{
$update_query ='UPDATE '.$table_name.' SET meta_key=REPLACE(meta_key,"'.$this->old_base_prefix.'","'.$this->new_prefix.'") WHERE meta_key LIKE "'.str_replace('_','\_',$this->old_base_prefix).'%";';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
else
{
if(is_multisite())
{
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%_capabilities%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.$item['meta_key'].'\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
$select_query='SELECT * FROM '.$table_name.' WHERE meta_key LIKE "%_user_level%";';
$results = $wpdb->get_results($select_query,ARRAY_A);
foreach ($results as $item)
{
$update_query='UPDATE '.$table_name.' SET meta_key=\''.$this->new_prefix.$item['meta_key'].'\' WHERE meta_key=\''.$item['meta_key'].'\';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'capabilities" WHERE meta_key="' . $this->old_base_prefix . 'capabilities";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user_level" WHERE meta_key="' . $this->old_base_prefix . 'user_level";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user-settings" WHERE meta_key="' . $this->old_base_prefix . 'user-settings";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'user-settings-time" WHERE meta_key="' . $this->old_base_prefix . 'user-settings-time";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
$update_query = 'UPDATE ' . $table_name . ' SET meta_key="' . $this->new_prefix . 'dashboard_quick_press_last_post_id" WHERE meta_key="' . $this->old_base_prefix . 'dashboard_quick_press_last_post_id";';
if ($this->execute_sql($update_query, $sub_task) === false)
{
$this->log->WriteLog($this->db_method->get_last_error(), 'notice');
}
}
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
return $ret;
}
}
if($this->old_site_url==$this->new_site_url)
{
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
return $ret;
}
if($this->is_mu)
{
if(substr($table_name, strlen($this->temp_new_prefix))=='blogs')
{
$this->log->WriteLog('Update mu blogs table', 'notice');
if((preg_match('#^https?://([^/]+)#i', $this->new_home_url, $matches) || preg_match('#^https?://([^/]+)#i', $this->new_site_url, $matches)) && (preg_match('#^https?://([^/]+)#i', $this->old_home_url, $old_matches) || preg_match('#^https?://([^/]+)#i', $this->old_site_url, $old_matches)))
{
$new_string = strtolower($matches[1]);
$old_string = strtolower($old_matches[1]);
$new_path='';
$old_path='';
if(defined( 'PATH_CURRENT_SITE' ))
{
$new_path=PATH_CURRENT_SITE;
}
$query = 'SELECT * FROM `'.$table_name.'`';
$result=$this->db_method->query($query,ARRAY_A);
if($result && sizeof($result)>0)
{
$rows = $result;
foreach ($rows as $row)
{
$update=array();
$where=array();
if($row['blog_id']==1)
{
$old_path=$row['path'];
}
$old_domain_data = $row['domain'];
$new_domain_data=str_replace($old_string,$new_string,$old_domain_data);
$temp_where='`blog_id` = "' . $row['blog_id'] . '"';
if (is_callable(array($wpdb, 'remove_placeholder_escape')))
$temp_where = $wpdb->remove_placeholder_escape($temp_where);
$where[] = $temp_where;
$update[] = '`domain` = "' . $new_domain_data . '"';
if(!empty($old_path)&&!empty($new_path))
{
$old_path_data= $row['path'];
$new_path_data=$this->str_replace_first($old_path,$new_path,$old_path_data);
$update[] = '`path` = "' . $new_path_data . '"';
}
if(!empty($update)&&!empty($where))
{
$update_query = 'UPDATE `'.$table_name.'` SET '.implode(', ', $update).' WHERE '.implode(' AND ', array_filter($where)).';';
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
}
}
}
}
}
$skip_table=false;
if(apply_filters('wpvivid_restore_db_skip_replace_tables',$skip_table,$table_name))
{
$this->log->WriteLog('Skipping table '.$table_name, 'Warning');
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
return $ret;
}
$query = 'SELECT COUNT(*) FROM `'.$table_name.'`';
$current_row=0;
$result=$this->db_method->query($query,ARRAY_N);
if($result && sizeof($result)>0)
{
$count=$result[0][0];
$this->log->WriteLog('Counting of rows in '.$table_name.': '.$count, 'notice');
if($count==0)
{
$ret['result']='success';
$ret['replace_row']=0;
$ret['current_replace_table_finish']=true;
return $ret;
}
$query='DESCRIBE `'.$table_name.'`';
$result=$this->db_method->query($query,ARRAY_A);
$columns=array();
foreach ($result as $data)
{
$column['Field']=$data['Field'];
if($data['Key']=='PRI')
$column['PRI']=1;
else
$column['PRI']=0;
if($data['Type']=='mediumblob')
{
$column['skip']=1;
}
$columns[]=$column;
}
$page=min(5000,$max_replace_row);
$update_query='';
$start_row=$row;
$replace_row=0;
for ($current_row = $start_row; $current_row < $count; $current_row += $page)
{
$this->log->WriteLog('Replacing the row in '.$current_row. ' line.', 'notice');
$sub_task['last_msg']='Importing sql file:'.$sql_file_name.' table: '.$table_name.' Replaced row: '.$current_row.'/'.$count.'; '.size_format($sub_task['exec_sql']['sql_files'][$sql_file_name]['sql_offset'],2).'/'.size_format($this->sum,2);
$this->update_sub_task($sub_task);
$query = 'SELECT * FROM `'.$table_name.'` LIMIT '.$current_row.', '.$page;
$replace_row+=$page;
$result=$this->db_method->query($query,ARRAY_A);
if($result && sizeof($result)>0)
{
$rows = $result;
foreach ($rows as $row)
{
$update=array();
$where=array();
foreach ($columns as $column)
{
if(isset($column['skip']))
{
//$this->log->WriteLog('Skipping mediumblob type data', 'notice');
continue;
}
$old_data = $row[$column['Field']];
if($column['PRI']==1)
{
$wpdb->escape_by_ref($old_data);
$temp_where='`'.$column['Field'].'` = "' . $old_data . '"';
if (is_callable(array($wpdb, 'remove_placeholder_escape')))
$temp_where = $wpdb->remove_placeholder_escape($temp_where);
$where[] = $temp_where;
}
$skip_row=false;
if(apply_filters('wpvivid_restore_db_skip_replace_rows',$skip_row,$table_name,$column['Field']))
{
continue;
}
$new_data=$this->replace_row_data($old_data);
if($new_data==$old_data)
continue;
$wpdb->escape_by_ref($new_data);
if (is_callable(array($wpdb, 'remove_placeholder_escape')))
$new_data = $wpdb->remove_placeholder_escape($new_data);
$update[] = '`'.$column['Field'].'` = "' . $new_data . '"';
}
if(!empty($update)&&!empty($where))
{
$temp_query = 'UPDATE `'.$table_name.'` SET '.implode(', ', $update).' WHERE '.implode(' AND ', array_filter($where)).';';
$type=$this->db_method->get_type();
if($type=='pdo_mysql')
{
if($update_query=='')
{
$update_query=$temp_query;
if(strlen($update_query)>$this->db_method->get_max_allow_packet())
{
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
$update_query='';
}
}
else if(strlen($temp_query)+strlen($update_query)>$this->db_method->get_max_allow_packet())
{
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
$update_query=$temp_query;
}
else
{
$update_query.=$temp_query;
}
}
else
{
$update_query=$temp_query;
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
$update_query='';
}
}
//return;
}
}
if($replace_row>$max_replace_row)
{
$current_row+= $page;
break;
}
}
if(!empty($update_query))
{
if($this->execute_sql($update_query,$sub_task)===false)
{
$this->log->WriteLog($this->db_method->get_last_error(),'notice');
}
}
if($current_row >= $count)
{
$replace_current_table_finish=true;
}
}
else
{
$replace_current_table_finish=true;
$current_row=0;
}
$this->log->WriteLog('Replacing row completed. Current row:'.$current_row, 'notice');
$ret['result']='success';
$ret['replace_row']=$current_row;
$ret['max_replace_row']=$max_replace_row;
$ret['current_replace_table_finish']=$replace_current_table_finish;
$this->log->WriteLog(wp_json_encode($ret), 'notice');
return $ret;
}
private function replace_row_data($old_data)
{
try{
$unserialize_data = @unserialize($old_data, array('allowed_classes' => false));
if($unserialize_data===false)
{
$old_data=$this->replace_string_v2($old_data);
}
else
{
$old_data=$this->replace_serialize_data($unserialize_data);
$old_data=serialize($old_data);
}
}
catch (Error $error)
{
$old_data=$this->replace_string_v2($old_data);
}
return $old_data;
}
private function replace_serialize_data($data)
{
if(is_string($data))
{
$serialize_data =@unserialize($data, array('allowed_classes' => false));
if($serialize_data===false)
{
$data=$this->replace_string_v2($data);
}
else
{
$data=serialize($this->replace_serialize_data($serialize_data));
}
}
else if(is_array($data))
{
foreach ($data as $key => $value)
{
if(is_string($value))
{
$data[$key]=$this->replace_string_v2($value);
}
else if(is_array($value))
{
$data[$key]=$this->replace_serialize_data($value);
}
else if(is_object($value))
{
if (is_a($value, '__PHP_Incomplete_Class'))
{
//
}
else
{
$data[$key]=$this->replace_serialize_data($value);
}
}
}
}
else if(is_object($data))
{
$temp = $data; // new $data_class();
if (is_a($data, '__PHP_Incomplete_Class'))
{
}
else
{
$props = get_object_vars($data);
foreach ($props as $key => $value)
{
if (strpos($key, "\0")===0)
continue;
if(is_string($value))
{
$temp->$key =$this->replace_string_v2($value);
}
else if(is_array($value))
{
$temp->$key=$this->replace_serialize_data($value);
}
else if(is_object($value))
{
$temp->$key=$this->replace_serialize_data($value);
}
}
}
$data = $temp;
unset($temp);
}
return $data;
}
private function get_remove_http_link($url)
{
if (0 === stripos($url, 'https://'))
{
$mix_link = '//'.substr($url, 8);
} elseif (0 === stripos($url, 'http://')) {
$mix_link = '//'.substr($url, 7);
}
else
{
$mix_link=false;
}
return $mix_link;
}
private function get_remove_http_link_ex($url)
{
if (0 === stripos($url, 'https://'))
{
$mix_link = '\/\/'.substr($url, 8);
} elseif (0 === stripos($url, 'http://')) {
$mix_link = '\/\/'.substr($url, 7);
}
else
{
$mix_link=false;
}
return $mix_link;
}
private function get_http_link_at_quote($url)
{
return str_replace('/','\/',$url);
}
public function replace_string_v2($old_string)
{
if(!is_string($old_string))
{
return $old_string;
}
$from=array();
$to=array();
$new_url_use_https=false;
if (0 === stripos($this->new_site_url, 'https://')|| stripos($this->new_site_url, 'https:\/\/'))
{
$new_url_use_https=true;
}
else if (0 === stripos($this->new_site_url, 'http://')|| stripos($this->new_site_url, 'http:\/\/'))
{
$new_url_use_https=false;
}
if(isset($this->old_mu_single_site_upload_url) && !empty($this->old_mu_single_site_upload_url))
{
$upload_dir = wp_upload_dir();
$tmp_upload_url=untrailingslashit($upload_dir['baseurl']);
$from[]=$this->old_mu_single_site_upload_url;
$to[]=$tmp_upload_url;
if(isset($this->old_mu_single_home_upload_url) && !empty($this->old_mu_single_home_upload_url))
{
if($this->old_mu_single_site_upload_url !== $this->old_mu_single_home_upload_url)
{
$from[]=$this->old_mu_single_home_upload_url;
$to[]=$tmp_upload_url;
}
}
}
if($this->old_site_url!=$this->new_site_url)
{
if(substr($this->replacing_table, strlen($this->new_prefix))=='posts'||substr($this->replacing_table, strlen($this->new_prefix))=='postmeta'||substr($this->replacing_table, strlen($this->new_prefix))=='options')
{
$remove_http_link=$this->get_remove_http_link($this->old_site_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link($this->new_site_url);
$from[]=$remove_http_link;
$to[]=$new_remove_http_link;
if($new_url_use_https)
{
$from[]='http:'.$new_remove_http_link;
$to[]='https:'.$new_remove_http_link;
}
else
{
$from[]='https:'.$new_remove_http_link;
$to[]='http:'.$new_remove_http_link;
}
$quote_old_site_url=$this->get_http_link_at_quote($remove_http_link);
$quote_new_site_url=$this->get_http_link_at_quote($new_remove_http_link);
$from[]=$quote_old_site_url;
$to[]=$quote_new_site_url;
if($new_url_use_https)
{
$from[]='http:'.$quote_new_site_url;
$to[]='https:'.$quote_new_site_url;
}
else
{
$from[]='https:'.$quote_new_site_url;
$to[]='http:'.$quote_new_site_url;
}
}
else
{
$remove_http_link=$this->get_remove_http_link_ex($this->old_site_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link_ex($this->new_site_url);
$from[]=$remove_http_link;
$to[]=$new_remove_http_link;
if($new_url_use_https)
{
$from[]='http:'.$new_remove_http_link;
$to[]='https:'.$new_remove_http_link;
}
else
{
$from[]='https:'.$new_remove_http_link;
$to[]='http:'.$new_remove_http_link;
}
}
}
$tmp_old_site_url = str_replace(':', '%3A', $this->old_site_url);
$tmp_old_site_url = str_replace('/', '%2F', $tmp_old_site_url);
$tmp_new_site_url = str_replace(':', '%3A', $this->new_site_url);
$tmp_new_site_url = str_replace('/', '%2F', $tmp_new_site_url);
$from[]=$tmp_old_site_url;
$to[]=$tmp_new_site_url;
}
else
{
$from[]=$this->old_site_url;
$to[]=$this->new_site_url;
$from[]=str_replace('/', '\/', $this->old_site_url);
$to[]=str_replace('/', '\/', $this->new_site_url);
$tmp_old_site_url = str_replace(':', '%3A', $this->old_site_url);
$tmp_old_site_url = str_replace('/', '%2F', $tmp_old_site_url);
$tmp_new_site_url = str_replace(':', '%3A', $this->new_site_url);
$tmp_new_site_url = str_replace('/', '%2F', $tmp_new_site_url);
$from[]=$tmp_old_site_url;
$to[]=$tmp_new_site_url;
}
}
if($this->old_home_url!=$this->old_site_url&&$this->old_home_url!=$this->new_home_url)
{
if(substr($this->replacing_table, strlen($this->new_prefix))=='posts'||substr($this->replacing_table, strlen($this->new_prefix))=='postmeta'||substr($this->replacing_table, strlen($this->new_prefix))=='options')
{
$remove_http_link=$this->get_remove_http_link($this->old_home_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link($this->new_home_url);
$from[]=$remove_http_link;
$to[]=$new_remove_http_link;
if($new_url_use_https)
{
$from[]='http:'.$new_remove_http_link;
$to[]='https:'.$new_remove_http_link;
}
else
{
$from[]='https:'.$new_remove_http_link;
$to[]='http:'.$new_remove_http_link;
}
$quote_old_site_url=$this->get_http_link_at_quote($remove_http_link);
$quote_new_site_url=$this->get_http_link_at_quote($new_remove_http_link);
$from[]=$quote_old_site_url;
$to[]=$quote_new_site_url;
if($new_url_use_https)
{
$from[]='http:'.$quote_new_site_url;
$to[]='https:'.$quote_new_site_url;
}
else
{
$from[]='https:'.$quote_new_site_url;
$to[]='http:'.$quote_new_site_url;
}
}
else
{
$remove_http_link=$this->get_remove_http_link_ex($this->old_home_url);
if($remove_http_link!==false)
{
$new_remove_http_link=$this->get_remove_http_link_ex($this->new_home_url);
$from[]=$remove_http_link;
$to[]=$new_remove_http_link;
if($new_url_use_https)
{
$from[]='http:'.$new_remove_http_link;
$to[]='https:'.$new_remove_http_link;
}
else
{
$from[]='https:'.$new_remove_http_link;
$to[]='http:'.$new_remove_http_link;
}
}
}
}
else
{
$from[]=$this->old_home_url;
$to[]=$this->new_home_url;
}
}
if(!empty($from)&&!empty($to))
{
$old_string=str_replace($from,$to,$old_string);
}
return $old_string;
}
public function skip_tables($skip_table,$table_name)
{
$skip_tables[]='adrotate_stats';
$skip_tables[]='login_security_solution_fail';
$skip_tables[]='icl_strings';
$skip_tables[]='icl_string_positions';
$skip_tables[]='icl_string_translations';
$skip_tables[]='icl_languages_translations';
$skip_tables[]='slim_stats';
$skip_tables[]='slim_stats_archive';
$skip_tables[]='es_online';
$skip_tables[]='ahm_download_stats';
$skip_tables[]='woocommerce_order_items';
$skip_tables[]='woocommerce_sessions';
$skip_tables[]='redirection_404';
$skip_tables[]='redirection_logs';
$skip_tables[]='wbz404_logs';
$skip_tables[]='wbz404_redirects';
$skip_tables[]='Counterize';
$skip_tables[]='Counterize_UserAgents';
$skip_tables[]='Counterize_Referers';
$skip_tables[]='et_bloom_stats';
$skip_tables[]='term_relationships';
$skip_tables[]='lbakut_activity_log';
$skip_tables[]='simple_feed_stats';
$skip_tables[]='svisitor_stat';
$skip_tables[]='itsec_log';
$skip_tables[]='relevanssi_log';
$skip_tables[]='wysija_email_user_stat';
$skip_tables[]='wponlinebackup_generations';
$skip_tables[]='blc_instances';
$skip_tables[]='wp_rp_tags';
$skip_tables[]='statpress';
$skip_tables[]='wfHits';
$skip_tables[]='wp_wfFileMods';
$skip_tables[]='tts_trafficstats';
$skip_tables[]='tts_referrer_stats';
$skip_tables[]='dmsguestbook';
$skip_tables[]='relevanssi';
$skip_tables[]='wfFileMods';
$skip_tables[]='learnpress_sessions';
$skip_tables[]='icl_string_pages';
$skip_tables[]='webarx_event_log';
$skip_tables[]='duplicator_packages';
$skip_tables[]='wsal_metadata';
$skip_tables[]='wsal_occurrences';
$skip_tables[]='simple_history_contexts';
$skip_tables[]='simple_history';
$skip_tables[]='wffilemods';
$skip_tables[]='statpress';
//
if(in_array(substr($table_name, strlen($this->temp_new_prefix)),$skip_tables))
{
$skip_table=true;
}
else
{
$skip_table=false;
}
return $skip_table;
}
public function skip_rows($skip_rows,$table_name,$column_name)
{
$row['table_name']='posts';
$row['column_name']='guid';
$rows[]=$row;
foreach ($rows as $row)
{
if($column_name==$row['column_name']&&$table_name==$this->temp_new_prefix.$row['table_name'])
{
$skip_rows=true;
break;
}
}
return $skip_rows;
}
public function skip_create_tables($skip_table,$table_name,$option)
{
if(isset($option['exclude_tables']))
{
$table_name=$this->old_prefix.substr($table_name,strlen($this->temp_new_prefix));
if(array_key_exists($table_name,$option['exclude_tables']))
{
$skip_table=true;
}
}
return $skip_table;
}
public function check_max_allow_packet_ex()
{
$max_all_packet_warning=false;
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-restore-db-method-2.php';
$this->db_method=new WPvivid_Restore_DB_Method_2();
$this->db_method->set_skip_query(0);
$ret=$this->db_method->connect_db();
if($ret['result']==WPVIVID_SUCCESS)
{
$max_allowed_packet = $this->db_method->query("SELECT @@session.max_allowed_packet;",ARRAY_N);
if($max_allowed_packet)
{
if(is_array($max_allowed_packet)&&isset($max_allowed_packet[0])&&isset($max_allowed_packet[0][0]))
{
if($max_allowed_packet[0][0]<16777216){
$max_all_packet_warning = 'max_allowed_packet = '.size_format($max_allowed_packet[0][0]).' is too small. The recommended value is 16M or higher. Too small value could lead to a failure when importing a larger database.';
}
}
}
}
return $max_all_packet_warning;
}
private function execute_sql($query,$sub_task)
{
$sub_task['exec_sql']['last_query']=$query;
//$this->update_sub_task($sub_task);
return $this->db_method->execute_sql($query);
}
public function finish_restore_db($sql_files,$local_path,$sub_task)
{
$this->init_db($sub_task);
$option_table = $this->temp_new_prefix.'options';
global $wpdb;
$db_siteurl = false;
$siteurl_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $option_table WHERE option_name = %s", 'siteurl' ) );
foreach ( $siteurl_sql as $siteurl )
{
$db_siteurl = untrailingslashit($siteurl->option_value);
}
if($db_siteurl !== false)
{
$update_query ='UPDATE '.$option_table.' SET option_value="'.$this->new_site_url.'" WHERE option_name="siteurl";';
$this->log->WriteLog($update_query, 'notice');
$this->log->WriteLog('update query len:'.strlen($update_query), 'notice');
$this->execute_sql($update_query,$sub_task);
}
else
{
$insert_query = $wpdb->prepare("INSERT INTO {$option_table} (option_name,option_value) VALUES ('siteurl',%s)", $this->new_site_url);
$this->log->WriteLog('siteurl not found, insert: '.$insert_query, 'notice');
if ($wpdb->get_results($insert_query) === false) {
$error = $wpdb->last_error;
$this->log->WriteLog('insert siteurl failed: '.$error, 'notice');
}
else
{
$this->log->WriteLog('insert siteurl success', 'notice');
}
}
$db_home = false;
$home_sql = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $option_table WHERE option_name = %s", 'home' ) );
foreach ( $home_sql as $home )
{
$db_home = untrailingslashit($home->option_value);
}
if($db_home !== false)
{
$update_query ='UPDATE '.$option_table.' SET option_value="'.$this->new_home_url.'" WHERE option_name="home";';
$this->log->WriteLog($update_query, 'notice');
$this->log->WriteLog('update query len:'.strlen($update_query), 'notice');
$this->execute_sql($update_query,$sub_task);
}
else
{
$insert_query = $wpdb->prepare("INSERT INTO {$option_table} (option_name,option_value) VALUES ('home',%s)", $this->new_home_url);
$this->log->WriteLog('home not found, insert: '.$insert_query, 'notice');
if ($wpdb->get_results($insert_query) === false) {
$error = $wpdb->last_error;
$this->log->WriteLog('insert home failed: '.$error, 'notice');
}
else
{
$this->log->WriteLog('insert home success', 'notice');
}
}
$sub_task['finished']=1;
foreach ($sql_files as $sql_file_name=>$sql_file)
{
$tmp_sql_file=$local_path.$sql_file_name;
if(file_exists($tmp_sql_file))
{
@wp_delete_file($tmp_sql_file);
}
}
$ret['result']='success';
$ret['sub_task']=$sub_task;
return $ret;
}
public function rename_db($sub_task)
{
global $wpdb;
//restore_db_reset
$wpdb->query('SET FOREIGN_KEY_CHECKS=0;');
$restore_task=get_option('wpvivid_restore_task',array());
$restore_detail_options=$restore_task['restore_detail_options'];
$restore_db_reset = $restore_detail_options['restore_db_reset'];
$this->log->WriteLog('Restore db success,now start rename temp table name prefix to new site prefix.','notice');
$temp_new_prefix='tmp'.$sub_task['exec_sql']['db_id'].'_';
$tables = $wpdb->get_results('SHOW TABLE STATUS');
$new_tables = array();
if (is_array($tables))
{
foreach ($tables as $table)
{
if (0 !== stripos($table->Name, $temp_new_prefix))
{
continue;
}
if (empty($table->Engine))
{
continue;
}
$new_tables[] = $table->Name;
}
}
else
{
$ret['result']='failed';
$ret['error']='Getting temp tables failed.';
return $ret;
}
if($restore_db_reset)
{
foreach ($tables as $table)
{
if (0 !== stripos($table->Name, $wpdb->prefix))
{
continue;
}
if (empty($table->Engine))
{
continue;
}
$wpdb->query('DROP TABLE IF EXISTS ' . $table->Name);
$this->log->WriteLog('DROP TABLE IF EXISTS ' . $table->Name,'notice');
}
}
else
{
foreach ($new_tables as $table)
{
$new_table=$this->str_replace_first($temp_new_prefix,$wpdb->prefix,$table);
if($wpdb->query('DROP TABLE IF EXISTS ' . $new_table)===false)
{
$error='Failed to drop table. Error:'.$wpdb->last_error;
$this->log->WriteLog($error,'error');
$ret['result']='failed';
$ret['error']=$error;
return $ret;
}
else
{
$this->log->WriteLog('DROP TABLE IF EXISTS ' . $new_table,'notice');
}
}
}
foreach ($new_tables as $table)
{
$new_table=$this->str_replace_first($temp_new_prefix,$wpdb->prefix,$table);
if($wpdb->query("RENAME TABLE {$table} TO {$new_table}")===false)
{
$error='Failed to rename table. Error:'.$wpdb->last_error;
$this->log->WriteLog($error,'error');
$ret['result']='failed';
$ret['error']=$error;
return $ret;
}
else
{
$this->log->WriteLog("RENAME TABLE {$table} TO {$new_table}",'notice');
}
}
wp_cache_flush();
update_option('wpvivid_restore_task',$restore_task,'no');
$this->log->WriteLog('Replacing table prefix succeeded.','notice');
//$ret=$this->test_access();
$ret['result']='success';
return $ret;
}
public function test_access()
{
$url=get_home_url();
$options=array();
$options['timeout']=15;
$request=wp_remote_request($url,$options);
if(!is_wp_error($request) && ($request['response']['code'] == 200))
{
$ret['result']='success';
}
else
{
$ret['result']='failed';
if ( is_wp_error( $request ) )
{
$error_message = $request->get_error_message();
$ret['error']="Sorry, something went wrong: $error_message. Please try again later or contact us.";
}
else if($request['response']['code'] != 200)
{
$ret['error']=$request['response']['message'];
}
else {
$ret['error']=$request;
}
}
return $ret;
}
public function is_og_table($table_name)
{
$table_prefix=substr($table_name,0,strlen($this->old_prefix));
if($table_prefix==$this->old_prefix)
{
return true;
}
else
{
return false;
}
}
public function is_mu_single_og_table($table_name)
{
$table_prefix=substr($table_name,0,strlen($this->old_prefix));
if($table_prefix==$this->old_prefix)
{
return true;
}
else
{
$table_prefix=substr($table_name,0,strlen($this->old_base_prefix));
if($table_prefix==$this->old_base_prefix)
{
return true;
}
else
{
return false;
}
}
}
} includes/new_backup/class-wpvivid-backup2.php 0000644 00000226076 15132770567 0015353 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Backup_2
{
public $end_shutdown_function;
public $current_task_id;
public $task;
public function __construct()
{
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-backup-task_2.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-mysqldump2.php';
include_once WPVIVID_PLUGIN_DIR . '/includes/new_backup/class-wpvivid-zip.php';
add_action('wp_ajax_wpvivid_prepare_backup_2',array( $this,'prepare_backup_2'));
add_action('wp_ajax_wpvivid_delete_ready_task_2',array($this,'delete_ready_task_2'));
add_action('wp_ajax_wpvivid_backup_now_2',array( $this,'backup_now_2'));
add_action('wp_ajax_wpvivid_list_tasks_2',array( $this,'list_tasks'));
add_action('wp_ajax_wpvivid_shutdown_backup',array( $this,'shutdown_backup'));
add_action('wp_ajax_wpvivid_delete_task_2',array( $this,'delete_task'));
add_action('wpvivid_task_monitor_event_2',array( $this,'task_monitor'));
add_action('wpvivid_backup_2_schedule_event',array( $this,'backup_schedule'));
//
add_action('wpvivid_handle_backup_2_succeed',array($this,'handle_backup_succeed'),10);
add_action('wpvivid_handle_backup_2_failed',array($this,'handle_backup_failed'),10);
//
add_action('wpvivid_clean_backup_2_data_event',array($this,'clean_backup_data_event'));
//
add_action(WPVIVID_MAIN_SCHEDULE_EVENT,array( $this,'main_schedule'));
//
add_filter('wpvivid_exclude_plugins',array($this,'exclude_plugins'),10);
//migrate
add_action('wp_ajax_wpvivid_send_backup_to_site_2',array( $this,'send_backup_to_site'));
add_action('wp_ajax_wpvivid_migrate_now_2',array( $this,'migrate_now'));
//
add_filter('wpvivid_default_exclude_folders' ,array($this, 'default_exclude_folders'));
}
public function exclude_plugins($exclude_plugins)
{
$exclude_plugins[]='wpvivid-backuprestore';
//$exclude_plugins[]='wp-cerber';
$exclude_plugins[]='.';
$exclude_plugins[]='wpvivid-backup-pro';
$exclude_plugins[]='wpvividdashboard';
//$exclude_plugins[]='wpvivid-staging';
return $exclude_plugins;
}
public function prepare_backup_2()
{
global $wpvivid_plugin;
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
if(isset($_POST['backup'])&&!empty($_POST['backup']))
{
$json = sanitize_text_field($_POST['backup']);
$json = stripslashes($json);
$backup_options = json_decode($json, true);
if (is_null($backup_options))
{
die();
}
if(!isset($backup_options['type']))
{
$backup_options['type']='Manual';
}
if(!isset($backup_options['backup_files'])||empty($backup_options['backup_files']))
{
$ret['result']='failed';
$ret['error']=__('A backup type is required.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
if(!isset($backup_options['local'])||!isset($backup_options['remote']))
{
$ret['result']='failed';
$ret['error']=__('Choose at least one storage location for backups.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
if(empty($backup_options['local']) && empty($backup_options['remote']))
{
$ret['result']='failed';
$ret['error']=__('Choose at least one storage location for backups.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
if ($backup_options['remote'] === '1')
{
$remote_storage = WPvivid_Setting::get_remote_options();
if ($remote_storage == false)
{
$ret['result']='failed';
$ret['error'] = __('There is no default remote storage configured. Please set it up first.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
}
if(apply_filters('wpvivid_need_clean_oldest_backup',true,$backup_options))
{
$wpvivid_plugin->clean_oldest_backup();
}
do_action('wpvivid_clean_oldest_backup',$backup_options);
if($this->is_tasks_backup_running())
{
$ret['result']='failed';
$ret['error']=__('A task is already running. Please wait until the running task is complete, and try again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$settings=$this->get_backup_settings($backup_options);
$backup=new WPvivid_Backup_Task_2();
$ret=$backup->new_backup_task($backup_options,$settings);
if($ret['result']=='success')
{
$html = '';
$html = apply_filters('wpvivid_add_backup_list', $html);
$ret['html'] = $html;
}
echo wp_json_encode($ret);
die();
}
}
catch (Exception $error)
{
$ret['result']='failed';
$message = 'An exception has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
$ret['error'] = $message;
$id=uniqid('wpvivid-');
$log_file_name=$id.'_backup';
$log=new WPvivid_Log();
$log->CreateLogFile($log_file_name,'no_folder','backup');
$log->WriteLog($message,'notice');
$log->CloseFile();
WPvivid_error_log::create_error_log($log->log_file);
error_log($message);
echo wp_json_encode($ret);
die();
}
}
public function delete_ready_task_2()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$tasks = get_option('wpvivid_task_list', array());
$delete_ids=array();
foreach ($tasks as $task)
{
if($task['status']['str']=='ready')
{
$delete_ids[]=$task['id'];
}
}
if(!empty($delete_ids))
{
foreach ($delete_ids as $id)
{
unset($tasks[$id]);
}
update_option('wpvivid_task_list',$tasks,'no');
}
$ret['result'] = 'success';
echo wp_json_encode($ret);
die();
}
public function is_tasks_backup_running($task_id='')
{
$tasks = get_option('wpvivid_task_list', array());
if(empty($task_id))
{
foreach ($tasks as $task)
{
if ($task['status']['str']=='running'||$task['status']['str']=='no_responds')
{
return true;
}
}
return false;
}
else
{
if(isset($tasks[$task_id]))
{
$task=$tasks[$task_id];
if ($task['status']['str']=='running'||$task['status']['str']=='no_responds')
{
return true;
}
}
return false;
}
}
public function get_backup_settings($backup_options)
{
$common_setting=get_option('wpvivid_common_setting',array());
$settings['db_connect_method']=isset($common_setting['db_connect_method'])?$common_setting['db_connect_method']:'wpdb';
$settings['memory_limit']=isset($common_setting['memory_limit'])?$common_setting['memory_limit']:'512M';
$settings['max_execution_time']=isset($common_setting['max_execution_time'])?$common_setting['max_execution_time']:900;
$settings['compress_file_use_cache']=isset($common_setting['compress_file_use_cache'])?$common_setting['compress_file_use_cache']:false;
$settings['compress_file_count']=isset($common_setting['compress_file_count'])?$common_setting['compress_file_count']:500;
$settings['max_file_size']=isset($common_setting['max_file_size'])?$common_setting['max_file_size']:200;
$settings['max_sql_file_size']=isset($common_setting['max_sql_file_size'])?$common_setting['max_sql_file_size']:200;
$settings['exclude_file_size']=isset($common_setting['exclude_file_size'])?$common_setting['exclude_file_size']:0;
$settings['max_resume_count']=isset($common_setting['max_resume_count'])?$common_setting['max_resume_count']:6;
$settings['zip_method']=isset($common_setting['zip_method'])?$common_setting['zip_method']:6;
$settings['is_merge']=isset($common_setting['ismerge'])?$common_setting['ismerge']:true;
$settings['save_local']=isset($common_setting['retain_local'])?$common_setting['retain_local']:false;
$settings['backup_symlink_folder']=isset($common_setting['backup_symlink_folder'])?$common_setting['backup_symlink_folder']:false;
if(isset($common_setting['zip_method']))
{
if($common_setting['zip_method'] === 'ziparchive')
{
$settings['zip_method']= 'ziparchive';
}
else{
$settings['zip_method']= 'pclzip';
}
}
else
{
if(class_exists('ZipArchive'))
{
if(method_exists('ZipArchive', 'addFile'))
{
$settings['zip_method']= 'ziparchive';
}
else
{
$settings['zip_method']= 'pclzip';
}
}
else
{
$settings['zip_method']= 'pclzip';
}
}
return $settings;
}
public function has_backup_task_noreponse()
{
$tasks = get_option('wpvivid_task_list', array());
foreach ($tasks as $task)
{
$current_time=time();
$run_time=$task['status']['run_time'];
$noreponse_time=$current_time-$run_time;
if($noreponse_time >= 3600)
{
if ($task['status']['str']=='running'||$task['status']['str']=='no_responds'||$task['status']['str']=='wait_resume')
{
unset($tasks[$task['id']]);
}
}
}
update_option('wpvivid_task_list', $tasks, 'no');
}
public function main_schedule($schedule_id='')
{
$this->has_backup_task_noreponse();
global $wpvivid_plugin;
do_action('wpvivid_set_current_schedule_id', $schedule_id);
$schedule_options=WPvivid_Schedule::get_schedule($schedule_id);
if(empty($schedule_options))
{
die();
}
$schedule_options['backup']['local'] = strval($schedule_options['backup']['local']);
$schedule_options['backup']['remote'] = strval($schedule_options['backup']['remote']);
$schedule_options['backup']['ismerge'] = strval($schedule_options['backup']['ismerge']);
$schedule_options['backup']['lock'] = strval($schedule_options['backup']['lock']);
if(!isset($schedule_options['backup']['type']))
{
$schedule_options['backup']['type']='Cron';
$schedule_options['backup']['action']='backup';
}
$ret = $this->pre_new_backup($schedule_options['backup']);
if ($ret['result'] == 'success')
{
$wpvivid_plugin->flush($ret['task_id']);
//start backup task.
$task_msg = WPvivid_taskmanager::get_task($ret['task_id']);
$wpvivid_plugin->update_last_backup_time($task_msg);
$this->backup_schedule($ret['task_id']);
}
$this->end_shutdown_function=true;
die();
}
public function pre_new_backup($backup_options)
{
global $wpvivid_plugin;
if(apply_filters('wpvivid_need_clean_oldest_backup',true,$backup_options))
{
$wpvivid_plugin->clean_oldest_backup();
}
do_action('wpvivid_clean_oldest_backup',$backup_options);
if($this->is_tasks_backup_running())
{
$ret['result']='failed';
$ret['error']=__('We detected that there is already a running backup task. Please wait until it completes then try again.', 'wpvivid');
return $ret;
}
$settings=$this->get_backup_settings($backup_options);
$backup=new WPvivid_Backup_Task_2();
$ret=$backup->new_backup_task($backup_options,$settings);
return $ret;
}
public function backup_now_2()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
register_shutdown_function(array($this,'deal_backup_shutdown_error'));
$this->end_shutdown_function=false;
$task_id = sanitize_key($_POST['task_id']);
$this->current_task_id=$task_id;
global $wpvivid_plugin;
if ($this->is_tasks_backup_running($task_id))
{
$ret['result'] = 'failed';
$ret['error'] = __('We detected that there is already a running backup task. Please wait until it completes then try again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
try
{
$this->update_backup_task_status($task_id,true,'running');
$wpvivid_plugin->flush($task_id);
$this->add_monitor_event($task_id);
$this->task=new WPvivid_Backup_Task_2($task_id);
$this->task->set_memory_limit();
$this->task->set_time_limit();
$wpvivid_plugin->wpvivid_log->OpenLogFile($this->task->task['options']['log_file_name']);
$wpvivid_plugin->wpvivid_log->WriteLog('Start backing up.','notice');
$wpvivid_plugin->wpvivid_log->WriteLogHander();
if(!$this->task->is_backup_finished())
{
$ret=$this->backup();
$this->task->clear_cache();
if($ret['result']!='success')
{
$wpvivid_plugin->wpvivid_log->WriteLog('Backup the file ends with an error '. $ret['error'],'error');
$this->task->update_backup_task_status(false,'error',false,false,$ret['error']);
do_action('wpvivid_handle_backup_2_failed', $task_id);
$this->end_shutdown_function=true;
$this->clear_monitor_schedule($task_id);
die();
}
}
if($this->task->need_upload())
{
$ret=$this->upload($task_id);
if($ret['result'] == WPVIVID_SUCCESS)
{
do_action('wpvivid_handle_backup_2_succeed',$task_id);
$this->update_backup_task_status($task_id,false,'completed');
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Uploading the file ends with an error '. $ret['error'], 'error');
do_action('wpvivid_handle_backup_2_failed',$task_id);
}
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Backup completed.','notice');
do_action('wpvivid_handle_backup_2_succeed', $task_id);
$this->update_backup_task_status($task_id,false,'completed');
}
$this->clear_monitor_schedule($task_id);
}
catch (Exception $error)
{
//catch error and stop task recording history
$message = 'An exception has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
error_log($message);
WPvivid_taskmanager::update_backup_task_status($task_id,false,'error',false,false,$message);
$wpvivid_plugin->wpvivid_log->WriteLog($message,'error');
do_action('wpvivid_handle_backup_2_failed',$task_id);
$this->end_shutdown_function=true;
die();
}
$this->end_shutdown_function=true;
die();
}
public function backup_schedule($task_id)
{
$this->current_task_id=$task_id;
if(empty($task_id))
{
die();
}
if ($this->is_tasks_backup_running($task_id))
{
$ret['result'] = 'failed';
$ret['error'] = __('We detected that there is already a running backup task. Please wait until it completes then try again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$this->end_shutdown_function=false;
register_shutdown_function(array($this,'deal_backup_shutdown_error'));
global $wpvivid_plugin;
try
{
WPvivid_taskmanager::update_backup_task_status($task_id,true,'running');
$wpvivid_plugin->flush($task_id);
$this->add_monitor_event($task_id);
$this->task=new WPvivid_Backup_Task_2($task_id);
$this->task->set_memory_limit();
$this->task->set_time_limit();
$this->task->update_schedule_last_backup_time();
$wpvivid_plugin->wpvivid_log->OpenLogFile(WPvivid_taskmanager::get_task_options($task_id,'log_file_name'));
$wpvivid_plugin->wpvivid_log->WriteLog('Start backing up.','notice');
$wpvivid_plugin->wpvivid_log->WriteLogHander();
if(!$this->task->is_backup_finished())
{
$ret=$this->backup();
$this->task->clear_cache();
if($ret['result']!='success')
{
$wpvivid_plugin->wpvivid_log->WriteLog('Backup the file ends with an error '. $ret['error'],'error');
$this->task->update_backup_task_status(false,'error',false,false,$ret['error']);
do_action('wpvivid_handle_backup_2_failed', $task_id);
$this->end_shutdown_function=true;
$this->clear_monitor_schedule($task_id);
die();
}
}
if($this->task->need_upload())
{
$ret=$this->upload($task_id);
if($ret['result'] == WPVIVID_SUCCESS)
{
do_action('wpvivid_handle_backup_2_succeed',$task_id);
WPvivid_taskmanager::update_backup_task_status($task_id,false,'completed');
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Uploading the file ends with an error '. $ret['error'], 'error');
do_action('wpvivid_handle_backup_2_failed',$task_id);
}
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Backup completed.','notice');
do_action('wpvivid_handle_backup_2_succeed', $task_id);
WPvivid_taskmanager::update_backup_task_status($task_id,false,'completed');
}
$this->clear_monitor_schedule($task_id);
}
catch (Exception $error)
{
//catch error and stop task recording history
$message = 'An exception has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
error_log($message);
WPvivid_taskmanager::update_backup_task_status($task_id,false,'error',false,false,$message);
$wpvivid_plugin->wpvivid_log->WriteLog($message,'error');
do_action('wpvivid_handle_backup_2_failed',$task_id);
$this->end_shutdown_function=true;
die();
}
$this->end_shutdown_function=true;
die();
}
public function backup()
{
$ret['result']='success';
$this->task->wpvivid_check_add_litespeed_server();
while (!$this->task->is_backup_finished())
{
if($this->task->check_cancel_backup())
{
$this->end_shutdown_function=true;
die();
}
$job=$this->task->get_next_job();
if($job===false)
break;
$this->task->set_time_limit();
$ret=$this->task->do_backup_job($job);
if($ret['result']!='success')
{
break;
}
}
if($ret['result']==='success')
{
$check_res = apply_filters('wpvivid_check_backup_completeness', true, $this->task->task_id);
if(!$check_res){
$ret['result'] = 'failed';
$ret['error'] = 'We have detected that this backup is either corrupted or incomplete. Please make sure your server disk space is sufficient then create a new backup. In order to successfully back up/restore a website, the amount of free server disk space needs to be at least twice the size of the website';
}
}
return $ret;
}
public function upload($task_id)
{
global $wpvivid_plugin;
$files=$this->task->get_backup_files();
$wpvivid_plugin->wpvivid_log->WriteLog('files: '.wp_json_encode($files),'notice');
$remote_options=$this->task->get_remote_options();
$remote_option=array_shift($remote_options);
if(!class_exists('WPvivid_Remote_collection'))
{
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-remote-collection.php';
$wpvivid_plugin->remote_collection=new WPvivid_Remote_collection();
}
$remote=$wpvivid_plugin->remote_collection->get_remote($remote_option);
try
{
$result=$remote->upload($task_id,$files,array($this,'upload_callback'));
if($result['result']=='success')
{
$this->update_backup_task_status($task_id,false,'running',false,0);
$wpvivid_plugin->wpvivid_log->WriteLog('Finish upload to '.$remote_option['type'],'notice');
if($remote_option['type']!=='send_to_site')
{
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',$remote_option['id'],WPVIVID_UPLOAD_SUCCESS,'Finish upload to'.$remote_option['type']);
}
WPvivid_taskmanager::update_backup_main_task_progress($task_id,'upload',100,1);
WPvivid_taskmanager::update_backup_task_status($task_id,false,'completed');
return array('result' => 'success');
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Finish upload to '.$remote_option['type'].' error:'.$result['error'],'notice');
if($remote_option['type']!=='send_to_site')
{
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',$remote_option['id'],WPVIVID_UPLOAD_FAILED,'Finish upload to'.$remote_option['type']);
}
$remote ->cleanup($files);
$last_error=$result['error'];
WPvivid_taskmanager::update_backup_task_status($task_id,false,'error',false,false,$last_error);
return array('result' => 'failed' , 'error' => $last_error);
}
}
catch (Exception $e)
{
//catch error and stop task recording history
$wpvivid_plugin->wpvivid_log->WriteLog('Finish upload to '.$remote_option['type'].' error:'.$e->getMessage(),'notice');
WPvivid_taskmanager::update_backup_sub_task_progress($task_id,'upload',$remote_option['id'],WPVIVID_UPLOAD_FAILED,'Finish upload to'.$remote_option['type']);
$last_error=$e->getMessage();
WPvivid_taskmanager::update_backup_task_status($task_id,false,'error',false,false,$last_error);
return array('result' => 'failed' , 'error' => $last_error);
}
}
public function upload_callback($offset,$current_name,$current_size,$last_time,$last_size)
{
$job_data=array();
$upload_data=array();
$upload_data['offset']=$offset;
$upload_data['current_name']=$current_name;
$upload_data['current_size']=$current_size;
$upload_data['last_time']=$last_time;
$upload_data['last_size']=$last_size;
$upload_data['descript']='Uploading '.$current_name;
$v =( $offset - $last_size ) / (time() - $last_time);
$v /= 1000;
$v=round($v,2);
global $wpvivid_plugin;
$this->task->check_cancel_backup();
$message='Uploading '.$current_name.' Total size: '.size_format($current_size,2).' Uploaded: '.size_format($offset,2).' speed:'.$v.'kb/s';
$wpvivid_plugin->wpvivid_log->WriteLog($message,'notice');
$progress=intval(($offset/$current_size)*100);
WPvivid_taskmanager::update_backup_main_task_progress($this->current_task_id,'upload',$progress,0);
WPvivid_taskmanager::update_backup_sub_task_progress($this->current_task_id,'upload','',WPVIVID_UPLOAD_UNDO,$message, $job_data, $upload_data);
}
public function handle_backup_succeed($task_id)
{
$task= new WPvivid_Backup_Task_2($task_id);
$task->update_end_time();
if($task->task['type']=='Migrate')
{
$backup_success_count = WPvivid_Setting::get_option('wpvivid_transfer_success_count');
if (empty($backup_success_count))
{
$backup_success_count = 0;
}
$backup_success_count++;
WPvivid_Setting::update_option('wpvivid_transfer_success_count', $backup_success_count);
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->WriteLog('Upload finished. Delete task '.$task->task['id'], 'notice');
$task->clean_local_files();
$task->wpvivid_check_clear_litespeed_rule();
$this->clear_monitor_schedule($task_id);
}
else
{
$backup=WPvivid_Backuplist::get_backup_by_id($task_id);
if($backup!==false)
{
$task->add_exist_backup($task_id);
}
else
{
$task->add_new_backup();
}
if($task->need_upload())
{
if(!$task->is_save_local())
{
$task->clean_local_files();
}
$remote_options=$this->task->get_remote_options();
WPvivid_Backuplist::update_backup($task_id,'remote', $remote_options);
}
set_time_limit(120);
$backup_ids=array();
$backup_ids=apply_filters('wpvivid_get_oldest_backup_ids',$backup_ids,true);
global $wpvivid_plugin;
if(!empty($backup_ids))
{
foreach ($backup_ids as $backup_id)
{
$wpvivid_plugin->delete_backup_by_id($backup_id);
}
}
$backup_success_count = WPvivid_Setting::get_option('wpvivid_backup_success_count');
if (empty($backup_success_count))
{
$backup_success_count = 0;
}
$backup_success_count++;
WPvivid_Setting::update_option('wpvivid_backup_success_count', $backup_success_count);
$wpvivid_plugin->wpvivid_analysis_backup($task->task);
$task_msg = WPvivid_taskmanager::get_task($task_id);
$wpvivid_plugin->update_last_backup_task($task_msg);
$task_msg = WPvivid_taskmanager::get_task($task_id);
update_option('wpvivid_last_msg',$task_msg,'no');
$this->clear_monitor_schedule($task_id);
WPvivid_taskmanager::mark_task($task_id);
if(!class_exists('WPvivid_mail_report'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-mail-report.php';
WPvivid_mail_report::send_report_mail_ex($task_id);
$task->wpvivid_check_clear_litespeed_rule();
}
}
public function handle_backup_failed($task_id)
{
global $wpvivid_plugin;
$task = WPvivid_taskmanager::get_task($task_id);
if($task['type']=='Migrate')
{
$backup_error_array = WPvivid_Setting::get_option('wpvivid_transfer_error_array');
if (empty($backup_error_array)) {
$backup_error_array = array();
}
if (!array_key_exists($task['id'], $backup_error_array['bu_error']))
{
$backup_error_array['bu_error']['task_id'] = $task['id'];
$backup_error_array['bu_error']['error_msg'] = $task['status']['error'];
WPvivid_Setting::update_option('wpvivid_transfer_error_array', $backup_error_array);
}
$new_task= new WPvivid_Backup_Task_2($task_id);
$new_task->update_end_time();
$new_task->clean_backup();
$wpvivid_plugin->wpvivid_log->WriteLog('Upload failed. Delete task '.$task['id'], 'notice');
$this->clear_monitor_schedule($task_id);
$new_task->wpvivid_check_clear_litespeed_rule();
}
else
{
$backup_error_array = WPvivid_Setting::get_option('wpvivid_backup_error_array');
if (!isset($backup_error_array) || empty($backup_error_array))
{
$backup_error_array = array();
$backup_error_array['bu_error']['task_id'] = '';
$backup_error_array['bu_error']['error_msg'] = '';
}
if (!array_key_exists($task_id, $backup_error_array['bu_error']))
{
$backup_error_array['bu_error']['task_id'] = $task_id;
$backup_error_array['bu_error']['error_msg'] = 'Unknown error.';
$general_setting=WPvivid_Setting::get_setting(true, "");
$need_notice = false;
if(!isset($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload'])){
$need_notice = true;
}
else{
if($general_setting['options']['wpvivid_compress_setting']['subpackage_plugin_upload']){
$need_notice = false;
}
else{
$need_notice = true;
}
}
if($need_notice)
{
$notice_msg = 'Backup error: '.$task['status']['error'].', task id: '.$task['id'];
$backup_error_array['bu_error']['error_msg']='<div class="notice notice-error inline"><p>'.$notice_msg.', Please switch to <a href="#" onclick="wpvivid_click_switch_page(\'wrap\', \'wpvivid_tab_debug\', true);">Website Info</a> page to send us the debug information. </p></div>';
}
else{
$notice_msg = 'Backup error: ' . $task['status']['error'] . ', task id: ' . $task['id'];
$backup_error_array['bu_error']['error_msg'] = '<div class="notice notice-error inline"><p>' . $notice_msg . ', Please switch to <a href="#" onclick="wpvivid_click_switch_page(\'wrap\', \'wpvivid_tab_debug\', true);">Website Info</a> page to send us the debug information. </p></div>';
}
}
WPvivid_Setting::update_option('wpvivid_backup_error_array', $backup_error_array);
$task_msg = WPvivid_taskmanager::get_task($task_id);
$wpvivid_plugin->update_last_backup_task($task_msg);
$task= new WPvivid_Backup_Task_2($task_id);
$task->update_end_time();
$this->add_clean_backup_data_event($task_id);
$task_msg = WPvivid_taskmanager::get_task($task_id);
update_option('wpvivid_last_msg',$task_msg,'no');
global $wpvivid_plugin;
if($wpvivid_plugin->wpvivid_log)
{
$wpvivid_plugin->wpvivid_log->WriteLog($task_msg['status']['error'],'error');
$wpvivid_plugin->wpvivid_log->CloseFile();
WPvivid_error_log::create_error_log($wpvivid_plugin->wpvivid_log->log_file);
}
$this->clear_monitor_schedule($task_id);
if(!class_exists('WPvivid_mail_report'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-mail-report.php';
WPvivid_mail_report::send_report_mail_ex($task_id);
WPvivid_taskmanager::mark_task($task_id);
$task->wpvivid_check_clear_litespeed_rule();
}
}
public function deal_backup_shutdown_error()
{
if($this->end_shutdown_function===false)
{
global $wpvivid_plugin;
$options = get_option('wpvivid_task_list',array());
if(!isset($options[$this->current_task_id]))
{
die();
}
$error = error_get_last();
$resume_backup=false;
$memory_limit=false;
$max_execution_time=false;
if (!is_null($error))
{
if (empty($error) || !in_array($error['type'], array(E_ERROR,E_RECOVERABLE_ERROR,E_CORE_ERROR,E_COMPILE_ERROR), true))
{
$wpvivid_plugin->wpvivid_log->WriteLog('In shutdown function last message type:'.$error['type'].' str:'.$error['message'],'notice');
}
if(preg_match('/Allowed memory size of.*$/', $error['message']))
{
$resume_backup=true;
$memory_limit=true;
}
else if(preg_match('/Maximum execution time of.*$/', $error['message']))
{
$resume_backup=true;
$max_execution_time=true;
}
}
$task= new WPvivid_Backup_Task_2($this->current_task_id);
$status=$task->get_status();
if($memory_limit===true)
{
if(!$task->check_memory_limit())
{
$wpvivid_plugin->wpvivid_log->WriteLog('Backup the file ends with an error '. $error['message'],'error');
$task->update_backup_task_status(false,'error',false,$status['resume_count'],$error['message']);
do_action('wpvivid_handle_backup_2_failed', $this->current_task_id);
$resume_backup=false;
}
}
if($max_execution_time===true)
{
$task->check_execution_time();
}
if($status['str']!='completed')
{
$max_resume_count=$task->get_max_resume_count();
$status=$task->get_status();
$status['resume_count']++;
if($status['resume_count']>$max_resume_count)
{
$message=__('Too many resumption attempts.', 'wpvivid-backuprestore');
$wpvivid_plugin->wpvivid_log->WriteLog('Backup the file ends with an error '. $message,'error');
$task->update_backup_task_status(false,'error',false,$status['resume_count'],$message);
if($resume_backup)
$task->check_timeout_backup_failed();
do_action('wpvivid_handle_backup_2_failed', $this->current_task_id);
}
else
{
$message=__('Task timed out.', 'wpvivid-backuprestore');
$wpvivid_plugin->wpvivid_log->WriteLog('Task timed out.','error');
$timestamp = wp_next_scheduled('wpvivid_backup_2_schedule_event',array($this->current_task_id));
if($timestamp===false)
{
$task->update_backup_task_status(false,'wait_resume',false,$status['resume_count']);
if($this->add_resume_event($this->current_task_id)===false)
{
$task->update_backup_task_status(false,'error',false,$status['resume_count'],$message);
$wpvivid_plugin->wpvivid_log->WriteLog('Backup the file ends with an error '. $message,'error');
if($resume_backup)
$task->check_timeout_backup_failed();
do_action('wpvivid_handle_backup_2_failed', $this->current_task_id);
}
}
}
}
}
die();
}
public function list_tasks()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
try
{
$ret = $this->_list_tasks();
echo wp_json_encode($ret);
}
catch (Exception $error)
{
$message = 'An exception has occurred. class: '.get_class($error).';msg: '.$error->getMessage().';code: '.$error->getCode().';line: '.$error->getLine().';in_file: '.$error->getFile().';';
error_log($message);
echo wp_json_encode(array('result'=>'failed','error'=>$message));
die();
}
die();
}
public function _list_tasks_ex()
{
if($this->wpvivid_check_litespeed_server() && $this->wpvivid_check_litespeed_cache_plugin())
{
wp_cache_delete('wpvivid_task_list', 'options');
}
$tasks = get_option('wpvivid_task_list', array());
$ret['result']='success';
$ret['progress_html']=false;
foreach ($tasks as $task)
{
if(!isset($task['id']))
{
continue;
}
$ret['task_id']=$task['id'];
$ret['need_update']=true;
if(isset($task['options']['export']))
{
$ret['export'] =$task['options']['export'];
}
else
{
$ret['export'] ='';
}
$backup_task=new WPvivid_Backup_Task_2($task['id']);
$info=$backup_task->get_backup_task_info();
if($info['status']['str']=='ready'||$info['status']['str']=='running'||$info['status']['str']=='wait_resume'||$info['status']['str']=='no_responds')
{
$ret['running_backup_taskid']=$task['id'];
if($info['status']['str']=='wait_resume')
{
$ret['wait_resume']=true;
$ret['next_resume_time']=$info['data']['next_resume_time'];
}
if($info['status']['str']=='no_responds')
{
$ret['task_no_response']=true;
}
$ret['progress_html'] = '<div class="action-progress-bar" id="wpvivid_action_progress_bar">
<div class="action-progress-bar-percent" id="wpvivid_action_progress_bar_percent" style="height:24px;width:'.$info['task_info']['backup_percent'].'"></div>
</div>
<div id="wpvivid_estimate_upload_info" style="float: left;">
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Total Size:', 'wpvivid-backuprestore') . '</span><span>'.$info['task_info']['total'].'</span></div>
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Uploaded:', 'wpvivid-backuprestore') . '</span><span>'.$info['task_info']['upload'].'</span></div>
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Speed:', 'wpvivid-backuprestore') . '</span><span>'.$info['task_info']['speed'].'</span></div>
</div>
<div style="float: left;">
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Network Connection:', 'wpvivid-backuprestore') . '</span><span>'.$info['task_info']['network_connection'].'</span></div>
</div>
<div style="clear:both;"></div>
<div style="margin-left:10px; float: left; width:100%;"><p id="wpvivid_current_doing">'.$info['task_info']['descript'].'</p></div>
<div style="clear: both;"></div>
<div>
<div id="wpvivid_backup_cancel" class="backup-log-btn"><input class="button-primary" id="wpvivid_backup_cancel_btn" type="submit" value="' . esc_attr('Cancel', 'wpvivid-backuprestore') . '" style="'.$info['task_info']['css_btn_cancel'].'" /></div>
</div>
<div style="clear: both;"></div>';
}
}
return $ret;
}
public function _list_tasks()
{
if($this->wpvivid_check_litespeed_server() && $this->wpvivid_check_litespeed_cache_plugin())
{
wp_cache_delete('wpvivid_task_list', 'options');
}
$tasks = get_option('wpvivid_task_list', array());
$ret['result']='success';
$ret['progress_html']=false;
$ret['upload_progress_html']=false;
$ret['success_notice_html'] =false;
$ret['error_notice_html'] =false;
$ret['need_update']=false;
$ret['last_msg_html']=false;
$ret['running_backup_taskid']='';
$ret['wait_resume']=false;
$ret['next_resume_time']=false;
$ret['need_refresh_remote']=false;
$ret['backup_finish_info']=false;
$ret['task_no_response']=false;
$finished_tasks=array();
$backup_success_count=0;
$backup_failed_count=0;
$success_log_file_name = '';
$ret['test']=$tasks;
foreach ($tasks as $task)
{
if(!isset($task['id']))
{
continue;
}
$ret['task_id']=$task['id'];
$ret['need_update']=true;
if(isset($task['options']['export']))
{
$ret['export'] =$task['options']['export'];
}
else
{
$ret['export'] ='';
}
$backup_task=new WPvivid_Backup_Task_2($task['id']);
$info=$backup_task->get_backup_task_info();
$ret['need_next_schedule']=$info['task_info']['need_next_schedule'];
if($info['task_info']['need_next_schedule']===true)
{
$timestamp = wp_next_scheduled('wpvivid_task_monitor_event_2',array($task['id']));
if($timestamp===false)
{
$this->add_monitor_event($task['id'],20);
}
}
if($info['status']['str']=='ready'||$info['status']['str']=='running'||$info['status']['str']=='wait_resume'||$info['status']['str']=='no_responds')
{
$ret['running_backup_taskid']=$task['id'];
if($info['status']['str']=='wait_resume')
{
$ret['wait_resume']=true;
$ret['next_resume_time']=$info['data']['next_resume_time'];
}
if($info['status']['str']=='no_responds')
{
$ret['task_no_response']=true;
}
$ret['progress_html'] = '<div class="action-progress-bar" id="wpvivid_action_progress_bar">
<div class="action-progress-bar-percent" id="wpvivid_action_progress_bar_percent" style="height:24px;width:'.$info['task_info']['backup_percent'].'"></div>
</div>
<div id="wpvivid_estimate_upload_info" style="float: left;">
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Total Size:', 'wpvivid-backuprestore') . '</span><span>'.$info['task_info']['total'].'</span></div>
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Uploaded:', 'wpvivid-backuprestore') . '</span><span>'.$info['task_info']['upload'].'</span></div>
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Speed:', 'wpvivid-backuprestore') . '</span><span>'.$info['task_info']['speed'].'</span></div>
</div>
<div style="float: left;">
<div class="backup-basic-info"><span class="wpvivid-element-space-right">' . __('Network Connection:', 'wpvivid-backuprestore') . '</span><span>'.$info['task_info']['network_connection'].'</span></div>
</div>
<div style="clear:both;"></div>
<div style="margin-left:10px; float: left; width:100%;"><p id="wpvivid_current_doing">'.$info['task_info']['descript'].'</p></div>
<div style="clear: both;"></div>
<div>
<div id="wpvivid_backup_cancel" class="backup-log-btn"><input class="button-primary" id="wpvivid_backup_cancel_btn" type="submit" value="' . esc_attr('Cancel', 'wpvivid-backuprestore') . '" style="'.$info['task_info']['css_btn_cancel'].'" /></div>
</div>
<div style="clear: both;"></div>';
}
if($info['status']['str']=='completed')
{
$finished_tasks[$task['id']]=$task;
$backup_success_count++;
$success_log_file_name = $task['id'].'_backup_log.txt';
}
else if($info['status']['str']=='error')
{
$finished_tasks[$task['id']]=$task;
$backup_failed_count++;
}
if(isset($task['options']['export'])&&$task['options']['export']=='auto_migrate')
{
$ret['upload_progress_html']=$ret['progress_html'];
$ret['progress_html']=false;
}
}
if(!empty($ret['running_backup_taskid']))
{
$timestamp = wp_next_scheduled('wpvivid_task_monitor_event_2',array($ret['running_backup_taskid']));
if($timestamp===false)
{
$this->add_monitor_event($ret['running_backup_taskid'],20);
}
}
if($backup_success_count>0)
{
$notice_msg = $backup_success_count.' backup task(s) finished. Please switch to <a href="#" onclick="wpvivid_click_switch_page(\'wrap\', \'wpvivid_tab_log\', true);">Log</a> page to check the details.';
$ret['success_notice_html'] ='<div class="notice notice-success is-dismissible inline" style="margin-bottom: 5px;"><p>'.$notice_msg.'</p>
<button type="button" class="notice-dismiss" onclick="click_dismiss_notice(this);">
<span class="screen-reader-text">Dismiss this notice.</span>
</button>
</div>';
}
//<a href="#" onclick="wpvivid_click_switch_page('wrap', 'wpvivid_tab_log', true);">Log</a>
if($backup_failed_count>0)
{
$admin_url = apply_filters('wpvivid_get_admin_url', '');
$notice_msg = $backup_failed_count.' backup task(s) have been failed. Please switch to <a href="#" onclick="wpvivid_click_switch_page(\'wrap\', \'wpvivid_tab_debug\', true);">Log</a> page to send us the debug information.';
$ret['error_notice_html'] ='<div class="notice notice-error inline" style="margin-bottom: 5px;"><p>'.$notice_msg.'</p></div>';
}
$delete_ids=array();
foreach ($tasks as $task)
{
if(array_key_exists($task['id'],$finished_tasks))
{
$delete_ids[]=$task['id'];
}
}
foreach ($delete_ids as $id)
{
unset($tasks[$id]);
}
WPvivid_Setting::update_option('wpvivid_task_list',$tasks);
return $ret;
}
public function shutdown_backup()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$task_id = sanitize_key($_POST['task_id']);
$backup_task=new WPvivid_Backup_Task_2($task_id);
if($backup_task->check_cancel_backup())
{
$ret['result'] = 'success';
}
else
{
$ret['result'] = 'failed';
}
echo wp_json_encode($ret);
die();
}
public function delete_task()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
if (isset($_POST['task_id']) && !empty($_POST['task_id']) && is_string($_POST['task_id']))
{
$task_id = sanitize_key($_POST['task_id']);
$options = get_option('wpvivid_task_list', array());
unset($options[$task_id]);
update_option('wpvivid_task_list',$options,'no');
$json['result'] = 'success';
echo wp_json_encode($json);
}
die();
}
public function update_backup_task_status($task_id,$reset_start_time=false,$status='',$reset_timeout=false,$resume_count=false,$error='')
{
$tasks=get_option('wpvivid_task_list', array());
if(array_key_exists ($task_id,$tasks))
{
$task = $tasks[$task_id];
$task['status']['run_time']=time();
if($reset_start_time)
$task['status']['start_time']=time();
if(!empty($status))
{
$task['status']['str']=$status;
}
if($reset_timeout)
$task['status']['timeout']=time();
if($resume_count!==false)
{
$task['status']['resume_count']=$resume_count;
}
if(!empty($error))
{
$task['status']['error']=$error;
}
$options = get_option('wpvivid_task_list', array());
$options[$task_id]=$task;
update_option('wpvivid_task_list',$options,'no');
return true;
}
else
{
return false;
}
}
public function task_monitor($task_id)
{
if(WPvivid_taskmanager::get_task($task_id)!==false)
{
$task=new WPvivid_Backup_Task_2($task_id);
$status=$task->get_status();
if($task->is_task_canceled())
{
$limit=$task->get_time_limit();
$last_active_time=time()-$status['run_time'];
if($last_active_time>180)
{
if($task->check_cancel_backup())
{
$this->end_shutdown_function=true;
die();
}
}
}
global $wpvivid_plugin;
$wpvivid_plugin->wpvivid_log->OpenLogFile(WPvivid_taskmanager::get_task_options($task_id,'log_file_name'));
if($status['str']=='running'||$status['str']=='error'||$status['str']=='no_responds')
{
$limit=$task->get_time_limit();
$time_spend=time()-$status['timeout'];
$last_active_time=time()-$status['run_time'];
if($time_spend>$limit&&$last_active_time>180)
{
//time out
$max_resume_count=$task->get_max_resume_count();
$task->check_timeout();
$status['resume_count']++;
if($status['resume_count']>$max_resume_count)
{
$message=__('Too many resumption attempts.', 'wpvivid-backuprestore');
$wpvivid_plugin->wpvivid_log->WriteLog('Backup the file ends with an error '. $message,'error');
$task->update_backup_task_status(false,'error',false,$status['resume_count'],$message);
$task->check_timeout_backup_failed();
do_action('wpvivid_handle_backup_2_failed', $task_id);
}
else
{
$message=__('Task timed out.', 'wpvivid-backuprestore');
$task->update_backup_task_status(false,'wait_resume',false,$status['resume_count']);
if($this->add_resume_event($task_id)===false)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Backup the file ends with an error '. $message,'error');
$task->update_backup_task_status(false,'error',false,$status['resume_count'],$message);
$task->check_timeout_backup_failed();
do_action('wpvivid_handle_backup_2_failed', $task_id);
}
}
}
else
{
$time_spend=time()-$status['run_time'];
if($time_spend>180)
{
$task->update_backup_task_status(false,'no_responds',false,$status['resume_count']);
$this->add_monitor_event($task_id);
}
else {
$this->add_monitor_event($task_id);
}
}
}
else if($status['str']=='wait_resume')
{
$timestamp = wp_next_scheduled(WPVIVID_RESUME_SCHEDULE_EVENT,array($task_id));
if($timestamp===false)
{
$message = 'Task timed out (WebHosting).';
$task->update_backup_task_status(false, 'wait_resume', false, $status['resume_count']);
if ($this->add_resume_event($task_id)===false)
{
$wpvivid_plugin->wpvivid_log->WriteLog('Backup the file ends with an error '. $message,'error');
$task->update_backup_task_status(false, 'error', false, $status['resume_count'], $message);
$task->check_timeout_backup_failed();
do_action('wpvivid_handle_backup_2_failed', $task_id);
}
}
}
}
}
private function add_resume_event($task_id)
{
$resume_time=time()+10;
$b=wp_schedule_single_event($resume_time,'wpvivid_backup_2_schedule_event',array($task_id));
if($b===false)
{
$timestamp = wp_next_scheduled('wpvivid_backup_2_schedule_event',array($task_id));
if($timestamp===false)
{
return false;
}
else
{
return true;
}
}
return true;
}
public function add_monitor_event($task_id,$next_time=120)
{
$resume_time=time()+$next_time;
$timestamp = wp_next_scheduled('wpvivid_task_monitor_event_2',array($task_id));
if($timestamp===false)
{
$b = wp_schedule_single_event($resume_time, 'wpvivid_task_monitor_event_2', array($task_id));
if ($b === false)
{
return false;
}
else
{
return true;
}
}
return true;
}
public function clear_monitor_schedule($id)
{
$timestamp =wp_next_scheduled('wpvivid_task_monitor_event_2',array($id));
if($timestamp!==false)
{
wp_unschedule_event($timestamp,'wpvivid_task_monitor_event_2',array($id));
}
}
public function add_clean_backup_data_event($task_id)
{
$task=WPvivid_taskmanager::get_task($task_id);
$tasks=WPvivid_Setting::get_option('wpvivid_clean_task_2');
$tasks[$task_id]=$task;
WPvivid_Setting::update_option('wpvivid_clean_task_2',$tasks);
$resume_time=time()+60;
$b=wp_schedule_single_event($resume_time,'wpvivid_clean_backup_2_data_event',array($task_id));
if($b===false)
{
$timestamp = wp_next_scheduled('wpvivid_clean_backup_2_data_event',array($task_id));
if($timestamp!==false)
{
$resume_time=max($resume_time,$timestamp+10*60+10);
$b=wp_schedule_single_event($resume_time,'wpvivid_clean_backup_2_data_event',array($task_id));
if($b===false)
{
return false;
}
}
else
{
return false;
}
}
return true;
}
public function clean_backup_data_event($task_id)
{
$tasks=get_option('wpvivid_clean_task_2',array());
if(isset($tasks[$task_id]))
{
$task_data=$tasks[$task_id];
unset($tasks[$task_id]);
}
update_option('wpvivid_clean_task_2',$tasks,'no');
if(!empty($task_data))
{
$task= new WPvivid_Backup_Task_2($task_id,$task_data);
$task->clean_backup();
$files=array();
if($task->need_upload())
{
$backup_files=$task->get_backup_files();
foreach ($backup_files as $file)
{
$files[]=basename($file);
}
if(!empty($files))
{
if(!class_exists('WPvivid_Upload'))
include_once WPVIVID_PLUGIN_DIR . '/includes/class-wpvivid-upload.php';
$upload=new WPvivid_Upload();
$upload->clean_remote_backup($task->get_remote_options(),$files);
}
}
//clean upload
}
}
public function wpvivid_check_litespeed_server()
{
$litespeed=false;
if ( isset( $_SERVER['HTTP_X_LSCACHE'] ) && $_SERVER['HTTP_X_LSCACHE'] )
{
$litespeed=true;
}
elseif ( isset( $_SERVER['LSWS_EDITION'] ) && strpos( $_SERVER['LSWS_EDITION'], 'Openlitespeed' ) === 0 ) {
$litespeed=true;
}
elseif ( isset( $_SERVER['SERVER_SOFTWARE'] ) && $_SERVER['SERVER_SOFTWARE'] == 'LiteSpeed' ) {
$litespeed=true;
}
return $litespeed;
}
public function wpvivid_check_litespeed_cache_plugin()
{
$litespeed_cache_plugin=false;
if(!function_exists('get_plugins'))
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
$litespeed_cache_slug='litespeed-cache/litespeed-cache.php';
if (is_multisite())
{
$active_plugins = array();
//network active
$mu_active_plugins = get_site_option( 'active_sitewide_plugins', array() );
if(!empty($mu_active_plugins)){
foreach ($mu_active_plugins as $plugin_name => $data){
$active_plugins[] = $plugin_name;
}
}
$plugins=get_mu_plugins();
if(count($plugins) == 0 || !isset($plugins[$litespeed_cache_slug])){
$plugins=get_plugins();
}
}
else
{
$active_plugins = get_option('active_plugins');
$plugins=get_plugins();
}
if(!empty($plugins))
{
if(isset($plugins[$litespeed_cache_slug]))
{
if(in_array($litespeed_cache_slug, $active_plugins))
{
$litespeed_cache_plugin=true;
}
else
{
$litespeed_cache_plugin=false;
}
}
else
{
$litespeed_cache_plugin=false;
}
}
else
{
$litespeed_cache_plugin=false;
}
return $litespeed_cache_plugin;
}
public function send_backup_to_site()
{
try
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
$options = WPvivid_Setting::get_option('wpvivid_saved_api_token');
if (empty($options))
{
$ret['result'] = 'failed';
$ret['error'] = __('A key is required.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$url = '';
foreach ($options as $key => $value)
{
$url = $value['url'];
}
if ($url === '')
{
$ret['result'] = 'failed';
$ret['error'] = __('The key is invalid.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
if ($options[$url]['expires'] != 0 && $options[$url]['expires'] < time())
{
$ret['result'] = 'failed';
$ret['error'] = __('The key has expired.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$json['test_connect']=1;
$json=wp_json_encode($json);
$crypt=new WPvivid_crypt(base64_decode($options[$url]['token']));
$data=$crypt->encrypt_message($json);
$data=base64_encode($data);
$args['body']=array('wpvivid_content'=>$data,'wpvivid_action'=>'send_to_site_connect');
$response=wp_remote_post($url,$args);
if ( is_wp_error( $response ) )
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $response->get_error_message();
echo wp_json_encode($ret);
die();
}
else
{
if($response['response']['code']==200)
{
$res=json_decode($response['body'],1);
if($res!=null) {
if($res['result']==WPVIVID_SUCCESS)
{
}
else
{
$ret['result']=WPVIVID_FAILED;
$ret['error']= $res['error'];
echo wp_json_encode($ret);
die();
}
}
else {
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'failed to parse returned data, unable to establish connection with the target site.';
$ret['response']=$response;
echo wp_json_encode($ret);
die();
}
}
else {
$ret['result']=WPVIVID_FAILED;
$ret['error']= 'upload error '.$response['response']['code'].' '.$response['body'];
echo wp_json_encode($ret);
die();
}
}
if (WPvivid_taskmanager::is_tasks_backup_running())
{
$ret['result'] = 'failed';
$ret['error'] = __('A task is already running. Please wait until the running task is complete, and try again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
$remote_option['url'] = $options[$url]['url'];
$remote_option['token'] = $options[$url]['token'];
$remote_option['type'] = WPVIVID_REMOTE_SEND_TO_SITE;
$remote_options['temp'] = $remote_option;
$backup_options = stripslashes(sanitize_text_field($_POST['backup_options']));
$backup_options = json_decode($backup_options, true);
$backup['backup_files'] = $backup_options['transfer_type'];
$backup['local'] = 0;
$backup['remote'] = 1;
$backup['ismerge'] = 1;
$backup['lock'] = 0;
$backup['remote_options'] = $remote_options;
$backup['type']='Migrate';
$backup['export']='auto_migrate';
/*
$backup_task = new WPvivid_Backup_Task();
$ret = $backup_task->new_backup_task($backup, 'Manual', 'transfer');
$task_id = $ret['task_id'];
global $wpvivid_plugin;
$wpvivid_plugin->check_backup($task_id, $backup);
echo wp_json_encode($ret);
die();
*/
$settings=$this->get_backup_settings($backup);
$task=new WPvivid_Backup_Task_2();
$ret=$task->new_backup_task($backup,$settings);
echo wp_json_encode($ret);
die();
}
catch (Exception $e){
$ret['result'] = 'failed';
$ret['error'] = $e->getMessage();
echo wp_json_encode($ret);
die();
}
}
public function migrate_now()
{
check_ajax_referer( 'wpvivid_ajax', 'nonce' );
$check=current_user_can('manage_options');
$check=apply_filters('wpvivid_ajax_check_security',$check);
if(!$check)
{
die();
}
register_shutdown_function(array($this,'deal_backup_shutdown_error'));
$this->end_shutdown_function=false;
$task_id = sanitize_key($_POST['task_id']);
$this->current_task_id=$task_id;
global $wpvivid_plugin;
if ($this->is_tasks_backup_running($task_id))
{
$ret['result'] = 'failed';
$ret['error'] = __('We detected that there is already a running backup task. Please wait until it completes then try again.', 'wpvivid-backuprestore');
echo wp_json_encode($ret);
die();
}
try
{
$this->update_backup_task_status($task_id,true,'running');
$wpvivid_plugin->flush($task_id);
$this->add_monitor_event($task_id);
$this->task=new WPvivid_Backup_Task_2($task_id);
$this->task->set_memory_limit();
$this->task->set_time_limit();
$wpvivid_plugin->wpvivid_log->OpenLogFile($this->task->task['options']['log_file_name']);
$wpvivid_plugin->wpvivid_log->WriteLog('Start backing up.','notice');
$wpvivid_plugin->wpvivid_log->WriteLogHander();
if(!$this->task->is_backup_finished())
{
$ret=$this->backup();
$this->task->clear_cache();
if($ret['result']!='success')
{
$wpvivid_plugin->wpvivid_log->WriteLog('Backup the file ends with an error '. $ret['error'],'error');
$this->task->update_backup_task_status(false,'error',false,false,$ret['error']);
do_action('wpvivid_handle_backup_2_failed', $task_id);
$this->end_shutdown_function=true;
$this->clear_monitor_schedule($task_id);
die();
}
}
if($this->task->need_upload())
{
$ret=$this->upload($task_id);
if($ret['result'] == WPVIVID_SUCCESS)
{
do_action('wpvivid_handle_backup_2_succeed',$task_id);
$this->update_backup_task_status($task_id,false,'completed');
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Uploading the file ends with an error '. $ret['error'], 'error');
do_action('wpvivid_handle_backup_2_failed',$task_id);
}
}
else
{
$wpvivid_plugin->wpvivid_log->WriteLog('Backup completed.','notice');
do_action('wpvivid_handle_backup_2_succeed', $task_id);
$this->update_backup_task_status($task_id,false,'completed');
}
$this->clear_monitor_schedule($task_id);
}
catch (Exception $error)
{
//catch error and stop task recording history
$message = 'An exception has occurred. class:'.get_class($error).';msg:'.$error->getMessage().';code:'.$error->getCode().';line:'.$error->getLine().';in_file:'.$error->getFile().';';
error_log($message);
WPvivid_taskmanager::update_backup_task_status($task_id,false,'error',false,false,$message);
$wpvivid_plugin->wpvivid_log->WriteLog($message,'error');
do_action('wpvivid_handle_backup_2_failed',$task_id);
$this->end_shutdown_function=true;
die();
}
$this->end_shutdown_function=true;
die();
}
public function default_exclude_folders($folders)
{
$upload_dir = wp_upload_dir();
$exclude_default = array();
$exclude_default[0]['type'] = 'folder';
$exclude_default[0]['path'] = $upload_dir['basedir'].'/'.'backwpup'; // BackWPup backup directory
$exclude_default[1]['type'] = 'folder';
$exclude_default[1]['path'] = $upload_dir['basedir'].'/'.'ShortpixelBackups'; //ShortpixelBackups
$exclude_default[2]['type'] = 'folder';
$exclude_default[2]['path'] = $upload_dir['basedir'].'/'.'backup';
$exclude_default[3]['type'] = 'folder';
$exclude_default[3]['path'] = $upload_dir['basedir'].'/'.'backwpup'; // BackWPup backup directory
$exclude_default[4]['type'] = 'folder';
$exclude_default[4]['path'] = $upload_dir['basedir'].'/'.'backup-guard'; // Wordpress Backup and Migrate Plugin backup directory
$exclude_default[5]['type'] = 'folder';
$exclude_default[5]['path'] = WP_CONTENT_DIR.'/'.'updraft'; // Updraft Plus backup directory
$exclude_default[6]['type'] = 'folder';
$exclude_default[6]['path'] = WP_CONTENT_DIR.'/'.'ai1wm-backups'; // All-in-one WP migration backup directory
$exclude_default[7]['type'] = 'folder';
$exclude_default[7]['path'] = WP_CONTENT_DIR.'/'.'backups'; // Xcloner backup directory
$exclude_default[8]['type'] = 'folder';
$exclude_default[8]['path'] = WP_CONTENT_DIR.'/'.'upgrade';
$exclude_default[10]['type'] = 'folder';
$exclude_default[10]['path'] = WP_CONTENT_DIR.'/'.'cache';
$exclude_default[11]['type'] = 'folder';
$exclude_default[11]['path'] = WP_CONTENT_DIR.'/'.'wphb-cache';
$exclude_default[12]['type'] = 'folder';
$exclude_default[12]['path'] = WP_CONTENT_DIR.'/'.'backup';
$exclude_default[13]['type'] = 'folder';
$exclude_default[13]['path'] = WP_CONTENT_DIR.'/'.'Dropbox_Backup';
//$exclude_default[14]['type'] = 'folder';
//$exclude_default[14]['path'] = WP_CONTENT_DIR.'/'.'mu-plugins';
$exclude_default[15]['type'] = 'folder';
$exclude_default[15]['path'] = WP_CONTENT_DIR.'/'.'backups-dup-pro'; // duplicator backup directory
$exclude_default[16]['type'] = 'folder';
$exclude_default[16]['path'] = WP_CONTENT_DIR.'/'.'backup-migration';
$exclude_default[17]['type'] = 'folder';
$exclude_default[17]['path'] = WP_CONTENT_DIR.'/'.'backups-dup-lite';
$exclude_default[18]['type'] = 'folder';
$exclude_default[18]['path'] = WP_PLUGIN_DIR.'/'.'wp-cerber';
$exclude_default[19]['type'] = 'file';
$exclude_default[19]['path'] = WP_CONTENT_DIR.'/'.'mysql.sql'; //mysql
$exclude_default[20]['type'] = 'folder';
$exclude_default[20]['path'] = WP_CONTENT_DIR.'/'.'wpvivid_uploads';
$exclude_default[21]['type'] = 'folder';
$exclude_default[21]['path'] = WP_CONTENT_DIR.'/'.'WPvivid_Uploads';
if(!empty($exclude_default))
{
foreach ($exclude_default as $index => $value)
{
$folders[$index]=$value;
}
}
return $folders;
}
} includes/new_backup/class-wpvivid-restore-file-2.php 0000644 00000064730 15132770567 0016560 0 ustar 00 <?php
if (!defined('WPVIVID_PLUGIN_DIR'))
{
die;
}
class WPvivid_Restore_File_2
{
public $log;
public function __construct($log=false)
{
$this->log=$log;
}
public function restore($sub_task,$backup_id)
{
if($sub_task['type']=='wp-core')
{
return $this->restore_core($sub_task,$backup_id);
}
$files=$sub_task['unzip_file']['files'];
$GLOBALS['wpvivid_restore_addon_type'] =$sub_task['type'];
//restore_reset
foreach ($files as $index=>$file)
{
if($file['finished']==1)
{
continue;
}
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['unzip_file']['last_unzip_file']=$file['file_name'];
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['file_name'].'</span>';
$this->update_sub_task($sub_task);
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
$backup_item = new WPvivid_Backup_Item($backup);
$extract_child_finished=isset($file['extract_child_finished'])?$file['extract_child_finished']:0;
if(isset($file['has_child'])&&$extract_child_finished==0)
{
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['unzip_file']['last_unzip_file']=$file['parent_file'];
$sub_task['unzip_file']['last_unzip_file_index']=0;
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['parent_file'].'</span>';
$this->update_sub_task($sub_task);
$root_path=$backup_item->get_local_path();
if(!file_exists($root_path))
{
@mkdir($root_path);
}
$this->log->WriteLog('Extracting file:'.$file['parent_file'],'notice');
$extract_files[]=$file['file_name'];
$ret=$this->extract_ex($root_path.$file['parent_file'],$extract_files,untrailingslashit($root_path),$sub_task['options']);
if($ret['result']!='success')
{
return $ret;
}
$this->log->WriteLog('Extracting file:'.$file['parent_file'].' succeeded.','notice');
$file_name=$root_path.$file['file_name'];
$sub_task['unzip_file']['files'][$index]['extract_child_finished']=1;
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['parent_file'].' completed.</span>';
$this->update_sub_task($sub_task);
}
else
{
$root_path=$backup_item->get_local_path();
$file_name=$root_path.$file['file_name'];
}
$root_path = '';
if (isset($file['options']['root']))
{
$root_path = $this->transfer_path(get_home_path() . $file['options']['root']);
}
else if (isset($file['options']['root_flag']))
{
if ($file['options']['root_flag'] == WPVIVID_BACKUP_ROOT_WP_CONTENT)
{
$root_path = $this->transfer_path(WP_CONTENT_DIR);
}
else if ($file['options']['root_flag'] == WPVIVID_BACKUP_ROOT_CUSTOM)
{
$root_path = $this->transfer_path(WP_CONTENT_DIR . DIRECTORY_SEPARATOR . WPvivid_Setting::get_backupdir());
}
else if ($file['options']['root_flag'] == WPVIVID_BACKUP_ROOT_WP_ROOT)
{
$root_path = $this->transfer_path(ABSPATH);
}
else if($file['options']['root_flag'] == WPVIVID_BACKUP_ROOT_WP_UPLOADS)
{
$upload_dir = wp_upload_dir();
$upload_path = $upload_dir['basedir'];
$root_path = $this->transfer_path($upload_path);
}
}
if($sub_task['restore_reset'])
{
if($sub_task['restore_reset_finished']===false)
{
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['last_msg']='<span>Cleaning folder:</span><span>'.$sub_task['type'].'</span>';
$this->update_sub_task($sub_task);
$this->log->WriteLog('Cleaning folder:'.$sub_task['type'],'notice');
$this->reset_restore($sub_task['type']);
$sub_task['restore_reset_finished']=true;
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['last_msg']='<span>Cleaning folder:</span><span>'.$sub_task['type'].' completed.</span>';
$this->update_sub_task($sub_task);
}
}
$root_path = rtrim($root_path, '/');
$root_path = rtrim($root_path, DIRECTORY_SEPARATOR);
$restore_task=get_option('wpvivid_restore_task',array());
$restore_detail_options=$restore_task['restore_detail_options'];
$unzip_files_pre_request=$restore_detail_options['unzip_files_pre_request'];
$use_index=$restore_detail_options['use_index'];
if($use_index==false)
{
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['file_name'].'</span>';
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['unzip_file']['last_unzip_file']=$file['file_name'];
$sub_task['unzip_file']['last_unzip_file_index']=0;
$this->update_sub_task($sub_task);
$this->log->WriteLog('Extracting file:'.$file_name,'notice');
$ret=$this->extract($file_name,untrailingslashit($root_path),$sub_task['options']);
if($ret['result']!='success')
{
return $ret;
}
$this->log->WriteLog('Extracting file:'.$file_name.' succeeded','notice');
$sub_task['unzip_file']['files'][$index]['finished']=1;
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['file_name'].' completed.</span>';
}
else
{
$sum=$this->get_zip_file_count($file_name);
$start=$file['index'];
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['file_name'].' '.$start.'/'.$sum.'</span>';
$sub_task['unzip_file']['sum']=$sum;
$sub_task['unzip_file']['start']=$start;
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['unzip_file']['last_unzip_file']=$file['file_name'];
$sub_task['unzip_file']['last_unzip_file_index']=$start;
$this->update_sub_task($sub_task);
$this->log->WriteLog('Extracting file:'.basename($file_name).' index:'.$start,'notice');
$ret=$this->extract_by_index($file_name,untrailingslashit($root_path),$start,$start+$unzip_files_pre_request,$sub_task['options']);
if($ret['result']!='success')
{
return $ret;
}
$this->log->WriteLog('Extracting file:'.basename($file_name).' index:'.$start.' finished.','notice');
$sub_task['unzip_file']['files'][$index]['index']=$start+$unzip_files_pre_request;
$sub_task['unzip_file']['last_action']='Unzipping';
if($start+$unzip_files_pre_request>=$sum)
{
$sub_task['unzip_file']['files'][$index]['finished']=1;
$sub_task['unzip_file']['sum']=0;
$sub_task['unzip_file']['start']=0;
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['file_name'].' completed.</span>';
}
else
{
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['file_name'].' '.$sub_task['unzip_file']['files'][$index]['index'].'/'.$sum.'</span>';
}
}
break;
}
if($this->check_restore_finished($sub_task))
{
$sub_task['finished']=1;
$sub_task['unzip_file']['unzip_finished']=1;
$sub_task['unzip_file']['sum']=0;
$sub_task['unzip_file']['start']=0;
}
$ret['result']='success';
$ret['sub_task']=$sub_task;
return $ret;
}
public function restore_core($sub_task,$backup_id)
{
$files=$sub_task['unzip_file']['files'];
$GLOBALS['wpvivid_restore_addon_type'] =$sub_task['type'];
//restore_reset
foreach ($files as $index=>$file)
{
if($file['finished']==1)
{
continue;
}
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['unzip_file']['last_unzip_file']=$file['file_name'];
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['file_name'].'</span>';
$this->update_sub_task($sub_task);
$backup = WPvivid_Backuplist::get_backup_by_id($backup_id);
$backup_item = new WPvivid_Backup_Item($backup);
$extract_child_finished=isset($file['extract_child_finished'])?$file['extract_child_finished']:0;
if(isset($file['has_child'])&&$extract_child_finished==0)
{
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['parent_file'].'</span>';
$this->update_sub_task($sub_task);
$root_path=$backup_item->get_local_path();
if(!file_exists($root_path))
{
@mkdir($root_path);
}
$this->log->WriteLog('Extracting file:'.$file['parent_file'],'notice');
$extract_files[]=$file['file_name'];
$ret=$this->extract_ex($root_path.$file['parent_file'],$extract_files,untrailingslashit($root_path),$sub_task['options']);
if($ret['result']!='success')
{
return $ret;
}
$this->log->WriteLog('Extracting file:'.$file['parent_file'].' succeeded.','notice');
$file_name=$root_path.$file['file_name'];
$sub_task['unzip_file']['files'][$index]['extract_child_finished']=1;
$sub_task['last_msg']='<span><strong>Extracting file:</strong></span><span>'.$file['parent_file'].' completed.</span>';
$this->update_sub_task($sub_task);
}
else
{
$root_path=$backup_item->get_local_path();
$file_name=$root_path.$file['file_name'];
}
if($sub_task['restore_reset'])
{
if($sub_task['restore_reset_finished']===false)
{
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['last_msg']='<span>Cleaning folder:</span><span>'.$sub_task['type'].'</span>';
$this->update_sub_task($sub_task);
$this->log->WriteLog('Cleaning folder:'.$sub_task['type'],'notice');
$this->reset_restore($sub_task['type']);
$sub_task['restore_reset_finished']=true;
$sub_task['unzip_file']['last_action']='Unzipping';
$sub_task['last_msg']='<span>Cleaning folder:</span><span>'.$sub_task['type'].' completed.</span>';
$this->update_sub_task($sub_task);
}
}
$root_path = $this->transfer_path(ABSPATH);
$root_path = rtrim($root_path, '/');
$root_path = rtrim($root_path, DIRECTORY_SEPARATOR);
$sub_task['last_msg']='<span><strong>Extracting Files:</strong></span><span>'.$file['file_name'].'</span>';
$sub_task['unzip_file']['last_action']='Unzipping';
$this->update_sub_task($sub_task);
$this->log->WriteLog('Extracting file:'.basename($file_name),'notice');
$ret=$this->extract($file_name,untrailingslashit($root_path),$sub_task['options']);
if($ret['result']!='success')
{
return $ret;
}
$this->log->WriteLog('Extracting file:'.basename($file_name).' succeeded.','notice');
$sub_task['unzip_file']['files'][$index]['finished']=1;
$sub_task['last_msg']='<span><strong>Extracting Files:</strong></span><span>'.$file['file_name'].' finished</span>';
$this->update_sub_task($sub_task);
}
if($this->check_restore_finished($sub_task))
{
$sub_task['finished']=1;
$sub_task['unzip_file']['unzip_finished']=1;
}
$ret['result']='success';
$ret['sub_task']=$sub_task;
return $ret;
}
public function extract($file_name,$root_path,$option)
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
if(!empty($option))
{
$GLOBALS['wpvivid_restore_option'] = $option;
}
if(!defined('PCLZIP_TEMPORARY_DIR'))
define(PCLZIP_TEMPORARY_DIR,dirname($root_path));
$archive = new WPvivid_PclZip($file_name);
$zip_ret = $archive->extract(WPVIVID_PCLZIP_OPT_PATH, $root_path,WPVIVID_PCLZIP_OPT_REPLACE_NEWER,WPVIVID_PCLZIP_CB_PRE_EXTRACT,'wpvivid_function_pre_extract_callback_2',WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,16);
if(!$zip_ret)
{
$ret['result']='failed';
$ret['error'] = $archive->errorInfo(true);
$this->log->WriteLog('Extracting failed. Error:'.$archive->errorInfo(true),'notice');
}
else
{
$ret['result']='success';
}
return $ret;
}
public function extract_ex($file_name,$extract_files,$root_path,$option)
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
if(!empty($option))
{
$GLOBALS['wpvivid_restore_option'] = $option;
}
if(!defined('PCLZIP_TEMPORARY_DIR'))
define(PCLZIP_TEMPORARY_DIR,dirname($root_path));
$archive = new WPvivid_PclZip($file_name);
$zip_ret = $archive->extract(WPVIVID_PCLZIP_OPT_BY_NAME,$extract_files,WPVIVID_PCLZIP_OPT_PATH, $root_path,WPVIVID_PCLZIP_OPT_REPLACE_NEWER,WPVIVID_PCLZIP_CB_PRE_EXTRACT,'wpvivid_function_pre_extract_callback_2',WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,16);
if(!$zip_ret)
{
$ret['result']='failed';
$ret['error'] = $archive->errorInfo(true);
$this->log->WriteLog('Extracting failed. Error:'.$archive->errorInfo(true),'notice');
}
else
{
$ret['result']='success';
}
return $ret;
}
public function extract_by_index($file_name,$root_path,$start,$end,$option)
{
$index=$start.'-'.$end;
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
if(!empty($option))
{
$GLOBALS['wpvivid_restore_option'] = $option;
}
if(!defined('PCLZIP_TEMPORARY_DIR'))
define(PCLZIP_TEMPORARY_DIR,dirname($root_path));
$archive = new WPvivid_PclZip($file_name);
$zip_ret = $archive->extractByIndex($index,WPVIVID_PCLZIP_OPT_PATH, $root_path,WPVIVID_PCLZIP_OPT_REPLACE_NEWER,WPVIVID_PCLZIP_CB_PRE_EXTRACT,'wpvivid_function_pre_extract_callback_2',WPVIVID_PCLZIP_OPT_TEMP_FILE_THRESHOLD,16);
if(!$zip_ret)
{
$ret['result']='failed';
$ret['error'] = $archive->errorInfo(true);
$this->log->WriteLog('Extracting failed. Error:'.$archive->errorInfo(true),'notice');
}
else
{
$ret['result']='success';
}
return $ret;
}
public function get_zip_file_count($file_name)
{
if (!class_exists('WPvivid_PclZip'))
include_once WPVIVID_PLUGIN_DIR . '/includes/zip/class-wpvivid-pclzip.php';
$archive = new WPvivid_PclZip($file_name);
$properties=$archive->properties();
return $properties['nb'];
}
public function check_restore_finished($sub_task)
{
$finished=true;
$files=$sub_task['unzip_file']['files'];
foreach ($files as $index=>$file)
{
if($file['finished']==1)
{
continue;
}
else
{
$finished=false;
}
}
return $finished;
}
private function transfer_path($path)
{
$path = str_replace('\\','/',$path);
$values = explode('/',$path);
return implode(DIRECTORY_SEPARATOR,$values);
}
public function update_sub_task($sub_task=false)
{
$restore_task=get_option('wpvivid_restore_task',array());
if($restore_task['do_sub_task']!==false)
{
$key=$restore_task['do_sub_task'];
$restore_task['update_time']=time();
if($sub_task!==false)
$restore_task['sub_tasks'][$key]=$sub_task;
update_option('wpvivid_restore_task',$restore_task,'no');
}
}
public function reset_restore($type)
{
if($type=='themes')
{
return $this->delete_themes();
}
else if($type=='plugin')
{
return $this->delete_plugins();
}
else if($type=='upload')
{
return $this->delete_uploads();
}
else if($type=='wp-content')
{
return $this->delete_wp_content();
}
//else if($type=='mu_plugins')
//{
// return $this->delete_mu_plugins();
//}
else if($type=='wp-core')
{
return $this->delete_core();
}
$ret['result']='success';
return $ret;
}
public function delete_themes()
{
if (!function_exists('delete_theme'))
{
require_once ABSPATH . 'wp-admin/includes/theme.php';
}
if (!function_exists('request_filesystem_credentials'))
{
require_once ABSPATH . 'wp-admin/includes/file.php';
}
$all_themes = wp_get_themes(array('errors' => null));
foreach ($all_themes as $theme_slug => $theme_details)
{
delete_theme($theme_slug);
}
update_option('template', '');
update_option('stylesheet', '');
update_option('current_theme', '');
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
public function delete_plugins()
{
if (!function_exists('get_plugins'))
{
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
if (!function_exists('request_filesystem_credentials'))
{
require_once ABSPATH . 'wp-admin/includes/file.php';
}
$wpvivid_backup_pro='wpvivid-backup-pro/wpvivid-backup-pro.php';
$wpvivid_backup='wpvivid-backuprestore/wpvivid-backuprestore.php';
$all_plugins = get_plugins();
unset($all_plugins[$wpvivid_backup_pro]);
unset($all_plugins[$wpvivid_backup]);
if (!empty($all_plugins))
{
$this->_delete_plugins(array_keys($all_plugins));
}
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
public function _delete_plugins($plugins)
{
if ( empty( $plugins ) )
{
return false;
}
$plugins_dir = trailingslashit( WP_PLUGIN_DIR );
foreach ( $plugins as $plugin_file )
{
$this_plugin_dir = trailingslashit( dirname( $plugins_dir . $plugin_file ) );
// If plugin is in its own directory, recursively delete the directory.
if ( strpos( $plugin_file, '/' ) && $this_plugin_dir != $plugins_dir )
{ //base check on if plugin includes directory separator AND that it's not the root plugin folder
$this->delete_folder($this_plugin_dir,$plugins_dir);
} else {
@wp_delete_file($plugins_dir . $plugin_file);
}
}
return true;
}
public function delete_uploads()
{
$upload_dir = wp_get_upload_dir();
$this->delete_folder($upload_dir['basedir'], $upload_dir['basedir']);
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
public function delete_folder($folder, $base_folder)
{
$files = array_diff(scandir($folder), array('.', '..'));
foreach ($files as $file)
{
if (is_dir($folder . DIRECTORY_SEPARATOR . $file))
{
$this->delete_folder($folder . DIRECTORY_SEPARATOR . $file, $base_folder);
} else {
@wp_delete_file($folder . DIRECTORY_SEPARATOR . $file);
}
} // foreach
if ($folder != $base_folder)
{
$tmp = @rmdir($folder);
return $tmp;
} else {
return true;
}
}
public function delete_wp_content()
{
global $wpvivid_plugin;
$wp_content_dir = trailingslashit(WP_CONTENT_DIR);
$wpvivid_backup=WPvivid_Setting::get_backupdir();
$whitelisted_folders = array('mu-plugins', 'plugins', 'themes', 'uploads',$wpvivid_backup);
$dirs = glob($wp_content_dir . '*', GLOB_ONLYDIR);
foreach ($dirs as $dir)
{
if (false == in_array(basename($dir), $whitelisted_folders))
{
$this->delete_folder($dir, $dir);
@rmdir($dir);
}
}
$ret['result']=WPVIVID_SUCCESS;
return $ret;
}
public function delete_mu_plugins()
{
$ret['result']=WPVIVID_SUCCESS;
$mu_plugins = get_mu_plugins();
if(empty($mu_plugins))
{
return $ret;
}
$this->delete_folder(WPMU_PLUGIN_DIR, WPMU_PLUGIN_DIR);
return $ret;
}
public function delete_core()
{
$ret['result']=WPVIVID_SUCCESS;
require_once( ABSPATH . 'wp-admin/includes/update-core.php' );
global $_old_files;
$wp_dir = ABSPATH;
foreach ( $_old_files as $old_file )
{
$old_file = $wp_dir . $old_file;
if ( ! file_exists( $old_file ) )
{
continue;
}
// If the file isn't deleted, try writing an empty string to the file instead.
@wp_delete_file($old_file);
}
return $ret;
}
}
function wpvivid_function_pre_extract_callback_2($p_event, &$p_header)
{
$plugins = substr(WP_PLUGIN_DIR, strpos(WP_PLUGIN_DIR, 'wp-content/'));
if ( isset( $GLOBALS['wpvivid_restore_option'] ) )
{
$option = $GLOBALS['wpvivid_restore_option'];
$type=$GLOBALS['wpvivid_restore_addon_type'];
if ($type == 'themes')
{
if (isset($option['remove_themes']))
{
foreach ($option['remove_themes'] as $slug => $themes)
{
if (empty($slug))
continue;
if(strpos($p_header['filename'],$plugins.DIRECTORY_SEPARATOR.$slug)!==false)
{
return 0;
}
}
}
}
else if ($type == 'plugin')
{
if (isset($option['remove_plugins']))
{
foreach ($option['remove_plugins'] as $slug => $plugin)
{
if (empty($slug))
continue;
if(strpos($p_header['filename'],$plugins.'/'.$slug)!==false)
{
return 0;
}
}
}
}
}
else
{
$option=array();
}
$path = str_replace('\\','/',WP_CONTENT_DIR);
$content_path = $path.'/';
if(strpos($p_header['filename'], $content_path.'advanced-cache.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'db.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'object-cache.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'],$plugins.'/wpvivid-backuprestore')!==false)
{
return 0;
}
if(strpos($p_header['filename'],'wp-config.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'],'wpvivid_package_info.json')!==false)
{
return 0;
}
if(isset($option['restore_htaccess'])&&$option['restore_htaccess'])
{
}
else
{
if(strpos($p_header['filename'],'.htaccess')!==false)
{
return 0;
}
}
if(strpos($p_header['filename'],'.user.ini')!==false)
{
return 0;
}
if(strpos($p_header['filename'],'wordfence-waf.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'mu-plugins/endurance-browser-cache.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'mu-plugins/endurance-page-cache.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'mu-plugins/endurance-php-edge.php')!==false)
{
return 0;
}
if(strpos($p_header['filename'], $content_path.'mu-plugins/wp-stack-cache.php')!==false)
{
return 0;
}
return 1;
} admin/css/wpvivid-quick-snapshot-style.css 0000644 00000000611 15132770567 0014746 0 ustar 00
.wpvivid-span-progress {
display:block;
width:100%;
height:1.5em;
background-color:#9d9fa5;
border-radius:0;
color: #fff;
}
.wpvivid-span-processed-progress {
display:block;
height:1.5em;
background-color:#8bc34a;
border-radius:0;
color: #fff;
padding-left:0.5em;
}
.wpvivid-dashicons-green {
color:#8bc34a;
} admin/css/wpvivid-admin-bar.css 0000644 00000000072 15132770567 0012472 0 ustar 00 #wpadminbar{
background-color: #ff8d00 !important;
} admin/css/wpvivid-staging-custom.css 0000644 00000101626 15132770567 0013613 0 ustar 00 .quickbackup-addon{width:100%; box-sizing:border-box;margin-right:10px; padding:10px;}
.quickbackup-addon label{display:inline-block;}
.quickstaging{width:100%;float:left; box-sizing:border-box;margin-right:10px; padding:10px;}
.quickstaging label{display:inline-block;margin-bottom:10px;}
.wpvivid-custom-setting-save{margin: 10px 0 10px 0 !important;display: block !important;float: left;}
.wpvivid-custom-td-border{border-left: 0;}
.wpvivid-custom-backup-detail-odd{margin: 5px 20px 15px 40px;}
.wpvivid-custom-backup-detail-even{background: #f7fcfe; border-left: 4px solid #f7fcfe;}
.wpvivid-custom-database-table-list tbody {
display:block;
max-height:200px;
overflow-y:auto;
padding: 0;
}
.wpvivid-custom-database-table-list thead{
display:table;
width:100%;
}
.wpvivid-custom-database-table-list tbody tr {
display:table;
width:100%;
table-layout:fixed;
}
.wpvivid-schedule-time-select-addon,
.wpvivid-schedule-type-select-addon,
.wpvivid-schedule-remote-select-addon,
.wpvivid-schedule-create-addon{
float: left;
padding: 0 10px 10px 10px;
}
/* Popup container */
.wpvivid-custom-popup {
width: 100%;
position: relative;
display: inline-block;
//cursor: pointer;
}
.wpvivid-custom-popup .wpvivid-custom-popuptext {
visibility: hidden;
//width: 220px;
//background-color: #555;
//color: #fff;
//text-align: center;
border-radius: 6px;
padding: 8px 0;
//position: absolute;
z-index: 1;
bottom: 75%;
//margin-left: -80px;
}
/* Popup arrow */
.wpvivid-custom-popup .wpvivid-custom-popuptext::before {
/*content: "\25B2";
position: absolute;
//top: 100%;
bottom: 95%;
left: 20%;
background-color: #555;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;*/
}
/* Toggle this class when clicking on the popup container (hide and show the popup) */
.wpvivid-custom-popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s
}
.wpvivid-custom-popup .hide {
visibility: hidden;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s
}
.wpvivid-custom-tree-contain{
width: 100%;
height: 300px;
border:1px dotted;
overflow: auto;
}
#wpvivid_custom_backup_tree .jstree-container-ul > .jstree-node {
background: transparent;
}
@media screen and (max-width:1650px) {
.quickbackup-addon{
float:none;
width:100%;
}
}
@media screen and (min-width:1600px) {
.wpvivid-pro-list{
width: calc(50% - 8px) !important;
}
.wpvivid-pro-list:nth-child(even){
margin-right: 0 !important;
}
.wpvivid-pro-list:nth-child(odd){
margin-left: 0 !important;
}
.wpvivid-pro-list:nth-child(3n){
}
.wpvivid-pro-list:nth-child(3n+1){
}
}
.wpvivid-custom-table-tr-expand{
background:#f1f1f1;
}
.wpvivid-custom-table-td-expand{
font-weight:bold;
}
.wpvivid-custom-table{
width: 100%;
}
.wpvivid-custom-database-wp-table-header{
height:30px;
border-left:4px solid #00a0d2;
padding-left:5px;
padding-top:5px;
background-color:#f5f5f5;
}
.wpvivid-custom-database-other-table-header{
height:30px;
border-left:4px solid #00a0d2;
padding-left:5px;
padding-top:5px;
background-color:#f5f5f5;
margin-top: 5px;
}
.wpvivid-custom-database-table-column{
width:32%;
float:left;
}
@media screen and (min-width: 1921px) {
.wpvivid-custom-database-table-column{
width:24%;
float:left;
}
}
@media screen and (max-width: 1920px) {
.wpvivid-custom-database-table-column{
width:24%;
float:left;
}
}
@media screen and (max-width: 1550px) {
.wpvivid-custom-database-table-column{
width:32%;
float:left;
}
}
@media screen and (max-width: 1200px) {
.wpvivid-custom-database-table-column{
width:49%;
float:left;
}
.wpvivid-database-table-addon{
padding-top: 5px;
}
}
@media screen and (max-width: 790px) {
.wpvivid-custom-database-table-column{
width:99%;
float:left;
}
}
.wpvivid-custom-uploads-left{
width:30%;
overflow:auto;
}
.wpvivid-custom-uploads-right{
width:70%;
padding: 5px;
}
.wpvivid-custom-uploads-tree{
width: 100%;
height: 250px;
max-height: 250px;
overflow-y: auto;
}
.wpvivid-export-download-list,
.wpvivid-custom-uploads-table{
width: 100%;
height: 250px;
overflow: auto;
}
.wpvivid-export-download-list ul:nth-of-type(odd) {background:#f1f1f1;}
.wpvivid-export-download-list ul:nth-of-type(even) {}
.wpvivid-export-download-list ul,
.wpvivid-export-download-list ul li{
width: 100%;
height: 24px;
margin: 0;
}
.wpvivid-custom-uploads-table ul:nth-of-type(odd) {background:#f1f1f1;}
.wpvivid-custom-uploads-table ul:nth-of-type(even) {}
.wpvivid-custom-uploads-table ul,
.wpvivid-custom-uploads-table ul li{
width: 100%;
height: 24px;
margin: 0;
}
.wpvivid-custom-uploads-table .wpvivid-custom-table-li-left{
width: 98%;
margin: 0;
float :left;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.wpvivid-custom-uploads-table .wpvivid-custom-table-li-right{
width: 2%;
margin: 0;
float :left;
}
.wpvivid-custom-uploads-table-body{
width:100%;
float:left;
}
.wpvivid-custom-li-folder-icon{
background: url("../js/jstree/dist/themes/default/32px.png") -260px -4px no-repeat;
width: 24px;
height: 24px;
line-height: 24px;
margin: 0 4px 0 4px;
float: left;
}
.wpvivid-custom-li-file-icon{
background: url("../js/jstree/dist/themes/default/32px.png") -100px -68px no-repeat;
width: 24px;
height: 24px;
line-height: 24px;
margin: 0 4px 0 4px;
float: left;
}
.wpvivid-custom-li-font{
height: 24px;
line-height: 24px;
margin: 0;
float: left;
}
.wpvivid-custom-li-close{
height: 24px;
line-height: 24px;
margin: 0 10px 0 0;
float: right;
}
.wpvivid-custom-li-database-extra-left{
height: 24px;
line-height: 24px;
margin: 0 0 0 10px;
float: left;
}
.wpvivid-custom-li-database-extra-right{
height: 24px;
line-height: 24px;
margin: 0 10px 0 0;
float: right;
}
.wpvivid-custom-uploads-table-body-left{
float:left;
}
.wpvivid-custom-uploads-table-body-right{
float:right;
}
.wpvivid-backup-to-font{
font-weight:bold;
}
.wpvivid-backup-now-space{
padding-top:10px;
}
.wpvivid-backup-now-size{
width:200px;
height:50px;
font-size:20px;
}
.wpvivid-backup-tips{
float:left;
width:100%;
background-color:#f1f1f1;
}
.wpvivid-backup-to-remote{
padding-left:20px;
margin-top:5px;
margin-bottom:10px;
border-left:4px solid #00a0d2;
}
div.wpvivid-note{
-moz-border-radius: 6px;
-webkit-border-radius: 6px;
background-color: #f5f5f5;
background-image: url(../Images/icons/Pencil-48.png);
background-position: 9px 0px;
background-repeat: no-repeat;
border: solid 1px #eee;
border-radius: 6px;
line-height: 18px;
overflow: hidden;
padding: 15px 60px;
margin:10px 15px 10px 15px;
}
.wpvivid_tooltip {
position: relative;
width:12px;
height:12px;
border:1px solid #0073aa;
background-color:#0073aa;
color:#fff;
text-align:center;
vertical-align:middle;
border-radius:12px;
}
.wpvivid_tooltiptext a{
color: #aa0000;
}
.wpvivid_tooltip .wpvivid_tooltiptext {
visibility: hidden;
width: 250px;
background-color: #0085ba;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px;
/* Position the tooltip */
position: absolute;
z-index: 1;
bottom: 20px;
left: 50%;
margin-left: -125px; /* Use half of the width (120/2 = 60), to center the tooltip */
box-sizing: border-box;
}
.wpvivid_tooltip:hover .wpvivid_tooltiptext {
visibility: visible;
}
.wpvivid_tooltip .wpvivid_tooltiptext::after {
content: " ";
position: absolute;
top: 100%; /* At the bottom of the tooltip */
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color:#0085ba transparent transparent transparent;
box-sizing: border-box;
}
.wpvivid_click_popup{
background-color:#f7f7f7;
float:left;
width:100%;
border-radius: 6px;
padding:10px;
box-sizing:border-box;
}
.quickbackup-addon a{
text-decoration: none;
}
.wpvivid-intab-addon .nav-tab-active,
.wpvivid-intab-addon .nav-tab-active:focus,
.wpvivid-intab-addon .nav-tab-active:focus:active,
.wpvivid-intab-addon .nav-tab-active:hover{
border-bottom: 1px solid #ffffff;
}
.wpvivid-schedule-fix,
.wpvivid-debug-text-fix,
.wpvivid-setting-text-fix{
height: 28px;
line-height: 28px;
}
@media screen and (max-width: 782px) {
.wpvivid-tooltip-fix{
margin-top: 15px !important;
}
.wpvivid-schedule-fix,
.wpvivid-debug-text-fix,
.wpvivid-setting-text-fix{
height: 36px;
line-height: 36px;
}
}
.wpvivid-text-space-bottom{margin-bottom: 5px;}
.wpvivid-text-space-right{margin-right: 5px;}
.wpvivid-element-space-bottom{margin-bottom: 10px;}
.wpvivid-element-space-right{margin-right: 10px;}
.wpvivid-restore-log-addon{padding: 10px;width: 100%;height: 500px;overflow: auto;box-sizing: border-box; border-top: none; border-color: #ccc;}
.wpvivid-custom-tree ul{margin: 0 !important;}
.wpvivid-staging-log{padding:10px; width:100%; height:300px; overflow:auto; box-sizing:border-box;}
.wpvivid-refresh-tree:hover{
background: #0085ba;
border-color: #0073aa #006799 #006799;
box-shadow: 0 1px 0 #006799;
color: #fff;
text-decoration: none;
text-shadow: 0 -1px 1px #006799, 1px 0 1px #006799, 0 1px 1px #006799, -1px 0 1px #006799;
padding: 0 2px;
border-radius: 3px;
}
.wpvivid-setting-addon input{
margin: 0 4px 0 0;
}
.wpvivid-pro-update{
display: inline-block;
vertical-align: top;
box-sizing: border-box;
margin: 3px 0 0 2px;
padding: 0 0 0 8px;
min-width: 18px;
height: 18px;
border-radius: 9px;
background-color: #ca4a1f;
color: #fff;
font-size: 11px;
line-height: 1.6;
text-align: center;
z-index: 26;
}
.schedule-active
{
background-color: #90ee90;
}
.wpvivid-transparency-tab,
.wpvivid-transparency-tab:hover,
.wpvivid-transparency-tab:focus,
.wpvivid-transparency-tab:focus:active{
background: #ffffff;
}
.column-wpvivid_role_name { width:25% }
.column-wpvivid_role { width:8% }
.column-wpvivid_role_edit { width:8% }
.wpvivid-local-remote-backup-list span{margin: 0;}
.wpvivid-schedule-list span{margin: 0;}
.wpvivid-log-list span{margin: 0;}
.wpvivid-upload-tr{border: 2px solid #006799; box-sizing:border-box; -moz-box-sizing:border-box; -webkit-box-sizing:border-box;}
.wpvivid-backup-list{border-collapse: collapse;}
.wpvivid-list-td-center{text-align: center!important;}
.wpvivid-backup-option-box{width:100%; border:1px solid #f1f1f1; float:left; padding:10px 10px 0 10px; box-sizing: border-box; margin-top: 10px;}
.wpvivid-tree-dashicons{
padding: 0 !important;
width: auto !important;
height: auto !important;
}
.wpvivid-tree-dashicons:before{
padding: 0 !important;
background-color: #007cba !important;
font-size: 20px !important;
color: #fff !important;
}
/**
* All of the CSS for your admin-specific functionality should be
* included in this file.
*/
.list-top-chip{float:left;display:block; vertical-align:middle; }
.list-top-chip::after{content:" "}
.backup-basic-info{min-width:100px; margin:10px; float:left;}
.quickbackup{width:calc(100% - 290px);float:left; box-sizing:border-box;margin-right:10px; padding:10px;}
.quickbackup label{display:inline-block;margin-bottom:10px;}
.qucikbackup-schedule{width:280px; float:left; box-sizing:border-box; min-width:280px;}
.quickstart-archive-block{width:33%;float:left; position:relative; box-sizing:border-box; }
.quickstart-storage-block{width:33%;padding:10px; float:left; position:relative; box-sizing:border-box;}
.quickstart-btn{width:33%;padding:10px; float:left; position:relative; box-sizing:border-box;}
.quickbackup-btn{display:block !important; margin:0 auto !important;width:150px;height:50px !important; line-height:48px !important; font-size:20px !important;}
.schedule-block{float:left;width:100%;padding:0 10px 10px 10px;box-sizing:border-box;}
.postbox:after{content: ".";display: block;height: 0;clear: both;visibility: hidden;}
.quickbackup-block .fieldset label{margin-bottom:5px;}
.custom-info{padding:10px;}
.quickstart-storage-setting{width:100%;float:left; padding-left:10px; box-sizing:border-box;background-color:#f1f1f1; margin-bottom:10px;}
.action-progress-bar{background-color:#f1f1f1 !important;margin:10px;color:#000;}
.action-progress-bar-percent{background-color:#0085ba !important;color:#fff;}
.storage-providers{float:left;padding:10px;cursor:pointer;}
.storage-providers:hover{background-color:#f1f1f1 !important; color:#fff !important;}
.storage-providers-active{background-color:#0085ba !important; color:#fff !important;}
.storage-account-block{padding:10px;}
.storage-account-button{margin:10px 10px 10px 0 !important;display:block !important; float:left;}
.schedule-tab-block{padding:10px;}
.schedule-tab-block input{display:line-block; margin-top:10px; margin-bottom:10px;margin-right:10px;}
.setting-tab-block{padding: 10px 10px 10px 0;}
.setting-tab-block input{display:line-block; margin-top:10px; margin-bottom:10px;margin-right:10px;}
.setting-page-content{padding-left:10px;}
.backup-log-btn{height:30px;float:left; margin-left:10px; margin-bottom:10px;}
@keyframes rotate { 0% { transform: rotate(0); } 100% { transform: rotate(359.9deg); } }
.wpvivid-backup-storage-list tr:hover,
.wpvivid-websiteinfo-list tr:hover,
.wpvivid-backuplist tr:hover,
.wpvivid-loglist tr:hover,
.wpvivid-remote-storage-list tr:hover {background-color: #f9f9f9;}
.restore_log{padding:10px; width:100%; height:500px; overflow:auto; box-sizing:border-box;}
.restore-button-position{margin:10px 10px 10px 0px; float:left;}
.restore-button-position input{margin-right:10px;}
.nav-tab.delete{display: block;overflow: hidden;position:relative;}
.nav-tab-delete-img{position: absolute;top: 0px;right: 3px;}
.button-secondary.log-page{background: #fff;color: #00a0d2;border: 1px solid #00a0d2;margin: 3px;}
.button-secondary.log-page:hover{color: #0b82a7;border: 1px solid #0b82a7;}
.button-secondary.log-page:focus{color: #00a0d2;border: 1px solid #00a0d2;}
.remote-storage-set-default-block{padding-top:10px;padding-left:10px;padding-right:10px;}
.remote-storage-set-default-block input{display:line-block; margin-top:10px; margin-bottom:10px;margin-right:10px;}
.remote-storage-ftp-passive-block,
.remote-storage-amazons3-storage-class,
.remote-storage-amazons3-encryption{padding-left:10px;}
.remote-storage-ftp-passive-block input,
.remote-storage-amazons3-storage-class input,
.remote-storage-amazons3-encryption input{display:line-block; margin-top:10px; margin-bottom:10px;margin-right:10px;}
.backup-list-head{}
.storage-account-form {padding-top: 1px; padding-bottom: 1px;}
.quicktransfer{width:100%; float:left; box-sizing:border-box;margin-right:10px; padding:10px;}
.quicktransfer label{display:inline-block;margin-bottom:10px;}
.quicktransfer-btn{display:block !important; margin:0 auto !important;width:220px;height:50px !important; line-height:48px !important; font-size:20px !important;}
.wpvivid-feature-pro{font-size:12px;border:1px solid #f1f1f1;padding:3px 5px;margin: 10px 10px 10px 0;border-radius:5px;}
@media screen and (max-width:1650px) {
.qucikbackup-schedule{
float:none;
width:100%;
}
.quickbackup{
float:none;
width:100%;
}
.export-import-block{
float:none;
width:100%;
}
}
@media only screen and (max-width: 1350px){
#poststuff #post-body.columns-2 {
margin:0;
}
#wpbody-content #post-body.columns-2 #postbox-container-1 {
margin-right: 0;
width: 100%;
}
}
@media screen and (max-width:1315px) {
.quickstart-storage-block{
width:50%;
}
.quickstart-archive-block{
width:50%;
}
.quickstart-btn{
clear:both;
float:none;
width:100%;
}
}
@media screen and (max-width:800px){
.tablelistcolumn{
display:block;
}
.backup-list-head{
display:none;
}
.backuptime{
font-size:16px;
}
.backuplist-delete-backup{
display:none;
}
.website-info-head{
display:none;
}
.log-head{
display:none;
}
.lafowef{
display:none;
}
.storage-account-form input{
width:360px;
}
}
@media screen and (max-width:600px) {
.quickstart-storage-block{
float:none;
width:100%;
}
.quickstart-archive-block{
float:none;
width:100%;
}
.quickstart-btn{
float:none;
width:100%;
}
}
/* Popup container */
.wpvivid-popup {
position: relative;
display: inline-block;
cursor: pointer;
}
/* The actual popup (appears on top) */
.wpvivid-popup .wpvivid-popuptext {
visibility: hidden;
width: 220px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 8px 0;
position: absolute;
z-index: 1;
bottom: 75%;
margin-left: -80px;
}
/* Popup arrow */
.wpvivid-popup .wpvivid-popuptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
/* Toggle this class when clicking on the popup container (hide and show the popup) */
.wpvivid-popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s
}
.wpvivid-popup .hide {
visibility: hidden;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s
}
/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}
@keyframes fadeIn {
from {opacity: 0;}
to {opacity:1 ;}
}
.wpvivid-storage-form{
margin-top:10px;
margin-bottom:5px;
}
.wpvivid-storage-select{
margin-top:10px;
margin-bottom:5px;
padding-bottom:8px;
padding-left:2px;
}
.wpvivid-storage-form input[type=text],
.wpvivid-storage-form input[type=password]{
width: 350px;
}
.wpvivid-storage-form-desc{
background-color:#f5f5f5;
margin-top:10px;
padding:4px 5px;
}
.wpvivid-debug-text-fix{
height: 28px;
line-height: 28px;
}
@media screen and (max-width: 782px) {
.wpvivid-debug-text-fix{
height: 36px;
line-height: 36px;
}
}
.wpvivid-text-space-bottom{margin-bottom: 5px;}
.wpvivid-text-space-right{margin-right: 5px;}
.wpvivid-element-space-bottom{margin-bottom: 10px;}
.wpvivid-element-space-right{margin-right: 10px;}
.wpvivid-export-type-provider{float: left; cursor: pointer; padding: 10px; height: 30px; line-height: 30px; border-right: 1px solid #e5e5e5;}
.wpvivid-export-type-provider:hover{background-color:#f1f1f1 !important; color:#fff !important;}
.wpvivid-export-type-provider-active{background-color:#0085ba !important; color:#fff !important;}
.wpvivid-import-log{padding:10px; width:100%; height:500px; overflow:auto; box-sizing:border-box;}
.import > tbody > :nth-child(odd) {background-color: #ffffff;}
.import > tbody tr:hover {background-color: #f9f9f9;}
.import .column-delete {width: 10%;}
.wpvivid-export-import-block span{margin: 0;}
.export-import-block{width:100%; box-sizing:border-box;margin-right:10px; padding:10px;}
.export-import-block label{display:inline-block;}
.export-import-block a{text-decoration: none;}
.wpvivid-canvas {
width:100%;
box-sizing: border-box;
}
.wpvivid-dashboard, .wpvivid-backup{
position: relative;
border: 1px solid #ccd0d4;
box-shadow: 0 1px 1px rgba(0,0,0,.04);
background: #fff;
}
.wpvivid-welcome-panel {
width:100%;
padding: 0px 10px 0;
border: 1px solid #ccd0d4;
box-shadow: 0 1px 1px rgba(0,0,0,.04);
background: #fff;
box-sizing: border-box;
}
.wpvivid-red {
background:red;
color:#fff;
}
.wpvivid-green {
background:#8bc34a;
color:#fff;
}
.wpvivid-blue {
background:#007cba;
color:#fff;
}
.wpvivid-orange {
background:orange;
color:#fff;
}
.wpvivid-grey {
background-color:grey;
color: #fff;
}
.wpvivid-grey-light {
background-color:#eee;
color: grey;
}
.wpvivid-hover-blue:hover{
background:#007cba;
color:#fff;
cursor:pointer;
}
.wpvivid-font-hover-blue:hover{
color:#007cba;
cursor:pointer;
}
.wpvivid-hover-green:hover{
background:#8bc34a;
color:#fff;
cursor:pointer;
}
span.dashicons{
margin-right:2px;
}
.wpvivid-welcome-panel .about-description{
font-size: 16px;
margin: 0;
}
.wpvivid-page-title {
font-weight: 700;
font-size:1.2em;
}
.wpvivid-dashicons-large {
font-size:5em;
width:1.2em;
height:1.2em;
float:left;
}
.wpvivid-dashicons-large:hover{
text-shadow: 0px 0px 2px rgba(0,0,0,0.4);
}
.wpvivid-dashicons-middle {
font-size:3em;
width:1.2em;
height:1.2em;
float:left;
}
.wpvivid-welcome-bar{
width:100%;
box-sizing: border-box;
}
.wpvivid-welcome-bar-left, .wpvivid-block-left {
width:50%;
float:left;
padding:1em;
box-sizing: border-box;
}
.wpvivid-welcome-bar-right, .wpvivid-block-right {
width:50%;
float:left;
padding:1em;
box-sizing: border-box;
}
.wpvivid-features-box, .wpvivid-two-cols{
width:50%;
float:left;
font:14px;
padding:1em 1em 1em 1em;
box-sizing: border-box;
}
.wpvivid-four-cols{
width:25%;
float:left;
font:14px;
box-sizing: border-box;
border:1px solid #f1f1f1;
}
.wpvivid-one-coloum {
width:100%;
float:left;
font:14px;
padding:1em 1em 1em 1em;
box-sizing: border-box;
}
.wpvivid-dashboard .wpvivid-two-col li {
border-bottom: 1px solid #eee;
margin: 0px;
padding: 10px;
box-sizing: border-box;
}
.wpvivid-dashboard .wpvivid-two-col li::after {
content: "";
clear: both;
display: table;
}
.wpvivid-dashboard .wpvivid-two-col li img {
padding:1em;
width: 5em;
height: 5em;
float: left;
margin: 0.5em;
}
.wpvivid-sidebar-main{
width:100%;
float:left;
font:13px;
box-sizing: border-box;
}
.wpvivid-sidebar-main li::after {
content: "";
clear: both;
display: table;
}
.wpvivid-sidebar-main li {
margin: 0px;
padding: 10px;
box-sizing: border-box;
}
.wpvivid-sidebar-main li img {
padding:1em;
width: 5em;
height: 5em;
float: left;
margin: 0.5em;
}
.wpvivid-sidebar{
width:100%;
float:left;
font:13px;
box-sizing: border-box;
}
.wpvivid-sidebar li::after {
content: "";
clear: both;
display: table;
}
.wpvivid-sidebar li {
border-bottom: 1px solid #eee;
margin: 0px;
padding: 10px;
box-sizing: border-box;
}
.wpvivid-sidebar li img {
padding:1em;
width: 5em;
height: 5em;
float: left;
margin: 0.5em;
}
.wpvivid-features-box-image-progress {
width:100%;
}
.wpvivid-features-box-image-optimiztion-details {
width:50%;
}
.wpvivid-features-box-image-optimiztion-plate {
width:50%;
}
.wpvivid-features-box-image-optimiztion-percentage{
margin-top:2.5em;
}
.wpvivid-features-box-image-optimiztion-number {
font-size: 5em;
font-family:Sans-serif;
font-weight:600;
color:orange;
float:left;
text-shadow:0 0.05em 0.05em rgba(0,0,0,0.4);
}
.wpvivid-features-box-image-optimiztion-percentage-unit {
font-size:1em;
color:grey;
float:left;
font-size:1.2em;
padding-bottom:1em;
}
.wpvivid-rectangle {
border-radius:0.4em;
padding:0.5em;
margin-left: 0.5em;
margin-right:0.5em;
font-size:0.8em;
}
.wpvivid-rectangle-small {
border-radius:0.4em;
padding:0.2em;
margin-left: 0.5em;
margin-right:0.5em;
font-size:0.6em;
}
.wpvivid-icon-16px{
font-size:16px;
margin-top:2px;
color:#aaa;
cursor:pointer;
}
.wpvivid-icon-16px-nopointer{
font-size:16px;
margin-top:2px;
}
.wpvivid-text-line{
padding:1px;
}
.wpvivid-text-selected{
background:#eee;
}
.wpvivid-text-line:hover{
background:#eee;
}
.wpvivid-span-progress {
display:block;
width:100%;
height:1.5em;
background-color:#9d9fa5;
border-radius:0;
color: #fff;
}
.wpvivid-span-processed-progress {
display:block;
height:1.5em;
background-color:#8bc34a;
border-radius:0;
color: #fff;
padding-left:0.5em;
}
.wpvivid-span-processed-percent-progress{
width:53%;
}
.wpvivid-clear-float {
content: "";
clear: both;
display: table;
width:100%;
}
.wpvivid-title {
font-size:1.2em;
color:#000;
}
.wpvivid-nav-bar{
width: 100%;
float: left;
padding: 1em;
background-color: #fff;
margin-bottom: 1em;
border-top:1px solid #ddd;
border-bottom:1px solid #ddd;
box-sizing: border-box;
}
.wpvivid-two-col{
width:50%;
float:left;
box-sizing: border-box;
}
.wpvivid-float-right{
float:right;
}
.wpvivid-float-left{
float:left;
}
.wpvivid-dashicons-white {
color:#ffffff;
}
.wpvivid-dashicons-green {
color:#8bc34a;
}
.wpvivid-dashicons-red {
color:red;
}
.wpvivid-dashicons-orange {
color:orange;
}
.wpvivid-dashicons-blue {
color:#007cba;
}
.wpvivid-dashicons-grey, .wpvivid-dashicons-editor-help{
color:#999;
}
.wpvivid-nav-tab-wrapper {
padding-bottom:0!important;
}
.wpvivid-nav-tab {
background:#ffffff;
}
.wpvivid-nav-tab-active,.wpvivid-nav-tab-active, .wpvivid-nav-tab-active:focus:active, .wpvivid-nav-tab-active:hover {
border-bottom:1px solid #ffffff;
background:#ffffff;
}
.wpvivid-tabcontent {
display: none;
}
.wpvivid-workflow {
padding:1em;
border:1px solid #eee;
border-radius:8px;
}
/* tooltip */
.wpvivid-tooltip {
display:inline-block;
position:relative;
text-align:left;
}
/* tooltip - top */
.wpvivid-top {
min-width:300px;
top:-20px;
left:50%;
transform:translate(-50%, -100%);
padding:10px 20px;
color:#444444;
background-color:#FFFFFF;
font-weight:normal;
font-size:13px;
border-radius:8px;
position:absolute;
z-index:99999999;
box-sizing:border-box;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
visibility:hidden; opacity:0; transition:opacity 0.8s;
}
.wpvivid-tooltip:hover .wpvivid-top {
visibility:visible; opacity:1;
}
.wpvivid-tooltip .wpvivid-top i {
position:absolute;
top:100%;
left:50%;
margin-left:-12px;
width:24px;
height:12px;
overflow:hidden;
}
.wpvivid-tooltip .wpvivid-top i::after {
content:'';
position:absolute;
width:12px;
height:12px;
left:50%;
transform:translate(-50%,-50%) rotate(45deg);
background-color:#FFFFFF;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
}
/* tooltip - bottom */
.wpvivid-bottom {
min-width:300px;
top:40px;
left:50%;
transform:translate(-50%, 0);
padding:10px 20px;
color:#444444;
background-color:#FFFFFF;
font-weight:normal;
font-size:13px;
border-radius:8px;
position:absolute;
z-index:99999999;
box-sizing:border-box;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
visibility:hidden; opacity:0; transition:opacity 0.4s;
}
.wpvivid-dashicons-editor-help:hover .wpvivid-bottom {
visibility:visible; opacity:1;
}
.wpvivid-dashicons-white:hover .wpvivid-bottom{
visibility:visible; opacity:1;
}
.wpvivid-tooltip .wpvivid-bottom i {
position:absolute;
bottom:100%;
left:50%;
margin-left:-12px;
width:24px;
height:12px;
overflow:hidden;
}
.wpvivid-tooltip .wpvivid-bottom i::after {
content:'';
position:absolute;
width:12px;
height:12px;
left:50%;
transform:translate(-50%,50%) rotate(45deg);
background-color:#FFFFFF;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
}
/* tooltip - left */
.wpvivid-left {
min-width:300px;
top:50%;
right:100%;
margin-right:20px;
transform:translate(0, -50%);
padding:10px 20px;
color:#444444;
background-color:#FFFFFF;
font-weight:normal;
font-size:13px;
border-radius:8px;
position:absolute;
z-index:99999999;
box-sizing:border-box;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
visibility:hidden; opacity:0; transition:opacity 0.8s;
}
.wpvivid-tooltip:hover .wpvivid-left {
visibility:visible; opacity:1;
}
.wpvivid-tooltip .wpvivid-left i {
position:absolute;
top:50%;
left:100%;
margin-top:-12px;
width:12px;
height:24px;
overflow:hidden;
}
.wpvivid-tooltip .wpvivid-left i::after {
content:'';
position:absolute;
width:12px;
height:12px;
left:0;
top:50%;
transform:translate(-50%,-50%) rotate(-45deg);
background-color:#FFFFFF;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
}
/* tooltip - right */
.wpvivid-right {
min-width:300px;
top:50%;
left:100%;
margin-left:20px;
transform:translate(0, -50%);
padding:10px 20px;
color:#444444;
background-color:#FFFFFF;
font-weight:normal;
font-size:13px;
border-radius:8px;
position:absolute;
z-index:99999999;
box-sizing:border-box;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
visibility:hidden;
opacity:0;
transition:opacity 0.8s;
}
.wpvivid-tooltip:hover .wpvivid-right {
visibility:visible; opacity:1;
}
.wpvivid-installer-list li{
padding:0.2em 0;
}
.wpvivid-tooltip .wpvivid-right i {
position:absolute;
top:50%;
right:100%;
margin-top:-12px;
width:12px;
height:24px;
overflow:hidden;
}
.wpvivid-tooltip .wpvivid-right i::after {
content:'';
position:absolute;
width:12px;
height:12px;
left:0;
top:50%;
transform:translate(50%,-50%) rotate(-45deg);
background-color:#FFFFFF;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
}
/* radio box style */
.wpvivid-radio {
display: block;
position: relative;
padding-left: 2em;
margin-bottom: 1em;
cursor: pointer;
font-size: 1em;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Hide the browser's default radio button */
.wpvivid-radio input {
position: absolute;
opacity: 0;
cursor: pointer;
}
/* Create a custom radio button */
.wpvivid-radio-checkmark {
position: absolute;
top: 2px;
left: 0;
height: 16px;
width: 16px;
background-color: #eee;
border-radius: 50%;
}
/* On mouse-over, add a grey background color */
.wpvivid-radio:hover input ~ .wpvivid-radio-checkmark {
background-color: #ccc;
}
/* When the radio button is checked, add a blue background */
.wpvivid-radio input:checked ~ .wpvivid-radio-checkmark {
background-color: #8bc34a;
}
/* Create the indicator (the dot/circle - hidden when not checked) */
.wpvivid-radio-checkmark:after {
content: "✔";
position: absolute;
font-size:12px;
top:-1px;
left:3px;
display: none;
color:white;
}
/* Show the indicator (dot/circle) when checked */
.wpvivid-radio input:checked ~ .wpvivid-radio-checkmark:after {
display: block;
}
/* custom checkbox */
/* Customize the label (the container) */
.wpvivid-checkbox {
display: block;
position: relative;
padding-left: 2em;
cursor: pointer;
font-size: 1em;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Hide the browser's default checkbox */
.wpvivid-checkbox input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
/* Create a custom checkbox */
.wpvivid-checkbox-checkmark {
position: absolute;
top: 3px;
left: 0;
height: 16px;
width: 16px;
background-color: #eee;
border-radius: 4px;
}
/* On mouse-over, add a grey background color */
.wpvivid-checkbox:hover input ~ .wpvivid-checkbox-checkmark {
background-color: #ccc;
border-radius: 4px;
}
/* When the checkbox is checked, add a blue background */
.wpvivid-checkbox input:checked ~ .wpvivid-checkbox-checkmark {
background-color: #8bc34a;
border-radius: 4px;
}
/* Create the checkmark/indicator (hidden when not checked) */
.wpvivid-checkbox-checkmark:after {
content: "";
position: absolute;
display: none;
}
/* Show the checkmark when checked */
.wpvivid-checkbox input:checked ~ .wpvivid-checkbox-checkmark:after {
display: block;
}
/* Style the checkmark/indicator */
.wpvivid-checkbox .wpvivid-checkbox-checkmark:after {
left: 4px;
top: 0px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0px 3px 3px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
/* toggle switch */
/* The switch - the box around the slider */
.wpvivid-switch {
position: relative;
display: inline-block;
width: 32px;
height: 16px;
}
/* Hide default HTML checkbox */
.wpvivid-switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.wpvivid-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0px;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.wpvivid-slider:before {
position: absolute;
content: "";
height: 12px;
width: 12px;
left: 2px;
bottom: 2px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .wpvivid-slider {
background-color: #8bc34a;
}
input:focus + .wpvivid-slider {
box-shadow: 0 0 1px #8bc34a;
}
input:checked + .wpvivid-slider:before {
-webkit-transform: translateX(16px);
-ms-transform: translateX(16px);
transform: translateX(16px);
}
/* Rounded sliders */
.wpvivid-slider.wpvivid-round {
border-radius: 16px;
}
.wpvivid-slider.wpvivid-round:before {
border-radius: 50%;
}
/*general postion*/
.wpvivid-tooltip-padding-top {
padding-top:0.2em;
}
.wpvivid-tooltip-padding-top-small {
padding-top:0.1em;
}
/* HD computer monitor */
@media only screen and (min-width: 1366px) {
.wpvivid-four-cols{
width:100%;
margin-bottom:1em;
}
}
/* Tablets in landscape mode, older desktop monitors */
@media only screen and (min-width: 1024px) and (max-width: 1365px) {
#poststuff #post-body.columns-2 {
margin-right: 0px;
}
#wpbody-content #post-body.columns-2 #postbox-container-1 {
margin-right: 0;
width: 100%;
}
.wpvivid-four-cols{
width:100%;
margin-bottom:1em;
}
}
/* Tablets in portrait mode, large display smartphones landscape mode */
@media only screen and (min-width: 768px) and (max-width: 1023px) {
.wpvivid-two-col {
width:100%;
}
.wpvivid-float-right{
float:left;
}
.wpvivid-four-cols{
width:100%;
margin-bottom:1em;
}
..wpvivid-welcome-bar-left{
width:100%;
}
.wpvivid-welcome-bar-right{
display:none;
}
.wpvivid-ignore{
display:none;
}
}
/* Smartphones in landscape mode */
@media only screen and (min-width: 421px) and (max-width: 767px) {
.wpvivid-features-box,.wpvivid-two-col {
width:100%;
}
.wpvivid-float-right{
float:left;
}
.wpvivid-welcome-bar-left{
width:100%;
}
.wpvivid-welcome-bar-right{
display:none;
}
.wpvivid-four-cols{
width:100%;
margin-bottom:1em;
}
.wpvivid-ignore{
display:none;
}
}
/* Smartphones in portrait mode */
@media only screen and (max-width: 420px) {
.wpvivid-features-box,.wpvivid-two-col {
width:100%;
}
.wpvivid-float-right{
float:left;
}
.wpvivid-welcome-bar-left{
width:100%;
}
.wpvivid-welcome-bar-right{
display:none;
}
.wpvivid-four-cols{
width:100%;
margin-bottom:1em;
}
.wpvivid-ignore{
display:none;
}
.wpvivid-img-opt-responsive{
margin-top:1em;
padding-top:1em;
border-top:1px solid #f1f1f1;
}
}
admin/css/wpvivid-admin.css 0000644 00000020422 15132770567 0011731 0 ustar 00 /**
* All of the CSS for your admin-specific functionality should be
* included in this file.
*/
.list-top-chip{float:left;display:block; vertical-align:middle; }
.list-top-chip::after{content:" "}
.backup-basic-info{min-width:100px; margin:10px; float:left;}
.quickbackup{width:calc(100% - 290px);float:left; box-sizing:border-box;margin-right:10px; padding:10px;}
.quickbackup label{display:inline-block;margin-bottom:10px;}
.qucikbackup-schedule{width:280px; float:left; box-sizing:border-box; min-width:280px;}
.quickstart-archive-block{width:33%;float:left; position:relative; box-sizing:border-box; }
.quickstart-storage-block{width:33%;padding:10px; float:left; position:relative; box-sizing:border-box;}
.quickstart-btn{width:33%;padding:10px; float:left; position:relative; box-sizing:border-box;}
.quickbackup-btn{display:block !important; margin:0 auto !important;width:150px;height:50px !important; line-height:48px !important; font-size:20px !important;}
.schedule-block{float:left;width:100%;padding:0 10px 10px 10px;box-sizing:border-box;}
.postbox:after{content: ".";display: block;height: 0;clear: both;visibility: hidden;}
.quickbackup-block .fieldset label{margin-bottom:5px;}
.custom-info{padding:10px;}
.quickstart-storage-setting{width:100%;float:left; padding-left:10px; box-sizing:border-box;background-color:#f1f1f1; margin-bottom:10px;}
.action-progress-bar{background-color:#f1f1f1 !important;margin:10px;color:#000;}
.action-progress-bar-percent{background-color:#0085ba !important;color:#fff;}
.storage-providers{float:left;padding:10px;cursor:pointer;}
.storage-providers:hover{background-color:#f1f1f1 !important; color:#fff !important;}
.storage-providers-active{background-color:#0085ba !important; color:#fff !important;}
.storage-account-block{padding:10px;}
.storage-account-button{margin:10px 10px 10px 0 !important;display:block !important; float:left;}
.schedule-tab-block{padding:10px;}
.schedule-tab-block input{display:line-block; margin-top:10px; margin-bottom:10px;margin-right:10px;}
.setting-tab-block{padding: 10px 10px 10px 0;}
.setting-tab-block input{display:line-block; margin-top:10px; margin-bottom:10px;margin-right:10px;}
.setting-page-content{padding-left:10px;}
.backup-log-btn{height:30px;float:left; margin-left:10px; margin-bottom:10px;}
@keyframes rotate { 0% { transform: rotate(0); } 100% { transform: rotate(359.9deg); } }
.wpvivid-backup-storage-list tr:hover,
.wpvivid-websiteinfo-list tr:hover,
.wpvivid-backuplist tr:hover,
.wpvivid-loglist tr:hover,
.wpvivid-remote-storage-list tr:hover {background-color: #f9f9f9;}
.restore_log{padding:10px; width:100%; height:500px; overflow:auto; box-sizing:border-box;}
.restore-button-position{margin:10px 10px 10px 0px; float:left;}
.restore-button-position input{margin-right:10px;}
.nav-tab.delete{display: block;overflow: hidden;position:relative;}
.nav-tab-delete-img{position: absolute;top: 0px;right: 3px;}
.button-secondary.log-page{background: #fff;color: #00a0d2;border: 1px solid #00a0d2;margin: 3px;}
.button-secondary.log-page:hover{color: #0b82a7;border: 1px solid #0b82a7;}
.button-secondary.log-page:focus{color: #00a0d2;border: 1px solid #00a0d2;}
.remote-storage-set-default-block{padding-top:10px;padding-left:10px;padding-right:10px;}
.remote-storage-set-default-block input{display:line-block; margin-top:10px; margin-bottom:10px;margin-right:10px;}
.remote-storage-ftp-passive-block,
.remote-storage-amazons3-storage-class,
.remote-storage-amazons3-encryption{padding-left:10px;}
.remote-storage-ftp-passive-block input,
.remote-storage-amazons3-storage-class input,
.remote-storage-amazons3-encryption input{display:line-block; margin-top:10px; margin-bottom:10px;margin-right:10px;}
.backup-list-head{}
.storage-account-form {padding-top: 1px; padding-bottom: 1px;}
.quicktransfer{width:100%; float:left; box-sizing:border-box;margin-right:10px; padding:10px;}
.quicktransfer label{display:inline-block;margin-bottom:10px;}
.quicktransfer-btn{display:block !important; margin:0 auto !important;width:220px;height:50px !important; line-height:48px !important; font-size:20px !important;}
.wpvivid-feature-pro{font-size:12px;border:1px solid #f1f1f1;padding:3px 5px;margin: 10px 10px 10px 0;border-radius:5px;}
@media screen and (max-width:1650px) {
.qucikbackup-schedule{
float:none;
width:100%;
}
.quickbackup{
float:none;
width:100%;
}
.export-import-block{
float:none;
width:100%;
}
}
@media only screen and (max-width: 1350px){
#poststuff #post-body.columns-2 {
margin:0;
}
#wpbody-content #post-body.columns-2 #postbox-container-1 {
margin-right: 0;
width: 100%;
}
}
@media screen and (max-width:1315px) {
.quickstart-storage-block{
width:50%;
}
.quickstart-archive-block{
width:50%;
}
.quickstart-btn{
clear:both;
float:none;
width:100%;
}
}
@media screen and (max-width:800px){
.tablelistcolumn{
display:block;
}
.backup-list-head{
display:none;
}
.backuptime{
font-size:16px;
}
.backuplist-delete-backup{
display:none;
}
.website-info-head{
display:none;
}
.log-head{
display:none;
}
.lafowef{
display:none;
}
.storage-account-form input{
width:360px;
}
}
@media screen and (max-width:600px) {
.quickstart-storage-block{
float:none;
width:100%;
}
.quickstart-archive-block{
float:none;
width:100%;
}
.quickstart-btn{
float:none;
width:100%;
}
}
/* Popup container */
.wpvivid-popup {
position: relative;
display: inline-block;
cursor: pointer;
}
/* The actual popup (appears on top) */
.wpvivid-popup .wpvivid-popuptext {
visibility: hidden;
width: 220px;
background-color: #555;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 8px 0;
position: absolute;
z-index: 1;
bottom: 75%;
margin-left: -80px;
}
/* Popup arrow */
.wpvivid-popup .wpvivid-popuptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
/* Toggle this class when clicking on the popup container (hide and show the popup) */
.wpvivid-popup .show {
visibility: visible;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s
}
.wpvivid-popup .hide {
visibility: hidden;
-webkit-animation: fadeIn 1s;
animation: fadeIn 1s
}
/* Add animation (fade in the popup) */
@-webkit-keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}
@keyframes fadeIn {
from {opacity: 0;}
to {opacity:1 ;}
}
.wpvivid-storage-form{
margin-top:10px;
margin-bottom:5px;
}
.wpvivid-storage-select{
margin-top:10px;
margin-bottom:5px;
padding-bottom:8px;
padding-left:2px;
}
.wpvivid-storage-form input[type=text],
.wpvivid-storage-form input[type=password]{
width: 350px;
}
.wpvivid-storage-form-desc{
background-color:#f5f5f5;
margin-top:10px;
padding:4px 5px;
}
.wpvivid-debug-text-fix{
height: 28px;
line-height: 28px;
}
@media screen and (max-width: 782px) {
.wpvivid-debug-text-fix{
height: 36px;
line-height: 36px;
}
}
.wpvivid-text-space-bottom{margin-bottom: 5px;}
.wpvivid-text-space-right{margin-right: 5px;}
.wpvivid-element-space-bottom{margin-bottom: 10px;}
.wpvivid-element-space-right{margin-right: 10px;}
.wpvivid-export-type-provider{float: left; cursor: pointer; padding: 10px; height: 30px; line-height: 30px; border-right: 1px solid #e5e5e5;}
.wpvivid-export-type-provider:hover{background-color:#f1f1f1 !important;}
.wpvivid-export-type-provider-active{background-color:#0085ba !important;}
.wpvivid-import-log{padding:10px; width:100%; height:500px; overflow:auto; box-sizing:border-box;}
.import > tbody > :nth-child(odd) {background-color: #ffffff;}
.import > tbody tr:hover {background-color: #f9f9f9;}
.import .column-delete {width: 10%;}
.wpvivid-export-import-block span{margin: 0;}
.export-import-block{width:100%; box-sizing:border-box;margin-right:10px; padding:10px;}
.export-import-block label{display:inline-block;}
.export-import-block a{text-decoration: none;}
.quickbackup-addon{width:100%; box-sizing:border-box;margin-right:10px; padding:10px;}
.quickbackup-addon label{display:inline-block;}
@media screen and (max-width:1650px) {
.quickbackup-addon{
float:none;
width:100%;
}
}
.quickbackup-addon a{
text-decoration: none;
}
.wpvivid-backup-tips{
float:left;
width:100%;
background-color:#f1f1f1;
}
.wpvivid-custom-table-manager.nav-tab-wrapper :nth-child(n+3):nth-child(-n+11) {
display:block;
} admin/css/wpvivid-snapshot-style.css 0000644 00000051132 15132770567 0013640 0 ustar 00 /**
* All of the CSS for WPvivid Plugins Dashboard should be
* included in this file.
*/
.wpvivid-canvas {
max-width:1600px;
box-sizing: border-box;
}
.wpvivid-dashboard, .wpvivid-backup{
position: relative;
border: 1px solid #ccd0d4;
box-shadow: 0 1px 1px rgba(0,0,0,.04);
background: #fff;
}
.wpvivid-welcome-panel {
width:100%;
padding: 0px 10px 0;
border: 1px solid #ccd0d4;
box-shadow: 0 1px 1px rgba(0,0,0,.04);
background: #fff;
box-sizing: border-box;
}
.wpvivid-red {
background:red;
color:#fff;
}
.wpvivid-green {
background:#8bc34a;
color:#fff;
}
.wpvivid-blue {
background:#007cba;
color:#fff;
}
.wpvivid-orange {
background:orange;
color:#fff;
}
.wpvivid-grey {
background-color:grey;
color: #fff;
}
span.dashicons{
margin-right:2px;
}
.wpvivid-welcome-panel .about-description{
font-size: 16px;
margin: 0;
}
.wpvivid-page-title {
font-weight: 700;
font-size:1.2em;
}
.wpvivid-dashicons-large {
font-size:5em;
width:1.2em;
height:1.2em;
float:left;
}
.wpvivid-dashicons-large:hover{
text-shadow: 0px 0px 2px rgba(0,0,0,0.4);
}
.wpvivid-dashicons-middle {
font-size:3em;
width:1.2em;
height:1.2em;
float:left;
}
.wpvivid-welcome-bar{
width:100%;
box-sizing: border-box;
}
.wpvivid-welcome-bar-left, .wpvivid-block-left {
width:50%;
float:left;
padding:1em;
box-sizing: border-box;
}
.wpvivid-welcome-bar-right, .wpvivid-block-right {
width:50%;
float:left;
padding:1em;
box-sizing: border-box;
}
.wpvivid-features-box, .wpvivid-two-cols{
width:50%;
float:left;
font-size:14px;
padding:1em 1em 1em 1em;
box-sizing: border-box;
}
.wpvivid-four-cols{
width:25%;
float:left;
font-size:14px;
box-sizing: border-box;
border:1px solid #f1f1f1;
}
.wpvivid-one-coloum {
width:100%;
float:left;
padding:1em 1em 1em 1em;
box-sizing: border-box;
}
.wpvivid-dashboard-list {
padding:1em;
border:1px solid #eee;
box-sizing: border-box;
}
.wpvivid-dashboard li {
border: 1px solid #eee;
margin: 0px;
padding: 10px;
box-sizing: border-box;
}
.wpvivid-dashboard li::after {
content: "";
clear: both;
display: table;
}
.wpvivid-dashboard .wpvivid-two-col li {
border: 1px solid #eee;
margin: 0px;
padding: 10px;
box-sizing: border-box;
}
.wpvivid-dashboard .wpvivid-two-col li::after {
content: "";
clear: both;
display: table;
}
.wpvivid-dashboard .wpvivid-three-cols li img {
padding:1em;
width: 5em;
height: 5em;
float: left;
margin: 0.5em;
}
.wpvivid-dashboard .wpvivid-two-col .wpvivid-three-cols li img {
padding:1em;
width: 5em;
height: 5em;
float: left;
margin: 0.5em;
}
.wpvivid-dashboard .wpvivid-three-cols li
{
width:33%;
float:left;
box-sizing: border-box;
}
.wpvivid-dashboard .wpvivid-three-cols-update{
position:absolute;
display:block;
width:1.5em;
height:1.5em;
border:1px solid orange;
border-radius:50%;
text-align:center;
vertical-align:middle;
background:orange;
color:#fff;
}
.wpvivid-dashboard .wpvivid-three-cols li {
border: 1px solid #eee;
padding:0.2em 0.2em 0 0.2em;
box-sizing: border-box;
}
.wpvivid-dashboard .wpvivid-three-cols li::after {
content: "";
clear: both;
display: table;
}
.wpvivid-dashboard .wpvivid-three-cols-li {
padding:0.5em 0;
}
.wpvivid-dashboard .wpvivid-three-cols-active {
background:#eaf1fe;
}
.wpvivid-sidebar-main{
width:100%;
float:left;
font-size:13px;
box-sizing: border-box;
}
.wpvivid-sidebar-main li::after {
content: "";
clear: both;
display: table;
}
.wpvivid-sidebar-main li {
margin: 0px;
padding: 10px;
box-sizing: border-box;
}
.wpvivid-sidebar-main li img {
padding:1em;
width: 5em;
height: 5em;
float: left;
margin: 0.5em;
}
.wpvivid-sidebar{
width:100%;
float:left;
font-size:13px;
box-sizing: border-box;
}
.wpvivid-sidebar li::after {
content: "";
clear: both;
display: table;
}
.wpvivid-sidebar li {
border-bottom: 1px solid #eee;
margin: 0px;
padding: 10px;
box-sizing: border-box;
}
.wpvivid-sidebar li img {
padding:1em;
width: 5em;
height: 5em;
float: left;
margin: 0.5em;
}
.wpvivid-features-box-image-progress {
width:100%;
}
.wpvivid-features-box-image-optimiztion-details {
width:50%;
}
.wpvivid-features-box-image-optimiztion-plate {
width:50%;
}
.wpvivid-features-box-image-optimiztion-percentage{
margin-top:2.5em;
}
.wpvivid-features-box-image-optimiztion-number {
font-size: 5em;
font-family:Sans-serif;
font-weight:600;
color:orange;
float:left;
text-shadow:0 0.05em 0.05em rgba(0,0,0,0.4);
}
.wpvivid-features-box-image-optimiztion-percentage-unit {
font-size:1em;
color:grey;
float:left;
font-size:1.2em;
padding-bottom:1em;
}
.wpvivid-rectangle {
border-radius:0.4em;
padding:0.5em;
margin-left: 0.5em;
margin-right:0.5em;
font-size:0.8em;
}
.wpvivid-rectangle-small {
border-radius:0.4em;
padding:0.2em;
margin-left: 0.5em;
margin-right:0.5em;
font-size:0.6em;
}
.wpvivid-span-progress {
display:block;
width:100%;
height:1.5em;
background-color:#9d9fa5;
border-radius:0;
color: #fff;
}
.wpvivid-span-processed-progress {
display:block;
height:1.5em;
background-color:#8bc34a;
border-radius:0;
color: #fff;
padding-left:0.5em;
}
.wpvivid-span-processed-percent-progress{
width:53%;
}
.wpvivid-clear-float {
content: "";
clear: both;
display: table;
width:100%;
}
.wpvivid-title {
font-size:1.2em;
color:#000;
}
.wpvivid-nav-bar{
width: 100%;
float: left;
padding: 1em;
background-color: #fff;
margin-bottom: 1em;
border-top:1px solid #ddd;
border-bottom:1px solid #ddd;
box-sizing: border-box;
}
.wpvivid-two-col{
width:50%;
float:left;
box-sizing: border-box;
}
.wpvivid-float-right{
float:right;
}
.wpvivid-float-left{
float:left;
}
.wpvivid-dashicons-green {
color:#8bc34a;
}
.wpvivid-dashicons-red {
color:red;
}
.wpvivid-dashicons-orange {
color:orange;
}
.wpvivid-dashicons-blue {
color:#007cba;
}
.wpvivid-dashicons-grey, .wpvivid-dashicons-editor-help{
color:#999;
}
.wpvivid-nav-tab-wrapper {
padding-bottom:0!important;
}
.wpvivid-nav-tab {
background:#ffffff;
}
.wpvivid-nav-tab-active,.wpvivid-nav-tab-active, .wpvivid-nav-tab-active:focus:active, .wpvivid-nav-tab-active:hover {
border-bottom:1px solid #ffffff;
background:#ffffff;
}
.wpvivid-tabcontent {
display: none;
}
.wpvivid-workflow {
padding:1em;
border:1px solid #eee;
border-radius:8px;
}
/* tooltip */
.wpvivid-tooltip {
display:inline-block;
position:relative;
text-align:left;
}
/* tooltip - top */
.wpvivid-top {
min-width:300px;
top:-20px;
left:50%;
transform:translate(-50%, -100%);
padding:10px 20px;
color:#444444;
background-color:#FFFFFF;
font-weight:normal;
font-size:13px;
border-radius:8px;
position:absolute;
z-index:99999999;
box-sizing:border-box;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
visibility:hidden; opacity:0; transition:opacity 0.8s;
}
.wpvivid-tooltip:hover .wpvivid-top {
visibility:visible; opacity:1;
}
.wpvivid-tooltip .wpvivid-top i {
position:absolute;
top:100%;
left:50%;
margin-left:-12px;
width:24px;
height:12px;
overflow:hidden;
}
.wpvivid-tooltip .wpvivid-top i::after {
content:'';
position:absolute;
width:12px;
height:12px;
left:50%;
transform:translate(-50%,-50%) rotate(45deg);
background-color:#FFFFFF;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
}
/* tooltip - bottom */
.wpvivid-bottom {
min-width:300px;
top:40px;
left:50%;
transform:translate(-50%, 0);
padding:10px 20px;
color:#444444;
background-color:#FFFFFF;
font-weight:normal;
font-size:13px;
border-radius:8px;
position:absolute;
z-index:99999999;
box-sizing:border-box;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
visibility:hidden; opacity:0; transition:opacity 0.4s;
}
.wpvivid-dashicons-editor-help:hover .wpvivid-bottom {
visibility:visible; opacity:1;
}
.wpvivid-dashicons-white-editor-help:hover .wpvivid-bottom {
visibility:visible; opacity:1;
}
.wpvivid-dashicons-white:hover .wpvivid-bottom {
visibility:visible; opacity:1;
}
.wpvivid-tooltip .wpvivid-bottom i {
position:absolute;
bottom:100%;
left:50%;
margin-left:-12px;
width:24px;
height:12px;
overflow:hidden;
}
.wpvivid-tooltip .wpvivid-bottom i::after {
content:'';
position:absolute;
width:12px;
height:12px;
left:50%;
transform:translate(-50%,50%) rotate(45deg);
background-color:#FFFFFF;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
}
/* tooltip - left */
.wpvivid-left {
min-width:300px;
top:50%;
right:100%;
margin-right:20px;
transform:translate(0, -50%);
padding:10px 20px;
color:#444444;
background-color:#FFFFFF;
font-weight:normal;
font-size:13px;
border-radius:8px;
position:absolute;
z-index:99999999;
box-sizing:border-box;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
visibility:hidden; opacity:0; transition:opacity 0.8s;
}
.wpvivid-tooltip:hover .wpvivid-left {
visibility:visible; opacity:1;
}
.wpvivid-tooltip .wpvivid-left i {
position:absolute;
top:50%;
left:100%;
margin-top:-12px;
width:12px;
height:24px;
overflow:hidden;
}
.wpvivid-tooltip .wpvivid-left i::after {
content:'';
position:absolute;
width:12px;
height:12px;
left:0;
top:50%;
transform:translate(-50%,-50%) rotate(-45deg);
background-color:#FFFFFF;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
}
/* tooltip - right */
.wpvivid-right {
min-width:300px;
top:50%;
left:100%;
margin-left:20px;
transform:translate(0, -50%);
padding:10px 20px;
color:#444444;
background-color:#FFFFFF;
font-weight:normal;
font-size:13px;
border-radius:8px;
position:absolute;
z-index:99999999;
box-sizing:border-box;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
visibility:hidden;
opacity:0;
transition:opacity 0.8s;
}
.wpvivid-tooltip:hover .wpvivid-right {
visibility:visible; opacity:1;
}
.wpvivid-installer-list li{
padding:0.2em 0;
}
.wpvivid-tooltip .wpvivid-right i {
position:absolute;
top:50%;
right:100%;
margin-top:-12px;
width:12px;
height:24px;
overflow:hidden;
}
.wpvivid-tooltip .wpvivid-right i::after {
content:'';
position:absolute;
width:12px;
height:12px;
left:0;
top:50%;
transform:translate(50%,-50%) rotate(-45deg);
background-color:#FFFFFF;
box-shadow:0 1px 8px rgba(0,0,0,0.5);
}
/* radio box style */
.wpvivid-radio {
display: block;
position: relative;
padding-left: 2em;
margin-bottom: 1em;
cursor: pointer;
font-size: 1em;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Hide the browser's default radio button */
.wpvivid-radio input {
position: absolute;
opacity: 0;
cursor: pointer;
}
/* Create a custom radio button */
.wpvivid-radio-checkmark {
position: absolute;
top: 2px;
left: 0;
height: 16px;
width: 16px;
background-color: #eee;
border-radius: 50%;
}
/* On mouse-over, add a grey background color */
.wpvivid-radio:hover input ~ .wpvivid-radio-checkmark {
background-color: #ccc;
}
/* When the radio button is checked, add a blue background */
.wpvivid-radio input:checked ~ .wpvivid-radio-checkmark {
background-color: #8bc34a;
}
/* Create the indicator (the dot/circle - hidden when not checked) */
.wpvivid-radio-checkmark:after {
content: "✔";
position: absolute;
font-size:12px;
top:-1px;
left:3px;
display: none;
color:white;
}
/* Show the indicator (dot/circle) when checked */
.wpvivid-radio input:checked ~ .wpvivid-radio-checkmark:after {
display: block;
}
/* custom checkbox */
/* Customize the label (the container) */
.wpvivid-checkbox {
display: block;
position: relative;
padding-left: 2em;
cursor: pointer;
font-size: 1em;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Hide the browser's default checkbox */
.wpvivid-checkbox input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}
/* Create a custom checkbox */
.wpvivid-checkbox-checkmark {
position: absolute;
top: 3px;
left: 0;
height: 16px;
width: 16px;
background-color: #eee;
border-radius: 4px;
}
/* On mouse-over, add a grey background color */
.wpvivid-checkbox:hover input ~ .wpvivid-checkbox-checkmark {
background-color: #ccc;
border-radius: 4px;
}
/* When the checkbox is checked, add a blue background */
.wpvivid-checkbox input:checked ~ .wpvivid-checkbox-checkmark {
background-color: #8bc34a;
border-radius: 4px;
}
/* Create the checkmark/indicator (hidden when not checked) */
.wpvivid-checkbox-checkmark:after {
content: "";
position: absolute;
display: none;
}
/* Show the checkmark when checked */
.wpvivid-checkbox input:checked ~ .wpvivid-checkbox-checkmark:after {
display: block;
}
/* Style the checkmark/indicator */
.wpvivid-checkbox .wpvivid-checkbox-checkmark:after {
left: 4px;
top: 0px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0px 3px 3px 0;
-webkit-transform: rotate(45deg);
-ms-transform: rotate(45deg);
transform: rotate(45deg);
}
/* toggle switch */
/* The switch - the box around the slider */
.wpvivid-switch {
position: relative;
display: inline-block;
width: 32px;
height: 16px;
}
/* Hide default HTML checkbox */
.wpvivid-switch input {
opacity: 0;
width: 0;
height: 0;
}
/* The slider */
.wpvivid-slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0px;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.wpvivid-slider:before {
position: absolute;
content: "";
height: 12px;
width: 12px;
left: 2px;
bottom: 2px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .wpvivid-slider {
background-color: #8bc34a;
}
input:focus + .wpvivid-slider {
box-shadow: 0 0 1px #8bc34a;
}
input:checked + .wpvivid-slider:before {
-webkit-transform: translateX(16px);
-ms-transform: translateX(16px);
transform: translateX(16px);
}
/* Rounded sliders */
.wpvivid-slider.wpvivid-round {
border-radius: 16px;
}
.wpvivid-slider.wpvivid-round:before {
border-radius: 50%;
}
/*general postion*/
.wpvivid-tooltip-padding-top {
padding-top:0.2em;
}
.wpvivid-tooltip-padding-top-small {
padding-top:0.1em;
}
/* HD computer monitor */
@media only screen and (min-width: 1366px) {
.wpvivid-four-cols{
width:100%;
margin-bottom:1em;
}
}
/* Tablets in landscape mode, older desktop monitors */
@media only screen and (min-width: 1024px) and (max-width: 1365px) {
#poststuff #post-body.columns-2 {
margin-right: 0px;
}
#wpbody-content #post-body.columns-2 #postbox-container-1 {
margin-right: 0;
width: 100%;
}
.wpvivid-four-cols{
width:100%;
margin-bottom:1em;
}
}
/* Tablets in portrait mode, large display smartphones landscape mode */
@media only screen and (min-width: 768px) and (max-width: 1023px) {
.wpvivid-two-col {
width:100%;
}
.wpvivid-float-right{
float:left;
}
.wpvivid-dashboard .wpvivid-three-cols li{
width:100%;
box-sizing: border-box;
}
.wpvivid-four-cols{
width:100%;
margin-bottom:1em;
}
.wpvivid-welcome-bar-left{
width:100%;
}
.wpvivid-welcome-bar-right{
display:none;
}
.wpvivid-ignore{
display:none;
}
}
/* Smartphones in landscape mode */
@media only screen and (min-width: 421px) and (max-width: 767px) {
.wpvivid-features-box,.wpvivid-two-col {
width:100%;
}
.wpvivid-float-right{
float:left;
}
.wpvivid-welcome-bar-left{
width:100%;
}
.wpvivid-welcome-bar-right{
display:none;
}
.wpvivid-four-cols{
width:100%;
margin-bottom:1em;
}
.wpvivid-ignore{
display:none;
}
.wpvivid-dashboard .wpvivid-three-cols li{
width:100%;
box-sizing: border-box;
}
}
/* Smartphones in portrait mode */
@media only screen and (max-width: 420px) {
.wpvivid-features-box,.wpvivid-two-col {
width:100%;
}
.wpvivid-float-right{
float:left;
}
.wpvivid-welcome-bar-left{
width:100%;
}
.wpvivid-welcome-bar-right{
display:none;
}
.wpvivid-four-cols{
width:100%;
margin-bottom:1em;
}
.wpvivid-ignore{
display:none;
}
.wpvivid-img-opt-responsive{
margin-top:1em;
padding-top:1em;
border-top:1px solid #f1f1f1;
}
.wpvivid-dashboard .wpvivid-three-cols li{
width:100%;
box-sizing: border-box;
}
}
.wpvivid-rectangle {
border-radius:0.4em;
padding:0.5em;
margin-left: 0.5em;
margin-right:0.5em;
font-size:0.8em;
}
.wpvivid-rectangle-small {
border-radius:0.4em;
padding:0.2em;
margin-left: 0.5em;
margin-right:0.5em;
font-size:0.6em;
}
.wpvivid-icon-16px{
font-size:16px;
margin-top:2px;
color:#aaa;
cursor:pointer;
}
.wpvivid-icon-16px-nopointer{
font-size:16px;
margin-top:2px;
}
.wpvivid-text-line{
padding:1px;
white-space:nowrap;
}
.wpvivid-text-selected{
background:#eee;
}
.wpvivid-text-line:hover{
background:#eee;
}
.wpvivid-grey {
background-color:grey;
color: #fff;
}
.wpvivid-grey-light {
background-color:#eee;
color: grey;
}
.wpvivid-hover-blue:hover{
background:#007cba;
color:#fff;
cursor:pointer;
}
.wpvivid-font-hover-blue:hover{
color:#007cba;
cursor:pointer;
}
.wpvivid-hover-green:hover{
background:#8bc34a;
color:#fff;
cursor:pointer;
}
.nav-tab-delete-img-addon{position: absolute;top: 2px;right: 3px;}
/* WPvivid Restore Progress Bar */
.wpvivid-stepper-wrapper
{
margin-top: auto;
display: flex;
justify-content: space-between;
margin-bottom: 20px;
}
.wpvivid-stepper-item
{
position: relative;
display: flex;
flex-direction: column;
align-items: center;
flex: 1;
}
@media (max-width: 768px)
{
.wpvivid-stepper-item
{
font-size: 12px;
}
}
.wpvivid-stepper-item::before
{
position: absolute;
content: "";
border-bottom: 2px solid #ccc;
width: 100%;
top: 20px;
left: -50%;
z-index: 2;
}
.wpvivid-stepper-item::after {
position: absolute;
content: "";
border-bottom: 2px solid #ccc;
width: 100%;
top: 20px;
left: 50%;
z-index: 2;
}
.wpvivid-stepper-item .wpvivid-step-counter {
position: relative;
z-index: 5;
display: flex;
justify-content: center;
align-items: center;
width: 40px;
height: 40px;
border-radius: 50%;
background: #ccc;
margin-bottom: 6px;
}
.wpvivid-stepper-item.active {
font-weight: bold;
}
.wpvivid-stepper-item.completed .wpvivid-step-counter {
background-color: #8bc34a;
color:#fff;
}
.wpvivid-stepper-item.completed::after {
position: absolute;
content: "";
border-bottom: 2px solid #4bb543;
width: 100%;
top: 20px;
left: 50%;
z-index: 3;
}
.wpvivid-stepper-item:first-child::before {
content: none;
}
.wpvivid-stepper-item:last-child::after {
content: none;
}
.wpvivid-custom-exclude-tree-info .jstree-open>.jstree-ocl {
background-position: -165px -75px !important;
}
.wpvivid-custom-exclude-tree-info .jstree-closed>.jstree-ocl {
background-position: -133px -75px !important;
}
.wpvivid-addon-info-text {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
.wpvivid-addons {
cursor:pointer;
}
.wpvivid-remote-storage-tab h2.nav-tab-wrapper :nth-child(n+3):nth-child(-n+11) {
display:block;
}
.quicksnapshot{width:100%;float:left; box-sizing:border-box;margin-right:10px; padding:10px;}
.quicksnapshot label{display:inline-block;margin-bottom:10px;} admin/class-wpvivid-admin.php 0000644 00000237237 15132770567 0012261 0 ustar 00 <?php
/**
* The admin-specific functionality of the plugin.
*
* @link https://wpvivid.com
* @since 0.9.1
*
* @package WPvivid
* @subpackage WPvivid/admin
*/
/**
* The admin-specific functionality of the plugin.
*
* Defines the plugin name, version, and two examples hooks for how to
* enqueue the admin-specific stylesheet and JavaScript.
*
* @package WPvivid
* @subpackage WPvivid/admin
* @author wpvivid team
*/
if (!defined('WPVIVID_PLUGIN_DIR')){
die;
}
class WPvivid_Admin
{
/**
* The ID of this plugin.
*
*
* @access private
* @var string $plugin_name The ID of this plugin.
*/
private $plugin_name;
/**
* The version of this plugin.
*
*
* @access private
* @var string $version The current version of this plugin.
*/
private $version;
private $screen_ids;
private $toolbar_menus;
private $submenus;
/**
* Initialize the class and set its properties.
*
*
* @param string $plugin_name The name of this plugin.
* @param string $version The version of this plugin.
*/
public function __construct($plugin_name, $version)
{
add_action('admin_enqueue_scripts',array( $this,'enqueue_styles'));
add_action('admin_enqueue_scripts',array( $this,'enqueue_scripts'));
if(is_multisite())
{
add_action('network_admin_menu',array( $this,'add_plugin_admin_menu'));
}
else
{
add_action('admin_menu',array( $this,'add_plugin_admin_menu'));
}
add_action('admin_bar_menu',array( $this,'add_toolbar_items'),100);
add_action('admin_head',array( $this,'wpvivid_get_siteurl'),100);
$plugin_basename = plugin_basename( plugin_dir_path( __DIR__ ) . 'wpvivid-backuprestore.php' );
add_filter('plugin_action_links_' . $plugin_basename, array( $this,'add_action_links'));
add_filter('wpvivid_add_tab_page', array($this, 'wpvivid_add_default_tab_page'));
add_filter('wpvivid_get_screen_ids',array($this,'get_screen_ids'),10);
add_filter('wpvivid_get_toolbar_menus',array($this,'get_toolbar_menus'),10);
add_filter('wpvivid_get_admin_menus',array($this,'get_admin_menus'),10);
//add_filter('wpvivid_add_side_bar', array($this, 'wpvivid_add_side_bar'), 10, 2);
add_action('wpvivid_add_side_bar', array($this, 'wpvivid_add_side_bar'), 10, 2);
add_action('wpvivid_before_setup_page',array($this,'show_add_my_review'));
add_action('wpvivid_before_setup_page',array($this,'check_extensions'));
add_action('wpvivid_before_setup_page',array($this,'check_amazons3'));
//add_action('wpvivid_before_setup_page',array($this,'check_dropbox'));
add_action('wpvivid_before_setup_page',array($this,'init_js_var'));
add_filter('wpvivid_add_log_tab_page', array($this, 'add_log_tab_page'), 10);
add_action('admin_notices', array($this, 'check_wpvivid_pro_version'));
add_action('admin_notices', array($this, 'check_wpvivid_free_htaccess_rule'));
add_filter('wpvivid_current_user_show_toolbar', array($this, 'current_user_show_toolbar'), 10, 2);
$this->plugin_name = $plugin_name;
$this->version = $version;
}
public function current_user_show_toolbar($show_toolbar, $capability)
{
if(is_admin()&¤t_user_can('manage_options'))
{
$show_toolbar=true;
}
return $show_toolbar;
}
public function add_log_tab_page($setting_array)
{
$setting_array['backup_log_page'] = array('index' => '1', 'tab_func' => array($this, 'wpvivid_add_tab_log'), 'page_func' => array($this, 'wpvivid_add_page_log'));
//$setting_array['read_log_page'] = array('index' => '2', 'tab_func' => array($this, 'wpvivid_add_tab_read_log'), 'page_func' => array($this, 'wpvivid_add_page_read_log'));
return $setting_array;
}
public function get_screen_ids($screen_ids)
{
$screen_ids[]='toplevel_page_'.$this->plugin_name;
$screen_ids[]='wpvivid-backup_page_wpvivid-transfer';
$screen_ids[]='wpvivid-backup_page_wpvivid-setting';
$screen_ids[]='wpvivid-backup_page_wpvivid-schedule';
$screen_ids[]='wpvivid-backup_page_wpvivid-remote';
$screen_ids[]='wpvivid-backup_page_wpvivid-website';
$screen_ids[]='wpvivid-backup_page_wpvivid-log';
$screen_ids[]='wpvivid-backup_page_wpvivid-key';
$screen_ids[]='wpvivid-backup_page_wpvivid-mainwp';
$screen_ids[]='wpvivid-backup_page_wpvivid_premium';
return $screen_ids;
}
public function get_toolbar_menus($toolbar_menus)
{
$menu['id']='wpvivid_admin_menu';
$menu['title']='WPvivid Backup';
$toolbar_menus[$menu['id']]=$menu;
$admin_url = admin_url();
$menu['id']='wpvivid_admin_menu_backup';
$menu['parent']='wpvivid_admin_menu';
$menu['title']=__('Backup & Restore', 'wpvivid-backuprestore');
$menu['tab']='admin.php?page=WPvivid&tab-backup';
$menu['href']=$admin_url . 'admin.php?page=WPvivid&tab-backup';
$menu['capability']='administrator';
$menu['index']=1;
$toolbar_menus[$menu['parent']]['child'][$menu['id']]=$menu;
return $toolbar_menus;
}
public function get_admin_menus($submenus)
{
$submenu['parent_slug']=$this->plugin_name;
$submenu['page_title']='WPvivid Backup';
$submenu['menu_title']=__('Backup & Restore', 'wpvivid-backuprestore');
$submenu['capability']='administrator';
$submenu['menu_slug']=$this->plugin_name;
$submenu['function']=array($this, 'display_plugin_setup_page');
$submenu['index']=1;
$submenus[$submenu['menu_slug']]=$submenu;
$submenu['parent_slug']=$this->plugin_name;
$submenu['page_title']='WPvivid Backup';
$submenu['menu_title']=__('Settings', 'wpvivid-backuprestore');
$submenu['capability']='administrator';
$submenu['menu_slug']='wpvivid-setting';
$submenu['function']=array($this, 'display_plugin_setup_page');
$submenu['index']=5;
$submenus[$submenu['menu_slug']]=$submenu;
return $submenus;
}
public function wpvivid_add_side_bar($html, $show_schedule = false){
$wpvivid_version = WPVIVID_PLUGIN_VERSION;
$wpvivid_version = apply_filters('wpvivid_display_pro_version', $wpvivid_version);
?>
<div class="postbox">
<h2>
<div style="float: left; margin-right: 5px;"><span style="margin: 0; padding: 0"><?php esc_html_e('Current Version: ', 'wpvivid-backuprestore'); echo esc_html($wpvivid_version);?></span></div>
<div style="float: left; margin-right: 5px;"><span style="margin: 0; padding: 0">|</span></div>
<div style="float: left; margin-left: 0;">
<span style="margin: 0; padding: 0"><a href="https://wordpress.org/plugins/wpvivid-backuprestore/#developers" target="_blank" style="text-decoration: none;"><?php esc_html_e('ChangeLog', 'wpvivid-backuprestore'); ?></a></span>
</div>
<div style="clear: both;"></div>
</h2>
</div>
<div class="postbox">
<h2>
<?php esc_html_e('Like the plugin? A'); ?>
<a href="https://wordpress.org/support/plugin/wpvivid-backuprestore/reviews/?filter=5#new-post" target="_blank" style="color: #ffba00;" ">★★★★★</a>
<?php esc_html_e('review will motivate us a lot.', 'wpvivid-backuprestore'); ?>
</h2>
</div>
<div id="wpvivid_backup_schedule_part"></div>
<div class="postbox">
<h2><span><?php esc_html_e('Troubleshooting', 'wpvivid-backuprestore'); ?></span></h2>
<div class="inside">
<table class="widefat" cellpadding="0">
<tbody>
<tr class="alternate">
<td class="row-title">
<?php esc_html_e('Read','wpvivid-backuprestore')?>
<a href="https://docs.wpvivid.com/troubleshooting-issues-wpvivid-backup-plugin.html" target="_blank"><?php esc_html_e('Troubleshooting page','wpvivid-backuprestore')?></a>
<?php esc_html_e(' for faster solutions.', 'wpvivid-backuprestore'); ?>
</td>
</tr>
<tr>
<td class="row-title">
<?php esc_html_e('Adjust','wpvivid-backuprestore')?>
<a href="https://docs.wpvivid.com/wpvivid-backup-free-advanced-settings.html" target="_blank"><?php esc_html_e('Adjust Advanced Settings','wpvivid-backuprestore')?></a>
<?php esc_html_e(' for higher task success rate.', 'wpvivid-backuprestore'); ?>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="postbox">
<h2><span><?php esc_html_e('How-to', 'wpvivid-backuprestore'); ?></span></h2>
<div class="inside">
<table class="widefat" cellpadding="0">
<tbody>
<tr class="alternate"><td class="row-title"><a href="https://docs.wpvivid.com/wpvivid-backup-free-general-settings.html" target="_blank"><?php esc_html_e('WPvivid Backup Settings', 'wpvivid-backuprestore'); ?></a></td></tr>
<tr><td class="row-title"><a href="https://docs.wpvivid.com/get-started-create-manual-backup.html" target="_blank"><?php esc_html_e('Create a Manual Backup', 'wpvivid-backuprestore'); ?></a></td></tr>
<tr class="alternate"><td class="row-title"><a href="https://docs.wpvivid.com/get-started-restore-site.html" target="_blank"><?php esc_html_e('Restore Your Site from a Backup', 'wpvivid-backuprestore'); ?></a></td></tr>
<tr><td class="row-title"><a href="https://docs.wpvivid.com/get-started-transfer-site.html" target="_blank"><?php esc_html_e('Migrate WordPress', 'wpvivid-backuprestore'); ?></a></td></tr>
</tbody>
</table>
</div>
</div>
<?php
}
/**
* Register the stylesheets for the admin area.
*
*
*/
public function enqueue_styles()
{
$this->screen_ids=apply_filters('wpvivid_get_screen_ids',$this->screen_ids);
if(in_array(get_current_screen()->id,$this->screen_ids))
{
wp_enqueue_style($this->plugin_name, WPVIVID_PLUGIN_DIR_URL . 'css/wpvivid-admin.css', array(), $this->version, 'all');
do_action('wpvivid_do_enqueue_styles');
}
}
/**
* Register the JavaScript for the admin area.
*
*
*/
public function enqueue_scripts()
{
$this->screen_ids=apply_filters('wpvivid_get_screen_ids',$this->screen_ids);
if(in_array(get_current_screen()->id,$this->screen_ids))
{
wp_enqueue_script($this->plugin_name, WPVIVID_PLUGIN_DIR_URL . 'js/wpvivid-admin.js', array('jquery'), $this->version, false);
wp_localize_script($this->plugin_name, 'wpvivid_ajax_object', array('ajax_url' => admin_url('admin-ajax.php'),'ajax_nonce'=>wp_create_nonce('wpvivid_ajax')));
wp_localize_script($this->plugin_name, 'wpvividlion', array(
'warning' => __('Warning:', 'wpvivid-backuprestore'),
'error' => __('Error:', 'wpvivid-backuprestore'),
'remotealias' => __('Warning: An alias for remote storage is required.', 'wpvivid-backuprestore'),
'remoteexist' => __('Warning: The alias already exists in storage list.', 'wpvivid-backuprestore'),
'backup_calc_timeout' => __('Calculating the size of files, folder and database timed out. If you continue to receive this error, please go to the plugin settings, uncheck \'Calculate the size of files, folder and database before backing up\', save changes, then try again.', 'wpvivid-backuprestore'),
'restore_step1' => __('Step One: In the backup list, click the \'Restore\' button on the backup you want to restore. This will bring up the restore tab', 'wpvivid-backuprestore'),
'restore_step2' => __('Step Two: Choose an option to complete restore, if any', 'wpvivid-backuprestore'),
'restore_step3' => __('Step Three: Click \'Restore\' button', 'wpvivid-backuprestore'),
'get_key_step1' => __('1. Visit Key tab page of WPvivid backup plugin of destination site.', 'wpvivid-backuprestore'),
'get_key_step2' => __('2. Generate a key by clicking Generate button and copy it.', 'wpvivid-backuprestore'),
'get_key_step3' => __('3. Go back to this page and paste the key in key box below. Lastly, click Save button.', 'wpvivid-backuprestore'),
));
wp_enqueue_script('plupload-all');
do_action('wpvivid_do_enqueue_scripts');
}
}
/**
* Register the administration menu for this plugin into the WordPress Dashboard menu.
*
*
*/
public function add_plugin_admin_menu()
{
/*
* Add a settings page for this plugin to the Settings menu.
*
* NOTE: Alternative menu locations are available via WordPress administration menu functions.
*
* Administration Menus: http://codex.wordpress.org/Administration_Menus
*
*/
if(!is_multisite())
{
$active_plugins = get_option('active_plugins');
}
else
{
$active_plugins = array();
//network active
$mu_active_plugins = get_site_option( 'active_sitewide_plugins', array() );
if(!empty($mu_active_plugins)){
foreach ($mu_active_plugins as $plugin_name => $data){
$active_plugins[] = $plugin_name;
}
}
}
if(!function_exists('get_plugins'))
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
$plugins=get_plugins();
$pro_wpvivid_slug='wpvivid-backup-pro/wpvivid-backup-pro.php';
$is_active_pro=false;
if(!empty($plugins))
{
if(isset($plugins[$pro_wpvivid_slug]))
{
if(in_array($pro_wpvivid_slug, $active_plugins))
{
$is_active_pro=true;
}
}
}
if(is_multisite() && !$is_active_pro)
{
$menu['page_title']= 'WPvivid Backup';
$menu['menu_title']= 'WPvivid Backup';
$menu['capability']='administrator';
$menu['menu_slug']= $this->plugin_name;
$menu['function']=array($this, 'display_plugin_setup_page_mu');
$menu['icon_url']='dashicons-cloud';
$menu['position']=100;
$menu = apply_filters('wpvivid_get_main_admin_menus', $menu);
add_menu_page( $menu['page_title'],$menu['menu_title'], $menu['capability'], $menu['menu_slug'], $menu['function'], $menu['icon_url'], $menu['position']);
}
else
{
$menu['page_title']= 'WPvivid Backup';
$menu['menu_title']= 'WPvivid Backup';
$menu['capability']='administrator';
$menu['menu_slug']= $this->plugin_name;
$menu['function']=array($this, 'display_plugin_setup_page');
$menu['icon_url']='dashicons-cloud';
$menu['position']=100;
$menu = apply_filters('wpvivid_get_main_admin_menus', $menu);
add_menu_page( $menu['page_title'],$menu['menu_title'], $menu['capability'], $menu['menu_slug'], $menu['function'], $menu['icon_url'], $menu['position']);
$this->submenus = apply_filters('wpvivid_get_admin_menus', $this->submenus);
usort($this->submenus, function ($a, $b) {
if ($a['index'] == $b['index'])
return 0;
if ($a['index'] > $b['index'])
return 1;
else
return -1;
});
foreach ($this->submenus as $submenu) {
add_submenu_page(
$submenu['parent_slug'],
$submenu['page_title'],
$submenu['menu_title'],
$submenu['capability'],
$submenu['menu_slug'],
$submenu['function']);
}
}
}
function add_toolbar_items($wp_admin_bar)
{
if (is_multisite())
{
$active_plugins = array();
//network active
$mu_active_plugins = get_site_option( 'active_sitewide_plugins', array() );
if(!empty($mu_active_plugins)){
foreach ($mu_active_plugins as $plugin_name => $data){
$active_plugins[] = $plugin_name;
}
}
if(!function_exists('get_plugins'))
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
$plugins=get_plugins();
$pro_wpvivid_slug='wpvivid-backup-pro/wpvivid-backup-pro.php';
$is_active_pro=false;
if(!empty($plugins))
{
if(isset($plugins[$pro_wpvivid_slug]))
{
if(in_array($pro_wpvivid_slug, $active_plugins))
{
$is_active_pro=true;
}
}
}
if(!is_network_admin())
{
return ;
}
if(!$is_active_pro)
{
return ;
}
}
global $wpvivid_plugin;
if(is_admin())
{
$show_admin_bar = $this->get_admin_bar_setting();
if ($show_admin_bar === true)
{
$show_toolbar=false;
if(is_admin()&¤t_user_can('manage_options'))
{
$show_toolbar=true;
}
else
{
$show_toolbar=apply_filters('wpvivid_current_user_show_toolbar', $show_toolbar, 'wpvivid-can-show-toolbar');
}
if($show_toolbar)
{
$this->toolbar_menus = apply_filters('wpvivid_get_toolbar_menus', $this->toolbar_menus);
foreach ($this->toolbar_menus as $menu)
{
$wp_admin_bar->add_menu(array(
'id' => $menu['id'],
'title' => '<span class="dashicons-cloud ab-icon"></span>'.$menu['title']
));
if (isset($menu['child']))
{
usort($menu['child'], function ($a, $b)
{
if($a['index']==$b['index'])
return 0;
if($a['index']>$b['index'])
return 1;
else
return -1;
});
foreach ($menu['child'] as $child_menu) {
if(isset($child_menu['capability']) && current_user_can($child_menu['capability'])) {
$wp_admin_bar->add_menu(array(
'id' => $child_menu['id'],
'parent' => $menu['id'],
'title' => $child_menu['title'],
'href' => $child_menu['href']
));
}
}
}
}
}
}
}
}
public function get_admin_bar_setting()
{
return WPvivid_Setting::get_admin_bar_setting();
}
public function add_action_links( $links )
{
if(!is_multisite())
{
$active_plugins = get_option('active_plugins');
}
else
{
$active_plugins = array();
//network active
$mu_active_plugins = get_site_option( 'active_sitewide_plugins', array() );
if(!empty($mu_active_plugins)){
foreach ($mu_active_plugins as $plugin_name => $data){
$active_plugins[] = $plugin_name;
}
}
}
if(!function_exists('get_plugins'))
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
$plugins=get_plugins();
$pro_wpvivid_slug='wpvivid-backup-pro/wpvivid-backup-pro.php';
$is_active_pro=false;
if(!empty($plugins))
{
if(isset($plugins[$pro_wpvivid_slug]))
{
if(in_array($pro_wpvivid_slug, $active_plugins))
{
$is_active_pro=true;
}
}
}
if($is_active_pro)
{
if(!is_multisite())
{
$settings_link = array(
'<a href="' . admin_url( 'admin.php?page=' . strtolower(sprintf('%s-dashboard', apply_filters('wpvivid_white_label_slug', 'wpvivid'))) ) . '">' . __('Settings', 'wpvivid-backuprestore') . '</a>',
);
}
else
{
$settings_link = array(
'<a href="' . network_admin_url( 'admin.php?page=' . strtolower(sprintf('%s-dashboard', apply_filters('wpvivid_white_label_slug', 'wpvivid'))) ) . '">' . __('Settings', 'wpvivid-backuprestore') . '</a>',
);
}
}
else
{
if(!is_multisite())
{
$settings_link = array(
'<a href="' . admin_url( 'admin.php?page=' . apply_filters('wpvivid_white_label_slug', $this->plugin_name) ) . '">' . __('Settings', 'wpvivid-backuprestore') . '</a>',
);
}
else
{
$settings_link = array(
'<a href="' . network_admin_url( 'admin.php?page=' . apply_filters('wpvivid_white_label_slug', $this->plugin_name) ) . '">' . __('Settings', 'wpvivid-backuprestore') . '</a>',
);
}
}
return array_merge( $settings_link, $links );
}
public static function wpvivid_get_siteurl(){
$wpvivid_siteurl = array();
$wpvivid_siteurl['home_url'] = home_url();
$wpvivid_siteurl['plug_url'] = plugins_url();
$wpvivid_siteurl['site_url'] = get_option( 'siteurl' );
return $wpvivid_siteurl;
}
/**
* Render the settings page for this plugin.
*
*
*/
public function display_plugin_setup_page()
{
do_action('wpvivid_before_setup_page');
add_action('wpvivid_display_page',array($this,'display'));
do_action('wpvivid_display_page');
}
public function display_plugin_setup_page_mu()
{
?>
<div class="notice notice-info" style="margin: 10px; padding: 10px;">
<span>The free version of WPvivid Backup Plugin does not support WordPress Multisite. You can consider upgrading to the <a href="https://wpvivid.com/pricing">pro version</a> as needed.</span>
</div>
<?php
}
public function migrate_notice()
{
$migrate_notice=false;
$migrate_status=WPvivid_Setting::get_option('wpvivid_migrate_status');
if(!empty($migrate_status) && $migrate_status == 'completed')
{
$migrate_notice=true;
echo '<div class="notice notice-warning is-dismissible"><p>';
esc_html_e('Migration is complete and htaccess file is replaced. In order to successfully complete the migration, you\'d better reinstall 301 redirect plugin, firewall and security plugin, and caching plugin if they exist.', 'wpvivid-backuprestore');
echo '</p></div>';
WPvivid_Setting::delete_option('wpvivid_migrate_status');
}
$restore = new WPvivid_restore_data();
if ($restore->has_restore())
{
$restore_status = $restore->get_restore_status();
if ($restore_status === WPVIVID_RESTORE_COMPLETED)
{
$restore->clean_restore_data();
do_action('wpvivid_rebuild_backup_list');
$need_review=WPvivid_Setting::get_option('wpvivid_need_review');
if($need_review=='not')
{
WPvivid_Setting::update_option('wpvivid_need_review','show');
$msg = esc_html(__('Cheers! WPvivid Backup plugin has restored successfully your website. If you found WPvivid Backup plugin helpful, a 5-star rating would be highly appreciated, which motivates us to keep providing new features.', 'wpvivid-backuprestore'));
WPvivid_Setting::update_option('wpvivid_review_msg',$msg);
}
else{
if(!$migrate_notice)
{
echo '<div class="notice notice-success is-dismissible"><p>'.esc_html_e('Restore completed successfully.', 'wpvivid-backuprestore').'</p></div>';
}
}
}
}
}
public function display()
{
include_once('partials/wpvivid-admin-display.php');
}
public static function wpvivid_get_page_request()
{
$request_page='wpvivid_tab_general';
if(isset($_REQUEST['wpvivid-remote-page-mainwp'])){
$request_page='wpvivid_tab_remote_storage';
}
if(isset($_REQUEST['tab-backup']))
{
$request_page='wpvivid_tab_general';
}
else if(isset($_REQUEST['tab-schedule']))
{
$request_page='wpvivid_tab_schedule';
}
else if(isset($_REQUEST['tab-transfer']))
{
$request_page='wpvivid_tab_migrate';
}
else if(isset($_REQUEST['tab-remote-storage']))
{
$request_page='wpvivid_tab_remote_storage';
}
else if(isset($_REQUEST['tab-settings']))
{
$request_page='wpvivid_tab_setting';
}
else if(isset($_REQUEST['tab-website-info']))
{
$request_page='wpvivid_tab_debug';
}
else if(isset($_REQUEST['tab-logs']))
{
$request_page='wpvivid_tab_log';
}
else if(isset($_REQUEST['tab-key']))
{
$request_page='wpvivid_tab_key';
}
else if(isset($_REQUEST['tab-mainwp']))
{
$request_page='wpvivid_tab_mainwp';
}
else if(isset($_REQUEST['page'])&&$_REQUEST['page']=='wpvivid-pro')
{
$request_page='wpvivid_tab_pro';
}
else if(isset($_REQUEST['page'])&&$_REQUEST['page']=='wpvivid-setting')
{
$request_page='wpvivid_tab_setting';
}
$request_page=apply_filters('wpvivid_set_page_request',$request_page);
return $request_page;
}
public static function show_add_my_review()
{
$review = WPvivid_Setting::get_option('wpvivid_need_review');
$review_msg = WPvivid_Setting::get_option('wpvivid_review_msg');
if (empty($review))
{
WPvivid_Setting::update_option('wpvivid_need_review', 'not');
} else {
if ($review == 'not')
{
}
else if ($review == 'show')
{
if(!empty($review_msg))
{
echo '<div class="notice notice-info notice-rate is-dismissible" id="wpvivid_notice_rate">
<p>' . esc_html($review_msg) . '</p>
<div style="padding-bottom: 10px;">
<span><input type="button" class="button-primary" option="review" name="rate-now" value="'.esc_attr__('Rate Us', 'wpvivid-backuprestore').'" /></span>
<span><input type="button" class="button-secondary" option="review" name="ask-later" value="'.esc_attr__('Maybe Later', 'wpvivid-backuprestore').'" /></span>
<span><input type="button" class="button-secondary" option="review" name="already-done" value="'.esc_attr__('Already Done', 'wpvivid-backuprestore').'" /></span>
<span><input type="button" class="button-secondary" option="review" name="never-ask" value="'.esc_attr__('Never', 'wpvivid-backuprestore').'" /></span>
</div>
</div>';
}
} else if ($review == 'do_not_ask')
{
} else
{
if (time() > $review)
{
if(!empty($review_msg))
{
echo '<div class="notice notice-info notice-rate is-dismissible" id="wpvivid_notice_rate">
<p>' . esc_html($review_msg) . '</p>
<div style="padding-bottom: 10px;">
<span><input type="button" class="button-primary" option="review" name="rate-now" value="'.esc_attr__('Rate Us', 'wpvivid-backuprestore').'" /></span>
<span><input type="button" class="button-secondary" option="review" name="ask-later" value="'.esc_attr__('Maybe Later', 'wpvivid-backuprestore').'" /></span>
<span><input type="button" class="button-secondary" option="review" name="already-done" value="'.esc_attr__('Already Done', 'wpvivid-backuprestore').'" /></span>
<span><input type="button" class="button-secondary" option="review" name="never-ask" value="'.esc_attr__('Never', 'wpvivid-backuprestore').'" /></span>
</div>
</div>';
}
}
}
}
}
public function check_amazons3()
{
$remoteslist=WPvivid_Setting::get_all_remote_options();
$need_amazons3_notice = false;
if(isset($remoteslist) && !empty($remoteslist))
{
foreach ($remoteslist as $remote_id => $value)
{
if($remote_id === 'remote_selected')
{
continue;
}
if($value['type'] == 'amazons3' && isset($value['s3Path']))
{
$need_amazons3_notice = true;
}
if($value['type'] == 's3compat' && isset($value['s3directory']))
{
$need_amazons3_notice = true;
}
}
}
if($need_amazons3_notice)
{
$amazons3_notice = WPvivid_Setting::get_option('wpvivid_amazons3_notice', 'not init');
if($amazons3_notice === 'not init')
{
$notice_message = __('As Amazon S3 and DigitalOcean Space have upgraded their connection methods, please delete the previous connections and re-add your Amazon S3/DigitalOcean Space accounts to make sure the connections work.', 'wpvivid-backuprestore');
echo '<div class="notice notice-warning" id="wpvivid_amazons3_notice">
<p>' . esc_html($notice_message) . '</p>
<div style="padding-bottom: 10px;">
<span><input type="button" class="button-secondary" value="I Understand" onclick="wpvivid_click_amazons3_notice();" /></span>
</div>
</div>';
}
}
}
public function check_dropbox()
{
if (is_multisite())
{
if(!is_network_admin())
{
return ;
}
}
if(!function_exists('get_plugins'))
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
$pro_wpvivid_slug='wpvivid-backup-pro/wpvivid-backup-pro.php';
if (is_multisite())
{
$active_plugins = array();
//network active
$mu_active_plugins = get_site_option( 'active_sitewide_plugins', array() );
if(!empty($mu_active_plugins)){
foreach ($mu_active_plugins as $plugin_name => $data){
$active_plugins[] = $plugin_name;
}
}
$plugins=get_mu_plugins();
if(count($plugins) == 0 || !isset($plugins[$pro_wpvivid_slug])){
$plugins=get_plugins();
}
}
else
{
$active_plugins = get_option('active_plugins');
$plugins=get_plugins();
}
if(!empty($plugins))
{
if(isset($plugins[$pro_wpvivid_slug]))
{
if(in_array($pro_wpvivid_slug, $active_plugins))
{
return;
}
}
$remoteslist=WPvivid_Setting::get_all_remote_options();
$need_dropbox_notice = false;
if(isset($remoteslist) && !empty($remoteslist))
{
foreach ($remoteslist as $remote_id => $value)
{
if($remote_id === 'remote_selected')
{
continue;
}
if($value['type'] == 'dropbox' && !isset($value['refresh_token']))
{
$need_dropbox_notice = true;
}
}
}
if($need_dropbox_notice)
{
$notice_message = __('Because Dropbox has upgraded their API on September 30, 2021, the new API is no longer compatible with the previous app\'s settings. Please re-add your Dropbox storage to ensure that it works properly.', 'wpvivid-backuprestore');
echo '<div class="notice notice-warning">
<p>' . esc_html($notice_message) . '</p>
</div>';
}
}
}
public function check_extensions()
{
$common_setting = WPvivid_Setting::get_setting(false, 'wpvivid_common_setting');
$db_connect_method = isset($common_setting['options']['wpvivid_common_setting']['db_connect_method']) ? $common_setting['options']['wpvivid_common_setting']['db_connect_method'] : 'wpdb';
$need_php_extensions = array();
$need_extensions_count = 0;
$extensions=get_loaded_extensions();
if(!function_exists("curl_init")){
$need_php_extensions[$need_extensions_count] = 'curl';
$need_extensions_count++;
}
if(!class_exists('PDO')){
$need_php_extensions[$need_extensions_count] = 'PDO';
$need_extensions_count++;
}
if(!function_exists("gzopen"))
{
$need_php_extensions[$need_extensions_count] = 'zlib';
$need_extensions_count++;
}
if(!array_search('pdo_mysql',$extensions) && $db_connect_method === 'pdo')
{
$need_php_extensions[$need_extensions_count] = 'pdo_mysql';
$need_extensions_count++;
}
if(!empty($need_php_extensions)){
$msg = '';
$figure = 0;
foreach ($need_php_extensions as $extension){
$figure++;
if($figure == 1){
$msg .= $extension;
}
else if($figure < $need_extensions_count) {
$msg .= ', '.$extension;
}
else if($figure == $need_extensions_count){
$msg .= ' and '.$extension;
}
}
if($figure == 1){
echo '<div class="notice notice-error"><p>';
echo sprintf('The %s extension is not detected. Please install the extension first.', esc_html($msg));
echo '</p></div>';
}
else{
echo '<div class="notice notice-error"><p>';
echo sprintf('The %s extensions are not detected. Please install the extensions first.', esc_html($msg));
echo '</p></div>';
}
}
if (!class_exists('PclZip')) include_once(ABSPATH.'/wp-admin/includes/class-pclzip.php');
if (!class_exists('PclZip'))
{
echo '<div class="notice notice-error"><p>';
esc_html_e('Class PclZip is not detected. Please update or reinstall your WordPress.', 'wpvivid-backuprestore');
echo '</p></div>';
}
$hide_notice = get_option('wpvivid_hide_wp_cron_notice', false);
if(defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON && $hide_notice === false){
echo '<div class="notice notice-error notice-wp-cron is-dismissible"><p>';
esc_html_e('In order to execute the scheduled backups properly, please set the DISABLE_WP_CRON constant to false. If you are using an external cron system, simply click \'X\' to dismiss this message.', 'wpvivid-backuprestore');
echo '</p></div>';
}
}
public function check_wpvivid_pro_version()
{
if (is_multisite())
{
if(!is_network_admin())
{
return ;
}
}
if(!function_exists('get_plugins'))
require_once(ABSPATH . 'wp-admin/includes/plugin.php');
$pro_wpvivid_slug='wpvivid-backup-pro/wpvivid-backup-pro.php';
if (is_multisite())
{
$active_plugins = array();
//network active
$mu_active_plugins = get_site_option( 'active_sitewide_plugins', array() );
if(!empty($mu_active_plugins)){
foreach ($mu_active_plugins as $plugin_name => $data){
$active_plugins[] = $plugin_name;
}
}
$plugins=get_mu_plugins();
if(count($plugins) == 0 || !isset($plugins[$pro_wpvivid_slug])){
$plugins=get_plugins();
}
}
else
{
$active_plugins = get_option('active_plugins');
$plugins=get_plugins();
}
if(!empty($plugins))
{
if(isset($plugins[$pro_wpvivid_slug]))
{
if(in_array($pro_wpvivid_slug, $active_plugins))
{
if(version_compare('2.0.23',$plugins[$pro_wpvivid_slug]['Version'],'>'))
{
?>
<div class="notice notice-warning" style="padding: 11px 15px;">
<?php echo sprintf('We detected that you are using a lower version of %s Pro, please update it to 2.0.23 or higher to ensure backing up to Google Drive works properly.', 'wpvivid-backuprestore'), esc_html(apply_filters('wpvivid_white_label_display', 'WPvivid Backup Plugin')); ?>
</div>
<?php
}
}
}
}
}
public function check_wpvivid_free_htaccess_rule()
{
$is_check = get_option('wpvivid_check_htaccess_rule_free', false);
if(!$is_check)
{
$dir = WPvivid_Setting::get_option('wpvivid_local_setting');
if (!isset($dir['path']))
{
$dir = WPvivid_Setting::set_default_local_option();
}
$wpvivid_backup_dir_htaccess = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir['path'].DIRECTORY_SEPARATOR.'.htaccess';
$wpvivid_backup_log_htaccess = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir['path'].DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'.htaccess';
$wpvivid_backup_error_log_htaccess = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.$dir['path'].DIRECTORY_SEPARATOR.'wpvivid_log'.DIRECTORY_SEPARATOR.'error'.'/.htaccess';
$wpvivid_staging_dir_htaccess = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'wpvivid_staging'.DIRECTORY_SEPARATOR.'.htaccess';
$wpvivid_staging_error_log_htaccess = WP_CONTENT_DIR.DIRECTORY_SEPARATOR.'wpvivid_staging'.DIRECTORY_SEPARATOR.'error'.'/.htaccess';
if(file_exists($wpvivid_backup_dir_htaccess))
{
wp_delete_file($wpvivid_backup_dir_htaccess);
WPvivid_Setting::wpvivid_write_htaccess_rule($wpvivid_backup_dir_htaccess);
}
if(file_exists($wpvivid_backup_log_htaccess))
{
wp_delete_file($wpvivid_backup_log_htaccess);
WPvivid_Setting::wpvivid_write_htaccess_rule($wpvivid_backup_log_htaccess);
}
if(file_exists($wpvivid_backup_error_log_htaccess))
{
wp_delete_file($wpvivid_backup_error_log_htaccess);
WPvivid_Setting::wpvivid_write_htaccess_rule($wpvivid_backup_error_log_htaccess);
}
if(file_exists($wpvivid_staging_dir_htaccess))
{
wp_delete_file($wpvivid_staging_dir_htaccess);
WPvivid_Setting::wpvivid_write_htaccess_rule($wpvivid_staging_dir_htaccess);
}
if(file_exists($wpvivid_staging_error_log_htaccess))
{
wp_delete_file($wpvivid_staging_error_log_htaccess);
WPvivid_Setting::wpvivid_write_htaccess_rule($wpvivid_staging_error_log_htaccess);
}
update_option('wpvivid_check_htaccess_rule_free', true, 'no');
}
}
public function init_js_var()
{
global $wpvivid_plugin;
$loglist=$wpvivid_plugin->get_log_list_ex();
$remoteslist=WPvivid_Setting::get_all_remote_options();
$default_remote_storage='';
foreach ($remoteslist['remote_selected'] as $value)
{
$default_remote_storage=$value;
}
?>
<script>
var wpvivid_siteurl = '<?php
$wpvivid_siteurl = array();
$wpvivid_siteurl=WPvivid_Admin::wpvivid_get_siteurl();
echo esc_url($wpvivid_siteurl['site_url']);
?>';
var wpvivid_plugurl = '<?php
echo esc_url(WPVIVID_PLUGIN_URL);
?>';
var wpvivid_log_count = '<?php
echo esc_attr(sizeof($loglist['log_list']['file']));
?>';
var wpvivid_log_array = '<?php
echo wp_json_encode($loglist);
?>';
var wpvivid_page_request = '<?php
$page_request = WPvivid_Admin::wpvivid_get_page_request();
echo esc_attr($page_request);
?>';
var wpvivid_default_remote_storage = '<?php
echo esc_attr($default_remote_storage);
?>';
</script>
<?php
}
public function wpvivid_add_default_tab_page($page_array){
$page_array['backup_restore'] = array('index' => '1', 'tab_func' => array($this, 'wpvivid_add_tab_backup_restore'), 'page_func' => array($this, 'wpvivid_add_page_backup'));
$page_array['schedule'] = array('index' => '2', 'tab_func' => array($this, 'wpvivid_add_tab_schedule'), 'page_func' => array($this, 'wpvivid_add_page_schedule'));
$page_array['remote_storage'] = array('index' => '4', 'tab_func' => array($this, 'wpvivid_add_tab_remote_storage'), 'page_func' => array($this, 'wpvivid_add_page_remote_storage'));
$page_array['setting'] = array('index' => '5', 'tab_func' => array($this, 'wpvivid_add_tab_setting'), 'page_func' => array($this, 'wpvivid_add_page_setting'));
$page_array['website_info'] = array('index' => '6', 'tab_func' => array($this, 'wpvivid_add_tab_website_info'), 'page_func' => array($this, 'wpvivid_add_page_website_info'));
$page_array['log'] = array('index' => '7', 'tab_func' => array($this, 'wpvivid_add_tab_log_ex'), 'page_func' => array($this, 'wpvivid_add_page_log_ex'));
$page_array['read_log'] = array('index' => '29', 'tab_func' => array($this, 'wpvivid_add_tab_read_log'), 'page_func' => array($this, 'wpvivid_add_page_read_log'));
$page_array['premium'] = array('index' => '10', 'tab_func' => array($this, 'wpvivid_add_tab_premium'), 'page_func' => array($this, 'wpvivid_add_page_premium'));
$hide_mwp_tab_page = get_option('wpvivid_hide_mwp_tab_page_v1', false);
if($hide_mwp_tab_page === false) {
$page_array['mwp'] = array('index' => '30', 'tab_func' => array($this, 'wpvivid_add_tab_mwp'), 'page_func' => array($this, 'wpvivid_add_page_mwp'));
}
return $page_array;
}
public function wpvivid_add_tab_backup_restore(){
?>
<a href="#" id="wpvivid_tab_general" class="nav-tab wrap-nav-tab nav-tab-active" onclick="switchTabs(event,'general-page')"><?php esc_html_e('Backup & Restore', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function wpvivid_add_tab_schedule(){
?>
<a href="#" id="wpvivid_tab_schedule" class="nav-tab wrap-nav-tab" onclick="switchTabs(event,'schedule-page')"><?php esc_html_e('Schedule', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function wpvivid_add_tab_remote_storage(){
?>
<a href="#" id="wpvivid_tab_remote_storage" class="nav-tab wrap-nav-tab" onclick="switchTabs(event,'storage-page')"><?php esc_html_e('Remote Storage', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function wpvivid_add_tab_setting(){
?>
<a href="#" id="wpvivid_tab_setting" class="nav-tab wrap-nav-tab" onclick="switchTabs(event,'settings-page')"><?php esc_html_e('Settings', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function wpvivid_add_tab_website_info(){
?>
<a href="#" id="wpvivid_tab_debug" class="nav-tab wrap-nav-tab" onclick="switchTabs(event,'debug-page')"><?php esc_html_e('Debug', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function wpvivid_add_tab_log(){
?>
<a href="#" id="wpvivid_tab_log" class="nav-tab log-nav-tab nav-tab-active" onclick="switchlogTabs(event,'logs-page')"><?php esc_html_e('Backup Logs', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function wpvivid_add_tab_read_log(){
?>
<a href="#" id="wpvivid_tab_read_log" class="nav-tab wrap-nav-tab delete" onclick="switchTabs(event,'log-read-page')" style="display: none;">
<div style="margin-right: 15px;"><?php esc_html_e('Log', 'wpvivid-backuprestore'); ?></div>
<div class="nav-tab-delete-img">
<img src="<?php echo esc_url( WPVIVID_PLUGIN_URL.'/admin/partials/images/delete-tab.png' ); ?>" style="vertical-align:middle; cursor:pointer;" onclick="wpvivid_close_tab(event, 'wpvivid_tab_read_log', 'wrap', 'wpvivid_tab_log');" />
</div>
</a>
<?php
}
public function wpvivid_add_tab_mwp(){
?>
<a href="#" id="wpvivid_tab_mainwp" class="nav-tab wrap-nav-tab delete" onclick="switchTabs(event, 'mwp-page')">
<div style="margin-right: 15px;"><?php esc_html_e('MainWP', 'wpvivid-backuprestore'); ?></div>
<div class="nav-tab-delete-img">
<img src="<?php echo esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/delete-tab.png'); ?>" style="vertical-align:middle; cursor:pointer;" onclick="wpvivid_close_tab(event, 'wpvivid_tab_mainwp', 'wrap', 'wpvivid_tab_general');" />
</div>
</a>
<?php
}
public function wpvivid_add_tab_premium(){
?>
<a href="#" id="wpvivid_tab_premium" class="nav-tab wrap-nav-tab" onclick="switchTabs(event,'premium-page')"><?php esc_html_e('Premium', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function wpvivid_add_page_backup()
{
?>
<div id="general-page" class="wrap-tab-content wpvivid_tab_general" name="tab-backup" style="width:100%;">
<div class="meta-box-sortables ui-sortable">
<?php
do_action('wpvivid_backuppage_add_module');
?>
<h2 class="nav-tab-wrapper" id="wpvivid_backup_tab" style="padding-bottom:0!important;">
<?php
$backuplist_array = array();
$backuplist_array = apply_filters('wpvivid_backuppage_load_backuplist', $backuplist_array);
foreach ($backuplist_array as $list_name) {
add_action('wpvivid_backuppage_add_tab', $list_name['tab_func'], $list_name['index']);
add_action('wpvivid_backuppage_add_page', $list_name['page_func'], $list_name['index']);
}
do_action('wpvivid_backuppage_add_tab');
?>
</h2>
<?php do_action('wpvivid_backuppage_add_page'); ?>
</div>
</div>
<script>
<?php do_action('wpvivid_backup_do_js'); ?>
</script>
<?php
}
public function wpvivid_add_page_schedule()
{
?>
<div id="schedule-page" class="wrap-tab-content wpvivid_tab_schedule" name="tab-schedule" style="display: none;">
<div>
<table class="widefat">
<tbody>
<?php do_action('wpvivid_schedule_add_cell'); ?>
<tfoot>
<tr>
<th class="row-title"><input class="button-primary storage-account-button" id="wpvivid_schedule_save" type="submit" name="" value="<?php esc_attr_e( 'Save Changes', 'wpvivid-backuprestore' ); ?>" /></th>
<th></th>
</tr>
</tfoot>
</tbody>
</table>
</div>
</div>
<script>
jQuery('#wpvivid_schedule_save').click(function(){
wpvivid_set_schedule();
wpvivid_settings_changed = false;
});
function wpvivid_set_schedule()
{
var schedule_data = wpvivid_ajax_data_transfer('schedule');
var ajax_data = {
'action': 'wpvivid_set_schedule',
'schedule': schedule_data
};
jQuery('#wpvivid_schedule_save').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function (data) {
try {
var jsonarray = jQuery.parseJSON(data);
jQuery('#wpvivid_schedule_save').css({'pointer-events': 'auto', 'opacity': '1'});
if (jsonarray.result === 'success') {
location.reload();
}
else {
alert(jsonarray.error);
}
}
catch (err) {
alert(err);
jQuery('#wpvivid_schedule_save').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
jQuery('#wpvivid_schedule_save').css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = wpvivid_output_ajaxerror('changing schedule', textStatus, errorThrown);
alert(error_message);
});
}
</script>
<?php
}
public function wpvivid_add_page_remote_storage()
{
?>
<div id="storage-page" class="wrap-tab-content wpvivid_tab_remote_storage" name="tab-storage" style="display:none;">
<div>
<div class="storage-content" id="storage-brand-2" style="">
<div class="postbox">
<?php do_action('wpvivid_add_storage_tab'); ?>
</div>
<div class="postbox storage-account-block" id="wpvivid_storage_account_block">
<?php do_action('wpvivid_add_storage_page'); ?>
</div>
<h2 class="nav-tab-wrapper" style="padding-bottom:0!important;">
<?php do_action('wpvivid_storage_add_tab'); ?>
</h2>
<?php do_action('wpvivid_storage_add_page'); ?>
</div>
</div>
</div>
<?php
}
public function wpvivid_add_page_setting()
{
?>
<div id="settings-page" class="wrap-tab-content wpvivid_tab_setting" name="tab-setting" style="display:none;">
<div>
<h2 class="nav-tab-wrapper" style="padding-bottom:0!important;">
<?php
$setting_array = array();
$setting_array = apply_filters('wpvivid_add_setting_tab_page', $setting_array);
foreach ($setting_array as $setting_name) {
add_action('wpvivid_settingpage_add_tab', $setting_name['tab_func'], $setting_name['index']);
add_action('wpvivid_settingpage_add_page', $setting_name['page_func'], $setting_name['index']);
}
do_action('wpvivid_settingpage_add_tab');
?>
</h2>
<?php do_action('wpvivid_settingpage_add_page'); ?>
<div><input class="button-primary" id="wpvivid_setting_general_save" type="submit" value="<?php esc_attr_e( 'Save Changes', 'wpvivid-backuprestore' ); ?>" /></div>
</div>
</div>
<script>
jQuery('#wpvivid_setting_general_save').click(function(){
wpvivid_set_general_settings();
wpvivid_settings_changed = false;
});
function wpvivid_set_general_settings()
{
var setting_data = wpvivid_ajax_data_transfer('setting');
var ajax_data = {
'action': 'wpvivid_set_general_setting',
'setting': setting_data
};
jQuery('#wpvivid_setting_general_save').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function (data) {
try {
var jsonarray = jQuery.parseJSON(data);
jQuery('#wpvivid_setting_general_save').css({'pointer-events': 'auto', 'opacity': '1'});
if (jsonarray.result === 'success') {
location.reload();
}
else {
alert(jsonarray.error);
}
}
catch (err) {
alert(err);
jQuery('#wpvivid_setting_general_save').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
jQuery('#wpvivid_setting_general_save').css({'pointer-events': 'auto', 'opacity': '1'});
var error_message = wpvivid_output_ajaxerror('changing base settings', textStatus, errorThrown);
alert(error_message);
});
}
</script>
<?php
}
public function wpvivid_add_tab_log_ex(){
?>
<a href="#" id="wpvivid_tab_log_ex" class="nav-tab wrap-nav-tab" onclick="switchTabs(event,'logs-page-ex')"><?php esc_html_e('Logs', 'wpvivid-backuprestore'); ?></a>
<?php
}
public function wpvivid_add_page_log_ex()
{
?>
<div id="logs-page-ex" class="wrap-tab-content wpvivid_tab_log" name="tab-logs" style="display:none;">
<div>
<h2 class="nav-tab-wrapper" style="padding-bottom:0!important;">
<?php
$setting_array = array();
$setting_array = apply_filters('wpvivid_add_log_tab_page', $setting_array);
foreach ($setting_array as $setting_name) {
add_action('wpvivid_logpage_add_tab', $setting_name['tab_func'], $setting_name['index']);
add_action('wpvivid_logpage_add_page', $setting_name['page_func'], $setting_name['index']);
}
do_action('wpvivid_logpage_add_tab');
?>
</h2>
<?php do_action('wpvivid_logpage_add_page'); ?>
</div>
</div>
<?php
}
public function wpvivid_add_page_website_info()
{
?>
<div id="debug-page" class="wrap-tab-content wpvivid_tab_debug" name="tab-debug" style="display:none;">
<table class="widefat">
<div style="padding: 0 0 20px 10px;"><?php esc_html_e('There are two ways available to send us the debug information. The first one is recommended.', 'wpvivid-backuprestore'); ?></div>
<div style="padding-left: 10px;">
<strong><?php esc_html_e('Method 1.', 'wpvivid-backuprestore'); ?></strong> <?php esc_html_e('If you have configured SMTP on your site, enter your email address and click the button below to send us the relevant information (website info and errors logs) when you are encountering errors. This will help us figure out what happened. Once the issue is resolved, we will inform you by your email address.', 'wpvivid-backuprestore'); ?>
</div>
<div style="padding:10px 10px 0">
<span class="wpvivid-element-space-right"><?php esc_html_e('WPvivid support email:', 'wpvivid-backuprestore'); ?></span><input type="text" id="wpvivid_support_mail" value="support@wpvivid.com" readonly />
<span class="wpvivid-element-space-right"><?php esc_html_e('Your email:', 'wpvivid-backuprestore'); ?></span><input type="text" id="wpvivid_user_mail" />
</div>
<div style="padding:10px 10px 0">
<div style="float: left;">
<div class="wpvivid-element-space-bottom wpvivid-text-space-right wpvivid-debug-text-fix" style="float: left;">
<?php esc_html_e('I am using:', 'wpvivid-backuprestore'); ?>
</div>
<div class="wpvivid-element-space-bottom wpvivid-text-space-right" style="float: left;">
<select id="wpvivid_debug_type">
<option selected="selected" value="sharehost"><?php esc_html_e('share hosting', 'wpvivid-backuprestore'); ?></option>
<option value="vps"><?php esc_html_e('VPS hosting', 'wpvivid-backuprestore'); ?></option>
</select>
</div>
<div style="clear: both;"></div>
</div>
<div id="wpvivid_debug_host" style="float: left;">
<div class="wpvivid-element-space-bottom wpvivid-text-space-right wpvivid-debug-text-fix" style="float: left;">
<?php esc_html_e('My web hosting provider is:', 'wpvivid-backuprestore'); ?>
</div>
<div class="wpvivid-element-space-bottom wpvivid-text-space-right" style="float: left;">
<input type="text" id="wpvivid_host_provider"/></div>
<div style="clear: both;"></div>
</div>
<div style="clear: both;"></div>
</div>
<div style="padding:0 10px;">
<textarea id="wpvivid_debug_comment" class="wp-editor-area" style="width:100%; height: 200px;" autocomplete="off" cols="60" placeholder="<?php esc_attr_e('Please describe your problem here.', 'wpvivid-backuprestore'); ?>" ></textarea>
</div>
<div class="schedule-tab-block">
<input class="button-primary" type="submit" value="<?php esc_attr_e( 'Send Debug Information to Us', 'wpvivid-backuprestore' ); ?>" onclick="wpvivid_click_send_debug_info();" />
</div>
<div style="clear:both;"></div>
<div style="padding-left: 10px;">
<strong><?php esc_html_e('Method 2.', 'wpvivid-backuprestore'); ?></strong> <?php esc_html_e('If you didn’t configure SMTP on your site, click the button below to download the relevant information (website info and error logs) to your PC when you are encountering some errors. Sending the files to us will help us diagnose what happened.', 'wpvivid-backuprestore'); ?>
</div>
<div class="schedule-tab-block">
<input class="button-primary" id="wpvivid_download_website_info" type="submit" name="download-website-info" value="<?php esc_attr_e( 'Download', 'wpvivid-backuprestore' ); ?>" />
</div>
<thead class="website-info-head">
<tr>
<th class="row-title" style="min-width: 260px;"><?php esc_html_e( 'Website Info Key', 'wpvivid-backuprestore' ); ?></th>
<th><?php esc_html_e( 'Website Info Value', 'wpvivid-backuprestore' ); ?></th>
</tr>
</thead>
<tbody class="wpvivid-websiteinfo-list" id="wpvivid_websiteinfo_list">
<?php
global $wpvivid_plugin;
$website_info=$wpvivid_plugin->get_website_info();
if(!empty($website_info['data'])){
foreach ($website_info['data'] as $key=>$value) { ?>
<?php
$website_value='';
if (is_array($value)) {
foreach ($value as $arr_value) {
if (empty($website_value)) {
$website_value = $website_value . $arr_value;
} else {
$website_value = $website_value . ', ' . $arr_value;
}
}
}
else{
if($value === true || $value === false){
if($value === true) {
$website_value = 'true';
}
else{
$website_value = 'false';
}
}
else {
$website_value = $value;
}
}
?>
<tr>
<td class="row-title tablelistcolumn"><label for="tablecell"><?php echo esc_html($key); ?></label></td>
<td class="tablelistcolumn"><?php echo esc_html($website_value); ?></td>
</tr>
<?php }} ?>
</tbody>
</table>
</div>
<script>
jQuery('#wpvivid_download_website_info').click(function(){
wpvivid_download_website_info();
});
/**
* Download the relevant website info and error logs to your PC for debugging purposes.
*/
function wpvivid_download_website_info(){
wpvivid_location_href=true;
location.href =ajaxurl+'?_wpnonce='+wpvivid_ajax_object.ajax_nonce+'&action=wpvivid_create_debug_package';
}
jQuery("#wpvivid_debug_type").change(function()
{
if(jQuery(this).val()=='sharehost')
{
jQuery("#wpvivid_debug_host").show();
}
else
{
jQuery("#wpvivid_debug_host").hide();
}
});
function wpvivid_click_send_debug_info(){
var wpvivid_user_mail = jQuery('#wpvivid_user_mail').val();
var server_type = jQuery('#wpvivid_debug_type').val();
var host_provider = jQuery('#wpvivid_host_provider').val();
var comment = jQuery('#wpvivid_debug_comment').val();
var ajax_data = {
'action': 'wpvivid_send_debug_info',
'user_mail': wpvivid_user_mail,
'server_type':server_type,
'host_provider':host_provider,
'comment':comment
};
wpvivid_post_request(ajax_data, function (data) {
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === "success") {
alert("<?php esc_html_e('Send succeeded.', 'wpvivid-backuprestore'); ?>");
}
else {
alert(jsonarray.error);
}
}
catch (err) {
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('sending debug information', textStatus, errorThrown);
alert(error_message);
});
}
</script>
<?php
}
public function wpvivid_add_page_log()
{
global $wpvivid_plugin;
$display_log_count=array(0=>"10",1=>"20",2=>"30",3=>"40",4=>"50");
$max_log_diaplay=20;
$loglist=$wpvivid_plugin->get_log_list_ex();
?>
<div id="logs-page" class="log-tab-content wpvivid_tab_log" name="tab-logs">
<table class="wp-list-table widefat plugins">
<thead class="log-head">
<tr>
<th class="row-title"><?php esc_html_e( 'Date', 'wpvivid-backuprestore' ); ?></th>
<th><?php esc_html_e( 'Log Type', 'wpvivid-backuprestore' ); ?></th>
<th><?php esc_html_e( 'Log File Name', 'wpvivid-backuprestore' ); ?></th>
<th><?php esc_html_e( 'Action', 'wpvivid-backuprestore' ); ?></th>
</tr>
</thead>
<tbody class="wpvivid-loglist" id="wpvivid_loglist">
<?php
do_action('wpvivid_get_log_list_output');
?>
</tbody>
</table>
<div style="padding-top: 10px; text-align: center;">
<input class="button-secondary log-page" id="wpvivid_pre_log_page" type="submit" value="<?php esc_attr_e( ' < Pre page ', 'wpvivid-backuprestore' ); ?>" />
<div style="font-size: 12px; display: inline-block; padding-left: 10px;">
<span id="wpvivid_log_page_info" style="line-height: 35px;">
<?php
$current_page=1;
$max_page=ceil(sizeof($loglist['log_list']['file'])/$max_log_diaplay);
if($max_page == 0) $max_page = 1;
echo esc_html($current_page.' / '.$max_page);
?>
</span>
</div>
<input class="button-secondary log-page" id="wpvivid_next_log_page" type="submit" value="<?php esc_attr_e( ' Next page > ', 'wpvivid-backuprestore' ); ?>" />
<div style="float: right;">
<select name="" id="wpvivid_display_log_count">
<?php
foreach ($display_log_count as $value){
if($value == $max_log_diaplay){
echo '<option selected="selected" value="' . esc_attr($value) . '">' . esc_html($value) . '</option>';
}
else {
echo '<option value="' . esc_attr($value) . '">' . esc_html($value) . '</option>';
}
}
?>
</select>
</div>
</div>
</div>
<script>
jQuery('#wpvivid_display_log_count').on("change", function(){
wpvivid_display_log_page();
});
jQuery('#wpvivid_pre_log_page').click(function(){
wpvivid_pre_log_page();
});
jQuery('#wpvivid_next_log_page').click(function(){
wpvivid_next_log_page();
});
function wpvivid_pre_log_page(){
if(wpvivid_cur_log_page > 1){
wpvivid_cur_log_page--;
}
wpvivid_display_log_page();
}
function wpvivid_next_log_page(){
var display_count = jQuery("#wpvivid_display_log_count option:selected").val();
var max_pages=Math.ceil(wpvivid_log_count/display_count);
if(wpvivid_cur_log_page < max_pages){
wpvivid_cur_log_page++;
}
wpvivid_display_log_page();
}
function wpvivid_display_log_page(){
var display_count = jQuery("#wpvivid_display_log_count option:selected").val();
var max_pages=Math.ceil(wpvivid_log_count/display_count);
if(max_pages == 0) max_pages = 1;
jQuery('#wpvivid_log_page_info').html(wpvivid_cur_log_page+ " / "+max_pages);
var begin = (wpvivid_cur_log_page - 1) * display_count;
var end = parseInt(begin) + parseInt(display_count);
jQuery("#wpvivid_loglist tr").hide();
jQuery('#wpvivid_loglist tr').each(function(i){
if (i >= begin && i < end)
{
jQuery(this).show();
}
});
}
function wpvivid_retrieve_log_list()
{
var ajax_data = {
'action': 'wpvivid_get_log_list'
};
wpvivid_post_request(ajax_data, function(data){
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === "success") {
jQuery('#wpvivid_loglist').html("");
jQuery('#wpvivid_loglist').append(jsonarray.html);
wpvivid_log_count = jsonarray.log_count;
wpvivid_display_log_page();
}
}
catch(err){
alert(err);
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
setTimeout(function () {
wpvivid_retrieve_log_list();
}, 3000);
});
}
</script>
<?php
}
public function wpvivid_add_page_read_log()
{
?>
<div id="log-read-page" class="wrap-tab-content wpvivid_tab_read_log" style="display:none;">
<div class="postbox restore_log" id="wpvivid_read_log_content">
<div></div>
</div>
</div>
<?php
}
public function wpvivid_add_page_mwp()
{
?>
<div id="mwp-page" class="wrap-tab-content wpvivid_tab_mainwp" name="tab-mwp" style="display:none;">
<div style="padding: 10px; background-color: #fff;">
<div style="margin-bottom: 10px;">
<?php esc_html_e('If you are a MainWP user, you can set up and control WPvivid Backup Free and Pro for every child site directly from your MainWP dashboard, using our WPvivid Backup for MainWP extension.', 'wpvivid-backuprestore'); ?>
</div>
<div style="margin-bottom: 10px;">
<input type="button" class="button-primary" id="wpvivid_download_mainwp_extension" value="<?php esc_attr_e('Download WPvivid Backup for MainWP', 'wpvivid-backuprestore'); ?>" />
</div>
<div style="margin-bottom: 10px;">
<?php esc_html_e('1. Create and download backups for a specific child site', 'wpvivid-backuprestore'); ?>
</div>
<div style="margin-bottom: 10px;">
<?php esc_html_e('2. Set backup schedules for all child sites', 'wpvivid-backuprestore'); ?>
</div>
<div style="margin-bottom: 10px;">
<?php
esc_html_e('3. Set WPvivid Backup Free and Pro settings for all child sites', 'wpvivid-backuprestore');
?>
</div>
<div style="margin-bottom: 10px;">
<?php
esc_html_e('4. Install, claim and update WPvivid Backup Pro for child sites in bulk', 'wpvivid-backuprestore');
?>
</div>
<div>
<?php
esc_html_e('5. Set up remote storage for child sites in bulk (for WPvivid Backup Pro only)', 'wpvivid-backuprestore');
?>
</div>
</div>
</div>
<script>
jQuery('#wpvivid_download_mainwp_extension').click(function(){
var tempwindow=window.open('_blank');
tempwindow.location='https://wordpress.org/plugins/wpvivid-backup-mainwp';
});
jQuery('#wpvivid_ask_for_discount').click(function(){
var tempwindow=window.open('_blank');
tempwindow.location='https://wpvivid.com/wpvivid-backup-for-mainwp';
});
</script>
<?php
}
public function wpvivid_add_page_premium(){
?>
<div id="premium-page" class="wrap-tab-content wpvivid_tab_premium" name="tab-premium" style="display: none;">
<table class="wp-list-table widefat plugins" style="border-collapse: collapse;">
<thead>
<tr class="backup-list-head" style="border-bottom: 0;">
<th><?php esc_html_e('Features', 'wpvivid-backuprestore'); ?></th>
<th style="text-align:center;"><?php esc_html_e('Blogger', 'wpvivid-backuprestore'); ?></th>
<th style="text-align:center;"><?php esc_html_e('Freelancer', 'wpvivid-backuprestore'); ?></th>
<th style="text-align:center;"><?php esc_html_e('Small Business', 'wpvivid-backuprestore'); ?></th>
<th style="text-align:center;"><?php esc_html_e('Ultimate', 'wpvivid-backuprestore'); ?></th>
</tr>
</thead>
<tbody class="wpvivid-backuplist">
<tr style="">
<td>
<p><strong><?php esc_html_e('Domains', 'wpvivid-backuprestore'); ?></strong></p>
<p><strong><?php esc_html_e('Backup & Migration Pro', 'wpvivid-backuprestore'); ?></strong></p>
<p><strong><?php esc_html_e('Image Optimization Pro (Unlimited/domain)', 'wpvivid-backuprestore'); ?></strong></p>
<p><strong><?php esc_html_e('Mulitsite Support', 'wpvivid-backuprestore'); ?></strong></p>
<p><strong><?php esc_html_e('Staging Pro', 'wpvivid-backuprestore'); ?></strong></p>
<p><strong><?php esc_html_e('White Label', 'wpvivid-backuprestore'); ?></strong></p>
<p><strong><?php esc_html_e('Roles & Capabilities', 'wpvivid-backuprestore'); ?></strong></p>
</td>
<td style="text-align:center;">
<p><span style="color: #81d742;"><?php esc_html_e('2 domains', 'wpvivid-backuprestore'); ?></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
</td>
<td style="text-align:center;">
<p><span style="color: #81d742;"><?php esc_html_e('Up to 10 domains', 'wpvivid-backuprestore'); ?></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
</td>
<td style="text-align:center;">
<p><span style="color: #81d742;"><?php esc_html_e('Up to 50 domains', 'wpvivid-backuprestore'); ?></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
</td>
<td style="text-align:center;">
<p><span style="color: #81d742;"><?php esc_html_e('Unlimited domains', 'wpvivid-backuprestore'); ?></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
<p><span style="height: 12px;width: 12px;background-color: #81d742;border-radius: 50%;display: inline-block;"></span></p>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="5" style="text-align:center;"><p style="margin-top: 6px;"><a href="https://wpvivid.com/pricing" class="page-title-action"><?php esc_html_e('See Plans', 'wpvivid-backuprestore'); ?></a></p></th>
</tr>
</tfoot>
</table>
</div>
<?php
}
} admin/partials/wpvivid-settings-page-display.php 0000644 00000146031 15132770567 0016111 0 ustar 00 <?php
function wpvivid_general_settings()
{
$general_setting=WPvivid_Setting::get_setting(true, "");
$display_backup_count=isset($general_setting['options']['wpvivid_common_setting']['max_backup_count'])?$general_setting['options']['wpvivid_common_setting']['max_backup_count']:WPVIVID_DEFAULT_BACKUP_COUNT;
//
$display_backup_count=intval($display_backup_count);
if($display_backup_count > 7)
{
$display_backup_count = 7;
}
if($general_setting['options']['wpvivid_common_setting']['estimate_backup'])
{
$wpvivid_setting_estimate_backup='checked';
}
else{
$wpvivid_setting_estimate_backup='';
}
/*if(!isset($general_setting['options']['wpvivid_common_setting']['show_tab_menu'])){
$wpvivid_show_tab_menu='checked';
}
else {
if ($general_setting['options']['wpvivid_common_setting']['show_tab_menu']) {
$wpvivid_show_tab_menu = 'checked';
} else {
$wpvivid_show_tab_menu = '';
}
}*/
if(!isset($general_setting['options']['wpvivid_common_setting']['show_admin_bar'])){
$show_admin_bar = 'checked';
}
else{
if($general_setting['options']['wpvivid_common_setting']['show_admin_bar']){
$show_admin_bar = 'checked';
}
else{
$show_admin_bar = '';
}
}
if(!isset($general_setting['options']['wpvivid_common_setting']['domain_include'])){
$wpvivid_domain_include = 'checked';
}
else{
if($general_setting['options']['wpvivid_common_setting']['domain_include']){
$wpvivid_domain_include = 'checked';
}
else{
$wpvivid_domain_include = '';
}
}
if(!isset($general_setting['options']['wpvivid_common_setting']['ismerge'])){
$wpvivid_ismerge = 'checked';
}
else{
if($general_setting['options']['wpvivid_common_setting']['ismerge'] == '1'){
$wpvivid_ismerge = 'checked';
}
else{
$wpvivid_ismerge = '';
}
}
if(!isset($general_setting['options']['wpvivid_common_setting']['retain_local'])){
$wpvivid_retain_local = '';
}
else{
if($general_setting['options']['wpvivid_common_setting']['retain_local'] == '1'){
$wpvivid_retain_local = 'checked';
}
else{
$wpvivid_retain_local = '';
}
}
if(!isset($general_setting['options']['wpvivid_common_setting']['uninstall_clear_folder'])){
$uninstall_clear_folder = '';
}
else{
if($general_setting['options']['wpvivid_common_setting']['uninstall_clear_folder'] == '1'){
$uninstall_clear_folder = 'checked';
}
else{
$uninstall_clear_folder = '';
}
}
if(!isset($general_setting['options']['wpvivid_common_setting']['backup_symlink_folder'])){
$backup_symlink_folder = '';
}
else{
if($general_setting['options']['wpvivid_common_setting']['backup_symlink_folder'] == '1'){
$backup_symlink_folder = 'checked';
}
else{
$backup_symlink_folder = '';
}
}
global $wpvivid_plugin;
$out_of_date=$wpvivid_plugin->_get_out_of_date_info();
?>
<div class="postbox schedule-tab-block">
<div>
<select option="setting" name="max_backup_count" id="wpvivid_max_backup_count">
<?php
for($i=1; $i<8;$i++){
if($i === $display_backup_count){
echo '<option selected="selected" value="' . esc_attr($i) . '">' . esc_attr($i) . '</option>';
}
else {
echo '<option value="' . esc_attr($i) . '">' . esc_attr($i) . '</option>';
}
}
?>
</select><strong style="margin-right: 10px;"><?php esc_html_e('backups retained', 'wpvivid-backuprestore'); ?></strong><a href="https://docs.wpvivid.com/wpvivid-backup-pro-backup-retention.html" style="text-decoration: none;"><?php esc_html_e('Pro feature: Retain more backups', 'wpvivid-backuprestore'); ?></a>
</div>
<div>
<label for="wpvivid_estimate_backup">
<input type="checkbox" option="setting" name="estimate_backup" id="wpvivid_estimate_backup" value="1" <?php echo esc_attr($wpvivid_setting_estimate_backup); ?> />
<span><?php esc_html_e('Calculate the size of files, folder and database before backing up', 'wpvivid-backuprestore' ); ?></span>
</label>
</div>
<div>
<label>
<input type="checkbox" option="setting" name="show_admin_bar" <?php echo esc_attr($show_admin_bar); ?> />
<span><?php esc_html_e('Show WPvivid backup plugin on top admin bar', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
<div>
<label>
<input type="checkbox" option="setting" name="ismerge" <?php echo esc_attr($wpvivid_ismerge); ?> />
<span><?php esc_html_e('Merge all the backup files into single package when a backup completes. This will save great disk spaces, though takes longer time. We recommended you check the option especially on sites with insufficient server resources.', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
<div>
<label>
<input type="checkbox" option="setting" name="retain_local" <?php echo esc_attr($wpvivid_retain_local); ?> />
<span><?php esc_html_e('Keep storing the backups in localhost after uploading to remote storage', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
<div>
<label>
<input type="checkbox" option="setting" name="uninstall_clear_folder" <?php echo esc_attr($uninstall_clear_folder); ?> />
<span><?php echo esc_html(sprintf('Delete the /%s folder and all backups in it when deleting WPvivid Backup plugin.', $general_setting['options']['wpvivid_local_setting']['path'])); ?></span>
</label>
</div>
<div>
<label>
<input type="checkbox" option="setting" name="backup_symlink_folder" <?php echo esc_attr($backup_symlink_folder); ?> />
<span><?php esc_html_e('Back up symlink folders. Including symlink folders may cause backup/migration failure. Uncheck this option unless you know how symlink folders work.', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
</div>
<div class="postbox schedule-tab-block">
<div><strong><?php esc_html_e('Backup Folder', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<div><p><?php esc_html_e('Name your folder, this folder must be writable for creating backup files.', 'wpvivid-backuprestore' ); ?><p> </div>
<input type="text" placeholder="wpvividbackups" option="setting" name="path" id="wpvivid_option_backup_dir" class="all-options" value="<?php echo esc_attr($general_setting['options']['wpvivid_local_setting']['path']); ?>" onkeyup="value=value.replace(/[^\a-\z\A-\Z0-9]/g,'')" onpaste="value=value.replace(/[^\a-\z\A-\Z0-9]/g,'')" />
<p><span class="wpvivid-element-space-right"><?php esc_html_e('Local storage directory:', 'wpvivid-backuprestore'); ?></span><span><?php echo esc_html(WP_CONTENT_DIR.'/'); ?><span id="wpvivid_setting_local_storage_path"><?php echo esc_html($general_setting['options']['wpvivid_local_setting']['path']); ?></span></span></p>
</div>
<div>
<label>
<input type="checkbox" option="setting" name="domain_include" <?php echo esc_attr($wpvivid_domain_include); ?> />
<span><?php esc_html_e('Display domain(url) of current site in backup name. (e.g. domain_wpvivid-5ceb938b6dca9_2019-05-27-07-36_backup_all.zip)', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
</div>
<div class="postbox schedule-tab-block">
<div><strong><?php esc_html_e('Remove out-of-date backups', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block" style="padding-bottom: 0;">
<fieldset>
<label for="users_can_register">
<p><span class="wpvivid-element-space-right"><?php esc_html_e('Web Server Directory:', 'wpvivid-backuprestore'); ?></span><span id="wpvivid_out_of_date_local_path"><?php echo esc_html($out_of_date['web_server']); ?></span></p>
<p><span style="margin-right: 2px;"><?php esc_html_e('Remote Storage Directory:', 'wpvivid-backuprestore'); ?></span><span id="wpvivid_out_of_date_remote_path">
<?php
$wpvivid_get_remote_directory = '';
$wpvivid_get_remote_directory = apply_filters('wpvivid_get_remote_directory', $wpvivid_get_remote_directory);
echo esc_html($wpvivid_get_remote_directory);
?>
</span>
</p>
</label>
</fieldset>
</div>
<div class="setting-tab-block" style="padding: 10px 10px 0 0;">
<input class="button-primary" id="wpvivid_delete_out_of_backup" style="margin-right:10px;" type="submit" name="delete-out-of-backup" value="<?php esc_attr_e( 'Remove', 'wpvivid-backuprestore' ); ?>" />
<p><?php esc_html_e('The action is irreversible! It will remove all backups are out-of-date (including local web server and remote storage) if they exist.', 'wpvivid-backuprestore'); ?> </p>
</div>
</div>
<script>
jQuery('#wpvivid_delete_out_of_backup').click(function(){
wpvivid_delete_out_of_date_backups();
});
/**
* This function will delete out of date backups.
*/
function wpvivid_delete_out_of_date_backups(){
var ajax_data={
'action': 'wpvivid_clean_out_of_date_backup'
};
jQuery('#wpvivid_delete_out_of_backup').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function(data){
jQuery('#wpvivid_delete_out_of_backup').css({'pointer-events': 'auto', 'opacity': '1'});
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === "success") {
alert("<?php esc_html_e('Out of date backups have been removed.', 'wpvivid-backuprestore'); ?>");
wpvivid_handle_backup_data(data);
}
}
catch(err){
alert(err);
jQuery('#wpvivid_delete_out_of_backup').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('deleting out of date backups', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_delete_out_of_backup').css({'pointer-events': 'auto', 'opacity': '1'});
});
}
</script>
<?php
}
function wpvivid_email_report()
{
$general_setting=WPvivid_Setting::get_setting(true, "");
$setting_email_enable='';
$setting_email_display = 'display: none;';
if(isset($general_setting['options']['wpvivid_email_setting']['email_enable'])){
if($general_setting['options']['wpvivid_email_setting']['email_enable']){
$setting_email_enable='checked';
$setting_email_display = '';
}
}
$wpvivid_setting_email_always='';
$wpvivid_setting_email_failed='';
if(isset($general_setting['options']['wpvivid_email_setting']['always'])&&$general_setting['options']['wpvivid_email_setting']['always']) {
$wpvivid_setting_email_always='checked';
}
else{
$wpvivid_setting_email_failed='checked';
}
?>
<div class="postbox schedule-tab-block" id="wpvivid_email_report">
<div><p>In order to use this function, please install a <strong><a target="_blank" href="https://wpvivid.com/8-best-smtp-plugins-for-wordpress.html" style="text-decoration: none;">WordPress SMTP plugin</a></strong> of your preference and configure your SMTP server first. This is because WordPress uses the PHP Mail function to send its emails by default, which is not supported by many hosts and can cause issues if it is not set properly.
</div>
<div>
<label for="wpvivid_general_email_enable">
<input type="checkbox" option="setting" name="email_enable" id="wpvivid_general_email_enable" value="1" <?php echo esc_attr($setting_email_enable); ?> />
<span><strong><?php esc_html_e( 'Enable email report', 'wpvivid-backuprestore' ); ?></strong></span>
</label>
</div>
<div id="wpvivid_general_email_setting" style="<?php echo esc_attr($setting_email_display); ?>" >
<input type="text" placeholder="example@yourdomain.com" option="setting" name="send_to" class="regular-text" id="wpvivid_mail" value="<?php
if(!empty($general_setting['options']['wpvivid_email_setting']['send_to'])) {
foreach ($general_setting['options']['wpvivid_email_setting']['send_to'] as $mail) {
if(!empty($mail) && !is_array($mail)) {
echo esc_attr($mail);
break;
}
}
}
?>" />
<input class="button-secondary" id="wpvivid_send_email_test" style="margin-top:10px;" type="submit" name="" value="<?php esc_attr_e( 'Test Email', 'wpvivid-backuprestore' ); ?>" title="Send an email for testing mail function"/>
<div id="wpvivid_send_email_res"></div>
<fieldset class="setting-tab-block">
<label >
<input type="radio" option="setting" name="always" value="1" <?php echo esc_attr($wpvivid_setting_email_always); ?> />
<span><?php esc_html_e( 'Always send an email notification when a backup is complete', 'wpvivid-backuprestore' ); ?></span>
</label><br>
<label >
<input type="radio" option="setting" name="always" value="0" <?php echo esc_attr($wpvivid_setting_email_failed); ?> />
<span><?php esc_html_e( 'Only send an email notification when a backup fails', 'wpvivid-backuprestore' ); ?></span>
</label><br>
</fieldset>
<div style="margin-bottom: 10px;">
<a href="https://wpvivid.com/wpvivid-backup-pro-email-report?utm_source=client_email_report&utm_medium=inner_link&utm_campaign=access" style="text-decoration: none;"><?php esc_html_e('Pro feature: Add another email address to get report', 'wpvivid-backuprestore'); ?></a>
</div>
</div>
</div>
<script>
jQuery('#wpvivid_send_email_test').click(function(){
wpvivid_email_test();
});
/**
* After enabling email report feature, and test if an email address works or not
*/
function wpvivid_email_test(){
var mail = jQuery('#wpvivid_mail').val();
var ajax_data = {
'action': 'wpvivid_test_send_mail',
'send_to': mail
};
wpvivid_post_request(ajax_data, function(data){
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
jQuery('#wpvivid_send_email_res').html('Test succeeded.');
}
else {
jQuery('#wpvivid_send_email_res').html('Test failed, ' + jsonarray.error);
}
}
catch(err){
alert(err);
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('sending test mail', textStatus, errorThrown);
alert(error_message);
});
}
</script>
<?php
}
function wpvivid_clean_junk()
{
global $wpvivid_plugin;
$junk_file=$wpvivid_plugin->_junk_files_info_ex();
?>
<div class="postbox schedule-tab-block" id="wpvivid_clean_junk">
<div>
<strong><?php esc_html_e('Web-server disk space in use by WPvivid', 'wpvivid-backuprestore'); ?></strong>
</div>
<div class="setting-tab-block">
<div class="setting-tab-block">
<span class="wpvivid-element-space-right"><?php esc_html_e('Total Size:', 'wpvivid-backuprestore'); ?></span>
<span class="wpvivid-size-calc wpvivid-element-space-right" id="wpvivid_junk_sum_size"><?php echo esc_html($junk_file['sum_size']); ?></span>
<span class="wpvivid-element-space-right"><?php esc_html_e( 'Backup Size:', 'wpvivid-backuprestore' ); ?></span>
<span class="wpvivid-size-calc wpvivid-element-space-right" id="wpvivid_backup_size"><?php echo esc_html($junk_file['backup_size']); ?></span>
<input class="button-secondary" id="wpvivid_calculate_size" style="margin-left:10px;" type="submit" name="Calculate-Sizes" value="<?php esc_attr_e( 'Calculate Sizes', 'wpvivid-backuprestore' ); ?>" />
</div>
<fieldset>
<label for="wpvivid_junk_log">
<input type="checkbox" id="wpvivid_junk_log" option="junk-files" name="log" value="junk-log" />
<span class="wpvivid-element-space-right"><?php esc_html_e( 'Logs Size:', 'wpvivid-backuprestore' ); ?></span>
<span class="wpvivid-size-calc" id="wpvivid_log_size"><?php echo esc_html($junk_file['log_dir_size']); ?></span>
</label>
</fieldset>
<fieldset>
<label for="wpvivid_junk_backup_cache">
<input type="checkbox" id="wpvivid_junk_backup_cache" option="junk-files" name="backup_cache" value="junk-backup-cache" />
<span class="wpvivid-element-space-right"><?php esc_html_e( 'Backup Cache Size:', 'wpvivid-backuprestore' ); ?></span>
<span class="wpvivid-size-calc" id="wpvivid_backup_cache_size"><?php echo esc_html($junk_file['backup_cache_size']); ?></span>
</label>
</fieldset>
<fieldset>
<label for="wpvivid_junk_file">
<input type="checkbox" id="wpvivid_junk_file" option="junk-files" name="junk_files" value="junk-files" />
<span class="wpvivid-element-space-right"><?php esc_html_e( 'Junk Size:', 'wpvivid-backuprestore' ); ?></span>
<span class="wpvivid-size-calc" id="wpvivid_junk_size"><?php echo esc_html($junk_file['junk_size']); ?></span>
</label>
</fieldset>
</div>
<div><input class="button-primary" id="wpvivid_clean_junk_file" type="submit" name="Empty-all-files" value="<?php esc_attr_e( 'Empty', 'wpvivid-backuprestore' ); ?>" /></div>
<div style="clear:both;"></div>
</div>
<script>
jQuery('#wpvivid_calculate_size').click(function(){
wpvivid_calculate_diskspaceused();
});
jQuery('#wpvivid_clean_junk_file').click(function(){
wpvivid_clean_junk_files();
});
/**
* Calculate the server disk space in use by WPvivid.
*/
function wpvivid_calculate_diskspaceused(){
var ajax_data={
'action': 'wpvivid_junk_files_info'
};
var current_size = jQuery('#wpvivid_junk_sum_size').html();
jQuery('#wpvivid_calculate_size').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#wpvivid_clean_junk_file').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('.wpvivid-size-calc').html("calculating...");
wpvivid_post_request(ajax_data, function(data){
jQuery('#wpvivid_calculate_size').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#wpvivid_clean_junk_file').css({'pointer-events': 'auto', 'opacity': '1'});
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === "success") {
jQuery('#wpvivid_junk_sum_size').html(jsonarray.data.sum_size);
jQuery('#wpvivid_log_size').html(jsonarray.data.log_dir_size);
jQuery('#wpvivid_backup_cache_size').html(jsonarray.data.backup_cache_size);
jQuery('#wpvivid_junk_size').html(jsonarray.data.junk_size);
jQuery('#wpvivid_backup_size').html(jsonarray.data.backup_size);
}
}
catch(err){
jQuery('#wpvivid_calculate_size').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#wpvivid_clean_junk_file').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#wpvivid_junk_sum_size').html(current_size);
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
jQuery('#wpvivid_calculate_size').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#wpvivid_clean_junk_file').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#wpvivid_junk_sum_size').html(current_size);
});
}
/**
* Clean junk files created during backups and restorations off your web server disk.
*/
function wpvivid_clean_junk_files(){
var descript = '<?php esc_html_e('The selected item(s) will be permanently deleted. Are you sure you want to continue?', 'wpvivid-backuprestore'); ?>';
var ret = confirm(descript);
if(ret === true){
var option_data = wpvivid_ajax_data_transfer('junk-files');
var ajax_data = {
'action': 'wpvivid_clean_local_storage',
'options': option_data
};
jQuery('#wpvivid_calculate_size').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#wpvivid_clean_junk_file').css({'pointer-events': 'none', 'opacity': '0.4'});
wpvivid_post_request(ajax_data, function (data) {
jQuery('#wpvivid_calculate_size').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#wpvivid_clean_junk_file').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('input[option="junk-files"]').prop('checked', false);
try {
var jsonarray = jQuery.parseJSON(data);
alert(jsonarray.msg);
if (jsonarray.result === "success") {
jQuery('#wpvivid_junk_sum_size').html(jsonarray.data.sum_size);
jQuery('#wpvivid_log_size').html(jsonarray.data.log_dir_size);
jQuery('#wpvivid_backup_cache_size').html(jsonarray.data.backup_cache_size);
jQuery('#wpvivid_junk_size').html(jsonarray.data.junk_size);
jQuery('#wpvivid_backup_size').html(jsonarray.data.backup_size);
jQuery('#wpvivid_loglist').html("");
jQuery('#wpvivid_loglist').append(jsonarray.html);
wpvivid_log_count = jsonarray.log_count;
wpvivid_display_log_page();
}
}
catch(err){
alert(err);
}
}, function (XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('cleaning out junk files', textStatus, errorThrown);
alert(error_message);
jQuery('#wpvivid_calculate_size').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('#wpvivid_clean_junk_file').css({'pointer-events': 'auto', 'opacity': '1'});
});
}
}
jQuery(document).ready(function ()
{
//wpvivid_calculate_diskspaceused();
});
</script>
<?php
}
function wpvivid_export_import_settings()
{
?>
<div class="postbox schedule-tab-block" id="wpvivid_export_import">
<div class="setting-tab-block" style="padding-bottom: 0;">
<input class="button-primary" id="wpvivid_setting_export" type="button" name="" value="<?php esc_attr_e( 'Export', 'wpvivid-backuprestore' ); ?>" />
<p><?php esc_html_e('Click \'Export\' button to save WPvivid settings on your local computer.', 'wpvivid-backuprestore'); ?> </p>
</div>
<div class="setting-tab-block" style="padding: 0 10px 0 0;">
<input type="file" name="fileTrans" id="wpvivid_select_import_file"></br>
<input class="button-primary" id="wpvivid_setting_import" type="button" name="" value="<?php esc_attr_e( 'Import', 'wpvivid-backuprestore' ); ?>" />
<p><?php esc_html_e('Importing the json file can help you set WPvivid\'s configuration on another wordpress site quickly.', 'wpvivid-backuprestore'); ?></p>
</div>
<div style="clear:both;"></div>
</div>
<script>
jQuery('#wpvivid_setting_export').click(function(){
wpvivid_export_settings();
});
jQuery('#wpvivid_setting_import').click(function(){
wpvivid_import_settings();
});
function wpvivid_export_settings() {
wpvivid_location_href=true;
location.href =ajaxurl+'?_wpnonce='+wpvivid_ajax_object.ajax_nonce+'&action=wpvivid_export_setting&setting=1&history=1&review=0';
}
function wpvivid_import_settings(){
var files = jQuery('input[name="fileTrans"]').prop('files');
if(files.length == 0){
alert('Choose a settings file and import it by clicking Import button.');
return;
}
else{
var reader = new FileReader();
reader.readAsText(files[0], "UTF-8");
reader.onload = function(evt){
var fileString = evt.target.result;
var ajax_data = {
'action': 'wpvivid_import_setting',
'data': fileString
};
wpvivid_post_request(ajax_data, function(data){
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
alert('The plugin settings were imported successfully.');
location.reload();
}
else {
alert('Error: ' + jsonarray.error);
}
}
catch(err){
alert(err);
}
}, function(XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('importing the previously-exported settings', textStatus, errorThrown);
jQuery('#wpvivid_display_log_content').html(error_message);
});
}
}
}
</script>
<?php
}
function wpvivid_advanced_settings()
{
//wpvivid_compress_setting backup
$common_setting=get_option('wpvivid_common_setting',array());
$max_file_size=isset($common_setting['max_file_size'])?$common_setting['max_file_size']:WPVIVID_DEFAULT_MAX_FILE_SIZE;
$exclude_file_size=isset($common_setting['exclude_file_size'])?$common_setting['exclude_file_size']:WPVIVID_DEFAULT_EXCLUDE_FILE_SIZE;
$max_execution_time=isset($common_setting['max_execution_time'])?$common_setting['max_execution_time']:WPVIVID_MAX_EXECUTION_TIME;
$memory_limit=isset($common_setting['memory_limit'])?$common_setting['memory_limit']:WPVIVID_MEMORY_LIMIT;
$migrate_size=isset($common_setting['migrate_size'])?$common_setting['migrate_size']:WPVIVID_MIGRATE_SIZE;
$wpvivid_max_resume_count=isset($common_setting['max_resume_count'])?$common_setting['max_resume_count']:WPVIVID_RESUME_RETRY_TIMES;
//$compress_file_use_cache=isset($common_setting['compress_file_use_cache'])?$common_setting['compress_file_use_cache']:false;
$compress_file_count=isset($common_setting['compress_file_count'])?$common_setting['compress_file_count']:500;
$max_sql_file_size=isset($common_setting['max_sql_file_size'])?$common_setting['max_sql_file_size']:200;
//restore
$restore_max_execution_time=isset($common_setting['restore_max_execution_time'])?$common_setting['restore_max_execution_time']:WPVIVID_RESTORE_MAX_EXECUTION_TIME;
$restore_memory_limit=isset($common_setting['restore_memory_limit'])?$common_setting['restore_memory_limit']:WPVIVID_RESTORE_MEMORY_LIMIT;
$replace_rows_pre_request=isset($common_setting['replace_rows_pre_request'])?$common_setting['replace_rows_pre_request']:10000;
$sql_file_buffer_pre_request=isset($common_setting['sql_file_buffer_pre_request'])?$common_setting['sql_file_buffer_pre_request']:'5';
$use_index=isset($common_setting['use_index'])?$common_setting['use_index']:1;
if($use_index)
{
$use_index=' checked';
}
else
{
$use_index=' ';
}
$unzip_files_pre_request=isset($common_setting['unzip_files_pre_request'])?$common_setting['unzip_files_pre_request']:1000;
//common
if(isset($common_setting['db_connect_method']))
{
if($common_setting['db_connect_method'] === 'wpdb')
{
$db_method_wpdb = 'checked';
$db_method_pdo = '';
}
else
{
$db_method_wpdb = '';
$db_method_pdo = 'checked';
}
}
else
{
$db_method_wpdb = 'checked';
$db_method_pdo = '';
}
if(isset($common_setting['zip_method']))
{
if($common_setting['zip_method'] === 'ziparchive')
{
$zip_method_archive = 'checked';
$zip_method_pclzip = '';
}
else{
$zip_method_archive = '';
$zip_method_pclzip = 'checked';
}
}
else
{
if(class_exists('ZipArchive'))
{
if(method_exists('ZipArchive', 'addFile'))
{
$zip_method_archive = 'checked';
$zip_method_pclzip = '';
}
else
{
$zip_method_archive = '';
$zip_method_pclzip = 'checked';
}
}
else
{
$zip_method_archive = '';
$zip_method_pclzip = 'checked';
}
}
if(isset($common_setting['backup_params']))
{
if($common_setting['backup_params'] === 'low')
{
$backup_params_low = 'checked';
$backup_params_mid = '';
$backup_params_high = '';
$backup_params_custom = '';
$backup_custom_setting_display = 'display: none;';
}
else if($common_setting['backup_params'] === 'mid')
{
$backup_params_low = '';
$backup_params_mid = 'checked';
$backup_params_high = '';
$backup_params_custom = '';
$backup_custom_setting_display = 'display: none;';
}
else if($common_setting['backup_params'] === 'high')
{
$backup_params_low = '';
$backup_params_mid = '';
$backup_params_high = 'checked';
$backup_params_custom = '';
$backup_custom_setting_display = 'display: none;';
}
else if($common_setting['backup_params'] === 'custom')
{
$backup_params_low = '';
$backup_params_mid = '';
$backup_params_high = '';
$backup_params_custom = 'checked';
$backup_custom_setting_display = '';
}
else
{
$backup_params_low = 'checked';
$backup_params_mid = '';
$backup_params_high = '';
$backup_params_custom = '';
$backup_custom_setting_display = 'display: none;';
}
}
else if(isset($common_setting['compress_file_count']))
{
$backup_params_low = '';
$backup_params_mid = '';
$backup_params_high = '';
$backup_params_custom = 'checked';
$backup_custom_setting_display = '';
}
else
{
$backup_params_low = 'checked';
$backup_params_mid = '';
$backup_params_high = '';
$backup_params_custom = '';
$backup_custom_setting_display = 'display: none;';
}
?>
<div class="postbox schedule-tab-block wpvivid-setting-addon" style="margin-bottom: 10px; padding-bottom: 0;">
<div class="wpvivid-element-space-bottom">
<strong><?php esc_html_e('Database access method.', 'wpvivid-backuprestore'); ?></strong>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="radio" option="setting" name="db_connect_method" value="wpdb" <?php echo esc_attr($db_method_wpdb); ?> />
<span class="wpvivid-element-space-right"><strong>WPDB</strong></span><span><?php esc_html_e('WPDB option has a better compatibility, but the speed of backup and restore is slower.', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="radio" option="setting" name="db_connect_method" value="pdo" <?php echo esc_attr($db_method_pdo); ?> />
<span class="wpvivid-element-space-right"><strong>PDO</strong></span><span><?php esc_html_e('It is recommended to choose PDO option if pdo_mysql extension is installed on your server, which lets you backup and restore your site faster.', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
</div>
<div class="postbox schedule-tab-block wpvivid-setting-addon" style="margin-bottom: 10px; padding-bottom: 0;">
<div class="wpvivid-element-space-bottom">
<strong><?php esc_html_e('Backup compression method.', 'wpvivid-backuprestore'); ?></strong>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="radio" option="setting" name="zip_method" value="ziparchive" <?php echo esc_attr($zip_method_archive); ?> />
<span class="wpvivid-element-space-right"><strong>ZipArchive</strong></span><span><?php esc_html_e('ZipArchive has a better flexibility which provides a higher backup success rate and speed. WPvivid Backup Plugin uses ZipArchive method by default. Using this method requires the ZIP extension to be installed within your PHP.', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="radio" option="setting" name="zip_method" value="pclzip" <?php echo esc_attr($zip_method_pclzip); ?> />
<span class="wpvivid-element-space-right"><strong>PCLZIP</strong></span><span><?php esc_html_e('PclZip is a much slower but more stable zip method that is included in every WordPress install. WPvivid will automatically switch to PclZip if the ZIP extension is not installed within your PHP.', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
</div>
<div class="postbox schedule-tab-block setting-page-content">
<div style="padding-top: 10px;">
<div class="wpvivid-element-space-bottom">
<strong><?php esc_html_e('Backup performance mode.', 'wpvivid-backuprestore'); ?></strong>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="radio" option="setting" name="backup_params" value="low" <?php esc_attr_e($backup_params_low); ?> />
<span class="wpvivid-element-space-right"><strong>Low (Balanced)</strong></span><span><?php esc_html_e('Use this default setting for minimal server resource usage, but expect longer backup times. Best for shared hosting or limited resources. Backups are split into 200MB chunks.', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="radio" option="setting" name="backup_params" value="mid" <?php esc_attr_e($backup_params_mid); ?> />
<span class="wpvivid-element-space-right"><strong>Mid (Standard)</strong></span><span><?php esc_html_e('This mode offers a good balance between backup speed and resource usage. It\'s suitable for most web hosting environments.', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="radio" option="setting" name="backup_params" value="high" <?php esc_attr_e($backup_params_high); ?> />
<span class="wpvivid-element-space-right"><strong>High (Accelerated)</strong></span><span><?php esc_html_e('This mode uses more server resources to reduce backup time, but is only recommended for dedicated servers. If backups time out or get stuck, consider Mid or Low mode. Backups are split into 4GB chunks.', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
<div class="wpvivid-element-space-bottom">
<label>
<input type="radio" option="setting" name="backup_params" value="custom" <?php esc_attr_e($backup_params_custom); ?> />
<span class="wpvivid-element-space-right"><strong>Custom (Advanced)</strong></span><span><?php esc_html_e('This mode allows fine-tuning of backup parameters. Incorrect configuration can lead to backup failures. It is recommended to use only with specific guidance from our support team.', 'wpvivid-backuprestore'); ?></span>
</label>
</div>
<div id="wpvivid_custom_backup_params" style="<?php esc_attr_e($backup_custom_setting_display); ?>">
<div><strong><?php esc_html_e('Compress Files Every', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<input type="text" placeholder="200" option="setting" name="max_file_size" id="wpvivid_max_zip" class="all-options" value="<?php echo esc_attr(str_replace('M', '', $max_file_size)); ?>" onkeyup="value=value.replace(/\D/g,'')" />MB
<div><p><?php esc_html_e( 'Some web hosting providers limit large zip files (e.g. 200MB), and therefore splitting your backup into many parts is an ideal way to avoid hitting the limitation if you are running a big website. Please try to adjust the value if you are encountering backup errors. When you set a value of 0MB, backups will be split every 4GB.', 'wpvivid-backuprestore' ); ?></div></p>
</div>
<div><strong><?php esc_html_e('Exclude the files which are larger than', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<input type="text" placeholder="0" option="setting" name="exclude_file_size" id="wpvivid_ignore_large" class="all-options" value="<?php echo esc_attr($exclude_file_size); ?>" onkeyup="value=value.replace(/\D/g,'')" />MB
<div><p><?php esc_html_e( 'Using the option will ignore the file larger than the certain size in MB when backing up, \'0\' (zero) means unlimited.', 'wpvivid-backuprestore' ); ?></p></div>
</div>
<div><strong><?php esc_html_e('PHP script execution timeout for backup', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<input type="text" placeholder="900" option="setting" name="max_execution_time" id="wpvivid_option_timeout" class="all-options" value="<?php echo esc_attr($max_execution_time); ?>" onkeyup="value=value.replace(/\D/g,'')" /><?php esc_html_e('Seconds', 'wpvivid-backuprestore'); ?>
<div><p><?php esc_html_e( 'The time-out is not your server PHP time-out. With the execution time exhausted, our plugin will shut the process of backup down. If the progress of backup encounters a time-out, that means you have a medium or large sized website, please try to scale the value bigger.', 'wpvivid-backuprestore' ); ?></p></div>
</div>
<div><strong><?php esc_html_e('PHP Memory Limit for backup', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<input type="text" placeholder="256" option="setting" name="memory_limit" class="all-options" value="<?php echo esc_attr(str_replace('M', '', $memory_limit)); ?>" onkeyup="value=value.replace(/\D/g,'')" />MB
<div><p><?php esc_html_e('Adjust this value to apply for a temporary PHP memory limit for WPvivid backup plugin to run a backup. We set this value to 256M by default. Increase the value if you encounter a memory exhausted error. Note: some web hosting providers may not support this.', 'wpvivid-backuprestore'); ?></p></div>
</div>
<div><strong><?php esc_html_e('The number of files compressed to the backup zip each time', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<input type="text" placeholder="500" option="setting" name="compress_file_count" id="wpvivid_compress_file_count" class="all-options" value="<?php echo esc_attr($compress_file_count); ?>" onkeyup="value=value.replace(/\D/g,'')" /><?php esc_html_e('Files', 'wpvivid-backuprestore'); ?>
<div><p><?php esc_html_e( 'When taking a backup, the plugin will compress this number of files to the backup zip each time. The default value is 500. The lower the value, the longer time the backup will take, but the higher the backup success rate. If you encounter a backup timeout issue, try to decrease this value.', 'wpvivid-backuprestore' ); ?></p></div>
</div>
<div><strong><?php esc_html_e('Split a sql file every this size', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<input type="text" placeholder="200" option="setting" name="max_sql_file_size" id="wpvivid_max_sql_file_size" class="all-options" value="<?php echo esc_attr($max_sql_file_size); ?>" onkeyup="value=value.replace(/\D/g,'')" /><?php esc_html_e('MB', 'wpvivid-backuprestore'); ?>
<div><p><?php esc_html_e( 'Some web hosting providers limit large zip files (e.g. 200MB), and therefore splitting your backup into many parts is an ideal way to avoid hitting the limitation if you are running a big website. Please try to adjust the value if you are encountering backup errors. If you use a value of 0 MB, any backup files won\'t be split.', 'wpvivid-backuprestore' ); ?></p></div>
</div>
<div><strong><?php esc_html_e('Chunk Size', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<input type="text" placeholder="2048" option="setting" name="migrate_size" class="all-options" value="<?php echo esc_attr($migrate_size); ?>" onkeyup="value=value.replace(/\D/g,'')" />KB
<div><p><?php esc_html_e('e.g. if you choose a chunk size of 2MB, a 8MB file will use 4 chunks. Decreasing this value will break the ISP\'s transmission limit, for example:512KB', 'wpvivid-backuprestore'); ?></p></div>
</div>
<div>
<strong>Retrying </strong>
<select option="setting" name="max_resume_count">
<?php
for($resume_count=3; $resume_count<10; $resume_count++){
if($resume_count === $wpvivid_max_resume_count){
echo '<option selected="selected" value="'.esc_attr($resume_count).'">'.esc_html($resume_count).'</option>';
}
else{
echo '<option value="'.esc_attr($resume_count).'">'.esc_html($resume_count).'</option>';
}
}
?>
</select>
<strong> times when encountering a time-out error</strong>
</div>
</div>
</div>
</div>
<div class="postbox schedule-tab-block wpvivid-setting-addon" style="margin-bottom: 10px; padding-bottom: 0;">
<div>
<div>
<input type="checkbox" option="setting" name="use_index" style="margin-right: 0px;" <?php echo esc_attr($use_index); ?> />
<strong><?php esc_html_e('Extract files by index for restoration', 'wpvivid-backuprestore'); ?></strong>
</div>
<div><p><?php esc_html_e('Specify the number of files to be extracted per request. The lower the number is, the slower the restoration, but the lower the chance of a timeout error or restore failure.', 'wpvivid-backuprestore'); ?></p></div>
</div>
<div class="setting-tab-block">
<input type="text" placeholder="1000" option="setting" name="unzip_files_pre_request" class="all-options" value="<?php echo esc_attr($unzip_files_pre_request); ?>" onkeyup="value=value.replace(/\D/g,'')" />Files are unzipped every PHP request
</div>
<div><strong><?php esc_html_e('PHP script execution timeout for restore', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<input type="text" placeholder="300" option="setting" name="restore_max_execution_time" class="all-options" value="<?php echo esc_attr($restore_max_execution_time); ?>" onkeyup="value=value.replace(/\D/g,'')" /><?php esc_html_e('Seconds', 'wpvivid-backuprestore'); ?>
<div><p><?php esc_html_e( 'The time-out is not your server PHP time-out. With the execution time exhausted, our plugin will shut the process of restore down. If the progress of restore encounters a time-out, that means you have a medium or large sized website, please try to scale the value bigger.', 'wpvivid-backuprestore' ); ?></p></div>
</div>
<div><strong><?php esc_html_e('PHP Memory Limit for restoration', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<input type="text" placeholder="256" option="setting" name="restore_memory_limit" class="all-options" value="<?php echo esc_attr(str_replace('M', '', $restore_memory_limit)); ?>" onkeyup="value=value.replace(/\D/g,'')" />MB
<div><p><?php esc_html_e('Adjust this value to apply for a temporary PHP memory limit for WPvivid backup plugin in restore process. We set this value to 256M by default. Increase the value if you encounter a memory exhausted error. Note: some web hosting providers may not support this.', 'wpvivid-backuprestore'); ?></p></div>
</div>
<div><strong><?php esc_html_e('Maximum rows of data to be processed per request for restoration', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<input type="text" placeholder="10000" option="setting" name="replace_rows_pre_request" class="all-options" value="<?php echo esc_attr($replace_rows_pre_request); ?>" onkeyup="value=value.replace(/\D/g,'')" />rows
<div><p><?php esc_html_e('The smaller it is, the slower the restoration will be, but the lower the chance of a timeout error.', 'wpvivid-backuprestore'); ?></p></div>
</div>
<div><strong><?php esc_html_e('Maximum size of sql file to be imported per request for restoration', 'wpvivid-backuprestore'); ?></strong></div>
<div class="setting-tab-block">
<input type="text" placeholder="5" option="setting" name="sql_file_buffer_pre_request" class="all-options" value="<?php echo esc_attr($sql_file_buffer_pre_request); ?>" onkeyup="value=value.replace(/\D/g,'')" />MB
<div><p><?php esc_html_e('Maximum rows of data to be processed per request.', 'wpvivid-backuprestore'); ?></p></div>
</div>
</div>
<?php
}
function wpvivid_add_setting_tab_page($setting_array){
$setting_array['general_setting'] = array('index' => '1', 'tab_func' => 'wpvivid_settingpage_add_tab_general', 'page_func' => 'wpvivid_settingpage_add_page_general');
$setting_array['advance_setting'] = array('index' => '2', 'tab_func' => 'wpvivid_settingpage_add_tab_advance', 'page_func' => 'wpvivid_settingpage_add_page_advance');
return $setting_array;
}
function wpvivid_settingpage_add_tab_general(){
?>
<a href="#" id="wpvivid_tab_general_setting" class="nav-tab setting-nav-tab nav-tab-active" onclick="switchsettingTabs(event,'page-general-setting')"><?php esc_html_e('General Settings', 'wpvivid-backuprestore'); ?></a>
<?php
}
function wpvivid_settingpage_add_tab_advance(){
?>
<a href="#" id="wpvivid_tab_advance_setting" class="nav-tab setting-nav-tab" onclick="switchsettingTabs(event,'page-advance-setting')"><?php esc_html_e('Advanced Settings', 'wpvivid-backuprestore'); ?></a>
<?php
}
function wpvivid_settingpage_add_page_general(){
?>
<div class="setting-tab-content wpvivid_tab_general_setting" id="page-general-setting" style="margin-top: 10px;">
<?php do_action('wpvivid_setting_add_general_cell'); ?>
</div>
<?php
}
function wpvivid_settingpage_add_page_advance(){
?>
<div class="setting-tab-content wpvivid_tab_advance_setting" id="page-advance-setting" style="margin-top: 10px; display: none;">
<?php do_action('wpvivid_setting_add_advance_cell'); ?>
</div>
<?php
}
add_filter('wpvivid_add_setting_tab_page', 'wpvivid_add_setting_tab_page', 10);
add_action('wpvivid_setting_add_general_cell','wpvivid_general_settings',10);
add_action('wpvivid_setting_add_advance_cell','wpvivid_advanced_settings',13);
add_action('wpvivid_setting_add_general_cell','wpvivid_email_report',14);
add_action('wpvivid_setting_add_general_cell','wpvivid_clean_junk',15);
add_action('wpvivid_setting_add_general_cell','wpvivid_export_import_settings',16);
?>
admin/partials/wpvivid-schedule-page-display.php 0000644 00000041335 15132770567 0016046 0 ustar 00 <?php
function wpvivid_schedule_settings()
{
?>
<tr>
<td class="row-title wpvivid-backup-settings-table tablelistcolumn"><label for="tablecell"><?php esc_html_e('Schedule Settings', 'wpvivid-backuprestore'); ?></label></td>
<td class="tablelistcolumn">
<div id="storage-brand-3">
<div>
<div>
<div class="postbox schedule-tab-block">
<label for="wpvivid_schedule_enable">
<input option="schedule" name="enable" type="checkbox" id="wpvivid_schedule_enable" />
<span><?php esc_html_e( 'Enable backup schedule', 'wpvivid-backuprestore' ); ?></span>
</label><br>
<label>
<div style="float: left;">
<input type="checkbox" disabled />
<span class="wpvivid-element-space-right" style="color: #ddd;"><?php esc_html_e('Enable Incremental Backup', 'wpvivid-backuprestore'); ?></span>
</div>
<div style="float: left; height: 32px; line-height: 32px;">
<span class="wpvivid-feature-pro">
<a href="https://docs.wpvivid.com/wpvivid-backup-pro-incremental-backups.html"><?php esc_html_e('Pro feature: learn more', 'wpvivid-backuprestore'); ?></a>
</span>
</div>
<div style="clear: both;"></div>
</label>
<label>
<div style="float: left;">
<input type="checkbox" disabled />
<span class="wpvivid-element-space-right" style="color: #ddd;"><?php esc_html_e('Advanced Schedule', 'wpvivid-backuprestore'); ?></span>
</div>
<div style="float: left; height: 32px; line-height: 32px;">
<span class="wpvivid-feature-pro">
<a href="https://docs.wpvivid.com/wpvivid-backup-pro-schedule-overview.html"><?php esc_html_e('Pro feature: learn more', 'wpvivid-backuprestore'); ?></a>
</span>
</div>
<div style="clear: both;"></div>
</label>
<div style="clear: both;"></div>
<div>
<?php
$time = '00:00:00';
$utime = strtotime($time);
echo '<p>1) '.'Scheduled job will start at <strong>UTC</strong> time:'.' '.esc_html(gmdate('H:i:s', $utime)).'</p>';
echo '<p>2) ';
esc_html_e('Being subjected to mechanisms of PHP, a scheduled backup task for your site will be triggered only when the site receives at least a visit at any page.', 'wpvivid-backuprestore');
echo '</p>';
?>
</div>
</div>
<div class="postbox schedule-tab-block">
<fieldset>
<legend class="screen-reader-text"><span>input type="radio"</span></legend>
<?php
$display_array = array("12Hours", "Daily", "Weekly", "Fortnightly", "Monthly");
foreach($display_array as $display)
{
$schedule_check = wpvivid_check_schedule_type($display);
if($schedule_check['result'])
{
echo ' <label><input type="radio" option="schedule" name="recurrence" value="'.esc_attr($schedule_check['type']).'" />';
if($display === '12Hours'){
echo '<span>'.esc_html__('12Hours', 'wpvivid-backuprestore').'</span></label><br>';
}
if($display === 'Daily'){
echo '<span>'.esc_html__('Daily', 'wpvivid-backuprestore').'</span></label><br>';
}
if($display === 'Weekly'){
echo '<span>'.esc_html__('Weekly', 'wpvivid-backuprestore').'</span></label><br>';
}
if($display === 'Fortnightly'){
echo '<span>'.esc_html__('Fortnightly', 'wpvivid-backuprestore').'</span></label><br>';
}
if($display === 'Monthly'){
echo '<span>'.esc_html__('Monthly', 'wpvivid-backuprestore').'</span></label><br>';
}
}
else{
echo '<p>Warning: Unable to set '.esc_html($display).' backup schedule</p>';
}
}
echo '<label>';
echo '<div style="float: left;">';
echo '<input type="radio" disabled />';
echo '<span class="wpvivid-element-space-right" style="color: #ddd;">';esc_html_e('Custom', 'wpvivid-backuprestore');echo '</span>';
echo '</div>';
echo '<div style="float: left; height: 32px; line-height: 32px;">';
echo '<span class="wpvivid-feature-pro">';
echo '<a href="https://docs.wpvivid.com/wpvivid-backup-pro-customize-start-time.html" style="text-decoration: none; margin-top: 10px;">';esc_html_e('Pro feature: learn more', 'wpvivid-backuprestore');echo '</a>';
echo '</span>';
echo '</div>';
echo '</label><br>';
?>
</fieldset>
</div>
</div>
</div>
<div class="postbox schedule-tab-block" id="wpvivid_schedule_backup_type">
<div>
<div>
<fieldset>
<legend class="screen-reader-text"><span>input type="radio"</span></legend>
<?php
echo '<label>';
echo '<input type="radio" option="schedule" name="backup_type" value="files+db"/>';
echo '<span>'.esc_html__('Database + Files (WordPress Files)', 'wpvivid-backuprestore').'</span>';
echo '</label><br>';
echo '<label>';
echo '<input type="radio" option="schedule" name="backup_type" value="files"/>';
echo '<span>'.esc_html__('WordPress Files (Exclude Database)', 'wpvivid-backuprestore').'</span>';
echo '</label><br>';
echo '<label>';
echo '<input type="radio" option="schedule" name="backup_type" value="db"/>';
echo '<span>'.esc_html__('Only Database', 'wpvivid-backuprestore').'</span>';
echo '</label><br>';
echo '<label>';
echo '<div style="float: left;">';
echo '<input type="radio" disabled />';
echo '<span class="wpvivid-element-space-right" style="color: #ddd;">'.esc_html__('Custom', 'wpvivid-backuprestore').'</span>';
echo '</div>';
echo '<div style="float: left; height: 32px; line-height: 32px;">';
echo '<span class="wpvivid-feature-pro">';
echo '<a href="https://docs.wpvivid.com/wpvivid-backup-pro-customize-what-to-backup-for-schedule.html" style="text-decoration: none;">'.esc_html__('Pro feature: learn more', 'wpvivid-backuprestore').'</a>';
echo '</span>';
echo '</div>';
echo '</label><br>';
?>
</fieldset>
</div>
<div style="clear:both;"></div>
</div>
</div>
<div class="postbox schedule-tab-block" id="wpvivid_schedule_remote_storage">
<div id="wpvivid_schedule_backup_local_remote">
<?php
$schedule=WPvivid_Schedule::get_schedule();
$backup_local = 'checked';
$backup_remote = '';
if($schedule['enable'] == true)
{
if($schedule['backup']['remote'] === 1)
{
$backup_local = '';
$backup_remote = 'checked';
}
else{
$backup_local = 'checked';
$backup_remote = '';
}
}
echo '<fieldset>
<label title="">
<input type="radio" option="schedule" name="save_local_remote" value="local" '.esc_attr($backup_local).' />
<span>'.esc_html__( 'Save backups on localhost (web server)', 'wpvivid-backuprestore' ).'</span>
</label><br>
<label title="">
<input type="radio" option="schedule" name="save_local_remote" value="remote" '.esc_attr($backup_remote).' />
<span>'.esc_html__( 'Send backups to remote storage (You can choose whether to keep the backup in localhost after it is uploaded to cloud storage in Settings.)', 'wpvivid-backuprestore' ).'</span>
</label>
<label style="display: none;">
<input type="checkbox" option="schedule" name="lock" value="0" />
</label>
</fieldset>';
?>
</div>
<div id="schedule_upload_storage" style="cursor:pointer;" title="<?php esc_html_e('Highlighted icon illuminates that you have choosed a remote storage to store backups', 'wpvivid-backuprestore'); ?>">
<?php
$remoteslist=WPvivid_Setting::get_all_remote_options();
$default_remote_storage=array();
foreach ($remoteslist['remote_selected'] as $value) {
$default_remote_storage[]=$value;
}
$remote_storage_type=array();
foreach ($remoteslist as $key=>$value)
{
if(in_array($key, $default_remote_storage))
{
$remote_storage_type[]=$value['type'];
}
}
$remote=array();
$remote=apply_filters('wpvivid_remote_pic', $remote);
if(is_array($remote))
{
foreach ($remote as $key => $value) {
$title = $value['title'];
if (in_array($key, $remote_storage_type)) {
$pic = $value['selected_pic'];
} else {
$pic = $value['default_pic'];
}
$url = apply_filters('wpvivid_get_wpvivid_pro_url', WPVIVID_PLUGIN_URL, $key);
echo '<img src="' . esc_url($url . $pic) . '" style="vertical-align:middle; " title="' . esc_attr($title) . '"/>';
}
echo '<img onclick="wpvivid_click_switch_page(\'wrap\', \'wpvivid_tab_remote_storage\', true);" src="'.esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/add-storages.png').'" style="vertical-align:middle;" title="'.esc_attr__('Add a storage', 'wpvivid-backuprestore').'"/>';
}
?>
</div>
</div>
<div class="postbox schedule-tab-block">
<div style="float:left; color: #ddd; margin-right: 10px;">
<?php esc_html_e('+ Add another schedule', 'wpvivid-backuprestore'); ?>
</div>
<span class="wpvivid-feature-pro">
<a href="https://docs.wpvivid.com/wpvivid-backup-pro-creating-schedules.html"><?php esc_html_e('Pro feature: learn more', 'wpvivid-backuprestore'); ?></a>
</span>
</div>
</div>
</td>
</tr>
<script>
<?php
do_action('wpvivid_schedule_do_js');
?>
</script>
<?php
}
function wpvivid_check_schedule_type($display)
{
$schedule_type = array(
'wpvivid_12hours' => '12Hours',
'twicedaily' => '12Hours',
'wpvivid_daily' => 'Daily',
'daily' => 'Daily',
'onceday' => 'Daily',
'wpvivid_weekly' => 'Weekly',
'weekly' => 'Weekly',
'wpvivid_fortnightly' => 'Fortnightly',
'fortnightly' => 'Fortnightly',
'wpvivid_monthly' => 'Monthly',
'monthly' => 'Monthly',
'montly' => 'Monthly'
);
$schedules = wp_get_schedules();
$check_res = false;
$ret = array();
foreach ($schedule_type as $key => $value){
if($value == $display){
if(isset($schedules[$key])){
$check_res = true;
$ret['type']=$key;
break;
}
}
}
$ret['result']=$check_res;
return $ret;
}
function wpvivid_schedule_do_js()
{
$schedule=WPvivid_Schedule::get_schedule();
if($schedule['enable'] == true)
{
?>
jQuery("#wpvivid_schedule_enable").prop('checked', true);
<?php
if($schedule['backup']['remote'] === 1)
{
$schedule_remote='remote';
}
else{
$schedule_remote='local';
}
}
else{
$schedule['recurrence']='wpvivid_daily';
$schedule['backup']['backup_files']='files+db';
$schedule_remote='local';
}
?>
jQuery("input:radio[value='<?php echo esc_attr($schedule['recurrence'])?>']").prop('checked', true);
jQuery("input:radio[value='<?php echo esc_attr($schedule['backup']['backup_files'])?>']").prop('checked', true);
jQuery("input:radio[name='save_local_remote'][value='remote']").click(function()
{
<?php
$remote_id_array = WPvivid_Setting::get_user_history('remote_selected');
$remote_id = '';
foreach ($remote_id_array as $value)
{
$remote_id = $value;
}
if(empty($remote_id))
{
?>
alert("<?php esc_html_e('There is no default remote storage configured. Please set it up first.', 'wpvivid-backuprestore'); ?>");
jQuery("input:radio[name='save_local_remote'][value='local']").prop('checked', true);
<?php
}
?>
});
<?php
}
add_action('wpvivid_schedule_add_cell','wpvivid_schedule_settings',11);
add_action('wpvivid_schedule_do_js','wpvivid_schedule_do_js',10);
?>
admin/partials/wpvivid-remote-storage-page-display.php 0000644 00000051245 15132770567 0017210 0 ustar 00 <?php
function wpvivid_add_tab_storage_list()
{
?>
<a href="#" id="wpvivid_tab_storage_list" class="nav-tab storage-nav-tab nav-tab-active" onclick="switchstorageTabs(event,'page-storage-list','page-storage-list')"><?php esc_html_e('Storages', 'wpvivid-backuprestore'); ?></a>
<?php
}
function wpvivid_add_tab_storage_edit()
{
?>
<a href="#" id="wpvivid_tab_storage_edit" class="nav-tab storage-nav-tab delete" onclick="switchstorageTabs(event,'page-storage_edit','page-storage_edit')" style="display: none;">
<div id="wpvivid_tab_storage_edit_text" style="margin-right: 15px;"><?php esc_html_e('Storage Edit', 'wpvivid-backuprestore'); ?></div>
<div class="nav-tab-delete-img">
<img src="<?php echo esc_url(plugins_url( 'images/delete-tab.png', __FILE__ )); ?>" style="vertical-align:middle; cursor:pointer;" onclick="wpvivid_close_tab(event, 'wpvivid_tab_storage_edit', 'storage', 'wpvivid_tab_storage_list');" />
</div>
</a>
<?php
}
function wpvivid_add_page_storage_list()
{
?>
<div class="storage-tab-content wpvivid_tab_storage_list" id="page-storage-list">
<div style="margin-top:10px;"><p><strong><?php esc_html_e('Please choose one storage to save your backups (remote storage)', 'wpvivid-backuprestore'); ?></strong></p></div>
<div class="schedule-tab-block"></div>
<div class="">
<table class="widefat">
<thead>
<tr>
<th></th>
<th></th>
<th><?php esc_html_e( 'Storage Provider', 'wpvivid-backuprestore' ); ?></th>
<th class="row-title"><?php esc_html_e( 'Remote Storage Alias', 'wpvivid-backuprestore' ); ?></th>
<th><?php esc_html_e( 'Actions', 'wpvivid-backuprestore' ); ?></th>
</tr>
</thead>
<tbody class="wpvivid-remote-storage-list" id="wpvivid_remote_storage_list">
<?php
$remoteslist=WPvivid_Setting::get_all_remote_options();
$default_remote_storage='';
foreach ($remoteslist['remote_selected'] as $value) {
$default_remote_storage=$value;
}
$i=1;
foreach ($remoteslist as $key=>$value)
{
if($key === 'remote_selected')
{
continue;
}
if ($key === $default_remote_storage)
{
$check_status = 'checked';
}
else
{
$check_status='';
}
$storage_type = $value['type'];
$storage_type=apply_filters('wpvivid_storage_provider_tran', $storage_type);
echo '<tr>
<td>'.esc_html($i++).'</td>
<td><input type="checkbox" name="remote_storage" value="'.esc_attr($key).'" '.esc_attr($check_status).' /></td>
<td>'.esc_html($storage_type).'</td>
<td class="row-title"><label for="tablecell">'.esc_html($value['name']).'</label></td>
<td>
<div style="float: left;"><img src="'.esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/Edit.png').'" onclick="click_retrieve_remote_storage(\''.esc_attr($key).'\',\''.esc_attr($value['type']).'\',\''.esc_attr($value['name']).'\'
);" style="vertical-align:middle; cursor:pointer;" title="'. esc_html__('Edit the remote storage', 'wpvivid-backuprestore') .'"/></div>
<div><img src="'.esc_url(WPVIVID_PLUGIN_URL.'/admin/partials/images/Delete.png').'" onclick="wpvivid_delete_remote_storage(\''.esc_attr($key).'\'
);" style="vertical-align:middle; cursor:pointer;" title="'. esc_html__('Remove the remote storage', 'wpvivid-backuprestore') .'"/></div>
</td>
</tr>';
}
?>
</tbody>
<tfoot>
<tr>
<th colspan="5" class="row-title"><input class="button-primary" id="wpvivid_set_default_remote_storage" type="submit" name="choose-remote-storage" value="<?php esc_attr_e( 'Save Changes', 'wpvivid-backuprestore' ); ?>" /></th>
</tr>
</tfoot>
</table>
</div>
</div>
<script>
jQuery('input[option=add-remote]').click(function(){
var storage_type = jQuery(".storage-providers-active").attr("remote_type");
wpvivid_add_remote_storage(storage_type);
wpvivid_settings_changed = false;
});
jQuery('#wpvivid_set_default_remote_storage').click(function(){
wpvivid_set_default_remote_storage();
wpvivid_settings_changed = false;
});
/**
* Add remote storages to the list
*
* @param action - The action to add or test a remote storage
* @param storage_type - Remote storage types (Amazon S3, SFTP and FTP server)
*/
function wpvivid_add_remote_storage(storage_type)
{
var remote_from = wpvivid_ajax_data_transfer(storage_type);
var ajax_data;
ajax_data = {
'action': 'wpvivid_add_remote',
'remote': remote_from,
'type': storage_type
};
jQuery('input[option=add-remote]').css({'pointer-events': 'none', 'opacity': '0.4'});
jQuery('#wpvivid_remote_notice').html('');
wpvivid_post_request(ajax_data, function (data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
jQuery('input[option=add-remote]').css({'pointer-events': 'auto', 'opacity': '1'});
jQuery('input:text[option='+storage_type+']').each(function(){
jQuery(this).val('');
});
jQuery('input:password[option='+storage_type+']').each(function(){
jQuery(this).val('');
});
wpvivid_handle_remote_storage_data(data);
}
else if (jsonarray.result === 'failed')
{
jQuery('#wpvivid_remote_notice').html(jsonarray.notice);
jQuery('input[option=add-remote]').css({'pointer-events': 'auto', 'opacity': '1'});
}
}
catch (err)
{
alert(err);
jQuery('input[option=add-remote]').css({'pointer-events': 'auto', 'opacity': '1'});
}
}, function (XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('adding the remote storage', textStatus, errorThrown);
alert(error_message);
jQuery('input[option=add-remote]').css({'pointer-events': 'auto', 'opacity': '1'});
});
}
function wpvivid_edit_remote_storage() {
var data_tran = 'edit-'+wpvivid_editing_storage_type;
var remote_data = wpvivid_ajax_data_transfer(data_tran);
var ajax_data;
ajax_data = {
'action': 'wpvivid_edit_remote',
'remote': remote_data,
'id': wpvivid_editing_storage_id,
'type': wpvivid_editing_storage_type
};
jQuery('#wpvivid_remote_notice').html('');
wpvivid_post_request(ajax_data, function(data){
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
jQuery('#wpvivid_tab_storage_edit').hide();
wpvivid_click_switch_page('storage', 'wpvivid_tab_storage_list', true);
wpvivid_handle_remote_storage_data(data);
}
else if (jsonarray.result === 'failed') {
jQuery('#wpvivid_remote_notice').html(jsonarray.notice);
}
}
catch(err){
alert(err);
}
},function(XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('editing the remote storage', textStatus, errorThrown);
alert(error_message);
});
}
/**
* Set a default remote storage for backups.
*/
function wpvivid_set_default_remote_storage(){
var remote_storage = new Array();
//remote_storage[0] = jQuery("input[name='remote_storage']:checked").val();
jQuery.each(jQuery("input[name='remote_storage']:checked"), function()
{
remote_storage.push(jQuery(this).val());
});
var ajax_data = {
'action': 'wpvivid_set_default_remote_storage',
'remote_storage': remote_storage
};
jQuery('#wpvivid_remote_notice').html('');
wpvivid_post_request(ajax_data, function(data){
wpvivid_handle_remote_storage_data(data);
}, function(XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('setting up the default remote storage', textStatus, errorThrown);
alert(error_message);
});
}
jQuery('#wpvivid_remote_storage_list').on("click", "input", function(){
var check_status = true;
if(jQuery(this).prop('checked') === true){
check_status = true;
}
else {
check_status = false;
}
jQuery('input[name="remote_storage"]').prop('checked', false);
if(check_status === true){
jQuery(this).prop('checked', true);
}
else {
jQuery(this).prop('checked', false);
}
});
function wpvivid_delete_remote_storage(storage_id){
var descript = '<?php esc_html_e('Deleting a remote storage will make it unavailable until it is added again. Are you sure to continue?', 'wpvivid-backuprestore'); ?>';
var ret = confirm(descript);
if(ret === true){
var ajax_data = {
'action': 'wpvivid_delete_remote',
'remote_id': storage_id
};
wpvivid_post_request(ajax_data, function(data){
wpvivid_handle_remote_storage_data(data);
},function(XMLHttpRequest, textStatus, errorThrown) {
var error_message = wpvivid_output_ajaxerror('deleting the remote storage', textStatus, errorThrown);
alert(error_message);
});
}
}
function wpvivid_handle_remote_storage_data(data){
var i = 0;
try {
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success') {
jQuery('#wpvivid_remote_storage_list').html('');
jQuery('#wpvivid_remote_storage_list').append(jsonarray.html);
jQuery('#upload_storage').html(jsonarray.pic);
jQuery('#schedule_upload_storage').html(jsonarray.pic);
jQuery('#wpvivid_out_of_date_remote_path').html(jsonarray.dir);
jQuery('#wpvivid_schedule_backup_local_remote').html(jsonarray.local_remote);
wpvivid_control_remote_storage(jsonarray.remote_storage);
jQuery('#wpvivid_remote_notice').html(jsonarray.notice);
}
else if(jsonarray.result === 'failed'){
alert(jsonarray.error);
}
}
catch(err){
alert(err);
}
}
function wpvivid_control_remote_storage(has_remote){
if(!has_remote){
if(jQuery("input:radio[name='save_local_remote'][value='remote']").prop('checked')) {
alert("<?php esc_html_e('There is no default remote storage configured. Please set it up first.', 'wpvivid-backuprestore'); ?>");
jQuery("input:radio[name='save_local_remote'][value='local']").prop('checked', true);
}
}
}
function click_retrieve_remote_storage(id,type,name)
{
wpvivid_editing_storage_id = id;
jQuery('.remote-storage-edit').hide();
jQuery('#wpvivid_tab_storage_edit').show();
jQuery('#wpvivid_tab_storage_edit_text').html(name);
wpvivid_editing_storage_type=type;
jQuery('#remote_storage_edit_'+wpvivid_editing_storage_type).fadeIn();
wpvivid_click_switch_page('storage', 'wpvivid_tab_storage_edit', true);
var ajax_data = {
'action': 'wpvivid_retrieve_remote',
'remote_id': id
};
wpvivid_post_request(ajax_data, function(data)
{
try
{
var jsonarray = jQuery.parseJSON(data);
if (jsonarray.result === 'success')
{
/*jQuery('input:text[option=edit-'+jsonarray.type+']').each(function(){
var key = jQuery(this).prop('name');
jQuery(this).val(jsonarray[key]);
});
jQuery('input:password[option=edit-'+jsonarray.type+']').each(function(){
var key = jQuery(this).prop('name');
jQuery(this).val(jsonarray[key]);
});*/
jQuery('input:checkbox[option=edit-'+jsonarray.type+']').each(function() {
var key = jQuery(this).prop('name');
var value;
if(jsonarray[key] == '0'){
value = false;
}
else{
value = true;
}
jQuery(this).prop('checked', value);
});
}
else
{
alert(jsonarray.error);
}
}
catch(err)
{
alert(err);
}
},function(XMLHttpRequest, textStatus, errorThrown)
{
var error_message = wpvivid_output_ajaxerror('retrieving the remote storage', textStatus, errorThrown);
alert(error_message);
});
}
</script>
<?php
}
function wpvivid_add_page_storage_edit()
{
?>
<div class="storage-tab-content wpvivid_tab_storage_edit" id="page-storage_edit" style="display:none;">
<div><?php do_action('wpvivid_edit_remote_page'); ?></div>
</div>
<script>
jQuery('input[option=edit-remote]').click(function(){
wpvivid_edit_remote_storage();
});
</script>
<?php
}
function wpvivid_storage_list($html)
{
$html='<h2 class="nav-tab-wrapper" style="padding-bottom:0!important;">';
$html.='<a href="#" id="wpvivid_tab_storage_list" class="nav-tab storage-nav-tab nav-tab-active" onclick="switchstorageTabs(event,\'page-storage-list\',\'page-storage-list\')">'. __('Storages', 'wpvivid-backuprestore').'</a>';
$html.='<a href="#" id="wpvivid_tab_storage_edit" class="nav-tab storage-nav-tab delete" onclick="switchstorageTabs(event,\'page-storage_edit\',\'page-storage_edit\')" style="display: none;">
<div id="wpvivid_tab_storage_edit_text" style="margin-right: 15px;">'.__('Storage Edit', 'wpvivid-backuprestore').'</div>
<div class="nav-tab-delete-img">
<img src="'.esc_url(plugins_url( 'images/delete-tab.png', __FILE__ )).'" style="vertical-align:middle; cursor:pointer;" onclick="wpvivid_close_tab(event, \'wpvivid_tab_storage_edit\', \'storage\', \'wpvivid_tab_storage_list\');" />
</div>
</a>';
$html.='</h2>';
$html.='<div class="storage-tab-content wpvivid_tab_storage_list" id="page-storage-list">
<div style="margin-top:10px;"><p><strong>'.__('Please choose one storage to save your backups (remote storage)', 'wpvivid-backuprestore').'</strong></p></div>
<div class="schedule-tab-block"></div>
<div class="">
<table class="widefat">
<thead>
<tr>
<th></th>
<th></th>
<th>'. __( 'Storage Provider', 'wpvivid-backuprestore' ).'</th>
<th class="row-title">'. __( 'Remote Storage Alias', 'wpvivid-backuprestore' ).'</th>
<th>'. __( 'Actions', 'wpvivid-backuprestore' ).'</th>
</tr>
</thead>
<tbody class="wpvivid-remote-storage-list" id="wpvivid_remote_storage_list">
';
$html_list='';
$html.= apply_filters('wpvivid_add_remote_storage_list', $html_list);
$html.='</tbody><tfoot><tr>
<th colspan="5" class="row-title"><input class="button-primary" id="wpvivid_set_default_remote_storage" type="submit" name="choose-remote-storage" value="'.esc_attr__( 'Save Changes', 'wpvivid-backuprestore' ).'" /></th>
</tr></tfoot></table></div></div>';
$html .= '<script>
jQuery(\'#wpvivid_remote_storage_list\').on("click", "input", function(){
var check_status = true;
if(jQuery(this).prop(\'checked\') === true){
check_status = true;
}
else {
check_status = false;
}
jQuery(\'input[name = "remote_storage"]\').prop(\'checked\', false);
if(check_status === true){
jQuery(this).prop(\'checked\', true);
}
else {
jQuery(this).prop(\'checked\', false);
}
});
</script>';
return $html;
}
add_action('wpvivid_storage_add_tab', 'wpvivid_add_tab_storage_list', 10);
add_action('wpvivid_storage_add_tab', 'wpvivid_add_tab_storage_edit', 11);
add_action('wpvivid_storage_add_page', 'wpvivid_add_page_storage_list', 10);
add_action('wpvivid_storage_add_page', 'wpvivid_add_page_storage_edit', 11);
//add_filter('wpvivid_storage_list','wpvivid_storage_list',10);
?>
<script>
function select_remote_storage(evt, storage_page_id)
{
var i, tablecontent, tablinks;
tablinks = document.getElementsByClassName("storage-providers");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace("storage-providers-active", "");
}
evt.currentTarget.className += " storage-providers-active";
jQuery(".storage-account-page").hide();
jQuery("#"+storage_page_id).show();
}
function switchstorageTabs(evt,contentName,storage_page_id) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="table-list-content" and hide them
tabcontent = document.getElementsByClassName("storage-tab-content");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="table-nav-tab" and remove the class "nav-tab-active"
tablinks = document.getElementsByClassName("storage-nav-tab");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" nav-tab-active", "");
}
// Show the current tab, and add an "storage-menu-active" class to the button that opened the tab
document.getElementById(contentName).style.display = "block";
evt.currentTarget.className += " nav-tab-active";
var top = jQuery('#'+storage_page_id).offset().top-jQuery('#'+storage_page_id).height();
jQuery('html, body').animate({scrollTop:top}, 'slow');
}
</script>