Beispiel #1
0
 /**
  * Display a List of Jobs
  *
  * @synopsis jobs
  */
 public function jobs($args, $assoc_args)
 {
     $jobids = BackWPup_Option::get_job_ids();
     WP_CLI::line(__('List of jobs', 'backwpup'));
     WP_CLI::line('----------------------------------------------------------------------');
     foreach ($jobids as $jobid) {
         WP_CLI::line(sprintf(__('ID: %1$d Name: %2$s', 'backwpup'), $jobid, BackWPup_Option::get($jobid, 'name')));
     }
 }
Beispiel #2
0
 /**
  * Display a List of Jobs
  *
  */
 public function jobs($args, $assoc_args)
 {
     $formatter_args = array('format' => 'table', 'fields' => array('Job ID', 'Name'), 'field' => NULL);
     $items = array();
     $formatter = new WP_CLI\Formatter($formatter_args);
     $jobids = BackWPup_Option::get_job_ids();
     foreach ($jobids as $jobid) {
         $items[] = array('Job ID' => $jobid, 'Name' => BackWPup_Option::get($jobid, 'name'));
     }
     $formatter->display_items($items);
 }
 /**
  * @global $wp_admin_bar WP_Admin_Bar
  */
 public function adminbar()
 {
     global $wp_admin_bar;
     /* @var WP_Admin_Bar $wp_admin_bar */
     $menu_title = '<span class="ab-icon"></span><span class="ab-label">' . BackWPup::get_plugin_data('name') . '</span>';
     $menu_herf = network_admin_url('admin.php') . '?page=backwpup';
     if (file_exists(BackWPup::get_plugin_data('running_file')) && current_user_can('backwpup_jobs_start')) {
         $menu_title = '<span class="ab-icon"></span><span class="ab-label">' . BackWPup::get_plugin_data('name') . ' <span id="backwpup-adminbar-running">' . __('running', 'backwpup') . '</span></span>';
         $menu_herf = network_admin_url('admin.php') . '?page=backwpupjobs';
     }
     if (current_user_can('backwpup')) {
         $wp_admin_bar->add_menu(array('id' => 'backwpup', 'title' => $menu_title, 'href' => $menu_herf, 'meta' => array('title' => BackWPup::get_plugin_data('name'))));
     }
     if (file_exists(BackWPup::get_plugin_data('running_file')) && current_user_can('backwpup_jobs_start')) {
         $wp_admin_bar->add_menu(array('id' => 'backwpup_working', 'parent' => 'backwpup_jobs', 'title' => __('Now Running', 'backwpup'), 'href' => network_admin_url('admin.php') . '?page=backwpupjobs'));
         $wp_admin_bar->add_menu(array('id' => 'backwpup_working_abort', 'parent' => 'backwpup_working', 'title' => __('Abort!', 'backwpup'), 'href' => wp_nonce_url(network_admin_url('admin.php') . '?page=backwpup&action=abort', 'abort-job')));
     }
     if (current_user_can('backwpup_jobs')) {
         $wp_admin_bar->add_menu(array('id' => 'backwpup_jobs', 'parent' => 'backwpup', 'title' => __('Jobs', 'backwpup'), 'href' => network_admin_url('admin.php') . '?page=backwpupjobs'));
     }
     if (current_user_can('backwpup_jobs_edit')) {
         $wp_admin_bar->add_menu(array('id' => 'backwpup_jobs_new', 'parent' => 'backwpup_jobs', 'title' => __('Add new', 'backwpup'), 'href' => network_admin_url('admin.php') . '?page=backwpupeditjob&tab=job'));
     }
     if (current_user_can('backwpup_logs')) {
         $wp_admin_bar->add_menu(array('id' => 'backwpup_logs', 'parent' => 'backwpup', 'title' => __('Logs', 'backwpup'), 'href' => network_admin_url('admin.php') . '?page=backwpuplogs'));
     }
     if (current_user_can('backwpup_backups')) {
         $wp_admin_bar->add_menu(array('id' => 'backwpup_backups', 'parent' => 'backwpup', 'title' => __('Backups', 'backwpup'), 'href' => network_admin_url('admin.php') . '?page=backwpupbackups'));
     }
     //add jobs
     $jobs = (array) BackWPup_Option::get_job_ids();
     foreach ($jobs as $jobid) {
         if (current_user_can('backwpup_jobs_edit')) {
             $name = BackWPup_Option::get($jobid, 'name');
             $wp_admin_bar->add_menu(array('id' => 'backwpup_jobs_' . $jobid, 'parent' => 'backwpup_jobs', 'title' => $name, 'href' => wp_nonce_url(network_admin_url('admin.php') . '?page=backwpupeditjob&tab=job&jobid=' . $jobid, 'edit-job')));
         }
         if (current_user_can('backwpup_jobs_start')) {
             $url = BackWPup_Job::get_jobrun_url('runnowlink', $jobid);
             $wp_admin_bar->add_menu(array('id' => 'backwpup_jobs_runnow_' . $jobid, 'parent' => 'backwpup_jobs_' . $jobid, 'title' => __('Run Now', 'backwpup'), 'href' => $url['url']));
         }
     }
 }
 /**
  * Save settings form data
  */
 public static function save_post_form()
 {
     if (!current_user_can('backwpup_settings')) {
         return;
     }
     //set default options if button clicked
     if (isset($_POST['default_settings']) && $_POST['default_settings']) {
         delete_site_option('backwpup_cfg_showadminbar');
         delete_site_option('backwpup_cfg_showfoldersize');
         delete_site_option('backwpup_cfg_jobstepretry');
         delete_site_option('backwpup_cfg_jobmaxexecutiontime');
         delete_site_option('backwpup_cfg_jobziparchivemethod');
         delete_site_option('backwpup_cfg_loglevel');
         delete_site_option('backwpup_cfg_jobwaittimems');
         delete_site_option('backwpup_cfg_jobrunauthkey');
         delete_site_option('backwpup_cfg_jobdooutput');
         delete_site_option('backwpup_cfg_maxlogs');
         delete_site_option('backwpup_cfg_gzlogs');
         delete_site_option('backwpup_cfg_protectfolders');
         delete_site_option('backwpup_cfg_authentication');
         delete_site_option('backwpup_cfg_logfolder');
         delete_site_option('backwpup_cfg_dropboxappkey');
         delete_site_option('backwpup_cfg_dropboxappsecret');
         delete_site_option('backwpup_cfg_dropboxsandboxappkey');
         delete_site_option('backwpup_cfg_dropboxsandboxappsecret');
         delete_site_option('backwpup_cfg_sugarsynckey');
         delete_site_option('backwpup_cfg_sugarsyncsecret');
         delete_site_option('backwpup_cfg_sugarsyncappid');
         BackWPup_Option::default_site_options();
         BackWPup_Admin::message(__('Settings reset to default', 'backwpup'));
         return;
     }
     update_site_option('backwpup_cfg_showadminbar', isset($_POST['showadminbar']) ? 1 : 0);
     update_site_option('backwpup_cfg_showfoldersize', isset($_POST['showfoldersize']) ? 1 : 0);
     if (100 > $_POST['jobstepretry'] && 0 < $_POST['jobstepretry']) {
         $_POST['jobstepretry'] = abs((int) $_POST['jobstepretry']);
     }
     if (empty($_POST['jobstepretry']) or !is_int($_POST['jobstepretry'])) {
         $_POST['jobstepretry'] = 3;
     }
     update_site_option('backwpup_cfg_jobstepretry', $_POST['jobstepretry']);
     $max_exe_time = abs((int) $_POST['jobmaxexecutiontime']);
     if (!is_int($max_exe_time) || $max_exe_time < 0) {
         $max_exe_time = 0;
     } elseif ($max_exe_time > 300) {
         $max_exe_time = 300;
     }
     update_site_option('backwpup_cfg_jobmaxexecutiontime', $max_exe_time);
     update_site_option('backwpup_cfg_jobziparchivemethod', $_POST['jobziparchivemethod'] == '' || $_POST['jobziparchivemethod'] == 'PclZip' || $_POST['jobziparchivemethod'] == 'ZipArchive' ? $_POST['jobziparchivemethod'] : '');
     update_site_option('backwpup_cfg_loglevel', in_array($_POST['loglevel'], array('normal_translated', 'normal', 'debug_translated', 'debug')) ? $_POST['loglevel'] : 'normal_translated');
     update_site_option('backwpup_cfg_jobwaittimems', $_POST['jobwaittimems']);
     update_site_option('backwpup_cfg_jobdooutput', isset($_POST['jobdooutput']) ? 1 : 0);
     update_site_option('backwpup_cfg_maxlogs', abs((int) $_POST['maxlogs']));
     update_site_option('backwpup_cfg_gzlogs', isset($_POST['gzlogs']) ? 1 : 0);
     update_site_option('backwpup_cfg_protectfolders', isset($_POST['protectfolders']) ? 1 : 0);
     $_POST['jobrunauthkey'] = preg_replace('/[^a-zA-Z0-9]/', '', trim($_POST['jobrunauthkey']));
     update_site_option('backwpup_cfg_jobrunauthkey', $_POST['jobrunauthkey']);
     $_POST['logfolder'] = trailingslashit(str_replace('\\', '/', trim(stripslashes($_POST['logfolder']))));
     //set def. folders
     if (empty($_POST['logfolder']) || $_POST['logfolder'] === '/') {
         delete_site_option('backwpup_cfg_logfolder');
         BackWPup_Option::default_site_options();
     } else {
         update_site_option('backwpup_cfg_logfolder', $_POST['logfolder']);
     }
     $authentication = get_site_option('backwpup_cfg_authentication', array('method' => '', 'basic_user' => '', 'basic_password' => '', 'user_id' => 0, 'query_arg' => ''));
     $authentication['method'] = in_array($_POST['authentication_method'], array('user', 'basic', 'query_arg')) ? $_POST['authentication_method'] : '';
     $authentication['basic_user'] = $_POST['authentication_basic_user'];
     $authentication['basic_password'] = BackWPup_Encryption::encrypt($_POST['authentication_basic_password']);
     $authentication['query_arg'] = $_POST['authentication_query_arg'];
     $authentication['user_id'] = (int) $_POST['authentication_user_id'];
     update_site_option('backwpup_cfg_authentication', $authentication);
     delete_site_transient('backwpup_cookies');
     do_action('backwpup_page_settings_save');
     BackWPup_Admin::message(__('Settings saved', 'backwpup'));
 }
 /**
  * @param $job_object
  * @return bool
  */
 public function job_run_archive(&$job_object)
 {
     $job_object->substeps_todo = 2 + $job_object->backup_filesize;
     $job_object->log(sprintf(__('%d. Trying to send backup file to S3 Service&#160;&hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']), E_USER_NOTICE);
     try {
         $s3 = new AmazonS3(array('key' => $job_object->job['s3accesskey'], 'secret' => BackWPup_Encryption::decrypt($job_object->job['s3secretkey']), 'certificate_authority' => TRUE));
         $base_url = $this->get_s3_base_url($job_object->job['s3region'], $job_object->job['s3base_url']);
         if (stristr($base_url, 'amazonaws.com')) {
             $s3->set_region(str_replace(array('http://', 'https://'), '', $base_url));
         } else {
             $s3->set_hostname(str_replace(array('http://', 'https://'), '', $base_url));
             $s3->allow_hostname_override(FALSE);
             if (substr($base_url, -1) == '/') {
                 $s3->enable_path_style(TRUE);
             }
         }
         if (stristr($base_url, 'http://')) {
             $s3->disable_ssl();
         }
         if ($s3->if_bucket_exists($job_object->job['s3bucket'])) {
             $job_object->log(sprintf(__('Connected to S3 Bucket "%1$s" in %2$s', 'backwpup'), $job_object->job['s3bucket'], $base_url), E_USER_NOTICE);
         } else {
             $job_object->log(sprintf(__('S3 Bucket "%s" does not exist!', 'backwpup'), $job_object->job['s3bucket']), E_USER_ERROR);
             return TRUE;
         }
         //transfer file to S3
         $job_object->log(__('Starting upload to S3 Service&#160;&hellip;', 'backwpup'), E_USER_NOTICE);
         //Transfer Backup to S3
         if ($job_object->job['s3storageclass'] == 'REDUCED_REDUNDANCY') {
             //set reduced redundancy or not
             $storage = AmazonS3::STORAGE_REDUCED;
         } else {
             $storage = AmazonS3::STORAGE_STANDARD;
         }
         if (empty($job_object->job['s3ssencrypt'])) {
             $job_object->job['s3ssencrypt'] = NULL;
         }
         //set progress bar
         $s3->register_streaming_read_callback(array($job_object, 'curl_read_callback'));
         $result = $s3->create_object($job_object->job['s3bucket'], $job_object->job['s3dir'] . $job_object->backup_file, array('fileUpload' => $job_object->backup_folder . $job_object->backup_file, 'acl' => AmazonS3::ACL_PRIVATE, 'storage' => $storage, 'encryption' => $job_object->job['s3ssencrypt']));
         if ($result->status >= 200 and $result->status < 300) {
             $job_object->substeps_done = 1 + $job_object->backup_filesize;
             $job_object->log(sprintf(__('Backup transferred to %s.', 'backwpup'), $this->get_s3_base_url($job_object->job['s3region'], $job_object->job['s3base_url']) . '/' . $job_object->job['s3bucket'] . '/' . $job_object->job['s3dir'] . $job_object->backup_file), E_USER_NOTICE);
             if (!empty($job_object->job['jobid'])) {
                 BackWPup_Option::update($job_object->job['jobid'], 'lastbackupdownloadurl', network_admin_url('admin.php') . '?page=backwpupbackups&action=downloads3&file=' . $job_object->job['s3dir'] . $job_object->backup_file . '&jobid=' . $job_object->job['jobid']);
             }
         } else {
             $job_object->log(sprintf(__('Cannot transfer backup to S3! (%1$d) %2$s', 'backwpup'), $result->status, $result->body), E_USER_ERROR);
         }
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('S3 Service API: %s', 'backwpup'), htmlentities($e->getMessage())), $e->getFile(), $e->getLine());
         return FALSE;
     }
     try {
         $backupfilelist = array();
         $filecounter = 0;
         $files = array();
         $objects = $s3->list_objects($job_object->job['s3bucket'], array('prefix' => $job_object->job['s3dir']));
         if (is_object($objects)) {
             foreach ($objects->body->Contents as $object) {
                 $file = basename((string) $object->Key);
                 $changetime = strtotime((string) $object->LastModified) + get_option('gmt_offset') * 3600;
                 if ($job_object->is_backup_archive($file)) {
                     $backupfilelist[$changetime] = $file;
                 }
                 $files[$filecounter]['folder'] = $this->get_s3_base_url($job_object->job['s3region'], $job_object->job['s3base_url']) . '/' . $job_object->job['s3bucket'] . '/' . dirname((string) $object->Key);
                 $files[$filecounter]['file'] = (string) $object->Key;
                 $files[$filecounter]['filename'] = basename($object->Key);
                 $files[$filecounter]['downloadurl'] = network_admin_url('admin.php') . '?page=backwpupbackups&action=downloads3&file=' . (string) $object->Key . '&jobid=' . $job_object->job['jobid'];
                 $files[$filecounter]['filesize'] = (int) $object->Size;
                 $files[$filecounter]['time'] = $changetime;
                 $filecounter++;
             }
         }
         if ($job_object->job['s3maxbackups'] > 0 && is_object($s3)) {
             //Delete old backups
             if (count($backupfilelist) > $job_object->job['s3maxbackups']) {
                 ksort($backupfilelist);
                 $numdeltefiles = 0;
                 while ($file = array_shift($backupfilelist)) {
                     if (count($backupfilelist) < $job_object->job['s3maxbackups']) {
                         break;
                     }
                     //delete files on S3
                     $delete_s3 = $s3->delete_object($job_object->job['s3bucket'], $job_object->job['s3dir'] . $file);
                     if ($delete_s3) {
                         foreach ($files as $key => $filedata) {
                             if ($filedata['file'] == $job_object->job['s3dir'] . $file) {
                                 unset($files[$key]);
                             }
                         }
                         $numdeltefiles++;
                     } else {
                         $job_object->log(sprintf(__('Cannot delete backup from %s.', 'backwpup'), $this->get_s3_base_url($job_object->job['s3region'], $job_object->job['s3base_url']) . '/' . $job_object->job['s3bucket'] . '/' . $job_object->job['s3dir'] . $file), E_USER_ERROR);
                     }
                 }
                 if ($numdeltefiles > 0) {
                     $job_object->log(sprintf(_n('One file deleted on S3 Bucket.', '%d files deleted on S3 Bucket', $numdeltefiles, 'backwpup'), $numdeltefiles), E_USER_NOTICE);
                 }
             }
         }
         set_site_transient('backwpup_' . $job_object->job['jobid'] . '_s3', $files, 60 * 60 * 24 * 7);
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('S3 Service API: %s', 'backwpup'), htmlentities($e->getMessage())), $e->getFile(), $e->getLine());
         return FALSE;
     }
     $job_object->substeps_done = 2 + $job_object->backup_filesize;
     return TRUE;
 }
    /**
     *
     */
    public static function page()
    {
        if (!empty($_GET['jobid'])) {
            $jobid = (int) $_GET['jobid'];
        } else {
            //generate jobid if not exists
            $newjobid = BackWPup_Option::get_job_ids();
            sort($newjobid);
            $jobid = end($newjobid) + 1;
        }
        $destinations = BackWPup::get_registered_destinations();
        $job_types = BackWPup::get_job_types();
        ?>
    <div class="wrap" id="backwpup-page">
		<?php 
        echo '<h2><span id="backwpup-page-icon">&nbsp;</span>' . sprintf(__('%1$s Job: %2$s', 'backwpup'), BackWPup::get_plugin_data('name'), '<span id="h2jobtitle">' . esc_html(BackWPup_Option::get($jobid, 'name')) . '</span>') . '</h2>';
        //default tabs
        $tabs = array('job' => array('name' => __('General', 'backwpup'), 'display' => TRUE), 'cron' => array('name' => __('Schedule', 'backwpup'), 'display' => TRUE));
        //add jobtypes to tabs
        $job_job_types = BackWPup_Option::get($jobid, 'type');
        foreach ($job_types as $typeid => $typeclass) {
            $tabid = 'jobtype-' . strtolower($typeid);
            $tabs[$tabid]['name'] = $typeclass->info['name'];
            $tabs[$tabid]['display'] = TRUE;
            if (!in_array($typeid, $job_job_types)) {
                $tabs[$tabid]['display'] = FALSE;
            }
        }
        //add destinations to tabs
        $jobdests = BackWPup_Option::get($jobid, 'destinations');
        foreach ($destinations as $destid => $dest) {
            $tabid = 'dest-' . strtolower($destid);
            $tabs[$tabid]['name'] = sprintf(__('To: %s', 'backwpup'), $dest['info']['name']);
            $tabs[$tabid]['display'] = TRUE;
            if (!in_array($destid, $jobdests)) {
                $tabs[$tabid]['display'] = FALSE;
            }
        }
        //display tabs
        echo '<h2 class="nav-tab-wrapper">';
        foreach ($tabs as $id => $tab) {
            $addclass = '';
            if ($id == $_GET['tab']) {
                $addclass = ' nav-tab-active';
            }
            $display = '';
            if (!$tab['display']) {
                $display = ' style="display:none;"';
            }
            echo '<a href="' . wp_nonce_url(network_admin_url('admin.php') . '?page=backwpupeditjob&tab=' . $id . '&jobid=' . $jobid, 'edit-job') . '" class="nav-tab' . $addclass . '" id="tab-' . $id . '" data-nexttab="' . $id . '" ' . $display . '>' . $tab['name'] . '</a>';
        }
        echo '</h2>';
        //display messages
        BackWPup_Admin::display_messages();
        echo '<form name="editjob" id="editjob" method="post" action="' . admin_url('admin-post.php') . '">';
        echo '<input type="hidden" id="jobid" name="jobid" value="' . $jobid . '" />';
        echo '<input type="hidden" name="tab" value="' . $_GET['tab'] . '" />';
        echo '<input type="hidden" name="nexttab" value="' . $_GET['tab'] . '" />';
        echo '<input type="hidden" name="page" value="backwpupeditjob" />';
        echo '<input type="hidden" name="action" value="backwpup" />';
        echo '<input type="hidden" name="anchor" value="" />';
        wp_nonce_field('backwpupeditjob_page');
        wp_nonce_field('backwpup_ajax_nonce', 'backwpupajaxnonce', FALSE);
        switch ($_GET['tab']) {
            case 'job':
                echo '<div class="table" id="info-tab-job">';
                ?>
				<h3 class="title"><?php 
                _e('Job Name', 'backwpup');
                ?>
</h3>
				<p></p>
				<table class="form-table">
					<tr>
						<th scope="row"><label for="name"><?php 
                _e('Please name this job.', 'backwpup');
                ?>
</label></th>
						<td>
							<input name="name" type="text" id="name" data-empty="<?php 
                _e('New Job', 'backwpup');
                ?>
"
								   value="<?php 
                echo BackWPup_Option::get($jobid, 'name');
                ?>
" class="regular-text" />
						</td>
					</tr>
				</table>

				<h3 class="title"><?php 
                _e('Job Tasks', 'backwpup');
                ?>
</h3>
				<p></p>
				<table class="form-table">
					<tr>
						<th scope="row"><?php 
                _e('This job is a&#160;&hellip;', 'backwpup');
                ?>
</th>
						<td>
							<fieldset>
								<legend class="screen-reader-text"><span><?php 
                _e('Job tasks', 'backwpup');
                ?>
</span>
								</legend><?php 
                foreach ($job_types as $id => $typeclass) {
                    $addclass = '';
                    if ($typeclass->creates_file()) {
                        $addclass .= ' filetype';
                    }
                    $title = '';
                    if (!empty($typeclass->info['help'])) {
                        $title = ' title="' . esc_attr($typeclass->info['help']) . '"';
                        $addclass .= ' help-tip';
                    }
                    echo '<label for="jobtype-select-' . strtolower($id) . '"><input class="jobtype-select checkbox' . $addclass . '"' . $title . '  id="jobtype-select-' . strtolower($id) . '" type="checkbox" ' . checked(TRUE, in_array($id, BackWPup_Option::get($jobid, 'type')), FALSE) . ' name="type[]" value="' . $id . '" /> ' . $typeclass->info['description'] . '</label><br />';
                }
                ?>
</fieldset>
						</td>
					</tr>
				</table>

				<h3 class="title hasdests"><?php 
                _e('Backup File Creation', 'backwpup');
                ?>
</h3>
				<p class="hasdests"></p>
				<table class="form-table hasdests">
					<?php 
                if (class_exists('BackWPup_Pro', FALSE)) {
                    ?>
					<tr>
						<th scope="row"><?php 
                    _e('Backup type', 'backwpup');
                    ?>
</th>
						<td>
							<fieldset>
								<legend class="screen-reader-text">	<span><?php 
                    _e('Backup type', 'backwpup');
                    ?>
</span></legend>
								<label for="idbackuptype-sync"><input class="radio"
									   type="radio"<?php 
                    checked('sync', BackWPup_Option::get($jobid, 'backuptype'), TRUE);
                    ?>
									   name="backuptype" id="idbackuptype-sync"
									   value="sync"/> <?php 
                    _e('Synchronize file by file to destination', 'backwpup');
                    ?>
</label><br/>
                                <label for="idbackuptype-archive"><input class="radio"
									   type="radio"<?php 
                    checked('archive', BackWPup_Option::get($jobid, 'backuptype'), TRUE);
                    ?>
									   name="backuptype" id="idbackuptype-archive"
									   value="archive"/> <?php 
                    _e('Create a backup archive', 'backwpup');
                    ?>
</label><br/>
							</fieldset>
						</td>
					</tr>
					<?php 
                }
                ?>
					<tr class="nosync">
						<th scope="row"><label for="archivename"><?php 
                _e('Archive name', 'backwpup');
                ?>
</label></th>
						<td>
							<input name="archivename" type="text" id="archivename"
								value="<?php 
                echo BackWPup_Option::get($jobid, 'archivename');
                ?>
"
								class="regular-text code help-tip" title="<?php 
                echo "<strong>" . esc_attr__('Replacement patterns:', 'backwpup') . "</strong><br />";
                echo esc_attr__('%d = Two digit day of the month, with leading zeros', 'backwpup') . '<br />';
                echo esc_attr__('%j = Day of the month, without leading zeros', 'backwpup') . '<br />';
                echo esc_attr__('%m = Day of the month, with leading zeros', 'backwpup') . '<br />';
                echo esc_attr__('%n = Representation of the month (without leading zeros)', 'backwpup') . '<br />';
                echo esc_attr__('%Y = Four digit representation for the year', 'backwpup') . '<br />';
                echo esc_attr__('%y = Two digit representation of the year', 'backwpup') . '<br />';
                echo esc_attr__('%a = Lowercase ante meridiem (am) and post meridiem (pm)', 'backwpup') . '<br />';
                echo esc_attr__('%A = Uppercase ante meridiem (AM) and post meridiem (PM)', 'backwpup') . '<br />';
                echo esc_attr__('%B = Swatch Internet Time', 'backwpup') . '<br />';
                echo esc_attr__('%g = Hour in 12-hour format, without leading zeros', 'backwpup') . '<br />';
                echo esc_attr__('%G = Hour in 24-hour format, without leading zeros', 'backwpup') . '<br />';
                echo esc_attr__('%h = Hour in 12-hour format, with leading zeros', 'backwpup') . '<br />';
                echo esc_attr__('%H = Hour in 24-hour format, with leading zeros', 'backwpup') . '<br />';
                echo esc_attr__('%i = Two digit representation of the minute', 'backwpup') . '<br />';
                echo esc_attr__('%s = Two digit representation of the second', 'backwpup') . '<br />';
                ?>
" />
							<?php 
                $current_time = current_time('timestamp');
                $datevars = array('%d', '%j', '%m', '%n', '%Y', '%y', '%a', '%A', '%B', '%g', '%G', '%h', '%H', '%i', '%s');
                $datevalues = array(date('d', $current_time), date('j', $current_time), date('m', $current_time), date('n', $current_time), date('Y', $current_time), date('y', $current_time), date('a', $current_time), date('A', $current_time), date('B', $current_time), date('g', $current_time), date('G', $current_time), date('h', $current_time), date('H', $current_time), date('i', $current_time), date('s', $current_time));
                $archivename = str_replace($datevars, $datevalues, BackWPup_Job::sanitize_file_name(BackWPup_Option::get($jobid, 'archivename')));
                echo '<p>Preview: <code><span id="archivefilename">' . $archivename . '</span><span id="archiveformat">' . BackWPup_Option::get($jobid, 'archiveformat') . '</span></code></p>';
                ?>
						</td>
					</tr>
					<tr class="nosync">
						<th scope="row"><?php 
                _e('Archive Format', 'backwpup');
                ?>
</th>
						<td>
							<fieldset>
								<legend class="screen-reader-text"><span><?php 
                _e('Archive Format', 'backwpup');
                ?>
</span></legend>
								<?php 
                if (function_exists('gzopen') || class_exists('ZipArchive')) {
                    echo '<label for="idarchiveformat-zip"><input class="radio help-tip" title="' . __('PHP Zip functions will be used if available (needs less memory). Otherwise the PCLZip class will be used.', 'backwpup') . '" type="radio"' . checked('.zip', BackWPup_Option::get($jobid, 'archiveformat'), FALSE) . ' name="archiveformat" id="idarchiveformat-zip" value=".zip" /> ' . __('Zip', 'backwpup') . '</label><br />';
                } else {
                    echo '<label for="idarchiveformat-zip"><input class="radio help-tip" title="' . __('Disabled due to missing PHP function.', 'backwpup') . '" type="radio"' . checked('.zip', BackWPup_Option::get($jobid, 'archiveformat'), FALSE) . ' name="archiveformat" id="idarchiveformat-zip" value=".zip" disabled="disabled" /> ' . __('Zip', 'backwpup') . '</label><br />';
                }
                echo '<label for="idarchiveformat-tar"><input class="radio help-tip" title="' . __('A tarballed, not compressed archive (fast and less memory)', 'backwpup') . '" type="radio"' . checked('.tar', BackWPup_Option::get($jobid, 'archiveformat'), FALSE) . ' name="archiveformat" id="idarchiveformat-tar" value=".tar" /> ' . __('Tar', 'backwpup') . '</label><br />';
                if (function_exists('gzopen')) {
                    echo '<label for="idarchiveformat-targz"><input class="radio help-tip" title="' . __('A tarballed, GZipped archive (fast and less memory)', 'backwpup') . '" type="radio"' . checked('.tar.gz', BackWPup_Option::get($jobid, 'archiveformat'), FALSE) . ' name="archiveformat" id="idarchiveformat-targz" value=".tar.gz" /> ' . __('Tar GZip', 'backwpup') . '</label><br />';
                } else {
                    echo '<label for="idarchiveformat-targz"><input class="radio help-tip" title="' . __('Disabled due to missing PHP function.', 'backwpup') . '" type="radio"' . checked('.tar.gz', BackWPup_Option::get($jobid, 'archiveformat'), FALSE) . ' name="archiveformat" id="idarchiveformat-targz" value=".tar.gz" disabled="disabled" /> ' . __('Tar GZip', 'backwpup') . '</label><br />';
                }
                if (function_exists('bzopen')) {
                    echo '<label for="idarchiveformat-tarbz2"><input class="radio help-tip" title="' . __('A tarballed, BZipped archive (fast and less memory)', 'backwpup') . '" type="radio"' . checked('.tar.bz2', BackWPup_Option::get($jobid, 'archiveformat'), FALSE) . ' name="archiveformat" id="idarchiveformat-tarbz2" value=".tar.bz2" /> ' . __('Tar BZip2', 'backwpup') . '</label><br />';
                } else {
                    echo '<label for="idarchiveformat-tarbz2"><input class="radio help-tip" title="' . __('Disabled due to missing PHP function.', 'backwpup') . '" type="radio"' . checked('.tar.bz2', BackWPup_Option::get($jobid, 'archiveformat'), FALSE) . ' name="archiveformat" id="idarchiveformat-tarbz2" value=".tar.bz2" disabled="disabled" /> ' . __('Tar BZip2', 'backwpup') . '</label><br />';
                }
                ?>
</fieldset>
						</td>
					</tr>
				</table>

				<h3 class="title hasdests"><?php 
                _e('Job Destination', 'backwpup');
                ?>
</h3>
				<p class="hasdests"></p>
				<table class="form-table hasdests">
					<tr>
						<th scope="row"><?php 
                _e('Where should your backup file be stored?', 'backwpup');
                ?>
</th>
						<td>
							<fieldset>
								<legend class="screen-reader-text"><span><?php 
                _e('Where should your backup file be stored?', 'backwpup');
                ?>
</span>
								</legend><?php 
                foreach ($destinations as $id => $dest) {
                    $syncclass = '';
                    if (!$dest['can_sync']) {
                        $syncclass = 'nosync';
                    }
                    $title = '';
                    $helpclass = '';
                    if (!empty($dest['info']['help'])) {
                        $title = ' title="' . esc_attr($dest['info']['help']) . '"';
                        $helpclass = ' help-tip';
                    }
                    echo '<span class="' . $syncclass . '"><label for="dest-select-' . strtolower($id) . '"><input class="checkbox' . $helpclass . '"' . $title . ' id="dest-select-' . strtolower($id) . '" type="checkbox" ' . checked(TRUE, in_array($id, BackWPup_Option::get($jobid, 'destinations')), FALSE) . ' name="destinations[]" value="' . $id . '" ' . disabled(!empty($dest['error']), TRUE, FALSE) . ' /> ' . $dest['info']['description'];
                    if (!empty($dest['error'])) {
                        echo '<br /><span class="description">' . $dest['error'] . '</span>';
                    }
                    echo '</label><br /></span>';
                }
                ?>
</fieldset>
						</td>
					</tr>
				</table>

				<h3 class="title"><?php 
                _e('Log Files', 'backwpup');
                ?>
</h3>
				<p></p>
				<table class="form-table">
					<tr>
						<th scope="row"><label for="mailaddresslog"><?php 
                _e('Send log to email address', 'backwpup');
                ?>
</label></th>
						<td>
							<input name="mailaddresslog" type="text" id="mailaddresslog"
								   value="<?php 
                echo BackWPup_Option::get($jobid, 'mailaddresslog');
                ?>
"
								   class="regular-text help-tip" title="<?php 
                esc_attr_e('Leave empty to not have log sent. Or separate with , for more than one receiver.', 'backwpup');
                ?>
" />
						</td>
					</tr>
					<tr>
						<th scope="row"><label for="mailaddresssenderlog"><?php 
                _e('Email FROM field', 'backwpup');
                ?>
</label></th>
						<td>
							<input name="mailaddresssenderlog" type="text" id="mailaddresssenderlog"
								   value="<?php 
                echo BackWPup_Option::get($jobid, 'mailaddresssenderlog');
                ?>
"
								   class="regular-text help-tip" title="<?php 
                esc_attr_e('Email "From" field (Name &lt;&#160;you@your-email-address.tld&#160;&gt;)', 'backwpup');
                ?>
" />
						</td>
					</tr>
					<tr>
						<th scope="row"><?php 
                _e('Errors only', 'backwpup');
                ?>
</th>
						<td>
                            <label for="idmailerroronly">
							<input class="checkbox" value="1" id="idmailerroronly"
								   type="checkbox" <?php 
                checked(BackWPup_Option::get($jobid, 'mailerroronly'), TRUE);
                ?>
								   name="mailerroronly" /> <?php 
                _e('Send email with log only when errors occur during job execution.', 'backwpup');
                ?>
							</label>
						</td>
					</tr>
				</table>
				<?php 
                echo '</div>';
                break;
            case 'cron':
                echo '<div class="table" id="info-tab-cron">';
                ?>
				<h3 class="title"><?php 
                _e('Job Schedule', 'backwpup');
                ?>
</h3>
				<p></p>
				<table class="form-table">
					<tr>
                        <th scope="row"><?php 
                _e('Start job', 'backwpup');
                ?>
</th>
                        <td>
                            <fieldset>
                                <legend class="screen-reader-text"><span><?php 
                _e('Start job', 'backwpup');
                ?>
</span></legend>
                                <label for="idactivetype"><input class="radio"
                                       type="radio"<?php 
                checked('', BackWPup_Option::get($jobid, 'activetype'), TRUE);
                ?>
                                       name="activetype" id="idactivetype"
                                       value="" /> <?php 
                _e('manually only', 'backwpup');
                ?>
</label><br/>
                                <label for="idactivetype-wpcron"><input class="radio"
                                       type="radio"<?php 
                checked('wpcron', BackWPup_Option::get($jobid, 'activetype'), TRUE);
                ?>
                                       name="activetype" id="idactivetype-wpcron"
                                       value="wpcron" /> <?php 
                _e('with WordPress cron', 'backwpup');
                ?>
</label><br/>
	                            <?php 
                $disabled = '';
                $easycron_api = get_site_option('backwpup_cfg_easycronapikey');
                if (empty($easycron_api)) {
                    $disabled = ' disabled="disabled"';
                }
                ?>
	                            <label for="idactivetype-easycron"><input class="radio help-tip"
			                            type="radio"<?php 
                checked('easycron', BackWPup_Option::get($jobid, 'activetype'), TRUE);
                ?>
			                            name="activetype" id="idactivetype-easycron"<?php 
                echo $disabled;
                ?>
			                            value="easycron" title="<?php 
                _e('Use EasyCron.com Cron jobs.');
                ?>
" /> <?php 
                _e('with <a href="https://www.easycron.com?ref=36673" class="help-tip" title="Affiliate Link!">EasyCron.com</a>', 'backwpup');
                ?>
	                            <?php 
                if (empty($easycron_api)) {
                    echo ' <strong>' . sprintf(__('Setup <a href="https://www.easycron.com?ref=36673" class="help-tip" title="Affiliate Link!">Account</a> / <a href="%s">API Key</a> first.', 'backwpup'), network_admin_url('admin.php') . '?page=backwpupsettings#backwpup-tab-apikey') . '</strong>';
                }
                ?>
	                            </label><br/>
	                            <?php 
                $url = BackWPup_Job::get_jobrun_url('runext', BackWPup_Option::get($jobid, 'jobid'));
                ?>
                                <label for="idactivetype-link"><input class="radio help-tip"
									   type="radio"<?php 
                checked('link', BackWPup_Option::get($jobid, 'activetype'), TRUE);
                ?>
									   name="activetype" id="idactivetype-link"
									   value="link" title="<?php 
                esc_attr_e('Copy the link for an external start. This option has to be activated to make the link work.', 'backwpup');
                ?>
" /> <?php 
                _e('with a link', 'backwpup');
                ?>
 <code><a href="<?php 
                echo $url['url'];
                ?>
" target="_blank"><?php 
                echo $url['url'];
                ?>
</a></code></label>
								<br />
                            </fieldset>
                        </td>
                    </tr>
                    <tr>
						<th scope="row"><?php 
                _e('Start job with CLI', 'backwpup');
                ?>
</th>
						<td class="help-tip" title="<?php 
                esc_attr_e('Use WP-CLI commands to let the job start with the server’s cron on command line interface.', 'backwpup');
                ?>
">
							<?php 
                _e('Use <a href="http://wp-cli.org/">WP-CLI</a> to run jobs from commandline.', 'backwpup');
                ?>
						</td>
                    </tr>
				</table>
				<h3 class="title wpcron"><?php 
                _e('Schedule execution time', 'backwpup');
                ?>
</h3>
				<?php 
                BackWPup_Page_Editjob::ajax_cron_text(array('cronstamp' => BackWPup_Option::get($jobid, 'cron'), 'crontype' => BackWPup_Option::get($jobid, 'cronselect')));
                ?>
				<table class="form-table wpcron">
					<tr>
						<th scope="row"><?php 
                _e('Scheduler type', 'backwpup');
                ?>
</th>
						<td>
							<fieldset>
								<legend class="screen-reader-text"><span><?php 
                _e('Scheduler type', 'backwpup');
                ?>
</span></legend>
                                <label for="idcronselect-basic"><input class="radio"
									   type="radio"<?php 
                checked('basic', BackWPup_Option::get($jobid, 'cronselect'), TRUE);
                ?>
									   name="cronselect" id="idcronselect-basic"
									   value="basic" /> <?php 
                _e('basic', 'backwpup');
                ?>
</label><br/>
                                <label for="idcronselect-advanced"><input class="radio"
									   type="radio"<?php 
                checked('advanced', BackWPup_Option::get($jobid, 'cronselect'), TRUE);
                ?>
									   name="cronselect" id="idcronselect-advanced"
									   value="advanced" /> <?php 
                _e('advanced', 'backwpup');
                ?>
</label><br/>
							</fieldset>
						</td>
					</tr>
					<?php 
                list($cronstr['minutes'], $cronstr['hours'], $cronstr['mday'], $cronstr['mon'], $cronstr['wday']) = explode(' ', BackWPup_Option::get($jobid, 'cron'), 5);
                if (strstr($cronstr['minutes'], '*/')) {
                    $minutes = explode('/', $cronstr['minutes']);
                } else {
                    $minutes = explode(',', $cronstr['minutes']);
                }
                if (strstr($cronstr['hours'], '*/')) {
                    $hours = explode('/', $cronstr['hours']);
                } else {
                    $hours = explode(',', $cronstr['hours']);
                }
                if (strstr($cronstr['mday'], '*/')) {
                    $mday = explode('/', $cronstr['mday']);
                } else {
                    $mday = explode(',', $cronstr['mday']);
                }
                if (strstr($cronstr['mon'], '*/')) {
                    $mon = explode('/', $cronstr['mon']);
                } else {
                    $mon = explode(',', $cronstr['mon']);
                }
                if (strstr($cronstr['wday'], '*/')) {
                    $wday = explode('/', $cronstr['wday']);
                } else {
                    $wday = explode(',', $cronstr['wday']);
                }
                ?>
                    <tr class="wpcronbasic"<?php 
                if (BackWPup_Option::get($jobid, 'cronselect') != 'basic') {
                    echo ' style="display:none;"';
                }
                ?>
>
                        <th scope="row"><?php 
                _e('Scheduler', 'backwpup');
                ?>
</th>
                        <td>
                            <table id="wpcronbasic">
                                <tr>
                                    <th>
										<?php 
                _e('Type', 'backwpup');
                ?>
                                    </th>
                                    <th>
                                    </th>
                                    <th>
										<?php 
                _e('Hour', 'backwpup');
                ?>
                                    </th>
                                    <th>
										<?php 
                _e('Minute', 'backwpup');
                ?>
                                    </th>
                                </tr>
                                <tr>
                                    <td><label for="idcronbtype-mon"><?php 
                echo '<input class="radio" type="radio"' . checked(TRUE, is_numeric($mday[0]), FALSE) . ' name="cronbtype" id="idcronbtype-mon" value="mon" /> ' . __('monthly', 'backwpup');
                ?>
</label></td>
                                    <td><select name="moncronmday"><?php 
                for ($i = 1; $i <= 31; $i++) {
                    echo '<option ' . selected(in_array("{$i}", $mday, TRUE), TRUE, FALSE) . '  value="' . $i . '" />' . __('on', 'backwpup') . ' ' . $i . '</option>';
                }
                ?>
</select></td>
                                    <td><select name="moncronhours"><?php 
                for ($i = 0; $i < 24; $i++) {
                    echo '<option ' . selected(in_array("{$i}", $hours, TRUE), TRUE, FALSE) . '  value="' . $i . '" />' . $i . '</option>';
                }
                ?>
</select></td>
                                    <td><select name="moncronminutes"><?php 
                for ($i = 0; $i < 60; $i = $i + 5) {
                    echo '<option ' . selected(in_array("{$i}", $minutes, TRUE), TRUE, FALSE) . '  value="' . $i . '" />' . $i . '</option>';
                }
                ?>
</select></td>
                                </tr>
                                <tr>
                                    <td><label for="idcronbtype-week"><?php 
                echo '<input class="radio" type="radio"' . checked(TRUE, is_numeric($wday[0]), FALSE) . ' name="cronbtype" id="idcronbtype-week" value="week" /> ' . __('weekly', 'backwpup');
                ?>
</label></td>
                                    <td><select name="weekcronwday">
										<?php 
                echo '<option ' . selected(in_array("0", $wday, TRUE), TRUE, FALSE) . '  value="0" />' . __('Sunday', 'backwpup') . '</option>';
                echo '<option ' . selected(in_array("1", $wday, TRUE), TRUE, FALSE) . '  value="1" />' . __('Monday', 'backwpup') . '</option>';
                echo '<option ' . selected(in_array("2", $wday, TRUE), TRUE, FALSE) . '  value="2" />' . __('Tuesday', 'backwpup') . '</option>';
                echo '<option ' . selected(in_array("3", $wday, TRUE), TRUE, FALSE) . '  value="3" />' . __('Wednesday', 'backwpup') . '</option>';
                echo '<option ' . selected(in_array("4", $wday, TRUE), TRUE, FALSE) . '  value="4" />' . __('Thursday', 'backwpup') . '</option>';
                echo '<option ' . selected(in_array("5", $wday, TRUE), TRUE, FALSE) . '  value="5" />' . __('Friday', 'backwpup') . '</option>';
                echo '<option ' . selected(in_array("6", $wday, TRUE), TRUE, FALSE) . '  value="6" />' . __('Saturday', 'backwpup') . '</option>';
                ?>
                                    </select></td>
                                    <td><select name="weekcronhours"><?php 
                for ($i = 0; $i < 24; $i++) {
                    echo '<option ' . selected(in_array("{$i}", $hours, TRUE), TRUE, FALSE) . '  value="' . $i . '" />' . $i . '</option>';
                }
                ?>
</select></td>
                                    <td><select name="weekcronminutes"><?php 
                for ($i = 0; $i < 60; $i = $i + 5) {
                    echo '<option ' . selected(in_array("{$i}", $minutes, TRUE), TRUE, FALSE) . '  value="' . $i . '" />' . $i . '</option>';
                }
                ?>
</select></td>
                                </tr>
                                <tr>
                                    <td><label for="idcronbtype-day"><?php 
                echo '<input class="radio" type="radio"' . checked("**", $mday[0] . $wday[0], FALSE) . ' name="cronbtype" id="idcronbtype-day" value="day" /> ' . __('daily', 'backwpup');
                ?>
</label></td>
                                    <td></td>
                                    <td><select name="daycronhours"><?php 
                for ($i = 0; $i < 24; $i++) {
                    echo '<option ' . selected(in_array("{$i}", $hours, TRUE), TRUE, FALSE) . '  value="' . $i . '" />' . $i . '</option>';
                }
                ?>
</select></td>
                                    <td><select name="daycronminutes"><?php 
                for ($i = 0; $i < 60; $i = $i + 5) {
                    echo '<option ' . selected(in_array("{$i}", $minutes, TRUE), TRUE, FALSE) . '  value="' . $i . '" />' . $i . '</option>';
                }
                ?>
</select></td>
                                </tr>
                                <tr>
                                    <td><label for="idcronbtype-hour"><?php 
                echo '<input class="radio" type="radio"' . checked("*", $hours[0], FALSE, FALSE) . ' name="cronbtype" id="idcronbtype-hour" value="hour" /> ' . __('hourly', 'backwpup');
                ?>
</label></td>
                                    <td></td>
                                    <td></td>
                                    <td><select name="hourcronminutes"><?php 
                for ($i = 0; $i < 60; $i = $i + 5) {
                    echo '<option ' . selected(in_array("{$i}", $minutes, TRUE), TRUE, FALSE) . '  value="' . $i . '" />' . $i . '</option>';
                }
                ?>
</select></td>
                                </tr>
                            </table>
                        </td>
                    </tr>
					<tr class="wpcronadvanced"<?php 
                if (BackWPup_Option::get($jobid, 'cronselect') != 'advanced') {
                    echo ' style="display:none;"';
                }
                ?>
>
						<th scope="row"><?php 
                _e('Scheduler', 'backwpup');
                ?>
</th>
						<td>
                            <div id="cron-min-box">
                                <b><?php 
                _e('Minutes:', 'backwpup');
                ?>
</b><br/>
								<?php 
                echo '<label for="idcronminutes"><input class="checkbox" type="checkbox"' . checked(in_array("*", $minutes, TRUE), TRUE, FALSE) . ' name="cronminutes[]" id="idcronminutes" value="*" /> ' . __('Any (*)', 'backwpup') . '</label><br />';
                ?>
                                <div id="cron-min"><?php 
                for ($i = 0; $i < 60; $i = $i + 5) {
                    echo '<label for="idcronminutes-' . $i . '"><input class="checkbox" type="checkbox"' . checked(in_array("{$i}", $minutes, TRUE), TRUE, FALSE) . ' name="cronminutes[]" id="idcronminutes-' . $i . '" value="' . $i . '" /> ' . $i . '</label><br />';
                }
                ?>
                                </div>
                            </div>
                            <div id="cron-hour-box">
                                <b><?php 
                _e('Hours:', 'backwpup');
                ?>
</b><br/>
								<?php 
                echo '<label for="idcronhours"><input class="checkbox" type="checkbox"' . checked(in_array("*", $hours, TRUE), TRUE, FALSE) . ' name="cronhours[]" for="idcronhours" value="*" /> ' . __('Any (*)', 'backwpup') . '</label><br />';
                ?>
                                <div id="cron-hour"><?php 
                for ($i = 0; $i < 24; $i++) {
                    echo '<label for="idcronhours-' . $i . '"><input class="checkbox" type="checkbox"' . checked(in_array("{$i}", $hours, TRUE), TRUE, FALSE) . ' name="cronhours[]" id="idcronhours-' . $i . '" value="' . $i . '" /> ' . $i . '</label><br />';
                }
                ?>
                                </div>
                            </div>
                            <div id="cron-day-box">
                                <b><?php 
                _e('Day of Month:', 'backwpup');
                ?>
</b><br/>
                                <label for="idcronmday"><input class="checkbox" type="checkbox"<?php 
                checked(in_array("*", $mday, TRUE), TRUE, TRUE);
                ?>
                                       name="cronmday[]" id="idcronmday" value="*"/> <?php 
                _e('Any (*)', 'backwpup');
                ?>
</label>
                                <br/>

                                <div id="cron-day">
									<?php 
                for ($i = 1; $i <= 31; $i++) {
                    echo '<label for="idcronmday-' . $i . '"><input class="checkbox" type="checkbox"' . checked(in_array("{$i}", $mday, TRUE), TRUE, FALSE) . ' name="cronmday[]" id="idcronmday-' . $i . '" value="' . $i . '" /> ' . $i . '</label><br />';
                }
                ?>
                                </div>
                            </div>
                            <div id="cron-month-box">
                                <b><?php 
                _e('Month:', 'backwpup');
                ?>
</b><br/>
								<?php 
                echo '<label for="idcronmon"><input class="checkbox" type="checkbox"' . checked(in_array("*", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon" value="*" /> ' . __('Any (*)', 'backwpup') . '</label><br />';
                ?>
                                <div id="cron-month">
									<?php 
                echo '<label for="idcronmon-1"><input class="checkbox" type="checkbox"' . checked(in_array("1", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-1" value="1" /> ' . __('January', 'backwpup') . '</label><br />';
                echo '<label for="idcronmon-2"><input class="checkbox" type="checkbox"' . checked(in_array("2", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-2" value="2" /> ' . __('February', 'backwpup') . '</label><br />';
                echo '<label for="idcronmon-3"><input class="checkbox" type="checkbox"' . checked(in_array("3", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-3" value="3" /> ' . __('March', 'backwpup') . '</label><br />';
                echo '<label for="idcronmon-4"><input class="checkbox" type="checkbox"' . checked(in_array("4", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-4" value="4" /> ' . __('April', 'backwpup') . '</label><br />';
                echo '<label for="idcronmon-5"><input class="checkbox" type="checkbox"' . checked(in_array("5", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-5" value="5" /> ' . __('May', 'backwpup') . '</label><br />';
                echo '<label for="idcronmon-6"><input class="checkbox" type="checkbox"' . checked(in_array("6", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-6" value="6" /> ' . __('June', 'backwpup') . '</label><br />';
                echo '<label for="idcronmon-7"><input class="checkbox" type="checkbox"' . checked(in_array("7", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-7" value="7" /> ' . __('July', 'backwpup') . '</label><br />';
                echo '<label for="idcronmon-8"><input class="checkbox" type="checkbox"' . checked(in_array("8", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-8" value="8" /> ' . __('August', 'backwpup') . '</label><br />';
                echo '<label for="idcronmon-9"><input class="checkbox" type="checkbox"' . checked(in_array("9", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-9" value="9" /> ' . __('September', 'backwpup') . '</label><br />';
                echo '<label for="idcronmon-10"><input class="checkbox" type="checkbox"' . checked(in_array("10", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-10" value="10" /> ' . __('October', 'backwpup') . '</label><br />';
                echo '<label for="idcronmon-11"><input class="checkbox" type="checkbox"' . checked(in_array("11", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-11" value="11" /> ' . __('November', 'backwpup') . '</label><br />';
                echo '<label for="idcronmon-12"><input class="checkbox" type="checkbox"' . checked(in_array("12", $mon, TRUE), TRUE, FALSE) . ' name="cronmon[]" id="idcronmon-12" value="12" /> ' . __('December', 'backwpup') . '</label><br />';
                ?>
                                </div>
                            </div>
                            <div id="cron-weekday-box">
                                <b><?php 
                _e('Day of Week:', 'backwpup');
                ?>
</b><br/>
								<?php 
                echo '<label for="idcronwday"><input class="checkbox" type="checkbox"' . checked(in_array("*", $wday, TRUE), TRUE, FALSE) . ' name="cronwday[]" id="idcronwday" value="*" /> ' . __('Any (*)', 'backwpup') . '</label><br />';
                ?>
                                <div id="cron-weekday">
									<?php 
                echo '<label for="idcronwday-0"><input class="checkbox" type="checkbox"' . checked(in_array("0", $wday, TRUE), TRUE, FALSE) . ' name="cronwday[]" id="idcronwday-0" value="0" /> ' . __('Sunday', 'backwpup') . '</label><br />';
                echo '<label for="idcronwday-1"><input class="checkbox" type="checkbox"' . checked(in_array("1", $wday, TRUE), TRUE, FALSE) . ' name="cronwday[]" id="idcronwday-1" value="1" /> ' . __('Monday', 'backwpup') . '</label><br />';
                echo '<label for="idcronwday-2"><input class="checkbox" type="checkbox"' . checked(in_array("2", $wday, TRUE), TRUE, FALSE) . ' name="cronwday[]" id="idcronwday-2" value="2" /> ' . __('Tuesday', 'backwpup') . '</label><br />';
                echo '<label for="idcronwday-3"><input class="checkbox" type="checkbox"' . checked(in_array("3", $wday, TRUE), TRUE, FALSE) . ' name="cronwday[]" id="idcronwday-3" value="3" /> ' . __('Wednesday', 'backwpup') . '</label><br />';
                echo '<label for="idcronwday-4"><input class="checkbox" type="checkbox"' . checked(in_array("4", $wday, TRUE), TRUE, FALSE) . ' name="cronwday[]" id="idcronwday-4" value="4" /> ' . __('Thursday', 'backwpup') . '</label><br />';
                echo '<label for="idcronwday-5"><input class="checkbox" type="checkbox"' . checked(in_array("5", $wday, TRUE), TRUE, FALSE) . ' name="cronwday[]" id="idcronwday-5" value="5" /> ' . __('Friday', 'backwpup') . '</label><br />';
                echo '<label for="idcronwday-6"><input class="checkbox" type="checkbox"' . checked(in_array("6", $wday, TRUE), TRUE, FALSE) . ' name="cronwday[]" id="idcronwday-6" value="6" /> ' . __('Saturday', 'backwpup') . '</label><br />';
                ?>
                                </div>
                            </div>
                            <br class="clear"/>
						</td>
					</tr>
				</table>
				<?php 
                echo '</div>';
                break;
            default:
                echo '<div class="table" id="info-tab-' . $_GET['tab'] . '">';
                if (strstr($_GET['tab'], 'dest-')) {
                    $dest_object = BackWPup::get_destination(str_replace('dest-', '', $_GET['tab']));
                    $dest_object->edit_tab($jobid);
                }
                if (strstr($_GET['tab'], 'jobtype-')) {
                    $id = strtoupper(str_replace('jobtype-', '', $_GET['tab']));
                    $job_types[$id]->edit_tab($jobid);
                }
                echo '</div>';
        }
        echo '<p class="submit">';
        submit_button(__('Save changes', 'backwpup'), 'primary', 'save', FALSE, array('tabindex' => '2', 'accesskey' => 'p'));
        echo '</p></form>';
        ?>
    </div>

    <script type="text/javascript">
    //<![CDATA[
    jQuery(document).ready(function ($) {
        // auto post if things changed
        var changed = false;
        $( '#editjob' ).change( function () {
            changed = true;
        });
		$( '.nav-tab' ).click( function () {
			if ( changed ) {
				$( 'input[name="nexttab"]' ).val( $(this).data( "nexttab" ) );
				$( '#editjob' ).submit();
				return false;
            }
		});
		<?php 
        //add inline js
        if (strstr($_GET['tab'], 'dest-')) {
            $dest_object = BackWPup::get_destination(str_replace('dest-', '', $_GET['tab']));
            $dest_object->edit_inline_js();
        }
        if (strstr($_GET['tab'], 'jobtype-')) {
            $id = strtoupper(str_replace('jobtype-', '', $_GET['tab']));
            $job_types[$id]->edit_inline_js();
        }
        ?>
    });
    //]]>
    </script>
	<?php 
    }
    /**
     * Displaying next jobs
     */
    private static function mb_next_jobs()
    {
        if (!current_user_can('backwpup_jobs')) {
            return;
        }
        ?>
		<table class="wp-list-table widefat" cellspacing="0">
			<caption><?php 
        _e('Next scheduled jobs', 'backwpup');
        ?>
</caption>
			<thead>
			<tr>
				<th style="width: 30%"><?php 
        _e('Time', 'backwpup');
        ?>
</th>
				<th style="width: 70%"><?php 
        _e('Job', 'backwpup');
        ?>
</th>
			</tr>
			</thead>
			<?php 
        //get next jobs
        $mainsactive = BackWPup_Option::get_job_ids('activetype', 'wpcron');
        sort($mainsactive);
        $alternate = TRUE;
        // add working job if it not in active jobs
        $job_object = BackWPup_Job::get_working_data();
        if (!empty($job_object) && !empty($job_object->job['jobid']) && !in_array($job_object->job['jobid'], $mainsactive)) {
            $mainsactive[] = $job_object->job['jobid'];
        }
        foreach ($mainsactive as $jobid) {
            $name = BackWPup_Option::get($jobid, 'name');
            if (!empty($job_object) && $job_object->job['jobid'] == $jobid) {
                $runtime = current_time('timestamp') - $job_object->job['lastrun'];
                if (!$alternate) {
                    echo '<tr>';
                    $alternate = TRUE;
                } else {
                    echo '<tr class="alternate">';
                    $alternate = FALSE;
                }
                echo '<td>' . sprintf('<span style="color:#e66f00;">' . __('working since %d seconds', 'backwpup') . '</span>', $runtime) . '</td>';
                echo '<td><span style="font-weight:bold;">' . esc_html($job_object->job['name']) . '</span><br />';
                echo "<a style=\"color:red;\" href=\"" . wp_nonce_url(network_admin_url('admin.php') . '?page=backwpupjobs&action=abort', 'abort-job') . "\">" . __('Abort', 'backwpup') . "</a>";
                echo "</td></tr>";
            } else {
                if (!$alternate) {
                    echo '<tr>';
                    $alternate = TRUE;
                } else {
                    echo '<tr class="alternate">';
                    $alternate = FALSE;
                }
                if ($nextrun = wp_next_scheduled('backwpup_cron', array('id' => $jobid)) + get_option('gmt_offset') * 3600) {
                    echo '<td>' . sprintf(__('%1$s at %2$s', 'backwpup'), date_i18n(get_option('date_format'), $nextrun, TRUE), date_i18n(get_option('time_format'), $nextrun, TRUE)) . '</td>';
                } else {
                    echo '<td><em>' . __('Not scheduled!', 'backwpup') . '</em></td>';
                }
                echo '<td><a href="' . wp_nonce_url(network_admin_url('admin.php') . '?page=backwpupeditjob&jobid=' . $jobid, 'edit-job') . '" title="' . esc_attr(__('Edit Job', 'backwpup')) . '">' . $name . '</a></td></tr>';
            }
        }
        if (empty($mainsactive) and !empty($job_object)) {
            echo '<tr><td colspan="2"><i>' . __('none', 'backwpup') . '</i></td></tr>';
        }
        ?>
		</table>
		<?php 
    }
 /**
  * @param $id
  */
 public function edit_form_post_save($id)
 {
     global $wpdb;
     /* @var wpdb $wpdb */
     if ($_POST['dbdumpfilecompression'] == '' || $_POST['dbdumpfilecompression'] == '.gz') {
         BackWPup_Option::update($id, 'dbdumpfilecompression', $_POST['dbdumpfilecompression']);
     }
     BackWPup_Option::update($id, 'dbdumpfile', sanitize_file_name($_POST['dbdumpfile']));
     //selected tables
     $dbdumpexclude = array();
     $checked_db_tables = array();
     if (isset($_POST['tabledb'])) {
         foreach ($_POST['tabledb'] as $dbtable) {
             $checked_db_tables[] = rawurldecode($dbtable);
         }
     }
     $dbtables = $wpdb->get_results('SHOW TABLES FROM `' . DB_NAME . '`', ARRAY_N);
     foreach ($dbtables as $dbtable) {
         if (!in_array($dbtable[0], $checked_db_tables)) {
             $dbdumpexclude[] = $dbtable[0];
         }
     }
     BackWPup_Option::update($id, 'dbdumpexclude', $dbdumpexclude);
 }
Beispiel #9
0
 private static function upgrade_from_version_two()
 {
     //load options
     $cfg = get_option('backwpup');
     //only exists in Version 2
     $jobs = get_option('backwpup_jobs');
     //delete old options
     delete_option('backwpup');
     delete_option('backwpup_jobs');
     //add new option default structure and without auto load cache
     if (!is_multisite()) {
         add_option('backwpup_jobs', array(), NULL, 'no');
     }
     //upgrade cfg
     //if old value switch it to new
     if (!empty($cfg['dirlogs'])) {
         $cfg['logfolder'] = $cfg['dirlogs'];
     }
     if (!empty($cfg['httpauthpassword'])) {
         if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $cfg['httpauthpassword'])) {
             $cfg['httpauthpassword'] = base64_decode($cfg['httpauthpassword']);
         }
         $cfg['httpauthpassword'] = BackWPup_Encryption::encrypt($cfg['httpauthpassword']);
     }
     // delete old not needed vars
     unset($cfg['dirtemp'], $cfg['dirlogs'], $cfg['logfilelist'], $cfg['jobscriptruntime'], $cfg['jobscriptruntimelong'], $cfg['last_activate'], $cfg['disablewpcron'], $cfg['phpzip'], $cfg['apicronservice'], $cfg['mailsndemail'], $cfg['mailsndname'], $cfg['mailmethod'], $cfg['mailsendmail'], $cfg['mailhost'], $cfg['mailpass'], $cfg['mailhostport'], $cfg['mailsecure'], $cfg['mailuser']);
     //save in options
     foreach ($cfg as $cfgname => $cfgvalue) {
         update_site_option('backwpup_cfg_' . $cfgname, $cfgvalue);
     }
     //Put old jobs to new if exists
     foreach ($jobs as $jobid => $jobvalue) {
         //convert general settings
         if (empty($jobvalue['jobid'])) {
             $jobvalue['jobid'] = $jobid;
         }
         if (empty($jobvalue['activated'])) {
             $jobvalue['activetype'] = '';
         } else {
             $jobvalue['activetype'] = 'wpcron';
         }
         if (!isset($jobvalue['cronselect']) && !isset($jobvalue['cron'])) {
             $jobvalue['cronselect'] = 'basic';
         } elseif (!isset($jobvalue['cronselect']) && isset($jobvalue['cron'])) {
             $jobvalue['cronselect'] = 'advanced';
         }
         $jobvalue['backuptype'] = 'archive';
         $jobvalue['type'] = explode('+', $jobvalue['type']);
         //save as array
         foreach ($jobvalue['type'] as $key => $type) {
             if ($type == 'DB') {
                 $jobvalue['type'][$key] = 'DBDUMP';
             }
             if ($type == 'OPTIMIZE') {
                 unset($jobvalue['type'][$key]);
             }
             if ($type == 'CHECK') {
                 $jobvalue['type'][$key] = 'DBCHECK';
             }
             if ($type == 'MAIL') {
                 $jobvalue['type'][$key] = 'EMAIL';
             }
         }
         $jobvalue['archivename'] = $jobvalue['fileprefix'] . '%Y-%m-%d_%H-%i-%s';
         $jobvalue['archiveformat'] = $jobvalue['fileformart'];
         //convert active destinations
         $jobvalue['destinations'] = array();
         if (!empty($jobvalue['backupdir']) && $jobvalue['backupdir'] != '/') {
             $jobvalue['destinations'][] = 'FOLDER';
         }
         if (!empty($jobvalue['mailaddress'])) {
             $jobvalue['destinations'][] = 'MAIL';
         }
         if (!empty($jobvalue['ftphost']) && !empty($jobvalue['ftpuser']) && !empty($jobvalue['ftppass'])) {
             $jobvalue['destinations'][] = 'FTP';
         }
         if (!empty($jobvalue['dropetoken']) && !empty($jobvalue['dropesecret'])) {
             $jobvalue['destinations'][] = 'DROPBOX';
         }
         if (!empty($jobvalue['sugarrefreshtoken']) && !empty($jobvalue['sugarroot'])) {
             $jobvalue['destinations'][] = 'SUGARSYNC';
         }
         if (!empty($jobvalue['awsAccessKey']) && !empty($jobvalue['awsSecretKey']) && !empty($jobvalue['awsBucket'])) {
             $jobvalue['destinations'][] = 'S3';
         }
         if (!empty($jobvalue['GStorageAccessKey']) and !empty($jobvalue['GStorageSecret']) && !empty($jobvalue['GStorageBucket']) && !in_array('S3', $jobvalue['destinations'])) {
             $jobvalue['destinations'][] = 'S3';
         }
         if (!empty($jobvalue['rscUsername']) && !empty($jobvalue['rscAPIKey']) && !empty($jobvalue['rscContainer'])) {
             $jobvalue['destinations'][] = 'RSC';
         }
         if (!empty($jobvalue['msazureHost']) && !empty($jobvalue['msazureAccName']) && !empty($jobvalue['msazureKey']) && !empty($jobvalue['msazureContainer'])) {
             $jobvalue['destinations'][] = 'MSAZURE';
         }
         //convert dropbox
         $jobvalue['dropboxtoken'] = '';
         //new app key are set must reauth
         $jobvalue['dropboxsecret'] = '';
         $jobvalue['dropboxroot'] = 'dropbox';
         $jobvalue['dropboxmaxbackups'] = $jobvalue['dropemaxbackups'];
         $jobvalue['dropboxdir'] = $jobvalue['dropedir'];
         unset($jobvalue['dropetoken'], $jobvalue['dropesecret'], $jobvalue['droperoot'], $jobvalue['dropemaxbackups'], $jobvalue['dropedir']);
         //convert amazon S3
         $jobvalue['s3accesskey'] = $jobvalue['awsAccessKey'];
         $jobvalue['s3secretkey'] = BackWPup_Encryption::encrypt($jobvalue['awsSecretKey']);
         $jobvalue['s3bucket'] = $jobvalue['awsBucket'];
         //get aws region
         $jobvalue['s3region'] = 'us-east-1';
         $jobvalue['s3base_url'] = '';
         $jobvalue['s3storageclass'] = !empty($jobvalue['awsrrs']) ? 'REDUCED_REDUNDANCY' : '';
         $jobvalue['s3dir'] = $jobvalue['awsdir'];
         $jobvalue['s3maxbackups'] = $jobvalue['awsmaxbackups'];
         unset($jobvalue['awsAccessKey'], $jobvalue['awsSecretKey'], $jobvalue['awsBucket'], $jobvalue['awsrrs'], $jobvalue['awsdir'], $jobvalue['awsmaxbackups']);
         //convert google storage
         $jobvalue['s3accesskey'] = $jobvalue['GStorageAccessKey'];
         $jobvalue['s3secretkey'] = BackWPup_Encryption::encrypt($jobvalue['GStorageSecret']);
         $jobvalue['s3bucket'] = $jobvalue['GStorageBucket'];
         $jobvalue['s3region'] = 'google-storage';
         $jobvalue['s3base_url'] = '';
         $jobvalue['s3ssencrypt'] = '';
         $jobvalue['s3dir'] = $jobvalue['GStoragedir'];
         $jobvalue['s3maxbackups'] = $jobvalue['GStoragemaxbackups'];
         unset($jobvalue['GStorageAccessKey'], $jobvalue['GStorageSecret'], $jobvalue['GStorageBucket'], $jobvalue['GStoragedir'], $jobvalue['GStoragemaxbackups']);
         //convert MS Azure storage
         $jobvalue['msazureaccname'] = $jobvalue['msazureAccName'];
         $jobvalue['msazurekey'] = BackWPup_Encryption::encrypt($jobvalue['msazureKey']);
         $jobvalue['msazurecontainer'] = $jobvalue['msazureContainer'];
         unset($jobvalue['msazureHost'], $jobvalue['msazureAccName'], $jobvalue['msazureKey'], $jobvalue['msazureContainer']);
         //convert FTP
         if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $jobvalue['ftppass'])) {
             $jobvalue['ftppass'] = base64_decode($jobvalue['ftppass']);
         }
         $jobvalue['ftppass'] = BackWPup_Encryption::encrypt($jobvalue['ftppass']);
         if (!empty($jobvalue['ftphost']) && strstr($jobvalue['ftphost'], ':')) {
             list($jobvalue['ftphost'], $jobvalue['ftphostport']) = explode(':', $jobvalue['ftphost'], 2);
         }
         //convert Sugarsync
         //convert Mail
         $jobvalue['emailaddress'] = $jobvalue['mailaddress'];
         $jobvalue['emailefilesize'] = $jobvalue['mailefilesize'];
         unset($jobvalue['mailaddress'], $jobvalue['mailefilesize']);
         //convert RSC
         $jobvalue['rscusername'] = $jobvalue['rscUsername'];
         $jobvalue['rscapikey'] = $jobvalue['rscAPIKey'];
         $jobvalue['rsccontainer'] = $jobvalue['rscContainer'];
         //convert jobtype DB Dump
         $jobvalue['dbdumpexclude'] = $jobvalue['dbexclude'];
         unset($jobvalue['dbexclude'], $jobvalue['dbshortinsert']);
         //convert jobtype DBDUMP, DBCHECK
         $jobvalue['dbcheckrepair'] = TRUE;
         unset($jobvalue['maintenance']);
         //convert jobtype wpexport
         //convert jobtype file
         $excludes = array();
         foreach ($jobvalue['backuprootexcludedirs'] as $folder) {
             $excludes[] = basename($folder);
         }
         $jobvalue['backuprootexcludedirs'] = $excludes;
         $excludes = array();
         foreach ($jobvalue['backupcontentexcludedirs'] as $folder) {
             $excludes[] = basename($folder);
         }
         $jobvalue['backupcontentexcludedirs'] = $excludes;
         $excludes = array();
         foreach ($jobvalue['backuppluginsexcludedirs'] as $folder) {
             $excludes[] = basename($folder);
         }
         $jobvalue['backuppluginsexcludedirs'] = $excludes;
         $excludes = array();
         foreach ($jobvalue['backupthemesexcludedirs'] as $folder) {
             $excludes[] = basename($folder);
         }
         $jobvalue['backupthemesexcludedirs'] = $excludes;
         $excludes = array();
         foreach ($jobvalue['backupuploadsexcludedirs'] as $folder) {
             $excludes[] = basename($folder);
         }
         $jobvalue['backupuploadsexcludedirs'] = $excludes;
         //delete not longer needed
         unset($jobvalue['cronnextrun'], $jobvalue['fileprefix'], $jobvalue['fileformart'], $jobvalue['scheduleintervaltype'], $jobvalue['scheduleintervalteimes'], $jobvalue['scheduleinterval'], $jobvalue['dropemail'], $jobvalue['dropepass'], $jobvalue['dropesignmethod']);
         //save in options
         foreach ($jobvalue as $jobvaluename => $jobvaluevalue) {
             BackWPup_Option::update($jobvalue['jobid'], $jobvaluename, $jobvaluevalue);
         }
     }
     set_site_transient('backwpup_upgrade_from_version_two', TRUE, 3600 * 24 * 7);
 }
 /**
  * @param $job_object
  * @return bool
  */
 public function job_run_archive(BackWPup_Job $job_object)
 {
     $job_object->substeps_todo = 2 + $job_object->backup_filesize;
     if ($job_object->steps_data[$job_object->step_working]['SAVE_STEP_TRY'] != $job_object->steps_data[$job_object->step_working]['STEP_TRY']) {
         $job_object->log(sprintf(__('%d. Try to send backup file to an FTP server&#160;&hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']), E_USER_NOTICE);
     }
     if (!empty($job_object->job['ftpssl'])) {
         //make SSL FTP connection
         if (function_exists('ftp_ssl_connect')) {
             $ftp_conn_id = ftp_ssl_connect($job_object->job['ftphost'], $job_object->job['ftphostport'], $job_object->job['ftptimeout']);
             if ($ftp_conn_id) {
                 $job_object->log(sprintf(__('Connected via explicit SSL-FTP to server: %s', 'backwpup'), $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport']), E_USER_NOTICE);
             } else {
                 $job_object->log(sprintf(__('Cannot connect via explicit SSL-FTP to server: %s', 'backwpup'), $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport']), E_USER_ERROR);
                 return FALSE;
             }
         } else {
             $job_object->log(__('PHP function to connect with explicit SSL-FTP to server does not exist!', 'backwpup'), E_USER_ERROR);
             return TRUE;
         }
     } else {
         //make normal FTP connection if SSL not work
         $ftp_conn_id = ftp_connect($job_object->job['ftphost'], $job_object->job['ftphostport'], $job_object->job['ftptimeout']);
         if ($ftp_conn_id) {
             $job_object->log(sprintf(__('Connected to FTP server: %s', 'backwpup'), $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport']), E_USER_NOTICE);
         } else {
             $job_object->log(sprintf(__('Cannot connect to FTP server: %s', 'backwpup'), $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport']), E_USER_ERROR);
             return FALSE;
         }
     }
     //FTP Login
     $job_object->log(sprintf(__('FTP client command: %s', 'backwpup'), 'USER ' . $job_object->job['ftpuser']), E_USER_NOTICE);
     if ($loginok = @ftp_login($ftp_conn_id, $job_object->job['ftpuser'], BackWPup_Encryption::decrypt($job_object->job['ftppass']))) {
         $job_object->log(sprintf(__('FTP server response: %s', 'backwpup'), 'User ' . $job_object->job['ftpuser'] . ' logged in.'), E_USER_NOTICE);
     } else {
         //if PHP ftp login don't work use raw login
         $return = ftp_raw($ftp_conn_id, 'USER ' . $job_object->job['ftpuser']);
         $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), $return[0]), E_USER_NOTICE);
         if (substr(trim($return[0]), 0, 3) <= 400) {
             $job_object->log(sprintf(__('FTP client command: %s', 'backwpup'), 'PASS *******'), E_USER_NOTICE);
             $return = ftp_raw($ftp_conn_id, 'PASS ' . BackWPup_Encryption::decrypt($job_object->job['ftppass']));
             if (substr(trim($return[0]), 0, 3) <= 400) {
                 $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), $return[0]), E_USER_NOTICE);
                 $loginok = TRUE;
             } else {
                 $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), $return[0]), E_USER_ERROR);
             }
         }
     }
     if (!$loginok) {
         return FALSE;
     }
     //SYSTYPE
     $job_object->log(sprintf(__('FTP client command: %s', 'backwpup'), 'SYST'), E_USER_NOTICE);
     $systype = ftp_systype($ftp_conn_id);
     if ($systype) {
         $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), $systype), E_USER_NOTICE);
     } else {
         $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), __('Error getting SYSTYPE', 'backwpup')), E_USER_ERROR);
     }
     //set actual ftp dir to ftp dir
     if (empty($job_object->job['ftpdir'])) {
         $job_object->job['ftpdir'] = trailingslashit(ftp_pwd($ftp_conn_id));
     }
     // prepend actual ftp dir if relative dir
     if (substr($job_object->job['ftpdir'], 0, 1) != '/') {
         $job_object->job['ftpdir'] = trailingslashit(ftp_pwd($ftp_conn_id)) . $job_object->job['ftpdir'];
     }
     //test ftp dir and create it if not exists
     if ($job_object->job['ftpdir'] != '/') {
         @ftp_chdir($ftp_conn_id, '/');
         //go to root
         $ftpdirs = explode('/', trim($job_object->job['ftpdir'], '/'));
         foreach ($ftpdirs as $ftpdir) {
             if (empty($ftpdir)) {
                 continue;
             }
             if (!@ftp_chdir($ftp_conn_id, $ftpdir)) {
                 if (@ftp_mkdir($ftp_conn_id, $ftpdir)) {
                     $job_object->log(sprintf(__('FTP Folder "%s" created!', 'backwpup'), $ftpdir), E_USER_NOTICE);
                     ftp_chdir($ftp_conn_id, $ftpdir);
                 } else {
                     $job_object->log(sprintf(__('FTP Folder "%s" cannot be created!', 'backwpup'), $ftpdir), E_USER_ERROR);
                     return FALSE;
                 }
             }
         }
     }
     // Get the current working directory
     $current_ftp_dir = trailingslashit(ftp_pwd($ftp_conn_id));
     if ($job_object->substeps_done == 0) {
         $job_object->log(sprintf(__('FTP current folder is: %s', 'backwpup'), $current_ftp_dir), E_USER_NOTICE);
     }
     //get file size to resume upload
     @clearstatcache();
     $job_object->substeps_done = @ftp_size($ftp_conn_id, $job_object->job['ftpdir'] . $job_object->backup_file);
     if ($job_object->substeps_done == -1) {
         $job_object->substeps_done = 0;
     }
     //PASV
     $job_object->log(sprintf(__('FTP client command: %s', 'backwpup'), 'PASV'), E_USER_NOTICE);
     if ($job_object->job['ftppasv']) {
         if (ftp_pasv($ftp_conn_id, TRUE)) {
             $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), __('Entering passive mode', 'backwpup')), E_USER_NOTICE);
         } else {
             $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), __('Cannot enter passive mode', 'backwpup')), E_USER_WARNING);
         }
     } else {
         if (ftp_pasv($ftp_conn_id, FALSE)) {
             $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), __('Entering normal mode', 'backwpup')), E_USER_NOTICE);
         } else {
             $job_object->log(sprintf(__('FTP server reply: %s', 'backwpup'), __('Cannot enter normal mode', 'backwpup')), E_USER_WARNING);
         }
     }
     if ($job_object->substeps_done < $job_object->backup_filesize) {
         $job_object->log(__('Starting upload to FTP &#160;&hellip;', 'backwpup'), E_USER_NOTICE);
         if ($fp = fopen($job_object->backup_folder . $job_object->backup_file, 'rb')) {
             //go to actual file pos
             fseek($fp, $job_object->substeps_done);
             $ret = ftp_nb_fput($ftp_conn_id, $current_ftp_dir . $job_object->backup_file, $fp, FTP_BINARY, $job_object->substeps_done);
             while ($ret == FTP_MOREDATA) {
                 $job_object->substeps_done = ftell($fp);
                 $job_object->update_working_data();
                 $job_object->do_restart_time();
                 $ret = ftp_nb_continue($ftp_conn_id);
             }
             if ($ret != FTP_FINISHED) {
                 $job_object->log(__('Cannot transfer backup to FTP server!', 'backwpup'), E_USER_ERROR);
                 return FALSE;
             } else {
                 $job_object->substeps_done = $job_object->backup_filesize + 1;
                 $job_object->log(sprintf(__('Backup transferred to FTP server: %s', 'backwpup'), $current_ftp_dir . $job_object->backup_file), E_USER_NOTICE);
                 if (!empty($job_object->job['jobid'])) {
                     BackWPup_Option::update($job_object->job['jobid'], 'lastbackupdownloadurl', "ftp://" . $job_object->job['ftpuser'] . ":" . BackWPup_Encryption::decrypt($job_object->job['ftppass']) . "@" . $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport'] . $current_ftp_dir . $job_object->backup_file);
                 }
             }
             fclose($fp);
         } else {
             $job_object->log(__('Can not open source file for transfer.', 'backwpup'), E_USER_ERROR);
             return FALSE;
         }
     }
     $backupfilelist = array();
     $filecounter = 0;
     $files = array();
     if ($filelist = ftp_nlist($ftp_conn_id, '.')) {
         foreach ($filelist as $file) {
             if (basename($file) != '.' && basename($file) != '..') {
                 if ($job_object->is_backup_archive($file)) {
                     $time = ftp_mdtm($ftp_conn_id, $file);
                     if ($time != -1) {
                         $backupfilelist[$time] = basename($file);
                     } else {
                         $backupfilelist[] = basename($file);
                     }
                 }
                 $files[$filecounter]['folder'] = 'ftp://' . $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport'] . $job_object->job['ftpdir'];
                 $files[$filecounter]['file'] = $job_object->job['ftpdir'] . basename($file);
                 $files[$filecounter]['filename'] = basename($file);
                 $files[$filecounter]['downloadurl'] = 'ftp://' . rawurlencode($job_object->job['ftpuser']) . ':' . rawurlencode(BackWPup_Encryption::decrypt($job_object->job['ftppass'])) . '@' . $job_object->job['ftphost'] . ':' . $job_object->job['ftphostport'] . $job_object->job['ftpdir'] . basename($file);
                 $files[$filecounter]['filesize'] = ftp_size($ftp_conn_id, $file);
                 $files[$filecounter]['time'] = ftp_mdtm($ftp_conn_id, $file);
                 $filecounter++;
             }
         }
     }
     if (!empty($job_object->job['ftpmaxbackups']) && $job_object->job['ftpmaxbackups'] > 0) {
         //Delete old backups
         if (count($backupfilelist) > $job_object->job['ftpmaxbackups']) {
             ksort($backupfilelist);
             $numdeltefiles = 0;
             while ($file = array_shift($backupfilelist)) {
                 if (count($backupfilelist) < $job_object->job['ftpmaxbackups']) {
                     break;
                 }
                 if (ftp_delete($ftp_conn_id, $file)) {
                     //delete files on ftp
                     foreach ($files as $key => $filedata) {
                         if ($filedata['file'] == $job_object->job['ftpdir'] . $file) {
                             unset($files[$key]);
                         }
                     }
                     $numdeltefiles++;
                 } else {
                     $job_object->log(sprintf(__('Cannot delete "%s" on FTP server!', 'backwpup'), $job_object->job['ftpdir'] . $file), E_USER_ERROR);
                 }
             }
             if ($numdeltefiles > 0) {
                 $job_object->log(sprintf(_n('One file deleted on FTP server', '%d files deleted on FTP server', $numdeltefiles, 'backwpup'), $numdeltefiles), E_USER_NOTICE);
             }
         }
     }
     set_site_transient('backwpup_' . $job_object->job['jobid'] . '_ftp', $files, YEAR_IN_SECONDS);
     $job_object->substeps_done++;
     ftp_close($ftp_conn_id);
     return TRUE;
 }
 /**
  * @param $id
  */
 public function edit_form_post_save($id)
 {
     BackWPup_Option::update($id, 'pluginlistfile', sanitize_file_name($_POST['pluginlistfile']));
     if ($_POST['pluginlistfilecompression'] == '' || $_POST['pluginlistfilecompression'] == '.gz' || $_POST['pluginlistfilecompression'] == '.bz2') {
         BackWPup_Option::update($id, 'pluginlistfilecompression', $_POST['pluginlistfilecompression']);
     }
 }
 /**
  * @param $job_object
  * @return bool
  */
 public function job_run_archive(BackWPup_Job $job_object)
 {
     $job_object->substeps_todo = 1;
     if (!empty($job_object->job['jobid'])) {
         BackWPup_Option::update($job_object->job['jobid'], 'lastbackupdownloadurl', add_query_arg(array('page' => 'backwpupbackups', 'action' => 'downloadfolder', 'file' => basename($job_object->backup_file), 'jobid' => $job_object->job['jobid']), network_admin_url('admin.php')));
     }
     //Delete old Backupfiles
     $backupfilelist = array();
     $files = array();
     if (is_writable($job_object->backup_folder) && ($dir = opendir($job_object->backup_folder))) {
         //make file list
         while (FALSE !== ($file = readdir($dir))) {
             if (is_writeable($job_object->backup_folder . $file) && !is_dir($job_object->backup_folder . $file) && !is_link($job_object->backup_folder . $file)) {
                 //list for deletion
                 if ($job_object->is_backup_archive($file)) {
                     $backupfilelist[filemtime($job_object->backup_folder . $file)] = $file;
                 }
             }
         }
         closedir($dir);
     }
     if ($job_object->job['maxbackups'] > 0) {
         if (count($backupfilelist) > $job_object->job['maxbackups']) {
             ksort($backupfilelist);
             $numdeltefiles = 0;
             while ($file = array_shift($backupfilelist)) {
                 if (count($backupfilelist) < $job_object->job['maxbackups']) {
                     break;
                 }
                 unlink($job_object->backup_folder . $file);
                 foreach ($files as $key => $filedata) {
                     if ($filedata['file'] == $job_object->backup_folder . $file) {
                         unset($files[$key]);
                     }
                 }
                 $numdeltefiles++;
             }
             if ($numdeltefiles > 0) {
                 $job_object->log(sprintf(_n('One backup file deleted', '%d backup files deleted', $numdeltefiles, 'backwpup'), $numdeltefiles), E_USER_NOTICE);
             }
         }
     }
     $job_object->substeps_done++;
     return TRUE;
 }
 /**
  *
  */
 public static function load()
 {
     //Create Table
     self::$listtable = new self();
     switch (self::$listtable->current_action()) {
         case 'delete':
             //Delete Job
             if (!current_user_can('backwpup_jobs_edit')) {
                 break;
             }
             if (is_array($_GET['jobs'])) {
                 check_admin_referer('bulk-jobs');
                 foreach ($_GET['jobs'] as $jobid) {
                     wp_clear_scheduled_hook('backwpup_cron', array('id' => $jobid));
                     BackWPup_Option::delete_job($jobid);
                 }
             }
             break;
         case 'copy':
             //Copy Job
             if (!current_user_can('backwpup_jobs_edit')) {
                 break;
             }
             $old_job_id = (int) $_GET['jobid'];
             check_admin_referer('copy-job_' . $_GET['jobid']);
             //create new
             $newjobid = BackWPup_Option::get_job_ids();
             sort($newjobid);
             $newjobid = end($newjobid) + 1;
             $old_options = BackWPup_Option::get_job($old_job_id);
             foreach ($old_options as $key => $option) {
                 if ($key == "jobid") {
                     $option = $newjobid;
                 }
                 if ($key == "name") {
                     $option = __('Copy of', 'backwpup') . ' ' . $option;
                 }
                 if ($key == "activetype") {
                     $option = '';
                 }
                 if ($key == "archivename") {
                     $option = str_replace($_GET['jobid'], $newjobid, $option);
                 }
                 if ($key == "logfile" || $key == "lastbackupdownloadurl" || $key == "lastruntime" || $key == "lastrun") {
                     continue;
                 }
                 BackWPup_Option::update($newjobid, $key, $option);
             }
             break;
         case 'runnow':
             $_GET['jobid'] = (int) $_GET['jobid'];
             if (!empty($_GET['jobid'])) {
                 if (!current_user_can('backwpup_jobs_start')) {
                     wp_die(__('Sorry, you don\'t have permissions to do that.', 'backwpup'));
                 }
                 check_admin_referer('backwpup_job_run-runnowlink');
                 //check temp folder
                 $temp_folder_message = BackWPup_File::check_folder(BackWPup::get_plugin_data('TEMP'), TRUE);
                 BackWPup_Admin::message($temp_folder_message, TRUE);
                 //check log folder
                 $log_folder = get_site_option('backwpup_cfg_logfolder');
                 $log_folder = BackWPup_File::get_absolute_path($log_folder);
                 $log_folder_message = BackWPup_File::check_folder($log_folder);
                 BackWPup_Admin::message($log_folder_message, TRUE);
                 //check backup destinations
                 $job_types = BackWPup::get_job_types();
                 $job_conf_types = BackWPup_Option::get($_GET['jobid'], 'type');
                 $creates_file = FALSE;
                 foreach ($job_types as $id => $job_type_class) {
                     if (in_array($id, $job_conf_types) && $job_type_class->creates_file()) {
                         $creates_file = TRUE;
                         break;
                     }
                 }
                 if ($creates_file) {
                     $job_conf_dests = BackWPup_Option::get($_GET['jobid'], 'destinations');
                     $destinations = 0;
                     /* @var BackWPup_Destinations $dest_class */
                     foreach (BackWPup::get_registered_destinations() as $id => $dest) {
                         if (!in_array($id, $job_conf_dests) || empty($dest['class'])) {
                             continue;
                         }
                         $dest_class = BackWPup::get_destination($id);
                         $job_settings = BackWPup_Option::get_job($_GET['jobid']);
                         if (!$dest_class->can_run($job_settings)) {
                             BackWPup_Admin::message(sprintf(__('The job "%s" destination "%s" is not configured properly', 'backwpup'), esc_attr(BackWPup_Option::get($_GET['jobid'], 'name')), $id), TRUE);
                         }
                         $destinations++;
                     }
                     if ($destinations < 1) {
                         BackWPup_Admin::message(sprintf(__('The job "%s" needs properly configured destinations to run!', 'backwpup'), esc_attr(BackWPup_Option::get($_GET['jobid'], 'name'))), TRUE);
                     }
                 }
                 //check server callback
                 $raw_response = BackWPup_Job::get_jobrun_url('test');
                 $test_result = '';
                 if (is_wp_error($raw_response)) {
                     $test_result .= sprintf(__('The HTTP response test get an error "%s"', 'backwpup'), $raw_response->get_error_message());
                 }
                 $response_code = wp_remote_retrieve_response_code($raw_response);
                 if ($response_code < 200 && $response_code > 204) {
                     $test_result .= sprintf(__('The HTTP response test get a false http status (%s)', 'backwpup'), wp_remote_retrieve_response_code($raw_response));
                 } else {
                     $response_body = wp_remote_retrieve_body($raw_response);
                     if (FALSE === strstr($response_body, 'BackWPup Test')) {
                         $test_result .= sprintf(__('Not expected HTTP response body: %s', 'backwpup'), esc_attr(strip_tags($response_body)));
                     }
                 }
                 if (!empty($test_result)) {
                     BackWPup_Admin::message($test_result, TRUE);
                 }
                 //only start job if messages empty
                 $log_messages = BackWPup_Admin::get_messages();
                 if (empty($log_messages)) {
                     $old_log_file = BackWPup_Option::get($_GET['jobid'], 'logfile');
                     BackWPup_Job::get_jobrun_url('runnow', $_GET['jobid']);
                     usleep(250000);
                     //wait a quarter second
                     $new_log_file = BackWPup_Option::get($_GET['jobid'], 'logfile', NULL, FALSE);
                     //sleep as long as job not started
                     $i = 0;
                     while ($old_log_file == $new_log_file) {
                         usleep(250000);
                         //wait a quarter second for next try
                         $new_log_file = BackWPup_Option::get($_GET['jobid'], 'logfile', NULL, FALSE);
                         //wait maximal 10 sec.
                         if ($i >= 40) {
                             BackWPup_Admin::message(sprintf(__('Job “%s” has started, but not responded for 10 seconds.', 'backwpup'), esc_attr(BackWPup_Option::get($_GET['jobid'], 'name'))), TRUE);
                             break 2;
                         }
                         $i++;
                     }
                     BackWPup_Admin::message(sprintf(__('Job "%s" started.', 'backwpup'), esc_attr(BackWPup_Option::get($_GET['jobid'], 'name'))));
                 }
             }
             break;
         case 'abort':
             //Abort Job
             if (!current_user_can('backwpup_jobs_start')) {
                 break;
             }
             check_admin_referer('abort-job');
             if (!file_exists(BackWPup::get_plugin_data('running_file'))) {
                 break;
             }
             //abort
             BackWPup_Job::user_abort();
             BackWPup_Admin::message(__('Job will be terminated.', 'backwpup'));
             break;
         default:
             do_action('backwpup_page_jobs_load', self::$listtable->current_action());
             break;
     }
     self::$listtable->prepare_items();
 }
Beispiel #14
0
 /**
  * Start job if in cron and run query args are set.
  */
 public static function cron_active($args = array())
 {
     //only if cron active
     if (!defined('DOING_CRON') || !DOING_CRON) {
         return;
     }
     if (isset($_GET['backwpup_run'])) {
         $args['run'] = sanitize_text_field($_GET['backwpup_run']);
     }
     if (isset($_GET['_nonce'])) {
         $args['nonce'] = sanitize_text_field($_GET['_nonce']);
     }
     if (isset($_GET['jobid'])) {
         $args['jobid'] = absint($_GET['jobid']);
     }
     $args = array_merge(array('run' => '', 'nonce' => '', 'jobid' => 0), $args);
     if (!in_array($args['run'], array('test', 'restart', 'runnow', 'runnowalt', 'runext', 'cronrun'), true)) {
         return;
     }
     //special header
     @session_write_close();
     @header('Content-Type: text/html; charset=' . get_bloginfo('charset'), true);
     @header('X-Robots-Tag: noindex, nofollow', true);
     nocache_headers();
     //on test die for fast feedback
     if ($args['run'] === 'test') {
         die('BackWPup test request');
     }
     if ($args['run'] === 'restart') {
         $job_object = BackWPup_Job::get_working_data();
         //restart job if not working or a restart wished
         $not_worked_time = microtime(TRUE) - $job_object->timestamp_last_update;
         if (!$job_object->pid || $not_worked_time > 300) {
             BackWPup_Job::start_http('restart');
             return;
         }
     }
     // generate normal nonce
     $nonce = substr(wp_hash(wp_nonce_tick() . 'backwpup_job_run-' . $args['run'], 'nonce'), -12, 10);
     //special nonce on external start
     if ($args['run'] === 'runext') {
         $nonce = get_site_option('backwpup_cfg_jobrunauthkey');
     }
     if ($args['run'] === 'cronrun') {
         $nonce = '';
     }
     // check nonce
     if ($nonce !== $args['nonce']) {
         return;
     }
     //check runext is allowed for job
     if ($args['run'] === 'runext') {
         $jobids_link = BackWPup_Option::get_job_ids('activetype', 'link');
         $jobids_easycron = BackWPup_Option::get_job_ids('activetype', 'easycron');
         $jobids_external = array_merge($jobids_link, $jobids_easycron);
         if (!in_array($args['jobid'], $jobids_external, true)) {
             return;
         }
     }
     //run BackWPup job
     BackWPup_Job::start_http($args['run'], $args['jobid']);
 }
 /**
  * @param $jobid
  */
 public function edit_form_post_save($jobid)
 {
     BackWPup_Option::update($jobid, 'dbcheckwponly', isset($_POST['dbcheckwponly']) && $_POST['dbcheckwponly'] == 1 ? TRUE : FALSE);
     BackWPup_Option::update($jobid, 'dbcheckrepair', isset($_POST['dbcheckrepair']) && $_POST['dbcheckrepair'] == 1 ? TRUE : FALSE);
 }
 /**
  * @return array
  */
 function get_destinations_list()
 {
     $jobdest = array();
     $jobids = BackWPup_Option::get_job_ids();
     if (!empty($jobids)) {
         foreach ($jobids as $jobid) {
             if (BackWPup_Option::get($jobid, 'backuptype') == 'sync') {
                 // jump over sync
                 continue;
             }
             $dests = BackWPup_Option::get($jobid, 'destinations');
             foreach ($dests as $dest) {
                 if (empty($this->destinations[$dest]['class'])) {
                     continue;
                 }
                 $dest_class = BackWPup::get_destination($dest);
                 $can_do_dest = $dest_class->file_get_list($jobid . '_' . $dest);
                 if (!empty($can_do_dest)) {
                     $jobdest[] = $jobid . '_' . $dest;
                 }
             }
         }
     }
     return $jobdest;
 }
Beispiel #17
0
 public static function status($backwpup_jobid)
 {
     if (empty($backwpup_jobid)) {
         $id = get_site_option('backwpup_cfg_easycronjobid');
     } else {
         $id = BackWPup_Option::get($backwpup_jobid, 'easycronjobid');
     }
     if (empty($id)) {
         return array();
     }
     $cron_job = get_site_transient('backwpup_easycron_' . $id);
     if (!empty($cron_job)) {
         return $cron_job;
     }
     $message = self::query_api('detail', array('id' => $id));
     if ($message['status'] == 'success' && !empty($message['cron_job'])) {
         set_site_transient('backwpup_easycron_' . $id, $message['cron_job'], 3600 - 30);
         return $message['cron_job'];
     } else {
         if ($message['error']['code'] == 25) {
             if (empty($backwpup_jobid)) {
                 delete_site_option('backwpup_cfg_easycronjobid');
             } else {
                 BackWPup_Option::delete($backwpup_jobid, 'easycronjobid');
             }
         }
     }
     return array();
 }
Beispiel #18
0
 /**
  * @param $job_object BAckWPup_Job
  * @return bool
  */
 public function job_run_archive(BackWPup_Job $job_object)
 {
     $job_object->substeps_todo = 2 + $job_object->backup_filesize;
     if ($job_object->steps_data[$job_object->step_working]['SAVE_STEP_TRY'] != $job_object->steps_data[$job_object->step_working]['STEP_TRY']) {
         $job_object->log(sprintf(__('%d. Trying to send backup file to S3 Service&#160;&hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']), E_USER_NOTICE);
     }
     try {
         $s3 = Aws\S3\S3Client::factory(array('key' => $job_object->job['s3accesskey'], 'secret' => BackWPup_Encryption::decrypt($job_object->job['s3secretkey']), 'region' => $job_object->job['s3region'], 'base_url' => $this->get_s3_base_url($job_object->job['s3region'], $job_object->job['s3base_url']), 'scheme' => 'https', 'ssl.certificate_authority' => BackWPup::get_plugin_data('cacert')));
         if ($job_object->steps_data[$job_object->step_working]['SAVE_STEP_TRY'] != $job_object->steps_data[$job_object->step_working]['STEP_TRY'] && $job_object->substeps_done < $job_object->backup_filesize) {
             if ($s3->doesBucketExist($job_object->job['s3bucket'])) {
                 $bucketregion = $s3->getBucketLocation(array('Bucket' => $job_object->job['s3bucket']));
                 $job_object->log(sprintf(__('Connected to S3 Bucket "%1$s" in %2$s', 'backwpup'), $job_object->job['s3bucket'], $bucketregion->get('Location')), E_USER_NOTICE);
             } else {
                 $job_object->log(sprintf(__('S3 Bucket "%s" does not exist!', 'backwpup'), $job_object->job['s3bucket']), E_USER_ERROR);
                 return TRUE;
             }
             if ($job_object->job['s3multipart'] && empty($job_object->steps_data[$job_object->step_working]['UploadId'])) {
                 //Check for aboded Multipart Uploads
                 $job_object->log(__('Checking for not aborted multipart Uploads&#160;&hellip;', 'backwpup'));
                 $multipart_uploads = $s3->listMultipartUploads(array('Bucket' => $job_object->job['s3bucket'], 'Prefix' => (string) $job_object->job['s3dir']));
                 $uploads = $multipart_uploads->get('Uploads');
                 if (!empty($uploads)) {
                     foreach ($uploads as $upload) {
                         $s3->abortMultipartUpload(array('Bucket' => $job_object->job['s3bucket'], 'Key' => $upload['Key'], 'UploadId' => $upload['UploadId']));
                         $job_object->log(sprintf(__('Upload for %s aborted.', 'backwpup'), $upload['Key']));
                     }
                 }
             }
             //transfer file to S3
             $job_object->log(__('Starting upload to S3 Service&#160;&hellip;', 'backwpup'));
         }
         if (!$job_object->job['s3multipart'] || $job_object->backup_filesize < 1048576 * 6) {
             //Prepare Upload
             if (!($up_file_handle = fopen($job_object->backup_folder . $job_object->backup_file, 'rb'))) {
                 $job_object->log(__('Can not open source file for transfer.', 'backwpup'), E_USER_ERROR);
                 return FALSE;
             }
             $create_args = array();
             $create_args['Bucket'] = $job_object->job['s3bucket'];
             $create_args['ACL'] = 'private';
             //encrxption
             if (!empty($job_object->job['s3ssencrypt'])) {
                 $create_args['ServerSideEncryption'] = $job_object->job['s3ssencrypt'];
             }
             //Storage Class
             if (!empty($job_object->job['s3storageclass'])) {
                 $create_args['StorageClass'] = $job_object->job['s3storageclass'];
             }
             $create_args['Metadata'] = array('BackupTime' => date('Y-m-d H:i:s', $job_object->start_time));
             $create_args['Body'] = $up_file_handle;
             $create_args['Key'] = $job_object->job['s3dir'] . $job_object->backup_file;
             $create_args['ContentType'] = $job_object->get_mime_type($job_object->backup_folder . $job_object->backup_file);
             try {
                 $s3->putObject($create_args);
             } catch (Aws\Common\Exception\MultipartUploadException $e) {
                 $job_object->log(E_USER_ERROR, sprintf(__('S3 Service API: %s', 'backwpup'), $e->getMessage()), $e->getFile(), $e->getLine());
                 return FALSE;
             }
         } else {
             //Prepare Upload
             if ($file_handle = fopen($job_object->backup_folder . $job_object->backup_file, 'rb')) {
                 fseek($file_handle, $job_object->substeps_done);
                 try {
                     if (empty($job_object->steps_data[$job_object->step_working]['UploadId'])) {
                         $args = array('ACL' => 'private', 'Bucket' => $job_object->job['s3bucket'], 'ContentType' => $job_object->get_mime_type($job_object->backup_folder . $job_object->backup_file), 'Key' => $job_object->job['s3dir'] . $job_object->backup_file);
                         if (!empty($job_object->job['s3ssencrypt'])) {
                             $args['ServerSideEncryption'] = $job_object->job['s3ssencrypt'];
                         }
                         if (!empty($job_object->job['s3storageclass'])) {
                             $args['StorageClass'] = empty($job_object->job['s3storageclass']) ? '' : $job_object->job['s3storageclass'];
                         }
                         $upload = $s3->createMultipartUpload($args);
                         $job_object->steps_data[$job_object->step_working]['UploadId'] = $upload->get('UploadId');
                         $job_object->steps_data[$job_object->step_working]['Parts'] = array();
                         $job_object->steps_data[$job_object->step_working]['Part'] = 1;
                     }
                     while (!feof($file_handle)) {
                         $chunk_upload_start = microtime(TRUE);
                         $part_data = fread($file_handle, 1048576 * 5);
                         //5MB Minimum part size
                         $part = $s3->uploadPart(array('Bucket' => $job_object->job['s3bucket'], 'UploadId' => $job_object->steps_data[$job_object->step_working]['UploadId'], 'Key' => $job_object->job['s3dir'] . $job_object->backup_file, 'PartNumber' => $job_object->steps_data[$job_object->step_working]['Part'], 'Body' => $part_data));
                         $chunk_upload_time = microtime(TRUE) - $chunk_upload_start;
                         $job_object->substeps_done = $job_object->substeps_done + strlen($part_data);
                         $job_object->steps_data[$job_object->step_working]['Parts'][] = array('ETag' => $part->get('ETag'), 'PartNumber' => $job_object->steps_data[$job_object->step_working]['Part']);
                         $job_object->steps_data[$job_object->step_working]['Part']++;
                         $time_remaining = $job_object->do_restart_time();
                         if ($time_remaining < $chunk_upload_time) {
                             $job_object->do_restart_time(TRUE);
                         }
                         $job_object->update_working_data();
                     }
                     $s3->completeMultipartUpload(array('Bucket' => $job_object->job['s3bucket'], 'UploadId' => $job_object->steps_data[$job_object->step_working]['UploadId'], 'Key' => $job_object->job['s3dir'] . $job_object->backup_file, 'Parts' => $job_object->steps_data[$job_object->step_working]['Parts']));
                 } catch (Exception $e) {
                     $job_object->log(E_USER_ERROR, sprintf(__('S3 Service API: %s', 'backwpup'), $e->getMessage()), $e->getFile(), $e->getLine());
                     if (!empty($job_object->steps_data[$job_object->step_working]['uploadId'])) {
                         $s3->abortMultipartUpload(array('Bucket' => $job_object->job['s3bucket'], 'UploadId' => $job_object->steps_data[$job_object->step_working]['uploadId'], 'Key' => $job_object->job['s3dir'] . $job_object->backup_file));
                     }
                     unset($job_object->steps_data[$job_object->step_working]['UploadId']);
                     unset($job_object->steps_data[$job_object->step_working]['Parts']);
                     unset($job_object->steps_data[$job_object->step_working]['Part']);
                     $job_object->substeps_done = 0;
                     if (is_resource($file_handle)) {
                         fclose($file_handle);
                     }
                     return FALSE;
                 }
                 fclose($file_handle);
             } else {
                 $job_object->log(__('Can not open source file for transfer.', 'backwpup'), E_USER_ERROR);
                 return FALSE;
             }
         }
         $result = $s3->headObject(array('Bucket' => $job_object->job['s3bucket'], 'Key' => $job_object->job['s3dir'] . $job_object->backup_file));
         if ($result->get('ContentLength') == filesize($job_object->backup_folder . $job_object->backup_file)) {
             $job_object->substeps_done = 1 + $job_object->backup_filesize;
             $job_object->log(sprintf(__('Backup transferred to %s.', 'backwpup'), $this->get_s3_base_url($job_object->job['s3region'], $job_object->job['s3base_url']) . '/' . $job_object->job['s3bucket'] . '/' . $job_object->job['s3dir'] . $job_object->backup_file), E_USER_NOTICE);
             if (!empty($job_object->job['jobid'])) {
                 BackWPup_Option::update($job_object->job['jobid'], 'lastbackupdownloadurl', network_admin_url('admin.php') . '?page=backwpupbackups&action=downloads3&file=' . $job_object->job['s3dir'] . $job_object->backup_file . '&jobid=' . $job_object->job['jobid']);
             }
         } else {
             $job_object->log(sprintf(__('Cannot transfer backup to S3! (%1$d) %2$s', 'backwpup'), $result->get("status"), $result->get("Message")), E_USER_ERROR);
         }
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('S3 Service API: %s', 'backwpup'), $e->getMessage()), $e->getFile(), $e->getLine());
         return FALSE;
     }
     try {
         $backupfilelist = array();
         $filecounter = 0;
         $files = array();
         $args = array('Bucket' => $job_object->job['s3bucket'], 'Prefix' => (string) $job_object->job['s3dir']);
         $objects = $s3->getIterator('ListObjects', $args);
         if (is_object($objects)) {
             foreach ($objects as $object) {
                 $file = basename($object['Key']);
                 $changetime = strtotime($object['LastModified']) + get_option('gmt_offset') * 3600;
                 if ($job_object->is_backup_archive($file)) {
                     $backupfilelist[$changetime] = $file;
                 }
                 $files[$filecounter]['folder'] = $this->get_s3_base_url($job_object->job['s3region'], $job_object->job['s3base_url']) . '/' . $job_object->job['s3bucket'] . '/' . dirname($object['Key']);
                 $files[$filecounter]['file'] = $object['Key'];
                 $files[$filecounter]['filename'] = basename($object['Key']);
                 if (!empty($object['StorageClass'])) {
                     $files[$filecounter]['info'] = sprintf(__('Storage Class: %s', 'backwpup'), $object['StorageClass']);
                 }
                 $files[$filecounter]['downloadurl'] = network_admin_url('admin.php') . '?page=backwpupbackups&action=downloads3&file=' . $object['Key'] . '&jobid=' . $job_object->job['jobid'];
                 $files[$filecounter]['filesize'] = $object['Size'];
                 $files[$filecounter]['time'] = $changetime;
                 $filecounter++;
             }
         }
         if ($job_object->job['s3maxbackups'] > 0 && is_object($s3)) {
             //Delete old backups
             if (count($backupfilelist) > $job_object->job['s3maxbackups']) {
                 ksort($backupfilelist);
                 $numdeltefiles = 0;
                 while ($file = array_shift($backupfilelist)) {
                     if (count($backupfilelist) < $job_object->job['s3maxbackups']) {
                         break;
                     }
                     //delete files on S3
                     $args = array('Bucket' => $job_object->job['s3bucket'], 'Key' => $job_object->job['s3dir'] . $file);
                     if ($s3->deleteObject($args)) {
                         foreach ($files as $key => $filedata) {
                             if ($filedata['file'] == $job_object->job['s3dir'] . $file) {
                                 unset($files[$key]);
                             }
                         }
                         $numdeltefiles++;
                     } else {
                         $job_object->log(sprintf(__('Cannot delete backup from %s.', 'backwpup'), $this->get_s3_base_url($job_object->job['s3region'], $job_object->job['s3base_url']) . '/' . $job_object->job['s3bucket'] . '/' . $job_object->job['s3dir'] . $file), E_USER_ERROR);
                     }
                 }
                 if ($numdeltefiles > 0) {
                     $job_object->log(sprintf(_n('One file deleted on S3 Bucket.', '%d files deleted on S3 Bucket', $numdeltefiles, 'backwpup'), $numdeltefiles), E_USER_NOTICE);
                 }
             }
         }
         set_site_transient('backwpup_' . $job_object->job['jobid'] . '_s3', $files, YEAR_IN_SECONDS);
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('S3 Service API: %s', 'backwpup'), $e->getMessage()), $e->getFile(), $e->getLine());
         return FALSE;
     }
     $job_object->substeps_done = 2 + $job_object->backup_filesize;
     return TRUE;
 }
 /**
  * @param $id
  */
 public function edit_form_post_save($id)
 {
     BackWPup_Option::update($id, 'wpexportcontent', $_POST['wpexportcontent']);
     BackWPup_Option::update($id, 'wpexportfile', BackWPup_Job::sanitize_file_name($_POST['wpexportfile']));
     if ($_POST['wpexportfilecompression'] == '' || $_POST['wpexportfilecompression'] == '.gz' || $_POST['wpexportfilecompression'] == '.bz2') {
         BackWPup_Option::update($id, 'wpexportfilecompression', $_POST['wpexportfilecompression']);
     }
 }
 /**
  * Save settings form data
  */
 public static function save_post_form()
 {
     if (!current_user_can('backwpup_settings')) {
         return;
     }
     //set default options if button clicked
     if (isset($_POST['default_settings']) && $_POST['default_settings']) {
         delete_site_option('backwpup_cfg_showadminbar');
         delete_site_option('backwpup_cfg_showfoldersize');
         delete_site_option('backwpup_cfg_jobstepretry');
         delete_site_option('backwpup_cfg_jobmaxexecutiontime');
         delete_site_option('backwpup_cfg_jobziparchivemethod');
         delete_site_option('backwpup_cfg_jobnotranslate');
         delete_site_option('backwpup_cfg_jobwaittimems');
         delete_site_option('backwpup_cfg_jobrunauthkey');
         delete_site_option('backwpup_cfg_maxlogs');
         delete_site_option('backwpup_cfg_gzlogs');
         delete_site_option('backwpup_cfg_protectfolders');
         delete_site_option('backwpup_cfg_httpauthuser');
         delete_site_option('backwpup_cfg_httpauthpassword');
         delete_site_option('backwpup_cfg_logfolder');
         delete_site_option('backwpup_cfg_dropboxappkey');
         delete_site_option('backwpup_cfg_dropboxappsecret');
         delete_site_option('backwpup_cfg_dropboxsandboxappkey');
         delete_site_option('backwpup_cfg_dropboxsandboxappsecret');
         delete_site_option('backwpup_cfg_sugarsynckey');
         delete_site_option('backwpup_cfg_sugarsyncsecret');
         delete_site_option('backwpup_cfg_sugarsyncappid');
         BackWPup_Option::default_site_options();
         BackWPup_Admin::message(__('Settings reset to default', 'backwpup'));
         return;
     }
     update_site_option('backwpup_cfg_showadminbar', isset($_POST['showadminbar']) ? 1 : 0);
     update_site_option('backwpup_cfg_showfoldersize', isset($_POST['showfoldersize']) ? 1 : 0);
     if (100 > $_POST['jobstepretry'] && 0 < $_POST['jobstepretry']) {
         $_POST['jobstepretry'] = abs((int) $_POST['jobstepretry']);
     }
     if (empty($_POST['jobstepretry']) or !is_int($_POST['jobstepretry'])) {
         $_POST['jobstepretry'] = 3;
     }
     update_site_option('backwpup_cfg_jobstepretry', $_POST['jobstepretry']);
     $max_exe_time = abs((int) $_POST['jobmaxexecutiontime']);
     if (!is_int($max_exe_time) || $max_exe_time < 0) {
         $max_exe_time = 0;
     } elseif ($max_exe_time > 300) {
         $max_exe_time = 300;
     }
     update_site_option('backwpup_cfg_jobmaxexecutiontime', $max_exe_time);
     update_site_option('backwpup_cfg_jobziparchivemethod', $_POST['jobziparchivemethod'] == '' || $_POST['jobziparchivemethod'] == 'PclZip' || $_POST['jobziparchivemethod'] == 'ZipArchive' ? $_POST['jobziparchivemethod'] : '');
     update_site_option('backwpup_cfg_jobnotranslate', isset($_POST['jobnotranslate']) ? 1 : 0);
     update_site_option('backwpup_cfg_jobwaittimems', $_POST['jobwaittimems']);
     update_site_option('backwpup_cfg_maxlogs', abs((int) $_POST['maxlogs']));
     update_site_option('backwpup_cfg_gzlogs', isset($_POST['gzlogs']) ? 1 : 0);
     update_site_option('backwpup_cfg_protectfolders', isset($_POST['protectfolders']) ? 1 : 0);
     update_site_option('backwpup_cfg_httpauthuser', $_POST['httpauthuser']);
     update_site_option('backwpup_cfg_httpauthpassword', BackWPup_Encryption::encrypt($_POST['httpauthpassword']));
     $_POST['jobrunauthkey'] = preg_replace('/[^a-zA-Z0-9]/', '', trim($_POST['jobrunauthkey']));
     update_site_option('backwpup_cfg_jobrunauthkey', $_POST['jobrunauthkey']);
     $_POST['logfolder'] = trailingslashit(str_replace('\\', '/', trim(stripslashes($_POST['logfolder']))));
     if ($_POST['logfolder'][0] == '.' || $_POST['logfolder'][0] != '/' && !preg_match('#^[a-zA-Z]:/#', $_POST['logfolder'])) {
         $_POST['logfolder'] = trailingslashit(str_replace('\\', '/', ABSPATH)) . $_POST['logfolder'];
     }
     //set def. folders
     if (empty($_POST['logfolder']) || $_POST['logfolder'] == '/') {
         delete_site_option('backwpup_cfg_logfolder');
         BackWPup_Option::default_site_options();
     } else {
         update_site_option('backwpup_cfg_logfolder', $_POST['logfolder']);
     }
     do_action('backwpup_page_settings_save');
     BackWPup_Admin::message(__('Settings saved', 'backwpup'));
 }
 /**
  * @param $job_object BAckWPup_Job
  * @return bool
  */
 public function job_run_archive(BackWPup_Job $job_object)
 {
     $job_object->substeps_todo = 2 + $job_object->backup_filesize;
     $job_object->substeps_done = 0;
     $job_object->log(sprintf(__('%d. Trying to send backup file to Rackspace cloud &hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']), E_USER_NOTICE);
     try {
         $conn = new OpenCloud\Rackspace(self::get_auth_url_by_region($job_object->job['rscregion']), array('username' => $job_object->job['rscusername'], 'apiKey' => BackWPup_Encryption::decrypt($job_object->job['rscapikey'])));
         //connect to cloud files
         $ostore = $conn->objectStoreService('cloudFiles', $job_object->job['rscregion'], 'publicURL');
         $container = $ostore->getContainer($job_object->job['rsccontainer']);
         $job_object->log(sprintf(__('Connected to Rackspace cloud files container %s', 'backwpup'), $job_object->job['rsccontainer']));
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('Rackspace Cloud API: %s', 'backwpup'), $e->getMessage()), $e->getFile(), $e->getLine());
         return FALSE;
     }
     try {
         //Transfer Backup to Rackspace Cloud
         $job_object->substeps_done = 0;
         $job_object->log(__('Upload to Rackspace cloud started &hellip;', 'backwpup'), E_USER_NOTICE);
         if ($handle = fopen($job_object->backup_folder . $job_object->backup_file, 'rb')) {
             $uploded = $container->uploadObject($job_object->job['rscdir'] . $job_object->backup_file, $handle);
             fclose($handle);
         } else {
             $job_object->log(__('Can not open source file for transfer.', 'backwpup'), E_USER_ERROR);
             return FALSE;
         }
         //			$transfer = $container->setupObjectTransfer( array(
         //															 'name' => $job_object->job[ 'rscdir' ] . $job_object->backup_file,
         //															 'path' => $job_object->backup_folder . $job_object->backup_file,
         //															 'concurrency' => 1,
         //															 'partSize'    => 4 * 1024 * 1024
         //														) );
         //			$uploded = $transfer->upload();
         if ($uploded) {
             $job_object->log(__('Backup File transferred to RSC://', 'backwpup') . $job_object->job['rsccontainer'] . '/' . $job_object->job['rscdir'] . $job_object->backup_file, E_USER_NOTICE);
             $job_object->substeps_done = 1 + $job_object->backup_filesize;
             if (!empty($job_object->job['jobid'])) {
                 BackWPup_Option::update($job_object->job['jobid'], 'lastbackupdownloadurl', network_admin_url('admin.php') . '?page=backwpupbackups&action=downloadrsc&file=' . $job_object->job['rscdir'] . $job_object->backup_file . '&jobid=' . $job_object->job['jobid']);
             }
         } else {
             $job_object->log(__('Cannot transfer backup to Rackspace cloud.', 'backwpup'), E_USER_ERROR);
             return FALSE;
         }
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('Rackspace Cloud API: %s', 'backwpup'), $e->getMessage()), $e->getFile(), $e->getLine());
         return FALSE;
     }
     try {
         $backupfilelist = array();
         $filecounter = 0;
         $files = array();
         $objlist = $container->objectList(array('prefix' => $job_object->job['rscdir']));
         while ($object = $objlist->next()) {
             $file = basename($object->getName());
             if ($job_object->job['rscdir'] . $file == $object->getName()) {
                 //only in the folder and not in complete bucket
                 if ($job_object->is_backup_archive($file)) {
                     $backupfilelist[strtotime($object->getLastModified())] = $object;
                 }
             }
             $files[$filecounter]['folder'] = "RSC://" . $job_object->job['rsccontainer'] . "/" . dirname($object->getName()) . "/";
             $files[$filecounter]['file'] = $object->getName();
             $files[$filecounter]['filename'] = basename($object->getName());
             $files[$filecounter]['downloadurl'] = network_admin_url('admin.php') . '?page=backwpupbackups&action=downloadrsc&file=' . $object->getName() . '&jobid=' . $job_object->job['jobid'];
             $files[$filecounter]['filesize'] = $object->getContentLength();
             $files[$filecounter]['time'] = strtotime($object->getLastModified());
             $filecounter++;
         }
         if (!empty($job_object->job['rscmaxbackups']) && $job_object->job['rscmaxbackups'] > 0) {
             //Delete old backups
             if (count($backupfilelist) > $job_object->job['rscmaxbackups']) {
                 ksort($backupfilelist);
                 $numdeltefiles = 0;
                 while ($file = array_shift($backupfilelist)) {
                     if (count($backupfilelist) < $job_object->job['rscmaxbackups']) {
                         break;
                     }
                     foreach ($files as $key => $filedata) {
                         if ($filedata['file'] == $file->getName()) {
                             unset($files[$key]);
                         }
                     }
                     $file->delete();
                     $numdeltefiles++;
                 }
                 if ($numdeltefiles > 0) {
                     $job_object->log(sprintf(_n('One file deleted on Rackspace cloud container.', '%d files deleted on Rackspace cloud container.', $numdeltefiles, 'backwpup'), $numdeltefiles), E_USER_NOTICE);
                 }
             }
         }
         set_site_transient('backwpup_' . $job_object->job['jobid'] . '_rsc', $files, 60 * 60 * 24 * 7);
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('Rackspace Cloud API: %s', 'backwpup'), $e->getMessage()), $e->getFile(), $e->getLine());
         return FALSE;
     }
     $job_object->substeps_done++;
     return TRUE;
 }
 /**
  * @param $jobid
  */
 public function edit_form_post_save($jobid)
 {
     BackWPup_Option::update($jobid, 'emailaddress', isset($_POST['emailaddress']) ? sanitize_email($_POST['emailaddress']) : '');
     BackWPup_Option::update($jobid, 'emailefilesize', isset($_POST['emailefilesize']) ? (int) $_POST['emailefilesize'] : 0);
     BackWPup_Option::update($jobid, 'emailsndemail', sanitize_email($_POST['emailsndemail']));
     BackWPup_Option::update($jobid, 'emailmethod', $_POST['emailmethod'] == '' || $_POST['emailmethod'] == 'mail' || $_POST['emailmethod'] == 'sendmail' || $_POST['emailmethod'] == 'smtp' ? $_POST['emailmethod'] : '');
     BackWPup_Option::update($jobid, 'emailsendmail', $_POST['emailsendmail']);
     BackWPup_Option::update($jobid, 'emailsndemailname', $_POST['emailsndemailname']);
     BackWPup_Option::update($jobid, 'emailhost', $_POST['emailhost']);
     BackWPup_Option::update($jobid, 'emailhostport', (int) $_POST['emailhostport']);
     BackWPup_Option::update($jobid, 'emailsecure', $_POST['emailsecure'] == 'ssl' || $_POST['emailsecure'] == 'tls' ? $_POST['emailsecure'] : '');
     BackWPup_Option::update($jobid, 'emailuser', $_POST['emailuser']);
     BackWPup_Option::update($jobid, 'emailpass', BackWPup_Encryption::encrypt($_POST['emailpass']));
 }
 /**
  * @param $job_object BackWPup_Job
  * @return bool
  */
 public function job_run_archive(BackWPup_Job $job_object)
 {
     $job_object->substeps_todo = 2 + $job_object->backup_filesize;
     $job_object->log(sprintf(__('%d. Try to send backup to SugarSync&#160;&hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']), E_USER_NOTICE);
     try {
         $sugarsync = new BackWPup_Destination_SugarSync_API($job_object->job['sugarrefreshtoken']);
         //Check Quota
         $user = $sugarsync->user();
         if (!empty($user->nickname)) {
             $job_object->log(sprintf(__('Authenticated to SugarSync with nickname %s', 'backwpup'), $user->nickname), E_USER_NOTICE);
         }
         $sugarsyncfreespase = (double) $user->quota->limit - (double) $user->quota->usage;
         //float fixes bug for display of no free space
         if ($job_object->backup_filesize > $sugarsyncfreespase) {
             $job_object->log(sprintf(_x('Not enough disk space available on SugarSync. Available: %s.', 'Available space on SugarSync', 'backwpup'), size_format($sugarsyncfreespase, 2)), E_USER_ERROR);
             $job_object->substeps_todo = 1 + $job_object->backup_filesize;
             return TRUE;
         } else {
             $job_object->log(sprintf(__('%s available at SugarSync', 'backwpup'), size_format($sugarsyncfreespase, 2)), E_USER_NOTICE);
         }
         //Create and change folder
         $sugarsync->mkdir($job_object->job['sugardir'], $job_object->job['sugarroot']);
         $dirid = $sugarsync->chdir($job_object->job['sugardir'], $job_object->job['sugarroot']);
         //Upload to SugarSync
         $job_object->substeps_done = 0;
         $job_object->log(__('Starting upload to SugarSync&#160;&hellip;', 'backwpup'), E_USER_NOTICE);
         self::$backwpup_job_object =& $job_object;
         $reponse = $sugarsync->upload($job_object->backup_folder . $job_object->backup_file);
         if (is_object($reponse)) {
             if (!empty($job_object->job['jobid'])) {
                 BackWPup_Option::update($job_object->job['jobid'], 'lastbackupdownloadurl', network_admin_url('admin.php') . '?page=backwpupbackups&action=downloadsugarsync&file=' . (string) $reponse . '&jobid=' . $job_object->job['jobid']);
             }
             $job_object->substeps_done++;
             $job_object->log(sprintf(__('Backup transferred to %s', 'backwpup'), 'https://' . $user->nickname . '.sugarsync.com/' . $sugarsync->showdir($dirid) . $job_object->backup_file), E_USER_NOTICE);
         } else {
             $job_object->log(__('Cannot transfer backup to SugarSync!', 'backwpup'), E_USER_ERROR);
             return FALSE;
         }
         $backupfilelist = array();
         $files = array();
         $filecounter = 0;
         $dir = $sugarsync->showdir($dirid);
         $getfiles = $sugarsync->getcontents('file');
         if (is_object($getfiles)) {
             foreach ($getfiles->file as $getfile) {
                 $getfile->displayName = utf8_decode((string) $getfile->displayName);
                 if ($job_object->is_backup_archive($getfile->displayName)) {
                     $backupfilelist[strtotime((string) $getfile->lastModified)] = (string) $getfile->ref;
                 }
                 $files[$filecounter]['folder'] = 'https://' . (string) $user->nickname . '.sugarsync.com/' . $dir;
                 $files[$filecounter]['file'] = (string) $getfile->ref;
                 $files[$filecounter]['filename'] = (string) $getfile->displayName;
                 $files[$filecounter]['downloadurl'] = network_admin_url('admin.php') . '?page=backwpupbackups&action=downloadsugarsync&file=' . (string) $getfile->ref . '&jobid=' . $job_object->job['jobid'];
                 $files[$filecounter]['filesize'] = (int) $getfile->size;
                 $files[$filecounter]['time'] = strtotime((string) $getfile->lastModified) + get_option('gmt_offset') * 3600;
                 $filecounter++;
             }
         }
         if (!empty($job_object->job['sugarmaxbackups']) && $job_object->job['sugarmaxbackups'] > 0) {
             //Delete old backups
             if (count($backupfilelist) > $job_object->job['sugarmaxbackups']) {
                 ksort($backupfilelist);
                 $numdeltefiles = 0;
                 while ($file = array_shift($backupfilelist)) {
                     if (count($backupfilelist) < $job_object->job['sugarmaxbackups']) {
                         break;
                     }
                     $sugarsync->delete($file);
                     //delete files on Cloud
                     foreach ($files as $key => $filedata) {
                         if ($filedata['file'] == $file) {
                             unset($files[$key]);
                         }
                     }
                     $numdeltefiles++;
                 }
                 if ($numdeltefiles > 0) {
                     $job_object->log(sprintf(_n('One file deleted on SugarSync folder', '%d files deleted on SugarSync folder', $numdeltefiles, 'backwpup'), $numdeltefiles), E_USER_NOTICE);
                 }
             }
         }
         set_site_transient('BackWPup_' . $job_object->job['jobid'] . '_SUGARSYNC', $files, 60 * 60 * 24 * 7);
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('SugarSync API: %s', 'backwpup'), $e->getMessage()), $e->getFile(), $e->getLine());
         return FALSE;
     }
     $job_object->substeps_done++;
     return TRUE;
 }
