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() { ?>

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(); ?>
 

input type="radio"
'regular-text', 'show_option_all' => __('All Categories', 'wpvivid-backuprestore') ) ); ?>
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', ) ); ?>
Enter a ID.(optional)
Enter a title.(optional)

*
_wpvivid-5dbf8d6a5f133_2019-11-08-03-15_export_.zip
$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(); ?>

Export post type:

Selected post(s):

.column-file_name { width:25% } .column-export_type { width:8% } .column-posts_count { width:8% } .column-media_size { width:8% } .column-import { width:8% } '; } 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 ''; } } 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']='
'; $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 = '
The export task is completed and the automatic download starts. If the automatic download didn\'t run, please click here to download.
'; $msg .= '
The count of exported '.$post_type.': '.$task['data']['export']['export_info']['post_count'].'.
'; $msg .= '
File name: '.$file_name.'.
'; $msg .= '
File size: '.size_format($file_size, 2).'.
'; $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']='

'.__('Export error:', 'wpvivid-backuprestore').' '.$task['status']['error'].'

'; $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 ''; esc_html_e('File size not match. please retry again.', 'wpvivid-backuprestore'); echo ''; die(); } } $admin_url = admin_url(); echo ''; esc_html_e('File not found. Please retry again.', 'wpvivid-backuprestore'); echo ''; 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()); ?>


'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' ); ?> 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')); $file_name=basename(sanitize_text_field($_POST['name'])); $validate = wp_check_filetype( $file_name ); if ( $validate['type'] == false ) { echo wp_json_encode(array('result'=>WPVIVID_FAILED, 'error' => 'File type is not allowed.')); die(); } $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; } 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; } } }