_" (see adcare_claim_nonce). */ define( 'ADCARE_NONCE', 'adcare_n_' ); define( 'ADCARE_NS', 'accessdossier-care/v1' ); /** Seconds a signed request stays valid, either side of the site's clock. */ define( 'ADCARE_WINDOW', 300 ); /** * True when the request carries a valid signature made with this site's connection key. * Signature = hex HMAC-SHA256( key, "GET\n\n" ), sent as X-ADCare-Signature with X-ADCare-Timestamp. * Every failure gives the same answer, so a stranger cannot tell a connected site from an unconnected one. * * @param WP_REST_Request $request The request. * @param string $extra More signed lines, as "\n" (empty for the status route). * @param string|null $key The key to check against; null = the connection key (status route). * @return true|WP_Error */ function adcare_verify_request( $request, $extra = '', $key = null ) { $deny = new WP_Error( 'adcare_unauthorized', 'Not authorized.', array( 'status' => 401 ) ); if ( null === $key ) { $key = (string) get_option( ADCARE_OPTION, '' ); $key = adcare_valid_key( $key ) ? $key : ''; } $ts = (string) $request->get_header( 'x_adcare_timestamp' ); $sig = strtolower( (string) $request->get_header( 'x_adcare_signature' ) ); if ( '' === $key || ! preg_match( '/^\d{1,12}\z/', $ts ) || ! preg_match( '/^[a-f0-9]{64}\z/', $sig ) ) { return $deny; } // A 5-minute window stops old replays. The status route answers the same read-only versions to a replay; the backup // route also signs a one-time nonce (adcare_verify_backup_request), so a replay inside the window is refused there. if ( abs( time() - (int) $ts ) > ADCARE_WINDOW ) { return $deny; } $expected = hash_hmac( 'sha256', $request->get_method() . "\n" . $request->get_route() . "\n" . $ts . $extra, $key ); return hash_equals( $expected, $sig ) ? true : $deny; } /** Plain text, capped, for anything read from plugin or theme headers (they are written by third parties). */ function adcare_text( $value ) { return substr( wp_strip_all_tags( (string) $value ), 0, 200 ); } /** * What Care sees: versions and pending updates only. No users, content, orders or form data. * * @return array */ function adcare_status() { global $wpdb, $wp_version; if ( ! function_exists( 'get_plugins' ) ) { require_once ABSPATH . 'wp-admin/includes/plugin.php'; } $core_updates = get_site_transient( 'update_core' ); $core_latest = null; if ( is_object( $core_updates ) && ! empty( $core_updates->updates ) ) { foreach ( $core_updates->updates as $u ) { // Core reads "current" (see find_core_update()); "version" is only a fallback for older stored offers. $offered = isset( $u->current ) ? $u->current : ( isset( $u->version ) ? $u->version : null ); if ( isset( $u->response ) && 'upgrade' === $u->response && null !== $offered ) { $core_latest = adcare_text( $offered ); break; } } } $plugin_updates = get_site_transient( 'update_plugins' ); $plugins = array(); foreach ( get_plugins() as $file => $data ) { $new = isset( $plugin_updates->response[ $file ]->new_version ) ? (string) $plugin_updates->response[ $file ]->new_version : null; $plugins[] = array( 'file' => $file, 'name' => adcare_text( $data['Name'] ), 'version' => adcare_text( $data['Version'] ), 'active' => is_plugin_active( $file ), 'update' => $new, ); } $theme_updates = get_site_transient( 'update_themes' ); $active_theme = get_stylesheet(); $themes = array(); foreach ( wp_get_themes() as $slug => $theme ) { $themes[] = array( 'slug' => $slug, 'name' => adcare_text( $theme->get( 'Name' ) ), 'version' => adcare_text( $theme->get( 'Version' ) ), 'active' => $slug === $active_theme, 'update' => isset( $theme_updates->response[ $slug ]['new_version'] ) ? (string) $theme_updates->response[ $slug ]['new_version'] : null, ); } return array( 'connector' => ADCARE_VERSION, 'site' => home_url( '/' ), 'checked' => gmdate( 'c' ), 'wordpress' => array( 'version' => $wp_version, 'update' => $core_latest, 'multisite' => is_multisite(), ), 'php' => PHP_VERSION, 'database' => $wpdb->db_version(), 'backups' => adcare_backups_allowed(), 'plugins' => $plugins, 'themes' => $themes, ); } add_action( 'rest_api_init', function () { register_rest_route( ADCARE_NS, '/status', array( 'methods' => 'GET', 'callback' => function () { $response = rest_ensure_response( adcare_status() ); // Never let a page cache or CDN hand this answer to an unsigned request. $response->header( 'Cache-Control', 'no-store, private, max-age=0' ); return $response; }, 'permission_callback' => 'adcare_verify_request', ) ); register_rest_route( ADCARE_NS, '/backup', array( 'methods' => 'GET', 'callback' => function ( $request ) { $q = $request->get_query_params(); $chunk = adcare_backup_chunk( (string) $q['part'], (string) ( $q['cursor'] ?? '' ) ); if ( is_wp_error( $chunk ) ) { return $chunk; } $response = rest_ensure_response( $chunk ); $response->header( 'Cache-Control', 'no-store, private, max-age=0' ); return $response; }, 'permission_callback' => 'adcare_verify_backup_request', ) ); } ); /** Settings > AccessDossier Care: paste the connection key, or disconnect. */ add_action( 'admin_menu', function () { add_options_page( 'AccessDossier Care', 'AccessDossier Care', 'manage_options', 'accessdossier-care', 'adcare_settings_page' ); } ); /** A connection key as Care makes it: "adc_" then 48 hex characters. */ function adcare_valid_key( $key ) { return (bool) preg_match( '/^adc_[a-f0-9]{48}\z/', (string) $key ); } /** * Applies the settings form. Returns "saved", "disconnected" or "invalid". Capability and nonce are checked by the caller. * * @param array $post The unslashed form fields. * @return string */ function adcare_apply_form( $post ) { if ( isset( $post['adcare_disconnect'] ) ) { delete_option( ADCARE_OPTION ); delete_option( ADCARE_BACKUPS ); delete_option( ADCARE_BACKUP_KEY ); return 'disconnected'; } $key = isset( $post['adcare_key'] ) ? strtolower( trim( sanitize_text_field( $post['adcare_key'] ) ) ) : ''; // An empty key box keeps the saved key, so the backups box can change without pasting the key again. if ( '' === $key && adcare_valid_key( get_option( ADCARE_OPTION, '' ) ) ) { $key = (string) get_option( ADCARE_OPTION ); } if ( ! adcare_valid_key( $key ) ) { return 'invalid'; } $bkey = isset( $post['adcare_backup_key'] ) ? strtolower( trim( sanitize_text_field( $post['adcare_backup_key'] ) ) ) : ''; if ( '' !== $bkey && ! adcare_valid_backup_key( $bkey ) ) { return 'invalid_backup_key'; } // A new connection key means Care made new keys: the saved backup key belongs to the old one, so it goes too. if ( (string) get_option( ADCARE_OPTION, '' ) !== $key ) { delete_option( ADCARE_BACKUP_KEY ); } update_option( ADCARE_OPTION, $key, false ); if ( '' !== $bkey ) { update_option( ADCARE_BACKUP_KEY, $bkey, false ); } $want = ! empty( $post['adcare_backups'] ); if ( $want && ! adcare_can_allow_backups() ) { update_option( ADCARE_BACKUPS, '0', false ); return 'backups_refused'; } if ( $want && ! adcare_valid_backup_key( get_option( ADCARE_BACKUP_KEY, '' ) ) ) { update_option( ADCARE_BACKUPS, '0', false ); return 'backup_key_needed'; } update_option( ADCARE_BACKUPS, $want ? '1' : '0', false ); return $want ? 'backups_on' : 'backups_off'; } /** A backup key as Care makes it: "adb_" then 48 hex characters. */ function adcare_valid_backup_key( $key ) { return (bool) preg_match( '/^adb_[a-f0-9]{48}\z/', (string) $key ); } /** Handles the settings form (admin only, nonce checked). */ add_action( 'admin_post_adcare_save', function () { if ( ! current_user_can( 'manage_options' ) ) { wp_die( esc_html__( 'You are not allowed to do that.', 'accessdossier-care' ) ); } check_admin_referer( 'adcare_save' ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- each field is sanitized in adcare_apply_form(). $result = adcare_apply_form( wp_unslash( $_POST ) ); wp_safe_redirect( add_query_arg( 'adcare', $result, admin_url( 'options-general.php?page=accessdossier-care' ) ) ); exit; } ); /** The settings screen. The saved key is never printed back. */ function adcare_settings_page() { if ( ! current_user_can( 'manage_options' ) ) { return; } $connected = '' !== (string) get_option( ADCARE_OPTION, '' ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only notice after our own redirect. $result = isset( $_GET['adcare'] ) ? sanitize_key( wp_unslash( $_GET['adcare'] ) ) : ''; $messages = array( 'backups_off' => array( 'success', __( 'Saved. Connected, and backups are off. AccessDossier Care can read this site\'s versions and updates.', 'accessdossier-care' ) ), 'backups_on' => array( 'success', __( 'Saved. Connected, and backups are on. AccessDossier Care makes a backup within a day.', 'accessdossier-care' ) ), 'backup_key_needed' => array( 'warning', __( 'Saved, but backups stay off: paste this site\'s backup key first. Find it on the site\'s page in AccessDossier Care (Show backup key).', 'accessdossier-care' ) ), 'invalid_backup_key' => array( 'error', __( 'That backup key does not look right. Copy it again from AccessDossier Care. It starts with adb_. Nothing was changed.', 'accessdossier-care' ) ), 'disconnected' => array( 'success', __( 'Disconnected. AccessDossier Care can no longer read this site.', 'accessdossier-care' ) ), 'backups_refused' => array( 'warning', __( 'Saved, but backups stay off: on a multisite network only a network admin on the main site can allow them.', 'accessdossier-care' ) ), 'invalid' => array( 'error', __( 'That key does not look right. Copy it again from AccessDossier Care. It starts with adc_.', 'accessdossier-care' ) ), ); ?>

