'string', 'required' => true, ); $routes = array( '/status' => array( \WP_REST_Server::READABLE, 'status', array() ), '/backups' => array( \WP_REST_Server::READABLE, 'list_backups', array() ), '/sizes' => array( \WP_REST_Server::READABLE, 'sizes', array( 'fresh' => array( 'type' => 'boolean' ) ) ), '/activity' => array( \WP_REST_Server::READABLE, 'activity', array() ), '/backup' => array( \WP_REST_Server::CREATABLE, 'start_backup', array( 'name' => array( 'type' => 'string' ), 'options' => array( 'type' => 'object' ), ), ), '/cancel' => array( \WP_REST_Server::CREATABLE, 'cancel', array() ), '/delete' => array( \WP_REST_Server::CREATABLE, 'delete_backup', array( 'file' => $file ) ), '/download-link' => array( \WP_REST_Server::CREATABLE, 'download_link', array( 'file' => $file ) ), '/restore' => array( \WP_REST_Server::CREATABLE, 'start_restore', array( 'file' => $file, 'confirm' => array( 'type' => 'string', 'required' => true, ), ), ), '/import/start' => array( \WP_REST_Server::CREATABLE, 'import_start', array( 'filename' => $file, 'size' => array( 'type' => 'integer', 'required' => true, ), ), ), '/import/chunk' => array( \WP_REST_Server::CREATABLE, 'import_chunk', array() ), '/import/finish' => array( \WP_REST_Server::CREATABLE, 'import_finish', array( 'upload_id' => $file, 'filename' => $file, 'size' => array( 'type' => 'integer', 'required' => true, ), ), ), '/import/abort' => array( \WP_REST_Server::CREATABLE, 'import_abort', array( 'upload_id' => $file ) ), '/job/(?P\d+)' => array( \WP_REST_Server::READABLE, 'job', array() ), '/diagnostics' => array( \WP_REST_Server::READABLE, 'diagnostics', array() ), ); foreach ( $routes as $route => $definition ) { register_rest_route( self::NAMESPACE_V1, $route, array( 'methods' => $definition[0], 'callback' => array( $this, $definition[1] ), 'permission_callback' => $guard, 'args' => $definition[2], ) ); } } /** * Everything the admin screen needs on load. * * @return \WP_REST_Response */ public function status() { $jobs = new JobStore(); $jobs->reap(); $job = $jobs->latest(); $dir = PathGuard::backups_dir(); return rest_ensure_response( array( 'job' => $job ? $this->job_payload( $job ) : null, 'backups' => BackupStore::all(), 'default_name' => BackupStore::default_name(), 'environment' => array( 'zip' => class_exists( '\ZipArchive' ), 'zlib' => function_exists( 'deflate_init' ), 'folder' => is_wp_error( $dir ) ? '' : 'wp-content/' . basename( $dir ) . '/', 'folder_error' => is_wp_error( $dir ) ? $dir->get_error_message() : '', 'disk_free' => ( ! is_wp_error( $dir ) && function_exists( 'disk_free_space' ) ) ? (int) @disk_free_space( $dir ) : 0, 'chunk_bytes' => $this->chunk_bytes(), ), ) ); } /** * List backup archives. * * @return \WP_REST_Response */ public function list_backups() { return rest_ensure_response( array( 'backups' => BackupStore::all() ) ); } /** * Make a one-time download link for a backup. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function download_link( $request ) { $file = (string) $request->get_param( 'file' ); $path = BackupStore::path( $file ); if ( is_wp_error( $path ) ) { return $path; } $token = \SiteZip\Security\DownloadLinks::create( $file, get_current_user_id() ); return rest_ensure_response( array( 'url' => add_query_arg( array( 'action' => 'sitezip_download', 'token' => $token, ), admin_url( 'admin-post.php' ) ), 'expires' => \SiteZip\Security\DownloadLinks::TTL, ) ); } /** * Sizes for the "What to include" list. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response */ public function sizes( $request ) { return rest_ensure_response( \SiteZip\Backup\SiteInfo::get( (bool) $request->get_param( 'fresh' ) ) ); } /** * Start a backup. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function start_backup( $request ) { $id = ( new JobRunner() )->start_backup( (string) $request->get_param( 'name' ), (array) $request->get_param( 'options' ) ); return is_wp_error( $id ) ? $id : rest_ensure_response( array( 'job_id' => $id ) ); } /** * Cancel the running job. * * @return \WP_REST_Response */ public function cancel() { return rest_ensure_response( array( 'cancelled' => ( new JobRunner() )->cancel() ) ); } /** * Delete a backup archive. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function delete_backup( $request ) { $running = ( new JobStore() )->get_running(); $file = (string) $request->get_param( 'file' ); if ( $running && isset( $running['state']['file'] ) && $running['state']['file'] === $file ) { return new \WP_Error( 'sitezip_busy', __( 'That backup is in use by the running job.', 'sitezip' ), array( 'status' => 409 ) ); } $path = BackupStore::path( $file ); $size = is_wp_error( $path ) ? 0 : (int) filesize( $path ); $deleted = BackupStore::delete( $file ); if ( is_wp_error( $deleted ) ) { return $deleted; } /* translators: 1: backup file name, 2: size. */ ( new JobStore() )->record( 'delete', $file, sprintf( __( 'Deleted %1$s (%2$s).', 'sitezip' ), $file, size_format( $size, 1 ) ) ); return rest_ensure_response( array( 'deleted' => true ) ); } /** * Start a restore. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function start_restore( $request ) { // Restoring overwrites the live site, so the intent is confirmed // explicitly rather than inferred from a single click. if ( 'RESTORE' !== strtoupper( trim( (string) $request->get_param( 'confirm' ) ) ) ) { return new \WP_Error( 'sitezip_confirm', __( 'Type RESTORE to confirm. This overwrites your current site.', 'sitezip' ), array( 'status' => 400 ) ); } $key = ''; $id = ( new JobRunner() )->start_restore( (string) $request->get_param( 'file' ), $key ); return is_wp_error( $id ) ? $id : rest_ensure_response( array( 'job_id' => $id, 'resume' => $key, ) ); } /** * Begin a chunked upload of a backup archive. * * Uploads are split into chunks below upload_max_filesize and * post_max_size, so an archive of any size can be imported through * the browser without changing PHP limits. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function import_start( $request ) { if ( ! BackupStore::is_valid_filename( basename( (string) $request->get_param( 'filename' ) ) ) ) { return new \WP_Error( 'sitezip_not_zip', __( 'Choose a .zip backup file.', 'sitezip' ), array( 'status' => 400 ) ); } $size = (int) $request->get_param( 'size' ); $dir = PathGuard::backups_dir(); if ( is_wp_error( $dir ) ) { return $dir; } $free = function_exists( 'disk_free_space' ) ? @disk_free_space( $dir ) : false; if ( $free && $free < $size ) { return new \WP_Error( 'sitezip_disk', sprintf( /* translators: 1: file size, 2: free space. */ __( 'Not enough free disk space for this file (%1$s needed, %2$s available).', 'sitezip' ), size_format( $size ), size_format( $free ) ), array( 'status' => 507 ) ); } $upload_id = bin2hex( random_bytes( 16 ) ); $path = BackupStore::upload_path( $upload_id ); if ( is_wp_error( $path ) || false === @file_put_contents( $path, '' ) ) { return new \WP_Error( 'sitezip_upload', __( 'Could not create the upload file. Check that wp-content is writable.', 'sitezip' ), array( 'status' => 500 ) ); } return rest_ensure_response( array( 'upload_id' => $upload_id, 'chunk_bytes' => $this->chunk_bytes(), ) ); } /** * Receive one chunk. * * The client sends the byte offset of the chunk. Re-sending a chunk * (after a network error) is safe: the file is cut back to that offset * before the chunk is written. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function import_chunk( $request ) { $path = BackupStore::upload_path( (string) $request->get_param( 'upload_id' ) ); if ( is_wp_error( $path ) ) { return $path; } if ( ! is_file( $path ) ) { return new \WP_Error( 'sitezip_upload_gone', __( 'This upload has expired. Start it again.', 'sitezip' ), array( 'status' => 404 ) ); } $files = $request->get_file_params(); if ( empty( $files['chunk']['tmp_name'] ) || UPLOAD_ERR_OK !== (int) $files['chunk']['error'] || ! is_uploaded_file( $files['chunk']['tmp_name'] ) ) { return new \WP_Error( 'sitezip_chunk', __( 'A part of the upload did not arrive. Check the PHP upload limits.', 'sitezip' ), array( 'status' => 400 ) ); } clearstatcache( true, $path ); $offset = (int) $request->get_param( 'offset' ); $current = (int) filesize( $path ); if ( $offset < 0 || $offset > $current ) { return new \WP_Error( 'sitezip_offset', __( 'Upload out of order.', 'sitezip' ), array( 'status' => 409, 'received' => $current ) ); } $out = @fopen( $path, 'c+b' ); $in = @fopen( $files['chunk']['tmp_name'], 'rb' ); if ( ! $out || ! $in ) { return new \WP_Error( 'sitezip_upload', __( 'Could not write the uploaded data.', 'sitezip' ), array( 'status' => 500 ) ); } ftruncate( $out, $offset ); fseek( $out, $offset ); $copied = stream_copy_to_stream( $in, $out ); fclose( $in ); fclose( $out ); if ( false === $copied || (int) $copied !== (int) $files['chunk']['size'] ) { return new \WP_Error( 'sitezip_upload', __( 'Could not write the uploaded data. The disk may be full.', 'sitezip' ), array( 'status' => 507 ) ); } return rest_ensure_response( array( 'received' => $offset + (int) $copied ) ); } /** * Verify a finished upload and add it to the backup list. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function import_finish( $request ) { $path = BackupStore::upload_path( (string) $request->get_param( 'upload_id' ) ); if ( is_wp_error( $path ) ) { return $path; } if ( ! is_file( $path ) ) { return new \WP_Error( 'sitezip_upload_gone', __( 'This upload has expired. Start it again.', 'sitezip' ), array( 'status' => 404 ) ); } clearstatcache( true, $path ); if ( (int) filesize( $path ) !== (int) $request->get_param( 'size' ) ) { @unlink( $path ); return new \WP_Error( 'sitezip_upload_size', __( 'The uploaded file is incomplete. Please try again.', 'sitezip' ), array( 'status' => 400 ) ); } if ( ! BackupStore::manifest( $path ) ) { @unlink( $path ); return new \WP_Error( 'sitezip_not_backup', __( 'That zip file is not a SiteZip archive.', 'sitezip' ), array( 'status' => 400 ) ); } $file = BackupStore::unique_filename( basename( (string) $request->get_param( 'filename' ) ) ); if ( is_wp_error( $file ) ) { return $file; } // A leftover fingerprint for a deleted file of the same name must not // be checked against this upload. @unlink( BackupStore::sum_path( dirname( $path ) . '/' . $file ) ); if ( ! @rename( $path, dirname( $path ) . '/' . $file ) ) { @unlink( $path ); return new \WP_Error( 'sitezip_upload', __( 'Could not save the uploaded backup.', 'sitezip' ), array( 'status' => 500 ) ); } /* translators: 1: backup file name, 2: size. */ ( new JobStore() )->record( 'import', $file, sprintf( __( 'Imported %1$s (%2$s).', 'sitezip' ), $file, size_format( (int) $request->get_param( 'size' ), 1 ) ) ); return rest_ensure_response( array( 'file' => $file ) ); } /** * Recent backups, restores, imports and deletions. * * @return \WP_REST_Response */ public function activity() { $items = array(); foreach ( ( new JobStore() )->recent( 30 ) as $job ) { $items[] = array( 'id' => (int) $job['id'], 'type' => $job['type'], 'status' => $job['status'], 'file' => isset( $job['state']['file'] ) ? (string) $job['state']['file'] : '', 'created' => $job['created_at'], 'updated' => $job['updated_at'], 'error' => (string) $job['error'], 'log' => (string) $job['log'], ); } return rest_ensure_response( array( 'items' => $items ) ); } /** * Discard an unfinished upload. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function import_abort( $request ) { $path = BackupStore::upload_path( (string) $request->get_param( 'upload_id' ) ); if ( is_wp_error( $path ) ) { return $path; } if ( is_file( $path ) ) { @unlink( $path ); } return rest_ensure_response( array( 'aborted' => true ) ); } /** * Server facts for troubleshooting a backup that does not move. * * Tests the same loopback the step engine uses, with and without the * forwarded HTTP auth, and reports the latest job's raw state. * * @return \WP_REST_Response */ public function diagnostics() { global $wp_version; $probe = static function ( $url, $args ) { $start = microtime( true ); $res = wp_remote_post( $url, $args + array( 'timeout' => 15, 'sslverify' => false ) ); $out = array( 'ms' => (int) ( 1000 * ( microtime( true ) - $start ) ) ); if ( is_wp_error( $res ) ) { $out['error'] = $res->get_error_message(); } else { $out['code'] = (int) wp_remote_retrieve_response_code( $res ); $out['body'] = substr( wp_strip_all_tags( (string) wp_remote_retrieve_body( $res ) ), 0, 200 ); } return $out; }; $ajax = admin_url( 'admin-ajax.php' ); $body = array( 'action' => 'sitezip_run', 'job' => 0, 'token' => 'diagnostics', ); $headers = JobRunner::loopback_headers(); $dir = PathGuard::backups_dir(); $job = ( new JobStore() )->latest(); $latest = null; if ( $job ) { $updated = strtotime( $job['updated_at'] . ' UTC' ); $log = array_filter( explode( "\n", (string) $job['log'] ) ); $latest = array( 'id' => (int) $job['id'], 'type' => $job['type'], 'status' => $job['status'], 'stage' => $job['stage'], 'progress' => (int) $job['progress'], 'error' => $job['error'], 'created' => $job['created_at'], 'updated' => $job['updated_at'], 'seconds_idle' => $updated ? time() - $updated : null, 'lock' => get_option( 'sitezip_lock_' . (int) $job['id'], false ), 'browser_driven' => JobRunner::is_browser_driven( (int) $job['id'] ), 'cron_next' => wp_next_scheduled( 'sitezip_run_job', array( (int) $job['id'] ) ), 'log_tail' => array_slice( $log, -15 ), ); } // phpcs:disable WordPress.Security.ValidatedSanitizedInput -- only checked for presence, never output. return rest_ensure_response( array( 'plugin' => SITEZIP_VERSION, 'wp' => $wp_version, 'php' => PHP_VERSION, 'sapi' => PHP_SAPI, 'server' => isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : '', 'max_execution' => ini_get( 'max_execution_time' ), 'memory_limit' => ini_get( 'memory_limit' ), 'disabled_funcs' => ini_get( 'disable_functions' ), 'zip' => class_exists( '\ZipArchive' ), 'home' => home_url(), 'ajax_url' => $ajax, 'auth_seen' => array( 'php_auth_user' => isset( $_SERVER['PHP_AUTH_USER'] ), 'http_auth' => ! empty( $_SERVER['HTTP_AUTHORIZATION'] ), 'redirect_auth' => ! empty( $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ), 'remote_user' => ! empty( $_SERVER['REMOTE_USER'] ), ), 'backups_dir' => is_wp_error( $dir ) ? $dir->get_error_message() : $dir, 'dir_writable' => ! is_wp_error( $dir ) && wp_is_writable( $dir ), 'disk_free' => ( ! is_wp_error( $dir ) && function_exists( 'disk_free_space' ) ) ? size_format( (int) @disk_free_space( $dir ) ) : null, 'disable_wp_cron' => defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON, 'alternate_wp_cron' => defined( 'ALTERNATE_WP_CRON' ) && ALTERNATE_WP_CRON, // Expect code 403 from this plugin: it means the loopback got through. 'loopback_with_auth' => $probe( $ajax, array( 'body' => $body, 'headers' => $headers ) ), 'loopback_no_auth' => $probe( $ajax, array( 'body' => $body ) ), 'cron_url' => $probe( site_url( 'wp-cron.php?doing_wp_cron=' . time() ), array( 'headers' => $headers ) ), 'latest_job' => $latest, 'trace' => get_option( 'sitezip_trace' ), ) ); // phpcs:enable WordPress.Security.ValidatedSanitizedInput } /** * Poll a job. * * @param \WP_REST_Request $request Request. * @return \WP_REST_Response|\WP_Error */ public function job( $request ) { $store = new JobStore(); $store->reap(); $job = $store->get( (int) $request->get_param( 'id' ) ); if ( ! $job ) { return new \WP_Error( 'sitezip_not_found', __( 'That job does not exist.', 'sitezip' ), array( 'status' => 404 ) ); } if ( ( new JobRunner() )->nudge( $job ) ) { $job = $store->get( (int) $job['id'] ); } return rest_ensure_response( $this->job_payload( $job ) ); } /** * Bytes done and expected for the current stage, for "X of Y" text. * * @param array $job Job row. * @return int[] Done, expected (0 when unknown). */ public static function progress_bytes( array $job ) { $s = $job['state']; if ( 'backup' === $job['type'] ) { $done = isset( $s['files']['bytes'] ) ? (int) $s['files']['bytes'] : ( isset( $s['file_bytes'] ) ? (int) $s['file_bytes'] : 0 ); return array( $done, isset( $s['options']['expect_files'] ) ? (int) $s['options']['expect_files'] : 0 ); } if ( 'verify' === $job['stage'] && ! empty( $s['sum']['size'] ) ) { return array( (int) $s['sum']['pos'], (int) $s['sum']['size'] ); } if ( 'extract' === $job['stage'] && ! empty( $s['bytes_total'] ) ) { return array( (int) $s['bytes_done'], (int) $s['bytes_total'] ); } if ( 'import' === $job['stage'] && isset( $s['cursor']['total'] ) ) { return array( (int) $s['cursor']['done'], (int) $s['cursor']['total'] ); } return array( 0, 0 ); } /** * Shape a job row for the UI. * * @param array $job Job row. * @return array */ private function job_payload( array $job ) { $state = $job['state']; $detail = ''; if ( 'backup' === $job['type'] && ! empty( $state['zip']['offset'] ) ) { $files = isset( $state['files']['count'] ) ? (int) $state['files']['count'] : ( isset( $state['file_count'] ) ? (int) $state['file_count'] : 0 ); $detail = sprintf( /* translators: 1: number of files, 2: archive size so far. */ __( '%1$s files ยท %2$s written', 'sitezip' ), number_format_i18n( $files ), size_format( (int) $state['zip']['offset'], 1 ) ); } elseif ( 'restore' === $job['type'] && 'extract' === $job['stage'] && ! empty( $state['entries'] ) ) { $detail = sprintf( /* translators: 1: entries extracted, 2: total entries. */ __( '%1$s of %2$s files', 'sitezip' ), number_format_i18n( (int) $state['cursor'] ), number_format_i18n( (int) $state['entries'] ) ); } return array( 'id' => (int) $job['id'], 'type' => $job['type'], 'status' => $job['status'], 'stage' => $job['stage'], 'progress' => (int) $job['progress'], 'detail' => $detail, 'bytes' => self::progress_bytes( $job )[0], 'expect' => self::progress_bytes( $job )[1], 'file' => isset( $state['file'] ) ? $state['file'] : '', 'error' => $job['error'], 'log' => $job['log'], 'started' => $job['created_at'], 'updated' => $job['updated_at'], 'inline' => JobRunner::is_browser_driven( (int) $job['id'] ), ); } /** * Upload chunk size that fits under this server's PHP limits. * * @return int */ private function chunk_bytes() { $limit = (int) wp_max_upload_size(); $chunk = (int) floor( $limit * 0.8 ); return max( 65536, min( 64 * MB_IN_BYTES, $chunk ) ); } }