-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathAbstractProcess.php
More file actions
1957 lines (1648 loc) · 56.1 KB
/
AbstractProcess.php
File metadata and controls
1957 lines (1648 loc) · 56.1 KB
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Imagify\Optimization\Process;
use Imagify\Deprecated\Traits\Optimization\Process\AbstractProcessDeprecatedTrait;
use Imagify\Job\MediaOptimization;
use Imagify\Optimization\Data\DataInterface;
use Imagify\Optimization\File;
defined( 'ABSPATH' ) || die( 'Cheatin’ uh?' );
/**
* Abstract class used to optimize medias.
*
* @since 1.9
* @author Grégory Viguier
*/
abstract class AbstractProcess implements ProcessInterface {
use AbstractProcessDeprecatedTrait;
/**
* The suffix used in the thumbnail size name.
*
* @var string
* @since 1.9
* @author Grégory Viguier
*/
const WEBP_SUFFIX = '@imagify-webp';
/**
* The suffix used in file name to create a temporary copy of the full size.
*
* @var string
* @since 1.9
* @author Grégory Viguier
*/
const TMP_SUFFIX = '@imagify-tmp';
/**
* Used for the name of the transient telling if a media is locked.
* %1$s is the context, %2$s is the media ID.
*
* @var string
* @since 1.9
* @author Grégory Viguier
*/
const LOCK_NAME = 'imagify_%1$s_%2$s_process_locked';
/**
* The data optimization object.
*
* @var DataInterface
* @since 1.9
* @access protected
* @author Grégory Viguier
*/
protected $data;
/**
* The optimization data format.
*
* @var array
* @since 1.9
* @access protected
* @author Grégory Viguier
*/
protected $data_format = [
'level' => null,
'status' => null,
'success' => null,
'error' => null,
'original_size' => null,
'optimized_size' => null,
];
/**
* A File instance.
*
* @var File
* @since 1.9
* @access protected
* @author Grégory Viguier
*/
protected $file;
/**
* Filesystem object.
*
* @var Imagify_Filesystem
* @since 1.9
* @access protected
* @author Grégory Viguier
*/
protected $filesystem;
/**
* Used to cache the plugin’s options.
*
* @var array
* @since 1.9
* @access protected
* @author Grégory Viguier
*/
protected $options = [];
/**
* The constructor.
*
* @since 1.9
* @access public
* @see self::constructor_accepts()
* @author Grégory Viguier
*
* @param mixed $id An ID, or whatever type the constructor accepts.
*/
public function __construct( $id ) {
if ( $id instanceof DataInterface ) {
$this->data = $id;
} elseif ( static::constructor_accepts( $id ) ) {
$data_class = str_replace( '\\Optimization\\Process\\', '\\Optimization\\Data\\', get_called_class() );
$data_class = '\\' . ltrim( $data_class, '\\' );
$this->data = new $data_class( $id );
} else {
$this->data = false;
}
$this->filesystem = \Imagify_Filesystem::get_instance();
}
/**
* Tell if the given entry can be accepted in the constructor.
*
* @since 1.9
* @access public
* @author Grégory Viguier
*
* @param mixed $id Whatever.
* @return bool
*/
public static function constructor_accepts( $id ) {
if ( $id instanceof DataInterface ) {
return true;
}
$data_class = str_replace( '\\Optimization\\Process\\', '\\Optimization\\Data\\', get_called_class() );
$data_class = '\\' . ltrim( $data_class, '\\' );
return $data_class::constructor_accepts( $id );
}
/**
* Get the data instance.
*
* @since 1.9
* @access public
* @author Grégory Viguier
*
* @return DataInterface|false
*/
public function get_data() {
return $this->data;
}
/**
* Get the media instance.
*
* @since 1.9
* @access public
* @author Grégory Viguier
*
* @return MediaInterface|false
*/
public function get_media() {
if ( ! $this->get_data() ) {
return false;
}
return $this->get_data()->get_media();
}
/**
* Get the File instance of the original file.
*
* @since 1.9.8
* @access public
* @author Grégory Viguier
*
* @return File|false
*/
public function get_original_file() {
if ( isset( $this->file ) ) {
return $this->file;
}
$this->file = false;
if ( $this->get_media() ) {
$this->file = new File( $this->get_media()->get_raw_original_path() );
}
return $this->file;
}
/**
* Get the File instance of the full size file.
*
* @since 1.9.8
* @access public
* @author Grégory Viguier
*
* @return File|false
*/
public function get_fullsize_file() {
if ( isset( $this->file ) ) {
return $this->file;
}
$this->file = false;
if ( $this->get_media() ) {
$this->file = new File( $this->get_media()->get_raw_fullsize_path() );
}
return $this->file;
}
/**
* Tell if the current media is valid.
*
* @since 1.9
* @access public
* @author Grégory Viguier
*
* @return bool
*/
public function is_valid() {
return $this->get_media() && $this->get_media()->is_valid();
}
/**
* Tell if the current user is allowed to operate Imagify in this context.
*
* @since 1.9
* @access public
* @author Grégory Viguier
*
* @param string $describer Capacity describer. See \Imagify\Context\ContextInterface->get_capacity() for possible values. Can also be a "real" user capacity.
* @return bool
*/
public function current_user_can( $describer ) {
if ( ! $this->is_valid() ) {
return false;
}
$media = $this->get_media();
return $media->get_context_instance()->current_user_can( $describer, $media->get_id() );
}
/** ----------------------------------------------------------------------------------------- */
/** OPTIMIZATION ============================================================================ */
/** ----------------------------------------------------------------------------------------- */
/**
* Optimize a media files.
*
* @since 1.9
* @access public
* @author Grégory Viguier
*
* @param int $optimization_level The optimization level (0=normal, 1=aggressive, 2=ultra).
* @param array $args An array of optionnal arguments.
* @return bool|WP_Error True if successfully launched. A \WP_Error instance on failure.
*/
public function optimize( $optimization_level = null, $args = [] ) {
if ( ! $this->is_valid() ) {
return new \WP_Error( 'invalid_media', __( 'This media is not valid.', 'imagify' ) );
}
$media = $this->get_media();
if ( ! $media->is_supported() ) {
return new \WP_Error( 'media_not_supported', __( 'This media is not supported.', 'imagify' ) );
}
$data = $this->get_data();
if ( $data->is_optimized() ) {
return new \WP_Error( 'optimized', __( 'This media has already been optimized by Imagify.', 'imagify' ) );
}
if ( $data->is_already_optimized() && $this->has_webp() ) {
// If already optimized but has WebP, delete WebP versions and optimization data.
$data->delete_optimization_data();
$deleted = $this->delete_webp_files();
if ( is_wp_error( $deleted ) ) {
return new \WP_Error( 'webp_not_deleted', __( 'Previous WebP files could not be deleted.', 'imagify' ) );
}
}
$sizes = $media->get_media_files();
$args = is_array( $args ) ? $args : [];
$args['hook_suffix'] = 'optimize_media';
// Optimize.
return $this->optimize_sizes( array_keys( $sizes ), $optimization_level, $args );
}
/**
* Re-optimize a media files with a different level.
*
* @since 1.9
* @access public
* @author Grégory Viguier
*
* @param int $optimization_level The optimization level (0=normal, 1=aggressive, 2=ultra).
* @param array $args An array of optionnal arguments.
* @return bool|WP_Error True if successfully launched. A \WP_Error instance on failure.
*/
public function reoptimize( $optimization_level = null, $args = [] ) {
if ( ! $this->is_valid() ) {
return new \WP_Error( 'invalid_media', __( 'This media is not valid.', 'imagify' ) );
}
$media = $this->get_media();
if ( ! $media->is_supported() ) {
return new \WP_Error( 'media_not_supported', __( 'This media is not supported.', 'imagify' ) );
}
$data = $this->get_data();
if ( ! $data->get_optimization_status() ) {
return new \WP_Error( 'not_processed_yet', __( 'This media has not been processed yet.', 'imagify' ) );
}
$optimization_level = $this->sanitize_optimization_level( $optimization_level );
if ( $data->get_optimization_level() === $optimization_level ) {
return new \WP_Error( 'identical_optimization_level', __( 'This media is already optimized with this level.', 'imagify' ) );
}
$this->restore();
$sizes = $media->get_media_files();
$args = is_array( $args ) ? $args : [];
$args['hook_suffix'] = 'reoptimize_media';
// Optimize.
return $this->optimize_sizes( array_keys( $sizes ), $optimization_level, $args );
}
/**
* Optimize several file sizes by pushing tasks into the queue.
*
* @since 1.9
* @access public
* @see MediaOptimization->task_before()
* @see MediaOptimization->task_after()
* @author Grégory Viguier
*
* @param array $sizes An array of media sizes (strings). Use "full" for the size of the main file.
* @param int $optimization_level The optimization level (0=normal, 1=aggressive, 2=ultra).
* @param array $args {
* An array of optionnal arguments.
*
* @type string $hook_suffix Suffix used to trigger hooks before and after optimization.
* }
* @return bool|WP_Error True if successfully launched. A \WP_Error instance on failure.
*/
public function optimize_sizes( $sizes, $optimization_level = null, $args = [] ) {
if ( ! $this->is_valid() ) {
return new \WP_Error( 'invalid_media', __( 'This media is not valid.', 'imagify' ) );
}
$media = $this->get_media();
if ( ! $media->is_supported() ) {
return new \WP_Error( 'media_not_supported', __( 'This media is not supported.', 'imagify' ) );
}
if ( ! $sizes ) {
return new \WP_Error( 'no_sizes', __( 'No sizes given to be optimized.', 'imagify' ) );
}
if ( empty( $args['locked'] ) ) {
if ( $this->is_locked() ) {
return new \WP_Error( 'media_locked', __( 'This media is already being processed.', 'imagify' ) );
}
$this->lock();
}
if ( $media->is_image() ) {
if ( $this->get_option( 'convert_to_webp' ) ) {
// Add WebP convertion.
$files = $media->get_media_files();
foreach ( $sizes as $size_name ) {
if ( empty( $files[ $size_name ] ) ) {
continue;
}
if ( 'image/webp' === $files[ $size_name ]['mime-type'] ) {
continue;
}
if ( in_array( $size_name . static::WEBP_SUFFIX, $sizes, true ) ) {
continue;
}
array_unshift( $sizes, $size_name . static::WEBP_SUFFIX );
}
}
if ( ! $media->get_context_instance()->can_backup() && ! $media->get_backup_path() && ! $this->get_data()->get_size_data( 'full', 'success' ) ) {
/**
* Backup is NOT activated, and a backup file does NOT exist yet, and the full size is NOT optimized yet.
* WebP conversion needs a backup file, even a temporary one: we’ll create one.
*/
$webp = false;
foreach ( $sizes as $size_name ) {
if ( $this->is_size_webp( $size_name ) ) {
$webp = true;
break;
}
}
if ( $webp ) {
// We have at least one WebP conversion to do: create a temporary backup.
$backuped = $this->get_original_file()->backup( $media->get_raw_backup_path() );
if ( $backuped ) {
// See \Imagify\Job\MediaOptimization->delete_backup().
$args['delete_backup'] = true;
}
}
}
}
$sizes = array_unique( $sizes );
$optimization_level = $this->sanitize_optimization_level( $optimization_level );
/**
* Filter the data sent to the optimization process.
*
* @since 1.9
* @author Grégory Viguier
*
* @param array $new_args Additional data to send to the optimization process.
* @param array $args Current data sent to the process.
* @param ProcessInterface $process The current optimization process.
* @param array $sizes Sizes being processed.
* @param int $optimization_level Optimization level.
*/
$new_args = apply_filters( 'imagify_optimize_sizes_args', [], $args, $this, $sizes, $optimization_level );
if ( $new_args && is_array( $new_args ) ) {
$args = array_merge( $new_args, $args );
}
/**
* Push the item to the queue, save the queue in the DB, empty the queue.
* A "batch" is then created in the DB with this unique item, it is then free to loop through its steps (files) without another item interfering (each media optimization has its own dedicated batch/queue).
*/
MediaOptimization::get_instance()->push_to_queue( [
'id' => $media->get_id(),
'sizes' => $sizes,
'optimization_level' => $optimization_level,
'process_class' => get_class( $this ),
'data' => $args,
] )->save();
return true;
}
/**
* Optimize one file with Imagify directly.
*
* @since 1.9
* @access public
* @author Grégory Viguier
*
* @param string $size The media size.
* @param int $optimization_level The optimization level (0=normal, 1=aggressive, 2=ultra).
* @return array|\WP_Error Optimized image data. A \WP_Error object on error.
*/
public function optimize_size( $size, $optimization_level = null ) {
if ( ! $this->is_valid() ) { // Bail out.
return new \WP_Error( 'invalid_media', __( 'This media is not valid.', 'imagify' ) );
}
$media = $this->get_media();
$sizes = $media->get_media_files();
$thumb_size = $size;
$webp = $this->is_size_webp( $size );
$path_is_temp = false;
if ( $webp ) {
// We'll make sure the file is an image later.
$thumb_size = $webp; // Contains the name of the non-WebP size.
$webp = true;
}
if ( empty( $sizes[ $thumb_size ]['path'] ) ) { // Bail out.
// This size is not in our list.
return new \WP_Error(
'unknown_size',
sprintf(
/* translators: %s is a size name. */
__( 'The size %s is unknown.', 'imagify' ),
'<code>' . esc_html( $thumb_size ) . '</code>'
)
);
}
if ( $this->get_data()->get_size_data( $size, 'success' ) ) { // Bail out.
// This size is already optimized with Imagify, and must not be optimized again.
if ( $webp ) {
return new \WP_Error(
'size_is_successfully_optimized',
sprintf(
/* translators: %s is a size name. */
__( 'The WebP format for the size %s already exists.', 'imagify' ),
'<code>' . esc_html( $thumb_size ) . '</code>'
)
);
} else {
return new \WP_Error(
'size_is_successfully_optimized',
sprintf(
/* translators: %s is a size name. */
__( 'The size %s is already optimized by Imagify.', 'imagify' ),
'<code>' . esc_html( $thumb_size ) . '</code>'
)
);
}
}
/**
* Starting from here, errors will be stored in the optimization data of the size.
*/
$path = $sizes[ $thumb_size ]['path'];
$optimization_level = $this->sanitize_optimization_level( $optimization_level );
if ( $webp && $this->get_data()->get_size_data( $thumb_size, 'success' ) ) {
// We want a WebP version but the source file is already optimized by Imagify.
$result = $this->create_temporary_copy( $thumb_size, $sizes );
if ( ! $result ) { // Bail out.
// Could not create a copy of the non-WebP version.
$response = new \WP_Error(
'non_webp_copy_failed',
sprintf(
/* translators: %s is a size name. */
__( 'Could not create an unoptimized copy of the size %s.', 'imagify' ),
'<code>' . esc_html( $thumb_size ) . '</code>'
)
);
$this->update_size_optimization_data( $response, $size, $optimization_level );
return $response;
}
/**
* $path now targets a temporary file.
*/
$path = $this->get_temporary_copy_path( $thumb_size, $sizes );
$path_is_temp = true;
}
$file = new File( $path ); // Original file or temporary copy.
if ( ! $file->is_supported( $media->get_allowed_mime_types() ) ) { // Bail out.
// This file type is not supported.
$extension = $file->get_extension();
if ( '' === $extension ) {
$response = new \WP_Error(
'no_extension',
__( 'With no extension, this file cannot be optimized.', 'imagify' )
);
} else {
$response = new \WP_Error(
'extension_not_supported',
sprintf(
/* translators: %s is a file extension. */
__( '%s cannot be optimized.', 'imagify' ),
'<code>' . esc_html( strtolower( $extension ) ) . '</code>'
)
);
}
if ( $path_is_temp ) {
$this->filesystem->delete( $path );
}
$this->update_size_optimization_data( $response, $size, $optimization_level );
return $response;
}
if ( $webp && ! $file->is_image() ) { // Bail out.
if ( $path_is_temp ) {
$this->filesystem->delete( $path );
}
$response = new \WP_Error(
'no_webp',
__( 'This file is not an image and cannot be converted to WebP format.', 'imagify' )
);
$this->update_size_optimization_data( $response, $size, $optimization_level );
return $response;
}
$is_disabled = ! empty( $sizes[ $thumb_size ]['disabled'] );
/**
* Fires before optimizing a file.
* Return a \WP_Error object to prevent the optimization.
*
* @since 1.9
* @author Grégory Viguier
*
* @param null|\WP_Error $response Null by default. Return a \WP_Error object to prevent optimization.
* @param ProcessInterface $process The optimization process instance.
* @param File $file The file instance. If $webp is true, $file references the non-WebP file.
* @param string $thumb_size The media size.
* @param int $optimization_level The optimization level (0=normal, 1=aggressive, 2=ultra).
* @param bool $webp The image will be converted to WebP.
* @param bool $is_disabled Tell if this size is disabled from optimization.
*/
$response = apply_filters( 'imagify_before_optimize_size', null, $this, $file, $thumb_size, $optimization_level, $webp, $is_disabled );
if ( ! is_wp_error( $response ) ) {
if ( $is_disabled ) {
// This size must not be optimized.
$response = new \WP_Error(
'unauthorized_size',
sprintf(
/* translators: %s is a size name. */
__( 'The size %s is not authorized to be optimized. Update your Imagify settings if you want to optimize it.', 'imagify' ),
'<code>' . esc_html( $thumb_size ) . '</code>'
)
);
} elseif ( ! $this->filesystem->exists( $file->get_path() ) ) {
$response = new \WP_Error(
'file_not_exists',
sprintf(
/* translators: %s is a file path. */
__( 'The file %s does not seem to exist.', 'imagify' ),
'<code>' . esc_html( $this->filesystem->make_path_relative( $file->get_path() ) ) . '</code>'
)
);
} elseif ( $webp && ! $this->can_create_webp_version( $file->get_path() ) ) {
$response = new \WP_Error(
'is_animated_gif',
__( 'This file is an animated gif: since Imagify does not support animated WebP, WebP creation for animated gif is disabled.', 'imagify' )
);
} elseif ( ! $this->filesystem->is_writable( $file->get_path() ) ) {
$response = new \WP_Error(
'file_not_writable',
sprintf(
/* translators: %s is a file path. */
__( 'The file %s does not seem to be writable.', 'imagify' ),
'<code>' . esc_html( $this->filesystem->make_path_relative( $file->get_path() ) ) . '</code>'
)
);
} else {
// Maybe resize the file.
$response = $this->maybe_resize( $thumb_size, $file );
if ( ! is_wp_error( $response ) ) {
// Resizing succeeded: optimize the file.
$response = $file->optimize( [
'backup' => ! $response['backuped'] && $this->can_backup( $size ),
'backup_path' => $media->get_raw_backup_path(),
'backup_source' => 'full' === $thumb_size ? $media->get_original_path() : null,
'optimization_level' => $optimization_level,
'convert' => $webp ? 'webp' : '',
'keep_exif' => $this->can_keep_exif( $size ),
'context' => $media->get_context(),
'original_size' => $response['file_size'],
] );
$response = $this->compare_webp_file_size( [
'response' => $response,
'file' => $file,
'is_webp' => $webp,
'non_webp_thumb_size' => $thumb_size,
'non_webp_file_path' => $sizes[ $thumb_size ]['path'], // Don't use $path nor $file->get_path(), it may return the path to a temporary file.
'optimization_level' => $optimization_level,
] );
}
}
}
$data = $this->update_size_optimization_data( $response, $size, $optimization_level );
/**
* Fires after optimizing a file.
*
* @since 1.9
* @author Grégory Viguier
*
* @param ProcessInterface $process The optimization process instance.
* @param File $file The file instance.
* @param string $thumb_size The media size.
* @param int $optimization_level The optimization level (0=normal, 1=aggressive, 2=ultra).
* @param bool $webp The image was supposed to be converted to WebP.
* @param bool $is_disabled Tell if this size is disabled from optimization.
*/
do_action( 'imagify_after_optimize_size', $this, $file, $thumb_size, $optimization_level, $webp, $is_disabled );
if ( ! $path_is_temp ) {
return $data;
}
// Delete the temporary copy.
$this->filesystem->delete( $path );
if ( is_wp_error( $response ) ) {
return $data;
}
// Rename the optimized file.
$destination_path = str_replace( static::TMP_SUFFIX . '.', '.', $file->get_path() );
$this->filesystem->move( $file->get_path(), $destination_path, true );
return $data;
}
/**
* Compare the file size of a file and its WebP version: if the WebP version is heavier than the non-WebP file, delete it.
*
* @since 1.9.4
* @access protected
* @author Grégory Viguier
*
* @param array $args {
* A list of mandatory arguments.
*
* @type \sdtClass|\WP_Error $response Optimized image data. A \WP_Error object on error.
* @type File $file The File instance of the file currently being optimized.
* @type bool $is_webp Tell if we're requesting a WebP file.
* @type string $non_webp_thumb_size Name of the corresponding non-WebP thumbnail size. If we're not creating a WebP file, this corresponds to the current thumbnail size.
* @type string $non_webp_file_path Path to the corresponding non-WebP file. If we're not creating a WebP file, this corresponds to the current file path.
* @type string $optimization_level The optimization level.
* }
* @return \sdtClass|\WP_Error Optimized image data. A \WP_Error object on error.
*/
protected function compare_webp_file_size( $args ) {
static $keep_large_webp;
if ( ! isset( $keep_large_webp ) ) {
/**
* Allow to not store WebP images that are larger than their non-WebP version.
*
* @since 1.9.4
* @author Grégory Viguier
*
* @param bool $keep_large_webp Set to false if you prefer your visitors over your Pagespeed score. Default value is true.
*/
$keep_large_webp = apply_filters( 'imagify_keep_large_webp', true );
}
if ( $keep_large_webp || is_wp_error( $args['response'] ) || ! $args['file']->is_image() ) {
return $args['response'];
}
// Optimization succeeded.
if ( $args['is_webp'] ) {
/**
* We just created a WebP version:
* Check if it is lighter than the (maybe optimized) non-WebP file.
*/
$data = $this->get_data()->get_size_data( $args['non_webp_thumb_size'] );
if ( ! $data ) {
// We haven’t tried to optimize the non-WebP size yet.
return $args['response'];
}
if ( ! empty( $data['optimized_size'] ) ) {
// The non-WebP size is optimized, we know the file size.
$non_webp_file_size = $data['optimized_size'];
} else {
// The non-WebP size is "already optimized" or "error": grab the file size directly from the file.
$non_webp_file_size = $this->filesystem->size( $args['non_webp_file_path'] );
}
if ( ! $non_webp_file_size || $non_webp_file_size > $args['response']->new_size ) {
// The new WebP file is lighter.
return $args['response'];
}
// The new WebP file is heavier than the non-WebP file: delete it and return an error.
$this->filesystem->delete( $args['file']->get_path() );
return new \WP_Error(
'webp_heavy',
sprintf(
/* translators: %s is a size name. */
__( 'The WebP version of the size %s is heavier than its non-WebP version.', 'imagify' ),
'<code>' . esc_html( $args['non_webp_thumb_size'] ) . '</code>'
)
);
}
/**
* We just created a non-WebP version:
* Check if its WebP version file is lighter than this one.
*/
$webp_size = $args['non_webp_thumb_size'] . static::WEBP_SUFFIX;
$webp_file_size = $this->get_data()->get_size_data( $webp_size, 'optimized_size' );
if ( ! $webp_file_size || $webp_file_size < $args['response']->new_size ) {
// The WebP file is lighter than this one.
return $args['response'];
}
// The new optimized file is lighter than the WebP file: delete the WebP file and store an error.
$webp_path = $args['file']->get_path_to_webp();
if ( $webp_path && $this->filesystem->is_writable( $webp_path ) ) {
$this->filesystem->delete( $webp_path );
}
$webp_response = new \WP_Error(
'webp_heavy',
sprintf(
/* translators: %s is a size name. */
__( 'The WebP version of the size %s is heavier than its non-WebP version.', 'imagify' ),
'<code>' . esc_html( $args['non_webp_thumb_size'] ) . '</code>'
)
);
$this->update_size_optimization_data( $webp_response, $webp_size, $args['optimization_level'] );
return $args['response'];
}
/**
* Restore the media files from the backup file.
*
* @since 1.9
* @access public
* @author Grégory Viguier
*
* @return bool|WP_Error True on success. A \WP_Error instance on failure.
*/
public function restore() {
if ( ! $this->is_valid() ) {
return new \WP_Error( 'invalid_media', __( 'This media is not valid.', 'imagify' ) );
}
$media = $this->get_media();
if ( ! $media->is_supported() ) {
return new \WP_Error( 'media_not_supported', __( 'This media is not supported.', 'imagify' ) );
}
if ( ! $media->has_backup() ) {
return new \WP_Error( 'no_backup', __( 'This media has no backup file.', 'imagify' ) );
}
if ( $this->is_locked() ) {
return new \WP_Error( 'media_locked', __( 'This media is already being processed.', 'imagify' ) );
}
$this->lock( 'restoring' );
$backup_path = $media->get_backup_path();
$original_path = $media->get_raw_original_path();
if ( $backup_path === $original_path ) {
// Uh?!
$this->unlock();
return new \WP_Error( 'same_path', __( 'Image path and backup path are identical.', 'imagify' ) );
}
$dest_dir = $this->filesystem->dir_path( $original_path );
if ( ! $this->filesystem->exists( $dest_dir ) ) {
$this->filesystem->make_dir( $dest_dir );
}
$dest_file_is_writable = ! $this->filesystem->exists( $original_path ) || $this->filesystem->is_writable( $original_path );
if ( ! $dest_file_is_writable || ! $this->filesystem->is_writable( $dest_dir ) ) {
$this->unlock();
return new \WP_Error( 'destination_not_writable', __( 'The image to replace is not writable.', 'imagify' ) );
}
// Get some data before doing anything.
$data = $this->get_data()->get_optimization_data();
$files = $media->get_media_files();
/**
* Fires before restoring a media.
* Return a \WP_Error object to prevent the restoration.
*
* @since 1.9
* @author Grégory Viguier
*
* @param null|\WP_Error $response Null by default. Return a \WP_Error object to prevent optimization.
* @param ProcessInterface $process Instance of this process.
*/
$response = apply_filters( 'imagify_before_restore_media', null, $this );
if ( ! is_wp_error( $response ) ) {
// Create the original image from the backup.
$response = $this->filesystem->copy( $backup_path, $original_path, true );
if ( ! $response ) {
// Failure.
$response = new \WP_Error( 'copy_failed', __( 'The backup file could not be copied over the optimized one.', 'imagify' ) );
} else {
// Backup successfully copied.
$this->filesystem->chmod_file( $original_path );
// Remove old optimization data.
$this->get_data()->delete_optimization_data();
if ( $media->is_image() ) {
// Restore the original dimensions in the database.
$media->update_dimensions();
// Delete the WebP version.
$this->delete_webp_file( $original_path );
// Restore the thumbnails.
$response = $this->restore_thumbnails();
}
}
}
/**
* Fires after restoring a media.
*
* @since 1.9
* @author Grégory Viguier
*
* @param ProcessInterface $process Instance of this process.
* @param bool|WP_Error $response The result of the operation: true on success, a WP_Error object on failure.
* @param array $files The list of files, before restoring them.
* @param array $data The optimization data, before deleting it.
*/
do_action( 'imagify_after_restore_media', $this, $response, $files, $data );
$this->unlock();
return $response;
}
/**
* Restore the thumbnails.
*
* @since 1.9
* @access protected
* @author Grégory Viguier
*
* @return bool|WP_Error True on success. A \WP_Error instance on failure.
*/
protected function restore_thumbnails() {
$media = $this->get_media();
/**
* Delete the WebP versions.
* If the full size file and the original file are not the same, the full size is considered like a thumbnail.
* In that case we must also delete the WebP file associated to the full size.
*/
$keep_full_webp = $media->get_raw_original_path() === $media->get_raw_fullsize_path();
$this->delete_webp_files( $keep_full_webp );
// Generate new thumbnails.
return $media->generate_thumbnails();
}
/** ----------------------------------------------------------------------------------------- */
/** BACKUP FILE ============================================================================= */
/** ----------------------------------------------------------------------------------------- */
/**
* Delete the backup file.
*
* @since 1.9
* @access public
* @author Grégory Viguier
*/
public function delete_backup() {
if ( ! $this->is_valid() ) {