PageRenderTime 1547ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/wpremote/hm-backup/hm-backup.php

https://github.com/vidor/vidor.me
PHP | 1263 lines | 524 code | 324 blank | 415 comment | 143 complexity | 0bed7c1dd9976f498d6d06d913ad7192 MD5 | raw file
  1. <?php
  2. /**
  3. * Generic file and database backup class
  4. *
  5. * @version 1.5.1
  6. */
  7. class HM_Backup {
  8. /**
  9. * The path where the backup file should be saved
  10. *
  11. * @string
  12. * @access public
  13. */
  14. public $path;
  15. /**
  16. * Whether the backup should be files only
  17. *
  18. * @bool
  19. * @access public
  20. */
  21. public $files_only;
  22. /**
  23. * Whether the backup should be database only
  24. *
  25. * @bool
  26. * @access public
  27. */
  28. public $database_only;
  29. /**
  30. * The filename of the backup file
  31. *
  32. * @string
  33. * @access public
  34. */
  35. public $archive_filename;
  36. /**
  37. * The filename of the database dump
  38. *
  39. * @string
  40. * @access public
  41. */
  42. public $database_dump_filename;
  43. /**
  44. * The path to the zip command
  45. *
  46. * @string
  47. * @access public
  48. */
  49. public $zip_command_path;
  50. /**
  51. * The path to the mysqldump command
  52. *
  53. * @string
  54. * @access public
  55. */
  56. public $mysqldump_command_path;
  57. /**
  58. * An array of exclude rules
  59. *
  60. * @array
  61. * @access public
  62. */
  63. public $excludes;
  64. /**
  65. * The path that should be backed up
  66. *
  67. * @var string
  68. * @access public
  69. */
  70. public $root;
  71. /**
  72. * Holds the current db connection
  73. *
  74. * @var resource
  75. * @access private
  76. */
  77. private $db;
  78. /**
  79. * Store the current backup instance
  80. *
  81. * @var object
  82. * @static
  83. * @access public
  84. */
  85. private static $instance;
  86. /**
  87. * An array of all the files in root
  88. * excluding excludes
  89. *
  90. * @var array
  91. * @access private
  92. */
  93. private $files;
  94. /**
  95. * Contains an array of errors
  96. *
  97. * @var mixed
  98. * @access private
  99. */
  100. private $errors;
  101. /**
  102. * Contains an array of warnings
  103. *
  104. * @var mixed
  105. * @access private
  106. */
  107. private $warnings;
  108. /**
  109. * The archive method used
  110. *
  111. * @var string
  112. * @access private
  113. */
  114. private $archive_method;
  115. /**
  116. * The mysqldump method used
  117. *
  118. * @var string
  119. * @access private
  120. */
  121. private $mysqldump_method;
  122. /**
  123. * Sets up the default properties
  124. *
  125. * @access public
  126. * @return null
  127. */
  128. public function __construct() {
  129. // Raise the memory limit and max_execution_time time
  130. @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
  131. @set_time_limit( 0 );
  132. $this->errors = array();
  133. set_error_handler( array( &$this, 'error_handler' ) );
  134. // Defaults
  135. $this->root = $this->conform_dir( ABSPATH );
  136. $this->path = $this->conform_dir( WP_CONTENT_DIR . '/backups' );
  137. $this->database_dump_filename = 'database_' . DB_NAME . '.sql';
  138. $this->archive_filename = strtolower( sanitize_file_name( get_bloginfo( 'name' ) . '.backup.' . date( 'Y-m-d-H-i-s', time() + ( current_time( 'timestamp' ) - time() ) ) . '.zip' ) );
  139. $this->mysqldump_command_path = $this->guess_mysqldump_command_path();
  140. $this->zip_command_path = $this->guess_zip_command_path();
  141. $this->database_only = false;
  142. $this->files_only = false;
  143. }
  144. /**
  145. * Return the current instance
  146. *
  147. * @access public
  148. * @static
  149. * @return object
  150. */
  151. public static function get_instance() {
  152. if ( empty( self::$instance ) )
  153. self::$instance = new HM_Backup();
  154. return self::$instance;
  155. }
  156. /**
  157. * The full filepath to the archive file.
  158. *
  159. * @access public
  160. * @return string
  161. */
  162. public function archive_filepath() {
  163. return trailingslashit( $this->path() ) . $this->archive_filename();
  164. }
  165. /**
  166. * The full filepath to the archive file.
  167. *
  168. * @access public
  169. * @return string
  170. */
  171. public function archive_filename() {
  172. return strtolower( sanitize_file_name( remove_accents( $this->archive_filename ) ) );
  173. }
  174. /**
  175. * The full filepath to the database dump file.
  176. *
  177. * @access public
  178. * @return string
  179. */
  180. public function database_dump_filepath() {
  181. return trailingslashit( $this->path() ) . $this->database_dump_filename();
  182. }
  183. public function database_dump_filename() {
  184. return strtolower( sanitize_file_name( remove_accents( $this->database_dump_filename ) ) );
  185. }
  186. public function root() {
  187. return $this->conform_dir( $this->root );
  188. }
  189. public function path() {
  190. return $this->conform_dir( $this->path );
  191. }
  192. public function archive_method() {
  193. return $this->archive_method;
  194. }
  195. public function mysqldump_method() {
  196. return $this->mysqldump_method;
  197. }
  198. /**
  199. * Kick off a backup
  200. *
  201. * @access public
  202. * @return bool
  203. */
  204. public function backup() {
  205. do_action( 'hmbkp_backup_started', $this );
  206. // Backup database
  207. if ( ! $this->files_only )
  208. $this->mysqldump();
  209. // Zip everything up
  210. $this->archive();
  211. do_action( 'hmbkp_backup_complete', $this );
  212. }
  213. /**
  214. * Create the mysql backup
  215. *
  216. * Uses mysqldump if available, falls back to PHP
  217. * if not.
  218. *
  219. * @access public
  220. * @return null
  221. */
  222. public function mysqldump() {
  223. do_action( 'hmbkp_mysqldump_started' );
  224. $this->mysqldump_method = 'mysqldump';
  225. // Use mysqldump if we can
  226. if ( $this->mysqldump_command_path ) {
  227. $host = reset( explode( ':', DB_HOST ) );
  228. $port = strpos( DB_HOST, ':' ) ? end( explode( ':', DB_HOST ) ) : '';
  229. // Path to the mysqldump executable
  230. $cmd = escapeshellarg( $this->mysqldump_command_path );
  231. // No Create DB command
  232. $cmd .= ' --no-create-db';
  233. // Make sure binary data is exported properly
  234. $cmd .= ' --hex-blob';
  235. // Username
  236. $cmd .= ' -u ' . escapeshellarg( DB_USER );
  237. // Don't pass the password if it's blank
  238. if ( DB_PASSWORD )
  239. $cmd .= ' -p' . escapeshellarg( DB_PASSWORD );
  240. // Set the host
  241. $cmd .= ' -h ' . escapeshellarg( $host );
  242. // Set the port if it was set
  243. if ( ! empty( $port ) )
  244. $cmd .= ' -P ' . $port;
  245. // The file we're saving too
  246. $cmd .= ' -r ' . escapeshellarg( $this->database_dump_filepath() );
  247. // The database we're dumping
  248. $cmd .= ' ' . escapeshellarg( DB_NAME );
  249. // Pipe STDERR to STDOUT
  250. $cmd .= ' 2>&1';
  251. // Store any returned data in warning
  252. $this->warning( $this->mysqldump_method, shell_exec( $cmd ) );
  253. }
  254. // If not or if the shell mysqldump command failed, use the PHP fallback
  255. if ( ! file_exists( $this->database_dump_filepath() ) )
  256. $this->mysqldump_fallback();
  257. do_action( 'hmbkp_mysqldump_finished' );
  258. }
  259. /**
  260. * PHP mysqldump fallback functions, exports the database to a .sql file
  261. *
  262. * @access public
  263. * @return null
  264. */
  265. public function mysqldump_fallback() {
  266. $this->errors_to_warnings( $this->mysqldump_method );
  267. $this->mysqldump_method = 'mysqldump_fallback';
  268. $this->db = mysql_pconnect( DB_HOST, DB_USER, DB_PASSWORD );
  269. mysql_select_db( DB_NAME, $this->db );
  270. mysql_set_charset( DB_CHARSET, $this->db );
  271. // Begin new backup of MySql
  272. $tables = mysql_query( 'SHOW TABLES' );
  273. $sql_file = "# WordPress : " . get_bloginfo( 'url' ) . " MySQL database backup\n";
  274. $sql_file .= "#\n";
  275. $sql_file .= "# Generated: " . date( 'l j. F Y H:i T' ) . "\n";
  276. $sql_file .= "# Hostname: " . DB_HOST . "\n";
  277. $sql_file .= "# Database: " . $this->sql_backquote( DB_NAME ) . "\n";
  278. $sql_file .= "# --------------------------------------------------------\n";
  279. for ( $i = 0; $i < mysql_num_rows( $tables ); $i++ ) {
  280. $curr_table = mysql_tablename( $tables, $i );
  281. // Create the SQL statements
  282. $sql_file .= "# --------------------------------------------------------\n";
  283. $sql_file .= "# Table: " . $this->sql_backquote( $curr_table ) . "\n";
  284. $sql_file .= "# --------------------------------------------------------\n";
  285. $this->make_sql( $sql_file, $curr_table );
  286. }
  287. }
  288. /**
  289. * Zip up all the files.
  290. *
  291. * Attempts to use the shell zip command, if
  292. * thats not available then it fallsback to
  293. * PHP ZipArchive and finally PclZip.
  294. *
  295. * @access public
  296. * @return null
  297. */
  298. public function archive() {
  299. do_action( 'hmbkp_archive_started' );
  300. // Do we have the path to the zip command
  301. if ( $this->zip_command_path )
  302. $this->zip();
  303. // If not or if the shell zip failed then use ZipArchive
  304. if ( empty( $this->archive_verified ) && class_exists( 'ZipArchive' ) && empty( $this->skip_zip_archive ) )
  305. $this->zip_archive();
  306. // If ZipArchive is unavailable or one of the above failed
  307. if ( empty( $this->archive_verified ) )
  308. $this->pcl_zip();
  309. // Delete the database dump file
  310. if ( file_exists( $this->database_dump_filepath() ) )
  311. unlink( $this->database_dump_filepath() );
  312. do_action( 'hmbkp_archive_finished' );
  313. }
  314. /**
  315. * Zip using the native zip command
  316. *
  317. * @access public
  318. * @return null
  319. */
  320. public function zip() {
  321. $this->archive_method = 'zip';
  322. // Zip up $this->root with excludes
  323. if ( ! $this->database_only && $this->exclude_string( 'zip' ) )
  324. $this->warning( $this->archive_method, shell_exec( 'cd ' . escapeshellarg( $this->root() ) . ' && ' . escapeshellarg( $this->zip_command_path ) . ' -rq ' . escapeshellarg( $this->archive_filepath() ) . ' ./' . ' -x ' . $this->exclude_string( 'zip' ) . ' 2>&1' ) );
  325. // Zip up $this->root without excludes
  326. elseif ( ! $this->database_only )
  327. $this->warning( $this->archive_method, shell_exec( 'cd ' . escapeshellarg( $this->root() ) . ' && ' . escapeshellarg( $this->zip_command_path ) . ' -rq ' . escapeshellarg( $this->archive_filepath() ) . ' ./' . ' 2>&1' ) );
  328. // Add the database dump to the archive
  329. if ( ! $this->files_only )
  330. $this->warning( $this->archive_method, shell_exec( 'cd ' . escapeshellarg( $this->path() ) . ' && ' . escapeshellarg( $this->zip_command_path ) . ' -uq ' . escapeshellarg( $this->archive_filepath() ) . ' ' . escapeshellarg( $this->database_dump_filename() ) . ' 2>&1' ) );
  331. $this->check_archive();
  332. }
  333. /**
  334. * Fallback for creating zip archives if zip command is
  335. * unnavailable.
  336. *
  337. * @access public
  338. * @param string $path
  339. */
  340. public function zip_archive() {
  341. $this->errors_to_warnings( $this->archive_method );
  342. $this->archive_method = 'ziparchive';
  343. $zip = new ZipArchive();
  344. if ( ! class_exists( 'ZipArchive' ) || ! $zip->open( $this->archive_filepath(), ZIPARCHIVE::CREATE ) )
  345. return;
  346. if ( ! $this->database_only ) {
  347. $files_added = 0;
  348. foreach ( $this->files() as $file ) {
  349. if ( is_dir( trailingslashit( $this->root() ) . $file ) )
  350. $zip->addEmptyDir( trailingslashit( $file ) );
  351. elseif ( is_file( trailingslashit( $this->root() ) . $file ) )
  352. $zip->addFile( trailingslashit( $this->root() ) . $file, $file );
  353. if ( ++$files_added % 500 === 0 )
  354. if ( ! $zip->close() || ! $zip->open( $this->archive_filepath(), ZIPARCHIVE::CREATE ) )
  355. return;
  356. }
  357. }
  358. // Add the database
  359. if ( ! $this->files_only )
  360. $zip->addFile( $this->database_dump_filepath(), $this->database_dump_filename() );
  361. if ( $zip->status )
  362. $this->warning( $this->archive_method, $zip->status );
  363. if ( $zip->statusSys )
  364. $this->warning( $this->archive_method, $zip->statusSys );
  365. $zip->close();
  366. $this->check_archive();
  367. }
  368. /**
  369. * Fallback for creating zip archives if zip command and ZipArchive are
  370. * unnavailable.
  371. *
  372. * Uses the PclZip library that ships with WordPress
  373. *
  374. * @access public
  375. * @param string $path
  376. */
  377. public function pcl_zip() {
  378. $this->errors_to_warnings( $this->archive_method );
  379. $this->archive_method = 'pclzip';
  380. global $_hmbkp_exclude_string;
  381. $_hmbkp_exclude_string = $this->exclude_string( 'regex' );
  382. $this->load_pclzip();
  383. $archive = new PclZip( $this->archive_filepath() );
  384. // Zip up everything
  385. if ( ! $this->database_only )
  386. if ( ! $archive->add( $this->root(), PCLZIP_OPT_REMOVE_PATH, $this->root(), PCLZIP_CB_PRE_ADD, 'hmbkp_pclzip_callback' ) )
  387. $this->warning( $this->archive_method, $archive->errorInfo( true ) );
  388. // Add the database
  389. if ( ! $this->files_only )
  390. if ( ! $archive->add( $this->database_dump_filepath(), PCLZIP_OPT_REMOVE_PATH, $this->path() ) )
  391. $this->warning( $this->archive_method, $archive->errorInfo( true ) );
  392. unset( $GLOBALS['_hmbkp_exclude_string'] );
  393. $this->check_archive();
  394. }
  395. /**
  396. * Verify that the archive is valid and contains all the files it should contain.
  397. *
  398. * @access public
  399. * @return bool
  400. */
  401. public function check_archive() {
  402. // If we've already passed then no need to check again
  403. if ( ! empty( $this->archive_verified ) )
  404. return true;
  405. if ( ! file_exists( $this->archive_filepath() ) )
  406. $this->error( $this->archive_method(), __( 'The backup file was not created', 'hmbkp' ) );
  407. // Verify using the zip command if possible
  408. if ( $this->zip_command_path ) {
  409. $verify = shell_exec( escapeshellarg( $this->zip_command_path ) . ' -T ' . escapeshellarg( $this->archive_filepath() ) . ' 2> /dev/null' );
  410. if ( strpos( $verify, 'OK' ) === false )
  411. $this->error( $this->archive_method(), $verify );
  412. }
  413. // If there are errors delete the backup file.
  414. if ( $this->errors( $this->archive_method() ) && file_exists( $this->archive_filepath() ) )
  415. unlink( $this->archive_filepath() );
  416. if ( $this->errors( $this->archive_method() ) )
  417. return false;
  418. return $this->archive_verified = true;
  419. }
  420. /**
  421. * Generate the array of files to be backed up by looping through
  422. * root, ignored unreadable files and excludes
  423. *
  424. * @access public
  425. * @return array
  426. */
  427. public function files() {
  428. if ( ! empty( $this->files ) )
  429. return $this->files;
  430. $this->files = array();
  431. if ( defined( 'RecursiveDirectoryIterator::FOLLOW_SYMLINKS' ) ) {
  432. $filesystem = new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $this->root(), RecursiveDirectoryIterator::FOLLOW_SYMLINKS ), RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD );
  433. $excludes = $this->exclude_string( 'regex' );
  434. foreach ( $filesystem as $file ) {
  435. if ( ! $file->isReadable() ) {
  436. $this->unreadable_files[] = $file->getPathName();
  437. continue;
  438. }
  439. $pathname = str_ireplace( trailingslashit( $this->root() ), '', $this->conform_dir( $file->getPathname() ) );
  440. // Excludes
  441. if ( $excludes && preg_match( '(' . $excludes . ')', $pathname ) )
  442. continue;
  443. // Don't include database dump as it's added separately
  444. if ( basename( $pathname ) == $this->database_dump_filename() )
  445. continue;
  446. $this->files[] = $pathname;
  447. }
  448. } else {
  449. $this->files = $this->files_fallback( $this->root() );
  450. }
  451. if ( ! empty( $this->unreadable_files ) )
  452. $this->warning( $this->archive_method(), __( 'The following files are unreadable and couldn\'t be backed up: ', 'hmbkp' ) . implode( ', ', $this->unreadable_files ) );
  453. return $this->files;
  454. }
  455. /**
  456. * Fallback function for generating a filesystem
  457. * array
  458. *
  459. * Used if RecursiveDirectoryIterator::FOLLOW_SYMLINKS isn't available
  460. *
  461. * @access private
  462. * @param stromg $dir
  463. * @param array $files. (default: array())
  464. * @return array
  465. */
  466. private function files_fallback( $dir, $files = array() ) {
  467. $handle = opendir( $dir );
  468. $excludes = $this->exclude_string( 'regex' );
  469. while ( $file = readdir( $handle ) ) :
  470. // Ignore current dir and containing dir and any unreadable files or directories
  471. if ( $file == '.' || $file == '..' )
  472. continue;
  473. $filepath = $this->conform_dir( trailingslashit( $dir ) . $file );
  474. $file = str_ireplace( trailingslashit( $this->root() ), '', $filepath );
  475. if ( ! is_readable( $filepath ) ) {
  476. $this->unreadable_files[] = $filepath;
  477. continue;
  478. }
  479. // Skip the backups dir and any excluded paths
  480. if ( ( $excludes && preg_match( '(' . $excludes . ')', $file ) ) )
  481. continue;
  482. $files[] = $file;
  483. if ( is_dir( $filepath ) )
  484. $files = $this->files_fallback( $filepath, $files );
  485. endwhile;
  486. return $files;
  487. }
  488. private function load_pclzip() {
  489. // Load PclZip
  490. if ( ! defined( 'PCLZIP_TEMPORARY_DIR' ) )
  491. define( 'PCLZIP_TEMPORARY_DIR', trailingslashit( $this->path() ) );
  492. require_once( ABSPATH . 'wp-admin/includes/class-pclzip.php' );
  493. }
  494. /**
  495. * Attempt to work out the path to mysqldump
  496. *
  497. * @access public
  498. * @return bool
  499. */
  500. public function guess_mysqldump_command_path() {
  501. if ( ! $this->shell_exec_available() )
  502. return '';
  503. // List of possible mysqldump locations
  504. $mysqldump_locations = array(
  505. '/usr/local/bin/mysqldump',
  506. '/usr/local/mysql/bin/mysqldump',
  507. '/usr/mysql/bin/mysqldump',
  508. '/usr/bin/mysqldump',
  509. '/opt/local/lib/mysql6/bin/mysqldump',
  510. '/opt/local/lib/mysql5/bin/mysqldump',
  511. '/opt/local/lib/mysql4/bin/mysqldump',
  512. '/xampp/mysql/bin/mysqldump',
  513. '/Program Files/xampp/mysql/bin/mysqldump',
  514. '/Program Files/MySQL/MySQL Server 6.0/bin/mysqldump',
  515. '/Program Files/MySQL/MySQL Server 5.5/bin/mysqldump',
  516. '/Program Files/MySQL/MySQL Server 5.4/bin/mysqldump',
  517. '/Program Files/MySQL/MySQL Server 5.1/bin/mysqldump',
  518. '/Program Files/MySQL/MySQL Server 5.0/bin/mysqldump',
  519. '/Program Files/MySQL/MySQL Server 4.1/bin/mysqldump'
  520. );
  521. if ( is_null( shell_exec( 'hash mysqldump 2>&1' ) ) )
  522. return 'mysqldump';
  523. // Find the one which works
  524. foreach ( $mysqldump_locations as $location )
  525. if ( @file_exists( $this->conform_dir( $location ) ) )
  526. return $location;
  527. return '';
  528. }
  529. /**
  530. * Attempt to work out the path to the zip command
  531. *
  532. * @access public
  533. * @return bool
  534. */
  535. public function guess_zip_command_path() {
  536. // Check shell_exec is available and hasn't been explicitly bypassed
  537. if ( ! $this->shell_exec_available() )
  538. return '';
  539. // List of possible zip locations
  540. $zip_locations = array(
  541. '/usr/bin/zip'
  542. );
  543. if ( is_null( shell_exec( 'hash zip 2>&1' ) ) )
  544. return 'zip';
  545. // Find the one which works
  546. foreach ( $zip_locations as $location )
  547. if ( @file_exists( $this->conform_dir( $location ) ) )
  548. return $location;
  549. return '';
  550. }
  551. /**
  552. * Generate the exclude param string for the zip backup
  553. *
  554. * Takes the exclude rules and formats them for use with either
  555. * the shell zip command or pclzip
  556. *
  557. * @access public
  558. * @param string $context. (default: 'zip')
  559. * @return string
  560. */
  561. public function exclude_string( $context = 'zip' ) {
  562. // Return a comma separated list by default
  563. $separator = ', ';
  564. $wildcard = '';
  565. // The zip command
  566. if ( $context == 'zip' ) {
  567. $wildcard = '*';
  568. $separator = ' -x ';
  569. // The PclZip fallback library
  570. } elseif ( $context == 'regex' ) {
  571. $wildcard = '([\s\S]*?)';
  572. $separator = '|';
  573. }
  574. // Sanitize the excludes
  575. $excludes = array_filter( array_unique( array_map( 'trim', (array) $this->excludes ) ) );
  576. // If path() is inside root(), exclude it
  577. if ( strpos( $this->path(), $this->root() ) !== false )
  578. $excludes[] = trailingslashit( $this->path() );
  579. foreach( $excludes as $key => &$rule ) {
  580. $file = $absolute = $fragment = false;
  581. // Files don't end with /
  582. if ( ! in_array( substr( $rule, -1 ), array( '\\', '/' ) ) )
  583. $file = true;
  584. // If rule starts with a / then treat as absolute path
  585. elseif ( in_array( substr( $rule, 0, 1 ), array( '\\', '/' ) ) )
  586. $absolute = true;
  587. // Otherwise treat as dir fragment
  588. else
  589. $fragment = true;
  590. // Strip $this->root and conform
  591. $rule = str_ireplace( $this->root(), '', untrailingslashit( $this->conform_dir( $rule ) ) );
  592. // Strip the preceeding slash
  593. if ( in_array( substr( $rule, 0, 1 ), array( '\\', '/' ) ) )
  594. $rule = substr( $rule, 1 );
  595. // Escape string for regex
  596. if ( $context == 'regex' )
  597. $rule = str_replace( '.', '\.', $rule );
  598. // Convert any existing wildcards
  599. if ( $wildcard != '*' && strpos( $rule, '*' ) !== false )
  600. $rule = str_replace( '*', $wildcard, $rule );
  601. // Wrap directory fragments and files in wildcards for zip
  602. if ( $context == 'zip' && ( $fragment || $file ) )
  603. $rule = $wildcard . $rule . $wildcard;
  604. // Add a wildcard to the end of absolute url for zips
  605. if ( $context == 'zip' && $absolute )
  606. $rule .= $wildcard;
  607. // Add and end carrot to files for pclzip but only if it doesn't end in a wildcard
  608. if ( $file && $context == 'regex' )
  609. $rule .= '$';
  610. // Add a start carrot to absolute urls for pclzip
  611. if ( $absolute && $context == 'regex' )
  612. $rule = '^' . $rule;
  613. }
  614. // Escape shell args for zip command
  615. if ( $context == 'zip' )
  616. $excludes = array_map( 'escapeshellarg', array_unique( $excludes ) );
  617. return implode( $separator, $excludes );
  618. }
  619. /**
  620. * Check whether safe mode is active or not
  621. *
  622. * @access private
  623. * @return bool
  624. */
  625. public function is_safe_mode_active() {
  626. if ( $safe_mode = ini_get( 'safe_mode' ) && strtolower( $safe_mode ) != 'off' )
  627. return true;
  628. return false;
  629. }
  630. /**
  631. * Check whether shell_exec has been disabled.
  632. *
  633. * @access private
  634. * @return bool
  635. */
  636. private function shell_exec_available() {
  637. // Are we in Safe Mode
  638. if ( $this->is_safe_mode_active() )
  639. return false;
  640. // Is shell_exec disabled?
  641. if ( in_array( 'shell_exec', array_map( 'trim', explode( ',', ini_get( 'disable_functions' ) ) ) ) )
  642. return false;
  643. // Can we issue a simple command
  644. if ( ! @shell_exec( 'pwd' ) )
  645. return false;
  646. return true;
  647. }
  648. /**
  649. * Sanitize a directory path
  650. *
  651. * @access public
  652. * @param string $dir
  653. * @param bool $rel. (default: false)
  654. * @return string $dir
  655. */
  656. public function conform_dir( $dir, $recursive = false ) {
  657. // Assume empty dir is root
  658. if ( ! $dir )
  659. $dir = '/';
  660. // Replace single forward slash (looks like double slash because we have to escape it)
  661. $dir = str_replace( '\\', '/', $dir );
  662. $dir = str_replace( '//', '/', $dir );
  663. // Remove the trailing slash
  664. if ( $dir !== '/' )
  665. $dir = untrailingslashit( $dir );
  666. // Carry on until completely normalized
  667. if ( ! $recursive && $this->conform_dir( $dir, true ) != $dir )
  668. return $this->conform_dir( $dir );
  669. return (string) $dir;
  670. }
  671. /**
  672. * Add backquotes to tables and db-names inSQL queries. Taken from phpMyAdmin.
  673. *
  674. * @access private
  675. * @param mixed $a_name
  676. */
  677. private function sql_backquote( $a_name ) {
  678. if ( ! empty( $a_name ) && $a_name != '*' ) {
  679. if ( is_array( $a_name ) ) {
  680. $result = array();
  681. reset( $a_name );
  682. while ( list( $key, $val ) = each( $a_name ) )
  683. $result[$key] = '`' . $val . '`';
  684. return $result;
  685. } else {
  686. return '`' . $a_name . '`';
  687. }
  688. } else {
  689. return $a_name;
  690. }
  691. }
  692. /**
  693. * Reads the Database table in $table and creates
  694. * SQL Statements for recreating structure and data
  695. * Taken partially from phpMyAdmin and partially from
  696. * Alain Wolf, Zurich - Switzerland
  697. * Website: http://restkultur.ch/personal/wolf/scripts/db_backup/
  698. *
  699. * @access private
  700. * @param string $sql_file
  701. * @param string $table
  702. */
  703. private function make_sql( $sql_file, $table ) {
  704. // Add SQL statement to drop existing table
  705. $sql_file .= "\n";
  706. $sql_file .= "\n";
  707. $sql_file .= "#\n";
  708. $sql_file .= "# Delete any existing table " . $this->sql_backquote( $table ) . "\n";
  709. $sql_file .= "#\n";
  710. $sql_file .= "\n";
  711. $sql_file .= "DROP TABLE IF EXISTS " . $this->sql_backquote( $table ) . ";\n";
  712. /* Table Structure */
  713. // Comment in SQL-file
  714. $sql_file .= "\n";
  715. $sql_file .= "\n";
  716. $sql_file .= "#\n";
  717. $sql_file .= "# Table structure of table " . $this->sql_backquote( $table ) . "\n";
  718. $sql_file .= "#\n";
  719. $sql_file .= "\n";
  720. // Get table structure
  721. $query = 'SHOW CREATE TABLE ' . $this->sql_backquote( $table );
  722. $result = mysql_query( $query, $this->db );
  723. if ( $result ) {
  724. if ( mysql_num_rows( $result ) > 0 ) {
  725. $sql_create_arr = mysql_fetch_array( $result );
  726. $sql_file .= $sql_create_arr[1];
  727. }
  728. mysql_free_result( $result );
  729. $sql_file .= ' ;';
  730. }
  731. /* Table Contents */
  732. // Get table contents
  733. $query = 'SELECT * FROM ' . $this->sql_backquote( $table );
  734. $result = mysql_query( $query, $this->db );
  735. if ( $result ) {
  736. $fields_cnt = mysql_num_fields( $result );
  737. $rows_cnt = mysql_num_rows( $result );
  738. }
  739. // Comment in SQL-file
  740. $sql_file .= "\n";
  741. $sql_file .= "\n";
  742. $sql_file .= "#\n";
  743. $sql_file .= "# Data contents of table " . $table . " (" . $rows_cnt . " records)\n";
  744. $sql_file .= "#\n";
  745. // Checks whether the field is an integer or not
  746. for ( $j = 0; $j < $fields_cnt; $j++ ) {
  747. $field_set[$j] = $this->sql_backquote( mysql_field_name( $result, $j ) );
  748. $type = mysql_field_type( $result, $j );
  749. if ( $type == 'tinyint' || $type == 'smallint' || $type == 'mediumint' || $type == 'int' || $type == 'bigint' || $type == 'timestamp')
  750. $field_num[$j] = true;
  751. else
  752. $field_num[$j] = false;
  753. }
  754. // Sets the scheme
  755. $entries = 'INSERT INTO ' . $this->sql_backquote( $table ) . ' VALUES (';
  756. $search = array( '\x00', '\x0a', '\x0d', '\x1a' ); //\x08\\x09, not required
  757. $replace = array( '\0', '\n', '\r', '\Z' );
  758. $current_row = 0;
  759. $batch_write = 0;
  760. while ( $row = mysql_fetch_row( $result ) ) {
  761. $current_row++;
  762. // build the statement
  763. for ( $j = 0; $j < $fields_cnt; $j++ ) {
  764. if ( ! isset($row[$j] ) ) {
  765. $values[] = 'NULL';
  766. } elseif ( $row[$j] == '0' || $row[$j] != '' ) {
  767. // a number
  768. if ( $field_num[$j] )
  769. $values[] = $row[$j];
  770. else
  771. $values[] = "'" . str_replace( $search, $replace, $this->sql_addslashes( $row[$j] ) ) . "'";
  772. } else {
  773. $values[] = "''";
  774. }
  775. }
  776. $sql_file .= " \n" . $entries . implode( ', ', $values ) . ") ;";
  777. // write the rows in batches of 100
  778. if ( $batch_write == 100 ) {
  779. $batch_write = 0;
  780. $this->write_sql( $sql_file );
  781. $sql_file = '';
  782. }
  783. $batch_write++;
  784. unset( $values );
  785. }
  786. mysql_free_result( $result );
  787. // Create footer/closing comment in SQL-file
  788. $sql_file .= "\n";
  789. $sql_file .= "#\n";
  790. $sql_file .= "# End of data contents of table " . $table . "\n";
  791. $sql_file .= "# --------------------------------------------------------\n";
  792. $sql_file .= "\n";
  793. $this->write_sql( $sql_file );
  794. }
  795. /**
  796. * Better addslashes for SQL queries.
  797. * Taken from phpMyAdmin.
  798. *
  799. * @access private
  800. * @param string $a_string. (default: '')
  801. * @param bool $is_like. (default: false)
  802. */
  803. private function sql_addslashes( $a_string = '', $is_like = false ) {
  804. if ( $is_like )
  805. $a_string = str_replace( '\\', '\\\\\\\\', $a_string );
  806. else
  807. $a_string = str_replace( '\\', '\\\\', $a_string );
  808. $a_string = str_replace( '\'', '\\\'', $a_string );
  809. return $a_string;
  810. }
  811. /**
  812. * Write the SQL file
  813. *
  814. * @access private
  815. * @param string $sql
  816. */
  817. private function write_sql( $sql ) {
  818. $sqlname = $this->database_dump_filepath();
  819. // Actually write the sql file
  820. if ( is_writable( $sqlname ) || ! file_exists( $sqlname ) ) {
  821. if ( ! $handle = fopen( $sqlname, 'a' ) )
  822. return;
  823. if ( ! fwrite( $handle, $sql ) )
  824. return;
  825. fclose( $handle );
  826. return true;
  827. }
  828. }
  829. /**
  830. * Get the errors
  831. *
  832. * @access public
  833. * @return null
  834. */
  835. public function errors( $context = null ) {
  836. if ( ! empty( $context ) )
  837. return isset( $this->errors[$context] ) ? $this->errors[$context] : array();
  838. return $this->errors;
  839. }
  840. /**
  841. * Add an error to the errors stack
  842. *
  843. * @access private
  844. * @param string $context
  845. * @param mixed $error
  846. * @return null
  847. */
  848. private function error( $context, $error ) {
  849. if ( empty( $context ) || empty( $error ) )
  850. return;
  851. $this->errors[$context][$_key = md5( implode( ':' , (array) $error ) )] = $error;
  852. }
  853. /**
  854. * Migrate errors to warnings
  855. *
  856. * @access private
  857. * @param string $context. (default: null)
  858. * @return null
  859. */
  860. private function errors_to_warnings( $context = null ) {
  861. $errors = empty( $context ) ? $this->errors() : array( $context => $this->errors( $context ) );
  862. if ( empty( $errors ) )
  863. return;
  864. foreach ( $errors as $error_context => $errors )
  865. foreach( $errors as $error )
  866. $this->warning( $error_context, $error );
  867. if ( $context )
  868. unset( $this->errors[$context] );
  869. else
  870. $this->errors = array();
  871. }
  872. /**
  873. * Get the warnings
  874. *
  875. * @access public
  876. * @return null
  877. */
  878. public function warnings( $context = null ) {
  879. if ( ! empty( $context ) )
  880. return isset( $this->warnings[$context] ) ? $this->warnings[$context] : array();
  881. return $this->warnings;
  882. }
  883. /**
  884. * Add an warning to the warnings stack
  885. *
  886. * @access private
  887. * @param string $context
  888. * @param mixed $warning
  889. * @return null
  890. */
  891. private function warning( $context, $warning ) {
  892. if ( empty( $context ) || empty( $warning ) )
  893. return;
  894. $this->warnings[$context][$_key = md5( implode( ':' , (array) $warning ) )] = $warning;
  895. }
  896. /**
  897. * Custom error handler for catching errors
  898. *
  899. * @access private
  900. * @param string $type
  901. * @param string $message
  902. * @param string $file
  903. * @param string $line
  904. * @return null
  905. */
  906. public function error_handler( $type ) {
  907. if ( ( defined( 'E_DEPRECATED' ) && $type == E_DEPRECATED ) || ( defined( 'E_STRICT' ) && $type == E_STRICT ) || error_reporting() === 0 )
  908. return false;
  909. $args = func_get_args();
  910. $this->warning( 'php', array_splice( $args, 0, 4 ) );
  911. return false;
  912. }
  913. }
  914. /**
  915. * Add file callback for PclZip, excludes files
  916. * and sets the database dump to be stored in the root
  917. * of the zip
  918. *
  919. * @access private
  920. * @param string $event
  921. * @param array &$file
  922. * @return bool
  923. */
  924. function hmbkp_pclzip_callback( $event, &$file ) {
  925. global $_hmbkp_exclude_string;
  926. // Don't try to add unreadable files.
  927. if ( ! is_readable( $file['filename'] ) || ! file_exists( $file['filename'] ) )
  928. return false;
  929. // Match everything else past the exclude list
  930. elseif ( $_hmbkp_exclude_string && preg_match( '(' . $_hmbkp_exclude_string . ')', $file['stored_filename'] ) )
  931. return false;
  932. return true;
  933. }