-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathMedia_Command.php
More file actions
1642 lines (1445 loc) · 52.3 KB
/
Media_Command.php
File metadata and controls
1642 lines (1445 loc) · 52.3 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
use WP_CLI\Utils;
/**
* Imports files as attachments, regenerates thumbnails, or lists registered image sizes.
*
* ## EXAMPLES
*
* # Re-generate all thumbnails, without confirmation.
* $ wp media regenerate --yes
* Found 3 images to regenerate.
* 1/3 Regenerated thumbnails for "Sydney Harbor Bridge" (ID 760).
* 2/3 Regenerated thumbnails for "Boardwalk" (ID 757).
* 3/3 Regenerated thumbnails for "Sunburst Over River" (ID 756).
* Success: Regenerated 3 of 3 images.
*
* # Import a local image and set it to be the featured image for a post.
* $ wp media import ~/Downloads/image.png --post_id=123 --title="A downloaded picture" --featured_image
* Imported file '/home/person/Downloads/image.png' as attachment ID 1753 and attached to post 123 as featured image.
* Success: Imported 1 of 1 images.
*
* # List all registered image sizes
* $ wp media image-size
* +---------------------------+-------+--------+-------+
* | name | width | height | crop |
* +---------------------------+-------+--------+-------+
* | full | | | N/A |
* | twentyfourteen-full-width | 1038 | 576 | hard |
* | large | 1024 | 1024 | soft |
* | medium_large | 768 | 0 | soft |
* | medium | 300 | 300 | soft |
* | thumbnail | 150 | 150 | hard |
* +---------------------------+-------+--------+-------+
*
* # Fix orientation for specific images.
* $ wp media fix-orientation 63
* 1/1 Fixing orientation for "Portrait_6" (ID 63).
* Success: Fixed 1 of 1 images.
*
* @package wp-cli
*/
class Media_Command extends WP_CLI_Command {
/**
* Clear the WP object cache after this many regenerations/imports.
*
* @var integer
*/
const WP_CLEAR_OBJECT_CACHE_INTERVAL = 500;
/**
* @var string|null
*/
private $destination_dir;
/**
* Regenerates thumbnails for one or more attachments.
*
* ## OPTIONS
*
* [<attachment-id>...]
* : One or more IDs of the attachments to regenerate.
*
* [--image_size=<image_size>]
* : Name of the image size to regenerate. Only thumbnails of this image size will be regenerated, thumbnails of other image sizes will not.
*
* [--skip-delete]
* : Skip deletion of the original thumbnails. If your thumbnails are linked from sources outside your control, it's likely best to leave them around. Defaults to false.
*
* [--only-missing]
* : Only generate thumbnails for images missing image sizes.
*
* [--delete-unknown]
* : Only delete thumbnails for old unregistered image sizes.
*
* [--yes]
* : Answer yes to the confirmation message. Confirmation only shows when no IDs passed as arguments.
*
* ## EXAMPLES
*
* # Regenerate thumbnails for given attachment IDs.
* $ wp media regenerate 123 124 125
* Found 3 images to regenerate.
* 1/3 Regenerated thumbnails for "Vertical Image" (ID 123).
* 2/3 Regenerated thumbnails for "Horizontal Image" (ID 124).
* 3/3 Regenerated thumbnails for "Beautiful Picture" (ID 125).
* Success: Regenerated 3 of 3 images.
*
* # Regenerate all thumbnails, without confirmation.
* $ wp media regenerate --yes
* Found 3 images to regenerate.
* 1/3 Regenerated thumbnails for "Sydney Harbor Bridge" (ID 760).
* 2/3 Regenerated thumbnails for "Boardwalk" (ID 757).
* 3/3 Regenerated thumbnails for "Sunburst Over River" (ID 756).
* Success: Regenerated 3 of 3 images.
*
* # Re-generate all thumbnails that have IDs between 1000 and 2000.
* $ seq 1000 2000 | xargs wp media regenerate
* Found 4 images to regenerate.
* 1/4 Regenerated thumbnails for "Vertical Featured Image" (ID 1027).
* 2/4 Regenerated thumbnails for "Horizontal Featured Image" (ID 1022).
* 3/4 Regenerated thumbnails for "Unicorn Wallpaper" (ID 1045).
* 4/4 Regenerated thumbnails for "I Am Worth Loving Wallpaper" (ID 1023).
* Success: Regenerated 4 of 4 images.
*
* # Re-generate only the thumbnails of "large" image size for all images.
* $ wp media regenerate --image_size=large
* Do you really want to regenerate the "large" image size for all images? [y/n] y
* Found 3 images to regenerate.
* 1/3 Regenerated "large" thumbnail for "Sydney Harbor Bridge" (ID 760).
* 2/3 No "large" thumbnail regeneration needed for "Boardwalk" (ID 757).
* 3/3 Regenerated "large" thumbnail for "Sunburst Over River" (ID 756).
* Success: Regenerated 3 of 3 images.
*
* @param string[] $args Positional arguments.
* @param array{image_size?: string, 'skip-delete'?: bool, 'only-missing'?: bool, 'delete-unknown'?: bool, yes?: bool} $assoc_args Associative arguments.
* @return void
*/
public function regenerate( $args, $assoc_args = array() ) {
$assoc_args = wp_parse_args(
$assoc_args,
[ 'image_size' => '' ]
);
$image_size = $assoc_args['image_size'];
if ( $image_size && ! in_array( $image_size, get_intermediate_image_sizes(), true ) ) {
WP_CLI::error( sprintf( 'Unknown image size "%s".', $image_size ) );
}
if ( empty( $args ) ) {
if ( $image_size ) {
WP_CLI::confirm( sprintf( 'Do you really want to regenerate the "%s" image size for all images?', $image_size ), $assoc_args );
} else {
WP_CLI::confirm( 'Do you really want to regenerate all images?', $assoc_args );
}
}
$skip_delete = Utils\get_flag_value( $assoc_args, 'skip-delete' );
$only_missing = Utils\get_flag_value( $assoc_args, 'only-missing' );
if ( $only_missing ) {
$skip_delete = true;
}
$delete_unknown = Utils\get_flag_value( $assoc_args, 'delete-unknown' );
if ( $delete_unknown ) {
$skip_delete = false;
}
$additional_mime_types = array();
if ( Utils\wp_version_compare( '4.7', '>=' ) ) {
$additional_mime_types[] = 'application/pdf';
}
$images = $this->get_images( $args, $additional_mime_types );
$count = $images->post_count;
if ( ! $count ) {
WP_CLI::warning( 'No images found.' );
return;
}
WP_CLI::log(
sprintf(
'Found %1$d %2$s to regenerate.',
$count,
_n( 'image', 'images', $count )
)
);
if ( $image_size ) {
$image_size_filters = $this->add_image_size_filters( $image_size );
}
$number = 0;
$successes = 0;
$errors = 0;
$skips = 0;
/**
* @var int $post_id
*/
foreach ( $images->posts as $post_id ) {
++$number;
if ( 0 === $number % self::WP_CLEAR_OBJECT_CACHE_INTERVAL ) {
// @phpstan-ignore function.deprecated
Utils\wp_clear_object_cache();
}
$this->process_regeneration( $post_id, $skip_delete, $only_missing, $delete_unknown, $image_size, $number . '/' . $count, $successes, $errors, $skips );
}
if ( isset( $image_size_filters ) ) {
$this->remove_image_size_filters( $image_size_filters );
}
Utils\report_batch_operation_results( 'image', 'regenerate', $count, $successes, $errors, $skips );
}
/**
* Creates attachments from local files or URLs.
*
* ## OPTIONS
*
* <file>...
* : Path to file or files to be imported. Supports the glob(3) capabilities of the current shell.
* If file is recognized as a URL (for example, with a scheme of http or ftp), the file will be
* downloaded to a temp file before being sideloaded.
*
* [--post_id=<post_id>]
* : ID of the post to attach the imported files to.
*
* [--post_name=<post_name>]
* : Name of the post to attach the imported files to.
*
* [--file_name=<name>]
* : Attachment name (post_name field).
*
* [--title=<title>]
* : Attachment title (post title field).
*
* [--caption=<caption>]
* : Caption for attachment (post excerpt field).
*
* [--alt=<alt_text>]
* : Alt text for image (saved as post meta).
*
* [--desc=<description>]
* : "Description" field (post content) of attachment post.
*
* [--skip-copy]
* : If set, media files (local only) are imported to the library but not moved on disk.
* File names will not be run through wp_unique_filename() with this set. When used, files
* will remain at their current location and will not be copied into any destination directory.
*
* [--destination-dir=<destination-dir>]
* : Path to the destination directory for uploaded imported files.
* Can be absolute or relative to ABSPATH. Ignored when used together with --skip-copy, as
* files are not moved on disk in that case.
*
* [--preserve-filetime]
* : Use the file modified time as the post published & modified dates.
* Remote files will always use the current time.
*
* [--featured_image]
* : If set, set the imported image as the Featured Image of the post it is attached to.
*
* [--porcelain[=<field>]]
* : Output a single field for each imported image. Defaults to attachment ID when used as flag.
* ---
* options:
* - url
* ---
*
* ## EXAMPLES
*
* # Import all jpgs in the current user's "Pictures" directory, not attached to any post.
* $ wp media import ~/Pictures/**\/*.jpg
* Imported file '/home/person/Pictures/landscape-photo.jpg' as attachment ID 1751.
* Imported file '/home/person/Pictures/fashion-icon.jpg' as attachment ID 1752.
* Success: Imported 2 of 2 items.
*
* # Import a local image and set it to be the post thumbnail for a post.
* $ wp media import ~/Downloads/image.png --post_id=123 --title="A downloaded picture" --featured_image
* Imported file '/home/person/Downloads/image.png' as attachment ID 1753 and attached to post 123 as featured image.
* Success: Imported 1 of 1 images.
*
* # Import a local image, but set it as the featured image for all posts.
* # 1. Import the image and get its attachment ID.
* # 2. Assign the attachment ID as the featured image for all posts.
* $ ATTACHMENT_ID="$(wp media import ~/Downloads/image.png --porcelain)"
* $ wp post list --post_type=post --format=ids | xargs -d ' ' -I % wp post meta add % _thumbnail_id $ATTACHMENT_ID
* Success: Added custom field.
* Success: Added custom field.
*
* # Import an image from the web.
* $ wp media import http://s.wordpress.org/style/images/wp-header-logo.png --title='The WordPress logo' --alt="Semantic personal publishing"
* Imported file 'http://s.wordpress.org/style/images/wp-header-logo.png' as attachment ID 1755.
* Success: Imported 1 of 1 images.
*
* # Get the URL for an attachment after import.
* $ wp media import http://s.wordpress.org/style/images/wp-header-logo.png --porcelain | xargs -I {} wp post list --post__in={} --field=url --post_type=attachment
* http://wordpress-develop.dev/wp-header-logo/
*
* @param string[] $args Positional arguments.
* @param array{post_id?: string, post_name?: string, file_name?: string, title?: string, caption?: string, alt?: string, desc?: string, 'skip-copy'?: bool, 'destination-dir'?: string, 'preserve-filetime'?: bool, featured_image?: bool, porcelain?: bool|string} $assoc_args Associative arguments.
* @return void
*/
public function import( $args, $assoc_args = array() ) {
$assoc_args = wp_parse_args(
$assoc_args,
array(
'file_name' => '',
'title' => '',
'caption' => '',
'alt' => '',
'desc' => '',
'post_name' => '',
'destination-dir' => '',
)
);
// Assume the most generic term
$noun = 'item';
// Current site's timezone offset.
// @phpstan-ignore cast.double
$gmt_offset = (float) get_option( 'gmt_offset' );
// Use the noun `image` when sure the media file is an image
if ( Utils\get_flag_value( $assoc_args, 'featured_image' ) || $assoc_args['alt'] ) {
$noun = 'image';
}
$porcelain = Utils\get_flag_value( $assoc_args, 'porcelain' );
if ( is_string( $porcelain ) && ! in_array( $porcelain, array( 'url' ), true ) ) {
WP_CLI::error( sprintf( 'Invalid value for <porcelain>: %s. Expected flag or \'url\'.', $porcelain ) );
}
if ( isset( $assoc_args['post_id'] ) ) {
if ( ! get_post( $assoc_args['post_id'] ) ) {
WP_CLI::warning( 'Invalid --post_id' );
$assoc_args['post_id'] = false;
}
} else {
$assoc_args['post_id'] = false;
}
$destdir = Utils\get_flag_value( $assoc_args, 'destination-dir' );
$this->destination_dir = $destdir;
$filter_upload_dir = function ( $uploads ) {
return $this->filter_upload_dir( $uploads );
};
$number = 0;
$successes = 0;
$errors = 0;
foreach ( $args as $file ) {
++$number;
if ( 0 === $number % self::WP_CLEAR_OBJECT_CACHE_INTERVAL ) {
// @phpstan-ignore function.deprecated
Utils\wp_clear_object_cache();
}
// phpcs:ignore WordPress.WP.AlternativeFunctions.parse_url_parse_url -- parse_url will only be used in absence of wp_parse_url.
$is_file_remote = function_exists( 'wp_parse_url' ) ? wp_parse_url( $file, PHP_URL_HOST ) : parse_url( $file, PHP_URL_HOST );
$orig_filename = $file;
$file_time = '';
if ( empty( $is_file_remote ) ) {
if ( ! file_exists( $file ) ) {
WP_CLI::warning( "Unable to import file '$file'. Reason: File doesn't exist." );
++$errors;
continue;
}
if ( Utils\get_flag_value( $assoc_args, 'skip-copy' ) ) {
$tempfile = $file;
} else {
$tempfile = $this->make_copy( $file );
}
$name = Utils\basename( $file );
if ( Utils\get_flag_value( $assoc_args, 'preserve-filetime' ) ) {
$file_time = @filemtime( $file );
}
} else {
$tempfile = download_url( $file );
if ( is_wp_error( $tempfile ) ) {
WP_CLI::warning(
sprintf(
"Unable to import file '%s'. Reason: %s",
$file,
implode( ', ', $tempfile->get_error_messages() )
)
);
++$errors;
continue;
}
$name = (string) strtok( Utils\basename( $file ), '?' );
}
if ( ! empty( $assoc_args['file_name'] ) ) {
$image_name = $this->get_image_name( $name, $assoc_args['file_name'] );
$name = ! empty( $image_name ) ? $image_name : $name;
}
$file_array = array(
'tmp_name' => $tempfile,
'name' => $name,
);
$post_array = array(
'post_title' => $assoc_args['title'],
'post_excerpt' => $assoc_args['caption'],
'post_content' => $assoc_args['desc'],
'post_name' => $assoc_args['post_name'],
);
if ( ! empty( $file_time ) ) {
$post_array['post_date'] = gmdate( 'Y-m-d H:i:s', (int) ( $file_time + ( $gmt_offset * HOUR_IN_SECONDS ) ) );
$post_array['post_date_gmt'] = gmdate( 'Y-m-d H:i:s', $file_time );
$post_array['post_modified'] = gmdate( 'Y-m-d H:i:s', (int) ( $file_time + ( $gmt_offset * HOUR_IN_SECONDS ) ) );
$post_array['post_modified_gmt'] = gmdate( 'Y-m-d H:i:s', $file_time );
}
$post_array = wp_slash( $post_array );
// use image exif/iptc data for title and caption defaults if possible
if ( empty( $post_array['post_title'] ) || empty( $post_array['post_excerpt'] ) ) {
// @codingStandardsIgnoreStart
$image_meta = @wp_read_image_metadata( $tempfile );
// @codingStandardsIgnoreEnd
if ( ! empty( $image_meta ) ) {
if ( empty( $post_array['post_title'] ) && trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) {
$post_array['post_title'] = $image_meta['title'];
}
if ( empty( $post_array['post_excerpt'] ) && trim( $image_meta['caption'] ) ) {
$post_array['post_excerpt'] = $image_meta['caption'];
}
}
}
if ( empty( $post_array['post_title'] ) ) {
$post_array['post_title'] = preg_replace( '/\.[^.]+$/', '', Utils\basename( $file ) );
}
if ( Utils\get_flag_value( $assoc_args, 'skip-copy' ) ) {
$wp_filetype = wp_check_filetype( $file, null );
$post_array['post_mime_type'] = $wp_filetype['type'];
$post_array['post_status'] = 'inherit';
$success = wp_insert_attachment( $post_array, $file, $assoc_args['post_id'] );
if ( is_wp_error( $success ) ) {
WP_CLI::warning(
sprintf(
"Unable to insert file '%s'. Reason: %s",
$orig_filename,
implode( ', ', $success->get_error_messages() )
)
);
++$errors;
continue;
}
wp_update_attachment_metadata( $success, wp_generate_attachment_metadata( $success, $file ) );
} else {
if ( ! empty( $destdir ) ) {
add_filter( 'upload_dir', $filter_upload_dir, PHP_INT_MAX );
}
// Deletes the temporary file.
$success = media_handle_sideload( $file_array, $assoc_args['post_id'], $assoc_args['title'], $post_array );
if ( is_wp_error( $success ) ) {
WP_CLI::warning(
sprintf(
"Unable to import file '%s'. Reason: %s",
$orig_filename,
implode( ', ', $success->get_error_messages() )
)
);
++$errors;
continue;
}
}
// Set alt text
if ( $assoc_args['alt'] ) {
update_post_meta( $success, '_wp_attachment_image_alt', wp_slash( $assoc_args['alt'] ) );
}
// Set as featured image, if --post_id and --featured_image are set
if ( $assoc_args['post_id'] && Utils\get_flag_value( $assoc_args, 'featured_image' ) ) {
update_post_meta( $assoc_args['post_id'], '_thumbnail_id', $success );
}
$attachment_success_text = '';
if ( $assoc_args['file_name'] ) {
$attachment_success_text .= " with file name {$name}";
}
if ( $assoc_args['post_id'] ) {
$attachment_success_text = " and attached to post {$assoc_args['post_id']}";
if ( Utils\get_flag_value( $assoc_args, 'featured_image' ) ) {
$attachment_success_text .= ' as featured image';
}
}
if ( $porcelain ) {
if ( 'url' === strtolower( $porcelain ) ) {
$file_location = $this->get_real_attachment_url( $success );
if ( $file_location ) {
WP_CLI::line( $file_location );
} else {
// This should never happen.
WP_CLI::error( 'Attachment URL not found' );
}
} else {
WP_CLI::line( (string) $success );
}
} else {
WP_CLI::log(
sprintf(
"Imported file '%s' as attachment ID %d%s.",
$orig_filename,
$success,
$attachment_success_text
)
);
}
++$successes;
}
remove_filter( 'upload_dir', $filter_upload_dir, PHP_INT_MAX );
// Report the result of the operation
if ( ! Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
Utils\report_batch_operation_results( $noun, 'import', count( $args ), $successes, $errors );
} elseif ( $errors ) {
WP_CLI::halt( 1 );
}
}
/**
* Lists image sizes registered with WordPress.
*
* ## OPTIONS
*
* [--fields=<fields>]
* : Limit the output to specific fields. Defaults to all fields.
*
* [--format=<format>]
* : Render output in a specific format
* ---
* default: table
* options:
* - table
* - json
* - csv
* - yaml
* - count
* ---
*
* ## AVAILABLE FIELDS
*
* These fields will be displayed by default for each image size:
* * name
* * width
* * height
* * crop
* * ratio
*
* ## EXAMPLES
*
* # List all registered image sizes
* $ wp media image-size
* +---------------------------+-------+--------+-------+-------+
* | name | width | height | crop | ratio |
* +---------------------------+-------+--------+-------+-------+
* | full | | | N/A | N/A |
* | twentyfourteen-full-width | 1038 | 576 | hard | 173:96|
* | large | 1024 | 1024 | soft | N/A |
* | medium_large | 768 | 0 | soft | N/A |
* | medium | 300 | 300 | soft | N/A |
* | thumbnail | 150 | 150 | hard | 1:1 |
* +---------------------------+-------+--------+-------+-------+
*
* @subcommand image-size
*
* @param string[] $args Positional arguments. Unused.
* @param array{fields?: string, format: string} $assoc_args Associative arguments.
* @return void
*/
public function image_size( $args, $assoc_args ) {
$assoc_args = array_merge(
array(
'fields' => 'name,width,height,crop,ratio',
),
$assoc_args
);
$sizes = $this->get_registered_image_sizes();
usort(
$sizes,
function ( $a, $b ) {
if ( $a['width'] === $b['width'] ) {
return 0;
}
return ( $a['width'] < $b['width'] ) ? 1 : -1;
}
);
array_unshift(
$sizes,
array(
'name' => 'full',
'width' => '',
'height' => '',
'crop' => 'N/A',
'ratio' => 'N/A',
)
);
WP_CLI\Utils\format_items( $assoc_args['format'], $sizes, explode( ',', $assoc_args['fields'] ) );
}
/**
* Get aspect ratio.
*
* @param int $width
* @param int $height
* @return string
*/
private function get_ratio( $width, $height ) {
if ( 0 === $height ) {
return "0:{$width}";
}
if ( 0 === $width ) {
return "{$height}:0";
}
$gcd = $this->gcd( $width, $height );
$width_ratio = $width / $gcd;
$height_ratio = $height / $gcd;
return "{$width_ratio}:{$height_ratio}";
}
/**
* Get the greatest common divisor.
*
* @param int $num1
* @param int $num2
* @return int
*/
private function gcd( $num1, $num2 ) {
while ( 0 !== $num2 ) {
$t = $num1 % $num2;
$num1 = $num2;
$num2 = $t;
}
return $num1;
}
/**
* Make a temporary file copy.
*
* {@see wp_tempnam()} inexplicably forces a .tmp extension, which spoils MIME type detection.
*
* @param string $path
* @return string
*/
private function make_copy( $path ) {
$dir = get_temp_dir();
$filename = Utils\basename( $path );
if ( empty( $filename ) ) {
$filename = (string) time();
}
$filename = $dir . wp_unique_filename( $dir, $filename );
if ( ! copy( $path, $filename ) ) {
WP_CLI::error( "Could not create temporary file for $path." );
}
return $filename;
}
/**
* Process media regeneration
*
* @param int $id Attachment ID.
* @param bool $skip_delete
* @param bool $only_missing
* @param bool $delete_unknown
* @param string $image_size
* @param string $progress
* @param int $successes
* @param int $errors
* @param int $skips
* @param-out int $successes
* @param-out int $errors
* @param-out int $skips
* @return void
*/
private function process_regeneration( $id, $skip_delete, $only_missing, $delete_unknown, $image_size, $progress, &$successes, &$errors, &$skips ) {
$title = get_the_title( $id );
if ( '' === $title ) {
// If audio or video cover art then the id is the sub attachment id, which has no title.
if ( metadata_exists( 'post', $id, '_cover_hash' ) ) {
// Unfortunately the only way to get the attachment title would be to do a non-indexed query against the meta value of `_thumbnail_id`. So don't.
$att_desc = sprintf( 'cover attachment (ID %d)', $id );
} else {
$att_desc = sprintf( '"(no title)" (ID %d)', $id );
}
} else {
$att_desc = sprintf( '"%1$s" (ID %2$d)', $title, $id );
}
$thumbnail_desc = $image_size ? sprintf( '"%s" thumbnail', $image_size ) : 'thumbnail';
$fullsizepath = $this->get_attached_file( $id );
if ( false === $fullsizepath || ! file_exists( $fullsizepath ) ) {
WP_CLI::warning( "Can't find $att_desc." );
++$errors;
return;
}
$is_pdf = 'application/pdf' === get_post_mime_type( $id );
$original_meta = wp_get_attachment_metadata( $id );
if ( $delete_unknown ) {
$this->delete_unknown_image_sizes( $id, $fullsizepath );
WP_CLI::log( "$progress Deleted unknown image sizes for $att_desc." );
++$successes;
return;
}
$needs_regeneration = $this->needs_regeneration( $id, $fullsizepath, $is_pdf, $image_size, $skip_delete, $skip_it );
if ( $skip_it ) {
WP_CLI::log( "$progress Skipped $thumbnail_desc regeneration for $att_desc." );
++$skips;
return;
}
if ( $only_missing && ! $needs_regeneration ) {
WP_CLI::log( "$progress No $thumbnail_desc regeneration needed for $att_desc." );
++$successes;
return;
}
$site_icon_filter = $this->add_site_icon_filter( $id );
// When regenerating a specific image size, use the file that WordPress normally
// serves (the scaled version for big images), not the original pre-scaled file.
// This prevents wp_generate_attachment_metadata() from re-creating the scaled
// version or auto-rotating the original during specific-size regeneration.
$generate_file = $fullsizepath;
if ( $image_size && ! $is_pdf ) {
$wp_attached_file = \get_attached_file( $id );
if ( $wp_attached_file && file_exists( $wp_attached_file ) ) {
$generate_file = $wp_attached_file;
}
}
$metadata = wp_generate_attachment_metadata( $id, $generate_file );
if ( $site_icon_filter ) {
remove_filter( 'intermediate_image_sizes_advanced', $site_icon_filter );
}
// Note it's possible for no metadata to be generated for PDFs if restricted to a specific image size.
if ( empty( $metadata ) && ! ( $is_pdf && $image_size ) ) {
WP_CLI::warning( sprintf( 'No metadata. (ID %d)', $id ) );
WP_CLI::log( "$progress Couldn't regenerate thumbnails for $att_desc." );
++$errors;
return;
}
// On read error, we might only get the filesize returned and nothing else.
if ( 1 === count( $metadata ) && array_key_exists( 'filesize', $metadata ) && ! ( $is_pdf && $image_size ) ) {
WP_CLI::warning( sprintf( 'Read error while retrieving metadata. (ID %d)', $id ) );
WP_CLI::log( "$progress Couldn't regenerate thumbnails for $att_desc." );
++$errors;
return;
}
if ( $image_size ) {
if ( $this->update_attachment_metadata_for_image_size( $id, $metadata, $image_size, $original_meta ) ) {
WP_CLI::log( "$progress Regenerated $thumbnail_desc for $att_desc." );
} else {
WP_CLI::log( "$progress No $thumbnail_desc regeneration needed for $att_desc." );
}
} else {
wp_update_attachment_metadata( $id, $metadata );
WP_CLI::log( "$progress Regenerated thumbnails for $att_desc." );
}
++$successes;
}
/**
* Removes old images.
*
* @param array $metadata
* @param string $fullsizepath
* @param string $image_size
* @return void
*/
private function remove_old_images( $metadata, $fullsizepath, $image_size ) {
if ( empty( $metadata['sizes'] ) ) {
return;
}
if ( $image_size ) {
if ( empty( $metadata['sizes'][ $image_size ] ) ) {
return;
}
$metadata['sizes'] = array( $image_size => $metadata['sizes'][ $image_size ] );
}
$dir_path = dirname( $fullsizepath ) . '/';
foreach ( $metadata['sizes'] as $size_info ) {
$intermediate_path = $dir_path . $size_info['file'];
if ( $intermediate_path === $fullsizepath ) {
continue;
}
if ( file_exists( $intermediate_path ) ) {
unlink( $intermediate_path );
}
}
}
/**
* Whether the attachment needs regeneration.
*
* @param int $att_id
* @param string $fullsizepath
* @param bool $is_pdf
* @param string $image_size
* @param bool $skip_delete
* @param bool $skip_it
* @param-out bool $skip_it
* @return bool
*/
private function needs_regeneration( $att_id, $fullsizepath, $is_pdf, $image_size, $skip_delete, &$skip_it ) {
// Assume not skipping.
$skip_it = false;
// Note: zero-length string returned if no metadata, for instance if PDF or non-standard image (eg an SVG).
$metadata = wp_get_attachment_metadata( $att_id );
$image_sizes = $this->get_intermediate_image_sizes_for_attachment( $fullsizepath, $is_pdf, $metadata, $att_id );
// First check if no applicable editor currently available (non-destructive - ie old thumbnails not removed).
if ( is_wp_error( $image_sizes ) && 'image_no_editor' === $image_sizes->get_error_code() ) {
// Warn unless PDF or non-standard image.
if ( ! $is_pdf && is_array( $metadata ) && ! empty( $metadata['sizes'] ) ) {
WP_CLI::warning( sprintf( '%s (ID %d)', $image_sizes->get_error_message(), $att_id ) );
}
$skip_it = true;
return false;
}
// If uploaded when applicable image editor such as Imagick unavailable, the metadata or sizes metadata may not exist.
if ( ! is_array( $metadata ) ) {
$metadata = array();
}
// If set `$metadata['sizes']` should be array but explicitly check as following code depends on it.
if ( ! isset( $metadata['sizes'] ) || ! is_array( $metadata['sizes'] ) ) {
$metadata['sizes'] = array();
}
// Remove any old thumbnails (so now destructive).
if ( ! $skip_delete ) {
$this->remove_old_images( $metadata, $fullsizepath, $image_size );
}
// Check for any other error (such as load error) apart from no editor available.
if ( is_wp_error( $image_sizes ) ) {
// Warn but assume it may be possible to regenerate and allow processing to continue and possibly fail.
WP_CLI::warning( sprintf( '%s (ID %d)', $image_sizes->get_error_message(), $att_id ) );
return true;
}
// Have sizes - check whether they're new ones or they've changed. Note that an attachment can have no sizes if it's on or below the thumbnail threshold.
if ( $image_size ) {
if ( empty( $image_sizes[ $image_size ] ) ) {
return false;
}
if ( empty( $metadata['sizes'][ $image_size ] ) ) {
return true;
}
/**
* @var array{sizes: array<string, array<string, mixed>>} $metadata
*/
$metadata['sizes'] = array( $image_size => $metadata['sizes'][ $image_size ] );
}
if ( $this->image_sizes_differ( $image_sizes, $metadata['sizes'] ) ) {
return true;
}
$dir_path = dirname( $fullsizepath ) . '/';
// Check that the thumbnail files exist.
/**
* @var array{file: string} $size_info
*/
foreach ( $metadata['sizes'] as $size_info ) {
$intermediate_path = $dir_path . $size_info['file'];
if ( $intermediate_path === $fullsizepath ) {
continue;
}
if ( ! file_exists( $intermediate_path ) ) {
return true;
}
}
return false;
}
/**
* Whether there's new image sizes or the width/height of existing image sizes have changed.
*
* @param array<string, array> $image_sizes
* @param array<string, array> $meta_sizes
* @return bool
*/
private function image_sizes_differ( $image_sizes, $meta_sizes ) {
// Check if have new image size(s).
if ( array_diff( array_keys( $image_sizes ), array_keys( $meta_sizes ) ) ) {
return true;
}
// Check if image sizes have changed.
foreach ( $image_sizes as $name => $image_size ) {
if ( $image_size['width'] !== $meta_sizes[ $name ]['width'] || $image_size['height'] !== $meta_sizes[ $name ]['height'] ) {
return true;
}
}
return false;
}
/**
* Returns image sizes for a given attachment.
*
* Like WP's get_intermediate_image_sizes(), but removes sizes that won't be generated for a particular attachment due to it being on or below their thresholds,
* and returns associative array with size name => width/height entries, resolved to crop values if applicable.
*
* @param string $fullsizepath Filepath of the attachment
* @param bool $is_pdf Whether it is a PDF.
* @param array<string, mixed>|false $metadata Attachment metadata.
* @param int $att_id Attachment ID.
*
* @return array|WP_Error Image sizes on success, WP_Error instance otherwise.
*/
private function get_intermediate_image_sizes_for_attachment( $fullsizepath, $is_pdf, $metadata, $att_id ) {
// Need to get width, height of attachment for image_resize_dimensions().
$editor = wp_get_image_editor( $fullsizepath );
if ( is_wp_error( $editor ) ) {
return $editor;
}
$result = $editor->load();
if ( is_wp_error( $result ) ) {
unset( $editor );
return $result;
}
list( $width, $height ) = array_values( $editor->get_size() );
unset( $editor );
$sizes = array();
foreach ( $this->get_intermediate_sizes( $is_pdf, $metadata, $att_id ) as $name => $size ) {
// Need to check destination and original width or height differ before calling image_resize_dimensions(), otherwise it will return non-false.
$dims = image_resize_dimensions( $width, $height, $size['width'], $size['height'], $size['crop'] );
if ( ( $width !== $size['width'] || $height !== $size['height'] ) && $dims ) {
list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
$sizes[ $name ] = array(
'width' => $dst_w,
'height' => $dst_h,
);
}
}
return $sizes;
}
/**
* Like WP's get_intermediate_image_sizes(), but returns associative array with name => size info entries (and caters for PDFs also).
*
* @param bool $is_pdf
* @param array<string, mixed>|false $metadata
* @param int $att_id
* @return array<string, array{width: int, height: int, crop: bool}>
*/
private function get_intermediate_sizes( $is_pdf, $metadata, $att_id ) {
if ( $is_pdf ) {
// Copied from wp_generate_attachment_metadata() in "wp-admin/includes/image.php".
$fallback_sizes = array(
'thumbnail',
'medium',
'large',
);
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Calling native WordPress hook.
$intermediate_image_sizes = apply_filters( 'fallback_intermediate_image_sizes', $fallback_sizes, $metadata );
} else {
$intermediate_image_sizes = get_intermediate_image_sizes();