PluginProbe
Media Cloud Sync / 1.3.0
Media Cloud Sync v1.3.0
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.0, at includes/api.php

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