wp/wp-content/plugins/wp-db-backup/wp-db-backup.php
changeset 7 cf61fcea0001
parent 0 d970ebf37754
child 18 be944660c56a
equal deleted inserted replaced
6:490d5cc509ed 7:cf61fcea0001
     1 <?php
     1 <?php
     2 /*
     2 /*
     3 Plugin Name: WordPress Database Backup
     3 Plugin Name: WordPress Database Backup
     4 Plugin URI: http://austinmatzko.com/wordpress-plugins/wp-db-backup/
     4 Plugin URI: https://github.com/matzko/wp-db-backup
     5 Description: On-demand backup of your WordPress database. Navigate to <a href="edit.php?page=wp-db-backup">Tools &rarr; Backup</a> to get started.
     5 Description: On-demand backup of your WordPress database. Navigate to <a href="edit.php?page=wp-db-backup">Tools &rarr; Backup</a> to get started.
     6 Author: Austin Matzko 
     6 Author: Austin Matzko
     7 Author URI: http://austinmatzko.com/
     7 Author URI: http://austinmatzko.com/
     8 Version: 2.2.4
     8 Version: 2.3.3
     9 
     9 
    10 Copyright 2013  Austin Matzko  (email : austin at pressedcode.com)
    10 Copyright 2018  Austin Matzko  (email : austin at pressedcode.com)
    11 
    11 
    12     This program is free software; you can redistribute it and/or modify
    12     This program is free software; you can redistribute it and/or modify
    13     it under the terms of the GNU General Public License as published by
    13     it under the terms of the GNU General Public License as published by
    14     the Free Software Foundation; either version 2 of the License, or
    14     the Free Software Foundation; either version 2 of the License, or
    15     (at your option) any later version.
    15     (at your option) any later version.
    22     You should have received a copy of the GNU General Public License
    22     You should have received a copy of the GNU General Public License
    23     along with this program; if not, write to the Free Software
    23     along with this program; if not, write to the Free Software
    24     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
    24     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
    25 */
    25 */
    26 
    26 
    27 /**
       
    28  * Change WP_BACKUP_DIR if you want to
       
    29  * use a different backup location
       
    30  */
       
    31 
       
    32 if ( ! defined('ABSPATH') ) {
    27 if ( ! defined('ABSPATH') ) {
    33 	die('Please do not load this file directly.');
    28 	die('Please do not load this file directly.');
    34 }
    29 }
    35 
    30 
    36 $rand = substr( md5( md5( DB_PASSWORD ) ), -5 );
    31 $rand = substr( md5( md5( DB_PASSWORD ) ), -5 );
    37 global $wpdbb_content_dir, $wpdbb_content_url, $wpdbb_plugin_dir;
    32 global $wpdbb_content_dir, $wpdbb_content_url;
    38 $wpdbb_content_dir = ( defined('WP_CONTENT_DIR') ) ? WP_CONTENT_DIR : ABSPATH . 'wp-content';
    33 $wpdbb_content_dir = ( defined('WP_CONTENT_DIR') ) ? WP_CONTENT_DIR : ABSPATH . 'wp-content';
    39 $wpdbb_content_url = ( defined('WP_CONTENT_URL') ) ? WP_CONTENT_URL : get_option('siteurl') . '/wp-content';
    34 $wpdbb_content_url = ( defined('WP_CONTENT_URL') ) ? WP_CONTENT_URL : get_option('siteurl') . '/wp-content';
    40 $wpdbb_plugin_dir = ( defined('WP_PLUGIN_DIR') ) ? WP_PLUGIN_DIR : $wpdbb_content_dir . '/plugins';
       
    41 
       
    42 if ( ! defined('WP_BACKUP_DIR') ) {
       
    43 	define('WP_BACKUP_DIR', $wpdbb_content_dir . '/backup-' . $rand . '/');
       
    44 }
       
    45 
       
    46 if ( ! defined('WP_BACKUP_URL') ) {
       
    47 	define('WP_BACKUP_URL', $wpdbb_content_url . '/backup-' . $rand . '/');
       
    48 }
       
    49 
    35 
    50 if ( ! defined('ROWS_PER_SEGMENT') ) {
    36 if ( ! defined('ROWS_PER_SEGMENT') ) {
    51 	define('ROWS_PER_SEGMENT', 100);
    37 	define('ROWS_PER_SEGMENT', 100);
    52 }
    38 }
    53 
    39 
    54 /** 
    40 /**
    55  * Set MOD_EVASIVE_OVERRIDE to true 
    41  * Set MOD_EVASIVE_OVERRIDE to true
    56  * and increase MOD_EVASIVE_DELAY 
    42  * and increase MOD_EVASIVE_DELAY
    57  * if the backup stops prematurely.
    43  * if the backup stops prematurely.
    58  */
    44  */
    59 // define('MOD_EVASIVE_OVERRIDE', false);
    45 // define('MOD_EVASIVE_OVERRIDE', false);
    60 if ( ! defined('MOD_EVASIVE_DELAY') ) {
    46 if ( ! defined('MOD_EVASIVE_DELAY') ) {
    61 	define('MOD_EVASIVE_DELAY', '500');
    47 	define('MOD_EVASIVE_DELAY', '500');
    69 	var $core_table_names = array();
    55 	var $core_table_names = array();
    70 	var $errors = array();
    56 	var $errors = array();
    71 	var $basename;
    57 	var $basename;
    72 	var $page_url;
    58 	var $page_url;
    73 	var $referer_check_key;
    59 	var $referer_check_key;
    74 	var $version = '2.1.5-alpha';
    60 	var $version = '2.3.3';
    75 
    61 
    76 	function module_check() {
    62 	function module_check() {
    77 		$mod_evasive = false;
    63 		$mod_evasive = false;
    78 		if ( defined( 'MOD_EVASIVE_OVERRIDE' ) && true === MOD_EVASIVE_OVERRIDE ) return true;
    64 		if ( defined( 'MOD_EVASIVE_OVERRIDE' ) && true === MOD_EVASIVE_OVERRIDE ) return true;
    79 		if ( ! defined( 'MOD_EVASIVE_OVERRIDE' ) || false === MOD_EVASIVE_OVERRIDE ) return false;
    65 		if ( ! defined( 'MOD_EVASIVE_OVERRIDE' ) || false === MOD_EVASIVE_OVERRIDE ) return false;
    80 		if ( function_exists('apache_get_modules') ) 
    66 		if ( function_exists('apache_get_modules') )
    81 			foreach( (array) apache_get_modules() as $mod ) 
    67 			foreach( (array) apache_get_modules() as $mod )
    82 				if ( false !== strpos($mod,'mod_evasive') || false !== strpos($mod,'mod_dosevasive') )
    68 				if ( false !== strpos($mod,'mod_evasive') || false !== strpos($mod,'mod_dosevasive') )
    83 					return true;
    69 					return true;
    84 		return false;
    70 		return false;
    85 	}
    71 	}
    86 
    72 
    87 	function wpdbBackup() {
    73 	function __construct() {
    88 		global $table_prefix, $wpdb;
    74 		global $table_prefix, $wpdb;
    89 		add_action('wp_ajax_save_backup_time', array(&$this, 'save_backup_time'));
    75 		add_action('wp_ajax_save_backup_time', array(&$this, 'save_backup_time'));
    90 		add_action('init', array(&$this, 'init_textdomain'));
    76 		add_action('init', array(&$this, 'init_textdomain'));
    91 		add_action('init', array(&$this, 'set_page_url'));
    77 		add_action('init', array(&$this, 'set_page_url'));
    92 		add_action('load-update-core.php', array(&$this, 'update_notice_action'));
    78 		add_action('admin_init', array(&$this, 'update_notice_action'));
    93 		add_action('wp_db_backup_cron', array(&$this, 'cron_backup'));
    79 		add_action('wp_db_backup_cron', array(&$this, 'cron_backup'));
    94 		add_action('wp_cron_daily', array(&$this, 'wp_cron_daily'));
    80 		add_action('wp_cron_daily', array(&$this, 'wp_cron_daily'));
    95 		add_filter('cron_schedules', array(&$this, 'add_sched_options'));
    81 		add_filter('cron_schedules', array(&$this, 'add_sched_options'));
    96 		add_filter('wp_db_b_schedule_choices', array(&$this, 'schedule_choices'));
    82 		add_filter('wp_db_b_schedule_choices', array(&$this, 'schedule_choices'));
    97 		
    83 
    98 		$table_prefix = ( isset( $table_prefix ) ) ? $table_prefix : $wpdb->prefix;
    84 		$table_prefix = ( isset( $table_prefix ) ) ? $table_prefix : $wpdb->prefix;
    99 		$datum = date("Ymd_B");
    85 		$datum = date("Ymd_B");
   100 		$this->backup_filename = DB_NAME . "_$table_prefix$datum.sql";
    86 		$this->backup_filename = DB_NAME . "_$table_prefix$datum.sql";
   101 
    87 
   102 		$possible_names = array(
    88 		$possible_names = array(
   120 		foreach( $possible_names as $name ) {
   106 		foreach( $possible_names as $name ) {
   121 			if ( isset( $wpdb->{$name} ) ) {
   107 			if ( isset( $wpdb->{$name} ) ) {
   122 				$this->core_table_names[] = $wpdb->{$name};
   108 				$this->core_table_names[] = $wpdb->{$name};
   123 			}
   109 			}
   124 		}
   110 		}
   125 	
   111 
   126 		$this->backup_dir = trailingslashit(apply_filters('wp_db_b_backup_dir', WP_BACKUP_DIR));
   112 		$requested_temp_dir = sanitize_text_field($_GET['wp_db_temp_dir']);
       
   113 		$this->backup_dir = trailingslashit(apply_filters('wp_db_b_backup_dir', (isset($requested_temp_dir) && is_writable($requested_temp_dir)) ? $requested_temp_dir : get_temp_dir()));
   127 		$this->basename = 'wp-db-backup';
   114 		$this->basename = 'wp-db-backup';
   128 	
   115 
   129 		$this->referer_check_key = $this->basename . '-download_' . DB_NAME;
   116 		$this->referer_check_key = $this->basename . '-download_' . DB_NAME;
   130 		if (isset($_POST['do_backup'])) {
   117 		if (isset($_POST['do_backup'])) {
   131 			$this->wp_secure('fatal');
   118 			$this->wp_secure('fatal');
   132 			check_admin_referer($this->referer_check_key);
   119 			check_admin_referer($this->referer_check_key);
   133 			$this->can_user_backup('main');
   120 			$this->can_user_backup('main');
       
   121 
   134 			// save exclude prefs
   122 			// save exclude prefs
   135 
   123 			update_option('wp_db_backup_excs', array(
   136 			$exc_revisions = isset( $_POST['exclude-revisions'] ) ? (array) $_POST['exclude-revisions'] : array();
   124 				'revisions' => $this->get_revisions_to_exclude(),
   137 			$exc_spam = isset( $_POST['exclude-spam'] ) ? (array) $_POST['exclude-spam'] : array();
   125 				'spam' => $this->get_spam_to_exclude()
   138 			update_option('wp_db_backup_excs', array('revisions' => $exc_revisions, 'spam' => $exc_spam));
   126 			));
   139 			switch($_POST['do_backup']) {
   127 			switch($_POST['do_backup']) {
   140 			case 'backup':
   128 			case 'backup':
   141 				add_action('init', array(&$this, 'perform_backup'));
   129 				add_action('init', array(&$this, 'perform_backup'));
   142 				break;
   130 				break;
   143 			case 'fragments':
   131 			case 'fragments':
   144 				add_action('admin_menu', array(&$this, 'fragment_menu'));
   132 				add_action('admin_menu', array(&$this, 'fragment_menu'));
   145 				break;				
   133 				break;
   146 			}
   134 			}
   147 		} elseif (isset($_GET['fragment'] )) {
   135 		} elseif (isset($_GET['fragment'] )) {
   148 			$this->can_user_backup('frame');
   136 			$this->can_user_backup('frame');
   149 			add_action('init', array(&$this, 'init'));
   137 			add_action('init', array(&$this, 'init'));
   150 		} elseif (isset($_GET['backup'] )) {
   138 		} elseif (isset($_GET['backup'] )) {
   152 			add_action('init', array(&$this, 'init'));
   140 			add_action('init', array(&$this, 'init'));
   153 		} else {
   141 		} else {
   154 			add_action('admin_menu', array(&$this, 'admin_menu'));
   142 			add_action('admin_menu', array(&$this, 'admin_menu'));
   155 		}
   143 		}
   156 	}
   144 	}
   157 	
   145 
   158 	function init() {
   146 	function init() {
   159 		$this->can_user_backup();
   147 		$this->can_user_backup();
   160 		if (isset($_GET['backup'])) {
   148 		if (isset($_GET['backup'])) {
   161 			$via = isset($_GET['via']) ? $_GET['via'] : 'http';
   149 			$via = isset($_GET['via']) ? sanitize_text_field($_GET['via']) : 'http';
   162 			
   150 
   163 			$this->backup_file = $_GET['backup'];
   151 			$this->backup_file = sanitize_text_field($_GET['backup']);
   164 			$this->validate_file($this->backup_file);
   152 			$this->validate_file($this->backup_file);
   165 
   153 
   166 			switch($via) {
   154 			switch($via) {
   167 			case 'smtp':
   155 			case 'smtp':
   168 			case 'email':
   156 			case 'email':
   169 				$success = $this->deliver_backup($this->backup_file, 'smtp', $_GET['recipient'], 'frame');
   157 				$success = $this->deliver_backup($this->backup_file, 'smtp', sanitize_text_field($_GET['recipient']), 'frame');
   170 				$this->error_display( 'frame' );
   158 				$this->error_display( 'frame' );
   171 				if ( $success ) {
   159 				if ( $success ) {
   172 					echo '
   160 					echo '
   173 						<!-- ' . $via . ' -->
   161 						<!-- ' . $via . ' -->
   174 						<script type="text/javascript"><!--\\
   162 						<script type="text/javascript"><!--\\
   175 					';
   163 					';
   176 					echo '
   164 					echo '
   177 						alert("' . __('Backup Complete!','wp-db-backup') . '");
   165 						alert("' . __('Backup Complete!','wp-db-backup') . '");
   178 						window.onbeforeunload = null; 
   166 						window.onbeforeunload = null;
   179 						</script>
   167 						</script>
   180 					';
   168 					';
   181 				}
   169 				}
   182 				break;
   170 				break;
   183 			default:
   171 			default:
   184 				$success = $this->deliver_backup($this->backup_file, $via);
   172 				$success = $this->deliver_backup($this->backup_file, $via);
   185 				echo $this->error_display( 'frame', false );
   173 				echo $this->error_display( 'frame', false );
   186 				
   174 
   187 				if ( $success ) {
   175 				if ( $success ) {
   188 					echo '
   176 					echo '
   189 					<script type="text/javascript">
   177 					<script type="text/javascript">
   190 						window.parent.setProgress("' . __('Backup Complete!','wp-db-backup') . '");
   178 						window.parent.setProgress("' . __('Backup Complete!','wp-db-backup') . '");
   191 					</script>
   179 					</script>
   193 				}
   181 				}
   194 			}
   182 			}
   195 			exit;
   183 			exit;
   196 		}
   184 		}
   197 		if (isset($_GET['fragment'] )) {
   185 		if (isset($_GET['fragment'] )) {
   198 			list($table, $segment, $filename) = explode(':', $_GET['fragment']);
   186 			list($table, $segment, $filename) = explode(':', sanitize_text_field($_GET['fragment']));
   199 			$this->validate_file($filename);
   187 			$this->validate_file($filename);
   200 			$this->backup_fragment($table, $segment, $filename);
   188 			$this->backup_fragment($table, $segment, $filename);
   201 		}
   189 		}
   202 
   190 
   203 		die();
   191 		die();
   214 		$base = ( function_exists('site_url') ) ? site_url('', 'admin') : get_option('siteurl');
   202 		$base = ( function_exists('site_url') ) ? site_url('', 'admin') : get_option('siteurl');
   215 		$this->page_url = add_query_arg( $query_args, $base . '/wp-admin/edit.php');
   203 		$this->page_url = add_query_arg( $query_args, $base . '/wp-admin/edit.php');
   216 	}
   204 	}
   217 
   205 
   218 	/*
   206 	/*
   219 	 * Add a link to back up your database when doing a core upgrade 
   207 	 * Add a link to back up your database when doing a core upgrade.
   220 	 */
   208 	 */
   221 	function update_notice_action() {
   209 	function update_notice_action() {
   222 		if ( 'upgrade-core' == $_REQUEST['action'] ) :
   210 		global $pagenow;
       
   211 		if (
       
   212 			(
       
   213 				isset($_REQUEST['action'])
       
   214 				&& ('upgrade-core' == $_REQUEST['action'])
       
   215 			)
       
   216 			|| (
       
   217 				!empty($pagenow) && ('update-core.php' == $pagenow)
       
   218 			)
       
   219 		) :
   223 			ob_start(array(&$this, 'update_notice'));
   220 			ob_start(array(&$this, 'update_notice'));
   224 			add_action('admin_footer', create_function('', 'ob_end_flush();'));
   221 			add_action('admin_footer', create_function('', 'ob_end_flush();'));
   225 		endif;
   222 		endif;
   226 	}
   223 	}
   227 		function update_notice($text = '') {
   224 
   228 			$pattern = '#(<a href\="' . __('http://codex.wordpress.org/WordPress_Backups') . '">.*?</p>)#';
   225 	function update_notice($text = '') {
   229 			$replace = '$1' . "\n<p>" . sprintf(__('Click <a href="%s" target="_blank">here</a> to back up your database using the WordPress Database Backup plugin. <strong>Note:</strong> WordPress Database Backup does <em>not</em> back up your files, just your database.', 'wp-db-backup'), 'tools.php?page=wp-db-backup') . "</p>\n"; 
   226 		$pattern = '#(<a href\="' . __('http://codex.wordpress.org/WordPress_Backups') . '">.*?</p>)#';
   230 			$text = preg_replace($pattern, $replace, $text);
   227 		$replace = '$1' . "\n<p>" . sprintf(__('Click <a href="%s" target="_blank">here</a> to back up your database using the WordPress Database Backup plugin. <strong>Note:</strong> WordPress Database Backup does <em>not</em> back up your files, just your database.', 'wp-db-backup'), 'tools.php?page=wp-db-backup') . "</p>\n";
   231 			return $text;
   228 		$text = preg_replace($pattern, $replace, $text);
   232 		}
   229 		return $text;
       
   230 	}
   233 
   231 
   234 	function build_backup_script() {
   232 	function build_backup_script() {
   235 		global $table_prefix, $wpdb;
   233 		global $table_prefix, $wpdb;
   236 	
   234 
   237 		echo "<div class='wrap'>";
   235 		echo "<div class='wrap'>";
   238 		echo 	'<fieldset class="options"><legend>' . __('Progress','wp-db-backup') . '</legend>
   236 		echo '<fieldset class="options"><legend>' . __('Progress','wp-db-backup') . '</legend>
   239 			<p><strong>' .
   237 			<p><strong>' .
   240 				__('DO NOT DO THE FOLLOWING AS IT WILL CAUSE YOUR BACKUP TO FAIL:','wp-db-backup').
   238 				__('DO NOT DO THE FOLLOWING AS IT WILL CAUSE YOUR BACKUP TO FAIL:','wp-db-backup').
   241 			'</strong></p>
   239 			'</strong></p>
   242 			<ol>
   240 			<ol>
   243 				<li>'.__('Close this browser','wp-db-backup').'</li>
   241 				<li>'.__('Close this browser','wp-db-backup').'</li>
   269 				errors.innerHTML = errors.innerHTML + str + "<br />";
   267 				errors.innerHTML = errors.innerHTML + str + "<br />";
   270 			}
   268 			}
   271 
   269 
   272 			function backup(table, segment) {
   270 			function backup(table, segment) {
   273 				var fram = document.getElementById("backuploader");
   271 				var fram = document.getElementById("backuploader");
   274 				fram.src = "' . $this->page_url . '&fragment=" + table + ":" + segment + ":' . $this->backup_filename . ':";
   272 				fram.src = "' . $this->page_url . '&fragment=" + table + ":" + segment + ":' . $this->backup_filename . ':&wp_db_temp_dir=' . $this->backup_dir . '";
   275 			}
   273 			}
   276 			
   274 
   277 			var curStep = 0;
   275 			var curStep = 0;
   278 			
   276 
   279 			function nextStep() {
   277 			function nextStep() {
   280 				backupStep(curStep);
   278 				backupStep(curStep);
   281 				curStep++;
   279 				curStep++;
   282 			}
   280 			}
   283 			
   281 
   284 			function finishBackup() {
   282 			function finishBackup() {
   285 				var fram = document.getElementById("backuploader");				
   283 				var fram = document.getElementById("backuploader");
   286 				setMeter(100);
   284 				setMeter(100);
   287 		';
   285 		';
   288 
   286 
   289 		$download_uri = add_query_arg('backup', $this->backup_filename, $this->page_url);
   287 		$download_uri = add_query_arg('backup', $this->backup_filename, $this->page_url);
   290 		switch($_POST['deliver']) {
   288 		switch($_POST['deliver']) {
   291 		case 'http':
   289 		case 'http':
   292 			echo '
   290 			echo '
   293 				setProgress("' . __('Preparing download.','wp-db-backup') . '");
   291 				setProgress("' . __('Preparing download.','wp-db-backup') . '");
   294 				window.onbeforeunload = null; 
   292 				window.onbeforeunload = null;
   295 				fram.src = "' . $download_uri . '";
   293 				fram.src = "' . $download_uri . '";
   296 				
   294 
   297 				setTimeout( function() {
   295 				setTimeout( function() {
   298 					var secondFrame = document.createElement("iframe");				
   296 					var secondFrame = document.createElement("iframe");
   299 					fram.parentNode.insertBefore(secondFrame, fram);
   297 					fram.parentNode.insertBefore(secondFrame, fram);
   300 					secondFrame.src = "' . $download_uri . '&download-retry=1";
   298 					secondFrame.src = "' . $download_uri . '&download-retry=1";
   301 				}, 30000 );
   299 				}, 30000 );
   302 			';
   300 			';
   303 			break;
   301 			break;
   304 		case 'smtp':
   302 		case 'smtp':
   305 			if ( get_option('wpdb_backup_recip') != $_POST['backup_recipient'] ) {
   303 			$email = sanitize_text_field(wp_unslash($_POST['backup_recipient']));
   306 				update_option('wpdb_backup_recip', $_POST['backup_recipient'] );
   304 			if ( get_option('wpdb_backup_recip') != $email) {
       
   305 				update_option('wpdb_backup_recip', $email);
   307 			}
   306 			}
   308 			echo '
   307 			echo '
   309 				setProgress("' . sprintf(__('Your backup has been emailed to %s','wp-db-backup'), $_POST['backup_recipient']) . '");
   308 				setProgress("' . sprintf(__('Your backup has been emailed to %s','wp-db-backup'), $email) . '");
   310 				window.onbeforeunload = null; 
   309 				window.onbeforeunload = null;
   311 				fram.src = "' . $download_uri . '&via=email&recipient=' . $_POST['backup_recipient'] . '";
   310 				fram.src = "' . $download_uri . '&via=email&recipient=' . $email . '";
   312 			';
   311 			';
   313 			break;
   312 			break;
   314 		default:
   313 		default:
   315 			echo '
   314 			echo '
   316 				setProgress("' . __('Backup Complete!','wp-db-backup') . '");
   315 				setProgress("' . __('Backup Complete!','wp-db-backup') . '");
   317 				window.onbeforeunload = null; 
   316 				window.onbeforeunload = null;
   318 			';
   317 			';
   319 		}
   318 		}
   320 		
   319 
   321 		echo '
   320 		echo '
   322 			}
   321 			}
   323 			
   322 
   324 			function backupStep(step) {
   323 			function backupStep(step) {
   325 				switch(step) {
   324 				switch(step) {
   326 				case 0: backup("", 0); break;
   325 				case 0: backup("", 0); break;
   327 		';
   326 		';
   328 		
   327 
   329 		$also_backup = array();
   328 		$also_backup = $this->get_post_data_array('other_tables');
   330 		if (isset($_POST['other_tables'])) {
   329 		$core_tables = $this->get_post_data_array('core_tables');
   331 			$also_backup = $_POST['other_tables'];
       
   332 		} else {
       
   333 			$also_backup = array();
       
   334 		}
       
   335 		$core_tables = $_POST['core_tables'];
       
   336 		$tables = array_merge($core_tables, $also_backup);
   330 		$tables = array_merge($core_tables, $also_backup);
   337 		$step_count = 1;
   331 		$step_count = 1;
   338 		foreach ($tables as $table) {
   332 		foreach ($tables as $table) {
   339 			$rec_count = $wpdb->get_var("SELECT count(*) FROM {$table}");
   333 			$rec_count = $wpdb->get_var("SELECT count(*) FROM {$table}");
   340 			$rec_segments = ceil($rec_count / ROWS_PER_SEGMENT);
   334 			$rec_segments = ceil($rec_count / ROWS_PER_SEGMENT);
   351 			} while($table_count < $rec_segments);
   345 			} while($table_count < $rec_segments);
   352 			echo "case {$step_count}: {$delay}backup(\"{$table}\", -1){$delay_time}; break;\n";
   346 			echo "case {$step_count}: {$delay}backup(\"{$table}\", -1){$delay_time}; break;\n";
   353 			$step_count++;
   347 			$step_count++;
   354 		}
   348 		}
   355 		echo "case {$step_count}: finishBackup(); break;";
   349 		echo "case {$step_count}: finishBackup(); break;";
   356 		
   350 
   357 		echo '
   351 		echo '
   358 				}
   352 				}
   359 				if(step != 0) setMeter(100 * step / ' . $step_count . ');
   353 				if(step != 0) setMeter(100 * step / ' . $step_count . ');
   360 			}
   354 			}
   361 
   355 
   367 		$this->backup_menu();
   361 		$this->backup_menu();
   368 	}
   362 	}
   369 
   363 
   370 	function backup_fragment($table, $segment, $filename) {
   364 	function backup_fragment($table, $segment, $filename) {
   371 		global $table_prefix, $wpdb;
   365 		global $table_prefix, $wpdb;
   372 			
   366 
   373 		echo "$table:$segment:$filename";
   367 		echo "$table:$segment:$filename";
   374 		
   368 
   375 		if($table == '') {
   369 		if($table == '') {
   376 			$msg = __('Creating backup file...','wp-db-backup');
   370 			$msg = __('Creating backup file...','wp-db-backup');
   377 		} else {
   371 		} else {
   378 			if($segment == -1) {
   372 			if($segment == -1) {
   379 				$msg = sprintf(__('Finished backing up table \\"%s\\".','wp-db-backup'), $table);
   373 				$msg = sprintf(__('Finished backing up table \\"%s\\".','wp-db-backup'), $table);
   380 			} else {
   374 			} else {
   381 				$msg = sprintf(__('Backing up table \\"%s\\"...','wp-db-backup'), $table);
   375 				$msg = sprintf(__('Backing up table \\"%s\\"...','wp-db-backup'), $table);
   382 			}
   376 			}
   383 		}
   377 		}
   384 		
   378 
   385 		if (is_writable($this->backup_dir)) {
   379 		if (is_writable($this->backup_dir)) {
   386 			$this->fp = $this->open($this->backup_dir . $filename, 'a');
   380 			$this->fp = $this->open($this->backup_dir . $filename, 'a');
   387 			if(!$this->fp) {
   381 			if(!$this->fp) {
   388 				$this->error(__('Could not open the backup file for writing!','wp-db-backup'));
   382 				$this->error(__('Could not open the backup file for writing!','wp-db-backup'));
   389 				$this->error(array('loc' => 'frame', 'kind' => 'fatal', 'msg' =>  __('The backup file could not be saved.  Please check the permissions for writing to your backup directory and try again.','wp-db-backup')));
   383 				$this->error(array('loc' => 'frame', 'kind' => 'fatal', 'msg' =>  __('The backup file could not be saved.  Please check the permissions for writing to your backup directory and try again.','wp-db-backup')));
   390 			}
   384 			}
   391 			else {
   385 			else {
   392 				if($table == '') {		
   386 				if($table == '') {
   393 					//Begin new backup of MySql
   387 					//Begin new backup of MySql
   394 					$this->stow("# " . __('WordPress MySQL database backup','wp-db-backup') . "\n");
   388 					$this->stow("# " . __('WordPress MySQL database backup','wp-db-backup') . "\n");
   395 					$this->stow("#\n");
   389 					$this->stow("#\n");
   396 					$this->stow("# " . sprintf(__('Generated: %s','wp-db-backup'),date("l j. F Y H:i T")) . "\n");
   390 					$this->stow("# " . sprintf(__('Generated: %s','wp-db-backup'),date("l j. F Y H:i T")) . "\n");
   397 					$this->stow("# " . sprintf(__('Hostname: %s','wp-db-backup'),DB_HOST) . "\n");
   391 					$this->stow("# " . sprintf(__('Hostname: %s','wp-db-backup'),DB_HOST) . "\n");
   403 						if ( !ini_get('safe_mode')) @set_time_limit(15*60);
   397 						if ( !ini_get('safe_mode')) @set_time_limit(15*60);
   404 						// Create the SQL statements
   398 						// Create the SQL statements
   405 						$this->stow("# --------------------------------------------------------\n");
   399 						$this->stow("# --------------------------------------------------------\n");
   406 						$this->stow("# " . sprintf(__('Table: %s','wp-db-backup'),$this->backquote($table)) . "\n");
   400 						$this->stow("# " . sprintf(__('Table: %s','wp-db-backup'),$this->backquote($table)) . "\n");
   407 						$this->stow("# --------------------------------------------------------\n");
   401 						$this->stow("# --------------------------------------------------------\n");
   408 					}			
   402 					}
   409 					$this->backup_table($table, $segment);
   403 					$this->backup_table($table, $segment);
   410 				}
   404 				}
   411 			}
   405 			}
   412 		} else {
   406 		} else {
   413 			$this->error(array('kind' => 'fatal', 'loc' => 'frame', 'msg' => __('The backup directory is not writeable!  Please check the permissions for writing to your backup directory and try again.','wp-db-backup')));
   407 			$this->error(array('kind' => 'fatal', 'loc' => 'frame', 'msg' => __('The backup directory is not writeable!  Please check the permissions for writing to your backup directory and try again.','wp-db-backup')));
   414 		}
   408 		}
   415 
   409 
   416 		if($this->fp) $this->close($this->fp);
   410 		if($this->fp) $this->close($this->fp);
   417 		
   411 
   418 		$this->error_display('frame');
   412 		$this->error_display('frame');
   419 
   413 
   420 		echo '<script type="text/javascript"><!--//
   414 		echo '<script type="text/javascript"><!--//
   421 		var msg = "' . $msg . '";
   415 		var msg = "' . $msg . '";
   422 		window.parent.setProgress(msg);
   416 		window.parent.setProgress(msg);
   428 
   422 
   429 	function perform_backup() {
   423 	function perform_backup() {
   430 		// are we backing up any other tables?
   424 		// are we backing up any other tables?
   431 		$also_backup = array();
   425 		$also_backup = array();
   432 		if (isset($_POST['other_tables']))
   426 		if (isset($_POST['other_tables']))
   433 			$also_backup = $_POST['other_tables'];
   427 			$also_backup = sanitize_text_field($_POST['other_tables']);
   434 		$core_tables = $_POST['core_tables'];
   428 		$core_tables = sanitize_text_field($_POST['core_tables']);
   435 		$this->backup_file = $this->db_backup($core_tables, $also_backup);
   429 		$this->backup_file = $this->db_backup($core_tables, $also_backup);
   436 		if (false !== $this->backup_file) {
   430 		if (false !== $this->backup_file) {
   437 			if ('smtp' == $_POST['deliver']) {
   431 			if ('smtp' == $_POST['deliver']) {
   438 				$this->deliver_backup($this->backup_file, $_POST['deliver'], $_POST['backup_recipient'], 'main');
   432 				$email = sanitize_text_field(wp_unslash($_POST['backup_recipient']));
   439 				if ( get_option('wpdb_backup_recip') != $_POST['backup_recipient'] ) {
   433 				$this->deliver_backup($this->backup_file, sanitize_text_field($_POST['deliver']), $email, 'main');
   440 					update_option('wpdb_backup_recip', $_POST['backup_recipient'] );
   434 				if ( get_option('wpdb_backup_recip') != $email ) {
       
   435 					update_option('wpdb_backup_recip', $email );
   441 				}
   436 				}
   442 				wp_redirect($this->page_url);
   437 				wp_redirect($this->page_url);
   443 			} elseif ('http' == $_POST['deliver']) {
   438 			} elseif ('http' == $_POST['deliver']) {
   444 				$download_uri = add_query_arg('backup',$this->backup_file,$this->page_url);
   439 				$download_uri = add_query_arg('backup',$this->backup_file,$this->page_url);
   445 				wp_redirect($download_uri); 
   440 				wp_redirect($download_uri);
   446 				exit;
   441 				exit;
   447 			}
   442 			}
   448 			// we do this to say we're done.
   443 			// we do this to say we're done.
   449 			$this->backup_complete = true;
   444 			$this->backup_complete = true;
   450 		}
   445 		}
   477 					for(var i=0; i < t[k].p.length; i++) {
   472 					for(var i=0; i < t[k].p.length; i++) {
   478 						if(t[k].name == t[k].p[i].getAttribute('name')) {
   473 						if(t[k].name == t[k].p[i].getAttribute('name')) {
   479 							t[k].p[i].id = k + '-table-' + i;
   474 							t[k].p[i].id = k + '-table-' + i;
   480 							t[k].p[i].onkeyup = t[k].p[i].onclick = function(e) {
   475 							t[k].p[i].onkeyup = t[k].p[i].onclick = function(e) {
   481 								e = e ? e : event;
   476 								e = e ? e : event;
   482 								if ( 16  == e.keyCode ) 
   477 								if ( 16  == e.keyCode )
   483 									return;
   478 									return;
   484 								var match = /([\w-]*)-table-(\d*)/.exec(this.id);
   479 								var match = /([\w-]*)-table-(\d*)/.exec(this.id);
   485 								var listname = match[1];
   480 								var listname = match[1];
   486 								var that = match[2];
   481 								var that = match[2];
   487 								if ( null === t[listname].s )
   482 								if ( null === t[listname].s )
   497 						}
   492 						}
   498 					}
   493 					}
   499 				}
   494 				}
   500 
   495 
   501 				<?php if ( function_exists('wp_schedule_event') ) : // needs to be at least WP 2.1 for ajax ?>
   496 				<?php if ( function_exists('wp_schedule_event') ) : // needs to be at least WP 2.1 for ajax ?>
   502 				if ( 'undefined' == typeof XMLHttpRequest ) 
   497 				if ( 'undefined' == typeof XMLHttpRequest )
   503 					var xml = new ActiveXObject( navigator.userAgent.indexOf('MSIE 5') >= 0 ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP' );
   498 					var xml = new ActiveXObject( navigator.userAgent.indexOf('MSIE 5') >= 0 ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP' );
   504 				else
   499 				else
   505 					var xml = new XMLHttpRequest();
   500 					var xml = new XMLHttpRequest();
   506 
   501 
   507 				var initTimeChange = function() {
   502 				var initTimeChange = function() {
   508 					var timeWrap = document.getElementById('backup-time-wrap');
   503 					var timeWrap = document.getElementById('backup-time-wrap');
   509 					var backupTime = document.getElementById('next-backup-time');
   504 					var backupTime = document.getElementById('next-backup-time');
   510 					if ( !! timeWrap && !! backupTime && ( 1 == <?php
   505 					if ( !! timeWrap && !! backupTime && ( 1 == <?php
   511 						echo (int) ( 'en' == strtolower( substr( get_locale(), 0, 2 ) ) );	
   506 						echo (int) ( 'en' == strtolower( substr( get_locale(), 0, 2 ) ) );
   512 					?> ) ) {
   507 					?> ) ) {
   513 						var span = document.createElement('span');
   508 						var span = document.createElement('span');
   514 						span.className = 'submit';
   509 						span.className = 'submit';
   515 						span.id = 'change-wrap';
   510 						span.id = 'change-wrap';
   516 						span.innerHTML = '<input type="submit" id="change-backup-time" name="change-backup-time" value="<?php _e('Change','wp-db-backup'); ?>" />';
   511 						span.innerHTML = '<input type="submit" id="change-backup-time" name="change-backup-time" value="<?php _e('Change','wp-db-backup'); ?>" />';
   528 					mainText.focus();
   523 					mainText.focus();
   529 					var saveTButton = document.getElementById('save-backup-time');
   524 					var saveTButton = document.getElementById('save-backup-time');
   530 					if ( !! saveTButton )
   525 					if ( !! saveTButton )
   531 						saveTButton.onclick = function(e) { saveTime(backupTime, mainText); return false; };
   526 						saveTButton.onclick = function(e) { saveTime(backupTime, mainText); return false; };
   532 					if ( !! mainText )
   527 					if ( !! mainText )
   533 						mainText.onkeydown = function(e) { 
   528 						mainText.onkeydown = function(e) {
   534 							e = e || window.event;
   529 							e = e || window.event;
   535 							if ( 13 == e.keyCode ) {
   530 							if ( 13 == e.keyCode ) {
   536 								saveTime(backupTime, mainText);
   531 								saveTime(backupTime, mainText);
   537 								return false;
   532 								return false;
   538 							}
   533 							}
   590 					font-size: larger;
   585 					font-size: larger;
   591 					font-weight: bold;
   586 					font-weight: bold;
   592 					margin-bottom: .5em;
   587 					margin-bottom: .5em;
   593 					padding: 1em;
   588 					padding: 1em;
   594 				}
   589 				}
   595 		
   590 
   596 				fieldset.options .instructions {
   591 				fieldset.options .instructions {
   597 					font-size: smaller;
   592 					font-size: smaller;
   598 				}
   593 				}
   599 
   594 
   600 				fieldset.options ul {
   595 				fieldset.options ul {
   606 
   601 
   607 				fieldset.options .submit {
   602 				fieldset.options .submit {
   608 					border-top: none;
   603 					border-top: none;
   609 				}
   604 				}
   610 		</style>
   605 		</style>
   611 		<?php 
   606 		<?php
   612 	}
   607 	}
   613 
   608 
   614 	function admin_load() {
   609 	function admin_load() {
   615 		add_action('admin_head', array(&$this, 'admin_header'));
   610 		add_action('admin_head', array(&$this, 'admin_header'));
   616 	}
   611 	}
   636 	function fragment_menu() {
   631 	function fragment_menu() {
   637 		$page_hook = add_management_page(__('Backup','wp-db-backup'), __('Backup','wp-db-backup'), 'import', $this->basename, array(&$this, 'build_backup_script'));
   632 		$page_hook = add_management_page(__('Backup','wp-db-backup'), __('Backup','wp-db-backup'), 'import', $this->basename, array(&$this, 'build_backup_script'));
   638 		add_action('load-' . $page_hook, array(&$this, 'admin_load'));
   633 		add_action('load-' . $page_hook, array(&$this, 'admin_load'));
   639 	}
   634 	}
   640 
   635 
   641 	/** 
   636 	/**
   642 	 * Add WP-DB-Backup-specific help options to the 2.7 =< WP contextual help menu
   637 	 * Add WP-DB-Backup-specific help options to the 2.7 =< WP contextual help menu
   643 	 * @return string The text of the help menu.
   638 	 * @return string The text of the help menu.
   644 	 */
   639 	 */
   645 	function help_menu() {
   640 	function help_menu() {
   646 		$text = "\n<a href=\"http://wordpress.org/extend/plugins/wp-db-backup/faq/\" target=\"_blank\">" . __('FAQ', 'wp-db-backup') . '</a>';
   641 		$text = "\n<a href=\"http://wordpress.org/extend/plugins/wp-db-backup/faq/\" target=\"_blank\">" . __('FAQ', 'wp-db-backup') . '</a>';
   672 	 */
   667 	 */
   673 	function sql_addslashes($a_string = '', $is_like = false) {
   668 	function sql_addslashes($a_string = '', $is_like = false) {
   674 		if ($is_like) $a_string = str_replace('\\', '\\\\\\\\', $a_string);
   669 		if ($is_like) $a_string = str_replace('\\', '\\\\\\\\', $a_string);
   675 		else $a_string = str_replace('\\', '\\\\', $a_string);
   670 		else $a_string = str_replace('\\', '\\\\', $a_string);
   676 		return str_replace('\'', '\\\'', $a_string);
   671 		return str_replace('\'', '\\\'', $a_string);
   677 	} 
   672 	}
   678 
   673 
   679 	/**
   674 	/**
   680 	 * Add backquotes to tables and db-names in
   675 	 * Add backquotes to tables and db-names in
   681 	 * SQL queries. Taken from phpMyAdmin.
   676 	 * SQL queries. Taken from phpMyAdmin.
   682 	 */
   677 	 */
   683 	function backquote($a_name) {
   678 	function backquote($a_name) {
   684 		if (!empty($a_name) && $a_name != '*') {
   679 		if (!empty($a_name) && $a_name != '*') {
   685 			if (is_array($a_name)) {
   680 			if (is_array($a_name)) {
   686 				$result = array();
   681 				$result = array();
   687 				reset($a_name);
   682 				reset($a_name);
   688 				while(list($key, $val) = each($a_name)) 
   683 				while(list($key, $val) = each($a_name))
   689 					$result[$key] = '`' . $val . '`';
   684 					$result[$key] = '`' . $val . '`';
   690 				return $result;
   685 				return $result;
   691 			} else {
   686 			} else {
   692 				return '`' . $a_name . '`';
   687 				return '`' . $a_name . '`';
   693 			}
   688 			}
   694 		} else {
   689 		} else {
   695 			return $a_name;
   690 			return $a_name;
   696 		}
   691 		}
   697 	} 
   692 	}
   698 
   693 
   699 	function open($filename = '', $mode = 'w') {
   694 	function open($filename = '', $mode = 'w') {
   700 		if ('' == $filename) return false;
   695 		if ('' == $filename) return false;
   701 		$fp = @fopen($filename, $mode);
   696 		$fp = @fopen($filename, $mode);
   702 		return $fp;
   697 		return $fp;
   713 	 */
   708 	 */
   714 	function stow($query_line) {
   709 	function stow($query_line) {
   715 		if(false === @fwrite($this->fp, $query_line))
   710 		if(false === @fwrite($this->fp, $query_line))
   716 			$this->error(__('There was an error writing a line to the backup script:','wp-db-backup') . '  ' . $query_line . '  ' . $php_errormsg);
   711 			$this->error(__('There was an error writing a line to the backup script:','wp-db-backup') . '  ' . $query_line . '  ' . $php_errormsg);
   717 	}
   712 	}
   718 	
   713 
   719 	/**
   714 	/**
   720 	 * Logs any error messages
   715 	 * Logs any error messages
   721 	 * @param array $args
   716 	 * @param array $args
   722 	 * @return bool
   717 	 * @return bool
   723 	 */
   718 	 */
   724 	function error($args = array()) {
   719 	function error($args = array()) {
   725 		if ( is_string( $args ) ) 
   720 		if ( is_string( $args ) )
   726 			$args = array('msg' => $args);
   721 			$args = array('msg' => $args);
   727 		$args = array_merge( array('loc' => 'main', 'kind' => 'warn', 'msg' => ''), $args);
   722 		$args = array_merge( array('loc' => 'main', 'kind' => 'warn', 'msg' => ''), $args);
   728 		$this->errors[$args['kind']][] = $args['msg'];
   723 		$this->errors[$args['kind']][] = $args['msg'];
   729 		if ( 'fatal' == $args['kind'] || 'frame' == $args['loc'])
   724 		if ( 'fatal' == $args['kind'] || 'frame' == $args['loc'])
   730 			$this->error_display($args['loc']);
   725 			$this->error_display($args['loc']);
   731 		return true;
   726 		return true;
   732 	}
   727 	}
   733 
   728 
   734 	/**
   729 	/**
   735 	 * Displays error messages 
   730 	 * Displays error messages
   736 	 * @param array $errs
   731 	 * @param array $errs
   737 	 * @param string $loc
   732 	 * @param string $loc
   738 	 * @return string
   733 	 * @return string
   739 	 */
   734 	 */
   740 	function error_display($loc = 'main', $echo = true) {
   735 	function error_display($loc = 'main', $echo = true) {
   746 		$errs['warn'] = isset( $errs['warn'] ) ? (array) $errs['warn'] : array();
   741 		$errs['warn'] = isset( $errs['warn'] ) ? (array) $errs['warn'] : array();
   747 		$err_list = array_slice( array_merge( $errs['fatal'], $errs['warn'] ), 0, 10);
   742 		$err_list = array_slice( array_merge( $errs['fatal'], $errs['warn'] ), 0, 10);
   748 		if ( 10 == count( $err_list ) )
   743 		if ( 10 == count( $err_list ) )
   749 			$err_list[9] = __('Subsequent errors have been omitted from this log.','wp-db-backup');
   744 			$err_list[9] = __('Subsequent errors have been omitted from this log.','wp-db-backup');
   750 		$wrap = ( 'frame' == $loc ) ? "<script type=\"text/javascript\">\n var msgList = ''; \n %1\$s \n if ( msgList ) alert(msgList); \n </script>" : '%1$s';
   745 		$wrap = ( 'frame' == $loc ) ? "<script type=\"text/javascript\">\n var msgList = ''; \n %1\$s \n if ( msgList ) alert(msgList); \n </script>" : '%1$s';
   751 		$line = ( 'frame' == $loc ) ? 
   746 		$line = ( 'frame' == $loc ) ?
   752 			"try{ window.parent.addError('%1\$s'); } catch(e) { msgList += ' %1\$s';}\n" :
   747 			"try{ window.parent.addError('%1\$s'); } catch(e) { msgList += ' %1\$s';}\n" :
   753 			"%1\$s<br />\n";
   748 			"%1\$s<br />\n";
   754 		foreach( (array) $err_list as $err )
   749 		foreach( (array) $err_list as $err )
   755 			$msg .= sprintf($line,str_replace(array("\n","\r"), '', addslashes($err)));
   750 			$msg .= sprintf($line,str_replace(array("\n","\r"), '', addslashes($err)));
   756 		$msg = sprintf($wrap,$msg);
   751 		$msg = sprintf($wrap,$msg);
   766 
   761 
   767 	/**
   762 	/**
   768 	 * Taken partially from phpMyAdmin and partially from
   763 	 * Taken partially from phpMyAdmin and partially from
   769 	 * Alain Wolf, Zurich - Switzerland
   764 	 * Alain Wolf, Zurich - Switzerland
   770 	 * Website: http://restkultur.ch/personal/wolf/scripts/db_backup/
   765 	 * Website: http://restkultur.ch/personal/wolf/scripts/db_backup/
   771 	
   766 
   772 	 * Modified by Scott Merrill (http://www.skippy.net/) 
   767 	 * Modified by Scott Merrill (http://www.skippy.net/)
   773 	 * to use the WordPress $wpdb object
   768 	 * to use the WordPress $wpdb object
   774 	 * @param string $table
   769 	 * @param string $table
   775 	 * @param string $segment
   770 	 * @param string $segment
   776 	 * @return void
   771 	 * @return void
   777 	 */
   772 	 */
   781 		$table_structure = $wpdb->get_results("DESCRIBE $table");
   776 		$table_structure = $wpdb->get_results("DESCRIBE $table");
   782 		if (! $table_structure) {
   777 		if (! $table_structure) {
   783 			$this->error(__('Error getting table details','wp-db-backup') . ": $table");
   778 			$this->error(__('Error getting table details','wp-db-backup') . ": $table");
   784 			return false;
   779 			return false;
   785 		}
   780 		}
   786 	
   781 
   787 		if(($segment == 'none') || ($segment == 0)) {
   782 		if(($segment == 'none') || ($segment == 0)) {
   788 			// Add SQL statement to drop existing table
   783 			// Add SQL statement to drop existing table
   789 			$this->stow("\n\n");
   784 			$this->stow("\n\n");
   790 			$this->stow("#\n");
   785 			$this->stow("#\n");
   791 			$this->stow("# " . sprintf(__('Delete any existing table %s','wp-db-backup'),$this->backquote($table)) . "\n");
   786 			$this->stow("# " . sprintf(__('Delete any existing table %s','wp-db-backup'),$this->backquote($table)) . "\n");
   792 			$this->stow("#\n");
   787 			$this->stow("#\n");
   793 			$this->stow("\n");
   788 			$this->stow("\n");
   794 			$this->stow("DROP TABLE IF EXISTS " . $this->backquote($table) . ";\n");
   789 			$this->stow("DROP TABLE IF EXISTS " . $this->backquote($table) . ";\n");
   795 			
   790 
   796 			// Table structure
   791 			// Table structure
   797 			// Comment in SQL-file
   792 			// Comment in SQL-file
   798 			$this->stow("\n\n");
   793 			$this->stow("\n\n");
   799 			$this->stow("#\n");
   794 			$this->stow("#\n");
   800 			$this->stow("# " . sprintf(__('Table structure of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
   795 			$this->stow("# " . sprintf(__('Table structure of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
   801 			$this->stow("#\n");
   796 			$this->stow("#\n");
   802 			$this->stow("\n");
   797 			$this->stow("\n");
   803 			
   798 
   804 			$create_table = $wpdb->get_results("SHOW CREATE TABLE $table", ARRAY_N);
   799 			$create_table = $wpdb->get_results("SHOW CREATE TABLE $table", ARRAY_N);
   805 			if (false === $create_table) {
   800 			if (false === $create_table) {
   806 				$err_msg = sprintf(__('Error with SHOW CREATE TABLE for %s.','wp-db-backup'), $table);
   801 				$err_msg = sprintf(__('Error with SHOW CREATE TABLE for %s.','wp-db-backup'), $table);
   807 				$this->error($err_msg);
   802 				$this->error($err_msg);
   808 				$this->stow("#\n# $err_msg\n#\n");
   803 				$this->stow("#\n# $err_msg\n#\n");
   809 			}
   804 			}
   810 			$this->stow($create_table[0][1] . ' ;');
   805 			$this->stow($create_table[0][1] . ' ;');
   811 			
   806 
   812 			if (false === $table_structure) {
   807 			if (false === $table_structure) {
   813 				$err_msg = sprintf(__('Error getting table structure of %s','wp-db-backup'), $table);
   808 				$err_msg = sprintf(__('Error getting table structure of %s','wp-db-backup'), $table);
   814 				$this->error($err_msg);
   809 				$this->error($err_msg);
   815 				$this->stow("#\n# $err_msg\n#\n");
   810 				$this->stow("#\n# $err_msg\n#\n");
   816 			}
   811 			}
   817 		
   812 
   818 			// Comment in SQL-file
   813 			// Comment in SQL-file
   819 			$this->stow("\n\n");
   814 			$this->stow("\n\n");
   820 			$this->stow("#\n");
   815 			$this->stow("#\n");
   821 			$this->stow('# ' . sprintf(__('Data contents of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
   816 			$this->stow('# ' . sprintf(__('Data contents of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
   822 			$this->stow("#\n");
   817 			$this->stow("#\n");
   823 		}
   818 		}
   824 		
   819 
   825 		if(($segment == 'none') || ($segment >= 0)) {
   820 		if(($segment == 'none') || ($segment >= 0)) {
   826 			$defs = array();
   821 			$defs = array();
   827 			$ints = array();
   822 			$ints = array();
   828 			foreach ($table_structure as $struct) {
   823 			foreach ($table_structure as $struct) {
   829 				if ( (0 === strpos($struct->Type, 'tinyint')) ||
   824 				if ( (0 === strpos($struct->Type, 'tinyint')) ||
   833 					(0 === strpos(strtolower($struct->Type), 'bigint')) ) {
   828 					(0 === strpos(strtolower($struct->Type), 'bigint')) ) {
   834 						$defs[strtolower($struct->Field)] = ( null === $struct->Default ) ? 'NULL' : $struct->Default;
   829 						$defs[strtolower($struct->Field)] = ( null === $struct->Default ) ? 'NULL' : $struct->Default;
   835 						$ints[strtolower($struct->Field)] = "1";
   830 						$ints[strtolower($struct->Field)] = "1";
   836 				}
   831 				}
   837 			}
   832 			}
   838 			
   833 
   839 			
   834 
   840 			// Batch by $row_inc
   835 			// Batch by $row_inc
   841 			
   836 
   842 			if($segment == 'none') {
   837 			if($segment == 'none') {
   843 				$row_start = 0;
   838 				$row_start = 0;
   844 				$row_inc = ROWS_PER_SEGMENT;
   839 				$row_inc = ROWS_PER_SEGMENT;
   845 			} else {
   840 			} else {
   846 				$row_start = $segment * ROWS_PER_SEGMENT;
   841 				$row_start = $segment * ROWS_PER_SEGMENT;
   847 				$row_inc = ROWS_PER_SEGMENT;
   842 				$row_inc = ROWS_PER_SEGMENT;
   848 			}
   843 			}
   849 			
   844 
   850 			do {	
   845 			do {
   851 				// don't include extra stuff, if so requested
   846 				// don't include extra stuff, if so requested
   852 				$excs = (array) get_option('wp_db_backup_excs');
   847 				$excs = (array) get_option('wp_db_backup_excs');
   853 				$where = '';
   848 				$where = '';
   854 				if ( is_array($excs['spam'] ) && in_array($table, $excs['spam']) ) {
   849 				if ( is_array($excs['spam'] ) && in_array($table, $excs['spam']) ) {
   855 					$where = ' WHERE comment_approved != "spam"';
   850 					$where = ' WHERE comment_approved != "spam"';
   856 				} elseif ( is_array($excs['revisions'] ) && in_array($table, $excs['revisions']) ) {
   851 				} elseif ( is_array($excs['revisions'] ) && in_array($table, $excs['revisions']) ) {
   857 					$where = ' WHERE post_type != "revision"';
   852 					$where = ' WHERE post_type != "revision"';
   858 				}
   853 				}
   859 				
   854 
   860 				if ( !ini_get('safe_mode')) @set_time_limit(15*60);
   855 				if ( !ini_get('safe_mode')) @set_time_limit(15*60);
   861 				$table_data = $wpdb->get_results("SELECT * FROM $table $where LIMIT {$row_start}, {$row_inc}", ARRAY_A);
   856 				$table_data = $wpdb->get_results("SELECT * FROM $table $where LIMIT {$row_start}, {$row_inc}", ARRAY_A);
   862 
   857 
   863 				$entries = 'INSERT INTO ' . $this->backquote($table) . ' VALUES (';	
   858 				$entries = 'INSERT INTO ' . $this->backquote($table) . ' VALUES (';
   864 				//    \x08\\x09, not required
   859 				//    \x08\\x09, not required
   865 				$search = array("\x00", "\x0a", "\x0d", "\x1a");
   860 				$search = array("\x00", "\x0a", "\x0d", "\x1a");
   866 				$replace = array('\0', '\n', '\r', '\Z');
   861 				$replace = array('\0', '\n', '\r', '\Z');
   867 				if($table_data) {
   862 				if($table_data) {
   868 					foreach ($table_data as $row) {
   863 					foreach ($table_data as $row) {
   869 						$values = array();
   864 						$values = array();
   870 						foreach ($row as $key => $value) {
   865 						foreach ($row as $key => $value) {
   871 							if ($ints[strtolower($key)]) {
   866 							if ( !empty($ints[strtolower($key)]) ) {
   872 								// make sure there are no blank spots in the insert syntax,
   867 								// make sure there are no blank spots in the insert syntax,
   873 								// yet try to avoid quotation marks around integers
   868 								// yet try to avoid quotation marks around integers
   874 								$value = ( null === $value || '' === $value) ? $defs[strtolower($key)] : $value;
   869 								$value = ( null === $value || '' === $value) ? $defs[strtolower($key)] : $value;
   875 								$values[] = ( '' === $value ) ? "''" : $value;
   870 								$values[] = ( '' === $value ) ? "''" : $value;
   876 							} else {
   871 							} else {
   881 					}
   876 					}
   882 					$row_start += $row_inc;
   877 					$row_start += $row_inc;
   883 				}
   878 				}
   884 			} while((count($table_data) > 0) and ($segment=='none'));
   879 			} while((count($table_data) > 0) and ($segment=='none'));
   885 		}
   880 		}
   886 		
   881 
   887 		if(($segment == 'none') || ($segment < 0)) {
   882 		if(($segment == 'none') || ($segment < 0)) {
   888 			// Create footer/closing comment in SQL-file
   883 			// Create footer/closing comment in SQL-file
   889 			$this->stow("\n");
   884 			$this->stow("\n");
   890 			$this->stow("#\n");
   885 			$this->stow("#\n");
   891 			$this->stow("# " . sprintf(__('End of data contents of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
   886 			$this->stow("# " . sprintf(__('End of data contents of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
   892 			$this->stow("# --------------------------------------------------------\n");
   887 			$this->stow("# --------------------------------------------------------\n");
   893 			$this->stow("\n");
   888 			$this->stow("\n");
   894 		}
   889 		}
   895 	} // end backup_table()
   890 	} // end backup_table()
   896 	
   891 
   897 	function db_backup($core_tables, $other_tables) {
   892 	function db_backup($core_tables, $other_tables) {
   898 		global $table_prefix, $wpdb;
   893 		global $table_prefix, $wpdb;
   899 		
   894 
   900 		if (is_writable($this->backup_dir)) {
   895 		if (is_writable($this->backup_dir)) {
   901 			$this->fp = $this->open($this->backup_dir . $this->backup_filename);
   896 			$this->fp = $this->open($this->backup_dir . $this->backup_filename);
   902 			if(!$this->fp) {
   897 			if(!$this->fp) {
   903 				$this->error(__('Could not open the backup file for writing!','wp-db-backup'));
   898 				$this->error(__('Could not open the backup file for writing!','wp-db-backup'));
   904 				return false;
   899 				return false;
   905 			}
   900 			}
   906 		} else {
   901 		} else {
   907 			$this->error(__('The backup directory is not writeable!','wp-db-backup'));
   902 			$this->error(__('The backup directory is not writeable!','wp-db-backup'));
   908 			return false;
   903 			return false;
   909 		}
   904 		}
   910 		
   905 
   911 		//Begin new backup of MySql
   906 		//Begin new backup of MySql
   912 		$this->stow("# " . __('WordPress MySQL database backup','wp-db-backup') . "\n");
   907 		$this->stow("# " . __('WordPress MySQL database backup','wp-db-backup') . "\n");
   913 		$this->stow("#\n");
   908 		$this->stow("#\n");
   914 		$this->stow("# " . sprintf(__('Generated: %s','wp-db-backup'),date("l j. F Y H:i T")) . "\n");
   909 		$this->stow("# " . sprintf(__('Generated: %s','wp-db-backup'),date("l j. F Y H:i T")) . "\n");
   915 		$this->stow("# " . sprintf(__('Hostname: %s','wp-db-backup'),DB_HOST) . "\n");
   910 		$this->stow("# " . sprintf(__('Hostname: %s','wp-db-backup'),DB_HOST) . "\n");
   916 		$this->stow("# " . sprintf(__('Database: %s','wp-db-backup'),$this->backquote(DB_NAME)) . "\n");
   911 		$this->stow("# " . sprintf(__('Database: %s','wp-db-backup'),$this->backquote(DB_NAME)) . "\n");
   917 		$this->stow("# --------------------------------------------------------\n");
   912 		$this->stow("# --------------------------------------------------------\n");
   918 		
   913 
   919 			if ( (is_array($other_tables)) && (count($other_tables) > 0) )
   914 			if ( (is_array($other_tables)) && (count($other_tables) > 0) )
   920 			$tables = array_merge($core_tables, $other_tables);
   915 			$tables = array_merge($core_tables, $other_tables);
   921 		else
   916 		else
   922 			$tables = $core_tables;
   917 			$tables = $core_tables;
   923 		
   918 
   924 		foreach ($tables as $table) {
   919 		foreach ($tables as $table) {
   925 			// Increase script execution time-limit to 15 min for every table.
   920 			// Increase script execution time-limit to 15 min for every table.
   926 			if ( !ini_get('safe_mode')) @set_time_limit(15*60);
   921 			if ( !ini_get('safe_mode')) @set_time_limit(15*60);
   927 			// Create the SQL statements
   922 			// Create the SQL statements
   928 			$this->stow("# --------------------------------------------------------\n");
   923 			$this->stow("# --------------------------------------------------------\n");
   929 			$this->stow("# " . sprintf(__('Table: %s','wp-db-backup'),$this->backquote($table)) . "\n");
   924 			$this->stow("# " . sprintf(__('Table: %s','wp-db-backup'),$this->backquote($table)) . "\n");
   930 			$this->stow("# --------------------------------------------------------\n");
   925 			$this->stow("# --------------------------------------------------------\n");
   931 			$this->backup_table($table);
   926 			$this->backup_table($table);
   932 		}
   927 		}
   933 				
   928 
   934 		$this->close($this->fp);
   929 		$this->close($this->fp);
   935 		
   930 
   936 		if (count($this->errors)) {
   931 		if (count($this->errors)) {
   937 			return false;
   932 			return false;
   938 		} else {
   933 		} else {
   939 			return $this->backup_filename;
   934 			return $this->backup_filename;
   940 		}
   935 		}
   941 		
   936 
   942 	} //wp_db_backup
   937 	} //wp_db_backup
   943 
   938 
   944 	/**
   939 	/**
   945 	 * Sends the backed-up file via email
   940 	 * Sends the backed-up file via email
   946 	 * @param string $to
   941 	 * @param string $to
   964 				$phpmailer = new PHPMailer();
   959 				$phpmailer = new PHPMailer();
   965 		}
   960 		}
   966 
   961 
   967 		// try to use phpmailer directly (WP 2.2+)
   962 		// try to use phpmailer directly (WP 2.2+)
   968 		if ( is_object( $phpmailer ) && ( strtolower(get_class( $phpmailer )) == 'phpmailer' ) ) {
   963 		if ( is_object( $phpmailer ) && ( strtolower(get_class( $phpmailer )) == 'phpmailer' ) ) {
   969 			
   964 
   970 			// Get the site domain and get rid of www.
   965 			// Get the site domain and get rid of www.
   971 			$sitename = strtolower( $_SERVER['SERVER_NAME'] );
   966 			$sitename = $this->get_sitename();
   972 			if ( substr( $sitename, 0, 4 ) == 'www.' ) {
       
   973 				$sitename = substr( $sitename, 4 );
       
   974 			}
       
   975 			$from_email = 'wordpress@' . $sitename;
   967 			$from_email = 'wordpress@' . $sitename;
   976 			$from_name = 'WordPress';
   968 			$from_name = 'WordPress';
   977 
   969 
   978 			// Empty out the values that may be set
   970 			// Empty out the values that may be set
   979 			$phpmailer->ClearAddresses();
   971 			$phpmailer->ClearAddresses();
   992 			$phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );
   984 			$phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );
   993 			$phpmailer->IsMail();
   985 			$phpmailer->IsMail();
   994 			$phpmailer->Subject = $subject;
   986 			$phpmailer->Subject = $subject;
   995 
   987 
   996 			do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
   988 			do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
   997 			
   989 
   998 			$result = @$phpmailer->Send();
   990 			$result = @$phpmailer->Send();
   999 
   991 
  1000 		// old-style: build the headers directly
   992 		// old-style: build the headers directly
  1001 		} else {
   993 		} else {
  1002 			$randomish = md5(time());
   994 			$randomish = md5(time());
  1003 			$boundary = "==WPBACKUP-$randomish";
   995 			$boundary = "==WPBACKUP-$randomish";
  1004 			$fp = fopen($diskfile,"rb");
   996 			$fp = fopen($diskfile,"rb");
  1005 			$file = fread($fp,filesize($diskfile)); 
   997 			$file = fread($fp,filesize($diskfile));
  1006 			$this->close($fp);
   998 			$this->close($fp);
  1007 			
   999 
  1008 			$data = chunk_split(base64_encode($file));
  1000 			$data = chunk_split(base64_encode($file));
  1009 			
  1001 
  1010 			$headers .= "MIME-Version: 1.0\n";
  1002 			$headers .= "MIME-Version: 1.0\n";
  1011 			$headers = 'From: wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])) . "\n";
  1003 			$headers = 'From: wordpress@' . preg_replace('#^www\.#', '', sanitize_text_field(strtolower($_SERVER['SERVER_NAME']))) . "\n";
  1012 			$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
  1004 			$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
  1013 		
  1005 
  1014 			// Add a multipart boundary above the plain message
  1006 			// Add a multipart boundary above the plain message
  1015 			$message = "This is a multi-part message in MIME format.\n\n" .
  1007 			$message = "This is a multi-part message in MIME format.\n\n" .
  1016 		        	"--{$boundary}\n" .
  1008 				"--{$boundary}\n" .
  1017 				"Content-Type: text/plain; charset=\"" . get_bloginfo('charset') . "\"\n" .
  1009 				"Content-Type: text/plain; charset=\"" . get_bloginfo('charset') . "\"\n" .
  1018 				"Content-Transfer-Encoding: 7bit\n\n" .
  1010 				"Content-Transfer-Encoding: 7bit\n\n" .
  1019 				$message . "\n\n";
  1011 				$message . "\n\n";
  1020 
  1012 
  1021 			// Add file attachment to the message
  1013 			// Add file attachment to the message
  1025 				"Content-Disposition: attachment;\n" .
  1017 				"Content-Disposition: attachment;\n" .
  1026 				" filename=\"{$filename}\"\n" .
  1018 				" filename=\"{$filename}\"\n" .
  1027 				"Content-Transfer-Encoding: base64\n\n" .
  1019 				"Content-Transfer-Encoding: base64\n\n" .
  1028 				$data . "\n\n" .
  1020 				$data . "\n\n" .
  1029 				"--{$boundary}--\n";
  1021 				"--{$boundary}--\n";
  1030 			
  1022 
  1031 			$result = @wp_mail($to, $subject, $message, $headers);
  1023 			$result = @wp_mail($to, $subject, $message, $headers);
  1032 		}
  1024 		}
  1033 		return $result;
  1025 		return $result;
  1034 
  1026 
  1035 	}
  1027 	}
  1036 
  1028 
  1037 	function deliver_backup($filename = '', $delivery = 'http', $recipient = '', $location = 'main') {
  1029 	function deliver_backup($filename = '', $delivery = 'http', $recipient = '', $location = 'main') {
  1038 		if ('' == $filename) { return false; }
  1030 		if ('' == $filename) { return false; }
  1039 		
  1031 
  1040 		$diskfile = $this->backup_dir . $filename;
  1032 		$diskfile = $this->backup_dir . $filename;
  1041 		$gz_diskfile = "{$diskfile}.gz";
  1033 		$gz_diskfile = "{$diskfile}.gz";
  1042 
  1034 
  1043 		/**
  1035 		/**
  1044 		 * Try upping the memory limit before gzipping
  1036 		 * Try upping the memory limit before gzipping
  1059 				if ( file_exists( $diskfile ) ) {
  1051 				if ( file_exists( $diskfile ) ) {
  1060 					unlink($diskfile);
  1052 					unlink($diskfile);
  1061 				}
  1053 				}
  1062 				$diskfile = $gz_diskfile;
  1054 				$diskfile = $gz_diskfile;
  1063 				$filename = "{$filename}.gz";
  1055 				$filename = "{$filename}.gz";
  1064 			
  1056 
  1065 			/**
  1057 			/**
  1066 			 * Try to compress to gzip, if available 
  1058 			 * Try to compress to gzip, if available
  1067 			 */
  1059 			 */
  1068 			} else {
  1060 			} else {
  1069 				if ( function_exists('gzencode') ) {
  1061 				if ( function_exists('gzencode') ) {
  1070 					if ( function_exists('file_get_contents') ) {
  1062 					if ( function_exists('file_get_contents') ) {
  1071 						$text = file_get_contents($diskfile);
  1063 						$text = file_get_contents($diskfile);
  1081 						$filename = "{$filename}.gz";
  1073 						$filename = "{$filename}.gz";
  1082 					}
  1074 					}
  1083 				}
  1075 				}
  1084 			}
  1076 			}
  1085 			/*
  1077 			/*
  1086 			 * 
  1078 			 *
  1087 			 */
  1079 			 */
  1088 		} elseif ( file_exists( $gz_diskfile ) && empty( $_GET['download-retry'] ) ) {
  1080 		} elseif ( file_exists( $gz_diskfile ) && empty( $_GET['download-retry'] ) ) {
  1089 			$diskfile = $gz_diskfile;
  1081 			$diskfile = $gz_diskfile;
  1090 			$filename = "{$filename}.gz";
  1082 			$filename = "{$filename}.gz";
  1091 		}
  1083 		}
  1092 
  1084 
  1093 		if ('http' == $delivery) {
  1085 		if ('http' == $delivery) {
  1094 			if ( ! file_exists( $diskfile ) ) {
  1086 			if ( ! file_exists( $diskfile ) ) {
  1095 				if ( empty( $_GET['download-retry'] ) ) { 
  1087 				if ( empty( $_GET['download-retry'] ) ) {
  1096 					$this->error(array('kind' => 'fatal', 'msg' => sprintf(__('File not found:%s','wp-db-backup'), "&nbsp;<strong>$filename</strong><br />") . '<br /><a href="' . $this->page_url . '">' . __('Return to Backup','wp-db-backup') . '</a>'));
  1088 					$this->error(array('kind' => 'fatal', 'msg' => sprintf(__('File not found:%s','wp-db-backup'), "&nbsp;<strong>$filename</strong><br />") . '<br /><a href="' . $this->page_url . '">' . __('Return to Backup','wp-db-backup') . '</a>'));
  1097 				} else {
  1089 				} else {
  1098 					return true;
  1090 					return true;
  1099 				}
  1091 				}
  1100 			} elseif ( file_exists( $diskfile ) ) {
  1092 			} elseif ( file_exists( $diskfile ) ) {
  1123 				$msg = __('The following errors were reported:','wp-db-backup') . "\n ";
  1115 				$msg = __('The following errors were reported:','wp-db-backup') . "\n ";
  1124 				if ( function_exists('error_get_last') ) {
  1116 				if ( function_exists('error_get_last') ) {
  1125 					$err = error_get_last();
  1117 					$err = error_get_last();
  1126 					$msg .= $err['message'];
  1118 					$msg .= $err['message'];
  1127 				} else {
  1119 				} else {
  1128 					$msg .= __('ERROR: The mail application has failed to deliver the backup.','wp-db-backup'); 
  1120 					$msg .= __('ERROR: The mail application has failed to deliver the backup.','wp-db-backup');
  1129 				}
  1121 				}
  1130 				$this->error(array('kind' => 'fatal', 'loc' => $location, 'msg' => $msg));
  1122 				$this->error(array('kind' => 'fatal', 'loc' => $location, 'msg' => $msg));
  1131 			} else {
  1123 			} else {
  1132 				if ( file_exists( $diskfile ) ) {
  1124 				if ( file_exists( $diskfile ) ) {
  1133 					unlink($diskfile);
  1125 					unlink($diskfile);
  1134 				}
  1126 				}
  1135 			}
  1127 			}
  1136 		}
  1128 		}
  1137 		return $success;
  1129 		return $success;
  1138 	}
  1130 	}
  1139 	
  1131 
  1140 	function backup_menu() {
  1132 	function backup_menu() {
  1141 		global $table_prefix, $wpdb;
  1133 		global $table_prefix, $wpdb;
  1142 		$feedback = '';
  1134 		$feedback = '';
  1143 		$whoops = false;
  1135 		$whoops = false;
  1144 		
  1136 
  1145 		// did we just do a backup?  If so, let's report the status
  1137 		// did we just do a backup?  If so, let's report the status
  1146 		if ( $this->backup_complete ) {
  1138 		if ( $this->backup_complete ) {
  1147 			$feedback = '<div class="updated wp-db-backup-updated"><p>' . __('Backup Successful','wp-db-backup') . '!';
  1139 			$feedback = '<div class="updated wp-db-backup-updated"><p>' . __('Backup Successful','wp-db-backup') . '!';
  1148 			$file = $this->backup_file;
  1140 			$file = $this->backup_file;
  1149 			switch($_POST['deliver']) {
  1141 			switch($_POST['deliver']) {
  1150 			case 'http':
  1142 			case 'http':
  1151 				$feedback .= '<br />' . sprintf(__('Your backup file: <a href="%1s">%2s</a> should begin downloading shortly.','wp-db-backup'), WP_BACKUP_URL . "{$this->backup_file}", $this->backup_file);
  1143 				$feedback .= '<br />' . sprintf(__('Your backup file: %2s should begin downloading shortly.','wp-db-backup'), "{$this->backup_file}", $this->backup_file);
  1152 				break;
  1144 				break;
  1153 			case 'smtp':
  1145 			case 'smtp':
  1154 				if (! is_email($_POST['backup_recipient'])) {
  1146 				$email = sanitize_text_field(wp_unslash($_POST['backup_recipient']));
       
  1147 				if (! is_email($email)) {
  1155 					$feedback .= get_option('admin_email');
  1148 					$feedback .= get_option('admin_email');
  1156 				} else {
  1149 				} else {
  1157 					$feedback .= $_POST['backup_recipient'];
  1150 					$feedback .= $email;
  1158 				}
  1151 				}
  1159 				$feedback = '<br />' . sprintf(__('Your backup has been emailed to %s','wp-db-backup'), $feedback);
  1152 				$feedback = '<br />' . sprintf(__('Your backup has been emailed to %s','wp-db-backup'), $feedback);
  1160 				break;
  1153 				break;
  1161 			case 'none':
       
  1162 				$feedback .= '<br />' . __('Your backup file has been saved on the server. If you would like to download it now, right click and select "Save As"','wp-db-backup');
       
  1163 				$feedback .= ':<br /> <a href="' . WP_BACKUP_URL . "$file\">$file</a> : " . sprintf(__('%s bytes','wp-db-backup'), filesize($this->backup_dir . $file));
       
  1164 			}
  1154 			}
  1165 			$feedback .= '</p></div>';
  1155 			$feedback .= '</p></div>';
  1166 		}
  1156 		}
  1167 	
  1157 
  1168 		// security check
  1158 		// security check
  1169 		$this->wp_secure();  
  1159 		$this->wp_secure();
  1170 
  1160 
  1171 		if (count($this->errors)) {
  1161 		if (count($this->errors)) {
  1172 			$feedback .= '<div class="updated wp-db-backup-updated error"><p><strong>' . __('The following errors were reported:','wp-db-backup') . '</strong></p>';
  1162 			$feedback .= '<div class="updated wp-db-backup-updated error"><p><strong>' . __('The following errors were reported:','wp-db-backup') . '</strong></p>';
  1173 			$feedback .= '<p>' . $this->error_display( 'main', false ) . '</p>';
  1163 			$feedback .= '<p>' . $this->error_display( 'main', false ) . '</p>';
  1174 			$feedback .= "</p></div>";
  1164 			$feedback .= "</p></div>";
  1175 		}
  1165 		}
  1176 
  1166 
  1177 		// did we just save options for wp-cron?
  1167 		// did we just save options for wp-cron?
  1178 		if ( (function_exists('wp_schedule_event') || function_exists('wp_cron_init')) 
  1168 		if ( (function_exists('wp_schedule_event') || function_exists('wp_cron_init'))
  1179 			&& isset($_POST['wp_cron_backup_options']) ) :
  1169 			&& isset($_POST['wp_cron_backup_options']) ) :
  1180 			do_action('wp_db_b_update_cron_options');
  1170 			do_action('wp_db_b_update_cron_options');
  1181 			if ( function_exists('wp_schedule_event') ) {
  1171 			if ( function_exists('wp_schedule_event') ) {
  1182 				wp_clear_scheduled_hook( 'wp_db_backup_cron' ); // unschedule previous
  1172 				wp_clear_scheduled_hook( 'wp_db_backup_cron' ); // unschedule previous
  1183 				$scheds = (array) wp_get_schedules();
  1173 				$scheds = (array) wp_get_schedules();
  1184 				$name = strval($_POST['wp_cron_schedule']);
  1174 				$name = sanitize_text_field(strval($_POST['wp_cron_schedule']));
  1185 				$interval = ( isset($scheds[$name]['interval']) ) ? 
  1175 				$interval = ( isset($scheds[$name]['interval']) ) ?
  1186 					(int) $scheds[$name]['interval'] : 0;
  1176 					(int) $scheds[$name]['interval'] : 0;
  1187 				update_option('wp_cron_backup_schedule', $name, false);
  1177 				update_option('wp_cron_backup_schedule', $name, false);
  1188 				if ( 0 !== $interval ) {
  1178 				if ( 0 !== $interval ) {
  1189 					wp_schedule_event(time() + $interval, $name, 'wp_db_backup_cron');
  1179 					wp_schedule_event(time() + $interval, $name, 'wp_db_backup_cron');
  1190 				}
  1180 				}
  1191 			}
  1181 			}
  1192 			else {
  1182 			else {
  1193 				update_option('wp_cron_backup_schedule', intval($_POST['cron_schedule']), false);
  1183 				update_option('wp_cron_backup_schedule', intval($_POST['cron_schedule']), false);
  1194 			}
  1184 			}
  1195 			update_option('wp_cron_backup_tables', isset( $_POST['wp_cron_backup_tables'] ) ? $_POST['wp_cron_backup_tables'] : array() );
  1185 			update_option('wp_cron_backup_tables', $this->get_submitted_tables_to_backup_in_cron());
  1196 			if (is_email($_POST['cron_backup_recipient'])) {
  1186 			if (is_email($_POST['cron_backup_recipient'])) {
  1197 				update_option('wp_cron_backup_recipient', $_POST['cron_backup_recipient'], false);
  1187 				update_option('wp_cron_backup_recipient', sanitize_text_field($_POST['cron_backup_recipient']), false);
  1198 			}
  1188 			}
  1199 			$feedback .= '<div class="updated wp-db-backup-updated"><p>' . __('Scheduled Backup Options Saved!','wp-db-backup') . '</p></div>';
  1189 			$feedback .= '<div class="updated wp-db-backup-updated"><p>' . __('Scheduled Backup Options Saved!','wp-db-backup') . '</p></div>';
  1200 		endif;
  1190 		endif;
  1201 		
  1191 
  1202 		$other_tables = array();
  1192 		$other_tables = array();
  1203 		$also_backup = array();
  1193 		$also_backup = array();
  1204 	
  1194 
  1205 		// Get complete db table list	
  1195 		// Get complete db table list
  1206 		$all_tables = $wpdb->get_results("SHOW TABLES", ARRAY_N);
  1196 		$all_tables = $wpdb->get_results("SHOW TABLES", ARRAY_N);
  1207 		$all_tables = array_map(create_function('$a', 'return $a[0];'), $all_tables);
  1197 		$all_tables = array_map(create_function('$a', 'return $a[0];'), $all_tables);
  1208 		// Get list of WP tables that actually exist in this DB (for 1.6 compat!)
  1198 		// Get list of WP tables that actually exist in this DB (for 1.6 compat!)
  1209 		$wp_backup_default_tables = array_intersect($all_tables, $this->core_table_names);
  1199 		$wp_backup_default_tables = array_intersect($all_tables, $this->core_table_names);
  1210 		// Get list of non-WP tables
  1200 		// Get list of non-WP tables
  1211 		$other_tables = array_diff($all_tables, $wp_backup_default_tables);
  1201 		$other_tables = array_diff($all_tables, $wp_backup_default_tables);
  1212 		
  1202 
  1213 		if ('' != $feedback)
  1203 		if ('' != $feedback)
  1214 			echo $feedback;
  1204 			echo $feedback;
  1215 
  1205 
  1216 		if ( ! $this->wp_secure() ) 	
  1206 		if ( ! $this->wp_secure() )
  1217 			return;
  1207 			return;
  1218 
  1208 
  1219 		// Give the new dirs the same perms as wp-content.
  1209 		// Give the new dirs the same perms as wp-content.
  1220 //		$stat = stat( ABSPATH . 'wp-content' );
  1210 //		$stat = stat( ABSPATH . 'wp-content' );
  1221 //		$dir_perms = $stat['mode'] & 0000777; // Get the permission bits.
  1211 //		$dir_perms = $stat['mode'] & 0000777; // Get the permission bits.
  1228 			$whoops = true;
  1218 			$whoops = true;
  1229 		// not writable due to write permissions
  1219 		// not writable due to write permissions
  1230 		} elseif ( !is_writable($this->backup_dir) && ! @chmod($this->backup_dir, $dir_perms) ) {
  1220 		} elseif ( !is_writable($this->backup_dir) && ! @chmod($this->backup_dir, $dir_perms) ) {
  1231 			?><div class="updated wp-db-backup-updated error"><p><?php _e('WARNING: Your backup directory is <strong>NOT</strong> writable! We cannot create the backup files.','wp-db-backup'); ?></p>
  1221 			?><div class="updated wp-db-backup-updated error"><p><?php _e('WARNING: Your backup directory is <strong>NOT</strong> writable! We cannot create the backup files.','wp-db-backup'); ?></p>
  1232 			<p><?php printf(__('Using your FTP client, try to set the backup directory&rsquo;s write permission to %1$s or %2$s: %3$s', 'wp-db-backup'), '<code>777</code>', '<code>a+w</code>', '<code>' . $this->backup_dir . '</code>'); ?>
  1222 			<p><?php printf(__('Using your FTP client, try to set the backup directory&rsquo;s write permission to %1$s or %2$s: %3$s', 'wp-db-backup'), '<code>777</code>', '<code>a+w</code>', '<code>' . $this->backup_dir . '</code>'); ?>
  1233 			</p></div><?php 
  1223 			</p></div><?php
  1234 			$whoops = true;
  1224 			$whoops = true;
  1235 		} else {
  1225 		} else {
  1236 			$this->fp = $this->open($this->backup_dir . 'test' );
  1226 			$this->fp = $this->open($this->backup_dir . 'test' );
  1237 			if( $this->fp ) { 
  1227 			if( $this->fp ) {
  1238 				$this->close($this->fp);
  1228 				$this->close($this->fp);
  1239 				@unlink($this->backup_dir . 'test' );
  1229 				@unlink($this->backup_dir . 'test' );
  1240 			// the directory is not writable probably due to safe mode
  1230 			// the directory is not writable probably due to safe mode
  1241 			} else {
  1231 			} else {
  1242 				?><div class="updated wp-db-backup-updated error"><p><?php _e('WARNING: Your backup directory is <strong>NOT</strong> writable! We cannot create the backup files.','wp-db-backup'); ?></p><?php 
  1232 				?><div class="updated wp-db-backup-updated error"><p><?php _e('WARNING: Your backup directory is <strong>NOT</strong> writable! We cannot create the backup files.','wp-db-backup'); ?></p><?php
  1243 				if( ini_get('safe_mode') ){
  1233 				if( ini_get('safe_mode') ){
  1244 					?><p><?php _e('This problem seems to be caused by your server&rsquo;s <code>safe_mode</code> file ownership restrictions, which limit what files web applications like WordPress can create.', 'wp-db-backup'); ?></p><?php 
  1234 					?><p><?php _e('This problem seems to be caused by your server&rsquo;s <code>safe_mode</code> file ownership restrictions, which limit what files web applications like WordPress can create.', 'wp-db-backup'); ?></p><?php
  1245 				}
  1235 				}
  1246 				?><?php printf(__('You can try to correct this problem by using your FTP client to delete and then re-create the backup directory: %s', 'wp-db-backup'), '<code>' . $this->backup_dir . '</code>');
  1236 				?><?php printf(__('You can try to correct this problem by using your FTP client to delete and then re-create the backup directory: %s', 'wp-db-backup'), '<code>' . $this->backup_dir . '</code>');
  1247 				?></div><?php 
  1237 				?></div><?php
  1248 				$whoops = true;
  1238 				$whoops = true;
  1249 			}
  1239 			}
  1250 		}
  1240 		}
  1251 
  1241 
  1252 		
  1242 
  1253 
  1243 
  1254 		if ( !file_exists($this->backup_dir . 'index.php') )
  1244 		if ( !file_exists($this->backup_dir . 'index.php') )
  1255 			@ touch($this->backup_dir . 'index.php');
  1245 			@ touch($this->backup_dir . 'index.php');
  1256 		?><div class='wrap'>
  1246 		?><div class='wrap'>
  1257 		<h2><?php _e('Backup','wp-db-backup') ?></h2>
  1247 		<h2><?php _e('Backup','wp-db-backup') ?></h2>
  1273 			}
  1263 			}
  1274 		}
  1264 		}
  1275 		?></ul>
  1265 		?></ul>
  1276 		</div>
  1266 		</div>
  1277 		<div class="tables-list extra-tables" id="extra-tables-list">
  1267 		<div class="tables-list extra-tables" id="extra-tables-list">
  1278 		<?php 
  1268 		<?php
  1279 		if (count($other_tables) > 0) { 
  1269 		if (count($other_tables) > 0) {
  1280 			?>
  1270 			?>
  1281 			<h4><?php _e('You may choose to include any of the following tables:','wp-db-backup'); ?></h4>
  1271 			<h4><?php _e('You may choose to include any of the following tables:','wp-db-backup'); ?></h4>
  1282 			<ul>
  1272 			<ul>
  1283 			<?php
  1273 			<?php
  1284 			foreach ($other_tables as $table) {
  1274 			foreach ($other_tables as $table) {
  1285 				?>
  1275 				?>
  1286 				<li><label><input type="checkbox" name="other_tables[]" value="<?php echo $table; ?>" /> <code><?php echo $table; ?></code></label>
  1276 				<li><label><input type="checkbox" name="other_tables[]" value="<?php echo $table; ?>" /> <code><?php echo $table; ?></code></label>
  1287 				<?php 
  1277 				<?php
  1288 			}
  1278 			}
  1289 			?></ul><?php 
  1279 			?></ul><?php
  1290 		}
  1280 		}
  1291 		?></div>
  1281 		?></div>
  1292 		</fieldset>
  1282 		</fieldset>
  1293 		
  1283 
  1294 		<fieldset class="options">
  1284 		<fieldset class="options">
  1295 			<legend><?php _e('Backup Options','wp-db-backup'); ?></legend>
  1285 			<legend><?php _e('Backup Options','wp-db-backup'); ?></legend>
  1296 			<p><?php  _e('What to do with the backup file:','wp-db-backup'); ?></p>
  1286 			<p><?php  _e('What to do with the backup file:','wp-db-backup'); ?></p>
  1297 			<ul>
  1287 			<ul>
  1298 			<li><label for="do_save">
       
  1299 				<input type="radio" id="do_save" name="deliver" value="none" style="border:none;" />
       
  1300 				<?php _e('Save to server','wp-db-backup'); 
       
  1301 				echo " (<code>" . $this->backup_dir . "</code>)"; ?>
       
  1302 			</label></li>
       
  1303 			<li><label for="do_download">
  1288 			<li><label for="do_download">
  1304 				<input type="radio" checked="checked" id="do_download" name="deliver" value="http" style="border:none;" />
  1289 				<input type="radio" checked="checked" id="do_download" name="deliver" value="http" style="border:none;" />
  1305 				<?php _e('Download to your computer','wp-db-backup'); ?>
  1290 				<?php _e('Download to your computer','wp-db-backup'); ?>
  1306 			</label></li>
  1291 			</label></li>
  1307 			<li><label for="do_email">
  1292 			<li><label for="do_email">
  1308 				<input type="radio" name="deliver" id="do_email" value="smtp" style="border:none;" />
  1293 				<input type="radio" name="deliver" id="do_email" value="smtp" style="border:none;" />
  1309 				<?php _e('Email backup to:','wp-db-backup'); ?>
  1294 				<?php _e('Email backup to:','wp-db-backup'); ?>
  1310 				<input type="text" name="backup_recipient" size="20" value="<?php 
  1295 				<input type="text" name="backup_recipient" size="20" value="<?php
  1311 					$backup_recip = get_option('wpdb_backup_recip');
  1296 					$backup_recip = get_option('wpdb_backup_recip');
  1312 					if ( empty( $backup_recip ) ) {
  1297 					if ( empty( $backup_recip ) ) {
  1313 						$backup_recip = get_option('admin_email');
  1298 						$backup_recip = get_option('admin_email');
  1314 					}
  1299 					}
  1315 
  1300 
  1316 					echo $backup_recip; ?>" />
  1301 					echo $backup_recip; ?>" />
  1317 			</label></li>
  1302 			</label></li>
  1318 			</ul>
  1303 			</ul>
  1319 			<?php if ( ! $whoops ) : ?>
  1304 			<?php if ( ! $whoops ) : ?>
  1320 			<input type="hidden" name="do_backup" id="do_backup" value="backup" /> 
  1305 			<input type="hidden" name="do_backup" id="do_backup" value="backup" />
  1321 			<p class="submit">
  1306 			<p class="submit">
  1322 				<input type="submit" name="submit" onclick="document.getElementById('do_backup').value='fragments';" value="<?php _e('Backup now!','wp-db-backup'); ?>" />
  1307 				<input type="submit" name="submit" onclick="document.getElementById('do_backup').value='fragments';" value="<?php _e('Backup now!','wp-db-backup'); ?>" />
  1323 			</p>
  1308 			</p>
  1324 			<?php else : ?>
  1309 			<?php else : ?>
  1325 				<div class="updated wp-db-backup-updated error"><p><?php _e('WARNING: Your backup directory is <strong>NOT</strong> writable!','wp-db-backup'); ?></p></div>
  1310 				<div class="updated wp-db-backup-updated error"><p><?php _e('WARNING: Your backup directory is <strong>NOT</strong> writable!','wp-db-backup'); ?></p></div>
  1326 			<?php endif; // ! whoops ?>
  1311 			<?php endif; // ! whoops ?>
  1327 		</fieldset>
  1312 		</fieldset>
  1328 		<?php do_action('wp_db_b_backup_opts'); ?>
  1313 		<?php do_action('wp_db_b_backup_opts'); ?>
  1329 		</form>
  1314 		</form>
  1330 		
  1315 
  1331 		<?php
  1316 		<?php
  1332 		// this stuff only displays if some sort of wp-cron is available 
  1317 		// this stuff only displays if some sort of wp-cron is available
  1333 		$cron = ( function_exists('wp_schedule_event') ) ? true : false; // wp-cron in WP 2.1+
  1318 		$cron = ( function_exists('wp_schedule_event') ) ? true : false; // wp-cron in WP 2.1+
  1334 		$cron_old = ( function_exists('wp_cron_init') && ! $cron ) ? true : false; // wp-cron plugin by Skippy
  1319 		$cron_old = ( function_exists('wp_cron_init') && ! $cron ) ? true : false; // wp-cron plugin by Skippy
  1335 		if ( $cron_old || $cron ) :
  1320 		if ( $cron_old || $cron ) :
  1336 			echo '<fieldset class="options"><legend>' . __('Scheduled Backup','wp-db-backup') . '</legend>';
  1321 			echo '<fieldset class="options"><legend>' . __('Scheduled Backup','wp-db-backup') . '</legend>';
  1337 			$datetime = get_option('date_format') . ' ' . get_option('time_format');
  1322 			$datetime = get_option('date_format') . ' ' . get_option('time_format');
  1340 				if ( ! empty( $next_cron ) ) :
  1325 				if ( ! empty( $next_cron ) ) :
  1341 					?>
  1326 					?>
  1342 					<p id="backup-time-wrap">
  1327 					<p id="backup-time-wrap">
  1343 					<?php printf(__('Next Backup: %s','wp-db-backup'), '<span id="next-backup-time">' . gmdate($datetime, $next_cron + (get_option('gmt_offset') * 3600)) . '</span>'); ?>
  1328 					<?php printf(__('Next Backup: %s','wp-db-backup'), '<span id="next-backup-time">' . gmdate($datetime, $next_cron + (get_option('gmt_offset') * 3600)) . '</span>'); ?>
  1344 					</p>
  1329 					</p>
  1345 					<?php 
  1330 					<?php
  1346 				endif;
  1331 				endif;
  1347 			elseif ( $cron_old ) :
  1332 			elseif ( $cron_old ) :
  1348 				?><p><?php printf(__('Last WP-Cron Daily Execution: %s','wp-db-backup'), gmdate($datetime, get_option('wp_cron_daily_lastrun') + (get_option('gmt_offset') * 3600))); ?><br /><?php 
  1333 				?><p><?php printf(__('Last WP-Cron Daily Execution: %s','wp-db-backup'), gmdate($datetime, get_option('wp_cron_daily_lastrun') + (get_option('gmt_offset') * 3600))); ?><br /><?php
  1349 				printf(__('Next WP-Cron Daily Execution: %s','wp-db-backup'), gmdate($datetime, (get_option('wp_cron_daily_lastrun') + (get_option('gmt_offset') * 3600) + 86400))); ?></p><?php 
  1334 				printf(__('Next WP-Cron Daily Execution: %s','wp-db-backup'), gmdate($datetime, (get_option('wp_cron_daily_lastrun') + (get_option('gmt_offset') * 3600) + 86400))); ?></p><?php
  1350 			endif;
  1335 			endif;
  1351 			?><form method="post" action="">
  1336 			?><form method="post" action="">
  1352 			<?php if ( function_exists('wp_nonce_field') ) wp_nonce_field($this->referer_check_key); ?>
  1337 			<?php if ( function_exists('wp_nonce_field') ) wp_nonce_field($this->referer_check_key); ?>
  1353 			<div class="tables-list">
  1338 			<div class="tables-list">
  1354 			<h4><?php _e('Schedule: ','wp-db-backup'); ?></h4>
  1339 			<h4><?php _e('Schedule: ','wp-db-backup'); ?></h4>
  1355 			<?php 
  1340 			<?php
  1356 			if ( $cron_old ) :
  1341 			if ( $cron_old ) :
  1357 				$wp_cron_backup_schedule = get_option('wp_cron_backup_schedule');
  1342 				$wp_cron_backup_schedule = get_option('wp_cron_backup_schedule');
  1358 				$schedule = array(0 => __('None','wp-db-backup'), 1 => __('Daily','wp-db-backup'));
  1343 				$schedule = array(0 => __('None','wp-db-backup'), 1 => __('Daily','wp-db-backup'));
  1359 				foreach ($schedule as $value => $name) {
  1344 				foreach ($schedule as $value => $name) {
  1360 					echo ' <input type="radio" style="border:none;" name="cron_schedule"';
  1345 					echo ' <input type="radio" style="border:none;" name="cron_schedule"';
  1391 				echo '</ul></div>';
  1376 				echo '</ul></div>';
  1392 			}
  1377 			}
  1393 			echo '<input type="hidden" name="wp_cron_backup_options" value="SET" /></form>';
  1378 			echo '<input type="hidden" name="wp_cron_backup_options" value="SET" /></form>';
  1394 			echo '</fieldset>';
  1379 			echo '</fieldset>';
  1395 		endif; // end of wp_cron (legacy) section
  1380 		endif; // end of wp_cron (legacy) section
  1396 		
  1381 
  1397 		echo '</div><!-- .wrap -->';
  1382 		echo '</div><!-- .wrap -->';
  1398 		
  1383 
  1399 	} // end wp_backup_menu()
  1384 	} // end wp_backup_menu()
  1400 
  1385 
  1401 	function get_sched() {
  1386 	function get_sched() {
  1402 		$options = array_keys( (array) wp_get_schedules() );
  1387 		$options = array_keys( (array) wp_get_schedules() );
  1403 		$freq = get_option('wp_cron_backup_schedule'); 
  1388 		$freq = get_option('wp_cron_backup_schedule');
  1404 		$freq = ( in_array( $freq , $options ) ) ? $freq : 'never';
  1389 		$freq = ( in_array( $freq , $options ) ) ? $freq : 'never';
  1405 		return $freq;
  1390 		return $freq;
  1406 	}
  1391 	}
  1407 
  1392 
  1408 	function schedule_choices($schedule) { // create the cron menu based on the schedule
  1393 	function schedule_choices($schedule) { // create the cron menu based on the schedule
  1428 			$menu .= "value='$name' /> $display</li>";
  1413 			$menu .= "value='$name' /> $display</li>";
  1429 		}
  1414 		}
  1430 		$menu .= '</ul>';
  1415 		$menu .= '</ul>';
  1431 		return $menu;
  1416 		return $menu;
  1432 	} // end schedule_choices()
  1417 	} // end schedule_choices()
  1433 	
  1418 
  1434 	function wp_cron_daily() { // for legacy cron plugin
  1419 	function wp_cron_daily() { // for legacy cron plugin
  1435 		$schedule = intval(get_option('wp_cron_backup_schedule'));
  1420 		$schedule = intval(get_option('wp_cron_backup_schedule'));
  1436 		// If scheduled backup is disabled
  1421 		// If scheduled backup is disabled
  1437 		if (0 == $schedule)
  1422 		if (0 == $schedule)
  1438 		        return;
  1423 		        return;
  1439 		else return $this->cron_backup();
  1424 		else return $this->cron_backup();
  1440 	} 
  1425 	}
  1441 
  1426 
  1442 	function cron_backup() {
  1427 	function cron_backup() {
  1443 		global $table_prefix, $wpdb;
  1428 		global $table_prefix, $wpdb;
  1444 		$all_tables = $wpdb->get_results("SHOW TABLES", ARRAY_N);
  1429 		$all_tables = $wpdb->get_results("SHOW TABLES", ARRAY_N);
  1445 		$all_tables = array_map(create_function('$a', 'return $a[0];'), $all_tables);
  1430 		$all_tables = array_map(create_function('$a', 'return $a[0];'), $all_tables);
  1446 		$core_tables = array_intersect($all_tables, $this->core_table_names);
  1431 		$core_tables = array_intersect($all_tables, $this->core_table_names);
  1447 		$other_tables = get_option('wp_cron_backup_tables');
  1432 		$other_tables = get_option('wp_cron_backup_tables');
  1448 		$recipient = get_option('wp_cron_backup_recipient');
  1433 		$recipient = get_option('wp_cron_backup_recipient');
  1449 		$backup_file = $this->db_backup($core_tables, $other_tables);
  1434 		$backup_file = $this->db_backup($core_tables, $other_tables);
  1450 		if (false !== $backup_file) 
  1435 		if (false !== $backup_file)
  1451 			return $this->deliver_backup($backup_file, 'smtp', $recipient, 'main');
  1436 			return $this->deliver_backup($backup_file, 'smtp', $recipient, 'main');
  1452 		else return false;
  1437 		else return false;
  1453 	}
  1438 	}
  1454 
  1439 
  1455 	function add_sched_options($sched) {
  1440 	function add_sched_options($sched) {
  1456 		$sched['weekly'] = array('interval' => 604800, 'display' => __('Once Weekly','wp-db-backup'));
  1441 		$sched['weekly'] = array('interval' => 604800, 'display' => __('Once Weekly','wp-db-backup'));
  1457 		return $sched;
  1442 		return $sched;
  1458 	}
  1443 	}
  1459 
  1444 
  1460 	/**
  1445 	/**
  1461 	 * Checks that WordPress has sufficient security measures 
  1446 	 * Checks that WordPress has sufficient security measures
  1462 	 * @param string $kind
  1447 	 * @param string $kind
  1463 	 * @return bool
  1448 	 * @return bool
  1464 	 */
  1449 	 */
  1465 	function wp_secure($kind = 'warn', $loc = 'main') {
  1450 	function wp_secure($kind = 'warn', $loc = 'main') {
  1466 		global $wp_version;
  1451 		global $wp_version;
  1481 		// make sure WPMU users are site admins, not ordinary admins
  1466 		// make sure WPMU users are site admins, not ordinary admins
  1482 		if ( function_exists('is_site_admin') && ! is_site_admin() )
  1467 		if ( function_exists('is_site_admin') && ! is_site_admin() )
  1483 			return false;
  1468 			return false;
  1484 		if ( ( $this->wp_secure('fatal', $loc) ) && current_user_can('import') )
  1469 		if ( ( $this->wp_secure('fatal', $loc) ) && current_user_can('import') )
  1485 			$can = $this->verify_nonce($_REQUEST['_wpnonce'], $this->referer_check_key, $loc);
  1470 			$can = $this->verify_nonce($_REQUEST['_wpnonce'], $this->referer_check_key, $loc);
  1486 		if ( false == $can ) 
  1471 		if ( false == $can )
  1487 			$this->error(array('loc' => $loc, 'kind' => 'fatal', 'msg' => __('You are not allowed to perform backups.','wp-db-backup')));
  1472 			$this->error(array('loc' => $loc, 'kind' => 'fatal', 'msg' => __('You are not allowed to perform backups.','wp-db-backup')));
  1488 		return $can;
  1473 		return $can;
  1489 	}
  1474 	}
  1490 
  1475 
  1491 	/**
  1476 	/**
  1496 	 * @return bool
  1481 	 * @return bool
  1497 	 */
  1482 	 */
  1498 	function verify_nonce($rec = '', $nonce = 'X', $loc = 'main') {
  1483 	function verify_nonce($rec = '', $nonce = 'X', $loc = 'main') {
  1499 		if ( wp_verify_nonce($rec, $nonce) )
  1484 		if ( wp_verify_nonce($rec, $nonce) )
  1500 			return true;
  1485 			return true;
  1501 		else 
  1486 		else
  1502 			$this->error(array('loc' => $loc, 'kind' => 'fatal', 'msg' => sprintf(__('There appears to be an unauthorized attempt from this site to access your database located at %1s.  The attempt has been halted.','wp-db-backup'),get_option('home'))));
  1487 			$this->error(array('loc' => $loc, 'kind' => 'fatal', 'msg' => sprintf(__('There appears to be an unauthorized attempt from this site to access your database located at %1s.  The attempt has been halted.','wp-db-backup'),get_option('home'))));
  1503 	}
  1488 	}
  1504 
  1489 
  1505 	/**
  1490 	/**
  1506 	 * Check whether a file to be downloaded is  
  1491 	 * Check whether a file to be downloaded is
  1507 	 * surreptitiously trying to download a non-backup file
  1492 	 * surreptitiously trying to download a non-backup file
  1508 	 * @param string $file
  1493 	 * @param string $file
  1509 	 * @return null
  1494 	 * @return null
  1510 	 */ 
  1495 	 */
  1511 	function validate_file($file) {
  1496 	function validate_file($file) {
  1512 		if ( (false !== strpos($file, '..')) || (false !== strpos($file, './')) || (':' == substr($file, 1, 1)) )
  1497 		if ( (false !== strpos($file, '..')) || (false !== strpos($file, './')) || (':' == substr($file, 1, 1)) )
  1513 			$this->error(array('kind' => 'fatal', 'loc' => 'frame', 'msg' => __("Cheatin' uh ?",'wp-db-backup')));
  1498 			$this->error(array('kind' => 'fatal', 'loc' => 'frame', 'msg' => __("Cheatin' uh ?",'wp-db-backup')));
  1514 	}
  1499 	}
  1515 
  1500 
       
  1501 	/**
       
  1502 	 * Get the sitename by query $_SERVER['SERVER_NAME']. 
       
  1503 	 * If it is not set, then use site_url() instead
       
  1504 	 * @return string
       
  1505 	 */
       
  1506 	function get_sitename() {
       
  1507 		$sitename='';
       
  1508 		if ( isset($_SERVER['SERVER_NAME']) ) {
       
  1509 			$sitename = strtolower( sanitize_text_field( $_SERVER['SERVER_NAME'] ) );
       
  1510 		} else {
       
  1511 			if ( function_exists('site_url') ) {
       
  1512 				// site_url() was added since 3.0.0
       
  1513 				// force http scheme so we can easily get rid of leading http://
       
  1514 				$sitename = strtolower( site_url( '', 'http' ) );
       
  1515 				$sitename = substr( $sitename, 7 );
       
  1516 			} else {
       
  1517 				// try to be compatible with versions < 3.0.0
       
  1518 				$sitename = strtolower( get_option( 'siteurl' ) );
       
  1519 				if ( substr( $sitename, 0, 7 ) == 'http://' ) {
       
  1520 					$sitename = substr( $sitename, 7 );
       
  1521 				} elseif ( substr( $sitename, 0, 8 ) == 'https://' ) {
       
  1522 					$sitename = substr( $sitename, 8 );
       
  1523 				}
       
  1524 			}
       
  1525 		}
       
  1526 		// get rid of www
       
  1527 		if ( substr( $sitename, 0, 4 ) == 'www.' ) {
       
  1528 			$sitename = substr( $sitename, 4 );
       
  1529 		}
       
  1530 		return $sitename;
       
  1531 	}
       
  1532 
       
  1533 
       
  1534 	/**
       
  1535 	 * Sanitize an array of content.
       
  1536 	 *
       
  1537 	 * @param array $array_of_data
       
  1538 	 *
       
  1539 	 * @return array
       
  1540 	 */
       
  1541 	function sanitize_array($array_to_sanitize) {
       
  1542 		$sanitized = array();
       
  1543 		foreach ( $array_to_sanitize as $key => $value ) {
       
  1544 			$sanitized[$key] = sanitize_text_field($value);
       
  1545 		}
       
  1546 		return $sanitized;
       
  1547 	}
       
  1548 
       
  1549 	/**
       
  1550 	 * Get a sanitized array of submitted $_POST values
       
  1551 	 *
       
  1552 	 * @param string $post_key The key of the $_POST array.
       
  1553 	 *
       
  1554 	 * @return array
       
  1555 	 */
       
  1556 	function get_post_data_array($post_key) {
       
  1557 		$sanitized_data = array();
       
  1558 		if (isset( $_POST[$post_key] )) {
       
  1559 			$sanitized_data = (array) $_POST[$post_key];
       
  1560 		}
       
  1561 		return $this->sanitize_array($sanitized_data);
       
  1562 	}
       
  1563 
       
  1564 	/**
       
  1565 	 * Get the revisions to exclude.
       
  1566 	 *
       
  1567 	 * @return array
       
  1568 	 */
       
  1569 	function get_revisions_to_exclude() {
       
  1570 		return $this->get_post_data_array('exclude-revisions');
       
  1571 	}
       
  1572 
       
  1573 	/**
       
  1574 	 * Get the spam to exclude.
       
  1575 	 *
       
  1576 	 * @return array
       
  1577 	 */
       
  1578 	function get_spam_to_exclude() {
       
  1579 		return $this->get_post_data_array('exclude-spam');
       
  1580 	}
       
  1581 
       
  1582 	/**
       
  1583 	 * Get the submitted tables to backup.
       
  1584 	 *
       
  1585 	 * @return array
       
  1586 	 */
       
  1587 	function get_submitted_tables_to_backup_in_cron() {
       
  1588 		return $this->get_post_data_array('wp_cron_backup_tables');
       
  1589 	}
  1516 }
  1590 }
  1517 
  1591 
  1518 function wpdbBackup_init() {
  1592 function wpdbBackup_init() {
  1519 	global $mywpdbbackup;
  1593 	global $mywpdbbackup;
  1520 	$mywpdbbackup = new wpdbBackup(); 	
  1594 	$mywpdbbackup = new wpdbBackup();
  1521 }
  1595 }
  1522 
  1596 
  1523 add_action('plugins_loaded', 'wpdbBackup_init');
  1597 add_action('plugins_loaded', 'wpdbBackup_init');
  1524 ?>
  1598 ?>