Beispiel #24
0
 /**
  *
  * Called on job stop makes cleanup and terminates the script
  *
  */
 private function end()
 {
     $this->step_working = 'END';
     $this->substeps_todo = 1;
     $abort = FALSE;
     if (!file_exists(BackWPup::get_plugin_data('running_file'))) {
         if (!$this->user_abort) {
             $abort = TRUE;
         }
         $this->log(__('Aborted by user!', 'backwpup'), E_USER_ERROR);
     }
     //delete old logs
     if (get_site_option('backwpup_cfg_maxlogs')) {
         $log_file_list = array();
         $log_folder = trailingslashit(dirname($this->logfile));
         if (is_readable($log_folder) && ($dir = opendir($log_folder))) {
             //make file list
             while (($file = readdir($dir)) !== FALSE) {
                 if (strpos($file, 'backwpup_log_') == 0 && FALSE !== strpos($file, '.html')) {
                     $log_file_list[filemtime($log_folder . $file)] = $file;
                 }
             }
             closedir($dir);
         }
         if (sizeof($log_file_list) > 0) {
             krsort($log_file_list, SORT_NUMERIC);
             $num_delete_files = 0;
             $i = -1;
             foreach ($log_file_list as $log_file) {
                 $i++;
                 if ($i < get_site_option('backwpup_cfg_maxlogs')) {
                     continue;
                 }
                 unlink($log_folder . $log_file);
                 $num_delete_files++;
             }
             if ($num_delete_files > 0) {
                 $this->log(sprintf(_n('One old log deleted', '%d old logs deleted', $num_delete_files, 'backwpup'), $num_delete_files));
             }
         }
     }
     //Display job working time
     if ($this->errors > 0) {
         $this->log(sprintf(__('Job has ended with errors in %s seconds. You must resolve the errors for correct execution.', 'backwpup'), current_time('timestamp') - $this->start_time), E_USER_ERROR);
     } elseif ($this->warnings > 0) {
         $this->log(sprintf(__('Job finished with warnings in %s seconds. Please resolve them for correct execution.', 'backwpup'), current_time('timestamp') - $this->start_time), E_USER_WARNING);
     } else {
         $this->log(sprintf(__('Job done in %s seconds.', 'backwpup'), current_time('timestamp') - $this->start_time, E_USER_NOTICE));
     }
     //Update job options
     if (!empty($this->job['jobid'])) {
         $this->job['lastruntime'] = current_time('timestamp') - $this->start_time;
         BackWPup_Option::update($this->job['jobid'], 'lastruntime', $this->job['lastruntime']);
     }
     //write header info
     if (!empty($this->logfile)) {
         if ($fd = fopen($this->logfile, 'r+')) {
             $filepos = ftell($fd);
             $found = 0;
             while (!feof($fd)) {
                 $line = fgets($fd);
                 if (stripos($line, '<meta name="backwpup_jobruntime"') !== FALSE) {
                     fseek($fd, $filepos);
                     fwrite($fd, str_pad('<meta name="backwpup_jobruntime" content="' . $this->job['lastruntime'] . '" />', 100) . PHP_EOL);
                     $found++;
                 }
                 if (stripos($line, '<meta name="backwpup_backupfilesize"') !== FALSE) {
                     fseek($fd, $filepos);
                     fwrite($fd, str_pad('<meta name="backwpup_backupfilesize" content="' . $this->backup_filesize . '" />', 100) . PHP_EOL);
                     $found++;
                 }
                 if ($found >= 2) {
                     break;
                 }
                 $filepos = ftell($fd);
             }
             fclose($fd);
         }
         //logfile end
         file_put_contents($this->logfile, "</body>" . PHP_EOL . "</html>", FILE_APPEND);
         //Send mail with log
         $sendmail = FALSE;
         if ($this->errors > 0 && !empty($this->job['mailerroronly']) && !empty($this->job['mailaddresslog'])) {
             $sendmail = TRUE;
         }
         if (empty($this->job['mailerroronly']) && !empty($this->job['mailaddresslog'])) {
             $sendmail = TRUE;
         }
         if ($sendmail) {
             //special subject
             $status = __('SUCCESSFUL', 'backwpup');
             $priority = 3;
             //Normal
             if ($this->warnings > 0) {
                 $status = __('WARNING', 'backwpup');
                 $priority = 2;
                 //High
             }
             if ($this->errors > 0) {
                 $status = __('ERROR', 'backwpup');
                 $priority = 1;
                 //Highest
             }
             $subject = sprintf(__('[%3$s] BackWPup log %1$s: %2$s', 'backwpup'), date_i18n('d-M-Y H:i', $this->start_time, TRUE), esc_attr($this->job['name']), $status);
             $headers = array();
             $headers[] = 'Content-Type: text/html; charset=' . get_bloginfo('charset');
             /* $headers[] = 'X-Priority: ' . $priority; */
             // Priority not working with header setting
             if (!empty($this->job['mailaddresssenderlog'])) {
                 if (FALSE === ($start_mail = strpos($this->job['mailaddresssenderlog'], '<'))) {
                     if (FALSE === strpos($this->job['mailaddresssenderlog'], '@')) {
                         $this->job['mailaddresssenderlog'] = '"' . str_replace(array('<', '>', '@'), '', $this->job['mailaddresssenderlog']) . '" <' . get_bloginfo('admin_email') . '>';
                     }
                 } elseif (FALSE === strpos($this->job['mailaddresssenderlog'], '>', $start_mail)) {
                     $this->job['mailaddresssenderlog'] = '"' . str_replace(array('<', '>', '@'), '', substr($this->job['mailaddresssenderlog'], 0, $start_mail)) . '" <' . get_bloginfo('admin_email') . '>';
                 }
                 $headers[] = 'From: ' . $this->job['mailaddresssenderlog'];
             }
             wp_mail($this->job['mailaddresslog'], $subject, file_get_contents($this->logfile), $headers);
         }
     }
     //set done
     $this->substeps_done = 1;
     $this->steps_done[] = 'END';
     //clean up temp
     self::clean_temp_folder();
     //remove shutdown action
     remove_action('shutdown', array($this, 'shutdown'));
     restore_exception_handler();
     restore_error_handler();
     if (!empty($this->run['PHP'])) {
         @ini_set('log_errors', $this->run['PHP']['INI']['LOG_ERRORS']);
         @ini_set('error_log', $this->run['PHP']['INI']['ERROR_LOG']);
         @ini_set('display_errors', $this->run['PHP']['INI']['DISPLAY_ERRORS']);
         @ini_set('html_errors', $this->run['PHP']['INI']['HTML_ERRORS']);
         @ini_set('zlib.output_compression', $this->run['PHP']['INI']['ZLIB_OUTPUT_COMPRESSION']);
         @ini_set('implicit_flush', $this->run['PHP']['INI']['IMPLICIT_FLUSH']);
         @ini_set('error_reporting', $this->run['PHP']['INI']['ERROR_REPORTING']);
         @ini_set('report_memleaks', $this->run['PHP']['INI']['REPORT_MEMLEAKS']);
         if (!empty($this->run['PHP']['ENV']['TEMPDIR'])) {
             @putenv('TMPDIR=' . $this->run['PHP']['ENV']['TEMPDIR']);
         }
     }
     BackWPup_Cron::check_cleanup();
     if ($abort) {
         exit;
     }
 }
