PageRenderTime 52ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-db-backup.php

https://github.com/hexalys/wp-db-backup
PHP | 1534 lines | 1290 code | 119 blank | 125 comment | 204 complexity | fafd6020644c53ccfb96ba6741bf50c6 MD5 | raw file
Possible License(s): GPL-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. Plugin Name: WordPress Database Backup
  4. Plugin URI: http://austinmatzko.com/wordpress-plugins/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.
  6. Author: Austin Matzko
  7. Author URI: http://austinmatzko.com/
  8. Version: 2.2.4-beta
  9. Copyright 2011 Austin Matzko (email : austin at pressedcode.com)
  10. This program is free software; you can redistribute it and/or modify
  11. it under the terms of the GNU General Public License as published by
  12. the Free Software Foundation; either version 2 of the License, or
  13. (at your option) any later version.
  14. This program is distributed in the hope that it will be useful,
  15. but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. GNU General Public License for more details.
  18. You should have received a copy of the GNU General Public License
  19. along with this program; if not, write to the Free Software
  20. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
  21. */
  22. /**
  23. * Change WP_BACKUP_DIR if you want to
  24. * use a different backup location
  25. */
  26. if ( ! defined('ABSPATH') ) {
  27. die('Please do not load this file directly.');
  28. }
  29. $rand = substr( md5( md5( DB_PASSWORD ) ), -5 );
  30. global $wpdbb_content_dir, $wpdbb_content_url, $wpdbb_plugin_dir;
  31. $wpdbb_content_dir = ( defined('WP_CONTENT_DIR') ) ? WP_CONTENT_DIR : ABSPATH . 'wp-content';
  32. $wpdbb_content_url = ( defined('WP_CONTENT_URL') ) ? WP_CONTENT_URL : get_option('siteurl') . '/wp-content';
  33. $wpdbb_plugin_dir = ( defined('WP_PLUGIN_DIR') ) ? WP_PLUGIN_DIR : $wpdbb_content_dir . '/plugins';
  34. if ( ! defined('WP_BACKUP_DIR') ) {
  35. define('WP_BACKUP_DIR', $wpdbb_content_dir . '/backup-' . $rand . '/');
  36. }
  37. if ( ! defined('WP_BACKUP_URL') ) {
  38. define('WP_BACKUP_URL', $wpdbb_content_url . '/backup-' . $rand . '/');
  39. }
  40. if ( ! defined('ROWS_PER_SEGMENT') ) {
  41. define('ROWS_PER_SEGMENT', 100);
  42. }
  43. /**
  44. * Set MOD_EVASIVE_OVERRIDE to true
  45. * and increase MOD_EVASIVE_DELAY
  46. * if the backup stops prematurely.
  47. */
  48. // define('MOD_EVASIVE_OVERRIDE', false);
  49. if ( ! defined('MOD_EVASIVE_DELAY') ) {
  50. define('MOD_EVASIVE_DELAY', '500');
  51. }
  52. class wpdbBackup {
  53. var $backup_complete = false;
  54. var $backup_file = '';
  55. var $backup_filename;
  56. var $core_table_names = array();
  57. var $errors = array();
  58. var $basename;
  59. var $page_url;
  60. var $referer_check_key;
  61. var $version = '2.1.5-alpha';
  62. function module_check() {
  63. $mod_evasive = false;
  64. if ( defined( 'MOD_EVASIVE_OVERRIDE' ) && true === MOD_EVASIVE_OVERRIDE ) return true;
  65. if ( ! defined( 'MOD_EVASIVE_OVERRIDE' ) || false === MOD_EVASIVE_OVERRIDE ) return false;
  66. if ( function_exists('apache_get_modules') )
  67. foreach( (array) apache_get_modules() as $mod )
  68. if ( false !== strpos($mod,'mod_evasive') || false !== strpos($mod,'mod_dosevasive') )
  69. return true;
  70. return false;
  71. }
  72. function wpdbBackup() {
  73. global $table_prefix, $wpdb;
  74. add_action('wp_ajax_save_backup_time', array(&$this, 'save_backup_time'));
  75. add_action('init', array(&$this, 'init_textdomain'));
  76. add_action('init', array(&$this, 'set_page_url'));
  77. add_action('load-update-core.php', array(&$this, 'update_notice_action'));
  78. add_action('wp_db_backup_cron', array(&$this, 'cron_backup'));
  79. add_action('wp_cron_daily', array(&$this, 'wp_cron_daily'));
  80. add_filter('cron_schedules', array(&$this, 'add_sched_options'));
  81. add_filter('wp_db_b_schedule_choices', array(&$this, 'schedule_choices'));
  82. $table_prefix = ( isset( $table_prefix ) ) ? $table_prefix : $wpdb->prefix;
  83. $datum = date("Ymd_B");
  84. $this->backup_filename = DB_NAME . "_$table_prefix$datum.sql";
  85. $possible_names = array(
  86. 'categories',
  87. 'commentmeta',
  88. 'comments',
  89. 'link2cat',
  90. 'linkcategories',
  91. 'links',
  92. 'options',
  93. 'post2cat',
  94. 'postmeta',
  95. 'posts',
  96. 'terms',
  97. 'term_taxonomy',
  98. 'term_relationships',
  99. 'users',
  100. 'usermeta',
  101. );
  102. foreach( $possible_names as $name ) {
  103. if ( isset( $wpdb->{$name} ) ) {
  104. $this->core_table_names[] = $wpdb->{$name};
  105. }
  106. }
  107. $this->backup_dir = trailingslashit(apply_filters('wp_db_b_backup_dir', WP_BACKUP_DIR));
  108. $this->basename = 'wp-db-backup';
  109. $this->referer_check_key = $this->basename . '-download_' . DB_NAME;
  110. if (isset($_POST['do_backup'])) {
  111. $this->wp_secure('fatal');
  112. check_admin_referer($this->referer_check_key);
  113. $this->can_user_backup('main');
  114. // save exclude prefs
  115. $exc_revisions = isset( $_POST['exclude-revisions'] ) ? (array) $_POST['exclude-revisions'] : array();
  116. $exc_spam = isset( $_POST['exclude-spam'] ) ? (array) $_POST['exclude-spam'] : array();
  117. update_option('wp_db_backup_excs', array('revisions' => $exc_revisions, 'spam' => $exc_spam));
  118. switch($_POST['do_backup']) {
  119. case 'backup':
  120. add_action('init', array(&$this, 'perform_backup'));
  121. break;
  122. case 'fragments':
  123. add_action('admin_menu', array(&$this, 'fragment_menu'));
  124. break;
  125. }
  126. } elseif (isset($_GET['fragment'] )) {
  127. $this->can_user_backup('frame');
  128. add_action('init', array(&$this, 'init'));
  129. } elseif (isset($_GET['backup'] )) {
  130. $this->can_user_backup();
  131. add_action('init', array(&$this, 'init'));
  132. } else {
  133. add_action('admin_menu', array(&$this, 'admin_menu'));
  134. }
  135. }
  136. function init() {
  137. $this->can_user_backup();
  138. if (isset($_GET['backup'])) {
  139. $via = isset($_GET['via']) ? $_GET['via'] : 'http';
  140. $this->backup_file = $_GET['backup'];
  141. $this->validate_file($this->backup_file);
  142. switch($via) {
  143. case 'smtp':
  144. case 'email':
  145. $success = $this->deliver_backup($this->backup_file, 'smtp', $_GET['recipient'], 'frame');
  146. $this->error_display( 'frame' );
  147. if ( $success ) {
  148. echo '
  149. <!-- ' . $via . ' -->
  150. <script type="text/javascript"><!--\\
  151. ';
  152. echo '
  153. alert("' . __('Backup Complete!','wp-db-backup') . '");
  154. window.onbeforeunload = null;
  155. </script>
  156. ';
  157. }
  158. break;
  159. default:
  160. $success = $this->deliver_backup($this->backup_file, $via);
  161. echo $this->error_display( 'frame', false );
  162. if ( $success ) {
  163. echo '
  164. <script type="text/javascript">
  165. window.parent.setProgress("' . __('Backup Complete!','wp-db-backup') . '");
  166. </script>
  167. ';
  168. }
  169. }
  170. exit;
  171. }
  172. if (isset($_GET['fragment'] )) {
  173. list($table, $segment, $filename) = explode(':', $_GET['fragment']);
  174. $this->validate_file($filename);
  175. $this->backup_fragment($table, $segment, $filename);
  176. }
  177. die();
  178. }
  179. function init_textdomain() {
  180. load_plugin_textdomain('wp-db-backup', str_replace(ABSPATH, '', dirname(__FILE__)), dirname(plugin_basename(__FILE__)));
  181. }
  182. function set_page_url() {
  183. $query_args = array( 'page' => $this->basename );
  184. if ( function_exists('wp_create_nonce') )
  185. $query_args = array_merge( $query_args, array('_wpnonce' => wp_create_nonce($this->referer_check_key)) );
  186. $base = ( function_exists('site_url') ) ? site_url('', 'admin') : get_option('siteurl');
  187. $this->page_url = add_query_arg( $query_args, $base . '/wp-admin/edit.php');
  188. }
  189. /*
  190. * Add a link to back up your database when doing a core upgrade
  191. */
  192. function update_notice_action() {
  193. if ( isset( $_REQUEST['action'] ) || 'upgrade-core' == $_REQUEST['action'] ) :
  194. ob_start(array(&$this, 'update_notice'));
  195. add_action('admin_footer', create_function('', 'ob_end_flush();'));
  196. endif;
  197. }
  198. function update_notice($text = '') {
  199. $pattern = '#(<a href\="' . __('http://codex.wordpress.org/WordPress_Backups') . '">.*?</p>)#';
  200. $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";
  201. $text = preg_replace($pattern, $replace, $text);
  202. return $text;
  203. }
  204. function build_backup_script() {
  205. global $table_prefix, $wpdb;
  206. echo "<div class='wrap'>";
  207. echo '<fieldset class="options"><legend>' . __('Progress','wp-db-backup') . '</legend>
  208. <p><strong>' .
  209. __('DO NOT DO THE FOLLOWING AS IT WILL CAUSE YOUR BACKUP TO FAIL:','wp-db-backup').
  210. '</strong></p>
  211. <ol>
  212. <li>'.__('Close this browser','wp-db-backup').'</li>
  213. <li>'.__('Reload this page','wp-db-backup').'</li>
  214. <li>'.__('Click the Stop or Back buttons in your browser','wp-db-backup').'</li>
  215. </ol>
  216. <p><strong>' . __('Progress:','wp-db-backup') . '</strong></p>
  217. <div id="meterbox" style="height:11px;width:80%;padding:3px;border:1px solid #659fff;"><div id="meter" style="color:#fff;height:11px;line-height:11px;background-color:#659fff;width:0%;text-align:center;font-size:6pt;">&nbsp;</div></div>
  218. <div id="progress_message"></div>
  219. <div id="errors"></div>
  220. </fieldset>
  221. <iframe id="backuploader" src="about:blank" style="visibility:hidden;border:none;height:1em;width:1px;"></iframe>
  222. <script type="text/javascript">
  223. //<![CDATA[
  224. window.onbeforeunload = function() {
  225. return "' . __('Navigating away from this page will cause your backup to fail.', 'wp-db-backup') . '";
  226. }
  227. function setMeter(pct) {
  228. var meter = document.getElementById("meter");
  229. meter.style.width = pct + "%";
  230. meter.innerHTML = Math.floor(pct) + "%";
  231. }
  232. function setProgress(str) {
  233. var progress = document.getElementById("progress_message");
  234. progress.innerHTML = str;
  235. }
  236. function addError(str) {
  237. var errors = document.getElementById("errors");
  238. errors.innerHTML = errors.innerHTML + str + "<br />";
  239. }
  240. function backup(table, segment) {
  241. var fram = document.getElementById("backuploader");
  242. fram.src = "' . $this->page_url . '&fragment=" + table + ":" + segment + ":' . $this->backup_filename . ':";
  243. }
  244. var curStep = 0;
  245. function nextStep() {
  246. backupStep(curStep);
  247. curStep++;
  248. }
  249. function finishBackup() {
  250. var fram = document.getElementById("backuploader");
  251. setMeter(100);
  252. ';
  253. $download_uri = add_query_arg('backup', $this->backup_filename, $this->page_url);
  254. switch($_POST['deliver']) {
  255. case 'http':
  256. echo '
  257. setProgress("' . __('Preparing download.','wp-db-backup') . '");
  258. window.onbeforeunload = null;
  259. fram.src = "' . $download_uri . '";
  260. setTimeout( function() {
  261. var secondFrame = document.createElement("iframe");
  262. fram.parentNode.insertBefore(secondFrame, fram);
  263. secondFrame.src = "' . $download_uri . '&download-retry=1";
  264. }, 30000 );
  265. ';
  266. break;
  267. case 'smtp':
  268. if ( get_option('wpdb_backup_recip') != $_POST['backup_recipient'] ) {
  269. update_option('wpdb_backup_recip', $_POST['backup_recipient'] );
  270. }
  271. echo '
  272. setProgress("' . sprintf(__('Your backup has been emailed to %s','wp-db-backup'), $_POST['backup_recipient']) . '");
  273. window.onbeforeunload = null;
  274. fram.src = "' . $download_uri . '&via=email&recipient=' . $_POST['backup_recipient'] . '";
  275. ';
  276. break;
  277. default:
  278. echo '
  279. setProgress("' . __('Backup Complete!','wp-db-backup') . '");
  280. window.onbeforeunload = null;
  281. ';
  282. }
  283. echo '
  284. }
  285. function backupStep(step) {
  286. switch(step) {
  287. case 0: backup("", 0); break;
  288. ';
  289. $also_backup = array();
  290. if (isset($_POST['other_tables'])) {
  291. $also_backup = $_POST['other_tables'];
  292. } else {
  293. $also_backup = array();
  294. }
  295. $core_tables = $_POST['core_tables'];
  296. $tables = array_merge($core_tables, $also_backup);
  297. $step_count = 1;
  298. foreach ($tables as $table) {
  299. $rec_count = $wpdb->get_var("SELECT count(*) FROM {$table}");
  300. $rec_segments = ceil($rec_count / ROWS_PER_SEGMENT);
  301. $table_count = 0;
  302. if ( $this->module_check() ) {
  303. $delay = "setTimeout('";
  304. $delay_time = "', " . (int) MOD_EVASIVE_DELAY . ")";
  305. }
  306. else { $delay = $delay_time = ''; }
  307. do {
  308. echo "case {$step_count}: {$delay}backup(\"{$table}\", {$table_count}){$delay_time}; break;\n";
  309. $step_count++;
  310. $table_count++;
  311. } while($table_count < $rec_segments);
  312. echo "case {$step_count}: {$delay}backup(\"{$table}\", -1){$delay_time}; break;\n";
  313. $step_count++;
  314. }
  315. echo "case {$step_count}: finishBackup(); break;";
  316. echo '
  317. }
  318. if(step != 0) setMeter(100 * step / ' . $step_count . ');
  319. }
  320. nextStep();
  321. // ]]>
  322. </script>
  323. </div>
  324. ';
  325. $this->backup_menu();
  326. }
  327. function backup_fragment($table, $segment, $filename) {
  328. global $table_prefix, $wpdb;
  329. echo "$table:$segment:$filename";
  330. if($table == '') {
  331. $msg = __('Creating backup file...','wp-db-backup');
  332. } else {
  333. if($segment == -1) {
  334. $msg = sprintf(__('Finished backing up table \\"%s\\".','wp-db-backup'), $table);
  335. } else {
  336. $msg = sprintf(__('Backing up table \\"%s\\"...','wp-db-backup'), $table);
  337. }
  338. }
  339. if (is_writable($this->backup_dir)) {
  340. $this->fp = $this->open($this->backup_dir . $filename, 'a');
  341. if(!$this->fp) {
  342. $this->error(__('Could not open the backup file for writing!','wp-db-backup'));
  343. $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')));
  344. }
  345. else {
  346. if($table == '') {
  347. //Begin new backup of MySql
  348. $this->stow("# " . __('WordPress MySQL database backup','wp-db-backup') . "\n");
  349. $this->stow("#\n");
  350. $this->stow("# " . sprintf(__('Generated: %s','wp-db-backup'),date("l j. F Y H:i T")) . "\n");
  351. $this->stow("# " . sprintf(__('Hostname: %s','wp-db-backup'),DB_HOST) . "\n");
  352. $this->stow("# " . sprintf(__('Database: %s','wp-db-backup'),$this->backquote(DB_NAME)) . "\n");
  353. $this->stow("# --------------------------------------------------------\n");
  354. } else {
  355. if($segment == 0) {
  356. // Increase script execution time-limit to 15 min for every table.
  357. if ( !ini_get('safe_mode')) @set_time_limit(15*60);
  358. // Create the SQL statements
  359. $this->stow("# --------------------------------------------------------\n");
  360. $this->stow("# " . sprintf(__('Table: %s','wp-db-backup'),$this->backquote($table)) . "\n");
  361. $this->stow("# --------------------------------------------------------\n");
  362. }
  363. $this->backup_table($table, $segment);
  364. }
  365. }
  366. } else {
  367. $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')));
  368. }
  369. if($this->fp) $this->close($this->fp);
  370. $this->error_display('frame');
  371. echo '<script type="text/javascript"><!--//
  372. var msg = "' . $msg . '";
  373. window.parent.setProgress(msg);
  374. window.parent.nextStep();
  375. //--></script>
  376. ';
  377. die();
  378. }
  379. function perform_backup() {
  380. // are we backing up any other tables?
  381. $also_backup = array();
  382. if (isset($_POST['other_tables']))
  383. $also_backup = $_POST['other_tables'];
  384. $core_tables = $_POST['core_tables'];
  385. $this->backup_file = $this->db_backup($core_tables, $also_backup);
  386. if (false !== $this->backup_file) {
  387. if ('smtp' == $_POST['deliver']) {
  388. $this->deliver_backup($this->backup_file, $_POST['deliver'], $_POST['backup_recipient'], 'main');
  389. if ( get_option('wpdb_backup_recip') != $_POST['backup_recipient'] ) {
  390. update_option('wpdb_backup_recip', $_POST['backup_recipient'] );
  391. }
  392. wp_redirect($this->page_url);
  393. } elseif ('http' == $_POST['deliver']) {
  394. $download_uri = add_query_arg('backup',$this->backup_file,$this->page_url);
  395. wp_redirect($download_uri);
  396. exit;
  397. }
  398. // we do this to say we're done.
  399. $this->backup_complete = true;
  400. }
  401. }
  402. function admin_header() {
  403. ?>
  404. <script type="text/javascript">
  405. //<![CDATA[
  406. if ( 'undefined' != typeof addLoadEvent ) {
  407. addLoadEvent(function() {
  408. var t = {'extra-tables-list':{name: 'other_tables[]'}, 'include-tables-list':{name: 'wp_cron_backup_tables[]'}};
  409. for ( var k in t ) {
  410. t[k].s = null;
  411. var d = document.getElementById(k);
  412. if ( ! d )
  413. continue;
  414. var ul = d.getElementsByTagName('ul').item(0);
  415. if ( ul ) {
  416. var lis = ul.getElementsByTagName('li');
  417. if ( 2 < lis.length ) {
  418. var text = document.createElement('p');
  419. text.className = 'instructions';
  420. text.innerHTML = '<?php _e('Click and hold down <code>[SHIFT]</code> to toggle multiple checkboxes', 'wp-db-backup'); ?>';
  421. ul.parentNode.insertBefore(text, ul);
  422. }
  423. }
  424. t[k].p = d.getElementsByTagName("input");
  425. for(var i=0; i < t[k].p.length; i++) {
  426. if(t[k].name == t[k].p[i].getAttribute('name')) {
  427. t[k].p[i].id = k + '-table-' + i;
  428. t[k].p[i].onkeyup = t[k].p[i].onclick = function(e) {
  429. e = e ? e : event;
  430. if ( 16 == e.keyCode )
  431. return;
  432. var match = /([\w-]*)-table-(\d*)/.exec(this.id);
  433. var listname = match[1];
  434. var that = match[2];
  435. if ( null === t[listname].s )
  436. t[listname].s = that;
  437. else if ( e.shiftKey ) {
  438. var start = Math.min(that, t[listname].s) + 1;
  439. var end = Math.max(that, t[listname].s);
  440. for( var j=start; j < end; j++)
  441. t[listname].p[j].checked = t[listname].p[j].checked ? false : true;
  442. t[listname].s = null;
  443. }
  444. }
  445. }
  446. }
  447. }
  448. <?php if ( function_exists('wp_schedule_event') ) : // needs to be at least WP 2.1 for ajax ?>
  449. if ( 'undefined' == typeof XMLHttpRequest )
  450. var xml = new ActiveXObject( navigator.userAgent.indexOf('MSIE 5') >= 0 ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP' );
  451. else
  452. var xml = new XMLHttpRequest();
  453. var initTimeChange = function() {
  454. var timeWrap = document.getElementById('backup-time-wrap');
  455. var backupTime = document.getElementById('next-backup-time');
  456. if ( !! timeWrap && !! backupTime && ( 1 == <?php
  457. echo (int) ( 'en' == strtolower( substr( get_locale(), 0, 2 ) ) );
  458. ?> ) ) {
  459. var span = document.createElement('span');
  460. span.className = 'submit';
  461. span.id = 'change-wrap';
  462. span.innerHTML = '<input type="submit" id="change-backup-time" name="change-backup-time" value="<?php _e('Change','wp-db-backup'); ?>" />';
  463. timeWrap.appendChild(span);
  464. backupTime.ondblclick = function(e) { span.parentNode.removeChild(span); clickTime(e, backupTime); };
  465. span.onclick = function(e) { span.parentNode.removeChild(span); clickTime(e, backupTime); };
  466. }
  467. }
  468. var clickTime = function(e, backupTime) {
  469. var tText = backupTime.innerHTML;
  470. backupTime.innerHTML = '<input type="text" value="' + tText + '" name="backup-time-text" id="backup-time-text" /> <span class="submit"><input type="submit" name="save-backup-time" id="save-backup-time" value="<?php _e('Save', 'wp-db-backup'); ?>" /></span>';
  471. backupTime.ondblclick = null;
  472. var mainText = document.getElementById('backup-time-text');
  473. mainText.focus();
  474. var saveTButton = document.getElementById('save-backup-time');
  475. if ( !! saveTButton )
  476. saveTButton.onclick = function(e) { saveTime(backupTime, mainText); return false; };
  477. if ( !! mainText )
  478. mainText.onkeydown = function(e) {
  479. e = e || window.event;
  480. if ( 13 == e.keyCode ) {
  481. saveTime(backupTime, mainText);
  482. return false;
  483. }
  484. }
  485. }
  486. var saveTime = function(backupTime, mainText) {
  487. var tVal = mainText.value;
  488. xml.open('POST', 'admin-ajax.php', true);
  489. xml.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  490. if ( xml.overrideMimeType )
  491. xml.setRequestHeader('Connection', 'close');
  492. xml.send('action=save_backup_time&_wpnonce=<?php echo wp_create_nonce($this->referer_check_key); ?>&backup-time='+tVal);
  493. xml.onreadystatechange = function() {
  494. if ( 4 == xml.readyState && '0' != xml.responseText ) {
  495. backupTime.innerHTML = xml.responseText;
  496. initTimeChange();
  497. }
  498. }
  499. }
  500. initTimeChange();
  501. <?php endif; // wp_schedule_event exists ?>
  502. });
  503. }
  504. //]]>
  505. </script>
  506. <style type="text/css">
  507. .wp-db-backup-updated {
  508. margin-top: 1em;
  509. }
  510. fieldset.options {
  511. border: 1px solid;
  512. margin-top: 1em;
  513. padding: 1em;
  514. -moz-border-radius: 8px;
  515. -khtml-border-radius: 8px;
  516. -webkit-border-top-left-radius: 8px;
  517. -webkit-border-top-right-radius: 8px;
  518. -webkit-border-bottom-left-radius: 8px;
  519. -webkit-border-bottom-right-radius: 8px;
  520. border-radius: 8px;
  521. }
  522. fieldset.options div.tables-list {
  523. float: left;
  524. padding: 1em;
  525. }
  526. fieldset.options input {
  527. }
  528. fieldset.options legend {
  529. font-size: larger;
  530. font-weight: bold;
  531. margin-bottom: .5em;
  532. padding: 1em;
  533. }
  534. fieldset.options .instructions {
  535. font-size: smaller;
  536. }
  537. fieldset.options ul {
  538. list-style-type: none;
  539. }
  540. fieldset.options li {
  541. text-align: left;
  542. }
  543. fieldset.options .submit {
  544. border-top: none;
  545. }
  546. </style>
  547. <?php
  548. }
  549. function admin_load() {
  550. add_action('admin_head', array(&$this, 'admin_header'));
  551. }
  552. function admin_menu() {
  553. global $_page_hook;
  554. $_page_hook = add_management_page(__('Backup','wp-db-backup'), __('Backup','wp-db-backup'), 'import', $this->basename, array(&$this, 'backup_menu'));
  555. add_action('load-' . $_page_hook, array(&$this, 'admin_load'));
  556. add_action( 'load-' . $_page_hook, array( &$this, 'add_help_tab' ) );
  557. }
  558. function add_help_tab() {
  559. global $_page_hook;
  560. $screen = get_current_screen();
  561. if ( $screen->id != $_page_hook )
  562. return;
  563. if ( function_exists( 'add_contextual_help' ) && ! method_exists( $screen, 'add_help_tab' ) ) {
  564. $text = $this->help_menu();
  565. add_contextual_help( $_page_hook, $text );
  566. }
  567. // @todo Check if $screen->id is current page
  568. $screen->add_help_tab( array(
  569. 'id' => 'wp_db_backup_help_tab',
  570. 'title' => __( 'Overview' ),
  571. 'content' => '<p>' . $this->help_menu() . '</p>'
  572. ) );
  573. }
  574. function fragment_menu() {
  575. $page_hook = add_management_page(__('Backup','wp-db-backup'), __('Backup','wp-db-backup'), 'import', $this->basename, array(&$this, 'build_backup_script'));
  576. add_action('load-' . $page_hook, array(&$this, 'admin_load'));
  577. }
  578. /**
  579. * Add WP-DB-Backup-specific help options to the 2.7 =< WP contextual help menu
  580. * return string The text of the help menu.
  581. */
  582. function help_menu() {
  583. $text = "\n<a href=\"http://wordpress.org/extend/plugins/wp-db-backup/faq/\" target=\"_blank\">" . __('FAQ', 'wp-db-backup') . '</a>';
  584. $text .= "\n<br />\n<a href=\"http://www.ilfilosofo.com/forum/forum/2\" target=\"_blank\">" . __('WP-DB-Backup Support Forum', 'wp-db-backup') . '</a>';
  585. return $text;
  586. }
  587. function save_backup_time() {
  588. if ( $this->can_user_backup() ) {
  589. // try to get a time from the input string
  590. $time = strtotime(strval($_POST['backup-time']));
  591. if ( ! empty( $time ) && time() < $time ) {
  592. wp_clear_scheduled_hook( 'wp_db_backup_cron' ); // unschedule previous
  593. $scheds = (array) wp_get_schedules();
  594. $name = get_option('wp_cron_backup_schedule');
  595. if ( 0 != $time ) {
  596. wp_schedule_event($time, $name, 'wp_db_backup_cron');
  597. echo gmdate(get_option('date_format') . ' ' . get_option('time_format'), $time + (get_option('gmt_offset') * 3600));
  598. exit;
  599. }
  600. }
  601. } else {
  602. die(0);
  603. }
  604. }
  605. /**
  606. * Better addslashes for SQL queries.
  607. * Taken from phpMyAdmin.
  608. */
  609. function sql_addslashes($a_string = '', $is_like = false) {
  610. if ($is_like) $a_string = str_replace('\\', '\\\\\\\\', $a_string);
  611. else $a_string = str_replace('\\', '\\\\', $a_string);
  612. return str_replace('\'', '\\\'', $a_string);
  613. }
  614. /**
  615. * Add backquotes to tables and db-names in
  616. * SQL queries. Taken from phpMyAdmin.
  617. */
  618. function backquote($a_name) {
  619. if (!empty($a_name) && $a_name != '*') {
  620. if (is_array($a_name)) {
  621. $result = array();
  622. reset($a_name);
  623. while(list($key, $val) = each($a_name))
  624. $result[$key] = '`' . $val . '`';
  625. return $result;
  626. } else {
  627. return '`' . $a_name . '`';
  628. }
  629. } else {
  630. return $a_name;
  631. }
  632. }
  633. function open($filename = '', $mode = 'w') {
  634. if ('' == $filename) return false;
  635. $fp = @fopen($filename, $mode);
  636. return $fp;
  637. }
  638. function close($fp) {
  639. fclose($fp);
  640. }
  641. /**
  642. * Write to the backup file
  643. * @param string $query_line the line to write
  644. * @return null
  645. */
  646. function stow($query_line) {
  647. if(false === @fwrite($this->fp, $query_line))
  648. $this->error(__('There was an error writing a line to the backup script:','wp-db-backup') . ' ' . $query_line . ' ' . $php_errormsg);
  649. }
  650. /**
  651. * Logs any error messages
  652. * @param array $args
  653. * @return bool
  654. */
  655. function error($args = array()) {
  656. if ( is_string( $args ) )
  657. $args = array('msg' => $args);
  658. $args = array_merge( array('loc' => 'main', 'kind' => 'warn', 'msg' => ''), $args);
  659. $this->errors[$args['kind']][] = $args['msg'];
  660. if ( 'fatal' == $args['kind'] || 'frame' == $args['loc'])
  661. $this->error_display($args['loc']);
  662. return true;
  663. }
  664. /**
  665. * Displays error messages
  666. * @param array $errs
  667. * @param string $loc
  668. * @return string
  669. */
  670. function error_display($loc = 'main', $echo = true) {
  671. $errs = $this->errors;
  672. unset( $this->errors );
  673. if ( ! count($errs) ) return;
  674. $msg = '';
  675. $errs['fatal'] = isset( $errs['fatal'] ) ? (array) $errs['fatal'] : array();
  676. $errs['warn'] = isset( $errs['warn'] ) ? (array) $errs['warn'] : array();
  677. $err_list = array_slice( array_merge( $errs['fatal'], $errs['warn'] ), 0, 10);
  678. if ( 10 == count( $err_list ) )
  679. $err_list[9] = __('Subsequent errors have been omitted from this log.','wp-db-backup');
  680. $wrap = ( 'frame' == $loc ) ? "<script type=\"text/javascript\">\n var msgList = ''; \n %1\$s \n if ( msgList ) alert(msgList); \n </script>" : '%1$s';
  681. $line = ( 'frame' == $loc ) ?
  682. "try{ window.parent.addError('%1\$s'); } catch(e) { msgList += ' %1\$s';}\n" :
  683. "%1\$s<br />\n";
  684. foreach( (array) $err_list as $err )
  685. $msg .= sprintf($line,str_replace(array("\n","\r"), '', addslashes($err)));
  686. $msg = sprintf($wrap,$msg);
  687. if ( count($errs['fatal'] ) ) {
  688. if ( function_exists('wp_die') && 'frame' != $loc ) wp_die(stripslashes($msg));
  689. else die($msg);
  690. }
  691. else {
  692. if ( $echo ) echo $msg;
  693. else return $msg;
  694. }
  695. }
  696. /**
  697. * Taken partially from phpMyAdmin and partially from
  698. * Alain Wolf, Zurich - Switzerland
  699. * Website: http://restkultur.ch/personal/wolf/scripts/db_backup/
  700. * Modified by Scott Merrill (http://www.skippy.net/)
  701. * to use the WordPress $wpdb object
  702. * @param string $table
  703. * @param string $segment
  704. * @return void
  705. */
  706. function backup_table($table, $segment = 'none') {
  707. global $wpdb;
  708. $table_structure = $wpdb->get_results("DESCRIBE $table");
  709. if (! $table_structure) {
  710. $this->error(__('Error getting table details','wp-db-backup') . ": $table");
  711. return false;
  712. }
  713. if(($segment == 'none') || ($segment == 0)) {
  714. // Add SQL statement to drop existing table
  715. $this->stow("\n\n");
  716. $this->stow("#\n");
  717. $this->stow("# " . sprintf(__('Delete any existing table %s','wp-db-backup'),$this->backquote($table)) . "\n");
  718. $this->stow("#\n");
  719. $this->stow("\n");
  720. $this->stow("DROP TABLE IF EXISTS " . $this->backquote($table) . ";\n");
  721. // Table structure
  722. // Comment in SQL-file
  723. $this->stow("\n\n");
  724. $this->stow("#\n");
  725. $this->stow("# " . sprintf(__('Table structure of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
  726. $this->stow("#\n");
  727. $this->stow("\n");
  728. $create_table = $wpdb->get_results("SHOW CREATE TABLE $table", ARRAY_N);
  729. if (false === $create_table) {
  730. $err_msg = sprintf(__('Error with SHOW CREATE TABLE for %s.','wp-db-backup'), $table);
  731. $this->error($err_msg);
  732. $this->stow("#\n# $err_msg\n#\n");
  733. }
  734. $this->stow($create_table[0][1] . ' ;');
  735. if (false === $table_structure) {
  736. $err_msg = sprintf(__('Error getting table structure of %s','wp-db-backup'), $table);
  737. $this->error($err_msg);
  738. $this->stow("#\n# $err_msg\n#\n");
  739. }
  740. // Comment in SQL-file
  741. $this->stow("\n\n");
  742. $this->stow("#\n");
  743. $this->stow('# ' . sprintf(__('Data contents of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
  744. $this->stow("#\n");
  745. }
  746. if(($segment == 'none') || ($segment >= 0)) {
  747. $defs = array();
  748. $ints = array();
  749. foreach ($table_structure as $struct) {
  750. if ( (0 === strpos($struct->Type, 'tinyint')) ||
  751. (0 === strpos(strtolower($struct->Type), 'smallint')) ||
  752. (0 === strpos(strtolower($struct->Type), 'mediumint')) ||
  753. (0 === strpos(strtolower($struct->Type), 'int')) ||
  754. (0 === strpos(strtolower($struct->Type), 'bigint')) ) {
  755. $defs[strtolower($struct->Field)] = ( null === $struct->Default ) ? 'NULL' : $struct->Default;
  756. $ints[strtolower($struct->Field)] = "1";
  757. }
  758. }
  759. // Batch by $row_inc
  760. if($segment == 'none') {
  761. $row_start = 0;
  762. $row_inc = ROWS_PER_SEGMENT;
  763. } else {
  764. $row_start = $segment * ROWS_PER_SEGMENT;
  765. $row_inc = ROWS_PER_SEGMENT;
  766. }
  767. do {
  768. // don't include extra stuff, if so requested
  769. $excs = (array) get_option('wp_db_backup_excs');
  770. $where = '';
  771. if ( is_array($excs['spam'] ) && in_array($table, $excs['spam']) ) {
  772. $where = ' WHERE comment_approved != "spam"';
  773. } elseif ( is_array($excs['revisions'] ) && in_array($table, $excs['revisions']) ) {
  774. $where = ' WHERE post_type != "revision"';
  775. }
  776. if ( !ini_get('safe_mode')) @set_time_limit(15*60);
  777. $table_data = $wpdb->get_results("SELECT * FROM $table $where LIMIT {$row_start}, {$row_inc}", ARRAY_A);
  778. $entries = 'INSERT INTO ' . $this->backquote($table) . ' VALUES (';
  779. // \x08\\x09, not required
  780. $search = array("\x00", "\x0a", "\x0d", "\x1a");
  781. $replace = array('\0', '\n', '\r', '\Z');
  782. if($table_data) {
  783. foreach ($table_data as $row) {
  784. $values = array();
  785. foreach ($row as $key => $value) {
  786. if ($ints[strtolower($key)]) {
  787. // make sure there are no blank spots in the insert syntax,
  788. // yet try to avoid quotation marks around integers
  789. $value = ( null === $value || '' === $value) ? $defs[strtolower($key)] : $value;
  790. $values[] = ( '' === $value ) ? "''" : $value;
  791. } else {
  792. $values[] = "'" . str_replace($search, $replace, $this->sql_addslashes($value)) . "'";
  793. }
  794. }
  795. $this->stow(" \n" . $entries . implode(', ', $values) . ');');
  796. }
  797. $row_start += $row_inc;
  798. }
  799. } while((count($table_data) > 0) and ($segment=='none'));
  800. }
  801. if(($segment == 'none') || ($segment < 0)) {
  802. // Create footer/closing comment in SQL-file
  803. $this->stow("\n");
  804. $this->stow("#\n");
  805. $this->stow("# " . sprintf(__('End of data contents of table %s','wp-db-backup'),$this->backquote($table)) . "\n");
  806. $this->stow("# --------------------------------------------------------\n");
  807. $this->stow("\n");
  808. }
  809. } // end backup_table()
  810. function db_backup($core_tables, $other_tables) {
  811. global $table_prefix, $wpdb;
  812. if (is_writable($this->backup_dir)) {
  813. $this->fp = $this->open($this->backup_dir . $this->backup_filename);
  814. if(!$this->fp) {
  815. $this->error(__('Could not open the backup file for writing!','wp-db-backup'));
  816. return false;
  817. }
  818. } else {
  819. $this->error(__('The backup directory is not writeable!','wp-db-backup'));
  820. return false;
  821. }
  822. //Begin new backup of MySql
  823. $this->stow("# " . __('WordPress MySQL database backup','wp-db-backup') . "\n");
  824. $this->stow("#\n");
  825. $this->stow("# " . sprintf(__('Generated: %s','wp-db-backup'),date("l j. F Y H:i T")) . "\n");
  826. $this->stow("# " . sprintf(__('Hostname: %s','wp-db-backup'),DB_HOST) . "\n");
  827. $this->stow("# " . sprintf(__('Database: %s','wp-db-backup'),$this->backquote(DB_NAME)) . "\n");
  828. $this->stow("# --------------------------------------------------------\n");
  829. if ( (is_array($other_tables)) && (count($other_tables) > 0) )
  830. $tables = array_merge($core_tables, $other_tables);
  831. else
  832. $tables = $core_tables;
  833. foreach ($tables as $table) {
  834. // Increase script execution time-limit to 15 min for every table.
  835. if ( !ini_get('safe_mode')) @set_time_limit(15*60);
  836. // Create the SQL statements
  837. $this->stow("# --------------------------------------------------------\n");
  838. $this->stow("# " . sprintf(__('Table: %s','wp-db-backup'),$this->backquote($table)) . "\n");
  839. $this->stow("# --------------------------------------------------------\n");
  840. $this->backup_table($table);
  841. }
  842. $this->close($this->fp);
  843. if (count($this->errors)) {
  844. return false;
  845. } else {
  846. return $this->backup_filename;
  847. }
  848. } //wp_db_backup
  849. /**
  850. * Sends the backed-up file via email
  851. * @param string $to
  852. * @param string $subject
  853. * @param string $message
  854. * @return bool
  855. */
  856. function send_mail( $to, $subject, $message, $diskfile) {
  857. global $phpmailer;
  858. $filename = basename($diskfile);
  859. extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message' ) ) );
  860. if ( !is_object( $phpmailer ) || ( strtolower(get_class( $phpmailer )) != 'phpmailer' ) ) {
  861. if ( file_exists( ABSPATH . WPINC . '/class-phpmailer.php' ) )
  862. require_once ABSPATH . WPINC . '/class-phpmailer.php';
  863. if ( file_exists( ABSPATH . WPINC . '/class-smtp.php' ) )
  864. require_once ABSPATH . WPINC . '/class-smtp.php';
  865. if ( class_exists( 'PHPMailer') )
  866. $phpmailer = new PHPMailer();
  867. }
  868. // try to use phpmailer directly (WP 2.2+)
  869. if ( is_object( $phpmailer ) && ( strtolower(get_class( $phpmailer )) == 'phpmailer' ) ) {
  870. // Get the site domain and get rid of www.
  871. $sitename = strtolower( $_SERVER['SERVER_NAME'] );
  872. if ( substr( $sitename, 0, 4 ) == 'www.' ) {
  873. $sitename = substr( $sitename, 4 );
  874. }
  875. $from_email = 'wordpress@' . $sitename;
  876. $from_name = 'WordPress';
  877. // Empty out the values that may be set
  878. $phpmailer->ClearAddresses();
  879. $phpmailer->ClearAllRecipients();
  880. $phpmailer->ClearAttachments();
  881. $phpmailer->ClearBCCs();
  882. $phpmailer->ClearCCs();
  883. $phpmailer->ClearCustomHeaders();
  884. $phpmailer->ClearReplyTos();
  885. $phpmailer->AddAddress( $to );
  886. $phpmailer->AddAttachment($diskfile, $filename);
  887. $phpmailer->Body = $message;
  888. $phpmailer->CharSet = apply_filters( 'wp_mail_charset', get_bloginfo('charset') );
  889. $phpmailer->From = apply_filters( 'wp_mail_from', $from_email );
  890. $phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );
  891. $phpmailer->IsMail();
  892. $phpmailer->Subject = $subject;
  893. do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
  894. $result = @$phpmailer->Send();
  895. // old-style: build the headers directly
  896. } else {
  897. $randomish = md5(time());
  898. $boundary = "==WPBACKUP-$randomish";
  899. $fp = fopen($diskfile,"rb");
  900. $file = fread($fp,filesize($diskfile));
  901. $this->close($fp);
  902. $data = chunk_split(base64_encode($file));
  903. $headers .= "MIME-Version: 1.0\n";
  904. $headers = 'From: wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])) . "\n";
  905. $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\n";
  906. // Add a multipart boundary above the plain message
  907. $message = "This is a multi-part message in MIME format.\n\n" .
  908. "--{$boundary}\n" .
  909. "Content-Type: text/plain; charset=\"" . get_bloginfo('charset') . "\"\n" .
  910. "Content-Transfer-Encoding: 7bit\n\n" .
  911. $message . "\n\n";
  912. // Add file attachment to the message
  913. $message .= "--{$boundary}\n" .
  914. "Content-Type: application/octet-stream;\n" .
  915. " name=\"{$filename}\"\n" .
  916. "Content-Disposition: attachment;\n" .
  917. " filename=\"{$filename}\"\n" .
  918. "Content-Transfer-Encoding: base64\n\n" .
  919. $data . "\n\n" .
  920. "--{$boundary}--\n";
  921. $result = @wp_mail($to, $subject, $message, $headers);
  922. }
  923. return $result;
  924. }
  925. function deliver_backup($filename = '', $delivery = 'http', $recipient = '', $location = 'main') {
  926. if ('' == $filename) { return false; }
  927. $diskfile = $this->backup_dir . $filename;
  928. $gz_diskfile = "{$diskfile}.gz";
  929. /**
  930. * Try upping the memory limit before gzipping
  931. */
  932. if ( function_exists('memory_get_usage') && ( (int) @ini_get('memory_limit') < 64 ) ) {
  933. @ini_set('memory_limit', '64M' );
  934. }
  935. if ( file_exists( $diskfile ) && empty( $_GET['download-retry'] ) ) {
  936. /**
  937. * Try gzipping with an external application
  938. */
  939. if ( file_exists( $diskfile ) && ! file_exists( $gz_diskfile ) ) {
  940. @exec( "gzip $diskfile" );
  941. }
  942. if ( file_exists( $gz_diskfile ) ) {
  943. if ( file_exists( $diskfile ) ) {
  944. unlink($diskfile);
  945. }
  946. $diskfile = $gz_diskfile;
  947. $filename = "{$filename}.gz";
  948. /**
  949. * Try to compress to gzip, if available
  950. */
  951. } else {
  952. if ( function_exists('gzencode') ) {
  953. if ( function_exists('file_get_contents') ) {
  954. $text = file_get_contents($diskfile);
  955. } else {
  956. $text = implode("", file($diskfile));
  957. }
  958. $gz_text = gzencode($text, 9);
  959. $fp = fopen($gz_diskfile, "w");
  960. fwrite($fp, $gz_text);
  961. if ( fclose($fp) ) {
  962. unlink($diskfile);
  963. $diskfile = $gz_diskfile;
  964. $filename = "{$filename}.gz";
  965. }
  966. }
  967. }
  968. /*
  969. *
  970. */
  971. } elseif ( file_exists( $gz_diskfile ) && empty( $_GET['download-retry'] ) ) {
  972. $diskfile = $gz_diskfile;
  973. $filename = "{$filename}.gz";
  974. }
  975. if ('http' == $delivery) {
  976. if ( ! file_exists( $diskfile ) ) {
  977. if ( empty( $_GET['download-retry'] ) ) {
  978. $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>'));
  979. } else {
  980. return true;
  981. }
  982. } elseif ( file_exists( $diskfile ) ) {
  983. header('Content-Description: File Transfer');
  984. header('Content-Type: application/octet-stream');
  985. header('Content-Length: ' . filesize($diskfile));
  986. header("Content-Disposition: attachment; filename=$filename");
  987. $success = readfile($diskfile);
  988. if ( $success ) {
  989. unlink($diskfile);
  990. }
  991. }
  992. } elseif ('smtp' == $delivery) {
  993. if (! file_exists($diskfile)) {
  994. $msg = sprintf(__('File %s does not exist!','wp-db-backup'), $diskfile);
  995. $this->error($msg);
  996. return false;
  997. }
  998. if (! is_email($recipient)) {
  999. $recipient = get_option('admin_email');
  1000. }
  1001. $message = sprintf(__("Attached to this email is\n %1s\n Size:%2s kilobytes\n",'wp-db-backup'), $filename, round(filesize($diskfile)/1024));
  1002. $success = $this->send_mail($recipient, get_bloginfo('name') . ' ' . __('Database Backup','wp-db-backup'), $message, $diskfile);
  1003. if ( false === $success ) {
  1004. $msg = __('The following errors were reported:','wp-db-backup') . "\n ";
  1005. if ( function_exists('error_get_last') ) {
  1006. $err = error_get_last();
  1007. $msg .= $err['message'];
  1008. } else {
  1009. $msg .= __('ERROR: The mail application has failed to deliver the backup.','wp-db-backup');
  1010. }
  1011. $this->error(array('kind' => 'fatal', 'loc' => $location, 'msg' => $msg));
  1012. } else {
  1013. if ( file_exists( $diskfile ) ) {
  1014. unlink($diskfile);
  1015. }
  1016. }
  1017. }
  1018. return $success;
  1019. }
  1020. function backup_menu() {
  1021. global $table_prefix, $wpdb;
  1022. $feedback = '';
  1023. $whoops = false;
  1024. // did we just do a backup? If so, let's report the status
  1025. if ( $this->backup_complete ) {
  1026. $feedback = '<div class="updated wp-db-backup-updated"><p>' . __('Backup Successful','wp-db-backup') . '!';
  1027. $file = $this->backup_file;
  1028. switch($_POST['deliver']) {
  1029. case 'http':
  1030. $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);
  1031. break;
  1032. case 'smtp':
  1033. if (! is_email($_POST['backup_recipient'])) {
  1034. $feedback .= get_option('admin_email');
  1035. } else {
  1036. $feedback .= $_POST['backup_recipient'];
  1037. }
  1038. $feedback = '<br />' . sprintf(__('Your backup has been emailed to %s','wp-db-backup'), $feedback);
  1039. break;
  1040. case 'none':
  1041. $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');
  1042. $feedback .= ':<br /> <a href="' . WP_BACKUP_URL . "$file\">$file</a> : " . sprintf(__('%s bytes','wp-db-backup'), filesize($this->backup_dir . $file));
  1043. }
  1044. $feedback .= '</p></div>';
  1045. }
  1046. // security check
  1047. $this->wp_secure();
  1048. if (count($this->errors)) {
  1049. $feedback .= '<div class="updated wp-db-backup-updated error"><p><strong>' . __('The following errors were reported:','wp-db-backup') . '</strong></p>';
  1050. $feedback .= '<p>' . $this->error_display( 'main', false ) . '</p>';
  1051. $feedback .= "</p></div>";
  1052. }
  1053. // did we just save options for wp-cron?
  1054. if ( (function_exists('wp_schedule_event') || function_exists('wp_cron_init'))
  1055. && isset($_POST['wp_cron_backup_options']) ) :
  1056. do_action('wp_db_b_update_cron_options');
  1057. if ( function_exists('wp_schedule_event') ) {
  1058. wp_clear_scheduled_hook( 'wp_db_backup_cron' ); // unschedule previous
  1059. $scheds = (array) wp_get_schedules();
  1060. $name = strval($_POST['wp_cron_schedule']);
  1061. $interval = ( isset($scheds[$name]['interval']) ) ?
  1062. (int) $scheds[$name]['interval'] : 0;
  1063. update_option('wp_cron_backup_schedule', $name, false);
  1064. if ( 0 !== $interval ) {
  1065. wp_schedule_event(time() + $interval, $name, 'wp_db_backup_cron');
  1066. }
  1067. }
  1068. else {
  1069. update_option('wp_cron_backup_schedule', intval($_POST['cron_schedule']), false);
  1070. }
  1071. update_option('wp_cron_backup_tables', isset( $_POST['wp_cron_backup_tables'] ) ? $_POST['wp_cron_backup_tables'] : array() );
  1072. if (is_email($_POST['cron_backup_recipient'])) {
  1073. update_option('wp_cron_backup_recipient', $_POST['cron_backup_recipient'], false);
  1074. }
  1075. $feedback .= '<div class="updated wp-db-backup-updated"><p>' . __('Scheduled Backup Options Saved!','wp-db-backup') . '</p></div>';
  1076. endif;
  1077. $other_tables = array();
  1078. $also_backup = array();
  1079. // Get complete db table list
  1080. $all_tables = $wpdb->get_results("SHOW TABLES", ARRAY_N);
  1081. $all_tables = array_map(create_function('$a', 'return $a[0];'), $all_tables);
  1082. // Get list of WP tables that actually exist in this DB (for 1.6 compat!)
  1083. $wp_backup_default_tables = array_intersect($all_tables, $this->core_table_names);
  1084. // Get list of non-WP tables
  1085. $other_tables = array_diff($all_tables, $wp_backup_default_tables);
  1086. if ('' != $feedback)
  1087. echo $feedback;
  1088. if ( ! $this->wp_secure() )
  1089. return;
  1090. // Give the new dirs the same perms as wp-content.
  1091. // $stat = stat( ABSPATH . 'wp-content' );
  1092. // $dir_perms = $stat['mode'] & 0000777; // Get the permission bits.
  1093. $dir_perms = '0777';
  1094. // the file doesn't exist and can't create it
  1095. if ( ! file_exists($this->backup_dir) && ! @mkdir($this->backup_dir) ) {
  1096. ?><div class="updated wp-db-backup-updated error"><p><?php _e('WARNING: Your backup directory does <strong>NOT</strong> exist, and we cannot create it.','wp-db-backup'); ?></p>
  1097. <p><?php printf(__('Using your FTP client, try to create the backup directory yourself: %s', 'wp-db-backup'), '<code>' . $this->backup_dir . '</code>'); ?></p></div><?php
  1098. $whoops = true;
  1099. // not writable due to write permissions
  1100. } elseif ( !is_writable($this->backup_dir) && ! @chmod($this->backup_dir, $dir_perms) ) {
  1101. ?><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>
  1102. <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>'); ?>
  1103. </p></div><?php
  1104. $whoops = true;
  1105. } else {
  1106. $this->fp = $this->open($this->backup_dir . 'test' );
  1107. if( $this->fp ) {
  1108. $this->close($this->fp);
  1109. @unlink($this->backup_dir . 'test' );
  1110. // the directory is not writable probably due to safe mode
  1111. } else {
  1112. ?><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
  1113. if( ini_get('safe_mode') ){
  1114. ?><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
  1115. }
  1116. ?><?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>');
  1117. ?></div><?php
  1118. $whoops = true;
  1119. }
  1120. }
  1121. if ( !file_exists($this->backup_dir . 'index.php') )
  1122. @ touch($this->backup_dir . 'index.php');
  1123. ?><div class='wrap'>
  1124. <h2><?php _e('Backup','wp-db-backup') ?></h2>
  1125. <form method="post" action="">
  1126. <?php if ( function_exists('wp_nonce_field') ) wp_nonce_field($this->referer_check_key); ?>
  1127. <fieldset class="options"><legend><?php _e('Tables','wp-db-backup') ?></legend>
  1128. <div class="tables-list core-tables alternate">
  1129. <h4><?php _e('These core WordPress tables will always be backed up:','wp-db-backup') ?></h4><ul><?php
  1130. $excs = (array) get_option('wp_db_backup_excs');
  1131. foreach ($wp_backup_default_tables as $table) {
  1132. if ( $table == $wpdb->comments ) {
  1133. $checked = ( isset($excs['spam']) && is_array($excs['spam'] ) && in_array($table, $excs['spam']) ) ? ' checked=\'checked\'' : '';
  1134. echo "<li><input type='hidden' name='core_tables[]' value='$table' /><code>$table</code> <span class='instructions'> <input type='checkbox' name='exclude-spam[]' value='$table' $checked /> " . __('Exclude spam comments', 'wp-db-backup') . '</span></li>';
  1135. } elseif ( function_exists('wp_get_post_revisions') && $table == $wpdb->posts ) {
  1136. $checked = ( isset($excs['revisions']) && is_array($excs['revisions'] ) && in_array($table, $excs['revisions']) ) ? ' checked=\'checked\'' : '';
  1137. echo "<li><input type='hidden' name='core_tables[]' value='$table' /><code>$table</code> <span class='instructions'> <input type='checkbox' name='exclude-revisions[]' value='$table' $checked /> " . __('Exclude post revisions', 'wp-db-backup') . '</span></li>';
  1138. } else {
  1139. echo "<li><input type='hidden' name='core_tables[]' value='$table' /><code>$table</code></li>";
  1140. }
  1141. }
  1142. ?></ul>
  1143. </div>
  1144. <div class="tables-list extra-tables" id="extra-tables-list">
  1145. <?php
  1146. if (count($other_tables) > 0) {
  1147. ?>
  1148. <h4><?php _e('You may choose to include any of the following tables:','wp-db-backup'); ?></h4>
  1149. <ul>
  1150. <?php
  1151. foreach ($other_tables as $table) {
  1152. ?>
  1153. <li><label><input type="checkbox" name="other_tables[]" value="<?php echo $table; ?>" /> <code><?php echo $table; ?></code></label>
  1154. <?php
  1155. }
  1156. ?></ul><?php
  1157. }
  1158. ?></div>
  1159. </fieldset>
  1160. <fieldset class="options">
  1161. <legend><?php _e('Backup Options','wp-db-backup'); ?></legend>
  1162. <p><?php _e('What to do with the backup file:','wp-db-backup'); ?></p>
  1163. <ul>
  1164. <li><label for="do_save">
  1165. <input type="radio" id="do_save" name="deliver" value="none" style="border:none;" />
  1166. <?php _e('Save to server','wp-db-backup');
  1167. echo " (<code>" . $this->backup_dir . "</code>)"; ?>
  1168. </label></li>
  1169. <li><label for="do_download">
  1170. <input type="radio" checked="checked" id="do_download" name="deliver" value="http" style="border:none;" />
  1171. <?php _e('Download to your computer','wp-db-backup'); ?>
  1172. </label></li>
  1173. <li><label for="do_email">
  1174. <input type="radio" name="deliver" id="do_email" value="smtp" style="border:none;" />
  1175. <?php _e('Email backup to:','wp-db-backup'); ?>
  1176. <input type="text" name="backup_recipient" size="20" value="<?php
  1177. $backup_recip = get_option('wpdb_backup_recip');
  1178. if ( empty( $backup_recip ) ) {
  1179. $backup_recip = get_option('admin_email');
  1180. }
  1181. echo $backup_recip; ?>" />
  1182. </label></li>
  1183. </ul>
  1184. <?php if ( ! $whoops ) : ?>
  1185. <input type="hidden" name="do_backup" id="do_backup" value="backup" />
  1186. <p class="submit">
  1187. <input type="submit" name="submit" onclick="document.getElementById('do_backup').value='fragments';" value="<?php _e('Backup now!','wp-db-backup'); ?>" />
  1188. </p>
  1189. <?php else : ?>
  1190. <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>
  1191. <?php endif; // ! whoops ?>
  1192. </fieldset>
  1193. <?php do_action('wp_db_b_backup_opts'); ?>
  1194. </form>
  1195. <?php
  1196. // this stuff only displays if some sort of wp-cron is available
  1197. $cron = ( function_exists('wp_schedule_event') ) ? true : false; // wp-cron in WP 2.1+
  1198. $cron_old = ( function_exists('wp_cron_init') && ! $cron ) ? true : false; // wp-cron plugin by Skippy
  1199. if ( $cron_old || $cron ) :
  1200. echo '<fieldset class="options"><legend>' . __('Scheduled Backup','wp-db-backup') . '</legend>';
  1201. $datetime = get_option('date_format') . ' ' . get_option('time_format');
  1202. if ( $cron ) :
  1203. $next_cron = wp_next_scheduled('wp_db_backup_cron');
  1204. if ( ! empty( $next_cron ) ) :
  1205. ?>
  1206. <p id="backup-time-wrap">
  1207. <?php printf(__('Next Backup: %s','wp-db-backup'), '<span id="next-backup-time">' . gmdate($datetime, $next_cron + (get_option('gmt_offset') * 3600)) . '</span>'); ?>
  1208. </p>
  1209. <?php
  1210. endif;
  1211. elseif ( $cron_old ) :
  1212. ?><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
  1213. 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
  1214. endif;
  1215. ?><form method="post" action="">

Large files files are truncated, but you can click here to view the full file