public function job_run(BackWPup_Job $job_object)
 {
     global $wpdb;
     $job_object->substeps_todo = 1;
     $job_object->log(sprintf(__('%d. Trying to generate a file with installed widget names …', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']));
     //build filename
     if (empty($job_object->temp['widgetlistfile'])) {
         $job_object->temp['widgetlistfile'] = $job_object->generate_filename($job_object->job['widgetlistfile'], 'sql') . $job_object->job['widgetlistfilecompression'];
     }
     $handle = fopen($job_object->temp['widgetlistfile'], 'w');
     if ($handle) {
         $query = "SELECT * FROM {$wpdb->options} WHERE option_name LIKE 'widget_%'";
         $rows = $wpdb->get_results($query);
         $header = '';
         foreach ($rows as $row) {
             $header .= "INSERT INTO {$wpdb->options} (option_name, option_value, autoload) VALUES" . "('" . esc_sql($row->option_name) . "', '" . esc_sql($row->option_value) . "', '" . esc_sql($row->autoload) . "')" . "ON DUPLICATE KEY UPDATE option_value = '" . esc_sql($row->option_value) . "';\n";
         }
         $query = "SELECT * FROM {$wpdb->options} WHERE option_name = 'sidebars_widgets'";
         $rows = $wpdb->get_results($query);
         foreach ($rows as $row) {
             $header .= "INSERT INTO {$wpdb->options} (option_name, option_value, autoload) VALUES" . "('" . esc_sql($row->option_name) . "', '" . esc_sql($row->option_value) . "', '" . esc_sql($row->autoload) . "')" . "ON DUPLICATE KEY UPDATE option_value = '" . esc_sql($row->option_value) . "';\n";
         }
         fwrite($handle, $header);
         fclose($handle);
     } else {
         $job_object->log(__('Can not open target file for writing.', 'backwpup'), E_USER_ERROR);
         return FALSE;
     }
     if ($job_object->temp['widgetlistfile']) {
         $job_object->additional_files_to_backup[] = $job_object->temp['widgetlistfile'];
         $job_object->log(sprintf(__('Added widget list file "%1$s" with %2$s to backup file list.', 'backwpup'), $job_object->temp['widgetlistfile'], size_format($job_object->temp['widgetlistfile']), 2));
     }
     $job_object->substeps_done = 1;
     return TRUE;
 }
Example #2
0
 public static function update($backwpup_jobid)
 {
     $params = array('id' => NULL, 'email_me' => 0, 'log_output_length' => 0, 'testfirst' => 0);
     if (empty($backwpup_jobid)) {
         $params['id'] = get_site_option('backwpup_cfg_easycronjobid');
         $params['cron_job_name'] = sprintf('WordPress on %s', home_url());
         $params['cron_expression'] = '*/5 * * * *';
         $url = BackWPup_Job::get_jobrun_url('runext', 0);
         $url = remove_query_arg('_nonce', $url['url']);
         $url = remove_query_arg('doing_wp_cron', $url);
         $url = remove_query_arg('backwpup_run', $url);
         $url = add_query_arg(array('doing_wp_cron' => ''), $url);
         $cookies = get_site_transient('backwpup_cookies');
         $params['url'] = $url;
         if (!empty($cookies)) {
             $params['cookies'] = http_build_query($cookies);
         }
     } else {
         $params['id'] = BackWPup_Option::get($backwpup_jobid, 'easycronjobid');
         if (empty($params['id'])) {
             $params['id'] = NULL;
         }
         $params['cron_job_name'] = sprintf('BackWPup %s on %s', BackWPup_Option::get($backwpup_jobid, 'name'), home_url());
         $params['cron_expression'] = BackWPup_Option::get($backwpup_jobid, 'cron');
         $url = BackWPup_Job::get_jobrun_url('runext', $backwpup_jobid);
         $cookies = get_site_transient('backwpup_cookies');
         $params['url'] = $url['url'];
         if (!empty($cookies)) {
             $params['cookies'] = http_build_query($cookies);
         }
     }
     if (empty($params['id'])) {
         $message = self::query_api('add', $params);
     } else {
         $message = self::query_api('edit', $params);
     }
     delete_site_transient('backwpup_easycron_' . $params['id']);
     if ($message['status'] == 'success' && !empty($message['cron_job_id'])) {
         if (empty($backwpup_jobid)) {
             update_site_option('backwpup_cfg_easycronjobid', $message['cron_job_id']);
         } else {
             BackWPup_Option::update($backwpup_jobid, 'easycronjobid', $message['cron_job_id']);
         }
         return TRUE;
     } else {
         if ($message['error']['code'] == 25) {
             if (empty($backwpup_jobid)) {
                 delete_site_option('backwpup_cfg_easycronjobid');
             } else {
                 BackWPup_Option::delete($backwpup_jobid, 'easycronjobid');
             }
         }
     }
     return FALSE;
 }
Example #3
0
 /**
  * See Status of a working job
  *
  * @param $args
  * @param $assoc_args
  */
 public function working($args, $assoc_args)
 {
     $job_object = BackWPup_Job::get_working_data();
     if (!is_object($job_object)) {
         WP_CLI::error(__('No job running', 'backwpup'));
     }
     $formatter_args = array('format' => 'table', 'fields' => array('JobID', 'Name', 'Warnings', 'Errors', 'On Step', 'Done'), 'field' => NULL);
     $formatter = new WP_CLI\Formatter($formatter_args);
     $items = array();
     $items[] = array('JobID' => $job_object->job['jobid'], 'Name' => $job_object->job['name'], 'Warnings' => $job_object->warnings, 'Errors' => $job_object->errors, 'On Step' => $job_object->steps_data[$job_object->step_working]['NAME'], 'Done' => $job_object->step_percent . ' / ' . $job_object->substep_percent, 'Last message' => str_replace('…', '...', strip_tags($job_object->lastmsg)));
     $formatter->display_items($items);
     WP_CLI::log('Last Message: ' . str_replace('…', '...', strip_tags($job_object->lastmsg)));
 }
Example #4
0
 /**
  * See Status of a working job
  *
  * @param $args
  * @param $assoc_args
  * @synopsis working
  */
 public function working($args, $assoc_args)
 {
     $job_object = BackWPup_Job::get_working_data();
     if (is_object($job_object)) {
         WP_CLI::error(__('No job running', 'backwpup'));
     }
     WP_CLI::line(__('Running job', 'backwpup'));
     WP_CLI::line('----------------------------------------------------------------------');
     WP_CLI::line(sprintf(__('ID: %1$d Name: %2$s', 'backwpup'), $job_object->job['jobid'], $job_object->job['name']));
     WP_CLI::line(sprintf(__('Warnings: %1$d Errors: %2$d', 'backwpup'), $job_object->warnings, $job_object->errors));
     WP_CLI::line(sprintf(__('Steps in percent: %1$d percent of step: %2$d', 'backwpup'), $job_object->step_percent, $job_object->substep_percent));
     WP_CLI::line(sprintf(__('On step: %s', 'backwpup'), $job_object->steps_data[$job_object->step_working]['NAME']));
     WP_CLI::line(sprintf(__('Last message: %s', 'backwpup'), str_replace('…', '...', strip_tags($job_object->lastmsg))));
 }
Example #5
0
 /**
  *
  */
 function prepare_items()
 {
     $this->job_types = BackWPup::get_job_types();
     $per_page = $this->get_items_per_page('backwpuplogs_per_page');
     if (empty($per_page) || $per_page < 1) {
         $per_page = 20;
     }
     //load logs
     $logfiles = array();
     if (is_readable($this->log_folder) && ($dir = opendir($this->log_folder))) {
         while (($file = readdir($dir)) !== FALSE) {
             $log_file = $this->log_folder . '/' . $file;
             if (is_file($log_file) && is_readable($log_file) && FALSE !== strpos($file, 'backwpup_log_') && FALSE !== strpos($file, '.html')) {
                 $logfiles[] = $file;
             }
         }
         closedir($dir);
     }
     //ordering
     $order = isset($_GET['order']) ? $_GET['order'] : 'desc';
     $orderby = isset($_GET['orderby']) ? $_GET['orderby'] : 'time';
     if ($orderby == 'time') {
         if ($order == 'asc') {
             sort($logfiles);
         } else {
             rsort($logfiles);
         }
     }
     //by page
     $start = intval(($this->get_pagenum() - 1) * $per_page);
     $end = $start + $per_page;
     if ($end > count($logfiles)) {
         $end = count($logfiles);
     }
     $this->items = array();
     $i = -1;
     foreach ($logfiles as $mtime => $logfile) {
         $i++;
         if ($i < $start) {
             continue;
         }
         if ($i >= $end) {
             break;
         }
         $this->items[$mtime] = BackWPup_Job::read_logheader($this->log_folder . '/' . $logfile);
         $this->items[$mtime]['file'] = $logfile;
     }
     $this->set_pagination_args(array('total_items' => count($logfiles), 'per_page' => $per_page, 'orderby' => $orderby, 'order' => $order));
 }
Example #6
0
 /**
  * Set needed filters and actions and load
  */
 private function __construct()
 {
     // Nothing else matters if we're not on the main site
     if (!is_main_site()) {
         return;
     }
     //auto loader
     spl_autoload_register(array($this, 'autoloader'));
     //start upgrade if needed
     if (get_site_option('backwpup_version') != self::get_plugin_data('Version')) {
         BackWPup_Install::activate();
     }
     //load pro features
     if (class_exists('BackWPup_Pro')) {
         BackWPup_Pro::get_instance();
     }
     //WP-Cron
     if (defined('DOING_CRON') && DOING_CRON) {
         if (!empty($_GET['backwpup_run']) && class_exists('BackWPup_Job')) {
             //early disable caches
             BackWPup_Job::disable_caches();
             //add action for running jobs in wp-cron.php
             add_action('wp_loaded', array('BackWPup_Cron', 'cron_active'), PHP_INT_MAX);
         } else {
             //add cron actions
             add_action('backwpup_cron', array('BackWPup_Cron', 'run'));
             add_action('backwpup_check_cleanup', array('BackWPup_Cron', 'check_cleanup'));
         }
         //if in cron the rest is not needed
         return;
     }
     //deactivation hook
     register_deactivation_hook(__FILE__, array('BackWPup_Install', 'deactivate'));
     //Admin bar
     if (get_site_option('backwpup_cfg_showadminbar', FALSE)) {
         add_action('init', array('BackWPup_Adminbar', 'get_instance'));
     }
     //only in backend
     if (is_admin() && class_exists('BackWPup_Admin')) {
         BackWPup_Admin::get_instance();
     }
     //work with wp-cli
     if (defined('WP_CLI') && WP_CLI && method_exists('WP_CLI', 'add_command')) {
         WP_CLI::add_command('backwpup', 'BackWPup_WP_CLI');
     }
 }
Example #7
0
 /**
  * Set needed filters and actions and load
  */
 private function __construct()
 {
     // Nothing else matters if we're not on the main site
     if (!is_main_site()) {
         return;
     }
     //auto loader
     spl_autoload_register(array($this, 'autoloader'));
     //Options
     new BackWPup_Option();
     //start upgrade if needed
     if (get_site_option('backwpup_version') != self::get_plugin_data('Version')) {
         BackWPup_Install::activate();
     }
     //load pro features
     if (class_exists('BackWPup_Pro')) {
         BackWPup_Pro::get_instance();
     }
     //WP-Cron
     if (defined('DOING_CRON') && DOING_CRON) {
         //early disable caches
         if (!empty($_GET['backwpup_run']) && class_exists('BackWPup_Job')) {
             BackWPup_Job::disable_caches();
         }
         // add normal cron actions
         add_action('backwpup_cron', array('BackWPup_Cron', 'run'));
         add_action('backwpup_check_cleanup', array('BackWPup_Cron', 'check_cleanup'));
         // add action for doing thinks if cron active
         // must done in int before wp-cron control
         add_action('init', array('BackWPup_Cron', 'cron_active'), 1);
         // if in cron the rest must not needed
         return;
     }
     //deactivation hook
     register_deactivation_hook(__FILE__, array('BackWPup_Install', 'deactivate'));
     //Things that must do in plugin init
     add_action('init', array($this, 'plugin_init'));
     //only in backend
     if (is_admin() && class_exists('BackWPup_Admin')) {
         BackWPup_Admin::get_instance();
     }
     //work with wp-cli
     if (defined('WP_CLI') && WP_CLI && class_exists('WP_CLI') && class_exists('BackWPup_WP_CLI')) {
         WP_CLI::addCommand('backwpup', 'BackWPup_WP_CLI');
     }
 }
Example #8
0
 /**
  * @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']));
         }
     }
 }
Example #9
0
 /**
  * @param $job_object
  * @return bool
  */
 public function job_run(BackWPup_Job $job_object)
 {
     global $wpdb, $post, $wp_query;
     $wxr_version = '1.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. Trying to create a WordPress export to XML file&#160;&hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']));
         $job_object->steps_data[$job_object->step_working]['wpexportfile'] = BackWPup::get_plugin_data('TEMP') . $job_object->generate_filename($job_object->job['wpexportfile'], 'xml', TRUE);
         $job_object->steps_data[$job_object->step_working]['substep'] = 'header';
         $job_object->steps_data[$job_object->step_working]['post_ids'] = array();
         $job_object->substeps_todo = 10;
         $job_object->substeps_done = 0;
     }
     add_filter('wxr_export_skip_postmeta', array($this, 'wxr_filter_postmeta'), 10, 2);
     if ($job_object->steps_data[$job_object->step_working]['substep'] == 'header') {
         if ('all' != $job_object->job['wpexportcontent'] && post_type_exists($job_object->job['wpexportcontent'])) {
             $ptype = get_post_type_object($job_object->job['wpexportcontent']);
             if (!$ptype->can_export) {
                 $job_object->log(sprintf(__('WP Export: Post type “%s” does not allow export.', 'backwpup'), $job_object->job['wpexportcontent']), E_USER_ERROR);
                 return FALSE;
             }
             $where = $wpdb->prepare("{$wpdb->posts}.post_type = %s", $job_object->job['wpexportcontent']);
         } else {
             $post_types = get_post_types(array('can_export' => true));
             $esses = array_fill(0, count($post_types), '%s');
             $where = $wpdb->prepare("{$wpdb->posts}.post_type IN (" . implode(',', $esses) . ')', $post_types);
             $job_object->job['wpexportcontent'] = 'all';
         }
         $where .= " AND {$wpdb->posts}.post_status != 'auto-draft'";
         // grab a snapshot of post IDs, just in case it changes during the export
         $job_object->steps_data[$job_object->step_working]['post_ids'] = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE {$where}");
         $job_object->substeps_todo = $job_object->substeps_todo + count($job_object->steps_data[$job_object->step_working]['post_ids']);
         $header = '<?xml version="1.0" encoding="' . get_bloginfo('charset') . "\" ?>\n";
         $header .= "<!-- This is a WordPress eXtended RSS file generated by the WordPress plugin BackWPup as an export of your site. -->\n";
         $header .= "<!-- It contains information about your site's posts, pages, comments, categories, and other content. -->\n";
         $header .= "<!-- You may use this file to transfer that content from one site to another. -->\n";
         $header .= "<!-- This file is not intended to serve as a complete backup of your site. -->\n\n";
         $header .= "<!-- To import this information into a WordPress site follow these steps: -->\n";
         $header .= "<!-- 1. Log in to that site as an administrator. -->\n";
         $header .= "<!-- 2. Go to Tools: Import in the WordPress admin panel. -->\n";
         $header .= "<!-- 3. Install the \"WordPress\" importer from the list. -->\n";
         $header .= "<!-- 4. Activate & Run Importer. -->\n";
         $header .= "<!-- 5. Upload this file using the form provided on that page. -->\n";
         $header .= "<!-- 6. You will first be asked to map the authors in this export file to users -->\n";
         $header .= "<!--    on the site. For each author, you may choose to map to an -->\n";
         $header .= "<!--    existing user on the site or to create a new user. -->\n";
         $header .= "<!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. -->\n";
         $header .= "<!--    contained in this file into your site. -->\n\n";
         $header .= "<!-- generator=\"WordPress/" . get_bloginfo_rss('version') . "\" created=\"" . date('Y-m-d H:i') . "\" -->\n";
         $header .= "<rss version=\"2.0\" xmlns:excerpt=\"http://wordpress.org/export/{$wxr_version}/excerpt/\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\" xmlns:wfw=\"http://wellformedweb.org/CommentAPI/\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:wp=\"http://wordpress.org/export/{$wxr_version}/\">\n";
         $header .= "<channel>\n";
         $header .= "\t<title>" . get_bloginfo_rss('name') . "</title>\n";
         $header .= "\t<link>" . get_bloginfo_rss('url') . "</link>\n";
         $header .= "\t<description>" . get_bloginfo_rss('description') . "</description>\n";
         $header .= "\t<pubDate>" . date('D, d M Y H:i:s +0000') . "</pubDate>\n";
         $header .= "\t<language>" . get_bloginfo_rss('language') . "</language>\n";
         $header .= "\t<wp:wxr_version>" . $wxr_version . "</wp:wxr_version>\n";
         $header .= "\t<wp:base_site_url>" . $this->wxr_site_url() . "</wp:base_site_url>\n";
         $header .= "\t<wp:base_blog_url>" . get_bloginfo_rss('url') . "</wp:base_blog_url>\n";
         $written = file_put_contents($job_object->steps_data[$job_object->step_working]['wpexportfile'], $header, FILE_APPEND);
         if ($written === FALSE) {
             $job_object->log(__('WP Export file could not written.', 'backwpup'), E_USER_ERROR);
             return FALSE;
         }
         unset($header);
         $job_object->steps_data[$job_object->step_working]['substep'] = 'authors';
         $job_object->substeps_done++;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->steps_data[$job_object->step_working]['substep'] == 'authors') {
         $written = file_put_contents($job_object->steps_data[$job_object->step_working]['wpexportfile'], $this->wxr_authors_list(), FILE_APPEND);
         if ($written === FALSE) {
             $job_object->log(__('WP Export file could not written.', 'backwpup'), E_USER_ERROR);
             return FALSE;
         }
         $job_object->steps_data[$job_object->step_working]['substep'] = 'cats';
         $job_object->substeps_done++;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->steps_data[$job_object->step_working]['substep'] == 'cats') {
         if ('all' == $job_object->job['wpexportcontent']) {
             $cats = array();
             $categories = (array) get_categories(array('get' => 'all'));
             // put categories in order with no child going before its parent
             while ($cat = array_shift($categories)) {
                 if ($cat->parent == 0 || isset($cats[$cat->parent])) {
                     $cats[$cat->term_id] = $cat;
                 } else {
                     $categories[] = $cat;
                 }
             }
             $cats_xml = '';
             foreach ($cats as $c) {
                 $parent_slug = $c->parent ? $cats[$c->parent]->slug : '';
                 $cats_xml .= "\t<wp:category><wp:term_id>" . $c->term_id . "</wp:term_id><wp:category_nicename>" . $c->slug . "</wp:category_nicename><wp:category_parent>" . $parent_slug . "</wp:category_parent>" . $this->wxr_cat_name($c) . $this->wxr_category_description($c) . "</wp:category>\n";
             }
             $written = file_put_contents($job_object->steps_data[$job_object->step_working]['wpexportfile'], $cats_xml, FILE_APPEND);
             if ($written === FALSE) {
                 $job_object->log(__('WP Export file could not written.', 'backwpup'), E_USER_ERROR);
                 return FALSE;
             }
             unset($cats_xml);
         }
         $job_object->steps_data[$job_object->step_working]['substep'] = 'tags';
         $job_object->substeps_done++;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->steps_data[$job_object->step_working]['substep'] == 'tags') {
         if ('all' == $job_object->job['wpexportcontent']) {
             $tags = (array) get_tags(array('get' => 'all'));
             $tags_xml = '';
             foreach ($tags as $t) {
                 $tags_xml .= "\t<wp:tag><wp:term_id>" . $t->term_id . "</wp:term_id><wp:tag_slug>" . $t->slug . "</wp:tag_slug>" . $this->wxr_tag_name($t) . $this->wxr_tag_description($t) . "</wp:tag>\n";
             }
             $written = file_put_contents($job_object->steps_data[$job_object->step_working]['wpexportfile'], $tags_xml, FILE_APPEND);
             if ($written === FALSE) {
                 $job_object->log(__('WP Export file could not written.', 'backwpup'), E_USER_ERROR);
                 return FALSE;
             }
             unset($tags_xml);
         }
         $job_object->steps_data[$job_object->step_working]['substep'] = 'terms';
         $job_object->substeps_done++;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->steps_data[$job_object->step_working]['substep'] == 'terms') {
         if ('all' == $job_object->job['wpexportcontent']) {
             $terms = array();
             $custom_taxonomies = get_taxonomies(array('_builtin' => false));
             $custom_terms = (array) get_terms($custom_taxonomies, array('get' => 'all'));
             // put terms in order with no child going before its parent
             while ($t = array_shift($custom_terms)) {
                 if ($t->parent == 0 || isset($terms[$t->parent])) {
                     $terms[$t->term_id] = $t;
                 } else {
                     $custom_terms[] = $t;
                 }
             }
             $terms_xml = '';
             foreach ($terms as $t) {
                 $parent_slug = $t->parent ? $terms[$t->parent]->slug : '';
                 $terms_xml .= "\t<wp:term><wp:term_id>" . $t->term_id . "</wp:term_id><wp:term_taxonomy>" . $t->taxonomy . "</wp:term_taxonomy><wp:term_slug>" . $t->slug . "</wp:term_slug><wp:term_parent>" . $parent_slug . "</wp:term_parent>" . $this->wxr_term_name($t) . $this->wxr_term_description($t) . "</wp:term>\n";
             }
             $written = file_put_contents($job_object->steps_data[$job_object->step_working]['wpexportfile'], $terms_xml, FILE_APPEND);
             if ($written === FALSE) {
                 $job_object->log(__('WP Export file could not written.', 'backwpup'), E_USER_ERROR);
                 return FALSE;
             }
             unset($terms_xml);
         }
         $job_object->steps_data[$job_object->step_working]['substep'] = 'menus';
         $job_object->substeps_done++;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->steps_data[$job_object->step_working]['substep'] == 'menus') {
         $menu_xml = '';
         if ('all' == $job_object->job['wpexportcontent']) {
             $menu_xml .= $this->wxr_nav_menu_terms();
         }
         $menu_xml .= "\t<generator>http://wordpress.org/?v=" . get_bloginfo_rss('version') . "</generator>\n";
         $written = file_put_contents($job_object->steps_data[$job_object->step_working]['wpexportfile'], $menu_xml, FILE_APPEND);
         if ($written === FALSE) {
             $job_object->log(__('WP Export file could not written.', 'backwpup'), E_USER_ERROR);
             return FALSE;
         }
         unset($menu_xml);
         $job_object->steps_data[$job_object->step_working]['substep'] = 'posts';
         $job_object->substeps_done++;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->steps_data[$job_object->step_working]['substep'] == 'posts') {
         if (!empty($job_object->steps_data[$job_object->step_working]['post_ids'])) {
             $wp_query->in_the_loop = true;
             // Fake being in the loop.
             // fetch 20 posts at a time rather than loading the entire table into memory
             while ($next_posts = array_splice($job_object->steps_data[$job_object->step_working]['post_ids'], 0, 20)) {
                 $where = 'WHERE ID IN (' . join(',', $next_posts) . ')';
                 $posts = $wpdb->get_results("SELECT * FROM {$wpdb->posts} {$where}");
                 $wxr_post = '';
                 // Begin Loop
                 foreach ($posts as $post) {
                     /* @var WP_Post $post */
                     $is_sticky = is_sticky($post->ID) ? 1 : 0;
                     $wxr_post .= "\t<item>\n";
                     $wxr_post .= "\t\t<title>" . apply_filters('the_title_rss', $post->post_title) . "</title>\n";
                     $wxr_post .= "\t\t<link>" . esc_url(apply_filters('the_permalink_rss', get_permalink($post))) . "</link>\n";
                     $wxr_post .= "\t\t<pubDate>" . mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true, $post), false) . "</pubDate>\n";
                     $wxr_post .= "\t\t<dc:creator>" . $this->wxr_cdata(get_the_author_meta('login', $post->post_author)) . "</dc:creator>\n";
                     $wxr_post .= "\t\t<guid isPermaLink=\"false\">" . esc_url(get_the_guid($post->ID)) . "</guid>\n";
                     $wxr_post .= "\t\t<description></description>\n";
                     $wxr_post .= "\t\t<content:encoded>" . $this->wxr_cdata(apply_filters('the_content_export', $post->post_content)) . "</content:encoded>\n";
                     $wxr_post .= "\t\t<excerpt:encoded>" . $this->wxr_cdata(apply_filters('the_excerpt_export', $post->post_excerpt)) . "</excerpt:encoded>\n";
                     $wxr_post .= "\t\t<wp:post_id>" . $post->ID . "</wp:post_id>\n";
                     $wxr_post .= "\t\t<wp:post_date>" . $post->post_date . "</wp:post_date>\n";
                     $wxr_post .= "\t\t<wp:post_date_gmt>" . $post->post_date_gmt . "</wp:post_date_gmt>\n";
                     $wxr_post .= "\t\t<wp:comment_status>" . $post->comment_status . "</wp:comment_status>\n";
                     $wxr_post .= "\t\t<wp:ping_status>" . $post->ping_status . "</wp:ping_status>\n";
                     $wxr_post .= "\t\t<wp:post_name>" . $post->post_name . "</wp:post_name>\n";
                     $wxr_post .= "\t\t<wp:status>" . $post->post_status . "</wp:status>\n";
                     $wxr_post .= "\t\t<wp:post_parent>" . $post->post_parent . "</wp:post_parent>\n";
                     $wxr_post .= "\t\t<wp:menu_order>" . $post->menu_order . "</wp:menu_order>\n";
                     $wxr_post .= "\t\t<wp:post_type>" . $post->post_type . "</wp:post_type>\n";
                     $wxr_post .= "\t\t<wp:post_password>" . $post->post_password . "</wp:post_password>\n";
                     $wxr_post .= "\t\t<wp:is_sticky>" . $is_sticky . "</wp:is_sticky>\n";
                     if ($post->post_type == 'attachment') {
                         $wxr_post .= "\t\t<wp:attachment_url>" . wp_get_attachment_url($post->ID) . "</wp:attachment_url>\n";
                     }
                     $wxr_post .= $this->wxr_post_taxonomy();
                     $postmeta = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->postmeta} WHERE post_id = %d", $post->ID));
                     foreach ($postmeta as $meta) {
                         if (apply_filters('wxr_export_skip_postmeta', false, $meta->meta_key, $meta)) {
                             continue;
                         }
                         $wxr_post .= "\t\t<wp:postmeta>\n\t\t\t<wp:meta_key>" . $meta->meta_key . "</wp:meta_key>\n\t\t\t<wp:meta_value>" . $this->wxr_cdata($meta->meta_value) . "</wp:meta_value>\n\t\t</wp:postmeta>\n";
                     }
                     $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->comments} WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID));
                     foreach ($comments as $c) {
                         $wxr_post .= "\t\t<wp:comment>\n";
                         $wxr_post .= "\t\t\t<wp:comment_id>" . $c->comment_ID . "</wp:comment_id>\n";
                         $wxr_post .= "\t\t\t<wp:comment_author>" . $this->wxr_cdata($c->comment_author) . "</wp:comment_author>\n";
                         $wxr_post .= "\t\t\t<wp:comment_author_email>" . $c->comment_author_email . "</wp:comment_author_email>\n";
                         $wxr_post .= "\t\t\t<wp:comment_author_url>" . esc_url_raw($c->comment_author_url) . "</wp:comment_author_url>\n";
                         $wxr_post .= "\t\t\t<wp:comment_author_IP>" . $c->comment_author_IP . "</wp:comment_author_IP>\n";
                         $wxr_post .= "\t\t\t<wp:comment_date>" . $c->comment_date . "</wp:comment_date>\n";
                         $wxr_post .= "\t\t\t<wp:comment_date_gmt>" . $c->comment_date_gmt . "</wp:comment_date_gmt>\n";
                         $wxr_post .= "\t\t\t<wp:comment_content>" . $this->wxr_cdata($c->comment_content) . "</wp:comment_content>\n";
                         $wxr_post .= "\t\t\t<wp:comment_approved>" . $c->comment_approved . "</wp:comment_approved>\n";
                         $wxr_post .= "\t\t\t<wp:comment_type>" . $c->comment_type . "</wp:comment_type>\n";
                         $wxr_post .= "\t\t\t<wp:comment_parent>" . $c->comment_parent . "</wp:comment_parent>\n";
                         $wxr_post .= "\t\t\t<wp:comment_user_id>" . $c->user_id . "</wp:comment_user_id>\n";
                         $c_meta = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->commentmeta} WHERE comment_id = %d", $c->comment_ID));
                         foreach ($c_meta as $meta) {
                             $wxr_post .= "\t\t\t<wp:commentmeta>\n\t\t\t\t<wp:meta_key>" . $meta->meta_key . "</wp:meta_key>\n\t\t\t\t<wp:meta_value>" . $this->wxr_cdata($meta->meta_value) . "</wp:meta_value>\n\t\t\t</wp:commentmeta>\n";
                         }
                         $wxr_post .= "\t\t</wp:comment>\n";
                     }
                     $wxr_post .= "\t</item>\n";
                     $job_object->substeps_done++;
                 }
                 $written = file_put_contents($job_object->steps_data[$job_object->step_working]['wpexportfile'], $wxr_post, FILE_APPEND);
                 if ($written === FALSE) {
                     $job_object->log(__('WP Export file could not written.', 'backwpup'), E_USER_ERROR);
                     return FALSE;
                 }
                 $job_object->do_restart_time();
             }
         }
         $written = file_put_contents($job_object->steps_data[$job_object->step_working]['wpexportfile'], "</channel>\n</rss>", FILE_APPEND);
         if ($written === FALSE) {
             $job_object->log(__('WP Export file could not written.', 'backwpup'), E_USER_ERROR);
             return FALSE;
         }
         $job_object->steps_data[$job_object->step_working]['substep'] = 'check';
         $job_object->substeps_done++;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     remove_filter('wxr_export_skip_postmeta', array($this, 'wxr_filter_postmeta'), 10);
     if ($job_object->steps_data[$job_object->step_working]['substep'] == 'check') {
         if (extension_loaded('simplexml') && class_exists('DOMDocument')) {
             $job_object->log(__('Check WP Export file&#160;&hellip;', 'backwpup'));
             $job_object->need_free_memory(filesize($job_object->steps_data[$job_object->step_working]['wpexportfile']) * 2);
             $valid = TRUE;
             $internal_errors = libxml_use_internal_errors(TRUE);
             $dom = new DOMDocument();
             $old_value = NULL;
             if (function_exists('libxml_disable_entity_loader')) {
                 $old_value = libxml_disable_entity_loader(TRUE);
             }
             $success = $dom->loadXML(file_get_contents($job_object->steps_data[$job_object->step_working]['wpexportfile']));
             if (!is_null($old_value)) {
                 libxml_disable_entity_loader($old_value);
             }
             if (!$success || isset($dom->doctype)) {
                 $errors = libxml_get_errors();
                 $valid = FALSE;
                 foreach ($errors as $error) {
                     switch ($error->level) {
                         case LIBXML_ERR_WARNING:
                             $job_object->log(E_USER_WARNING, sprintf(__('XML WARNING (%s): %s', 'backwpup'), $error->code, trim($error->message)), $job_object->steps_data[$job_object->step_working]['wpexportfile'], $error->line);
                             break;
                         case LIBXML_ERR_ERROR:
                             $job_object->log(E_USER_WARNING, sprintf(__('XML RECOVERABLE (%s): %s', 'backwpup'), $error->code, trim($error->message)), $job_object->steps_data[$job_object->step_working]['wpexportfile'], $error->line);
                             break;
                         case LIBXML_ERR_FATAL:
                             $job_object->log(E_USER_WARNING, sprintf(__('XML ERROR (%s): %s', 'backwpup'), $error->code, trim($error->message)), $job_object->steps_data[$job_object->step_working]['wpexportfile'], $error->line);
                             break;
                     }
                 }
             } else {
                 $xml = simplexml_import_dom($dom);
                 unset($dom);
                 // halt if loading produces an error
                 if (!$xml) {
                     $job_object->log(__('There was an error when reading this WXR file', 'backwpup'), E_USER_ERROR);
                     $valid = FALSE;
                 } else {
                     $wxr_version = $xml->xpath('/rss/channel/wp:wxr_version');
                     if (!$wxr_version) {
                         $job_object->log(__('This does not appear to be a WXR file, missing/invalid WXR version number', 'backwpup'), E_USER_ERROR);
                         $valid = FALSE;
                     }
                     $wxr_version = (string) trim($wxr_version[0]);
                     // confirm that we are dealing with the correct file format
                     if (!preg_match('/^\\d+\\.\\d+$/', $wxr_version)) {
                         $job_object->log(__('This does not appear to be a WXR file, missing/invalid WXR version number', 'backwpup'), E_USER_ERROR);
                         $valid = FALSE;
                     }
                 }
             }
             libxml_use_internal_errors($internal_errors);
             if ($valid) {
                 $job_object->log(__('WP Export file is a valid WXR file.', 'backwpup'));
             }
         } else {
             $job_object->log(__('WP Export file can not be checked, because no XML extension is loaded, to ensure the file verification.', 'backwpup'));
         }
         $job_object->steps_data[$job_object->step_working]['substep'] = 'compress';
         $job_object->substeps_done++;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     //Compress file
     if ($job_object->steps_data[$job_object->step_working]['substep'] == 'compress') {
         if (!empty($job_object->job['wpexportfilecompression'])) {
             $job_object->log(__('Compressing file&#160;&hellip;', 'backwpup'));
             try {
                 $compress = new BackWPup_Create_Archive($job_object->steps_data[$job_object->step_working]['wpexportfile'] . $job_object->job['wpexportfilecompression']);
                 if ($compress->add_file($job_object->steps_data[$job_object->step_working]['wpexportfile'])) {
                     unset($compress);
                     unlink($job_object->steps_data[$job_object->step_working]['wpexportfile']);
                     $job_object->steps_data[$job_object->step_working]['wpexportfile'] .= $job_object->job['wpexportfilecompression'];
                     $job_object->log(__('Compressing done.', 'backwpup'));
                 }
             } catch (Exception $e) {
                 $job_object->log($e->getMessage(), E_USER_ERROR, $e->getFile(), $e->getLine());
                 unset($compress);
                 return FALSE;
             }
         }
         $job_object->steps_data[$job_object->step_working]['substep'] = 'addfile';
         $job_object->substeps_done++;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->steps_data[$job_object->step_working]['substep'] == 'addfile') {
         //add XML file to backup files
         if (is_readable($job_object->steps_data[$job_object->step_working]['wpexportfile'])) {
             $job_object->additional_files_to_backup[] = $job_object->steps_data[$job_object->step_working]['wpexportfile'];
             $filesize = filesize($job_object->steps_data[$job_object->step_working]['wpexportfile']);
             $job_object->log(sprintf(__('Added XML export "%1$s" with %2$s to backup file list.', 'backwpup'), basename($job_object->steps_data[$job_object->step_working]['wpexportfile']), size_format($filesize, 2)));
         }
         $job_object->substeps_done++;
         $job_object->update_working_data();
     }
     return TRUE;
 }
