PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/backupbuddy/lib/mysqlbuddy/mysqlbuddy.php

https://bitbucket.org/summitds/bloomsburgpa.org
PHP | 868 lines | 539 code | 155 blank | 174 comment | 82 complexity | 73a255b06f205c55ff47f9417fd5261d MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, BSD-3-Clause, GPL-3.0, LGPL-2.1
  1. <?php
  2. /* pb_backupbuddy_mysqlbuddy class
  3. *
  4. * @since 3.0.0
  5. *
  6. * Helps backup and restore database tables.
  7. * Dumps a mysql database (all tables, tables with a certain prefix, or none) with additional inclusions/exclusions of tables possible.
  8. * Automatically determines available dump methods (unless method is forced). Runs methods in order of preference. Falls back automatically
  9. * to any `lesser` methods if any fail.
  10. *
  11. * Requirements:
  12. *
  13. * Expects mysql to already be set up and connected.
  14. *
  15. * General process order:
  16. *
  17. * Construction: __construct() -> [available_zip_methods()]
  18. * Dump: dump() -> _calculate_tables() -> [_mysql and/or _php]
  19. *
  20. Method process:
  21. * _mysql method (FAST):
  22. * Builds the command line -> runs command via exec() -> checks exit code -> verifies .sql file was created; falls to next method if exit code is bad or .sql file is missing.
  23. * _php method (SLOW; compatibility mode; only mode pre-3.0):
  24. * Iterates through all tables issuing SQL commands to server to get create statements and all database content. Very brute force method.
  25. *
  26. * @author Dustin Bolton < http://dustinbolton.com >
  27. */
  28. class pb_backupbuddy_mysqlbuddy {
  29. const COMMAND_LINE_LENGTH_CHECK_THRESHOLD = 250; // If command line is longer than this then we will try to determine max command line length.
  30. /********** Properties **********/
  31. private $_version = '0.0.1'; // Internal version number for this library.
  32. private $_database_host = ''; // Database host/server. @see __construct().
  33. private $_database_socket = ''; // If using sockets, points to socket file. Left blank if sockets not in use. @see __construct().
  34. private $_database_name = ''; // Database name. @see __construct().
  35. private $_database_user = ''; // Database username. @see __construct().
  36. private $_database_pass = ''; // Database password. @see __construct().
  37. private $_database_prefix = ''; // Database table prefix to backup when in prefix mode. @see __construct().
  38. private $_base_dump_mode = ''; // Determines base tables to include in backup. Ex: none, all, or by prefix. @see __construct().
  39. private $_additional_includes = array(); // Additional tables to backup in addition to those determined by base mode.
  40. private $_additional_excludes = array(); // Tables to exclude from ( $_additional_includes + those determined by base mode ).
  41. private $_methods = array(); // Available mechanisms for dumping in order of preference.
  42. private $_mysql_directories = array(); // Populated by _calculate_mysql_directory().
  43. private $_default_mysql_directories = array( '/usr/bin/', '/usr/bin/mysql/', '/usr/local/bin/' ); // If mysql tells us where its installed we prepend to this. Beginning and trailing slashes.
  44. private $_mysql_directory = ''; // Tested working mysql directory to use for actual dump.
  45. private $_commandbuddy;
  46. /********** Methods **********/
  47. /* __construct()
  48. *
  49. * Default constructor.
  50. *
  51. * @param string $database_host Host / server of database to pull from. May be in the format: `localhost` for normal; `localhost:/path/to/mysql.sock` for sockets. If sockets then parased and internal class variables set appropriately.
  52. * @param string $database_name Name of database to pull from.
  53. * @param string $database_user User of database to pull from.
  54. * @param string $database_pass Pass of database to pull from.
  55. * @param string $database_prefix Prefix of tables in database to pull from / insert into (only used if base mode is `prefix`).
  56. * @param array $force_methods Optional parameter to override automatic method detection. Skips test and runs first method first. Falls back to other methods if any failure. Possible methods: commandline, php
  57. * @return
  58. */
  59. public function __construct( $database_host, $database_name, $database_user, $database_pass, $database_prefix, $force_methods = array() ) {
  60. // Handles command line execution.
  61. require_once( pb_backupbuddy::plugin_path() . '/lib/commandbuddy/commandbuddy.php' );
  62. $this->_commandbuddy = new pb_backupbuddy_commandbuddy();
  63. // Check for use of sockets in host. Handle if using sockets.
  64. //$database_host = 'localhost:/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock';
  65. if ( strpos( $database_host, ':' ) === false ) { // Normal host.
  66. pb_backupbuddy::status( 'details', 'Database host for dumping: `' . $database_host . '`' );
  67. $this->_database_host = $database_host;
  68. } else { // Non-normal host specification.
  69. $host_split = explode( ':', $database_host );
  70. if ( !is_numeric( $host_split[1] ) ) { // String so assume a socket.
  71. pb_backupbuddy::status( 'details', 'Database host (socket) for dumping. Host: `' . $host_split[0] . '`; Socket: `' . $host_split[1] . '`.' );
  72. $this->_database_host = $host_split[0];
  73. $this->_database_socket = $host_split[1];
  74. } else { // Numeric, treat as port and leave as one piece.
  75. $this->_database_host = $database_host;
  76. }
  77. }
  78. unset( $host_split );
  79. pb_backupbuddy::status( 'details', 'Loading mysqldump library.' );
  80. pb_backupbuddy::status( 'details', 'Mysql server default directories: `' . implode( ',', $this->_default_mysql_directories ) . '`' );
  81. $this->_database_name = $database_name;
  82. $this->_database_user = $database_user;
  83. $this->_database_pass = $database_pass;
  84. $this->_database_prefix = $database_prefix;
  85. if ( is_array( $force_methods ) ) {
  86. pb_backupbuddy::status( 'details', 'mysqlbuddy: Force method sound of `' . count( $force_methods ) . '` passed.' );
  87. } else {
  88. pb_backupbuddy::status( 'details', 'mysqlbuddy: Force method not an array.' );
  89. }
  90. // Set mechanism for dumping / restoring.
  91. if ( count( $force_methods ) > 0 ) { // Mechanism forced. Overriding automatic check.
  92. pb_backupbuddy::status( 'message', 'mysqlbuddy: Settings overriding automatic detection of available database dump methods. Using forced override methods: `' . implode( ',', $force_methods ) . '`.' );
  93. $this->_methods = $force_methods;
  94. } else { // No method defined; auto-detect the best.
  95. pb_backupbuddy::status( 'message', 'mysqlbuddy: Method not forced. About to detect directory and available methods.' );
  96. // Try to determine mysql location / possible locations.
  97. $this->_mysql_directories = $this->_calculate_mysql_dir(); // Don't need to check this in forced mode.
  98. $this->_methods = $this->available_dump_methods(); // Run after _calculate_mysql_dir().
  99. }
  100. pb_backupbuddy::status( 'message', 'mysqlbuddy: Detected database dump methods: `' . implode( ',', $this->_methods ) . '`.' );
  101. } // End __construct().
  102. /* available_dump_methods()
  103. *
  104. * function description
  105. *
  106. * @param
  107. * @return string Possible returns: mysqldump, php
  108. */
  109. public function available_dump_methods() {
  110. pb_backupbuddy::status( 'details', 'mysqldump test: Testing available mysql database dump methods.' );
  111. if ( function_exists( 'exec' ) ) { // Exec is available so test mysqldump from here.
  112. pb_backupbuddy::status( 'details', 'mysqldump test: exec() function exists. Testing running mysqldump via exec().' );
  113. /********** Begin preparing command **********/
  114. // Handle Windows wanting .exe.
  115. if ( stristr( PHP_OS, 'WIN' ) && !stristr( PHP_OS, 'DARWIN' ) ) { // Running Windows. (not darwin)
  116. $command = 'msqldump.exe';
  117. } else {
  118. $command = 'mysqldump';
  119. }
  120. $command .= " --version";
  121. // Redirect STDERR to STDOUT.
  122. $command .= ' 2>&1';
  123. /********** End preparing command **********/
  124. // Loop through all possible directories to run command through.
  125. foreach( $this->_mysql_directories as $mysql_directory ) { // Try each possible directory. mysql directory included trailing slash.
  126. // Run command.
  127. pb_backupbuddy::status( 'details', 'mysqldump test running next.' );
  128. list( $exec_output, $exec_exit_code ) = $this->_commandbuddy->execute( $mysql_directory . $command );
  129. if ( stristr( implode( ' ', $exec_output ), 'Ver' ) !== false ) { // String Ver appeared in response (expected response to mysqldump --version
  130. pb_backupbuddy::status( 'details', 'mysqldump test: Command appears to be accessible and returns expected response.' );
  131. $this->_mysql_directory = $mysql_directory; // Set to use this directory for the real dump.
  132. return array( 'commandline', 'php' ); // mysqldump best, php next.
  133. }
  134. }
  135. } else { // No exec() so must fall back to PHP method only.
  136. pb_backupbuddy::status( 'details', 'mysqldump test: exec() unavailable so skipping command line mysqldump check.' );
  137. pb_backupbuddy::status( 'message', 'mysqldump test: Falling back to database compatibility mode (PHPdump emulation). This is slower.' );
  138. return array( 'php' );
  139. }
  140. return array( 'php' );
  141. } // End available_dump_method().
  142. /* _calculate_mysql_dir()
  143. *
  144. * Tries to determine the path to where mysql is installed. Needed for running by command line. Prepends found location to list of possible default mysql directories.
  145. *
  146. * @return array Array of directories in preferred order.
  147. */
  148. private function _calculate_mysql_dir() {
  149. pb_backupbuddy::status( 'details', 'mysqlbuddy: Attempting to calculate exact mysql directory.' );
  150. $failed = true;
  151. $mysql_directories = $this->_default_mysql_directories;
  152. $result = mysql_query( "SHOW VARIABLES LIKE 'basedir'" );
  153. if ( $result !== false ) {
  154. $row = mysql_fetch_row( $result );
  155. if ( $row !== false ) {
  156. $basedir = rtrim( $row[1], '/\\' ); // Trim trailing slashes.
  157. $mysqldir = $basedir . '/bin/';
  158. array_unshift( $mysql_directories, $mysqldir ); // Prepends the just found directory to the beginning of the list.
  159. pb_backupbuddy::status( 'details', 'mysqlbuddy: Mysql reported its directory. Reported: `' . $row[1] . '`; Adding binary location to beginning of mysql directory list: `' . $mysqldir . '`' );
  160. $failed = false;
  161. }
  162. mysql_free_result( $result ); // Free memory.
  163. }
  164. if ( $failed === true ) {
  165. pb_backupbuddy::status( 'details', 'mysqlbuddy: Mysql would not report its directory.' );
  166. }
  167. return $mysql_directories;
  168. } // End _calculate_mysql_dir().
  169. /* dump()
  170. *
  171. * function description
  172. *
  173. * @see _mysqldump().
  174. * @see _phpdump().
  175. *
  176. * @param string $output_directory Directory to output to. May also be used as a temporary file location. Trailing slash auto-added if missing.
  177. * @param array $tables Array of tables to dump.
  178. * REMOVED: @param string $base_dump_mode Determines which database tables to dump by default. $additional_[includes/excludes] modified. Modes: all, none, or prefix.
  179. * REMOVED: @param array $additional_includes Array of additional table(s) to INCLUDE in dump. Added in addition to those found by the $base_dump_mode
  180. * REMOVED: @param array $additional_excludes Array of additional table(s) to EXCLUDE from dump. Removed from those found by the $base_dump_mode + $additional_includes.
  181. * @return
  182. */
  183. public function dump( $output_directory, $tables = array() ) { //, $base_dump_mode, $additional_includes = array(), $additional_excludes = array() ) {
  184. $return = false;
  185. $output_directory = rtrim( $output_directory, '/' ) . '/'; // Make sure we have trailing slash.
  186. pb_backupbuddy::status( 'action', 'start_database' );
  187. pb_backupbuddy::status( 'message', 'Starting database dump procedure.' );
  188. pb_backupbuddy::status( 'details', "mysqlbuddy: Output directory: `{$output_directory}`." );
  189. if ( count( $tables ) == 1 ) {
  190. pb_backupbuddy::status( 'details', 'Dumping single table `' . $tables[0] . '`.' );
  191. } else {
  192. pb_backupbuddy::status( 'details', 'Table dump count: `' . count( $tables ) . '`.' );
  193. }
  194. if ( file_exists( $output_directory . 'db_1.sql' ) ) {
  195. pb_backupbuddy::status( 'details', 'Database SQL file exists. It will be appended to.' );
  196. }
  197. // Attempt each method in order.
  198. pb_backupbuddy::status( 'details', 'Preparing to dump using available method(s) by priority. Methods: `' . implode( ',', $this->_methods ) . '`' );
  199. foreach( $this->_methods as $method ) {
  200. if ( method_exists( $this, "_dump_{$method}" ) ) {
  201. pb_backupbuddy::status( 'details', 'mysqlbuddy: Attempting dump method `' . $method . '`.' );
  202. $result = call_user_func( array( $this, "_dump_{$method}" ), $output_directory, $tables );
  203. if ( $result === true ) { // Dump completed succesfully with this method.
  204. pb_backupbuddy::status( 'details', 'mysqlbuddy: Dump method `' . $method . '` completed successfully.' );
  205. $return = true;
  206. break;
  207. } elseif ( $result === false ) { // Dump failed this method. Will try compatibility fallback to next mode if able.
  208. // Do nothing. Will try next mode next loop.
  209. pb_backupbuddy::status( 'details', 'mysqlbuddy: Dump method `' . $method . '` failed. Trying another compatibility mode next if able.' );
  210. } else { // Something else returned; need to resume? TODO: this is for future use for resuming dump.
  211. pb_backupbuddy::status( 'details', 'mysqlbuddy: Unexepected response: `' . implode( ',', $result ) . '`' );
  212. }
  213. }
  214. }
  215. //pb_backupbuddy::status( 'status', 'database_end' );
  216. pb_backupbuddy::status( 'action', 'finish_database' );
  217. if ( $return === true ) { // Success.
  218. pb_backupbuddy::status( 'message', 'Database dump procedure succeeded.' );
  219. return true;
  220. } else { // Overall failure.
  221. pb_backupbuddy::status( 'error', 'Database dump procedure failed.' );
  222. return false;
  223. }
  224. } // End dump().
  225. /* _dump_commandline()
  226. *
  227. * function description
  228. *
  229. * @param string $output_directory Directory to output to. May also be used as a temporary file location. Trailing slash required. dump() auto-adds trailing slash before passing.
  230. * @param array $tables Array of tables to dump.
  231. * REMOVED: @param string $base_dump_mode Base dump mode. Used to tell whether or not to dump entire database or piecemeal tables. Try to keep command line short.
  232. * REMOVED: @param array $additional_excludes Additional excludes. Used to tell whether or not to dump entire database or piecemeal tables. Try to keep command line short.
  233. * @return
  234. */
  235. private function _dump_commandline( $output_directory, $tables ) { //, $base_dump_mode, $additional_excludes ) {
  236. $output_file = $output_directory . 'db_1.sql';
  237. pb_backupbuddy::status( 'details', 'mysqlbuddy: Preparing to run command line mysqldump via exec().' );
  238. $exclude_command = '';
  239. /*
  240. if ( ( $base_dump_mode == 'all' ) && ( count( $additional_excludes ) == 0 ) ) { // Dumping ALL tables in the database so do not specify tables in command line.
  241. // Do nothing. Just dump full database.
  242. pb_backupbuddy::status( 'details', 'mysqlbuddy: Dumping entire database with no exclusions.' );
  243. } elseif ( ( $base_dump_mode == 'all' ) && ( count( $additional_excludes ) > 0 ) ) { // Dumping all tables by default BUT also excluding certain ones.
  244. pb_backupbuddy::status( 'details', 'mysqlbuddy: Dumping entire database with additional exclusions.' );
  245. // Handle additional exclusions.
  246. $additional_excludes = array_filter( $additional_excludes ); // ignore any phantom excludes.
  247. foreach( $additional_excludes as $additional_exclude ) {
  248. $exclude_command .= " --ignore-table={$this->_database_name}.{$additional_exclude}";
  249. }
  250. } else { // Only dumping certain
  251. pb_backupbuddy::status( 'details', 'mysqlbuddy: Dumping specific tables.' );
  252. $tables_string = implode( ' ', $tables ); // Specific tables listed to dump.
  253. }
  254. */
  255. $tables_string = implode( ' ', $tables ); // Specific tables listed to dump.
  256. /********** Begin preparing command **********/
  257. // Handle Windows wanting .exe.
  258. if ( stristr( PHP_OS, 'WIN' ) && !stristr( PHP_OS, 'DARWIN' ) ) { // Running Windows. (not darwin)
  259. $command = $this->_mysql_directory . 'msqldump.exe';
  260. } else {
  261. $command = $this->_mysql_directory . 'mysqldump';
  262. }
  263. // Handle possible sockets.
  264. if ( $this->_database_socket != '' ) {
  265. $command .= " --socket={$this->_database_socket}";
  266. pb_backupbuddy::status( 'details', 'mysqlbuddy: Using sockets in command.' );
  267. }
  268. // TODO WINDOWS NOTE: information in the MySQL documentation about mysqldump needing to use --result-file= on Windows to avoid some issue with line endings.
  269. /*
  270. Notes:
  271. --skip-opt Skips some default options. MUST add back in create-options else autoincrement will be lost! See http://dev.mysql.com/doc/refman/5.5/en/mysqldump.html#option_mysqldump_opt
  272. --quick
  273. --skip-comments Dont bother with extra comments.
  274. --create-options Required to add in auto increment option.
  275. --disable-keys Prevent re-indexing the database after each and every insert until the entire table is inserted. Prevents timeouts when a db table has fulltext keys especially.
  276. */
  277. $command .= " --host={$this->_database_host} --user={$this->_database_user} --password={$this->_database_pass} --skip-opt --quick --disable-keys --skip-comments --create-options {$exclude_command} {$this->_database_name} {$tables_string} >> {$output_file}";
  278. /********** End preparing command **********/
  279. /********** Begin command line length check **********/
  280. // Simple check command line length. If it appears long then do advanced check via command line to see what actual limit is. Falls back if too long to execute our process in one go.
  281. // TODO: In the future handle fallback better by possibly breaking the command up if possible rather than strict fallback to PHP dumping.
  282. $command_length = strlen( $command );
  283. pb_backupbuddy::status( 'details', 'mysqlbuddy: Command length: `' . $command_length . '`.' );
  284. if ( $command_length > self::COMMAND_LINE_LENGTH_CHECK_THRESHOLD ) { // Arbitrary length. Seems standard max lengths are > 200000 on Linux. ~8600 on Windows?
  285. pb_backupbuddy::status( 'details', 'mysqlbuddy: Command line length of `' . $command_length . '` (bytes) is large enough ( >' . self::COMMAND_LINE_LENGTH_CHECK_THRESHOLD . ' ) to verify compatibility. Checking maximum allowed command line length for this sytem.' );
  286. list( $exec_output, $exec_exit_code ) = $this->_commandbuddy->execute( 'echo $(( $(getconf ARG_MAX) - $(env | wc -c) ))' ); // Value will be a number. This is the maximum byte size of the command line.
  287. pb_backupbuddy::status( 'details', 'mysqlbuddy: Command output: `' . implode( ',', $exec_output ) . '`; Exit code: `' . $exec_exit_code . '`; Exit code description: `' . pb_backupbuddy::$filesystem->exit_code_lookup( $exec_exit_code ) . '`' );
  288. if ( is_array( $exec_output ) && is_numeric( $exec_output[0] ) ) {
  289. pb_backupbuddy::status( 'details', 'mysqlbuddy: Detected maximum command line length for this system: `' . $exec_output[0] . '`.' );
  290. if ( $command_length > ( $exec_output[0] - 100 ) ) { // Check if we exceed maximum length. Subtract 100 to make room for path definition.
  291. pb_backupbuddy::status( 'details', 'mysqlbuddy: This system\'s maximum command line length of `' . $exec_output[0] . '` is shorter than command length of `' . $command_length . '`. Falling back into compatibility mode to insure database dump integrity.' );
  292. } else {
  293. pb_backupbuddy::status( 'details', 'mysqlbuddy: This system\'s maximum command line length of `' . $exec_output[0] . '` is longer than command length of `' . $command_length . '`. Continuing.' );
  294. }
  295. } else {
  296. pb_backupbuddy::status( 'details', 'mysqlbuddy: Unable to determine maximum command line length. Falling back into compatibility mode to insure database dump integrity.' );
  297. return false; // Fall back to compatibilty mode just in case.
  298. }
  299. } else {
  300. pb_backupbuddy::status( 'details', 'mysqlbuddy: Command line length length check skipped since it is less than check threshold `' . self::COMMAND_LINE_LENGTH_CHECK_THRESHOLD . '`.' );
  301. }
  302. /********** End command line length check **********/
  303. // Run command.
  304. pb_backupbuddy::status( 'details', 'mysqlbuddy: Running dump via commandline next.' );
  305. list( $exec_output, $exec_exit_code ) = $this->_commandbuddy->execute( $command );
  306. // If mysql went away while we were busy with command line try to re-establish.
  307. global $wpdb;
  308. if ( @mysql_ping( $wpdb->dbh ) !== true ) { // No longer connected to database.
  309. pb_backupbuddy::status( 'error', 'mysqlbuddy: Error #43849374. Database went away from PHP while running from command line. The PHP <--> mysql connection likely timed out while we were doing other things.' );
  310. // Clean up connection.
  311. @mysql_close( $wpdb->dbh );
  312. $wpdb->ready = false;
  313. // Attempt to reconnect.
  314. $wpdb->db_connect();
  315. // Check if reconnect worked.
  316. if ( ( NULL == $wpdb->dbh ) || ( !mysql_ping( $wpdb->dbh ) ) ) { // Reconnect failed if we have a null resource or ping fails
  317. pb_backupbuddy::status( 'error', __('Database Server reconnection failed.', 'it-l10n-backupbuddy' ) );
  318. } else {
  319. pb_backupbuddy::status( 'details', __( 'Database Server reconnection successful.', 'it-l10n-backupbuddy' ) );
  320. $result = true;
  321. }
  322. }
  323. // Check the result of the
  324. if ( $exec_exit_code == '0' ) {
  325. pb_backupbuddy::status( 'details', 'mysqlbuddy: Command appears to succeeded and returned proper response.' );
  326. if ( file_exists( $output_file ) ) { // SQL file found. SUCCESS!
  327. pb_backupbuddy::status( 'message', 'mysqlbuddy: Database dump SQL file exists.' );
  328. // Display final SQL file size.
  329. $sql_filesize = pb_backupbuddy::$format->file_size( filesize( $output_file ) );
  330. pb_backupbuddy::status( 'details', 'Final SQL database dump file size of `' . basename( $output_file ) . '`: ' . $sql_filesize . '.' );
  331. return true;
  332. } else { // SQL file MISSING. FAILURE!
  333. pb_backupbuddy::status( 'error', 'mysqlbuddy: Though command reported success database dump SQL file is missing: `' . $output_file . '`.' );
  334. return false;
  335. }
  336. } else {
  337. pb_backupbuddy::status( 'details', 'mysqlbuddy: Warning #9030. Command did not exit normally. This is normal is your server does not support command line mysql functionality. Falling back to database dump compatibility modes.' );
  338. return false;
  339. }
  340. // Should never get to here.
  341. pb_backupbuddy::status( 'error', 'mysqlbuddy: Uncaught exception #453890.' );
  342. return false;
  343. } // End _dump_commandline().
  344. /* _phpdump()
  345. *
  346. * PHP-based dumping of SQL data. Compatibility mode. Was only mode pre-3.0.
  347. *
  348. * @param string $output_directory Directory to output to. May also be used as a temporary file location. Trailing slash required. dump() auto-adds trailing slash before passing.
  349. * @param array $tables Array of tables to dump.
  350. * REMOVED: @param string $base_dump_mode Base dump mode. NOT USED. Consistent with other dump mode.
  351. * REMOVED: @param array $additional_excludes Additional excludes. NOT USED. Consistent with other dump mode.
  352. * @return
  353. */
  354. private function _dump_php( $output_directory, $tables ) { //, $base_dump_mode, $additional_excludes ) {
  355. $output_file = $output_directory . 'db_1.sql';
  356. pb_backupbuddy::status( 'details', 'mysqlbuddy: Preparing to run PHP mysqldump compatibility mode.' );
  357. if ( false === ( $file_handle = fopen( $output_file, 'a' ) ) ) {
  358. pb_backupbuddy::status( 'error', 'Error #9018: Database file is not creatable/writable. Check your permissions for file `' . $output_file . '` in directory `' . $output_directory . '`.' );
  359. return false;
  360. }
  361. global $wpdb;
  362. if ( !is_object( $wpdb ) ) {
  363. pb_backupbuddy::status( 'error', 'WordPress database object $wpdb did not exist. This should not happen.' );
  364. error_log( 'WordPress database object $wpdb did not exist. This should not happen. BackupBuddy Error #8945587973.' );
  365. return false;
  366. }
  367. // Connect if not connected for importbuddy.
  368. if ( !mysql_ping( $wpdb->dbh ) ) {
  369. mysql_connect( $this->_database_host, $this->_database_user, $this->_database_pass );
  370. mysql_select_db( $this->_database_name );
  371. }
  372. $_count = 0;
  373. $insert_sql = '';
  374. global $wpdb; // Used later for checking that we are still connected to DB.
  375. // Iterate through all the tables to backup.
  376. // TODO: Future ability to break up DB exporting to multiple page loads if needed. Really still need this now that we have command line dump?
  377. foreach( $tables as $table_key => $table ) {
  378. $create_table = mysql_query("SHOW CREATE TABLE `{$table}`");
  379. if ( $create_table === false ) {
  380. pb_backupbuddy::status( 'error', 'Unable to access and dump database table `' . $table . '`. Table may not exist. Skipping backup of this table.' );
  381. //pb_backupbuddy::$classes['core']->mail_error( 'Error #4537384: Unable to access and dump database table `' . $table . '`. Table may not exist. Skipping backup of this table.' );
  382. continue; // Skip this iteration as accessing this table failed.
  383. }
  384. // Table creation text.
  385. $create_table_array = mysql_fetch_array( $create_table );
  386. mysql_free_result( $create_table ); // Free memory.
  387. $insert_sql .= str_replace( "\n", '', $create_table_array[1] ) . ";\n"; // Remove internal linebreaks; only put one at end.
  388. unset( $create_table_array );
  389. // Disable keys for this table.
  390. $insert_sql .= "/*!40000 ALTER TABLE `{$table}` DISABLE KEYS */;\n";
  391. // Row creation text for all rows within this table.
  392. $table_query = mysql_query("SELECT * FROM `$table`") or pb_backupbuddy::status( 'error', 'Error #9001: Unable to read database table `' . $table . '`. Your backup will not include data from this table (you may ignore this warning if you do not need this specific data). This is due to the following error: ' . mysql_error() );
  393. if ( $table_query === false ) {
  394. pb_backupbuddy::status( 'error', 'ERROR #85449745. Unable to retrieve data from table `' . $table . '`. This table may be corrupt (try repairing the database) or too large to hold in memory (increase mysql and/or PHP memory). Check your PHP error log for further errors which may provide further information. Not continuing database dump to insure backup integrity.' );
  395. return false;
  396. }
  397. $num_fields = mysql_num_fields($table_query);
  398. while ( $fetch_row = mysql_fetch_array( $table_query ) ) {
  399. $insert_sql .= "INSERT INTO `$table` VALUES(";
  400. for ( $n=1; $n<=$num_fields; $n++ ) {
  401. $m = $n - 1;
  402. if ( $fetch_row[$m] === NULL ) {
  403. $insert_sql .= "NULL, ";
  404. } else {
  405. $insert_sql .= "'" . mysql_real_escape_string( $fetch_row[$m] ) . "', ";
  406. }
  407. }
  408. $insert_sql = substr( $insert_sql, 0, -2 );
  409. $insert_sql .= ");\n";
  410. fwrite( $file_handle, $insert_sql );
  411. $insert_sql = '';
  412. // Help keep HTTP alive.
  413. $_count++;
  414. if ($_count >= 400) {
  415. echo ' ';
  416. flush();
  417. $_count = 0;
  418. }
  419. } // End foreach $tables.
  420. // Re-enable keys for this table.
  421. $insert_sql .= "/*!40000 ALTER TABLE `{$table}` ENABLE KEYS */;\n";
  422. // testing: mysql_close( $wpdb->dbh );
  423. // Verify database is still connected and working properly. Sometimes mysql runs out of memory and dies in the above foreach.
  424. // No point in reconnecting as we can NOT trust that our dump was succesful anymore (it most likely was not).
  425. if ( @mysql_ping( $wpdb->dbh ) ) { // Still connected to database.
  426. mysql_free_result( $table_query ); // Free memory.
  427. } else { // Database not connected.
  428. pb_backupbuddy::status( 'error', __( 'ERROR #9026: The mySQL server went away unexpectedly during database dump. This is almost always caused by mySQL running out of memory. The backup integrity can no longer be guaranteed so the backup has been halted.' ) . ' ' . __( 'Last table dumped before database server went away: ' ) . '`' . $table . '`.' );
  429. return false;
  430. }
  431. // Help keep HTTP alive.
  432. echo ' ';
  433. pb_backupbuddy::status( 'details', 'Dumped database table `' . $table . '`.' );
  434. flush();
  435. //unset( $tables[$table_key] );
  436. }
  437. fclose( $file_handle );
  438. unset( $file_handle );
  439. pb_backupbuddy::status( 'details', __('Finished PHP based SQL dump method.', 'it-l10n-backupbuddy' ) );
  440. return true;
  441. } // End _phpdump().
  442. /* get_methods()
  443. *
  444. * Get an array of methods. Note: If force overriding methods then detected methods will not be able to display.
  445. *
  446. * @return array Array of methods.
  447. */
  448. public function get_methods() {
  449. return $this->_methods;
  450. }
  451. /* import()
  452. *
  453. * Import SQL contents of a .sql file into the database. Only modification is to table prefix if needed. Prefixes (new and old) provided in constructor.
  454. * Automatically handles fallback based on best available methods.
  455. *
  456. * @param string $sql_file Full absolute path to .sql file to import from.
  457. * @param string $old_prefix Old database prefix. New prefix provided in constructor.
  458. * @param int $query_start Query number (aka line number) to resume import at.
  459. * @param boolean $ignore_existing Whether or not to allow import if tables exist already. Default: false.
  460. * @return mixed true on success (boolean)
  461. * false on failure (boolean)
  462. * integer (int) on needing a resumse (integer is resume number for next page loads $query_start)
  463. */
  464. public function import( $sql_file, $old_prefix, $query_start = 0, $ignore_existing = false ) {
  465. $return = false;
  466. // Require a new table prefix.
  467. if ( $this->_database_prefix == '' ) {
  468. pb_backupbuddy::status( 'error', 'ERROR 9008: A database prefix is required for importing.' );
  469. }
  470. if ( $query_start > 0 ) {
  471. pb_backupbuddy::status( 'message', 'Continuing to restore database dump starting at query ' . $query_start . '.' );
  472. } else {
  473. pb_backupbuddy::status( 'message', 'Restoring database dump. This may take a moment...' );
  474. }
  475. // Check whether or not tables already exist that might collide.
  476. if ( $ignore_existing === false ) {
  477. if ( $query_start == 0 ) { // Check number of tables already existing with this prefix. Skips this check on substeps of DB import.
  478. $result = mysql_query( "SHOW TABLES LIKE '" . mysql_real_escape_string( str_replace( '_', '\_', $this->_database_prefix ) ) . "%'" );
  479. if ( mysql_num_rows( $result ) > 0 ) {
  480. pb_backupbuddy::status( 'error', 'Error #9014: Database import halted to prevent overwriting existing WordPress data.', 'The database already contains a WordPress installation with this prefix (' . mysql_num_rows( $result ) . ' tables). Restore has been stopped to prevent overwriting existing data. *** Please go back and enter a new database name and/or prefix OR select the option to wipe the database prior to import from the advanced settings on the first import step. ***' );
  481. return false;
  482. }
  483. unset( $result );
  484. }
  485. }
  486. pb_backupbuddy::status( 'message', 'Starting database import procedure.' );
  487. pb_backupbuddy::status( 'details', 'mysqlbuddy: Maximum execution time for this run: ' . pb_backupbuddy::$options['max_execution_time'] . ' seconds.' );
  488. pb_backupbuddy::status( 'details', 'mysqlbuddy: Old prefix: `' . $old_prefix . '`; New prefix: `' . $this->_database_prefix . '`.' );
  489. pb_backupbuddy::status( 'details', "mysqlbuddy: Importing SQL file: `{$sql_file}`. Old prefix: `{$old_prefix}`. Query start: `{$query_start}`." );
  490. flush();
  491. // Attempt each method in order.
  492. pb_backupbuddy::status( 'details', 'Preparing to import using available method(s) by priority. Basing import methods off dump methods: `' . implode( ',', $this->_methods ) . '`' );
  493. foreach( $this->_methods as $method ) {
  494. if ( method_exists( $this, "_import_{$method}" ) ) {
  495. pb_backupbuddy::status( 'details', 'mysqlbuddy: Attempting import method `' . $method . '`.' );
  496. $result = call_user_func( array( $this, "_import_{$method}" ), $sql_file, $old_prefix, $query_start, $ignore_existing );
  497. if ( $result === true ) { // Dump completed succesfully with this method.
  498. pb_backupbuddy::status( 'details', 'mysqlbuddy: Import method `' . $method . '` completed successfully.' );
  499. $return = true;
  500. break;
  501. } elseif ( $result === false ) { // Dump failed this method. Will try compatibility fallback to next mode if able.
  502. // Do nothing. Will try next mode next loop.
  503. pb_backupbuddy::status( 'details', 'mysqlbuddy: Import method `' . $method . '` failed. Trying another compatibility mode next if able.' );
  504. } else { // Something else returned; used for resuming (integer) or a message (string).
  505. pb_backupbuddy::status( 'details', 'mysqlbuddy: Non-boolean response (usually means resume is needed): `' . $result . '`' );
  506. return $result; // Dont fallback if this happens. Usually means resume is needed to finish.
  507. }
  508. }
  509. }
  510. if ( $return === true ) { // Success.
  511. pb_backupbuddy::status( 'message', 'Database import procedure succeeded.' );
  512. return true;
  513. } else { // Overall failure.
  514. pb_backupbuddy::status( 'error', 'Database import procedure did not complete or failed.' );
  515. return false;
  516. }
  517. } // End import().
  518. public function _import_commandline( $sql_file, $old_prefix, $query_start = 0, $ignore_existing = false ) {
  519. pb_backupbuddy::status( 'details', 'mysqlbuddy: Preparing to run command line mysql import via exec().' );
  520. // If prefix has changed then need to update the file.
  521. if ( $old_prefix != $this->_database_prefix ) {
  522. if ( !isset( pb_backupbuddy::$classes['textreplacebuddy'] ) ) {
  523. require_once( pb_backupbuddy::plugin_path() . '/lib/textreplacebuddy/textreplacebuddy.php' );
  524. pb_backupbuddy::$classes['textreplacebuddy'] = new pb_backupbuddy_textreplacebuddy();
  525. };
  526. pb_backupbuddy::$classes['textreplacebuddy']->set_methods( array( 'commandline' ) ); // dont fallback into text version here.
  527. $regex_condition = "(INSERT INTO|CREATE TABLE|REFERENCES|CONSTRAINT|ALTER TABLE) (`?){$old_prefix}";
  528. pb_backupbuddy::$classes['textreplacebuddy']->string_replace( $sql_file, $old_prefix, $this->_database_prefix, $regex_condition );
  529. $sql_file = $sql_file . '.tmp'; // New SQL file created by textreplacebuddy.
  530. }
  531. /********** Begin preparing command **********/
  532. // Handle Windows wanting .exe. Note: executable directory path is prepended on exec() line of code.
  533. if ( stristr( PHP_OS, 'WIN' ) && !stristr( PHP_OS, 'DARWIN' ) ) { // Running Windows. (not darwin)
  534. $command = 'msql.exe';
  535. } else {
  536. $command = 'mysql';
  537. }
  538. // Handle possible sockets.
  539. if ( $this->_database_socket != '' ) {
  540. $command .= " --socket={$this->_database_socket}";
  541. pb_backupbuddy::status( 'details', 'mysqlbuddy: Using sockets in command.' );
  542. }
  543. $command .= " --host={$this->_database_host} --user={$this->_database_user} --password={$this->_database_pass} --default_character_set utf8 {$this->_database_name} < {$sql_file}";
  544. /********** End preparing command **********/
  545. // Run command.
  546. pb_backupbuddy::status( 'details', 'mysqlbuddy: Running import via command line next.' );
  547. list( $exec_output, $exec_exit_code ) = $this->_commandbuddy->execute( $this->_mysql_directory . $command );
  548. // TODO: Removed mysql pinging here. Do we need (or even want) that here?
  549. // Check the result of the execution.
  550. if ( $exec_exit_code == '0' ) {
  551. pb_backupbuddy::status( 'details', 'mysqlbuddy: Command appears to succeeded and returned proper response.' );
  552. return true;
  553. } else {
  554. pb_backupbuddy::status( 'error', 'mysqlbuddy: Command did not exit normally. Falling back to database dump compatibility modes.' );
  555. return false;
  556. }
  557. // Should never get to here.
  558. pb_backupbuddy::status( 'error', 'mysqlbuddy: Uncaught exception #433053890.' );
  559. return false;
  560. } // End _import_commandline().
  561. function string_begins_with( $string, $search ) {
  562. return ( strncmp( $string, $search, strlen($search) ) == 0 );
  563. }
  564. /* _import_php()
  565. *
  566. * Import from .SQL file into database via PHP by reading in file line by line.
  567. * Using codebase from BackupBuddy / importbuddy 2.x.
  568. * @see import().
  569. * @since 2.x.
  570. *
  571. * @param SEE import() PARAMETERS!!
  572. * @return mixed True on success (and completion), integer on incomplete (resume needed via $query_start), false on failure.
  573. */
  574. public function _import_php( $sql_file, $old_prefix, $query_start = 0, $ignore_existing = false ) {
  575. $this->time_start = time();
  576. pb_backupbuddy::status( 'message', 'Starting import of SQL data... This may take a moment...' );
  577. $file_stream = fopen( $sql_file, 'r' );
  578. if ( false === $file_stream ) {
  579. pb_backupbuddy::status( 'error', 'Error #9009: Unable to find any database backup data in the selected backup or could not open file (possibly due to permissions). Tried opening file `' . $sql_file . '`. Error #9009.' );
  580. return false;
  581. }
  582. // Iterate through each full row action and import it one at a time.
  583. $query_count = 0;
  584. $file_data = '';
  585. /* $in_create_table_block = false; */
  586. while ( ! feof( $file_stream ) ) {
  587. while ( false === strpos( $file_data, ";\n" ) ) {
  588. $file_data .= fread( $file_stream, 4096 );
  589. }
  590. $queries = explode( ";\n", $file_data );
  591. if ( preg_match( "/;\n$/", $file_data ) ) {
  592. $file_data = '';
  593. } else {
  594. $file_data = array_pop( $queries );
  595. }
  596. // TODO: DEBUGGING:
  597. //pb_backupbuddy::$options['max_execution_time'] = 0.41;
  598. // Loops through each full query.
  599. foreach ( (array) $queries as $query ) {
  600. if ( $query_count < ( $query_start - 1 ) ) { // Handle skipping any queries up to the point we are at.
  601. $query_count++;
  602. continue; // Continue to next foreach iteration.
  603. } else {
  604. $query_count++;
  605. }
  606. $query = trim( $query );
  607. if ( empty( $query ) || ( $this->string_begins_with( $query, '/*!40103' ) ) ) { // If blank line or starts with /*!40103 (mysqldump file has this junk in it).
  608. continue;
  609. }
  610. /*
  611. if ( $in_create_table_block === true ) {
  612. } else { // Watch for beginning of CREATE TABLE block if not in one.
  613. // Handle broken up CREATE TABLE blocks caused by mysqldump.
  614. if ( $this->string_begins_with( $query, 'CREATE TABLE' ) ) {
  615. $in_create_table_block = true;
  616. }
  617. }
  618. */
  619. $result = $this->_import_sql_dump_line( $query, $old_prefix, $ignore_existing );
  620. if ( false === $result ) { // Skipped query
  621. continue;
  622. }
  623. if ( 0 === ( $query_count % 2000 ) ) { // Display Working every 1500 queries imported.
  624. pb_backupbuddy::status( 'message', 'Working... Imported ' . $query_count . ' queries so far.' );
  625. }
  626. /*
  627. if ( 0 === ( $query_count % 6000 ) ) {
  628. echo "<br>\n";
  629. }
  630. */
  631. // If we are within 1 second of reaching maximum PHP runtime then stop here so that it can be picked up in another PHP process...
  632. if ( ( ( microtime( true ) - $this->time_start ) + 1 ) >= pb_backupbuddy::$options['max_execution_time'] ) {
  633. // TODO: Debugging:
  634. //if ( ( ( microtime( true ) - $this->time_start ) ) >= pb_backupbuddy::$options['max_execution_time'] ) {
  635. pb_backupbuddy::status( 'message', 'Exhausted available PHP time to import for this page load. Last query: ' . $query_count . '.' );
  636. fclose( $file_stream );
  637. return ( $query_count + 1 );
  638. //break 2;
  639. } // End if.
  640. } // End foreach().
  641. } // End while().
  642. fclose( $file_stream );
  643. pb_backupbuddy::status( 'message', 'Import of SQL data in compatibility mode (PHP) complete.' );
  644. pb_backupbuddy::status( 'message', 'Took ' . round( microtime( true ) - $this->time_start, 3 ) . ' seconds on ' . $query_count . ' queries. ' );
  645. return true;
  646. } // End _import_php().
  647. /**
  648. * _import_sql_dump_line()
  649. *
  650. * Imports a line/query into the database.
  651. * Handles using the specified table prefix.
  652. * @since 2.x.
  653. *
  654. * @param string $query Query string to run for importing.
  655. * @param string $old_prefix Old prefix. (new prefix was passed in constructor).
  656. * @return boolean True=success, False=failed.
  657. *
  658. */
  659. function _import_sql_dump_line( $query, $old_prefix, $ignore_existing ) {
  660. $new_prefix = $this->_database_prefix;
  661. $query_operators = 'INSERT INTO|CREATE TABLE|REFERENCES|CONSTRAINT|ALTER TABLE';
  662. // Replace database prefix in query.
  663. if ( $old_prefix !== $new_prefix ) {
  664. $query = preg_replace( "/^($query_operators)(\s+`?)$old_prefix/i", "\${1}\${2}$new_prefix", $query ); // 4-29-11
  665. }
  666. // Run the query
  667. // Disabled to prevent from running on EVERY line. Now just running before this. mysql_query("SET NAMES 'utf8'"); // Force UTF8
  668. $result = mysql_query( $query );
  669. if ( false === $result ) {
  670. if ( $ignore_existing !== true ) {
  671. $mysql_error = mysql_error();
  672. pb_backupbuddy::status( 'error', 'Error #9010: Unable to import SQL query: ' . $mysql_error );
  673. if ( false !== stristr( $mysql_error, 'server has gone away' ) ) { // if string denotes that mysql server has gone away bail since it will likely just flood user with errors...
  674. pb_backupbuddy::status( 'error', 'Error #9010b: Halting backup process as mysql server has gone away and database data could not be imported. Typically the restore cannot continue so the process has been halted. This is usually caused by a problematic mysql server at your hosting provider, low mysql timeouts, etc. Contact your hosting company for support.' );
  675. die( 'BACKUP HALTED' );
  676. }
  677. }
  678. return false;
  679. } else {
  680. return true;
  681. }
  682. } // End _import_sql_dump_line().
  683. } // End pb_backupbuddy_mysqlbuddy class.
  684. ?>