Repository navigation
Expand file tree
/
Copy pathclass-tiny-image.php
More file actions
904 lines (781 loc) · 26.1 KB
/
Copy pathclass-tiny-image.php
File metadata and controls
904 lines (781 loc) · 26.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
<?php
/*
* Tiny Compress Images - WordPress plugin.
* Copyright (C) 2015-2018 Tinify B.V.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
class Tiny_Image {
const ORIGINAL = 0;
const ORIGINAL_UNSCALED = 'original_unscaled';
/** @var Tiny_Settings */
private $settings;
private $id;
private $name;
private $wp_metadata;
private $sizes = array();
private $statistics = array();
public function __construct(
$settings,
$id,
$wp_metadata = null,
$tiny_metadata = null,
$active_sizes = null,
$active_tinify_sizes = null
) {
$this->settings = $settings;
$this->id = $id;
$this->wp_metadata = $wp_metadata;
$this->parse_wp_metadata();
$this->parse_tiny_metadata( $tiny_metadata );
$this->detect_duplicates( $active_sizes, $active_tinify_sizes );
}
private function parse_wp_metadata() {
if ( ! is_array( $this->wp_metadata ) ) {
$this->wp_metadata = wp_get_attachment_metadata( $this->id );
}
if ( ! is_array( $this->wp_metadata ) || ! isset( $this->wp_metadata['file'] ) ) {
/*
No file metadata found, this might be another plugin messing with
metadata. Simply ignore this! */
return;
}
$upload_dir = wp_upload_dir();
$path_prefix = $upload_dir['basedir'] . '/';
$path_info = pathinfo( $this->wp_metadata['file'] );
if ( isset( $path_info['dirname'] ) ) {
$path_prefix .= $path_info['dirname'] . '/';
}
/*
Do not use pathinfo for getting the filename.
It doesn't work when the filename starts with a special character. */
$path_parts = explode( '/', $this->wp_metadata['file'] );
$this->name = end( $path_parts );
$filename = $path_prefix . $this->name;
$this->sizes[ self::ORIGINAL ] = new Tiny_Image_Size( $filename );
if ( isset( $this->wp_metadata['original_image'] ) ) {
$this->sizes[ self::ORIGINAL_UNSCALED ] = new Tiny_Image_Size(
$path_prefix . wp_basename( $this->wp_metadata['original_image'] )
);
}
// Ensure 'sizes' exists and is an array to prevent PHP Warnings
$sizes = isset( $this->wp_metadata['sizes'] ) && is_array( $this->wp_metadata['sizes'] )
? $this->wp_metadata['sizes']
: array();
$sanitized_sizes = array();
foreach ( $sizes as $size_name => $size_info ) {
// size is valid when its an array and has a file
if ( is_array( $size_info ) && isset( $size_info['file'] ) ) {
// Add to sanitized metadata
$sanitized_sizes[ $size_name ] = $size_info;
$this->sizes[ $size_name ] = new Tiny_Image_Size(
$path_prefix . wp_basename( $size_info['file'] )
);
}
}
// Update the metadata with only the valid sizes found
$this->wp_metadata['sizes'] = $sanitized_sizes;
}
private function detect_duplicates( $active_sizes, $active_tinify_sizes ) {
$filenames = array();
if ( is_array( $this->wp_metadata )
&& isset( $this->wp_metadata['file'] )
&& isset( $this->wp_metadata['sizes'] )
&& is_array( $this->wp_metadata['sizes'] ) ) {
if ( null == $active_sizes ) {
$active_sizes = $this->settings->get_sizes();
}
if ( null == $active_tinify_sizes ) {
$active_tinify_sizes = $this->settings->get_active_tinify_sizes();
}
foreach ( $this->wp_metadata['sizes'] as $size_name => $size ) {
if ( $this->sizes[ $size_name ]->has_been_compressed()
&& array_key_exists( $size_name, $active_sizes ) ) {
$filenames = $this->duplicate_check( $filenames, $size['file'], $size_name );
}
}
foreach ( $this->wp_metadata['sizes'] as $size_name => $size ) {
if ( in_array( $size_name, $active_tinify_sizes, true ) ) {
$filenames = $this->duplicate_check( $filenames, $size['file'], $size_name );
}
}
foreach ( $this->wp_metadata['sizes'] as $size_name => $size ) {
if ( array_key_exists( $size_name, $active_sizes ) ) {
$filenames = $this->duplicate_check( $filenames, $size['file'], $size_name );
}
}
foreach ( $this->wp_metadata['sizes'] as $size_name => $size ) {
$filenames = $this->duplicate_check( $filenames, $size['file'], $size_name );
}
}
}
private function duplicate_check( $filenames, $file, $size_name ) {
if ( isset( $filenames[ $file ] ) ) {
if ( $filenames[ $file ] != $size_name ) {
$this->sizes[ $size_name ]->mark_duplicate( $filenames[ $file ] );
}
} else {
$filenames[ $file ] = $size_name;
}
return $filenames;
}
/**
* Will retrieve compression meta data for the given post_id.
*
* As migrations on large libraries can take longer, we will fall back on
* the legacy key on migrating. We can remove the LEGACY_META_KEY on 3.8.0.
*
* @since 3.7.0
*
* @param int $post_id Attachment ID.
* @return mixed The stored tiny metadata, or '' when none exists.
*/
public static function get_tiny_metadata( $post_id ) {
$tiny_metadata = get_post_meta( $post_id, Tiny_Config::META_KEY, true );
if ( empty( $tiny_metadata ) ) {
$tiny_metadata = get_post_meta( $post_id, Tiny_Config::LEGACY_META_KEY, true );
}
return $tiny_metadata;
}
private function parse_tiny_metadata( $tiny_metadata = null ) {
if ( is_null( $tiny_metadata ) ) {
$tiny_metadata = self::get_tiny_metadata( $this->id );
}
if ( $tiny_metadata ) {
foreach ( $tiny_metadata as $size => $meta ) {
if ( ! isset( $this->sizes[ $size ] ) ) {
if ( self::is_retina( $size ) && Tiny_Settings::wr2x_active() ) {
$size_name = rtrim( $size, '_wr2x' );
if ( 'original' === $size_name ) {
$size_name = '0';
}
$retina_path = wr2x_get_retina(
$this->sizes[ $size_name ]->filename
);
$this->sizes[ $size ] = new Tiny_Image_Size( $retina_path );
} else {
$this->sizes[ $size ] = new Tiny_Image_Size();
}
}
$this->sizes[ $size ]->meta = $meta;
}
}
}
public function get_id() {
return $this->id;
}
public function get_name() {
return $this->name;
}
public function get_wp_metadata() {
return $this->wp_metadata;
}
public function file_type_allowed() {
return in_array(
$this->get_mime_type(),
array( 'image/jpeg', 'image/png', 'image/webp' ),
true
);
}
public function get_mime_type() {
return get_post_mime_type( $this->id );
}
public function compress() {
Tiny_Logger::debug(
'compress',
array(
'image_id' => $this->id,
'name' => $this->name,
)
);
if ( $this->settings->get_compressor() === null || ! $this->file_type_allowed() ) {
return;
}
/**
* Fires before an image is sent for compression.
*
* The metadata is passed along because it has not necessarily been
* stored yet. On upload the compression runs from within
* `wp_generate_attachment_metadata`, before WordPress saves it.
*
* @since 3.7.0
*
* @param int $attachment_id The attachment ID
* @param array $wp_metadata The attachment metadata
*/
do_action(
'tiny_image_before_compression',
$this->id,
$this->wp_metadata
);
$success = 0;
$failed = 0;
$active_tinify_sizes = $this->settings->get_active_tinify_sizes();
if ( $this->settings->get_conversion_enabled() ) {
$uncompressed_sizes = $this->filter_image_sizes( 'uncompressed', $active_tinify_sizes );
$unconverted_sizes = $this->filter_image_sizes( 'unconverted', $active_tinify_sizes );
$unprocessed_sizes = $uncompressed_sizes + $unconverted_sizes;
} else {
$unprocessed_sizes = $this->filter_image_sizes( 'uncompressed', $active_tinify_sizes );
}
$compressor = $this->settings->get_compressor();
$convert_to = $this->convert_to();
foreach ( $unprocessed_sizes as $size_name => $size ) {
if ( ! $size->is_duplicate() ) {
$size->add_tiny_meta_start();
$this->update_tiny_post_meta();
$resize = $this->settings->get_resize_options( $size_name );
$preserve = $this->settings->get_preserve_options( $size_name );
Tiny_Logger::debug(
'compress size',
array(
'image_id' => $this->id,
'size' => $size_name,
'resize' => $resize,
'preserve' => $preserve,
'convert' => $convert_to,
'modified' => $size->modified(),
'filename' => $size->filename,
'is_duplicate' => $size->is_duplicate(),
'exists' => $size->exists(),
'has_been_compressed' => $size->has_been_compressed(),
'filesize' => $size->filesize(),
'mimetype' => $size->mimetype(),
)
);
try {
$response = $compressor->compress_file(
$size->filename,
$resize,
$preserve,
$convert_to
);
// ensure that all conversion are in the same format as the first one
$convert_to = isset( $response['convert'] ) ?
array( $response['convert']['type'] ) :
$convert_to;
$size->add_tiny_meta( $response );
++$success;
Tiny_Logger::debug(
'compress success',
array(
'size' => $size_name,
'image_id' => $this->id,
)
);
} catch ( Tiny_Exception $e ) {
$size->add_tiny_meta_error( $e );
++$failed;
Tiny_Logger::error(
'compress failed',
array(
'error' => $e->get_message(),
'size' => $size_name,
'image_id' => $this->id,
)
);
}
$this->add_wp_metadata( $size_name, $size );
$this->update_tiny_post_meta();
}// End if().
}// End foreach().
/*
Other plugins can hook into this action to execute custom logic
after the image sizes have been compressed, ie. cache flushing.
*/
do_action( 'tiny_image_after_compression', $this->id, $success );
return array(
'success' => $success,
'failed' => $failed,
);
}
public function delete_converted_image() {
$sizes = $this->get_image_sizes();
foreach ( $sizes as $size ) {
$size->delete_converted_image_size();
}
}
public function compress_retina( $size_name, $path ) {
if ( $this->settings->get_compressor() === null || ! $this->file_type_allowed() ) {
return;
}
if ( ! isset( $this->sizes[ $size_name ] ) ) {
$this->sizes[ $size_name ] = new Tiny_Image_Size( $path );
}
$size = $this->sizes[ $size_name ];
$compressor = $this->settings->get_compressor();
$convert_to = $this->convert_to();
if ( ! $size->has_been_compressed() ) {
$size->add_tiny_meta_start();
$this->update_tiny_post_meta();
$preserve = $this->settings->get_preserve_options( $size_name );
try {
$response = $compressor->compress_file( $path, false, $preserve, $convert_to );
$size->add_tiny_meta( $response );
} catch ( Tiny_Exception $e ) {
$size->add_tiny_meta_error( $e );
}
$this->update_tiny_post_meta();
}
}
public function remove_retina_metadata() {
// Remove metadata from all sizes, as this callback only fires when all
// retina sizes are deleted.
foreach ( $this->sizes as $size_name => $size ) {
if ( self::is_retina( $size_name ) ) {
unset( $this->sizes[ $size_name ] );
}
}
$this->update_tiny_post_meta();
}
public function add_wp_metadata( $size_name, $size ) {
if ( self::is_original( $size_name ) ) {
if ( isset( $size->meta['output'] ) ) {
$output = $size->meta['output'];
if ( isset( $output['width'] ) && isset( $output['height'] ) ) {
$this->wp_metadata['width'] = $output['width'];
$this->wp_metadata['height'] = $output['height'];
$this->wp_metadata['filesize'] = $output['size'];
}
}
}
}
public function update_tiny_post_meta() {
$tiny_metadata = array();
foreach ( $this->sizes as $size_name => $size ) {
$tiny_metadata[ $size_name ] = $size->meta;
}
update_post_meta( $this->id, Tiny_Config::META_KEY, $tiny_metadata );
/*
This action is being used by WPML:
https://gist.github.com/srdjan-jcc/5c47685cda4da471dff5757ba3ce5ab1
*/
do_action( 'updated_tiny_postmeta', $this->id, Tiny_Config::META_KEY, $tiny_metadata );
}
public function get_image_sizes() {
$original = isset( $this->sizes[ self::ORIGINAL ] )
? array(
self::ORIGINAL => $this->sizes[ self::ORIGINAL ],
)
: array();
$compressed = array();
$uncompressed = array();
foreach ( $this->sizes as $size_name => $size ) {
if ( self::is_original( $size_name ) ) {
continue;
}
if ( $size->has_been_compressed() ) {
$compressed[ $size_name ] = $size;
} else {
$uncompressed[ $size_name ] = $size;
}
}
ksort( $compressed );
ksort( $uncompressed );
return $original + $compressed + $uncompressed;
}
public function get_image_size( $size = self::ORIGINAL, $create = false ) {
if ( isset( $this->sizes[ $size ] ) ) {
return $this->sizes[ $size ];
} elseif ( $create ) {
return new Tiny_Image_Size();
} else {
return null;
}
}
public function filter_image_sizes( $method, $filter_sizes = null ) {
$selection = array();
if ( is_null( $filter_sizes ) ) {
$filter_sizes = array_keys( $this->sizes );
}
foreach ( $filter_sizes as $size_name ) {
if ( ! isset( $this->sizes[ $size_name ] ) ) {
continue;
}
$tiny_image_size = $this->sizes[ $size_name ];
if ( $tiny_image_size->$method() ) {
$selection[ $size_name ] = $tiny_image_size;
}
}
return $selection;
}
public function get_count( $methods, $count_sizes = null ) {
$stats = array_fill_keys( $methods, 0 );
if ( is_null( $count_sizes ) ) {
$count_sizes = array_keys( $this->sizes );
}
foreach ( $count_sizes as $size ) {
if ( ! isset( $this->sizes[ $size ] ) ) {
continue;
}
foreach ( $methods as $method ) {
if ( $this->sizes[ $size ]->$method() ) {
++$stats[ $method ];
}
}
}
return $stats;
}
public function get_latest_error() {
$active_tinify_sizes = $this->settings->get_active_tinify_sizes();
$error_message = null;
$last_timestamp = null;
foreach ( $this->sizes as $size_name => $size ) {
if ( in_array( $size_name, $active_tinify_sizes, true ) ) {
if ( isset( $size->meta['error'] ) && isset( $size->meta['message'] ) ) {
if (
null === $last_timestamp ||
$last_timestamp < $size->meta['timestamp']
) {
$last_timestamp = $size->meta['timestamp'];
$error_message = Tiny_Helpers::truncate_text(
$size->meta['message'],
140
);
}
}
}
}
return $error_message;
}
public function get_savings( $stats ) {
$before = $stats['initial_total_size'];
$after = $stats['compressed_total_size'];
if ( 0 === $before ) {
$savings = 0;
} else {
$savings = ( $before - $after ) / $before * 100;
}
return '' . number_format( $savings, 1 );
}
public function get_statistics( $active_sizes, $active_tinify_sizes ) {
if ( $this->statistics ) {
Tiny_Logger::error( 'Strangely the image statistics are asked for again.' );
return $this->statistics;
}
$this->statistics['initial_total_size'] = 0;
$this->statistics['compressed_total_size'] = 0;
$this->statistics['image_sizes_compressed'] = 0;
$this->statistics['available_uncompressed_sizes'] = 0;
$this->statistics['image_sizes_converted'] = 0;
$this->statistics['available_unconverted_sizes'] = 0;
$this->statistics['image_sizes_optimized'] = 0;
$this->statistics['available_unoptimized_sizes'] = 0;
$conversion_enabled = $this->settings->get_conversion_enabled();
foreach ( $this->sizes as $size_name => $size ) {
// skip duplicates or inactive sizes
if ( $size->is_duplicate() || ! isset( $active_sizes[ $size_name ] ) ) {
continue;
}
$file_size = $size->filesize();
$is_active_size = in_array( $size_name, $active_tinify_sizes, true );
if ( isset( $size->meta['input'] ) ) {
$input_size = (int) $size->meta['input']['size'];
$this->statistics['initial_total_size'] += $input_size;
if ( isset( $size->meta['output'] ) ) {
$output_size = (int) $size->meta['output']['size'];
if ( $size->modified() ) {
$this->statistics['compressed_total_size'] += $file_size;
if ( $is_active_size ) {
++$this->statistics['available_uncompressed_sizes'];
}
} else {
$this->statistics['compressed_total_size'] += $output_size;
++$this->statistics['image_sizes_compressed'];
}
} else {
$this->statistics['compressed_total_size'] += $input_size;
}
} elseif ( $size->exists() ) {
$this->statistics['initial_total_size'] += $file_size;
$this->statistics['compressed_total_size'] += $file_size;
if ( $is_active_size ) {
++$this->statistics['available_uncompressed_sizes'];
}
}
if ( $is_active_size ) {
if ( $size->has_been_converted() ) {
++$this->statistics['image_sizes_converted'];
} else {
++$this->statistics['available_unconverted_sizes'];
}
$needs_compression = $size->uncompressed();
$needs_conversion = $conversion_enabled && $size->unconverted();
if ( $needs_compression || $needs_conversion ) {
++$this->statistics['available_unoptimized_sizes'];
} elseif ( $size->compressed() && ( ! $conversion_enabled
|| $size->has_been_converted() ) ) {
++$this->statistics['image_sizes_optimized'];
}
}
}// End foreach().
return $this->statistics;
}
public static function is_original( $size ) {
return self::ORIGINAL === $size;
}
/**
* Check wether given $size is the original_unscaled image size.
*
* @since 3.6.14
*
* @param string $size the size descriptor
* @return bool true if size is the original unscaled image
*/
public static function is_original_unscaled( $size ) {
return self::ORIGINAL_UNSCALED === $size;
}
public static function is_retina( $size ) {
return strrpos( $size, 'wr2x' ) === strlen( $size ) - strlen( 'wr2x' );
}
public function can_be_converted() {
return $this->settings->get_conversion_enabled() && $this->file_type_allowed();
}
/**
* Get the targeted conversion.
* If a size is already converted, then we use that size's mimetype so
* sizes never mix formats, even when the settings changed since.
* If nothing is converted yet, we use the settings conversion settings.
*
* @since 3.6.4
*
* @return array{string} mimetypes to which the image should be converted to
*/
private function convert_to() {
$convert_settings = $this->settings->get_conversion_options();
if ( ! $convert_settings['convert'] ) {
// conversion is off so return no mimetypes to convert to
return array();
}
foreach ( $this->sizes as $size ) {
if ( ! $size->converted() ) {
continue;
}
$type = $size->meta['convert']['type'];
if ( in_array( $type, array( 'image/avif', 'image/webp' ), true ) ) {
return array( $type );
}
}
return $convert_settings['convert_to'];
}
/**
* Marks the image as compressed without actually compressing it.
*
* This method parses existing metadata and delegates to each image size to mark
* itself as compressed. It considers conversion settings when marking the sizes.
* This is useful for images that are already optimized or when you want to skip
* compression while still marking them as processed in the system.
*
* @since 3.0.0
*/
public function mark_as_compressed() {
$this->parse_tiny_metadata();
$conversion_enabled = $this->settings->get_conversion_enabled();
$active_tinify_sizes = $this->settings->get_active_tinify_sizes();
if ( $this->settings->get_conversion_enabled() ) {
$uncompressed_sizes = $this->filter_image_sizes( 'uncompressed', $active_tinify_sizes );
$unconverted_sizes = $this->filter_image_sizes( 'unconverted', $active_tinify_sizes );
$unprocessed_sizes = $uncompressed_sizes + $unconverted_sizes;
} else {
$unprocessed_sizes = $this->filter_image_sizes( 'uncompressed', $active_tinify_sizes );
}
foreach ( $unprocessed_sizes as $size ) {
$size->mark_as_compressed( $conversion_enabled );
}
$this->update_tiny_post_meta();
}
/**
* Retrieves the original image of the Tiny_Image
*
*
* @return Tiny_Image_Size|false the image or false if does not exist
*/
private function get_original_image() {
$original_image = $this->get_image_size( self::ORIGINAL_UNSCALED );
if ( null === $original_image ) {
$original_image = $this->get_image_size();
}
if ( null === $original_image ) {
return false;
}
return $original_image;
}
/**
* Builds the filesystem path where the backup of the original image is
* (or would be) stored.
*
* @return string|false the backup file path, or false if there is no original image
*/
private function get_backup_path() {
$original_image = $this->get_original_image();
if ( false === $original_image ) {
return false;
}
$file_path = $original_image->filename;
$upload_dir = wp_upload_dir();
$basedir = trailingslashit( $upload_dir['basedir'] );
if ( Tiny_Helpers::str_starts_with( $file_path, $basedir ) ) {
$file_path = substr( $file_path, strlen( $basedir ) );
}
return $basedir . 'tinify_backup/' . $file_path;
}
/**
* Creates a backup copy of the original image, if one does not already exist.
*
* @return bool true on success, false on failure or if a backup already exists
*/
public function create_backup() {
$backup_file_path = $this->get_backup_path();
if ( false === $backup_file_path ) {
return false;
}
$wp_filesystem = Tiny_Helpers::get_wp_filesystem();
if ( false === $wp_filesystem ) {
return false;
}
if ( $wp_filesystem->exists( $backup_file_path ) ) {
return false;
}
$backup_dir = dirname( $backup_file_path );
if ( ! wp_mkdir_p( $backup_dir ) ) {
return false;
}
$original_image = $this->get_original_image();
return $wp_filesystem->copy( $original_image->filename, $backup_file_path );
}
/**
* Retrieves the public URL of the backup of the original image.
*
* @return string|false the backup URL, or false if no backup exists
*/
public function get_backup() {
$backup_file_path = $this->get_backup_path();
if ( false === $backup_file_path ) {
return false;
}
$wp_filesystem = Tiny_Helpers::get_wp_filesystem();
if ( false === $wp_filesystem ) {
return false;
}
if ( ! $wp_filesystem->exists( $backup_file_path ) ) {
return false;
}
$upload_dir = wp_upload_dir();
$basedir = trailingslashit( $upload_dir['basedir'] );
$baseurl = trailingslashit( $upload_dir['baseurl'] );
return str_replace( $basedir, $baseurl, $backup_file_path );
}
/**
* Regenerates all thumbnail sizes of an attachment from a file.
*
* Uses wp_create_image_subsizes() when available, which does not apply
* the `wp_generate_attachment_metadata` filter. That filter is what starts
* a compression and the image that has just been restored should be left alone.
*
* @since 3.7.0
*
* @param string $filename Absolute path of the image to regenerate from.
* @return array The regenerated attachment metadata.
*/
private function regenerate_sizes( $filename ) {
// https://developer.wordpress.org/reference/functions/wp_create_image_subsizes/
if ( function_exists( 'wp_create_image_subsizes' ) ) {
return wp_create_image_subsizes( $filename, $this->id );
}
/*
WordPress < 5.3 has no way of regenerating the sizes without applying
the filter, so it is disabled for the duration of the call. */
global $tiny_plugin;
$compress_on_upload = ( $tiny_plugin instanceof Tiny_Plugin )
? array( $tiny_plugin, 'process_attachment' )
: null;
if ( $compress_on_upload ) {
remove_filter( 'wp_generate_attachment_metadata', $compress_on_upload, 10 );
}
// https://developer.wordpress.org/reference/functions/wp_generate_attachment_metadata/
$metadata = wp_generate_attachment_metadata( $this->id, $filename );
if ( $compress_on_upload ) {
add_filter( 'wp_generate_attachment_metadata', $compress_on_upload, 10, 2 );
}
return $metadata;
}
/**
* Restores the original image from its backup.
*
* - Copies the backup file over the current original.
* - Clears compression metadata for all image sizes.
* - Regenerates all thumbnail sizes from the restored image.
* - Updates the WordPress attachment metadata.
*
* @since 3.7.0
*
* @return bool True on success, false if no backup exists or the copy fails.
*/
public function restore_backup() {
$backup_file_path = $this->get_backup_path();
if ( false === $backup_file_path ) {
return false;
}
$wp_filesystem = Tiny_Helpers::get_wp_filesystem();
if ( false === $wp_filesystem ) {
return false;
}
if ( ! $wp_filesystem->exists( $backup_file_path ) ) {
return false;
}
$original_image = $this->get_original_image();
if ( false === $original_image ) {
return false;
}
if ( ! $wp_filesystem->copy( $backup_file_path, $original_image->filename, true ) ) {
return false;
}
// Clear compression metadata for all image sizes.
foreach ( $this->sizes as $size ) {
$size->meta = array();
}
$this->update_tiny_post_meta();
// Regenerate all thumbnail sizes from the restored image.
$new_metadata = $this->regenerate_sizes( $original_image->filename );
if ( $new_metadata ) {
$this->wp_metadata = $new_metadata;
wp_update_attachment_metadata( $this->id, $this->wp_metadata );
$this->sizes = array();
$this->parse_wp_metadata();
}
return true;
}
/**
* Deletes the backup file of the original image, if it exists.
*
* @since 3.7.0
*
* @return bool True on success or if no backup exists, false on deletion failure.
*/
public function delete_backup() {
$backup_file_path = $this->get_backup_path();
if ( false === $backup_file_path ) {
return true;
}
$wp_filesystem = Tiny_Helpers::get_wp_filesystem();
if ( false === $wp_filesystem ) {
return false;
}
if ( ! $wp_filesystem->exists( $backup_file_path ) ) {
return true;
}
return $wp_filesystem->delete( $backup_file_path );
}
}