Beispiel #25
0
 /**
  *
  * Called on job stop makes cleanup and terminates the script
  *
  */
 private function end()
 {
     $this->step_working = 'END';
     $this->substeps_todo = 1;
     if (!file_exists(BackWPup::get_plugin_data('running_file'))) {
         $this->log(__('Aborted by user!', 'backwpup'), E_USER_ERROR);
     }
     //delete old logs
     if (get_site_option('backwpup_cfg_maxlogs')) {
         $log_file_list = array();
         $log_folder = trailingslashit(dirname($this->logfile));
         if (is_readable($log_folder) && ($dir = opendir($log_folder))) {
             //make file list
             while (($file = readdir($dir)) !== false) {
                 if (strpos($file, 'backwpup_log_') == 0 && false !== strpos($file, '.html')) {
                     $log_file_list[filemtime($log_folder . $file)] = $file;
                 }
             }
             closedir($dir);
         }
         if (sizeof($log_file_list) > 0) {
             krsort($log_file_list, SORT_NUMERIC);
             $num_delete_files = 0;
             $i = -1;
             foreach ($log_file_list as $log_file) {
                 $i++;
                 if ($i < get_site_option('backwpup_cfg_maxlogs')) {
                     continue;
                 }
                 unlink($log_folder . $log_file);
                 $num_delete_files++;
             }
             if ($num_delete_files > 0) {
                 $this->log(sprintf(_n('One old log deleted', '%d old logs deleted', $num_delete_files, 'backwpup'), $num_delete_files));
             }
         }
     }
     //Display job working time
     if ($this->errors > 0) {
         $this->log(sprintf(__('Job has ended with errors in %s seconds. You must resolve the errors for correct execution.', 'backwpup'), current_time('timestamp') - $this->start_time), E_USER_ERROR);
     } elseif ($this->warnings > 0) {
         $this->log(sprintf(__('Job finished with warnings in %s seconds. Please resolve them for correct execution.', 'backwpup'), current_time('timestamp') - $this->start_time), E_USER_WARNING);
     } else {
         $this->log(sprintf(__('Job done in %s seconds.', 'backwpup'), current_time('timestamp') - $this->start_time));
     }
     //Update job options
     $this->job['lastruntime'] = current_time('timestamp') - $this->start_time;
     BackWPup_Option::update($this->job['jobid'], 'lastruntime', $this->job['lastruntime']);
     //write header info
     if (!empty($this->logfile)) {
         if ($fd = fopen($this->logfile, 'r+')) {
             $filepos = ftell($fd);
             $found = 0;
             while (!feof($fd)) {
                 $line = fgets($fd);
                 if (stripos($line, '<meta name="backwpup_jobruntime"') !== false) {
                     fseek($fd, $filepos);
                     fwrite($fd, str_pad('<meta name="backwpup_jobruntime" content="' . $this->job['lastruntime'] . '" />', 100) . PHP_EOL);
                     $found++;
                 }
                 if (stripos($line, '<meta name="backwpup_backupfilesize"') !== false) {
                     fseek($fd, $filepos);
                     fwrite($fd, str_pad('<meta name="backwpup_backupfilesize" content="' . $this->backup_filesize . '" />', 100) . PHP_EOL);
                     $found++;
                 }
                 if ($found >= 2) {
                     break;
                 }
                 $filepos = ftell($fd);
             }
             fclose($fd);
         }
         //Send mail with log
         $sendmail = false;
         if ($this->job['mailaddresslog']) {
             $sendmail = true;
         }
         if ($this->errors === 0 && $this->job['mailerroronly']) {
             $sendmail = false;
         }
         if ($sendmail) {
             //special subject
             $status = __('SUCCESSFUL', 'backwpup');
             if ($this->warnings > 0) {
                 $status = __('WARNING', 'backwpup');
             }
             if ($this->errors > 0) {
                 $status = __('ERROR', 'backwpup');
             }
             $subject = sprintf(__('[%3$s] BackWPup log %1$s: %2$s', 'backwpup'), date_i18n('d-M-Y H:i', $this->start_time, true), esc_attr($this->job['name']), $status);
             $headers = array();
             $headers[] = 'Content-Type: text/html; charset=' . get_bloginfo('charset');
             if ($this->job['mailaddresssenderlog']) {
                 $this->job['mailaddresssenderlog'] = str_replace(array('&lt;', '&gt;'), array('<', '>'), $this->job['mailaddresssenderlog']);
                 $bracket_pos = strpos($this->job['mailaddresssenderlog'], '<');
                 $at_pos = strpos($this->job['mailaddresssenderlog'], '@');
                 if ($bracket_pos === false || $at_pos === false) {
                     $this->job['mailaddresssenderlog'] = str_replace(array('<', '>'), '', $this->job['mailaddresssenderlog']) . ' <' . get_bloginfo('admin_email') . '>';
                 }
                 $headers[] = 'From: ' . $this->job['mailaddresssenderlog'];
             }
             wp_mail($this->job['mailaddresslog'], $subject, file_get_contents($this->logfile), $headers);
         }
     }
     //set done
     $this->substeps_done = 1;
     $this->steps_done[] = 'END';
     //clean up temp
     self::clean_temp_folder();
     //remove shutdown action
     remove_action('shutdown', array($this, 'shutdown'));
     restore_exception_handler();
     restore_error_handler();
     //logfile end
     file_put_contents($this->logfile, "</body>" . PHP_EOL . "</html>", FILE_APPEND);
     BackWPup_Cron::check_cleanup();
     exit;
 }
