-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathclass-bootstrap.php
2003 lines (1703 loc) · 72.6 KB
/
class-bootstrap.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
/**
* Bootstrap
*
* @since 0.2.0
*/
namespace wpCloud\StatelessMedia {
use Google\Cloud\Storage\StorageClient;
use Google\Auth\HttpHandler\HttpHandlerFactory;
use wpCloud\StatelessMedia\Sync\FileSync;
use wpCloud\StatelessMedia\Sync\ImageSync;
use wpCloud\StatelessMedia\Sync\NonLibrarySync;
if (!class_exists('wpCloud\StatelessMedia\Bootstrap')) {
final class Bootstrap extends \UsabilityDynamics\WP\Bootstrap_Plugin {
const REQUIRED_PHP_VERSION = '5.5';
/**
* Google Storage Client
* Use $this->get_client()
*
* @var \wpCloud\StatelessMedia\GS_CLient
*/
private $client;
/**
* Plugin core version.
*
* @static
* @property $version
* @type {Object}
*/
public static $version = '3.0';
/**
* Singleton Instance Reference.
*
* @protected
* @static
* @property $instance
* @type \wpCloud\StatelessMedia\Bootstrap object
*/
protected static $instance = null;
/**
* Constructor
* Attention: MUST NOT BE CALLED DIRECTLY! USE get_instance() INSTEAD!
* @param $args
* @author peshkov@UD
*/
protected function __construct($args) {
/**
* Need to be loaded before plugin initialization.
*/
if ( !(defined('WP_STATELESS_COMPATIBILITY_GAE') && !WP_STATELESS_COMPATIBILITY_GAE) ) {
AppEngine::instance();
}
parent::__construct($args);
/**
* Add custom args to api ping request
*/
add_filter('ud-api-client-ping-args', function ($args, $_, $__) {
$args['multisite'] = is_multisite();
$args['stateless_media'] = Utility::get_stateless_media_data_count();
return $args;
}, 10, 3);
//** Define our Admin Notices handler object */
$this->errors = new Errors(array_merge($args, array(
'type' => $this->type
)));
// Initialize compatibility modules.
add_action('plugins_loaded', function () {
Addons::instance();
new Module();
DynamicImageSupport::instance();
}, 20);
/**
* Define settings and UI.
*
* Example:
*
* Get option
* $this->get( 'sm.client_id' )
*
* Manually Update/Add option
* $this->set( 'sm.client_id', 'zxcvv12adffse' );
*/
$this->settings = new Settings($this);
}
/**
* Prevent loading of textdomain
*/
public function load_textdomain() {
}
/**
* Instantiate class.
*/
public function init() {
// Parse feature falgs, set constants.
$this->parse_feature_flags();
$sm_mode = $this->get('sm.mode');
new SyncNonMedia();
ImageSync::instance();
FileSync::instance();
NonLibrarySync::instance();
// Invoke REST API
add_action('rest_api_init', array($this, 'api_init'));
// Register meta boxes and fields for media edit page
add_filter('rwmb_meta_boxes', array($this, 'attachment_meta_box_callback'));
// Register meta boxes and fields for media modal page
add_filter('attachment_fields_to_edit', array($this, 'attachment_modal_meta_box_callback'), 11, 2);
/**
* Init hook
*/
add_action('admin_init', array($this, 'admin_init'));
/**
* Handle switch blog properly.
*/
add_action('switch_blog', array($this, 'on_switch_blog'), 10, 2);
/**
* Filter for getting stateless settings
*/
add_filter('stateless::get_settings', array($this, 'get_settings'), 10);
/**
* Init AJAX jobs
*/
new Ajax();
/**
* Load WP-CLI Commands
*/
if (defined('WP_CLI') && WP_CLI) {
include_once($this->path('lib/cli/class-sm-cli-command.php', 'dir'));
}
/**
* Add scripts
*/
add_action('admin_enqueue_scripts', array($this, 'admin_enqueue_scripts'));
/**
* Delete table when blog is deleted.
*/
add_action('wp_delete_site', array($this, 'wp_delete_site'));
/**
* To prevent fatal errors for users who use PHP 5.5 or less.
*/
if (version_compare(PHP_VERSION, self::REQUIRED_PHP_VERSION, '<')) {
$this->errors->add(sprintf(__('The plugin requires PHP %s or higher. You current PHP version %s is too old.', ud_get_stateless_media()->domain), '<b>' . self::REQUIRED_PHP_VERSION . '</b>', '<b>' . PHP_VERSION . '</b>'));
}
/**
* Add the currently processing nag
*/
foreach (Utility::get_available_sync_classes() as $process) {
if ($process->is_running()) {
$this->errors->add([
'title' => __('Media Library Synchronization Underway', ud_get_stateless_media()->domain),
'message' => __('WP-Stateless is synchronizing your media library in accordance with the Mode setting. You can view progress or stop the process via the WP-Stateless Sync settings area.', ud_get_stateless_media()->domain),
'button' => __('View Synchronization', ud_get_stateless_media()->domain),
'button_link' => admin_url('upload.php?page=stateless-settings&tab=stless_sync_tab'),
'key' => 'processing-in-progress'
], 'message');
break;
}
}
/* Initialize plugin only if Mode is not 'disabled'. */
if (($sm_mode !== 'disabled' && $sm_mode !== 'stateless') || ($sm_mode === 'stateless' && (wp_doing_ajax() || wp_doing_cron()))) {
/**
* Determine if we have issues with connection to Google Storage Bucket
* if SM is not disabled.
*/
$is_connected = $this->is_connected_to_gs();
if (is_wp_error($is_connected)) {
$this->errors->add($is_connected->get_error_message(), 'warning');
}
if ($googleSDKVersionConflictError = get_transient("wp_stateless_google_sdk_conflict")) {
$this->errors->add($googleSDKVersionConflictError, 'warning');
}
/**
* Carry on only if we do not have errors.
*/
if (!$this->has_errors()) {
if (in_array($sm_mode, array('cdn', 'ephemeral', 'stateless'))) {
/**
* init main filters
*/
$this->_init_filters('main');
}
if ($sm_mode === 'ephemeral' || $sm_mode === 'stateless') {
// Store attachment id in a static variable on 'intermediate_image_sizes_advanced' filter.
// Utility::store_can_delete_attachment();
if (function_exists('is_wp_version_compatible') && is_wp_version_compatible('5.3-RC4-46673')) {
add_filter('intermediate_image_sizes_advanced', array('wpCloud\StatelessMedia\Utility', 'store_can_delete_attachment'), 10, 3);
}
}
if ($sm_mode === 'stateless') {
/**
* Replacing local path to gs:// for using it on StreamWrapper
*/
add_filter('upload_dir', array($this, 'filter_upload_dir'), 99);
/**
* Stateless mode working only with GD library
*/
add_filter('wp_image_editors', array($this, 'select_wp_image_editors'));
/**
* Init GS client
*/
global $gs_client;
if ($gs_client = $this->init_gs_client()) {
StreamWrapper::register($gs_client);
}
}
if ($this->get('sm.delete_remote') == 'true') {
/**
* On physical file deletion we remove any from GS
* We need priority grater than default (10) for ShortPixel plugin to work properly.
*/
add_filter('delete_attachment', array($this, 'remove_media'), 11);
}
/**
* init client's filters
*/
$this->_init_filters('client');
}
} elseif ($sm_mode == 'stateless') {
/**
* Determine if we have issues with connection to Google Storage Bucket
* if SM is not disabled.
*/
$is_connected = $this->is_connected_to_gs();
if (is_wp_error($is_connected)) {
$this->errors->add($is_connected->get_error_message(), 'warning');
}
if ($googleSDKVersionConflictError = get_transient("wp_stateless_google_sdk_conflict")) {
$this->errors->add($googleSDKVersionConflictError, 'warning');
}
/**
* Carry on only if we do not have errors.
*/
if (!$this->has_errors()) {
/**
* Replacing local path to gs:// for using it on StreamWrapper
*/
add_filter('upload_dir', array($this, 'filter_upload_dir'), 99);
/**
* Stateless mode working only with GD library
*/
add_filter('wp_image_editors', array($this, 'select_wp_image_editors'));
/**
* Init GS client
*/
global $gs_client;
if ($gs_client = $this->init_gs_client()) {
StreamWrapper::register($gs_client);
}
/**
* init client's filters
*/
$this->_init_filters('client');
/**
* init main filters
*/
$this->_init_filters('main');
}
}
}
/**
* Init additional filters which uses on all modes
* @param string $type
*/
private function _init_filters($type = '') {
switch ($type) {
case 'main':
add_filter('wp_get_attachment_image_attributes', array($this, 'wp_get_attachment_image_attributes'), 20, 3);
add_filter('wp_get_attachment_url', array($this, 'wp_get_attachment_url'), 20, 2);
add_filter('get_attached_file', array($this, 'get_attached_file'), 9, 2);
add_filter('attachment_url_to_postid', array($this, 'attachment_url_to_postid'), 20, 2);
if ($this->get('sm.body_rewrite') == 'true' || $this->get('sm.body_rewrite') == 'enable_editor') {
add_filter('the_content', array($this, 'the_content_filter'), 99);
}
if ($this->get('sm.body_rewrite') == 'true' || $this->get('sm.body_rewrite') == 'enable_meta') {
add_filter('get_post_metadata', array($this, 'post_metadata_filter'), 2, 4);
}
add_filter('wp_stateless_bucket_link', array($this, 'wp_stateless_bucket_link'));
break;
case 'client':
/**
* Add custom actions to media rows
*/
add_filter('media_row_actions', array($this, 'add_custom_row_actions'), 10, 3);
/**
* Hashify file name if option is enabled
*/
if ($this->get('sm.hashify_file_name') == 'true') {
add_filter('sanitize_file_name', array('wpCloud\StatelessMedia\Utility', 'randomize_filename'), 10);
}
/**
* Override Cache Control is option is enabled
*/
$cacheControl = trim($this->get('sm.cache_control'));
if (!empty($cacheControl)) {
add_filter('sm:item:cacheControl', array($this, 'override_cache_control'));
}
add_filter('wp_stateless_file_name', array($this, 'handle_root_dir'), 10, 4);
/**
* Extends metadata by adding GS information.
*/
add_filter('wp_get_attachment_metadata', array($this, 'wp_get_attachment_metadata'), 10, 2);
/**
* Add/Edit Media
*
* Once added or edited we can get into Attachment ID then get all image sizes and sync them with GS
* We can't use this. That's prevent removing this filter.
*/
add_filter('wp_update_attachment_metadata', array('wpCloud\StatelessMedia\Utility', 'add_media'), 999, 2);
/**
* Delete original in the end of generating metadata
* it does not work with PDF
*/
// add_filter('wp_generate_attachment_metadata', function ($metadata, $attachment_id, $state) {
// if (!in_array(ud_get_stateless_media()->get('sm.mode'), array('ephemeral'))) return $metadata;
// @unlink(get_attached_file($attachment_id, true));
// return $metadata;
// }, 99, 3);
/**
* Rewrite Image URLS
*/
add_filter('image_downsize', array($this, 'image_downsize'), 99, 3);
add_filter('wp_calculate_image_srcset', array($this, 'wp_calculate_image_srcset'), 10, 5);
/**
* Trigger module initialization and registration.
*/
do_action('sm::module::init', $this->get('sm'));
break;
case 'default':
break;
}
}
/**
* The default $editors value:
*
* array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' )
* @param $editors
* @return array
*/
public function select_wp_image_editors($editors) {
return array('WP_Image_Editor_GD');
}
/**
* @param callable|null $httpHandler
* @return StorageClient
* @throws \Exception
*/
public function init_gs_client(callable $httpHandler = null) {
// May be Loading Google SDK....
if (!class_exists('HttpHandlerFactory')) {
include_once(ud_get_stateless_media()->path('lib/Google/vendor/autoload.php', 'dir'));
}
$httpHandler = $httpHandler ? $httpHandler : HttpHandlerFactory::build();
$json_key = json_decode($this->settings->get('sm.key_json'), true);
if (!empty($json_key)) {
return new StorageClient(
[
'keyFile' => $json_key,
'httpHandler' => function ($request, $options) use ($httpHandler) {
$xGoogApiClientHeader = $request->getHeaderLine('x-goog-api-client');
$request = $request->withHeader('x-goog-api-client', $xGoogApiClientHeader);
return call_user_func_array($httpHandler, [$request, $options]);
},
'authHttpHandler' => HttpHandlerFactory::build(),
]
);
}
}
/**
* Replacing root dir with GCS path
* @param $uploads
* @return array
*/
public function filter_upload_dir($uploads) {
global $default_dir;
if ($default_dir) return $uploads;
//Bucket
$bucket = $this->get('sm.bucket');
//Bucket folder path
$root_dir = $this->get('sm.root_dir');
$root_dir = apply_filters("wp_stateless_handle_root_dir", $root_dir);
/**
* Subdir not uses on Stateless mode
*/
$uploads['subdir'] = '';
$basedir = rtrim(sprintf('gs://%s/%s', $bucket, $root_dir), '/');
$baseurl = rtrim(sprintf('https://storage.googleapis.com/%s/%s', $bucket, $root_dir), '/');
$uploads = array(
'url' => rtrim($baseurl . $uploads['subdir'], '/'),
'path' => $basedir . $uploads['subdir'],
'subdir' => $uploads['subdir'],
'basedir' => $basedir,
'baseurl' => $baseurl,
'error' => false,
);
return $uploads;
}
/**
* Rebuild srcset from gs_link.
* Using calculations returned from WordPress wp_calculate_image_srcset()
*
* @param $sources
* @param $size_array
* @param $image_src
* @param $image_meta
* @param $attachment_id
* @return array
*/
public function wp_calculate_image_srcset($sources, $size_array, $image_src, $image_meta, $attachment_id) {
$sm_mode = $this->get('sm.mode');
/**
* In Backup mode using local URL
*/
if ("backup" == $sm_mode) {
return $sources;
}
if (empty($image_meta['gs_link'])) {
$image_meta = wp_get_attachment_metadata($attachment_id);
}
if (is_array($sources) && !empty($image_meta['gs_link'])) {
$gs_name = $image_meta['gs_name'];
// getting position of root_dir in gs_name.
$root_dir_pos = strpos($gs_name, $image_meta['file']);
// removing rood_dir from gs_name so we can compare to replace url with gs_link.
if ($root_dir_pos !== false) {
$gs_name = substr($gs_name, $root_dir_pos);
}
if (!isset($gs_name) || empty($gs_name)) {
return [];
}
foreach ($sources as $width => &$image) {
// If srcset includes original image src, replace it
if (substr_compare($image['url'], $gs_name, -strlen($gs_name)) === 0) {
$image['url'] = $image_meta['gs_link'];
// Replace all sizes
} elseif (isset($image_meta['sizes']) && is_array($image_meta['sizes'])) {
$found = false;
foreach ($image_meta['sizes'] as $key => $meta) {
if (!isset($meta['gs_name']) || empty($meta['gs_name'])) {
continue;
}
$thumb_gs_name = $meta['gs_name'];
// removing rood_dir from gs_name
if ($root_dir_pos !== false) {
$thumb_gs_name = substr($thumb_gs_name, $root_dir_pos);
}
if (substr_compare($image['url'], $thumb_gs_name, -strlen($thumb_gs_name)) === 0) {
$image['url'] = $meta['gs_link'];
$found = true;
break;
}
}
// if no size found and mode is ephemeral or stateless and nothing to show for srcset item - unset that item
if (!$found && ($sm_mode === 'ephemeral' || $sm_mode === 'stateless')) {
$image = null;
}
} else {
// if mode is stateless and nothing to show for srcset item - unset that item
if ($sm_mode === 'ephemeral' || $sm_mode === 'stateless') {
$image = null;
}
}
}
} elseif (is_array($sources) && $sm_mode === 'stateless') {
foreach ($sources as $width => &$image) {
// Set default src
$image['url'] = $image_src;
}
}
return is_array($sources) ? array_filter($sources) : $sources;
}
/**
* Return gs host.
* If custom domain is set it's return bucket name as host,
* else return storage.googleapis.com as host and append bucket name at the end.
*
* @param array $sm
* @return mixed|void
*/
public function get_gs_host($sm = array()) {
$sm = $sm ? $sm : $this->get('sm');
$image_host = 'https://storage.googleapis.com/';
$image_host .= $sm['bucket'];
$custom_domain = $sm['custom_domain'];
$is_ssl = strpos($custom_domain, 'https://');
$custom_domain = str_replace(array('http://', 'https://'), '', $custom_domain);
$custom_domain = trim($custom_domain, '/');
// checking whether the provided domain is valid.
// if the custom domain is same as the bucket name
// or the custom domain is using https.
if (!empty($sm['bucket']) && !empty($custom_domain) && $custom_domain !== 'storage.googleapis.com' && ($is_ssl === 0 || $custom_domain == $sm['bucket'])) {
$image_host = $is_ssl === 0 ? 'https://' : 'http://'; // bucketname will be host
$image_host .= $custom_domain;
}
return apply_filters('get_gs_host', $image_host, $image_host, $sm['bucket'], $is_ssl, $sm);
}
/**
* Filter for wp_stateless_bucket_link if custom domain is set.
* It's get attachment url and remove "storage.googleapis.com" from url.
* So that custom url can be used.
*
* @param $fileLink
* @return mixed|string
*/
public function wp_stateless_bucket_link($fileLink) {
$bucketname = $this->get('sm.bucket');
$custom_domain = $this->get('sm.custom_domain');
$is_ssl = strpos($custom_domain, 'https://') === 0;
$fileLink_is_ssl = strpos($fileLink, 'https://') === 0;
$custom_domain = str_replace(array('http://', 'https://'), '', $custom_domain);
$custom_domain = trim($custom_domain, '/');
if (!empty($bucketname) && $custom_domain !== 'storage.googleapis.com' && $custom_domain == $bucketname && strpos($fileLink, $bucketname) > 8) {
$fileLink = ($is_ssl ? 'https://' : 'http://') . substr($fileLink, strpos($fileLink, $bucketname));
} elseif ($custom_domain !== 'storage.googleapis.com' && $custom_domain == $bucketname && $fileLink_is_ssl !== $is_ssl) {
if ($is_ssl)
$fileLink = str_replace(array('http://', 'https://'), 'https://', $fileLink);
else
$fileLink = str_replace(array('http://', 'https://'), 'http://', $fileLink);
}
return $fileLink;
}
/**
* Return settings page url.
*
* @param string $path
* @return string
*/
public function get_settings_page_url($path = '') {
$url = get_admin_url(get_current_blog_id(), (is_network_admin() ? 'network/settings.php' : 'upload.php'));
return $url . $path;
}
/**
* Get new blog settings once switched blog.
* @param $new_blog
* @param $prev_blog_id
*/
public function on_switch_blog($new_blog, $prev_blog_id) {
$this->settings->refresh();
}
/**
* Get settings handler.
* Filling array if some settings missing.
*
* @param $settings
* @return
*/
public function get_settings($settings) {
$settings_list = array(
'mode',
'body_rewrite',
'body_rewrite_types',
'bucket',
'root_dir',
'key_json',
'cache_control',
'delete_remote',
'custom_domain',
'organize_media',
'hashify_file_name'
);
foreach ($settings_list as $setting) {
/** If setting is already exist, just skip it */
if (isset($settings[$setting])) {
continue;
}
$value = $this->get('sm.' . $setting);
/** Decode json to array */
if ($value && is_string($value) && $setting === 'key_json') {
$value = json_decode($value, true);
$setting = 'key';
}
$settings[$setting] = $value;
}
return $settings;
}
/**
* Remove all settings.
* @param bool $network
*/
public function reset($network = false) {
$this->settings->reset($network);
}
/**
* @param $actions
* @param $post
* @param $detached
* @return mixed
*/
public function add_custom_row_actions($actions, $post, $detached) {
if (!current_user_can('upload_files')) return $actions;
$sm_cloud = get_post_meta($post->ID, 'sm_cloud', 1);
$sm_mode = $this->get('sm.mode');
if (!empty($sm_cloud) && $sm_mode === 'stateless') return $actions;
if ($post && 'attachment' == $post->post_type && 'image/' == substr($post->post_mime_type, 0, 6)) {
$actions['sm_sync'] = '<a href="javascript:;" data-id="' . $post->ID . '" data-type="image" class="sm_inline_sync">' . __('Regenerate and Sync with GCS', ud_get_stateless_media()->domain) . '</a>';
}
if ($post && 'attachment' == $post->post_type && 'image/' != substr($post->post_mime_type, 0, 6)) {
$actions['sm_sync'] = '<a href="javascript:;" data-id="' . $post->ID . '" data-type="other" class="sm_inline_sync">' . __('Sync with GCS', ud_get_stateless_media()->domain) . '</a>';
}
return $actions;
}
/**
* Define REST API.
*
* @author korotkov@UD
*/
public function api_init() {
$route_namespace = 'wp-stateless/v1';
$api_namespace = 'wpCloud\StatelessMedia\API';
register_rest_route($route_namespace, '/status', array(
'methods' => \WP_REST_Server::READABLE,
'callback' => array($api_namespace, 'status'),
'permission_callback' => '__return_true'
));
register_rest_route($route_namespace, '/getSettings', array(
'methods' => \WP_REST_Server::READABLE,
'callback' => array($api_namespace, 'getSettings'),
'permission_callback' => array($api_namespace, 'authCheck')
));
register_rest_route($route_namespace, '/updateSettings', array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array($api_namespace, 'updateSettings'),
'permission_callback' => array($api_namespace, 'authCheck')
));
register_rest_route($route_namespace, '/sync/getProcesses', array(
'methods' => \WP_REST_Server::READABLE,
'callback' => array($api_namespace, 'syncGetProcesses'),
'permission_callback' => array($api_namespace, 'authCheck')
));
register_rest_route($route_namespace, '/sync/getProcess/(?P<id>\S+)', array(
'methods' => \WP_REST_Server::READABLE,
'callback' => array($api_namespace, 'syncGetProcess'),
'permission_callback' => array($api_namespace, 'authCheck')
));
register_rest_route($route_namespace, '/sync/run', array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array($api_namespace, 'syncRun'),
'permission_callback' => array($api_namespace, 'authCheck')
));
register_rest_route($route_namespace, '/sync/stop', array(
'methods' => \WP_REST_Server::CREATABLE,
'callback' => array($api_namespace, 'syncStop'),
'permission_callback' => array($api_namespace, 'authCheck')
));
}
/**
* Metabox for media modal page
* @param $form_fields
* @param $post
* @return array
*/
public function attachment_modal_meta_box_callback($form_fields, $post) {
// Do not show on media edit page, only on modal
// Do not show if we are not in Media Library
if ( isset($_GET['post']) || wp_doing_ajax() ) {
return $form_fields;
}
$link = get_edit_post_link($post->ID);
$form_field['label'] = '';
$form_field['input'] = 'html';
$form_field['html'] = sprintf("<script>jQuery('.sm_edit_links').remove();jQuery('.actions').prepend('<a class=\"sm_edit_links\" href=\"%s#sm-attachment-metabox\">%s</a> | ')</script>", $link, __("View stateless meta", ud_get_stateless_media()->domain));
$form_field['show_in_modal'] = true;
$form_fields['sm_html'] = $form_field;
return $form_fields;
}
/**
* Metabox for media edit page
* @param $meta_boxes
* @return array
*/
public function attachment_meta_box_callback($meta_boxes) {
$post_id = false;
if (isset($_GET['post'])) {
$post_id = intval($_GET['post']);
} elseif (isset($_POST['post_ID'])) {
$post_id = intval($_POST['post_ID']);
} elseif (isset($_GET['item'])) {
$post_id = intval($_GET['item']);
} elseif (isset($_POST['item'])) {
$post_id = intval($_POST['item']);
}
return $this->_prepare_data_for_metabox($meta_boxes, $post_id);
}
/**
* Prepare data for metabox fields
* @param $meta_boxes
* @param $post_id
* @return array
*/
private function _prepare_data_for_metabox($meta_boxes, $post_id) {
$post = get_post($post_id);
$sm_cloud = get_post_meta($post_id, 'sm_cloud', 1);
$sm_mode = $this->get('sm.mode');
if (empty($post)) {
return $meta_boxes;
}
$sizes = $this->get_image_sizes();
$fields = array();
if ($sm_mode !== 'stateless' || empty($sm_cloud)) {
$fields[] = array(
'name' => __('Regenerate', ud_get_stateless_media()->domain),
'id' => 'storage_bucket_url',
'type' => 'custom_html',
'std' => $this->_prepare_generate_link($post, false, '', true, $sm_cloud),
'tab' => 'thumbnails',
);
}
if (is_array($sm_cloud) && !empty($sm_cloud['fileLink'])) {
$fields[] = array(
'type' => 'heading',
'name' => 'Files',
'tab' => 'thumbnails',
);
$fields[] = array(
'name' => __('Original', ud_get_stateless_media()->domain),
'id' => 'storage_bucket_url',
'type' => 'custom_html',
'media_modal' => true,
'std' => '<label><input type="text" class="widefat urlfield" readonly="readonly" value="' . esc_attr($sm_cloud['fileLink']) . '" />
<a href="' . $sm_cloud['fileLink'] . '" target="_blank" class="sm-view-link"><i class="dashicons dashicons-external"></i></a> ' . $this->_prepare_generate_link($post, true, '', false, $sm_cloud) . ' </label>',
'tab' => 'thumbnails',
);
if (!empty($sm_cloud['sizes']) && is_array($sm_cloud['sizes'])) {
foreach ($sm_cloud['sizes'] as $size_label => $size) {
$fields[] = array(
'name' => __(sprintf("%s x %s", ($size['width'] ?: $sizes[$size_label]['width']), ($size['height'] ?: $sizes[$size_label]['height'])), ud_get_stateless_media()->domain),
'id' => 'storage_bucket_url' . $size_label,
'type' => 'custom_html',
'media_modal' => true,
'std' => '<label><input type="text" class="widefat urlfield" readonly="readonly" value="' . esc_attr($size['fileLink']) . '" />
<a href="' . $size['fileLink'] . '" target="_blank" class="sm-view-link"><i class="dashicons dashicons-external"></i></a> ' . $this->_prepare_generate_link($post, true, $size_label, false, $sm_cloud) . ' </label>',
'tab' => 'thumbnails',
);
}
}
if (!empty($sm_cloud['cacheControl'])) {
$fields[] = array(
'name' => __('Cache Control', ud_get_stateless_media()->domain),
'id' => 'cache_control',
'type' => 'custom_html',
'std' => '<label><input type="text" class="widefat urlfield" readonly="readonly" value="' . $sm_cloud['cacheControl'] . '" /></label>',
'tab' => 'meta',
);
}
if (!empty($sm_cloud['bucket'])) {
$fields[] = array(
'name' => __('Storage Bucket', ud_get_stateless_media()->domain),
'id' => 'storage_bukcet',
'type' => 'custom_html',
'std' => '<label><input type="text" class="widefat urlfield" readonly="readonly" value="gs://' . esc_attr($sm_cloud['bucket']) . '" />
<a href="https://console.cloud.google.com/storage/browser/' . esc_attr($sm_cloud['bucket']) . '" target="_blank" class="sm-view-link"><i class="dashicons dashicons-external"></i></a></label>',
'tab' => 'meta',
);
}
}
$meta_boxes[] = apply_filters('sm::attachment::meta', array(
'id' => 'sm-attachment-metabox',
'title' => __('Stateless', ud_get_stateless_media()->domain),
'post_types' => 'attachment',
//'media_modal' => true,
//set context `side` for left column
'context' => 'normal',
'priority' => 'low',
'tabs' => array(
'thumbnails' => array(
'label' => __('Thumbnails', ud_get_stateless_media()->domain),
'icon' => 'dashicons-format-gallery',
),
'meta' => array(
'label' => __('Meta', ud_get_stateless_media()->domain),
'icon' => 'dashicons-admin-site',
),
),
// Tab style: 'default', 'box' or 'left'. Optional
'tab_style' => 'left',
// Show meta box wrapper around tabs? true (default) or false. Optional
'tab_wrapper' => true,
'fields' => $fields
), $post->ID);
return $meta_boxes;
}
/**
* Preparing link for sync
* @param $post
* @param bool $use_icon
* @param string $size
* @param bool $button
* @param array $sm_cloud
* @return string
*/
private function _prepare_generate_link($post, $use_icon = false, $size = '', $button = false, $sm_cloud = array()) {
$sync = '';
$sm_mode = $this->get('sm.mode');
if (current_user_can('upload_files') && $sm_mode !== 'disabled' && ($sm_mode !== 'stateless' || empty($sm_cloud))) {
if ($post && 'attachment' == $post->post_type && 'image/' == substr($post->post_mime_type, 0, 6)) {
$sync = '<a href="javascript:;" data-type="image" data-id="' . $post->ID . '" data-size="' . $size . '" data-reload_page="' . $button . '"
class="sm_inline_sync ' . ($button ? 'button button-primary button-large' : '') . '">' . ($use_icon ? "<i class='dashicons dashicons-image-rotate'></i>" : __('Regenerate and Sync with GCS', ud_get_stateless_media()->domain)) . '</a>';
}
if ($post && 'attachment' == $post->post_type && 'image/' != substr($post->post_mime_type, 0, 6)) {
$sync = '<a href="javascript:;" data-type="other" data-id="' . $post->ID . '" data-size="' . $size . '" data-reload_page="' . $button . '"
class="sm_inline_sync ' . ($button ? 'button button-primary button-large' : '') . '">' . ($use_icon ? "<i class='dashicons dashicons-image-rotate'></i>" : __('Sync with GCS', ud_get_stateless_media()->domain)) . '</a>';
}
} elseif ($button && $sm_mode !== 'stateless') {
$sync = __('You do not have access to sync or Stateless mode is Disabled', ud_get_stateless_media()->domain);
}
return $sync;
}
/**
* @param $current_path
* @param $use_root boolean: whether to use the root dir or not.
* 0 will be passed from various compatibilities so that the root dir is not used.
* false will passed from some compatibilities to use the value as local path.
* @param $attachment_id
* @param $size
* @return string
*/
public function handle_root_dir($current_path, $use_root = true, $attachment_id = '', $size = '') {
global $wpdb;
//non media files
if ($use_root === 0) {
$table_name = $wpdb->prefix . 'sm_sync';
$non_media = $wpdb->get_var($wpdb->prepare("SELECT file FROM {$table_name} WHERE file like '%%%s';", $current_path));
if ($non_media) {
return $non_media;
}
}
$root_dir = $this->get('sm.root_dir');
$root_dir_regex = '~^' . apply_filters("wp_stateless_handle_root_dir", $root_dir, true) . '/~';
/**
* Retrieve Y/M and other tags from current path
*/
$path_elements = apply_filters('wp_stateless_unhandle_root_dir', $current_path);
$root_dir = apply_filters("wp_stateless_handle_root_dir", $root_dir, false, $path_elements);
$upload_dir = wp_upload_dir();
$current_path = str_replace(wp_normalize_path(trailingslashit($upload_dir['basedir'])), '', wp_normalize_path($current_path));
$current_path = str_replace(wp_normalize_path(trailingslashit($upload_dir['baseurl'])), '', wp_normalize_path($current_path));
$current_path = str_replace(trailingslashit($this->get_gs_host()), '', $current_path);
/**
* Using only filename. Other parts of path included to $root_dir.
* excluding compatibility.
*/
if ($use_root) {
$current_path = basename($current_path);
}
if (!$use_root) {
// removing the root dir if already exists in the beginning.
$raw_name = preg_replace($root_dir_regex, '', $current_path);
if ($raw_name && is_multisite() && ($blog_id = get_current_blog_id()) != 1) {
$folder = "sites/{$blog_id}/";
if (strpos($raw_name, $folder) === 0) return $raw_name;
return "$folder$raw_name";
}
return $raw_name;