prefix . WP360_MC_TABLE; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE {$table_name} ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, attachment_id BIGINT UNSIGNED NULL, original_relative_path VARCHAR(500) NOT NULL, file_size BIGINT UNSIGNED NOT NULL DEFAULT 0, reason VARCHAR(30) NOT NULL, status VARCHAR(20) NOT NULL DEFAULT 'legacy', moved_at DATETIME NOT NULL, PRIMARY KEY (id), KEY status (status), KEY attachment_id (attachment_id) ) {$charset_collate};"; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; dbDelta( $sql ); self::legacy_dir_path(); self::original_legacy_dir_path(); } /** Legt (falls noetig) einen Ordner mit PHP-Ausfuehrungsschutz an und gibt seinen Pfad zurueck. */ private static function prepare_dir( $dir ) { if ( ! is_dir( $dir ) ) { wp_mkdir_p( $dir ); } $filesystem = self::filesystem(); $htaccess = $dir . '/.htaccess'; if ( ! $filesystem->exists( $htaccess ) ) { $filesystem->put_contents( $htaccess, "\n\tRequire all denied\n\n", FS_CHMOD_FILE ); } return $dir; } /** Absoluter Pfad zu wp-content/uploads-legacy (Aufraeum-Funde). */ public static function legacy_dir_path() { $upload_dir = wp_get_upload_dir(); return self::prepare_dir( trailingslashit( dirname( $upload_dir['basedir'] ) ) . 'uploads-legacy' ); } /** Absoluter Pfad zu wp-content/uploads-original-legacy (Backups verkleinerter Originale). */ public static function original_legacy_dir_path() { $upload_dir = wp_get_upload_dir(); return self::prepare_dir( trailingslashit( dirname( $upload_dir['basedir'] ) ) . 'uploads-original-legacy' ); } /** Welcher Legacy-Ordner fuer einen gegebenen Grund zustaendig ist. */ private static function bucket_dir_for_reason( $reason ) { return $reason === self::ORIGINAL_BACKUP_REASON ? self::original_legacy_dir_path() : self::legacy_dir_path(); } /** * Dateisystem-Zugriff ueber die WP_Filesystem-API. Bei der Methode "direct" * (Normalfall, auch in AJAX- und WP-CLI-Requests) wird das globale * $wp_filesystem per WP_Filesystem() initialisiert. Verlangt die Seite FTP/SSH * (keine direkten Schreibrechte fuer wp-content), liesse sich ohne * Zugangsdaten-Dialog keine Verbindung aufbauen und die Pfade passten nicht * zum FTP-Root -- dann wird eine eigene WP_Filesystem_Direct-Instanz genutzt, * die genau wie bisher mit den PHP-Rechten arbeitet, statt den Scan * abzubrechen. * * @return WP_Filesystem_Base */ private static function filesystem() { global $wp_filesystem; if ( null !== self::$filesystem ) { return self::$filesystem; } if ( ! function_exists( 'WP_Filesystem' ) ) { require_once ABSPATH . 'wp-admin/includes/file.php'; } $context = self::uploads_dir_path(); if ( 'direct' === get_filesystem_method( array(), $context ) && WP_Filesystem( false, $context ) && $wp_filesystem instanceof WP_Filesystem_Direct ) { self::$filesystem = $wp_filesystem; return self::$filesystem; } require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php'; require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-direct.php'; // Dieselben Standardrechte, die WP_Filesystem() sonst setzt; copy() braucht sie. if ( ! defined( 'FS_CHMOD_DIR' ) ) { define( 'FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- WP-Core-Konstante, gleicher Standardwert wie in WP_Filesystem(). } if ( ! defined( 'FS_CHMOD_FILE' ) ) { define( 'FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- WP-Core-Konstante, gleicher Standardwert wie in WP_Filesystem(). } self::$filesystem = new WP_Filesystem_Direct( null ); return self::$filesystem; } /** * Verschiebt eine einzelne Datei (ueberschreibt ein vorhandenes Ziel, wie * rename()). WP_Filesystem_Direct::move() versucht erst rename() und faellt * dann auf copy+delete zurueck, meldet aber auch dann Erfolg, wenn die Quelle * nicht geloescht werden konnte. Liegt die Quelle danach noch da, wird die * Kopie am Ziel entfernt und false zurueckgegeben -- die Datei soll nie * doppelt vorhanden sein. * * @param string $source Absoluter Quellpfad. * @param string $target Absoluter Zielpfad. * @return bool */ private static function move_file( $source, $target ) { if ( ! self::filesystem()->move( $source, $target, true ) ) { return false; } if ( file_exists( $source ) ) { wp_delete_file( $target ); return false; } return true; } /** Absoluter Pfad zu wp-content/uploads. */ public static function uploads_dir_path() { $upload_dir = wp_get_upload_dir(); return $upload_dir['basedir']; } /** * Verschiebt eine Datei von uploads/$relative_path in den fuer $reason * zustaendigen Legacy-Ordner und legt die Tracking-Zeile an. Gibt die neue * ID zurueck oder false bei Fehler. * * @param string $relative_path Pfad relativ zu uploads/, z. B. "2026/09/foo.jpg". * @param int|null $attachment_id Zugehoerige Attachment-ID, falls vorhanden. * @param string $reason 'unused_attachment' | 'orphaned_size' | 'filesystem_orphan' | 'downscaled_original'. */ public static function move_to_legacy( $relative_path, $attachment_id, $reason ) { global $wpdb; // Pfade stammen u. a. aus _wp_attached_file und den Attachment- // Metadaten; ein "../" darin fuehrte aus uploads/ hinaus. if ( preg_match( '#(^|[/\\\\])\.\.([/\\\\]|$)#', $relative_path ) ) { return false; } $source = trailingslashit( self::uploads_dir_path() ) . ltrim( $relative_path, '/' ); if ( ! is_file( $source ) || is_link( $source ) ) { return false; } $target = trailingslashit( self::bucket_dir_for_reason( $reason ) ) . ltrim( $relative_path, '/' ); wp_mkdir_p( dirname( $target ) ); $size = filesize( $source ); // move_file() versucht erst rename() und faellt z. B. beim Verschieben // ueber Dateisystem-/Mount-Grenzen hinweg (cross-device link) auf // copy+delete zurueck, statt den Verschiebe-Vorgang fuer diese Datei // stillschweigend abzubrechen. Bleibt einer der beiden Schritte auf // halbem Weg stecken, wird die Kopie am Ziel wieder entfernt: entweder // die Datei landet vollstaendig im Legacy-Ordner, oder sie bleibt // unveraendert an der Quelle -- nie doppelt vorhanden. if ( ! self::move_file( $source, $target ) ) { wp_delete_file( $target ); ++self::$failed_moves; error_log(sprintf('[360degrees Media Cleaner] Verschieben fehlgeschlagen: %s -> %s', $source, $target)); // phpcs:ignore return false; } $inserted = $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- eigene Tracking-Tabelle, dafuer gibt es keine WP-API. $wpdb->prefix . WP360_MC_TABLE, array( 'attachment_id' => $attachment_id ? (int) $attachment_id : null, 'original_relative_path' => $relative_path, 'file_size' => (int) $size, 'reason' => $reason, 'status' => 'legacy', 'moved_at' => current_time( 'mysql' ), ), array( '%d', '%s', '%d', '%s', '%s', '%s' ) ); // Ohne Tracking-Zeile (z. B. Tabelle fehlt) liesse sich die Datei nie // wiederherstellen -- dann lieber zurueck an ihren Platz. if ( false === $inserted ) { self::move_file( $target, $source ); ++self::$failed_moves; return false; } return (int) $wpdb->insert_id; } /** Schiebt einen Tracking-Eintrag aus seinem Legacy-Ordner zurueck nach uploads. */ public static function restore( $item_id ) { global $wpdb; $item = self::get_item( $item_id ); if ( ! $item ) { return false; } $source = trailingslashit( self::bucket_dir_for_reason( $item->reason ) ) . ltrim( $item->original_relative_path, '/' ); $target = trailingslashit( self::uploads_dir_path() ) . ltrim( $item->original_relative_path, '/' ); if ( ! is_file( $source ) ) { // Datei fehlt bereits (manuell geloescht?) -- Tracking-Zeile trotzdem aufraeumen. $wpdb->delete( $wpdb->prefix . WP360_MC_TABLE, array( 'id' => $item_id ), array( '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- eigene Tracking-Tabelle, dafuer gibt es keine WP-API; nichts davon wird gecacht. return false; } wp_mkdir_p( dirname( $target ) ); // Bei einem verkleinerten Original liegt an der Zielposition bereits die // verkleinerte Ersatzdatei -- die muss weichen, damit das Original // zurueck an ihren Platz kann. if ( $item->reason === self::ORIGINAL_BACKUP_REASON && is_file( $target ) ) { wp_delete_file( $target ); } if ( ! self::move_file( $source, $target ) ) { return false; } if ( $item->reason === self::ORIGINAL_BACKUP_REASON && $item->attachment_id ) { self::refresh_attachment_dimensions( (int) $item->attachment_id, $target ); } $wpdb->delete( $wpdb->prefix . WP360_MC_TABLE, array( 'id' => $item_id ), array( '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- eigene Tracking-Tabelle, dafuer gibt es keine WP-API; nichts davon wird gecacht. return true; } /** Restored alle aktuell als "legacy" gefuehrten Original-Backups auf einmal. Gibt die Anzahl zurueck. */ public static function restore_all_original_backups() { global $wpdb; $table = $wpdb->prefix . WP360_MC_TABLE; $ids = $wpdb->get_col( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- eigene Tracking-Tabelle; der Status muss aktuell sein, kein Cache. $wpdb->prepare( "SELECT id FROM {$table} WHERE reason = %s AND status = 'legacy'", // phpcs:ignore self::ORIGINAL_BACKUP_REASON ) ); $restored = 0; foreach ( $ids as $id ) { if ( self::restore( $id ) ) { ++$restored; } } return $restored; } /** Aktualisiert Breite/Hoehe in der Attachment-Metadata nach dem Zuruecksetzen eines Originals. */ private static function refresh_attachment_dimensions( $attachment_id, $file_path ) { $size = @getimagesize( $file_path ); if ( ! $size ) { return; } $meta = wp_get_attachment_metadata( $attachment_id ); if ( ! is_array( $meta ) ) { return; } $meta['width'] = $size[0]; $meta['height'] = $size[1]; wp_update_attachment_metadata( $attachment_id, $meta ); } /** Markiert Eintraege als "trashed" (rein Status-Aenderung, Datei bleibt im Legacy-Ordner liegen). */ public static function trash( array $item_ids ) { global $wpdb; if ( empty( $item_ids ) ) { return 0; } $ids = implode( ',', array_map( 'intval', $item_ids ) ); $table = $wpdb->prefix . WP360_MC_TABLE; return $wpdb->query("UPDATE {$table} SET status = 'trashed' WHERE id IN ({$ids})"); // phpcs:ignore } /** Loescht die Dateien der uebergebenen (getrashten) Eintraege endgueltig von der Platte. */ public static function empty_trash( array $item_ids ) { global $wpdb; $deleted = 0; foreach ( $item_ids as $item_id ) { $item = self::get_item( $item_id ); if ( ! $item || $item->status !== 'trashed' ) { continue; } $path = trailingslashit( self::bucket_dir_for_reason( $item->reason ) ) . ltrim( $item->original_relative_path, '/' ); if ( is_file( $path ) ) { wp_delete_file( $path ); } $wpdb->delete( $wpdb->prefix . WP360_MC_TABLE, array( 'id' => $item_id ), array( '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- eigene Tracking-Tabelle, dafuer gibt es keine WP-API; nichts davon wird gecacht. ++$deleted; } return $deleted; } public static function get_item( $item_id ) { global $wpdb; $table = $wpdb->prefix . WP360_MC_TABLE; return $wpdb->get_row($wpdb->prepare("SELECT * FROM {$table} WHERE id = %d", $item_id)); // phpcs:ignore } /** * Summe der Dateigroessen fuer einen Status, in Bytes. * * @param string $status 'legacy' oder 'trashed'. * @param string|null $reason_filter null = keine Einschraenkung (alle Gruende), * 'exclude_originals' = alles AUSSER Original-Backups, * ein konkreter reason-String = nur dieser Grund. */ public static function total_size( $status, $reason_filter = null ) { global $wpdb; $table = $wpdb->prefix . WP360_MC_TABLE; if ( $reason_filter === null ) { return (int) $wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(file_size), 0) FROM {$table} WHERE status = %s", $status)); // phpcs:ignore } if ( $reason_filter === 'exclude_originals' ) { return (int) $wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(file_size), 0) FROM {$table} WHERE status = %s AND reason != %s", $status, self::ORIGINAL_BACKUP_REASON)); // phpcs:ignore } return (int) $wpdb->get_var($wpdb->prepare("SELECT COALESCE(SUM(file_size), 0) FROM {$table} WHERE status = %s AND reason = %s", $status, $reason_filter)); // phpcs:ignore } /** @see total_size() fuer die Bedeutung von $reason_filter. */ public static function count( $status, $reason_filter = null ) { global $wpdb; $table = $wpdb->prefix . WP360_MC_TABLE; if ( $reason_filter === null ) { return (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE status = %s", $status)); // phpcs:ignore } if ( $reason_filter === 'exclude_originals' ) { return (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE status = %s AND reason != %s", $status, self::ORIGINAL_BACKUP_REASON)); // phpcs:ignore } return (int) $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$table} WHERE status = %s AND reason = %s", $status, $reason_filter)); // phpcs:ignore } }