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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
|
<?php /** * WebP class: WebP * * @package Smush\Core\Modules * @since 3.8.0 */
namespace Smush\Core\Modules;
use WP_Smush; use Smush\Core\Helper;
if ( ! defined( 'WPINC' ) ) { die; }
/** * Class WebP extends Abstract_Module. */ class WebP extends Abstract_Module {
/** * If server is configured for webp * * @access private * @var bool $is_configured */ private $is_configured;
/** * Get the unique name of this module. * * @return string */ public function get_mod_name() { return 'webp'; }
/** * Initialize the module. */ public function init() { // Show success message after deleting all webp images. add_action( 'wp_smush_header_notices', array( $this, 'maybe_show_notices' ) ); }
/** * Enables and disables the WebP module. * * @since 3.8.0 * * @param boolean $enable Whether to enable or disable WebP. */ public function toggle_webp( $enable = true ) { $this->settings->set( 'webp_mod', $enable );
global $wp_filesystem; if ( is_null( $wp_filesystem ) ) { WP_Filesystem(); }
$parsed_udir = $this->get_upload_dir(); $flag_file_path = $parsed_udir['webp_path'] . '/disable_smush_webp';
// Handle the file used as a flag by the server rules. if ( $enable ) { $wp_filesystem->delete( $flag_file_path, true ); } else { $wp_filesystem->put_contents( $flag_file_path, '' ); } }
/** * Get status of server configuration for webp. * * @since 3.8.0 * * @param bool $force force to recheck. * * @return bool */ public function is_configured( $force = false ) { if ( ! is_null( $this->is_configured ) && ! $force ) { return $this->is_configured; }
$this->is_configured = $this->check_server_config();
return $this->is_configured; }
/** * Check if server is configured to serve webp image. * * @since 3.8.0 * * @return bool */ private function check_server_config() { $this->create_test_files(); $udir = $this->get_upload_dir(); $test_image = $udir['upload_url'] . '/smush-webp-test.png';
$args['headers']['Accept'] = 'image/webp';
// Add support for basic auth in WPMU DEV staging. if ( isset( $_SERVER['WPMUDEV_HOSTING_ENV'] ) && 'staging' === $_SERVER['WPMUDEV_HOSTING_ENV'] && isset( $_SERVER['PHP_AUTH_USER'] ) ) { $args['headers']['Authorization'] = 'Basic ' . base64_encode( $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'] ); }
$response = wp_remote_get( $test_image, $args ); $code = wp_remote_retrieve_response_code( $response );
// Check the image's format when the request was successful. if ( 200 === $code ) { $content_type = wp_remote_retrieve_header( $response, 'content-type' ); return 'image/webp' === $content_type; }
// Return the response code and message otherwise. return new \WP_Error( $code, wp_remote_retrieve_response_message( $response ) ); }
/** * Code to use on Nginx servers. * * @param bool $marker whether to wrap code with marker comment lines. * @return string */ public function get_nginx_code( $marker = true ) { $udir = $this->get_upload_dir();
$base = trailingslashit( dirname( $udir['upload_rel_path'] ) ); $directory = trailingslashit( basename( $udir['upload_rel_path'] ) ); $regex_base = $base . '(' . $directory . ')';
$code = 'location ~* "' . str_replace( '/', '\/', $regex_base ) . '(.*.(?:png|jpe?g))" { add_header Vary Accept; set $image_path $2; if (-f "' . $udir['webp_path'] . '/disable_smush_webp") { break; } if ($http_accept !~* "webp") { break; } try_files /' . trailingslashit( $udir['webp_rel_path'] ) . '$image_path.webp $uri =404; }';
if ( true === $marker ) { $code = $this->marker_line() . "\n" . $code; $code = $code . "\n" . $this->marker_line( true ); } return $code; }
/** * Code to use on Apache servers. * * @param bool $marker whether to wrap code with marker comment lines. * @return string */ public function get_apache_code( $marker = false ) { $udir = $this->get_upload_dir();
$code = '<IfModule mod_rewrite.c> RewriteEngine On RewriteCond %{DOCUMENT_ROOT}/' . $udir['webp_rel_path'] . '/disable_smush_webp !-f RewriteCond %{HTTP_ACCEPT} image/webp RewriteCond %{REQUEST_FILENAME} -f RewriteCond %{DOCUMENT_ROOT}/' . $udir['webp_rel_path'] . '/$1.$2.webp -f RewriteRule ^/?(.+)\.(jpe?g|png)$ /' . $udir['webp_rel_path'] . '/$1.$2.webp [NC,T=image/webp,E=WEBP_image] </IfModule>
<IfModule mod_headers.c> Header append Vary Accept env=WEBP_image </IfModule>
<IfModule mod_mime.c> AddType image/webp .webp </IfModule>';
if ( true === $marker ) { $code = $this->marker_line() . "\n" . $code; $code = $code . "\n" . $this->marker_line( true ); } return $code; }
/** * Retrieves uploads directory and WebP directory information. * All paths and urls do not have trailing slash. * * @return array */ public function get_upload_dir() { static $upload_dir_info; if ( isset( $upload_dir_info ) ) { return $upload_dir_info; }
if ( ! is_multisite() || is_main_site() ) { $upload = wp_upload_dir(); } else { // Use the main site's upload directory for all subsite's webp converted images. // This makes it easier to have a single rule on the server configs for serving webp in mu. $blog_id = get_main_site_id(); switch_to_blog( $blog_id ); $upload = wp_upload_dir(); restore_current_blog(); }
// Getting relative paths. // Environments like Flywheel have an ABSPATH that's not used in the paths. $path_base = false !== strpos( $upload['basedir'], ABSPATH ) ? ABSPATH : dirname( WP_CONTENT_DIR );
$upload_rel_path = substr( $upload['basedir'], strlen( $path_base ) ); $upload_rel_path = ltrim( $upload_rel_path, '/' ); $webp_rel_path = dirname( $upload_rel_path ) . '/smush-webp';
$upload_dir_info = array( 'upload_path' => $upload['basedir'], 'upload_rel_path' => $upload_rel_path, 'upload_url' => $upload['baseurl'], 'webp_path' => dirname( $upload['basedir'] ) . '/smush-webp', 'webp_rel_path' => $webp_rel_path, 'webp_url' => dirname( $upload['baseurl'] ) . '/smush-webp', );
return $upload_dir_info; }
/** * Create test files and required directory. */ public function create_test_files() { $udir = $this->get_upload_dir(); $test_png_file = $udir['upload_path'] . '/smush-webp-test.png'; $test_webp_file = $udir['webp_path'] . '/smush-webp-test.png.webp';
if ( ! file_exists( $test_png_file ) ) { copy( WP_SMUSH_DIR . 'app/assets/images/smush-webp-test.png', $test_png_file ); }
if ( ! file_exists( $test_webp_file ) ) { // Check and create webp_path. if ( ! is_dir( $udir['webp_path'] ) ) { wp_mkdir_p( $udir['webp_path'] ); } copy( WP_SMUSH_DIR . 'app/assets/images/smush-webp-test.png.webp', $test_webp_file ); } }
/** * Retrieves related webp image file path for a given non webp image file path. * Also create required directories for webp image if not exists. * * @param string $file_path Non webp image file path. * @param bool $make Weather to create required directories. * * @return string */ public function get_webp_file_path( $file_path, $make = false ) { $udir = $this->get_upload_dir();
$file_rel_path = substr( $file_path, strlen( $udir['upload_path'] ) ); $webp_file_path = $udir['webp_path'] . $file_rel_path . '.webp';
if ( $make ) { $webp_file_dir = dirname( $webp_file_path ); if ( ! is_dir( $webp_file_dir ) ) { wp_mkdir_p( $webp_file_dir ); } }
return $webp_file_path; }
/** * Check whether the given attachment id or mime type can be converted to WebP. * * @param string $id Atachment ID. * @param string $mime Mime type. * * @return bool */ private function can_be_converted( $id = '', $mime = '' ) { if ( empty( $id ) && empty( $mime ) ) { return false; }
$mime = empty( $mime ) ? get_post_mime_type( $id ) : $mime;
// This image can not be converted to webp. if ( ! ( 'image/jpeg' === $mime || 'image/png' === $mime ) ) { return false; } return true; }
/** * Checks whether an attachment should be converted to WebP. * Returns false if WebP isn't configured, the attachment was already converted, * or if the attachment can't be converted ( @see self::can_be_converted() ). * * @since 3.8.0 * * @param string $id Attachment ID. * * @return bool */ public function should_be_converted( $id ) { // Avoid conversion when webp disabled, or when Smush is Free. if ( ! $this->settings->get( 'webp_mod' ) || ! WP_Smush::is_pro() ) { return false; }
$meta = get_post_meta( $id, Smush::$smushed_meta_key, true ); $webp_udir = $this->get_upload_dir();
// The image was already converted to WebP. if ( ! empty( $meta['webp_flag'] ) && file_exists( $webp_udir['webp_path'] . '/' . $meta['webp_flag'] ) ) { return false; }
return $this->can_be_converted( $id ); }
/** * Deletes all the webp files when an attachment is deleted * Update Smush::$smushed_meta_key meta ( optional ) * Used in Smush::delete_images() and Backup::restore_image() * * @since 3.8.0 * * @param int $image_id Attachment ID. * @param bool $update_meta Whether to update meta or not. * @param string $main_file Main file to replace the one retrieved via the $id. * Useful for deleting webp images after PNG to JPG conversion. */ public function delete_images( $image_id, $update_meta = true, $main_file = '' ) { $meta = wp_get_attachment_metadata( $image_id );
// File path for original image. if ( empty( $main_file ) ) { $main_file = get_attached_file( $image_id ); }
// Not a supported image? Exit. if ( ! in_array( strtolower( pathinfo( $main_file, PATHINFO_EXTENSION ) ), array( 'gif', 'jpg', 'jpeg', 'png' ), true ) ) { return; }
$main_file_webp = $this->get_webp_file_path( $main_file );
$dir_path = dirname( $main_file_webp );
if ( file_exists( $main_file_webp ) ) { unlink( $main_file_webp ); }
if ( ! empty( $meta['sizes'] ) ) { foreach ( $meta['sizes'] as $size_key => $size_data ) { $size_file = path_join( $dir_path, $size_data['file'] ); if ( file_exists( $size_file . '.webp' ) ) { unlink( $size_file . '.webp' ); } } }
if ( $update_meta ) { $smushed_meta_key = Smush::$smushed_meta_key; $stats = get_post_meta( $image_id, $smushed_meta_key, true ); if ( ! empty( $stats ) && is_array( $stats ) ) { unset( $stats['webp_flag'] ); update_post_meta( $image_id, $smushed_meta_key, $stats ); } } }
/** * Deletes all webp images for the whole network or the current subsite. * It deletes the whole smush-webp directory when it's a single install * or a MU called from the network admin (and the current_user_can( manage_network )). * * @since 3.8.0 */ public function delete_all() { global $wp_filesystem; if ( is_null( $wp_filesystem ) ) { WP_Filesystem(); }
$parsed_udir = $this->get_upload_dir();
// Delete the whole webp directory only when on single install or network admin. $wp_filesystem->delete( $parsed_udir['webp_path'], true ); }
/** * Renders the notice after deleting all webp images. * * @since 3.8.0 * * @param string $tab Smush tab name. */ public function maybe_show_notices( $tab ) { // Show only on WebP page. if ( ! isset( $tab ) || 'webp' !== $tab ) { return; }
// Show only when there are images in the library, except on mu, where the count is always 0. if ( ! is_multisite() && 0 === WP_Smush::get_instance()->core()->total_count ) { return; }
$show_message = filter_input( INPUT_GET, 'notice', FILTER_SANITIZE_STRING ); // Success notice after deleting all WebP images. if ( 'webp-deleted' === $show_message ) { $message = __( 'WebP files were deleted successfully.', 'wp-smushit' ); echo '<div role="alert" id="wp-smush-webp-delete-all-notice" data-message="' . esc_attr( $message ) . '" class="sui-notice" aria-live="assertive"></div>'; } }
/* * Server related methods. */
/** * Get the server code snippet * * @param string $server Server name (nginx,apache...). * @param array $args optional value to pass to the user function. * * @return string */ private function get_server_code_snippet( $server, $args = array() ) { $method = 'get_' . str_replace( array( '-', ' ' ), '', strtolower( $server ) ) . '_code'; if ( ! method_exists( $this, $method ) ) { return ''; }
return call_user_func_array( array( $this, $method ), array( $args ) ); }
/** * Return the server type (Apache, NGINX...) * * @return string Server type */ public static function get_server_type() { global $is_apache, $is_IIS, $is_iis7, $is_nginx;
$type = '';
if ( $is_apache ) { // It's a common configuration to use nginx in front of Apache. // Let's make sure that this server is Apache. $response = wp_remote_get( home_url() );
if ( is_wp_error( $response ) ) { // Bad luck. $type = 'apache'; } else { $server = strtolower( wp_remote_retrieve_header( $response, 'server' ) ); // Could be LiteSpeed too. $type = strpos( $server, 'nginx' ) !== false ? 'nginx' : 'apache'; } } elseif ( $is_nginx ) { $type = 'nginx'; } elseif ( $is_IIS ) { $type = 'IIS'; } elseif ( $is_iis7 ) { $type = 'IIS 7'; }
return $type; }
/** * Get a list of server types * * @return array */ public function get_servers() { return array( 'apache' => 'Apache / LiteSpeed', 'nginx' => 'NGINX', 'iis' => 'IIS', 'cloudflare' => 'Cloudflare', ); }
/** * Get code snippet for a module and server type * * @param string $server_type Server type (nginx, apache...). * @param array $args optional value. * * @return string Code snippet */ private function get_code_snippet( $server_type = '', $args = array() ) { $module_name = $this->get_mod_name();
if ( ! $server_type ) { $server_type = $this->get_server_type(); } $code_snippet = $this->get_server_code_snippet( $server_type, $args ); return apply_filters( 'smush_code_snippet', $code_snippet, $server_type, $module_name ); }
/** * Get path of .htaccess file located in site root directory. * * @return string; */ private function htaccess_file() { if ( ! function_exists( 'wp_upload_dir' ) ) { require_once ABSPATH . 'wp-includes/functions.php'; }
$uploads = wp_upload_dir();
return $uploads['basedir'] . '/.htaccess'; }
/** * Check if .htaccess is writable. * * @return bool */ private function is_htaccess_writable() { $file = $this->htaccess_file(); $home_path = get_home_path(); return ( ! file_exists( $file ) && is_writable( $home_path ) ) || is_writable( $file ); }
/** * Get unique string to use at marker comment line in .htaccess or nginx config file. * * @return string */ private function marker_suffix() { return 'SMUSH-' . strtoupper( $this->get_mod_name() ); }
/** * Get unique string to use as marker comment line in .htaccess or nginx config file. * * @param bool $end whether to use marker after end of the config code. * @return string */ private function marker_line( $end = false ) { if ( true === $end ) { return '# END ' . $this->marker_suffix(); } else { return '# BEGIN ' . $this->marker_suffix(); } }
/** * Check if .htaccess has rules for this module in place. * * @return bool */ public function is_htaccess_written() { $file = $this->htaccess_file();
if ( ! function_exists( 'extract_from_markers' ) ) { require_once ABSPATH . 'wp-admin/includes/misc.php'; }
$existing_rules = array_filter( extract_from_markers( $file, $this->marker_suffix() ) ); return ! empty( $existing_rules ); }
/** * Add rules .htaccess file. * * @since 3.8.0 * * @return bool|string True on success. String with the error message on failure. */ public function save_htaccess() { if ( $this->is_htaccess_written() ) { return esc_html__( 'The .htaccess file already contains the WebP rules from Smush.', 'wp-smushit' ); }
$cannot_write_message = sprintf( /* translators: 1. opening 'a' tag to premium support, 2. closing 'a' tag. */ esc_html__( 'We tried to apply the .htaccess rules automatically but we were unable to complete this action. Make sure the file permissions on your .htaccess file are set to 644, or switch to manual mode and apply the rules yourself. If you need further assistance, you can %1$scontact support%2$s for help.', 'wp-smushit' ), '<a href="https://premium.wpmudev.org/hub/support/#get-support" target="_blank">', '</a>' ); if ( ! $this->is_htaccess_writable() ) { return $cannot_write_message; }
$code = $this->get_code_snippet( 'apache' ); $code = explode( "\n", $code ); $file = $this->htaccess_file(); $markers_inserted = insert_with_markers( $file, $this->marker_suffix(), $code );
if ( ! $markers_inserted ) { return $cannot_write_message; } return true; }
/** * Remove rules from .htaccess file. * * @since 3.8.0 * * @return bool|string True on success. String with the error message on failure. */ public function unsave_htaccess() { if ( ! $this->is_htaccess_written() ) { return esc_html__( "The .htaccess file doesn't contain the WebP rules from Smush.", 'wp-smushit' ); }
$cannot_write_message = esc_html__( 'We were unable to automatically remove the rules. We recommend trying to remove the rules manually. If you don’t have access to the .htaccess file to remove it manually, please consult with your hosting provider to change the configuration on the server.', 'wp-smushit' ); if ( ! $this->is_htaccess_writable() ) { return $cannot_write_message; }
$file = $this->htaccess_file(); $markers_inserted = insert_with_markers( $file, $this->marker_suffix(), '' );
if ( ! $markers_inserted ) { return $cannot_write_message; } return true; } }
|