Beispiel #26
0
 /**
  * Start job if in cron and run query args are set.
  */
 public static function cron_active()
 {
     //only if cron active
     if (!defined('DOING_CRON') || !DOING_CRON) {
         return;
     }
     //only work if backwpup_run as query var ist set and nothing else and the value ist right
     if (empty($_GET['backwpup_run']) || !in_array($_GET['backwpup_run'], array('test', 'restart', 'runnow', 'runnowalt', 'runext', 'cronrun'))) {
         return;
     }
     //special header
     @session_write_close();
     @header('Content-Type: text/html; charset=' . get_bloginfo('charset'), TRUE);
     @header('X-Robots-Tag: noindex, nofollow', TRUE);
     @header('X-BackWPup-Version: ' . BackWPup::get_plugin_data('version'), TRUE);
     nocache_headers();
     //on test die for fast feedback
     if ($_GET['backwpup_run'] == 'test') {
         die('BackWPup Test');
     }
     // generate normal nonce
     $nonce = substr(wp_hash(wp_nonce_tick() . 'backwpup_job_run-' . $_GET['backwpup_run'], 'nonce'), -12, 10);
     //special nonce on external start
     if ($_GET['backwpup_run'] == 'runext') {
         $nonce = get_site_option('backwpup_cfg_jobrunauthkey');
     }
     // check nonce
     if (empty($_GET['_nonce']) || $nonce != $_GET['_nonce']) {
         return;
     }
     //check runext is allowed for job
     if ($_GET['backwpup_run'] == 'runext') {
         $jobids_external = BackWPup_Option::get_job_ids('activetype', 'link');
         if (!isset($_GET['jobid']) || !in_array($_GET['jobid'], $jobids_external)) {
             return;
         }
     }
     //run BackWPup job
     BackWPup_Job::start_http($_GET['backwpup_run']);
     die;
 }
 /**
  * @param $job_object
  * @return bool
  */
 public function job_run_archive(&$job_object)
 {
     $job_object->substeps_todo = $job_object->backup_filesize + 2;
     if ($job_object->steps_data[$job_object->step_working]['SAVE_STEP_TRY'] != $job_object->steps_data[$job_object->step_working]['STEP_TRY']) {
         $job_object->log(sprintf(__('%d. Try sending backup to a Microsoft Azure (Blob)&#160;&hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']), E_USER_NOTICE);
     }
     try {
         set_include_path(get_include_path() . PATH_SEPARATOR . BackWPup::get_plugin_data('plugindir') . '/vendor/PEAR/');
         /* @var $blobRestProxy   WindowsAzure\Blob\BlobRestProxy */
         //https causes an error SSL: Connection reset by peer that is why http
         $blobRestProxy = WindowsAzure\Common\ServicesBuilder::getInstance()->createBlobService('DefaultEndpointsProtocol=http;AccountName=' . $job_object->job['msazureaccname'] . ';AccountKey=' . BackWPup_Encryption::decrypt($job_object->job['msazurekey']));
         if ($job_object->steps_data[$job_object->step_working]['SAVE_STEP_TRY'] != $job_object->steps_data[$job_object->step_working]['STEP_TRY']) {
             //test vor existing container
             $containers = $blobRestProxy->listContainers()->getContainers();
             $container_url = '';
             foreach ($containers as $container) {
                 if ($container->getName() == $job_object->job['msazurecontainer']) {
                     $container_url = $container->getUrl();
                     break;
                 }
             }
             if (empty($container_url)) {
                 $job_object->log(sprintf(__('MS Azure container "%s" does not exist!', 'backwpup'), $job_object->job['msazurecontainer']), E_USER_ERROR);
                 return TRUE;
             } else {
                 $job_object->log(sprintf(__('Connected to MS Azure container "%s".', 'backwpup'), $job_object->job['msazurecontainer']), E_USER_NOTICE);
             }
             $job_object->log(__('Starting upload to MS Azure&#160;&hellip;', 'backwpup'), E_USER_NOTICE);
         }
         //Prepare Upload
         $file_handel = fopen($job_object->backup_folder . $job_object->backup_file, 'rb');
         fseek($file_handel, $job_object->substeps_done);
         if (empty($job_object->steps_data[$job_object->step_working]['BlockList'])) {
             $job_object->steps_data[$job_object->step_working]['BlockList'] = array();
         }
         while (!feof($file_handel)) {
             $chunk_upload_start = microtime(TRUE);
             $block_count = count($job_object->steps_data[$job_object->step_working]['BlockList']) + 1;
             $data = fread($file_handel, 1048576 * 4);
             //4MB
             $block_id = md5($data) . str_pad($block_count, 6, "0", STR_PAD_LEFT);
             $blobRestProxy->createBlobBlock($job_object->job['msazurecontainer'], $job_object->job['msazuredir'] . $job_object->backup_file, $block_id, $data);
             $job_object->steps_data[$job_object->step_working]['BlockList'][] = $block_id;
             $chunk_upload_time = microtime(TRUE) - $chunk_upload_start;
             $job_object->substeps_done = $job_object->substeps_done + strlen($data);
             $time_remaining = $job_object->do_restart_time();
             if ($time_remaining < $chunk_upload_time) {
                 $job_object->do_restart_time(TRUE);
             }
             $job_object->update_working_data();
         }
         fclose($file_handel);
         //crate blog list
         $blocklist = new WindowsAzure\Blob\Models\BlockList();
         foreach ($job_object->steps_data[$job_object->step_working]['BlockList'] as $block_id) {
             $blocklist->addUncommittedEntry($block_id);
         }
         unset($job_object->steps_data[$job_object->step_working]['BlockList']);
         //Commit Blocks
         $blobRestProxy->commitBlobBlocks($job_object->job['msazurecontainer'], $job_object->job['msazuredir'] . $job_object->backup_file, $blocklist->getEntries());
         $job_object->substeps_done++;
         $job_object->log(sprintf(__('Backup transferred to %s', 'backwpup'), $container_url . '/' . $job_object->job['msazuredir'] . $job_object->backup_file), E_USER_NOTICE);
         if (!empty($job_object->job['jobid'])) {
             BackWPup_Option::update($job_object->job['jobid'], 'lastbackupdownloadurl', network_admin_url('admin.php') . '?page=backwpupbackups&action=downloadmsazure&file=' . $job_object->job['msazuredir'] . $job_object->backup_file . '&jobid=' . $job_object->job['jobid']);
         }
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('Microsoft Azure API: %s', 'backwpup'), htmlentities($e->getMessage())), $e->getFile(), $e->getLine());
         $job_object->substeps_done = 0;
         unset($job_object->steps_data[$job_object->step_working]['BlockList']);
         if (isset($file_handel) && is_resource($file_handel)) {
             fclose($file_handel);
         }
         return FALSE;
     }
     try {
         $backupfilelist = array();
         $filecounter = 0;
         $files = array();
         $blob_options = new WindowsAzure\Blob\Models\ListBlobsOptions();
         $blob_options->setPrefix($job_object->job['msazuredir']);
         $blobs = $blobRestProxy->listBlobs($job_object->job['msazurecontainer'], $blob_options)->getBlobs();
         if (is_array($blobs)) {
             foreach ($blobs as $blob) {
                 $file = basename($blob->getName());
                 if ($job_object->is_backup_archive($file)) {
                     $backupfilelist[$blob->getProperties()->getLastModified()->getTimestamp()] = $file;
                 }
                 $files[$filecounter]['folder'] = $container_url . "/" . dirname($blob->getName()) . "/";
                 $files[$filecounter]['file'] = $blob->getName();
                 $files[$filecounter]['filename'] = basename($blob->getName());
                 $files[$filecounter]['downloadurl'] = network_admin_url('admin.php') . '?page=backwpupbackups&action=downloadmsazure&file=' . $blob->getName() . '&jobid=' . $job_object->job['jobid'];
                 $files[$filecounter]['filesize'] = $blob->getProperties()->getContentLength();
                 $files[$filecounter]['time'] = $blob->getProperties()->getLastModified()->getTimestamp() + get_option('gmt_offset') * 3600;
                 $filecounter++;
             }
         }
         // Delete old backups
         if (!empty($job_object->job['msazuremaxbackups']) && $job_object->job['msazuremaxbackups'] > 0) {
             if (count($backupfilelist) > $job_object->job['msazuremaxbackups']) {
                 ksort($backupfilelist);
                 $numdeltefiles = 0;
                 while ($file = array_shift($backupfilelist)) {
                     if (count($backupfilelist) < $job_object->job['msazuremaxbackups']) {
                         break;
                     }
                     $blobRestProxy->deleteBlob($job_object->job['msazurecontainer'], $job_object->job['msazuredir'] . $file);
                     foreach ($files as $key => $filedata) {
                         if ($filedata['file'] == $job_object->job['msazuredir'] . $file) {
                             unset($files[$key]);
                         }
                     }
                     $numdeltefiles++;
                 }
                 if ($numdeltefiles > 0) {
                     $job_object->log(sprintf(_n('One file deleted on Microsoft Azure container.', '%d files deleted on Microsoft Azure container.', $numdeltefiles, 'backwpup'), $numdeltefiles), E_USER_NOTICE);
                 }
             }
         }
         set_site_transient('backwpup_' . $job_object->job['jobid'] . '_msazure', $files, 60 * 60 * 24 * 7);
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('Microsoft Azure API: %s', 'backwpup'), htmlentities($e->getMessage())), $e->getFile(), $e->getLine());
         return FALSE;
     }
     $job_object->substeps_done = $job_object->backup_filesize + 2;
     return TRUE;
 }
