From fcb4b9d5cf256e542344d2c0b197ae02e4d94a12 Mon Sep 17 00:00:00 2001 From: alext Date: Fri, 15 Sep 2017 13:36:37 +0200 Subject: [PATCH] Autoformatted php files based on CodeIgniter style guide. --- src/application/controllers/Appointments.php | 1075 +++++++++-------- src/application/controllers/Backend.php | 117 +- src/application/controllers/Backend_api.php | 1019 +++++++++------- src/application/controllers/Captcha.php | 11 +- src/application/controllers/Errors.php | 44 +- src/application/controllers/Google.php | 118 +- src/application/controllers/Installation.php | 52 +- src/application/controllers/User.php | 91 +- src/application/controllers/api/index.html | 4 +- .../controllers/api/v1/API_V1_Controller.php | 60 +- src/application/controllers/api/v1/Admins.php | 117 +- .../controllers/api/v1/Appointments.php | 133 +- .../controllers/api/v1/Availabilities.php | 227 ++-- .../controllers/api/v1/Categories.php | 123 +- .../controllers/api/v1/Customers.php | 119 +- .../controllers/api/v1/Providers.php | 125 +- .../controllers/api/v1/Secretaries.php | 121 +- .../controllers/api/v1/Services.php | 121 +- .../controllers/api/v1/Settings.php | 107 +- .../controllers/api/v1/Unavailabilities.php | 133 +- src/application/controllers/api/v1/index.html | 4 +- src/application/controllers/index.html | 4 +- .../helpers/custom_exceptions_helper.php | 29 +- .../helpers/data_validation_helper.php | 8 +- src/application/helpers/general_helper.php | 40 +- .../helpers/google_analytics_helper.php | 11 +- src/application/helpers/index.html | 4 +- .../helpers/installation_helper.php | 30 +- src/application/language/bulgarian/index.html | 4 +- .../language/bulgarian/translations_lang.php | 2 +- src/application/language/chinese/index.html | 4 +- .../language/chinese/migration_lang.php | 16 +- .../language/chinese/translations_lang.php | 2 +- src/application/language/danish/index.html | 4 +- .../language/danish/migration_lang.php | 16 +- .../language/danish/translations_lang.php | 2 +- src/application/language/dutch/index.html | 4 +- .../language/dutch/migration_lang.php | 16 +- .../language/dutch/translations_lang.php | 528 ++++---- src/application/language/english/index.html | 4 +- .../language/english/translations_lang.php | 2 +- src/application/language/finnish/index.html | 4 +- .../language/finnish/migration_lang.php | 16 +- .../language/finnish/translations_lang.php | 2 +- src/application/language/french/index.html | 4 +- .../language/french/migration_lang.php | 16 +- .../language/french/translations_lang.php | 2 +- src/application/language/german/index.html | 4 +- .../language/german/migration_lang.php | 16 +- .../language/german/translations_lang.php | 2 +- src/application/language/greek/index.html | 4 +- .../language/greek/migration_lang.php | 16 +- .../language/greek/translations_lang.php | 2 +- src/application/language/hindi/index.html | 4 +- .../language/hindi/migration_lang.php | 16 +- .../language/hindi/translations_lang.php | 2 +- src/application/language/hungarian/index.html | 4 +- .../language/hungarian/migration_lang.php | 16 +- .../language/hungarian/translations_lang.php | 2 +- src/application/language/index.html | 4 +- src/application/language/italian/index.html | 4 +- .../language/italian/migration_lang.php | 14 +- .../language/italian/translations_lang.php | 2 +- src/application/language/japanese/index.html | 4 +- .../language/japanese/migration_lang.php | 16 +- .../language/japanese/translations_lang.php | 2 +- .../language/luxembourgish/index.html | 4 +- .../language/luxembourgish/migration_lang.php | 16 +- .../luxembourgish/translations_lang.php | 2 +- src/application/language/polish/index.html | 4 +- .../language/polish/migration_lang.php | 16 +- .../language/portuguese-br/index.html | 4 +- .../language/portuguese-br/migration_lang.php | 16 +- .../portuguese-br/translations_lang.php | 2 +- .../language/portuguese/index.html | 4 +- .../language/portuguese/migration_lang.php | 16 +- .../language/portuguese/translations_lang.php | 2 +- src/application/language/romanian/index.html | 4 +- .../language/romanian/migration_lang.php | 16 +- .../language/romanian/translations_lang.php | 2 +- src/application/language/russian/index.html | 4 +- .../language/russian/migration_lang.php | 16 +- .../language/russian/translations_lang.php | 2 +- src/application/language/slovak/index.html | 4 +- .../language/slovak/migration_lang.php | 16 +- .../language/slovak/translations_lang.php | 2 +- src/application/language/spanish/index.html | 4 +- .../language/spanish/migration_lang.php | 16 +- .../language/spanish/translations_lang.php | 40 +- src/application/language/turkish/index.html | 4 +- .../language/turkish/migration_lang.php | 16 +- .../language/turkish/translations_lang.php | 2 +- src/application/libraries/Google_sync.php | 112 +- .../migrations/001_specific_calendar_sync.php | 26 +- .../002_add_google_analytics_setting.php | 6 +- ...003_add_customer_notifications_setting.php | 6 +- .../004_add_date_format_setting.php | 6 +- .../005_add_require_captcha_setting.php | 6 +- .../006_add_calendar_view_setting.php | 14 +- .../007_add_service_availabilities_type.php | 14 +- .../008_add_service_attendants_number.php | 16 +- src/application/migrations/index.html | 4 +- src/application/models/Admins_model.php | 385 +++--- src/application/models/Appointments_model.php | 222 ++-- src/application/models/Customers_model.php | 196 +-- src/application/models/Providers_model.php | 317 +++-- src/application/models/Roles_model.php | 34 +- src/application/models/Secretaries_model.php | 282 +++-- src/application/models/Services_model.php | 251 ++-- src/application/models/Settings_model.php | 74 +- src/application/models/User_model.php | 84 +- src/application/models/index.html | 4 +- src/engine/Api/V1/Authorization.php | 29 +- src/engine/Api/V1/Exception.php | 30 +- src/engine/Api/V1/Parsers/Admins.php | 113 +- src/engine/Api/V1/Parsers/Appointments.php | 94 +- src/engine/Api/V1/Parsers/Categories.php | 49 +- src/engine/Api/V1/Parsers/Customers.php | 75 +- .../Api/V1/Parsers/ParsersInterface.php | 18 +- src/engine/Api/V1/Parsers/Providers.php | 156 ++- src/engine/Api/V1/Parsers/Secretaries.php | 118 +- src/engine/Api/V1/Parsers/Services.php | 81 +- src/engine/Api/V1/Parsers/Settings.php | 42 +- .../Api/V1/Parsers/Unavailabilities.php | 75 +- src/engine/Api/V1/Processors/Filter.php | 6 +- src/engine/Api/V1/Processors/Minimize.php | 49 +- src/engine/Api/V1/Processors/Paginate.php | 30 +- .../Api/V1/Processors/ProcessorsInterface.php | 2 +- src/engine/Api/V1/Processors/Search.php | 44 +- src/engine/Api/V1/Processors/Sort.php | 59 +- src/engine/Api/V1/Request.php | 19 +- src/engine/Api/V1/Response.php | 84 +- src/engine/Notifications/Email.php | 92 +- src/engine/Types/Boolean.php | 7 +- src/engine/Types/Decimal.php | 7 +- src/engine/Types/Email.php | 7 +- src/engine/Types/Integer.php | 9 +- src/engine/Types/NonEmptyText.php | 7 +- src/engine/Types/Text.php | 7 +- src/engine/Types/Type.php | 29 +- src/engine/Types/UnsignedInteger.php | 11 +- src/engine/Types/Url.php | 7 +- test/php/bootstrap.php | 2 +- test/php/engine/Api/V1/AuthorizationTest.php | 14 +- test/php/engine/Api/V1/FilterTest.php | 7 +- test/php/engine/Api/V1/MinimizeTest.php | 7 +- test/php/engine/Api/V1/PaginationTest.php | 7 +- test/php/engine/Api/V1/ResponseTest.php | 7 +- test/php/engine/Api/V1/SearchTest.php | 7 +- test/php/engine/Api/V1/SortTest.php | 7 +- test/php/engine/Api/V1/fixtures/admin.json | 4 +- .../engine/Api/V1/fixtures/appointment.json | 10 +- test/php/engine/Api/V1/fixtures/category.json | 4 +- test/php/engine/Api/V1/fixtures/customer.json | 12 +- test/php/engine/Api/V1/fixtures/provider.json | 44 +- .../php/engine/Api/V1/fixtures/secretary.json | 6 +- test/php/engine/Api/V1/fixtures/service.json | 8 +- .../Api/V1/fixtures/unavailability.json | 8 +- test/php/engine/Types/BooleanTest.php | 18 +- test/php/engine/Types/DecimalTest.php | 16 +- test/php/engine/Types/EmailTest.php | 21 +- test/php/engine/Types/IntegerTest.php | 17 +- test/php/engine/Types/NonEmptyTextTest.php | 19 +- test/php/engine/Types/TextTest.php | 16 +- test/php/engine/Types/UnsignedIntegerTest.php | 17 +- test/php/engine/Types/UrlTest.php | 21 +- test/php/phpunit.xml | 2 +- 167 files changed, 5063 insertions(+), 3716 deletions(-) diff --git a/src/application/controllers/Appointments.php b/src/application/controllers/Appointments.php index 493aa92d..f3dcaf48 100755 --- a/src/application/controllers/Appointments.php +++ b/src/application/controllers/Appointments.php @@ -1,4 +1,7 @@ -load->library('session'); + $this->load->library('session'); $this->load->helper('installation'); // Set user's selected language. - if ($this->session->userdata('language')) { - $this->config->set_item('language', $this->session->userdata('language')); - $this->lang->load('translations', $this->session->userdata('language')); - } else { - $this->lang->load('translations', $this->config->item('language')); // default - } + if ($this->session->userdata('language')) + { + $this->config->set_item('language', $this->session->userdata('language')); + $this->lang->load('translations', $this->session->userdata('language')); + } else + { + $this->lang->load('translations', $this->config->item('language')); // default + } - // Common helpers - $this->load->helper('google_analytics'); - } + // Common helpers + $this->load->helper('google_analytics'); + } /** * Default callback method of the application. @@ -51,8 +57,10 @@ class Appointments extends CI_Controller { * * @param string $appointment_hash DB appointment hash of an existing record (default ''). */ - public function index($appointment_hash = '') { - if (!is_ea_installed()) { + public function index($appointment_hash = '') + { + if ( ! is_ea_installed()) + { redirect('installation/index'); return; } @@ -63,39 +71,43 @@ class Appointments extends CI_Controller { $this->load->model('customers_model'); $this->load->model('settings_model'); - try { - $available_services = $this->services_model->get_available_services(); + try + { + $available_services = $this->services_model->get_available_services(); $available_providers = $this->providers_model->get_available_providers(); - $company_name = $this->settings_model->get_setting('company_name'); - $date_format = $this->settings_model->get_setting('date_format'); + $company_name = $this->settings_model->get_setting('company_name'); + $date_format = $this->settings_model->get_setting('date_format'); - // Remove the data that are not needed inside the $available_providers array. - foreach ($available_providers as $index=>$provider) { - $stripped_data = array( - 'id' => $provider['id'], - 'first_name' => $provider['first_name'], - 'last_name' => $provider['last_name'], - 'services' => $provider['services'] - ); - $available_providers[$index] = $stripped_data; - } + // Remove the data that are not needed inside the $available_providers array. + foreach ($available_providers as $index => $provider) + { + $stripped_data = [ + 'id' => $provider['id'], + 'first_name' => $provider['first_name'], + 'last_name' => $provider['last_name'], + 'services' => $provider['services'] + ]; + $available_providers[$index] = $stripped_data; + } // If an appointment hash is provided then it means that the customer // is trying to edit a registered appointment record. - if ($appointment_hash !== '') { + if ($appointment_hash !== '') + { // Load the appointments data and enable the manage mode of the page. $manage_mode = TRUE; - $results = $this->appointments_model->get_batch(array('hash' => $appointment_hash)); + $results = $this->appointments_model->get_batch(['hash' => $appointment_hash]); - if (count($results) === 0) { + if (count($results) === 0) + { // The requested appointment doesn't exist in the database. Display // a message to the customer. - $view = array( + $view = [ 'message_title' => $this->lang->line('appointment_not_found'), - 'message_text' => $this->lang->line('appointment_does_not_exist_in_db'), - 'message_icon' => base_url('assets/img/error.png') - ); + 'message_text' => $this->lang->line('appointment_does_not_exist_in_db'), + 'message_icon' => base_url('assets/img/error.png') + ]; $this->load->view('appointments/message', $view); return; } @@ -104,27 +116,29 @@ class Appointments extends CI_Controller { $provider = $this->providers_model->get_row($appointment['id_users_provider']); $customer = $this->customers_model->get_row($appointment['id_users_customer']); - } else { + } else + { // The customer is going to book a new appointment so there is no // need for the manage functionality to be initialized. $manage_mode = FALSE; - $appointment = array(); - $provider = array(); - $customer = array(); + $appointment = []; + $provider = []; + $customer = []; } // Load the book appointment view. - $view = array ( - 'available_services' => $available_services, - 'available_providers' => $available_providers, - 'company_name' => $company_name, - 'manage_mode' => $manage_mode, - 'date_format' => $date_format, - 'appointment_data' => $appointment, - 'provider_data' => $provider, - 'customer_data' => $customer - ); - } catch(Exception $exc) { + $view = [ + 'available_services' => $available_services, + 'available_providers' => $available_providers, + 'company_name' => $company_name, + 'manage_mode' => $manage_mode, + 'date_format' => $date_format, + 'appointment_data' => $appointment, + 'provider_data' => $provider, + 'customer_data' => $customer + ]; + } catch (Exception $exc) + { $view['exceptions'][] = $exc; } @@ -140,8 +154,10 @@ class Appointments extends CI_Controller { * * @param string $appointment_hash This is used to distinguish the appointment record. */ - public function cancel($appointment_hash) { - try { + public function cancel($appointment_hash) + { + try + { $this->load->model('appointments_model'); $this->load->model('providers_model'); $this->load->model('customers_model'); @@ -149,8 +165,9 @@ class Appointments extends CI_Controller { $this->load->model('settings_model'); // Check whether the appointment hash exists in the database. - $records = $this->appointments_model->get_batch(array('hash' => $appointment_hash)); - if (count($records) == 0) { + $records = $this->appointments_model->get_batch(['hash' => $appointment_hash]); + if (count($records) == 0) + { throw new Exception('No record matches the provided hash.'); } @@ -159,87 +176,100 @@ class Appointments extends CI_Controller { $customer = $this->customers_model->get_row($appointment['id_users_customer']); $service = $this->services_model->get_row($appointment['id_services']); - $company_settings = array( + $company_settings = [ 'company_name' => $this->settings_model->get_setting('company_name'), 'company_email' => $this->settings_model->get_setting('company_email'), 'company_link' => $this->settings_model->get_setting('company_link') - ); + ]; // :: DELETE APPOINTMENT RECORD FROM THE DATABASE. - if (!$this->appointments_model->delete($appointment['id'])) { + if ( ! $this->appointments_model->delete($appointment['id'])) + { throw new Exception('Appointment could not be deleted from the database.'); } // :: SYNC APPOINTMENT REMOVAL WITH GOOGLE CALENDAR - if ($appointment['id_google_calendar'] != NULL) { - try { + if ($appointment['id_google_calendar'] != NULL) + { + try + { $google_sync = filter_var($this->providers_model - ->get_setting('google_sync',$appointment['id_users_provider']), FILTER_VALIDATE_BOOLEAN); + ->get_setting('google_sync', $appointment['id_users_provider']), FILTER_VALIDATE_BOOLEAN); - if ($google_sync == TRUE) { + if ($google_sync == TRUE) + { $google_token = json_decode($this->providers_model - ->get_setting('google_token', $provider['id'])); + ->get_setting('google_token', $provider['id'])); $this->load->library('Google_sync'); $this->google_sync->refresh_token($google_token->refresh_token); $this->google_sync->delete_appointment($provider, $appointment['id_google_calendar']); } - } catch(Exception $exc) { + } catch (Exception $exc) + { $exceptions[] = $exc; } } // :: SEND NOTIFICATION EMAILS TO CUSTOMER AND PROVIDER - try { + try + { $this->config->load('email'); $email = new \EA\Engine\Notifications\Email($this, $this->config->config); $send_provider = filter_var($this->providers_model - ->get_setting('notifications', $provider['id']), FILTER_VALIDATE_BOOLEAN); + ->get_setting('notifications', $provider['id']), FILTER_VALIDATE_BOOLEAN); - if ($send_provider === TRUE) { + if ($send_provider === TRUE) + { $email->sendDeleteAppointment($appointment, $provider, - $service, $customer, $company_settings, new Email($provider['email']), - new Text($_POST['cancel_reason'])); + $service, $customer, $company_settings, new Email($provider['email']), + new Text($_POST['cancel_reason'])); } - $send_customer = filter_var($this->settings_model->get_setting('customer_notifications'), - FILTER_VALIDATE_BOOLEAN); + $send_customer = filter_var($this->settings_model->get_setting('customer_notifications'), + FILTER_VALIDATE_BOOLEAN); - if ($send_customer === TRUE) { - $email->sendDeleteAppointment($appointment, $provider, - $service, $customer, $company_settings, new Email($customer['email']), - new Text($_POST['cancel_reason'])); - } + if ($send_customer === TRUE) + { + $email->sendDeleteAppointment($appointment, $provider, + $service, $customer, $company_settings, new Email($customer['email']), + new Text($_POST['cancel_reason'])); + } - } catch(Exception $exc) { + } catch (Exception $exc) + { $exceptions[] = $exc; } - } catch(Exception $exc) { + } catch (Exception $exc) + { // Display the error message to the customer. $exceptions[] = $exc; } - $view = array( + $view = [ 'message_title' => $this->lang->line('appointment_cancelled_title'), 'message_text' => $this->lang->line('appointment_cancelled'), 'message_icon' => base_url('assets/img/success.png') - ); + ]; - if (isset($exceptions)) { + if (isset($exceptions)) + { $view['exceptions'] = $exceptions; } $this->load->view('appointments/message', $view); } - /** + /** * GET an specific appointment book and redirect to the success screen. * * @param int $appointment_id Contains the ID of the appointment to retrieve. */ - public function book_success($appointment_id) { + public function book_success($appointment_id) + { //if the appointment id doesn't exist or zero redirect to index - if(!$appointment_id){ + if ( ! $appointment_id) + { redirect('appointments'); } $this->load->model('appointments_model'); @@ -247,20 +277,21 @@ class Appointments extends CI_Controller { $this->load->model('services_model'); $this->load->model('settings_model'); //retrieve the data needed in the view - $appointment = $this->appointments_model->get_row($appointment_id); + $appointment = $this->appointments_model->get_row($appointment_id); $provider = $this->providers_model->get_row($appointment['id_users_provider']); $service = $this->services_model->get_row($appointment['id_services']); $company_name = $this->settings_model->get_setting('company_name'); //get the exceptions $exceptions = $this->session->flashdata('book_success'); - // :: LOAD THE BOOK SUCCESS VIEW - $view = array( - 'appointment_data' => $appointment, - 'provider_data' => $provider, - 'service_data' => $service, - 'company_name' => $company_name, - ); - if($exceptions){ + // :: LOAD THE BOOK SUCCESS VIEW + $view = [ + 'appointment_data' => $appointment, + 'provider_data' => $provider, + 'service_data' => $service, + 'company_name' => $company_name, + ]; + if ($exceptions) + { $view['exceptions'] = $exceptions; } $this->load->view('appointments/book_success', $view); @@ -283,56 +314,63 @@ class Appointments extends CI_Controller { * * Outputs a JSON string with the availabilities. */ - public function ajax_get_available_hours() { + public function ajax_get_available_hours() + { $this->load->model('providers_model'); $this->load->model('appointments_model'); $this->load->model('settings_model'); $this->load->model('services_model'); - try { - // Do not continue if there was no provider selected (more likely there is no provider in the system). - if (empty($_POST['provider_id'])) { - echo json_encode(array()); - return; - } + try + { + // Do not continue if there was no provider selected (more likely there is no provider in the system). + if (empty($_POST['provider_id'])) + { + echo json_encode([]); + return; + } // If manage mode is TRUE then the following we should not consider the selected // appointment when calculating the available time periods of the provider. $exclude_appointments = ($_POST['manage_mode'] === 'true') - ? array($_POST['appointment_id']) - : array(); + ? [$_POST['appointment_id']] + : []; - // If the user has selected the "any-provider" option then we will need to search - // for an available provider that will provide the requested service. - if ($_POST['provider_id'] === ANY_PROVIDER) { - $_POST['provider_id'] = $this->_search_any_provider($_POST['service_id'], $_POST['selected_date']); - if ($_POST['provider_id'] === NULL) { - echo json_encode(array()); - return; - } - } + // If the user has selected the "any-provider" option then we will need to search + // for an available provider that will provide the requested service. + if ($_POST['provider_id'] === ANY_PROVIDER) + { + $_POST['provider_id'] = $this->_search_any_provider($_POST['service_id'], $_POST['selected_date']); + if ($_POST['provider_id'] === NULL) + { + echo json_encode([]); + return; + } + } $availabilities_type = $this->services_model->get_value('availabilities_type', $_POST['service_id']); $attendants_number = $this->services_model->get_value('attendants_number', $_POST['service_id']); - $empty_periods = $this->_get_provider_available_time_periods($_POST['provider_id'], - $_POST['selected_date'], $exclude_appointments); + $empty_periods = $this->_get_provider_available_time_periods($_POST['provider_id'], + $_POST['selected_date'], $exclude_appointments); $available_hours = $this->_calculate_available_hours($empty_periods, $_POST['selected_date'], - $_POST['service_duration'], filter_var($_POST['manage_mode'], FILTER_VALIDATE_BOOLEAN), - $availabilities_type); + $_POST['service_duration'], filter_var($_POST['manage_mode'], FILTER_VALIDATE_BOOLEAN), + $availabilities_type); - if ($attendants_number > 1) { + if ($attendants_number > 1) + { $this->_get_multiple_attendants_hours($available_hours, $attendants_number, $_POST['service_id'], $_POST['selected_date']); } echo json_encode($available_hours); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -341,12 +379,14 @@ class Appointments extends CI_Controller { * * Outputs a JSON string with the appointment ID. */ - public function ajax_register_appointment() { - try { + public function ajax_register_appointment() + { + try + { $post_data = $_POST['post_data']; // alias - $post_data['manage_mode'] = filter_var($post_data['manage_mode'], FILTER_VALIDATE_BOOLEAN); + $post_data['manage_mode'] = filter_var($post_data['manage_mode'], FILTER_VALIDATE_BOOLEAN); - $this->load->model('appointments_model'); + $this->load->model('appointments_model'); $this->load->model('providers_model'); $this->load->model('services_model'); $this->load->model('customers_model'); @@ -354,503 +394,588 @@ class Appointments extends CI_Controller { // Validate the CAPTCHA string. if ($this->settings_model->get_setting('require_captcha') === '1' - && $this->session->userdata('captcha_phrase') !== $_POST['captcha']) { - echo json_encode(array( - 'captcha_verification' => FALSE, - 'expected_phrase' => $this->session->userdata('captcha_phrase') - )); - return; + && $this->session->userdata('captcha_phrase') !== $_POST['captcha']) + { + echo json_encode([ + 'captcha_verification' => FALSE, + 'expected_phrase' => $this->session->userdata('captcha_phrase') + ]); + return; } // Check appointment availability. - if (!$this->_check_datetime_availability()) { + if ( ! $this->_check_datetime_availability()) + { throw new Exception($this->lang->line('requested_hour_is_unavailable')); } $appointment = $_POST['post_data']['appointment']; $customer = $_POST['post_data']['customer']; - if ($this->customers_model->exists($customer)) { + if ($this->customers_model->exists($customer)) + { $customer['id'] = $this->customers_model->find_record_id($customer); - } + } $customer_id = $this->customers_model->add($customer); $appointment['id_users_customer'] = $customer_id; - $appointment['is_unavailable'] = (int)$appointment['is_unavailable']; // needs to be type casted + $appointment['is_unavailable'] = (int)$appointment['is_unavailable']; // needs to be type casted $appointment['id'] = $this->appointments_model->add($appointment); $appointment['hash'] = $this->appointments_model->get_value('hash', $appointment['id']); $provider = $this->providers_model->get_row($appointment['id_users_provider']); $service = $this->services_model->get_row($appointment['id_services']); - $company_settings = array( + $company_settings = [ 'company_name' => $this->settings_model->get_setting('company_name'), 'company_link' => $this->settings_model->get_setting('company_link'), 'company_email' => $this->settings_model->get_setting('company_email'), 'date_format' => $this->settings_model->get_setting('date_format') - ); + ]; // :: SYNCHRONIZE APPOINTMENT WITH PROVIDER'S GOOGLE CALENDAR // The provider must have previously granted access to his google calendar account // in order to sync the appointment. - try { + try + { $google_sync = filter_var($this->providers_model->get_setting('google_sync', - $appointment['id_users_provider']), FILTER_VALIDATE_BOOLEAN); + $appointment['id_users_provider']), FILTER_VALIDATE_BOOLEAN); - if ($google_sync == TRUE) { + if ($google_sync == TRUE) + { $google_token = json_decode($this->providers_model - ->get_setting('google_token', $appointment['id_users_provider'])); + ->get_setting('google_token', $appointment['id_users_provider'])); $this->load->library('google_sync'); $this->google_sync->refresh_token($google_token->refresh_token); - if ($post_data['manage_mode'] === FALSE) { + if ($post_data['manage_mode'] === FALSE) + { // Add appointment to Google Calendar. $google_event = $this->google_sync->add_appointment($appointment, $provider, - $service, $customer, $company_settings); + $service, $customer, $company_settings); $appointment['id_google_calendar'] = $google_event->id; $this->appointments_model->add($appointment); - } else { + } else + { // Update appointment to Google Calendar. $appointment['id_google_calendar'] = $this->appointments_model - ->get_value('id_google_calendar', $appointment['id']); + ->get_value('id_google_calendar', $appointment['id']); $this->google_sync->update_appointment($appointment, $provider, - $service, $customer, $company_settings); + $service, $customer, $company_settings); } } - } catch(Exception $exc) { + } catch (Exception $exc) + { log_message('error', $exc->getMessage()); log_message('error', $exc->getTraceAsString()); } // :: SEND NOTIFICATION EMAILS TO BOTH CUSTOMER AND PROVIDER - try { + try + { $this->config->load('email'); $email = new \EA\Engine\Notifications\Email($this, $this->config->config); - if ($post_data['manage_mode'] == FALSE) { + if ($post_data['manage_mode'] == FALSE) + { $customer_title = new Text($this->lang->line('appointment_booked')); $customer_message = new Text($this->lang->line('thank_you_for_appointment')); $provider_title = new Text($this->lang->line('appointment_added_to_your_plan')); $provider_message = new Text($this->lang->line('appointment_link_description')); - } else { + } else + { $customer_title = new Text($this->lang->line('appointment_changes_saved')); $customer_message = new Text(''); $provider_title = new Text($this->lang->line('appointment_details_changed')); $provider_message = new Text(''); } - $customer_link = new Url(site_url('appointments/index/' . $appointment['hash'])); - $provider_link = new Url(site_url('backend/index/' . $appointment['hash'])); + $customer_link = new Url(site_url('appointments/index/' . $appointment['hash'])); + $provider_link = new Url(site_url('backend/index/' . $appointment['hash'])); - $send_customer = filter_var($this->settings_model->get_setting('customer_notifications'), - FILTER_VALIDATE_BOOLEAN); + $send_customer = filter_var($this->settings_model->get_setting('customer_notifications'), + FILTER_VALIDATE_BOOLEAN); - if ($send_customer === TRUE) { - $email->sendAppointmentDetails($appointment, $provider, - $service, $customer,$company_settings, $customer_title, - $customer_message, $customer_link, new Email($customer['email'])); - } - - $send_provider = filter_var($this->providers_model ->get_setting('notifications', $provider['id']), - FILTER_VALIDATE_BOOLEAN); - - if ($send_provider === TRUE) { + if ($send_customer === TRUE) + { $email->sendAppointmentDetails($appointment, $provider, - $service, $customer, $company_settings, $provider_title, - $provider_message, $provider_link, new Email($provider['email'])); + $service, $customer, $company_settings, $customer_title, + $customer_message, $customer_link, new Email($customer['email'])); } - } catch(Exception $exc) { + + $send_provider = filter_var($this->providers_model->get_setting('notifications', $provider['id']), + FILTER_VALIDATE_BOOLEAN); + + if ($send_provider === TRUE) + { + $email->sendAppointmentDetails($appointment, $provider, + $service, $customer, $company_settings, $provider_title, + $provider_message, $provider_link, new Email($provider['email'])); + } + } catch (Exception $exc) + { log_message('error', $exc->getMessage()); log_message('error', $exc->getTraceAsString()); } - echo json_encode(array( - 'appointment_id' => $appointment['id'] - )); + echo json_encode([ + 'appointment_id' => $appointment['id'] + ]); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } /** - * [AJAX] Get Unavailable Dates - * - * Get an array with the available dates of a specific provider, service and month of the year. Provide the + * [AJAX] Get Unavailable Dates + * + * Get an array with the available dates of a specific provider, service and month of the year. Provide the * "provider_id", "service_id" and "selected_date" as GET parameters to the request. The "selected_date" parameter * must have the Y-m-d format. - * + * * Outputs a JSON string with the unavailable dates. that are unavailable. - */ - public function ajax_get_unavailable_dates() { - try { - $provider_id = $this->input->get('provider_id'); - $service_id = $this->input->get('service_id'); - $selected_date = new DateTime($this->input->get('selected_date')); - $number_of_days = (int)$selected_date->format('t'); - $unavailable_dates = array(); + */ + public function ajax_get_unavailable_dates() + { + try + { + $provider_id = $this->input->get('provider_id'); + $service_id = $this->input->get('service_id'); + $selected_date = new DateTime($this->input->get('selected_date')); + $number_of_days = (int)$selected_date->format('t'); + $unavailable_dates = []; - // Handle the "Any Provider" case. - if ($provider_id === ANY_PROVIDER) { - $provider_id = $this->_search_any_provider($service_id, $this->input->get('selected_date')); - if ($provider_id === NULL) { // No provider is available in the selected date. - for ($i=1; $i<=$number_of_days; $i++) { - $current_date = new DateTime($selected_date->format('Y-m') . '-' . $i); - $unavailable_dates[] = $current_date->format('Y-m-d'); - } - echo json_encode($unavailable_dates); - return; - } - } + // Handle the "Any Provider" case. + if ($provider_id === ANY_PROVIDER) + { + $provider_id = $this->_search_any_provider($service_id, $this->input->get('selected_date')); + if ($provider_id === NULL) + { // No provider is available in the selected date. + for ($i = 1; $i <= $number_of_days; $i++) + { + $current_date = new DateTime($selected_date->format('Y-m') . '-' . $i); + $unavailable_dates[] = $current_date->format('Y-m-d'); + } + echo json_encode($unavailable_dates); + return; + } + } - // Get the available time periods for every day of this month. - $this->load->model('services_model'); + // Get the available time periods for every day of this month. + $this->load->model('services_model'); $service_duration = (int)$this->services_model->get_value('duration', $service_id); - $availabilities_type = (int)$this->services_model->get_value('availabilities_type', $service_id); + $availabilities_type = (int)$this->services_model->get_value('availabilities_type', $service_id); - for ($i=1; $i<=$number_of_days; $i++) { - $current_date = new DateTime($selected_date->format('Y-m') . '-' . $i); + for ($i = 1; $i <= $number_of_days; $i++) + { + $current_date = new DateTime($selected_date->format('Y-m') . '-' . $i); - if ($current_date < new DateTime(date('Y-m-d 00:00:00'))) { // Past dates become immediately unavailable. - $unavailable_dates[] = $current_date->format('Y-m-d'); - continue; - } + if ($current_date < new DateTime(date('Y-m-d 00:00:00'))) + { // Past dates become immediately unavailable. + $unavailable_dates[] = $current_date->format('Y-m-d'); + continue; + } - $empty_periods = $this->_get_provider_available_time_periods($provider_id, - $current_date->format('Y-m-d')); + $empty_periods = $this->_get_provider_available_time_periods($provider_id, + $current_date->format('Y-m-d')); - $available_hours = $this->_calculate_available_hours($empty_periods, $current_date->format('Y-m-d'), - $service_duration, false, $availabilities_type); + $available_hours = $this->_calculate_available_hours($empty_periods, $current_date->format('Y-m-d'), + $service_duration, FALSE, $availabilities_type); - if (empty($available_hours)) { - $unavailable_dates[] = $current_date->format('Y-m-d'); - } - } + if (empty($available_hours)) + { + $unavailable_dates[] = $current_date->format('Y-m-d'); + } + } - echo json_encode($unavailable_dates); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + echo json_encode($unavailable_dates); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } - } + } - /** - * Check whether the provider is still available in the selected appointment date. - * - * It might be times where two or more customers select the same appointment date and time. This shouldn't be + /** + * Check whether the provider is still available in the selected appointment date. + * + * It might be times where two or more customers select the same appointment date and time. This shouldn't be * allowed to happen, so one of the two customers will eventually get the preferred date and the other one will have * to choose for another date. Use this method just before the customer confirms the appointment details. If the * selected date was taken in the mean time, the customer must be prompted to select another time for his * appointment. * - * @return bool Returns whether the selected datetime is still available. - */ - protected function _check_datetime_availability() { - $this->load->model('services_model'); - $this->load->model('appointments_model'); + * @return bool Returns whether the selected datetime is still available. + */ + protected function _check_datetime_availability() + { + $this->load->model('services_model'); + $this->load->model('appointments_model'); - $appointment = $_POST['post_data']['appointment']; + $appointment = $_POST['post_data']['appointment']; - $service_duration = $this->services_model->get_value('duration', $appointment['id_services']); + $service_duration = $this->services_model->get_value('duration', $appointment['id_services']); - $exclude_appointments = (isset($appointment['id'])) ? array($appointment['id']) : array(); + $exclude_appointments = (isset($appointment['id'])) ? [$appointment['id']] : []; $attendants_number = $this->services_model->get_value('attendants_number', $appointment['id_services']); - if ($attendants_number > 1) { + if ($attendants_number > 1) + { // Exclude all the appointments that will are currently registered. $exclude = $this->appointments_model->get_batch([ 'id_services' => $appointment['id_services'], 'start_datetime' => $appointment['start_datetime'] ]); - if (!empty($exclude) && count($exclude) < $attendants_number) { - foreach ($exclude as $entry) { + if ( ! empty($exclude) && count($exclude) < $attendants_number) + { + foreach ($exclude as $entry) + { $exclude_appointments[] = $entry['id']; } } } - if ($appointment['id_users_provider'] === ANY_PROVIDER) { - $appointment['id_users_provider'] = $this->_search_any_provider($appointment['id_services'], - date('Y-m-d', strtotime($appointment['start_datetime']))); - $_POST['post_data']['appointment']['id_users_provider'] = $appointment['id_users_provider']; - return TRUE; // The selected provider is always available. - } + if ($appointment['id_users_provider'] === ANY_PROVIDER) + { + $appointment['id_users_provider'] = $this->_search_any_provider($appointment['id_services'], + date('Y-m-d', strtotime($appointment['start_datetime']))); + $_POST['post_data']['appointment']['id_users_provider'] = $appointment['id_users_provider']; + return TRUE; // The selected provider is always available. + } - $available_periods = $this->_get_provider_available_time_periods( - $appointment['id_users_provider'], date('Y-m-d', strtotime($appointment['start_datetime'])), - $exclude_appointments); + $available_periods = $this->_get_provider_available_time_periods( + $appointment['id_users_provider'], date('Y-m-d', strtotime($appointment['start_datetime'])), + $exclude_appointments); - $is_still_available = FALSE; + $is_still_available = FALSE; - foreach($available_periods as $period) { - $appt_start = new DateTime($appointment['start_datetime']); - $appt_start = $appt_start->format('H:i'); + foreach ($available_periods as $period) + { + $appt_start = new DateTime($appointment['start_datetime']); + $appt_start = $appt_start->format('H:i'); - $appt_end = new DateTime($appointment['start_datetime']); - $appt_end->add(new DateInterval('PT' . $service_duration . 'M')); - $appt_end = $appt_end->format('H:i'); + $appt_end = new DateTime($appointment['start_datetime']); + $appt_end->add(new DateInterval('PT' . $service_duration . 'M')); + $appt_end = $appt_end->format('H:i'); - $period_start = date('H:i', strtotime($period['start'])); - $period_end = date('H:i', strtotime($period['end'])); + $period_start = date('H:i', strtotime($period['start'])); + $period_end = date('H:i', strtotime($period['end'])); - if ($period_start <= $appt_start && $period_end >= $appt_end) { - $is_still_available = TRUE; - break; - } - } + if ($period_start <= $appt_start && $period_end >= $appt_end) + { + $is_still_available = TRUE; + break; + } + } - return $is_still_available; - } + return $is_still_available; + } - /** - * Get an array containing the free time periods (start - end) of a selected date. - * - * This method is very important because there are many cases where the system needs to know when a provider is + /** + * Get an array containing the free time periods (start - end) of a selected date. + * + * This method is very important because there are many cases where the system needs to know when a provider is * available for an appointment. This method will return an array that belongs to the selected date and contains * values that have the start and the end time of an available time period. - * - * @param int $provider_id Provider record ID. - * @param string $selected_date Date to be checked (MySQL formatted string). - * @param array $exclude_appointments Array containing the IDs of the appointments that will not be taken into + * + * @param int $provider_id Provider record ID. + * @param string $selected_date Date to be checked (MySQL formatted string). + * @param array $exclude_appointments Array containing the IDs of the appointments that will not be taken into * consideration when the available time periods are calculated. - * - * @return array Returns an array with the available time periods of the provider. - */ - protected function _get_provider_available_time_periods($provider_id, $selected_date, - $exclude_appointments = array()) { - $this->load->model('appointments_model'); - $this->load->model('providers_model'); + * + * @return array Returns an array with the available time periods of the provider. + */ + protected function _get_provider_available_time_periods( + $provider_id, + $selected_date, + $exclude_appointments = [] + ) { + $this->load->model('appointments_model'); + $this->load->model('providers_model'); - // Get the provider's working plan and reserved appointments. - $working_plan = json_decode($this->providers_model->get_setting('working_plan', $provider_id), TRUE); + // Get the provider's working plan and reserved appointments. + $working_plan = json_decode($this->providers_model->get_setting('working_plan', $provider_id), TRUE); - $where_clause = array( - 'id_users_provider' => $provider_id - ); + $where_clause = [ + 'id_users_provider' => $provider_id + ]; - $reserved_appointments = $this->appointments_model->get_batch($where_clause); + $reserved_appointments = $this->appointments_model->get_batch($where_clause); - // Sometimes it might be necessary to not take into account some appointment records - // in order to display what the providers' available time periods would be without them. - foreach ($exclude_appointments as $excluded_id) { - foreach ($reserved_appointments as $index => $reserved) { - if ($reserved['id'] == $excluded_id) { - unset($reserved_appointments[$index]); - } - } - } + // Sometimes it might be necessary to not take into account some appointment records + // in order to display what the providers' available time periods would be without them. + foreach ($exclude_appointments as $excluded_id) + { + foreach ($reserved_appointments as $index => $reserved) + { + if ($reserved['id'] == $excluded_id) + { + unset($reserved_appointments[$index]); + } + } + } - // Find the empty spaces on the plan. The first split between the plan is due to - // a break (if exist). After that every reserved appointment is considered to be - // a taken space in the plan. - $selected_date_working_plan = $working_plan[strtolower(date('l', strtotime($selected_date)))]; - $available_periods_with_breaks = array(); + // Find the empty spaces on the plan. The first split between the plan is due to + // a break (if exist). After that every reserved appointment is considered to be + // a taken space in the plan. + $selected_date_working_plan = $working_plan[strtolower(date('l', strtotime($selected_date)))]; + $available_periods_with_breaks = []; - if (isset($selected_date_working_plan['breaks'])) { - $start = new DateTime($selected_date_working_plan['start']); - $end = new DateTime($selected_date_working_plan['end']); - $available_periods_with_breaks[] = array( - 'start' => $selected_date_working_plan['start'], - 'end' => $selected_date_working_plan['end'] - ); + if (isset($selected_date_working_plan['breaks'])) + { + $start = new DateTime($selected_date_working_plan['start']); + $end = new DateTime($selected_date_working_plan['end']); + $available_periods_with_breaks[] = [ + 'start' => $selected_date_working_plan['start'], + 'end' => $selected_date_working_plan['end'] + ]; - // Split the working plan to available time periods that do not contain the breaks in them. - foreach ($selected_date_working_plan['breaks'] as $index => $break) { - $break_start = new DateTime($break['start']); - $break_end = new DateTime($break['end']); + // Split the working plan to available time periods that do not contain the breaks in them. + foreach ($selected_date_working_plan['breaks'] as $index => $break) + { + $break_start = new DateTime($break['start']); + $break_end = new DateTime($break['end']); - if ($break_start < $start) { - $break_start = $start; - } + if ($break_start < $start) + { + $break_start = $start; + } - if ($break_end > $end) { - $break_end = $end; - } + if ($break_end > $end) + { + $break_end = $end; + } - if ($break_start >= $break_end) { - continue; - } + if ($break_start >= $break_end) + { + continue; + } - foreach ($available_periods_with_breaks as $key => $open_period) { - $s = new DateTime($open_period['start']); - $e = new DateTime($open_period['end']); + foreach ($available_periods_with_breaks as $key => $open_period) + { + $s = new DateTime($open_period['start']); + $e = new DateTime($open_period['end']); - if ($s < $break_end && $break_start < $e) { // check for overlap - $changed = FALSE; - if ($s < $break_start) { - $open_start = $s; - $open_end = $break_start; - $available_periods_with_breaks[] = array( - 'start' => $open_start->format("H:i"), - 'end' => $open_end->format("H:i") - ); - $changed = TRUE; - } + if ($s < $break_end && $break_start < $e) + { // check for overlap + $changed = FALSE; + if ($s < $break_start) + { + $open_start = $s; + $open_end = $break_start; + $available_periods_with_breaks[] = [ + 'start' => $open_start->format("H:i"), + 'end' => $open_end->format("H:i") + ]; + $changed = TRUE; + } - if ($break_end < $e) { - $open_start = $break_end; - $open_end = $e; - $available_periods_with_breaks[] = array( - 'start' => $open_start->format("H:i"), - 'end' => $open_end->format("H:i") - ); - $changed = TRUE; - } + if ($break_end < $e) + { + $open_start = $break_end; + $open_end = $e; + $available_periods_with_breaks[] = [ + 'start' => $open_start->format("H:i"), + 'end' => $open_end->format("H:i") + ]; + $changed = TRUE; + } - if ($changed) { - unset($available_periods_with_breaks[$key]); - } - } - } - } - } + if ($changed) + { + unset($available_periods_with_breaks[$key]); + } + } + } + } + } - // Break the empty periods with the reserved appointments. - $available_periods_with_appointments = $available_periods_with_breaks; + // Break the empty periods with the reserved appointments. + $available_periods_with_appointments = $available_periods_with_breaks; - foreach($reserved_appointments as $appointment) { - foreach($available_periods_with_appointments as $index => &$period) { - $a_start = strtotime($appointment['start_datetime']); - $a_end = strtotime($appointment['end_datetime']); - $p_start = strtotime($selected_date . ' ' . $period['start']); - $p_end = strtotime($selected_date . ' ' .$period['end']); + foreach ($reserved_appointments as $appointment) + { + foreach ($available_periods_with_appointments as $index => &$period) + { + $a_start = strtotime($appointment['start_datetime']); + $a_end = strtotime($appointment['end_datetime']); + $p_start = strtotime($selected_date . ' ' . $period['start']); + $p_end = strtotime($selected_date . ' ' . $period['end']); - if ($a_start <= $p_start && $a_end <= $p_end && $a_end <= $p_start) { - // The appointment does not belong in this time period, so we - // will not change anything. - } else if ($a_start <= $p_start && $a_end <= $p_end && $a_end >= $p_start) { - // The appointment starts before the period and finishes somewhere inside. - // We will need to break this period and leave the available part. - $period['start'] = date('H:i', $a_end); - } else if ($a_start >= $p_start && $a_end <= $p_end) { - // The appointment is inside the time period, so we will split the period - // into two new others. - unset($available_periods_with_appointments[$index]); - $available_periods_with_appointments[] = array( - 'start' => date('H:i', $p_start), - 'end' => date('H:i', $a_start) - ); - $available_periods_with_appointments[] = array( - 'start' => date('H:i', $a_end), - 'end' => date('H:i', $p_end) - ); - } else if ($a_start >= $p_start && $a_end >= $p_start && $a_start <= $p_end) { - // The appointment starts in the period and finishes out of it. We will - // need to remove the time that is taken from the appointment. - $period['end'] = date('H:i', $a_start); - } else if ($a_start >= $p_start && $a_end >= $p_end && $a_start >= $p_end) { - // The appointment does not belong in the period so do not change anything. - } else if ($a_start <= $p_start && $a_end >= $p_end && $a_start <= $p_end) { - // The appointment is bigger than the period, so this period needs to be removed. - unset($available_periods_with_appointments[$index]); - } - } - } + if ($a_start <= $p_start && $a_end <= $p_end && $a_end <= $p_start) + { + // The appointment does not belong in this time period, so we + // will not change anything. + } else + { + if ($a_start <= $p_start && $a_end <= $p_end && $a_end >= $p_start) + { + // The appointment starts before the period and finishes somewhere inside. + // We will need to break this period and leave the available part. + $period['start'] = date('H:i', $a_end); + } else + { + if ($a_start >= $p_start && $a_end <= $p_end) + { + // The appointment is inside the time period, so we will split the period + // into two new others. + unset($available_periods_with_appointments[$index]); + $available_periods_with_appointments[] = [ + 'start' => date('H:i', $p_start), + 'end' => date('H:i', $a_start) + ]; + $available_periods_with_appointments[] = [ + 'start' => date('H:i', $a_end), + 'end' => date('H:i', $p_end) + ]; + } else + { + if ($a_start >= $p_start && $a_end >= $p_start && $a_start <= $p_end) + { + // The appointment starts in the period and finishes out of it. We will + // need to remove the time that is taken from the appointment. + $period['end'] = date('H:i', $a_start); + } else + { + if ($a_start >= $p_start && $a_end >= $p_end && $a_start >= $p_end) + { + // The appointment does not belong in the period so do not change anything. + } else + { + if ($a_start <= $p_start && $a_end >= $p_end && $a_start <= $p_end) + { + // The appointment is bigger than the period, so this period needs to be removed. + unset($available_periods_with_appointments[$index]); + } + } + } + } + } + } + } + } - return array_values($available_periods_with_appointments); - } + return array_values($available_periods_with_appointments); + } - /** - * Search for any provider that can handle the requested service. - * - * This method will return the database ID of the provider with the most available periods. - * - * @param int $service_id The requested service ID. - * @param string $selected_date The date to be searched. - * - * @return int Returns the ID of the provider that can provide the service at the selected date. - */ - protected function _search_any_provider($service_id, $selected_date) { - $this->load->model('providers_model'); - $this->load->model('services_model'); - $available_providers = $this->providers_model->get_available_providers(); - $service = $this->services_model->get_row($service_id); - $provider_id = NULL; - $max_hours_count = 0; + /** + * Search for any provider that can handle the requested service. + * + * This method will return the database ID of the provider with the most available periods. + * + * @param int $service_id The requested service ID. + * @param string $selected_date The date to be searched. + * + * @return int Returns the ID of the provider that can provide the service at the selected date. + */ + protected function _search_any_provider($service_id, $selected_date) + { + $this->load->model('providers_model'); + $this->load->model('services_model'); + $available_providers = $this->providers_model->get_available_providers(); + $service = $this->services_model->get_row($service_id); + $provider_id = NULL; + $max_hours_count = 0; - foreach($available_providers as $provider) { - foreach($provider['services'] as $provider_service_id) { - if ($provider_service_id == $service_id) { // Check if the provider is available for the requested date. - $empty_periods = $this->_get_provider_available_time_periods($provider['id'], $selected_date); - $available_hours = $this->_calculate_available_hours($empty_periods, $selected_date, - $service['duration'], false, $service['availabilities_type']); - if (count($available_hours) > $max_hours_count) { - $provider_id = $provider['id']; - $max_hours_count = count($available_hours); - } - } - } - } + foreach ($available_providers as $provider) + { + foreach ($provider['services'] as $provider_service_id) + { + if ($provider_service_id == $service_id) + { // Check if the provider is available for the requested date. + $empty_periods = $this->_get_provider_available_time_periods($provider['id'], $selected_date); + $available_hours = $this->_calculate_available_hours($empty_periods, $selected_date, + $service['duration'], FALSE, $service['availabilities_type']); + if (count($available_hours) > $max_hours_count) + { + $provider_id = $provider['id']; + $max_hours_count = count($available_hours); + } + } + } + } - return $provider_id; - } + return $provider_id; + } - /** - * Calculate the available appointment hours. - * - * Calculate the available appointment hours for the given date. The empty spaces - * are broken down to 15 min and if the service fit in each quarter then a new - * available hour is added to the "$available_hours" array. - * - * @param array $empty_periods Contains the empty periods as generated by the "_get_provider_available_time_periods" + /** + * Calculate the available appointment hours. + * + * Calculate the available appointment hours for the given date. The empty spaces + * are broken down to 15 min and if the service fit in each quarter then a new + * available hour is added to the "$available_hours" array. + * + * @param array $empty_periods Contains the empty periods as generated by the "_get_provider_available_time_periods" * method. - * @param string $selected_date The selected date to be search (format ) - * @param int $service_duration The service duration is required for the hour calculation. - * @param bool $manage_mode (optional) Whether we are currently on manage mode (editing an existing appointment). + * @param string $selected_date The selected date to be search (format ) + * @param int $service_duration The service duration is required for the hour calculation. + * @param bool $manage_mode (optional) Whether we are currently on manage mode (editing an existing appointment). * @param string $availabilities_type Optional ('flexible'), the service availabilities type. - * - * @return array Returns an array with the available hours for the appointment. - */ - protected function _calculate_available_hours(array $empty_periods, $selected_date, $service_duration, - $manage_mode = FALSE, $availabilities_type = 'flexible') { - $this->load->model('settings_model'); + * + * @return array Returns an array with the available hours for the appointment. + */ + protected function _calculate_available_hours( + array $empty_periods, + $selected_date, + $service_duration, + $manage_mode = FALSE, + $availabilities_type = 'flexible' + ) { + $this->load->model('settings_model'); - $available_hours = array(); + $available_hours = []; - foreach ($empty_periods as $period) { - $start_hour = new DateTime($selected_date . ' ' . $period['start']); - $end_hour = new DateTime($selected_date . ' ' . $period['end']); + foreach ($empty_periods as $period) + { + $start_hour = new DateTime($selected_date . ' ' . $period['start']); + $end_hour = new DateTime($selected_date . ' ' . $period['end']); $interval = $availabilities_type === AVAILABILITIES_TYPE_FIXED ? (int)$service_duration : 15; - $current_hour = $start_hour; - $diff = $current_hour->diff($end_hour); + $current_hour = $start_hour; + $diff = $current_hour->diff($end_hour); - while (($diff->h * 60 + $diff->i) >= intval($service_duration)) { - $available_hours[] = $current_hour->format('H:i'); - $current_hour->add(new DateInterval('PT' . $interval . 'M')); - $diff = $current_hour->diff($end_hour); - } - } + while (($diff->h * 60 + $diff->i) >= intval($service_duration)) + { + $available_hours[] = $current_hour->format('H:i'); + $current_hour->add(new DateInterval('PT' . $interval . 'M')); + $diff = $current_hour->diff($end_hour); + } + } - // If the selected date is today, remove past hours. It is important include the timeout before - // booking that is set in the back-office the system. Normally we might want the customer to book - // an appointment that is at least half or one hour from now. The setting is stored in minutes. - if (date('m/d/Y', strtotime($selected_date)) === date('m/d/Y')) { - $book_advance_timeout = $this->settings_model->get_setting('book_advance_timeout'); + // If the selected date is today, remove past hours. It is important include the timeout before + // booking that is set in the back-office the system. Normally we might want the customer to book + // an appointment that is at least half or one hour from now. The setting is stored in minutes. + if (date('m/d/Y', strtotime($selected_date)) === date('m/d/Y')) + { + $book_advance_timeout = $this->settings_model->get_setting('book_advance_timeout'); - foreach($available_hours as $index => $value) { - $available_hour = strtotime($value); - $current_hour = strtotime('+' . $book_advance_timeout . ' minutes', strtotime('now')); - if ($available_hour <= $current_hour) { - unset($available_hours[$index]); - } - } - } + foreach ($available_hours as $index => $value) + { + $available_hour = strtotime($value); + $current_hour = strtotime('+' . $book_advance_timeout . ' minutes', strtotime('now')); + if ($available_hour <= $current_hour) + { + unset($available_hours[$index]); + } + } + } - $available_hours = array_values($available_hours); - sort($available_hours, SORT_STRING ); - $available_hours = array_values($available_hours); + $available_hours = array_values($available_hours); + sort($available_hours, SORT_STRING); + $available_hours = array_values($available_hours); - return $available_hours; - } + return $available_hours; + } /** * Get multiple attendants hours. @@ -862,25 +987,31 @@ class Appointments extends CI_Controller { * @param int $service_id Selected service ID. * @param string $selected_date The selected appointment date. */ - protected function _get_multiple_attendants_hours(&$available_hours, $attendants_number, $service_id, - $selected_date) { + protected function _get_multiple_attendants_hours( + &$available_hours, + $attendants_number, + $service_id, + $selected_date + ) { $this->load->model('appointments_model'); $appointments = $this->appointments_model->get_batch( 'id_services = ' . $this->db->escape($service_id) . ' AND DATE(start_datetime) = DATE(' . $this->db->escape(date('Y-m-d', strtotime($selected_date))) . ')'); - foreach($appointments as $appointment) { + foreach ($appointments as $appointment) + { $hour = date('H:i', strtotime($appointment['start_datetime'])); $current_attendants_number = $this->appointments_model->appointment_count_for_hour($service_id, - $selected_date, $hour); - if ($current_attendants_number < $attendants_number && !in_array($hour, $available_hours)) { + $selected_date, $hour); + if ($current_attendants_number < $attendants_number && ! in_array($hour, $available_hours)) + { $available_hours[] = $hour; } } $available_hours = array_values($available_hours); - sort($available_hours, SORT_STRING ); - $available_hours = array_values($available_hours); + sort($available_hours, SORT_STRING); + $available_hours = array_values($available_hours); } } diff --git a/src/application/controllers/Backend.php b/src/application/controllers/Backend.php index a501f48a..1d8fa989 100644 --- a/src/application/controllers/Backend.php +++ b/src/application/controllers/Backend.php @@ -1,4 +1,7 @@ -load->library('session'); - // Set user's selected language. - if ($this->session->userdata('language')) { - $this->config->set_item('language', $this->session->userdata('language')); - $this->lang->load('translations', $this->session->userdata('language')); - } else { - $this->lang->load('translations', $this->config->item('language')); // default + // Set user's selected language. + if ($this->session->userdata('language')) + { + $this->config->set_item('language', $this->session->userdata('language')); + $this->lang->load('translations', $this->session->userdata('language')); + } else + { + $this->lang->load('translations', $this->config->item('language')); // default } } @@ -42,10 +48,12 @@ class Backend extends CI_Controller { * * @param string $appointment_hash Appointment edit dialog will appear when the page loads (default ''). */ - public function index($appointment_hash = '') { + public function index($appointment_hash = '') + { $this->session->set_userdata('dest_url', site_url('backend')); - if (!$this->_has_privileges(PRIV_APPOINTMENTS)) { + if ( ! $this->_has_privileges(PRIV_APPOINTMENTS)) + { return; } @@ -71,20 +79,24 @@ class Backend extends CI_Controller { $view['calendar_view'] = $user['settings']['calendar_view']; $this->set_user_data($view); - if ($this->session->userdata('role_slug') === DB_SLUG_SECRETARY) { + if ($this->session->userdata('role_slug') === DB_SLUG_SECRETARY) + { $secretary = $this->secretaries_model->get_row($this->session->userdata('user_id')); $view['secretary_providers'] = $secretary['providers']; - } else { - $view['secretary_providers'] = array(); + } else + { + $view['secretary_providers'] = []; } - $results = $this->appointments_model->get_batch(array('hash' => $appointment_hash)); + $results = $this->appointments_model->get_batch(['hash' => $appointment_hash]); - if ($appointment_hash !== '' && count($results) > 0) { + if ($appointment_hash !== '' && count($results) > 0) + { $appointment = $results[0]; $appointment['customer'] = $this->customers_model->get_row($appointment['id_users_customer']); $view['edit_appointment'] = $appointment; // This will display the appointment edit dialog on page load. - } else { + } else + { $view['edit_appointment'] = NULL; } @@ -98,12 +110,14 @@ class Backend extends CI_Controller { * * In this page the user can manage all the customer records of the system. */ - public function customers() { + public function customers() + { $this->session->set_userdata('dest_url', site_url('backend/customers')); - if (!$this->_has_privileges(PRIV_CUSTOMERS)) { - return; - } + if ( ! $this->_has_privileges(PRIV_CUSTOMERS)) + { + return; + } $this->load->model('providers_model'); $this->load->model('customers_model'); @@ -134,10 +148,12 @@ class Backend extends CI_Controller { * * NOTICE: The services that each provider is able to service is managed from the backend services page. */ - public function services() { + public function services() + { $this->session->set_userdata('dest_url', site_url('backend/services')); - if (!$this->_has_privileges(PRIV_SERVICES)) { + if ( ! $this->_has_privileges(PRIV_SERVICES)) + { return; } @@ -166,10 +182,12 @@ class Backend extends CI_Controller { * In this page the admin user will be able to manage the system users. By this, we mean the provider, secretary and * admin users. This is also the page where the admin defines which service can each provider provide. */ - public function users() { + public function users() + { $this->session->set_userdata('dest_url', site_url('backend/users')); - if (!$this->_has_privileges(PRIV_USERS)) { + if ( ! $this->_has_privileges(PRIV_USERS)) + { return; } @@ -204,10 +222,12 @@ class Backend extends CI_Controller { * be able to make change to the current Easy!Appointment installation (core settings like company name, book * timeout etc). */ - public function settings() { + public function settings() + { $this->session->set_userdata('dest_url', site_url('backend/settings')); - if (!$this->_has_privileges(PRIV_SYSTEM_SETTINGS, FALSE) - && !$this->_has_privileges(PRIV_USER_SETTINGS)) { + if ( ! $this->_has_privileges(PRIV_SYSTEM_SETTINGS, FALSE) + && ! $this->_has_privileges(PRIV_USER_SETTINGS)) + { return; } @@ -250,11 +270,14 @@ class Backend extends CI_Controller { * logged in then he will be prompted to log in. If he hasn't the required privileges then an info message will be * displayed. */ - protected function _has_privileges($page, $redirect = TRUE) { + protected function _has_privileges($page, $redirect = TRUE) + { // Check if user is logged in. $user_id = $this->session->userdata('user_id'); - if ($user_id == FALSE) { // User not logged in, display the login view. - if ($redirect) { + if ($user_id == FALSE) + { // User not logged in, display the login view. + if ($redirect) + { header('Location: ' . site_url('user/login')); } return FALSE; @@ -262,9 +285,11 @@ class Backend extends CI_Controller { // Check if the user has the required privileges for viewing the selected page. $role_slug = $this->session->userdata('role_slug'); - $role_priv = $this->db->get_where('ea_roles', array('slug' => $role_slug))->row_array(); - if ($role_priv[$page] < PRIV_VIEW) { // User does not have the permission to view the page. - if ($redirect) { + $role_priv = $this->db->get_where('ea_roles', ['slug' => $role_slug])->row_array(); + if ($role_priv[$page] < PRIV_VIEW) + { // User does not have the permission to view the page. + if ($redirect) + { header('Location: ' . site_url('user/no_privileges')); } return FALSE; @@ -282,22 +307,29 @@ class Backend extends CI_Controller { * This method can be used either by loading the page in the browser or by an ajax request. But it will answer with * JSON encoded data. */ - public function update() { - try { - if (!$this->_has_privileges(PRIV_SYSTEM_SETTINGS, TRUE)) + public function update() + { + try + { + if ( ! $this->_has_privileges(PRIV_SYSTEM_SETTINGS, TRUE)) + { throw new Exception('You do not have the required privileges for this task!'); + } $this->load->library('migration'); - if (!$this->migration->current()) + if ( ! $this->migration->current()) + { throw new Exception($this->migration->error_string()); + } echo json_encode(AJAX_SUCCESS); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -306,7 +338,8 @@ class Backend extends CI_Controller { * * @param array $view Contains the view data. */ - protected function set_user_data(&$view) { + protected function set_user_data(&$view) + { $this->load->model('roles_model'); // Get privileges diff --git a/src/application/controllers/Backend_api.php b/src/application/controllers/Backend_api.php index 1b005152..afa9c200 100644 --- a/src/application/controllers/Backend_api.php +++ b/src/application/controllers/Backend_api.php @@ -1,4 +1,7 @@ -security->csrf_show_error(); } $this->load->library('session'); $this->load->model('roles_model'); - if ($this->session->userdata('role_slug')) { + if ($this->session->userdata('role_slug')) + { $this->privileges = $this->roles_model->get_privileges($this->session->userdata('role_slug')); } // Set user's selected language. - if ($this->session->userdata('language')) { - $this->config->set_item('language', $this->session->userdata('language')); - $this->lang->load('translations', $this->session->userdata('language')); - } else { - $this->lang->load('translations', $this->config->item('language')); // default + if ($this->session->userdata('language')) + { + $this->config->set_item('language', $this->session->userdata('language')); + $this->lang->load('translations', $this->session->userdata('language')); + } else + { + $this->lang->load('translations', $this->config->item('language')); // default } } /** - * Get Calendar Events + * Get Calendar Events * * This method will return all the calendar events within a specified period. */ - public function ajax_get_calendar_events() { - try { + public function ajax_get_calendar_events() + { + try + { $this->output->set_content_type('application/json'); $this->load->model('appointments_model'); $this->load->model('customers_model'); @@ -73,18 +83,19 @@ class Backend_api extends CI_Controller { $response = [ 'appointments' => $this->appointments_model->get_batch([ - 'is_unavailable' => false, + 'is_unavailable' => FALSE, 'start_datetime >=' => $startDate, 'end_datetime <=' => $endDate ]), 'unavailabilities' => $this->appointments_model->get_batch([ - 'is_unavailable' => true, + 'is_unavailable' => TRUE, 'start_datetime >=' => $startDate, 'end_datetime <=' => $endDate ]) ]; - foreach($response['appointments'] as &$appointment) { + foreach ($response['appointments'] as &$appointment) + { $appointment['provider'] = $this->providers_model->get_row($appointment['id_users_provider']); $appointment['service'] = $this->services_model->get_row($appointment['id_services']); $appointment['customer'] = $this->customers_model->get_row($appointment['id_users_customer']); @@ -94,42 +105,53 @@ class Backend_api extends CI_Controller { $roleSlug = $this->session->userdata('role_slug'); // If the current user is a provider he must only see his own appointments. - if ($roleSlug === DB_SLUG_PROVIDER) { - foreach($response['appointments'] as $index => $appointment) { - if ((int)$appointment['id_users_provider'] !== (int)$userId) { + if ($roleSlug === DB_SLUG_PROVIDER) + { + foreach ($response['appointments'] as $index => $appointment) + { + if ((int)$appointment['id_users_provider'] !== (int)$userId) + { unset($response['appointments'][$index]); } } - foreach($response['unavailabilities'] as $index => $unavailability) { - if ((int)$unavailability['id_users_provider'] !== (int)$userId) { + foreach ($response['unavailabilities'] as $index => $unavailability) + { + if ((int)$unavailability['id_users_provider'] !== (int)$userId) + { unset($response['unavailabilities'][$index]); } } } // If the current user is a secretary he must only see the appointments of his providers. - if ($roleSlug === DB_SLUG_SECRETARY) { + if ($roleSlug === DB_SLUG_SECRETARY) + { $this->load->model('secretaries_model'); $providers = $this->secretaries_model->get_row($userId)['providers']; - foreach($response['appointments'] as $index => $appointment) { - if (!in_array((int)$appointment['id_users_provider'], $providers)) { + foreach ($response['appointments'] as $index => $appointment) + { + if ( ! in_array((int)$appointment['id_users_provider'], $providers)) + { unset($response['appointments'][$index]); } } - foreach($response['unavailabilities'] as $index => $unavailability) { - if (!in_array((int)$unavailability['id_users_provider'], $providers)) { + foreach ($response['unavailabilities'] as $index => $unavailability) + { + if ( ! in_array((int)$unavailability['id_users_provider'], $providers)) + { unset($response['unavailabilities'][$index]); } } } $this->output->set_output(json_encode($response)); - } catch(Exception $exc) { + } catch (Exception $exc) + { $this->output->set_output(json_encode([ - 'exceptions' => [exceptionToJavaScript($exc)] - ])); + 'exceptions' => [exceptionToJavaScript($exc)] + ])); } } @@ -146,14 +168,18 @@ class Backend_api extends CI_Controller { * - string $_POST['start_date'] The user selected start date. * - string $_POST['end_date'] The user selected end date. */ - public function ajax_get_calendar_appointments() { - try { - if ($this->privileges[PRIV_APPOINTMENTS]['view'] == FALSE) { + public function ajax_get_calendar_appointments() + { + try + { + if ($this->privileges[PRIV_APPOINTMENTS]['view'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } - if (!isset($_POST['filter_type'])) { - echo json_encode(array( 'appointments' => array())); + if ( ! isset($_POST['filter_type'])) + { + echo json_encode(['appointments' => []]); return; } @@ -162,46 +188,51 @@ class Backend_api extends CI_Controller { $this->load->model('services_model'); $this->load->model('customers_model'); - if ($_POST['filter_type'] == FILTER_TYPE_PROVIDER) { + if ($_POST['filter_type'] == FILTER_TYPE_PROVIDER) + { $where_id = 'id_users_provider'; - } else { + } else + { $where_id = 'id_services'; } // Get appointments - $where_clause = array( + $where_clause = [ $where_id => $_POST['record_id'], //'start_datetime >=' => $_POST['start_date'], //'end_datetime <=' => $_POST['end_date'], 'is_unavailable' => FALSE - ); + ]; $response['appointments'] = $this->appointments_model->get_batch($where_clause); - foreach($response['appointments'] as &$appointment) { + foreach ($response['appointments'] as &$appointment) + { $appointment['provider'] = $this->providers_model->get_row($appointment['id_users_provider']); $appointment['service'] = $this->services_model->get_row($appointment['id_services']); $appointment['customer'] = $this->customers_model->get_row($appointment['id_users_customer']); } // Get unavailable periods (only for provider). - if ($_POST['filter_type'] == FILTER_TYPE_PROVIDER) { - $where_clause = array( + if ($_POST['filter_type'] == FILTER_TYPE_PROVIDER) + { + $where_clause = [ $where_id => $_POST['record_id'], //'start_datetime >=' => $_POST['start_date'], //'end_datetime <=' => $_POST['end_date'], 'is_unavailable' => TRUE - ); + ]; $response['unavailables'] = $this->appointments_model->get_batch($where_clause); } echo json_encode($response); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -213,43 +244,50 @@ class Backend_api extends CI_Controller { * - array $_POST['appointment_data'] (OPTIONAL) Array with the appointment data. * - array $_POST['customer_data'] (OPTIONAL) Array with the customer data. */ - public function ajax_save_appointment() { - try { - $this->load->model('appointments_model'); - $this->load->model('providers_model'); - $this->load->model('services_model'); - $this->load->model('customers_model'); - $this->load->model('settings_model'); + public function ajax_save_appointment() + { + try + { + $this->load->model('appointments_model'); + $this->load->model('providers_model'); + $this->load->model('services_model'); + $this->load->model('customers_model'); + $this->load->model('settings_model'); // :: SAVE CUSTOMER CHANGES TO DATABASE - if (isset($_POST['customer_data'])) { - $customer = json_decode($_POST['customer_data'], true); + if (isset($_POST['customer_data'])) + { + $customer = json_decode($_POST['customer_data'], TRUE); - $REQUIRED_PRIV = (!isset($customer['id'])) - ? $this->privileges[PRIV_CUSTOMERS]['add'] - : $this->privileges[PRIV_CUSTOMERS]['edit']; - if ($REQUIRED_PRIV == FALSE) { + $REQUIRED_PRIV = ( ! isset($customer['id'])) + ? $this->privileges[PRIV_CUSTOMERS]['add'] + : $this->privileges[PRIV_CUSTOMERS]['edit']; + if ($REQUIRED_PRIV == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $customer['id'] = $this->customers_model->add($customer); } - // :: SAVE APPOINTMENT CHANGES TO DATABASE - if (isset($_POST['appointment_data'])) { - $appointment = json_decode($_POST['appointment_data'], true); + // :: SAVE APPOINTMENT CHANGES TO DATABASE + if (isset($_POST['appointment_data'])) + { + $appointment = json_decode($_POST['appointment_data'], TRUE); - $REQUIRED_PRIV = (!isset($appointment['id'])) - ? $this->privileges[PRIV_APPOINTMENTS]['add'] - : $this->privileges[PRIV_APPOINTMENTS]['edit']; - if ($REQUIRED_PRIV == FALSE) { + $REQUIRED_PRIV = ( ! isset($appointment['id'])) + ? $this->privileges[PRIV_APPOINTMENTS]['add'] + : $this->privileges[PRIV_APPOINTMENTS]['edit']; + if ($REQUIRED_PRIV == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $manage_mode = isset($appointment['id']); // If the appointment does not contain the customer record id, then it // means that is is going to be inserted. Get the customer's record id. - if (!isset($appointment['id_users_customer'])) { + if ( ! isset($appointment['id_users_customer'])) + { $appointment['id_users_customer'] = $customer['id']; } @@ -261,52 +299,60 @@ class Backend_api extends CI_Controller { $customer = $this->customers_model->get_row($appointment['id_users_customer']); $service = $this->services_model->get_row($appointment['id_services']); - $company_settings = array( - 'company_name' => $this->settings_model->get_setting('company_name'), - 'company_link' => $this->settings_model->get_setting('company_link'), - 'company_email' => $this->settings_model->get_setting('company_email') - ); + $company_settings = [ + 'company_name' => $this->settings_model->get_setting('company_name'), + 'company_link' => $this->settings_model->get_setting('company_link'), + 'company_email' => $this->settings_model->get_setting('company_email') + ]; // :: SYNC APPOINTMENT CHANGES WITH GOOGLE CALENDAR - try { + try + { $google_sync = $this->providers_model->get_setting('google_sync', - $appointment['id_users_provider']); + $appointment['id_users_provider']); - if ($google_sync == TRUE) { + if ($google_sync == TRUE) + { $google_token = json_decode($this->providers_model->get_setting('google_token', - $appointment['id_users_provider'])); + $appointment['id_users_provider'])); $this->load->library('Google_sync'); $this->google_sync->refresh_token($google_token->refresh_token); - if ($appointment['id_google_calendar'] == NULL) { + if ($appointment['id_google_calendar'] == NULL) + { $google_event = $this->google_sync->add_appointment($appointment, $provider, - $service, $customer, $company_settings); + $service, $customer, $company_settings); $appointment['id_google_calendar'] = $google_event->id; $this->appointments_model->add($appointment); // Store google calendar id. - } else { + } else + { $this->google_sync->update_appointment($appointment, $provider, - $service, $customer, $company_settings); + $service, $customer, $company_settings); } } - } catch(Exception $exc) { + } catch (Exception $exc) + { $warnings[] = exceptionToJavaScript($exc); } // :: SEND EMAIL NOTIFICATIONS TO PROVIDER AND CUSTOMER - try { - $this->config->load('email'); + try + { + $this->config->load('email'); $email = new \EA\Engine\Notifications\Email($this, $this->config->config); $send_provider = $this->providers_model - ->get_setting('notifications', $provider['id']); + ->get_setting('notifications', $provider['id']); - if (!$manage_mode) { + if ( ! $manage_mode) + { $customer_title = new Text($this->lang->line('appointment_booked')); $customer_message = new Text($this->lang->line('thank_you_for_appointment')); $provider_title = new Text($this->lang->line('appointment_added_to_your_plan')); $provider_message = new Text($this->lang->line('appointment_link_description')); - } else { + } else + { $customer_title = new Text($this->lang->line('appointment_changes_saved')); $customer_message = new Text(''); $provider_title = new Text($this->lang->line('appointment_details_changed')); @@ -318,33 +364,39 @@ class Backend_api extends CI_Controller { $send_customer = $this->settings_model->get_setting('customer_notifications'); - if ((bool)$send_customer === TRUE) { + if ((bool)$send_customer === TRUE) + { $email->sendAppointmentDetails($appointment, $provider, - $service, $customer, $company_settings, $customer_title, - $customer_message, $customer_link, new Email($customer['email'])); + $service, $customer, $company_settings, $customer_title, + $customer_message, $customer_link, new Email($customer['email'])); } - if ($send_provider == TRUE) { + if ($send_provider == TRUE) + { $email->sendAppointmentDetails($appointment, $provider, - $service, $customer, $company_settings, $provider_title, - $provider_message, $provider_link, new Email($provider['email'])); + $service, $customer, $company_settings, $provider_title, + $provider_message, $provider_link, new Email($provider['email'])); } - } catch(Exception $exc) { + } catch (Exception $exc) + { $warnings[] = exceptionToJavaScript($exc); } - if (!isset($warnings)) { + if ( ! isset($warnings)) + { echo json_encode(AJAX_SUCCESS); - } else { - echo json_encode(array( + } else + { + echo json_encode([ 'warnings' => $warnings - )); + ]); } - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -359,13 +411,17 @@ class Backend_api extends CI_Controller { * * - int $_POST['appointment_id'] The appointment id to be deleted. */ - public function ajax_delete_appointment() { - try { - if ($this->privileges[PRIV_APPOINTMENTS]['delete'] == FALSE) { + public function ajax_delete_appointment() + { + try + { + if ($this->privileges[PRIV_APPOINTMENTS]['delete'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } - if (!isset($_POST['appointment_id'])) { + if ( ! isset($_POST['appointment_id'])) + { throw new Exception('No appointment id provided.'); } @@ -381,69 +437,80 @@ class Backend_api extends CI_Controller { $customer = $this->customers_model->get_row($appointment['id_users_customer']); $service = $this->services_model->get_row($appointment['id_services']); - $company_settings = array( + $company_settings = [ 'company_name' => $this->settings_model->get_setting('company_name'), 'company_email' => $this->settings_model->get_setting('company_email'), 'company_link' => $this->settings_model->get_setting('company_link') - ); + ]; // :: DELETE APPOINTMENT RECORD FROM DATABASE $this->appointments_model->delete($_POST['appointment_id']); // :: SYNC DELETE WITH GOOGLE CALENDAR - if ($appointment['id_google_calendar'] != NULL) { - try { + if ($appointment['id_google_calendar'] != NULL) + { + try + { $google_sync = $this->providers_model->get_setting('google_sync', $provider['id']); - if ($google_sync == TRUE) { + if ($google_sync == TRUE) + { $google_token = json_decode($this->providers_model - ->get_setting('google_token', $provider['id'])); + ->get_setting('google_token', $provider['id'])); $this->load->library('Google_sync'); $this->google_sync->refresh_token($google_token->refresh_token); $this->google_sync->delete_appointment($provider, $appointment['id_google_calendar']); } - } catch(Exception $exc) { + } catch (Exception $exc) + { $warnings[] = exceptionToJavaScript($exc); } } // :: SEND NOTIFICATION EMAILS TO PROVIDER AND CUSTOMER - try { + try + { $this->config->load('email'); - $email = new \EA\Engine\Notifications\Email($this, $this->config->config); + $email = new \EA\Engine\Notifications\Email($this, $this->config->config); $send_provider = $this->providers_model - ->get_setting('notifications', $provider['id']); + ->get_setting('notifications', $provider['id']); - if ((bool)$send_provider === TRUE) { + if ((bool)$send_provider === TRUE) + { $email->sendDeleteAppointment($appointment, $provider, - $service, $customer, $company_settings, new Email($provider['email']), - new Text($_POST['delete_reason'])); + $service, $customer, $company_settings, new Email($provider['email']), + new Text($_POST['delete_reason'])); } $send_customer = $this->settings_model->get_setting('customer_notifications'); - if ((bool)$send_customer === TRUE) { + if ((bool)$send_customer === TRUE) + { $email->sendDeleteAppointment($appointment, $provider, - $service, $customer, $company_settings, new Email($customer['email']), - new Text($_POST['delete_reason'])); + $service, $customer, $company_settings, new Email($customer['email']), + new Text($_POST['delete_reason'])); } - } catch(Exception $exc) { + } catch (Exception $exc) + { $warnings[] = exceptionToJavaScript($exc); } // :: SEND RESPONSE TO CLIENT BROWSER - if (!isset($warnings)) { + if ( ! isset($warnings)) + { echo json_encode(AJAX_SUCCESS); // Everything executed successfully. - } else { - echo json_encode(array( + } else + { + echo json_encode([ 'warnings' => $warnings // There were warnings during the operation. - )); + ]); } - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -457,13 +524,18 @@ class Backend_api extends CI_Controller { * * - string $_POST['provider_id'] The selected provider record id. */ - public function ajax_disable_provider_sync() { - try { - if (!isset($_POST['provider_id'])) + public function ajax_disable_provider_sync() + { + try + { + if ( ! isset($_POST['provider_id'])) + { throw new Exception('Provider id not specified.'); + } if ($this->privileges[PRIV_USERS]['edit'] == FALSE - && $this->session->userdata('user_id') != $_POST['provider_id']) { + && $this->session->userdata('user_id') != $_POST['provider_id']) + { throw new Exception('You do not have the required privileges for this task.'); } @@ -475,10 +547,11 @@ class Backend_api extends CI_Controller { echo json_encode(AJAX_SUCCESS); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -491,53 +564,59 @@ class Backend_api extends CI_Controller { * * Outputs the search results. */ - public function ajax_filter_customers() { - try { - if ($this->privileges[PRIV_CUSTOMERS]['view'] == FALSE) { + public function ajax_filter_customers() + { + try + { + if ($this->privileges[PRIV_CUSTOMERS]['view'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $this->load->model('appointments_model'); $this->load->model('services_model'); $this->load->model('providers_model'); - $this->load->model('customers_model'); + $this->load->model('customers_model'); - $key = $this->db->escape_str($_POST['key']); + $key = $this->db->escape_str($_POST['key']); $key = strtoupper($key); - $where_clause = - '(first_name LIKE upper("%' . $key . '%") OR ' . - 'last_name LIKE upper("%' . $key . '%") OR ' . - 'email LIKE upper("%' . $key . '%") OR ' . - 'phone_number LIKE upper("%' . $key . '%") OR ' . - 'address LIKE upper("%' . $key . '%") OR ' . - 'city LIKE upper("%' . $key . '%") OR ' . - 'zip_code LIKE upper("%' . $key . '%") OR ' . - 'notes LIKE upper("%' . $key . '%"))'; + $where_clause = + '(first_name LIKE upper("%' . $key . '%") OR ' . + 'last_name LIKE upper("%' . $key . '%") OR ' . + 'email LIKE upper("%' . $key . '%") OR ' . + 'phone_number LIKE upper("%' . $key . '%") OR ' . + 'address LIKE upper("%' . $key . '%") OR ' . + 'city LIKE upper("%' . $key . '%") OR ' . + 'zip_code LIKE upper("%' . $key . '%") OR ' . + 'notes LIKE upper("%' . $key . '%"))'; $customers = $this->customers_model->get_batch($where_clause); - foreach($customers as &$customer) { + foreach ($customers as &$customer) + { $appointments = $this->appointments_model - ->get_batch(array('id_users_customer' => $customer['id'])); + ->get_batch(['id_users_customer' => $customer['id']]); - foreach($appointments as &$appointment) { + foreach ($appointments as &$appointment) + { $appointment['service'] = $this->services_model - ->get_row($appointment['id_services']); + ->get_row($appointment['id_services']); $appointment['provider'] = $this->providers_model - ->get_row($appointment['id_users_provider']); + ->get_row($appointment['id_users_provider']); } $customer['appointments'] = $appointments; } - echo json_encode($customers); + echo json_encode($customers); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); - } + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); + } } /** @@ -547,15 +626,18 @@ class Backend_api extends CI_Controller { * * - array $_POST['unavailable'] JSON encoded array that contains the unavailable period data. */ - public function ajax_save_unavailable() { - try { + public function ajax_save_unavailable() + { + try + { // Check privileges - $unavailable = json_decode($_POST['unavailable'], true); + $unavailable = json_decode($_POST['unavailable'], TRUE); - $REQUIRED_PRIV = (!isset($unavailable['id'])) - ? $this->privileges[PRIV_APPOINTMENTS]['add'] - : $this->privileges[PRIV_APPOINTMENTS]['edit']; - if ($REQUIRED_PRIV == FALSE) { + $REQUIRED_PRIV = ( ! isset($unavailable['id'])) + ? $this->privileges[PRIV_APPOINTMENTS]['add'] + : $this->privileges[PRIV_APPOINTMENTS]['edit']; + if ($REQUIRED_PRIV == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } @@ -569,41 +651,49 @@ class Backend_api extends CI_Controller { $unavailable = $this->appointments_model->get_row($unavailable['id']); // fetch all inserted data // Google Sync - try { + try + { $google_sync = $this->providers_model->get_setting('google_sync', - $unavailable['id_users_provider']); + $unavailable['id_users_provider']); - if ($google_sync) { + if ($google_sync) + { $google_token = json_decode($this->providers_model->get_setting('google_token', - $unavailable['id_users_provider'])); + $unavailable['id_users_provider'])); $this->load->library('google_sync'); $this->google_sync->refresh_token($google_token->refresh_token); - if ($unavailable['id_google_calendar'] == NULL) { + if ($unavailable['id_google_calendar'] == NULL) + { $google_event = $this->google_sync->add_unavailable($provider, $unavailable); $unavailable['id_google_calendar'] = $google_event->id; $this->appointments_model->add_unavailable($unavailable); - } else { + } else + { $google_event = $this->google_sync->update_unavailable($provider, $unavailable); } } - } catch(Exception $exc) { + } catch (Exception $exc) + { $warnings[] = $exc; } - if (isset($warnings)) { - echo json_encode(array( + if (isset($warnings)) + { + echo json_encode([ 'warnings' => $warnings - )); - } else { + ]); + } else + { echo json_encode(AJAX_SUCCESS); } - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -614,9 +704,12 @@ class Backend_api extends CI_Controller { * * - int $_POST['unavailable_id'] Record id to be deleted. */ - public function ajax_delete_unavailable() { - try { - if ($this->privileges[PRIV_APPOINTMENTS]['delete'] == FALSE) { + public function ajax_delete_unavailable() + { + try + { + if ($this->privileges[PRIV_APPOINTMENTS]['delete'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } @@ -630,30 +723,36 @@ class Backend_api extends CI_Controller { $this->appointments_model->delete_unavailable($unavailable['id']); // Google Sync - try { + try + { $google_sync = $this->providers_model->get_setting('google_sync', $provider['id']); - if ($google_sync == TRUE) { + if ($google_sync == TRUE) + { $google_token = json_decode($this->providers_model->get_setting('google_token', $provider['id'])); $this->load->library('google_sync'); $this->google_sync->refresh_token($google_token->refresh_token); $this->google_sync->delete_unavailable($provider, $unavailable['id_google_calendar']); } - } catch(Exception $exc) { + } catch (Exception $exc) + { $warnings[] = $exc; } - if (isset($warnings)) { - echo json_encode(array( + if (isset($warnings)) + { + echo json_encode([ 'warnings' => $warnings - )); - } else { + ]); + } else + { echo json_encode(AJAX_SUCCESS); } - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -664,27 +763,31 @@ class Backend_api extends CI_Controller { * * - array $_POST['customer'] JSON encoded array that contains the customer's data. */ - public function ajax_save_customer() { - try { + public function ajax_save_customer() + { + try + { $this->load->model('customers_model'); - $customer = json_decode($_POST['customer'], true); + $customer = json_decode($_POST['customer'], TRUE); - $REQUIRED_PRIV = (!isset($customer['id'])) - ? $this->privileges[PRIV_CUSTOMERS]['add'] - : $this->privileges[PRIV_CUSTOMERS]['edit']; - if ($REQUIRED_PRIV == FALSE) { + $REQUIRED_PRIV = ( ! isset($customer['id'])) + ? $this->privileges[PRIV_CUSTOMERS]['add'] + : $this->privileges[PRIV_CUSTOMERS]['edit']; + if ($REQUIRED_PRIV == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $customer_id = $this->customers_model->add($customer); - echo json_encode(array( + echo json_encode([ 'status' => AJAX_SUCCESS, 'id' => $customer_id - )); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + ]); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -695,19 +798,23 @@ class Backend_api extends CI_Controller { * * - int $_POST['customer_id'] Customer record id to be deleted. */ - public function ajax_delete_customer() { - try { - if ($this->privileges[PRIV_CUSTOMERS]['delete'] == FALSE) { + public function ajax_delete_customer() + { + try + { + if ($this->privileges[PRIV_CUSTOMERS]['delete'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $this->load->model('customers_model'); $this->customers_model->delete($_POST['customer_id']); echo json_encode(AJAX_SUCCESS); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -718,27 +825,31 @@ class Backend_api extends CI_Controller { * * - array $_POST['service'] Contains the service data (json encoded). */ - public function ajax_save_service() { - try { + public function ajax_save_service() + { + try + { $this->load->model('services_model'); - $service = json_decode($_POST['service'], true); + $service = json_decode($_POST['service'], TRUE); - $REQUIRED_PRIV = (!isset($service['id'])) - ? $this->privileges[PRIV_SERVICES]['add'] - : $this->privileges[PRIV_SERVICES]['edit']; - if ($REQUIRED_PRIV == FALSE) { + $REQUIRED_PRIV = ( ! isset($service['id'])) + ? $this->privileges[PRIV_SERVICES]['add'] + : $this->privileges[PRIV_SERVICES]['edit']; + if ($REQUIRED_PRIV == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } - $service_id =$this->services_model->add($service); - echo json_encode(array( + $service_id = $this->services_model->add($service); + echo json_encode([ 'status' => AJAX_SUCCESS, 'id' => $service_id - )); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + ]); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -749,19 +860,23 @@ class Backend_api extends CI_Controller { * * - int $_POST['service_id'] Record id to be deleted. */ - public function ajax_delete_service() { - try { - if ($this->privileges[PRIV_SERVICES]['delete'] == FALSE) { + public function ajax_delete_service() + { + try + { + if ($this->privileges[PRIV_SERVICES]['delete'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $this->load->model('services_model'); $result = $this->services_model->delete($_POST['service_id']); echo ($result) ? json_encode(AJAX_SUCCESS) : json_encode(AJAX_FAILURE); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -774,24 +889,28 @@ class Backend_api extends CI_Controller { * * Outputs a JSON encoded array back to client. */ - public function ajax_filter_services() { - try { - if ($this->privileges[PRIV_SERVICES]['view'] == FALSE) { + public function ajax_filter_services() + { + try + { + if ($this->privileges[PRIV_SERVICES]['view'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $this->load->model('services_model'); $key = $this->db->escape_str($_POST['key']); $where = - '(name LIKE "%' . $key . '%" OR duration LIKE "%' . $key . '%" OR ' . - 'price LIKE "%' . $key . '%" OR currency LIKE "%' . $key . '%" OR ' . - 'description LIKE "%' . $key . '%")'; + '(name LIKE "%' . $key . '%" OR duration LIKE "%' . $key . '%" OR ' . + 'price LIKE "%' . $key . '%" OR currency LIKE "%' . $key . '%" OR ' . + 'description LIKE "%' . $key . '%")'; $services = $this->services_model->get_batch($where); echo json_encode($services); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -803,27 +922,31 @@ class Backend_api extends CI_Controller { * - array $_POST['category'] Json encoded array with the category data. If an ID value is provided then the * category is going to be updated instead of inserted. */ - public function ajax_save_service_category() { - try { + public function ajax_save_service_category() + { + try + { $this->load->model('services_model'); - $category = json_decode($_POST['category'], true); + $category = json_decode($_POST['category'], TRUE); - $REQUIRED_PRIV = (!isset($category['id'])) - ? $this->privileges[PRIV_SERVICES]['add'] - : $this->privileges[PRIV_SERVICES]['edit']; - if ($REQUIRED_PRIV == FALSE) { + $REQUIRED_PRIV = ( ! isset($category['id'])) + ? $this->privileges[PRIV_SERVICES]['add'] + : $this->privileges[PRIV_SERVICES]['edit']; + if ($REQUIRED_PRIV == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $category_id = $this->services_model->add_category($category); - echo json_encode(array( + echo json_encode([ 'status' => AJAX_SUCCESS, 'id' => $category_id - )); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + ]); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -832,19 +955,23 @@ class Backend_api extends CI_Controller { * * - int $_POST['category_id'] Record id to be deleted. */ - public function ajax_delete_service_category() { - try { - if ($this->privileges[PRIV_SERVICES]['delete'] == FALSE) { + public function ajax_delete_service_category() + { + try + { + if ($this->privileges[PRIV_SERVICES]['delete'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $this->load->model('services_model'); $result = $this->services_model->delete_category($_POST['category_id']); echo ($result) ? json_encode(AJAX_SUCCESS) : json_encode(AJAX_FAILURE); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -857,9 +984,12 @@ class Backend_api extends CI_Controller { * * Outputs a JSON encoded array back to client with the category records. */ - public function ajax_filter_service_categories() { - try { - if ($this->privileges[PRIV_SERVICES]['view'] == FALSE) { + public function ajax_filter_service_categories() + { + try + { + if ($this->privileges[PRIV_SERVICES]['view'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } @@ -868,10 +998,11 @@ class Backend_api extends CI_Controller { $where = '(name LIKE "%' . $key . '%" OR description LIKE "%' . $key . '%")'; $categories = $this->services_model->get_all_categories($where); echo json_encode($categories); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -884,9 +1015,12 @@ class Backend_api extends CI_Controller { * * Outputs a JSON encoded array back to client with the admin records. */ - public function ajax_filter_admins() { - try { - if ($this->privileges[PRIV_USERS]['view'] == FALSE) { + public function ajax_filter_admins() + { + try + { + if ($this->privileges[PRIV_USERS]['view'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } @@ -900,10 +1034,11 @@ class Backend_api extends CI_Controller { 'OR zip_code LIKE "%' . $key . '%" OR notes LIKE "%' . $key . '%")'; $admins = $this->admins_model->get_batch($where); echo json_encode($admins); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -917,30 +1052,34 @@ class Backend_api extends CI_Controller { * * Outputs an array with the operation status and the record id that was saved into the database. */ - public function ajax_save_admin() { - try { + public function ajax_save_admin() + { + try + { $this->load->model('admins_model'); - $admin = json_decode($_POST['admin'], true); + $admin = json_decode($_POST['admin'], TRUE); - $REQUIRED_PRIV = (!isset($admin['id'])) - ? $this->privileges[PRIV_USERS]['add'] - : $this->privileges[PRIV_USERS]['edit']; - if ($REQUIRED_PRIV == FALSE) { + $REQUIRED_PRIV = ( ! isset($admin['id'])) + ? $this->privileges[PRIV_USERS]['add'] + : $this->privileges[PRIV_USERS]['edit']; + if ($REQUIRED_PRIV == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $admin_id = $this->admins_model->add($admin); - $response = array( + $response = [ 'status' => AJAX_SUCCESS, 'id' => $admin_id - ); + ]; echo json_encode($response); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -953,19 +1092,23 @@ class Backend_api extends CI_Controller { * * Outputs the operation result constant (AJAX_SUCCESS or AJAX_FAILURE). */ - public function ajax_delete_admin() { - try { - if ($this->privileges[PRIV_USERS]['delete'] == FALSE) { + public function ajax_delete_admin() + { + try + { + if ($this->privileges[PRIV_USERS]['delete'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $this->load->model('admins_model'); $result = $this->admins_model->delete($_POST['admin_id']); echo ($result) ? json_encode(AJAX_SUCCESS) : json_encode(AJAX_FAILURE); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -978,9 +1121,12 @@ class Backend_api extends CI_Controller { * * Outputs a JSON encoded array back to client with the provider records. */ - public function ajax_filter_providers() { - try { - if ($this->privileges[PRIV_USERS]['view'] == FALSE) { + public function ajax_filter_providers() + { + try + { + if ($this->privileges[PRIV_USERS]['view'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } @@ -994,10 +1140,11 @@ class Backend_api extends CI_Controller { 'OR zip_code LIKE "%' . $key . '%" OR notes LIKE "%' . $key . '%")'; $providers = $this->providers_model->get_batch($where); echo json_encode($providers); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -1011,35 +1158,40 @@ class Backend_api extends CI_Controller { * * Outputs the success constant 'AJAX_SUCCESS' so javascript knows that everything completed successfully. */ - public function ajax_save_provider() { - try { + public function ajax_save_provider() + { + try + { $this->load->model('providers_model'); - $provider = json_decode($_POST['provider'], true); + $provider = json_decode($_POST['provider'], TRUE); - $REQUIRED_PRIV = (!isset($provider['id'])) - ? $this->privileges[PRIV_USERS]['add'] - : $this->privileges[PRIV_USERS]['edit']; - if ($REQUIRED_PRIV == FALSE) { + $REQUIRED_PRIV = ( ! isset($provider['id'])) + ? $this->privileges[PRIV_USERS]['add'] + : $this->privileges[PRIV_USERS]['edit']; + if ($REQUIRED_PRIV == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } - if (!isset($provider['settings']['working_plan'])) { + if ( ! isset($provider['settings']['working_plan'])) + { $this->load->model('settings_model'); $provider['settings']['working_plan'] = $this->settings_model - ->get_setting('company_working_plan'); + ->get_setting('company_working_plan'); } $provider_id = $this->providers_model->add($provider); - echo json_encode(array( + echo json_encode([ 'status' => AJAX_SUCCESS, 'id' => $provider_id - )); + ]); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -1052,19 +1204,23 @@ class Backend_api extends CI_Controller { * * Outputs the operation result constant (AJAX_SUCCESS or AJAX_FAILURE). */ - public function ajax_delete_provider() { - try { - if ($this->privileges[PRIV_USERS]['delete'] == FALSE) { + public function ajax_delete_provider() + { + try + { + if ($this->privileges[PRIV_USERS]['delete'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $this->load->model('providers_model'); $result = $this->providers_model->delete($_POST['provider_id']); echo ($result) ? json_encode(AJAX_SUCCESS) : json_encode(AJAX_FAILURE); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -1077,9 +1233,12 @@ class Backend_api extends CI_Controller { * * Outputs a JSON encoded array back to client with the secretary records. */ - public function ajax_filter_secretaries() { - try { - if ($this->privileges[PRIV_USERS]['view'] == FALSE) { + public function ajax_filter_secretaries() + { + try + { + if ($this->privileges[PRIV_USERS]['view'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } @@ -1093,10 +1252,11 @@ class Backend_api extends CI_Controller { 'OR zip_code LIKE "%' . $key . '%" OR notes LIKE "%' . $key . '%")'; $secretaries = $this->secretaries_model->get_batch($where); echo json_encode($secretaries); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -1110,28 +1270,32 @@ class Backend_api extends CI_Controller { * * Outputs the success constant 'AJAX_SUCCESS' so JavaScript knows that everything completed successfully. */ - public function ajax_save_secretary() { - try { + public function ajax_save_secretary() + { + try + { $this->load->model('secretaries_model'); - $secretary = json_decode($_POST['secretary'], true); + $secretary = json_decode($_POST['secretary'], TRUE); - $REQUIRED_PRIV = (!isset($secretary['id'])) - ? $this->privileges[PRIV_USERS]['add'] - : $this->privileges[PRIV_USERS]['edit']; - if ($REQUIRED_PRIV == FALSE) { + $REQUIRED_PRIV = ( ! isset($secretary['id'])) + ? $this->privileges[PRIV_USERS]['add'] + : $this->privileges[PRIV_USERS]['edit']; + if ($REQUIRED_PRIV == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $secretary_id = $this->secretaries_model->add($secretary); - echo json_encode(array( + echo json_encode([ 'status' => AJAX_SUCCESS, 'id' => $secretary_id - )); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + ]); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -1144,19 +1308,23 @@ class Backend_api extends CI_Controller { * * Outputs the operation result constant (AJAX_SUCCESS or AJAX_FAILURE). */ - public function ajax_delete_secretary() { - try { - if ($this->privileges[PRIV_USERS]['delete'] == FALSE) { + public function ajax_delete_secretary() + { + try + { + if ($this->privileges[PRIV_USERS]['delete'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $this->load->model('secretaries_model'); $result = $this->secretaries_model->delete($_POST['secretary_id']); echo ($result) ? json_encode(AJAX_SUCCESS) : json_encode(AJAX_FAILURE); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -1171,28 +1339,38 @@ class Backend_api extends CI_Controller { * - array $_POST['settings'] Contains an array with settings. * - bool $_POST['type'] Determines the settings type, can be either SETTINGS_SYSTEM or SETTINGS_USER. */ - public function ajax_save_settings() { - try { - if ($_POST['type'] == SETTINGS_SYSTEM) { - if ($this->privileges[PRIV_SYSTEM_SETTINGS]['edit'] == FALSE) { + public function ajax_save_settings() + { + try + { + if ($_POST['type'] == SETTINGS_SYSTEM) + { + if ($this->privileges[PRIV_SYSTEM_SETTINGS]['edit'] == FALSE) + { throw new Exception('You do not have the required privileges for this task.'); } $this->load->model('settings_model'); - $settings = json_decode($_POST['settings'], true); + $settings = json_decode($_POST['settings'], TRUE); $this->settings_model->save_settings($settings); - } else if ($_POST['type'] == SETTINGS_USER) { - if ($this->privileges[PRIV_USER_SETTINGS]['edit'] == FALSE) { - throw new Exception('You do not have the required privileges for this task.'); + } else + { + if ($_POST['type'] == SETTINGS_USER) + { + if ($this->privileges[PRIV_USER_SETTINGS]['edit'] == FALSE) + { + throw new Exception('You do not have the required privileges for this task.'); + } + $this->load->model('user_model'); + $this->user_model->save_settings(json_decode($_POST['settings'], TRUE)); } - $this->load->model('user_model'); - $this->user_model->save_settings(json_decode($_POST['settings'], true)); } echo json_encode(AJAX_SUCCESS); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -1204,17 +1382,20 @@ class Backend_api extends CI_Controller { * - string $_POST['username'] Record's username to validate. * - bool $_POST['record_exists'] Whether the record already exists in database. */ - public function ajax_validate_username() { - try { + public function ajax_validate_username() + { + try + { // We will only use the function in the admins_model because it is sufficient // for the rest user types for now (providers, secretaries). $this->load->model('admins_model'); $is_valid = $this->admins_model->validate_username($_POST['username'], $_POST['user_id']); echo json_encode($is_valid); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -1227,18 +1408,23 @@ class Backend_api extends CI_Controller { * * - string $_POST['language'] Selected language name. */ - public function ajax_change_language() { - try { + public function ajax_change_language() + { + try + { // Check if language exists in the available languages. - $found = false; - foreach($this->config->item('available_languages') as $lang) { - if ($lang == $_POST['language']) { - $found = true; + $found = FALSE; + foreach ($this->config->item('available_languages') as $lang) + { + if ($lang == $_POST['language']) + { + $found = TRUE; break; } } - if (!$found) { + if ( ! $found) + { throw new Exception('Translations for the given language does not exist (' . $_POST['language'] . ').'); } @@ -1247,11 +1433,12 @@ class Backend_api extends CI_Controller { echo json_encode(AJAX_SUCCESS); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); - } + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); + } } /** @@ -1264,29 +1451,36 @@ class Backend_api extends CI_Controller { * * - string $_POST['provider_id'] Provider record id. */ - public function ajax_get_google_calendars() { - try { + public function ajax_get_google_calendars() + { + try + { $this->load->library('google_sync'); $this->load->model('providers_model'); - if (!isset($_POST['provider_id'])) + if ( ! isset($_POST['provider_id'])) + { throw new Exception('Provider id is required in order to fetch the google calendars.'); + } // Check if selected provider has sync enabled. $google_sync = $this->providers_model->get_setting('google_sync', $_POST['provider_id']); - if ($google_sync) { + if ($google_sync) + { $google_token = json_decode($this->providers_model->get_setting('google_token', $_POST['provider_id'])); $this->google_sync->refresh_token($google_token->refresh_token); $calendars = $this->google_sync->get_google_calendars(); echo json_encode($calendars); - } else { + } else + { echo json_encode(AJAX_FAILURE); } - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); - } + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); + } } /** @@ -1299,21 +1493,26 @@ class Backend_api extends CI_Controller { * - int $_POST['provider_id'] Provider record id. * - string $_POST['calendar_id'] Google calendar's id. */ - public function ajax_select_google_calendar() { - try { + public function ajax_select_google_calendar() + { + try + { if ($this->privileges[PRIV_USERS]['edit'] == FALSE - && $this->session->userdata('user_id') != $_POST['provider_id']) { + && $this->session->userdata('user_id') != $_POST['provider_id']) + { throw new Exception('You do not have the required privileges for this task.'); } $this->load->model('providers_model'); - $result = $this->providers_model->set_setting('google_calendar', $_POST['calendar_id'], $_POST['provider_id']); + $result = $this->providers_model->set_setting('google_calendar', $_POST['calendar_id'], + $_POST['provider_id']); echo json_encode(($result) ? AJAX_SUCCESS : AJAX_FAILURE); - } catch (Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } } diff --git a/src/application/controllers/Captcha.php b/src/application/controllers/Captcha.php index 45c436bf..8e674fb7 100644 --- a/src/application/controllers/Captcha.php +++ b/src/application/controllers/Captcha.php @@ -1,4 +1,7 @@ -load->library('session'); } @@ -28,7 +32,8 @@ class Captcha extends CI_Controller { /** * Make a request to this method to get a captcha image. */ - public function index() { + public function index() + { header('Content-type: image/jpeg'); $builder = new Gregwar\Captcha\CaptchaBuilder; $builder->build(); diff --git a/src/application/controllers/Errors.php b/src/application/controllers/Errors.php index c7fcd65b..74062670 100644 --- a/src/application/controllers/Errors.php +++ b/src/application/controllers/Errors.php @@ -1,4 +1,7 @@ -load->library('session'); + $this->load->library('session'); - // Set user's selected language. - if ($this->session->userdata('language')) { - $this->config->set_item('language', $this->session->userdata('language')); - $this->lang->load('translations', $this->session->userdata('language')); - } else { - $this->lang->load('translations', $this->config->item('language')); // default - } - } + // Set user's selected language. + if ($this->session->userdata('language')) + { + $this->config->set_item('language', $this->session->userdata('language')); + $this->lang->load('translations', $this->session->userdata('language')); + } else + { + $this->lang->load('translations', $this->config->item('language')); // default + } + } /** * Display the 404 error page. */ - public function index() { + public function index() + { $this->e404(); } /** * Display the 404 error page. */ - public function error404() { - $this->load->helper('google_analytics'); + public function error404() + { + $this->load->helper('google_analytics'); $this->load->model('settings_model'); $view['company_name'] = $this->settings_model->get_setting('company_name'); $this->load->view('general/error404', $view); diff --git a/src/application/controllers/Google.php b/src/application/controllers/Google.php index 0bdd1bab..c440f60e 100644 --- a/src/application/controllers/Google.php +++ b/src/application/controllers/Google.php @@ -1,4 +1,7 @@ -load->library('session'); } @@ -35,9 +39,10 @@ class Google extends CI_Controller { * * @param int $provider_id The provider id, for whom the sync authorization is made. */ - public function oauth($provider_id) { - // Store the provider id for use on the callback function. - $_SESSION['oauth_provider_id'] = $provider_id; + public function oauth($provider_id) + { + // Store the provider id for use on the callback function. + $_SESSION['oauth_provider_id'] = $provider_id; // Redirect browser to google user content page. $this->load->library('Google_sync'); @@ -55,23 +60,28 @@ class Google extends CI_Controller { * documentation of OAuth), every Easy!Appointments installation should use its own calendar api key. So in every * api console account, the "http://path-to-e!a/google/oauth_callback" should be included in an allowed redirect URL. */ - public function oauth_callback() { - if (isset($_GET['code'])) { + public function oauth_callback() + { + if (isset($_GET['code'])) + { $this->load->library('Google_sync'); $token = $this->google_sync->authenticate($_GET['code']); - // Store the token into the database for future reference. - if (isset($_SESSION['oauth_provider_id'])) { + // Store the token into the database for future reference. + if (isset($_SESSION['oauth_provider_id'])) + { $this->load->model('providers_model'); $this->providers_model->set_setting('google_sync', TRUE, $_SESSION['oauth_provider_id']); $this->providers_model->set_setting('google_token', $token, $_SESSION['oauth_provider_id']); $this->providers_model->set_setting('google_calendar', 'primary', $_SESSION['oauth_provider_id']); - } else { + } else + { echo '

