*/ public function orphans(): array { $base = $this->backups->base_dir(); if ( ! is_dir( $base ) ) { return array(); } $used = $this->referenced_paths(); $orphans = array(); foreach ( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $base, RecursiveDirectoryIterator::SKIP_DOTS ) ) as $file ) { if ( ! $file->isFile() || $file->isLink() || in_array( $file->getFilename(), array( '.htaccess', 'index.php' ), true ) ) { continue; } $relative = substr( (string) $file->getPathname(), strlen( $base ) + 1 ); if ( ! isset( $used[ $relative ] ) ) { $orphans[] = array( 'path' => $relative, 'bytes' => (int) $file->getSize(), 'size_label' => Format::bytes( (int) $file->getSize() ), 'modified' => (int) $file->getMTime(), ); } } usort( $orphans, static fn( $a, $b ) => strcmp( $a['path'], $b['path'] ) ); return $orphans; } /** * Deletes orphans the person confirmed, skipping anything that is no longer an orphan. * * @param string[] $paths Relative paths from orphans(). * @return int Files deleted. */ public function delete_orphans( array $paths ): int { $base = $this->backups->base_dir(); $current = array_column( $this->orphans(), 'path' ); $deleted = 0; foreach ( array_intersect( $paths, $current ) as $relative ) { $path = $base . '/' . $relative; if ( is_file( $path ) && ! is_link( $path ) && Paths::is_inside( $path, array( $base ) ) ) { wp_delete_file( $path ); ++$deleted; } } return $deleted; } /** * Verifies one page of backups against their recorded checksums. * * @param int $after_id Exclusive lower bound. * @return array{checked: int, problems: array, next: int} */ public function verify_page( int $after_id ): array { $ids = $this->items->attachments_with_backup( $after_id, self::PAGE_SIZE ); $checked = 0; $problems = array(); foreach ( $ids as $id ) { $record = $this->state->get( $id )['backup'] ?? null; if ( ! is_array( $record ) ) { continue; } ++$checked; if ( null === $this->backups->absolute_path( $record ) ) { $message = __( 'The backup file is missing.', 'pixelkeep' ); } elseif ( ! $this->backups->verify( $record ) ) { $message = __( 'The backup no longer matches its checksum.', 'pixelkeep' ); } else { continue; } $problems[] = array( 'id' => $id, 'title' => get_the_title( $id ), 'message' => $message, ); } return array( 'checked' => $checked, 'problems' => $problems, 'next' => count( $ids ) === self::PAGE_SIZE ? (int) end( $ids ) : 0, ); } /** * Collects every backup path attachments refer to. * * @return array */ private function referenced_paths(): array { global $wpdb; $used = array(); $values = $wpdb->get_col( $wpdb->prepare( "SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s", AttachmentState::META_STATE ) ); foreach ( is_array( $values ) ? $values : array() as $value ) { $state = maybe_unserialize( $value ); if ( is_array( $state ) && ! empty( $state['backup']['path'] ) ) { $used[ (string) $state['backup']['path'] ] = true; } } return $used; } }