PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/betaimages/chakalos
PHP | 382 lines | 218 code | 73 blank | 91 comment | 34 complexity | fe06d683f64ee3255e66d5a31b8f0f97 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. class pb_backupbuddy_import {
  3. /**
  4. * migrate_htaccess()
  5. *
  6. * Migrates .htaccess.bb_temp file if it exists.
  7. *
  8. * @return boolean False only if file is unwritable. True if write success; true if file does not even exist.
  9. *
  10. */
  11. function migrate_htaccess() {
  12. if ( pb_backupbuddy::$options['skip_htaccess'] == true ) {
  13. pb_backupbuddy::status( 'message', 'Skipping .htaccess migration based on settings.' );
  14. return true;
  15. }
  16. if ( file_exists( ABSPATH . '.htaccess.bb_temp' ) && ( !is_writable( ABSPATH . '.htaccess.bb_temp' ) ) ) {
  17. pb_backupbuddy::status( 'error', 'Error #9020: Unable to write to `.htaccess.bb_temp` file. Verify permissions.' );
  18. pb_backupbuddy::alert( 'Warning: Unable to write to file `.htaccess.bb_temp`. Verify this file has proper write permissions. You may receive 404 Not Found errors on your site if this is not corrected. To fix after migration completes: Log in to your WordPress admin and select Settings:: Permalinks from the left menu then save.', '9020' );
  19. return false;
  20. }
  21. // If no .htaccess.bb_temp file exists then create a basic default one then migrate that as needed. @since 2.2.32.
  22. if ( !file_exists( ABSPATH . '.htaccess.bb_temp' ) ) {
  23. pb_backupbuddy::status( 'message', 'No `.htaccess.bb_temp` file found. Creating basic default .htaccess.bb_temp file.' );
  24. // Default .htaccess file.
  25. $htaccess_contents =
  26. "# BEGIN WordPress\n
  27. <IfModule mod_rewrite.c>\n
  28. RewriteEngine On\n
  29. RewriteBase /\n
  30. RewriteRule ^index\\.php$ - [L]\n
  31. RewriteCond %{REQUEST_FILENAME} !-f\n
  32. RewriteCond %{REQUEST_FILENAME} !-d\n
  33. RewriteRule . /index.php [L]\n
  34. </IfModule>\n
  35. # END WordPress\n";
  36. file_put_contents( ABSPATH . '.htaccess.bb_temp', $htaccess_contents );
  37. unset( $htaccess_contents );
  38. }
  39. pb_backupbuddy::status( 'message', 'Migrating `.htaccess.bb_temp` file...' );
  40. $oldurl = strtolower( pb_backupbuddy::$options['dat_file']['siteurl'] );
  41. $oldurl = str_replace( '/', '\\', $oldurl );
  42. $oldurl = str_replace( 'http:\\', '', $oldurl );
  43. $oldurl = trim( $oldurl, '\\' );
  44. $oldurl = explode( '\\', $oldurl );
  45. $oldurl[0] = '';
  46. $newurl = strtolower( pb_backupbuddy::$options['siteurl'] );
  47. $newurl = str_replace( '/', '\\', $newurl );
  48. $newurl = str_replace( 'http:\\', '', $newurl );
  49. $newurl = trim( $newurl, '\\' );
  50. $newurl = explode( '\\', $newurl );
  51. $newurl[0] = '';
  52. pb_backupbuddy::status( 'message', 'Checking `.htaccess.bb_temp` file.' );
  53. // If the URL (domain and/or URL subdirectory ) has changed, then need to update .htaccess.bb_temp file.
  54. if ( $newurl !== $oldurl ) {
  55. pb_backupbuddy::status( 'message', 'URL directory has changed. Updating from `' . implode( '/', $oldurl ) . '` to `' . implode( '/', $newurl ) . '`.' );
  56. $rewrite_lines = array();
  57. $got_rewrite = false;
  58. $rewrite_path = implode( '/', $newurl );
  59. $file_array = file( ABSPATH . '.htaccess.bb_temp' );
  60. foreach ($file_array as $line_number => $line) {
  61. if ( $got_rewrite == true ) { // In a WordPress section.
  62. if ( strstr( $line, 'END WordPress' ) ) { // End of a WordPress block so stop replacing.
  63. $got_rewrite = false;
  64. $rewrite_lines[] = $line; // Captures end of WordPress block.
  65. } else {
  66. if ( strstr( $line, 'RewriteBase' ) ) { // RewriteBase
  67. $rewrite_lines[] = 'RewriteBase ' . $rewrite_path . '/' . "\n";
  68. } elseif ( strstr( $line, 'RewriteRule' ) ) { // RewriteRule
  69. if ( strstr( $line, '^index\.php$' ) ) { // Handle new strange rewriterule. Leave as is.
  70. $rewrite_lines[] = $line;
  71. pb_backupbuddy::status( 'details', 'Htaccess ^index\.php$ detected. Leaving as is.' );
  72. } else { // Normal spot.
  73. $rewrite_lines[] = 'RewriteRule . ' . $rewrite_path . '/index.php' . "\n";
  74. }
  75. } else {
  76. $rewrite_lines[] = $line; // Captures everything inside WordPress block we arent modifying.
  77. }
  78. }
  79. } else { // Outside a WordPress section.
  80. if ( strstr( $line, 'BEGIN WordPress' ) ) {
  81. $got_rewrite = true; // Beginning of a WordPress block so start replacing.
  82. }
  83. $rewrite_lines[] = $line; // Captures everything outside of WordPress block.
  84. }
  85. }
  86. $handling = fopen( ABSPATH . '.htaccess.bb_temp', 'w');
  87. fwrite( $handling, implode( $rewrite_lines ) );
  88. fclose( $handling );
  89. unset( $handling );
  90. pb_backupbuddy::status( 'message', 'Migrated `.htaccess.bb_temp` file. It will be renamed back to `.htaccess` on the final step.' );
  91. } else {
  92. pb_backupbuddy::status( 'message', 'No changes needed for `.htaccess.bb_temp` file.' );
  93. }
  94. return true;
  95. } // End migrate_htaccess().
  96. /**
  97. * wipe_database()
  98. *
  99. * Clear out the existing database to prepare for importing new data.
  100. *
  101. * @return boolean Currently always true.
  102. */
  103. function wipe_database( $prefix ) {
  104. if ( $prefix == '' ) {
  105. pb_backupbuddy::status( 'warning', 'No database prefix specified to wipe.' );
  106. return false;
  107. }
  108. pb_backupbuddy::status( 'message', 'Beginning wipe of database tables matching prefix `' . $prefix . '`...' );
  109. // Connect to database.
  110. $this->connect_database();
  111. $query = "SHOW TABLES LIKE '" . mysql_real_escape_string( str_replace( '_', '\_', $prefix ) ) . "%'"; // Underscore must be escaped for use in mysql LIKE to make literal.
  112. pb_backupbuddy::status( 'message', 'Drop query: `' . $query . '`.' );
  113. $result = mysql_query( $query );
  114. $table_wipe_count = mysql_num_rows( $result );
  115. while( $row = mysql_fetch_row( $result ) ) {
  116. pb_backupbuddy::status( 'details', 'Dropping table `' . $row[0] . '`.' );
  117. mysql_query( 'DROP TABLE `' . $row[0] . '`' );
  118. }
  119. mysql_free_result( $result ); // Free memory.
  120. pb_backupbuddy::status( 'message', 'Wiped database of ' . $table_wipe_count . ' tables.' );
  121. return true;
  122. } // End wipe_database().
  123. /**
  124. * wipe_database()
  125. *
  126. * Clear out the existing database to prepare for importing new data.
  127. *
  128. * @return boolean Currently always true.
  129. */
  130. function wipe_database_all( $confirm = false ) {
  131. if ( $confirm !== true ) {
  132. die( 'Error #5466566: Parameter 1 to wipe_database_all() must be boolean true to proceed.' );
  133. }
  134. pb_backupbuddy::status( 'message', 'Beginning wipe of ALL database tables...' );
  135. // Connect to database.
  136. $this->connect_database();
  137. $query = "SHOW TABLES";
  138. pb_backupbuddy::status( 'message', 'Drop query: `' . $query . '`.' );
  139. $result = mysql_query( $query );
  140. $table_wipe_count = mysql_num_rows( $result );
  141. while( $row = mysql_fetch_row( $result ) ) {
  142. pb_backupbuddy::status( 'details', 'Dropping table `' . $row[0] . '`.' );
  143. mysql_query( 'DROP TABLE `' . $row[0] . '`' );
  144. }
  145. mysql_free_result( $result ); // Free memory.
  146. pb_backupbuddy::status( 'message', 'Wiped database of ' . $table_wipe_count . ' tables.' );
  147. return true;
  148. } // End wipe_database_all().
  149. /* preg_escape_back()
  150. *
  151. * Escape backreferences from string for use with regex. Used by migrate_wp_config().
  152. * @see migrate_wp_config()
  153. *
  154. * @param string $string String to escape.
  155. * @return string Escaped string.
  156. */
  157. function preg_escape_back($string) {
  158. // Replace $ with \$ and \ with \\
  159. $string = preg_replace('#(?<!\\\\)(\\$|\\\\)#', '\\\\$1', $string);
  160. return $string;
  161. } // End preg_escape_back().
  162. /**
  163. * migrate_wp_config()
  164. *
  165. * Migrates and updates the wp-config.php file contents as needed.
  166. *
  167. * @return true|string True on success. On false returns the new wp-config file content.
  168. */
  169. function migrate_wp_config() {
  170. pb_backupbuddy::status( 'message', 'Starting migration of wp-config.php file...' );
  171. flush();
  172. if ( file_exists( ABSPATH . 'wp-config.php' ) ) {
  173. // Useful REGEX site: http://gskinner.com/RegExr/
  174. $updated_home_url = false;
  175. $wp_config = array();
  176. $lines = file( ABSPATH . 'wp-config.php' );
  177. $patterns = array();
  178. $replacements = array();
  179. /*
  180. Update WP_SITEURL, WP_HOME if they exist.
  181. Update database DB_NAME, DB_USER, DB_PASSWORD, and DB_HOST.
  182. RegExp: /define\([\s]*('|")WP_SITEURL('|"),[\s]*('|")(.)*('|")[\s]*\);/gi
  183. pattern: define\([\s]*('|")WP_SITEURL('|"),[\s]*('|")(.)*('|")[\s]*\);
  184. */
  185. $pattern[0] = '/define\([\s]*(\'|")WP_SITEURL(\'|"),[\s]*(\'|")(.)*(\'|")[\s]*\);/i';
  186. $replace[0] = "define( 'WP_SITEURL', '" . trim( pb_backupbuddy::$options['siteurl'], '/' ) . "' );";
  187. pb_backupbuddy::status( 'details', 'wp-config.php: Setting WP_SITEURL (if applicable) to `' . trim( pb_backupbuddy::$options['siteurl'], '/' ) . '`.' );
  188. $pattern[1] = '/define\([\s]*(\'|")WP_HOME(\'|"),[\s]*(\'|")(.)*(\'|")[\s]*\);/i';
  189. $replace[1] = "define( 'WP_HOME', '" . trim( pb_backupbuddy::$options['home'], '/' ) . "' );";
  190. pb_backupbuddy::status( 'details', 'wp-config.php: Setting WP_HOME (if applicable) to `' . trim( pb_backupbuddy::$options['home'], '/' ) . '`.' );
  191. $pattern[2] = '/define\([\s]*(\'|")DB_NAME(\'|"),[\s]*(\'|")(.)*(\'|")[\s]*\);/i';
  192. $replace[2] = "define( 'DB_NAME', '" . pb_backupbuddy::$options['db_name'] . "' );";
  193. $pattern[3] = '/define\([\s]*(\'|")DB_USER(\'|"),[\s]*(\'|")(.)*(\'|")[\s]*\);/i';
  194. $replace[3] = "define( 'DB_USER', '" . pb_backupbuddy::$options['db_user'] . "' );";
  195. $pattern[4] = '/define\([\s]*(\'|")DB_PASSWORD(\'|"),[\s]*(\'|")(.)*(\'|")[\s]*\);/i';
  196. $replace[4] = "define( 'DB_PASSWORD', '" . $this->preg_escape_back( pb_backupbuddy::$options['db_password'] ) . "' );";
  197. $pattern[5] = '/define\([\s]*(\'|")DB_HOST(\'|"),[\s]*(\'|")(.)*(\'|")[\s]*\);/i';
  198. $replace[5] = "define( 'DB_HOST', '" . pb_backupbuddy::$options['db_server'] . "' );";
  199. // If multisite, update domain.
  200. if ( pb_backupbuddy::$options['domain'] != '' ) {
  201. $pattern[6] = '/define\([\s]*(\'|")DOMAIN_CURRENT_SITE(\'|"),[\s]*(\'|")(.)*(\'|")[\s]*\);/i';
  202. $replace[6] = "define( 'DOMAIN_CURRENT_SITE', '" . pb_backupbuddy::$options['domain'] . "' );";
  203. pb_backupbuddy::status( 'details', 'wp-config.php: Setting DOMAIN_CURRENT_SITE (if applicable) to `' . pb_backupbuddy::$options['domain'] . '`.' );
  204. } else {
  205. pb_backupbuddy::status( 'details', 'wp-config.php did not upload DOMAIN_CURRENT_SITE as it was blank.' );
  206. }
  207. /*
  208. Update table prefix.
  209. RegExp: /\$table_prefix[\s]*=[\s]*('|")(.)*('|");/gi
  210. pattern: \$table_prefix[\s]*=[\s]*('|")(.)*('|");
  211. */
  212. $pattern[7] = '/\$table_prefix[\s]*=[\s]*(\'|")(.)*(\'|");/i';
  213. $replace[7] = '$table_prefix = \'' . pb_backupbuddy::$options['db_prefix'] . '\';';
  214. // Perform the actual replacement.
  215. $lines = preg_replace( $pattern, $replace, $lines );
  216. // Check that we can write to this file.
  217. if ( !is_writable( ABSPATH . 'wp-config.php' ) ) {
  218. pb_backupbuddy::alert( 'ERROR: Unable to write to file wp-config.php. Verify this file has proper write permissions.', true, '9020' );
  219. return implode( "\n", $lines );
  220. }
  221. // Write changes to config file.
  222. if ( false === ( file_put_contents( ABSPATH . 'wp-config.php', $lines ) ) ) {
  223. pb_backupbuddy::alert( 'ERROR: Unable to save changes to wp-config.php. Verify this file has proper write permissions.', true, '9020' );
  224. return implode( "\n", $lines );
  225. }
  226. unset( $lines );
  227. } else {
  228. pb_backupbuddy::status( 'warning', 'Warning: wp-config.php file not found.' );
  229. pb_backupbuddy::alert( 'Note: wp-config.php file not found. This is normal for a database only backup.' );
  230. }
  231. pb_backupbuddy::status( 'message', 'Migration of wp-config.php complete.' );
  232. return true;
  233. } // End migrate_wp_config().
  234. function get_dat_file_array( $dat_file ) {
  235. pb_backupbuddy::status( 'details', 'Loading backup dat file.' );
  236. if ( file_exists( $dat_file ) ) {
  237. $backupdata = file_get_contents( $dat_file );
  238. } else { // Missing.
  239. pb_backupbuddy::alert( 'Error #9003: BackupBuddy data file (backupbuddy_dat.php) missing or unreadable. There may be a problem with the backup file, the files could not be extracted (you may manually extract the zip file in this directory to manually do this portion of restore), or the files were deleted before this portion of the restore was reached. Start the import process over or try manually extracting (unzipping) the files then starting over. Restore will not continue to protect integrity of any existing data.', true, '9003' );
  240. die( ' Halted.' );
  241. }
  242. // Unserialize data; If it fails it then decodes the obscufated data then unserializes it. (new dat file method starting at 2.0).
  243. if ( !is_serialized( $backupdata ) || ( false === ( $return = unserialize( $backupdata ) ) ) ) {
  244. // Skip first line.
  245. $second_line_pos = strpos( $backupdata, "\n" ) + 1;
  246. $backupdata = substr( $backupdata, $second_line_pos );
  247. // Decode back into an array.
  248. $return = unserialize( base64_decode( $backupdata ) );
  249. }
  250. pb_backupbuddy::status( 'details', 'Successfully loaded backup dat file.' );
  251. return $return;
  252. } // End load_dat_file().
  253. // TODO: switch to using pb_backupbuddy::status_box() instead.
  254. /**
  255. * status_box()
  256. *
  257. * Displays a textarea for placing status text into.
  258. *
  259. * @param $default_text string First line of text to display.
  260. * @param boolean $hidden Whether or not to apply display: none; CSS.
  261. * @return string HTML for textarea.
  262. */
  263. function status_box( $default_text = '', $hidden = false ) {
  264. define( 'PB_STATUS', true ); // Tells framework status() function to output future logging info into status box via javascript.
  265. $return = '<textarea readonly="readonly" id="importbuddy_status" wrap="off"';
  266. if ( $hidden === true ) {
  267. $return .= ' style="display: none; "';
  268. }
  269. $return .= '>' . $default_text . '</textarea>';
  270. return $return;
  271. }
  272. /**
  273. * connect()
  274. *
  275. * Initializes a connection to the mysql database.
  276. *
  277. * @return boolean True on success; else false. Success testing is very loose.
  278. */
  279. function connect_database() {
  280. // Set up database connection.
  281. if ( false === @mysql_connect( pb_backupbuddy::$options['db_server'], pb_backupbuddy::$options['db_user'], pb_backupbuddy::$options['db_password'] ) ) {
  282. pb_backupbuddy::alert( 'ERROR: Unable to connect to database server and/or log in. Verify the database server name, username, and password. Details: ' . mysql_error(), true, '9006' );
  283. return false;
  284. }
  285. $database_name = mysql_real_escape_string( pb_backupbuddy::$options['db_name'] );
  286. flush();
  287. // Select the database.
  288. if ( false === @mysql_select_db( pb_backupbuddy::$options['db_name'] ) ) {
  289. pb_backupbuddy::status( 'error', 'Error: Unable to connect or authenticate to database `' . pb_backupbuddy::$options['db_name'] . '`.' );
  290. return false;
  291. }
  292. // Set up character set. Important.
  293. mysql_query("SET NAMES 'utf8'");
  294. return true;
  295. }
  296. /**
  297. * migrate_database()
  298. *
  299. * Migrates the already imported database's content for updates ABSPATH and URL.
  300. *
  301. * @return boolean True=success, False=failed.
  302. *
  303. */
  304. function migrate_database() {
  305. require( 'importbuddy/classes/_migrate_database.php' );
  306. return $return;
  307. }
  308. } // End class.
  309. ?>