Sync provider id not specified!

'; } - } else { + } else + { echo '

Authorization Failed!

'; - } + } } /** @@ -83,16 +93,20 @@ class Google extends CI_Controller { * * @param int $provider_id Provider record to be synced. */ - public function sync($provider_id = NULL) { - try { + public function sync($provider_id = NULL) + { + try + { // The user must be logged in. $this->load->library('session'); - if ($this->session->userdata('user_id') == FALSE) { + if ($this->session->userdata('user_id') == FALSE) + { return; } - if ($provider_id === NULL) { + if ($provider_id === NULL) + { throw new Exception('Provider id not specified.'); } @@ -107,7 +121,8 @@ class Google extends CI_Controller { // Check whether the selected provider has google sync enabled. $google_sync = $this->providers_model->get_setting('google_sync', $provider['id']); - if (!$google_sync) { + if ( ! $google_sync) + { throw new Exception('The selected provider has not the google synchronization setting enabled.'); } @@ -121,42 +136,49 @@ class Google extends CI_Controller { $start = strtotime('-' . $sync_past_days . ' days', strtotime(date('Y-m-d'))); $end = strtotime('+' . $sync_future_days . ' days', strtotime(date('Y-m-d'))); - $where_clause = array( + $where_clause = [ 'start_datetime >=' => date('Y-m-d H:i:s', $start), 'end_datetime <=' => date('Y-m-d H:i:s', $end), 'id_users_provider' => $provider['id'] - ); + ]; $appointments = $this->appointments_model->get_batch($where_clause); - $company_settings = array( + $company_settings = [ 'company_name' => $this->settings_model->get_setting('company_name'), 'company_link' => $this->settings_model->get_setting('company_link'), 'company_email' => $this->settings_model->get_setting('company_email') - ); + ]; // Sync each appointment with Google Calendar by following the project's sync protocol (see documentation). - foreach($appointments as $appointment) { - if ($appointment['is_unavailable'] == FALSE) { + foreach ($appointments as $appointment) + { + if ($appointment['is_unavailable'] == FALSE) + { $service = $this->services_model->get_row($appointment['id_services']); $customer = $this->customers_model->get_row($appointment['id_users_customer']); - } else { + } else + { $service = NULL; $customer = NULL; } // If current appointment not synced yet, add to gcal. - if ($appointment['id_google_calendar'] == NULL) { + if ($appointment['id_google_calendar'] == NULL) + { $google_event = $this->google_sync->add_appointment($appointment, $provider, - $service, $customer, $company_settings); + $service, $customer, $company_settings); $appointment['id_google_calendar'] = $google_event->id; $this->appointments_model->add($appointment); // Save gcal id - } else { + } else + { // Appointment is synced with google calendar. - try { + try + { $google_event = $this->google_sync->get_event($provider, $appointment['id_google_calendar']); - if ($google_event->status == 'cancelled') { + if ($google_event->status == 'cancelled') + { throw new Exception('Event is cancelled, remove the record from Easy!Appointments.'); } @@ -167,17 +189,20 @@ class Google extends CI_Controller { $event_start = strtotime($google_event->getStart()->getDateTime()); $event_end = strtotime($google_event->getEnd()->getDateTime()); - if ($appt_start != $event_start || $appt_end != $event_end) { + if ($appt_start != $event_start || $appt_end != $event_end) + { $is_different = TRUE; } - if ($is_different) { + if ($is_different) + { $appointment['start_datetime'] = date('Y-m-d H:i:s', $event_start); $appointment['end_datetime'] = date('Y-m-d H:i:s', $event_end); $this->appointments_model->add($appointment); } - } catch(Exception $exc) { + } catch (Exception $exc) + { // Appointment not found on gcal, delete from e!a. $this->appointments_model->delete($appointment['id']); $appointment['id_google_calendar'] = NULL; @@ -189,11 +214,13 @@ class Google extends CI_Controller { $google_calendar = $provider['settings']['google_calendar']; $events = $this->google_sync->get_sync_events($google_calendar, $start, $end); - foreach($events->getItems() as $event) { - $results = $this->appointments_model->get_batch(array('id_google_calendar' => $event->getId())); - if (count($results) == 0) { + foreach ($events->getItems() as $event) + { + $results = $this->appointments_model->get_batch(['id_google_calendar' => $event->getId()]); + if (count($results) == 0) + { // Record doesn't exist in E!A, so add the event now. - $appointment = array( + $appointment = [ 'start_datetime' => date('Y-m-d H:i:s', strtotime($event->start->getDateTime())), 'end_datetime' => date('Y-m-d H:i:s', strtotime($event->end->getDateTime())), 'is_unavailable' => TRUE, @@ -202,17 +229,18 @@ class Google extends CI_Controller { 'id_google_calendar' => $event->getId(), 'id_users_customer' => NULL, 'id_services' => NULL, - ); + ]; $this->appointments_model->add($appointment); } } echo json_encode(AJAX_SUCCESS); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } } diff --git a/src/application/controllers/Installation.php b/src/application/controllers/Installation.php index a09a483c..3d8b9bd1 100644 --- a/src/application/controllers/Installation.php +++ b/src/application/controllers/Installation.php @@ -1,4 +1,7 @@ -load->helper('installation'); $this->load->library('session'); // Set user's selected language. - if ($this->session->userdata('language')) { + if ($this->session->userdata('language')) + { $this->config->set_item('language', $this->session->userdata('language')); $this->lang->load('translations', $this->session->userdata('language')); - } else { + } else + { $this->lang->load('translations', $this->config->item('language')); // default } } @@ -39,15 +45,17 @@ class Installation extends CI_Controller { /** * Display the installation page. */ - public function index() { - if (is_ea_installed()) { + public function index() + { + if (is_ea_installed()) + { redirect('appointments/index'); return; } - $this->load->view('general/installation', array( + $this->load->view('general/installation', [ 'base_url' => $this->config->item('base_url') - )); + ]); } /** @@ -58,9 +66,12 @@ class Installation extends CI_Controller { * - array $_POST['admin'] Contains the initial admin user data. The App needs at least one admin user to work. * - array $_POST['company'] Contains the basic company data. */ - public function ajax_install() { - try { - if (is_ea_installed()) { + public function ajax_install() + { + try + { + if (is_ea_installed()) + { return; } @@ -68,7 +79,8 @@ class Installation extends CI_Controller { $file_contents = file_get_contents(dirname(BASEPATH) . '/assets/sql/structure.sql'); $sql_queries = explode(';', $file_contents); array_pop($sql_queries); - foreach($sql_queries as $query) { + foreach ($sql_queries as $query) + { $this->db->query($query); } @@ -76,13 +88,14 @@ class Installation extends CI_Controller { $file_contents = file_get_contents(dirname(BASEPATH) . '/assets/sql/data.sql'); $sql_queries = explode(';', $file_contents); array_pop($sql_queries); - foreach($sql_queries as $query) { + foreach ($sql_queries as $query) + { $this->db->query($query); } // Insert admin $this->load->model('admins_model'); - $admin = json_decode($_POST['admin'], true); + $admin = json_decode($_POST['admin'], TRUE); $admin['settings']['username'] = $admin['username']; $admin['settings']['password'] = $admin['password']; $admin['settings']['calendar_view'] = CALENDAR_VIEW_DEFAULT; @@ -97,7 +110,7 @@ class Installation extends CI_Controller { // Save company settings $this->load->model('settings_model'); - $company = json_decode($_POST['company'], true); + $company = json_decode($_POST['company'], TRUE); $this->settings_model->set_setting('company_name', $company['company_name']); $this->settings_model->set_setting('company_email', $company['company_email']); $this->settings_model->set_setting('company_link', $company['company_link']); @@ -114,10 +127,11 @@ class Installation extends CI_Controller { echo json_encode(AJAX_SUCCESS); - } catch (Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } } diff --git a/src/application/controllers/User.php b/src/application/controllers/User.php index f8e16ba7..85c84fea 100644 --- a/src/application/controllers/User.php +++ b/src/application/controllers/User.php @@ -1,4 +1,7 @@ -load->library('session'); // Set user's selected language. - if ($this->session->userdata('language')) { - $this->config->set_item('language', $this->session->userdata('language')); - $this->lang->load('translations', $this->session->userdata('language')); - } else { - $this->lang->load('translations', $this->config->item('language')); // default + if ($this->session->userdata('language')) + { + $this->config->set_item('language', $this->session->userdata('language')); + $this->lang->load('translations', $this->session->userdata('language')); + } else + { + $this->lang->load('translations', $this->config->item('language')); // default } } @@ -41,20 +47,23 @@ class User extends CI_Controller { * * The default method will redirect the browser to the user/login URL. */ - public function index() { + public function index() + { header('Location: ' . site_url('user/login')); } /** * Display the login page. */ - public function login() { + public function login() + { $this->load->model('settings_model'); $view['base_url'] = $this->config->item('base_url'); $view['dest_url'] = $this->session->userdata('dest_url'); - if (!$view['dest_url']) { + if ( ! $view['dest_url']) + { $view['dest_url'] = site_url('backend'); } @@ -65,7 +74,8 @@ class User extends CI_Controller { /** * Display the logout page. */ - public function logout() { + public function logout() + { $this->load->model('settings_model'); $this->session->unset_userdata('user_id'); @@ -82,7 +92,8 @@ class User extends CI_Controller { /** * Display the "forgot password" page. */ - public function forgot_password() { + public function forgot_password() + { $this->load->model('settings_model'); $view['base_url'] = $this->config->item('base_url'); $view['company_name'] = $this->settings_model->get_setting('company_name'); @@ -92,7 +103,8 @@ class User extends CI_Controller { /** * Display the "not authorized" page. */ - public function no_privileges() { + public function no_privileges() + { $this->load->model('settings_model'); $view['base_url'] = $this->config->item('base_url'); $view['company_name'] = $this->settings_model->get_setting('company_name'); @@ -108,26 +120,32 @@ class User extends CI_Controller { * - 'role_slug' * - 'dest_url' */ - public function ajax_check_login() { - try { - if (!isset($_POST['username']) || !isset($_POST['password'])) { + public function ajax_check_login() + { + try + { + if ( ! isset($_POST['username']) || ! isset($_POST['password'])) + { throw new Exception('Invalid credentials given!'); } $this->load->model('user_model'); $user_data = $this->user_model->check_login($_POST['username'], $_POST['password']); - if ($user_data) { + if ($user_data) + { $this->session->set_userdata($user_data); // Save data on user's session. echo json_encode(AJAX_SUCCESS); - } else { + } else + { echo json_encode(AJAX_FAILURE); } - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } @@ -140,11 +158,14 @@ class User extends CI_Controller { * - string $_POST['username'] Username to be validated. * - string $_POST['email'] Email to be validated. */ - public function ajax_forgot_password() { - try { - if (!isset($_POST['username']) || !isset($_POST['email'])) { + public function ajax_forgot_password() + { + try + { + if ( ! isset($_POST['username']) || ! isset($_POST['email'])) + { throw new Exception('You must enter a valid username and email address in ' - . 'order to get a new password!'); + . 'order to get a new password!'); } $this->load->model('user_model'); @@ -152,23 +173,25 @@ class User extends CI_Controller { $new_password = $this->user_model->regenerate_password($_POST['username'], $_POST['email']); - if ($new_password != FALSE) { - $this->config->load('email'); + if ($new_password != FALSE) + { + $this->config->load('email'); $email = new \EA\Engine\Notifications\Email($this, $this->config->config); - $company_settings = array( + $company_settings = [ 'company_name' => $this->settings_model->get_setting('company_name'), 'company_link' => $this->settings_model->get_setting('company_link'), 'company_email' => $this->settings_model->get_setting('company_email') - ); + ]; $email->sendPassword(new NonEmptyText($new_password), new Email($_POST['email']), $company_settings); } echo ($new_password != FALSE) ? json_encode(AJAX_SUCCESS) : json_encode(AJAX_FAILURE); - } catch(Exception $exc) { - echo json_encode(array( - 'exceptions' => array(exceptionToJavaScript($exc)) - )); + } catch (Exception $exc) + { + echo json_encode([ + 'exceptions' => [exceptionToJavaScript($exc)] + ]); } } } diff --git a/src/application/controllers/api/index.html b/src/application/controllers/api/index.html index c942a79c..423d9d58 100644 --- a/src/application/controllers/api/index.html +++ b/src/application/controllers/api/index.html @@ -1,10 +1,10 @@ - 403 Forbidden + 403 Forbidden

Directory access is forbidden.

- \ No newline at end of file + diff --git a/src/application/controllers/api/v1/API_V1_Controller.php b/src/application/controllers/api/v1/API_V1_Controller.php index 3f778c64..6778bf42 100644 --- a/src/application/controllers/api/v1/API_V1_Controller.php +++ b/src/application/controllers/api/v1/API_V1_Controller.php @@ -1,4 +1,7 @@ -_requestAuthentication(); - return; + return; } parent::__construct(); - try { + try + { $username = new NonEmptyText($_SERVER['PHP_AUTH_USER']); $password = new NonEmptyText($_SERVER['PHP_AUTH_PW']); - $authorization = new \EA\Engine\Api\V1\Authorization($this); - $authorization->basic($username, $password); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); + $authorization = new \EA\Engine\Api\V1\Authorization($this); + $authorization->basic($username, $password); + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); } } /** * Sets request authentication headers. */ - protected function _requestAuthentication() { + protected function _requestAuthentication() + { header('WWW-Authenticate: Basic realm="Easy!Appointments"'); header('HTTP/1.0 401 Unauthorized'); exit('You are not authorized to use the API.'); @@ -64,31 +72,33 @@ class API_V1_Controller extends CI_Controller { * Outputs the required headers and messages for exception handling. * * Call this method from catch blocks of child controller callbacks. - * + * * @param \Exception $exception Thrown exception to be outputted. */ - protected function _handleException(\Exception $exception) { + protected function _handleException(\Exception $exception) + { $error = [ 'code' => $exception->getCode() ?: 500, - 'message'=> $exception->getMessage(), - ]; + 'message' => $exception->getMessage(), + ]; - $header = $exception instanceof \EA\Engine\Api\V1\Exception - ? $exception->getCode() . ' ' . $exception->getHeader() + $header = $exception instanceof \EA\Engine\Api\V1\Exception + ? $exception->getCode() . ' ' . $exception->getHeader() : '500 Internal Server Error'; header('HTTP/1.0 ' . $header); header('Content-Type: application/json'); - echo json_encode($error, JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT); + echo json_encode($error, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); } /** - * Throw an API exception stating that the requested record was not found. - * + * Throw an API exception stating that the requested record was not found. + * * @throws \EA\Engine\Api\V1\Exception */ - protected function _throwRecordNotFound() { - throw new \EA\Engine\Api\V1\Exception('The requested record was not found!', 404, 'Not Found'); + protected function _throwRecordNotFound() + { + throw new \EA\Engine\Api\V1\Exception('The requested record was not found!', 404, 'Not Found'); } } diff --git a/src/application/controllers/api/v1/Admins.php b/src/application/controllers/api/v1/Admins.php index c17c96d4..66256407 100644 --- a/src/application/controllers/api/v1/Admins.php +++ b/src/application/controllers/api/v1/Admins.php @@ -1,4 +1,7 @@ -load->model('admins_model'); + $this->load->model('admins_model'); $this->parser = new \EA\Engine\Api\V1\Parsers\Admins; } /** - * GET API Method - * + * GET API Method + * * @param int $id Optional (null), the record ID to be returned. */ - public function get($id = null) { - try { - $condition = $id !== null ? 'id = ' . $id : null; - $admins = $this->admins_model->get_batch($condition); + public function get($id = NULL) + { + try + { + $condition = $id !== NULL ? 'id = ' . $id : NULL; + $admins = $this->admins_model->get_batch($condition); - if ($id !== null && count($admins) === 0) { + if ($id !== NULL && count($admins) === 0) + { $this->_throwRecordNotFound(); } $response = new Response($admins); $response->encode($this->parser) - ->search() - ->sort() - ->paginate() - ->minimize() - ->singleEntry($id) - ->output(); + ->search() + ->sort() + ->paginate() + ->minimize() + ->singleEntry($id) + ->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } @@ -72,75 +80,86 @@ class Admins extends API_V1_Controller { /** * POST API Method */ - public function post() { - try { + public function post() + { + try + { // Insert the admin to the database. - $request = new Request(); - $admin = $request->getBody(); - $this->parser->decode($admin); - - if (isset($admin['id'])) { + $request = new Request(); + $admin = $request->getBody(); + $this->parser->decode($admin); + + if (isset($admin['id'])) + { unset($admin['id']); } $id = $this->admins_model->add($admin); // Fetch the new object from the database and return it to the client. - $batch = $this->admins_model->get_batch('id = ' . $id); - $response = new Response($batch); + $batch = $this->admins_model->get_batch('id = ' . $id); + $response = new Response($batch); $status = new NonEmptyText('201 Created'); - $response->encode($this->parser)->singleEntry(true)->output($status); - } catch (\Exception $exception) { + $response->encode($this->parser)->singleEntry(TRUE)->output($status); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * PUT API Method + * PUT API Method * * @param int $id The record ID to be updated. */ - public function put($id) { - try { + public function put($id) + { + try + { // Update the admin record. - $batch = $this->admins_model->get_batch('id = ' . $id); + $batch = $this->admins_model->get_batch('id = ' . $id); - if ($id !== null && count($batch) === 0) { + if ($id !== NULL && count($batch) === 0) + { $this->_throwRecordNotFound(); } - - $request = new Request(); - $updatedAdmin = $request->getBody(); + + $request = new Request(); + $updatedAdmin = $request->getBody(); $baseAdmin = $batch[0]; - $this->parser->decode($updatedAdmin, $baseAdmin); - $updatedAdmin['id'] = $id; + $this->parser->decode($updatedAdmin, $baseAdmin); + $updatedAdmin['id'] = $id; $id = $this->admins_model->add($updatedAdmin); - + // Fetch the updated object from the database and return it to the client. - $batch = $this->admins_model->get_batch('id = ' . $id); - $response = new Response($batch); - $response->encode($this->parser)->singleEntry($id)->output(); - } catch (\Exception $exception) { + $batch = $this->admins_model->get_batch('id = ' . $id); + $response = new Response($batch); + $response->encode($this->parser)->singleEntry($id)->output(); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * DELETE API Method + * DELETE API Method * * @param int $id The record ID to be deleted. */ - public function delete($id) { - try { + public function delete($id) + { + try + { $this->admins_model->delete($id); $response = new Response([ - 'code' => 200, + 'code' => 200, 'message' => 'Record was deleted successfully!' ]); $response->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } diff --git a/src/application/controllers/api/v1/Appointments.php b/src/application/controllers/api/v1/Appointments.php index d35b37c3..00b08f41 100644 --- a/src/application/controllers/api/v1/Appointments.php +++ b/src/application/controllers/api/v1/Appointments.php @@ -1,4 +1,7 @@ -load->model('appointments_model'); $this->parser = new \EA\Engine\Api\V1\Parsers\Appointments; } /** - * GET API Method - * + * GET API Method + * * @param int $id Optional (null), the record ID to be returned. */ - public function get($id = null) { - try { - $condition = $id !== null ? 'id = ' . $id : null; - $appointments = $this->appointments_model->get_batch($condition); + public function get($id = NULL) + { + try + { + $condition = $id !== NULL ? 'id = ' . $id : NULL; + $appointments = $this->appointments_model->get_batch($condition); - if ($id !== null && count($appointments) === 0) { + if ($id !== NULL && count($appointments) === 0) + { $this->_throwRecordNotFound(); } - $response = new Response($appointments); + $response = new Response($appointments); $response->encode($this->parser) - ->search() - ->sort() - ->paginate() - ->minimize() - ->singleEntry($id) - ->output(); + ->search() + ->sort() + ->paginate() + ->minimize() + ->singleEntry($id) + ->output(); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); - } + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); + } } /** - * POST API Method + * POST API Method */ - public function post() { - try { + public function post() + { + try + { // Insert the appointment to the database. - $request = new Request(); + $request = new Request(); $appointment = $request->getBody(); - $this->parser->decode($appointment); + $this->parser->decode($appointment); - if (isset($appointment['id'])) { + if (isset($appointment['id'])) + { unset($appointment['id']); } $id = $this->appointments_model->add($appointment); // Fetch the new object from the database and return it to the client. - $batch = $this->appointments_model->get_batch('id = ' . $id); - $response = new Response($batch); + $batch = $this->appointments_model->get_batch('id = ' . $id); + $response = new Response($batch); $status = new NonEmptyText('201 Created'); - $response->encode($this->parser)->singleEntry(true)->output($status); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); - } + $response->encode($this->parser)->singleEntry(TRUE)->output($status); + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); + } } /** - * PUT API Method + * PUT API Method * * @param int $id The record ID to be updated. */ - public function put($id) { - try { + public function put($id) + { + try + { // Update the appointment record. - $batch = $this->appointments_model->get_batch('id = ' . $id); + $batch = $this->appointments_model->get_batch('id = ' . $id); - if ($id !== null && count($batch) === 0) { + if ($id !== NULL && count($batch) === 0) + { $this->_throwRecordNotFound(); } - - $request = new Request(); - $updatedAppointment = $request->getBody(); + + $request = new Request(); + $updatedAppointment = $request->getBody(); $baseAppointment = $batch[0]; - $this->parser->decode($updatedAppointment, $baseAppointment); - $updatedAppointment['id'] = $id; + $this->parser->decode($updatedAppointment, $baseAppointment); + $updatedAppointment['id'] = $id; $id = $this->appointments_model->add($updatedAppointment); - + // Fetch the updated object from the database and return it to the client. - $batch = $this->appointments_model->get_batch('id = ' . $id); - $response = new Response($batch); - $response->encode($this->parser)->singleEntry($id)->output(); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); - } + $batch = $this->appointments_model->get_batch('id = ' . $id); + $response = new Response($batch); + $response->encode($this->parser)->singleEntry($id)->output(); + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); + } } /** - * DELETE API Method + * DELETE API Method * * @param int $id The record ID to be deleted. */ - public function delete($id) { - try { + public function delete($id) + { + try + { $this->appointments_model->delete($id); $response = new Response([ - 'code' => 200, + 'code' => 200, 'message' => 'Record was deleted successfully!' ]); $response->output(); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); - } + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); + } } } diff --git a/src/application/controllers/api/v1/Availabilities.php b/src/application/controllers/api/v1/Availabilities.php index c5d50cb6..39415890 100644 --- a/src/application/controllers/api/v1/Availabilities.php +++ b/src/application/controllers/api/v1/Availabilities.php @@ -1,4 +1,7 @@ -load->model('appointments_model'); $this->load->model('providers_model'); @@ -40,26 +44,31 @@ class Availabilities extends API_V1_Controller { * Provide the "providerId", "serviceId" and "date" GET parameters to get the availabilities for a specific date. * If no "date" was provided then the current date will be used. */ - public function get() { - try { + public function get() + { + try + { $providerId = new UnsignedInteger($this->input->get('providerId')); $serviceId = new UnsignedInteger($this->input->get('serviceId')); - if ($this->input->get('date')) { + if ($this->input->get('date')) + { $date = new DateTime($this->input->get('date')); - } else { + } else + { $date = new DateTime(); } $service = $this->services_model->get_row($serviceId->get()); $emptyPeriods = $this->_getProviderAvailableTimePeriods($providerId->get(), - $date->format('Y-m-d'), []); + $date->format('Y-m-d'), []); $availableHours = $this->_calculateAvailableHours($emptyPeriods, - $date->format('Y-m-d'), $service['duration'], false, $service['availabilities_type']); + $date->format('Y-m-d'), $service['duration'], FALSE, $service['availabilities_type']); - if ($service['attendants_number'] > 1) { + if ($service['attendants_number'] > 1) + { $this->_getMultipleAttendantsHours($availableHours, $service['attendants_number'], $service['id'], $date->format('Y-m-d')); } @@ -68,7 +77,8 @@ class Availabilities extends API_V1_Controller { ->set_content_type('application/json') ->set_output(json_encode($availableHours)); - } catch(\Exception $exception) { + } catch (\Exception $exception) + { exit($this->_handleException($exception)); } } @@ -88,25 +98,31 @@ class Availabilities extends API_V1_Controller { * * @return array Returns an array with the available time periods of the provider. */ - protected function _getProviderAvailableTimePeriods($provider_id, $selected_date, - $exclude_appointments = array()) { + protected function _getProviderAvailableTimePeriods( + $provider_id, + $selected_date, + $exclude_appointments = [] + ) { $this->load->model('appointments_model'); $this->load->model('providers_model'); // Get the provider's working plan and reserved appointments. $working_plan = json_decode($this->providers_model->get_setting('working_plan', $provider_id), TRUE); - $where_clause = array( + $where_clause = [ 'id_users_provider' => $provider_id - ); + ]; $reserved_appointments = $this->appointments_model->get_batch($where_clause); // Sometimes it might be necessary to not take into account some appointment records // in order to display what the providers' available time periods would be without them. - foreach ($exclude_appointments as $excluded_id) { - foreach ($reserved_appointments as $index => $reserved) { - if ($reserved['id'] == $excluded_id) { + foreach ($exclude_appointments as $excluded_id) + { + foreach ($reserved_appointments as $index => $reserved) + { + if ($reserved['id'] == $excluded_id) + { unset($reserved_appointments[$index]); } } @@ -116,60 +132,70 @@ class Availabilities extends API_V1_Controller { // a break (if exist). After that every reserved appointment is considered to be // a taken space in the plan. $selected_date_working_plan = $working_plan[strtolower(date('l', strtotime($selected_date)))]; - $available_periods_with_breaks = array(); + $available_periods_with_breaks = []; - if (isset($selected_date_working_plan['breaks'])) { + if (isset($selected_date_working_plan['breaks'])) + { $start = new DateTime($selected_date_working_plan['start']); $end = new DateTime($selected_date_working_plan['end']); - $available_periods_with_breaks[] = array( + $available_periods_with_breaks[] = [ 'start' => $selected_date_working_plan['start'], 'end' => $selected_date_working_plan['end'] - ); + ]; // Split the working plan to available time periods that do not contain the breaks in them. - foreach ($selected_date_working_plan['breaks'] as $index => $break) { + foreach ($selected_date_working_plan['breaks'] as $index => $break) + { $break_start = new DateTime($break['start']); $break_end = new DateTime($break['end']); - if ($break_start < $start) { + if ($break_start < $start) + { $break_start = $start; } - if ($break_end > $end) { + if ($break_end > $end) + { $break_end = $end; } - if ($break_start >= $break_end) { + if ($break_start >= $break_end) + { continue; } - foreach ($available_periods_with_breaks as $key => $open_period) { + foreach ($available_periods_with_breaks as $key => $open_period) + { $s = new DateTime($open_period['start']); $e = new DateTime($open_period['end']); - if ($s < $break_end && $break_start < $e) { // check for overlap + if ($s < $break_end && $break_start < $e) + { // check for overlap $changed = FALSE; - if ($s < $break_start) { + if ($s < $break_start) + { $open_start = $s; $open_end = $break_start; - $available_periods_with_breaks[] = array( + $available_periods_with_breaks[] = [ 'start' => $open_start->format("H:i"), 'end' => $open_end->format("H:i") - ); + ]; $changed = TRUE; } - if ($break_end < $e) { + if ($break_end < $e) + { $open_start = $break_end; $open_end = $e; - $available_periods_with_breaks[] = array( + $available_periods_with_breaks[] = [ 'start' => $open_start->format("H:i"), 'end' => $open_end->format("H:i") - ); + ]; $changed = TRUE; } - if ($changed) { + if ($changed) + { unset($available_periods_with_breaks[$key]); } } @@ -180,41 +206,64 @@ class Availabilities extends API_V1_Controller { // Break the empty periods with the reserved appointments. $available_periods_with_appointments = $available_periods_with_breaks; - foreach($reserved_appointments as $appointment) { - foreach($available_periods_with_appointments as $index => &$period) { + foreach ($reserved_appointments as $appointment) + { + foreach ($available_periods_with_appointments as $index => &$period) + { $a_start = strtotime($appointment['start_datetime']); - $a_end = strtotime($appointment['end_datetime']); - $p_start = strtotime($selected_date . ' ' . $period['start']); - $p_end = strtotime($selected_date . ' ' .$period['end']); + $a_end = strtotime($appointment['end_datetime']); + $p_start = strtotime($selected_date . ' ' . $period['start']); + $p_end = strtotime($selected_date . ' ' . $period['end']); - if ($a_start <= $p_start && $a_end <= $p_end && $a_end <= $p_start) { + if ($a_start <= $p_start && $a_end <= $p_end && $a_end <= $p_start) + { // The appointment does not belong in this time period, so we // will not change anything. - } else if ($a_start <= $p_start && $a_end <= $p_end && $a_end >= $p_start) { - // The appointment starts before the period and finishes somewhere inside. - // We will need to break this period and leave the available part. - $period['start'] = date('H:i', $a_end); - } else if ($a_start >= $p_start && $a_end <= $p_end) { - // The appointment is inside the time period, so we will split the period - // into two new others. - unset($available_periods_with_appointments[$index]); - $available_periods_with_appointments[] = array( - 'start' => date('H:i', $p_start), - 'end' => date('H:i', $a_start) - ); - $available_periods_with_appointments[] = array( - 'start' => date('H:i', $a_end), - 'end' => date('H:i', $p_end) - ); - } else if ($a_start >= $p_start && $a_end >= $p_start && $a_start <= $p_end) { - // The appointment starts in the period and finishes out of it. We will - // need to remove the time that is taken from the appointment. - $period['end'] = date('H:i', $a_start); - } else if ($a_start >= $p_start && $a_end >= $p_end && $a_start >= $p_end) { - // The appointment does not belong in the period so do not change anything. - } else if ($a_start <= $p_start && $a_end >= $p_end && $a_start <= $p_end) { - // The appointment is bigger than the period, so this period needs to be removed. - unset($available_periods_with_appointments[$index]); + } else + { + if ($a_start <= $p_start && $a_end <= $p_end && $a_end >= $p_start) + { + // The appointment starts before the period and finishes somewhere inside. + // We will need to break this period and leave the available part. + $period['start'] = date('H:i', $a_end); + } else + { + if ($a_start >= $p_start && $a_end <= $p_end) + { + // The appointment is inside the time period, so we will split the period + // into two new others. + unset($available_periods_with_appointments[$index]); + $available_periods_with_appointments[] = [ + 'start' => date('H:i', $p_start), + 'end' => date('H:i', $a_start) + ]; + $available_periods_with_appointments[] = [ + 'start' => date('H:i', $a_end), + 'end' => date('H:i', $p_end) + ]; + } else + { + if ($a_start >= $p_start && $a_end >= $p_start && $a_start <= $p_end) + { + // The appointment starts in the period and finishes out of it. We will + // need to remove the time that is taken from the appointment. + $period['end'] = date('H:i', $a_start); + } else + { + if ($a_start >= $p_start && $a_end >= $p_end && $a_start >= $p_end) + { + // The appointment does not belong in the period so do not change anything. + } else + { + if ($a_start <= $p_start && $a_end >= $p_end && $a_start <= $p_end) + { + // The appointment is bigger than the period, so this period needs to be removed. + unset($available_periods_with_appointments[$index]); + } + } + } + } + } } } } @@ -238,13 +287,19 @@ class Availabilities extends API_V1_Controller { * * @return array Returns an array with the available hours for the appointment. */ - protected function _calculateAvailableHours(array $empty_periods, $selected_date, $service_duration, - $manage_mode = FALSE, $availabilities_type = 'flexible') { + protected function _calculateAvailableHours( + array $empty_periods, + $selected_date, + $service_duration, + $manage_mode = FALSE, + $availabilities_type = 'flexible' + ) { $this->load->model('settings_model'); - $available_hours = array(); + $available_hours = []; - foreach ($empty_periods as $period) { + foreach ($empty_periods as $period) + { $start_hour = new DateTime($selected_date . ' ' . $period['start']); $end_hour = new DateTime($selected_date . ' ' . $period['end']); $interval = $availabilities_type === AVAILABILITIES_TYPE_FIXED ? (int)$service_duration : 15; @@ -252,7 +307,8 @@ class Availabilities extends API_V1_Controller { $current_hour = $start_hour; $diff = $current_hour->diff($end_hour); - while (($diff->h * 60 + $diff->i) >= intval($service_duration)) { + while (($diff->h * 60 + $diff->i) >= intval($service_duration)) + { $available_hours[] = $current_hour->format('H:i'); $current_hour->add(new DateInterval('PT' . $interval . 'M')); $diff = $current_hour->diff($end_hour); @@ -262,20 +318,23 @@ class Availabilities extends API_V1_Controller { // If the selected date is today, remove past hours. It is important include the timeout before // booking that is set in the back-office the system. Normally we might want the customer to book // an appointment that is at least half or one hour from now. The setting is stored in minutes. - if (date('m/d/Y', strtotime($selected_date)) === date('m/d/Y')) { + if (date('m/d/Y', strtotime($selected_date)) === date('m/d/Y')) + { $book_advance_timeout = $this->settings_model->get_setting('book_advance_timeout'); - foreach($available_hours as $index => $value) { + foreach ($available_hours as $index => $value) + { $available_hour = strtotime($value); $current_hour = strtotime('+' . $book_advance_timeout . ' minutes', strtotime('now')); - if ($available_hour <= $current_hour) { + if ($available_hour <= $current_hour) + { unset($available_hours[$index]); } } } $available_hours = array_values($available_hours); - sort($available_hours, SORT_STRING ); + sort($available_hours, SORT_STRING); $available_hours = array_values($available_hours); return $available_hours; @@ -291,25 +350,31 @@ class Availabilities extends API_V1_Controller { * @param int $service_id Selected service ID. * @param string $selected_date The selected appointment date. */ - protected function _getMultipleAttendantsHours(&$available_hours, $attendants_number, $service_id, - $selected_date) { + protected function _getMultipleAttendantsHours( + &$available_hours, + $attendants_number, + $service_id, + $selected_date + ) { $this->load->model('appointments_model'); $appointments = $this->appointments_model->get_batch( 'id_services = ' . $this->db->escape($service_id) . ' AND DATE(start_datetime) = DATE(' . $this->db->escape(date('Y-m-d', strtotime($selected_date))) . ')'); - foreach($appointments as $appointment) { + foreach ($appointments as $appointment) + { $hour = date('H:i', strtotime($appointment['start_datetime'])); $current_attendants_number = $this->appointments_model->appointment_count_for_hour($service_id, - $selected_date, $hour); - if ($current_attendants_number < $attendants_number && !in_array($hour, $available_hours)) { + $selected_date, $hour); + if ($current_attendants_number < $attendants_number && ! in_array($hour, $available_hours)) + { $available_hours[] = $hour; } } $available_hours = array_values($available_hours); - sort($available_hours, SORT_STRING ); - $available_hours = array_values($available_hours); + sort($available_hours, SORT_STRING); + $available_hours = array_values($available_hours); } } diff --git a/src/application/controllers/api/v1/Categories.php b/src/application/controllers/api/v1/Categories.php index 4df8bdcd..cb861cdb 100644 --- a/src/application/controllers/api/v1/Categories.php +++ b/src/application/controllers/api/v1/Categories.php @@ -1,4 +1,7 @@ -load->model('services_model'); + $this->load->model('services_model'); $this->parser = new \EA\Engine\Api\V1\Parsers\Categories; } /** - * GET API Method - * + * GET API Method + * * @param int $id Optional (null), the record ID to be returned. */ - public function get($id = null) { - try { - $condition = $id !== null ? 'id = ' . $id : ''; - $categories = $this->services_model->get_all_categories($condition); + public function get($id = NULL) + { + try + { + $condition = $id !== NULL ? 'id = ' . $id : ''; + $categories = $this->services_model->get_all_categories($condition); - if ($id !== null && count($categories) === 0) { + if ($id !== NULL && count($categories) === 0) + { $this->_throwRecordNotFound(); } $response = new Response($categories); $response->encode($this->parser) - ->search() - ->sort() - ->paginate() - ->minimize() - ->singleEntry($id) - ->output(); + ->search() + ->sort() + ->paginate() + ->minimize() + ->singleEntry($id) + ->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } @@ -72,75 +80,86 @@ class Categories extends API_V1_Controller { /** * POST API Method */ - public function post() { - try { + public function post() + { + try + { // Insert the category to the database. - $request = new Request(); - $category = $request->getBody(); - $this->parser->decode($category); - - if (isset($category['id'])) { + $request = new Request(); + $category = $request->getBody(); + $this->parser->decode($category); + + if (isset($category['id'])) + { unset($category['id']); } $id = $this->services_model->add_category($category); // Fetch the new object from the database and return it to the client. - $batch = $this->services_model->get_all_categories('id = ' . $id); - $response = new Response($batch); + $batch = $this->services_model->get_all_categories('id = ' . $id); + $response = new Response($batch); $status = new NonEmptyText('201 Created'); - $response->encode($this->parser)->singleEntry(true)->output($status); - } catch (\Exception $exception) { + $response->encode($this->parser)->singleEntry(TRUE)->output($status); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * PUT API Method + * PUT API Method * - * @param int $id The record ID to be updated. + * @param int $id The record ID to be updated. */ - public function put($id) { - try { + public function put($id) + { + try + { // Update the category record. - $batch = $this->services_model->get_all_categories('id = ' . $id); + $batch = $this->services_model->get_all_categories('id = ' . $id); - if ($id !== null && count($batch) === 0) { + if ($id !== NULL && count($batch) === 0) + { $this->_throwRecordNotFound(); } - - $request = new Request(); - $updatedCategory = $request->getBody(); + + $request = new Request(); + $updatedCategory = $request->getBody(); $baseCategory = $batch[0]; - $this->parser->decode($updatedCategory, $baseCategory); - $updatedCategory['id'] = $id; + $this->parser->decode($updatedCategory, $baseCategory); + $updatedCategory['id'] = $id; $id = $this->services_model->add_category($updatedCategory); - + // Fetch the updated object from the database and return it to the client. - $batch = $this->services_model->get_all_categories('id = ' . $id); - $response = new Response($batch); - $response->encode($this->parser)->singleEntry($id)->output(); - } catch (\Exception $exception) { + $batch = $this->services_model->get_all_categories('id = ' . $id); + $response = new Response($batch); + $response->encode($this->parser)->singleEntry($id)->output(); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * DELETE API Method + * DELETE API Method * - * @param int $id The record ID to be deleted. + * @param int $id The record ID to be deleted. */ - public function delete($id) { - try { + public function delete($id) + { + try + { $result = $this->services_model->delete_category($id); $response = new Response([ - 'code' => 200, + 'code' => 200, 'message' => 'Record was deleted successfully!' ]); $response->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } diff --git a/src/application/controllers/api/v1/Customers.php b/src/application/controllers/api/v1/Customers.php index ad38b151..37ca2569 100644 --- a/src/application/controllers/api/v1/Customers.php +++ b/src/application/controllers/api/v1/Customers.php @@ -1,4 +1,7 @@ -load->model('customers_model'); + $this->load->model('customers_model'); $this->parser = new \EA\Engine\Api\V1\Parsers\Customers; } /** - * GET API Method - * + * GET API Method + * * @param int $id Optional (null), the record ID to be returned. */ - public function get($id = null) { - try { - $condition = $id !== null ? 'id = ' . $id : null; - $customers = $this->customers_model->get_batch($condition); + public function get($id = NULL) + { + try + { + $condition = $id !== NULL ? 'id = ' . $id : NULL; + $customers = $this->customers_model->get_batch($condition); - if ($id !== null && count($customers) === 0) { + if ($id !== NULL && count($customers) === 0) + { $this->_throwRecordNotFound(); } $response = new Response($customers); $response->encode($this->parser) - ->search() - ->sort() - ->paginate() - ->minimize() - ->singleEntry($id) - ->output(); + ->search() + ->sort() + ->paginate() + ->minimize() + ->singleEntry($id) + ->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * POST API Method + * POST API Method */ - public function post() { - try { + public function post() + { + try + { // Insert the customer to the database. - $request = new Request(); - $customer = $request->getBody(); - $this->parser->decode($customer); - - if (isset($customer['id'])) { + $request = new Request(); + $customer = $request->getBody(); + $this->parser->decode($customer); + + if (isset($customer['id'])) + { unset($customer['id']); } $id = $this->customers_model->add($customer); // Fetch the new object from the database and return it to the client. - $batch = $this->customers_model->get_batch('id = ' . $id); - $response = new Response($batch); + $batch = $this->customers_model->get_batch('id = ' . $id); + $response = new Response($batch); $status = new NonEmptyText('201 Created'); - $response->encode($this->parser)->singleEntry(true)->output($status); - } catch (\Exception $exception) { + $response->encode($this->parser)->singleEntry(TRUE)->output($status); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * PUT API Method + * PUT API Method * * @param int $id The record ID to be updated. */ - public function put($id) { - try { + public function put($id) + { + try + { // Update the customer record. - $batch = $this->customers_model->get_batch('id = ' . $id); + $batch = $this->customers_model->get_batch('id = ' . $id); - if ($id !== null && count($batch) === 0) { + if ($id !== NULL && count($batch) === 0) + { $this->_throwRecordNotFound(); } - - $request = new Request(); - $updatedCustomer = $request->getBody(); + + $request = new Request(); + $updatedCustomer = $request->getBody(); $baseCustomer = $batch[0]; - $this->parser->decode($updatedCustomer, $baseCustomer); - $updatedCustomer['id'] = $id; + $this->parser->decode($updatedCustomer, $baseCustomer); + $updatedCustomer['id'] = $id; $id = $this->customers_model->add($updatedCustomer); - + // Fetch the updated object from the database and return it to the client. - $batch = $this->customers_model->get_batch('id = ' . $id); - $response = new Response($batch); - $response->encode($this->parser)->singleEntry($id)->output(); - } catch (\Exception $exception) { + $batch = $this->customers_model->get_batch('id = ' . $id); + $response = new Response($batch); + $response->encode($this->parser)->singleEntry($id)->output(); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * DELETE API Method + * DELETE API Method * * @param int $id The record ID to be deleted. */ - public function delete($id) { - try { + public function delete($id) + { + try + { $result = $this->customers_model->delete($id); $response = new Response([ - 'code' => 200, + 'code' => 200, 'message' => 'Record was deleted successfully!' ]); $response->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } diff --git a/src/application/controllers/api/v1/Providers.php b/src/application/controllers/api/v1/Providers.php index 5a0d5f2c..c5b2f582 100644 --- a/src/application/controllers/api/v1/Providers.php +++ b/src/application/controllers/api/v1/Providers.php @@ -1,4 +1,7 @@ -load->model('providers_model'); + $this->load->model('providers_model'); $this->parser = new \EA\Engine\Api\V1\Parsers\Providers; } /** - * GET API Method - * - * @param int $id Optional (null), the record ID to be returned. + * GET API Method + * + * @param int $id Optional (null), the record ID to be returned. */ - public function get($id = null) { - try { - $condition = $id !== null ? 'id = ' . $id : null; - $providers = $this->providers_model->get_batch($condition); + public function get($id = NULL) + { + try + { + $condition = $id !== NULL ? 'id = ' . $id : NULL; + $providers = $this->providers_model->get_batch($condition); - if ($id !== null && count($providers) === 0) { + if ($id !== NULL && count($providers) === 0) + { $this->_throwRecordNotFound(); } $response = new Response($providers); $response->encode($this->parser) - ->search() - ->sort() - ->paginate() - ->minimize() - ->singleEntry($id) - ->output(); + ->search() + ->sort() + ->paginate() + ->minimize() + ->singleEntry($id) + ->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * POST API Method + * POST API Method */ - public function post() { - try { + public function post() + { + try + { // Insert the provider to the database. - $request = new Request(); - $provider = $request->getBody(); - $this->parser->decode($provider); - - if (isset($provider['id'])) { + $request = new Request(); + $provider = $request->getBody(); + $this->parser->decode($provider); + + if (isset($provider['id'])) + { unset($provider['id']); } $id = $this->providers_model->add($provider); // Fetch the new object from the database and return it to the client. - $batch = $this->providers_model->get_batch('id = ' . $id); - $response = new Response($batch); + $batch = $this->providers_model->get_batch('id = ' . $id); + $response = new Response($batch); $status = new NonEmptyText('201 Created'); - $response->encode($this->parser)->singleEntry(true)->output($status); - } catch (\Exception $exception) { + $response->encode($this->parser)->singleEntry(TRUE)->output($status); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * PUT API Method + * PUT API Method * - * @param int $id The record ID to be updated. + * @param int $id The record ID to be updated. */ - public function put($id) { - try { + public function put($id) + { + try + { // Update the provider record. - $batch = $this->providers_model->get_batch('id = ' . $id); + $batch = $this->providers_model->get_batch('id = ' . $id); - if ($id !== null && count($batch) === 0) { + if ($id !== NULL && count($batch) === 0) + { $this->_throwRecordNotFound(); } - - $request = new Request(); - $updatedProvider = $request->getBody(); + + $request = new Request(); + $updatedProvider = $request->getBody(); $baseProvider = $batch[0]; - $this->parser->decode($updatedProvider, $baseProvider); - $updatedProvider['id'] = $id; + $this->parser->decode($updatedProvider, $baseProvider); + $updatedProvider['id'] = $id; $id = $this->providers_model->add($updatedProvider); - + // Fetch the updated object from the database and return it to the client. - $batch = $this->providers_model->get_batch('id = ' . $id); - $response = new Response($batch); - $response->encode($this->parser)->singleEntry($id)->output(); - } catch (\Exception $exception) { + $batch = $this->providers_model->get_batch('id = ' . $id); + $response = new Response($batch); + $response->encode($this->parser)->singleEntry($id)->output(); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * DELETE API Method + * DELETE API Method * - * @param int $id The record ID to be deleted. + * @param int $id The record ID to be deleted. */ - public function delete($id) { - try { + public function delete($id) + { + try + { $result = $this->providers_model->delete($id); $response = new Response([ - 'code' => 200, + 'code' => 200, 'message' => 'Record was deleted successfully!' ]); $response->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } diff --git a/src/application/controllers/api/v1/Secretaries.php b/src/application/controllers/api/v1/Secretaries.php index 0fdfbacf..eab7a347 100644 --- a/src/application/controllers/api/v1/Secretaries.php +++ b/src/application/controllers/api/v1/Secretaries.php @@ -1,4 +1,7 @@ -load->model('secretaries_model'); + $this->load->model('secretaries_model'); $this->parser = new \EA\Engine\Api\V1\Parsers\Secretaries; } /** - * GET API Method - * + * GET API Method + * * @param int $id Optional (null), the record ID to be returned. */ - public function get($id = null) { - try { - $condition = $id !== null ? 'id = ' . $id : null; - $secretaries = $this->secretaries_model->get_batch($condition); + public function get($id = NULL) + { + try + { + $condition = $id !== NULL ? 'id = ' . $id : NULL; + $secretaries = $this->secretaries_model->get_batch($condition); - if ($id !== null && count($secretaries) === 0) { + if ($id !== NULL && count($secretaries) === 0) + { $this->_throwRecordNotFound(); } $response = new Response($secretaries); $response->encode($this->parser) - ->search() - ->sort() - ->paginate() - ->minimize() - ->singleEntry($id) - ->output(); + ->search() + ->sort() + ->paginate() + ->minimize() + ->singleEntry($id) + ->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * POST API Method + * POST API Method */ - public function post() { - try { + public function post() + { + try + { // Insert the secretary to the database. - $request = new Request(); - $secretary = $request->getBody(); - $this->parser->decode($secretary); - - if (isset($secretary['id'])) { + $request = new Request(); + $secretary = $request->getBody(); + $this->parser->decode($secretary); + + if (isset($secretary['id'])) + { unset($secretary['id']); } $id = $this->secretaries_model->add($secretary); // Fetch the new object from the database and return it to the client. - $batch = $this->secretaries_model->get_batch('id = ' . $id); - $response = new Response($batch); + $batch = $this->secretaries_model->get_batch('id = ' . $id); + $response = new Response($batch); $status = new NonEmptyText('201 Created'); - $response->encode($this->parser)->singleEntry(true)->output($status); - } catch (\Exception $exception) { + $response->encode($this->parser)->singleEntry(TRUE)->output($status); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * PUT API Method + * PUT API Method * * @param int $id The record ID to be updated. */ - public function put($id) { - try { + public function put($id) + { + try + { // Update the secretary record. - $batch = $this->secretaries_model->get_batch('id = ' . $id); + $batch = $this->secretaries_model->get_batch('id = ' . $id); - if ($id !== null && count($batch) === 0) { + if ($id !== NULL && count($batch) === 0) + { $this->_throwRecordNotFound(); } - - $request = new Request(); - $updatedSecretary = $request->getBody(); + + $request = new Request(); + $updatedSecretary = $request->getBody(); $baseSecretary = $batch[0]; - $this->parser->decode($updatedSecretary, $baseSecretary); - $updatedSecretary['id'] = $id; + $this->parser->decode($updatedSecretary, $baseSecretary); + $updatedSecretary['id'] = $id; $id = $this->secretaries_model->add($updatedSecretary); - + // Fetch the updated object from the database and return it to the client. - $batch = $this->secretaries_model->get_batch('id = ' . $id); - $response = new Response($batch); - $response->encode($this->parser)->singleEntry($id)->output(); - } catch (\Exception $exception) { + $batch = $this->secretaries_model->get_batch('id = ' . $id); + $response = new Response($batch); + $response->encode($this->parser)->singleEntry($id)->output(); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * DELETE API Method + * DELETE API Method * - * @param int $id The record ID to be deleted. + * @param int $id The record ID to be deleted. */ - public function delete($id) { - try { + public function delete($id) + { + try + { $result = $this->secretaries_model->delete($id); $response = new Response([ - 'code' => 200, + 'code' => 200, 'message' => 'Record was deleted successfully!' ]); $response->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } diff --git a/src/application/controllers/api/v1/Services.php b/src/application/controllers/api/v1/Services.php index 4979dc3c..4a2c77e6 100644 --- a/src/application/controllers/api/v1/Services.php +++ b/src/application/controllers/api/v1/Services.php @@ -1,4 +1,7 @@ -load->model('services_model'); + $this->load->model('services_model'); $this->parser = new \EA\Engine\Api\V1\Parsers\Services; } /** - * GET API Method - * + * GET API Method + * * @param int $id Optional (null), the record ID to be returned. */ - public function get($id = null) { - try { - $condition = $id !== null ? 'id = ' . $id : null; - $services = $this->services_model->get_batch($condition); + public function get($id = NULL) + { + try + { + $condition = $id !== NULL ? 'id = ' . $id : NULL; + $services = $this->services_model->get_batch($condition); - if ($id !== null && count($services) === 0) { + if ($id !== NULL && count($services) === 0) + { $this->_throwRecordNotFound(); } $response = new Response($services); $response->encode($this->parser) - ->search() - ->sort() - ->paginate() - ->minimize() - ->singleEntry($id) - ->output(); + ->search() + ->sort() + ->paginate() + ->minimize() + ->singleEntry($id) + ->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * POST API Method + * POST API Method */ - public function post() { - try { + public function post() + { + try + { // Insert the service to the database. - $request = new Request(); - $service = $request->getBody(); - $this->parser->decode($service); - - if (isset($service['id'])) { + $request = new Request(); + $service = $request->getBody(); + $this->parser->decode($service); + + if (isset($service['id'])) + { unset($service['id']); } $id = $this->services_model->add($service); // Fetch the new object from the database and return it to the client. - $batch = $this->services_model->get_batch('id = ' . $id); - $response = new Response($batch); + $batch = $this->services_model->get_batch('id = ' . $id); + $response = new Response($batch); $status = new NonEmptyText('201 Created'); - $response->encode($this->parser)->singleEntry(true)->output($status); - } catch (\Exception $exception) { + $response->encode($this->parser)->singleEntry(TRUE)->output($status); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * PUT API Method + * PUT API Method * * @param int $id The record ID to be updated. */ - public function put($id) { - try { + public function put($id) + { + try + { // Update the service record. - $batch = $this->services_model->get_batch('id = ' . $id); + $batch = $this->services_model->get_batch('id = ' . $id); - if ($id !== null && count($batch) === 0) { + if ($id !== NULL && count($batch) === 0) + { $this->_throwRecordNotFound(); } - - $request = new Request(); - $updatedService = $request->getBody(); + + $request = new Request(); + $updatedService = $request->getBody(); $baseService = $batch[0]; - $this->parser->decode($updatedService, $baseService); - $updatedService['id'] = $id; + $this->parser->decode($updatedService, $baseService); + $updatedService['id'] = $id; $id = $this->services_model->add($updatedService); - + // Fetch the updated object from the database and return it to the client. - $batch = $this->services_model->get_batch('id = ' . $id); - $response = new Response($batch); - $response->encode($this->parser)->singleEntry($id)->output(); - } catch (\Exception $exception) { + $batch = $this->services_model->get_batch('id = ' . $id); + $response = new Response($batch); + $response->encode($this->parser)->singleEntry($id)->output(); + } catch (\Exception $exception) + { $this->_handleException($exception); } } /** - * DELETE API Method + * DELETE API Method * * @param int $id The record ID to be deleted. */ - public function delete($id) { - try { + public function delete($id) + { + try + { $result = $this->services_model->delete($id); $response = new Response([ - 'code' => 200, + 'code' => 200, 'message' => 'Record was deleted successfully!' ]); $response->output(); - } catch (\Exception $exception) { + } catch (\Exception $exception) + { $this->_handleException($exception); } } diff --git a/src/application/controllers/api/v1/Settings.php b/src/application/controllers/api/v1/Settings.php index 1c8268f9..c84dee00 100644 --- a/src/application/controllers/api/v1/Settings.php +++ b/src/application/controllers/api/v1/Settings.php @@ -1,4 +1,7 @@ -load->model('settings_model'); $this->parser = new \EA\Engine\Api\V1\Parsers\Settings; } /** - * GET API Method - * + * GET API Method + * * @param string $name Optional (null), the setting name to be returned. */ - public function get($name = null) { - try { - $settings = $this->settings_model->get_settings(); + public function get($name = NULL) + { + try + { + $settings = $this->settings_model->get_settings(); - if ($name !== null) { - $setting = null; + if ($name !== NULL) + { + $setting = NULL; - foreach ($settings as $entry) { - if ($entry['name'] === $name) { + foreach ($settings as $entry) + { + if ($entry['name'] === $name) + { $setting = $entry; break; } } - if (empty($setting)) { + if (empty($setting)) + { $this->_throwRecordNotFound(); } @@ -66,65 +76,72 @@ class Settings extends API_V1_Controller { $settings = [ $setting - ]; - } + ]; + } - $response = new Response($settings); + $response = new Response($settings); $response->encode($this->parser) - ->search() - ->sort() - ->paginate() - ->minimize() - ->singleEntry($name) - ->output(); + ->search() + ->sort() + ->paginate() + ->minimize() + ->singleEntry($name) + ->output(); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); } } /** - * PUT API Method + * PUT API Method * * @param string $name The setting name to be inserted/updated. */ - public function put($name) { - try { - $request = new Request(); - $value = $request->getBody()['value']; - $this->settings_model->set_setting($name, $value); - + public function put($name) + { + try + { + $request = new Request(); + $value = $request->getBody()['value']; + $this->settings_model->set_setting($name, $value); + // Fetch the updated object from the database and return it to the client. $response = new Response([ [ 'name' => $name, 'value' => $value ] - ]); - $response->encode($this->parser)->singleEntry($name)->output(); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); - } + ]); + $response->encode($this->parser)->singleEntry($name)->output(); + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); + } } /** - * DELETE API Method + * DELETE API Method * - * @param string $name The setting name to be deleted. + * @param string $name The setting name to be deleted. */ - public function delete($name) { - try { + public function delete($name) + { + try + { $result = $this->settings_model->remove_setting($name); $response = new Response([ - 'code' => 200, + 'code' => 200, 'message' => 'Record was deleted successfully!' ]); $response->output(); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); - } + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); + } } } diff --git a/src/application/controllers/api/v1/Unavailabilities.php b/src/application/controllers/api/v1/Unavailabilities.php index bfcd8d4c..c2910ecc 100644 --- a/src/application/controllers/api/v1/Unavailabilities.php +++ b/src/application/controllers/api/v1/Unavailabilities.php @@ -1,4 +1,7 @@ -load->model('appointments_model'); $this->parser = new \EA\Engine\Api\V1\Parsers\Unavailabilities; } /** - * GET API Method - * - * @param int $id Optional (null), the record ID to be returned. + * GET API Method + * + * @param int $id Optional (null), the record ID to be returned. */ - public function get($id = null) { - try { - $condition = $id !== null ? 'id = ' . $id : 'is_unavailable = 1'; - $unavailabilities = $this->appointments_model->get_batch($condition); + public function get($id = NULL) + { + try + { + $condition = $id !== NULL ? 'id = ' . $id : 'is_unavailable = 1'; + $unavailabilities = $this->appointments_model->get_batch($condition); - if ($id !== null && count($unavailabilities) === 0) { + if ($id !== NULL && count($unavailabilities) === 0) + { $this->_throwRecordNotFound(); } - $response = new Response($unavailabilities); + $response = new Response($unavailabilities); $response->encode($this->parser) - ->search() - ->sort() - ->paginate() - ->minimize() - ->singleEntry($id) - ->output(); + ->search() + ->sort() + ->paginate() + ->minimize() + ->singleEntry($id) + ->output(); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); - } + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); + } } /** * POST API Method */ - public function post() { - try { + public function post() + { + try + { // Insert the appointment to the database. - $request = new Request(); + $request = new Request(); $unavailability = $request->getBody(); - $this->parser->decode($unavailability); + $this->parser->decode($unavailability); - if (isset($unavailability['id'])) { + if (isset($unavailability['id'])) + { unset($unavailability['id']); } $id = $this->appointments_model->add_unavailable($unavailability); // Fetch the new object from the database and return it to the client. - $batch = $this->appointments_model->get_batch('id = ' . $id); - $response = new Response($batch); + $batch = $this->appointments_model->get_batch('id = ' . $id); + $response = new Response($batch); $status = new NonEmptyText('201 Created'); - $response->encode($this->parser)->singleEntry(true)->output($status); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); - } + $response->encode($this->parser)->singleEntry(TRUE)->output($status); + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); + } } /** - * PUT API Method + * PUT API Method * - * @param int $id The record ID to be updated. + * @param int $id The record ID to be updated. */ - public function put($id) { - try { + public function put($id) + { + try + { // Update the appointment record. - $batch = $this->appointments_model->get_batch('id = ' . $id); + $batch = $this->appointments_model->get_batch('id = ' . $id); - if ($id !== null && count($batch) === 0) { + if ($id !== NULL && count($batch) === 0) + { $this->_throwRecordNotFound(); } - - $request = new Request(); - $updatedUnavailability = $request->getBody(); + + $request = new Request(); + $updatedUnavailability = $request->getBody(); $baseUnavailability = $batch[0]; - $this->parser->decode($updatedUnavailability, $baseUnavailability); - $updatedUnavailability['id'] = $id; + $this->parser->decode($updatedUnavailability, $baseUnavailability); + $updatedUnavailability['id'] = $id; $id = $this->appointments_model->add_unavailable($updatedUnavailability); - + // Fetch the updated object from the database and return it to the client. - $batch = $this->appointments_model->get_batch('id = ' . $id); - $response = new Response($batch); - $response->encode($this->parser)->singleEntry($id)->output(); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); - } + $batch = $this->appointments_model->get_batch('id = ' . $id); + $response = new Response($batch); + $response->encode($this->parser)->singleEntry($id)->output(); + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); + } } /** - * DELETE API Method + * DELETE API Method * * @param int $id The record ID to be deleted. */ - public function delete($id) { - try { + public function delete($id) + { + try + { $result = $this->appointments_model->delete_unavailable($id); $response = new Response([ - 'code' => 200, + 'code' => 200, 'message' => 'Record was deleted successfully!' ]); $response->output(); - } catch(\Exception $exception) { - exit($this->_handleException($exception)); - } + } catch (\Exception $exception) + { + exit($this->_handleException($exception)); + } } } diff --git a/src/application/controllers/api/v1/index.html b/src/application/controllers/api/v1/index.html index c942a79c..423d9d58 100644 --- a/src/application/controllers/api/v1/index.html +++ b/src/application/controllers/api/v1/index.html @@ -1,10 +1,10 @@ - 403 Forbidden + 403 Forbidden

Directory access is forbidden.

- \ No newline at end of file + diff --git a/src/application/controllers/index.html b/src/application/controllers/index.html index c942a79c..423d9d58 100644 --- a/src/application/controllers/index.html +++ b/src/application/controllers/index.html @@ -1,10 +1,10 @@ - 403 Forbidden + 403 Forbidden

Directory access is forbidden.

- \ No newline at end of file + diff --git a/src/application/helpers/custom_exceptions_helper.php b/src/application/helpers/custom_exceptions_helper.php index 2b3c05ce..b5eaa042 100644 --- a/src/application/helpers/custom_exceptions_helper.php +++ b/src/application/helpers/custom_exceptions_helper.php @@ -1,4 +1,7 @@ -
@@ -71,13 +79,14 @@ function exceptionToHtml($exc) { * @param Exception $exception The given exception object. * @return string Returns the json encoded object of the exception. */ -function exceptionToJavaScript($exception) { - return json_encode(array( +function exceptionToJavaScript($exception) +{ + return json_encode([ 'code' => $exception->getCode(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'message' => $exception->getMessage(), 'previous' => $exception->getPrevious(), 'trace' => $exception->getTraceAsString() - )); + ]); } diff --git a/src/application/helpers/data_validation_helper.php b/src/application/helpers/data_validation_helper.php index 119d3301..3faa6671 100644 --- a/src/application/helpers/data_validation_helper.php +++ b/src/application/helpers/data_validation_helper.php @@ -1,4 +1,7 @@ -load->model('settings_model'); $google_analytics_code = $ci->settings_model->get_setting('google_analytics_code'); - if ($google_analytics_code !== '') { + if ($google_analytics_code !== '') + { echo '