PageRenderTime 32ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/backupbuddy/classes/core.php

https://bitbucket.org/betaimages/chakalos
PHP | 1756 lines | 1201 code | 306 blank | 249 comment | 229 complexity | f039ce688c796a7fa660be131f30766e MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. // Helper functions for BackupBuddy.
  3. // TODO: Eventually break out of a lot of these from BB core. Migrating from old framework to new resulted in this mid-way transition but it's a bit messy...
  4. class pb_backupbuddy_core {
  5. /* is_network_activated()
  6. *
  7. * Returns a boolean indicating whether a plugin is network activated or not.
  8. *
  9. * @return boolean True if plugin is network activated, else false.
  10. */
  11. function is_network_activated() {
  12. if ( !function_exists( 'is_plugin_active_for_network' ) ) { // Function is not available on all WordPress pages for some reason according to codex.
  13. require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
  14. }
  15. if ( is_plugin_active_for_network( basename( pb_backupbuddy::plugin_path() ) . '/' . pb_backupbuddy::settings( 'init' ) ) ) { // Path relative to wp-content\plugins\ directory.
  16. return true;
  17. } else {
  18. return false;
  19. }
  20. } // End is_network_activated().
  21. /* backup_integrity_check()
  22. *
  23. * Scans a backup file and saves the result in data structure. Checks for key files & that .zip can be read properly. Stores results with details in data structure.
  24. *
  25. * @param string $file Full pathname & filename to backup file to check.
  26. * @return boolean True if integrity 100% passed, else false. ( Side note: Result details stored in pb_backupbuddy::$options['backups'][$serial]['integrity'] ).
  27. */
  28. function backup_integrity_check( $file ) {
  29. $serial = $this->get_serial_from_file( $file );
  30. // User selected to rescan a file.
  31. if ( pb_backupbuddy::_GET( 'reset_integrity' ) == $serial ) {
  32. pb_backupbuddy::alert( 'Rescanning backup integrity for backup file `' . basename( $file ) . '`' );
  33. }
  34. if ( isset( pb_backupbuddy::$options['backups'][$serial]['integrity'] ) && ( count( pb_backupbuddy::$options['backups'][$serial]['integrity'] ) > 0 ) && ( pb_backupbuddy::_GET( 'reset_integrity' ) != $serial ) ) { // Already have integrity data and NOT resetting this one.
  35. pb_backupbuddy::status( 'details', 'Integrity data for backup `' . $serial . '` is cached; not scanning again.' );
  36. return;
  37. } elseif ( pb_backupbuddy::_GET( 'reset_integrity' ) == $serial ) { // Resetting this one.
  38. pb_backupbuddy::status( 'details', 'Resetting backup integrity stats for backup with serial `' . $serial . '`.' );
  39. }
  40. if ( pb_backupbuddy::$options['integrity_check'] == '0' ) { // Integrity checking disabled.
  41. $file_stats = @stat( $file );
  42. if ( $file_stats === false ) { // stat failure.
  43. pb_backupbuddy::alert( 'Error #4539774. Unable to get file details ( via stat() ) for file `' . $file . '`. The file may be corrupt or too large for the server.' );
  44. $file_size = 0;
  45. $file_modified = 0;
  46. } else { // stat success.
  47. $file_size = $file_stats['size'];
  48. $file_modified = $file_stats['mtime'];
  49. }
  50. unset( $file_stats );
  51. $integrity = array(
  52. 'status' => 'Unknown',
  53. 'status_details' => __( 'Integrity checking disabled based on settings. This file has not been verified.', 'it-l10n-backupbuddy' ),
  54. 'scan_time' => 0,
  55. 'detected_type' => 'unknown',
  56. 'size' => $file_size,
  57. 'modified' => $file_modified,
  58. 'file' => basename( $file ),
  59. 'comment' => false,
  60. );
  61. pb_backupbuddy::$options['backups'][$serial]['integrity'] = array_merge( pb_backupbuddy::settings( 'backups_integrity_defaults' ), $integrity );
  62. pb_backupbuddy::save();
  63. return;
  64. }
  65. //***** BEGIN CALCULATING STATUS DETAILS.
  66. // Status defaults.
  67. $status_details = array(
  68. 'found_dat' => false,
  69. 'found_sql' => false,
  70. 'found_wpconfig' => false,
  71. 'scan_log' => '',
  72. );
  73. $backup_type = '';
  74. if ( !isset( pb_backupbuddy::$classes['zipbuddy'] ) ) {
  75. require_once( pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php' );
  76. pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy( pb_backupbuddy::$options['backup_directory'] );
  77. }
  78. pb_backupbuddy::set_status_serial( 'zipbuddy_test' ); // Redirect logging output to a certain log file.
  79. // Look for comment.
  80. $comment = pb_backupbuddy::$classes['zipbuddy']->get_comment( $file );
  81. // Check for DAT file.
  82. if ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, 'wp-content/uploads/backupbuddy_temp/' . $serial . '/backupbuddy_dat.php' ) === true ) { // Post 2.0 full backup
  83. $status_details['found_dat'] = true;
  84. $backup_type = 'full';
  85. }
  86. if ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, 'wp-content/uploads/temp_' . $serial . '/backupbuddy_dat.php' ) === true ) { // Pre 2.0 full backup
  87. $status_details['found_dat'] = true;
  88. $backup_type = 'full';
  89. }
  90. if ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, 'backupbuddy_dat.php' ) === true ) { // DB backup
  91. $status_details['found_dat'] = true;
  92. $backup_type = 'db';
  93. }
  94. // Check for DB SQL file.
  95. if ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, 'wp-content/uploads/backupbuddy_temp/' . $serial . '/db_1.sql' ) === true ) { // post 2.0 full backup
  96. $status_details['found_sql'] = true;
  97. $backup_type = 'full';
  98. }
  99. if ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, 'wp-content/uploads/temp_' . $serial . '/db.sql' ) === true ) { // pre 2.0 full backup
  100. $status_details['found_sql'] = true;
  101. $backup_type = 'full';
  102. }
  103. if ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, 'db_1.sql' ) === true ) { // db only backup 2.0+
  104. $status_details['found_sql'] = true;
  105. $backup_type = 'db';
  106. }
  107. if ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, 'db.sql' ) === true ) { // db only backup pre-2.0
  108. $status_details['found_sql'] = true;
  109. $backup_type = 'db';
  110. }
  111. // Check for WordPress config file.
  112. if ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, 'wp-config.php' ) === true ) {
  113. $status_details['found_wpconfig'] = true;
  114. $backup_type = 'full';
  115. }
  116. if ( pb_backupbuddy::$classes['zipbuddy']->file_exists( $file, 'wp-content/uploads/backupbuddy_temp/' . $serial . '/wp-config.php' ) === true ) {
  117. $status_details['found_wpconfig'] = true;
  118. $backup_type = 'full';
  119. }
  120. // Get zip scan log details.
  121. $temp_details = pb_backupbuddy::get_status( 'zipbuddy_test' ); // Get zipbuddy scan log.
  122. foreach( $temp_details as $temp_detail ) {
  123. $status_details['scan_log'][] = $temp_detail[4];
  124. }
  125. pb_backupbuddy::set_status_serial( '' ); // Stop redirecting log to a specific file.
  126. // Calculate status descriptions.
  127. $integrity_status = 'pass'; // Default.
  128. if ( $status_details['found_dat'] !== true ) {
  129. $integrity_status = 'fail';
  130. $integrity_description .= __('Error #7843564: Missing DAT file.', 'it-l10n-backupbuddy' );
  131. }
  132. if ( $status_details['found_sql'] !== true ) {
  133. $integrity_status = 'fail';
  134. $integrity_description .= __('Error #4664236: Missing database SQL file.', 'it-l10n-backupbuddy' );
  135. }
  136. if ( ( $backup_type == 'full' ) && ( $status_details['found_wpconfig'] !== true ) ) {
  137. $integrity_status = 'fail';
  138. $integrity_description .= __('Error #47834674: Missing wp-config.php file.', 'it-l10n-backupbuddy' );
  139. }
  140. if ( $integrity_status == 'pass' ) { // All tests passed.
  141. $integrity_description = __( 'All tests passed.', 'it-l10n-backupbuddy' );
  142. }
  143. //$integrity_description .= '<br><br>' . __('Technical Details', 'it-l10n-backupbuddy' ) . ':<br />' . $integrity_zipresult_details;
  144. //***** END CALCULATING STATUS DETAILS.
  145. // Get file information from file system.
  146. $file_stats = @stat( $file );
  147. if ( $file_stats === false ) { // stat failure.
  148. pb_backupbuddy::alert( 'Error #4539774b. Unable to get file details ( via stat() ) for file `' . $file . '`. The file may be corrupt or too large for the server.' );
  149. $file_size = 0;
  150. $file_modified = 0;
  151. } else { // stat success.
  152. $file_size = $file_stats['size'];
  153. $file_modified = $file_stats['ctime']; // Created time.
  154. }
  155. unset( $file_stats );
  156. // Compile array of results for saving into data structure.
  157. $integrity = array(
  158. 'status' => $integrity_status,
  159. 'status_details' => $status_details, // $integrity_description,
  160. 'scan_time' => time(),
  161. 'detected_type' => $backup_type,
  162. 'size' => $file_size,
  163. 'modified' => $file_modified, // Actually created time now.
  164. 'file' => basename( $file ),
  165. 'comment' => $comment, // boolean false if no comment. string if comment.
  166. );
  167. pb_backupbuddy::$options['backups'][$serial]['integrity'] = array_merge( pb_backupbuddy::settings( 'backups_integrity_defaults' ), $integrity );
  168. pb_backupbuddy::save();
  169. //pb_backupbuddy::$classes['zipbuddy']->clear_status();
  170. if ( $integrity_status == 'pass' ) { // 100% success
  171. return true;
  172. } else {
  173. return false;
  174. }
  175. } // End backup_integrity_check().
  176. /* get_serial_from_file()
  177. *
  178. * Returns the backup serial based on the filename.
  179. *
  180. * @param string $file Filename containing a serial to extract.
  181. * @return string Serial found.
  182. */
  183. public function get_serial_from_file( $file ) {
  184. $serial = strrpos( $file, '-' ) + 1;
  185. $serial = substr( $file, $serial, ( strlen( $file ) - $serial - 4 ) );
  186. return $serial;
  187. } // End get_serial_from_file().
  188. /**
  189. * versions_confirm()
  190. *
  191. * Check the version of an item and compare it to the minimum requirements BackupBuddy requires.
  192. *
  193. * @param string $type Optional. If left blank '' then all tests will be performed. Valid values: wordpress, php, ''.
  194. * @param boolean $notify Optional. Whether or not to alert to the screen (and throw error to log) of a version issue.\
  195. * @return boolean True if the selected type is a bad version
  196. */
  197. function versions_confirm( $type = '', $notify = false ) {
  198. $bad_version = false;
  199. if ( ( $type == 'wordpress' ) || ( $type == '' ) ) {
  200. global $wp_version;
  201. if ( version_compare( $wp_version, pb_backupbuddy::settings( 'wp_minimum' ), '<=' ) ) {
  202. if ( $notify === true ) {
  203. pb_backupbuddy::alert( sprintf( __('ERROR: BackupBuddy requires WordPress version %1$s or higher. You may experience unexpected behavior or complete failure in this environment. Please consider upgrading WordPress.', 'it-l10n-backupbuddy' ), $this->_wp_minimum) );
  204. pb_backupbuddy::log( 'Unsupported WordPress Version: ' . $wp_version , 'error' );
  205. }
  206. $bad_version = true;
  207. }
  208. }
  209. if ( ( $type == 'php' ) || ( $type == '' ) ) {
  210. if ( version_compare( PHP_VERSION, pb_backupbuddy::settings( 'php_minimum' ), '<=' ) ) {
  211. if ( $notify === true ) {
  212. pb_backupbuddy::alert( sprintf( __('ERROR: BackupBuddy requires PHP version %1$s or higher. You may experience unexpected behavior or complete failure in this environment. Please consider upgrading PHP.', 'it-l10n-backupbuddy' ), PHP_VERSION ) );
  213. pb_backupbuddy::log( 'Unsupported PHP Version: ' . PHP_VERSION , 'error' );
  214. }
  215. $bad_version = true;
  216. }
  217. }
  218. return $bad_version;
  219. } // End versions_confirm().
  220. /* get_directory_exclusions()
  221. *
  222. * Get sanitized directory exclusions. See important note below!
  223. * IMPORTANT NOTE: Cannot exclude the temp directory here as this is where SQL and DAT files are stored for inclusion in the backup archive.
  224. *
  225. * @return array Array of directories to exclude.
  226. */
  227. public static function get_directory_exclusions() {
  228. // Get initial array.
  229. $exclusions = trim( pb_backupbuddy::$options['excludes'] ); // Trim string.
  230. $exclusions = preg_split('/\n|\r|\r\n/', $exclusions ); // Break into array on any type of line ending.
  231. // Add additional internal exclusions.
  232. $exclusions[] = str_replace( rtrim( ABSPATH, '\\\/' ), '', pb_backupbuddy::$options['backup_directory'] ); // Exclude backup directory.
  233. $exclusions[] = '/wp-content/uploads/pb_backupbuddy/'; // BackupBuddy logs and junk.
  234. $exclusions[] = '/importbuddy/'; // Exclude importbuddy directory in root.
  235. $exclusions[] = '/importbuddy.php'; // Exclude importbuddy.php script in root.
  236. // Clean up & sanitize array.
  237. array_walk( $exclusions, create_function( '&$val', '$val = rtrim( trim( $val ), \'/\' );' ) ); // Apply trim to all items within.
  238. $exclusions = array_filter( $exclusions, 'strlen' ); // Remove any empty / blank lines.
  239. // IMPORTANT NOTE: Cannot exclude the temp directory here as this is where SQL and DAT files are stored for inclusion in the backup archive.
  240. return $exclusions;
  241. } // End get_directory_exclusions().
  242. /* mail_error()
  243. *
  244. * Sends an error email to the defined email address(es) on settings page.
  245. *
  246. * @param string $message Message to be included in the body of the email.
  247. * @return null
  248. */
  249. function mail_error( $message ) {
  250. if ( !isset( pb_backupbuddy::$options ) ) {
  251. pb_backupbuddy::load();
  252. }
  253. $subject = pb_backupbuddy::$options['email_notify_error_subject'];
  254. $body = pb_backupbuddy::$options['email_notify_error_body'];
  255. $replacements = array(
  256. '{site_url}' => site_url(),
  257. '{backupbuddy_version}' => pb_backupbuddy::settings( 'version' ),
  258. '{current_datetime}' => date(DATE_RFC822),
  259. '{message}' => $message
  260. );
  261. foreach( $replacements as $replace_key => $replacement ) {
  262. $subject = str_replace( $replace_key, $replacement, $subject );
  263. $body = str_replace( $replace_key, $replacement, $body );
  264. }
  265. $email = pb_backupbuddy::$options['email_notify_error'];
  266. pb_backupbuddy::status( 'error', 'Sending email error notification. Subject: `' . $subject . '`; body: `' . $body . '`; recipient(s): `' . $email . '`.' );
  267. if ( !empty( $email ) ) {
  268. wp_mail( $email, $subject, $body, 'From: '.$email."\r\n".'Reply-To: '.get_option('admin_email')."\r\n");
  269. }
  270. } // End mail_error().
  271. /* mail_notify_scheduled()
  272. *
  273. * Sends a message email to the defined email address(es) on settings page.
  274. *
  275. * @param string $start_or_complete Whether this is the notifcation for starting or completing. Valid values: start, complete
  276. * @param string $message Message to be included in the body of the email.
  277. * @return null
  278. */
  279. function mail_notify_scheduled( $serial, $start_or_complete, $message ) {
  280. if ( !isset( pb_backupbuddy::$options ) ) {
  281. pb_backupbuddy::load();
  282. }
  283. if ( $start_or_complete == 'start' ) {
  284. $email = pb_backupbuddy::$options['email_notify_scheduled_start'];
  285. $subject = pb_backupbuddy::$options['email_notify_scheduled_start_subject'];
  286. $body = pb_backupbuddy::$options['email_notify_scheduled_start_body'];
  287. $replacements = array(
  288. '{site_url}' => site_url(),
  289. '{backupbuddy_version}' => pb_backupbuddy::settings( 'version' ),
  290. '{current_datetime}' => date(DATE_RFC822),
  291. '{message}' => $message
  292. );
  293. } elseif ( $start_or_complete == 'complete' ) {
  294. $email = pb_backupbuddy::$options['email_notify_scheduled_complete'];
  295. $subject = pb_backupbuddy::$options['email_notify_scheduled_complete_subject'];
  296. $body = pb_backupbuddy::$options['email_notify_scheduled_complete_body'];
  297. $replacements = array(
  298. '{site_url}' => site_url(),
  299. '{backupbuddy_version}' => pb_backupbuddy::settings( 'version' ),
  300. '{current_datetime}' => date(DATE_RFC822),
  301. '{message}' => $message,
  302. '{backup_serial}' => $serial,
  303. '{download_link}' => pb_backupbuddy::ajax_url( 'download_archive' ) . '&backupbuddy_backup=' . basename( pb_backupbuddy::$options['backups'][$serial]['archive_file'] ),
  304. '{backup_file}' => basename( pb_backupbuddy::$options['backups'][$serial]['archive_file'] ),
  305. '{backup_size}' => pb_backupbuddy::$format->file_size( pb_backupbuddy::$options['backups'][$serial]['archive_size'] ),
  306. '{backup_type}' => pb_backupbuddy::$options['backups'][$serial]['type'],
  307. );
  308. } else {
  309. pb_backupbuddy::status( 'error', 'ERROR #54857845785: Fatally halted. Invalid schedule type. Expected `start` or `complete`. Got `' . $start_or_complete . '`.' );
  310. }
  311. foreach( $replacements as $replace_key => $replacement ) {
  312. $subject = str_replace( $replace_key, $replacement, $subject );
  313. $body = str_replace( $replace_key, $replacement, $body );
  314. }
  315. pb_backupbuddy::status( 'error', 'Sending email schedule notification. Subject: `' . $subject . '`; body: `' . $body . '`; recipient(s): `' . $email . '`.' );
  316. if ( !empty( $email ) ) {
  317. wp_mail( $email, $subject, $body, 'From: '.$email."\r\n".'Reply-To: '.get_option('admin_email')."\r\n");
  318. }
  319. } // End mail_notify_scheduled().
  320. /* backup_prefix()
  321. *
  322. * Strips all non-file-friendly characters from the site URL. Used in making backup zip filename.
  323. *
  324. * @return string The filename friendly converted site URL.
  325. */
  326. function backup_prefix() {
  327. $siteurl = site_url();
  328. $siteurl = str_replace( 'http://', '', $siteurl );
  329. $siteurl = str_replace( 'https://', '', $siteurl );
  330. $siteurl = str_replace( '/', '_', $siteurl );
  331. $siteurl = str_replace( '\\', '_', $siteurl );
  332. $siteurl = str_replace( '.', '_', $siteurl );
  333. $siteurl = str_replace( ':', '_', $siteurl ); // Alternative port from 80 is stored in the site url.
  334. $siteurl = str_replace( '~', '_', $siteurl ); // Strip ~.
  335. return $siteurl;
  336. } // End backup_prefix().
  337. /* send_remote_destination()
  338. *
  339. * function description
  340. *
  341. * @param int $destination_id ID number (index of the destinations array) to send it.
  342. * @param string $file Full file path of file to send.
  343. * @param string $trigger What triggered this backup. Valid values: scheduled, manual.
  344. * @param bool $send_importbuddy Whether or not importbuddy.php should also be sent with the file to destination.
  345. * @return bool Send status. true success, false failed.
  346. */
  347. function send_remote_destination( $destination_id, $file, $trigger = '', $send_importbuddy = false ) {
  348. pb_backupbuddy::status( 'details', 'Sending file `' . $file . '` to remote destination `' . $destination_id . '` triggered by `' . $trigger . '`.' );
  349. if ( defined( 'PB_DEMO_MODE' ) ) {
  350. return false;
  351. }
  352. // Record some statistics.
  353. $identifier = pb_backupbuddy::random_string( 12 );
  354. pb_backupbuddy::$options['remote_sends'][$identifier] = array(
  355. 'destination' => $destination_id,
  356. 'file' => $file,
  357. 'file_size' => filesize( $file ),
  358. 'trigger' => $trigger, // What triggered this backup. Valid values: scheduled, manual.
  359. 'send_importbuddy' => $send_importbuddy,
  360. 'start_time' => time(),
  361. 'finish_time' => 0,
  362. 'status' => 'timeout', // success, failure, timeout (default assumption if this is not updated in this PHP load)
  363. );
  364. pb_backupbuddy::save();
  365. // Prepare variables to pass to remote destination handler.
  366. $files = array( $file );
  367. $destination_settings = &pb_backupbuddy::$options['remote_destinations'][$destination_id];
  368. // For Stash we will check the quota prior to initiating send.
  369. if ( pb_backupbuddy::$options['remote_destinations'][$destination_id]['type'] == 'stash' ) {
  370. // Pass off to destination handler.
  371. require_once( pb_backupbuddy::plugin_path() . '/destinations/bootstrap.php' );
  372. $send_result = pb_backupbuddy_destinations::get_info( 'stash' ); // Used to kick the Stash destination into life.
  373. $stash_quota = pb_backupbuddy_destination_stash::get_quota( pb_backupbuddy::$options['remote_destinations'][$destination_id], true );
  374. if ( $file != '' ) {
  375. $backup_file_size = filesize( $file );
  376. } else {
  377. $backip_file_size = 50000;
  378. }
  379. if ( ( $backup_file_size + $stash_quota['quota_used'] ) > $stash_quota['quota_total'] ) {
  380. $message = '';
  381. $message .= "You do not have enough Stash storage space to send this file. Please upgrade your Stash storage at http://ithemes.com/member/stash.php or delete files to make space.\n\n";
  382. $message .= 'Attempting to send file of size ' . pb_backupbuddy::$format->file_size( $backup_file_size ) . ' but you only have ' . $stash_quota['quota_available_nice'] . ' available. ';
  383. $message .= 'Currently using ' . $stash_quota['quota_used_nice'] . ' of ' . $stash_quota['quota_total_nice'] . ' (' . $stash_quota['quota_used_percent'] . '%).';
  384. pb_backupbuddy::status( 'error', $message );
  385. pb_backupbuddy::$classes['core']->mail_error( $message );
  386. pb_backupbuddy::$options['remote_sends'][$identifier]['status'] = 'Failure. Insufficient destination space.';
  387. pb_backupbuddy::save();
  388. return false;
  389. } else {
  390. if ( isset( $stash_quota['quota_warning'] ) && ( $stash_quota['quota_warning'] != '' ) ) {
  391. // We log warning of usage but dont send error email.
  392. $message = '';
  393. $message .= 'WARNING: ' . $stash_quota['quota_warning'] . "\n\nPlease upgrade your Stash storage at http://ithemes.com/member/stash.php or delete files to make space.\n\n";
  394. $message .= 'Currently using ' . $stash_quota['quota_used_nice'] . ' of ' . $stash_quota['quota_total_nice'] . ' (' . $stash_quota['quota_used_percent'] . '%).';
  395. pb_backupbuddy::status( 'details', $message );
  396. //pb_backupbuddy::$classes['core']->mail_error( $message );
  397. }
  398. }
  399. }
  400. if ( $send_importbuddy === true ) {
  401. pb_backupbuddy::status( 'details', 'Generating temporary importbuddy.php file for remote send.' );
  402. $importbuddy_temp = pb_backupbuddy::$options['temp_directory'] . 'importbuddy.php'; // Full path & filename to temporary importbuddy
  403. $this->importbuddy( $importbuddy_temp ); // Create temporary importbuddy.
  404. pb_backupbuddy::status( 'details', 'Generated temporary importbuddy.' );
  405. $files[] = $importbuddy_temp; // Add importbuddy file to the list of files to send.
  406. $send_importbuddy = true; // Track to delete after finished.
  407. } else {
  408. pb_backupbuddy::status( 'details', 'Not sending importbuddy.' );
  409. }
  410. // Pass off to destination handler.
  411. require_once( pb_backupbuddy::plugin_path() . '/destinations/bootstrap.php' );
  412. $send_result = pb_backupbuddy_destinations::send( $destination_settings, $files );
  413. $this->kick_db(); // Kick the database to make sure it didn't go away, preventing options saving.
  414. // Update stats.
  415. pb_backupbuddy::$options['remote_sends'][$identifier]['finish_time'] = time();
  416. if ( $send_result === true ) { // succeeded.
  417. pb_backupbuddy::$options['remote_sends'][$identifier]['status'] = 'success';
  418. pb_backupbuddy::status( 'details', 'Remote send SUCCESS.' );
  419. } elseif ( $send_result === false ) { // failed.
  420. pb_backupbuddy::$options['remote_sends'][$identifier]['status'] = 'failure';
  421. pb_backupbuddy::status( 'details', 'Remote send FAILURE.' );
  422. } elseif ( is_array( $send_result ) ) { // Array so multipart.
  423. pb_backupbuddy::$options['remote_sends'][$identifier]['status'] = 'multipart';
  424. pb_backupbuddy::$options['remote_sends'][$identifier]['finish_time'] = 0;
  425. pb_backupbuddy::$options['remote_sends'][$identifier]['_multipart_id'] = $send_result[0];
  426. pb_backupbuddy::$options['remote_sends'][$identifier]['_multipart_status'] = $send_result[1];
  427. pb_backupbuddy::status( 'details', 'Multipart send in progress.' );
  428. } else {
  429. pb_backupbuddy::status( 'error', 'Error #5485785576463. Invalid status send result: `' . $send_result . '`.' );
  430. }
  431. pb_backupbuddy::save();
  432. // If we sent importbuddy then delete the local copy to clean up.
  433. if ( $send_importbuddy !== false ) {
  434. @unlink( $importbuddy_temp ); // Delete temporary importbuddy.
  435. }
  436. return $send_result;
  437. } // End send_remote_destination().
  438. /* destination_send()
  439. *
  440. * Send file(s) to a destination. Pass full array of destination settings.
  441. *
  442. * @param array $destination_settings All settings for this destination for this action.
  443. * @param array $files Array of files to send (full path).
  444. * @return bool|array Bool true = success, bool false = fail, array = multipart transfer.
  445. */
  446. public function destination_send( $destination_settings, $files ) {
  447. // Pass off to destination handler.
  448. require_once( pb_backupbuddy::plugin_path() . '/destinations/bootstrap.php' );
  449. $send_result = pb_backupbuddy_destinations::send( $destination_settings, $files );
  450. return $send_result;
  451. } // End destination_send().
  452. /* backups_list()
  453. *
  454. * function description
  455. *
  456. * @param string $type Valid options: default, migrate
  457. * @param boolean $subsite_mode When in subsite mode only backups for that specific subsite will be listed.
  458. * @return
  459. */
  460. public function backups_list( $type = 'default', $subsite_mode = false ) {
  461. if ( pb_backupbuddy::_POST( 'bulk_action' ) == 'delete_backup' ) {
  462. $needs_save = false;
  463. pb_backupbuddy::verify_nonce( pb_backupbuddy::_POST( '_wpnonce' ) ); // Security check to prevent unauthorized deletions by posting from a remote place.
  464. $deleted_files = array();
  465. foreach( pb_backupbuddy::_POST( 'items' ) as $item ) {
  466. if ( file_exists( pb_backupbuddy::$options['backup_directory'] . $item ) ) {
  467. if ( @unlink( pb_backupbuddy::$options['backup_directory'] . $item ) === true ) {
  468. $deleted_files[] = $item;
  469. if ( count( pb_backupbuddy::$options['backups'] ) > 5 ) { // Keep a minimum number of backups in array for stats.
  470. $this_serial = $this->get_serial_from_file( $item );
  471. unset( pb_backupbuddy::$options['backups'][$this_serial] );
  472. $needs_save = true;
  473. }
  474. } else {
  475. pb_backupbuddy::alert( 'Error: Unable to delete backup file `' . $item . '`. Please verify permissions.', true );
  476. }
  477. } // End if file exists.
  478. } // End foreach.
  479. if ( $needs_save === true ) {
  480. pb_backupbuddy::save();
  481. }
  482. pb_backupbuddy::alert( __( 'Deleted backup(s):', 'it-l10n-backupbuddy' ) . ' ' . implode( ', ', $deleted_files ) );
  483. } // End if deleting backup(s).
  484. $backups = array();
  485. $backup_sort_dates = array();
  486. $files = glob( pb_backupbuddy::$options['backup_directory'] . 'backup*.zip' );
  487. if ( is_array( $files ) && !empty( $files ) ) { // For robustness. Without open_basedir the glob() function returns an empty array for no match. With open_basedir in effect the glob() function returns a boolean false for no match.
  488. $backup_prefix = $this->backup_prefix(); // Backup prefix for this site. Used for MS checking that this user can see this backup.
  489. foreach( $files as $file_id => $file ) {
  490. if ( ( $subsite_mode === true ) && is_multisite() ) { // If a Network and NOT the superadmin must make sure they can only see the specific subsite backups for security purposes.
  491. // Only allow viewing of their own backups.
  492. if ( !strstr( $file, $backup_prefix ) ) {
  493. unset( $files[$file_id] ); // Remove this backup from the list. This user does not have access to it.
  494. continue; // Skip processing to next file.
  495. }
  496. }
  497. $serial = pb_backupbuddy::$classes['core']->get_serial_from_file( $file );
  498. // Populate integrity data structure in options.
  499. pb_backupbuddy::$classes['core']->backup_integrity_check( $file );
  500. // Backup status.
  501. $pretty_status = array(
  502. 'pass' => '<span class="pb_label pb_label-success">Good</span>', //'Good',
  503. 'fail' => '<span class="pb_label pb_label-important">Bad</span>',
  504. );
  505. // Backup type.
  506. $pretty_type = array(
  507. 'full' => 'Full',
  508. 'db' => 'Database',
  509. );
  510. $step_times = array();
  511. if ( isset( pb_backupbuddy::$options['backups'][$serial]['steps'] ) ) {
  512. foreach( pb_backupbuddy::$options['backups'][$serial]['steps'] as $step ) {
  513. if ( isset( $step['finish_time'] ) && ( $step['finish_time'] != 0 ) ) {
  514. // Step time taken.
  515. $step_times[] = $step['finish_time'] - $step['start_time'];
  516. }
  517. } // End foreach.
  518. } else { // End if serial in array is set.
  519. $step_times[] = 'unknown';
  520. } // End if serial in array is NOT set.
  521. $step_times = implode( ', ', $step_times );
  522. // Calculate zipping step time to use later for calculating write speed.
  523. if ( isset( pb_backupbuddy::$options['backups'][$serial]['steps']['backup_zip_files'] ) ) {
  524. $zip_time = pb_backupbuddy::$options['backups'][$serial]['steps']['backup_zip_files'];
  525. } else {
  526. $zip_time = 0;
  527. }
  528. // Calculate write speed in MB/sec for this backup.
  529. if ( $zip_time == '0' ) { // Took approx 0 seconds to backup so report this speed.
  530. if ( !isset( $finish_time ) || ( $finish_time == '0' ) ) {
  531. $write_speed = 'unknown';
  532. } else {
  533. $write_speed = '> ' . pb_backupbuddy::$format->file_size( pb_backupbuddy::$options['backups'][$serial]['integrity']['size'] );
  534. }
  535. } else {
  536. $write_speed = pb_backupbuddy::$format->file_size( pb_backupbuddy::$options['backups'][$serial]['integrity']['size'] / $zip_time );
  537. }
  538. // Calculate start and finish.
  539. if ( isset( pb_backupbuddy::$options['backups'][$serial]['start_time'] ) && isset( pb_backupbuddy::$options['backups'][$serial]['finish_time'] ) && ( pb_backupbuddy::$options['backups'][$serial]['start_time'] >0 ) && ( pb_backupbuddy::$options['backups'][$serial]['finish_time'] > 0 ) ) {
  540. $start_time = pb_backupbuddy::$options['backups'][$serial]['start_time'];
  541. $finish_time = pb_backupbuddy::$options['backups'][$serial]['finish_time'];
  542. $total_time = $finish_time - $start_time;
  543. } else {
  544. $total_time = 'unknown';
  545. }
  546. // Figure out trigger.
  547. if ( isset( pb_backupbuddy::$options['backups'][$serial]['trigger'] ) ) {
  548. $trigger = pb_backupbuddy::$options['backups'][$serial]['trigger'];
  549. } else {
  550. $trigger = __( 'Unknown', 'it-l10n-backupbuddy' );
  551. }
  552. // HTML output for stats.
  553. $statistics = '';
  554. if ( $total_time != 'unknown' ) {
  555. $statistics .= "<span style='width: 80px; display: inline-block;'>Total time:</span>{$total_time} secs<br>";
  556. }
  557. if ( $step_times != 'unknown' ) {
  558. $statistics .= "<span style='width: 80px; display: inline-block;'>Step times:</span>{$step_times}<br>";
  559. }
  560. if ( $write_speed != 'unknown' ) {
  561. $statistics .= "<span style='width: 80px; display: inline-block;'>Write speed:</span>{$write_speed}/sec";
  562. }
  563. // Calculate time ago.
  564. $time_ago = '<span class="description">' . pb_backupbuddy::$format->time_ago( pb_backupbuddy::$options['backups'][$serial]['integrity']['modified'] ) . ' ago</span>';
  565. // Calculate main row string.
  566. if ( $type == 'default' ) { // Default backup listing.
  567. $main_string = '<a href="' . pb_backupbuddy::ajax_url( 'download_archive' ) . '&backupbuddy_backup=' . basename( $file ) . '">' . basename( $file ) . '</a>';
  568. } elseif ( $type == 'migrate' ) { // Migration backup listing.
  569. $main_string = '<a class="pb_backupbuddy_hoveraction_migrate" rel="' . basename( $file ) . '" href="' . pb_backupbuddy::page_url() . '&migrate=' . basename( $file ) . '&value=' . basename( $file ) . '">' . basename( $file ) . '</a>';
  570. } else {
  571. $main_string = '{Unknown type.}';
  572. }
  573. // Add comment to main row string if applicable.
  574. if ( isset( pb_backupbuddy::$options['backups'][$serial]['integrity']['comment'] ) && ( pb_backupbuddy::$options['backups'][$serial]['integrity']['comment'] !== false ) && ( pb_backupbuddy::$options['backups'][$serial]['integrity']['comment'] !== '' ) ) {
  575. $main_string .= '<br><span class="description">Note: <span class="pb_backupbuddy_notetext">' . pb_backupbuddy::$options['backups'][$serial]['integrity']['comment'] . '</span></span>';
  576. }
  577. if ( pb_backupbuddy::$options['backups'][$serial]['integrity']['status'] == 'pass' ) {
  578. $status_details = __( 'All tests passed.', 'it-l10n-backupbuddy' );
  579. } else {
  580. $status_details = pb_backupbuddy::$options['backups'][$serial]['integrity']['status_details'];
  581. }
  582. $backups[basename( $file )] = array(
  583. array( basename( $file ), $main_string ),
  584. pb_backupbuddy::$format->prettify( pb_backupbuddy::$options['backups'][$serial]['integrity']['detected_type'], $pretty_type ),
  585. pb_backupbuddy::$format->file_size( pb_backupbuddy::$options['backups'][$serial]['integrity']['size'] ),
  586. pb_backupbuddy::$format->date( pb_backupbuddy::$format->localize_time( pb_backupbuddy::$options['backups'][$serial]['integrity']['modified'] ) ) . '<br>' . $time_ago,
  587. $statistics,
  588. pb_backupbuddy::$format->prettify( pb_backupbuddy::$options['backups'][$serial]['integrity']['status'], $pretty_status ) .
  589. ' <a href="' . pb_backupbuddy::page_url() . '&reset_integrity=' . $serial . '" title="Rescan integrity. Last checked ' . pb_backupbuddy::$format->date( pb_backupbuddy::$options['backups'][$serial]['integrity']['scan_time'] ) . '."><img src="' . pb_backupbuddy::plugin_url() . '/images/refresh_gray.gif" style="vertical-align: -1px;"></a>' .
  590. '<div class="row-actions"><a title="' . __( 'Integrity Check Details', 'it-l10n-backupbuddy' ) . '" href="' . pb_backupbuddy::ajax_url( 'integrity_status' ) . '&serial=' . $serial . '&#038;TB_iframe=1&#038;width=640&#038;height=600" class="thickbox">' . __( 'View Details', 'it-l10n-backupbuddy' ) . '</a></div>',
  591. );
  592. $backup_sort_dates[basename( $file)] = pb_backupbuddy::$options['backups'][$serial]['integrity']['modified'];
  593. } // End foreach().
  594. } // End if.
  595. // Sort backup sizes.
  596. arsort( $backup_sort_dates );
  597. // Re-arrange backups based on sort dates.
  598. $sorted_backups = array();
  599. foreach( $backup_sort_dates as $backup_file => $backup_sort_date ) {
  600. $sorted_backups[$backup_file] = $backups[$backup_file];
  601. unset( $backups[$backup_file] );
  602. }
  603. unset( $backups );
  604. return $sorted_backups;
  605. } // End backups_list().
  606. // If output file not specified then outputs to browser as download.
  607. // IMPORTANT: If outputting to browser (no output file) must die() after outputting content if using AJAX. Do not output to browser anything after this function in this case.
  608. public static function importbuddy( $output_file = '', $importbuddy_pass_hash = '' ) {
  609. if ( defined( 'PB_DEMO_MODE' ) ) {
  610. echo 'Access denied in demo mode.';
  611. return;
  612. }
  613. pb_backupbuddy::set_greedy_script_limits(); // Some people run out of PHP memory.
  614. if ( $importbuddy_pass_hash == '' ) {
  615. if ( !isset( pb_backupbuddy::$options ) ) {
  616. pb_backupbuddy::load();
  617. }
  618. $importbuddy_pass_hash = pb_backupbuddy::$options['importbuddy_pass_hash'];
  619. }
  620. if ( $importbuddy_pass_hash == '' ) {
  621. $message = 'Error #9032: Warning only - You have not set a password to generate the ImportBuddy script yet on the BackupBuddy Settings page. If you are creating a backup, the importbuddy.php restore script will not be included in the backup. You can download it from the Restore page. If you were trying to download ImportBuddy then you may have a plugin confict preventing the page from prompting you to enter a password.';
  622. pb_backupbuddy::status( 'warning', $message );
  623. return false;
  624. }
  625. $output = file_get_contents( pb_backupbuddy::plugin_path() . '/_importbuddy/_importbuddy.php' );
  626. if ( $importbuddy_pass_hash != '' ) {
  627. $output = preg_replace('/#PASSWORD#/', $importbuddy_pass_hash, $output, 1 ); // Only replaces first instance.
  628. }
  629. $output = preg_replace('/#VERSION#/', pb_backupbuddy::settings( 'version' ), $output, 1 ); // Only replaces first instance.
  630. // PACK IMPORTBUDDY
  631. $_packdata = array( // NO TRAILING OR PRECEEDING SLASHES!
  632. '_importbuddy/importbuddy' => 'importbuddy',
  633. 'classes/_migrate_database.php' => 'importbuddy/classes/_migrate_database.php',
  634. 'classes/core.php' => 'importbuddy/classes/core.php',
  635. 'classes/import.php' => 'importbuddy/classes/import.php',
  636. 'images/working.gif' => 'importbuddy/images/working.gif',
  637. 'images/bullet_go.png' => 'importbuddy/images/bullet_go.png',
  638. 'images/favicon.png' => 'importbuddy/images/favicon.png',
  639. 'images/sort_down.png' => 'importbuddy/images/sort_down.png',
  640. 'lib/dbreplace' => 'importbuddy/lib/dbreplace',
  641. 'lib/dbimport' => 'importbuddy/lib/dbimport',
  642. 'lib/commandbuddy' => 'importbuddy/lib/commandbuddy',
  643. 'lib/zipbuddy' => 'importbuddy/lib/zipbuddy',
  644. 'lib/mysqlbuddy' => 'importbuddy/lib/mysqlbuddy',
  645. 'lib/textreplacebuddy' => 'importbuddy/lib/textreplacebuddy',
  646. 'lib/cpanel' => 'importbuddy/lib/cpanel',
  647. 'pluginbuddy' => 'importbuddy/pluginbuddy',
  648. 'controllers/pages/server_info' => 'importbuddy/controllers/pages/server_info',
  649. 'controllers/pages/server_info.php' => 'importbuddy/controllers/pages/server_info.php',
  650. //'classes/_get_backup_dat.php' => 'importbuddy/classes/_get_backup_dat.php',
  651. // Stash
  652. 'destinations/stash/lib/class.itx_helper.php' => 'importbuddy/classes/class.itx_helper.php',
  653. 'destinations/stash/lib/aws-sdk/lib/requestcore' => 'importbuddy/lib/requestcore',
  654. //'destinations/bootstrap.php' => 'importbuddy/destinations/bootstrap.php',
  655. //'destinations/stash' => 'importbuddy/destinations/stash',
  656. );
  657. $output .= "\n<?php /*\n###PACKDATA,BEGIN\n";
  658. foreach( $_packdata as $pack_source => $pack_destination ) {
  659. $pack_source = '/' . $pack_source;
  660. if ( is_dir( pb_backupbuddy::plugin_path() . $pack_source ) ) {
  661. $files = pb_backupbuddy::$filesystem->deepglob( pb_backupbuddy::plugin_path() . $pack_source );
  662. } else {
  663. $files = array( pb_backupbuddy::plugin_path() . $pack_source );
  664. }
  665. foreach( $files as $file ) {
  666. if ( is_file( $file ) ) {
  667. $source = str_replace( pb_backupbuddy::plugin_path(), '', $file );
  668. $destination = $pack_destination . substr( $source, strlen( $pack_source ) );
  669. $output .= "###PACKDATA,FILE_START,{$source},{$destination}\n";
  670. $output .= base64_encode( file_get_contents( $file ) );
  671. $output .= "\n";
  672. $output .= "###PACKDATA,FILE_END,{$source},{$destination}\n";
  673. }
  674. }
  675. }
  676. $output .= "###PACKDATA,END\n*/";
  677. $output .= "\n\n\n\n\n\n\n\n\n\n";
  678. if ( $output_file == '' ) { // No file so output to browser.
  679. header( 'Content-Description: File Transfer' );
  680. header( 'Content-Type: text/plain; name=importbuddy.php' );
  681. header( 'Content-Disposition: attachment; filename=importbuddy.php' );
  682. header( 'Expires: 0' );
  683. header( 'Content-Length: ' . strlen( $output ) );
  684. flush();
  685. echo $output;
  686. flush();
  687. // BE SURE TO die() AFTER THIS AND NOT OUTPUT TO BROWSER!
  688. } else { // Write to file.
  689. file_put_contents( $output_file, $output );
  690. }
  691. } // End importbuddy().
  692. // TODO: RepairBuddy is not yet converted into new framework so just using pre-BB3.0 version for now.
  693. public function repairbuddy( $output_file = '' ) {
  694. if ( defined( 'PB_DEMO_MODE' ) ) {
  695. echo 'Access denied in demo mode.';
  696. return;
  697. }
  698. if ( !isset( pb_backupbuddy::$options ) ) {
  699. pb_backupbuddy::load();
  700. }
  701. $output = file_get_contents( pb_backupbuddy::plugin_path() . '/_repairbuddy.php' );
  702. if ( pb_backupbuddy::$options['repairbuddy_pass_hash'] != '' ) {
  703. $output = preg_replace('/#PASSWORD#/', pb_backupbuddy::$options['repairbuddy_pass_hash'], $output, 1 ); // Only replaces first instance.
  704. }
  705. $output = preg_replace('/#VERSION#/', pb_backupbuddy::settings( 'version' ), $output, 1 ); // Only replaces first instance.
  706. if ( $output_file == '' ) { // No file so output to browser.
  707. header( 'Content-Description: File Transfer' );
  708. header( 'Content-Type: text/plain; name=repairbuddy.php' );
  709. header( 'Content-Disposition: attachment; filename=repairbuddy.php' );
  710. header( 'Expires: 0' );
  711. header( 'Content-Length: ' . strlen( $output ) );
  712. flush();
  713. echo $output;
  714. flush();
  715. // BE SURE TO die() AFTER THIS AND NOT OUTPUT TO BROWSER!
  716. } else { // Write to file.
  717. file_put_contents( $output_file, $output );
  718. }
  719. } // End repairbuddy().
  720. function pretty_destination_type( $type ) {
  721. if ( $type == 'rackspace' ) {
  722. return 'Rackspace';
  723. } elseif ( $type == 'email' ) {
  724. return 'Email';
  725. } elseif ( $type == 's3' ) {
  726. return 'Amazon S3';
  727. } elseif ( $type == 'ftp' ) {
  728. return 'FTP';
  729. } elseif ( $type == 'dropbox' ) {
  730. return 'Dropbox';
  731. } else {
  732. return $type;
  733. }
  734. } // End pretty_destination_type().
  735. // $max_depth int Maximum depth of tree to display. Npte that deeper depths are still traversed for size calculations.
  736. function build_icicle( $dir, $base, $icicle_json, $max_depth = 10, $depth_count = 0, $is_root = true ) {
  737. $bg_color = '005282';
  738. $depth_count++;
  739. $bg_color = dechex( hexdec( $bg_color ) - ( $depth_count * 15 ) );
  740. $icicle_json = '{' . "\n";
  741. $dir_name = $dir;
  742. $dir_name = str_replace( ABSPATH, '', $dir );
  743. $dir_name = str_replace( '\\', '/', $dir_name );
  744. $dir_size = 0;
  745. $sub = opendir( $dir );
  746. $has_children = false;
  747. while( $file = readdir( $sub ) ) {
  748. if ( ( $file == '.' ) || ( $file == '..' ) ) {
  749. continue; // Next loop.
  750. } elseif ( is_dir( $dir . '/' . $file ) ) {
  751. $dir_array = '';
  752. $response = $this->build_icicle( $dir . '/' . $file, $base, $dir_array, $max_depth, $depth_count, false );
  753. if ( ( $max_depth-1 > 0 ) || ( $max_depth == -1 ) ) { // Only adds to the visual tree if depth isnt exceeded.
  754. if ( $max_depth > 0 ) {
  755. $max_depth = $max_depth - 1;
  756. }
  757. if ( $has_children === false ) { // first loop add children section
  758. $icicle_json .= '"children": [' . "\n";
  759. } else {
  760. $icicle_json .= ',';
  761. }
  762. $icicle_json .= $response[0];
  763. $has_children = true;
  764. }
  765. $dir_size += $response[1];
  766. unset( $response );
  767. unset( $file );
  768. } else {
  769. $stats = stat( $dir . '/' . $file );
  770. $dir_size += $stats['size'];
  771. unset( $file );
  772. }
  773. }
  774. closedir( $sub );
  775. unset( $sub );
  776. if ( $has_children === true ) {
  777. $icicle_json .= ' ]' . "\n";
  778. }
  779. if ( $has_children === true ) {
  780. $icicle_json .= ',';
  781. }
  782. $icicle_json .= '"id": "node_' . str_replace( '/', ':', $dir_name ) . ': ^' . str_replace( ' ', '~', pb_backupbuddy::$format->file_size( $dir_size ) ) . '"' . "\n";
  783. $dir_name = str_replace( '/', '', strrchr( $dir_name, '/' ) );
  784. if ( $dir_name == '' ) { // Set root to be /.
  785. $dir_name = '/';
  786. }
  787. $icicle_json .= ', "name": "' . $dir_name . ' (' . pb_backupbuddy::$format->file_size( $dir_size ) . ')"' . "\n";
  788. $icicle_json .= ',"data": { "$dim": ' . ( $dir_size + 10 ) . ', "$color": "#' . str_pad( $bg_color, 6, '0', STR_PAD_LEFT ) . '" }' . "\n";
  789. $icicle_json .= '}';
  790. if ( $is_root !== true ) {
  791. //$icicle_json .= ',x';
  792. }
  793. return array( $icicle_json, $dir_size );
  794. } // End build_icicle().
  795. // return array of tests and their results.
  796. public function preflight_check() {
  797. $tests = array();
  798. // MULTISITE BETA WARNING.
  799. if ( is_multisite() && pb_backupbuddy::$classes['core']->is_network_activated() && !defined( 'PB_DEMO_MODE' ) ) { // Multisite installation.
  800. $tests[] = array(
  801. 'test' => 'multisite_beta',
  802. 'success' => false,
  803. 'message' => 'BETA WARNING:
  804. Multisite functionality is in BETA and is not supported. It is for preview or experimental use only. It is not for use on live sites.
  805. Use of beta Multisite features on production sites is at your own risk.
  806. See the <a href="http://ithemes.com/codex/page/BackupBuddy_Multisite">Multisite Knowledge Base</a> for additional information.
  807. Multisite functionality does not receive official technical support due to the beta status.
  808. <br><br>
  809. Migrating entire Multisite Networks to a new URL is NOT supported.
  810. Networks cannot not be migrated to a new URL (especially in or out of a subdirectory) without advanced user assistance.
  811. As such, we do not officially support migrating a Network to a new URL.
  812. If you do migrate an entire Network to a new URL only the main site URLs will be migrated in the
  813. database. You may use the Server Information page Mass Database Text Replacement tool to manually
  814. migrate each subsite URL as needed. We recommend only advanced users attempt this. This is a technical
  815. limitation of Multisite Network migrations only, and only when the URL would change.
  816. '
  817. );
  818. }
  819. // LOOPBACKS TEST.
  820. if ( ( $loopback_response = $this->loopback_test() ) === true ) {
  821. $success = true;
  822. $message = '';
  823. } else { // failed
  824. $success = false;
  825. if ( defined( 'ALTERNATE_WP_CRON' ) && ( ALTERNATE_WP_CRON == true ) ) {
  826. $message = __('Running in Alternate WordPress Cron mode. HTTP Loopback Connections are not enabled on this server but you have overridden this in the wp-config.php file (this is a good thing).', 'it-l10n-backupbuddy' ) . ' <a href="http://ithemes.com/codex/page/BackupBuddy:_Frequent_Support_Issues#HTTP_Loopback_Connections_Disabled" target="_new">' . __('Additional Information Here', 'it-l10n-backupbuddy' ) . '</a>.';
  827. } else {
  828. $message = __('HTTP Loopback Connections are not enabled on this server. You may encounter stalled, significantly delayed backups, or other difficulties.', 'it-l10n-backupbuddy' ) . ' <a href="http://ithemes.com/codex/page/BackupBuddy:_Frequent_Support_Issues#HTTP_Loopback_Connections_Disabled" target="_new">' . __('Click for instructions on how to resolve this issue.', 'it-l10n-backupbuddy' ) . '</a>';
  829. }
  830. }
  831. $tests[] = array(
  832. 'test' => 'loopbacks',
  833. 'success' => $success,
  834. 'message' => $message,
  835. );
  836. // Reminder if no schedules are set up yet.
  837. /* CURRENTLY MOVED TO SCHEDULES PAGE.
  838. if ( count( pb_backupbuddy::$options['schedules'] ) == 0 ) {
  839. $success = false;
  840. $message = __( 'Reminder: Creating a <a href="?page=pb_backupbuddy_scheduling">scheduled backup</a> keeps your site safe and backed up without requiring manual backups. Create a schedule or dismiss this alert (link to the right) to hide it.', 'it-l10n-backupbuddy' );
  841. } else {
  842. $success = true;
  843. $message = '';
  844. }
  845. $tests[] = array(
  846. 'test' => 'no_schedule_reminder',
  847. 'success' => $success,
  848. 'message' => $message,
  849. );
  850. */
  851. // WORDPRESS IN SUBDIRECTORIES TEST.
  852. $wordpress_locations = $this->get_wordpress_locations();
  853. if ( count( $wordpress_locations ) > 0 ) {
  854. $success = false;
  855. $message = __( 'WordPress may have been detected in one or more subdirectories. Backing up multiple instances of WordPress may result in server timeouts due to increased backup time. You may exclude WordPress directories via the Settings page. Detected non-excluded locations:', 'it-l10n-backupbuddy' ) . ' ' . implode( ', ', $wordpress_locations );
  856. } else {
  857. $success = true;
  858. $message = '';
  859. }
  860. $tests[] = array(
  861. 'test' => 'wordpress_subdirectories',
  862. 'success' => $success,
  863. 'message' => $message,
  864. );
  865. // Log file directory writable for status logging.
  866. $status_directory = WP_CONTENT_DIR . '/uploads/pb_' . pb_backupbuddy::settings( 'slug' ) . '/';
  867. if ( ! is_writable( $status_directory ) ) {
  868. $success = false;
  869. $message = 'The status log file directory `' . $status_directory . '` is not writable. Please verify permissions before creating a backup. Backup status information will be unavailable until this is resolved.';
  870. } else {
  871. $success = true;
  872. $message = '';
  873. }
  874. $tests[] = array(
  875. 'test' => 'status_directory_writable',
  876. 'success' => $success,
  877. 'message' => $message,
  878. );
  879. // CHECK ZIP AVAILABILITY.
  880. require_once( pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php' );
  881. if ( !isset( pb_backupbuddy::$classes['zipbuddy'] ) ) {
  882. pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy( pb_backupbuddy::$options['backup_directory'] );
  883. }
  884. if ( !in_array( 'exec', pb_backupbuddy::$classes['zipbuddy']->_zip_methods ) ) {
  885. $success = false;
  886. $message = __('Your server does not support command line ZIP which is a BackupBuddy server requirement. Backups will be performed in compatibility mode.', 'it-l10n-backupbuddy' )
  887. . __('Directory/file exclusion is not available in this mode so even existing backups will be backed up.', 'it-l10n-backupbuddy' )
  888. . ' '
  889. . __('You may encounter stalled or significantly delayed backups.', 'it-l10n-backupbuddy' )
  890. . '<a href="http://ithemes.com/codex/page/BackupBuddy:_Frequent_Support_Issues#Compatibility_Mode" target="_new">'
  891. . ' ' . __('Click for instructions on how to resolve this issue.', 'it-l10n-backupbuddy' )
  892. . '</a>';
  893. } else { // Success.
  894. $success = true;
  895. $message = '';
  896. }
  897. $tests[] = array(
  898. 'test' => 'zip_methods',
  899. 'success' => $success,
  900. 'message' => $message,
  901. );
  902. // Show warning if recent backups reports it is not complete yet. (3min is recent)
  903. if ( isset( pb_backupbuddy::$options['backups'][pb_backupbuddy::$options['last_backup_serial']]['updated_time'] ) && ( time() - pb_backupbuddy::$options['backups'][pb_backupbuddy::$options['last_backup_serial']]['updated_time'] < 180 ) ) { // Been less than 3min since last backup.
  904. if ( !empty( pb_backupbuddy::$options['backups'][pb_backupbuddy::$options['last_backup_serial']]['steps'] ) ) {
  905. $found_unfinished = false;
  906. foreach( pb_backupbuddy::$options['backups'][pb_backupbuddy::$options['last_backup_serial']]['steps'] as $step ) {
  907. if ( $step['finish_time'] == '0' ) { // Found an unfinished step.
  908. $found_unfinished = true;
  909. break;
  910. }
  911. }
  912. if ( $found_unfinished === true ) {
  913. $tests[] = array(
  914. 'test' => 'recent_backup',
  915. 'success' => false,
  916. 'message' => __('A backup was recently started and reports unfinished steps. You should wait unless you are sure the previous backup has completed or failed to avoid placing a heavy load on your server.', 'it-l10n-backupbuddy' ) .
  917. ' Last updated: ' . pb_backupbuddy::$format->date( pb_backupbuddy::$options['backups'][pb_backupbuddy::$options['last_backup_serial']]['updated_time'] ) . '; '.
  918. ' Serial: ' . pb_backupbuddy::$options['last_backup_serial']
  919. ,
  920. );
  921. }
  922. }
  923. }
  924. // Check if any backups are in site root (ie from a recent restore).
  925. $files = glob( ABSPATH . 'backup-*.zip' );
  926. if ( !is_array( $files ) || empty( $files ) ) {
  927. $files = array();
  928. }
  929. foreach( $files as &$file ) {
  930. $file = basename( $file );
  931. }
  932. if ( count( $files ) > 0 ) {
  933. $files_string = implode( ', ', $files );
  934. $tests[] = array(
  935. 'test' => 'root_backups-' . $files_string,
  936. 'success' => false,
  937. 'message' => 'One or more backup files, `' . $files_string . '` was found in the root directory of this site. This may be leftover from a recent restore. You should usually remove backup files from the site root for security.',
  938. );
  939. }
  940. // Warn if any BackupBuddy ZIP files are found in root of directory (ie from an import).
  941. return $tests;
  942. } // End preflight_check().
  943. // returns true on success, error message otherwise.
  944. /* loopback_test()
  945. *
  946. * Connects back to same site via AJAX call to an AJAX slug that has NOT been registered.
  947. * WordPress AJAX returns a -1 (or 0 in newer version?) for these. Also not logged into
  948. * admin when connecting back. Checks to see if body contains -1 / 0. If loopbacks are not
  949. * enabled then will fail connecting or do something else.
  950. *
  951. *
  952. * @param
  953. * @return boolean True on success, string error message otherwise.
  954. */
  955. function loopback_test() {
  956. $loopback_url = admin_url('admin-ajax.php');
  957. pb_backupbuddy::status( 'details', 'Testing loopback connections by connecting back to site at the URL: `' . $loopback_url . '`. It should display simply "0" or "-1" in the body.' );
  958. $response = wp_remote_get(
  959. $loopback_url,
  960. array(
  961. 'method' => 'GET',
  962. 'timeout' => 5, // 5 second delay. A loopback should be very fast.
  963. 'redirection' => 5,
  964. 'httpversion' => '1.0',
  965. 'blocking' => true,
  966. 'headers' => array(),
  967. 'body' => null,
  968. 'cookies' => array()
  969. )
  970. );
  971. if( is_wp_error( $response ) ) { // Loopback failed. Some kind of error.
  972. $error = $response->get_error_message();
  973. pb_backupbuddy::status( 'error', 'Loopback test error: `' . $error . '`.' );
  974. return 'Error: ' . $error;
  975. } else {
  976. if ( ( $response['body'] == '-1' ) || ( $response['body'] == '0' ) ) { // Loopback succeeded.
  977. pb_backupbuddy::status( 'details', 'HTTP Loopback test success. Returned `' . $response['body'] . '`.' );
  978. return true;
  979. } else { // Loopback failed.
  980. $error = 'A loopback seemed to occur but the value `' . $response['body'] . '` was not correct.';
  981. pb_backupbuddy::status( 'error', $error );
  982. return $error;
  983. }
  984. }
  985. }
  986. // Returns array of subdirectories that contain WordPress.
  987. function get_wordpress_locations() {
  988. $wordpress_locations = array();
  989. $files = glob( ABSPATH . '*/' );
  990. if ( !is_array( $files ) || empty( $files ) ) {
  991. $files = array();
  992. }
  993. foreach( $files as $file ) {
  994. if ( file_exists( $file . 'wp-config.php' ) ) {
  995. $wordpress_locations[] = rtrim( '/' . str_replace( ABSPATH, '', $file ), '/\\' );
  996. }
  997. }
  998. // Remove any excluded directories from showing up in this.
  999. $directory_exclusions = $this->get_directory_exclusions();
  1000. $wordpress_locations = array_diff( $wordpress_locations, $directory_exclusions );
  1001. return $wordpress_locations;
  1002. }
  1003. // TODO: coming soon.
  1004. // Run through potential orphaned files, data structures, etc caused by failed backups and clean things up.
  1005. // Also verifies anti-directory browsing files exists, etc.
  1006. function periodic_cleanup( $backup_age_limit = 43200, $die_on_fail = true ) {
  1007. pb_backupbuddy::status( 'message', 'Starting cleanup procedure for BackupBuddy v' . pb_backupbuddy::settings( 'version' ) . '.' );
  1008. if ( !isset( pb_backupbuddy::$options ) ) {
  1009. $this->load();
  1010. }
  1011. // TODO: Check for orphaned .gz files in root from PCLZip.
  1012. // Cleanup backup itegrity portion of array.
  1013. // (status logging info inside function)
  1014. $this->trim_backups_integrity_stats();
  1015. // Cleanup logs in pb_backupbuddy dirctory.
  1016. pb_backupbuddy::status( 'details', 'Cleaning up old logs.' );
  1017. $log_directory = WP_CONTENT_DIR . '/uploads/pb_' . pb_backupbuddy::settings( 'slug' ) . '/';
  1018. $files = glob( $log_directory . '*.txt' );
  1019. if ( is_array( $files ) && !empty( $files ) ) { // For robustness. Without open_basedir the glob() function returns an empty array for no match. With open_basedir in effect the glob() function returns a boolean false for no match.
  1020. foreach( $files as $file ) {
  1021. $file_stats = stat( $file );
  1022. if ( ( time() - $file_stats['mtime'] ) > $backup_age_limit ) { // If older than 12 hours, delete the log.
  1023. @unlink( $file );
  1024. }
  1025. }
  1026. }
  1027. // Cleanup excess backup stats.
  1028. pb_backupbuddy::status( 'details', 'Cleaning up backup stats.' );
  1029. if ( count( pb_backupbuddy::$options['backups'] ) > 3 ) { // Keep a minimum number of backups in array for stats.
  1030. $number_backups = count( pb_backupbuddy::$options['backups'] );
  1031. $kept_loop_count = 0;
  1032. $needs_save = false;
  1033. foreach( pb_backupbuddy::$options['backups'] as $backup_serial => $backup ) {
  1034. if ( ( $number_backups - $kept_loop_count ) > 3 ) {
  1035. if ( isset( $backup['archive_file'] ) && !file_exists( $backup['archive_file'] ) ) {
  1036. unset( pb_backupbuddy::$options['backups'][$backup_serial] );
  1037. $needs_save = true;
  1038. } else {
  1039. $kept_loop_count++;
  1040. }
  1041. }
  1042. }
  1043. if ( $needs_save === true ) {
  1044. //echo 'saved';
  1045. pb_backupbuddy::save();
  1046. }
  1047. }
  1048. // Cleanup any temporary local destinations.
  1049. pb_backupbuddy::status( 'details', 'Cleaning up any temporary local destinations.' );
  1050. foreach( pb_backupbuddy::$options['remote_destinations'] as $destination_id => $destination ) {
  1051. if ( ( $destination['type'] == 'local' ) && ( isset( $destination['temporary'] ) && ( $destination['temporary'] === true ) ) ) { // If local and temporary.
  1052. if ( ( time() - $destination['created'] ) > $backup_age_limit ) { // Older than 12 hours; clear out!
  1053. pb_backupbuddy::status( 'details', 'Cleaned up stale local destination `' . $destination_id . '`.' );
  1054. unset( pb_backupbuddy::$options['remote_destinations'][$destination_id] );
  1055. pb_backupbuddy::save();
  1056. }
  1057. }
  1058. }
  1059. // Cleanup excess remote sending stats.
  1060. pb_backupbuddy::status( 'details', 'Cleaning up remote send stats.' );
  1061. $this->trim_remote_send_stats();
  1062. // Check for orphaned backups in the data structure that havent been updates in 12+ hours & cleanup after them.
  1063. pb_backupbuddy::status( 'details', 'Cleaning up data structure.' );
  1064. foreach( (array)pb_backupbuddy::$options['backups'] as $backup_serial => $backup ) {
  1065. if ( isset( $backup['updated_time'] ) ) {
  1066. if ( ( time() - $backup['updated_time'] ) > $backup_age_limit ) { // If more than 12 hours has passed...
  1067. pb_backupbuddy::status( 'details', 'Cleaned up stale backup `' . $backup_serial . '`.' );
  1068. $this->final_cleanup( $backup_serial );
  1069. }
  1070. }
  1071. }
  1072. // Verify existance of anti-directory browsing files in backup directory.
  1073. pb_backupbuddy::status( 'details', 'Verifying anti-directory browsing security on backup directory.' );
  1074. pb_backupbuddy::anti_directory_browsing( pb_backupbuddy::$options['backup_directory'], $die_on_fail );
  1075. // Verify existance of anti-directory browsing files in status log directory.
  1076. pb_backupbuddy::status( 'details', 'Verifying anti-directory browsing security on status log directory.' );
  1077. $status_directory = WP_CONTENT_DIR . '/uploads/pb_' . pb_backupbuddy::settings( 'slug' ) . '/';
  1078. pb_backupbuddy::anti_directory_browsing( $status_directory, $die_on_fail );
  1079. // Handle high security mode archives directory .htaccess system. If high security backup directory mode: Make sure backup archives are NOT downloadable by default publicly. This is only lifted for ~8 seconds during a backup download for security. Overwrites any existing .htaccess in this location.
  1080. if ( pb_backupbuddy::$options['lock_archives_directory'] == '0' ) { // Normal security mode. Put normal .htaccess.
  1081. pb_backupbuddy::status( 'details', 'Removing .htaccess high security mode for backups directory. Normal mode .htaccess to be added next.' );
  1082. // Remove high security .htaccess.
  1083. if ( file_exists( pb_backupbuddy::$options['backup_directory'] . '.htaccess' ) ) {
  1084. $unlink_status = @unlink( pb_backupbuddy::$options['backup_directory'] . '.htaccess' );
  1085. if ( $unlink_status === false ) {
  1086. pb_backupbuddy::alert( 'Error #844594. Unable to temporarily remove .htaccess security protection on archives directory to allow downloading. Please verify permissions of the BackupBuddy archives directory or manually download via FTP.' );
  1087. }
  1088. }
  1089. // Place normal .htaccess.
  1090. pb_backupbuddy::anti_directory_browsing( pb_backupbuddy::$options['backup_directory'], $die_on_fail );
  1091. } else { // High security mode. Make sure high security .htaccess in place.
  1092. pb_backupbuddy::status( 'details', 'Adding .htaccess high security mode for backups directory.' );
  1093. $htaccess_creation_status = @file_put_contents( pb_backupbuddy::$options['backup_directory'] . '.htaccess', 'deny from all' );
  1094. if ( $htaccess_creation_status === false ) {
  1095. pb_backupbuddy::alert( 'Error #344894545. Security Warning! Unable to create security file (.htaccess) in backups archive directory. This file prevents unauthorized downloading of backups should someone be able to guess the backup location and filenames. This is unlikely but for best security should be in place. Please verify permissions on the backups directory.' );
  1096. }
  1097. }
  1098. // Verify existance of anti-directory browsing files in temporary directory.
  1099. pb_backupbuddy::status( 'details', 'Verifying anti-directory browsing security on temp directory.' );
  1100. pb_backupbuddy::anti_directory_browsing( pb_backupbuddy::$options['temp_directory'], $die_on_fail );
  1101. // Remove any copy of importbuddy.php in root.
  1102. pb_backupbuddy::status( 'details', 'Cleaning up importbuddy.php script in site root if it exists.' );
  1103. if ( file_exists( ABSPATH . 'importbuddy.php' ) ) {
  1104. pb_backupbuddy::status( 'details', 'Unlinked importbuddy.php in root of site.' );
  1105. unlink( ABSPATH . 'importbuddy.php' );
  1106. }
  1107. // Remove any copy of importbuddy directory in root.
  1108. pb_backupbuddy::status( 'details', 'Cleaning up importbuddy directory in site root if it exists.' );
  1109. if ( file_exists( ABSPATH . 'importbuddy/' ) ) {
  1110. pb_backupbuddy::status( 'details', 'Unlinked importbuddy directory recursively in root of site.' );
  1111. pb_backupbuddy::$filesystem->unlink_recursive( ABSPATH . 'importbuddy/' );
  1112. }
  1113. // Remove any old temporary directories in wp-content/uploads/backupbuddy_temp/. Logs any directories it cannot delete.
  1114. pb_backupbuddy::status( 'details', 'Cleaning up any old temporary zip directories in: wp-content/uploads/backupbuddy_temp/' );
  1115. $temp_directory = WP_CONTENT_DIR . '/uploads/backupbuddy_temp/';
  1116. $files = glob( $temp_directory . '*' );
  1117. if ( is_array( $files ) && !empty( $files ) ) { // For robustness. Without open_basedir the glob() function returns an empty array for no match. With open_basedir in effect the glob() function returns a boolean false for no match.
  1118. foreach( $files as $file ) {
  1119. if ( ( strpos( $file, 'index.' ) !== false ) || ( strpos( $file, '.htaccess' ) !== false ) ) { // Index file or htaccess dont get deleted so go to next file.
  1120. continue;
  1121. }
  1122. $file_stats = stat( $file );
  1123. if ( ( time() - $file_stats['mtime'] ) > $backup_age_limit ) { // If older than 12 hours, delete the log.
  1124. if ( @pb_backupbuddy::$filesystem->unlink_recursive( $file ) === false ) {
  1125. pb_backupbuddy::status( 'error', 'Unable to clean up (delete) temporary directory/file: `' . $file . '`. You should manually delete it or check permissions.' );
  1126. }
  1127. }
  1128. }
  1129. }
  1130. // Remove any old temporary zip directories: wp-content/uploads/backupbuddy_backups/temp_zip_XXXX/. Logs any directories it cannot delete.
  1131. pb_backupbuddy::status( 'details', 'Cleaning up any old temporary zip directories in backup directory temp location `' . pb_backupbuddy::$options['backup_directory'] . 'temp_zip_XXXX/`.' );
  1132. // $temp_directory = WP_CONTENT_DIR . '/uploads/backupbuddy_backups/temp_zip_*';
  1133. $temp_directory = pb_backupbuddy::$options['backup_directory'] . 'temp_zip_*';
  1134. $files = glob( $temp_directory . '*' );
  1135. if ( is_array( $files ) && !empty( $files ) ) { // For robustness. Without open_basedir the glob() function returns an empty array for no match. With open_basedir in effect the glob() function returns a boolean false for no match.
  1136. foreach( $files as $file ) {
  1137. if ( ( strpos( $file, 'index.' ) !== false ) || ( strpos( $file, '.htaccess' ) !== false ) ) { // Index file or htaccess dont get deleted so go to next file.
  1138. continue;
  1139. }
  1140. $file_stats = stat( $file );
  1141. if ( ( time() - $file_stats['mtime'] ) > $backup_age_limit ) { // If older than 12 hours, delete the log.
  1142. if ( @pb_backupbuddy::$filesystem->unlink_recursive( $file ) === false ) {
  1143. pb_backupbuddy::status( 'error', 'Unable to clean up (delete) temporary directory/file: `' . $file . '`. You should manually delete it or check permissions.' );
  1144. }
  1145. }
  1146. }
  1147. }
  1148. pb_backupbuddy::status( 'message', 'Finished cleanup procedure.' );
  1149. } // End periodic_cleanup().
  1150. public function final_cleanup( $serial ) {
  1151. if ( !isset( pb_backupbuddy::$options ) ) {
  1152. pb_backupbuddy::load();
  1153. }
  1154. pb_backupbuddy::status( 'details', 'cron_final_cleanup started' );
  1155. // Delete temporary data directory.
  1156. if ( isset( pb_backupbuddy::$options['backups'][$serial]['temp_directory'] ) && file_exists( pb_backupbuddy::$options['backups'][$serial]['temp_directory'] ) ) {
  1157. pb_backupbuddy::$filesystem->unlink_recursive( pb_backupbuddy::$options['backups'][$serial]['temp_directory'] );
  1158. }
  1159. // Delete temporary zip directory.
  1160. if ( isset( pb_backupbuddy::$options['backups'][$serial]['temporary_zip_directory'] ) && file_exists( pb_backupbuddy::$options['backups'][$serial]['temporary_zip_directory'] ) ) {
  1161. pb_backupbuddy::$filesystem->unlink_recursive( pb_backupbuddy::$options['backups'][$serial]['temporary_zip_directory'] );
  1162. }
  1163. // Delete status log text file.
  1164. if ( file_exists( pb_backupbuddy::$options['backup_directory'] . 'temp_status_' . $serial . '.txt' ) ) {
  1165. unlink( pb_backupbuddy::$options['backup_directory'] . 'temp_status_' . $serial. '.txt' );
  1166. }
  1167. } // End final_cleanup().
  1168. /* trim_remote_send_stats()
  1169. *
  1170. * Handles trimming the number of remote sends to the most recent ones.
  1171. *
  1172. * @return null
  1173. */
  1174. public function trim_remote_send_stats() {
  1175. $limit = 5; // Maximum number of remote sends to keep track of.
  1176. // Return if limit not yet met.
  1177. if ( count( pb_backupbuddy::$options['remote_sends'] ) <= $limit ) {
  1178. return;
  1179. }
  1180. // Uses the negative offset of array_slice() to grab the last X number of items from array.
  1181. pb_backupbuddy::$options['remote_sends'] = array_slice( pb_backupbuddy::$options['remote_sends'], ( $limit * -1 ) );
  1182. pb_backupbuddy::save();
  1183. } // End trim_remote_send_stats().
  1184. /* trim_backups_integrity_stats()
  1185. *
  1186. * Handles trimming the number of backup integrity items in the data structure. Trims to all backups left or 10, whichever is more.
  1187. *
  1188. * @param
  1189. * @return
  1190. */
  1191. public function trim_backups_integrity_stats() {
  1192. pb_backupbuddy::status( 'details', 'Trimming backup integrity stats.' );
  1193. $minimum = 10; // Minimum number of backups' integrity to keep track of.
  1194. if ( !isset( pb_backupbuddy::$options['backups'] ) ) { // No integrity checks yet.
  1195. return;
  1196. }
  1197. // Put newest backups first.
  1198. $existing_backups = array_reverse( pb_backupbuddy::$options['backups'] );
  1199. // Remove any backup integrity stats for deleted backups. Will re-add from temp array if we drop under the minimum.
  1200. foreach( $existing_backups as $backup_serial => $existing_backup ) {
  1201. if ( !isset( $existing_backup['archive_file'] ) || ( !file_exists( $existing_backup['archive_file'] ) ) ) {
  1202. unset( pb_backupbuddy::$options['backups'][$backup_serial] ); // File gone so erase from options. Will re-add if we go under our minimum.
  1203. }
  1204. } // End foreach.
  1205. // Need to make sure the database connection is active. Sometimes it goes away during long bouts doing other things -- sigh.
  1206. // This is not essential so use include and not require (suppress any warning)
  1207. pb_backupbuddy::status( 'details', 'Loading DB kicker in case database has gone away.' );
  1208. @include_once( pb_backupbuddy::plugin_path() . '/lib/wpdbutils/wpdbutils.php' );
  1209. if ( class_exists( 'pluginbuddy_wpdbutils' ) ) {
  1210. // This is the database object we want to use
  1211. global $wpdb;
  1212. // Get our helper object and let it use us to output status messages
  1213. $dbhelper = new pluginbuddy_wpdbutils( $wpdb );
  1214. // If we cannot kick the database into life then signal the error and return false which will stop the backup
  1215. // Otherwise all is ok and we can just fall through and let the function return true
  1216. if ( !$dbhelper->kick() ) {
  1217. pb_backupbuddy::status( 'error', __('Database Server has gone away, unable to save remote transfer status.', 'it-l10n-backupbuddy' ) );
  1218. return false;
  1219. } else {
  1220. pb_backupbuddy::status( 'details', 'Database seems to still be connected.' );
  1221. }
  1222. } else {
  1223. // Utils not available so cannot verify database connection status - just notify
  1224. pb_backupbuddy::status( 'details', __('Database Server connection status unverified.', 'it-l10n-backupbuddy' ) );
  1225. }
  1226. // If dropped under the minimum try to add back in some to get enough sample points.
  1227. if ( count( pb_backupbuddy::$options['backups'] ) < $minimum ) {
  1228. foreach( $existing_backups as $backup_serial => $existing_backup ) {
  1229. if ( !isset( pb_backupbuddy::$options['backups'][$backup_serial] ) ) {
  1230. pb_backupbuddy::$options['backups'][$backup_serial] = $existing_backup; // Add item.
  1231. }
  1232. // If hit minimum then stop looping to add.
  1233. if ( count( pb_backupbuddy::$options['backups'] ) >= $minimum ) {
  1234. break;
  1235. }
  1236. }
  1237. // Put array back in normal order.
  1238. pb_backupbuddy::$options['backups'] = array_reverse( pb_backupbuddy::$options['backups'] );
  1239. pb_backupbuddy::save();
  1240. } else { // Still have enough stats. Save.
  1241. pb_backupbuddy::$options['backups'] = array_reverse( pb_backupbuddy::$options['backups'] );
  1242. pb_backupbuddy::save();
  1243. }
  1244. } // End trim_backups_integrity_stats().
  1245. /* get_site_size()
  1246. *
  1247. * Returns an array with the site size and the site size sans exclusions. Saves updates stats in options.
  1248. *
  1249. * @return array Index 0: site size; Index 1: site size sans excluded files/dirs.
  1250. */
  1251. public function get_site_size() {
  1252. $exclusions = pb_backupbuddy_core::get_directory_exclusions();
  1253. $dir_array = array();
  1254. $result = pb_backupbuddy::$filesystem->dir_size_map( ABSPATH, ABSPATH, $exclusions, $dir_array );
  1255. unset( $dir_array ); // Free this large chunk of memory.
  1256. $total_size = pb_backupbuddy::$options['stats']['site_size'] = $result[0];
  1257. $total_size_excluded = pb_backupbuddy::$options['stats']['site_size_excluded'] = $result[1];
  1258. pb_backupbuddy::$options['stats']['site_size_updated'] = time();
  1259. pb_backupbuddy::save();
  1260. return array( $total_size, $total_size_excluded );
  1261. } // End get_site_size().
  1262. /* get_database_size()
  1263. *
  1264. * Return array of database size, database sans exclusions.
  1265. *
  1266. * @return array Index 0: db size, Index 1: db size sans exclusions.
  1267. */
  1268. public function get_database_size() {
  1269. global $wpdb;
  1270. $prefix = $wpdb->prefix;
  1271. $prefix_length = strlen( $wpdb->prefix );
  1272. $additional_includes = explode( "\n", pb_backupbuddy::$options['mysqldump_additional_includes'] );
  1273. array_walk( $additional_includes, create_function('&$val', '$val = trim($val);'));
  1274. $additional_excludes = explode( "\n", pb_backupbuddy::$options['mysqldump_additional_excludes'] );
  1275. array_walk( $additional_excludes, create_function('&$val', '$val = trim($val);'));
  1276. $total_size = 0;
  1277. $total_size_with_exclusions = 0;
  1278. $result = mysql_query("SHOW TABLE STATUS");
  1279. while( $rs = mysql_fetch_array( $result ) ) {
  1280. $excluded = true; // Default.
  1281. // TABLE STATUS.
  1282. $resultb = mysql_query("CHECK TABLE `{$rs['Name']}`");
  1283. while( $rsb = mysql_fetch_array( $resultb ) ) {
  1284. if ( $rsb['Msg_type'] == 'status' ) {
  1285. $status = $rsb['Msg_text'];
  1286. }
  1287. }
  1288. mysql_free_result( $resultb );
  1289. // TABLE SIZE.
  1290. $size = ( $rs['Data_length'] + $rs['Index_length'] );
  1291. $total_size += $size;
  1292. // HANDLE EXCLUSIONS.
  1293. if ( pb_backupbuddy::$options['backup_nonwp_tables'] == 0 ) { // Only matching prefix.
  1294. if ( ( substr( $rs['Name'], 0, $prefix_length ) == $prefix ) OR ( in_array( $rs['Name'], $additional_includes ) ) ) {
  1295. if ( !in_array( $rs['Name'], $additional_excludes ) ) {
  1296. $total_size_with_exclusions += $size;
  1297. $excluded = false;
  1298. }
  1299. }
  1300. } else { // All tables.
  1301. if ( !in_array( $rs['Name'], $additional_excludes ) ) {
  1302. $total_size_with_exclusions += $size;
  1303. $excluded = false;
  1304. }
  1305. }
  1306. }
  1307. pb_backupbuddy::$options['stats']['db_size'] = $total_size;
  1308. pb_backupbuddy::$options['stats']['db_size_excluded'] = $total_size_with_exclusions;
  1309. pb_backupbuddy::$options['stats']['db_size_updated'] = time();
  1310. pb_backupbuddy::save();
  1311. mysql_free_result( $result );
  1312. return array( $total_size, $total_size_with_exclusions );
  1313. } // End get_database_size().
  1314. /* Doesnt work?
  1315. public function error_handler( $error_number, $error_string, $error_file, $error_line ) {
  1316. pb_backupbuddy::status( 'error', "PHP error caught. Error #`{$error_number}`; Description: `{$error_string}`; File: `{$error_file}`; Line: `{$error_line}`." );
  1317. return true;
  1318. }
  1319. */
  1320. public function kick_db() {
  1321. $kick_db = true; // Change true to false for debugging purposes to disable kicker.
  1322. // Need to make sure the database connection is active. Sometimes it goes away during long bouts doing other things -- sigh.
  1323. // This is not essential so use include and not require (suppress any warning)
  1324. if ( $kick_db === true ) {
  1325. pb_backupbuddy::status( 'details', 'kick_db()' );
  1326. pb_backupbuddy::status( 'details', 'Loading DB kicker in case database has gone away.' );
  1327. @include_once( pb_backupbuddy::plugin_path() . '/lib/wpdbutils/wpdbutils.php' );
  1328. if ( class_exists( 'pluginbuddy_wpdbutils' ) ) {
  1329. // This is the database object we want to use
  1330. global $wpdb;
  1331. // Get our helper object and let it use us to output status messages
  1332. $dbhelper = new pluginbuddy_wpdbutils( $wpdb );
  1333. // If we cannot kick the database into life then signal the error and return false which will stop the backup
  1334. // Otherwise all is ok and we can just fall through and let the function return true
  1335. if ( !$dbhelper->kick() ) {
  1336. pb_backupbuddy::status( 'error', __('Database Server has gone away, unable to update remote destination transfer status. This is most often caused by mysql running out of memory or timing out far too early. Please contact your host.', 'it-l10n-backupbuddy' ) );
  1337. } else {
  1338. pb_backupbuddy::status( 'details', 'Database seems to still be connected.' );
  1339. }
  1340. } else {
  1341. // Utils not available so cannot verify database connection status - just notify
  1342. pb_backupbuddy::status( 'details', __('Database Server connection status unverified.', 'it-l10n-backupbuddy' ) );
  1343. }
  1344. }
  1345. } // End kick_db().
  1346. public function verify_directories() {
  1347. // Keep backup directory up to date.
  1348. //if ( pb_backupbuddy::$options['backup_directory'] != ( ABSPATH . 'wp-content/uploads/backupbuddy_backups/' ) ) {
  1349. if ( ( pb_backupbuddy::$options['backup_directory'] == '' ) || ( ! @is_writable( pb_backupbuddy::$options['backup_directory'] ) ) ) {
  1350. $default_backup_dir = ABSPATH . 'wp-content/uploads/backupbuddy_backups/';
  1351. pb_backupbuddy::status( 'details', 'Backup directory invalid. Updating from `' . pb_backupbuddy::$options['backup_directory'] . '` to the default `' . $default_backup_dir . '`.' );
  1352. pb_backupbuddy::$options['backup_directory'] = $default_backup_dir;
  1353. pb_backupbuddy::save();
  1354. }
  1355. // Make backup directory if it does not exist yet.
  1356. //pb_backupbuddy::status( 'details', 'Verifying backup directory `' . pb_backupbuddy::$options['backup_directory'] . '` exists.' );
  1357. if ( !file_exists( pb_backupbuddy::$options['backup_directory'] ) ) {
  1358. pb_backupbuddy::status( 'details', 'Backup directory does not exist. Attempting to create.' );
  1359. if ( pb_backupbuddy::$filesystem->mkdir( pb_backupbuddy::$options['backup_directory'] ) === false ) {
  1360. pb_backupbuddy::status( 'error', sprintf( __('Unable to create backup storage directory (%s)', 'it-l10n-backupbuddy' ) , pb_backupbuddy::$options['backup_directory'] ) );
  1361. pb_backupbuddy::alert( sprintf( __('Unable to create backup storage directory (%s)', 'it-l10n-backupbuddy' ) , pb_backupbuddy::$options['backup_directory'] ), true, '9002' );
  1362. }
  1363. }
  1364. // Keep temp directory up to date.
  1365. if ( pb_backupbuddy::$options['temp_directory'] != ( ABSPATH . 'wp-content/uploads/backupbuddy_temp/' ) ) {
  1366. pb_backupbuddy::status( 'details', 'Temporary directory has changed. Updating from `' . pb_backupbuddy::$options['temp_directory'] . '` to `' . ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . '`.' );
  1367. pb_backupbuddy::$options['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/';
  1368. pb_backupbuddy::save();
  1369. }
  1370. // Make backup directory if it does not exist yet.
  1371. if ( !file_exists( pb_backupbuddy::$options['temp_directory'] ) ) {
  1372. pb_backupbuddy::status( 'details', 'Temporary directory does not exist. Attempting to create.' );
  1373. if ( pb_backupbuddy::$filesystem->mkdir( pb_backupbuddy::$options['temp_directory'] ) === false ) {
  1374. pb_backupbuddy::status( 'error', sprintf( __('Unable to create temporary storage directory (%s)', 'it-l10n-backupbuddy' ) , pb_backupbuddy::$options['temp_directory'] ) );
  1375. pb_backupbuddy::alert( sprintf( __('Unable to create temporary storage directory (%s)', 'it-l10n-backupbuddy' ) , pb_backupbuddy::$options['temp_directory'] ), true, '9002' );
  1376. }
  1377. }
  1378. } // End verify_directories().
  1379. }
  1380. ?>