forked from joppuyo/acf-image-aspect-ratio-crop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
acf-image-aspect-ratio-crop.php
1363 lines (1188 loc) · 44.2 KB
/
acf-image-aspect-ratio-crop.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
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
/*
Plugin Name: Advanced Custom Fields: Image Aspect Ratio Crop
Plugin URI: https://github.com/joppuyo/acf-image-aspect-ratio-crop
Description: ACF field that allows user to crop image to a specific aspect ratio or pixel size
Version: 5.1.2
Author: Johannes Siipola
Author URI: https://siipo.la
License: GPLv2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: acf-image-aspect-ratio-crop
*/
// exit if accessed directly
if (!defined('ABSPATH')) {
exit();
}
class npx_acf_plugin_image_aspect_ratio_crop
{
// vars
public $settings;
public $user_settings;
public $temp_path;
/*
* __construct
*
* This function will setup the class functionality
*
* @type function
* @date 17/02/2016
* @since 1.0.0
*
* @param n/a
* @return n/a
*/
function __construct()
{
// settings
// - these will be passed into the field class.
if (!function_exists('get_plugin_data')) {
require_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$this->settings = [
'version' => get_plugin_data(__FILE__)['Version'],
'url' => plugin_dir_url(__FILE__),
'path' => plugin_dir_path(__FILE__),
];
$this->temp_path = null;
// set text domain
// https://codex.wordpress.org/Function_Reference/load_plugin_textdomain
load_plugin_textdomain('acf-image-aspect-ratio-crop');
add_action('plugins_loaded', [$this, 'initialize_settings']);
// include field
add_action('acf/include_field_types', [$this, 'include_field_types']); // v5
add_action('rest_api_init', [$this, 'rest_api_init']);
add_action(
'acf/save_post',
function ($post_id) {
if ($post_id === 'options' && !empty($_GET['page'])) {
// Options page needs an unique id
$post_id = $_GET['page'];
}
$temp_post_id = $_POST['aiarc_temp_post_id'];
// Bail early if we don't have data to process
if (empty($temp_post_id)) {
return;
}
// Let's find all posts with temp post id
$temp_attachments = get_posts([
'post_type' => 'attachment',
'posts_per_page' => -1,
'meta_query' => [
[
'key' => 'acf_image_aspect_ratio_crop_temp_post_id',
'value' => $temp_post_id,
'compare' => '=',
],
],
]);
foreach ($temp_attachments as $attachment) {
// Attach parent post id to temporary attachments
update_post_meta(
$attachment->ID,
'acf_image_aspect_ratio_crop_parent_post_id',
$post_id
);
// Remove temporary data
delete_post_meta(
$attachment->ID,
'acf_image_aspect_ratio_crop_temp_post_id'
);
delete_post_meta(
$attachment->ID,
'acf_image_aspect_ratio_crop_timestamp'
);
}
// Bail early if unused attachment deletion is disabled
if (!$this->user_settings['delete_unused']) {
return;
}
$post_attachments = get_posts([
'post_type' => 'attachment',
'posts_per_page' => -1,
'meta_query' => [
[
'key' =>
'acf_image_aspect_ratio_crop_parent_post_id',
'value' => $post_id,
'compare' => '=',
],
],
]);
// Find crop field names
// Compare crop field names to post input
// Delete unused posts
$current_post = get_post($post_id);
if (function_exists('parse_blocks') && $current_post) {
$this->debug('parse blocks');
$blocks = parse_blocks($current_post->post_content);
$this->debug($blocks);
}
$this->debug('found following post attachments');
$this->debug($post_attachments);
$this->debug('found following fields');
$fields = $_POST['acf'];
$this->debug($fields);
$preserve_ids = [];
$this->check_fields($fields, $preserve_ids);
$post_attachment_ids = array_map(function ($attachment) {
return $attachment->ID;
}, $post_attachments);
$delete_ids = array_diff($post_attachment_ids, $preserve_ids);
$this->debug('preserve ids');
$this->debug($preserve_ids);
$this->debug('all ids');
$this->debug($post_attachment_ids);
$this->debug('delete ids');
$this->debug($delete_ids);
foreach ($delete_ids as $delete_id) {
wp_delete_attachment($delete_id, true);
}
},
15
);
add_action('wp_ajax_acf_image_aspect_ratio_crop_crop', function () {
// WTF WordPress
$post = array_map('stripslashes_deep', $_POST);
$data = json_decode($post['data'], true);
$attachment_id = $this->create_crop($data);
wp_send_json(['id' => $attachment_id]);
wp_die();
});
add_action(
'wp_ajax_acf_image_aspect_ratio_crop_get_attachment',
function () {
// WTF WordPress
$post = array_map('stripslashes_deep', $_POST);
$data = json_decode($post['data'], true);
$attachment_id = $data['attachment_id'];
$attachment = get_post($attachment_id);
if (!$attachment) {
wp_die(
__(
'Attachment not found',
'acf-image-aspect-ratio-crop'
),
[
'response' => 404,
]
);
}
$attachment = wp_prepare_attachment_for_js($attachment);
wp_send_json($attachment);
wp_die();
}
);
// Old WPML 4.2.9 compat
add_action(
'wpml_media_create_duplicate_attachment',
[$this, 'wpml_copy_fields_old'],
25,
2
);
// New 4.3.19, 4.4.3 WPML compat
add_action(
'wpml_after_update_attachment_texts',
[$this, 'wpml_copy_fields_new'],
25,
2
);
// Enable Media Replace compat: if file is replaced using Enable Media Replace, wipe the coordinate data
add_filter('wp_handle_upload', function ($data) {
$id = attachment_url_to_postid($data['url']);
if ($id !== 0) {
$posts = get_posts([
'post_type' => 'attachment',
'posts_per_page' => -1,
'meta_query' => [
[
'key' =>
'acf_image_aspect_ratio_crop_original_image_id',
'value' => $id,
'compare' => '=',
],
[
'key' => 'acf_image_aspect_ratio_crop_coordinates',
'compare' => 'EXISTS',
],
],
]);
if (!empty($posts)) {
foreach ($posts as $post) {
delete_post_meta(
$post->ID,
'acf_image_aspect_ratio_crop_coordinates'
);
}
}
}
return $data;
});
// Hide cropped images in media library grid view
add_filter('ajax_query_attachments_args', function ($args) {
// post__in is only defined when clicking edit button in attachment
if (empty($args['post__in'])) {
$args['meta_query'] = [
[
'key' => 'acf_image_aspect_ratio_crop',
'compare' => 'NOT EXISTS',
],
];
}
return $args;
});
// Add plugin to WordPress admin menu
add_action('admin_menu', function () {
add_submenu_page(
null,
__(
'ACF Image Aspect Ratio Crop',
'acf-image-aspect-ratio-crop'
),
__(
'ACF Image Aspect Ratio Crop',
'acf-image-aspect-ratio-crop'
),
'manage_options',
'acf-image-aspect-ratio-crop',
[$this, 'settings_page']
);
});
// Add settings link on the plugin page
add_filter(
'plugin_action_links_' . plugin_basename(__FILE__),
function ($links) {
$settings_link =
'<a href="options-general.php?page=acf-image-aspect-ratio-crop">' .
__('Settings', 'acf-image-aspect-ratio-crop') .
'</a>';
array_unshift($links, $settings_link);
return $links;
}
);
// Donate link
add_filter(
'plugin_row_meta',
function ($links, $file) {
if ($file === plugin_basename(__FILE__)) {
array_push(
$links,
'<a href="https://github.com/sponsors/joppuyo">' .
esc_html__(
'Support development on GitHub Sponsors',
'acf-image-aspect-ratio-crop'
) .
'</a>'
);
}
return $links;
},
10,
2
);
if (!wp_next_scheduled('aiarc_delete_unused_attachments')) {
wp_schedule_event(
time(),
'daily',
'aiarc_delete_unused_attachments'
);
}
add_action('aiarc_delete_unused_attachments', [
$this,
'delete_unused_attachments',
]);
add_filter('wpgraphql_acf_supported_fields', function (
$supported_fields
) {
array_push($supported_fields, 'image_aspect_ratio_crop');
return $supported_fields;
});
add_filter(
'wpgraphql_acf_register_graphql_field',
function ($field_config, $type_name, $field_name, $config) {
// How to add new WPGraphQL fields is super undocumented, I used this code as a base
// https://github.com/wp-graphql/wp-graphql/issues/214#issuecomment-653141685
$acf_field = isset($config['acf_field'])
? $config['acf_field']
: null;
$acf_type = isset($acf_field['type'])
? $acf_field['type']
: null;
$resolve = $field_config['resolve'];
if ($acf_type == 'image_aspect_ratio_crop') {
$field_config = [
'type' => 'MediaItem',
'resolve' => function (
$root,
$args,
$context,
$info
) use ($resolve) {
$value = $resolve($root, $args, $context, $info);
return WPGraphQL\Data\DataSource::resolve_post_object(
(int) $value,
$context
);
},
];
}
return $field_config;
},
10,
4
);
add_filter(
'pll_translate_post_meta',
[$this, 'translate_post_meta_polylang'],
10,
5
);
add_filter(
'wpml_duplicate_generic_string',
[$this, 'translate_post_meta_wpml'],
10,
3
);
// If no alt-text is found for our cropped image, check to see if it exists in the original
add_filter(
'wp_get_attachment_image_attributes',
function ($attr, $attachment) {
if (!isset($attr['alt']) || empty($attr['alt'])) {
$original_id = get_post_meta($attachment->ID, 'acf_image_aspect_ratio_crop_original_image_id', true);
$original_alt = get_post_meta($original_id, '_wp_attachment_image_alt', true);
$attr['alt'] = $original_alt;
}
return $attr;
},
10,
2
);
}
/*
* include_field_types
*
* This function will include the field type class
*
* @type function
* @date 17/02/2016
* @since 1.0.0
*
* @param $version (int) major ACF version. Defaults to false
* @return n/a
*/
function include_field_types()
{
// include
include_once 'fields/class-npx-acf-field-image-aspect-ratio-crop-v5.php';
}
/**
* Render WordPress plugin settings page
*/
public function settings_page()
{
$updated = false;
$settings = $this->user_settings;
if (!empty($_POST)) {
check_admin_referer('acf-image-aspect-ratio-crop');
if (!empty($_POST['modal_type'])) {
$settings['modal_type'] = $_POST['modal_type'];
}
if (!empty($_POST['delete_unused'])) {
$settings['delete_unused'] = filter_var(
$_POST['delete_unused'],
FILTER_VALIDATE_BOOLEAN
);
}
if (!empty($_POST['rest_api_compat'])) {
$settings['rest_api_compat'] = filter_var(
$_POST['rest_api_compat'],
FILTER_VALIDATE_BOOLEAN
);
}
update_option('acf-image-aspect-ratio-crop-settings', $settings);
$updated = true;
}
$modal_type = $settings['modal_type'];
$delete_unused = $settings['delete_unused'];
$rest_api_compat = $settings['rest_api_compat'];
echo '<div class="wrap">';
echo '<h1>' .
__('ACF Image Aspect Ratio Crop', 'acf-image-aspect-ratio-crop') .
'</h1>';
echo '<div class="js-finnish-base-forms-admin-notices"></div>';
if ($updated) {
echo '<div class="notice notice-success">';
echo '<p>' .
__('Options have been updated', 'acf-image-aspect-ratio-crop') .
'</p>';
echo '</div>';
}
echo '<form method="post">';
echo '<table class="form-table">';
echo '<tbody>';
echo '<tr>';
echo '<th scope="row">';
echo '<label for="modal_type">' .
__(
'Image displayed in attachment edit modal dialog',
'acf-image-aspect-ratio-crop'
) .
'</label>';
echo '</th>';
echo '<td>';
echo '<p><input type="radio" id="cropped" name="modal_type" value="cropped" ' .
checked($modal_type, 'cropped', false) .
'><label for="cropped"> ' .
__('Cropped image', 'acf-image-aspect-ratio-crop') .
'</label></p>';
echo '<p><input type="radio" id="original" name="modal_type" value="original" ' .
checked($modal_type, 'original', false) .
'><label for="original"> ' .
__('Original image', 'acf-image-aspect-ratio-crop') .
'</label></p>';
echo '</td>';
echo '</tr>';
echo '<tr>';
echo '<th scope="row">';
echo '<label for="modal_type">' .
__('Delete unused cropped images', 'acf-image-aspect-ratio-crop') .
' ' .
__('(Beta feature)', 'acf-image-aspect-ratio-crop') .
'</label>';
echo '</th>';
echo '<td>';
echo '<p><input type="radio" id="delete_unused_true" name="delete_unused" value="true" ' .
checked($delete_unused, true, false) .
'><label for="delete_unused_true"> ' .
__('Enabled', 'acf-image-aspect-ratio-crop') .
'</label></p>';
echo '<p><input type="radio" id="delete_unused_false" name="delete_unused" value="false" ' .
checked($delete_unused, false, false) .
'><label for="delete_unused_false"> ' .
__('Disabled', 'acf-image-aspect-ratio-crop') .
'</label></p>';
echo '</td>';
echo '</tr>';
echo '<tr>';
echo '<td colspan="2" style="padding: 0">';
echo __(
'Please note that "Delete unused cropped images" feature is a beta feature because it requires more testing. Please do not enable the option without first backing up your database and uploads in order to prevent potential data loss.',
'acf-image-aspect-ratio-crop'
);
echo '</td>';
echo '</tr>';
echo '<tr>';
echo '<th scope="row">';
echo '<label for="modal_type">' .
__('REST API compatibility mode', 'acf-image-aspect-ratio-crop') .
'</label>';
echo '</th>';
echo '<td>';
echo '<p><input type="radio" id="rest_api_compat_true" name="rest_api_compat" value="true" ' .
checked($rest_api_compat, true, false) .
'><label for="rest_api_compat_true"> ' .
__('Enabled', 'acf-image-aspect-ratio-crop') .
'</label></p>';
echo '<p><input type="radio" id="rest_api_compat_false" name="rest_api_compat" value="false" ' .
checked($rest_api_compat, false, false) .
'><label for="rest_api_compat_false"> ' .
__('Disabled', 'acf-image-aspect-ratio-crop') .
'</label></p>';
echo '</td>';
echo '</tr>';
echo '<tr>';
echo '<td colspan="2" style="padding: 0">';
echo __(
'When you enable the REST API compatibility mode, cropping in the WordPress administration interface will use admin-ajax.php instead of the REST API. Use this compatibility mode if you do not have REST API enabled. Please note that this is a temporary fix since the REST API is the way forward. The compatibility mode will be removed in a future major release of the plugin.',
'acf-image-aspect-ratio-crop'
);
echo '</td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
echo '<p class="submit">';
echo '<input class="button-primary js-finnish-base-forms-submit-button" type="submit" name="submit-button" value="Save">';
echo '</p>';
wp_nonce_field('acf-image-aspect-ratio-crop');
echo '</form>';
echo '</div>';
}
function initialize_settings()
{
$database_version = get_option('acf-image-aspect-ratio-crop-version');
$plugin_version = $this->settings['version'];
$settings = get_option('acf-image-aspect-ratio-crop-settings')
? get_option('acf-image-aspect-ratio-crop-settings')
: [];
// Initialize database settings
if (empty($database_version)) {
update_option(
'acf-image-aspect-ratio-crop-version',
$plugin_version
);
}
if (
version_compare(
get_option('acf-image-aspect-ratio-crop-version'),
$plugin_version,
'lt'
)
) {
// Database migrations here
update_option(
'acf-image-aspect-ratio-crop-version',
$plugin_version
);
}
$default_user_settings = [
'modal_type' => 'cropped',
'delete_unused' => false,
'rest_api_compat' => false,
];
$this->user_settings = array_merge($default_user_settings, $settings);
$this->settings['user_settings'] = $this->user_settings;
}
/**
* Clean up any temporary files
*/
private function cleanup()
{
if ($this->temp_path) {
@unlink($this->temp_path);
}
}
public function delete_unused_attachments()
{
$this->debug('delete unused attachments cron');
// Bail early if unused attachment deletion is disabled
if (!$this->user_settings['delete_unused']) {
$this->debug('user has disabled unused attachment deletion');
return;
}
$timestamp = (new DateTime())->modify('-7 days')->format('U');
$posts = get_posts([
'post_type' => 'attachment',
'meta_query' => [
[
'key' => 'acf_image_aspect_ratio_crop_timestamp',
'compare' => '<',
'value' => $timestamp,
'type' => 'numeric',
],
],
]);
foreach ($posts as $post) {
$this->debug('deleting unused attachment ' . $post->ID);
wp_delete_attachment($post->ID, true);
}
}
function debug($message)
{
if (defined('WP_DEBUG') && WP_DEBUG === true) {
error_log(print_r($message, true));
}
}
private function log_error($description, $object = false)
{
error_log("ACF Image Aspect Ratio Crop: $description");
if ($object) {
error_log(print_r($object, true));
}
}
private function crop(WP_Image_Editor $image, $data)
{
$image->crop($data['x'], $data['y'], $data['width'], $data['height']);
}
public function check_fields($fields, &$preserve_ids)
{
$this->debug($preserve_ids);
foreach ($fields as $key => $field) {
if (is_array($field)) {
$this->check_fields($field, $preserve_ids);
}
// This is kinda of a hack but nested fields are named like field_59416ac78945f_field_59217cf6eb710 in the
// POST request and we are only interested in the last part so we just use a regex here to chop off the
// last part
preg_match_all('/field_[a-z0-9]+/', $key, $matches);
if (!empty($matches[0])) {
$last = array_values(array_slice($matches[0], -1))[0];
$definition = get_field_object($last);
if (
!empty($field) &&
!empty($definition) &&
$definition['type'] === 'image_aspect_ratio_crop'
) {
array_push($preserve_ids, $field);
}
}
}
}
public function jpeg_quality($jpeg_quality)
{
return apply_filters('aiarc_jpeg_quality', $jpeg_quality);
}
public function translate_post_meta_polylang(
$value,
$key,
$lang,
$from,
$to
) {
// When creating translated duplicated attachment if there is a translated version of
// the original image, use it
if (get_post_type($from) === 'attachment') {
if ($key === 'acf_image_aspect_ratio_crop_original_image_id') {
return pll_get_post($value, $lang)
? pll_get_post($value, $lang)
: $value;
}
}
// When creating translated copy of any post if there is a translated version of the
// cropped image, use it
if (get_post_type($from) !== 'attachment') {
$original_field = get_field_object($key, $from);
if (
$value &&
$original_field &&
$original_field['type'] &&
$original_field['type'] === 'image_aspect_ratio_crop'
) {
$translated_value = pll_get_post($value, $lang);
if ($translated_value) {
return $translated_value;
}
}
}
return $value;
}
public function translate_post_meta_wpml($value, $lang, $meta_data)
{
if ($meta_data['context'] !== 'custom_field') {
return $value;
}
$key = $meta_data['key'];
$to = $meta_data['post_id'];
$from = $meta_data['master_post_id'];
// When creating translated copy of any post if there is a translated version of the
// cropped image, use it
if (get_post_type($from) !== 'attachment') {
$original_field = get_field_object($key, $from);
if (
$value &&
$original_field &&
$original_field['type'] &&
$original_field['type'] === 'image_aspect_ratio_crop'
) {
$translated_value = apply_filters(
'wpml_object_id',
$value,
'attachment',
false,
$lang
);
if ($translated_value) {
return $translated_value;
}
}
}
return $value;
}
public function wpml_copy_fields_old(
$attachment_id,
$duplicate_attachment_id
) {
$this->wpml_copy_fields($attachment_id, $duplicate_attachment_id);
}
public function wpml_copy_fields_new($attachment_id, $duplicate_attachment)
{
$duplicate_attachment_id = $duplicate_attachment->element_id;
$this->wpml_copy_fields($attachment_id, $duplicate_attachment_id);
}
public function wpml_copy_fields($attachment_id, $duplicate_attachment_id)
{
$keys = [
'acf_image_aspect_ratio_crop',
'acf_image_aspect_ratio_crop_original_image_id',
'acf_image_aspect_ratio_crop_coordinates',
];
foreach ($keys as $key) {
$value = get_post_meta($attachment_id, $key, true);
if ($value) {
update_post_meta($duplicate_attachment_id, $key, $value);
}
}
}
public function rest_api_init()
{
register_rest_route('aiarc/v1', '/upload', [
'methods' => 'POST',
'callback' => [$this, 'rest_api_upload_callback'],
'permission_callback' => function () {
return true;
},
]);
register_rest_route('aiarc/v1', '/crop', [
'methods' => 'POST',
'callback' => [$this, 'rest_api_crop_callback'],
'permission_callback' => function () {
return true;
},
]);
register_rest_route('aiarc/v1', '/get/(?P<id>\d+)', [
'methods' => 'GET',
'callback' => [$this, 'rest_api_get_callback'],
'args' => ['id' => []],
'permission_callback' => function () {
return true;
},
]);
}
public function rest_api_get_callback(WP_REST_Request $data)
{
// TODO: validate nonce
$attachment_id = $data->get_param('id');
$attachment = get_post($attachment_id);
if (!$attachment) {
wp_send_json_error(
new WP_Error(
'attachment_not_found',
__('Attachment not found', 'acf-image-aspect-ratio-crop')
),
404
);
}
$attachment = wp_prepare_attachment_for_js($attachment);
return new WP_REST_Response($attachment);
}
public function rest_api_crop_callback(WP_REST_Request $data)
{
$this->rest_api_check_nonce($data);
$parameters = $data->get_json_params();
$attachment_id = $this->create_crop($parameters);
return [
'id' => $attachment_id,
];
}
public function rest_api_upload_callback(WP_REST_Request $data)
{
$this->rest_api_check_nonce($data);
if (empty($data->get_file_params()['image'])) {
return new WP_Error(
'image_field_missing',
__('Image field missing.', 'acf-image-aspect-ratio-crop')
);
}
if (empty($data->get_param('key'))) {
return new WP_Error(
'key_field_missing',
__('Key field missing.', 'acf-image-aspect-ratio-crop')
);
}
$key = $data->get_param('key');
$field_object = get_field_object($key);
$mime_types = $field_object['mime_types'];
$min_size = $field_object['min_size'];
$max_size = $field_object['max_size'];
$min_width = $field_object['min_width'];
$max_width = $field_object['max_width'];
$min_height = $field_object['min_height'];
$max_height = $field_object['max_height'];
// MIME validation
$file_mime = mime_content_type(
$data->get_file_params()['image']['tmp_name']
);
$allowed_mime_types = $this->extension_list_to_mime_array($mime_types);
if (
!empty($allowed_mime_types) &&
!in_array($file_mime, $allowed_mime_types)
) {
return new WP_Error(
'invalid_mime_type',
__('Invalid file type.', 'acf-image-aspect-ratio-crop')
);
}
// File size validation
if (
!empty($max_size) &&
$data->get_file_params()['image']['size'] > $max_size * 1000000
) {
return new WP_Error(
'file_too_large',
sprintf(
__(
'File size too large. Maximum file size is %d megabytes.',
'acf-image-aspect-ratio-crop'
),
$max_size
),
'acf-image-aspect-ratio-crop'
);
}
if (
!empty($min_size) &&
$data->get_file_params()['image']['size'] < $min_size * 1000000
) {
return new WP_Error(
'file_too_small',
sprintf(
__(
'File size too small. Minimum file size is %d megabytes.',
'acf-image-aspect-ratio-crop'
),
$min_size
),
'acf-image-aspect-ratio-crop'
);
}
// Image size validation
$image_size = @getimagesize(
$data->get_file_params()['image']['tmp_name']
);
if (!$image_size) {
return new WP_Error(
'failed_to_parse_image',
__('Failed to parse image.', 'acf-image-aspect-ratio-crop')
);
}
$image_width = $image_size[0];
$image_height = $image_size[1];
if (
!empty($min_width) &&
!empty($min_height) &&
($image_width < $min_width || $image_height < $min_height)
) {
return new WP_Error(
'image_too_small',
sprintf(
__(
'Image too small. Minimum image dimensions are %d×%d pixels.',
'acf-image-aspect-ratio-crop'
),
$min_width,
$min_height
),
'acf-image-aspect-ratio-crop'
);
}
if (
!empty($max_width) &&
!empty($max_height) &&
($image_width > $max_width || $image_height > $max_height)
) {
return new WP_Error(
'image_too_large',
sprintf(
__(
'Image too large. Maximum image dimensions are %d×%d pixels.',
'acf-image-aspect-ratio-crop'
),
$max_width,