$settings * @param string $keep File name that must survive (the backup just made), or ''. * @return array{deleted:string[],failed:string[],kept:int} */ public static function apply( array $settings, JobStore $store, string $keep = '' ): array { $result = array( 'deleted' => array(), 'failed' => array(), 'kept' => 0, ); $scheduled = ScheduleSettings::scheduledFiles(); $library = Library::all(); // newest first. $names = array_column( $library, 'file' ); // Forget names whose files are gone, so the list cannot grow without end. ScheduleSettings::setScheduledFiles( array_values( array_intersect( $scheduled, $names ) ) ); if ( empty( $settings['retention_enabled'] ) ) { $result['kept'] = count( $names ); return $result; } $limit = max( 1, (int) $settings['retention_max'] ); $scope = array(); foreach ( $library as $item ) { if ( ! empty( $settings['retention_manual'] ) || in_array( $item['file'], $scheduled, true ) ) { $scope[] = $item['file']; } } $in_use = self::inUse( $store ); $excess = array_slice( $scope, $limit ); // everything after the newest $limit, oldest last. foreach ( $excess as $file ) { if ( $file === $keep || in_array( (string) Library::path( $file ), $in_use, true ) ) { continue; } if ( Library::delete( $file ) ) { $result['deleted'][] = $file; } else { $result['failed'][] = $file; } } ScheduleSettings::setScheduledFiles( array_values( array_diff( array_intersect( $scheduled, $names ), $result['deleted'] ) ) ); $result['kept'] = count( $names ) - count( $result['deleted'] ); return $result; } /** * @return string[] Paths of archives an unfinished import is reading. */ private static function inUse( JobStore $store ): array { $paths = array(); foreach ( $store->ids() as $id ) { $job = $store->load( $id ); if ( null !== $job && ! $job->isTerminal() && is_string( $job->get( 'archive_path' ) ) && '' !== $job->get( 'archive_path' ) ) { $paths[] = (string) $job->get( 'archive_path' ); } } return $paths; } }