' . esc_html__( 'Settings', 'accessdossier-care' ) . '' ); return $links; } ); /** On a network, only a network admin on the main site may allow backups (the copy holds the whole network). */ function adcare_can_allow_backups() { return ! is_multisite() || ( is_main_site() && current_user_can( 'manage_network_options' ) ); } /** True when this site's admin allowed backups (Settings > AccessDossier Care) and a backup key is saved. */ function adcare_backups_allowed() { return '1' === (string) get_option( ADCARE_BACKUPS, '0' ) && adcare_valid_backup_key( get_option( ADCARE_BACKUP_KEY, '' ) ); } /** Bytes of site data in one backup answer, and seconds of work per answer: small enough for shared hosts. */ define( 'ADCARE_CHUNK', 4194304 ); define( 'ADCARE_CHUNK_SECONDS', 10 ); /** The wp-content folders a backup copies. Nothing else under wp-content, and nothing above it. */ define( 'ADCARE_FOLDERS', array( 'plugins', 'themes', 'uploads' ) ); /** * The backup route's check: a valid signature that also covers the two query parameters, then the admin's yes. * Signed string: "GET\n\n\n\n". A bad part or cursor, or any other query parameter, * gets the same 401 as a bad signature. * * @param WP_REST_Request $request The request. * @return true|WP_Error */ function adcare_verify_backup_request( $request ) { $deny = new WP_Error( 'adcare_unauthorized', 'Not authorized.', array( 'status' => 401 ) ); $q = $request->get_query_params(); $part = isset( $q['part'] ) && is_string( $q['part'] ) ? $q['part'] : ''; $cursor = isset( $q['cursor'] ) && is_string( $q['cursor'] ) ? $q['cursor'] : ''; $nonce = strtolower( (string) $request->get_header( 'x_adcare_nonce' ) ); $extra = array_diff( array_keys( $q ), array( 'part', 'cursor', 'rest_route' ) ); $bkey = (string) get_option( ADCARE_BACKUP_KEY, '' ); if ( $extra || ! in_array( $part, array( 'db', 'files' ), true ) || ! adcare_valid_cursor( $cursor ) || ! preg_match( '/^[a-f0-9]{32}\z/', $nonce ) || ! adcare_valid_backup_key( $bkey ) ) { return $deny; } // Signed with the BACKUP key, never the connection key: the key that reads versions cannot export the site. $ok = adcare_verify_request( $request, "\n" . $nonce . "\n" . $part . "\n" . $cursor, $bkey ); if ( true !== $ok ) { return $ok; } if ( ! adcare_claim_nonce( (int) $request->get_header( 'x_adcare_timestamp' ), $nonce ) ) { return $deny; } // Only a signed caller (Care) learns that backups are off here. On a network, only the main site backs up (the whole // network shares one database and one wp-content, so a subsite cannot be copied on its own). if ( ! adcare_backups_allowed() || ( is_multisite() && ! is_main_site() ) ) { return new WP_Error( 'adcare_backups_off', 'Backups are not allowed on this site.', array( 'status' => 403 ) ); } return true; } /** * One use per signed (timestamp, nonce): a single INSERT IGNORE into the options table claims it, so two copies of one * request cannot both pass, even at the same instant, and no object cache can forget it. A failed write refuses * (fails closed). Rows whose timestamp is already outside the signing window are pruned, because the window check * refuses those requests anyway; the timestamp is in the row's name (zero-padded, so names sort by time). * * @param int $ts The signed timestamp (already checked to be inside the window). * @param string $nonce 32 lowercase hex characters (already checked). * @return bool True when this request is the first to use them. */ function adcare_claim_nonce( $ts, $nonce ) { global $wpdb; // phpcs:disable WordPress.DB.DirectDatabaseQuery -- an atomic claim; the options API has no insert-if-absent. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s AND option_name < %s", $wpdb->esc_like( ADCARE_NONCE ) . '%', ADCARE_NONCE . sprintf( '%012d', time() - ADCARE_WINDOW - 60 ) ) ); $n = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, '1', 'no')", ADCARE_NONCE . sprintf( '%012d', $ts ) . '_' . $nonce ) ); // phpcs:enable return 1 === $n; } /** A cursor is empty (start) or ":" or ":": printable, no newline, at most 1024 bytes. */ function adcare_valid_cursor( $cursor ) { return strlen( $cursor ) <= 1024 && ( '' === $cursor || (bool) preg_match( '/^[^\x00-\x1f\x7f]+\z/', $cursor ) ); } /** * One piece of a backup. Read-only: it only reads tables and files. * Answer: part, cursor, next (the cursor for the next piece, null when this part is done), data (base64), sha256 of * the bytes, and for files the entries (path, offset, length, size) the bytes belong to and how many could not be read. * * @param string $part "db" or "files". * @param string $cursor Where to start ("" for the beginning). * @param int $max Byte budget for this piece. * @return array|WP_Error */ function adcare_backup_chunk( $part, $cursor, $max = ADCARE_CHUNK ) { $until = microtime( true ) + ADCARE_CHUNK_SECONDS; $out = 'db' === $part ? adcare_db_chunk( $cursor, $max, $until ) : adcare_files_chunk( $cursor, $max, $until ); if ( is_wp_error( $out ) ) { return $out; } $data = $out['data']; unset( $out['data'] ); return array_merge( array( 'part' => $part, 'cursor' => $cursor, ), $out, array( 'sha256' => hash( 'sha256', $data ), 'data' => base64_encode( $data ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- binary-safe transport of the backup bytes. ) ); } /** MySQL string literal, binary-safe (the escapes of mysql_real_escape_string, so a value never holds a raw newline). */ function adcare_sql_value( $v ) { if ( null === $v ) { return 'NULL'; } return "'" . strtr( (string) $v, array( '\\' => '\\\\', "\0" => '\\0', "\n" => '\\n', "\r" => '\\r', "'" => "\\'", '"' => '\\"', "\x1a" => '\\Z', ) ) . "'"; } /** * Database piece: WordPress's own tables only (names starting with the site's table prefix), in name order; each table * starts with DROP TABLE IF EXISTS and its CREATE TABLE, then INSERTs in pages of 5 rows. The first piece starts like * mysqldump (character set, sql_mode, foreign key checks off). The connector's own key and backups setting are left out. * ponytail: rows are paged 5 at a time with LIMIT/OFFSET on a live database: a row added or removed * mid-backup can be missed or repeated, OFFSET slows on very large tables, and one page of huge rows can pass the byte * budget. Keyset paging on the primary key is the upgrade if drills on busy or large sites show it. */ function adcare_db_chunk( $cursor, $max, $until ) { global $wpdb; // phpcs:disable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- read-only backup reads; table names come from SHOW TABLES and are checked below. $tables = $wpdb->get_col( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $wpdb->base_prefix ) . '%' ) ); $tables = array_values( array_filter( $tables, function ( $t ) { return (bool) preg_match( '/^[A-Za-z0-9_$]+\z/', $t ); } ) ); sort( $tables, SORT_STRING ); if ( ! $tables ) { return new WP_Error( 'adcare_db_read', 'Could not read a table.', array( 'status' => 500 ) ); } $table = '' === $cursor ? $tables[0] : null; $row = 0; if ( '' !== $cursor ) { if ( ! preg_match( '/^([A-Za-z0-9_$]+):(\d{1,12})\z/', $cursor, $m ) || ! in_array( $m[1], $tables, true ) ) { return new WP_Error( 'adcare_bad_cursor', 'Unknown cursor.', array( 'status' => 400 ) ); } $table = $m[1]; $row = (int) $m[2]; } $data = ''; // The dump declares the connection's own character set; any other set is refused rather than mislabelled. if ( ! in_array( $wpdb->charset, array( 'utf8mb4', 'utf8', 'latin1' ), true ) ) { return new WP_Error( 'adcare_db_charset', 'Unsupported database encoding.', array( 'status' => 422 ) ); } if ( '' === $cursor ) { $cs = $wpdb->charset; $data .= "SET NAMES $cs;\nSET SESSION sql_mode = 'NO_AUTO_VALUE_ON_ZERO';\nSET FOREIGN_KEY_CHECKS = 0;\n"; } $own = array( ADCARE_OPTION, ADCARE_BACKUPS, ADCARE_BACKUP_KEY ); while ( null !== $table ) { $view = false; if ( 0 === $row ) { $create = $wpdb->get_row( "SHOW CREATE TABLE `$table`", ARRAY_N ); if ( ! isset( $create[1] ) ) { return new WP_Error( 'adcare_db_read', 'Could not read a table.', array( 'status' => 500 ) ); } // A view is not a table: no rows to copy, and its definition is left out. $view = 0 !== stripos( ltrim( $create[1] ), 'CREATE TABLE' ); if ( ! $view ) { $data .= "DROP TABLE IF EXISTS `$table`;\n" . $create[1] . ";\n"; } } // Page in primary key order (every column when there is none), so pages never overlap or skip on a still table. $order = ''; if ( ! $view ) { $desc = $wpdb->get_results( "DESCRIBE `$table`", ARRAY_A ); $pk = array_column( array_filter( (array) $desc, function ( $c ) { return 'PRI' === ( $c['Key'] ?? '' ); } ), 'Field' ); $cols = $pk ? $pk : array_column( (array) $desc, 'Field' ); if ( ! $cols ) { return new WP_Error( 'adcare_db_read', 'Could not read a table.', array( 'status' => 500 ) ); } $order = '`' . implode( '`,`', array_map( function ( $c ) { return str_replace( '`', '``', $c ); }, $cols ) ) . '`'; } // The backup's own nonce rows come and go in the options table while it is paged (adcare_claim_nonce): they are // left out of the query itself, so adding or pruning them never shifts the OFFSET of a real row. $where = ''; if ( ! $view && preg_match( '/options\z/', $table ) && in_array( 'option_name', array_column( (array) $desc, 'Field' ), true ) ) { $where = $wpdb->prepare( 'WHERE option_name NOT LIKE %s ', $wpdb->esc_like( ADCARE_NONCE ) . '%' ); } while ( ! $view ) { if ( strlen( $data ) >= $max || microtime( true ) > $until ) { return array( 'next' => "$table:$row", 'data' => $data ); } $rows = $wpdb->get_results( "SELECT * FROM `$table` {$where}ORDER BY $order LIMIT 5 OFFSET $row", ARRAY_A ); if ( null === $rows || '' !== $wpdb->last_error ) { return new WP_Error( 'adcare_db_read', 'Could not read a table.', array( 'status' => 500 ) ); } if ( ! $rows ) { break; } $cols = '`' . implode( '`,`', array_keys( $rows[0] ) ) . '`'; foreach ( $rows as $r ) { // Never copy the connection key: a restored copy must not be able to answer Care with this site's key. if ( isset( $r['option_name'] ) && in_array( $r['option_name'], $own, true ) && preg_match( '/options\z/', $table ) ) { $row++; continue; } $data .= "INSERT INTO `$table` ($cols) VALUES (" . implode( ',', array_map( 'adcare_sql_value', $r ) ) . ");\n"; $row++; if ( strlen( $data ) >= $max ) { return array( 'next' => "$table:$row", 'data' => $data ); } } } $at = array_search( $table, $tables, true ); $table = $tables[ $at + 1 ] ?? null; $row = 0; if ( null !== $table && ( strlen( $data ) >= $max || microtime( true ) > $until ) ) { return array( 'next' => "$table:0", 'data' => $data ); } } // phpcs:enable return array( 'next' => null, 'data' => $data ); } /** * Files and folders that hold or may hold secrets, never copied: any wp-config copy, env and key files, database dumps, * logs, editor leftovers, and other backup plugins' folders and archives (they hold wp-config.php and full dumps). * ponytail: a name list; an uploaded .zip outside those folders is copied as the media it usually is. */ function adcare_secret_name( $name ) { return (bool) preg_match( '/^(.*wp-config.*|\.env.*|\.htpasswd|\.git|\.svn|\.ssh|\.aws|\.npmrc|auth\.json|credentials.*\.json|service-account.*\.json|debug\.log|id_(rsa|dsa|ecdsa|ed25519).*|.*\.(pem|key|p12|pfx|ppk|jks|keystore|kdbx|p8|sql|sql\.gz|wpress|bak|old|orig|save|swp)|backwpup-.*|updraft|ai1wm-backups|backups-dup-.*|wpvivid.*|backup-guard|backupbuddy_backups|wp-staging.*|.*\.log)\z/is', $name ); } /** A name Care cannot store as a path (a backslash or a control character, a newline included). */ function adcare_odd_name( $name ) { return (bool) preg_match( '/[\x00-\x1f\x7f\\\\]/', $name ); } /** * The copied files under wp-content, as "folder/sub/name" paths, in a fixed order (names sorted at each level), starting * at $from (a path split into its names) when given. Yields false for each link or unreadable folder it skips, so * nothing outside wp-content is read and nothing is left out silently. */ function adcare_walk( $rel, $from ) { $dir = WP_CONTENT_DIR . ( '' === $rel ? '' : '/' . $rel ); $names = @scandir( $dir ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- an unreadable folder is reported, not fatal. if ( false === $names ) { yield false; return; } sort( $names, SORT_STRING ); foreach ( $names as $name ) { if ( '.' === $name || '..' === $name || ( '' === $rel && ! in_array( $name, ADCARE_FOLDERS, true ) ) ) { continue; } $sub = null; if ( $from ) { $c = strcmp( $name, $from[0] ); if ( $c < 0 ) { continue; } $sub = 0 === $c && count( $from ) > 1 ? array_slice( $from, 1 ) : null; $from = null; } // A name Care cannot store is skipped and counted (the backup says partial), before the secret list, so a newline // cannot hide anything (the list also matches across newlines: the s flag). Both come after the resume point, so a // later piece does not count a name again. if ( adcare_odd_name( $name ) ) { yield false; continue; } if ( adcare_secret_name( $name ) ) { continue; } $path = '' === $rel ? $name : $rel . '/' . $name; $full = WP_CONTENT_DIR . '/' . $path; // Never a link, at any level: a link could point outside wp-content. It is counted as skipped, so the backup // says it is partial. if ( is_link( $full ) ) { yield false; continue; } if ( is_dir( $full ) ) { yield from adcare_walk( $path, $sub ); } elseif ( is_file( $full ) ) { yield $path; } } } /** * Files piece: whole files and slices of large ones, up to $max bytes. The cursor ":" resumes inside a file. */ function adcare_files_chunk( $cursor, $max, $until ) { $from_path = ''; $from_byte = 0; if ( '' !== $cursor ) { if ( ! preg_match( '/^(\d{1,15}):(.+)\z/', $cursor, $m ) || in_array( '..', explode( '/', $m[2] ), true ) ) { return new WP_Error( 'adcare_bad_cursor', 'Unknown cursor.', array( 'status' => 400 ) ); } $from_byte = (int) $m[1]; $from_path = $m[2]; } $entries = array(); $data = ''; $skipped = 0; foreach ( adcare_walk( '', '' === $from_path ? null : explode( '/', $from_path ) ) as $path ) { if ( false === $path ) { $skipped++; continue; } if ( strlen( $data ) >= $max || count( $entries ) >= 2000 || microtime( true ) > $until ) { return array( 'next' => "0:$path", 'entries' => $entries, 'skipped' => $skipped, 'data' => $data ); } $full = WP_CONTENT_DIR . '/' . $path; $size = @filesize( $full ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged $fh = false === $size ? false : @fopen( $full, 'rb' ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- read-only streaming read. if ( false === $fh ) { $skipped++; continue; } // The path was checked for links on the way down; check where the open file really is, too. $real = realpath( $full ); $root = realpath( WP_CONTENT_DIR ); $open = fstat( $fh ); $now = false === $real ? false : @stat( $real ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged // The open handle must be the file at that real path (same device and inode), inside wp-content. if ( false === $real || false === $root || 0 !== strpos( $real, $root . DIRECTORY_SEPARATOR ) || ! $open || ! $now || $open['dev'] !== $now['dev'] || $open['ino'] !== $now['ino'] ) { fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose $skipped++; continue; } $at = $path === $from_path ? min( $from_byte, $size ) : 0; fseek( $fh, $at ); $want = (int) min( $max - strlen( $data ), $size - $at ); $bytes = $want > 0 ? (string) fread( $fh, $want ) : ''; // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fread fclose( $fh ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose $entries[] = array( 'path' => $path, 'offset' => $at, 'length' => strlen( $bytes ), 'size' => $size, ); $data .= $bytes; if ( $at + strlen( $bytes ) < $size ) { // The file was cut by the byte budget (or shrank while being read): the next piece resumes inside it. return array( 'next' => ( $at + strlen( $bytes ) ) . ":$path", 'entries' => $entries, 'skipped' => $skipped, 'data' => $data ); } } return array( 'next' => null, 'entries' => $entries, 'skipped' => $skipped, 'data' => $data ); }