PageRenderTime 59ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/betaimages/chakalos
PHP | 1577 lines | 951 code | 332 blank | 294 comment | 221 complexity | ae993318070aeeae47ebdb76997949f9 MD5 | raw file
Possible License(s): BSD-3-Clause

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

  1. <?php
  2. /* pb_backupbuddy_backup class
  3. *
  4. * Handles the actual backup procedures.
  5. *
  6. * USED BY:
  7. *
  8. * 1) Full & DB backups
  9. * 2) Multisite backups & exports
  10. *
  11. */
  12. class pb_backupbuddy_backup {
  13. private $_errors = array(); // TODO: No longer used? Remove?
  14. private $_status_logging_started = false; // Marked true once anything has been status logged during this process. Used by status().
  15. // PHP date() timestamp format for the backup archive filename. DATE is default.
  16. const ARCHIVE_NAME_FORMAT_DATE = 'Y_m_d'; // Format when archive_name_format = date.
  17. const ARCHIVE_NAME_FORMAT_DATETIME = 'Y_m_d-h_ia'; // Format when archive_name_format = datetime.
  18. /* __construct()
  19. *
  20. * Default contructor. Initialized core and zipbuddy classes.
  21. *
  22. * @return null
  23. */
  24. function __construct() {
  25. // Load core if it has not been instantiated yet.
  26. if ( !isset( pb_backupbuddy::$classes['core'] ) ) {
  27. require_once( pb_backupbuddy::plugin_path() . '/classes/core.php' );
  28. pb_backupbuddy::$classes['core'] = new pb_backupbuddy_core();
  29. }
  30. // Load zipbuddy if it has not been instantiated yet.
  31. if ( !isset( pb_backupbuddy::$classes['zipbuddy'] ) ) {
  32. require_once( pb_backupbuddy::plugin_path() . '/lib/zipbuddy/zipbuddy.php' );
  33. pb_backupbuddy::$classes['zipbuddy'] = new pluginbuddy_zipbuddy( pb_backupbuddy::$options['backup_directory'] );
  34. }
  35. // Register PHP shutdown function to help catch and log fatal PHP errors during backup.
  36. register_shutdown_function( array( &$this, 'shutdown_function' ) );
  37. } // End __construct().
  38. /* shutdown_function()
  39. *
  40. * Used for catching fatal PHP errors during backup to write to log for debugging.
  41. *
  42. * @return null
  43. */
  44. public function shutdown_function() {
  45. // Get error message.
  46. // Error types: http://php.net/manual/en/errorfunc.constants.php
  47. $e = error_get_last();
  48. if ( $e === NULL ) { // No error of any kind.
  49. return;
  50. } else { // Some type of error.
  51. if ( !is_array( $e ) || ( $e['type'] != E_ERROR ) && ( $e['type'] != E_USER_ERROR ) ) { // Return if not a fatal error.
  52. return;
  53. }
  54. }
  55. // Calculate log directory.
  56. if ( defined( 'PB_STANDALONE' ) && PB_STANDALONE === true ) {
  57. $log_directory = ABSPATH . 'importbuddy/';
  58. } else {
  59. $log_directory = WP_CONTENT_DIR . '/uploads/pb_backupbuddy/';
  60. }
  61. $main_file = $log_directory . 'log-' . pb_backupbuddy::$options['log_serial'] . '.txt';
  62. // Determine if writing to a serial log.
  63. if ( pb_backupbuddy::$_status_serial != '' ) {
  64. $serial = pb_backupbuddy::$_status_serial;
  65. $serial_file = $log_directory . 'status-' . $serial . '_' . pb_backupbuddy::$options['log_serial'] . '.txt';
  66. $write_serial = true;
  67. } else {
  68. $write_serial = false;
  69. }
  70. // Format error message.
  71. $e_string = "---\n" . __( 'Fatal PHP error encountered:', 'it-l10n-backupbuddy' ) . "\n";
  72. foreach( (array)$e as $e_line_title => $e_line ) {
  73. $e_string .= $e_line_title . ' => ' . $e_line . "\n";
  74. }
  75. $e_string .= "---\n";
  76. // Write to log.
  77. @file_put_contents( $main_file, $e_string, FILE_APPEND );
  78. if ( $write_serial === true ) {
  79. @file_put_contents( $serial_file, $e_string, FILE_APPEND );
  80. }
  81. } // End shutdown_function.
  82. /* start_backup_process()
  83. *
  84. * Initializes the entire backup process.
  85. *
  86. * @param string $type Backup type. Valid values: db, full, export.
  87. * @param string $trigger What triggered this backup. Valid values: scheduled, manual.
  88. * @param array $pre_backup Array of functions to prepend to the backup steps array.
  89. * @param array $post_backup Array of functions to append to the backup steps array. Ie. sending to remote destination.
  90. * @param string $schedule_title Title name of schedule. Used for tracking what triggered this in logging. For debugging.
  91. * @param string $serial_override If provided then this serial will be used instead of an auto-generated one.
  92. * @param array $export_plugins For use in export backup type. List of plugins to export.
  93. * @return boolean True on success; false otherwise.
  94. */
  95. function start_backup_process( $type, $trigger = 'manual', $pre_backup = array(), $post_backup = array(), $schedule_title = '', $serial_override = '', $export_plugins = array() ) {
  96. if ( $serial_override != '' ) {
  97. $serial = $serial_override;
  98. } else {
  99. $serial = pb_backupbuddy::random_string( 10 );
  100. }
  101. pb_backupbuddy::set_status_serial( $serial ); // Default logging serial.
  102. global $wp_version;
  103. pb_backupbuddy::status( 'details', 'BackupBuddy v' . pb_backupbuddy::settings( 'version' ) . ' using WordPress v' . $wp_version . ' on ' . PHP_OS . '.' );
  104. //pb_backupbuddy::status( 'details', __('Peak memory usage', 'it-l10n-backupbuddy' ) . ': ' . round( memory_get_peak_usage() / 1048576, 3 ) . ' MB' );
  105. if ( $this->pre_backup( $serial, $type, $trigger, $pre_backup, $post_backup, $schedule_title, $export_plugins ) === false ) {
  106. return false;
  107. }
  108. if ( ( $trigger == 'scheduled' ) && ( pb_backupbuddy::$options['email_notify_scheduled_start'] != '' ) ) {
  109. pb_backupbuddy::status( 'details', __('Sending scheduled backup start email notification if applicable.', 'it-l10n-backupbuddy' ) );
  110. pb_backupbuddy::$classes['core']->mail_notify_scheduled( $serial, 'start', __('Scheduled backup', 'it-l10n-backupbuddy' ) . ' (' . $this->_backup['schedule_title'] . ') has begun.' );
  111. }
  112. if ( ( pb_backupbuddy::$options['backup_mode'] == '2' ) || ( $trigger == 'scheduled' ) ) { // Modern mode with crons.
  113. pb_backupbuddy::status( 'message', 'Running in modern backup mode based on settings. Mode value: `' . pb_backupbuddy::$options['backup_mode'] . '`. Trigger: `' . $trigger . '`.' );
  114. // If using alternate cron on a manually triggered backup then skip running the cron on this pageload to avoid header already sent warnings.
  115. if ( ( $trigger == 'manual' ) && defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON ) {
  116. $this->cron_next_step( false );
  117. } else {
  118. $this->cron_next_step( true );
  119. }
  120. } else { // Classic mode; everything runs in this single PHP page load.
  121. pb_backupbuddy::status( 'message', 'Running in classic backup mode based on settings.' );
  122. $this->process_backup( $this->_backup['serial'], $trigger );
  123. }
  124. return true;
  125. } // End start_backup_process().
  126. /* pre_backup()
  127. *
  128. * Set up the backup data structure containing steps, set up temp directories, etc.
  129. *
  130. * @param string $type Backup type. Valid values: db, full, export.
  131. * @param string $trigger What triggered this backup. Valid values: scheduled, manual.
  132. * @param array $pre_backup Array of functions to prepend to the backup steps array.
  133. * @param array $post_backup Array of functions to append to the backup steps array. Ie. sending to remote destination.
  134. * @param string $schedule_title Title name of schedule. Used for tracking what triggered this in logging. For debugging.
  135. * @param array $export_plugins For use in export backup type. List of plugins to export.
  136. * @return boolean True on success; false otherwise.
  137. */
  138. function pre_backup( $serial, $type, $trigger, $pre_backup = array(), $post_backup = array(), $schedule_title = '', $export_plugins = array() ) {
  139. // Log some status information.
  140. pb_backupbuddy::status( 'details', __( 'Performing pre-backup procedures.', 'it-l10n-backupbuddy' ) );
  141. if ( $type == 'full' ) {
  142. pb_backupbuddy::status( 'message', __( 'Full backup mode.', 'it-l10n-backupbuddy' ) );
  143. } elseif ( $type == 'db' ) {
  144. pb_backupbuddy::status( 'message', __( 'Database only backup mode.', 'it-l10n-backupbuddy' ) );
  145. } elseif ( $type == 'export' ) {
  146. pb_backupbuddy::status( 'message', __( 'Multisite Site Export mode.', 'it-l10n-backupbuddy' ) );
  147. } else {
  148. pb_backupbuddy::status( 'error', __( 'Unknown backup mode.', 'it-l10n-backupbuddy' ) );
  149. }
  150. //pb_backupbuddy::status( 'error', __( 'Error #9020: Testing.', 'it-l10n-backupbuddy' ) );
  151. // Delete all backup archives if this troubleshooting option is enabled.
  152. if ( pb_backupbuddy::$options['delete_archives_pre_backup'] == '1' ) {
  153. pb_backupbuddy::status( 'message', 'Deleting all existing backups prior to backup as configured on the settings page.' );
  154. $file_list = glob( pb_backupbuddy::$options['backup_directory'] . 'backup*.zip' );
  155. if ( is_array( $file_list ) && !empty( $file_list ) ) {
  156. foreach( $file_list as $file ) {
  157. if ( @unlink( $file ) === true ) {
  158. pb_backupbuddy::status( 'details', 'Deleted backup archive `' . basename( $file ) . '` based on settings to delete all backups.' );
  159. } else {
  160. pb_backupbuddy::status( 'details', 'Unable to delete backup archive `' . basename( $file ) . '` based on settings to delete all backups. Verify permissions.' );
  161. }
  162. }
  163. }
  164. }
  165. // Generate unique serial ID.
  166. pb_backupbuddy::status( 'details', 'Backup serial generated: `' . $serial . '`.' );
  167. $this->_backup = &pb_backupbuddy::$options['backups'][$serial]; // Set reference.
  168. // Cleanup internal stats.
  169. pb_backupbuddy::status( 'details', 'Resetting statistics for last backup time and number of edits since last backup.' );
  170. pb_backupbuddy::$options['last_backup'] = time(); // Reset time since last backup.
  171. pb_backupbuddy::$options['edits_since_last'] = 0; // Reset edit stats for notifying user of how many posts/pages edited since last backup happened.
  172. pb_backupbuddy::$options['last_backup_serial'] = $serial;
  173. // Prepare some values for setting up the backup data.
  174. $siteurl_stripped = pb_backupbuddy::$classes['core']->backup_prefix();
  175. if ( pb_backupbuddy::$options['force_compatibility'] == '1' ) {
  176. $force_compatibility = true;
  177. } else {
  178. $force_compatibility = false;
  179. }
  180. // Calculate customizable section of archive filename (date vs date+time).
  181. if ( pb_backupbuddy::$options['archive_name_format'] == 'datetime' ) { // "datetime" = Date + time.
  182. $backupfile_datetime = date( self::ARCHIVE_NAME_FORMAT_DATETIME, pb_backupbuddy::$format->localize_time( time() ) );
  183. } else { // "date" = date only (the default).
  184. $backupfile_datetime = date( self::ARCHIVE_NAME_FORMAT_DATE, pb_backupbuddy::$format->localize_time( time() ) );
  185. }
  186. // Set up the backup data.
  187. $this->_backup = array(
  188. 'serial' => $serial, // Unique identifier.
  189. 'backup_mode' => pb_backupbuddy::$options['backup_mode'], // Tells whether modern or classic mode.
  190. 'type' => $type, // db, full, or export.
  191. 'start_time' => time(), // When backup started. Now.
  192. 'finish_time' => 0,
  193. 'updated_time' => time(), // When backup last updated. Subsequent steps update this.
  194. 'status' => array(), // TODO: what goes in this?
  195. 'archive_size' => 0,
  196. 'schedule_title' => $schedule_title, // Title of the schedule that made this backup happen (if applicable).
  197. 'backup_directory' => pb_backupbuddy::$options['backup_directory'], // Directory backups stored in.
  198. 'archive_file' => pb_backupbuddy::$options['backup_directory'] . 'backup-' . $siteurl_stripped . '-' . $backupfile_datetime . '-' . $type . '-' . $serial . '.zip', // Unique backup ZIP filename.
  199. 'trigger' => $trigger, // How backup was triggered: manual or scheduled.
  200. 'force_compatibility' => $force_compatibility, // Boolean on whether compatibily zip mode was forced or not.
  201. 'steps' => array(), // Backup steps to perform. Set next in this code.
  202. 'integrity' => array(), // Used later for tests and stats post backup.
  203. 'temp_directory' => '', // Temp directory to store SQL and DAT file. Differs for exports. Defined in a moment...
  204. 'backup_root' => '', // Where to start zipping from. Usually root of site. Defined in a moment...
  205. 'export_plugins' => array(), // Plugins to export during MS export of a subsite.
  206. 'additional_table_includes' => array(),
  207. 'additional_table_excludes' => array(),
  208. 'directory_exclusions' => pb_backupbuddy::$classes['core']->get_directory_exclusions(),
  209. 'table_sizes' => array(), // Array of tables to backup AND their sizes.
  210. 'breakout_tables' => array(), // Array of tables that will be broken out to separate steps.
  211. );
  212. // Figure out paths.
  213. if ( $this->_backup['type'] == 'full' ) {
  214. $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/';
  215. $this->_backup['backup_root'] = ABSPATH; // ABSPATH contains trailing slash.
  216. } elseif ( $this->_backup['type'] == 'db' ) {
  217. $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/';
  218. $this->_backup['backup_root'] = $this->_backup['temp_directory'];
  219. } elseif ( $this->_backup['type'] == 'export' ) {
  220. // WordPress unzips into wordpress subdirectory by default so must include that in path.
  221. $this->_backup['temp_directory'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/wordpress/wp-content/uploads/backupbuddy_temp/' . $serial . '/'; // We store temp data for export within the temporary WordPress installation within the temp directory. A bit confusing; sorry about that.
  222. $this->_backup['backup_root'] = ABSPATH . 'wp-content/uploads/backupbuddy_temp/' . $serial . '/wordpress/';
  223. } else {
  224. pb_backupbuddy::status( 'error', __('Backup FAILED. Unknown backup type.', 'it-l10n-backupbuddy' ) );
  225. pb_backupbuddy::status( 'action', 'halt_script' ); // Halt JS on page.
  226. }
  227. // Plugins to export (only for MS exports).
  228. if ( count( $export_plugins ) > 0 ) {
  229. $this->_backup['export_plugins'] = $export_plugins;
  230. }
  231. // Calculate additional database table inclusion/exclusion.
  232. $additional_includes = explode( "\n", pb_backupbuddy::$options['mysqldump_additional_includes'] );
  233. array_walk( $additional_includes, create_function('&$val', '$val = trim($val);'));
  234. $this->_backup['additional_table_includes'] = array_unique( $additional_includes ); // removes duplicates.
  235. $additional_excludes = explode( "\n", pb_backupbuddy::$options['mysqldump_additional_excludes'] );
  236. array_walk( $additional_excludes, create_function('&$val', '$val = trim($val);'));
  237. $this->_backup['additional_table_excludes'] = array_unique( $additional_excludes ); // removes duplicates.
  238. unset( $additional_includes );
  239. unset( $additional_excludes );
  240. /********* Begin setting up steps array. *********/
  241. if ( $type == 'export' ) {
  242. pb_backupbuddy::status( 'details', 'Setting up export-specific steps.' );
  243. $this->_backup['steps'][] = array(
  244. 'function' => 'ms_download_extract_wordpress',
  245. 'args' => array(),
  246. 'start_time' => 0,
  247. 'finish_time' => 0,
  248. 'attempts' => 0,
  249. );
  250. $this->_backup['steps'][] = array(
  251. 'function' => 'ms_create_wp_config',
  252. 'args' => array(),
  253. 'start_time' => 0,
  254. 'finish_time' => 0,
  255. 'attempts' => 0,
  256. );
  257. $this->_backup['steps'][] = array(
  258. 'function' => 'ms_copy_plugins',
  259. 'args' => array(),
  260. 'start_time' => 0,
  261. 'finish_time' => 0,
  262. 'attempts' => 0,
  263. );
  264. $this->_backup['steps'][] = array(
  265. 'function' => 'ms_copy_themes',
  266. 'args' => array(),
  267. 'start_time' => 0,
  268. 'finish_time' => 0,
  269. 'attempts' => 0,
  270. );
  271. $this->_backup['steps'][] = array(
  272. 'function' => 'ms_copy_media',
  273. 'args' => array(),
  274. 'start_time' => 0,
  275. 'finish_time' => 0,
  276. 'attempts' => 0,
  277. );
  278. $this->_backup['steps'][] = array(
  279. 'function' => 'ms_copy_users_table', // Create temp user and usermeta tables.
  280. 'args' => array(),
  281. 'start_time' => 0,
  282. 'finish_time' => 0,
  283. 'attempts' => 0,
  284. );
  285. }
  286. if ( pb_backupbuddy::$options['skip_database_dump'] != '1' ) { // Backup database if not skipping.
  287. global $wpdb;
  288. // Default tables to backup.
  289. if ( pb_backupbuddy::$options['backup_nonwp_tables'] == '1' ) { // Backup all tables.
  290. $base_dump_mode = 'all';
  291. } else { // Only backup matching prefix.
  292. $base_dump_mode = 'prefix';
  293. }
  294. // Calculate tables to dump based on the provided information. $tables will be an array of tables.
  295. $tables = $this->_calculate_tables( $base_dump_mode, $this->_backup['additional_table_includes'], $this->_backup['additional_table_excludes'] );
  296. // Obtain tables sizes. Surround each table name by a single quote and implode with commas for SQL query to get sizes.
  297. $tables_formatted = $tables;
  298. foreach( $tables_formatted as &$table_formatted ) {
  299. $table_formatted = "'{$table_formatted}'";
  300. }
  301. $tables_formatted = implode( ',', $tables_formatted );
  302. $result = mysql_query( "SHOW TABLE STATUS WHERE Name IN({$tables_formatted});" );
  303. while( $rs = mysql_fetch_array( $result ) ) {
  304. $this->_backup['table_sizes'][ $rs['Name'] ] = ( $rs['Data_length'] + $rs['Index_length'] );
  305. }
  306. unset( $tables_formatted );
  307. // Tables we will try to break out into standalone steps if possible.
  308. $breakout_tables_defaults = array(
  309. $wpdb->prefix . 'posts',
  310. $wpdb->prefix . 'postmeta',
  311. );
  312. // Step through tables we want to break out and figure out which ones were indeed set to be backed up and break them out.
  313. if ( pb_backupbuddy::$options['breakout_tables'] == '0' ) { // Breaking out DISABLED.
  314. pb_backupbuddy::status( 'details', 'Breaking out tables DISABLED based on settings.' );
  315. } else { // Breaking out ENABLED.
  316. pb_backupbuddy::status( 'details', 'Breaking out tables ENABLED based on settings. Tables to be broken out into individual steps: `' . implode( ', ', $breakout_tables_defaults ) . '`.' );
  317. foreach( (array)$breakout_tables_defaults as $breakout_tables_default ) {
  318. if ( in_array( $breakout_tables_default, $tables ) ) {
  319. $this->_backup['breakout_tables'][] = $breakout_tables_default;
  320. $tables = array_diff( $tables, array( $breakout_tables_default ) ); // Remove from main table backup list.
  321. }
  322. }
  323. }
  324. unset( $breakout_tables_defaults ); // No longer needed.
  325. $this->_backup['steps'][] = array(
  326. 'function' => 'backup_create_database_dump',
  327. 'args' => array( $tables ),
  328. 'start_time' => 0,
  329. 'finish_time' => 0,
  330. 'attempts' => 0,
  331. );
  332. // Set up backup steps for additional broken out tables.
  333. foreach( $this->_backup['breakout_tables'] as $breakout_table ) {
  334. $this->_backup['steps'][] = array(
  335. 'function' => 'backup_create_database_dump',
  336. 'args' => array( array( $breakout_table ) ),
  337. 'start_time' => 0,
  338. 'finish_time' => 0,
  339. 'attempts' => 0,
  340. );
  341. }
  342. } else {
  343. pb_backupbuddy::status( 'message', __( 'Skipping database dump based on advanced options.', 'it-l10n-backupbuddy' ) );
  344. }
  345. $this->_backup['steps'][] = array(
  346. 'function' => 'backup_zip_files',
  347. 'args' => array(),
  348. 'start_time' => 0,
  349. 'finish_time' => 0,
  350. 'attempts' => 0,
  351. );
  352. if ( $type == 'export' ) {
  353. $this->_backup['steps'][] = array( // Multisite export specific cleanup.
  354. 'function' => 'ms_cleanup', // Removes temp user and usermeta tables.
  355. 'args' => array(),
  356. 'start_time' => 0,
  357. 'finish_time' => 0,
  358. 'attempts' => 0,
  359. );
  360. }
  361. $this->_backup['steps'][] = array(
  362. 'function' => 'post_backup',
  363. 'args' => array(),
  364. 'start_time' => 0,
  365. 'finish_time' => 0,
  366. 'attempts' => 0,
  367. );
  368. // Prepend and append pre backup and post backup steps.
  369. $this->_backup['steps'] = array_merge( $pre_backup, $this->_backup['steps'], $post_backup );
  370. /********* End setting up steps array. *********/
  371. /********* Begin directory creation and security. *********/
  372. pb_backupbuddy::anti_directory_browsing( $this->_backup['backup_directory'] );
  373. // Prepare temporary directory for holding SQL and data file.
  374. if ( !file_exists( $this->_backup['temp_directory'] ) ) {
  375. if ( pb_backupbuddy::$filesystem->mkdir( $this->_backup['temp_directory'] ) === false ) {
  376. pb_backupbuddy::status( 'error', 'Error #9002. Unable to create temporary storage directory (' . $this->_backup['temp_directory'] . ')' );
  377. return false;
  378. }
  379. }
  380. if ( !is_writable( $this->_backup['temp_directory'] ) ) {
  381. pb_backupbuddy::status( 'error', 'Error #9015. Temp data directory is not writable. Check your permissions. (' . $this->_backup['temp_directory'] . ')' );
  382. return false;
  383. }
  384. pb_backupbuddy::anti_directory_browsing( ABSPATH . 'wp-content/uploads/backupbuddy_temp/' );
  385. // Prepare temporary directory for holding ZIP file while it is being generated.
  386. $this->_backup['temporary_zip_directory'] = pb_backupbuddy::$options['backup_directory'] . 'temp_zip_' . $this->_backup['serial'] . '/';
  387. if ( !file_exists( $this->_backup['temporary_zip_directory'] ) ) {
  388. if ( pb_backupbuddy::$filesystem->mkdir( $this->_backup['temporary_zip_directory'] ) === false ) {
  389. pb_backupbuddy::status( 'details', 'Error #9002. Unable to create temporary ZIP storage directory (' . $this->_backup['temporary_zip_directory'] . ')' );
  390. return false;
  391. }
  392. }
  393. if ( !is_writable( $this->_backup['temporary_zip_directory'] ) ) {
  394. pb_backupbuddy::status( 'error', 'Error #9015. Temp data directory is not writable. Check your permissions. (' . $this->_backup['temporary_zip_directory'] . ')' );
  395. return false;
  396. }
  397. /********* End directory creation and security *********/
  398. //$this->echo();
  399. // Schedule cleanup of temporary files and such for XX hours in the future just in case everything goes wrong we dont leave junk too long.
  400. wp_schedule_single_event( ( time() + ( 48 * 60 * 60 ) ), pb_backupbuddy::cron_tag( 'final_cleanup' ), array( $serial ) );
  401. // Generate backup DAT (data) file containing details about the backup.
  402. if ( $this->backup_create_dat_file( $trigger ) !== true ) {
  403. pb_backupbuddy::status( 'details', __('Problem creating DAT file.', 'it-l10n-backupbuddy' ) );
  404. return false;
  405. }
  406. // Generating ImportBuddy file to include in the backup for FULL BACKUPS ONLY currently. Cannot put in DB because it would be in root and be excluded or conflict on extraction.
  407. if ( $type == 'full' ) {
  408. pb_backupbuddy::status( 'details', 'Generating ImportBuddy tool to include in backup archive: `' . $this->_backup['temp_directory'] . 'importbuddy.php`.' );
  409. pb_backupbuddy::$classes['core']->importbuddy( $this->_backup['temp_directory'] . 'importbuddy.php' );
  410. pb_backupbuddy::status( 'details', 'ImportBuddy generation complete.' );
  411. }
  412. // Save all of this.
  413. pb_backupbuddy::save();
  414. pb_backupbuddy::status( 'details', __('Finished pre-backup procedures.', 'it-l10n-backupbuddy' ) );
  415. pb_backupbuddy::status( 'action', 'finish_settings' );
  416. return true;
  417. } // End pre_backup().
  418. /* process_backup()
  419. *
  420. * Process and run the next backup step.
  421. *
  422. * @param string $serial Unique backup identifier.
  423. * @param string $trigger What triggered this processing: manual or scheduled.
  424. * @return boolean True on success, false otherwise.
  425. */
  426. function process_backup( $serial, $trigger = 'manual' ) {
  427. pb_backupbuddy::status( 'details', 'Running process_backup() for serial `' . $serial . '`.' );
  428. // Assign reference to backup data structure for this backup.
  429. $this->_backup = &pb_backupbuddy::$options['backups'][$serial];
  430. $found_next_step = false;
  431. foreach( (array)$this->_backup['steps'] as $step_index => $step ) { // Loop through steps finding first step that has not run.
  432. if ( ( $step['start_time'] != 0 ) && ( $step['finish_time'] == 0 ) ) { // A step has begun but has not finished. This should not happen but the WP cron is funky. Wait a while before continuing.
  433. $this->_backup['steps'][$step_index]['attempts']++; // Increment this as an attempt.
  434. pb_backupbuddy::save();
  435. if ( $step['attempts'] < 6 ) {
  436. $wait_time = 60 * $step['attempts']; // Each attempt adds a minute of wait time.
  437. pb_backupbuddy::status( 'message', 'A scheduled step attempted to run before the previous step completed. Waiting `' . $wait_time . '` seconds before continuing for it to catch up. Attempt number `' . $step['attempts'] . '`.' );
  438. $this->cron_next_step( false, $wait_time );
  439. return false;
  440. } else { // Too many attempts to run this step.
  441. pb_backupbuddy::status( 'error', 'A scheduled step attempted to run before the previous step completed. After several attempts (`' . $step['attempts'] . '`) of failure BackupBuddy has given up. Halting backup.' );
  442. return false;
  443. }
  444. break;
  445. } elseif ( $step['start_time'] == 0 ) { // Step that has not started yet.
  446. $found_next_step = true;
  447. $this->_backup['steps'][$step_index]['start_time'] = time(); // Set this step time to now.
  448. $this->_backup['steps'][$step_index]['attempts']++; // Increment this as an attempt.
  449. pb_backupbuddy::save();
  450. pb_backupbuddy::status( 'details', 'Found next step to run: `' . $step['function'] . '`.' );
  451. break; // Break out of foreach loop to continue.
  452. } else { // Last case: Finished. Skip.
  453. // Do nothing for completed steps.
  454. }
  455. } // End foreach().
  456. if ( $found_next_step === false ) { // No more steps to perform; return.
  457. return false;
  458. }
  459. pb_backupbuddy::save();
  460. pb_backupbuddy::status( 'details', __('Peak memory usage', 'it-l10n-backupbuddy' ) . ': ' . round( memory_get_peak_usage() / 1048576, 3 ) . ' MB' );
  461. /********* Begin Running Step Function **********/
  462. if ( method_exists( $this, $step['function'] ) ) {
  463. $args = '';
  464. foreach( $step['args'] as $arg ) {
  465. if ( is_array( $arg ) ) {
  466. $args .= '{' . implode( ',', $arg ) . '},';
  467. } else {
  468. $args .= implode( ',', $step['args'] ) . ',';
  469. }
  470. }
  471. pb_backupbuddy::status( 'details', 'Starting step function `' . $step['function'] . '` with args `' . $args . '` now (' . time() . ').' );
  472. $response = call_user_func_array( array( &$this, $step['function'] ), $step['args'] );
  473. } else {
  474. pb_backupbuddy::status( 'error', __( 'Error #82783745: Invalid function `' . $step['function'] . '`' ) );
  475. $response = false;
  476. }
  477. /********* End Running Step Function **********/
  478. //unset( $step );
  479. if ( $response === false ) { // Function finished but reported failure.
  480. pb_backupbuddy::status( 'error', 'Failed function `' . pb_backupbuddy::$options['backups'][$serial]['steps'][$step_index]['function'] . '`. Backup terminated.' );
  481. pb_backupbuddy::status( 'details', __('Peak memory usage', 'it-l10n-backupbuddy' ) . ': ' . round( memory_get_peak_usage() / 1048576, 3 ) . ' MB' );
  482. pb_backupbuddy::status( 'action', 'halt_script' ); // Halt JS on page.
  483. if ( pb_backupbuddy::$options['log_level'] == '3' ) {
  484. $debugging = "\n\n\n\n\n\nDebugging information sent due to error logging set to high debugging mode: \n\n" . pb_backupbuddy::random_string( 10 ) . base64_encode( print_r( debug_backtrace(), true ) ) . "\n\n";
  485. } else {
  486. $debugging = '';
  487. }
  488. pb_backupbuddy::$classes['core']->mail_error( 'One or more backup steps reported a failure. Backup failure running function `' . pb_backupbuddy::$options['backups'][$serial]['steps'][$step_index]['function'] . '` with the arguments `' . implode( ',', pb_backupbuddy::$options['backups'][$serial]['steps'][$step_index]['args'] ) . '` with backup serial `' . $serial . '`. Please run a manual backup of the same type to verify backups are working properly.' . $debugging );
  489. return false;
  490. } else { // Function finished successfully.
  491. pb_backupbuddy::$options['backups'][$serial]['steps'][$step_index]['finish_time'] = time();
  492. pb_backupbuddy::$options['backups'][$serial]['updated_time'] = time();
  493. pb_backupbuddy::save();
  494. pb_backupbuddy::status( 'details', sprintf( __('Finished function `%s`.', 'it-l10n-backupbuddy' ), pb_backupbuddy::$options['backups'][$serial]['steps'][$step_index]['function'] ) );
  495. pb_backupbuddy::status( 'details', __('Peak memory usage', 'it-l10n-backupbuddy' ) . ': ' . round( memory_get_peak_usage() / 1048576, 3 ) . ' MB' );
  496. $found_another_step = false;
  497. foreach( pb_backupbuddy::$options['backups'][$serial]['steps'] as $next_step ) { // Loop through each step and see if any have not started yet.
  498. if ( $next_step['start_time'] == 0 ) { // Another unstarted step exists. Schedule it.
  499. $found_another_step = true;
  500. if ( ( pb_backupbuddy::$options['backup_mode'] == '2' ) || ( $trigger == 'scheduled' ) ) {
  501. $this->cron_next_step();
  502. } else { // classic mode
  503. $this->process_backup( pb_backupbuddy::$options['backups'][$serial]['serial'], $trigger );
  504. }
  505. break;
  506. }
  507. } // End foreach().
  508. if ( $found_another_step == false ) {
  509. pb_backupbuddy::status( 'details', __( 'No more backup steps remain. Finishing...', 'it-l10n-backupbuddy' ) );
  510. pb_backupbuddy::$options['backups'][$serial]['finish_time'] = time();
  511. pb_backupbuddy::save();
  512. } else {
  513. pb_backupbuddy::status( 'details', 'Completed step function `' . $step['function'] . '` now (' . time() . ').' );
  514. pb_backupbuddy::status( 'details', 'The next should run in a moment. If it does not please check for plugin conflicts and that the next step is scheduled in the cron on the Server Information page.' );
  515. }
  516. return true;
  517. }
  518. } // End process_backup().
  519. /* cron_next_step()
  520. *
  521. * Schedule the next step into the cron. Defaults to scheduling to happen _NOW_. Automatically opens a loopback to trigger cron in another process by default.
  522. *
  523. * @param boolean $spawn_cron Whether or not to to spawn a loopback to run the cron. If using an offset this most likely should be false. Default: true
  524. * @param int $future_offset Seconds in the future for this process to run. Most likely set $spawn_cron false if using an offset. Default: 0
  525. * @return null
  526. */
  527. function cron_next_step( $spawn_cron = true, $future_offset = 0 ) {
  528. pb_backupbuddy::status( 'details', 'Scheduling Cron for `' . $this->_backup['serial'] . '`.' );
  529. // Need to make sure the database connection is active. Sometimes it goes away during long bouts doing other things -- sigh.
  530. // This is not essential so use include and not require (suppress any warning)
  531. pb_backupbuddy::status( 'details', 'Loading DB kicker in case database has gone away.' );
  532. @include_once( pb_backupbuddy::plugin_path() . '/lib/wpdbutils/wpdbutils.php' );
  533. if ( class_exists( 'pluginbuddy_wpdbutils' ) ) {
  534. // This is the database object we want to use
  535. global $wpdb;
  536. // Get our helper object and let it use us to output status messages
  537. $dbhelper = new pluginbuddy_wpdbutils( $wpdb );
  538. // If we cannot kick the database into life then signal the error and return false which will stop the backup
  539. // Otherwise all is ok and we can just fall through and let the function return true
  540. if ( !$dbhelper->kick() ) {
  541. pb_backupbuddy::status( 'error', __('Database Server has gone away, unable to schedule next backup step. The backup cannot continue. This is most often caused by mysql running out of memory or timing out far too early. Please contact your host.', 'it-l10n-backupbuddy' ) );
  542. pb_backupbuddy::status( 'action', 'halt_script' ); // Halt JS on page.
  543. return false;
  544. } else {
  545. pb_backupbuddy::status( 'details', 'Database seems to still be connected.' );
  546. }
  547. } else {
  548. // Utils not available so cannot verify database connection status - just notify
  549. pb_backupbuddy::status( 'details', __('Database Server connection status unverified.', 'it-l10n-backupbuddy' ) );
  550. }
  551. $cron_time = ( time() + $future_offset );
  552. $cron_tag = pb_backupbuddy::cron_tag( 'process_backup' );
  553. $cron_args = array( $this->_backup['serial'] );
  554. pb_backupbuddy::status( 'details', 'Scheduling next step to run at `' . $cron_time . '` with cron tag `' . $cron_tag . '` and serial arguments `' . implode( ',', $cron_args ) . '`. If the backup stalls at this point check the Server Information page cron section to see if a step with these values is listed to determine if the problem is with scheduling the next step or the next step is scheduled but not running.' );
  555. $schedule_result = wp_schedule_single_event( $cron_time, $cron_tag, $cron_args );
  556. if ( $schedule_result === false ) {
  557. pb_backupbuddy::status( 'error', 'Unable to schedule next cron step. Verify that another plugin is not preventing / conflicting.' );
  558. }
  559. if ( $spawn_cron === true ) {
  560. spawn_cron( time() + 150 ); // Adds > 60 seconds to get around once per minute cron running limit.
  561. }
  562. update_option( '_transient_doing_cron', 0 ); // Prevent cron-blocking for next item.
  563. pb_backupbuddy::status( 'details', 'Next step scheduled in cron.' );
  564. return;
  565. } // End cron_next_step().
  566. /* backup_create_dat_file()
  567. *
  568. * Generates backupbuddy_dat.php within the temporary directory containing the
  569. * random serial in its name. This file contains a serialized array that has been
  570. * XOR encrypted for security. The XOR key is backupbuddy_SERIAL where SERIAL
  571. * is the randomized set of characters in the ZIP filename. This file contains
  572. * various information about the source site.
  573. *
  574. * @param string $trigger What triggered this backup. Valid values: scheduled, manual.
  575. * @return boolean true on success making dat file; else false
  576. */
  577. function backup_create_dat_file( $trigger ) {
  578. pb_backupbuddy::status( 'details', __( 'Creating DAT (data) file snapshotting site & backup information.', 'it-l10n-backupbuddy' ) );
  579. global $wpdb, $current_blog;
  580. $is_multisite = $is_multisite_export = false; //$from_multisite is from a site within a network
  581. $upload_url_rewrite = $upload_url = '';
  582. if ( ( is_multisite() && ( $trigger == 'scheduled' ) ) || (is_multisite() && is_network_admin() ) ) { // MS Network Export IF ( in a network and triggered by a schedule ) OR ( in a network and logged in as network admin)
  583. $is_multisite = true;
  584. } elseif ( is_multisite() ) { // MS Export (individual site)
  585. $is_multisite_export = true;
  586. $uploads = wp_upload_dir();
  587. $upload_url_rewrite = site_url( str_replace( ABSPATH, '', $uploads[ 'basedir' ] ) ); // URL we rewrite uploads to. REAL direct url.
  588. $upload_url = $uploads[ 'baseurl' ]; // Pretty virtual path to uploads directory.
  589. }
  590. // Handle wp-config.php file in a parent directory.
  591. if ( $this->_backup['type'] == 'full' ) {
  592. $wp_config_parent = false;
  593. if ( file_exists( ABSPATH . 'wp-config.php' ) ) { // wp-config in normal place.
  594. pb_backupbuddy::status( 'details', 'wp-config.php found in normal location.' );
  595. } else { // wp-config not in normal place.
  596. pb_backupbuddy::status( 'message', 'wp-config.php not found in normal location; checking parent directory.' );
  597. if ( file_exists( dirname( ABSPATH ) . '/wp-config.php' ) ) { // Config in parent.
  598. $wp_config_parent = true;
  599. pb_backupbuddy::status( 'message', 'wp-config.php found in parent directory. Copying wp-config.php to temporary location for backing up.' );
  600. $this->_backup['wp-config_in_parent'] = true;
  601. copy( dirname( ABSPATH ) . '/wp-config.php', $this->_backup['temp_directory'] . 'wp-config.php' );
  602. } else {
  603. pb_backupbuddy::status( 'error', 'wp-config.php not found in normal location NOR parent directory. This will result in an incomplete backup which will be marked as bad.' );
  604. }
  605. }
  606. } else {
  607. $wp_config_parent = false;
  608. }
  609. $dat_content = array(
  610. // Backup Info.
  611. 'backupbuddy_version' => pb_backupbuddy::settings( 'version' ),
  612. 'backup_time' => $this->_backup['start_time'],
  613. 'backup_type' => $this->_backup['type'],
  614. 'serial' => $this->_backup['serial'],
  615. 'trigger' => $trigger, // What triggered this backup. Valid values: scheduled, manual.
  616. 'wp-config_in_parent' => $wp_config_parent, // Whether or not the wp-config.php file is in one parent directory up. If in parent directory it will be copied into the temp serial directory along with the .sql and DAT file. On restore we will NOT place in a parent directory due to potential permission issues, etc. It will be moved into the normal location. Value set to true later in this function if applicable.
  617. // WordPress Info.
  618. 'abspath' => ABSPATH,
  619. 'siteurl' => site_url(),
  620. 'homeurl' => home_url(),
  621. 'blogname' => get_option( 'blogname' ),
  622. 'blogdescription' => get_option( 'blogdescription' ),
  623. // Database Info.
  624. 'db_prefix' => $wpdb->prefix,
  625. 'db_name' => DB_NAME,
  626. 'db_user' => DB_USER,
  627. 'db_server' => DB_HOST,
  628. 'db_password' => DB_PASSWORD,
  629. 'db_exclusions' => implode( ',', explode( "\n", pb_backupbuddy::$options['mysqldump_additional_excludes'] ) ),
  630. 'breakout_tables' => $this->_backup['breakout_tables'], // Tables broken out into individual backup steps.
  631. 'tables_sizes' => $this->_backup['table_sizes'], // Tables backed up and their sizes.
  632. // Multisite Info.
  633. 'is_multisite' => $is_multisite, // Full Network backup?
  634. 'is_multisite_export' => $is_multisite_export, // Subsite backup (export)?
  635. 'domain' => is_object( $current_blog ) ? $current_blog->domain : '', // Ex: bob.com
  636. 'path' => is_object( $current_blog ) ? $current_blog->path : '', // Ex: /wordpress/
  637. 'upload_url' => $upload_url, // Pretty URL.
  638. 'upload_url_rewrite' => $upload_url_rewrite, // Real existing URL that the pretty URL will be rewritten to.
  639. // ImportBuddy Options.
  640. // 'import_display_previous_values' => pb_backupbuddy::$options['import_display_previous_values'], // Whether or not to display the previous values from the source on import. Useful if customer does not want to blatantly display previous values to anyone restoring the backup.
  641. ); // End setting $dat_content.
  642. // If currently using SSL or forcing admin SSL then we will check the hardcoded defined URL to make sure it matches.
  643. if ( is_ssl() OR ( defined( 'FORCE_SSL_ADMIN' ) && FORCE_SSL_ADMIN == true ) ) {
  644. $dat_content['siteurl'] = get_option('siteurl');
  645. pb_backupbuddy::status( 'details', __('Compensating for SSL in siteurl.', 'it-l10n-backupbuddy' ) );
  646. }
  647. // Serialize .dat file array.
  648. $dat_content = base64_encode( serialize( $dat_content ) );
  649. // Write data to the dat file.
  650. $dat_file = $this->_backup['temp_directory'] . 'backupbuddy_dat.php';
  651. if ( false === ( $file_handle = fopen( $dat_file, 'w' ) ) ) {
  652. pb_backupbuddy::status( 'details', sprintf( __('Error #9017: Temp data file is not creatable/writable. Check your permissions. (%s)', 'it-l10n-backupbuddy' ), $dat_file ) );
  653. pb_backupbuddy::status( 'error', 'Temp data file is not creatable/writable. Check your permissions. (' . $dat_file . ')', '9017' );
  654. return false;
  655. }
  656. fwrite( $file_handle, "<?php die('Access Denied.'); ?>\n" . $dat_content );
  657. fclose( $file_handle );
  658. pb_backupbuddy::status( 'details', __('Finished creating DAT (data) file.', 'it-l10n-backupbuddy' ) );
  659. return true;
  660. } // End backup_create_dat_file().
  661. /* backup_create_database_dump()
  662. *
  663. * Prepares configuration and passes to the mysqlbuddy library to handle backing up the database.
  664. * Automatically handles falling back to compatibility modes.
  665. *
  666. * @return boolean True on success; false otherwise.
  667. */
  668. function backup_create_database_dump( $tables ) {
  669. pb_backupbuddy::status( 'action', 'start_database' );
  670. pb_backupbuddy::status( 'message', __('Starting database backup process.', 'it-l10n-backupbuddy' ) );
  671. if ( pb_backupbuddy::$options['force_mysqldump_compatibility'] == '1' ) {
  672. pb_backupbuddy::status( 'message', 'Forcing database dump compatibility mode based on settings. Use PHP-based dump mode only.' );
  673. $force_methods = array( 'php' ); // Force php mode only.
  674. } else {
  675. pb_backupbuddy::status( 'message', 'Using auto-detected database dump method(s) based on settings.' );
  676. $force_methods = array(); // Default, auto-detect.
  677. }
  678. // Load mysqlbuddy and perform dump.
  679. require_once( pb_backupbuddy::plugin_path() . '/lib/mysqlbuddy/mysqlbuddy.php' );
  680. global $wpdb;
  681. pb_backupbuddy::$classes['mysqlbuddy'] = new pb_backupbuddy_mysqlbuddy( DB_HOST, DB_NAME, DB_USER, DB_PASSWORD, $wpdb->prefix, $force_methods ); // $database_host, $database_name, $database_user, $database_pass, $old_prefix, $force_method = array()
  682. $result = pb_backupbuddy::$classes['mysqlbuddy']->dump( $this->_backup['temp_directory'], $tables );
  683. // Check and make sure mysql server is still around. If it's missing at this point we may not be able to trust that it succeeded properly.
  684. global $wpdb;
  685. if ( @mysql_ping( $wpdb->dbh ) === false ) { // No longer connected to database if false.
  686. pb_backupbuddy::status( 'error', __( 'ERROR #9027b: The mySQL server went away at some point during the database dump step. This is almost always caused by mySQL running out of memory or the mysql server timing out far too early. Contact your host. The database dump integrity can no longer be guaranteed so the backup has been halted.' ) );
  687. if ( $result === true ) {
  688. pb_backupbuddy::status( 'details', 'The database dump reported SUCCESS prior to this problem.' );
  689. } else {
  690. pb_backupbuddy::status( 'details', 'The database dump reported FAILURE prior to this problem.' );
  691. }
  692. pb_backupbuddy::status( 'action', 'halt_script' ); // Halt JS on page.
  693. return false;
  694. }
  695. return $result;
  696. } // End backup_create_database_dump().
  697. /* backup_zip_files()
  698. *
  699. * Create ZIP file containing everything.
  700. *
  701. * @return boolean True on success; false otherwise.
  702. */
  703. function backup_zip_files() {
  704. pb_backupbuddy::status( 'action', 'start_files' );
  705. pb_backupbuddy::status( 'details', 'Backup root: `' . $this->_backup['backup_root'] . '`.' );
  706. // Use compression?
  707. if ( pb_backupbuddy::$options['compression'] == '1' ) {
  708. $compression = true;
  709. } else {
  710. $compression = false;
  711. }
  712. // Create zip file!
  713. $zip_response = pb_backupbuddy::$classes['zipbuddy']->add_directory_to_zip(
  714. $this->_backup['archive_file'], // string Zip file to create.
  715. $this->_backup['backup_root'], // string Directory to zip up (root).
  716. $compression, // bool Compression?
  717. $this->_backup['directory_exclusions'], // array Files/directories to exclude. (array of strings).
  718. $this->_backup['temporary_zip_directory'], // string Temp directory location to store zip file in.
  719. $this->_backup['force_compatibility'] // bool Whether or not to force compatibilty mode.
  720. );
  721. // Zip results.
  722. if ( $zip_response === true ) {
  723. pb_backupbuddy::status( 'message', __('Backup ZIP file successfully created.', 'it-l10n-backupbuddy' ) );
  724. if ( chmod( $this->_backup['archive_file'], 0644) ) {
  725. pb_backupbuddy::status( 'details', __('Chmod of ZIP file to 0644 succeeded.', 'it-l10n-backupbuddy' ) );
  726. } else {
  727. pb_backupbuddy::status( 'details', __('Chmod of ZIP file to 0644 failed.', 'it-l10n-backupbuddy' ) );
  728. }
  729. } else {
  730. pb_backupbuddy::status( 'error', __('Error #3382: Backup FAILED. Unable to successfully generate ZIP archive.', 'it-l10n-backupbuddy' ) );
  731. pb_backupbuddy::status( 'error', __('Error #3382 help: http://ithemes.com/codex/page/BackupBuddy:_Error_Codes#3382', 'it-l10n-backupbuddy' ) );
  732. pb_backupbuddy::status( 'action', 'halt_script' ); // Halt JS on page.
  733. return false;
  734. }
  735. // Need to make sure the database connection is active. Sometimes it goes away during long bouts doing other things -- sigh.
  736. // This is not essential so use include and not require (suppress any warning)
  737. pb_backupbuddy::status( 'details', 'Loading DB kicker in case database has gone away.' );
  738. @include_once( pb_backupbuddy::plugin_path() . '/lib/wpdbutils/wpdbutils.php' );
  739. if ( class_exists( 'pluginbuddy_wpdbutils' ) ) {
  740. // This is the database object we want to use
  741. global $wpdb;
  742. // Get our helper object and let it use us to output status messages
  743. $dbhelper = new pluginbuddy_wpdbutils( $wpdb );
  744. // If we cannot kick the database into life then signal the error and return false which will stop the backup
  745. // Otherwise all is ok and we can just fall through and let the function return true
  746. if ( !$dbhelper->kick() ) {
  747. pb_backupbuddy::status( 'error', __('Backup FAILED. Backup file produced but Database Server has gone away, unable to schedule next backup step', 'it-l10n-backupbuddy' ) );
  748. return false;
  749. } else {
  750. pb_backupbuddy::status( 'details', 'Database seems to still be connected.' );
  751. }
  752. } else {
  753. // Utils not available so cannot verify database connection status - just notify
  754. pb_backupbuddy::status( 'details', __('Database Server connection status unverified.', 'it-l10n-backupbuddy' ) );
  755. }
  756. return true;
  757. } // End backup_zip_files().
  758. /* trim_old_archives()
  759. *
  760. * Get rid of excess archives based on user-defined parameters.
  761. *
  762. * @param
  763. * @return
  764. */
  765. function trim_old_archives() {
  766. pb_backupbuddy::status( 'details', __('Trimming old archives (if needed).', 'it-l10n-backupbuddy' ) );
  767. $summed_size = 0;
  768. $file_list = glob( pb_backupbuddy::$options['backup_directory'] . 'backup*.zip' );
  769. if ( is_array( $file_list ) && !empty( $file_list ) ) {
  770. foreach( (array) $file_list as $file ) {
  771. $file_stats = stat( $file );
  772. $modified_time = $file_stats['ctime'];
  773. $filename = str_replace( pb_backupbuddy::$options['backup_directory'], '', $file ); // Just the file name.
  774. $files[$modified_time] = array(
  775. 'filename' => $filename,
  776. 'size' => $file_stats['size'],
  777. 'modified' => $modified_time,
  778. );
  779. $summed_size += ( $file_stats['size'] / 1048576 ); // MB
  780. }
  781. }
  782. unset( $file_list );
  783. if ( empty( $files ) ) { // return if no archives (nothing else to do).
  784. pb_backupbuddy::status( 'details', __( 'No old archive trimming needed.', 'it-l10n-backupbuddy' ) );
  785. return true;
  786. } else {
  787. krsort( $files );
  788. }
  789. $trim_count = 0;
  790. // Limit by number of archives if set. Deletes oldest archives over this limit.
  791. if ( ( pb_backupbuddy::$options['archive_limit'] > 0 ) && ( count( $files ) ) > pb_backupbuddy::$options['archive_limit'] ) {
  792. // Need to trim.
  793. $i = 0;
  794. foreach( $files as $file ) {
  795. $i++;
  796. if ( $i > pb_backupbuddy::$options['archive_limit'] ) {
  797. pb_backupbuddy::status( 'details', sprintf( __('Deleting old archive `%s` due as it causes archives to exceed total number allowed.', 'it-l10n-backupbuddy' ), $file['filename'] ) );
  798. unlink( pb_backupbuddy::$options['backup_directory'] . $file['filename'] );
  799. $trim_count++;
  800. }
  801. }
  802. }
  803. // Limit by size of archives, oldest first if set.
  804. $files = array_reverse( $files, true ); // Reversed so we delete oldest files first as long as size limit still is surpassed; true = preserve keys.
  805. if ( ( pb_backupbuddy::$options['archive_limit_size'] > 0 ) && ( $summed_size > pb_backupbuddy::$options['archive_limit_size'] ) ) {
  806. // Need to trim.
  807. foreach( $files as $file ) {
  808. if ( $summed_size > pb_backupbuddy::$options['archive_limit_size'] ) {
  809. $summed_size = $summed_size - ( $file['size'] / 1048576 );
  810. pb_backupbuddy::status( 'details', sprintf( __('Deleting old archive `%s` due as it causes archives to exceed total size allowed.', 'it-l10n-backupbuddy' ), $file['filename'] ) );
  811. if ( $file['filename'] != basename( $this->_backup['archive_file'] ) ) { // Delete excess archives as long as it is not the just-made backup.
  812. unlink( pb_backupbuddy::$options['backup_directory'] . $file['filename'] );
  813. $trim_count++;
  814. } else {
  815. $message = __( 'ERROR #9028: Based on your backup archive limits (size limit) the backup that was just created would be deleted. Skipped deleting this backup. Please update your archive limits.' );
  816. pb_backupbuddy::status( 'message', $message );
  817. pb_backupbuddy::$classes['core']->mail_error( $message );
  818. }
  819. }
  820. }
  821. }
  822. pb_backupbuddy::status( 'details', 'Trimmed ' . $trim_count . ' old archives based on settings archive limits.' );
  823. return true;
  824. } // End trim_old_archives().
  825. /* post_backup()
  826. *
  827. * Post-backup procedured. Clean up, send notifications, etc.
  828. *
  829. * @return null
  830. */
  831. function post_backup() {
  832. pb_backupbuddy::status( 'message', __('Cleaning up after backup.', 'it-l10n-backupbuddy' ) );
  833. // Delete temporary data directory.
  834. if ( file_exists( $this->_backup['temp_directory'] ) ) {
  835. pb_backupbuddy::status( 'details', __('Removing temp data directory.', 'it-l10n-backupbuddy' ) );
  836. pb_backupbuddy::$filesystem->unlink_recursive( $this->_backup['temp_directory'] );
  837. }
  838. // Delete temporary ZIP directory.
  839. if ( file_exists( pb_backupbuddy::$options['backup_directory'] . 'temp_zip_' . $this->_backup['serial'] . '/' ) ) {
  840. pb_backupbuddy::status( 'details', __('Removing temp zip directory.', 'it-l10n-backupbuddy' ) );
  841. pb_backupbuddy::$filesystem->unlink_recursive( pb_backupbuddy::$options['backup_directory'] . 'temp_zip_' . $this->_backup['serial'] . '/' );
  842. }
  843. $this->trim_old_archives(); // Clean up any old excess archives pushing us over defined limits in settings.
  844. $message = 'completed successfully in ' . pb_backupbuddy::$format->time_duration( time() - $this->_backup['start_time'] ) . ".\n";
  845. //$message .= "File: " . basename( $this->_backup['archive_file'] ) . "\n";
  846. //$message .= "Download: " . pb_backupbuddy::ajax_url( 'download_archive' ) . '&backupbuddy_backup=' . basename( $this->_backup['archive_file'] ) . "\n";
  847. $this->_backup['archive_size'] = filesize( $this->_backup['archive_file'] );
  848. pb_backupbuddy::status( 'details', __('Final ZIP file size', 'it-l10n-backupbuddy' ) . ': ' . pb_backupbuddy::$format->fil

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