PageRenderTime 41ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/wordpress/wp-content/plugins/backupbuddy/destinations/sftp/init.php

https://github.com/kronda/kronda
PHP | 279 lines | 209 code | 42 blank | 28 comment | 36 complexity | 4928f5efd64f782b9894613f93e348cb MD5 | raw file
  1. <?php
  2. // DO NOT CALL THIS CLASS DIRECTLY. CALL VIA: pb_backupbuddy_destination in bootstrap.php.
  3. class pb_backupbuddy_destination_sftp {
  4. public static $destination_info = array(
  5. 'name' => 'sFTP',
  6. 'description' => 'Secure File Transport Protocol (over SSH) is a more secure way of sending files between servers than FTP by using SSH. Web hosting accounts are more frequently providing this feature for greater security. This implementation is fully in PHP so PHP memory limits may be a limiting factor on some servers.',
  7. );
  8. // Default settings. Should be public static for auto-merging.
  9. public static $default_settings = array(
  10. 'type' => 'sftp', // MUST MATCH your destination slug.
  11. 'title' => '', // Required destination field.
  12. 'address' => '',
  13. 'username' => '',
  14. 'password' => '',
  15. 'path' => '',
  16. 'archive_limit' => 0,
  17. 'url' => '', // optional url for migration that corresponds to this sftp/path.
  18. );
  19. public static function _init() {
  20. //die( get_include_path() . PATH_SEPARATOR . 'phpseclib' );
  21. set_include_path(get_include_path() . PATH_SEPARATOR . pb_backupbuddy::plugin_path() . '/destinations/sftp/lib/phpseclib');
  22. require_once( pb_backupbuddy::plugin_path() . '/destinations/sftp/lib/phpseclib/Net/SFTP.php' );
  23. if ( '3' == pb_backupbuddy::$options['log_level'] ) { // Crank up logging level if in debug mode.
  24. define('NET_SFTP_LOGGING', NET_SFTP_LOG_COMPLEX);
  25. }
  26. } // end _init().
  27. /* send()
  28. *
  29. * Send one or more files.
  30. *
  31. * @param array $files Array of one or more files to send.
  32. * @return boolean True on success, else false.
  33. */
  34. public static function send( $settings = array(), $files = array(), $send_id = '' ) {
  35. pb_backupbuddy::status( 'details', 'FTP class send() function started.' );
  36. self::_init();
  37. // Connect to server.
  38. $server = $settings['address'];
  39. $port = '22'; // Default sFTP port.
  40. if ( strstr( $server, ':' ) ) { // Handle custom sFTP port.
  41. $server_params = explode( ':', $server );
  42. $server = $server_params[0];
  43. $port = $server_params[1];
  44. }
  45. pb_backupbuddy::status( 'details', 'Connecting to sFTP server...' );
  46. $sftp = new Net_SFTP( $server, $port );
  47. if ( ! $sftp->login( $settings['username'], $settings['password'] ) ) {
  48. pb_backupbuddy::status( 'error', 'Connection to sFTP server FAILED.' );
  49. pb_backupbuddy::status( 'details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.' );
  50. return false;
  51. } else {
  52. pb_backupbuddy::status( 'details', 'Success connecting to sFTP server.' );
  53. }
  54. pb_backupbuddy::status( 'details', 'Attempting to create path (if it does not exist)...' );
  55. if ( true === $sftp->mkdir( $settings['path'] ) ) { // Try to make directory.
  56. pb_backupbuddy::status( 'details', 'Directory created.' );
  57. } else {
  58. pb_backupbuddy::status( 'details', 'Directory not created.' );
  59. }
  60. // Change to directory.
  61. pb_backupbuddy::status( 'details', 'Attempting to change into directory...' );
  62. if ( true === $sftp->chdir( $settings['path'] ) ) {
  63. pb_backupbuddy::status( 'details', 'Changed into directory.' );
  64. } else {
  65. pb_backupbuddy::status( 'error', 'Unable to change into specified path. Verify the path is correct with valid permissions.' );
  66. pb_backupbuddy::status( 'details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.' );
  67. return false;
  68. }
  69. // Upload files.
  70. $total_transfer_size = 0;
  71. $total_transfer_time = 0;
  72. foreach( $files as $file ) {
  73. if ( ! file_exists( $file ) ) {
  74. pb_backupbuddy::status( 'error', 'Error #859485495. Could not upload local file `' . $file . '` to send to sFTP as it does not exist. Verify the file exists, permissions of file, parent directory, and that ownership is correct. You may need suphp installed on the server.' );
  75. }
  76. if ( ! is_readable( $file ) ) {
  77. pb_backupbuddy::status( 'error', 'Error #8594846548. Could not read local file `' . $file . '` to send to sFTP as it is not readable. Verify permissions of file, parent directory, and that ownership is correct. You may need suphp installed on the server.' );
  78. }
  79. $filesize = filesize( $file );
  80. $total_transfer_size += $filesize;
  81. $destination_file = $settings['path'] . '/' . basename( $file );
  82. pb_backupbuddy::status( 'details', 'About to put to sFTP local file `' . $file . '` of size `' . pb_backupbuddy::$format->file_size( $filesize ) . '` to remote file `' . $destination_file . '`.' );
  83. $send_time = -microtime( true );
  84. $upload = $sftp->put( $destination_file, $file, NET_SFTP_LOCAL_FILE );
  85. $send_time += microtime( true );
  86. $total_transfer_time += $send_time;
  87. if ( $upload === false ) { // Failed sending.
  88. $error_message = 'ERROR #9012 ( http://ithemes.com/codex/page/BackupBuddy:_Error_Codes#9012 ). sFTP file upload failed. Check file permissions & disk quota.';
  89. pb_backupbuddy::status( 'error', $error_message );
  90. backupbuddy_core::mail_error( $error_message );
  91. pb_backupbuddy::status( 'details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.' );
  92. return false;
  93. } else { // Success sending.
  94. pb_backupbuddy::status( 'details', 'Success completely sending `' . basename( $file ) . '` to destination.' );
  95. // Start remote backup limit
  96. if ( $settings['archive_limit'] > 0 ) {
  97. pb_backupbuddy::status( 'details', 'Archive limit enabled. Getting contents of backup directory.' );
  98. $contents = $sftp->rawlist( $settings['path'] ); // already in destination directory/path.
  99. // Create array of backups
  100. $bkupprefix = backupbuddy_core::backup_prefix();
  101. $backups = array();
  102. foreach ( $contents as $filename => $backup ) {
  103. // check if file is backup
  104. $pos = strpos( $filename, 'backup-' . $bkupprefix . '-' );
  105. if ( $pos !== FALSE ) {
  106. $backups[] = array(
  107. 'file' => $filename,
  108. 'modified' => $backup['mtime'],
  109. );
  110. }
  111. }
  112. function backupbuddy_number_sort( $a,$b ) {
  113. return $a['modified']<$b['modified'];
  114. }
  115. // Sort by modified using custom sort function above.
  116. usort( $backups, 'backupbuddy_number_sort' );
  117. if ( ( count( $backups ) ) > $settings['archive_limit'] ) {
  118. pb_backupbuddy::status( 'details', 'More backups found (' . count( $backups ) . ') than limit permits (' . $settings['archive_limit'] . ').' . print_r( $backups, true ) );
  119. $delete_fail_count = 0;
  120. $i = 0;
  121. foreach( $backups as $backup ) {
  122. $i++;
  123. if ( $i > $settings['archive_limit'] ) {
  124. if ( false === $sftp->delete( $settings['path'] . '/' . $backup['file'] ) ) {
  125. pb_backupbuddy::status( 'details', 'Unable to delete excess sFTP file `' . $backup['file'] . '` in path `' . $settings['path'] . '`.' );
  126. $delete_fail_count++;
  127. } else {
  128. pb_backupbuddy::status( 'details', 'Deleted excess sFTP file `' . $backup['file'] . '` in path `' . $settings['path'] . '`.' );
  129. }
  130. }
  131. }
  132. if ( $delete_fail_count != 0 ) {
  133. backupbuddy_core::mail_error( sprintf( __('sFTP remote limit could not delete %s backups. Please check and verify file permissions.', 'it-l10n-backupbuddy' ), $delete_fail_count ) );
  134. pb_backupbuddy::status( 'error', 'Unable to delete one or more excess backup archives. File storage limit may be exceeded. Manually clean up backups and check permissions.' );
  135. } else {
  136. pb_backupbuddy::status( 'details', 'No problems encountered deleting excess backups.' );
  137. }
  138. } else {
  139. pb_backupbuddy::status( 'details', 'Not enough backups found to exceed limit. Skipping limit enforcement.' );
  140. }
  141. } else {
  142. pb_backupbuddy::status( 'details', 'No sFTP archive file limit to enforce.' );
  143. }
  144. // End remote backup limit
  145. }
  146. } // end $files loop.
  147. // Load destination fileoptions.
  148. pb_backupbuddy::status( 'details', 'About to load fileoptions data.' );
  149. require_once( pb_backupbuddy::plugin_path() . '/classes/fileoptions.php' );
  150. $fileoptions_obj = new pb_backupbuddy_fileoptions( backupbuddy_core::getLogDirectory() . 'fileoptions/send-' . $send_id . '.txt', $read_only = false, $ignore_lock = false, $create_file = false );
  151. if ( true !== ( $result = $fileoptions_obj->is_ok() ) ) {
  152. pb_backupbuddy::status( 'error', __('Fatal Error #9034.843498. Unable to access fileoptions data.', 'it-l10n-backupbuddy' ) . ' Error: ' . $result );
  153. return false;
  154. }
  155. pb_backupbuddy::status( 'details', 'Fileoptions data loaded.' );
  156. $fileoptions = &$fileoptions_obj->options;
  157. // Save stats.
  158. $fileoptions['write_speed'] = $total_transfer_size / $total_transfer_time;
  159. $fileoptions_obj->save();
  160. unset( $fileoptions_obj );
  161. return true;
  162. } // End send().
  163. /* test()
  164. *
  165. * function description
  166. *
  167. * @param array $settings Destination settings.
  168. * @return bool|string True on success, string error message on failure.
  169. */
  170. public static function test( $settings ) {
  171. self::_init();
  172. // Connect to server.
  173. $server = $settings['address'];
  174. $port = '22'; // Default sFTP port.
  175. if ( strstr( $server, ':' ) ) { // Handle custom sFTP port.
  176. $server_params = explode( ':', $server );
  177. $server = $server_params[0];
  178. $port = $server_params[1];
  179. }
  180. pb_backupbuddy::status( 'details', 'Connecting to sFTP server...' );
  181. $sftp = new Net_SFTP( $server, $port );
  182. if ( ! $sftp->login( $settings['username'], $settings['password'] ) ) {
  183. pb_backupbuddy::status( 'error', 'Connection to sFTP server FAILED.' );
  184. pb_backupbuddy::status( 'details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.' );
  185. return __( 'Unable to connect to server using host, username, and password combination provided.', 'it-l10n-backupbuddy' );
  186. } else {
  187. pb_backupbuddy::status( 'details', 'Success connecting to sFTP server.' );
  188. }
  189. pb_backupbuddy::status( 'details', 'Attempting to create path (if it does not exist)...' );
  190. if ( true === $sftp->mkdir( $settings['path'] ) ) { // Try to make directory.
  191. pb_backupbuddy::status( 'details', 'Directory created.' );
  192. } else {
  193. pb_backupbuddy::status( 'details', 'Directory not created.' );
  194. }
  195. $destination_file = $settings['path'] . '/backupbuddy_test.txt';
  196. pb_backupbuddy::status( 'details', 'About to put to sFTP test file `backupbuddy_test.txt` to remote location `' . $destination_file . '`.' );
  197. $send_time = -microtime( true );
  198. if ( true !== $sftp->put( $destination_file, 'Upload test for BackupBuddy destination. Delete me.' ) ) {
  199. pb_backupbuddy::status( 'details', 'sFTP test: Failure uploading test file.' );
  200. $sftp->delete( $destination_file ); // Just in case it partionally made file. This has happened oddly.
  201. pb_backupbuddy::status( 'details', 'sFTP log (if available & enabled via full logging mode): `' . $sftp->getSFTPLog() . '`.' );
  202. return __('Failure uploading. Check path & permissions.', 'it-l10n-backupbuddy' );
  203. } else { // File uploaded.
  204. pb_backupbuddy::status( 'details', 'File uploaded.' );
  205. if ( $settings['url'] != '' ) {
  206. $response = wp_remote_get( rtrim( $settings['url'], '/\\' ) . '/backupbuddy_test.txt', array(
  207. 'method' => 'GET',
  208. 'timeout' => 20,
  209. 'redirection' => 5,
  210. 'httpversion' => '1.0',
  211. 'blocking' => true,
  212. 'headers' => array(),
  213. 'body' => null,
  214. 'cookies' => array()
  215. )
  216. );
  217. if ( is_wp_error( $response ) ) {
  218. return __( 'Failure. Unable to connect to the provided optional URL.', 'it-l10n-backupbuddy' );
  219. }
  220. if ( stristr( $response['body'], 'backupbuddy' ) === false ) {
  221. return __('Failure. The path appears valid but the URL does not correspond to it. Leave the URL blank if not using this destination for migrations.', 'it-l10n-backupbuddy' );
  222. }
  223. }
  224. pb_backupbuddy::status( 'details', 'sFTP test: Deleting temp test file.' );
  225. $sftp->delete( $destination_file );
  226. }
  227. return true; // Success if we got this far.
  228. } // End test().
  229. } // End class.