PluginProbe
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin / 0.9.8
OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin v0.9.8
1.1.10 1.1.9 1.1.8 1.1.7 1.1.6 1.1.5 1.1.4 1.1.3 1.1.2 1.1.1 1.1.0 1.0.1 1.0.0 0.9.8 0.9.7 0.9.6 0.9.4 0.9.5 0.9.3 0.9.2 0.9.1 0.9.0 0.8.9 0.8.8 0.8.7 All 34 releases
desktop-mode / includes / media-query.php

media-query.php in OpenStation: Desktop Windows, Dock & Virtual Desktops for WP Admin 0.9.8, at includes/media-query.php

226 lines 8.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Desktop Mode — Media dimension filtering for REST.
4 *
5 * Adds two opt-in query parameters to `/wp/v2/media`:
6 *
7 * - `desktop_mode_min_width` — only return images at least this many pixels wide.
8 * - `desktop_mode_min_height` — only return images at least this many pixels tall.
9 *
10 * The OS Settings wallpaper picker uses these to keep a site with thousands
11 * of small product images from burying the handful of desktop-worthy HD
12 * shots under an infinite-scroll slog. The client still applies the same
13 * filter locally as a belt-and-suspenders safeguard — if the server-side
14 * filter ever ships mis-stamped meta, the UI still hides too-small images.
15 *
16 * Why not `meta_query` on `_wp_attachment_metadata` directly? That key is
17 * stored serialized, so SQL can't compare its `width`/`height` members
18 * reliably. We stamp two flat numeric meta keys on every new attachment
19 * (and opportunistically backfill existing ones) so `WP_Meta_Query` can
20 * use a normal NUMERIC `>=` comparison.
21 *
22 * @package WPDesktopMode
23 */
24
25 defined( 'ABSPATH' ) || exit;
26
27 /** Numeric post-meta keys stamped on every image attachment. */
28 const DESKTOP_MODE_META_WIDTH = '_desktop_mode_width';
29 const DESKTOP_MODE_META_HEIGHT = '_desktop_mode_height';
30
31 /** Option key flipped to `1` once every image has been backfilled. */
32 const DESKTOP_MODE_BACKFILL_DONE_OPTION = 'desktop_mode_media_dims_backfilled';
33
34 /** How many legacy attachments to backfill per filtered REST request. */
35 const DESKTOP_MODE_MEDIA_BACKFILL_BATCH = 50;
36
37 /**
38 * Stamp numeric dimension meta whenever an attachment's metadata is
39 * generated or updated. Hooked on both `wp_generate_attachment_metadata`
40 * (new uploads) and `wp_update_attachment_metadata` (regenerated
41 * thumbnails, image editor saves) so the stamp stays in sync with
42 * whatever Core thinks the canonical dimensions are.
43 *
44 * @param array $metadata Attachment metadata.
45 * @param int $attachment_id Attachment post ID.
46 * @return array The metadata, unchanged — we only read from it.
47 */
48 function desktop_mode_stamp_media_dimensions( $metadata, $attachment_id ) {
49 if ( ! is_array( $metadata ) ) {
50 return $metadata;
51 }
52
53 $width = isset( $metadata['width'] ) ? (int) $metadata['width'] : 0;
54 $height = isset( $metadata['height'] ) ? (int) $metadata['height'] : 0;
55
56 // Stamp zero for images we can't measure (SVGs, broken files) so the
57 // backfill sweep knows we've already inspected this row and doesn't
58 // re-check it on every subsequent filtered request.
59 update_post_meta( $attachment_id, DESKTOP_MODE_META_WIDTH, max( 0, $width ) );
60 update_post_meta( $attachment_id, DESKTOP_MODE_META_HEIGHT, max( 0, $height ) );
61
62 return $metadata;
63 }
64 add_filter( 'wp_generate_attachment_metadata', 'desktop_mode_stamp_media_dimensions', 10, 2 );
65 add_filter( 'wp_update_attachment_metadata', 'desktop_mode_stamp_media_dimensions', 10, 2 );
66
67 /**
68 * Register the `desktop_mode_min_width` / `desktop_mode_min_height` query parameters on
69 * the media collection so Core sanitizes them before they reach our
70 * query filter. Without this, the params would still work but would
71 * show up as unknown to any REST consumer introspecting the schema.
72 *
73 * @param array $params Existing collection params.
74 * @return array
75 */
76 function desktop_mode_register_media_query_params( $params ) {
77 $params['desktop_mode_min_width'] = array(
78 'description' => __( 'Only return images at least this many pixels wide.', 'desktop-mode' ),
79 'type' => 'integer',
80 'minimum' => 1,
81 );
82 $params['desktop_mode_min_height'] = array(
83 'description' => __( 'Only return images at least this many pixels tall.', 'desktop-mode' ),
84 'type' => 'integer',
85 'minimum' => 1,
86 );
87 return $params;
88 }
89 add_filter( 'rest_attachment_collection_params', 'desktop_mode_register_media_query_params' );
90
91 /**
92 * Inject meta_query clauses on the attachment REST query when either
93 * dimension filter is present. Triggers a bounded backfill first so
94 * legacy attachments (uploaded before this filter existed) start
95 * participating without a one-shot CLI command.
96 *
97 * @param array $args WP_Query args built by the REST controller.
98 * @param WP_REST_Request $request The REST request.
99 * @return array The query args, possibly with extra meta_query entries.
100 */
101 function desktop_mode_filter_media_by_dimensions( $args, $request ) {
102 $min_width = absint( $request->get_param( 'desktop_mode_min_width' ) );
103 $min_height = absint( $request->get_param( 'desktop_mode_min_height' ) );
104
105 if ( ! $min_width && ! $min_height ) {
106 return $args;
107 }
108
109 // Chip away at any remaining unstamped attachments before the query
110 // runs, so a site upgrading into this feature gets useful results on
111 // roughly the first few picker opens rather than after a CLI run.
112 // Logged-in users only — anonymous REST readers can still use the
113 // dimension filters, but must never trigger database writes (or the
114 // NOT EXISTS sweep query) on a public, unauthenticated endpoint.
115 if ( is_user_logged_in() ) {
116 desktop_mode_backfill_media_dimensions( DESKTOP_MODE_MEDIA_BACKFILL_BATCH );
117 }
118
119 $meta_query = isset( $args['meta_query'] ) && is_array( $args['meta_query'] )
120 ? $args['meta_query']
121 : array();
122
123 $clauses = array();
124 if ( $min_width ) {
125 $clauses[] = array(
126 'key' => DESKTOP_MODE_META_WIDTH,
127 'value' => $min_width,
128 'compare' => '>=',
129 'type' => 'NUMERIC',
130 );
131 }
132 if ( $min_height ) {
133 $clauses[] = array(
134 'key' => DESKTOP_MODE_META_HEIGHT,
135 'value' => $min_height,
136 'compare' => '>=',
137 'type' => 'NUMERIC',
138 );
139 }
140
141 if ( count( $clauses ) > 1 ) {
142 $clauses['relation'] = 'AND';
143 }
144
145 // Compose with any existing meta_query so we don't stomp other
146 // filters (Core's own, or anything plugins have layered on).
147 if ( empty( $meta_query ) ) {
148 $args['meta_query'] = $clauses; // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- NUMERIC >= dimension filter on indexed meta keys; canonical WP pattern for picker filtering.
149 } else {
150 $args['meta_query'] = array( // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- composed AND clause merging caller meta_query with our dimension filter.
151 'relation' => 'AND',
152 $meta_query,
153 $clauses,
154 );
155 }
156
157 return $args;
158 }
159 add_filter( 'rest_attachment_query', 'desktop_mode_filter_media_by_dimensions', 10, 2 );
160
161 /**
162 * Stamp dimension meta on up to $batch image attachments that don't
163 * have it yet. Returns early once a site has been fully backfilled so
164 * filtered REST requests don't keep paying for an empty sweep query.
165 *
166 * Ordering by `ID DESC` so newest attachments get stamped first — the
167 * user is most likely to be looking for something they uploaded
168 * recently, so we prioritize the tail they're staring at.
169 *
170 * @param int $batch Maximum attachments to stamp this pass.
171 * @return int Number of attachments stamped (0 when nothing remained).
172 */
173 function desktop_mode_backfill_media_dimensions( $batch ) {
174 if ( get_option( DESKTOP_MODE_BACKFILL_DONE_OPTION ) ) {
175 return 0;
176 }
177
178 $ids = get_posts(
179 array(
180 'post_type' => 'attachment',
181 'post_status' => 'inherit',
182 'post_mime_type' => 'image',
183 'posts_per_page' => (int) $batch,
184 'orderby' => 'ID',
185 'order' => 'DESC',
186 'fields' => 'ids',
187 'no_found_rows' => true,
188 'update_post_term_cache' => false,
189 // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- one-shot backfill targeting the small subset of attachments that lack our dimension stamp; runs at most $batch rows per filtered request and stops once the site option flips.
190 'meta_query' => array(
191 array(
192 'key' => DESKTOP_MODE_META_WIDTH,
193 'compare' => 'NOT EXISTS',
194 ),
195 ),
196 )
197 );
198
199 if ( empty( $ids ) ) {
200 // Flip the flag so future filtered requests skip this query.
201 // If a plugin ever adds new images via a back door that bypasses
202 // `wp_generate_attachment_metadata`, those can be picked up by
203 // manually deleting this option.
204 update_option( DESKTOP_MODE_BACKFILL_DONE_OPTION, 1, false );
205 return 0;
206 }
207
208 foreach ( $ids as $id ) {
209 // `wp_get_attachment_metadata()` hits the object cache if it was
210 // primed by the enclosing query; otherwise it's a single meta
211 // lookup per id. We're bounded at $batch per request so the
212 // per-request overhead stays predictable.
213 $metadata = wp_get_attachment_metadata( $id );
214
215 $width = is_array( $metadata ) && isset( $metadata['width'] ) ? (int) $metadata['width'] : 0;
216 $height = is_array( $metadata ) && isset( $metadata['height'] ) ? (int) $metadata['height'] : 0;
217
218 // Always stamp, even when zero — that's how the sweep query
219 // knows to skip this row on the next pass.
220 update_post_meta( $id, DESKTOP_MODE_META_WIDTH, max( 0, $width ) );
221 update_post_meta( $id, DESKTOP_MODE_META_HEIGHT, max( 0, $height ) );
222 }
223
224 return count( $ids );
225 }
226