Example #10
0
 /**
  * @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;
 }
    /**
     * Page Output
     */
    public static function page()
    {
        global $wpdb;
        ?>
    <div class="wrap" id="backwpup-page">
		<h1><?php 
        echo sprintf(__('%s &rsaquo; Settings', 'backwpup'), BackWPup::get_plugin_data('name'));
        ?>
</h1>
		<?php 
        $tabs = array('general' => __('General', 'backwpup'), 'job' => __('Jobs', 'backwpup'), 'log' => __('Logs', 'backwpup'), 'net' => __('Network', 'backwpup'), 'apikey' => __('API Keys', 'backwpup'), 'information' => __('Information', 'backwpup'));
        $tabs = apply_filters('backwpup_page_settings_tab', $tabs);
        echo '<h2 class="nav-tab-wrapper">';
        foreach ($tabs as $id => $name) {
            echo '<a href="#backwpup-tab-' . esc_attr($id) . '" class="nav-tab">' . esc_attr($name) . '</a>';
        }
        echo '</h2>';
        BackWPup_Admin::display_messages();
        ?>

    <form id="settingsform" action="<?php 
        echo admin_url('admin-post.php');
        ?>
" method="post">
		<?php 
        wp_nonce_field('backwpupsettings_page');
        ?>
        <input type="hidden" name="page" value="backwpupsettings" />
	    <input type="hidden" name="action" value="backwpup" />
    	<input type="hidden" name="anchor" value="#backwpup-tab-general" />

		<div class="table ui-tabs-hide" id="backwpup-tab-general">

			<h3 class="title"><?php 
        _e('Display Settings', 'backwpup');
        ?>
</h3>
            <p><?php 
        _e('Do you want to see BackWPup in the WordPress admin bar?', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><?php 
        _e('Admin bar', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Admin Bar', 'backwpup');
        ?>
</span></legend>
                            <label for="showadminbarmenu">
                                <input name="showadminbarmenu" type="checkbox" id="showadminbarmenu" value="1" <?php 
        checked(get_site_option('backwpup_cfg_showadminbar'), TRUE);
        ?>
 />
								<?php 
        _e('Show BackWPup links in admin bar.', 'backwpup');
        ?>
                            </label>
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php 
        _e('Folder sizes', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Folder sizes', 'backwpup');
        ?>
</span></legend>
                            <label for="showfoldersize">
                                <input name="showfoldersize" type="checkbox" id="showfoldersize" value="1" <?php 
        checked(get_site_option('backwpup_cfg_showfoldersize'), TRUE);
        ?>
 />
								<?php 
        _e('Display folder sizes in the files tab when editing a job. (Might increase loading time of files tab.)', 'backwpup');
        ?>
                            </label>
                        </fieldset>
                    </td>
                </tr>
            </table>
			<h3 class="title"><?php 
        _e('Security', 'backwpup');
        ?>
</h3>
			<p><?php 
        _e('Security option for BackWPup', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><?php 
        _e('Protect folders', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Protect folders', 'backwpup');
        ?>
</span></legend>
                            <label for="protectfolders">
                                <input name="protectfolders" type="checkbox" id="protectfolders" value="1" <?php 
        checked(get_site_option('backwpup_cfg_protectfolders'), TRUE);
        ?>
 />
								<?php 
        _e('Protect BackWPup folders ( Temp, Log and Backups ) with <code>.htaccess</code> and <code>index.php</code>', 'backwpup');
        ?>
                            </label>
                        </fieldset>
                    </td>
                </tr>
            </table>

			<?php 
        do_action('backwpup_page_settings_tab_generel');
        ?>

		</div>

        <div class="table ui-tabs-hide" id="backwpup-tab-log">

            <p><?php 
        _e('Every time BackWPup runs a backup job, a log file is being generated. Choose where to store your log files and how many of them.', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="logfolder"><?php 
        _e('Log file folder', 'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="logfolder" type="text" id="logfolder" value="<?php 
        echo esc_attr(get_site_option('backwpup_cfg_logfolder'));
        ?>
" class="regular-text code"/>
	                    <p class="description"><?php 
        echo sprintf(__('You can use absolute or relative path! Relative path is relative to %s.', 'backwpup'), '<code>' . trailingslashit(str_replace('\\', '/', WP_CONTENT_DIR)) . '</code>');
        ?>
</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="maxlogs"><?php 
        _e('Maximum log files', 'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="maxlogs" type="number" min="0" step="1" id="maxlogs" value="<?php 
        echo absint(get_site_option('backwpup_cfg_maxlogs'));
        ?>
" class="small-text"/>
	                    <?php 
        _e('Maximum log files in folder.', 'backwpup');
        ?>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php 
        _e('Compression', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Compression', 'backwpup');
        ?>
</span></legend>
                            <label for="gzlogs">
                                <input name="gzlogs" type="checkbox" id="gzlogs" value="1" <?php 
        checked(get_site_option('backwpup_cfg_gzlogs'), TRUE);
        if (!function_exists('gzopen')) {
            echo ' disabled="disabled"';
        }
        ?>
 />
								<?php 
        _e('Compress log files with GZip.', 'backwpup');
        ?>
                            </label>
                        </fieldset>
                    </td>
                </tr>
	            <tr>
		            <th scope="row"><?php 
        _e('Logging Level', 'backwpup');
        ?>
</th>
		            <td>
			            <fieldset>
				            <legend class="screen-reader-text"><span><?php 
        _e('Logging Level', 'backwpup');
        ?>
</span></legend>
				            <label for="loglevel">
					            <select name="loglevel" size="1">
						            <option value="normal_translated" <?php 
        selected(get_site_option('backwpup_cfg_loglevel', 'normal_translated'), 'normal_translated');
        ?>
><?php 
        _e('Normal (translated)', 'backwpup');
        ?>
</option>
						            <option value="normal" <?php 
        selected(get_site_option('backwpup_cfg_loglevel'), 'normal');
        ?>
><?php 
        _e('Normal (not translated)', 'backwpup');
        ?>
</option>
						            <option value="debug_translated" <?php 
        selected(get_site_option('backwpup_cfg_loglevel'), 'debug_translated');
        ?>
><?php 
        _e('Debug (translated)', 'backwpup');
        ?>
</option>
						            <option value="debug" <?php 
        selected(get_site_option('backwpup_cfg_loglevel'), 'debug');
        ?>
><?php 
        _e('Debug (not translated)', 'backwpup');
        ?>
</option>
					            </select>
				            </label>
				            <p class="description"><?php 
        esc_attr_e('Debug log has much more informations than normal logs. It is for support and should be handled carefully. For support is the best to use a not translated log file. Usage of not translated logs can reduce the PHP memory usage too.', 'backwpup');
        ?>
</p>
			            </fieldset>
		            </td>
	            </tr>
            </table>

        </div>
        <div class="table ui-tabs-hide" id="backwpup-tab-job">

            <p><?php 
        _e('There are a couple of general options for backup jobs. Set them here.', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="jobstepretry"><?php 
        _e("Maximum number of retries for job steps", 'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="jobstepretry" type="number" min="1" step="1" max="99" id="jobstepretry" value="<?php 
        echo absint(get_site_option('backwpup_cfg_jobstepretry'));
        ?>
" class="small-text" />
                    </td>
                </tr>
				<tr>
                    <th scope="row"><?php 
        _e('Maximum script execution time', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Maximum PHP Script execution time', 'backwpup');
        ?>
</span></legend>
                            <label for="jobmaxexecutiontime">
                                <input name="jobmaxexecutiontime" type="number" min="0" step="1" max="300" id="jobmaxexecutiontime" value="<?php 
        echo absint(get_site_option('backwpup_cfg_jobmaxexecutiontime'));
        ?>
" class="small-text" />
								<?php 
        _e('seconds.', 'backwpup');
        ?>
	                            <p class="description"><?php 
        _e('Job will restart before hitting maximum execution time. Restarts will be disabled on CLI usage. If <code>ALTERNATE_WP_CRON</code> has been defined, WordPress Cron will be used for restarts, so it can take a while. 0 means no maximum.', 'backwpup');
        ?>
</p>
							</label>
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="jobrunauthkey"><?php 
        _e('Key to start jobs externally with an URL', 'backwpup');
        ?>
</label>
                    </th>
                    <td>
                        <input name="jobrunauthkey" type="text" id="jobrunauthkey" value="<?php 
        echo esc_attr(get_site_option('backwpup_cfg_jobrunauthkey'));
        ?>
" class="text code"/>
	                    <p class="description"><?php 
        _e('Will be used to protect job starts from unauthorized person.', 'backwpup');
        ?>
</p>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php 
        _e('Reduce server load', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Reduce server load', 'backwpup');
        ?>
</span></legend>
                            <label for="jobwaittimems">
								<select name="jobwaittimems" size="1">
									<option value="0" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 0);
        ?>
><?php 
        _e('disabled', 'backwpup');
        ?>
</option>
                                    <option value="10000" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 10000);
        ?>
><?php 
        _e('minimum', 'backwpup');
        ?>
</option>
                                    <option value="30000" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 30000);
        ?>
><?php 
        _e('medium', 'backwpup');
        ?>
</option>
                                    <option value="90000" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 90000);
        ?>
><?php 
        _e('maximum', 'backwpup');
        ?>
</option>
                                </select>
                            </label>
	                        <p class="description"><?php 
        _e('This adds short pauses to the process. Can be used to reduce the CPU load.', 'backwpup');
        ?>
</p>
                        </fieldset>
                    </td>
                </tr>
	            <tr>
		            <th scope="row"><?php 
        _e('Empty output on working', 'backwpup');
        ?>
</th>
		            <td>
			            <fieldset>
				            <legend class="screen-reader-text"><span><?php 
        _e('Enable an empty Output on backup working.', 'backwpup');
        ?>
</span></legend>
				            <label for="jobdooutput">
					            <input name="jobdooutput" type="checkbox" id="jobdooutput" value="1" <?php 
        checked(get_site_option('backwpup_cfg_jobdooutput'), TRUE);
        ?>
 />
					            <?php 
        _e('Enable an empty Output on backup working.', 'backwpup');
        ?>
				            </label>
				            <p class="description"><?php 
        _e('This do an empty output on job working. This can help in some situations or can brake the working. You must test it.', 'backwpup');
        ?>
</p>
			            </fieldset>
		            </td>
	            </tr>
            </table>

        </div>

        <div class="table ui-tabs-hide" id="backwpup-tab-net">

			<h3><?php 
        echo sprintf(__('Authentication for <code>%s</code>', 'backwpup'), site_url('wp-cron.php'));
        ?>
</h3>
            <p><?php 
        _e('If you protected your blog with HTTP basic authentication (.htaccess), or you use a Plugin to secure wp-cron.php, then use the authentication methods below.', 'backwpup');
        ?>
</p>
            <?php 
        $authentication = get_site_option('backwpup_cfg_authentication', array('method' => '', 'basic_user' => '', 'basic_password' => '', 'user_id' => 0, 'query_arg' => ''));
        ?>
	        <table class="form-table">
	            <tr>
		            <th scope="row"><?php 
        _e('Authentication method', 'backwpup');
        ?>
</th>
		            <td>
			            <fieldset>
				            <legend class="screen-reader-text"><span><?php 
        _e('Authentication method', 'backwpup');
        ?>
</span></legend>
				            <label for="authentication_method">
					            <select name="authentication_method" id="authentication_method" size="1" >
						            <option value="" <?php 
        selected($authentication['method'], '');
        ?>
><?php 
        _e('none', 'backwpup');
        ?>
</option>
						            <option value="basic" <?php 
        selected($authentication['method'], 'basic');
        ?>
><?php 
        _e('Basic auth', 'backwpup');
        ?>
</option>
						            <option value="user" <?php 
        selected($authentication['method'], 'user');
        ?>
><?php 
        _e('WordPress User', 'backwpup');
        ?>
</option>
						            <option value="query_arg" <?php 
        selected($authentication['method'], 'query_arg');
        ?>
><?php 
        _e('Query argument', 'backwpup');
        ?>
</option>
					            </select>
				            </label>
			            </fieldset>
		            </td>
	            </tr>
                <tr class="authentication_basic" <?php 
        if ($authentication['method'] !== 'basic') {
            echo 'style="display:none"';
        }
        ?>
>
                    <th scope="row"><label for="authentication_basic_user"><?php 
        _e('Basic Auth Username:'******'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="authentication_basic_user" type="text" id="authentication_basic_user" value="<?php 
        echo esc_attr($authentication['basic_user']);
        ?>
" class="regular-text" autocomplete="off" />
                    </td>
                </tr>
                <tr class="authentication_basic" <?php 
        if ($authentication['method'] !== 'basic') {
            echo 'style="display:none"';
        }
        ?>
>
			        <th scope="row"><label for="authentication_basic_password"><?php 
        _e('Basic Auth Password:'******'backwpup');
        ?>
</label></th>
			        <td>
				        <input name="authentication_basic_password" type="password" id="authentication_basic_password" value="<?php 
        echo esc_attr(BackWPup_Encryption::decrypt($authentication['basic_password']));
        ?>
" class="regular-text" autocomplete="off" />
		        </tr>
		        <tr class="authentication_user" <?php 
        if ($authentication['method'] !== 'user') {
            echo 'style="display:none"';
        }
        ?>
>
			        <th scope="row"><?php 
        _e('Select WordPress User', 'backwpup');
        ?>
</th>
			        <td>
				        <fieldset>
					        <legend class="screen-reader-text"><span><?php 
        _e('Select WordPress User', 'backwpup');
        ?>
</span>
					        </legend>
					        <label for="authentication_user_id">
						        <select name="authentication_user_id" size="1" >
							        <?php 
        $users = get_users(array('who' => 'administrators', 'number' => 99, 'orderby' => 'display_name'));
        foreach ($users as $user) {
            echo '<option value="' . $user->ID . '" ' . selected($authentication['user_id'], $user->ID, FALSE) . '>' . esc_attr($user->display_name) . '</option>';
        }
        ?>
						        </select>
					        </label>
				        </fieldset>
			        </td>
		        </tr>
		        <tr class="authentication_query_arg" <?php 
        if ($authentication['method'] != 'query_arg') {
            echo 'style="display:none"';
        }
        ?>
>
			        <th scope="row"><label for="authentication_query_arg"><?php 
        _e('Query arg key=value:', 'backwpup');
        ?>
</label></th>
			        <td>
				        ?<input name="authentication_query_arg" type="text" id="authentication_query_arg" value="<?php 
        echo esc_attr($authentication['query_arg']);
        ?>
" class="regular-text" />
			        </td>
		        </tr>
            </table>

        </div>

        <div class="table ui-tabs-hide" id="backwpup-tab-apikey">

			<?php 
        do_action('backwpup_page_settings_tab_apikey');
        ?>

        </div>

        <div class="table ui-tabs-hide" id="backwpup-tab-information">
			<br />
			<?php 
        echo '<table class="wp-list-table widefat fixed" cellspacing="0" style="width:85%;margin-left:auto;margin-right:auto;">';
        echo '<thead><tr><th width="35%">' . __('Setting', 'backwpup') . '</th><th>' . __('Value', 'backwpup') . '</th></tr></thead>';
        echo '<tfoot><tr><th>' . __('Setting', 'backwpup') . '</th><th>' . __('Value', 'backwpup') . '</th></tr></tfoot>';
        echo '<tr title="&gt;=3.2"><td>' . __('WordPress version', 'backwpup') . '</td><td>' . esc_html(BackWPup::get_plugin_data('wp_version')) . '</td></tr>';
        if (!class_exists('BackWPup_Pro', FALSE)) {
            echo '<tr title=""><td>' . __('BackWPup version', 'backwpup') . '</td><td>' . esc_html(BackWPup::get_plugin_data('Version')) . ' <a href="' . __('http://backwpup.com', 'backwpup') . '">' . __('Get pro.', 'backwpup') . '</a></td></tr>';
        } else {
            echo '<tr title=""><td>' . __('BackWPup Pro version', 'backwpup') . '</td><td>' . esc_html(BackWPup::get_plugin_data('Version')) . '</td></tr>';
        }
        $bit = '';
        if (PHP_INT_SIZE === 4) {
            $bit = ' (32bit)';
        }
        if (PHP_INT_SIZE === 8) {
            $bit = ' (64bit)';
        }
        echo '<tr title="&gt;=5.3.3"><td>' . __('PHP version', 'backwpup') . '</td><td>' . esc_html(PHP_VERSION . ' ' . $bit) . '</td></tr>';
        echo '<tr title="&gt;=5.0.7"><td>' . __('MySQL version', 'backwpup') . '</td><td>' . esc_html($wpdb->get_var("SELECT VERSION() AS version")) . '</td></tr>';
        if (function_exists('curl_version')) {
            $curlversion = curl_version();
            echo '<tr title=""><td>' . __('cURL version', 'backwpup') . '</td><td>' . esc_html($curlversion['version']) . '</td></tr>';
            echo '<tr title=""><td>' . __('cURL SSL version', 'backwpup') . '</td><td>' . esc_html($curlversion['ssl_version']) . '</td></tr>';
        } else {
            echo '<tr title=""><td>' . __('cURL version', 'backwpup') . '</td><td>' . __('unavailable', 'backwpup') . '</td></tr>';
        }
        echo '<tr title=""><td>' . __('WP-Cron url:', 'backwpup') . '</td><td>' . site_url('wp-cron.php') . '</td></tr>';
        //response test
        echo '<tr><td>' . __('Server self connect:', 'backwpup') . '</td><td>';
        $raw_response = BackWPup_Job::get_jobrun_url('test');
        $response_code = wp_remote_retrieve_response_code($raw_response);
        $response_body = wp_remote_retrieve_body($raw_response);
        if (strstr($response_body, 'BackWPup test request') === false) {
            $test_result = __('<strong>Not expected HTTP response:</strong><br>', 'backwpup');
            if (!$response_code) {
                $test_result .= sprintf(__('WP Http Error: <code>%s</code>', 'backwpup'), esc_html($raw_response->get_error_message())) . '<br>';
            } else {
                $test_result .= sprintf(__('Status-Code: <code>%d</code>', 'backwpup'), esc_html($response_code)) . '<br>';
            }
            $response_headers = wp_remote_retrieve_headers($raw_response);
            foreach ($response_headers as $key => $value) {
                $test_result .= esc_html(ucfirst($key)) . ': <code>' . esc_html($value) . '</code><br>';
            }
            $content = esc_html(wp_remote_retrieve_body($raw_response));
            if ($content) {
                $test_result .= sprintf(__('Content: <code>%s</code>', 'backwpup'), $content);
            }
            echo $test_result;
        } else {
            _e('Response Test O.K.', 'backwpup');
        }
        echo '</td></tr>';
        //folder test
        echo '<tr><td>' . __('Temp folder:', 'backwpup') . '</td><td>';
        if (!is_dir(BackWPup::get_plugin_data('TEMP'))) {
            echo sprintf(__('Temp folder %s doesn\'t exist.', 'backwpup'), esc_html(BackWPup::get_plugin_data('TEMP')));
        } elseif (!is_writable(BackWPup::get_plugin_data('TEMP'))) {
            echo sprintf(__('Temporary folder %s is not writable.', 'backwpup'), esc_html(BackWPup::get_plugin_data('TEMP')));
        } else {
            echo esc_html(BackWPup::get_plugin_data('TEMP'));
        }
        echo '</td></tr>';
        $log_folder = esc_html(get_site_option('backwpup_cfg_logfolder'));
        $log_folder = BackWPup_File::get_absolute_path($log_folder);
        echo '<tr><td>' . __('Log folder:', 'backwpup') . '</td><td>';
        if (!is_dir($log_folder)) {
            echo sprintf(__('Logs folder %s not exist.', 'backwpup'), $log_folder);
        } elseif (!is_writable($log_folder)) {
            echo sprintf(__('Log folder %s is not writable.', 'backwpup'), $log_folder);
        } else {
            echo $log_folder;
        }
        echo '</td></tr>';
        echo '<tr title=""><td>' . __('Server', 'backwpup') . '</td><td>' . esc_html($_SERVER['SERVER_SOFTWARE']) . '</td></tr>';
        echo '<tr title=""><td>' . __('Operating System', 'backwpup') . '</td><td>' . esc_html(PHP_OS) . '</td></tr>';
        echo '<tr title=""><td>' . __('PHP SAPI', 'backwpup') . '</td><td>' . esc_html(PHP_SAPI) . '</td></tr>';
        $php_user = __('Function Disabled', 'backwpup');
        if (function_exists('get_current_user')) {
            $php_user = get_current_user();
        }
        echo '<tr title=""><td>' . __('Current PHP user', 'backwpup') . '</td><td>' . esc_html($php_user) . '</td></tr>';
        echo '<tr title="&gt;=30"><td>' . __('Maximum execution time', 'backwpup') . '</td><td>' . esc_html(ini_get('max_execution_time')) . ' ' . __('seconds', 'backwpup') . '</td></tr>';
        if (defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON) {
            echo '<tr title="ALTERNATE_WP_CRON"><td>' . __('Alternative WP Cron', 'backwpup') . '</td><td>' . __('On', 'backwpup') . '</td></tr>';
        } else {
            echo '<tr title="ALTERNATE_WP_CRON"><td>' . __('Alternative WP Cron', 'backwpup') . '</td><td>' . __('Off', 'backwpup') . '</td></tr>';
        }
        if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
            echo '<tr title="DISABLE_WP_CRON"><td>' . __('Disabled WP Cron', 'backwpup') . '</td><td>' . __('On', 'backwpup') . '</td></tr>';
        } else {
            echo '<tr title="DISABLE_WP_CRON"><td>' . __('Disabled WP Cron', 'backwpup') . '</td><td>' . __('Off', 'backwpup') . '</td></tr>';
        }
        if (defined('FS_CHMOD_DIR')) {
            echo '<tr title="FS_CHMOD_DIR"><td>' . __('CHMOD Dir', 'backwpup') . '</td><td>' . esc_html(FS_CHMOD_DIR) . '</td></tr>';
        } else {
            echo '<tr title="FS_CHMOD_DIR"><td>' . __('CHMOD Dir', 'backwpup') . '</td><td>0755</td></tr>';
        }
        $now = localtime(time(), TRUE);
        echo '<tr title=""><td>' . __('Server Time', 'backwpup') . '</td><td>' . esc_html($now['tm_hour'] . ':' . $now['tm_min']) . '</td></tr>';
        echo '<tr title=""><td>' . __('Blog Time', 'backwpup') . '</td><td>' . date('H:i', current_time('timestamp')) . '</td></tr>';
        echo '<tr title=""><td>' . __('Blog Timezone', 'backwpup') . '</td><td>' . esc_html(get_option('timezone_string')) . '</td></tr>';
        echo '<tr title=""><td>' . __('Blog Time offset', 'backwpup') . '</td><td>' . sprintf(__('%s hours', 'backwpup'), (int) get_option('gmt_offset')) . '</td></tr>';
        echo '<tr title="WPLANG"><td>' . __('Blog language', 'backwpup') . '</td><td>' . get_bloginfo('language') . '</td></tr>';
        echo '<tr title="utf8"><td>' . __('MySQL Client encoding', 'backwpup') . '</td><td>';
        echo defined('DB_CHARSET') ? DB_CHARSET : '';
        echo '</td></tr>';
        echo '<tr title="URF-8"><td>' . __('Blog charset', 'backwpup') . '</td><td>' . get_bloginfo('charset') . '</td></tr>';
        echo '<tr title="&gt;=128M"><td>' . __('PHP Memory limit', 'backwpup') . '</td><td>' . esc_html(ini_get('memory_limit')) . '</td></tr>';
        echo '<tr title="WP_MEMORY_LIMIT"><td>' . __('WP memory limit', 'backwpup') . '</td><td>' . esc_html(WP_MEMORY_LIMIT) . '</td></tr>';
        echo '<tr title="WP_MAX_MEMORY_LIMIT"><td>' . __('WP maximum memory limit', 'backwpup') . '</td><td>' . esc_html(WP_MAX_MEMORY_LIMIT) . '</td></tr>';
        echo '<tr title=""><td>' . __('Memory in use', 'backwpup') . '</td><td>' . size_format(@memory_get_usage(TRUE), 2) . '</td></tr>';
        //disabled PHP functions
        $disabled = esc_html(ini_get('disable_functions'));
        if (!empty($disabled)) {
            $disabledarry = explode(',', $disabled);
            echo '<tr title=""><td>' . __('Disabled PHP Functions:', 'backwpup') . '</td><td>';
            echo implode(', ', $disabledarry);
            echo '</td></tr>';
        }
        //Loaded PHP Extensions
        echo '<tr title=""><td>' . __('Loaded PHP Extensions:', 'backwpup') . '</td><td>';
        $extensions = get_loaded_extensions();
        sort($extensions);
        echo esc_html(implode(', ', $extensions));
        echo '</td></tr>';
        echo '</table>';
        ?>
        </div>

		<?php 
        do_action('backwpup_page_settings_tab_content');
        ?>

        <p class="submit">
            <input type="submit" name="submit" id="submit" class="button-primary" value="<?php 
        _e('Save Changes', 'backwpup');
        ?>
" />
			&nbsp;
			<input type="submit" name="default_settings" id="default_settings" class="button-secondary" value="<?php 
        _e('Reset all settings to default', 'backwpup');
        ?>
" />
        </p>
    </form>
    </div>
	<?php 
    }
Example #12
0
 /**
  *
  * Function to generate json data
  *
  */
 public static function ajax_working()
 {
     check_ajax_referer('backwpupworking_ajax_nonce');
     $logfile = isset($_GET['logfile']) ? get_site_option('backwpup_cfg_logfolder') . trim($_GET['logfile']) : NULL;
     $logpos = isset($_GET['logpos']) ? (int) $_GET['logpos'] : 0;
     //check if logfile renamed
     if (file_exists($logfile . '.gz')) {
         $logfile .= '.gz';
     }
     if (!is_readable($logfile)) {
         die('0');
     }
     $job_object = BackWPup_Job::get_working_data();
     $done = 0;
     if (is_object($job_object)) {
         $warnings = $job_object->warnings;
         $errors = $job_object->errors;
         $step_percent = $job_object->step_percent;
         $substep_percent = $job_object->substep_percent;
         $runtime = current_time('timestamp') - $job_object->start_time;
         $onstep = $job_object->steps_data[$job_object->step_working]['NAME'];
         $lastmsg = $job_object->lastmsg;
         $lasterrormsg = $job_object->lasterrormsg;
     } else {
         $logheader = BackWPup_Job::read_logheader($logfile);
         $warnings = $logheader['warnings'];
         $runtime = $logheader['runtime'];
         $errors = $logheader['errors'];
         $step_percent = 100;
         $substep_percent = 100;
         $onstep = '<div class="backwpup-message backwpup-info"><p>' . __('Job completed', 'backwpup') . '</p></div>';
         if ($errors > 0) {
             $lastmsg = '<div class="error"><p>' . __('ERROR:', 'backwpup') . ' ' . sprintf(__('Job has ended with errors in %s seconds. You must resolve the errors for correct execution.', 'backwpup'), $logheader['runtime']) . '</p></div>';
         } elseif ($warnings > 0) {
             $lastmsg = '<div class="backwpup-message backwpup-warning"><p>' . __('WARNING:', 'backwpup') . ' ' . sprintf(__('Job has done with warnings in %s seconds. Please resolve them for correct execution.', 'backwpup'), $logheader['runtime']) . '</p></div>';
         } else {
             $lastmsg = '<div class="updated"><p>' . sprintf(__('Job done in %s seconds.', 'backwpup'), $logheader['runtime']) . '</p></div>';
         }
         $lasterrormsg = '';
         $done = 1;
     }
     if ('.gz' == substr($logfile, -3)) {
         $logfiledata = file_get_contents('compress.zlib://' . $logfile, FALSE, NULL, $logpos);
     } else {
         $logfiledata = file_get_contents($logfile, FALSE, NULL, $logpos);
     }
     preg_match('/<body[^>]*>/si', $logfiledata, $match);
     if (!empty($match[0])) {
         $startpos = strpos($logfiledata, $match[0]) + strlen($match[0]);
     } else {
         $startpos = 0;
     }
     $endpos = stripos($logfiledata, '</body>');
     if (FALSE === $endpos) {
         $endpos = strlen($logfiledata);
     }
     $length = strlen($logfiledata) - (strlen($logfiledata) - $endpos) - $startpos;
     wp_send_json(array('log_pos' => strlen($logfiledata) + $logpos, 'log_text' => substr($logfiledata, $startpos, $length), 'warning_count' => $warnings, 'error_count' => $errors, 'running_time' => $runtime, 'step_percent' => $step_percent, 'on_step' => $onstep, 'last_msg' => $lastmsg, 'last_error_msg' => $lasterrormsg, 'sub_step_percent' => $substep_percent, 'job_done' => $done));
 }
Example #13
0
 /**
  *
  * Function to generate json data
  *
  */
 public static function ajax_working()
 {
     check_ajax_referer('backwpupworking_ajax_nonce');
     if (!current_user_can('backwpup_jobs_start')) {
         die('-1');
     }
     $log_folder = get_site_option('backwpup_cfg_logfolder');
     $log_folder = BackWPup_File::get_absolute_path($log_folder);
     $logfile = isset($_GET['logfile']) ? $log_folder . basename(trim($_GET['logfile'])) : NULL;
     $logpos = isset($_GET['logpos']) ? absint($_GET['logpos']) : 0;
     $restart_url = '';
     //check if logfile renamed
     if (file_exists($logfile . '.gz')) {
         $logfile .= '.gz';
     }
     if (!is_readable($logfile) || strstr($_GET['logfile'], 'backwpup_log_') === false) {
         die('0');
     }
     $job_object = BackWPup_Job::get_working_data();
     $done = 0;
     if (is_object($job_object)) {
         $warnings = $job_object->warnings;
         $errors = $job_object->errors;
         $step_percent = $job_object->step_percent;
         $substep_percent = $job_object->substep_percent;
         $runtime = current_time('timestamp') - $job_object->start_time;
         $onstep = $job_object->steps_data[$job_object->step_working]['NAME'];
         $lastmsg = $job_object->lastmsg;
         $lasterrormsg = $job_object->lasterrormsg;
     } else {
         $logheader = BackWPup_Job::read_logheader($logfile);
         $warnings = $logheader['warnings'];
         $runtime = $logheader['runtime'];
         $errors = $logheader['errors'];
         $step_percent = 100;
         $substep_percent = 100;
         $onstep = '<div class="backwpup-message backwpup-info"><p>' . esc_html__('Job completed', 'backwpup') . '</p></div>';
         if ($errors > 0) {
             $lastmsg = '<div class="error"><p>' . esc_html__('ERROR:', 'backwpup') . ' ' . sprintf(esc_html__('Job has ended with errors in %s seconds. You must resolve the errors for correct execution.', 'backwpup'), $logheader['runtime']) . '</p></div>';
         } elseif ($warnings > 0) {
             $lastmsg = '<div class="backwpup-message backwpup-warning"><p>' . esc_html__('WARNING:', 'backwpup') . ' ' . sprintf(esc_html__('Job has done with warnings in %s seconds. Please resolve them for correct execution.', 'backwpup'), $logheader['runtime']) . '</p></div>';
         } else {
             $lastmsg = '<div class="updated"><p>' . sprintf(esc_html__('Job done in %s seconds.', 'backwpup'), $logheader['runtime']) . '</p></div>';
         }
         $lasterrormsg = '';
         $done = 1;
     }
     if ('.gz' == substr($logfile, -3)) {
         $logfiledata = file_get_contents('compress.zlib://' . $logfile, FALSE, NULL, $logpos);
     } else {
         $logfiledata = file_get_contents($logfile, FALSE, NULL, $logpos);
     }
     preg_match('/<body[^>]*>/si', $logfiledata, $match);
     if (!empty($match[0])) {
         $startpos = strpos($logfiledata, $match[0]) + strlen($match[0]);
     } else {
         $startpos = 0;
     }
     $endpos = stripos($logfiledata, '</body>');
     if (FALSE === $endpos) {
         $endpos = strlen($logfiledata);
     }
     $length = strlen($logfiledata) - (strlen($logfiledata) - $endpos) - $startpos;
     //check if restart must done on ALTERNATE_WP_CRON
     if (is_object($job_object) && defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON) {
         $restart = BackWPup_Job::get_jobrun_url('restartalt');
         if ($job_object->pid === 0 && $job_object->uniqid === '') {
             $restart_url = $restart['url'];
         }
         $last_update = microtime(TRUE) - $job_object->timestamp_last_update;
         if (empty($job_object->pid) && $last_update > 10) {
             $restart_url = $restart['url'];
         }
     }
     wp_send_json(array('log_pos' => strlen($logfiledata) + $logpos, 'log_text' => substr($logfiledata, $startpos, $length), 'warning_count' => $warnings, 'error_count' => $errors, 'running_time' => $runtime, 'step_percent' => $step_percent, 'on_step' => $onstep, 'last_msg' => $lastmsg, 'last_error_msg' => $lasterrormsg, 'sub_step_percent' => $substep_percent, 'restart_url' => $restart_url, 'job_done' => $done));
 }
Example #14
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 $id
  */
 public function edit_form_post_save($id)
 {
     BackWPup_Option::update($id, 'pluginlistfile', BackWPup_Job::sanitize_file_name($_POST['pluginlistfile']));
     if ($_POST['pluginlistfilecompression'] == '' || $_POST['pluginlistfilecompression'] == '.gz' || $_POST['pluginlistfilecompression'] == '.bz2') {
         BackWPup_Option::update($id, 'pluginlistfilecompression', $_POST['pluginlistfilecompression']);
     }
 }
Example #16
0
 public static function user_abort()
 {
     /* @var $job_object BackWPup_Job */
     $job_object = BackWPup_Job::get_working_data();
     unlink(BackWPup::get_plugin_data('running_file'));
     //if job not working currently abort it this way for message
     $not_worked_time = microtime(true) - $job_object->timestamp_last_update;
     $restart_time = get_site_option('backwpup_cfg_jobmaxexecutiontime');
     if (empty($restart_time)) {
         $restart_time = 60;
     }
     if (empty($job_object->pid) || $not_worked_time > $restart_time) {
         $job_object->user_abort = true;
         $job_object->update_working_data();
     }
 }
    /**
     * 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 $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;
 }
Example #19
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 $job_object
  * @return bool
  */
 public function job_run_archive(BackWPup_Job $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();
             $job_object->steps_data[$job_object->step_working]['container_url'] = '';
             foreach ($containers as $container) {
                 if ($container->getName() == $job_object->job['msazurecontainer']) {
                     $job_object->steps_data[$job_object->step_working]['container_url'] = $container->getUrl();
                     break;
                 }
             }
             if (!$job_object->steps_data[$job_object->step_working]['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
         if ($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)) {
                 $data = fread($file_handel, 1048576 * 4);
                 //4MB
                 if (strlen($data) == 0) {
                     continue;
                 }
                 $chunk_upload_start = microtime(TRUE);
                 $block_count = count($job_object->steps_data[$job_object->step_working]['BlockList']) + 1;
                 $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);
         } else {
             $job_object->log(__('Can not open source file for transfer.', 'backwpup'), E_USER_ERROR);
             return FALSE;
         }
         //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'), $job_object->steps_data[$job_object->step_working]['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'), $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'] = $job_object->steps_data[$job_object->step_working]['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, YEAR_IN_SECONDS);
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('Microsoft Azure API: %s', 'backwpup'), $e->getMessage()), $e->getFile(), $e->getLine());
         return FALSE;
     }
     $job_object->substeps_done = $job_object->backup_filesize + 2;
     return TRUE;
 }
 protected function backup_now()
 {
     if (!isset($_POST['settings']['job_id'])) {
         return array('error' => __('Missing job id', $this->plugin_translate));
     }
     // Simulate http://wp/wp-admin/admin.php?jobid=1&page=backwpupjobs&action=runnow
     $_GET['jobid'] = $_POST['settings']['job_id'];
     $_REQUEST['action'] = 'runnow';
     $_REQUEST['_wpnonce'] = wp_create_nonce('backwpup_job_run-runnowlink');
     update_site_option('backwpup_messages', array());
     $this->wp_list_table_dependency();
     ob_start();
     BackWPup_Page_Jobs::load();
     ob_end_clean();
     $output = $this->check_backwpup_messages();
     if (isset($output['error'])) {
         return array('error' => 'BackWPup_Page_Jobs::load fail: ' . $output['error']);
     } else {
         $job_object = BackWPup_Job::get_working_data();
         if (is_object($job_object)) {
             return array('success' => 1, 'response' => $output['message'], 'logfile' => basename($job_object->logfile));
         } else {
             return array('success' => 1, 'response' => $output['message']);
         }
     }
 }
Example #22
0
 /**
  * @param $job_object
  * @return bool
  */
 public function job_run(BackWPup_Job $job_object)
 {
     $abs_path = realpath(ABSPATH);
     if ($job_object->job['backupabsfolderup']) {
         $abs_path = dirname($abs_path);
     }
     $abs_path = trailingslashit(str_replace('\\', '/', $abs_path));
     $job_object->log(sprintf(__('%d. Trying to make a list of folders to back up&#160;&hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']));
     $job_object->substeps_todo = 8;
     $job_object->temp['folders_to_backup'] = array();
     //Folder lists for blog folders
     if ($job_object->substeps_done == 0) {
         if ($abs_path && !empty($job_object->job['backuproot'])) {
             $abs_path = trailingslashit(str_replace('\\', '/', $abs_path));
             $excludes = $this->get_exclude_dirs($abs_path);
             foreach ($job_object->job['backuprootexcludedirs'] as $folder) {
                 $excludes[] = trailingslashit($abs_path . $folder);
             }
             $this->get_folder_list($job_object, $abs_path, $excludes);
             $job_object->add_folders_to_backup($this->folers_to_backup);
             $this->folers_to_backup = array();
         }
         $job_object->substeps_done = 1;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->substeps_done == 1) {
         $wp_content_dir = realpath(WP_CONTENT_DIR);
         if ($wp_content_dir && !empty($job_object->job['backupcontent'])) {
             $wp_content_dir = trailingslashit(str_replace('\\', '/', $wp_content_dir));
             $excludes = $this->get_exclude_dirs($wp_content_dir);
             foreach ($job_object->job['backupcontentexcludedirs'] as $folder) {
                 $excludes[] = trailingslashit($wp_content_dir . $folder);
             }
             $this->get_folder_list($job_object, $wp_content_dir, $excludes);
             $job_object->add_folders_to_backup($this->folers_to_backup);
             $this->folers_to_backup = array();
         }
         $job_object->substeps_done = 2;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->substeps_done == 2) {
         $wp_plugin_dir = realpath(WP_PLUGIN_DIR);
         if ($wp_plugin_dir && !empty($job_object->job['backupplugins'])) {
             $wp_plugin_dir = trailingslashit(str_replace('\\', '/', $wp_plugin_dir));
             $excludes = $this->get_exclude_dirs($wp_plugin_dir);
             foreach ($job_object->job['backuppluginsexcludedirs'] as $folder) {
                 $excludes[] = trailingslashit($wp_plugin_dir . $folder);
             }
             $this->get_folder_list($job_object, $wp_plugin_dir, $excludes);
             $job_object->add_folders_to_backup($this->folers_to_backup);
             $this->folers_to_backup = array();
         }
         $job_object->substeps_done = 3;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->substeps_done == 3) {
         $theme_root = realpath(get_theme_root());
         if ($theme_root && !empty($job_object->job['backupthemes'])) {
             $theme_root = trailingslashit(str_replace('\\', '/', $theme_root));
             $excludes = $this->get_exclude_dirs($theme_root);
             foreach ($job_object->job['backupthemesexcludedirs'] as $folder) {
                 $excludes[] = trailingslashit($theme_root . $folder);
             }
             $this->get_folder_list($job_object, $theme_root, $excludes);
             $job_object->add_folders_to_backup($this->folers_to_backup);
             $this->folers_to_backup = array();
         }
         $job_object->substeps_done = 4;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->substeps_done == 4) {
         $upload_dir = realpath(BackWPup_File::get_upload_dir());
         if ($upload_dir && !empty($job_object->job['backupuploads'])) {
             $upload_dir = trailingslashit(str_replace('\\', '/', $upload_dir));
             $excludes = $this->get_exclude_dirs($upload_dir);
             foreach ($job_object->job['backupuploadsexcludedirs'] as $folder) {
                 $excludes[] = trailingslashit($upload_dir . $folder);
             }
             $this->get_folder_list($job_object, $upload_dir, $excludes);
             $job_object->add_folders_to_backup($this->folers_to_backup);
             $this->folers_to_backup = array();
         }
         $job_object->substeps_done = 5;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->substeps_done == 5) {
         //include dirs
         if ($job_object->job['dirinclude']) {
             $dirinclude = explode(',', $job_object->job['dirinclude']);
             $dirinclude = array_unique($dirinclude);
             //Crate file list for includes
             foreach ($dirinclude as $dirincludevalue) {
                 if (is_dir($dirincludevalue)) {
                     $this->get_folder_list($job_object, $dirincludevalue);
                 }
             }
             $job_object->add_folders_to_backup($this->folers_to_backup);
             $this->folers_to_backup = array();
         }
         $job_object->substeps_done = 6;
         $job_object->update_working_data();
         $job_object->do_restart_time();
     }
     if ($job_object->substeps_done == 6) {
         //clean up folder list
         $folders = $job_object->get_folders_to_backup();
         $job_object->add_folders_to_backup($folders, TRUE);
         $job_object->update_working_data();
         $job_object->do_restart_time();
         $job_object->substeps_done = 7;
     }
     //add extra files if selected
     if (!empty($job_object->job['backupspecialfiles'])) {
         if (is_readable(ABSPATH . 'wp-config.php') && empty($job_object->job['backuproot'])) {
             $job_object->additional_files_to_backup[] = str_replace('\\', '/', ABSPATH . 'wp-config.php');
             $job_object->log(sprintf(__('Added "%s" to backup file list', 'backwpup'), 'wp-config.php'));
         } elseif (BackWPup_File::is_in_open_basedir(dirname(ABSPATH))) {
             if (is_readable(dirname(ABSPATH) . '/wp-config.php') && !is_readable(dirname(ABSPATH) . '/wp-settings.php')) {
                 $job_object->additional_files_to_backup[] = str_replace('\\', '/', dirname(ABSPATH) . '/wp-config.php');
                 $job_object->log(sprintf(__('Added "%s" to backup file list', 'backwpup'), 'wp-config.php'));
             }
         }
         if (is_readable($abs_path . '.htaccess') && empty($job_object->job['backuproot'])) {
             $job_object->additional_files_to_backup[] = $abs_path . '.htaccess';
             $job_object->log(sprintf(__('Added "%s" to backup file list', 'backwpup'), '.htaccess'));
         }
         if (is_readable($abs_path . '.htpasswd') && empty($job_object->job['backuproot'])) {
             $job_object->additional_files_to_backup[] = $abs_path . '.htpasswd';
             $job_object->log(sprintf(__('Added "%s" to backup file list', 'backwpup'), '.htpasswd'));
         }
         if (is_readable($abs_path . 'robots.txt') && empty($job_object->job['backuproot'])) {
             $job_object->additional_files_to_backup[] = $abs_path . 'robots.txt';
             $job_object->log(sprintf(__('Added "%s" to backup file list', 'backwpup'), 'robots.txt'));
         }
         if (is_readable($abs_path . 'favicon.ico') && empty($job_object->job['backuproot'])) {
             $job_object->additional_files_to_backup[] = $abs_path . 'favicon.ico';
             $job_object->log(sprintf(__('Added "%s" to backup file list', 'backwpup'), 'favicon.ico'));
         }
     }
     if ($job_object->count_folder == 0 && count($job_object->additional_files_to_backup) == 0) {
         $job_object->log(__('No files/folder for the backup.', 'backwpup'), E_USER_WARNING);
     } elseif ($job_object->count_folder > 1) {
         $job_object->log(sprintf(__('%1$d folders to backup.', 'backwpup'), $job_object->count_folder));
     }
     $job_object->substeps_done = 8;
     return TRUE;
 }
Example #23
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 $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. 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'), $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'), $e->getMessage()), $e->getFile(), $e->getLine());
         return FALSE;
     }
     $job_object->substeps_done = 2 + $job_object->backup_filesize;
     return TRUE;
 }
 /**
  * @param        $file
  * @param string $name
  * @return mixed
  */
 public function upload($file, $name = '')
 {
     if (empty($name)) {
         $name = basename($file);
     }
     $content_type = BackWPup_Job::get_mime_type($file);
     $xmlrequest = '<?xml version="1.0" encoding="UTF-8"?>';
     $xmlrequest .= '<file>';
     $xmlrequest .= '<displayName>' . mb_convert_encoding($name, 'UTF-8', $this->encoding) . '</displayName>';
     $xmlrequest .= '<mediaType>' . $content_type . '</mediaType>';
     $xmlrequest .= '</file>';
     $this->doCall($this->folder, $xmlrequest, 'POST');
     $getfiles = $this->getcontents('file');
     foreach ($getfiles->file as $getfile) {
         if ($getfile->displayName == $name) {
             $this->doCall($getfile->ref . '/data', $file, 'PUT');
             return $getfile->ref;
         }
     }
 }
    /**
     * Page Output
     */
    public static function page()
    {
        global $wpdb;
        ?>
    <div class="wrap" id="backwpup-page">
		<h2><span id="backwpup-page-icon">&nbsp;</span><?php 
        echo sprintf(__('%s Settings', 'backwpup'), BackWPup::get_plugin_data('name'));
        ?>
</h2>
		<?php 
        $tabs = array('general' => __('General', 'backwpup'), 'job' => __('Jobs', 'backwpup'), 'log' => __('Logs', 'backwpup'), 'net' => __('Network', 'backwpup'), 'apikey' => __('API Keys', 'backwpup'), 'information' => __('Information', 'backwpup'));
        $tabs = apply_filters('backwpup_page_settings_tab', $tabs);
        echo '<h2 class="nav-tab-wrapper">';
        foreach ($tabs as $id => $name) {
            echo '<a href="#backwpup-tab-' . $id . '" class="nav-tab">' . $name . '</a>';
        }
        echo '</h2>';
        BackWPup_Admin::display_messages();
        ?>

    <form id="settingsform" action="<?php 
        echo admin_url('admin-post.php?action=backwpup');
        ?>
" method="post">
		<?php 
        wp_nonce_field('backwpupsettings_page');
        ?>
        <input type="hidden" name="page" value="backwpupsettings" />
    	<input type="hidden" name="anchor" value="#backwpup-tab-general" />

		<div class="table ui-tabs-hide" id="backwpup-tab-general">

			<h3 class="title"><?php 
        _e('Display Settings', 'backwpup');
        ?>
</h3>
            <p><?php 
        _e('Do you want to see BackWPup in the WordPress admin bar?', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><?php 
        _e('Admin bar', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Admin Bar', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="showadminbar">
                                <input name="showadminbar" type="checkbox" id="showadminbar"
                                       value="1" <?php 
        checked(get_site_option('backwpup_cfg_showadminbar'), TRUE);
        ?>
 />
								<?php 
        _e('Show BackWPup links in admin bar.', 'backwpup');
        ?>
</label>
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php 
        _e('Folder sizes', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Folder sizes', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="showfoldersize">
                                <input name="showfoldersize" type="checkbox" id="showfoldersize"
                                       value="1" <?php 
        checked(get_site_option('backwpup_cfg_showfoldersize'), TRUE);
        ?>
 />
								<?php 
        _e('Display folder sizes in the files tab when editing a job. (Might increase loading time of files tab.)', 'backwpup');
        ?>
</label>
                        </fieldset>
                    </td>
                </tr>
            </table>
			<h3 class="title"><?php 
        _e('Security', 'backwpup');
        ?>
</h3>
			<p><?php 
        _e('Security option for BackWPup', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><?php 
        _e('Protect folders', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Protect folders', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="protectfolders">
                                <input name="protectfolders" type="checkbox" id="protectfolders"
                                       value="1" <?php 
        checked(get_site_option('backwpup_cfg_protectfolders'), TRUE);
        ?>
 />
								<?php 
        _e('Protect BackWPup folders ( Temp, Log and Backups ) with <code>.htaccess</code> and <code>index.php</code>', 'backwpup');
        ?>
                            </label>
                        </fieldset>
                    </td>
                </tr>
            </table>

			<?php 
        do_action('backwpup_page_settings_tab_generel');
        ?>

		</div>

        <div class="table ui-tabs-hide" id="backwpup-tab-log">

            <p><?php 
        _e('Every time BackWPup runs a backup job, a log file is being generated. Choose where to store your log files and how many of them.', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="logfolder"><?php 
        _e('Log file folder', 'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="logfolder" type="text" id="logfolder"
                               value="<?php 
        echo get_site_option('backwpup_cfg_logfolder');
        ?>
"
                               class="regular-text code"/>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="maxlogs"><?php 
        _e('Maximum number of log files in folder', 'backwpup');
        ?>
</label>
                    </th>
                    <td>
                        <input name="maxlogs" type="text" id="maxlogs" title="<?php 
        esc_attr_e('Oldest files will be deleted first.', 'backwpup');
        ?>
"
                               value="<?php 
        echo get_site_option('backwpup_cfg_maxlogs');
        ?>
" class="small-text code help-tip"/>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php 
        _e('Compression', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Compression', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="gzlogs">
                                <input name="gzlogs" type="checkbox" id="gzlogs"
                                       value="1" <?php 
        checked(get_site_option('backwpup_cfg_gzlogs'), TRUE);
        if (!function_exists('gzopen')) {
            echo " disabled=\"disabled\"";
        }
        ?>
 />
								<?php 
        _e('Compress log files with GZip.', 'backwpup');
        ?>
</label>
                        </fieldset>
                    </td>
                </tr>
            </table>

        </div>
        <div class="table ui-tabs-hide" id="backwpup-tab-job">

            <p><?php 
        _e('There are a couple of general options for backup jobs. Set them here.', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="jobstepretry"><?php 
        _e("Maximum number of retries for job steps", 'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="jobstepretry" type="text" id="jobstepretry"
                               value="<?php 
        echo get_site_option('backwpup_cfg_jobstepretry');
        ?>
"
                               class="small-text code" />
                    </td>
                </tr>
				<tr>
                    <th scope="row"><?php 
        _e('Maximum script execution time', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Maximum PHP Script execution time', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="jobmaxexecutiontime">
                                <input name="jobmaxexecutiontime" type="text" id="jobmaxexecutiontime" size="3" title="<?php 
        esc_attr_e('Job will restart before hitting maximum execution time. It will not work with CLI and not on every step during execution. If <code>ALTERNATE_WP_CRON</code> has been defined, WordPress Cron will be used.', 'backwpup');
        ?>
"
                                       value="<?php 
        echo get_site_option('backwpup_cfg_jobmaxexecutiontime');
        ?>
" class="help-tip" />
								<?php 
        _e('seconds. 0 = disabled.', 'backwpup');
        ?>
							</label>
                        </fieldset>
                    </td>
                </tr>
				<tr>
                    <th scope="row"><?php 
        _e('Method for creating ZIP-file archives', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Method for creating ZIP-file archives', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="jobziparchivemethod">
								<select name="jobziparchivemethod" size="1" class="help-tip" title="<?php 
        esc_attr_e('Auto = Uses PHP class ZipArchive if available; otherwise uses PclZip.<br />ZipArchive = Uses less memory, but many open files at a time.<br />PclZip = Uses more memory, but only 2 open files at a time.', 'backwpup');
        ?>
">
									<option value="" <?php 
        selected(get_site_option('backwpup_cfg_jobziparchivemethod'), '');
        ?>
><?php 
        _e('Auto', 'backwpup');
        ?>
</option>
                                    <option value="ZipArchive" <?php 
        selected(get_site_option('backwpup_cfg_jobziparchivemethod'), 'ZipArchive');
        disabled(function_exists('ZipArchive'), TRUE);
        ?>
><?php 
        _e('ZipArchive', 'backwpup');
        ?>
</option>
                                    <option value="PclZip" <?php 
        selected(get_site_option('backwpup_cfg_jobziparchivemethod'), 'PclZip');
        ?>
><?php 
        _e('PclZip', 'backwpup');
        ?>
</option>
                                </select>
                            </label>
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <th scope="row">
                        <label for="jobrunauthkey"><?php 
        _e('Key to start jobs externally with an URL', 'backwpup');
        ?>
</label>
                    </th>
                    <td>
                        <input name="jobrunauthkey" type="text" id="jobrunauthkey" title="<?php 
        esc_attr_e('empty = deactivated. Will be used to protect job starts from unauthorized person.', 'backwpup');
        ?>
"
                               value="<?php 
        echo get_site_option('backwpup_cfg_jobrunauthkey');
        ?>
" class="text code help-tip"/>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php 
        _e('No translation', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('No Translation', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="jobnotranslate">
                                <input name="jobnotranslate" type="checkbox" id="jobnotranslate"
                                       value="1" <?php 
        checked(get_site_option('backwpup_cfg_jobnotranslate'), TRUE);
        ?>
 />
								<?php 
        _e('No translation for the job, the log will be written in English', 'backwpup');
        ?>
                            </label>
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <th scope="row"><?php 
        _e('Reduce server load', 'backwpup');
        ?>
</th>
                    <td>
                        <fieldset>
                            <legend class="screen-reader-text"><span><?php 
        _e('Reduce server load', 'backwpup');
        ?>
</span>
                            </legend>
                            <label for="jobwaittimems">
								<select name="jobwaittimems" size="1" class="help-tip" title="<?php 
        esc_attr_e('This adds short pauses to the process. Can be used to reduce the CPU load.<br /> Disabled = off<br /> minimum = shortest sleep<br /> medium = middle between minimum and maximum<br /> maximum = longest sleep<br />', 'backwpup');
        ?>
">
									<option value="0" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 0);
        ?>
><?php 
        _e('disabled', 'backwpup');
        ?>
</option>
                                    <option value="10000" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 10000);
        ?>
><?php 
        _e('minimum', 'backwpup');
        ?>
</option>
                                    <option value="30000" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 30000);
        ?>
><?php 
        _e('medium', 'backwpup');
        ?>
</option>
                                    <option value="90000" <?php 
        selected(get_site_option('backwpup_cfg_jobwaittimems'), 90000);
        ?>
><?php 
        _e('maximum', 'backwpup');
        ?>
</option>
                                </select>
                            </label>
                        </fieldset>
                    </td>
                </tr>
            </table>

        </div>

        <div class="table ui-tabs-hide" id="backwpup-tab-net">

			<h3 class="title"><?php 
        _e('Authentication', 'backwpup');
        ?>
</h3>
            <p><?php 
        _e('Is your blog protected with HTTP basic authentication (.htaccess)? If yes, please set the username and password for authentication here.', 'backwpup');
        ?>
</p>
            <table class="form-table">
                <tr>
                    <th scope="row"><label for="httpauthuser"><?php 
        _e('Username:'******'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="httpauthuser" type="text" id="httpauthuser"
                               value="<?php 
        echo get_site_option('backwpup_cfg_httpauthuser');
        ?>
"
                               class="regular-text" autocomplete="off" />
                    </td>
                </tr>
                <tr>
                    <th scope="row"><label for="httpauthpassword"><?php 
        _e('Password:'******'backwpup');
        ?>
</label></th>
                    <td>
                        <input name="httpauthpassword" type="password" id="httpauthpassword"
                               value="<?php 
        echo BackWPup_Encryption::decrypt(get_site_option('backwpup_cfg_httpauthpassword'));
        ?>
"
                               class="regular-text" autocomplete="off" />
                </tr>
            </table>

        </div>

        <div class="table ui-tabs-hide" id="backwpup-tab-apikey">

			<?php 
        do_action('backwpup_page_settings_tab_apikey');
        ?>

        </div>

        <div class="table ui-tabs-hide" id="backwpup-tab-information">
			<br />
			<?php 
        echo '<table class="wp-list-table widefat fixed" cellspacing="0" style="width: 85%;margin-left:auto;;margin-right:auto;">';
        echo '<thead><tr><th width="35%">' . __('Setting', 'backwpup') . '</th><th>' . __('Value', 'backwpup') . '</th></tr></thead>';
        echo '<tfoot><tr><th>' . __('Setting', 'backwpup') . '</th><th>' . __('Value', 'backwpup') . '</th></tr></tfoot>';
        echo '<tr title="&gt;=3.2"><td>' . __('WordPress version', 'backwpup') . '</td><td>' . BackWPup::get_plugin_data('wp_version') . '</td></tr>';
        if (!class_exists('BackWPup_Pro', FALSE)) {
            echo '<tr title=""><td>' . __('BackWPup version', 'backwpup') . '</td><td>' . BackWPup::get_plugin_data('Version') . ' <a href="' . translate(BackWPup::get_plugin_data('pluginuri'), 'backwpup') . '">' . __('Get pro.', 'backwpup') . '</a></td></tr>';
        } else {
            echo '<tr title=""><td>' . __('BackWPup Pro version', 'backwpup') . '</td><td>' . BackWPup::get_plugin_data('Version') . '</td></tr>';
        }
        echo '<tr title="&gt;=5.3.3"><td>' . __('PHP version', 'backwpup') . '</td><td>' . PHP_VERSION . '</td></tr>';
        echo '<tr title="&gt;=5.0.7"><td>' . __('MySQL version', 'backwpup') . '</td><td>' . $wpdb->get_var("SELECT VERSION() AS version") . '</td></tr>';
        if (function_exists('curl_version')) {
            $curlversion = curl_version();
            echo '<tr title=""><td>' . __('cURL version', 'backwpup') . '</td><td>' . $curlversion['version'] . '</td></tr>';
            echo '<tr title=""><td>' . __('cURL SSL version', 'backwpup') . '</td><td>' . $curlversion['ssl_version'] . '</td></tr>';
        } else {
            echo '<tr title=""><td>' . __('cURL version', 'backwpup') . '</td><td>' . __('unavailable', 'backwpup') . '</td></tr>';
        }
        echo '<tr title=""><td>' . __('WP-Cron url:', 'backwpup') . '</td><td>' . site_url('wp-cron.php') . '</td></tr>';
        //response test
        echo '<tr><td>' . __('Server self connect:', 'backwpup') . '</td><td>';
        $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));
        }
        $headers = wp_remote_retrieve_headers($raw_response);
        if (isset($headers['x-backwpup-ver']) && $headers['x-backwpup-ver'] != BackWPup::get_plugin_data('version')) {
            $test_result .= sprintf(__('The BackWPup HTTP response header returns a false value: "%s"', 'backwpup'), $headers['x-backwpup-ver']);
        }
        if (empty($test_result)) {
            _e('Response Test O.K.', 'backwpup');
        } else {
            echo $test_result;
        }
        echo '</td></tr>';
        //folder test
        echo '<tr><td>' . __('Temp folder:', 'backwpup') . '</td><td>';
        if (!is_dir(BackWPup::get_plugin_data('TEMP'))) {
            echo sprintf(__('Temp folder %s doesn\'t exist.', 'backwpup'), BackWPup::get_plugin_data('TEMP'));
        } elseif (!is_writable(BackWPup::get_plugin_data('TEMP'))) {
            echo sprintf(__('Temporary folder %s is not writable.', 'backwpup'), BackWPup::get_plugin_data('TEMP'));
        } else {
            echo BackWPup::get_plugin_data('TEMP');
        }
        echo '</td></tr>';
        echo '<tr><td>' . __('Log folder:', 'backwpup') . '</td><td>';
        if (!is_dir(get_site_option('backwpup_cfg_logfolder'))) {
            echo sprintf(__('Logs folder %s not exist.', 'backwpup'), get_site_option('backwpup_cfg_logfolder'));
        } elseif (!is_writable(get_site_option('backwpup_cfg_logfolder'))) {
            echo sprintf(__('Log folder %s is not writable.', 'backwpup'), get_site_option('backwpup_cfg_logfolder'));
        } else {
            echo get_site_option('backwpup_cfg_logfolder');
        }
        echo '</td></tr>';
        echo '<tr title=""><td>' . __('Server', 'backwpup') . '</td><td>' . $_SERVER['SERVER_SOFTWARE'] . '</td></tr>';
        echo '<tr title=""><td>' . __('Operating System', 'backwpup') . '</td><td>' . PHP_OS . '</td></tr>';
        echo '<tr title=""><td>' . __('PHP SAPI', 'backwpup') . '</td><td>' . PHP_SAPI . '</td></tr>';
        echo '<tr title=""><td>' . __('Current PHP user', 'backwpup') . '</td><td>' . get_current_user() . '</td></tr>';
        $text = (bool) ini_get('safe_mode') ? __('On', 'backwpup') : __('Off', 'backwpup');
        echo '<tr title=""><td>' . __('Safe Mode', 'backwpup') . '</td><td>' . $text . '</td></tr>';
        echo '<tr title="&gt;=30"><td>' . __('Maximum execution time', 'backwpup') . '</td><td>' . ini_get('max_execution_time') . ' ' . __('seconds', 'backwpup') . '</td></tr>';
        if (defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON) {
            echo '<tr title="ALTERNATE_WP_CRON"><td>' . __('Alternative WP Cron', 'backwpup') . '</td><td>' . __('On', 'backwpup') . '</td></tr>';
        } else {
            echo '<tr title="ALTERNATE_WP_CRON"><td>' . __('Alternative WP Cron', 'backwpup') . '</td><td>' . __('Off', 'backwpup') . '</td></tr>';
        }
        if (defined('DISABLE_WP_CRON') && DISABLE_WP_CRON) {
            echo '<tr title="DISABLE_WP_CRON"><td>' . __('Disabled WP Cron', 'backwpup') . '</td><td>' . __('On', 'backwpup') . '</td></tr>';
        } else {
            echo '<tr title="DISABLE_WP_CRON"><td>' . __('Disabled WP Cron', 'backwpup') . '</td><td>' . __('Off', 'backwpup') . '</td></tr>';
        }
        if (defined('FS_CHMOD_DIR')) {
            echo '<tr title="FS_CHMOD_DIR"><td>' . __('CHMOD Dir', 'backwpup') . '</td><td>' . FS_CHMOD_DIR . '</td></tr>';
        } else {
            echo '<tr title="FS_CHMOD_DIR"><td>' . __('CHMOD Dir', 'backwpup') . '</td><td>0755</td></tr>';
        }
        $now = localtime(time(), TRUE);
        echo '<tr title=""><td>' . __('Server Time', 'backwpup') . '</td><td>' . $now['tm_hour'] . ':' . $now['tm_min'] . '</td></tr>';
        echo '<tr title=""><td>' . __('Blog Time', 'backwpup') . '</td><td>' . date_i18n('H:i') . '</td></tr>';
        echo '<tr title=""><td>' . __('Blog Timezone', 'backwpup') . '</td><td>' . get_option('timezone_string') . '</td></tr>';
        echo '<tr title=""><td>' . __('Blog Time offset', 'backwpup') . '</td><td>' . sprintf(__('%s hours', 'backwpup'), get_option('gmt_offset')) . '</td></tr>';
        echo '<tr title="WPLANG"><td>' . __('Blog language', 'backwpup') . '</td><td>' . get_bloginfo('language') . '</td></tr>';
        echo '<tr title="utf8"><td>' . __('MySQL Client encoding', 'backwpup') . '</td><td>';
        echo defined('DB_CHARSET') ? DB_CHARSET : '';
        echo '</td></tr>';
        echo '<tr title="URF-8"><td>' . __('Blog charset', 'backwpup') . '</td><td>' . get_bloginfo('charset') . '</td></tr>';
        echo '<tr title="&gt;=128M"><td>' . __('PHP Memory limit', 'backwpup') . '</td><td>' . ini_get('memory_limit') . '</td></tr>';
        echo '<tr title="WP_MEMORY_LIMIT"><td>' . __('WP memory limit', 'backwpup') . '</td><td>' . WP_MEMORY_LIMIT . '</td></tr>';
        echo '<tr title="WP_MAX_MEMORY_LIMIT"><td>' . __('WP maximum memory limit', 'backwpup') . '</td><td>' . WP_MAX_MEMORY_LIMIT . '</td></tr>';
        echo '<tr title=""><td>' . __('Memory in use', 'backwpup') . '</td><td>' . size_format(@memory_get_usage(TRUE), 2) . '</td></tr>';
        //disabled PHP functions
        $disabled = ini_get('disable_functions');
        if (!empty($disabled)) {
            $disabledarry = explode(',', $disabled);
            echo '<tr title=""><td>' . __('Disabled PHP Functions:', 'backwpup') . '</td><td>';
            echo implode(', ', $disabledarry);
            echo '</td></tr>';
        }
        //Loaded PHP Extensions
        echo '<tr title=""><td>' . __('Loaded PHP Extensions:', 'backwpup') . '</td><td>';
        $extensions = get_loaded_extensions();
        sort($extensions);
        echo implode(', ', $extensions);
        echo '</td></tr>';
        echo '</table>';
        ?>
        </div>

		<?php 
        do_action('backwpup_page_settings_tab_content');
        ?>

        <p class="submit">
            <input type="submit" name="submit" id="submit" class="button-primary" value="<?php 
        _e('Save Changes', 'backwpup');
        ?>
" />
			&nbsp;
			<input type="submit" name="default_settings" id="default_settings" class="button-secondary" value="<?php 
        _e('Reset all settings to default', 'backwpup');
        ?>
" />
        </p>
    </form>
    </div>
	<?php 
    }
 /**
  * @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 Dropbox&#160;&hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']));
     }
     try {
         $dropbox = new BackWPup_Destination_Dropbox_API($job_object->job['dropboxroot']);
         // cahnge oauth1 to oauth2 token
         if (!empty($job_object->job['dropboxsecret']) && empty($job_object->job['dropboxtoken']['access_token'])) {
             $dropbox->setOAuthTokens(array('access_token' => $job_object->job['dropboxtoken'], 'oauth_token_secret' => BackWPup_Encryption::decrypt($job_object->job['dropboxsecret'])));
             $job_object->job['dropboxtoken'] = $dropbox->token_from_oauth1();
             BackWPup_Option::update($job_object->job['jobid'], 'dropboxtoken', $job_object->job['dropboxtoken']);
             BackWPup_Option::delete($job_object->job['jobid'], 'dropboxsecret');
         }
         // set the tokens
         $dropbox->setOAuthTokens($job_object->job['dropboxtoken']);
         //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'])) {
                 if ($job_object->is_debug()) {
                     $user = $info['display_name'] . ' (' . $info['email'] . ')';
                 } else {
                     $user = $info['display_name'];
                 }
                 $job_object->log(sprintf(__('Authenticated with Dropbox of user: %s', 'backwpup'), $user));
                 //Quota
                 if ($job_object->is_debug()) {
                     $dropboxfreespase = $info['quota_info']['quota'] - $info['quota_info']['shared'] - $info['quota_info']['normal'];
                     $job_object->log(sprintf(__('%s available on your Dropbox', 'backwpup'), size_format($dropboxfreespase, 2)));
                 }
             } else {
                 $job_object->log(__('Not Authenticated with Dropbox!', 'backwpup'), E_USER_ERROR);
                 return false;
             }
             $job_object->log(__('Uploading to Dropbox&#160;&hellip;', 'backwpup'));
         }
         // put the file
         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://content.dropboxapi.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://content.dropboxapi.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, YEAR_IN_SECONDS);
     } catch (Exception $e) {
         $job_object->log(E_USER_ERROR, sprintf(__('Dropbox API: %s', 'backwpup'), $e->getMessage()), $e->getFile(), $e->getLine());
         return false;
     }
     $job_object->substeps_done++;
     return true;
 }
 /**
  * @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;
 }
    /**
     *
     */
    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 
    }
 /**
  * Dumps the Database
  *
  * @param $job_object BackWPup_Job
  *
  * @return bool
  */
 public function job_run(BackWPup_Job $job_object)
 {
     $job_object->substeps_todo = 1;
     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 backup database&#160;&hellip;', 'backwpup'), $job_object->steps_data[$job_object->step_working]['STEP_TRY']));
     }
     //build filename
     if (empty($job_object->steps_data[$job_object->step_working]['dbdumpfile'])) {
         $job_object->steps_data[$job_object->step_working]['dbdumpfile'] = $job_object->generate_filename($job_object->job['dbdumpfile'], 'sql') . $job_object->job['dbdumpfilecompression'];
     }
     try {
         //Connect to Database
         $sql_dump = new BackWPup_MySQLDump(array('dumpfile' => BackWPup::get_plugin_data('TEMP') . $job_object->steps_data[$job_object->step_working]['dbdumpfile']));
         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(__('Connected to database %1$s on %2$s', 'backwpup'), DB_NAME, DB_HOST));
         }
         //Exclude Tables
         foreach ($sql_dump->tables_to_dump as $key => $table) {
             if (in_array($table, $job_object->job['dbdumpexclude'], true)) {
                 unset($sql_dump->tables_to_dump[$key]);
             }
         }
         //set steps must done
         $job_object->substeps_todo = count($sql_dump->tables_to_dump);
         if ($job_object->substeps_todo == 0) {
             $job_object->log(__('No tables to backup.', 'backwpup'), E_USER_WARNING);
             unset($sql_dump);
             return TRUE;
         }
         //dump head
         if (!isset($job_object->steps_data[$job_object->step_working]['is_head'])) {
             $sql_dump->dump_head(TRUE);
             $job_object->steps_data[$job_object->step_working]['is_head'] = TRUE;
         }
         //dump tables
         $i = 0;
         foreach ($sql_dump->tables_to_dump as $table) {
             if ($i < $job_object->substeps_done) {
                 $i++;
                 continue;
             }
             if (empty($job_object->steps_data[$job_object->step_working]['tables'][$table])) {
                 $num_records = $sql_dump->dump_table_head($table);
                 $job_object->steps_data[$job_object->step_working]['tables'][$table] = array('start' => 0, 'length' => 1000);
                 if ($job_object->is_debug()) {
                     $job_object->log(sprintf(__('Backup database table "%s" with "%s" records', 'backwpup'), $table, $num_records));
                 }
             }
             $while = true;
             while ($while) {
                 $dump_start_time = microtime(TRUE);
                 $done_records = $sql_dump->dump_table($table, $job_object->steps_data[$job_object->step_working]['tables'][$table]['start'], $job_object->steps_data[$job_object->step_working]['tables'][$table]['length']);
                 $dump_time = microtime(TRUE) - $dump_start_time;
                 if (empty($dump_time)) {
                     $dump_time = 0.01;
                 }
                 if ($done_records < $job_object->steps_data[$job_object->step_working]['tables'][$table]['length']) {
                     //that is the last chunk
                     $while = FALSE;
                 }
                 $job_object->steps_data[$job_object->step_working]['tables'][$table]['start'] = $job_object->steps_data[$job_object->step_working]['tables'][$table]['start'] + $done_records;
                 // dump time per record and set next length
                 $length = ceil($done_records / $dump_time * $job_object->get_restart_time());
                 if ($length > 25000 || 0 >= $job_object->get_restart_time()) {
                     $length = 25000;
                 }
                 if ($length < 1000) {
                     $length = 1000;
                 }
                 $job_object->steps_data[$job_object->step_working]['tables'][$table]['length'] = $length;
                 $job_object->do_restart_time();
             }
             $sql_dump->dump_table_footer($table);
             $job_object->substeps_done++;
             $i++;
             $job_object->update_working_data();
         }
         //dump footer
         $sql_dump->dump_footer();
         unset($sql_dump);
     } catch (Exception $e) {
         $job_object->log($e->getMessage(), E_USER_ERROR, $e->getFile(), $e->getLine());
         unset($sql_dump);
         return FALSE;
     }
     $filesize = filesize(BackWPup::get_plugin_data('TEMP') . $job_object->steps_data[$job_object->step_working]['dbdumpfile']);
     if (!is_file(BackWPup::get_plugin_data('TEMP') . $job_object->steps_data[$job_object->step_working]['dbdumpfile']) || $filesize < 1) {
         $job_object->log(__('MySQL backup file not created', 'backwpup'), E_USER_ERROR);
         return FALSE;
     } else {
         $job_object->additional_files_to_backup[] = BackWPup::get_plugin_data('TEMP') . $job_object->steps_data[$job_object->step_working]['dbdumpfile'];
         $job_object->log(sprintf(__('Added database dump "%1$s" with %2$s to backup file list', 'backwpup'), $job_object->steps_data[$job_object->step_working]['dbdumpfile'], size_format($filesize, 2)));
     }
     //cleanups
     unset($job_object->steps_data[$job_object->step_working]['tables']);
     $job_object->log(__('Database backup done!', 'backwpup'));
     return TRUE;
 }