PluginProbe
aBlocks – Gutenberg Blocks, User Dashboard Builder, Popup Builder, Form Builder & Animation Builder / trunk
aBlocks – Gutenberg Blocks, User Dashboard Builder, Popup Builder, Form Builder & Animation Builder vtrunk
2.13.0 2.13.1 2.12.0 2.11.1 2.11.0 2.10.0 2.9.0 2.7.4 2.7.5 2.7.6 2.7.7 2.8.0 2.8.1 2.9.1 trunk 1.0 1.0-beta1 1.0-beta2 1.0-beta3 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.1.2 All 80 releases
ablocks / includes / performance / image-tools.php

image-tools.php in aBlocks – Gutenberg Blocks, User Dashboard Builder, Popup Builder, Form Builder & Animation Builder trunk, at includes/performance/image-tools.php

163 lines 5.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace ABlocks\Performance;
3
4 if ( ! defined( 'ABSPATH' ) ) {
5 exit;
6 }
7
8 use ABlocks\Helper;
9 use ABlocks\Classes\Images\Compressor;
10 use ABlocks\Classes\Images\Quarantine;
11
12 /**
13 * Performance Suite — image compression and media cleanup.
14 *
15 * Wires the pieces together: optimize-on-upload, the scheduled quarantine
16 * sweep, and cleanup of an attachment's stored originals when it is deleted.
17 *
18 * Distinct from {@see ImageOptimizer}, which only changes how images are
19 * *delivered* (lazy-loading, dimensions) and never touches a file. This one
20 * rewrites files on disk, which is why every part of it is opt-in.
21 */
22 class ImageTools {
23
24 const SWEEP_HOOK = 'ablocks/images/quarantine_sweep';
25
26 public static function init() {
27 if ( defined( 'WP_CLI' ) && \WP_CLI ) {
28 \ABlocks\Classes\Images\Cli::register();
29 }
30
31 add_action( self::SWEEP_HOOK, [ __CLASS__, 'run_sweep' ] );
32 add_action( 'init', [ __CLASS__, 'ensure_events' ] );
33
34 // An attachment's stored originals are useless once the attachment is
35 // gone, and would otherwise sit in uploads forever.
36 add_action( 'delete_attachment', [ Compressor::class, 'delete_backups' ] );
37 // A deleted file must not keep answering to its old content hash.
38 add_action( 'delete_attachment', [ \ABlocks\Classes\Images\DuplicateScanner::class, 'forget' ] );
39
40 if ( (bool) Helper::get_settings( 'perf_image_optimize_on_upload', false ) ) {
41 // Priority 20: after WordPress has generated the thumbnail sizes, so
42 // every derivative is compressed rather than just the original.
43 add_filter( 'wp_generate_attachment_metadata', [ __CLASS__, 'optimize_new_upload' ], 20, 2 );
44 }
45 }
46
47 /**
48 * Keep the quarantine sweep scheduled only while something is held.
49 */
50 public static function ensure_events() {
51 $summary = Quarantine::summary();
52 $next = wp_next_scheduled( self::SWEEP_HOOK );
53
54 if ( $summary['count'] > 0 && ! $next ) {
55 wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::SWEEP_HOOK );
56 } elseif ( 0 === $summary['count'] && $next ) {
57 wp_unschedule_event( $next, self::SWEEP_HOOK );
58 }
59 }
60
61 /**
62 * Delete quarantined images that have outlived the retention window.
63 *
64 * Only runs when the site has opted into automatic deletion. Otherwise items
65 * are held indefinitely and removed by an explicit action, because silently
66 * destroying media that a scan merely *suspected* was unused is not a
67 * default anyone should get by accident.
68 *
69 * @return array
70 */
71 public static function run_sweep() {
72 if ( ! (bool) Helper::get_settings( 'perf_image_quarantine_autodelete', false ) ) {
73 return [
74 'deleted' => 0,
75 'bytes' => 0,
76 ];
77 }
78
79 $days = (int) Helper::get_settings( 'perf_image_quarantine_days', Quarantine::RETENTION_DAYS );
80
81 return Quarantine::sweep( $days );
82 }
83
84 /**
85 * Compress an image as it is uploaded.
86 *
87 * @param array $metadata Attachment metadata.
88 * @param int $attachment_id Attachment ID.
89 * @return array
90 */
91 public static function optimize_new_upload( $metadata, $attachment_id ) {
92 $mime = get_post_mime_type( $attachment_id );
93 if ( ! in_array( $mime, Compressor::SUPPORTED, true ) ) {
94 return $metadata;
95 }
96
97 $level = (string) Helper::get_settings( 'perf_image_level', '2x' );
98 $webp = (bool) Helper::get_settings( 'perf_image_webp', true );
99
100 // Never let an optimization failure break an upload: the attachment and
101 // its metadata matter far more than the saving.
102 try {
103 Compressor::optimize_attachment( $attachment_id, $level, $webp );
104 } catch ( \Throwable $e ) {
105 if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
106 error_log( 'aBlocks image optimize: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
107 }
108 }
109
110 return $metadata;
111 }
112
113 /**
114 * Totals for the settings screen.
115 *
116 * @return array
117 */
118 public static function stats() {
119 global $wpdb;
120
121 $rows = $wpdb->get_col(
122 $wpdb->prepare(
123 "SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key = %s LIMIT 5000",
124 Compressor::META_KEY
125 )
126 );
127
128 $before = 0;
129 $after = 0;
130 foreach ( (array) $rows as $row ) {
131 $record = maybe_unserialize( $row );
132 if ( ! is_array( $record ) ) {
133 continue;
134 }
135 $before += isset( $record['before'] ) ? (int) $record['before'] : 0;
136 $after += isset( $record['after'] ) ? (int) $record['after'] : 0;
137 }
138
139 $quarantine = Quarantine::summary();
140 $originals = Compressor::originals_size();
141
142 return [
143 // The configured strength travels with the stats because the bulk
144 // run lives on the Scanner, outside the settings form. Without it
145 // the Scanner would fall back to a default and quietly compress a
146 // 5x site at 2x — the run would look like it worked.
147 'level' => (string) Helper::get_settings( 'perf_image_level', '2x' ),
148 'webp' => (bool) Helper::get_settings( 'perf_image_webp', true ),
149 'optimized' => count( (array) $rows ),
150 'saved_bytes' => max( 0, $before - $after ),
151 'saved' => size_format( max( 0, $before - $after ), 1 ),
152 'pending' => count( Compressor::pending_ids( 500, false ) ),
153 'quarantined' => (int) $quarantine['count'],
154 'quarantine_size' => size_format( (int) $quarantine['bytes'], 1 ),
155 // What deleting the stored originals would reclaim, so the choice
156 // can be presented with a number rather than as a leap of faith.
157 'originals_bytes' => (int) $originals,
158 'originals' => size_format( (int) $originals, 1 ),
159 'originals_count' => count( Compressor::ids_with_originals() ),
160 ];
161 }
162 }
163