| 1 |
<?php |
| 2 |
|
| 3 |
namespace FluentBooking\App\Services; |
| 4 |
|
| 5 |
use FluentBooking\App\Services\PermissionManager; |
| 6 |
|
| 7 |
class ImportService |
| 8 |
{ |
| 9 |
/* |
| 10 |
* Import host data from JSON |
| 11 |
* @param array|string $data JSON data or array |
| 12 |
* @param bool $useCurrentUser If true, the current user will be used as the host |
| 13 |
* @return \FluentBooking\App\Models\Calendar|\WP_Error |
| 14 |
*/ |
| 15 |
public function importHostJson($data, $useCurrentUser = true) |
| 16 |
{ |
| 17 |
if (!PermissionManager::userCan(['manage_all_data', 'manage_other_calendars'])) { |
| 18 |
return new \WP_Error('invalid_data', __('You are not authorized to import calendar', 'fluent-booking')); |
| 19 |
} |
| 20 |
|
| 21 |
if (!$useCurrentUser && !PermissionManager::userCan('manage_all_data')) { |
| 22 |
$useCurrentUser = true; |
| 23 |
} |
| 24 |
|
| 25 |
if (is_string($data)) { |
| 26 |
$data = json_decode($data, true); |
| 27 |
} |
| 28 |
|
| 29 |
if (!$data || !is_array($data) || empty($data['data_type']) || $data['data_type'] !== 'host') { |
| 30 |
return new \WP_Error('invalid_data', 'Invalid data provided'); |
| 31 |
} |
| 32 |
|
| 33 |
if (empty($data['title']) || empty($data['slug'])) { |
| 34 |
return new \WP_Error('invalid_data', 'Invalid data provided'); |
| 35 |
} |
| 36 |
|
| 37 |
$createdCalendar = CalendarService::createCalendar($data, $useCurrentUser); |
| 38 |
|
| 39 |
if (is_wp_error($createdCalendar)) { |
| 40 |
return new \WP_Error($createdCalendar->get_error_code(), $createdCalendar->get_error_message()); |
| 41 |
} |
| 42 |
|
| 43 |
return $createdCalendar; |
| 44 |
} |
| 45 |
|
| 46 |
/* |
| 47 |
* Import host data from JSON URL |
| 48 |
* @param string $jsonUrl JSON URL |
| 49 |
* @param bool $useCurrentUser If true, the current user will be used as the host |
| 50 |
* @return \FluentBooking\App\Models\Calendar|\WP_Error |
| 51 |
*/ |
| 52 |
public function importHostByJSONUrl($jsonUrl, $useCurrentUser = true) |
| 53 |
{ |
| 54 |
$response = wp_safe_remote_get($jsonUrl, [ |
| 55 |
'timeout' => 30, |
| 56 |
'headers' => [ |
| 57 |
'Accept' => 'application/json' |
| 58 |
] |
| 59 |
]); |
| 60 |
|
| 61 |
if (is_wp_error($response)) { |
| 62 |
return $response; |
| 63 |
} |
| 64 |
|
| 65 |
// check if the status code is not 200 |
| 66 |
if (wp_remote_retrieve_response_code($response) !== 200) { |
| 67 |
return new \WP_Error('invalid_response', 'Invalid response from the server'); |
| 68 |
} |
| 69 |
|
| 70 |
$body = json_decode(wp_remote_retrieve_body($response), true); |
| 71 |
|
| 72 |
return $this->importHostJson($body, $useCurrentUser); |
| 73 |
} |
| 74 |
} |
| 75 |
|