base_dir(); if ( ! wp_mkdir_p( $dir ) ) { return null; } Paths::protect_dir( $dir ); $root = dirname( $dir ); if ( self::ROOT_DIR === basename( $root ) ) { Paths::protect_dir( $root ); } return $dir; } /** * Whether backups can be opened from the web, tested with a harmless file on this site. * * The answer comes from a real request, so the warning goes away once the server blocks * them. If the test cannot run, Nginx is assumed exposed because it ignores .htaccess. * * @param bool $recheck Whether to ignore the stored answer. * @return bool */ public function needs_server_rules( bool $recheck = false ): bool { $stored = get_transient( self::EXPOSURE_TRANSIENT ); if ( ! $recheck && false !== $stored ) { return 'yes' === $stored; } $exposed = $this->probe_exposure(); set_transient( self::EXPOSURE_TRANSIENT, $exposed ? 'yes' : 'no', HOUR_IN_SECONDS ); return $exposed; } /** * Whether this server is Nginx, for showing the right rule. * * @return bool */ public function is_nginx(): bool { $software = isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : ''; return false !== stripos( $software, 'nginx' ); } /** * Requests a probe file from the backup folder. * * @return bool */ private function probe_exposure(): bool { $dir = $this->ensure_dir(); if ( null === $dir ) { return false; } $uploads = wp_upload_dir( null, false ); $base = untrailingslashit( (string) $uploads['basedir'] ); if ( ! str_starts_with( $dir, $base . '/' ) ) { return false; } $content = 'pixelkeep-probe-' . wp_generate_password( 12, false, false ); $file = $dir . '/pixelkeep-probe.txt'; file_put_contents( $file, $content ); $response = wp_remote_get( (string) $uploads['baseurl'] . substr( $file, strlen( $base ) ), array( 'timeout' => 5, 'redirection' => 0, 'sslverify' => false, ) ); wp_delete_file( $file ); if ( is_wp_error( $response ) ) { return $this->is_nginx(); } return 200 === wp_remote_retrieve_response_code( $response ) && wp_remote_retrieve_body( $response ) === $content; } /** * Returns the existing backup for this master, or creates one. * * @param int $attachment_id Attachment ID. * @param string $master Absolute master path. * @param string $method Method about to be applied. * @param int|null $quality Quality about to be applied. * @param bool $reuse False when the master was replaced, so an old backup no longer applies. * @return array|WP_Error Backup record. */ public function ensure( int $attachment_id, string $master, string $method, ?int $quality, bool $reuse = true ): array|WP_Error { $existing = $this->state->get( $attachment_id )['backup'] ?? null; if ( $reuse && is_array( $existing ) && $this->record_is_for_master( $existing, $master ) && null !== $this->absolute_path( $existing ) ) { return $existing; } $dir = $this->ensure_dir(); if ( null === $dir || ! Paths::is_inside( $master ) ) { return new WP_Error( 'backup_failed', 'Backup directory unavailable.' ); } $bytes = (int) filesize( $master ); $free = function_exists( 'disk_free_space' ) ? disk_free_space( $dir ) : false; if ( false !== $free && $free < $bytes * 1.1 ) { return new WP_Error( 'disk_full', 'Not enough disk space.' ); } $relative = Paths::relative( $master ); $subdir = preg_match( '#^(\d{4}/\d{2})/#', $relative, $matches ) ? $matches[1] : gmdate( 'Y/m' ); if ( ! wp_mkdir_p( $dir . '/' . $subdir ) ) { return new WP_Error( 'backup_failed', 'Could not create backup folder.' ); } // An unrelated older backup of a replaced master is never overwritten. $target = $dir . '/' . $subdir . '/' . wp_unique_filename( $dir . '/' . $subdir, $attachment_id . '-' . wp_basename( $master ) ); $checksum = hash_file( 'sha256', $master ); $partial = $target . '.partial'; if ( false === $checksum || ! copy( $master, $partial ) ) { wp_delete_file( $partial ); return new WP_Error( 'backup_failed', 'Could not copy master.' ); } if ( hash_file( 'sha256', $partial ) !== $checksum || ! Paths::filesystem()->move( $partial, $target ) ) { wp_delete_file( $partial ); return new WP_Error( 'backup_failed', 'Backup verification failed.' ); } return array( 'path' => substr( $target, strlen( $dir ) + 1 ), 'master' => $relative, 'bytes' => $bytes, 'sha256' => $checksum, 'created_at' => current_time( 'mysql', true ), 'method' => $method, 'quality' => $quality, ); } /** * Resolves a record to an existing file inside the backup directory. * * @param array $record Backup record. * @return string|null Absolute path. */ public function absolute_path( array $record ): ?string { if ( empty( $record['path'] ) ) { return null; } $dir = $this->base_dir(); $path = $dir . '/' . ltrim( (string) $record['path'], '/' ); if ( ! is_file( $path ) || ! Paths::is_inside( $path, array( $dir ) ) ) { return null; } return $path; } /** * Whether a backup file still matches its recorded checksum. * * @param array $record Backup record. * @return bool */ public function verify( array $record ): bool { $path = $this->absolute_path( $record ); return null !== $path && hash_file( 'sha256', $path ) === ( $record['sha256'] ?? '' ); } /** * Whether a record belongs to this master path. * * @param array $record Backup record. * @param string $master Absolute master path. * @return bool */ public function record_is_for_master( array $record, string $master ): bool { return ( $record['master'] ?? '' ) === Paths::relative( $master ); } /** * Removes an attachment's backup, derivatives and records when the attachment is deleted. * * Tracked through the state, so other attachments' backups are never touched. * * @param int $attachment_id Attachment ID. * @return void */ public function on_delete_attachment( int $attachment_id ): void { $state = $this->state->get( $attachment_id ); if ( isset( $state['backup'] ) && is_array( $state['backup'] ) ) { $this->delete_file( $state['backup'] ); } $this->derivatives->delete_all( $attachment_id ); $this->stats->apply( $this->items->delete_attachment( $attachment_id ) ); } /** * Deletes backups older than the retention period. Runs from cron only. * * @return int Backups removed. */ public function prune_expired(): int { $days = $this->settings->int( 'retention_days' ); if ( $days <= 0 ) { return 0; } $cutoff = gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ); $removed = 0; foreach ( $this->items->attachments_with_backup_before( $cutoff, self::RETENTION_BATCH ) as $attachment_id ) { $state = $this->state->get( $attachment_id ); if ( isset( $state['backup'] ) && is_array( $state['backup'] ) ) { // The table's created_at can predate the backup, so check the record's own date. if ( ( $state['backup']['created_at'] ?? '' ) >= $cutoff ) { continue; } $this->delete_file( $state['backup'] ); unset( $state['backup'] ); $this->state->save( $attachment_id, $state ); ++$removed; } $this->items->clear_backup_path( $attachment_id ); $this->log->write( 'info', 'backup_expired', $attachment_id ); } return $removed; } /** * Deletes a backup file, refusing anything outside the backup directory. * * @param array $record Backup record. * @return void */ private function delete_file( array $record ): void { $path = $this->absolute_path( $record ); if ( null !== $path ) { wp_delete_file( $path ); } } }