Beispiel #28
0
 /**
  *
  */
 public static function load()
 {
     //Create Table
     self::$listtable = new self();
     switch (self::$listtable->current_action()) {
         case 'delete':
             //Delete Job
             if (!current_user_can('backwpup_jobs_edit')) {
                 break;
             }
             if (is_array($_GET['jobs'])) {
                 check_admin_referer('bulk-jobs');
                 foreach ($_GET['jobs'] as $jobid) {
                     wp_clear_scheduled_hook('backwpup_cron', array('id' => absint($jobid)));
                     BackWPup_Option::delete_job(absint($jobid));
                 }
             }
             break;
         case 'copy':
             //Copy Job
             if (!current_user_can('backwpup_jobs_edit')) {
                 break;
             }
             $old_job_id = absint($_GET['jobid']);
             check_admin_referer('copy-job_' . $old_job_id);
             //create new
             $newjobid = BackWPup_Option::get_job_ids();
             sort($newjobid);
             $newjobid = end($newjobid) + 1;
             $old_options = BackWPup_Option::get_job($old_job_id);
             foreach ($old_options as $key => $option) {
                 if ($key === "jobid") {
                     $option = $newjobid;
                 }
                 if ($key === "name") {
                     $option = __('Copy of', 'backwpup') . ' ' . $option;
                 }
                 if ($key === "activetype") {
                     $option = '';
                 }
                 if ($key === "archivename") {
                     $option = str_replace($old_job_id, $newjobid, $option);
                 }
                 if ($key === "logfile" || $key === "lastbackupdownloadurl" || $key === "lastruntime" || $key === "lastrun") {
                     continue;
                 }
                 BackWPup_Option::update($newjobid, $key, $option);
             }
             break;
         case 'runnow':
             $jobid = absint($_GET['jobid']);
             if ($jobid) {
                 if (!current_user_can('backwpup_jobs_start')) {
                     wp_die(__('Sorry, you don\'t have permissions to do that.', 'backwpup'));
                 }
                 check_admin_referer('backwpup_job_run-runnowlink');
                 //check temp folder
                 $temp_folder_message = BackWPup_File::check_folder(BackWPup::get_plugin_data('TEMP'), TRUE);
                 BackWPup_Admin::message($temp_folder_message, TRUE);
                 //check log folder
                 $log_folder = get_site_option('backwpup_cfg_logfolder');
                 $log_folder = BackWPup_File::get_absolute_path($log_folder);
                 $log_folder_message = BackWPup_File::check_folder($log_folder);
                 BackWPup_Admin::message($log_folder_message, TRUE);
                 //check backup destinations
                 $job_types = BackWPup::get_job_types();
                 $job_conf_types = BackWPup_Option::get($jobid, 'type');
                 $creates_file = FALSE;
                 foreach ($job_types as $id => $job_type_class) {
                     if (in_array($id, $job_conf_types, true) && $job_type_class->creates_file()) {
                         $creates_file = TRUE;
                         break;
                     }
                 }
                 if ($creates_file) {
                     $job_conf_dests = BackWPup_Option::get($jobid, 'destinations');
                     $destinations = 0;
                     /* @var BackWPup_Destinations $dest_class */
                     foreach (BackWPup::get_registered_destinations() as $id => $dest) {
                         if (!in_array($id, $job_conf_dests, true) || empty($dest['class'])) {
                             continue;
                         }
                         $dest_class = BackWPup::get_destination($id);
                         $job_settings = BackWPup_Option::get_job($jobid);
                         if (!$dest_class->can_run($job_settings)) {
                             BackWPup_Admin::message(sprintf(__('The job "%s" destination "%s" is not configured properly', 'backwpup'), esc_attr(BackWPup_Option::get($jobid, 'name')), $id), TRUE);
                         }
                         $destinations++;
                     }
                     if ($destinations < 1) {
                         BackWPup_Admin::message(sprintf(__('The job "%s" needs properly configured destinations to run!', 'backwpup'), esc_attr(BackWPup_Option::get($jobid, 'name'))), TRUE);
                     }
                 }
                 //only start job if messages empty
                 $log_messages = BackWPup_Admin::get_messages();
                 if (empty($log_messages)) {
                     $old_log_file = BackWPup_Option::get($jobid, 'logfile');
                     BackWPup_Job::get_jobrun_url('runnow', $jobid);
                     usleep(250000);
                     //wait a quarter second
                     $new_log_file = BackWPup_Option::get($jobid, 'logfile', null, false);
                     //sleep as long as job not started
                     $i = 0;
                     while ($old_log_file === $new_log_file) {
                         usleep(250000);
                         //wait a quarter second for next try
                         $new_log_file = BackWPup_Option::get($jobid, 'logfile', null, false);
                         //wait maximal 10 sec.
                         if ($i >= 40) {
                             BackWPup_Admin::message(sprintf(__('Job "%s" has started, but not responded for 10 seconds. Please check <a href="%s">information</a>.', 'backwpup'), esc_attr(BackWPup_Option::get($jobid, 'name')), network_admin_url('admin.php') . '?page=backwpupsettings#backwpup-tab-information'), true);
                             break 2;
                         }
                         $i++;
                     }
                     BackWPup_Admin::message(sprintf(__('Job "%s" started.', 'backwpup'), esc_attr(BackWPup_Option::get($jobid, 'name'))));
                 }
             }
             break;
         case 'abort':
             //Abort Job
             if (!current_user_can('backwpup_jobs_start')) {
                 break;
             }
             check_admin_referer('abort-job');
             if (!file_exists(BackWPup::get_plugin_data('running_file'))) {
                 break;
             }
             //abort
             BackWPup_Job::user_abort();
             BackWPup_Admin::message(__('Job will be terminated.', 'backwpup'));
             break;
         default:
             do_action('backwpup_page_jobs_load', self::$listtable->current_action());
             break;
     }
     self::$listtable->prepare_items();
 }
 /**
  * @param $job_object
  * @return bool
  */
 public function job_run_archive(&$job_object)
 {
     $job_object->substeps_todo = 2 + $job_object->backup_filesize;
     if ($job_object->steps_data[$job_object->step_working]['SAVE_STEP_TRY'] != $job_object->steps_data[$job_object->step_working]['STEP_TRY']) {
         $job_object->log(sprintf(__('%d. Try to send backup file to Dropbox&#160;&hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']), E_USER_NOTICE);
     }
     try {
         $dropbox = new BackWPup_Destination_Dropbox_API($job_object->job['dropboxroot']);
         // set the tokens
         $dropbox->setOAuthTokens($job_object->job['dropboxtoken'], BackWPup_Encryption::decrypt($job_object->job['dropboxsecret']));
         //get account info
         if ($job_object->steps_data[$job_object->step_working]['SAVE_STEP_TRY'] != $job_object->steps_data[$job_object->step_working]['STEP_TRY']) {
             $info = $dropbox->accountInfo();
             if (!empty($info['uid'])) {
                 $job_object->log(sprintf(__('Authenticated with Dropbox of user %s', 'backwpup'), $info['display_name'] . ' (' . $info['email'] . ')'), E_USER_NOTICE);
             } else {
                 $job_object->log(__('Not Authenticated with Dropbox!', 'backwpup'), E_USER_ERROR);
                 return FALSE;
             }
             // put the file
             $job_object->log(__('Uploading to Dropbox&#160;&hellip;', 'backwpup'), E_USER_NOTICE);
         }
         self::$backwpup_job_object =& $job_object;
         if ($job_object->substeps_done < $job_object->backup_filesize) {
             //only if upload not complete
             $response = $dropbox->upload($job_object->backup_folder . $job_object->backup_file, $job_object->job['dropboxdir'] . $job_object->backup_file);
             if ($response['bytes'] == $job_object->backup_filesize) {
                 if (!empty($job_object->job['jobid'])) {
                     BackWPup_Option::update($job_object->job['jobid'], 'lastbackupdownloadurl', network_admin_url('admin.php') . '?page=backwpupbackups&action=downloaddropbox&file=' . ltrim($response['path'], '/') . '&jobid=' . $job_object->job['jobid']);
                 }
                 $job_object->substeps_done = 1 + $job_object->backup_filesize;
                 $job_object->log(sprintf(__('Backup transferred to %s', 'backwpup'), 'https://api-content.dropbox.com/1/files/' . $job_object->job['dropboxroot'] . $response['path']), E_USER_NOTICE);
             } else {
                 if ($response['bytes'] != $job_object->backup_filesize) {
                     $job_object->log(__('Uploaded file size and local file size don\'t match.', 'backwpup'), E_USER_ERROR);
                 } else {
                     $job_object->log(sprintf(__('Error transfering backup to %s.', 'backwpup') . ' ' . $response['error'], __('Dropbox', 'backwpup')), E_USER_ERROR);
                 }
                 return FALSE;
             }
         }
         $backupfilelist = array();
         $filecounter = 0;
         $files = array();
         $metadata = $dropbox->metadata($job_object->job['dropboxdir']);
         if (is_array($metadata)) {
             foreach ($metadata['contents'] as $data) {
                 if ($data['is_dir'] != TRUE) {
                     $file = basename($data['path']);
                     if ($job_object->is_backup_archive($file)) {
                         $backupfilelist[strtotime($data['modified'])] = $file;
                     }
                     $files[$filecounter]['folder'] = "https://api-content.dropbox.com/1/files/" . $job_object->job['dropboxroot'] . dirname($data['path']) . "/";
                     $files[$filecounter]['file'] = $data['path'];
                     $files[$filecounter]['filename'] = basename($data['path']);
                     $files[$filecounter]['downloadurl'] = network_admin_url('admin.php') . '?page=backwpupbackups&action=downloaddropbox&file=' . $data['path'] . '&jobid=' . $job_object->job['jobid'];
                     $files[$filecounter]['filesize'] = $data['bytes'];
                     $files[$filecounter]['time'] = strtotime($data['modified']) + get_option('gmt_offset') * 3600;
                     $filecounter++;
                 }
             }
         }
         if ($job_object->job['dropboxmaxbackups'] > 0 && is_object($dropbox)) {
             //Delete old backups
             if (count($backupfilelist) > $job_object->job['dropboxmaxbackups']) {
                 ksort($backupfilelist);
                 $numdeltefiles = 0;
                 while ($file = array_shift($backupfilelist)) {
                     if (count($backupfilelist) < $job_object->job['dropboxmaxbackups']) {
                         break;
                     }
                     $response = $dropbox->fileopsDelete($job_object->job['dropboxdir'] . $file);
                     //delete files on Cloud
                     if ($response['is_deleted'] == 'true') {
                         foreach ($files as $key => $filedata) {
                             if ($filedata['file'] == '/' . $job_object->job['dropboxdir'] . $file) {
                                 unset($files[$key]);
                             }
                         }
                         $numdeltefiles++;
                     } else {
                         $job_object->log(sprintf(__('Error while deleting file from Dropbox: %s', 'backwpup'), $file), E_USER_ERROR);
                     }
                 }
                 if ($numdeltefiles > 0) {
                     $job_object->log(sprintf(_n('One file deleted from Dropbox', '%d files deleted on Dropbox', $numdeltefiles, 'backwpup'), $numdeltefiles), E_USER_NOTICE);
                 }
             }
         }
         set_site_transient('backwpup_' . $job_object->job['jobid'] . '_dropbox', $files, 60 * 60 * 24 * 7);
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('Dropbox API: %s', 'backwpup'), htmlentities($e->getMessage())), $e->getFile(), $e->getLine());
         return FALSE;
     }
     $job_object->substeps_done++;
     return TRUE;
 }
