PluginProbe
Media Cloud Sync / 1.3.10
Media Cloud Sync v1.3.10
1.4.0 1.3.12 1.3.11 1.3.10 trunk 1.0.0 1.0.1 1.0.2 1.0.3 1.1.0 1.1.1 1.2.0 1.2.10 1.2.11 1.2.12 1.2.13 1.2.2 1.2.3 1.2.4 1.2.5 1.2.6 1.2.7 1.2.8 1.2.9 1.3.0 All 34 releases
media-cloud-sync / includes / api.php

api.php in Media Cloud Sync 1.3.10, at includes/api.php

549 lines 15.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 namespace Dudlewebs\WPMCS;
3
4 use WP_REST_Response;
5
6 defined('ABSPATH') || exit;
7
8 class Api {
9 private static $instance = null;
10 private $token;
11 private $version;
12 private $assets_url;
13
14 /**
15 * Constructor
16 * @since 1.0.0
17 */
18
19 public function __construct() {
20 $this->assets_url = WPMCS_ASSETS_URL;
21 $this->version = WPMCS_VERSION;
22 $this->token = WPMCS_TOKEN;
23
24 add_action( 'rest_api_init', array( $this, 'register_routes' ) );
25 }
26
27
28 /**
29 * Register API routes
30 */
31
32 public function register_routes() {
33 $this->add_route( '/verifyCredentials', 'verifyCredentials', 'POST' );
34 $this->add_route( '/permissions/checkExist', 'verifyBucketExist', 'POST' );
35 $this->add_route( '/permissions/addNewBucket', 'createBucket', 'POST' );
36 $this->add_route( '/permissions/write', 'verifyObjectWrite', 'POST' );
37 $this->add_route( '/permissions/delete', 'verifyObjectDelete', 'POST' );
38 $this->add_route( '/permissions/read', 'verifyObjectRead', 'POST' );
39
40 $this->add_route( '/security/get_security', 'getBucketSecuritySettings', 'POST' );
41 $this->add_route( '/security/block_public_access', 'changePublicAccess', 'POST' );
42 $this->add_route( '/security/object_ownership_enforce', 'changeObjectOwnership', 'POST' );
43
44 $this->add_route( '/getSettings', 'getSettings' );
45 $this->add_route( '/saveConfig', 'saveConfig', 'POST' );
46 $this->add_route( '/refreshCounts', 'refreshCounts', 'POST' );
47 $this->add_route( '/getErrorLogs', 'getErrorLogs', 'POST' );
48
49 // Upgrade Database Routes
50 $this->add_route( '/upgrade/status', 'getUpgradeStatus' );
51 $this->add_route( '/upgrade/start', 'startUpgrade', 'POST' );
52
53 // Sync Routes
54 $this->add_route( '/sync/status', 'getStatus' );
55 $this->add_route( '/sync/start', 'startSync', 'POST' );
56 $this->add_route( '/sync/pause', 'pauseSync', 'POST' );
57 $this->add_route( '/sync/resume', 'resumeSync', 'POST' );
58 $this->add_route( '/sync/stop', 'stopSync', 'POST' );
59
60 $this->add_route( '/sync/retrySingle', 'retrySingle', 'POST' );
61 }
62
63 /**
64 * Verify the Service Credentials
65 */
66 public function verifyCredentials( $data ) {
67 return new WP_REST_Response( Service::instance()->verifyCredentials($data->get_params()), 200 );
68 }
69
70 /**
71 * Verify the Bucket exist
72 */
73 public function verifyBucketExist( $data ) {
74 return new WP_REST_Response( Service::instance()->verifyBucketExist($data->get_params()), 200 );
75 }
76
77 /**
78 * Create the bucket
79 */
80 public function createBucket( $data ) {
81 return new WP_REST_Response( Service::instance()->createBucket($data->get_params()), 200 );
82 }
83
84
85 /**
86 * Verify the Bucket Write Permission
87 */
88 public function verifyObjectWrite( $data ) {
89 return new WP_REST_Response( Service::instance()->verifyObjectWritePermission($data->get_params()), 200 );
90 }
91
92 /**
93 * Verify the Bucket delete Permission
94 */
95 public function verifyObjectDelete( $data ) {
96 return new WP_REST_Response( Service::instance()->verifyObjectDeletePermission($data->get_params()), 200 );
97 }
98
99 /**
100 * Verify the Bucket Read Permission
101 */
102 public function verifyObjectRead( $data ) {
103 return new WP_REST_Response( Service::instance()->verifyObjectReadPermission(), 200 );
104 }
105
106 /**
107 * Get the Security Settings
108 */
109 public function getBucketSecuritySettings( $data ) {
110 return new WP_REST_Response( Service::instance()->getBucketSecuritySettings($data->get_params()), 200 );
111 }
112
113
114 /**
115 * Change the Public Access
116 */
117 public function changePublicAccess( $data ) {
118 return new WP_REST_Response( Service::instance()->changePublicAccess($data->get_params()), 200 );
119 }
120
121
122 /**
123 * Change the Object Ownership
124 */
125 public function changeObjectOwnership( $data ) {
126 return new WP_REST_Response( Service::instance()->changeObjectOwnership($data->get_params()), 200 );
127 }
128
129 /**
130 * Get Settings
131 */
132 public function getSettings( ) {
133 // Fetch and update media counts for make sure they are up to date
134 Counter::fetch_and_update();
135
136 $data = [
137 'credentials' => Utils::get_credentials( '', [], true ),
138 'common' => [
139 'version' => defined('WPMCS_PRO_VERSION') ? WPMCS_PRO_VERSION : WPMCS_VERSION,
140 'counts' => [
141 'all' => Counter::get_count(),
142 'categorized' => $this->getSortedMediaCounts()
143 ],
144 'status' => Utils::get_status('', false),
145 'settings' => Utils::get_settings(),
146 ],
147 'sync' => Sync::instance()->get_status(),
148 'license' => defined('WPMCS_PRO_VERSION') ? Utils::get_safe_license_data() : [],
149 ];
150
151 return new WP_REST_Response( $data, 200 );
152 }
153
154 /**
155 * Save the Configurations
156 */
157 public function saveConfig( $data ) {
158 $saveData = $data->get_params();
159 $result = [
160 'success' => false,
161 'message' => esc_html__('Something went wrong. Invalid data recieved', 'media-cloud-sync')
162 ];
163
164 $action = isset($saveData['action']) ? $saveData['action'] : false;
165 if($action === false) return new WP_REST_Response( $result, 200 );
166
167 $service = isset($saveData['service']) ? $saveData['service'] : false;
168 $serviceLabel = isset($saveData['serviceLabel']) ? $saveData['serviceLabel'] : '';
169 $cdn = isset($saveData['cdn']) ? $saveData['cdn'] : [];
170 $config = isset($saveData['config']) ? $saveData['config'] : false;
171 $bucketConfig = isset($saveData['bucketConfig']) ? $saveData['bucketConfig'] : [];
172 $security = isset($saveData['security']) ? $saveData['security'] : [];
173 $settings = isset($saveData['settings']) ? $saveData['settings'] : [];
174
175 $serviceOk = true;
176 $settingsOk = true;
177
178 if( $action === 'cdn' ){
179 $existing = Utils::get_credentials();
180 $existing['cdn'] = $cdn;
181
182 $updated = Utils::update_option('credentials', $existing, Schema::getConstant('GLOBAL_SETTINGS_KEY'));
183 $updatedSettings = Utils::update_option('settings', $settings, Schema::getConstant('GLOBAL_SETTINGS_KEY'));
184
185 if(!$updated) $serviceOk = false;
186 }
187
188
189 if($action === 'all' || $action === 'service'){
190 if ( $service === false || empty($config) || empty($bucketConfig)) return new WP_REST_Response( $result, 200 );
191
192 $updated = Utils::update_option(
193 'credentials',
194 [
195 'service' => $service,
196 'serviceLabel' => $serviceLabel,
197 'cdn' => $cdn,
198 'config' => $config,
199 'bucketConfig' => $bucketConfig,
200 'security' => $security
201 ],
202 Schema::getConstant('GLOBAL_SETTINGS_KEY')
203 );
204 if(!$updated) $serviceOk = false;
205
206 if($serviceOk) {
207 Utils::set_status('cdnRead', [
208 'status' => false,
209 'message' => '',
210 'lastChecked' => null
211 ]);
212 }
213 }
214
215 if(($action === 'all' || $action === 'settings')) {
216 $updatedSettings = Utils::update_option('settings', $settings, Schema::getConstant('GLOBAL_SETTINGS_KEY'));
217
218 // Clear content meta cache if settings updated
219 Utils::clear_all_content_meta();
220 if(!$updatedSettings) $settingsOk = false;
221 }
222
223 // If action is all, service or settings, clear caches and update counts
224 if($action === 'all' || $action === 'service' || $action === 'settings') {
225 //clear object cache
226 Cache::flush_object_cache();
227 // clear all meta of attachments
228 Integration::instance()->clear_all_meta();
229 // clear all content meta
230 Utils::clear_all_content_meta();
231 // update counts
232 Counter::instance()->fetch_and_update();
233 }
234
235
236 if($serviceOk && $settingsOk) {
237 $result = [
238 'success' => true,
239 'message' => esc_html__('Configuration saved successfully', 'media-cloud-sync')
240 ];
241 }
242
243 return new WP_REST_Response( $result, 200 );
244 }
245
246
247 /**
248 * Refresh the Media Counts
249 *
250 */
251 public function refreshCounts( ) {
252 Cache::flush_object_cache();
253 Integration::instance()->clear_all_meta();
254 Counter::instance()->fetch_and_update();
255
256 $result = [
257 'success' => true,
258 'counts' => [
259 'all' => Counter::get_count(),
260 'categorized' => $this->getSortedMediaCounts()
261 ],
262 'message' => esc_html__('Media counts refreshed successfully', 'media-cloud-sync')
263 ];
264 return new WP_REST_Response( $result, 200 );
265 }
266
267
268 /**
269 * Start Upgrade
270 * @since 1.3.6
271 */
272 public function startUpgrade( $request ) {
273 $result = Upgrade::instance()->start_upgrade();
274 return new WP_REST_Response( $result, 200 );
275 }
276
277
278 /**
279 * Get Upgrade Status
280 * @since 1.3.6
281 */ public function getUpgradeStatus( $request ) {
282 $result = Upgrade::instance()->get_progress();
283 return new WP_REST_Response( $result, 200 );
284 }
285
286
287 /**
288 * Get Media Error Logs
289 * @since 1.2.13
290 */
291 public function getErrorLogs( $request ) {
292 $params = $request->get_params();
293 $type = isset($params['type']) ? $params['type'] : 'all';
294 $page = isset($params['page']) ? $params['page'] : null;
295 $per_page = isset($params['per_page']) ? $params['per_page'] : null;
296
297 if($type !== 'all') {
298 $logs = Logger::instance()->get_logs_by_type($type, $page, $per_page);
299 } else {
300 $logs = Logger::instance()->get_all_logs($page, $per_page);
301 }
302
303 $result = [
304 'success' => true,
305 'logs' => $logs,
306 'message' => esc_html__('Error logs fetched successfully', 'media-cloud-sync')
307 ];
308 return new WP_REST_Response( $result, 200 );
309 }
310
311
312 /**
313 * Get Status
314 * @since 1.2.13
315 */
316 public function getStatus( $request ) {
317 // Fetch and update media counts for make sure they are up to date
318 $action = isset($request->get_params()['action']) ? $request->get_params()['action'] : 'all';
319 $status = Sync::instance()->get_status();
320
321 if($action !== 'all') {
322 $status = isset($status[$action]) ? $status[$action] : [];
323 }
324
325 $result = [
326 'success' => true,
327 'status' => $status,
328 'counts' => [
329 'all' => Counter::get_count(),
330 'categorized' => $this->getSortedMediaCounts()
331 ],
332 'message' => esc_html__('Status fetched successfully', 'media-cloud-sync')
333 ];
334
335 return new WP_REST_Response( $result, 200 );
336 }
337
338
339 /**
340 * Start Sync
341 * @since 1.2.13
342 */
343 public function startSync( $data ) {
344 $action = isset($data->get_params()['action']) ? $data->get_params()['action'] : '';
345 if(empty($action)) {
346 $result = [
347 'success' => false,
348 'message' => esc_html__('Invalid action', 'media-cloud-sync')
349 ];
350 return new WP_REST_Response( $result, 200 );
351 }
352 $status = Sync::instance()->start($action);
353
354 $result = [
355 'success' => true,
356 'status' => $status,
357 'message' => esc_html__('Sync started successfully', 'media-cloud-sync')
358 ];
359 return new WP_REST_Response( $result, 200 );
360 }
361
362
363 /**
364 * Pause Sync
365 * @since 1.2.13
366 */
367 public function pauseSync( $data ) {
368 $action = isset($data->get_params()['action']) ? $data->get_params()['action'] : '';
369 if(empty($action)) {
370 $result = [
371 'success' => false,
372 'message' => esc_html__('Invalid action', 'media-cloud-sync')
373 ];
374 return new WP_REST_Response( $result, 200 );
375 }
376 $status = Sync::instance()->pause($action);
377
378 $result = [
379 'success' => true,
380 'status' => $status,
381 'message' => esc_html__('Sync paused successfully', 'media-cloud-sync')
382 ];
383 return new WP_REST_Response( $result, 200 );
384 }
385
386
387 /**
388 * Resume Sync
389 * @since 1.2.13
390 */
391 public function resumeSync( $data ) {
392 $action = isset($data->get_params()['action']) ? $data->get_params()['action'] : '';
393 if(empty($action)) {
394 $result = [
395 'success' => false,
396 'message' => esc_html__('Invalid action', 'media-cloud-sync')
397 ];
398 return new WP_REST_Response( $result, 200 );
399 }
400 $status = Sync::instance()->resume($action);
401
402 $result = [
403 'success' => true,
404 'status' => $status,
405 'message' => esc_html__('Sync resumed successfully', 'media-cloud-sync')
406 ];
407 return new WP_REST_Response( $result, 200 );
408 }
409
410
411 /**
412 * Stop Sync
413 * @since 1.2.13
414 */
415 public function stopSync( $data ) {
416 $action = isset($data->get_params()['action']) ? $data->get_params()['action'] : '';
417 if(empty($action)) {
418 $result = [
419 'success' => false,
420 'message' => esc_html__('Invalid action', 'media-cloud-sync')
421 ];
422 return new WP_REST_Response( $result, 200 );
423 }
424 $status = Sync::instance()->stop($action);
425
426 $result = [
427 'success' => true,
428 'status' => $status,
429 'counts' => [
430 'all' => Counter::get_count(),
431 'categorized' => $this->getSortedMediaCounts()
432 ],
433 'message' => esc_html__('Sync stopped successfully', 'media-cloud-sync')
434 ];
435 return new WP_REST_Response( $result, 200 );
436 }
437
438
439 /**
440 * Retry a Media Sync Error
441 */
442 public function retrySingle( $data ) {
443 $params = $data->get_params();
444 $id = isset($params['id']) ? $params['id'] : '';
445 $source_type = isset($params['source_type']) ? $params['source_type'] : 'media_library';
446 $type = isset($params['type']) ? $params['type'] : '';
447 $status = false;
448 if(empty($id) || empty($source_type) || empty($type)) {
449 $result = [
450 'success' => false,
451 'message' => esc_html__('Invalid parameters', 'media-cloud-sync')
452 ];
453 return new WP_REST_Response( $result, 200 );
454 }
455 // Retry Sync
456 $handler = Sync::instance()->get_class_by_action($type);
457 if($handler) {
458 $handler->retry_single($id, $source_type);
459 }
460
461 $status = Utils::is_empty(Logger::instance()->get_log($type, $id, $source_type)) ? true : false;
462
463 $result = [
464 'success' => $status,
465 'message' => $status ? esc_html__('Media synced successfully', 'media-cloud-sync') : esc_html__('Media sync failed', 'media-cloud-sync')
466 ];
467 return new WP_REST_Response( $result, 200 );
468 }
469
470
471 /**
472 * Get Sorted Media Counts
473 * Sorts media counts by source type
474 * @since 1.2.13
475 */
476 private function getSortedMediaCounts() {
477 $sorted_counts = [];
478 $detailed_counts = Counter::get_count( 'all', false );
479 if(!empty($detailed_counts)) {
480 $source_labels = Integration::$source_labels;
481 if(!empty($source_labels)) {
482 $prefixes = array_keys($source_labels);
483 foreach($detailed_counts as $source_type => $counts) {
484 $found_prefix = false;
485 foreach($prefixes as $prefix) {
486 $found_prefix = strpos($source_type, $prefix) === 0 ? $prefix : false;;
487 if($found_prefix !== false) break;
488 }
489
490 if($found_prefix !== false) {
491 $sorted_counts[$found_prefix] = [
492 'label' => $source_labels[$found_prefix],
493 'uploaded' => isset($sorted_counts[$found_prefix]['data']['uploaded'])
494 ? $sorted_counts[$found_prefix]['data']['uploaded'] + $counts['uploaded']
495 : $counts['uploaded'],
496 'total' => isset($sorted_counts[$found_prefix]['data']['total'])
497 ? $sorted_counts[$found_prefix]['data']['total'] + $counts['total']
498 : $counts['total']
499 ];
500 }
501 }
502 }
503 }
504
505 return $sorted_counts;
506 }
507
508
509 /**
510 * Helper function to create Adding Route
511 * @since 1.0.0
512 */
513 private function add_route( $slug, $callBack, $method = 'GET' ) {
514 register_rest_route(
515 $this->token . '/v1',
516 $slug,
517 array(
518 'methods' => $method,
519 'callback' => array( $this, $callBack ),
520 'permission_callback' => array( $this, 'getPermission' ),
521 ) );
522 }
523
524 /**
525 * Permission Callback
526 **/
527 public function getPermission() {
528 if ( current_user_can( 'manage_options' ) ) {
529 return true;
530 } else {
531 return false;
532 }
533 }
534
535 /**
536 * Ensures only one instance of Class is loaded or can be loaded.
537 *
538 * @return Api Class instance
539 * @since 1.0.0
540 * @static
541 */
542 public static function instance(){
543 if (is_null(self::$instance)) {
544 self::$instance = new self();
545 }
546 return self::$instance;
547 }
548 }
549