-
Notifications
You must be signed in to change notification settings - Fork 2
/
wp-blurhash.php
338 lines (274 loc) · 9.37 KB
/
wp-blurhash.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
<?php
/**
* Plugin Name: WP Blurhash
* Plugin URI: XWP.io
* Description: Adds Blurhash preload support to WordPress.
* Author: pbearne, XWP
* Author URI: XWP.io
* Text Domain: wp-blurhash
* Domain Path: /languages
* Version: 0.1.0
*
* @package wp-Blurhash
*/
// Your code starts here.
require_once __DIR__ . '/vendor/autoload.php';
use kornrunner\Blurhash\Blurhash;
/**
* Add Blurhash preload support to WordPress.
*
* TODO: Add settings to turn on and select method used client-side bg image or canvas.
* TODO: remove direct calls to GD li / support imagick.
* Look at the load function in these files src/wp-includes/class-wp-image-editor.php and src/wp-includes/class-wp-image-editor-imagick.php
* TODO: Add tests
*/
class wp_blurhash {
public function __construct() {
add_filter( 'wp_generate_attachment_metadata', [ $this, 'blurhash_metadata' ], 10, 2 );
add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_plugin_scripts' ] );
add_action( 'rest_api_init', [ $this, 'register_rest_routes' ] );
// do we have the new filter or are duplicating core the functions?
if ( has_filter( 'wp_img_tag_add_adjust' ) ) {
add_filter( 'wp_img_tag_add_adjust', [ $this, 'tag_add_adjust' ], 10, 3 );
} else {
add_filter( 'the_content', [ $this, 'filter_content_tags' ] );
add_filter( 'wp_blurhash_img_tag_add_adjust', [ $this, 'tag_add_adjust' ], 10, 3 );
}
add_filter( 'attachment_fields_to_edit', [ $this, 'add_blurhash_media_setting' ], 10, 2 );
add_filter( 'attachment_fields_to_save', [ $this, 'save_blurhash_media_setting' ], 10, 2);
}
/**
* TODO: this needs to wired up to so that attachment_image have the data hash added
*
* @param $html
* @param $attachment_id
*
* @return string
*/
public function wp_blurhash_wp_get_attachment_image( $html, $attachment_id ) {
$image_meta = wp_get_attachment_metadata( $attachment_id );
if ( ! empty( $image_meta['blurhash'] ) ) {
$html = str_replace( '<img', '<img data-blurhash="' . $image_meta['blurhash'] . '"', $html );
}
return $html;
}
/**
* @return void
*/
public function register_rest_routes() {
$d = register_rest_route( 'blurhash/v1', '/get/(?P<id>\d+)', array(
'methods' => WP_REST_Server::READABLE,
'callback' => [ $this, 'handle_rest_call' ],
'permission_callback' => [ $this, 'rest_permission_callback' ],
) );
}
/**
* @return bool
*/
// TDOD: fix permission check
public function rest_permission_callback() {
return true;
return current_user_can( 'upload_files' );
}
public function handle_rest_call( $request ) {
$id = $request->get_param( 'id' );
return $this->get_blurhash_by_id( $id );
}
public function get_blurhash_by_id( $id ) {
$file = get_attached_file( $id );
wp_raise_memory_limit( 'image' );
$image_editor = wp_get_image_editor( $file );
if ( is_wp_error( $image_editor ) ) {
// This image cannot be edited.
return;
}
$size = $image_editor->get_size();
$width = $size['width'];
$height = $size['height'];
$skip_factor = (int) ( $width + $height ) / 10;
$pixels = [];
if ( 'WP_Image_Editor_Imagick' === get_class( $image_editor ) ) {
//TODO: create imagick version of blurhash
$imagick = new Imagick($file);
for ( $y = 0; $y < $height; $y=$y+$skip_factor ) {
$row = [];
for ( $x = 0; $x < $width; $x=$x+$skip_factor ) {
$pixel = $imagick->getImagePixelColor( $x, $y );
$colors = $pixel->getColor();
$row[] = [ $colors['r'], $colors['g'], $colors['b'] ];
}
$pixels[] = $row;
}
} else {
if ( function_exists( 'imagecreatefromwebp' ) && 'image/webp' === wp_get_image_mime( $file ) ) {
$image = imagecreatefromwebp( $file );
} else {
$image = imagecreatefromstring( file_get_contents( $file ) );
}
for ( $y = 0; $y < $height; $y=$y+$skip_factor ) {
$row = [];
for ( $x = 0; $x < $width; $x=$x+$skip_factor ) {
$index = imagecolorat( $image, $x, $y );
$colors = imagecolorsforindex( $image, $index );
$row[] = [ $colors['red'], $colors['green'], $colors['blue'] ];
}
$pixels[] = $row;
}
}
$components_x = 4;
$components_y = 3;
return Blurhash::encode( $pixels, $components_x, $components_y );
}
// TODO: off-load this to api call
/**
* @param $metadata
* @param $attachment_id
*
* @return array $metadata
*/
public function blurhash_metadata( $metadata, $attachment_id ) {
// this is failing when calling local host but works in browser
// $burhash = wp_remote_get( get_rest_url() . 'blurhash/v1/get' . $attachment_id );
// so calling directly for now
$burhash = $this->get_blurhash_by_id( $attachment_id );
if( ! empty( $burhash ) ) {
$metadata['blurhash'] = $burhash;
}
return $metadata;
}
/**
* @param $filtered_image
* @param $context
* @param $attachment_id
*
* @return string image tag
*/
public function tag_add_adjust( $filtered_image, $context, $attachment_id ) {
$image_meta = wp_get_attachment_metadata( $attachment_id );
if ( isset( $image_meta['blurhash'] ) ) {
$data = sprintf( 'data-blurhash="%s" ', $image_meta['blurhash'] );
$filtered_image = str_replace( '<img ', '<img ' . $data, $filtered_image );
}
return $filtered_image;
}
/**
* @return void
*/
public function enqueue_plugin_scripts() {
wp_enqueue_script( 'blurhash', plugin_dir_url( __FILE__ ) . 'dist/blurhash.js' );
}
/**
* @param $content
* @param $context
*
* @return string content
*/
public function filter_content_tags( $content, $context = null ) {
if ( null === $context ) {
$context = current_filter();
}
if ( ! preg_match_all( '/<(img|iframe)\s[^>]+>/', $content, $matches, PREG_SET_ORDER ) ) {
return $content;
}
// List of the unique `img` tags found in $content.
$images = array();
// List of the unique `iframe` tags found in $content.
$iframes = array();
foreach ( $matches as $match ) {
list( $tag, $tag_name ) = $match;
switch ( $tag_name ) {
case 'img':
if ( preg_match( '/wp-image-([0-9]+)/i', $tag, $class_id ) ) {
$attachment_id = absint( $class_id[1] );
if ( $attachment_id ) {
// If exactly the same image tag is used more than once, overwrite it.
// All identical tags will be replaced later with 'str_replace()'.
$images[ $tag ] = $attachment_id;
break;
}
}
$images[ $tag ] = 0;
break;
}
}
// Reduce the array to unique attachment IDs.
$attachment_ids = array_unique( array_filter( array_values( $images ) ) );
if ( count( $attachment_ids ) > 1 ) {
/*
* Warm the object cache with post and meta information for all found
* images to avoid making individual database calls.
*/
_prime_post_caches( $attachment_ids, false, true );
}
// Iterate through the matches in order of occurrence as it is relevant for whether or not to lazy-load.
foreach ( $matches as $match ) {
// Filter an image match.
if ( isset( $images[ $match[0] ] ) ) {
$filtered_image = $match[0];
$attachment_id = $images[ $match[0] ];
/**
* Filters img tag that will be injected into the content.
*
* @param string $filtered_image the img tag with attributes being created that will
* replace the source img tag in the content.
* @param string $context Optional. Additional context to pass to the filters.
* Defaults to `current_filter()` when not set.
* @param int $attachment_id the ID of the image attachment.
*
* @since 1.0.0
*
*/
$filtered_image = apply_filters( 'wp_blurhash_img_tag_add_adjust', $filtered_image, $context, $attachment_id );
if ( $filtered_image !== $match[0] ) {
$content = str_replace( $match[0], $filtered_image, $content );
}
}
}
return $content;
}
/**
* Add checkbox setting to enable/disable blurhash for a given media.
*
* @param array $form_fields
* @param WP_Post $post
*
* @return array
*/
public function add_blurhash_media_setting( array $form_fields, WP_Post $post ) {
$image_meta = wp_get_attachment_metadata( $post->ID );
$checked_text = isset( $image_meta['blurhash'] ) ? 'checked' : '';
$html_input = "<input type='checkbox' $checked_text value='1'
name='attachments[{$post->ID}][blurhash]' id='attachments[{$post->ID}][blurhash]' />";
$form_fields['blurhash'] = array(
'label' => __( 'Blurhash', 'wp-blurhash' ),
'input' => 'html',
'html' => $html_input,
);
return $form_fields;
}
/**
* Save blurhash setting value for a media post.
*
* @param array $post
* @param array $attachment
*
* @return array
*/
public function save_blurhash_media_setting( array $post, array $attachment ) {
$attachment_id = $post['ID'];
$image_meta = wp_get_attachment_metadata( $attachment_id );
if ( isset( $attachment['blurhash'] ) ) {
if ( ! isset( $image_meta['blurhash'] ) ) {
// If enabling blurhash from media setting and image meta doesn't have any, generate a new one.
$image_meta = $this->blurhash_metadata( $image_meta, $attachment_id );
wp_update_attachment_metadata( $attachment_id, $image_meta );
}
} elseif ( isset( $image_meta['blurhash'] ) ) {
// If disabling blurhash from media setting and blurhash set in image meta, unset it.
unset( $image_meta['blurhash'] );
wp_update_attachment_metadata( $attachment_id, $image_meta );
}
return $post;
}
}
new WP_Blurhash();