Beispiel #30
0
 /**
  *
  */
 public static function load()
 {
     //Create Table
     self::$listtable = new self();
     switch (self::$listtable->current_action()) {
         case 'delete':
             //Delete Job
             if (!current_user_can('backwpup_jobs_edit')) {
                 break;
             }
             if (is_array($_GET['jobs'])) {
                 check_admin_referer('bulk-jobs');
                 foreach ($_GET['jobs'] as $jobid) {
                     wp_clear_scheduled_hook('backwpup_cron', array('id' => $jobid));
                     BackWPup_Option::delete_job($jobid);
                 }
             }
             break;
         case 'copy':
             //Copy Job
             if (!current_user_can('backwpup_jobs_edit')) {
                 break;
             }
             $old_job_id = (int) $_GET['jobid'];
             check_admin_referer('copy-job_' . $_GET['jobid']);
             //create new
             $newjobid = BackWPup_Option::get_job_ids();
             sort($newjobid);
             $newjobid = end($newjobid) + 1;
             $old_options = BackWPup_Option::get_job($old_job_id);
             foreach ($old_options as $key => $option) {
                 if ($key == "jobid") {
                     $option = $newjobid;
                 }
                 if ($key == "name") {
                     $option = __('Copy of', 'backwpup') . ' ' . $option;
                 }
                 if ($key == "activetype") {
                     $option = '';
                 }
                 if ($key == "archivename") {
                     $option = str_replace($_GET['jobid'], $newjobid, $option);
                 }
                 if ($key == "logfile" || $key == "lastbackupdownloadurl" || $key == "lastruntime" || $key == "lastrun") {
                     continue;
                 }
                 BackWPup_Option::update($newjobid, $key, $option);
             }
             break;
         case 'start_cli':
             //Get cmd start file
             if (!current_user_can('backwpup_jobs_start')) {
                 break;
             }
             check_admin_referer('start_cli');
             if (empty($_GET['jobid'])) {
                 break;
             }
             if (FALSE === strpos(PHP_OS, "WIN")) {
                 header("Pragma: public");
                 header("Expires: 0");
                 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                 header("Content-Type: application/octet-stream");
                 header("Content-Disposition: attachment; filename=BackWPup_cmd_start_job_" . $_GET['jobid'] . ".sh;");
                 if (defined('PHP_BINDIR')) {
                     echo "#!/bin/sh" . PHP_EOL;
                 }
                 echo "@\$1php -c \"" . php_ini_loaded_file() . "\" -r \"\$_SERVER[ 'SERVER_ADDR' ] = '" . $_SERVER['SERVER_ADDR'] . "'; \$_SERVER[ 'REMOTE_ADDR' ] = '" . $_SERVER['REMOTE_ADDR'] . "'; \$_SERVER[ 'HTTP_HOST' ] = '" . $_SERVER['HTTP_HOST'] . "'; \$_SERVER[ 'HTTP_USER_AGENT' ] = '" . BackWPup::get_plugin_data('name') . "'; define( 'DOING_CRON', TRUE ); require '" . ABSPATH . "wp-load.php'; if( class_exists( 'BackWPup_Job' ) ) BackWPup_Job::start_cli( " . $_GET['jobid'] . " );\"";
                 die;
             } else {
                 header("Pragma: public");
                 header("Expires: 0");
                 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
                 header("Content-Type: application/octet-stream");
                 header("Content-Disposition: attachment; filename=BackWPup_cmd_start_job_" . $_GET['jobid'] . ".cmd;");
                 echo "@%1php.exe -c \"" . php_ini_loaded_file() . "\" -r \"\$_SERVER[ 'SERVER_ADDR' ] = '" . $_SERVER['SERVER_ADDR'] . "'; \$_SERVER[ 'REMOTE_ADDR' ] = '" . $_SERVER['REMOTE_ADDR'] . "'; \$_SERVER[ 'HTTP_HOST' ] = '" . $_SERVER['HTTP_HOST'] . "'; \$_SERVER[ 'HTTP_USER_AGENT' ] = '" . BackWPup::get_plugin_data('name') . "'; define( 'DOING_CRON', TRUE ); require '" . ABSPATH . "wp-load.php'; if( class_exists( 'BackWPup_Job' ) ) BackWPup_Job::start_cli( " . $_GET['jobid'] . " );\"";
                 die;
             }
             break;
         case 'runnow':
             if (!empty($_GET['jobid'])) {
                 if (!current_user_can('backwpup_jobs_start')) {
                     wp_die(__('Sorry, you don\'t have permissions to do that.', 'backwpup'));
                 }
                 check_admin_referer('backwpup_job_run-runnowlink');
                 //check temp folder
                 BackWPup_Job::check_folder(BackWPup::get_plugin_data('TEMP'), TRUE);
                 //check log folder
                 BackWPup_Job::check_folder(get_site_option('backwpup_cfg_logfolder'));
                 //check server callback
                 $raw_response = BackWPup_Job::get_jobrun_url('test');
                 $test_result = '';
                 if (is_wp_error($raw_response)) {
                     $test_result .= sprintf(__('The HTTP response test get an error "%s"', 'backwpup'), $raw_response->get_error_message());
                 } elseif (200 != wp_remote_retrieve_response_code($raw_response) && 204 != wp_remote_retrieve_response_code($raw_response)) {
                     $test_result .= sprintf(__('The HTTP response test get a false http status (%s)', 'backwpup'), wp_remote_retrieve_response_code($raw_response));
                 }
                 if (!empty($test_result)) {
                     BackWPup_Admin::message($test_result, TRUE);
                 }
                 //only start job if messages empty
                 $log_messages = BackWPup_Admin::get_messages();
                 if (empty($log_messages)) {
                     $old_log_file = BackWPup_Option::get($_GET['jobid'], 'logfile');
                     BackWPup_Job::get_jobrun_url('runnow', $_GET['jobid']);
                     usleep(250000);
                     //wait a quarter second
                     $new_log_file = BackWPup_Option::get($_GET['jobid'], 'logfile', NULL, FALSE);
                     //sleep as long as job not started
                     $i = 0;
                     while ($old_log_file == $new_log_file) {
                         usleep(250000);
                         //wait a quarter second for next try
                         $new_log_file = BackWPup_Option::get($_GET['jobid'], 'logfile', NULL, FALSE);
                         //wait maximal 10 sec.
                         if ($i >= 40) {
                             BackWPup_Admin::message(sprintf(__('Job start for "%s" not answered after 10 seconds.', 'backwpup'), esc_attr(BackWPup_Option::get($_GET['jobid'], 'name'))), TRUE);
                             break 2;
                         }
                         $i++;
                     }
                     BackWPup_Admin::message(sprintf(__('Job "%s" started.', 'backwpup'), esc_attr(BackWPup_Option::get($_GET['jobid'], 'name'))));
                 }
             }
             break;
         case 'abort':
             //Abort Job
             if (!current_user_can('backwpup_jobs_start')) {
                 break;
             }
             check_admin_referer('abort-job');
             if (!file_exists(BackWPup::get_plugin_data('running_file'))) {
                 break;
             }
             //abort
             BackWPup_Job::user_abort();
             BackWPup_Admin::message(__('Job will be terminated.', 'backwpup'));
             break;
         default:
             do_action('backwpup_page_jobs_load', self::$listtable->current_action());
             break;
     }
     self::$listtable->prepare_items();
 }