From c8a9e2c24bb9d2d01710975f0969bca03b38fc3c Mon Sep 17 00:00:00 2001 From: Alex Tselegidis Date: Wed, 29 Nov 2023 10:24:09 +0100 Subject: [PATCH] Enable prettier for php and reformat the entire application directory --- .prettierignore | 5 +- .prettierrc.json | 5 +- application/config/app.php | 2 +- application/config/autoload.php | 12 +- application/config/config.php | 47 +- application/config/constants.php | 1 - application/config/database.php | 13 +- application/config/google.php | 1 - application/config/migration.php | 4 +- application/config/mimes.php | 142 ++- application/config/profiler.php | 1 - application/config/routes.php | 11 +- application/config/testing/routes.php | 3 +- application/controllers/About.php | 15 +- application/controllers/Account.php | 44 +- application/controllers/Admins.php | 129 +-- application/controllers/Api_settings.php | 35 +- application/controllers/Appointments.php | 119 +-- application/controllers/Backend.php | 12 +- application/controllers/Backend_api.php | 5 +- application/controllers/Blocked_periods.php | 108 +- application/controllers/Booking.php | 463 ++++----- .../controllers/Booking_cancellation.php | 30 +- .../controllers/Booking_confirmation.php | 14 +- application/controllers/Booking_settings.php | 43 +- application/controllers/Business_settings.php | 58 +- application/controllers/Calendar.php | 435 ++++---- application/controllers/Captcha.php | 9 +- application/controllers/Consents.php | 20 +- application/controllers/Console.php | 23 +- application/controllers/General_settings.php | 47 +- application/controllers/Google.php | 204 ++-- .../controllers/Google_analytics_settings.php | 35 +- application/controllers/Installation.php | 40 +- application/controllers/Integrations.php | 11 +- application/controllers/Legal_settings.php | 39 +- application/controllers/Localization.php | 19 +- application/controllers/Login.php | 33 +- application/controllers/Logout.php | 11 +- .../controllers/Matomo_analytics_settings.php | 35 +- application/controllers/Privacy.php | 26 +- application/controllers/Providers.php | 112 +-- application/controllers/Recovery.php | 36 +- application/controllers/Secretaries.php | 123 +-- .../controllers/Service_categories.php | 112 +-- application/controllers/Services.php | 109 +-- application/controllers/Test.php | 6 +- application/controllers/Unavailabilities.php | 93 +- application/controllers/Update.php | 24 +- application/controllers/User.php | 11 +- application/controllers/Webhooks.php | 71 +- .../controllers/api/v1/Admins_api_v1.php | 72 +- .../api/v1/Appointments_api_v1.php | 269 +++-- .../api/v1/Availabilities_api_v1.php | 15 +- .../controllers/api/v1/Customers_api_v1.php | 66 +- .../controllers/api/v1/Providers_api_v1.php | 82 +- .../controllers/api/v1/Secretaries_api_v1.php | 72 +- .../api/v1/Service_categories_api_v1.php | 73 +- .../controllers/api/v1/Services_api_v1.php | 75 +- .../controllers/api/v1/Settings_api_v1.php | 36 +- .../api/v1/Unavailabilities_api_v1.php | 69 +- .../controllers/api/v1/Webhooks_api_v1.php | 73 +- application/core/EA_Benchmark.php | 5 +- application/core/EA_Cache.php | 5 +- application/core/EA_Calendar.php | 5 +- application/core/EA_Config.php | 5 +- application/core/EA_Controller.php | 46 +- application/core/EA_DB_forge.php | 5 +- application/core/EA_DB_query_builder.php | 7 +- application/core/EA_DB_utility.php | 5 +- application/core/EA_Email.php | 5 +- application/core/EA_Encrypt.php | 5 +- application/core/EA_Encryption.php | 5 +- application/core/EA_Exceptions.php | 5 +- application/core/EA_Hooks.php | 5 +- application/core/EA_Input.php | 26 +- application/core/EA_Lang.php | 5 +- application/core/EA_Loader.php | 22 +- application/core/EA_Log.php | 5 +- application/core/EA_Migration.php | 3 +- application/core/EA_Model.php | 56 +- application/core/EA_Output.php | 5 +- application/core/EA_Profiler.php | 5 +- application/core/EA_Router.php | 5 +- application/core/EA_Security.php | 33 +- application/core/EA_Session.php | 5 +- application/core/EA_URI.php | 5 +- application/core/EA_Upload.php | 5 +- application/helpers/array_helper.php | 36 +- application/helpers/asset_helper.php | 10 +- application/helpers/config_helper.php | 56 +- application/helpers/date_helper.php | 67 +- application/helpers/debug_helper.php | 12 +- application/helpers/env_helper.php | 10 +- application/helpers/html_helper.php | 41 +- application/helpers/http_helper.php | 69 +- application/helpers/installation_helper.php | 2 +- application/helpers/language_helper.php | 7 +- application/helpers/password_helper.php | 10 +- application/helpers/path_helper.php | 7 +- application/helpers/permission_helper.php | 26 +- application/helpers/rate_limit_helper.php | 28 +- application/helpers/routes_helper.php | 12 +- application/helpers/session_helper.php | 18 +- application/helpers/setting_helper.php | 33 +- application/helpers/validation_helper.php | 2 +- application/index.html | 4 +- application/language/arabic/calendar_lang.php | 16 +- application/language/arabic/date_lang.php | 96 +- application/language/arabic/email_lang.php | 9 +- .../language/arabic/form_validation_lang.php | 81 +- application/language/arabic/ftp_lang.php | 41 +- application/language/arabic/imglib_lang.php | 37 +- .../language/arabic/migration_lang.php | 6 +- application/language/arabic/number_lang.php | 16 +- .../language/arabic/pagination_lang.php | 16 +- application/language/arabic/profiler_lang.php | 16 +- .../language/arabic/translations_lang.php | 81 +- .../language/arabic/unit_test_lang.php | 16 +- application/language/arabic/upload_lang.php | 22 +- .../language/bulgarian/calendar_lang.php | 16 +- application/language/bulgarian/date_lang.php | 96 +- application/language/bulgarian/db_lang.php | 18 +- application/language/bulgarian/email_lang.php | 21 +- .../bulgarian/form_validation_lang.php | 81 +- application/language/bulgarian/ftp_lang.php | 41 +- .../language/bulgarian/imglib_lang.php | 37 +- .../language/bulgarian/migration_lang.php | 12 +- .../language/bulgarian/number_lang.php | 16 +- .../language/bulgarian/pagination_lang.php | 16 +- .../language/bulgarian/profiler_lang.php | 16 +- .../language/bulgarian/translations_lang.php | 126 ++- .../language/bulgarian/unit_test_lang.php | 16 +- .../language/bulgarian/upload_lang.php | 22 +- .../language/catalan/calendar_lang.php | 16 +- application/language/catalan/date_lang.php | 96 +- application/language/catalan/db_lang.php | 5 +- application/language/catalan/email_lang.php | 11 +- .../language/catalan/form_validation_lang.php | 81 +- application/language/catalan/ftp_lang.php | 41 +- application/language/catalan/imglib_lang.php | 37 +- .../language/catalan/migration_lang.php | 28 +- application/language/catalan/number_lang.php | 16 +- .../language/catalan/pagination_lang.php | 16 +- .../language/catalan/profiler_lang.php | 16 +- .../language/catalan/translations_lang.php | 132 ++- .../language/catalan/unit_test_lang.php | 16 +- application/language/catalan/upload_lang.php | 22 +- .../language/chinese/calendar_lang.php | 16 +- application/language/chinese/date_lang.php | 96 +- application/language/chinese/db_lang.php | 10 +- application/language/chinese/email_lang.php | 10 +- .../language/chinese/form_validation_lang.php | 81 +- application/language/chinese/ftp_lang.php | 41 +- application/language/chinese/imglib_lang.php | 37 +- .../language/chinese/migration_lang.php | 10 +- application/language/chinese/number_lang.php | 16 +- .../language/chinese/pagination_lang.php | 16 +- .../language/chinese/profiler_lang.php | 16 +- .../language/chinese/translations_lang.php | 69 +- .../language/chinese/unit_test_lang.php | 16 +- application/language/chinese/upload_lang.php | 22 +- .../language/croatian/calendar_lang.php | 17 +- application/language/croatian/date_lang.php | 96 +- application/language/croatian/db_lang.php | 9 +- application/language/croatian/email_lang.php | 11 +- .../croatian/form_validation_lang.php | 78 +- application/language/croatian/ftp_lang.php | 44 +- application/language/croatian/imglib_lang.php | 38 +- .../language/croatian/migration_lang.php | 16 +- application/language/croatian/number_lang.php | 17 +- .../language/croatian/pagination_lang.php | 17 +- .../language/croatian/profiler_lang.php | 17 +- .../language/croatian/translations_lang.php | 123 ++- .../language/croatian/unit_test_lang.php | 16 +- application/language/croatian/upload_lang.php | 25 +- application/language/czech/calendar_lang.php | 16 +- application/language/czech/date_lang.php | 96 +- application/language/czech/email_lang.php | 9 +- .../language/czech/form_validation_lang.php | 81 +- application/language/czech/ftp_lang.php | 41 +- application/language/czech/imglib_lang.php | 37 +- application/language/czech/number_lang.php | 16 +- .../language/czech/pagination_lang.php | 16 +- application/language/czech/profiler_lang.php | 16 +- .../language/czech/translations_lang.php | 115 ++- application/language/czech/unit_test_lang.php | 16 +- application/language/czech/upload_lang.php | 22 +- application/language/danish/calendar_lang.php | 16 +- application/language/danish/date_lang.php | 96 +- application/language/danish/db_lang.php | 3 +- application/language/danish/email_lang.php | 9 +- .../language/danish/form_validation_lang.php | 81 +- application/language/danish/ftp_lang.php | 41 +- application/language/danish/imglib_lang.php | 37 +- application/language/danish/number_lang.php | 16 +- .../language/danish/pagination_lang.php | 16 +- application/language/danish/profiler_lang.php | 16 +- .../language/danish/translations_lang.php | 103 +- .../language/danish/unit_test_lang.php | 16 +- application/language/danish/upload_lang.php | 22 +- application/language/dutch/calendar_lang.php | 16 +- application/language/dutch/date_lang.php | 96 +- application/language/dutch/db_lang.php | 12 +- application/language/dutch/email_lang.php | 9 +- .../language/dutch/form_validation_lang.php | 81 +- application/language/dutch/ftp_lang.php | 41 +- application/language/dutch/imglib_lang.php | 37 +- application/language/dutch/number_lang.php | 16 +- .../language/dutch/pagination_lang.php | 16 +- application/language/dutch/profiler_lang.php | 16 +- .../language/dutch/translations_lang.php | 136 ++- application/language/dutch/unit_test_lang.php | 16 +- application/language/dutch/upload_lang.php | 22 +- .../language/english/calendar_lang.php | 16 +- application/language/english/date_lang.php | 96 +- application/language/english/db_lang.php | 5 +- application/language/english/email_lang.php | 11 +- .../language/english/form_validation_lang.php | 81 +- application/language/english/ftp_lang.php | 41 +- application/language/english/imglib_lang.php | 37 +- application/language/english/number_lang.php | 16 +- .../language/english/pagination_lang.php | 16 +- .../language/english/profiler_lang.php | 16 +- .../language/english/translations_lang.php | 121 ++- .../language/english/unit_test_lang.php | 16 +- application/language/english/upload_lang.php | 22 +- .../language/estonian/calendar_lang.php | 16 +- application/language/estonian/date_lang.php | 96 +- application/language/estonian/db_lang.php | 5 +- application/language/estonian/email_lang.php | 11 +- .../estonian/form_validation_lang.php | 81 +- application/language/estonian/ftp_lang.php | 41 +- application/language/estonian/imglib_lang.php | 37 +- .../language/estonian/migration_lang.php | 18 +- application/language/estonian/number_lang.php | 16 +- .../language/estonian/pagination_lang.php | 16 +- .../language/estonian/profiler_lang.php | 16 +- .../language/estonian/translations_lang.php | 84 +- .../language/estonian/unit_test_lang.php | 16 +- application/language/estonian/upload_lang.php | 22 +- .../language/finnish/calendar_lang.php | 16 +- application/language/finnish/date_lang.php | 96 +- application/language/finnish/db_lang.php | 5 +- application/language/finnish/email_lang.php | 11 +- .../language/finnish/form_validation_lang.php | 77 +- application/language/finnish/ftp_lang.php | 41 +- application/language/finnish/imglib_lang.php | 34 +- .../language/finnish/migration_lang.php | 18 +- application/language/finnish/number_lang.php | 16 +- .../language/finnish/pagination_lang.php | 16 +- .../language/finnish/profiler_lang.php | 16 +- .../language/finnish/translations_lang.php | 90 +- .../language/finnish/unit_test_lang.php | 16 +- application/language/finnish/upload_lang.php | 16 +- application/language/french/calendar_lang.php | 16 +- application/language/french/date_lang.php | 96 +- application/language/french/db_lang.php | 31 +- application/language/french/email_lang.php | 22 +- .../language/french/form_validation_lang.php | 81 +- application/language/french/ftp_lang.php | 41 +- application/language/french/imglib_lang.php | 37 +- .../language/french/migration_lang.php | 6 +- application/language/french/number_lang.php | 16 +- .../language/french/pagination_lang.php | 16 +- application/language/french/profiler_lang.php | 16 +- .../language/french/translations_lang.php | 163 ++- .../language/french/unit_test_lang.php | 16 +- application/language/french/upload_lang.php | 22 +- application/language/german/calendar_lang.php | 16 +- application/language/german/date_lang.php | 96 +- application/language/german/db_lang.php | 12 +- application/language/german/email_lang.php | 12 +- .../language/german/form_validation_lang.php | 79 +- application/language/german/ftp_lang.php | 41 +- application/language/german/imglib_lang.php | 37 +- application/language/german/number_lang.php | 16 +- .../language/german/pagination_lang.php | 16 +- application/language/german/profiler_lang.php | 16 +- .../language/german/translations_lang.php | 169 ++-- .../language/german/unit_test_lang.php | 16 +- application/language/german/upload_lang.php | 22 +- application/language/greek/calendar_lang.php | 16 +- application/language/greek/date_lang.php | 96 +- application/language/greek/db_lang.php | 6 +- application/language/greek/email_lang.php | 12 +- .../language/greek/form_validation_lang.php | 81 +- application/language/greek/ftp_lang.php | 41 +- application/language/greek/imglib_lang.php | 37 +- application/language/greek/number_lang.php | 16 +- .../language/greek/pagination_lang.php | 16 +- application/language/greek/profiler_lang.php | 16 +- .../language/greek/translations_lang.php | 157 ++- application/language/greek/unit_test_lang.php | 16 +- application/language/greek/upload_lang.php | 22 +- application/language/hebrew/calendar_lang.php | 16 +- application/language/hebrew/date_lang.php | 96 +- application/language/hebrew/email_lang.php | 10 +- .../language/hebrew/form_validation_lang.php | 81 +- application/language/hebrew/ftp_lang.php | 41 +- application/language/hebrew/imglib_lang.php | 37 +- application/language/hebrew/number_lang.php | 16 +- .../language/hebrew/pagination_lang.php | 16 +- application/language/hebrew/profiler_lang.php | 16 +- .../language/hebrew/translations_lang.php | 90 +- .../language/hebrew/unit_test_lang.php | 16 +- application/language/hebrew/upload_lang.php | 22 +- application/language/hindi/calendar_lang.php | 16 +- application/language/hindi/date_lang.php | 96 +- application/language/hindi/db_lang.php | 9 +- application/language/hindi/email_lang.php | 9 +- .../language/hindi/form_validation_lang.php | 81 +- application/language/hindi/ftp_lang.php | 41 +- application/language/hindi/imglib_lang.php | 37 +- application/language/hindi/number_lang.php | 16 +- .../language/hindi/pagination_lang.php | 16 +- application/language/hindi/profiler_lang.php | 16 +- .../language/hindi/translations_lang.php | 106 +- application/language/hindi/unit_test_lang.php | 16 +- application/language/hindi/upload_lang.php | 22 +- .../language/hungarian/calendar_lang.php | 16 +- application/language/hungarian/date_lang.php | 96 +- application/language/hungarian/db_lang.php | 59 +- application/language/hungarian/email_lang.php | 51 +- .../hungarian/form_validation_lang.php | 81 +- application/language/hungarian/ftp_lang.php | 41 +- .../language/hungarian/imglib_lang.php | 37 +- .../language/hungarian/migration_lang.php | 27 +- .../language/hungarian/number_lang.php | 16 +- .../language/hungarian/pagination_lang.php | 16 +- .../language/hungarian/profiler_lang.php | 16 +- .../language/hungarian/translations_lang.php | 117 ++- .../language/hungarian/unit_test_lang.php | 16 +- .../language/hungarian/upload_lang.php | 22 +- .../language/italian/calendar_lang.php | 16 +- application/language/italian/date_lang.php | 96 +- application/language/italian/db_lang.php | 27 +- application/language/italian/email_lang.php | 21 +- .../language/italian/form_validation_lang.php | 28 +- application/language/italian/ftp_lang.php | 22 +- application/language/italian/imglib_lang.php | 40 +- .../language/italian/migration_lang.php | 12 +- application/language/italian/number_lang.php | 16 +- .../language/italian/pagination_lang.php | 16 +- .../language/italian/profiler_lang.php | 16 +- .../language/italian/translations_lang.php | 135 ++- .../language/italian/unit_test_lang.php | 16 +- application/language/italian/upload_lang.php | 28 +- .../language/japanese/calendar_lang.php | 16 +- application/language/japanese/date_lang.php | 96 +- application/language/japanese/db_lang.php | 10 +- application/language/japanese/email_lang.php | 21 +- .../japanese/form_validation_lang.php | 81 +- application/language/japanese/ftp_lang.php | 41 +- application/language/japanese/imglib_lang.php | 37 +- .../language/japanese/migration_lang.php | 10 +- application/language/japanese/number_lang.php | 16 +- .../language/japanese/pagination_lang.php | 16 +- .../language/japanese/profiler_lang.php | 16 +- .../language/japanese/translations_lang.php | 105 +- .../language/japanese/unit_test_lang.php | 16 +- application/language/japanese/upload_lang.php | 22 +- .../language/luxembourgish/calendar_lang.php | 16 +- .../language/luxembourgish/date_lang.php | 96 +- .../language/luxembourgish/db_lang.php | 5 +- .../language/luxembourgish/email_lang.php | 11 +- .../luxembourgish/form_validation_lang.php | 81 +- .../language/luxembourgish/ftp_lang.php | 41 +- .../language/luxembourgish/imglib_lang.php | 37 +- .../language/luxembourgish/migration_lang.php | 18 +- .../language/luxembourgish/number_lang.php | 16 +- .../luxembourgish/pagination_lang.php | 16 +- .../language/luxembourgish/profiler_lang.php | 16 +- .../luxembourgish/translations_lang.php | 138 ++- .../language/luxembourgish/unit_test_lang.php | 16 +- .../language/luxembourgish/upload_lang.php | 22 +- .../language/marathi/calendar_lang.php | 16 +- application/language/marathi/date_lang.php | 96 +- application/language/marathi/db_lang.php | 12 +- application/language/marathi/email_lang.php | 27 +- .../language/marathi/form_validation_lang.php | 81 +- application/language/marathi/ftp_lang.php | 41 +- application/language/marathi/imglib_lang.php | 37 +- .../language/marathi/migration_lang.php | 16 +- application/language/marathi/number_lang.php | 16 +- .../language/marathi/pagination_lang.php | 16 +- .../language/marathi/profiler_lang.php | 16 +- .../language/marathi/translations_lang.php | 107 +- .../language/marathi/unit_test_lang.php | 16 +- application/language/marathi/upload_lang.php | 22 +- .../language/persian/calendar_lang.php | 16 +- application/language/persian/date_lang.php | 96 +- application/language/persian/db_lang.php | 10 +- application/language/persian/email_lang.php | 21 +- .../language/persian/form_validation_lang.php | 81 +- application/language/persian/ftp_lang.php | 41 +- application/language/persian/imglib_lang.php | 37 +- .../language/persian/migration_lang.php | 10 +- application/language/persian/number_lang.php | 16 +- .../language/persian/pagination_lang.php | 16 +- .../language/persian/profiler_lang.php | 16 +- .../language/persian/translations_lang.php | 108 +- .../language/persian/unit_test_lang.php | 16 +- application/language/persian/upload_lang.php | 22 +- application/language/polish/calendar_lang.php | 16 +- application/language/polish/date_lang.php | 96 +- application/language/polish/db_lang.php | 61 +- application/language/polish/email_lang.php | 51 +- .../language/polish/form_validation_lang.php | 78 +- application/language/polish/ftp_lang.php | 41 +- application/language/polish/imglib_lang.php | 37 +- .../language/polish/migration_lang.php | 26 +- application/language/polish/number_lang.php | 16 +- .../language/polish/pagination_lang.php | 16 +- application/language/polish/profiler_lang.php | 16 +- .../language/polish/translations_lang.php | 87 +- .../language/polish/unit_test_lang.php | 16 +- application/language/polish/upload_lang.php | 22 +- .../language/portuguese-br/calendar_lang.php | 16 +- .../language/portuguese-br/date_lang.php | 96 +- .../language/portuguese-br/db_lang.php | 31 +- .../language/portuguese-br/email_lang.php | 19 +- .../portuguese-br/form_validation_lang.php | 79 +- .../language/portuguese-br/ftp_lang.php | 41 +- .../language/portuguese-br/imglib_lang.php | 40 +- .../language/portuguese-br/migration_lang.php | 10 +- .../language/portuguese-br/number_lang.php | 16 +- .../portuguese-br/pagination_lang.php | 16 +- .../language/portuguese-br/profiler_lang.php | 16 +- .../portuguese-br/translations_lang.php | 120 ++- .../language/portuguese-br/unit_test_lang.php | 16 +- .../language/portuguese-br/upload_lang.php | 25 +- .../language/portuguese/calendar_lang.php | 16 +- application/language/portuguese/date_lang.php | 96 +- application/language/portuguese/db_lang.php | 22 +- .../language/portuguese/email_lang.php | 19 +- .../portuguese/form_validation_lang.php | 81 +- application/language/portuguese/ftp_lang.php | 41 +- .../language/portuguese/imglib_lang.php | 37 +- .../language/portuguese/migration_lang.php | 10 +- .../language/portuguese/number_lang.php | 16 +- .../language/portuguese/pagination_lang.php | 16 +- .../language/portuguese/profiler_lang.php | 16 +- .../language/portuguese/translations_lang.php | 111 ++- .../language/portuguese/unit_test_lang.php | 16 +- .../language/portuguese/upload_lang.php | 22 +- .../language/romanian/calendar_lang.php | 16 +- application/language/romanian/date_lang.php | 96 +- application/language/romanian/db_lang.php | 13 +- application/language/romanian/email_lang.php | 19 +- .../romanian/form_validation_lang.php | 81 +- application/language/romanian/ftp_lang.php | 41 +- application/language/romanian/imglib_lang.php | 37 +- .../language/romanian/migration_lang.php | 26 +- application/language/romanian/number_lang.php | 16 +- .../language/romanian/pagination_lang.php | 16 +- .../language/romanian/profiler_lang.php | 16 +- .../language/romanian/translations_lang.php | 120 ++- .../language/romanian/unit_test_lang.php | 16 +- application/language/romanian/upload_lang.php | 22 +- .../language/russian/calendar_lang.php | 16 +- application/language/russian/date_lang.php | 96 +- application/language/russian/db_lang.php | 16 +- application/language/russian/email_lang.php | 19 +- .../language/russian/form_validation_lang.php | 79 +- application/language/russian/ftp_lang.php | 41 +- application/language/russian/imglib_lang.php | 40 +- .../language/russian/migration_lang.php | 10 +- application/language/russian/number_lang.php | 16 +- .../language/russian/pagination_lang.php | 16 +- .../language/russian/profiler_lang.php | 16 +- .../language/russian/translations_lang.php | 129 ++- .../language/russian/unit_test_lang.php | 16 +- application/language/russian/upload_lang.php | 28 +- .../language/serbian/calendar_lang.php | 16 +- application/language/serbian/date_lang.php | 96 +- application/language/serbian/db_lang.php | 5 +- application/language/serbian/email_lang.php | 11 +- .../language/serbian/form_validation_lang.php | 81 +- application/language/serbian/ftp_lang.php | 41 +- application/language/serbian/imglib_lang.php | 37 +- application/language/serbian/number_lang.php | 16 +- .../language/serbian/pagination_lang.php | 16 +- .../language/serbian/profiler_lang.php | 16 +- .../language/serbian/translations_lang.php | 108 +- .../language/serbian/unit_test_lang.php | 16 +- application/language/serbian/upload_lang.php | 22 +- application/language/slovak/calendar_lang.php | 16 +- application/language/slovak/date_lang.php | 96 +- application/language/slovak/db_lang.php | 49 +- application/language/slovak/email_lang.php | 41 +- .../language/slovak/form_validation_lang.php | 81 +- application/language/slovak/ftp_lang.php | 41 +- application/language/slovak/imglib_lang.php | 37 +- .../language/slovak/migration_lang.php | 16 +- application/language/slovak/number_lang.php | 16 +- .../language/slovak/pagination_lang.php | 16 +- application/language/slovak/profiler_lang.php | 16 +- .../language/slovak/translations_lang.php | 120 ++- .../language/slovak/unit_test_lang.php | 16 +- application/language/slovak/upload_lang.php | 22 +- .../language/spanish/calendar_lang.php | 16 +- application/language/spanish/date_lang.php | 96 +- application/language/spanish/db_lang.php | 24 +- application/language/spanish/email_lang.php | 21 +- .../language/spanish/form_validation_lang.php | 81 +- application/language/spanish/ftp_lang.php | 41 +- application/language/spanish/imglib_lang.php | 37 +- .../language/spanish/migration_lang.php | 28 +- application/language/spanish/number_lang.php | 16 +- .../language/spanish/pagination_lang.php | 16 +- .../language/spanish/profiler_lang.php | 16 +- .../language/spanish/translations_lang.php | 144 ++- .../language/spanish/unit_test_lang.php | 16 +- application/language/spanish/upload_lang.php | 22 +- .../language/swedish/calendar_lang.php | 16 +- application/language/swedish/date_lang.php | 96 +- application/language/swedish/db_lang.php | 13 +- application/language/swedish/email_lang.php | 19 +- .../language/swedish/form_validation_lang.php | 80 +- application/language/swedish/ftp_lang.php | 41 +- application/language/swedish/imglib_lang.php | 37 +- .../language/swedish/migration_lang.php | 10 +- application/language/swedish/number_lang.php | 16 +- .../language/swedish/pagination_lang.php | 16 +- .../language/swedish/profiler_lang.php | 16 +- .../language/swedish/translations_lang.php | 99 +- .../language/swedish/unit_test_lang.php | 16 +- application/language/swedish/upload_lang.php | 25 +- .../language/turkish/calendar_lang.php | 16 +- application/language/turkish/date_lang.php | 96 +- application/language/turkish/db_lang.php | 59 +- application/language/turkish/email_lang.php | 51 +- .../language/turkish/form_validation_lang.php | 81 +- application/language/turkish/ftp_lang.php | 41 +- application/language/turkish/imglib_lang.php | 37 +- .../language/turkish/migration_lang.php | 26 +- application/language/turkish/number_lang.php | 16 +- .../language/turkish/pagination_lang.php | 16 +- .../language/turkish/profiler_lang.php | 16 +- .../language/turkish/translations_lang.php | 114 ++- .../language/turkish/unit_test_lang.php | 16 +- application/language/turkish/upload_lang.php | 22 +- application/libraries/Accounts.php | 40 +- application/libraries/Api.php | 89 +- application/libraries/Availability.php | 658 ++++++------- application/libraries/Captcha_builder.php | 926 ++++++++---------- application/libraries/Email_messages.php | 100 +- application/libraries/Google_sync.php | 107 +- application/libraries/Ics_calendar.php | 85 +- application/libraries/Ics_file.php | 32 +- application/libraries/Ics_provider.php | 91 +- application/libraries/Instance.php | 53 +- application/libraries/Notifications.php | 116 ++- application/libraries/Permissions.php | 42 +- application/libraries/Synchronization.php | 186 ++-- application/libraries/Timezones.php | 38 +- application/libraries/Webhooks_client.php | 26 +- application/libraries/index.html | 4 +- .../migrations/001_specific_calendar_sync.php | 416 +++++--- .../002_add_google_analytics_setting.php | 9 +- ...003_add_customer_notifications_setting.php | 9 +- .../004_add_date_format_setting.php | 9 +- .../005_add_require_captcha_setting.php | 9 +- .../006_add_calendar_view_setting.php | 9 +- .../007_add_service_availabilities_type.php | 9 +- .../008_add_service_attendants_number.php | 9 +- .../migrations/009_change_column_types.php | 403 ++++++-- .../010_add_time_format_setting.php | 9 +- ...11_remove_prefix_from_fkey_constraints.php | 311 ++++-- application/migrations/012_legal_contents.php | 68 +- .../013_add_weekday_start_setting.php | 9 +- ...014_create_appointment_location_column.php | 19 +- ...rking_plan_exceptions_to_user_settings.php | 11 +- .../016_add_require_phone_number_setting.php | 9 +- .../migrations/017_add_api_token_setting.php | 10 +- .../migrations/018_add_timezone_to_users.php | 6 +- .../019_add_display_any_provider_setting.php | 9 +- .../migrations/020_add_language_to_users.php | 6 +- .../021_modify_sync_period_columns.php | 15 +- .../022_add_booking_field_settings.php | 42 +- ...service_categories_table_to_categories.php | 9 +- ...ce_categories_column_of_services_table.php | 45 +- ...available_column_of_appointments_table.php | 9 +- ...026_add_color_column_to_services_table.php | 9 +- ...add_color_column_to_appointments_table.php | 9 +- .../028_add_matomo_analytics_url_setting.php | 9 +- ...ay_delete_personal_information_setting.php | 9 +- .../030_add_disable_booking_setting.php | 9 +- ...31_add_disable_booking_message_setting.php | 12 +- .../032_add_company_logo_setting.php | 9 +- .../033_add_company_color_setting.php | 9 +- .../034_add_display_login_button_setting.php | 9 +- ...dd_is_private_column_to_services_table.php | 9 +- ...6_add_is_private_column_to_users_table.php | 9 +- .../migrations/037_add_timestamp_columns.php | 41 +- .../migrations/038_add_theme_setting.php | 9 +- .../039_add_limit_customer_access_setting.php | 9 +- .../migrations/040_create_webhooks_table.php | 35 +- ...041_add_webhooks_column_to_roles_table.php | 11 +- .../042_add_future_booking_limit_setting.php | 11 +- ...add_appointment_status_options_setting.php | 9 +- ...dd_status_column_to_appointments_table.php | 9 +- ...delete_datetime_column_from_all_tables.php | 19 +- ...service_categories_table_to_categories.php | 9 +- ...ce_categories_column_of_services_table.php | 45 +- .../048_create_blocked_periods_table.php | 29 +- ..._blocked_periods_column_to_roles_table.php | 11 +- application/models/Admins_model.php | 429 ++++---- application/models/Appointments_model.php | 295 +++--- application/models/Blocked_periods_model.php | 205 ++-- application/models/Consents_model.php | 117 +-- application/models/Providers_model.php | 735 +++++++------- application/models/Roles_model.php | 161 ++- application/models/Secretaries_model.php | 600 ++++++------ .../models/Service_categories_model.php | 162 ++- application/models/Services_model.php | 256 +++-- application/models/Settings_model.php | 133 ++- application/models/Unavailabilities_model.php | 229 +++-- application/models/Users_model.php | 253 +++-- application/models/Webhooks_model.php | 119 +-- .../components/appointment_status_options.php | 4 +- .../views/components/backend_footer.php | 10 +- .../views/components/backend_header.php | 29 +- .../components/booking_cancellation_frame.php | 4 +- .../views/components/booking_final_step.php | 40 +- .../views/components/booking_footer.php | 4 +- .../views/components/booking_info_step.php | 54 +- .../views/components/booking_time_step.php | 4 +- .../views/components/booking_type_step.php | 56 +- .../views/components/color_selection.php | 8 +- .../views/components/company_color_style.php | 4 +- .../views/components/cookie_notice_modal.php | 2 +- .../components/google_analytics_script.php | 25 +- .../views/components/js_vars_script.php | 2 +- .../components/matomo_analytics_script.php | 4 +- .../views/components/privacy_policy_modal.php | 2 +- .../components/terms_and_conditions_modal.php | 2 +- .../views/components/timezone_dropdown.php | 6 +- .../components/unavailabilities_modal.php | 6 +- .../working_plan_exceptions_modal.php | 4 +- .../emails/appointment_deleted_email.php | 12 +- .../views/emails/appointment_saved_email.php | 8 +- .../views/errors/cli/error_exception.php | 10 +- application/views/errors/cli/error_php.php | 10 +- .../views/errors/html/error_exception.php | 10 +- application/views/layouts/account_layout.php | 17 +- application/views/layouts/backend_layout.php | 25 +- application/views/layouts/booking_layout.php | 51 +- application/views/layouts/message_layout.php | 29 +- application/views/pages/about.php | 25 +- application/views/pages/account.php | 27 +- application/views/pages/admins.php | 16 +- application/views/pages/api_settings.php | 14 +- application/views/pages/blocked_periods.php | 10 +- application/views/pages/booking.php | 24 +- .../views/pages/booking_cancellation.php | 14 +- .../views/pages/booking_confirmation.php | 14 +- application/views/pages/booking_message.php | 14 +- application/views/pages/booking_settings.php | 70 +- application/views/pages/business_settings.php | 52 +- application/views/pages/calendar.php | 83 +- application/views/pages/customers.php | 43 +- application/views/pages/general_settings.php | 18 +- .../views/pages/google_analytics_settings.php | 14 +- application/views/pages/installation.php | 17 +- application/views/pages/integrations.php | 14 +- application/views/pages/legal_settings.php | 33 +- application/views/pages/login.php | 10 +- application/views/pages/logout.php | 8 +- .../views/pages/matomo_analytics_settings.php | 14 +- application/views/pages/providers.php | 26 +- application/views/pages/recovery.php | 14 +- application/views/pages/secretaries.php | 14 +- .../views/pages/service_categories.php | 10 +- application/views/pages/services.php | 12 +- application/views/pages/webhooks.php | 18 +- package-lock.json | 88 +- package.json | 3 +- 679 files changed, 16004 insertions(+), 14523 deletions(-) diff --git a/.prettierignore b/.prettierignore index a0428d48af..d12cb0bd30 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,9 +1,10 @@ .idea -application +.github +.run build docker docs +node_modules storage system -tests vendor diff --git a/.prettierrc.json b/.prettierrc.json index 37dc1cf4c8..742418e5d8 100644 --- a/.prettierrc.json +++ b/.prettierrc.json @@ -5,5 +5,8 @@ "bracketSpacing": false, "bracketSameLine": false, "quoteProps": "preserve", - "trailingComma": "none" + "trailingComma": "none", + "trailingCommaPHP": false, + "phpVersion": "8.0", + "plugins": ["@prettier/plugin-php"] } diff --git a/application/config/app.php b/application/config/app.php index 8a627558f6..645504803d 100644 --- a/application/config/app.php +++ b/application/config/app.php @@ -11,7 +11,7 @@ $config['version'] = '1.5.0-dev.4'; // This must be changed manually. -$config['url'] = Config::BASE_URL; +$config['url'] = Config::BASE_URL; $config['debug'] = Config::DEBUG_MODE; diff --git a/application/config/autoload.php b/application/config/autoload.php index c9587ef9a4..dedfcee161 100644 --- a/application/config/autoload.php +++ b/application/config/autoload.php @@ -40,7 +40,6 @@ $autoload['packages'] = []; - /* | ------------------------------------------------------------------- | Auto-load Libraries @@ -55,7 +54,6 @@ $autoload['libraries'] = ['database', 'session']; - /* | ------------------------------------------------------------------- | Auto-load Helper Files @@ -89,7 +87,6 @@ 'validation' ]; - /* | ------------------------------------------------------------------- | Auto-load Config files @@ -103,12 +100,7 @@ | */ -$autoload['config'] = [ - 'app', - 'google', - 'email' -]; - +$autoload['config'] = ['app', 'google', 'email']; /* | ------------------------------------------------------------------- @@ -125,7 +117,6 @@ $autoload['language'] = []; - /* | ------------------------------------------------------------------- | Auto-load Models @@ -138,6 +129,5 @@ $autoload['model'] = []; - /* End of file autoload.php */ /* Location: ./application/config/autoload.php */ diff --git a/application/config/config.php b/application/config/config.php index 9da55288e2..454c62e5f4 100644 --- a/application/config/config.php +++ b/application/config/config.php @@ -16,17 +16,17 @@ */ $protocol = - (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') - || (isset($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443) - || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') - ? 'https://' : 'http://'; + (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') || + (isset($_SERVER['SERVER_PORT']) && (int) $_SERVER['SERVER_PORT'] === 443) || + (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') + ? 'https://' + : 'http://'; $domain = $_SERVER['HTTP_HOST'] ?? 'localhost'; $request_uri = dirname($_SERVER['SCRIPT_NAME']); -if ($request_uri === '.') -{ +if ($request_uri === '.') { $request_uri = ''; } @@ -117,7 +117,7 @@ 'sk' => 'slovak', 'es' => 'spanish', 'sv' => 'swedish', - 'tr' => 'turkish', + 'tr' => 'turkish' ]; $config['language_codes'] = $languages; @@ -195,8 +195,7 @@ | setting this variable to TRUE (boolean). See the user guide for details. | */ -$config['enable_hooks'] = TRUE; - +$config['enable_hooks'] = true; /* |-------------------------------------------------------------------------- @@ -212,7 +211,6 @@ */ $config['subclass_prefix'] = 'EA_'; - /* |-------------------------------------------------------------------------- | Allowed URL Characters @@ -232,7 +230,6 @@ */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; - /* |-------------------------------------------------------------------------- | Enable Query Strings @@ -258,8 +255,8 @@ | use segment based URLs. | */ -$config['allow_get_array'] = TRUE; -$config['enable_query_strings'] = FALSE; +$config['allow_get_array'] = true; +$config['enable_query_strings'] = false; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; // experimental not currently in use @@ -352,9 +349,9 @@ $config['sess_cookie_name'] = 'ea_session'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = __DIR__ . '/../../storage/sessions'; -$config['sess_match_ip'] = FALSE; +$config['sess_match_ip'] = false; $config['sess_time_to_update'] = 300; -$config['sess_regenerate_destroy'] = FALSE; +$config['sess_regenerate_destroy'] = false; /* |-------------------------------------------------------------------------- @@ -370,7 +367,7 @@ $config['cookie_prefix'] = ''; $config['cookie_domain'] = ''; $config['cookie_path'] = '/'; -$config['cookie_secure'] = strpos($config['base_url'], 'https') !== FALSE; +$config['cookie_secure'] = strpos($config['base_url'], 'https') !== false; /* |-------------------------------------------------------------------------- @@ -384,16 +381,11 @@ | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. */ -$config['csrf_protection'] = TRUE; +$config['csrf_protection'] = true; $config['csrf_token_name'] = 'csrf_token'; $config['csrf_cookie_name'] = 'csrf_cookie'; $config['csrf_expire'] = 7200; -$config['csrf_exclude_uris'] = [ - 'api/v1/.*', - 'booking/.*', - 'booking_cancellation/.*', - 'booking_confirmation/.*' -]; +$config['csrf_exclude_uris'] = ['api/v1/.*', 'booking/.*', 'booking_cancellation/.*', 'booking_confirmation/.*']; /* |-------------------------------------------------------------------------- @@ -412,7 +404,7 @@ | by the output class. Do not 'echo' any values with compression enabled. | */ -$config['compress_output'] = FALSE; +$config['compress_output'] = false; /* |-------------------------------------------------------------------------- @@ -427,7 +419,6 @@ */ $config['time_reference'] = 'local'; - /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags @@ -438,8 +429,7 @@ | in your view files. Options are TRUE or FALSE (boolean) | */ -$config['rewrite_short_tags'] = FALSE; - +$config['rewrite_short_tags'] = false; /* |-------------------------------------------------------------------------- @@ -463,8 +453,7 @@ | will control the number of requests a client can sent to the app. | */ -$config['rate_limiting'] = TRUE; - +$config['rate_limiting'] = true; /* End of file config.php */ /* Location: ./application/config/config.php */ diff --git a/application/config/constants.php b/application/config/constants.php index 1f2dbad6db..15b5e840f2 100644 --- a/application/config/constants.php +++ b/application/config/constants.php @@ -36,7 +36,6 @@ const FOPEN_WRITE_CREATE_STRICT = 'xb'; const FOPEN_READ_WRITE_CREATE_STRICT = 'x+b'; - /* |-------------------------------------------------------------------------- | Application Data diff --git a/application/config/database.php b/application/config/database.php index 7073044e4c..f77fa1fcb9 100644 --- a/application/config/database.php +++ b/application/config/database.php @@ -47,7 +47,7 @@ */ $active_group = 'default'; -$query_builder = TRUE; +$query_builder = true; $db['default']['hostname'] = Config::DB_HOST; $db['default']['username'] = Config::DB_USERNAME; @@ -55,16 +55,15 @@ $db['default']['database'] = Config::DB_NAME; $db['default']['dbdriver'] = 'mysqli'; $db['default']['dbprefix'] = 'ea_'; -$db['default']['pconnect'] = TRUE; -$db['default']['db_debug'] = TRUE; -$db['default']['cache_on'] = FALSE; +$db['default']['pconnect'] = true; +$db['default']['db_debug'] = true; +$db['default']['cache_on'] = false; $db['default']['cachedir'] = ''; $db['default']['char_set'] = 'utf8mb4'; $db['default']['dbcollat'] = 'utf8mb4_unicode_ci'; $db['default']['swap_pre'] = ''; -$db['default']['autoinit'] = TRUE; -$db['default']['stricton'] = FALSE; - +$db['default']['autoinit'] = true; +$db['default']['stricton'] = false; /* End of file database.php */ /* Location: ./application/config/database.php */ diff --git a/application/config/google.php b/application/config/google.php index f511e45b38..49d8103236 100644 --- a/application/config/google.php +++ b/application/config/google.php @@ -15,4 +15,3 @@ $config['google_client_id'] = Config::GOOGLE_CLIENT_ID; $config['google_client_secret'] = Config::GOOGLE_CLIENT_SECRET; - diff --git a/application/config/migration.php b/application/config/migration.php index c722db4540..b11078288c 100755 --- a/application/config/migration.php +++ b/application/config/migration.php @@ -9,7 +9,7 @@ | whenever you intend to do a schema migration. | */ -$config['migration_enabled'] = TRUE; +$config['migration_enabled'] = true; /* |-------------------------------------------------------------------------- @@ -23,7 +23,6 @@ */ $config['migration_version'] = 0; - /* |-------------------------------------------------------------------------- | Migrations Path @@ -36,6 +35,5 @@ */ $config['migration_path'] = APPPATH . 'migrations/'; - /* End of file migration.php */ /* Location: ./application/config/migration.php */ diff --git a/application/config/mimes.php b/application/config/mimes.php index e9e94773f6..7f6bccd32a 100644 --- a/application/config/mimes.php +++ b/application/config/mimes.php @@ -10,10 +10,33 @@ | */ return [ - 'hqx' => ['application/mac-binhex40', 'application/mac-binhex', 'application/x-binhex40', 'application/x-mac-binhex40'], + 'hqx' => [ + 'application/mac-binhex40', + 'application/mac-binhex', + 'application/x-binhex40', + 'application/x-mac-binhex40' + ], 'cpt' => 'application/mac-compactpro', - 'csv' => ['text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain'], - 'bin' => ['application/macbinary', 'application/mac-binary', 'application/octet-stream', 'application/x-binary', 'application/x-macbinary'], + 'csv' => [ + 'text/x-comma-separated-values', + 'text/comma-separated-values', + 'application/octet-stream', + 'application/vnd.ms-excel', + 'application/x-csv', + 'text/x-csv', + 'text/csv', + 'application/csv', + 'application/excel', + 'application/vnd.msexcel', + 'text/plain' + ], + 'bin' => [ + 'application/macbinary', + 'application/mac-binary', + 'application/octet-stream', + 'application/x-binary', + 'application/x-macbinary' + ], 'dms' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', @@ -31,9 +54,31 @@ 'smi' => 'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', - 'xls' => ['application/vnd.ms-excel', 'application/msexcel', 'application/x-msexcel', 'application/x-ms-excel', 'application/x-excel', 'application/x-dos_ms_excel', 'application/xls', 'application/x-xls', 'application/excel', 'application/download', 'application/vnd.ms-office', 'application/msword'], - 'ppt' => ['application/powerpoint', 'application/vnd.ms-powerpoint', 'application/vnd.ms-office', 'application/msword'], - 'pptx' => ['application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/x-zip', 'application/zip'], + 'xls' => [ + 'application/vnd.ms-excel', + 'application/msexcel', + 'application/x-msexcel', + 'application/x-ms-excel', + 'application/x-excel', + 'application/x-dos_ms_excel', + 'application/xls', + 'application/x-xls', + 'application/excel', + 'application/download', + 'application/vnd.ms-office', + 'application/msword' + ], + 'ppt' => [ + 'application/powerpoint', + 'application/vnd.ms-powerpoint', + 'application/vnd.ms-office', + 'application/msword' + ], + 'pptx' => [ + 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + 'application/x-zip', + 'application/zip' + ], 'wbxml' => 'application/wbxml', 'wmlc' => 'application/wmlc', 'dcr' => 'application/x-director', @@ -43,7 +88,14 @@ 'gtar' => 'application/x-gtar', 'gz' => 'application/x-gzip', 'gzip' => 'application/x-gzip', - 'php' => ['application/x-httpd-php', 'application/php', 'application/x-php', 'text/php', 'text/x-php', 'application/x-httpd-php-source'], + 'php' => [ + 'application/x-httpd-php', + 'application/php', + 'application/x-php', + 'text/php', + 'text/x-php', + 'application/x-httpd-php-source' + ], 'php4' => 'application/x-httpd-php', 'php3' => 'application/x-httpd-php', 'phtml' => 'application/x-httpd-php', @@ -56,7 +108,13 @@ 'z' => 'application/x-compress', 'xhtml' => 'application/xhtml+xml', 'xht' => 'application/xhtml+xml', - 'zip' => ['application/x-zip', 'application/zip', 'application/x-zip-compressed', 'application/s-compressed', 'multipart/x-zip'], + 'zip' => [ + 'application/x-zip', + 'application/zip', + 'application/x-zip-compressed', + 'application/s-compressed', + 'multipart/x-zip' + ], 'rar' => ['application/x-rar', 'application/rar', 'application/x-rar-compressed'], 'mid' => 'audio/midi', 'midi' => 'audio/midi', @@ -72,7 +130,19 @@ 'ra' => 'audio/x-realaudio', 'rv' => 'video/vnd.rn-realvideo', 'wav' => ['audio/x-wav', 'audio/wave', 'audio/wav'], - 'bmp' => ['image/bmp', 'image/x-bmp', 'image/x-bitmap', 'image/x-xbitmap', 'image/x-win-bitmap', 'image/x-windows-bmp', 'image/ms-bmp', 'image/x-ms-bmp', 'application/bmp', 'application/x-bmp', 'application/x-win-bitmap'], + 'bmp' => [ + 'image/bmp', + 'image/x-bmp', + 'image/x-bitmap', + 'image/x-xbitmap', + 'image/x-win-bitmap', + 'image/x-windows-bmp', + 'image/ms-bmp', + 'image/x-ms-bmp', + 'application/bmp', + 'application/x-bmp', + 'application/x-win-bitmap' + ], 'gif' => 'image/gif', 'jpeg' => ['image/jpeg', 'image/pjpeg'], 'jpg' => ['image/jpeg', 'image/pjpeg'], @@ -107,10 +177,25 @@ 'avi' => ['video/x-msvideo', 'video/msvideo', 'video/avi', 'application/x-troff-msvideo'], 'movie' => 'video/x-sgi-movie', 'doc' => ['application/msword', 'application/vnd.ms-office'], - 'docx' => ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword', 'application/x-zip'], + 'docx' => [ + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/zip', + 'application/msword', + 'application/x-zip' + ], 'dot' => ['application/msword', 'application/vnd.ms-office'], - 'dotx' => ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip', 'application/msword'], - 'xlsx' => ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/vnd.ms-excel', 'application/msword', 'application/x-zip'], + 'dotx' => [ + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/zip', + 'application/msword' + ], + 'xlsx' => [ + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + 'application/zip', + 'application/vnd.ms-excel', + 'application/msword', + 'application/x-zip' + ], 'word' => ['application/msword', 'application/octet-stream'], 'xl' => 'application/excel', 'eml' => 'message/rfc822', @@ -155,11 +240,36 @@ 'ics' => 'text/calendar', 'ical' => 'text/calendar', 'zsh' => 'text/x-scriptzsh', - '7z' => ['application/x-7z-compressed', 'application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'], - '7zip' => ['application/x-7z-compressed', 'application/x-compressed', 'application/x-zip-compressed', 'application/zip', 'multipart/x-zip'], - 'cdr' => ['application/cdr', 'application/coreldraw', 'application/x-cdr', 'application/x-coreldraw', 'image/cdr', 'image/x-cdr', 'zz-application/zz-winassoc-cdr'], + '7z' => [ + 'application/x-7z-compressed', + 'application/x-compressed', + 'application/x-zip-compressed', + 'application/zip', + 'multipart/x-zip' + ], + '7zip' => [ + 'application/x-7z-compressed', + 'application/x-compressed', + 'application/x-zip-compressed', + 'application/zip', + 'multipart/x-zip' + ], + 'cdr' => [ + 'application/cdr', + 'application/coreldraw', + 'application/x-cdr', + 'application/x-coreldraw', + 'image/cdr', + 'image/x-cdr', + 'zz-application/zz-winassoc-cdr' + ], 'wma' => ['audio/x-ms-wma', 'video/x-ms-asf'], - 'jar' => ['application/java-archive', 'application/x-java-application', 'application/x-jar', 'application/x-compressed'], + 'jar' => [ + 'application/java-archive', + 'application/x-java-application', + 'application/x-jar', + 'application/x-compressed' + ], 'svg' => ['image/svg+xml', 'application/xml', 'text/xml'], 'vcf' => 'text/x-vcard', 'srt' => ['text/srt', 'text/plain'], diff --git a/application/config/profiler.php b/application/config/profiler.php index 4c08a5a39c..63b1fecfca 100644 --- a/application/config/profiler.php +++ b/application/config/profiler.php @@ -12,6 +12,5 @@ | */ - /* End of file profiler.php */ /* Location: ./application/config/profiler.php */ diff --git a/application/config/routes.php b/application/config/routes.php index d52a18ee69..0ee2d88e50 100644 --- a/application/config/routes.php +++ b/application/config/routes.php @@ -55,7 +55,7 @@ $route['404_override'] = ''; -$route['translate_uri_dashes'] = FALSE; +$route['translate_uri_dashes'] = false; /* | ------------------------------------------------------------------------- @@ -86,19 +86,16 @@ header('Access-Control-Allow-Credentials: "true"'); -if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) -{ +if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) { // May also be using PUT, PATCH, HEAD etc header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD'); } -if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) -{ +if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) { header('Access-Control-Allow-Headers: ' . $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']); } -if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') -{ +if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit(0); } diff --git a/application/config/testing/routes.php b/application/config/testing/routes.php index f5b2c68d59..a5d538fe6e 100644 --- a/application/config/testing/routes.php +++ b/application/config/testing/routes.php @@ -13,8 +13,7 @@ $route['default_controller'] = 'test/index'; $route['404_override'] = 'test/index'; // when in doubt, use the hammer -$route['translate_uri_dashes'] = FALSE; - +$route['translate_uri_dashes'] = false; /* End of file routes.php */ /* Location: ./application/config/testing/routes.php */ diff --git a/application/controllers/About.php b/application/controllers/About.php index 3388876741..2cb21c7d17 100644 --- a/application/controllers/About.php +++ b/application/controllers/About.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class About extends EA_Controller { +class About extends EA_Controller +{ /** * About constructor. */ @@ -48,11 +49,9 @@ public function index() session(['dest_url' => site_url('about')]); $user_id = session('user_id'); - - if (cannot('view', PRIV_USER_SETTINGS)) - { - if ($user_id) - { + + if (cannot('view', PRIV_USER_SETTINGS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -65,14 +64,14 @@ public function index() script_vars([ 'user_id' => $user_id, - 'role_slug' => $role_slug, + 'role_slug' => $role_slug ]); html_vars([ 'page_title' => lang('settings'), 'active_menu' => PRIV_SYSTEM_SETTINGS, 'user_display_name' => $this->accounts->get_user_display_name($user_id), - 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug), + 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug) ]); $this->load->view('pages/about'); diff --git a/application/controllers/Account.php b/application/controllers/Account.php index b95923db32..3547ccedd3 100644 --- a/application/controllers/Account.php +++ b/application/controllers/Account.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Account extends EA_Controller { +class Account extends EA_Controller +{ /** * Account constructor. */ @@ -49,10 +50,8 @@ public function index() $user_id = session('user_id'); - if (cannot('view', PRIV_USER_SETTINGS)) - { - if ($user_id) - { + if (cannot('view', PRIV_USER_SETTINGS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -64,14 +63,14 @@ public function index() $account = $this->users_model->find($user_id); script_vars([ - 'account' => $account, + 'account' => $account ]); html_vars([ 'page_title' => lang('settings'), 'active_menu' => PRIV_SYSTEM_SETTINGS, 'user_display_name' => $this->accounts->get_user_display_name($user_id), - 'grouped_timezones' => $this->timezones->to_grouped_array(), + 'grouped_timezones' => $this->timezones->to_grouped_array() ]); $this->load->view('pages/account'); @@ -82,10 +81,8 @@ public function index() */ public function save() { - try - { - if (cannot('edit', PRIV_USER_SETTINGS)) - { + try { + if (cannot('edit', PRIV_USER_SETTINGS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } @@ -110,15 +107,9 @@ public function save() 'settings' ]); - $this->users_model->only($account['settings'], [ - 'username', - 'password', - 'notifications', - 'calendar_view' - ]); + $this->users_model->only($account['settings'], ['username', 'password', 'notifications', 'calendar_view']); - if (empty($account['password'])) - { + if (empty($account['password'])) { unset($account['password']); } @@ -128,13 +119,11 @@ public function save() 'user_email' => $account['email'], 'username' => $account['settings']['username'], 'timezone' => $account['timezone'], - 'language' => $account['language'], + 'language' => $account['language'] ]); response(); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -144,8 +133,7 @@ public function save() */ public function validate_username() { - try - { + try { $username = request('username'); $user_id = request('user_id'); @@ -153,11 +141,9 @@ public function validate_username() $is_valid = $this->users_model->validate_username($username, $user_id); json_response([ - 'is_valid' => $is_valid, + 'is_valid' => $is_valid ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Admins.php b/application/controllers/Admins.php index 3a0628315e..1fee46a888 100644 --- a/application/controllers/Admins.php +++ b/application/controllers/Admins.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Admins extends EA_Controller { +class Admins extends EA_Controller +{ /** * Admins constructor. */ @@ -46,10 +47,8 @@ public function index() $user_id = session('user_id'); - if (cannot('view', PRIV_USERS)) - { - if ($user_id) - { + if (cannot('view', PRIV_USERS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -64,15 +63,15 @@ public function index() 'user_id' => $user_id, 'role_slug' => $role_slug, 'timezones' => $this->timezones->to_array(), - 'min_password_length' => MIN_PASSWORD_LENGTH, + 'min_password_length' => MIN_PASSWORD_LENGTH ]); - + html_vars([ 'page_title' => lang('admins'), 'active_menu' => PRIV_USERS, 'user_display_name' => $this->accounts->get_user_display_name($user_id), 'grouped_timezones' => $this->timezones->to_grouped_array(), - 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug), + 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug) ]); $this->load->view('pages/admins'); @@ -83,11 +82,9 @@ public function index() */ public function search() { - try - { - if (cannot('view', PRIV_USERS)) - { - abort(403,'Forbidden'); + try { + if (cannot('view', PRIV_USERS)) { + abort(403, 'Forbidden'); } $keyword = request('keyword', ''); @@ -101,9 +98,7 @@ public function search() $admins = $this->admins_model->search($keyword, $limit, $offset, $order_by); json_response($admins); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -113,13 +108,11 @@ public function search() */ public function store() { - try - { - if (cannot('add', PRIV_USERS)) - { + try { + if (cannot('add', PRIV_USERS)) { abort(403, 'Forbidden'); } - + $admin = request('admin'); $this->admins_model->only($admin, [ @@ -138,26 +131,39 @@ public function store() 'settings' ]); - $this->admins_model->only($admin['settings'], [ - 'username', - 'password', - 'notifications', - 'calendar_view' - ]); + $this->admins_model->only($admin['settings'], ['username', 'password', 'notifications', 'calendar_view']); $admin_id = $this->admins_model->save($admin); - - $admin = $this->admins_model->find($admin_id); - - $this->webhooks_client->trigger(WEBHOOK_ADMIN_SAVE, $admin); + + $admin = $this->admins_model->find($admin_id); + + $this->webhooks_client->trigger(WEBHOOK_ADMIN_SAVE, $admin); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $admin_id ]); + } catch (Throwable $e) { + json_exception($e); } - catch (Throwable $e) - { + } + + /** + * Find an admin. + */ + public function find() + { + try { + if (cannot('view', PRIV_USERS)) { + abort(403, 'Forbidden'); + } + + $admin_id = request('admin_id'); + + $admin = $this->admins_model->find($admin_id); + + json_response($admin); + } catch (Throwable $e) { json_exception($e); } } @@ -167,10 +173,8 @@ public function store() */ public function update() { - try - { - if (cannot('edit', PRIV_USERS)) - { + try { + if (cannot('edit', PRIV_USERS)) { abort(403, 'Forbidden'); } @@ -193,12 +197,7 @@ public function update() 'settings' ]); - $this->admins_model->only($admin['settings'], [ - 'username', - 'password', - 'notifications', - 'calendar_view' - ]); + $this->admins_model->only($admin['settings'], ['username', 'password', 'notifications', 'calendar_view']); $admin_id = $this->admins_model->save($admin); @@ -207,12 +206,10 @@ public function update() $this->webhooks_client->trigger(WEBHOOK_ADMIN_SAVE, $admin); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $admin_id ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -222,10 +219,8 @@ public function update() */ public function destroy() { - try - { - if (cannot('delete', PRIV_USERS)) - { + try { + if (cannot('delete', PRIV_USERS)) { abort(403, 'Forbidden'); } @@ -238,35 +233,9 @@ public function destroy() $this->webhooks_client->trigger(WEBHOOK_ADMIN_DELETE, $admin); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { - json_exception($e); - } - } - - /** - * Find an admin. - */ - public function find() - { - try - { - if (cannot('view', PRIV_USERS)) - { - abort(403, 'Forbidden'); - } - - $admin_id = request('admin_id'); - - $admin = $this->admins_model->find($admin_id); - - json_response($admin); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Api_settings.php b/application/controllers/Api_settings.php index c57ec94a66..910cd41ed1 100644 --- a/application/controllers/Api_settings.php +++ b/application/controllers/Api_settings.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Api_settings extends EA_Controller { +class Api_settings extends EA_Controller +{ /** * Api_settings constructor. */ @@ -40,10 +41,8 @@ public function index() $user_id = session('user_id'); - if (cannot('view', PRIV_SYSTEM_SETTINGS)) - { - if ($user_id) - { + if (cannot('view', PRIV_SYSTEM_SETTINGS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -57,13 +56,13 @@ public function index() script_vars([ 'user_id' => $user_id, 'role_slug' => $role_slug, - 'api_settings' => $this->settings_model->get('name like "api_%"'), + 'api_settings' => $this->settings_model->get('name like "api_%"') ]); html_vars([ 'page_title' => lang('api'), 'active_menu' => PRIV_SYSTEM_SETTINGS, - 'user_display_name' => $this->accounts->get_user_display_name($user_id), + 'user_display_name' => $this->accounts->get_user_display_name($user_id) ]); $this->load->view('pages/api_settings'); @@ -74,21 +73,21 @@ public function index() */ public function save() { - try - { - if (cannot('edit', PRIV_SYSTEM_SETTINGS)) - { + try { + if (cannot('edit', PRIV_SYSTEM_SETTINGS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } $settings = request('api_settings', []); - foreach ($settings as $setting) - { - $existing_setting = $this->settings_model->query()->where('name', $setting['name'])->get()->row_array(); + foreach ($settings as $setting) { + $existing_setting = $this->settings_model + ->query() + ->where('name', $setting['name']) + ->get() + ->row_array(); - if ( ! empty($existing_setting)) - { + if (!empty($existing_setting)) { $setting['id'] = $existing_setting['id']; } @@ -96,9 +95,7 @@ public function save() } response(); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Appointments.php b/application/controllers/Appointments.php index 519013646a..e07fb8247d 100644 --- a/application/controllers/Appointments.php +++ b/application/controllers/Appointments.php @@ -21,7 +21,8 @@ * * @package Controllers */ -class Appointments extends EA_Controller { +class Appointments extends EA_Controller +{ /** * Appointments constructor. */ @@ -54,10 +55,8 @@ public function index(string $appointment_hash = '') */ public function search() { - try - { - if (cannot('view', PRIV_APPOINTMENTS)) - { + try { + if (cannot('view', PRIV_APPOINTMENTS)) { abort(403, 'Forbidden'); } @@ -72,9 +71,7 @@ public function search() $appointments = $this->appointments_model->search($keyword, $limit, $offset, $order_by); json_response($appointments); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -84,25 +81,23 @@ public function search() */ public function store() { - try - { - if (cannot('add', PRIV_APPOINTMENTS)) - { + try { + if (cannot('add', PRIV_APPOINTMENTS)) { abort(403, 'Forbidden'); } - $appointment = json_decode(request('appointment'), TRUE); + $appointment = json_decode(request('appointment'), true); $this->appointments_model->only($appointment, [ - 'start_datetime', - 'end_datetime', - 'location', - 'notes', - 'color', - 'is_unavailability', - 'id_users_provider', - 'id_users_customer', - 'id_services', + 'start_datetime', + 'end_datetime', + 'location', + 'notes', + 'color', + 'is_unavailability', + 'id_users_provider', + 'id_users_customer', + 'id_services' ]); $appointment_id = $this->appointments_model->save($appointment); @@ -112,12 +107,30 @@ public function store() $this->webhooks_client->trigger(WEBHOOK_APPOINTMENT_SAVE, $appointment); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $appointment_id ]); + } catch (Throwable $e) { + json_exception($e); } - catch (Throwable $e) - { + } + + /** + * Find an appointment. + */ + public function find() + { + try { + if (cannot('view', PRIV_APPOINTMENTS)) { + abort(403, 'Forbidden'); + } + + $appointment_id = request('appointment_id'); + + $appointment = $this->appointments_model->find($appointment_id); + + json_response($appointment); + } catch (Throwable $e) { json_exception($e); } } @@ -127,14 +140,12 @@ public function store() */ public function update() { - try - { - if (cannot('edit', PRIV_APPOINTMENTS)) - { + try { + if (cannot('edit', PRIV_APPOINTMENTS)) { abort(403, 'Forbidden'); } - $appointment = json_decode(request('appointment'), TRUE); + $appointment = json_decode(request('appointment'), true); $this->appointments_model->only($appointment, [ 'id', @@ -146,18 +157,16 @@ public function update() 'is_unavailability', 'id_users_provider', 'id_users_customer', - 'id_services', + 'id_services' ]); $appointment_id = $this->appointments_model->save($appointment); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $appointment_id ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -167,51 +176,23 @@ public function update() */ public function destroy() { - try - { - if (cannot('delete', PRIV_APPOINTMENTS)) - { + try { + if (cannot('delete', PRIV_APPOINTMENTS)) { abort(403, 'Forbidden'); } $appointment_id = request('appointment_id'); - - $appointment = $this->appointments_model->find($appointment_id); + + $appointment = $this->appointments_model->find($appointment_id); $this->appointments_model->delete($appointment_id); $this->webhooks_client->trigger(WEBHOOK_APPOINTMENT_DELETE, $appointment); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { - json_exception($e); - } - } - - /** - * Find an appointment. - */ - public function find() - { - try - { - if (cannot('view', PRIV_APPOINTMENTS)) - { - abort(403, 'Forbidden'); - } - - $appointment_id = request('appointment_id'); - - $appointment = $this->appointments_model->find($appointment_id); - - json_response($appointment); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Backend.php b/application/controllers/Backend.php index 62628728d3..b7eb42bc24 100755 --- a/application/controllers/Backend.php +++ b/application/controllers/Backend.php @@ -36,10 +36,11 @@ * Handles the backend related operations. * * @package Controllers - * + * * @deprecated Since 1.5 */ -class Backend extends EA_Controller { +class Backend extends EA_Controller +{ /** * Display the calendar page. * @@ -47,12 +48,9 @@ class Backend extends EA_Controller { */ public function index(string $appointment_hash = '') { - if (empty($appointment_hash)) - { + if (empty($appointment_hash)) { redirect('calendar'); - } - else - { + } else { redirect('calendar/reschedule/' . $appointment_hash); } } diff --git a/application/controllers/Backend_api.php b/application/controllers/Backend_api.php index e9be3766e0..b0798d196a 100755 --- a/application/controllers/Backend_api.php +++ b/application/controllers/Backend_api.php @@ -36,10 +36,11 @@ * Handles the backend API related operations. * * @package Controllers - * + * * @deprecated Since 1.5 */ -class Backend_api extends EA_Controller { +class Backend_api extends EA_Controller +{ /** * Get Calendar Events */ diff --git a/application/controllers/Blocked_periods.php b/application/controllers/Blocked_periods.php index d228d3e016..418295539c 100644 --- a/application/controllers/Blocked_periods.php +++ b/application/controllers/Blocked_periods.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Blocked_periods extends EA_Controller { +class Blocked_periods extends EA_Controller +{ /** * Blocked_periods constructor. */ @@ -46,10 +47,8 @@ public function index() $user_id = session('user_id'); - if (cannot('view', PRIV_BLOCKED_PERIODS)) - { - if ($user_id) - { + if (cannot('view', PRIV_BLOCKED_PERIODS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -65,7 +64,7 @@ public function index() 'role_slug' => $role_slug, 'date_format' => setting('date_format'), 'time_format' => setting('time_format'), - 'first_weekday' => setting('first_weekday'), + 'first_weekday' => setting('first_weekday') ]); html_vars([ @@ -73,7 +72,7 @@ public function index() 'active_menu' => PRIV_BLOCKED_PERIODS, 'user_display_name' => $this->accounts->get_user_display_name($user_id), 'timezones' => $this->timezones->to_array(), - 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug), + 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug) ]); $this->load->view('pages/blocked_periods'); @@ -84,10 +83,8 @@ public function index() */ public function search() { - try - { - if (cannot('view', PRIV_BLOCKED_PERIODS)) - { + try { + if (cannot('view', PRIV_BLOCKED_PERIODS)) { abort(403, 'Forbidden'); } @@ -102,9 +99,7 @@ public function search() $blocked_periods = $this->blocked_periods_model->search($keyword, $limit, $offset, $order_by); json_response($blocked_periods); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -114,21 +109,14 @@ public function search() */ public function store() { - try - { - if (cannot('add', PRIV_BLOCKED_PERIODS)) - { + try { + if (cannot('add', PRIV_BLOCKED_PERIODS)) { abort(403, 'Forbidden'); } $blocked_period = request('blocked_period'); - $this->blocked_periods_model->only($blocked_period, [ - 'name', - 'start_datetime', - 'end_datetime', - 'notes' - ]); + $this->blocked_periods_model->only($blocked_period, ['name', 'start_datetime', 'end_datetime', 'notes']); $blocked_period_id = $this->blocked_periods_model->save($blocked_period); @@ -137,12 +125,30 @@ public function store() $this->webhooks_client->trigger(WEBHOOK_BLOCKED_PERIOD_SAVE, $blocked_period); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $blocked_period_id ]); + } catch (Throwable $e) { + json_exception($e); } - catch (Throwable $e) - { + } + + /** + * Find a service-category. + */ + public function find() + { + try { + if (cannot('view', PRIV_BLOCKED_PERIODS)) { + abort(403, 'Forbidden'); + } + + $blocked_period_id = request('blocked_period_id'); + + $blocked_period = $this->blocked_periods_model->find($blocked_period_id); + + json_response($blocked_period); + } catch (Throwable $e) { json_exception($e); } } @@ -152,10 +158,8 @@ public function store() */ public function update() { - try - { - if (cannot('edit', PRIV_BLOCKED_PERIODS)) - { + try { + if (cannot('edit', PRIV_BLOCKED_PERIODS)) { abort(403, 'Forbidden'); } @@ -176,12 +180,10 @@ public function update() $this->webhooks_client->trigger(WEBHOOK_BLOCKED_PERIOD_SAVE, $blocked_period); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $blocked_period_id ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -191,10 +193,8 @@ public function update() */ public function destroy() { - try - { - if (cannot('delete', PRIV_BLOCKED_PERIODS)) - { + try { + if (cannot('delete', PRIV_BLOCKED_PERIODS)) { abort(403, 'Forbidden'); } @@ -207,35 +207,9 @@ public function destroy() $this->webhooks_client->trigger(WEBHOOK_BLOCKED_PERIOD_DELETE, $blocked_period); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { - json_exception($e); - } - } - - /** - * Find a service-category. - */ - public function find() - { - try - { - if (cannot('view', PRIV_BLOCKED_PERIODS)) - { - abort(403, 'Forbidden'); - } - - $blocked_period_id = request('blocked_period_id'); - - $blocked_period = $this->blocked_periods_model->find($blocked_period_id); - - json_response($blocked_period); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Booking.php b/application/controllers/Booking.php index 5800dd292e..3ec007bc9b 100755 --- a/application/controllers/Booking.php +++ b/application/controllers/Booking.php @@ -21,7 +21,8 @@ * * @package Controllers */ -class Booking extends EA_Controller { +class Booking extends EA_Controller +{ /** * Booking constructor. */ @@ -46,6 +47,20 @@ public function __construct() $this->load->library('webhooks_client'); } + /** + * Render the booking page and display the selected appointment. + * + * This method will call the "index" callback to handle the page rendering. + * + * @param string $appointment_hash + */ + public function reschedule(string $appointment_hash) + { + html_vars(['appointment_hash' => $appointment_hash]); + + $this->index(); + } + /** * Render the booking page. * @@ -53,8 +68,7 @@ public function __construct() */ public function index() { - if ( ! is_app_installed()) - { + if (!is_app_installed()) { redirect('installation'); return; @@ -67,12 +81,11 @@ public function index() $google_analytics_code = setting('google_analytics_code'); $matomo_analytics_url = setting('matomo_analytics_url'); - if ($disable_booking) - { + if ($disable_booking) { $disable_booking_message = setting('disable_booking_message'); html_vars([ - 'show_message' => TRUE, + 'show_message' => true, 'page_title' => lang('page_title') . ' ' . $company_name, 'message_title' => lang('booking_is_disabled'), 'message_text' => $disable_booking_message, @@ -86,11 +99,10 @@ public function index() return; } - $available_services = $this->services_model->get_available_services(TRUE); - $available_providers = $this->providers_model->get_available_providers(TRUE); + $available_services = $this->services_model->get_available_services(true); + $available_providers = $this->providers_model->get_available_providers(true); - foreach ($available_providers as &$available_provider) - { + foreach ($available_providers as &$available_provider) { // Only expose the required provider data. $this->providers_model->only($available_provider, [ @@ -133,8 +145,7 @@ public function index() $book_advance_timeout = setting('book_advance_timeout'); $theme = request('theme', setting('theme', 'default')); - if (empty($theme) || ! file_exists(__DIR__ . '/../../assets/css/themes/' . $theme . '.min.css')) - { + if (empty($theme) || !file_exists(__DIR__ . '/../../assets/css/themes/' . $theme . '.min.css')) { $theme = 'default'; } @@ -143,18 +154,16 @@ public function index() $appointment_hash = html_vars('appointment_hash'); - if ( ! empty($appointment_hash)) - { + if (!empty($appointment_hash)) { // Load the appointments data and enable the manage mode of the booking page. - $manage_mode = TRUE; + $manage_mode = true; $results = $this->appointments_model->get(['hash' => $appointment_hash]); - if (empty($results)) - { + if (empty($results)) { html_vars([ - 'show_message' => TRUE, + 'show_message' => true, 'page_title' => lang('page_title') . ' ' . $company_name, 'message_title' => lang('appointment_not_found'), 'message_text' => lang('appointment_does_not_exist_in_db'), @@ -174,14 +183,13 @@ public function index() $limit = strtotime('+' . $book_advance_timeout . ' minutes', strtotime('now')); - if ($start_datetime < $limit) - { + if ($start_datetime < $limit) { $hours = floor($book_advance_timeout / 60); - $minutes = ($book_advance_timeout % 60); + $minutes = $book_advance_timeout % 60; html_vars([ - 'show_message' => TRUE, + 'show_message' => true, 'page_title' => lang('page_title') . ' ' . $company_name, 'message_title' => lang('appointment_locked'), 'message_text' => strtr(lang('appointment_locked_message'), [ @@ -200,18 +208,16 @@ public function index() $appointment = $results[0]; $provider = $this->providers_model->find($appointment['id_users_provider']); $customer = $this->customers_model->find($appointment['id_users_customer']); - $customer_token = md5(uniqid(mt_rand(), TRUE)); + $customer_token = md5(uniqid(mt_rand(), true)); // Cache the token for 10 minutes. $this->cache->save('customer-token-' . $customer_token, $customer['id'], 600); - } - else - { - $manage_mode = FALSE; - $customer_token = FALSE; - $appointment = NULL; - $provider = NULL; - $customer = NULL; + } else { + $manage_mode = false; + $customer_token = false; + $appointment = null; + $provider = null; + $customer = null; } script_vars([ @@ -226,7 +232,7 @@ public function index() 'future_booking_limit' => setting('future_booking_limit'), 'appointment_data' => $appointment, 'provider_data' => $provider, - 'customer_data' => $customer, + 'customer_data' => $customer ]); html_vars([ @@ -272,187 +278,48 @@ public function index() 'customer_token' => $customer_token, 'appointment_data' => $appointment, 'provider_data' => $provider, - 'customer_data' => $customer, + 'customer_data' => $customer ]); $this->load->view('pages/booking'); } - /** - * Render the booking page and display the selected appointment. - * - * This method will call the "index" callback to handle the page rendering. - * - * @param string $appointment_hash - */ - public function reschedule(string $appointment_hash) - { - html_vars(['appointment_hash' => $appointment_hash]); - - $this->index(); - } - - /** - * Get the available appointment hours for the selected date. - * - * This method answers to an AJAX request. It calculates the available hours for the given service, provider and - * date. - */ - public function get_available_hours() - { - try - { - $provider_id = request('provider_id'); - $service_id = request('service_id'); - $selected_date = request('selected_date'); - - // Do not continue if there was no provider selected (more likely there is no provider in the system). - - if (empty($provider_id)) - { - json_response(); - - 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_appointment_id = request('manage_mode') ? request('appointment_id') : NULL; - - // 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. - - $service = $this->services_model->find($service_id); - - if ($provider_id === ANY_PROVIDER) - { - $providers = $this->providers_model->get(); - - $available_hours = []; - - foreach ($providers as $provider) - { - if ( ! in_array($service_id, $provider['services'])) - { - continue; - } - - $provider_available_hours = $this->availability->get_available_hours($selected_date, $service, $provider, $exclude_appointment_id); - - $available_hours = array_merge($available_hours, $provider_available_hours); - } - - $available_hours = array_unique(array_values($available_hours)); - - sort($available_hours); - - $response = $available_hours; - } - else - { - $provider = $this->providers_model->find($provider_id); - - $response = $this->availability->get_available_hours($selected_date, $service, $provider, $exclude_appointment_id); - } - - json_response($response); - } - catch (Throwable $e) - { - json_exception($e); - } - } - - /** - * 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 Service ID - * @param string $date Selected date (Y-m-d). - * @param string|null $hour Selected hour (H:i). - * - * @return int|null Returns the ID of the provider that can provide the service at the selected date. - * - * @throws Exception - */ - protected function search_any_provider(int $service_id, string $date, string $hour = NULL): ?int - { - $available_providers = $this->providers_model->get_available_providers(TRUE); - - $service = $this->services_model->find($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. - $available_hours = $this->availability->get_available_hours($date, $service, $provider); - - if (count($available_hours) > $max_hours_count && (empty($hour) || in_array($hour, $available_hours))) - { - $provider_id = $provider['id']; - - $max_hours_count = count($available_hours); - } - } - } - } - - return $provider_id; - } - - /** * Register the appointment to the database. */ public function register() { - try - { + try { $post_data = request('post_data'); $captcha = request('captcha'); $appointment = $post_data['appointment']; $customer = $post_data['customer']; $manage_mode = filter_var($post_data['manage_mode'], FILTER_VALIDATE_BOOLEAN); - if ( ! array_key_exists('address', $customer)) - { + if (!array_key_exists('address', $customer)) { $customer['address'] = ''; } - if ( ! array_key_exists('city', $customer)) - { + if (!array_key_exists('city', $customer)) { $customer['city'] = ''; } - if ( ! array_key_exists('zip_code', $customer)) - { + if (!array_key_exists('zip_code', $customer)) { $customer['zip_code'] = ''; } - if ( ! array_key_exists('notes', $customer)) - { + if (!array_key_exists('notes', $customer)) { $customer['notes'] = ''; } - if ( ! array_key_exists('phone_number', $customer)) - { + if (!array_key_exists('phone_number', $customer)) { $customer['address'] = ''; } // Check appointment availability before registering it to the database. $appointment['id_users_provider'] = $this->check_datetime_availability(); - if ( ! $appointment['id_users_provider']) - { + if (!$appointment['id_users_provider']) { throw new RuntimeException(lang('requested_hour_is_unavailable')); } @@ -460,23 +327,21 @@ public function register() $service = $this->services_model->find($appointment['id_services']); - $require_captcha = (bool)setting('require_captcha'); + $require_captcha = (bool) setting('require_captcha'); $captcha_phrase = session('captcha_phrase'); // Validate the CAPTCHA string. - if ($require_captcha && strtoupper($captcha_phrase) !== strtoupper($captcha)) - { + if ($require_captcha && strtoupper($captcha_phrase) !== strtoupper($captcha)) { json_response([ - 'captcha_verification' => FALSE + 'captcha_verification' => false ]); return; } - if ($this->customers_model->exists($customer)) - { + if ($this->customers_model->exists($customer)) { $customer['id'] = $this->customers_model->find_record_id($customer); $existing_appointments = $this->appointments_model->get([ @@ -485,19 +350,16 @@ public function register() 'end_datetime >=' => $appointment['end_datetime'] ]); - if (count($existing_appointments)) - { + if (count($existing_appointments)) { throw new RuntimeException(lang('customer_is_already_booked')); } } - if (empty($appointment['location']) && ! empty($service['location'])) - { + if (empty($appointment['location']) && !empty($service['location'])) { $appointment['location'] = $service['location']; } - if (empty($appointment['color']) && ! empty($service['color'])) - { + if (empty($appointment['color']) && !empty($service['color'])) { $appointment['color'] = $service['color']; } @@ -508,18 +370,16 @@ public function register() 'first_name' => $customer['first_name'] ?? '-', 'last_name' => $customer['last_name'] ?? '-', 'email' => $customer['email'] ?? '-', - 'ip' => $customer_ip, + 'ip' => $customer_ip ]; - if (setting('display_terms_and_conditions')) - { + if (setting('display_terms_and_conditions')) { $consent['type'] = 'terms-and-conditions'; $this->consents_model->save($consent); } - if (setting('display_privacy_policy')) - { + if (setting('display_privacy_policy')) { $consent['type'] = 'privacy-policy'; $this->consents_model->save($consent); @@ -539,19 +399,19 @@ public function register() 'state', 'zip_code', 'timezone', - 'language', + 'language' ]); $customer_id = $this->customers_model->save($customer); $customer = $this->customers_model->find($customer_id); $appointment['id_users_customer'] = $customer_id; - $appointment['is_unavailability'] = FALSE; + $appointment['is_unavailability'] = false; $appointment['color'] = $service['color']; $appointment_status_options_json = setting('appointment_status_options', '[]'); - $appointment_status_options = json_decode($appointment_status_options_json, TRUE) ?? []; - $appointment['status'] = $appointment_status_options[0] ?? NULL; + $appointment_status_options = json_decode($appointment_status_options_json, true) ?? []; + $appointment['status'] = $appointment_status_options[0] ?? null; $this->appointments_model->only($appointment, [ 'id', @@ -564,7 +424,7 @@ public function register() 'is_unavailability', 'id_users_provider', 'id_users_customer', - 'id_services', + 'id_services' ]); $appointment_id = $this->appointments_model->save($appointment); @@ -580,7 +440,14 @@ public function register() $this->synchronization->sync_appointment_saved($appointment, $service, $provider, $customer, $settings); - $this->notifications->notify_appointment_saved($appointment, $service, $provider, $customer, $settings, $manage_mode); + $this->notifications->notify_appointment_saved( + $appointment, + $service, + $provider, + $customer, + $settings, + $manage_mode + ); $this->webhooks_client->trigger(WEBHOOK_APPOINTMENT_SAVE, $appointment); @@ -590,9 +457,7 @@ public function register() ]; json_response($response); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -623,8 +488,7 @@ protected function check_datetime_availability(): ?int $hour = $appointment_start->format('H:i'); - if ($appointment['id_users_provider'] === ANY_PROVIDER) - { + if ($appointment['id_users_provider'] === ANY_PROVIDER) { $appointment['id_users_provider'] = $this->search_any_provider($appointment['id_services'], $date, $hour); return $appointment['id_users_provider']; @@ -632,26 +496,146 @@ protected function check_datetime_availability(): ?int $service = $this->services_model->find($appointment['id_services']); - $exclude_appointment_id = $appointment['id'] ?? NULL; + $exclude_appointment_id = $appointment['id'] ?? null; $provider = $this->providers_model->find($appointment['id_users_provider']); - $available_hours = $this->availability->get_available_hours($date, $service, $provider, $exclude_appointment_id); + $available_hours = $this->availability->get_available_hours( + $date, + $service, + $provider, + $exclude_appointment_id + ); - $is_still_available = FALSE; + $is_still_available = false; $appointment_hour = date('H:i', strtotime($appointment['start_datetime'])); - foreach ($available_hours as $available_hour) - { - if ($appointment_hour === $available_hour) - { - $is_still_available = TRUE; + foreach ($available_hours as $available_hour) { + if ($appointment_hour === $available_hour) { + $is_still_available = true; break; } } - return $is_still_available ? $appointment['id_users_provider'] : NULL; + return $is_still_available ? $appointment['id_users_provider'] : null; + } + + /** + * 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 Service ID + * @param string $date Selected date (Y-m-d). + * @param string|null $hour Selected hour (H:i). + * + * @return int|null Returns the ID of the provider that can provide the service at the selected date. + * + * @throws Exception + */ + protected function search_any_provider(int $service_id, string $date, string $hour = null): ?int + { + $available_providers = $this->providers_model->get_available_providers(true); + + $service = $this->services_model->find($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. + $available_hours = $this->availability->get_available_hours($date, $service, $provider); + + if ( + count($available_hours) > $max_hours_count && + (empty($hour) || in_array($hour, $available_hours)) + ) { + $provider_id = $provider['id']; + + $max_hours_count = count($available_hours); + } + } + } + } + + return $provider_id; + } + + /** + * Get the available appointment hours for the selected date. + * + * This method answers to an AJAX request. It calculates the available hours for the given service, provider and + * date. + */ + public function get_available_hours() + { + try { + $provider_id = request('provider_id'); + $service_id = request('service_id'); + $selected_date = request('selected_date'); + + // Do not continue if there was no provider selected (more likely there is no provider in the system). + + if (empty($provider_id)) { + json_response(); + + 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_appointment_id = request('manage_mode') ? request('appointment_id') : null; + + // 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. + + $service = $this->services_model->find($service_id); + + if ($provider_id === ANY_PROVIDER) { + $providers = $this->providers_model->get(); + + $available_hours = []; + + foreach ($providers as $provider) { + if (!in_array($service_id, $provider['services'])) { + continue; + } + + $provider_available_hours = $this->availability->get_available_hours( + $selected_date, + $service, + $provider, + $exclude_appointment_id + ); + + $available_hours = array_merge($available_hours, $provider_available_hours); + } + + $available_hours = array_unique(array_values($available_hours)); + + sort($available_hours); + + $response = $available_hours; + } else { + $provider = $this->providers_model->find($provider_id); + + $response = $this->availability->get_available_hours( + $selected_date, + $service, + $provider, + $exclude_appointment_id + ); + } + + json_response($response); + } catch (Throwable $e) { + json_exception($e); + } } /** @@ -665,40 +649,35 @@ protected function check_datetime_availability(): ?int */ public function get_unavailable_dates() { - try - { + try { $provider_id = request('provider_id'); $service_id = request('service_id'); $appointment_id = request('appointment_id'); $manage_mode = filter_var(request('manage_mode'), FILTER_VALIDATE_BOOLEAN); $selected_date_string = request('selected_date'); $selected_date = new DateTime($selected_date_string); - $number_of_days_in_month = (int)$selected_date->format('t'); + $number_of_days_in_month = (int) $selected_date->format('t'); $unavailable_dates = []; - $provider_ids = $provider_id === ANY_PROVIDER - ? $this->search_providers_by_service($service_id) - : [$provider_id]; + $provider_ids = + $provider_id === ANY_PROVIDER ? $this->search_providers_by_service($service_id) : [$provider_id]; - $exclude_appointment_id = $manage_mode ? $appointment_id : NULL; + $exclude_appointment_id = $manage_mode ? $appointment_id : null; // Get the service record. $service = $this->services_model->find($service_id); - for ($i = 1; $i <= $number_of_days_in_month; $i++) - { + for ($i = 1; $i <= $number_of_days_in_month; $i++) { $current_date = new DateTime($selected_date->format('Y-m') . '-' . $i); - if ($current_date < new DateTime(date('Y-m-d 00:00:00'))) - { + if ($current_date < new DateTime(date('Y-m-d 00:00:00'))) { // Past dates become immediately unavailability. $unavailable_dates[] = $current_date->format('Y-m-d'); continue; } // Finding at least one slot of availability. - foreach ($provider_ids as $current_provider_id) - { + foreach ($provider_ids as $current_provider_id) { $provider = $this->providers_model->find($current_provider_id); $available_hours = $this->availability->get_available_hours( @@ -708,32 +687,27 @@ public function get_unavailable_dates() $exclude_appointment_id ); - if ( ! empty($available_hours)) - { + if (!empty($available_hours)) { break; } } // No availability amongst all the provider. - if (empty($available_hours)) - { + if (empty($available_hours)) { $unavailable_dates[] = $current_date->format('Y-m-d'); } } - if (count($unavailable_dates) === $number_of_days_in_month) - { + if (count($unavailable_dates) === $number_of_days_in_month) { json_response([ - 'is_month_unavailable' => TRUE, + 'is_month_unavailable' => true ]); return; } json_response($unavailable_dates); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -749,15 +723,12 @@ public function get_unavailable_dates() */ protected function search_providers_by_service(int $service_id): array { - $available_providers = $this->providers_model->get_available_providers(TRUE); + $available_providers = $this->providers_model->get_available_providers(true); $provider_list = []; - foreach ($available_providers as $provider) - { - foreach ($provider['services'] as $provider_service_id) - { - if ($provider_service_id === $service_id) - { + foreach ($available_providers as $provider) { + foreach ($provider['services'] as $provider_service_id) { + if ($provider_service_id === $service_id) { // Check if the provider is affected to the selected service. $provider_list[] = $provider['id']; } diff --git a/application/controllers/Booking_cancellation.php b/application/controllers/Booking_cancellation.php index 2b993fc03f..40c8aabb3a 100755 --- a/application/controllers/Booking_cancellation.php +++ b/application/controllers/Booking_cancellation.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Booking_cancellation extends EA_Controller { +class Booking_cancellation extends EA_Controller +{ /** * Booking_cancellation constructor. */ @@ -47,19 +48,16 @@ public function __construct() */ public function of(string $appointment_hash) { - try - { + try { $cancellation_reason = request('cancellation_reason'); - if ($this->input->method() !== 'post' || empty($cancellation_reason)) - { + if ($this->input->method() !== 'post' || empty($cancellation_reason)) { abort(403, 'Forbidden'); } $occurrences = $this->appointments_model->get(['hash' => $appointment_hash]); - if (empty($occurrences)) - { + if (empty($occurrences)) { html_vars([ 'page_title' => lang('appointment_not_found'), 'company_color' => setting('company_color'), @@ -67,7 +65,7 @@ public function of(string $appointment_hash) 'message_text' => lang('appointment_does_not_exist_in_db'), 'message_icon' => base_url('assets/img/error.png'), 'google_analytics_code' => setting('google_analytics_code'), - 'matomo_analytics_url' => setting('matomo_analytics_url'), + 'matomo_analytics_url' => setting('matomo_analytics_url') ]); $this->load->view('pages/booking_message'); @@ -95,13 +93,17 @@ public function of(string $appointment_hash) $this->synchronization->sync_appointment_deleted($appointment, $provider); - $this->notifications->notify_appointment_deleted($appointment, $service, $provider, $customer, $settings, $cancellation_reason); + $this->notifications->notify_appointment_deleted( + $appointment, + $service, + $provider, + $customer, + $settings, + $cancellation_reason + ); $this->webhooks_client->trigger(WEBHOOK_APPOINTMENT_DELETE, $appointment); - - } - catch (Throwable $e) - { + } catch (Throwable $e) { log_message('error', 'Booking Cancellation Exception: ' . $e->getMessage()); } @@ -109,7 +111,7 @@ public function of(string $appointment_hash) 'page_title' => lang('appointment_cancelled_title'), 'company_color' => setting('company_color'), 'google_analytics_code' => setting('google_analytics_code'), - 'matomo_analytics_url' => setting('matomo_analytics_url'), + 'matomo_analytics_url' => setting('matomo_analytics_url') ]); $this->load->view('pages/booking_cancellation'); diff --git a/application/controllers/Booking_confirmation.php b/application/controllers/Booking_confirmation.php index 64300f1120..7f71b593f0 100755 --- a/application/controllers/Booking_confirmation.php +++ b/application/controllers/Booking_confirmation.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Booking_confirmation extends EA_Controller { +class Booking_confirmation extends EA_Controller +{ /** * Booking_confirmation constructor. */ @@ -30,13 +31,13 @@ public function __construct() $this->load->model('providers_model'); $this->load->model('services_model'); $this->load->model('customers_model'); - + $this->load->library('google_sync'); } /** * Display the appointment registration success page. - * + * * @throws Exception */ public function of() @@ -45,8 +46,7 @@ public function of() $occurrences = $this->appointments_model->get(['hash' => $appointment_hash]); - if (empty($occurrences)) - { + if (empty($occurrences)) { redirect('appointments'); // The appointment does not exist. return; @@ -54,14 +54,14 @@ public function of() $appointment = $occurrences[0]; - $add_to_google_url = $this->google_sync->get_add_to_google_url($appointment['id']); + $add_to_google_url = $this->google_sync->get_add_to_google_url($appointment['id']); html_vars([ 'page_title' => lang('success'), 'company_color' => setting('company_color'), 'google_analytics_code' => setting('google_analytics_code'), 'matomo_analytics_url' => setting('matomo_analytics_url'), - 'add_to_google_url' => $add_to_google_url, + 'add_to_google_url' => $add_to_google_url ]); $this->load->view('pages/booking_confirmation'); diff --git a/application/controllers/Booking_settings.php b/application/controllers/Booking_settings.php index 1796e82f58..5743a4364e 100644 --- a/application/controllers/Booking_settings.php +++ b/application/controllers/Booking_settings.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Booking_settings extends EA_Controller { +class Booking_settings extends EA_Controller +{ /** * Booking_settings constructor. */ @@ -48,11 +49,9 @@ public function index() session(['dest_url' => site_url('booking_settings')]); $user_id = session('user_id'); - - if (cannot('view', PRIV_SYSTEM_SETTINGS)) - { - if ($user_id) - { + + if (cannot('view', PRIV_SYSTEM_SETTINGS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -72,7 +71,7 @@ public function index() html_vars([ 'page_title' => lang('settings'), 'active_menu' => PRIV_SYSTEM_SETTINGS, - 'user_display_name' => $this->accounts->get_user_display_name($user_id), + 'user_display_name' => $this->accounts->get_user_display_name($user_id) ]); $this->load->view('pages/booking_settings'); @@ -83,37 +82,31 @@ public function index() */ public function save() { - try - { - if (cannot('edit', PRIV_SYSTEM_SETTINGS)) - { + try { + if (cannot('edit', PRIV_SYSTEM_SETTINGS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } $settings = request('booking_settings', []); - foreach ($settings as $setting) - { - $existing_setting = $this->settings_model->query()->where('name', $setting['name'])->get()->row_array(); + foreach ($settings as $setting) { + $existing_setting = $this->settings_model + ->query() + ->where('name', $setting['name']) + ->get() + ->row_array(); - if ( ! empty($existing_setting)) - { + if (!empty($existing_setting)) { $setting['id'] = $existing_setting['id']; } - $this->settings_model->only($setting, [ - 'id', - 'name', - 'value' - ]); - + $this->settings_model->only($setting, ['id', 'name', 'value']); + $this->settings_model->save($setting); } response(); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Business_settings.php b/application/controllers/Business_settings.php index db04ebd22c..5a60909a4b 100644 --- a/application/controllers/Business_settings.php +++ b/application/controllers/Business_settings.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Business_settings extends EA_Controller { +class Business_settings extends EA_Controller +{ /** * Business_logic constructor. */ @@ -48,11 +49,9 @@ public function index() session(['dest_url' => site_url('business_settings')]); $user_id = session('user_id'); - - if (cannot('view', PRIV_SYSTEM_SETTINGS)) - { - if ($user_id) - { + + if (cannot('view', PRIV_SYSTEM_SETTINGS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -68,13 +67,13 @@ public function index() 'role_slug' => $role_slug, 'business_settings' => $this->settings_model->get(), 'first_weekday' => setting('first_weekday'), - 'time_format' => setting('time_format'), + 'time_format' => setting('time_format') ]); html_vars([ 'page_title' => lang('settings'), 'active_menu' => PRIV_SYSTEM_SETTINGS, - 'user_display_name' => $this->accounts->get_user_display_name($user_id), + 'user_display_name' => $this->accounts->get_user_display_name($user_id) ]); $this->load->view('pages/business_settings'); @@ -85,37 +84,31 @@ public function index() */ public function save() { - try - { - if (cannot('edit', PRIV_SYSTEM_SETTINGS)) - { + try { + if (cannot('edit', PRIV_SYSTEM_SETTINGS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } $settings = request('business_settings', []); - foreach ($settings as $setting) - { - $existing_setting = $this->settings_model->query()->where('name', $setting['name'])->get()->row_array(); + foreach ($settings as $setting) { + $existing_setting = $this->settings_model + ->query() + ->where('name', $setting['name']) + ->get() + ->row_array(); - if ( ! empty($existing_setting)) - { + if (!empty($existing_setting)) { $setting['id'] = $existing_setting['id']; } - - $this->settings_model->only($setting, [ - 'id', - 'name', - 'value' - ]); + + $this->settings_model->only($setting, ['id', 'name', 'value']); $this->settings_model->save($setting); } response(); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -125,10 +118,8 @@ public function save() */ public function apply_global_working_plan() { - try - { - if (cannot('edit', PRIV_SYSTEM_SETTINGS)) - { + try { + if (cannot('edit', PRIV_SYSTEM_SETTINGS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } @@ -136,15 +127,12 @@ public function apply_global_working_plan() $providers = $this->providers_model->get(); - foreach ($providers as $provider) - { + foreach ($providers as $provider) { $this->providers_model->set_setting($provider['id'], 'working_plan', $working_plan); } response(); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Calendar.php b/application/controllers/Calendar.php index f587c7c4ca..7168923c05 100644 --- a/application/controllers/Calendar.php +++ b/application/controllers/Calendar.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Calendar extends EA_Controller { +class Calendar extends EA_Controller +{ /** * Calendar constructor. */ @@ -42,6 +43,18 @@ public function __construct() $this->load->library('webhooks_client'); } + /** + * Render the calendar page and display the selected appointment. + * + * This method will call the "index" callback to handle the page rendering. + * + * @param string $appointment_hash Appointment hash. + */ + public function reschedule(string $appointment_hash) + { + $this->index($appointment_hash); + } + /** * Display the main backend page. * @@ -53,14 +66,12 @@ public function __construct() */ public function index(string $appointment_hash = '') { - session(['dest_url' => site_url('backend/index' . (! empty($appointment_hash) ? '/' . $appointment_hash : ''))]); + session(['dest_url' => site_url('backend/index' . (!empty($appointment_hash) ? '/' . $appointment_hash : ''))]); $user_id = session('user_id'); - if (cannot('view', PRIV_APPOINTMENTS)) - { - if ($user_id) - { + if (cannot('view', PRIV_APPOINTMENTS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -75,21 +86,18 @@ public function index(string $appointment_hash = '') $secretary_providers = []; - if ($role_slug === DB_SLUG_SECRETARY) - { + if ($role_slug === DB_SLUG_SECRETARY) { $secretary = $this->secretaries_model->find(session('user_id')); $secretary_providers = $secretary['providers']; } - $edit_appointment = NULL; + $edit_appointment = null; - if ( ! empty($appointment_hash)) - { + if (!empty($appointment_hash)) { $occurrences = $this->appointments_model->get(['hash' => $appointment_hash]); - if ($appointment_hash !== '' && ! empty($occurrences)) - { + if ($appointment_hash !== '' && !empty($occurrences)) { $edit_appointment = $occurrences[0]; $this->appointments_model->load($edit_appointment, ['customer']); @@ -100,18 +108,20 @@ public function index(string $appointment_hash = '') $available_providers = $this->providers_model->get_available_providers(); - if ($role_slug === DB_SLUG_PROVIDER) - { - $available_providers = array_values(array_filter($available_providers, function ($available_provider) use ($user_id) { - return (int)$available_provider['id'] === (int)$user_id; - })); + if ($role_slug === DB_SLUG_PROVIDER) { + $available_providers = array_values( + array_filter($available_providers, function ($available_provider) use ($user_id) { + return (int) $available_provider['id'] === (int) $user_id; + }) + ); } - if ($role_slug === DB_SLUG_SECRETARY) - { - $available_providers = array_values(array_filter($available_providers, function ($available_provider) use ($secretary_providers) { - return in_array($available_provider['id'], $secretary_providers); - })); + if ($role_slug === DB_SLUG_SECRETARY) { + $available_providers = array_values( + array_filter($available_providers, function ($available_provider) use ($secretary_providers) { + return in_array($available_provider['id'], $secretary_providers); + }) + ); } $available_services = $this->services_model->get_available_services(); @@ -134,7 +144,7 @@ public function index(string $appointment_hash = '') 'available_services' => $available_services, 'secretary_providers' => $secretary_providers, 'edit_appointment' => $edit_appointment, - 'customers' => $this->customers_model->get(NULL, 50, NULL, 'update_datetime DESC'), + 'customers' => $this->customers_model->get(null, 50, null, 'update_datetime DESC') ]); html_vars([ @@ -149,7 +159,7 @@ public function index(string $appointment_hash = '') 'available_providers' => $available_providers, 'available_services' => $available_services, 'secretary_providers' => $secretary_providers, - 'appointment_status_options' => json_decode($appointment_status_options, TRUE) ?? [], + 'appointment_status_options' => json_decode($appointment_status_options, true) ?? [], 'require_first_name' => setting('require_first_name'), 'require_last_name' => setting('require_last_name'), 'require_email' => setting('require_email'), @@ -157,47 +167,32 @@ public function index(string $appointment_hash = '') 'require_address' => setting('require_address'), 'require_city' => setting('require_city'), 'require_zip_code' => setting('require_zip_code'), - 'require_notes' => setting('require_notes'), + 'require_notes' => setting('require_notes') ]); $this->load->view('pages/calendar'); } - /** - * Render the calendar page and display the selected appointment. - * - * This method will call the "index" callback to handle the page rendering. - * - * @param string $appointment_hash Appointment hash. - */ - public function reschedule(string $appointment_hash) - { - $this->index($appointment_hash); - } - /** * Save appointment changes that are made from the backend calendar page. */ public function save_appointment() { - try - { + try { $customer_data = request('customer_data'); $appointment_data = request('appointment_data'); - $this->check_event_permissions((int)$appointment_data['id_users_provider']); + $this->check_event_permissions((int) $appointment_data['id_users_provider']); // Save customer changes to the database. - if ($customer_data) - { + if ($customer_data) { $customer = $customer_data; - $required_permissions = ! empty($customer['id']) + $required_permissions = !empty($customer['id']) ? can('add', PRIV_CUSTOMERS) : can('edit', PRIV_CUSTOMERS); - if ( ! $required_permissions) - { + if (!$required_permissions) { throw new RuntimeException('You do not have the required permissions for this task.'); } @@ -213,37 +208,33 @@ public function save_appointment() 'zip_code', 'timezone', 'language', - 'notes', + 'notes' ]); $customer['id'] = $this->customers_model->save($customer); } // Save appointment changes to the database. - $manage_mode = ! empty($appointment_data['id']); + $manage_mode = !empty($appointment_data['id']); - if ($appointment_data) - { + if ($appointment_data) { $appointment = $appointment_data; - $required_permissions = ! empty($appointment['id']) + $required_permissions = !empty($appointment['id']) ? can('add', PRIV_APPOINTMENTS) : can('edit', PRIV_APPOINTMENTS); - if ( ! $required_permissions) - { + if (!$required_permissions) { throw new RuntimeException('You do not have the required permissions for this task.'); } // If the appointment does not contain the customer record id, then it means that is going to be // inserted. - if ( ! isset($appointment['id_users_customer'])) - { + if (!isset($appointment['id_users_customer'])) { $appointment['id_users_customer'] = $customer['id'] ?? $customer_data['id']; } - if ($manage_mode && ! empty($appointment['id'])) - { + if ($manage_mode && !empty($appointment['id'])) { $this->synchronization->remove_appointment_on_provider_change($appointment['id']); } @@ -259,21 +250,20 @@ public function save_appointment() 'is_unavailability', 'id_users_provider', 'id_users_customer', - 'id_services', + 'id_services' ]); $appointment['id'] = $this->appointments_model->save($appointment); } - if (empty($appointment['id'])) - { + if (empty($appointment['id'])) { throw new RuntimeException('The appointment ID is not available.'); } $appointment = $this->appointments_model->find($appointment['id']); - $provider = $this->providers_model->find($appointment['id_users_provider'], TRUE); - $customer = $this->customers_model->find($appointment['id_users_customer'], TRUE); - $service = $this->services_model->find($appointment['id_services'], TRUE); + $provider = $this->providers_model->find($appointment['id_users_provider'], true); + $customer = $this->customers_model->find($appointment['id_users_customer'], true); + $service = $this->services_model->find($appointment['id_services'], true); $settings = [ 'company_name' => setting('company_name'), @@ -285,20 +275,42 @@ public function save_appointment() $this->synchronization->sync_appointment_saved($appointment, $service, $provider, $customer, $settings); - $this->notifications->notify_appointment_saved($appointment, $service, $provider, $customer, $settings, $manage_mode); + $this->notifications->notify_appointment_saved( + $appointment, + $service, + $provider, + $customer, + $settings, + $manage_mode + ); $this->webhooks_client->trigger(WEBHOOK_APPOINTMENT_SAVE, $appointment); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } + private function check_event_permissions(int $provider_id): void + { + $user_id = (int) session('user_id'); + $role_slug = session('role_slug'); + + if ( + $role_slug === DB_SLUG_SECRETARY && + !$this->secretaries_model->is_provider_supported($user_id, $provider_id) + ) { + abort(403); + } + + if ($role_slug === DB_SLUG_PROVIDER && $user_id !== $provider_id) { + abort(403); + } + } + /** * Delete appointment from the database. * @@ -308,29 +320,26 @@ public function save_appointment() */ public function delete_appointment() { - try - { - if (cannot('delete', 'appointments')) - { + try { + if (cannot('delete', 'appointments')) { throw new RuntimeException('You do not have the required permissions for this task.'); } $appointment_id = request('appointment_id'); - $cancellation_reason = (string)request('cancellation_reason'); + $cancellation_reason = (string) request('cancellation_reason'); - if (empty($appointment_id)) - { + if (empty($appointment_id)) { throw new InvalidArgumentException('No appointment id provided.'); } // Store appointment data for later use in this method. $appointment = $this->appointments_model->find($appointment_id); - $this->check_event_permissions((int)$appointment['id_users_provider']); + $this->check_event_permissions((int) $appointment['id_users_provider']); - $provider = $this->providers_model->find($appointment['id_users_provider'], TRUE); - $customer = $this->customers_model->find($appointment['id_users_customer'], TRUE); - $service = $this->services_model->find($appointment['id_services'], TRUE); + $provider = $this->providers_model->find($appointment['id_users_provider'], true); + $customer = $this->customers_model->find($appointment['id_users_customer'], true); + $service = $this->services_model->find($appointment['id_services'], true); $settings = [ 'company_name' => setting('company_name'), @@ -343,18 +352,23 @@ public function delete_appointment() // Delete appointment record from the database. $this->appointments_model->delete($appointment_id); - $this->notifications->notify_appointment_deleted($appointment, $service, $provider, $customer, $settings, $cancellation_reason); + $this->notifications->notify_appointment_deleted( + $appointment, + $service, + $provider, + $customer, + $settings, + $cancellation_reason + ); $this->synchronization->sync_appointment_deleted($appointment, $provider); $this->webhooks_client->trigger(WEBHOOK_APPOINTMENT_DELETE, $appointment); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -364,21 +378,19 @@ public function delete_appointment() */ public function save_unavailability() { - try - { + try { // Check privileges $unavailability = request('unavailability'); - $required_permissions = ( ! isset($unavailability['id'])) + $required_permissions = !isset($unavailability['id']) ? can('add', PRIV_APPOINTMENTS) : can('edit', PRIV_APPOINTMENTS); - if ( ! $required_permissions) - { + if (!$required_permissions) { throw new RuntimeException('You do not have the required permissions for this task.'); } - $provider_id = (int)$unavailability['id_users_provider']; + $provider_id = (int) $unavailability['id_users_provider']; $this->check_event_permissions($provider_id); @@ -393,12 +405,10 @@ public function save_unavailability() $this->webhooks_client->trigger(WEBHOOK_UNAVAILABILITY_SAVE, $unavailability); json_response([ - 'success' => TRUE, + 'success' => true, 'warnings' => $warnings ?? [] ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -408,10 +418,8 @@ public function save_unavailability() */ public function delete_unavailability() { - try - { - if (cannot('delete', PRIV_APPOINTMENTS)) - { + try { + if (cannot('delete', PRIV_APPOINTMENTS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } @@ -419,7 +427,7 @@ public function delete_unavailability() $unavailability = $this->unavailabilities_model->find($unavailability_id); - $this->check_event_permissions((int)$unavailability['id_users_provider']); + $this->check_event_permissions((int) $unavailability['id_users_provider']); $provider = $this->providers_model->find($unavailability['id_users_provider']); @@ -430,11 +438,9 @@ public function delete_unavailability() $this->webhooks_client->trigger(WEBHOOK_UNAVAILABILITY_DELETE, $unavailability); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -444,10 +450,8 @@ public function delete_unavailability() */ public function save_working_plan_exception() { - try - { - if (cannot('edit', PRIV_USERS)) - { + try { + if (cannot('edit', PRIV_USERS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } @@ -455,9 +459,8 @@ public function save_working_plan_exception() $working_plan_exception = request('working_plan_exception'); - if ( ! $working_plan_exception) - { - $working_plan_exception = NULL; + if (!$working_plan_exception) { + $working_plan_exception = null; } $provider_id = request('provider_id'); @@ -465,11 +468,9 @@ public function save_working_plan_exception() $this->providers_model->save_working_plan_exception($provider_id, $date, $working_plan_exception); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -479,12 +480,10 @@ public function save_working_plan_exception() */ public function delete_working_plan_exception() { - try - { + try { $required_permissions = can('edit', PRIV_CUSTOMERS); - if ( ! $required_permissions) - { + if (!$required_permissions) { throw new RuntimeException('You do not have the required permissions for this task.'); } @@ -495,11 +494,9 @@ public function delete_working_plan_exception() $this->providers_model->delete_working_plan_exception($provider_id, $date); json_response([ - 'success' => TRUE + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -511,12 +508,10 @@ public function delete_working_plan_exception() */ public function get_calendar_appointments_for_table_view() { - try - { + try { $required_permissions = can('view', PRIV_APPOINTMENTS); - if ( ! $required_permissions) - { + if (!$required_permissions) { throw new RuntimeException('You do not have the required permissions for this task.'); } @@ -535,11 +530,10 @@ public function get_calendar_appointments_for_table_view() ]) ]; - foreach ($response['appointments'] as &$appointment) - { - $appointment['provider'] = $this->providers_model->find($appointment['id_users_provider'], TRUE); - $appointment['service'] = $this->services_model->find($appointment['id_services'], TRUE); - $appointment['customer'] = $this->customers_model->find($appointment['id_users_customer'], TRUE); + foreach ($response['appointments'] as &$appointment) { + $appointment['provider'] = $this->providers_model->find($appointment['id_users_provider'], true); + $appointment['service'] = $this->services_model->find($appointment['id_services'], true); + $appointment['customer'] = $this->customers_model->find($appointment['id_users_customer'], true); } unset($appointment); @@ -549,22 +543,17 @@ public function get_calendar_appointments_for_table_view() $role_slug = session('role_slug'); // If the current user is a provider he must only see his own appointments. - if ($role_slug === DB_SLUG_PROVIDER) - { - foreach ($response['appointments'] as $index => $appointment) - { - if ((int)$appointment['id_users_provider'] !== (int)$user_id) - { + if ($role_slug === DB_SLUG_PROVIDER) { + foreach ($response['appointments'] as $index => $appointment) { + if ((int) $appointment['id_users_provider'] !== (int) $user_id) { unset($response['appointments'][$index]); } } $response['appointments'] = array_values($response['appointments']); - foreach ($response['unavailabilities'] as $index => $unavailability) - { - if ((int)$unavailability['id_users_provider'] !== (int)$user_id) - { + foreach ($response['unavailabilities'] as $index => $unavailability) { + if ((int) $unavailability['id_users_provider'] !== (int) $user_id) { unset($response['unavailabilities'][$index]); } } @@ -573,24 +562,19 @@ public function get_calendar_appointments_for_table_view() } // If the current user is a secretary he must only see the appointments of his providers. - if ($role_slug === DB_SLUG_SECRETARY) - { + if ($role_slug === DB_SLUG_SECRETARY) { $providers = $this->secretaries_model->find($user_id)['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]); } } $response['appointments'] = array_values($response['appointments']); - 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]); } } @@ -598,15 +582,13 @@ public function get_calendar_appointments_for_table_view() $response['unavailabilities'] = array_values($response['unavailabilities']); } - // Add blocked periods to the response. + // Add blocked periods to the response. $start_date = request('start_date'); $end_date = request('end_date'); $response['blocked_periods'] = $this->blocked_periods_model->get_for_period($start_date, $end_date); json_response($response); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -619,10 +601,8 @@ public function get_calendar_appointments_for_table_view() */ public function get_calendar_appointments() { - try - { - if (cannot('view', PRIV_APPOINTMENTS)) - { + try { + if (cannot('view', PRIV_APPOINTMENTS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } @@ -630,8 +610,7 @@ public function get_calendar_appointments() $filter_type = request('filter_type'); - if ( ! $filter_type && $record_id !== FILTER_TYPE_ALL) - { + if (!$filter_type && $record_id !== FILTER_TYPE_ALL) { json_response([ 'appointments' => [], 'unavailabilities' => [] @@ -642,16 +621,11 @@ public function get_calendar_appointments() $record_id = $this->db->escape($record_id); - if ($filter_type == FILTER_TYPE_PROVIDER) - { + if ($filter_type == FILTER_TYPE_PROVIDER) { $where_id = 'id_users_provider'; - } - elseif ($filter_type === FILTER_TYPE_SERVICE) - { + } elseif ($filter_type === FILTER_TYPE_SERVICE) { $where_id = 'id_services'; - } - else - { + } else { $where_id = $record_id; } @@ -659,39 +633,68 @@ public function get_calendar_appointments() $start_date = $this->db->escape(request('start_date')); $end_date = $this->db->escape(date('Y-m-d', strtotime(request('end_date') . ' +1 day'))); - $where_clause = $where_id . ' = ' . $record_id . ' - AND ((start_datetime > ' . $start_date . ' AND start_datetime < ' . $end_date . ') - or (end_datetime > ' . $start_date . ' AND end_datetime < ' . $end_date . ') - or (start_datetime <= ' . $start_date . ' AND end_datetime >= ' . $end_date . ')) + $where_clause = + $where_id . + ' = ' . + $record_id . + ' + AND ((start_datetime > ' . + $start_date . + ' AND start_datetime < ' . + $end_date . + ') + or (end_datetime > ' . + $start_date . + ' AND end_datetime < ' . + $end_date . + ') + or (start_datetime <= ' . + $start_date . + ' AND end_datetime >= ' . + $end_date . + ')) AND is_unavailability = 0 '; $response['appointments'] = $this->appointments_model->get($where_clause); - foreach ($response['appointments'] as &$appointment) - { - $appointment['provider'] = $this->providers_model->find($appointment['id_users_provider'], TRUE); - $appointment['service'] = $this->services_model->find($appointment['id_services'], TRUE); - $appointment['customer'] = $this->customers_model->find($appointment['id_users_customer'], TRUE); + foreach ($response['appointments'] as &$appointment) { + $appointment['provider'] = $this->providers_model->find($appointment['id_users_provider'], true); + $appointment['service'] = $this->services_model->find($appointment['id_services'], true); + $appointment['customer'] = $this->customers_model->find($appointment['id_users_customer'], true); } // Get unavailability periods (only for provider). $response['unavailabilities'] = []; - if ($filter_type == FILTER_TYPE_PROVIDER) - { - $where_clause = $where_id . ' = ' . $record_id . ' - AND ((start_datetime > ' . $start_date . ' AND start_datetime < ' . $end_date . ') - or (end_datetime > ' . $start_date . ' AND end_datetime < ' . $end_date . ') - or (start_datetime <= ' . $start_date . ' AND end_datetime >= ' . $end_date . ')) + if ($filter_type == FILTER_TYPE_PROVIDER) { + $where_clause = + $where_id . + ' = ' . + $record_id . + ' + AND ((start_datetime > ' . + $start_date . + ' AND start_datetime < ' . + $end_date . + ') + or (end_datetime > ' . + $start_date . + ' AND end_datetime < ' . + $end_date . + ') + or (start_datetime <= ' . + $start_date . + ' AND end_datetime >= ' . + $end_date . + ')) AND is_unavailability = 1 '; $response['unavailabilities'] = $this->unavailabilities_model->get($where_clause); } - foreach ($response['unavailabilities'] as &$unavailability) - { + foreach ($response['unavailabilities'] as &$unavailability) { $unavailability['provider'] = $this->providers_model->find($unavailability['id_users_provider']); } @@ -702,22 +705,17 @@ public function get_calendar_appointments() $role_slug = session('role_slug'); // If the current user is a provider he must only see his own appointments. - if ($role_slug === DB_SLUG_PROVIDER) - { - foreach ($response['appointments'] as $index => $appointment) - { - if ((int)$appointment['id_users_provider'] !== (int)$user_id) - { + if ($role_slug === DB_SLUG_PROVIDER) { + foreach ($response['appointments'] as $index => $appointment) { + if ((int) $appointment['id_users_provider'] !== (int) $user_id) { unset($response['appointments'][$index]); } } $response['appointments'] = array_values($response['appointments']); - foreach ($response['unavailabilities'] as $index => $unavailability) - { - if ((int)$unavailability['id_users_provider'] !== (int)$user_id) - { + foreach ($response['unavailabilities'] as $index => $unavailability) { + if ((int) $unavailability['id_users_provider'] !== (int) $user_id) { unset($response['unavailabilities'][$index]); } } @@ -726,57 +724,34 @@ public function get_calendar_appointments() } // If the current user is a secretary he must only see the appointments of his providers. - if ($role_slug === DB_SLUG_SECRETARY) - { + if ($role_slug === DB_SLUG_SECRETARY) { $providers = $this->secretaries_model->find($user_id)['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]); } } $response['appointments'] = array_values($response['appointments']); - 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]); } } $response['unavailabilities'] = array_values($response['unavailabilities']); } - - // Add blocked periods to the response. - $start_date = request('start_date'); - $end_date = request('end_date'); - $response['blocked_periods'] = $this->blocked_periods_model->get_for_period($start_date, $end_date); + + // Add blocked periods to the response. + $start_date = request('start_date'); + $end_date = request('end_date'); + $response['blocked_periods'] = $this->blocked_periods_model->get_for_period($start_date, $end_date); json_response($response); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } - - private function check_event_permissions(int $provider_id): void - { - $user_id = (int)session('user_id'); - $role_slug = session('role_slug'); - - if ($role_slug === DB_SLUG_SECRETARY && ! $this->secretaries_model->is_provider_supported($user_id, $provider_id)) - { - abort(403); - } - - if ($role_slug === DB_SLUG_PROVIDER && $user_id !== $provider_id) - { - abort(403); - } - } } diff --git a/application/controllers/Captcha.php b/application/controllers/Captcha.php index b7922e5a33..31b69a39b6 100644 --- a/application/controllers/Captcha.php +++ b/application/controllers/Captcha.php @@ -11,16 +11,15 @@ * @since v1.0.0 * ---------------------------------------------------------------------------- */ -use Gregwar\Captcha\CaptchaBuilder; - /** * Captcha controller. - * + * * Handles the captcha operations. * * @package Controllers */ -class Captcha extends EA_Controller { +class Captcha extends EA_Controller +{ /** * Class Constructor */ @@ -39,7 +38,7 @@ public function index() $this->captcha_builder->setDistortion(true); $this->captcha_builder->setMaxBehindLines(1); $this->captcha_builder->setMaxFrontLines(1); - $this->captcha_builder->setBackgroundColor(255,255,255); + $this->captcha_builder->setBackgroundColor(255, 255, 255); $this->captcha_builder->build(); session(['captcha_phrase' => $this->captcha_builder->getPhrase()]); header('Content-type: image/jpeg'); diff --git a/application/controllers/Consents.php b/application/controllers/Consents.php index f7b42947b4..990838b209 100644 --- a/application/controllers/Consents.php +++ b/application/controllers/Consents.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Consents extends EA_Controller { +class Consents extends EA_Controller +{ /** * Consents constructor. */ @@ -34,28 +35,25 @@ public function __construct() */ public function save() { - try - { + try { $consent = request('consent'); $consent['ip'] = $this->input->ip_address(); $occurrences = $this->consents_model->get(['ip' => $consent['ip']], 1, 0, 'create_datetime DESC'); - if ( ! empty($occurrences)) - { + if (!empty($occurrences)) { $last_consent = $occurrences[0]; $last_consent_create_datetime_instance = new DateTime($last_consent['create_datetime']); $threshold_datetime_instance = new DateTime('-24 hours'); - if ($last_consent_create_datetime_instance > $threshold_datetime_instance) - { + if ($last_consent_create_datetime_instance > $threshold_datetime_instance) { // Do not create a new consent. json_response([ - 'success' => TRUE, + 'success' => true ]); return; @@ -65,12 +63,10 @@ public function save() $consent['id'] = $this->consents_model->save($consent); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $consent['id'] ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Console.php b/application/controllers/Console.php index 8a59982b1e..f403237954 100644 --- a/application/controllers/Console.php +++ b/application/controllers/Console.php @@ -18,14 +18,14 @@ * * Handles all the Console related operations. */ -class Console extends EA_Controller { +class Console extends EA_Controller +{ /** * Console constructor. */ public function __construct() { - if ( ! is_cli()) - { + if (!is_cli()) { exit('No direct script access allowed'); } @@ -57,7 +57,9 @@ public function install() $password = $this->instance->seed(); - response(PHP_EOL . '⇾ Installation completed, login with "administrator" / "' . $password . '".' . PHP_EOL . PHP_EOL); + response( + PHP_EOL . '⇾ Installation completed, login with "administrator" / "' . $password . '".' . PHP_EOL . PHP_EOL + ); } /** @@ -112,7 +114,7 @@ public function seed() */ public function backup() { - $this->instance->backup($GLOBALS['argv'][3] ?? NULL); + $this->instance->backup($GLOBALS['argv'][3] ?? null); } /** @@ -132,18 +134,15 @@ public function sync() { $providers = $this->providers_model->get(); - foreach ($providers as $provider) - { - if ( ! filter_var($provider['settings']['google_sync'], FILTER_VALIDATE_BOOLEAN)) - { + foreach ($providers as $provider) { + if (!filter_var($provider['settings']['google_sync'], FILTER_VALIDATE_BOOLEAN)) { continue; } - Google::sync((string)$provider['id']); + Google::sync((string) $provider['id']); } } - /** * Show help information about the console capabilities. * @@ -174,7 +173,7 @@ public function help() '⇾ php index.php console backup', '⇾ php index.php console sync', '', - '', + '' ]; response(implode(PHP_EOL, $help)); diff --git a/application/controllers/General_settings.php b/application/controllers/General_settings.php index 6d88533457..bc97101e62 100644 --- a/application/controllers/General_settings.php +++ b/application/controllers/General_settings.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class General_settings extends EA_Controller { +class General_settings extends EA_Controller +{ /** * Calendar constructor. */ @@ -39,11 +40,9 @@ public function index() session(['dest_url' => site_url('general_settings')]); $user_id = session('user_id'); - - if (cannot('view', PRIV_SYSTEM_SETTINGS)) - { - if ($user_id) - { + + if (cannot('view', PRIV_SYSTEM_SETTINGS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -51,26 +50,26 @@ public function index() return; } - + $role_slug = session('role_slug'); - + $available_theme_files = glob(__DIR__ . '/../../assets/css/themes/*.min.css'); - + $available_themes = array_map(function ($available_theme_file) { - return str_replace('.min.css', '', basename($available_theme_file)); - }, $available_theme_files); + return str_replace('.min.css', '', basename($available_theme_file)); + }, $available_theme_files); script_vars([ 'user_id' => $user_id, 'role_slug' => $role_slug, - 'general_settings' => $this->settings_model->get(), + 'general_settings' => $this->settings_model->get() ]); html_vars([ 'page_title' => lang('settings'), 'active_menu' => PRIV_SYSTEM_SETTINGS, 'user_display_name' => $this->accounts->get_user_display_name($user_id), - 'available_themes' => $available_themes, + 'available_themes' => $available_themes ]); $this->load->view('pages/general_settings'); @@ -81,21 +80,21 @@ public function index() */ public function save() { - try - { - if (cannot('edit', PRIV_SYSTEM_SETTINGS)) - { + try { + if (cannot('edit', PRIV_SYSTEM_SETTINGS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } $settings = request('general_settings', []); - foreach ($settings as $setting) - { - $existing_setting = $this->settings_model->query()->where('name', $setting['name'])->get()->row_array(); + foreach ($settings as $setting) { + $existing_setting = $this->settings_model + ->query() + ->where('name', $setting['name']) + ->get() + ->row_array(); - if ( ! empty($existing_setting)) - { + if (!empty($existing_setting)) { $setting['id'] = $existing_setting['id']; } @@ -103,9 +102,7 @@ public function save() } response(); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Google.php b/application/controllers/Google.php index 2bc10e08ca..21bf796cd9 100644 --- a/application/controllers/Google.php +++ b/application/controllers/Google.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Google extends EA_Controller { +class Google extends EA_Controller +{ /** * Google constructor. */ @@ -40,10 +41,9 @@ public function __construct() * needs to be relatively small, because a lot of API calls might be necessary and this will lead to consuming the * Google limit for the Calendar API usage. */ - public static function sync(string $provider_id = NULL): void + public static function sync(string $provider_id = null): void { - try - { + try { /** @var EA_Controller $CI */ $CI = get_instance(); @@ -60,13 +60,11 @@ public static function sync(string $provider_id = NULL): void $user_id = session('user_id'); - if ( ! $user_id && ! is_cli()) - { + if (!$user_id && !is_cli()) { return; } - if ( ! $provider_id) - { + if (!$provider_id) { throw new InvalidArgumentException('No provider ID provided.'); } @@ -75,12 +73,11 @@ public static function sync(string $provider_id = NULL): void // Check whether the selected provider has the Google Sync enabled. $google_sync = $CI->providers_model->get_setting($provider['id'], 'google_sync'); - if ( ! $google_sync) - { + if (!$google_sync) { return; // The selected provider does not have the Google Syncing enabled. } - $google_token = json_decode($provider['settings']['google_token'], TRUE); + $google_token = json_decode($provider['settings']['google_token'], true); $CI->google_sync->refresh_token($google_token['refresh_token']); @@ -114,25 +111,26 @@ public static function sync(string $provider_id = NULL): void $provider_timezone = new DateTimeZone($provider['timezone']); // Sync each appointment with Google Calendar by following the project's sync protocol (see documentation). - foreach ($local_events as $local_event) - { - if ( ! $local_event['is_unavailability']) - { + foreach ($local_events as $local_event) { + if (!$local_event['is_unavailability']) { $service = $CI->services_model->find($local_event['id_services']); $customer = $CI->customers_model->find($local_event['id_users_customer']); $events_model = $CI->appointments_model; - } - else - { - $service = NULL; - $customer = NULL; + } else { + $service = null; + $customer = null; $events_model = $CI->unavailabilities_model; } // If current appointment not synced yet, add to Google Calendar. - if ( ! $local_event['id_google_calendar']) - { - $google_event = $CI->google_sync->add_appointment($local_event, $provider, $service, $customer, $settings); + if (!$local_event['id_google_calendar']) { + $google_event = $CI->google_sync->add_appointment( + $local_event, + $provider, + $service, + $customer, + $settings + ); $local_event['id_google_calendar'] = $google_event->getId(); @@ -141,85 +139,75 @@ public static function sync(string $provider_id = NULL): void continue; } - // Appointment is synced with Google Calendar. - try - { + try { $google_event = $CI->google_sync->get_event($provider, $local_event['id_google_calendar']); - if ($google_event->getStatus() == 'cancelled') - { + if ($google_event->getStatus() == 'cancelled') { throw new Exception('Event is cancelled, remove the record from Easy!Appointments.'); } // If Google Calendar event is different from Easy!Appointments appointment then update Easy!Appointments record. $local_event_start = strtotime($local_event['start_datetime']); $local_event_end = strtotime($local_event['end_datetime']); - $google_event_start = new DateTime($google_event->getStart()->getDateTime() ?? $google_event->getEnd()->getDate()); + $google_event_start = new DateTime( + $google_event->getStart()->getDateTime() ?? $google_event->getEnd()->getDate() + ); $google_event_start->setTimezone($provider_timezone); - $google_event_end = new DateTime($google_event->getEnd()->getDateTime() ?? $google_event->getEnd()->getDate()); + $google_event_end = new DateTime( + $google_event->getEnd()->getDateTime() ?? $google_event->getEnd()->getDate() + ); $google_event_end->setTimezone($provider_timezone); - $google_event_notes = $local_event['is_unavailability'] ? $google_event->getSummary() . ' ' . $google_event->getDescription() : $google_event->getDescription(); + $google_event_notes = $local_event['is_unavailability'] + ? $google_event->getSummary() . ' ' . $google_event->getDescription() + : $google_event->getDescription(); - $is_different = $local_event_start !== $google_event_start->getTimestamp() - || $local_event_end !== $google_event_end->getTimestamp() - || $local_event['notes'] !== $google_event_notes; + $is_different = + $local_event_start !== $google_event_start->getTimestamp() || + $local_event_end !== $google_event_end->getTimestamp() || + $local_event['notes'] !== $google_event_notes; - if ($is_different) - { + if ($is_different) { $local_event['start_datetime'] = $google_event_start->format('Y-m-d H:i:s'); $local_event['end_datetime'] = $google_event_end->format('Y-m-d H:i:s'); $local_event['notes'] = $google_event_notes; $events_model->save($local_event); } - - } - catch (Throwable) - { + } catch (Throwable) { // Appointment not found on Google Calendar, delete from Easy!Appointments. $events_model->delete($local_event['id']); - $local_event['id_google_calendar'] = NULL; + $local_event['id_google_calendar'] = null; } } // Add Google Calendar events that do not exist in Easy!Appointments. $google_calendar = $provider['settings']['google_calendar']; - try - { + try { $google_events = $CI->google_sync->get_sync_events($google_calendar, $start, $end); - } - catch (Throwable $e) - { - if ($e->getCode() === 404) - { + } catch (Throwable $e) { + if ($e->getCode() === 404) { log_message('error', 'Google - Remote Calendar not found for provider ID: ' . $provider_id); return; // The remote calendar was not found. - } - else - { + } else { throw $e; } } - foreach ($google_events->getItems() as $google_event) - { - if ($google_event->getStatus() === 'cancelled') - { + foreach ($google_events->getItems() as $google_event) { + if ($google_event->getStatus() === 'cancelled') { continue; } - if ($google_event->getStart() === NULL || $google_event->getEnd() === NULL) - { + if ($google_event->getStart() === null || $google_event->getEnd() === null) { continue; } - if ($google_event->getStart()->getDateTime() === $google_event->getEnd()->getDateTime()) - { + if ($google_event->getStart()->getDateTime() === $google_event->getEnd()->getDateTime()) { continue; } @@ -230,15 +218,15 @@ public static function sync(string $provider_id = NULL): void $appointment_results = $CI->appointments_model->get(['id_google_calendar' => $google_event->getId()]); - if ( ! empty($appointment_results)) - { + if (!empty($appointment_results)) { continue; } - $unavailability_results = $CI->unavailabilities_model->get(['id_google_calendar' => $google_event->getId()]); + $unavailability_results = $CI->unavailabilities_model->get([ + 'id_google_calendar' => $google_event->getId() + ]); - if ( ! empty($unavailability_results)) - { + if (!empty($unavailability_results)) { continue; } @@ -246,25 +234,26 @@ public static function sync(string $provider_id = NULL): void $local_event = [ 'start_datetime' => $google_event_start->format('Y-m-d H:i:s'), 'end_datetime' => $google_event_end->format('Y-m-d H:i:s'), - 'is_unavailability' => TRUE, + 'is_unavailability' => true, 'location' => $google_event->getLocation(), 'notes' => $google_event->getSummary() . ' ' . $google_event->getDescription(), 'id_users_provider' => $provider_id, 'id_google_calendar' => $google_event->getId(), - 'id_users_customer' => NULL, - 'id_services' => NULL, + 'id_users_customer' => null, + 'id_services' => null ]; $CI->unavailabilities_model->save($local_event); } json_response([ - 'success' => TRUE + 'success' => true ]); - } - catch (Throwable $e) - { - log_message('error', 'Google - Sync completed with an error (provider ID "' . $provider_id . '"): ' . $e->getMessage()); + } catch (Throwable $e) { + log_message( + 'error', + 'Google - Sync completed with an error (provider ID "' . $provider_id . '"): ' . $e->getMessage() + ); json_exception($e); } @@ -280,8 +269,7 @@ public static function sync(string $provider_id = NULL): void */ public function oauth(string $provider_id): void { - if ( ! $this->session->userdata('user_id')) - { + if (!$this->session->userdata('user_id')) { show_error('Forbidden', 403); } @@ -308,15 +296,13 @@ public function oauth(string $provider_id): void */ public function oauth_callback(): void { - if ( ! session('user_id')) - { + if (!session('user_id')) { abort(403, 'Forbidden'); } $code = request('code'); - if (empty($code)) - { + if (empty($code)) { response('Code authorization failed.'); return; @@ -324,8 +310,7 @@ public function oauth_callback(): void $token = $this->google_sync->authenticate($code); - if (empty($token)) - { + if (empty($token)) { response('Token authorization failed.'); return; @@ -334,14 +319,11 @@ public function oauth_callback(): void // Store the token into the database for future reference. $oauth_provider_id = session('oauth_provider_id'); - if ($oauth_provider_id) - { - $this->providers_model->set_setting($oauth_provider_id, 'google_sync', TRUE); + if ($oauth_provider_id) { + $this->providers_model->set_setting($oauth_provider_id, 'google_sync', true); $this->providers_model->set_setting($oauth_provider_id, 'google_token', json_encode($token)); $this->providers_model->set_setting($oauth_provider_id, 'google_calendar', 'primary'); - } - else - { + } else { response('Sync provider id not specified.'); } } @@ -354,37 +336,32 @@ public function oauth_callback(): void */ public function get_google_calendars(): void { - try - { - $provider_id = (int)request('provider_id'); + try { + $provider_id = (int) request('provider_id'); - if (empty($provider_id)) - { + if (empty($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($provider_id, 'google_sync'); - if ( ! $google_sync) - { + if (!$google_sync) { json_response([ - 'success' => FALSE + 'success' => false ]); return; } - $google_token = json_decode($this->providers_model->get_setting($provider_id, 'google_token'), TRUE); + $google_token = json_decode($this->providers_model->get_setting($provider_id, 'google_token'), true); $this->google_sync->refresh_token($google_token['refresh_token']); $calendars = $this->google_sync->get_google_calendars(); json_response($calendars); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -396,14 +373,12 @@ public function get_google_calendars(): void */ public function select_google_calendar(): void { - try - { + try { $provider_id = request('provider_id'); $user_id = session('user_id'); - if (cannot('edit', PRIV_USERS) && (int)$user_id !== (int)$provider_id) - { + if (cannot('edit', PRIV_USERS) && (int) $user_id !== (int) $provider_id) { throw new RuntimeException('You do not have the required permissions for this task.'); } @@ -412,11 +387,9 @@ public function select_google_calendar(): void $this->providers_model->set_setting($provider_id, 'google_calendar', $calendar_id); json_response([ - 'success' => TRUE + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -430,36 +403,29 @@ public function select_google_calendar(): void */ public function disable_provider_sync(): void { - try - { + try { $provider_id = request('provider_id'); - if ( ! $provider_id) - { + if (!$provider_id) { throw new Exception('Provider id not specified.'); } $user_id = session('user_id'); - if ( - cannot('edit', PRIV_USERS) - && (int)$user_id !== (int)$provider_id) - { + if (cannot('edit', PRIV_USERS) && (int) $user_id !== (int) $provider_id) { throw new RuntimeException('You do not have the required permissions for this task.'); } - $this->providers_model->set_setting($provider_id, 'google_sync', FALSE); + $this->providers_model->set_setting($provider_id, 'google_sync', false); $this->providers_model->set_setting($provider_id, 'google_token'); $this->appointments_model->clear_google_sync_ids($provider_id); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Google_analytics_settings.php b/application/controllers/Google_analytics_settings.php index 185896f4ad..16230b3112 100644 --- a/application/controllers/Google_analytics_settings.php +++ b/application/controllers/Google_analytics_settings.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Google_analytics_settings extends EA_Controller { +class Google_analytics_settings extends EA_Controller +{ /** * Google_analytics_settings constructor. */ @@ -40,10 +41,8 @@ public function index() $user_id = session('user_id'); - if (cannot('view', PRIV_SYSTEM_SETTINGS)) - { - if ($user_id) - { + if (cannot('view', PRIV_SYSTEM_SETTINGS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -57,13 +56,13 @@ public function index() script_vars([ 'user_id' => $user_id, 'role_slug' => $role_slug, - 'google_analytics_settings' => $this->settings_model->get('name like "google_analytics_%"'), + 'google_analytics_settings' => $this->settings_model->get('name like "google_analytics_%"') ]); html_vars([ 'page_title' => lang('google_analytics'), 'active_menu' => PRIV_SYSTEM_SETTINGS, - 'user_display_name' => $this->accounts->get_user_display_name($user_id), + 'user_display_name' => $this->accounts->get_user_display_name($user_id) ]); $this->load->view('pages/google_analytics_settings'); @@ -74,21 +73,21 @@ public function index() */ public function save() { - try - { - if (cannot('edit', PRIV_SYSTEM_SETTINGS)) - { + try { + if (cannot('edit', PRIV_SYSTEM_SETTINGS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } $settings = request('google_analytics_settings', []); - foreach ($settings as $setting) - { - $existing_setting = $this->settings_model->query()->where('name', $setting['name'])->get()->row_array(); + foreach ($settings as $setting) { + $existing_setting = $this->settings_model + ->query() + ->where('name', $setting['name']) + ->get() + ->row_array(); - if ( ! empty($existing_setting)) - { + if (!empty($existing_setting)) { $setting['id'] = $existing_setting['id']; } @@ -96,9 +95,7 @@ public function save() } response(); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Installation.php b/application/controllers/Installation.php index f274e3b0fb..e1719b6c53 100644 --- a/application/controllers/Installation.php +++ b/application/controllers/Installation.php @@ -18,20 +18,21 @@ * * @package Controllers */ -class Installation extends EA_Controller { +class Installation extends EA_Controller +{ /** * Installation constructor. */ public function __construct() { parent::__construct(); - + $this->load->model('admins_model'); $this->load->model('settings_model'); $this->load->model('services_model'); $this->load->model('providers_model'); $this->load->model('customers_model'); - + $this->load->library('instance'); } @@ -40,8 +41,7 @@ public function __construct() */ public function index() { - if (is_app_installed()) - { + if (is_app_installed()) { redirect(); return; } @@ -56,23 +56,21 @@ public function index() */ public function perform() { - try - { - if (is_app_installed()) - { + try { + if (is_app_installed()) { return; } $admin = request('admin'); $company = request('company'); - $this->instance->migrate(); + $this->instance->migrate(); // Insert admin $admin['timezone'] = 'UTC'; $admin['settings']['username'] = $admin['username']; $admin['settings']['password'] = $admin['password']; - $admin['settings']['notifications'] = TRUE; + $admin['settings']['notifications'] = true; $admin['settings']['calendar_view'] = CALENDAR_VIEW_DEFAULT; unset($admin['username'], $admin['password']); $admin['id'] = $this->admins_model->save($admin); @@ -82,14 +80,14 @@ public function perform() 'user_email' => $admin['email'], 'role_slug' => DB_SLUG_ADMIN, 'timezone' => $admin['timezone'], - 'username' => $admin['settings']['username'] + 'username' => $admin['settings']['username'] ]); // Save company settings setting([ 'company_name' => $company['company_name'], 'company_email' => $company['company_email'], - 'company_link' => $company['company_link'], + 'company_link' => $company['company_link'] ]); // Service @@ -108,19 +106,17 @@ public function perform() 'last_name' => 'Doe', 'email' => 'jane@example.org', 'phone_number' => '+1 (000) 000-0000', - 'services' => [ - $service_id - ], + 'services' => [$service_id], 'settings' => [ 'username' => 'janedoe', 'password' => random_string(), 'working_plan' => setting('company_working_plan'), - 'notifications' => TRUE, - 'google_sync' => FALSE, + 'notifications' => true, + 'google_sync' => false, 'sync_past_days' => 30, 'sync_future_days' => 90, 'calendar_view' => CALENDAR_VIEW_DEFAULT - ], + ] ]); // Customer @@ -128,15 +124,13 @@ public function perform() 'first_name' => 'James', 'last_name' => 'Doe', 'email' => 'james@example.org', - 'phone_number' => '+1 (000) 000-0000', + 'phone_number' => '+1 (000) 000-0000' ]); json_response([ 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Integrations.php b/application/controllers/Integrations.php index 77f7b6b0a7..1b5d036c62 100644 --- a/application/controllers/Integrations.php +++ b/application/controllers/Integrations.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Integrations extends EA_Controller { +class Integrations extends EA_Controller +{ /** * Integrations constructor. */ @@ -49,10 +50,8 @@ public function index() $user_id = session('user_id'); - if (cannot('view', PRIV_SYSTEM_SETTINGS)) - { - if ($user_id) - { + if (cannot('view', PRIV_SYSTEM_SETTINGS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -67,7 +66,7 @@ public function index() 'page_title' => lang('integrations'), 'active_menu' => PRIV_SYSTEM_SETTINGS, 'user_display_name' => $this->accounts->get_user_display_name($user_id), - 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug), + 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug) ]); $this->load->view('pages/integrations'); diff --git a/application/controllers/Legal_settings.php b/application/controllers/Legal_settings.php index 06c30ec465..052ebca19d 100644 --- a/application/controllers/Legal_settings.php +++ b/application/controllers/Legal_settings.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Legal_settings extends EA_Controller { +class Legal_settings extends EA_Controller +{ /** * Legal_contents constructor. */ @@ -39,11 +40,9 @@ public function index() session(['dest_url' => site_url('legal_settings')]); $user_id = session('user_id'); - - if (cannot('view', PRIV_SYSTEM_SETTINGS)) - { - if ($user_id) - { + + if (cannot('view', PRIV_SYSTEM_SETTINGS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -51,19 +50,19 @@ public function index() return; } - + $role_slug = session('role_slug'); script_vars([ 'user_id' => $user_id, 'role_slug' => $role_slug, - 'legal_settings' => $this->settings_model->get(), + 'legal_settings' => $this->settings_model->get() ]); html_vars([ 'page_title' => lang('settings'), 'active_menu' => PRIV_SYSTEM_SETTINGS, - 'user_display_name' => $this->accounts->get_user_display_name($user_id), + 'user_display_name' => $this->accounts->get_user_display_name($user_id) ]); $this->load->view('pages/legal_settings'); @@ -74,21 +73,21 @@ public function index() */ public function save() { - try - { - if (cannot('edit', PRIV_SYSTEM_SETTINGS)) - { + try { + if (cannot('edit', PRIV_SYSTEM_SETTINGS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } $settings = request('legal_settings', []); - foreach ($settings as $setting) - { - $existing_setting = $this->settings_model->query()->where('name', $setting['name'])->get()->row_array(); + foreach ($settings as $setting) { + $existing_setting = $this->settings_model + ->query() + ->where('name', $setting['name']) + ->get() + ->row_array(); - if ( ! empty($existing_setting)) - { + if (!empty($existing_setting)) { $setting['id'] = $existing_setting['id']; } @@ -96,9 +95,7 @@ public function save() } response(); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Localization.php b/application/controllers/Localization.php index b04ccb3f95..6cba363bcd 100644 --- a/application/controllers/Localization.php +++ b/application/controllers/Localization.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Localization extends EA_Controller { +class Localization extends EA_Controller +{ /** * Change system language for current user. * @@ -28,14 +29,14 @@ class Localization extends EA_Controller { */ public function change_language() { - try - { + try { // Check if language exists in the available languages. $language = request('language'); - if ( ! in_array($language, config('available_languages'))) - { - throw new RuntimeException('Translations for the given language does not exist (' . request('language') . ').'); + if (!in_array($language, config('available_languages'))) { + throw new RuntimeException( + 'Translations for the given language does not exist (' . request('language') . ').' + ); } $language = request('language'); @@ -45,11 +46,9 @@ public function change_language() config(['language' => $language]); json_response([ - 'success' => TRUE + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Login.php b/application/controllers/Login.php index bb627b750f..6b5473ceb4 100644 --- a/application/controllers/Login.php +++ b/application/controllers/Login.php @@ -14,11 +14,12 @@ /** * Login controller. * - * Handles the login page functionality. + * Handles the login page functionality. * * @package Controllers */ -class Login extends EA_Controller { +class Login extends EA_Controller +{ /** * Login constructor. */ @@ -30,12 +31,12 @@ public function __construct() $this->load->library('email_messages'); script_vars([ - 'dest_url' => session('dest_url', site_url('calendar')), + 'dest_url' => session('dest_url', site_url('calendar')) ]); } /** - * Render the login page. + * Render the login page. */ public function index() { @@ -45,48 +46,42 @@ public function index() 'dest_url' => session('dest_url', site_url('calendar')), 'company_name' => setting('company_name') ]); - + $this->load->view('pages/login'); } /** - * Validate the provided credentials and start a new session if the validation was successful. + * Validate the provided credentials and start a new session if the validation was successful. */ public function validate() { - try - { + try { $username = request('username'); - if (empty($username)) - { + if (empty($username)) { throw new InvalidArgumentException('No username value provided.'); } $password = request('password'); - if (empty($password)) - { + if (empty($password)) { throw new InvalidArgumentException('No password value provided.'); } $user_data = $this->accounts->check_login($username, $password); - if (empty($user_data)) - { + if (empty($user_data)) { throw new InvalidArgumentException('Invalid credentials provided, please try again.'); } - + $this->session->sess_regenerate(); session($user_data); // Save data in the session. json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Logout.php b/application/controllers/Logout.php index 079147b7a2..19b7378bb5 100644 --- a/application/controllers/Logout.php +++ b/application/controllers/Logout.php @@ -18,16 +18,17 @@ * * @package Controllers */ -class Logout extends EA_Controller { +class Logout extends EA_Controller +{ /** - * Render the logout page. + * Render the logout page. */ public function index() { $this->session->sess_destroy(); - - $company_name = setting('company_name'); - + + $company_name = setting('company_name'); + html_vars([ 'page_title' => lang('log_out'), 'company_name' => $company_name diff --git a/application/controllers/Matomo_analytics_settings.php b/application/controllers/Matomo_analytics_settings.php index 597ad2829d..2b0fa20bb6 100644 --- a/application/controllers/Matomo_analytics_settings.php +++ b/application/controllers/Matomo_analytics_settings.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Matomo_analytics_settings extends EA_Controller { +class Matomo_analytics_settings extends EA_Controller +{ /** * Matomo_analytics_settings constructor. */ @@ -40,10 +41,8 @@ public function index() $user_id = session('user_id'); - if (cannot('view', PRIV_SYSTEM_SETTINGS)) - { - if ($user_id) - { + if (cannot('view', PRIV_SYSTEM_SETTINGS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -57,13 +56,13 @@ public function index() script_vars([ 'user_id' => $user_id, 'role_slug' => $role_slug, - 'matomo_analytics_settings' => $this->settings_model->get('name like "matomo_analytics_%"'), + 'matomo_analytics_settings' => $this->settings_model->get('name like "matomo_analytics_%"') ]); html_vars([ 'page_title' => lang('matomo_analytics'), 'active_menu' => PRIV_SYSTEM_SETTINGS, - 'user_display_name' => $this->accounts->get_user_display_name($user_id), + 'user_display_name' => $this->accounts->get_user_display_name($user_id) ]); $this->load->view('pages/matomo_analytics_settings'); @@ -74,21 +73,21 @@ public function index() */ public function save() { - try - { - if (cannot('edit', PRIV_SYSTEM_SETTINGS)) - { + try { + if (cannot('edit', PRIV_SYSTEM_SETTINGS)) { throw new RuntimeException('You do not have the required permissions for this task.'); } $settings = request('matomo_analytics_settings', []); - foreach ($settings as $setting) - { - $existing_setting = $this->settings_model->query()->where('name', $setting['name'])->get()->row_array(); + foreach ($settings as $setting) { + $existing_setting = $this->settings_model + ->query() + ->where('name', $setting['name']) + ->get() + ->row_array(); - if ( ! empty($existing_setting)) - { + if (!empty($existing_setting)) { $setting['id'] = $existing_setting['id']; } @@ -96,9 +95,7 @@ public function save() } response(); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Privacy.php b/application/controllers/Privacy.php index 90f9f7d9e3..6c8775ca8b 100644 --- a/application/controllers/Privacy.php +++ b/application/controllers/Privacy.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Privacy extends EA_Controller { +class Privacy extends EA_Controller +{ /** * Privacy constructor. */ @@ -36,38 +37,33 @@ public function __construct() */ public function delete_personal_information() { - try - { + try { $display_delete_personal_information = setting('display_delete_personal_information'); - if ( ! $display_delete_personal_information) - { + if (!$display_delete_personal_information) { abort(403, 'Forbidden'); } $customer_token = request('customer_token'); - if (empty($customer_token)) - { + if (empty($customer_token)) { throw new InvalidArgumentException('Invalid customer token value provided.'); } $customer_id = $this->cache->get('customer-token-' . $customer_token); - if (empty($customer_id)) - { - throw new InvalidArgumentException('Customer ID does not exist, please reload the page ' - . 'and try again.'); + if (empty($customer_id)) { + throw new InvalidArgumentException( + 'Customer ID does not exist, please reload the page ' . 'and try again.' + ); } $this->customers_model->delete($customer_id); json_response([ - 'success' => TRUE + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Providers.php b/application/controllers/Providers.php index 418d6f880b..b800d137b0 100644 --- a/application/controllers/Providers.php +++ b/application/controllers/Providers.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Providers extends EA_Controller { +class Providers extends EA_Controller +{ /** * Providers constructor. */ @@ -47,10 +48,8 @@ public function index() $user_id = session('user_id'); - if (cannot('view', PRIV_USERS)) - { - if ($user_id) - { + if (cannot('view', PRIV_USERS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -63,8 +62,7 @@ public function index() $services = $this->services_model->get(); - foreach ($services as &$service) - { + foreach ($services as &$service) { $this->services_model->only($service, ['id', 'name']); } @@ -77,7 +75,7 @@ public function index() 'first_weekday' => setting('first_weekday'), 'min_password_length' => MIN_PASSWORD_LENGTH, 'timezones' => $this->timezones->to_array(), - 'services' => $services, + 'services' => $services ]); html_vars([ @@ -86,7 +84,7 @@ public function index() 'user_display_name' => $this->accounts->get_user_display_name($user_id), 'grouped_timezones' => $this->timezones->to_grouped_array(), 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug), - 'services' => $this->services_model->get(), + 'services' => $this->services_model->get() ]); $this->load->view('pages/providers'); @@ -97,10 +95,8 @@ public function index() */ public function search() { - try - { - if (cannot('view', PRIV_USERS)) - { + try { + if (cannot('view', PRIV_USERS)) { abort(403, 'Forbidden'); } @@ -115,9 +111,7 @@ public function search() $providers = $this->providers_model->search($keyword, $limit, $offset, $order_by); json_response($providers); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -127,10 +121,8 @@ public function search() */ public function store() { - try - { - if (cannot('add', PRIV_USERS)) - { + try { + if (cannot('add', PRIV_USERS)) { abort(403, 'Forbidden'); } @@ -152,7 +144,7 @@ public function store() 'is_private', 'id_roles', 'settings', - 'services', + 'services' ]); $this->providers_model->only($provider['settings'], [ @@ -165,7 +157,7 @@ public function store() ]); $this->providers_model->optional($provider, [ - 'services' => [], + 'services' => [] ]); $provider_id = $this->providers_model->save($provider); @@ -175,12 +167,30 @@ public function store() $this->webhooks_client->trigger(WEBHOOK_PROVIDER_SAVE, $provider); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $provider_id ]); + } catch (Throwable $e) { + json_exception($e); } - catch (Throwable $e) - { + } + + /** + * Find a provider. + */ + public function find() + { + try { + if (cannot('view', PRIV_USERS)) { + abort(403, 'Forbidden'); + } + + $provider_id = request('provider_id'); + + $provider = $this->providers_model->find($provider_id); + + json_response($provider); + } catch (Throwable $e) { json_exception($e); } } @@ -190,10 +200,8 @@ public function store() */ public function update() { - try - { - if (cannot('edit', PRIV_USERS)) - { + try { + if (cannot('edit', PRIV_USERS)) { abort(403, 'Forbidden'); } @@ -216,7 +224,7 @@ public function update() 'is_private', 'id_roles', 'settings', - 'services', + 'services' ]); $this->providers_model->only($provider['settings'], [ @@ -229,7 +237,7 @@ public function update() ]); $this->providers_model->optional($provider, [ - 'services' => [], + 'services' => [] ]); $provider_id = $this->providers_model->save($provider); @@ -239,12 +247,10 @@ public function update() $this->webhooks_client->trigger(WEBHOOK_PROVIDER_SAVE, $provider); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $provider_id ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -254,10 +260,8 @@ public function update() */ public function destroy() { - try - { - if (cannot('delete', PRIV_USERS)) - { + try { + if (cannot('delete', PRIV_USERS)) { abort(403, 'Forbidden'); } @@ -270,35 +274,9 @@ public function destroy() $this->webhooks_client->trigger(WEBHOOK_PROVIDER_DELETE, $provider); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { - json_exception($e); - } - } - - /** - * Find a provider. - */ - public function find() - { - try - { - if (cannot('view', PRIV_USERS)) - { - abort(403, 'Forbidden'); - } - - $provider_id = request('provider_id'); - - $provider = $this->providers_model->find($provider_id); - - json_response($provider); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Recovery.php b/application/controllers/Recovery.php index dbfa53bfbe..2e38a84d95 100644 --- a/application/controllers/Recovery.php +++ b/application/controllers/Recovery.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Recovery extends EA_Controller { +class Recovery extends EA_Controller +{ /** * User constructor. */ @@ -35,45 +36,38 @@ public function __construct() */ public function index() { - $company_name = setting('company_name'); - + $company_name = setting('company_name'); + html_vars([ 'page_title' => lang('forgot_your_password'), 'dest_url' => session('dest_url', site_url('backend')), 'company_name' => $company_name - ]); - + ]); + $this->load->view('pages/recovery'); } - + /** * Recover the user password and notify the user via email. */ public function perform() { - try - { + try { $username = request('username'); - if (empty($username)) - { + if (empty($username)) { throw new InvalidArgumentException('No username value provided.'); } $email = request('email'); - if (empty($email)) - { + if (empty($email)) { throw new InvalidArgumentException('No email value provided.'); } - $new_password = $this->accounts->regenerate_password( - $username, - $email - ); + $new_password = $this->accounts->regenerate_password($username, $email); - if ($new_password) - { + if ($new_password) { $settings = [ 'company_name' => setting('company_name'), 'company_link' => setting('company_link'), @@ -84,11 +78,9 @@ public function perform() } json_response([ - 'success' => TRUE + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Secretaries.php b/application/controllers/Secretaries.php index 8737e06326..8902de8c54 100644 --- a/application/controllers/Secretaries.php +++ b/application/controllers/Secretaries.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Secretaries extends EA_Controller { +class Secretaries extends EA_Controller +{ /** * Secretaries constructor. */ @@ -46,11 +47,9 @@ public function index() session(['dest_url' => site_url('secretaries')]); $user_id = session('user_id'); - - if (cannot('view', PRIV_USERS)) - { - if ($user_id) - { + + if (cannot('view', PRIV_USERS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -63,13 +62,8 @@ public function index() $providers = $this->providers_model->get(); - foreach ($providers as &$provider) - { - $this->providers_model->only($provider, [ - 'id', - 'first_name', - 'last_name' - ]); + foreach ($providers as &$provider) { + $this->providers_model->only($provider, ['id', 'first_name', 'last_name']); } script_vars([ @@ -77,7 +71,7 @@ public function index() 'role_slug' => $role_slug, 'timezones' => $this->timezones->to_array(), 'min_password_length' => MIN_PASSWORD_LENGTH, - 'providers' => $providers, + 'providers' => $providers ]); html_vars([ @@ -86,7 +80,7 @@ public function index() 'user_display_name' => $this->accounts->get_user_display_name($user_id), 'grouped_timezones' => $this->timezones->to_grouped_array(), 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug), - 'providers' => $this->providers_model->get(), + 'providers' => $this->providers_model->get() ]); $this->load->view('pages/secretaries'); @@ -97,10 +91,8 @@ public function index() */ public function search() { - try - { - if (cannot('view', PRIV_USERS)) - { + try { + if (cannot('view', PRIV_USERS)) { abort(403, 'Forbidden'); } @@ -115,9 +107,7 @@ public function search() $secretaries = $this->secretaries_model->search($keyword, $limit, $offset, $order_by); json_response($secretaries); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -127,10 +117,8 @@ public function search() */ public function store() { - try - { - if (cannot('add', PRIV_USERS)) - { + try { + if (cannot('add', PRIV_USERS)) { abort(403, 'Forbidden'); } @@ -152,7 +140,7 @@ public function store() 'is_private', 'id_roles', 'settings', - 'providers', + 'providers' ]); $this->secretaries_model->only($secretary['settings'], [ @@ -163,7 +151,7 @@ public function store() ]); $this->secretaries_model->optional($secretary, [ - 'providers' => [], + 'providers' => [] ]); $secretary_id = $this->secretaries_model->save($secretary); @@ -173,12 +161,30 @@ public function store() $this->webhooks_client->trigger(WEBHOOK_SECRETARY_SAVE, $secretary); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $secretary_id ]); + } catch (Throwable $e) { + json_exception($e); } - catch (Throwable $e) - { + } + + /** + * Find a secretary. + */ + public function find() + { + try { + if (cannot('view', PRIV_USERS)) { + abort(403, 'Forbidden'); + } + + $secretary_id = request('secretary_id'); + + $secretary = $this->secretaries_model->find($secretary_id); + + json_response($secretary); + } catch (Throwable $e) { json_exception($e); } } @@ -188,15 +194,13 @@ public function store() */ public function update() { - try - { - if (cannot('edit', PRIV_USERS)) - { + try { + if (cannot('edit', PRIV_USERS)) { abort(403, 'Forbidden'); } $secretary = request('secretary'); - + $this->secretaries_model->only($secretary, [ 'id', 'first_name', @@ -214,7 +218,7 @@ public function update() 'is_private', 'id_roles', 'settings', - 'providers', + 'providers' ]); $this->secretaries_model->only($secretary['settings'], [ @@ -225,10 +229,9 @@ public function update() ]); $this->secretaries_model->optional($secretary, [ - 'providers' => [], + 'providers' => [] ]); - $secretary_id = $this->secretaries_model->save($secretary); $secretary = $this->secretaries_model->find($secretary_id); @@ -236,12 +239,10 @@ public function update() $this->webhooks_client->trigger(WEBHOOK_SECRETARY_SAVE, $secretary); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $secretary_id ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -251,10 +252,8 @@ public function update() */ public function destroy() { - try - { - if (cannot('delete', PRIV_USERS)) - { + try { + if (cannot('delete', PRIV_USERS)) { abort(403, 'Forbidden'); } @@ -267,35 +266,9 @@ public function destroy() $this->webhooks_client->trigger(WEBHOOK_SECRETARY_DELETE, $secretary); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { - json_exception($e); - } - } - - /** - * Find a secretary. - */ - public function find() - { - try - { - if (cannot('view', PRIV_USERS)) - { - abort(403, 'Forbidden'); - } - - $secretary_id = request('secretary_id'); - - $secretary = $this->secretaries_model->find($secretary_id); - - json_response($secretary); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Service_categories.php b/application/controllers/Service_categories.php index 452396a0c6..bfc2eeeb22 100644 --- a/application/controllers/Service_categories.php +++ b/application/controllers/Service_categories.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Service_categories extends EA_Controller { +class Service_categories extends EA_Controller +{ /** * Service-categories constructor. */ @@ -46,10 +47,8 @@ public function index() $user_id = session('user_id'); - if (cannot('view', PRIV_SERVICES)) - { - if ($user_id) - { + if (cannot('view', PRIV_SERVICES)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -62,7 +61,7 @@ public function index() script_vars([ 'user_id' => $user_id, - 'role_slug' => $role_slug, + 'role_slug' => $role_slug ]); html_vars([ @@ -70,7 +69,7 @@ public function index() 'active_menu' => PRIV_SERVICES, 'user_display_name' => $this->accounts->get_user_display_name($user_id), 'timezones' => $this->timezones->to_array(), - 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug), + 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug) ]); $this->load->view('pages/service_categories'); @@ -81,10 +80,8 @@ public function index() */ public function search() { - try - { - if (cannot('view', PRIV_SERVICES)) - { + try { + if (cannot('view', PRIV_SERVICES)) { abort(403, 'Forbidden'); } @@ -99,9 +96,7 @@ public function search() $service_categories = $this->service_categories_model->search($keyword, $limit, $offset, $order_by); json_response($service_categories); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -111,19 +106,14 @@ public function search() */ public function store() { - try - { - if (cannot('add', PRIV_SERVICES)) - { + try { + if (cannot('add', PRIV_SERVICES)) { abort(403, 'Forbidden'); } $service_category = request('service_category'); - $this->service_categories_model->only($service_category, [ - 'name', - 'description' - ]); + $this->service_categories_model->only($service_category, ['name', 'description']); $service_category_id = $this->service_categories_model->save($service_category); @@ -132,12 +122,30 @@ public function store() $this->webhooks_client->trigger(WEBHOOK_SERVICE_CATEGORY_SAVE, $service_category); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $service_category_id ]); + } catch (Throwable $e) { + json_exception($e); } - catch (Throwable $e) - { + } + + /** + * Find a service-category. + */ + public function find() + { + try { + if (cannot('view', PRIV_SERVICES)) { + abort(403, 'Forbidden'); + } + + $service_category_id = request('service_category_id'); + + $service_category = $this->service_categories_model->find($service_category_id); + + json_response($service_category); + } catch (Throwable $e) { json_exception($e); } } @@ -147,20 +155,14 @@ public function store() */ public function update() { - try - { - if (cannot('edit', PRIV_SERVICES)) - { + try { + if (cannot('edit', PRIV_SERVICES)) { abort(403, 'Forbidden'); } $service_category = request('service_category'); - $this->service_categories_model->only($service_category, [ - 'id', - 'name', - 'description' - ]); + $this->service_categories_model->only($service_category, ['id', 'name', 'description']); $service_category_id = $this->service_categories_model->save($service_category); @@ -169,12 +171,10 @@ public function update() $this->webhooks_client->trigger(WEBHOOK_SERVICE_CATEGORY_SAVE, $service_category); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $service_category_id ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -184,10 +184,8 @@ public function update() */ public function destroy() { - try - { - if (cannot('delete', PRIV_SERVICES)) - { + try { + if (cannot('delete', PRIV_SERVICES)) { abort(403, 'Forbidden'); } @@ -200,35 +198,9 @@ public function destroy() $this->webhooks_client->trigger(WEBHOOK_SERVICE_CATEGORY_DELETE, $service_category); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { - json_exception($e); - } - } - - /** - * Find a service-category. - */ - public function find() - { - try - { - if (cannot('view', PRIV_SERVICES)) - { - abort(403, 'Forbidden'); - } - - $service_category_id = request('service_category_id'); - - $service_category = $this->service_categories_model->find($service_category_id); - - json_response($service_category); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Services.php b/application/controllers/Services.php index f7df16fe3a..b35bbce0c0 100644 --- a/application/controllers/Services.php +++ b/application/controllers/Services.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Services extends EA_Controller { +class Services extends EA_Controller +{ /** * Services constructor. */ @@ -46,10 +47,8 @@ public function index() $user_id = session('user_id'); - if (cannot('view', PRIV_SERVICES)) - { - if ($user_id) - { + if (cannot('view', PRIV_SERVICES)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -63,7 +62,7 @@ public function index() script_vars([ 'user_id' => $user_id, 'role_slug' => $role_slug, - 'event_minimum_duration' => EVENT_MINIMUM_DURATION, + 'event_minimum_duration' => EVENT_MINIMUM_DURATION ]); html_vars([ @@ -71,7 +70,7 @@ public function index() 'active_menu' => PRIV_SERVICES, 'user_display_name' => $this->accounts->get_user_display_name($user_id), 'timezones' => $this->timezones->to_array(), - 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug), + 'privileges' => $this->roles_model->get_permissions_by_slug($role_slug) ]); $this->load->view('pages/services'); @@ -82,10 +81,8 @@ public function index() */ public function search() { - try - { - if (cannot('view', PRIV_SERVICES)) - { + try { + if (cannot('view', PRIV_SERVICES)) { abort(403, 'Forbidden'); } @@ -100,9 +97,7 @@ public function search() $services = $this->services_model->search($keyword, $limit, $offset, $order_by); json_response($services); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -112,10 +107,8 @@ public function search() */ public function store() { - try - { - if (cannot('add', PRIV_SERVICES)) - { + try { + if (cannot('add', PRIV_SERVICES)) { abort(403, 'Forbidden'); } @@ -132,11 +125,11 @@ public function store() 'availabilities_type', 'attendants_number', 'is_private', - 'id_service_categories', + 'id_service_categories' ]); $this->services_model->optional($service, [ - 'id_service_categories' => NULL + 'id_service_categories' => null ]); $service_id = $this->services_model->save($service); @@ -146,12 +139,30 @@ public function store() $this->webhooks_client->trigger(WEBHOOK_SERVICE_SAVE, $service); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $service_id ]); + } catch (Throwable $e) { + json_exception($e); } - catch (Throwable $e) - { + } + + /** + * Find a service. + */ + public function find() + { + try { + if (cannot('delete', PRIV_SERVICES)) { + abort(403, 'Forbidden'); + } + + $service_id = request('service_id'); + + $service = $this->services_model->find($service_id); + + json_response($service); + } catch (Throwable $e) { json_exception($e); } } @@ -161,10 +172,8 @@ public function store() */ public function update() { - try - { - if (cannot('edit', PRIV_SERVICES)) - { + try { + if (cannot('edit', PRIV_SERVICES)) { abort(403, 'Forbidden'); } @@ -182,11 +191,11 @@ public function update() 'availabilities_type', 'attendants_number', 'is_private', - 'id_service_categories', + 'id_service_categories' ]); $this->services_model->optional($service, [ - 'id_service_categories' => NULL + 'id_service_categories' => null ]); $service_id = $this->services_model->save($service); @@ -196,12 +205,10 @@ public function update() $this->webhooks_client->trigger(WEBHOOK_SERVICE_SAVE, $service); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $service_id ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -211,10 +218,8 @@ public function update() */ public function destroy() { - try - { - if (cannot('delete', PRIV_SERVICES)) - { + try { + if (cannot('delete', PRIV_SERVICES)) { abort(403, 'Forbidden'); } @@ -227,35 +232,9 @@ public function destroy() $this->webhooks_client->trigger(WEBHOOK_SERVICE_DELETE, $service); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { - json_exception($e); - } - } - - /** - * Find a service. - */ - public function find() - { - try - { - if (cannot('delete', PRIV_SERVICES)) - { - abort(403, 'Forbidden'); - } - - $service_id = request('service_id'); - - $service = $this->services_model->find($service_id); - - json_response($service); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Test.php b/application/controllers/Test.php index e729149f8c..b0744429a5 100644 --- a/application/controllers/Test.php +++ b/application/controllers/Test.php @@ -15,8 +15,7 @@ * This file can only be used in a testing environment and only from the termninal. */ -if (ENVIRONMENT !== 'testing' || ! is_cli()) -{ +if (ENVIRONMENT !== 'testing' || !is_cli()) { show_404(); } @@ -26,7 +25,8 @@ * This controller does not have or need any logic, it is just used so that CI can be loaded properly during the test * execution. */ -class Test extends EA_Controller { +class Test extends EA_Controller +{ /** * Placeholder callback. * diff --git a/application/controllers/Unavailabilities.php b/application/controllers/Unavailabilities.php index bdf3ffca02..7871c2a351 100644 --- a/application/controllers/Unavailabilities.php +++ b/application/controllers/Unavailabilities.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Unavailabilities extends EA_Controller { +class Unavailabilities extends EA_Controller +{ /** * Unavailabilities constructor. */ @@ -39,10 +40,8 @@ public function __construct() */ public function search() { - try - { - if (cannot('view', PRIV_APPOINTMENTS)) - { + try { + if (cannot('view', PRIV_APPOINTMENTS)) { abort(403, 'Forbidden'); } @@ -57,9 +56,7 @@ public function search() $unavailabilities = $this->unavailabilities_model->search($keyword, $limit, $offset, $order_by); json_response($unavailabilities); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -69,10 +66,8 @@ public function search() */ public function store() { - try - { - if (cannot('add', PRIV_APPOINTMENTS)) - { + try { + if (cannot('add', PRIV_APPOINTMENTS)) { abort(403, 'Forbidden'); } @@ -89,7 +84,7 @@ public function store() 'zip_code', 'notes', 'timezone', - 'language', + 'language' ]); $unavailability_id = $this->unavailabilities_model->save($unavailability); @@ -103,12 +98,30 @@ public function store() $this->webhooks_client->trigger(WEBHOOK_UNAVAILABILITY_SAVE, $unavailability); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $unavailability_id ]); + } catch (Throwable $e) { + json_exception($e); } - catch (Throwable $e) - { + } + + /** + * Find an unavailability. + */ + public function find() + { + try { + if (cannot('view', PRIV_APPOINTMENTS)) { + abort(403, 'Forbidden'); + } + + $unavailability_id = request('unavailability_id'); + + $unavailability = $this->unavailabilities_model->find($unavailability_id); + + json_response($unavailability); + } catch (Throwable $e) { json_exception($e); } } @@ -118,10 +131,8 @@ public function store() */ public function update() { - try - { - if (cannot('edit', PRIV_APPOINTMENTS)) - { + try { + if (cannot('edit', PRIV_APPOINTMENTS)) { abort(403, 'Forbidden'); } @@ -138,12 +149,10 @@ public function update() $this->webhooks_client->trigger(WEBHOOK_UNAVAILABILITY_SAVE, $unavailability); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $unavailability_id ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -153,10 +162,8 @@ public function update() */ public function destroy() { - try - { - if (cannot('delete', PRIV_APPOINTMENTS)) - { + try { + if (cannot('delete', PRIV_APPOINTMENTS)) { abort(403, 'Forbidden'); } @@ -169,35 +176,9 @@ public function destroy() $this->webhooks_client->trigger(WEBHOOK_UNAVAILABILITY_DELETE, $unavailability); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { - json_exception($e); - } - } - - /** - * Find an unavailability. - */ - public function find() - { - try - { - if (cannot('view', PRIV_APPOINTMENTS)) - { - abort(403, 'Forbidden'); - } - - $unavailability_id = request('unavailability_id'); - - $unavailability = $this->unavailabilities_model->find($unavailability_id); - - json_response($unavailability); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/Update.php b/application/controllers/Update.php index c87f55d4aa..f083314a9d 100644 --- a/application/controllers/Update.php +++ b/application/controllers/Update.php @@ -18,20 +18,21 @@ * * @package Controllers */ -class Update extends EA_Controller { +class Update extends EA_Controller +{ /** * Update constructor. */ public function __construct() { parent::__construct(); - + $this->load->model('admins_model'); $this->load->model('settings_model'); $this->load->model('services_model'); $this->load->model('providers_model'); $this->load->model('customers_model'); - + $this->load->library('instance'); } @@ -46,14 +47,11 @@ public function __construct() */ public function index() { - try - { + try { $user_id = session('user_id'); - if (cannot('edit', PRIV_SYSTEM_SETTINGS)) - { - if ($user_id) - { + if (cannot('edit', PRIV_SYSTEM_SETTINGS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -64,11 +62,9 @@ public function index() $this->instance->migrate(); - $view = ['success' => TRUE]; - } - catch (Throwable $e) - { - $view = ['success' => FALSE, 'exception' => $e->getMessage()]; + $view = ['success' => true]; + } catch (Throwable $e) { + $view = ['success' => false, 'exception' => $e->getMessage()]; } html_vars($view); diff --git a/application/controllers/User.php b/application/controllers/User.php index 3bd5fa7a9b..10af0024fd 100644 --- a/application/controllers/User.php +++ b/application/controllers/User.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class User extends EA_Controller { +class User extends EA_Controller +{ /** * User constructor. */ @@ -40,7 +41,7 @@ public function index() /** * Display the login page. - * + * * @deprecated Since 1.5 Use the Login controller instead. */ public function login() @@ -50,17 +51,17 @@ public function login() /** * Display the logout page. - * + * * @deprecated Since 1.5 Use the Logout controller instead. */ public function logout() { - redirect('logout'); + redirect('logout'); } /** * Display the password recovery page. - * + * * @deprecated Since 1.5 Use the Logout controller instead. */ public function forgot_password() diff --git a/application/controllers/Webhooks.php b/application/controllers/Webhooks.php index ea6fd23133..eb76791a26 100644 --- a/application/controllers/Webhooks.php +++ b/application/controllers/Webhooks.php @@ -18,7 +18,8 @@ * * @package Controllers */ -class Webhooks extends EA_Controller { +class Webhooks extends EA_Controller +{ /** * Webhooks constructor. */ @@ -45,10 +46,8 @@ public function index() $user_id = session('user_id'); - if (cannot('view', PRIV_WEBHOOKS)) - { - if ($user_id) - { + if (cannot('view', PRIV_WEBHOOKS)) { + if ($user_id) { abort(403, 'Forbidden'); } @@ -61,7 +60,7 @@ public function index() script_vars([ 'user_id' => $user_id, - 'role_slug' => $role_slug, + 'role_slug' => $role_slug ]); html_vars([ @@ -100,10 +99,8 @@ public function index() */ public function search() { - try - { - if (cannot('view', PRIV_WEBHOOKS)) - { + try { + if (cannot('view', PRIV_WEBHOOKS)) { abort(403, 'Forbidden'); } @@ -118,9 +115,7 @@ public function search() $webhooks = $this->webhooks_model->search($keyword, $limit, $offset, $order_by); json_response($webhooks); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -130,10 +125,8 @@ public function search() */ public function store() { - try - { - if (cannot('add', PRIV_WEBHOOKS)) - { + try { + if (cannot('add', PRIV_WEBHOOKS)) { abort(403, 'Forbidden'); } @@ -145,18 +138,16 @@ public function store() 'actions', 'secret_token', 'is_ssl_verified', - 'notes', + 'notes' ]); $webhook_id = $this->webhooks_model->save($webhook); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $webhook_id ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -166,10 +157,8 @@ public function store() */ public function update() { - try - { - if (cannot('edit', PRIV_WEBHOOKS)) - { + try { + if (cannot('edit', PRIV_WEBHOOKS)) { abort(403, 'Forbidden'); } @@ -182,18 +171,16 @@ public function update() 'actions', 'secret_token', 'is_ssl_verified', - 'notes', + 'notes' ]); $webhook_id = $this->webhooks_model->save($webhook); json_response([ - 'success' => TRUE, + 'success' => true, 'id' => $webhook_id ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -203,10 +190,8 @@ public function update() */ public function destroy() { - try - { - if (cannot('delete', PRIV_WEBHOOKS)) - { + try { + if (cannot('delete', PRIV_WEBHOOKS)) { abort(403, 'Forbidden'); } @@ -215,11 +200,9 @@ public function destroy() $this->webhooks_model->delete($webhook_id); json_response([ - 'success' => TRUE, + 'success' => true ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -229,10 +212,8 @@ public function destroy() */ public function find() { - try - { - if (cannot('view', PRIV_WEBHOOKS)) - { + try { + if (cannot('view', PRIV_WEBHOOKS)) { abort(403, 'Forbidden'); } @@ -241,9 +222,7 @@ public function find() $webhook = $this->webhooks_model->find($webhook_id); json_response($webhook); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/api/v1/Admins_api_v1.php b/application/controllers/api/v1/Admins_api_v1.php index d4c08cfe3b..d751c1206d 100644 --- a/application/controllers/api/v1/Admins_api_v1.php +++ b/application/controllers/api/v1/Admins_api_v1.php @@ -16,7 +16,8 @@ * * @package Controllers */ -class Admins_api_v1 extends EA_Controller { +class Admins_api_v1 extends EA_Controller +{ /** * Admins_api_v1 constructor. */ @@ -38,8 +39,7 @@ public function __construct() */ public function index() { - try - { + try { $keyword = $this->api->request_keyword(); $limit = $this->api->request_limit(); @@ -53,28 +53,23 @@ public function index() $with = $this->api->request_with(); $admins = empty($keyword) - ? $this->admins_model->get(NULL, $limit, $offset, $order_by) + ? $this->admins_model->get(null, $limit, $offset, $order_by) : $this->admins_model->search($keyword, $limit, $offset, $order_by); - foreach ($admins as &$admin) - { + foreach ($admins as &$admin) { $this->admins_model->api_encode($admin); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->admins_model->only($admin, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->admins_model->load($admin, $with); } } json_response($admins); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -84,10 +79,9 @@ public function index() * * @param int|null $id Admin ID. */ - public function show(int $id = NULL) + public function show(int $id = null) { - try - { + try { $fields = $this->api->request_fields(); $with = $this->api->request_with(); @@ -96,27 +90,22 @@ public function show(int $id = NULL) $this->admins_model->api_encode($admin); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->admins_model->only($admin, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->admins_model->load($admin, $with); } - if ( ! $admin) - { + if (!$admin) { response('', 404); return; } json_response($admin); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -126,19 +115,16 @@ public function show(int $id = NULL) */ public function store() { - try - { + try { $admin = request(); $this->admins_model->api_decode($admin); - if (array_key_exists('id', $admin)) - { + if (array_key_exists('id', $admin)) { unset($admin['id']); } - if ( ! array_key_exists('settings', $admin)) - { + if (!array_key_exists('settings', $admin)) { throw new InvalidArgumentException('No settings property provided.'); } @@ -149,9 +135,7 @@ public function store() $this->admins_model->api_encode($created_admin); json_response($created_admin, 201); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -163,12 +147,10 @@ public function store() */ public function update(int $id) { - try - { + try { $occurrences = $this->admins_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -187,9 +169,7 @@ public function update(int $id) $this->admins_model->api_encode($updated_admin); json_response($updated_admin); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -201,12 +181,10 @@ public function update(int $id) */ public function destroy(int $id) { - try - { + try { $occurrences = $this->admins_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -215,9 +193,7 @@ public function destroy(int $id) $this->admins_model->delete($id); response('', 204); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/api/v1/Appointments_api_v1.php b/application/controllers/api/v1/Appointments_api_v1.php index 669f77892f..0e26e7937f 100644 --- a/application/controllers/api/v1/Appointments_api_v1.php +++ b/application/controllers/api/v1/Appointments_api_v1.php @@ -16,7 +16,8 @@ * * @package Controllers */ -class Appointments_api_v1 extends EA_Controller { +class Appointments_api_v1 extends EA_Controller +{ /** * Appointments_api_v1 constructor. */ @@ -44,8 +45,7 @@ public function __construct() */ public function index() { - try - { + try { $keyword = $this->api->request_keyword(); $limit = $this->api->request_limit(); @@ -58,14 +58,13 @@ public function index() $with = $this->api->request_with(); - $where = NULL; + $where = null; // Date query param. $date = request('date'); - if ( ! empty($date)) - { + if (!empty($date)) { $where['DATE(start_datetime)'] = (new DateTime($date))->format('Y-m-d'); } @@ -73,8 +72,7 @@ public function index() $from = request('from'); - if ( ! empty($from)) - { + if (!empty($from)) { $where['DATE(start_datetime) >='] = (new DateTime($from))->format('Y-m-d'); } @@ -82,8 +80,7 @@ public function index() $till = request('till'); - if ( ! empty($till)) - { + if (!empty($till)) { $where['DATE(end_datetime) <='] = (new DateTime($till))->format('Y-m-d'); } @@ -91,8 +88,7 @@ public function index() $service_id = request('serviceId'); - if ( ! empty($service_id)) - { + if (!empty($service_id)) { $where['id_services'] = $service_id; } @@ -100,8 +96,7 @@ public function index() $provider_id = request('providerId'); - if ( ! empty($provider_id)) - { + if (!empty($provider_id)) { $where['id_users_provider'] = $provider_id; } @@ -109,8 +104,7 @@ public function index() $customer_id = request('customerId'); - if ( ! empty($customer_id)) - { + if (!empty($customer_id)) { $where['id_users_customer'] = $customer_id; } @@ -118,40 +112,68 @@ public function index() ? $this->appointments_model->get($where, $limit, $offset, $order_by) : $this->appointments_model->search($keyword, $limit, $offset, $order_by); - foreach ($appointments as &$appointment) - { + foreach ($appointments as &$appointment) { $this->appointments_model->api_encode($appointment); $this->aggregates($appointment); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->appointments_model->only($appointment, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->appointments_model->load($appointment, $with); } } json_response($appointments); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } + /** + * Load the relations of the current appointment if the "aggregates" query parameter is present. + * + * This is a compatibility addition to the appointment resource which was the only one to support it. + * + * Use the "attach" query parameter instead as this one will be removed. + * + * @param array $appointment Appointment data. + * + * @deprecated Since 1.5 + */ + private function aggregates(array &$appointment) + { + $aggregates = request('aggregates') !== null; + + if ($aggregates) { + $appointment['service'] = $this->services_model->find( + $appointment['id_services'] ?? ($appointment['serviceId'] ?? null), + true + ); + $appointment['provider'] = $this->providers_model->find( + $appointment['id_users_provider'] ?? ($appointment['providerId'] ?? null), + true + ); + $appointment['customer'] = $this->customers_model->find( + $appointment['id_users_customer'] ?? ($appointment['customerId'] ?? null), + true + ); + $this->services_model->api_encode($appointment['service']); + $this->providers_model->api_encode($appointment['provider']); + $this->customers_model->api_encode($appointment['customer']); + } + } + /** * Get a single appointment. * * @param int|null $id Appointment ID. */ - public function show(int $id = NULL) + public function show(int $id = null) { - try - { + try { $fields = $this->api->request_fields(); $with = $this->api->request_with(); @@ -160,27 +182,22 @@ public function show(int $id = NULL) $this->appointments_model->api_encode($appointment); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->appointments_model->only($appointment, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->appointments_model->load($appointment, $with); } - if ( ! $appointment) - { + if (!$appointment) { response('Not Found', 404); return; } json_response($appointment); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -190,19 +207,16 @@ public function show(int $id = NULL) */ public function store() { - try - { + try { $appointment = request(); $this->appointments_model->api_decode($appointment); - if (array_key_exists('id', $appointment)) - { + if (array_key_exists('id', $appointment)) { unset($appointment['id']); } - if ( ! array_key_exists('end_datetime', $appointment)) - { + if (!array_key_exists('end_datetime', $appointment)) { $appointment['end_datetime'] = $this->calculate_end_datetime($appointment); } @@ -215,13 +229,67 @@ public function store() $this->appointments_model->api_encode($created_appointment); json_response($created_appointment, 201); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } + /** + * Calculate the end date time of an appointment based on the selected service. + * + * @param array $appointment Appointment data. + * + * @return string Returns the end date time value. + * + * @throws Exception + */ + private function calculate_end_datetime(array $appointment): string + { + $duration = $this->services_model->value($appointment['id_services'], 'duration'); + + $end = new DateTime($appointment['start_datetime']); + + $end->add(new DateInterval('PT' . $duration . 'M')); + + return $end->format('Y-m-d H:i:s'); + } + + /** + * Send the required notifications and trigger syncing after saving an appointment. + * + * @param array $appointment Appointment data. + * @param string $action Performed action ("store" or "update"). + */ + private function notify_and_sync_appointment(array $appointment, string $action = 'store') + { + $manage_mode = $action === 'update'; + + $service = $this->services_model->find($appointment['id_services'], true); + + $provider = $this->providers_model->find($appointment['id_users_provider'], true); + + $customer = $this->customers_model->find($appointment['id_users_customer'], true); + + $settings = [ + 'company_name' => setting('company_name'), + 'company_email' => setting('company_email'), + 'company_link' => setting('company_link'), + 'date_format' => setting('date_format'), + 'time_format' => setting('time_format') + ]; + + $this->synchronization->sync_appointment_saved($appointment, $service, $provider, $customer, $settings); + + $this->notifications->notify_appointment_saved( + $appointment, + $service, + $provider, + $customer, + $settings, + $manage_mode + ); + } + /** * Update an appointment. * @@ -229,12 +297,10 @@ public function store() */ public function update(int $id) { - try - { + try { $occurrences = $this->appointments_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -255,9 +321,7 @@ public function update(int $id) $this->appointments_model->api_encode($updated_appointment); json_response($updated_appointment); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -269,12 +333,10 @@ public function update(int $id) */ public function destroy(int $id) { - try - { + try { $occurrences = $this->appointments_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -282,11 +344,11 @@ public function destroy(int $id) $deleted_appointment = $occurrences[0]; - $service = $this->services_model->find($deleted_appointment['id_services'], TRUE); + $service = $this->services_model->find($deleted_appointment['id_services'], true); - $provider = $this->providers_model->find($deleted_appointment['id_users_provider'], TRUE); + $provider = $this->providers_model->find($deleted_appointment['id_users_provider'], true); - $customer = $this->customers_model->find($deleted_appointment['id_users_customer'], TRUE); + $customer = $this->customers_model->find($deleted_appointment['id_users_customer'], true); $settings = [ 'company_name' => setting('company_name'), @@ -300,88 +362,17 @@ public function destroy(int $id) $this->synchronization->sync_appointment_deleted($deleted_appointment, $provider); - $this->notifications->notify_appointment_deleted($deleted_appointment, $service, $provider, $customer, $settings); + $this->notifications->notify_appointment_deleted( + $deleted_appointment, + $service, + $provider, + $customer, + $settings + ); response('', 204); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } - - /** - * Send the required notifications and trigger syncing after saving an appointment. - * - * @param array $appointment Appointment data. - * @param string $action Performed action ("store" or "update"). - */ - private function notify_and_sync_appointment(array $appointment, string $action = 'store') - { - $manage_mode = $action === 'update'; - - $service = $this->services_model->find($appointment['id_services'], TRUE); - - $provider = $this->providers_model->find($appointment['id_users_provider'], TRUE); - - $customer = $this->customers_model->find($appointment['id_users_customer'], TRUE); - - $settings = [ - 'company_name' => setting('company_name'), - 'company_email' => setting('company_email'), - 'company_link' => setting('company_link'), - 'date_format' => setting('date_format'), - 'time_format' => setting('time_format') - ]; - - $this->synchronization->sync_appointment_saved($appointment, $service, $provider, $customer, $settings); - - $this->notifications->notify_appointment_saved($appointment, $service, $provider, $customer, $settings, $manage_mode); - } - - /** - * Calculate the end date time of an appointment based on the selected service. - * - * @param array $appointment Appointment data. - * - * @return string Returns the end date time value. - * - * @throws Exception - */ - private function calculate_end_datetime(array $appointment): string - { - $duration = $this->services_model->value($appointment['id_services'], 'duration'); - - $end = new DateTime($appointment['start_datetime']); - - $end->add(new DateInterval('PT' . $duration . 'M')); - - return $end->format('Y-m-d H:i:s'); - } - - /** - * Load the relations of the current appointment if the "aggregates" query parameter is present. - * - * This is a compatibility addition to the appointment resource which was the only one to support it. - * - * Use the "attach" query parameter instead as this one will be removed. - * - * @param array $appointment Appointment data. - * - * @deprecated Since 1.5 - */ - private function aggregates(array &$appointment) - { - $aggregates = request('aggregates') !== NULL; - - if ($aggregates) - { - $appointment['service'] = $this->services_model->find($appointment['id_services'] ?? $appointment['serviceId'] ?? NULL, TRUE); - $appointment['provider'] = $this->providers_model->find($appointment['id_users_provider'] ?? $appointment['providerId'] ?? NULL, TRUE); - $appointment['customer'] = $this->customers_model->find($appointment['id_users_customer'] ?? $appointment['customerId'] ?? NULL, TRUE); - $this->services_model->api_encode($appointment['service']); - $this->providers_model->api_encode($appointment['provider']); - $this->customers_model->api_encode($appointment['customer']); - } - } } diff --git a/application/controllers/api/v1/Availabilities_api_v1.php b/application/controllers/api/v1/Availabilities_api_v1.php index a7b5b5101b..e0a87ec84b 100644 --- a/application/controllers/api/v1/Availabilities_api_v1.php +++ b/application/controllers/api/v1/Availabilities_api_v1.php @@ -16,7 +16,8 @@ * * @package Controllers */ -class Availabilities_api_v1 extends EA_Controller { +class Availabilities_api_v1 extends EA_Controller +{ /** * Availabilities_api_v1 constructor. */ @@ -27,7 +28,7 @@ public function __construct() $this->load->library('api'); $this->api->auth(); - + $this->load->model('appointments_model'); $this->load->model('providers_model'); $this->load->model('services_model'); @@ -55,16 +56,14 @@ public function __construct() */ public function get() { - try - { + try { $provider_id = request('providerId'); $service_id = request('serviceId'); $date = request('date'); - if ( ! $date) - { + if (!$date) { $date = date('Y-m-d'); } @@ -75,9 +74,7 @@ public function get() $available_hours = $this->availability->get_available_hours($date, $service, $provider); json_response($available_hours); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/api/v1/Customers_api_v1.php b/application/controllers/api/v1/Customers_api_v1.php index f98a10c47a..693cc7b560 100644 --- a/application/controllers/api/v1/Customers_api_v1.php +++ b/application/controllers/api/v1/Customers_api_v1.php @@ -16,7 +16,8 @@ * * @package Controllers */ -class Customers_api_v1 extends EA_Controller { +class Customers_api_v1 extends EA_Controller +{ /** * Customers_api_v1 constructor. */ @@ -36,8 +37,7 @@ public function __construct() */ public function index() { - try - { + try { $keyword = $this->api->request_keyword(); $limit = $this->api->request_limit(); @@ -51,28 +51,23 @@ public function index() $with = $this->api->request_with(); $customers = empty($keyword) - ? $this->customers_model->get(NULL, $limit, $offset, $order_by) + ? $this->customers_model->get(null, $limit, $offset, $order_by) : $this->customers_model->search($keyword, $limit, $offset, $order_by); - foreach ($customers as &$customer) - { + foreach ($customers as &$customer) { $this->customers_model->api_encode($customer); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->customers_model->only($customer, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->customers_model->load($customer, $with); } } json_response($customers); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -82,32 +77,27 @@ public function index() * * @param int|null $id Customer ID. */ - public function show(int $id = NULL) + public function show(int $id = null) { - try - { + try { $fields = $this->api->request_fields(); $customer = $this->customers_model->find($id); $this->customers_model->api_encode($customer); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->customers_model->only($customer, $fields); } - if ( ! $customer) - { + if (!$customer) { response('', 404); return; } json_response($customer); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -117,14 +107,12 @@ public function show(int $id = NULL) */ public function store() { - try - { + try { $customer = request(); $this->customers_model->api_decode($customer); - if (array_key_exists('id', $customer)) - { + if (array_key_exists('id', $customer)) { unset($customer['id']); } @@ -135,9 +123,7 @@ public function store() $this->customers_model->api_encode($created_customer); json_response($created_customer, 201); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -149,12 +135,10 @@ public function store() */ public function update(int $id) { - try - { + try { $occurrences = $this->customers_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -173,9 +157,7 @@ public function update(int $id) $this->customers_model->api_encode($updated_customer); json_response($updated_customer); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -187,12 +169,10 @@ public function update(int $id) */ public function destroy(int $id) { - try - { + try { $occurrences = $this->customers_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -201,9 +181,7 @@ public function destroy(int $id) $this->customers_model->delete($id); response('', 204); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/api/v1/Providers_api_v1.php b/application/controllers/api/v1/Providers_api_v1.php index 61928f2265..916942b970 100644 --- a/application/controllers/api/v1/Providers_api_v1.php +++ b/application/controllers/api/v1/Providers_api_v1.php @@ -16,7 +16,8 @@ * * @package Controllers */ -class Providers_api_v1 extends EA_Controller { +class Providers_api_v1 extends EA_Controller +{ /** * Providers_api_v1 constructor. */ @@ -36,8 +37,7 @@ public function __construct() */ public function index() { - try - { + try { $keyword = $this->api->request_keyword(); $limit = $this->api->request_limit(); @@ -47,32 +47,27 @@ public function index() $order_by = $this->api->request_order_by(); $fields = $this->api->request_fields(); - + $with = $this->api->request_with(); $providers = empty($keyword) - ? $this->providers_model->get(NULL, $limit, $offset, $order_by) + ? $this->providers_model->get(null, $limit, $offset, $order_by) : $this->providers_model->search($keyword, $limit, $offset, $order_by); - foreach ($providers as &$provider) - { + foreach ($providers as &$provider) { $this->providers_model->api_encode($provider); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->providers_model->only($provider, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->providers_model->load($provider, $with); } } json_response($providers); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -82,39 +77,33 @@ public function index() * * @param int|null $id Provider ID. */ - public function show(int $id = NULL) + public function show(int $id = null) { - try - { + try { $fields = $this->api->request_fields(); - + $with = $this->api->request_with(); $provider = $this->providers_model->find($id); $this->providers_model->api_encode($provider); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->providers_model->only($provider, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->providers_model->load($provider, $with); } - if ( ! $provider) - { + if (!$provider) { response('', 404); return; } json_response($provider); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -124,29 +113,24 @@ public function show(int $id = NULL) */ public function store() { - try - { + try { $provider = request(); $this->providers_model->api_decode($provider); - if (array_key_exists('id', $provider)) - { + if (array_key_exists('id', $provider)) { unset($provider['id']); } - if ( ! array_key_exists('services', $provider)) - { + if (!array_key_exists('services', $provider)) { throw new InvalidArgumentException('No services property provided.'); } - if ( ! array_key_exists('settings', $provider)) - { + if (!array_key_exists('settings', $provider)) { throw new InvalidArgumentException('No settings property provided.'); } - if ( ! array_key_exists('working_plan', $provider['settings'])) - { + if (!array_key_exists('working_plan', $provider['settings'])) { $provider['settings']['working_plan'] = setting('company_working_plan'); } @@ -157,9 +141,7 @@ public function store() $this->providers_model->api_encode($created_provider); json_response($created_provider, 201); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -171,12 +153,10 @@ public function store() */ public function update(int $id) { - try - { + try { $occurrences = $this->providers_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -195,9 +175,7 @@ public function update(int $id) $this->providers_model->api_encode($updated_provider); json_response($updated_provider); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -209,12 +187,10 @@ public function update(int $id) */ public function destroy(int $id) { - try - { + try { $occurrences = $this->providers_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -223,9 +199,7 @@ public function destroy(int $id) $this->providers_model->delete($id); response('', 204); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/api/v1/Secretaries_api_v1.php b/application/controllers/api/v1/Secretaries_api_v1.php index 6c50e168a0..9d151565a0 100644 --- a/application/controllers/api/v1/Secretaries_api_v1.php +++ b/application/controllers/api/v1/Secretaries_api_v1.php @@ -16,7 +16,8 @@ * * @package Controllers */ -class Secretaries_api_v1 extends EA_Controller { +class Secretaries_api_v1 extends EA_Controller +{ /** * Secretaries_api_v1 constructor. */ @@ -36,8 +37,7 @@ public function __construct() */ public function index() { - try - { + try { $keyword = $this->api->request_keyword(); $limit = $this->api->request_limit(); @@ -51,28 +51,23 @@ public function index() $with = $this->api->request_with(); $secretaries = empty($keyword) - ? $this->secretaries_model->get(NULL, $limit, $offset, $order_by) + ? $this->secretaries_model->get(null, $limit, $offset, $order_by) : $this->secretaries_model->search($keyword, $limit, $offset, $order_by); - foreach ($secretaries as &$secretary) - { + foreach ($secretaries as &$secretary) { $this->secretaries_model->api_encode($secretary); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->secretaries_model->only($secretary, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->secretaries_model->load($secretary, $with); } } json_response($secretaries); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -82,32 +77,27 @@ public function index() * * @param int|null $id Secretary ID. */ - public function show(int $id = NULL) + public function show(int $id = null) { - try - { + try { $fields = $this->api->request_fields(); $secretary = $this->secretaries_model->find($id); $this->secretaries_model->api_encode($secretary); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->secretaries_model->only($secretary, $fields); } - if ( ! $secretary) - { + if (!$secretary) { response('', 404); return; } json_response($secretary); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -117,24 +107,20 @@ public function show(int $id = NULL) */ public function store() { - try - { + try { $secretary = request(); $this->secretaries_model->api_decode($secretary); - if (array_key_exists('id', $secretary)) - { + if (array_key_exists('id', $secretary)) { unset($secretary['id']); } - if ( ! array_key_exists('providers', $secretary)) - { + if (!array_key_exists('providers', $secretary)) { throw new InvalidArgumentException('No providers property provided.'); } - if ( ! array_key_exists('settings', $secretary)) - { + if (!array_key_exists('settings', $secretary)) { throw new InvalidArgumentException('No settings property provided.'); } @@ -145,9 +131,7 @@ public function store() $this->secretaries_model->api_encode($created_secretary); json_response($created_secretary, 201); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -159,12 +143,10 @@ public function store() */ public function update(int $id) { - try - { + try { $occurrences = $this->secretaries_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -183,9 +165,7 @@ public function update(int $id) $this->secretaries_model->api_encode($updated_secretary); json_response($updated_secretary); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -197,12 +177,10 @@ public function update(int $id) */ public function destroy(int $id) { - try - { + try { $occurrences = $this->secretaries_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -211,9 +189,7 @@ public function destroy(int $id) $this->secretaries_model->delete($id); response('', 204); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/api/v1/Service_categories_api_v1.php b/application/controllers/api/v1/Service_categories_api_v1.php index 0ba60876fa..c8c8448183 100644 --- a/application/controllers/api/v1/Service_categories_api_v1.php +++ b/application/controllers/api/v1/Service_categories_api_v1.php @@ -16,7 +16,8 @@ * * @package Controllers */ -class Service_categories_api_v1 extends EA_Controller { +class Service_categories_api_v1 extends EA_Controller +{ /** * Service_categories_api_v1 constructor. */ @@ -36,8 +37,7 @@ public function __construct() */ public function index() { - try - { + try { $keyword = $this->api->request_keyword(); $limit = $this->api->request_limit(); @@ -47,32 +47,27 @@ public function index() $order_by = $this->api->request_order_by(); $fields = $this->api->request_fields(); - + $with = $this->api->request_with(); $service_categories = empty($keyword) - ? $this->service_categories_model->get(NULL, $limit, $offset, $order_by) + ? $this->service_categories_model->get(null, $limit, $offset, $order_by) : $this->service_categories_model->search($keyword, $limit, $offset, $order_by); - foreach ($service_categories as &$service_category) - { + foreach ($service_categories as &$service_category) { $this->service_categories_model->api_encode($service_category); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->service_categories_model->only($service_category, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->service_categories_model->load($service_category, $with); } } json_response($service_categories); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -82,39 +77,33 @@ public function index() * * @param int|null $id Service-category ID. */ - public function show(int $id = NULL) + public function show(int $id = null) { - try - { + try { $fields = $this->api->request_fields(); - + $with = $this->api->request_with(); $service_category = $this->service_categories_model->find($id); $this->service_categories_model->api_encode($service_category); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->service_categories_model->only($service_category, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->service_categories_model->load($service_category, $with); } - if ( ! $service_category) - { + if (!$service_category) { response('', 404); return; } json_response($service_category); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -124,14 +113,12 @@ public function show(int $id = NULL) */ public function store() { - try - { + try { $service_category = request(); $this->service_categories_model->api_decode($service_category); - if (array_key_exists('id', $service_category)) - { + if (array_key_exists('id', $service_category)) { unset($service_category['id']); } @@ -142,9 +129,7 @@ public function store() $this->service_categories_model->api_encode($created_service_category); json_response($created_service_category, 201); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -156,12 +141,10 @@ public function store() */ public function update(int $id) { - try - { + try { $occurrences = $this->service_categories_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -180,9 +163,7 @@ public function update(int $id) $this->service_categories_model->api_encode($updated_service_category); json_response($updated_service_category); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -194,12 +175,10 @@ public function update(int $id) */ public function destroy(int $id) { - try - { + try { $occurrences = $this->service_categories_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -208,9 +187,7 @@ public function destroy(int $id) $this->service_categories_model->delete($id); response('', 204); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/api/v1/Services_api_v1.php b/application/controllers/api/v1/Services_api_v1.php index 96c12f6208..fa6f250d03 100644 --- a/application/controllers/api/v1/Services_api_v1.php +++ b/application/controllers/api/v1/Services_api_v1.php @@ -16,7 +16,8 @@ * * @package Controllers */ -class Services_api_v1 extends EA_Controller { +class Services_api_v1 extends EA_Controller +{ /** * Services_api_v1 constructor. */ @@ -36,8 +37,7 @@ public function __construct() */ public function index() { - try - { + try { $keyword = $this->api->request_keyword(); $limit = $this->api->request_limit(); @@ -47,32 +47,27 @@ public function index() $order_by = $this->api->request_order_by(); $fields = $this->api->request_fields(); - + $with = $this->api->request_with(); $services = empty($keyword) - ? $this->services_model->get(NULL, $limit, $offset, $order_by) + ? $this->services_model->get(null, $limit, $offset, $order_by) : $this->services_model->search($keyword, $limit, $offset, $order_by); - foreach ($services as &$service) - { + foreach ($services as &$service) { $this->services_model->api_encode($service); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->services_model->only($service, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->services_model->load($service, $with); } } json_response($services); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -82,39 +77,33 @@ public function index() * * @param int|null $id Service ID. */ - public function show(int $id = NULL) + public function show(int $id = null) { - try - { + try { $fields = $this->api->request_fields(); - + $with = $this->api->request_with(); $service = $this->services_model->find($id); $this->services_model->api_encode($service); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->services_model->only($service, $fields); } - - if ( ! empty($with)) - { + + if (!empty($with)) { $this->services_model->load($service, $with); } - if ( ! $service) - { + if (!$service) { response('', 404); return; } json_response($service); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -124,14 +113,12 @@ public function show(int $id = NULL) */ public function store() { - try - { + try { $service = request(); $this->services_model->api_decode($service); - if (array_key_exists('id', $service)) - { + if (array_key_exists('id', $service)) { unset($service['id']); } @@ -142,9 +129,7 @@ public function store() $this->services_model->api_encode($created_service); json_response($created_service, 201); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -156,12 +141,10 @@ public function store() */ public function update(int $id) { - try - { + try { $occurrences = $this->services_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -180,9 +163,7 @@ public function update(int $id) $this->services_model->api_encode($updated_service); json_response($updated_service); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -194,12 +175,10 @@ public function update(int $id) */ public function destroy(int $id) { - try - { + try { $occurrences = $this->services_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -208,9 +187,7 @@ public function destroy(int $id) $this->services_model->delete($id); response('', 204); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/api/v1/Settings_api_v1.php b/application/controllers/api/v1/Settings_api_v1.php index 33f029f297..8dd55cc3a0 100644 --- a/application/controllers/api/v1/Settings_api_v1.php +++ b/application/controllers/api/v1/Settings_api_v1.php @@ -16,7 +16,8 @@ * * @package Controllers */ -class Settings_api_v1 extends EA_Controller { +class Settings_api_v1 extends EA_Controller +{ /** * Settings_api_v1 constructor. */ @@ -36,8 +37,7 @@ public function __construct() */ public function index() { - try - { + try { $keyword = $this->api->request_keyword(); $limit = $this->api->request_limit(); @@ -49,23 +49,19 @@ public function index() $fields = $this->api->request_fields(); $settings = empty($keyword) - ? $this->settings_model->get(NULL, $limit, $offset, $order_by) + ? $this->settings_model->get(null, $limit, $offset, $order_by) : $this->settings_model->search($keyword, $limit, $offset, $order_by); - foreach ($settings as &$setting) - { + foreach ($settings as &$setting) { $this->settings_model->api_encode($setting); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->settings_model->only($setting, $fields); } } json_response($settings); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -77,17 +73,14 @@ public function index() */ public function show(string $name) { - try - { + try { $value = setting($name); json_response([ 'name' => $name, - 'value' => $value, + 'value' => $value ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -99,19 +92,16 @@ public function show(string $name) */ public function update(string $name) { - try - { + try { $value = request('value'); setting([$name => $value]); json_response([ 'name' => $name, - 'value' => $value, + 'value' => $value ]); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/api/v1/Unavailabilities_api_v1.php b/application/controllers/api/v1/Unavailabilities_api_v1.php index 1359229a7a..dbf304bdb5 100644 --- a/application/controllers/api/v1/Unavailabilities_api_v1.php +++ b/application/controllers/api/v1/Unavailabilities_api_v1.php @@ -16,7 +16,8 @@ * * @package Controllers */ -class Unavailabilities_api_v1 extends EA_Controller { +class Unavailabilities_api_v1 extends EA_Controller +{ /** * Unavailabilities_api_v1 constructor. */ @@ -36,8 +37,7 @@ public function __construct() */ public function index() { - try - { + try { $keyword = $this->api->request_keyword(); $limit = $this->api->request_limit(); @@ -51,28 +51,23 @@ public function index() $with = $this->api->request_with(); $unavailabilities = empty($keyword) - ? $this->unavailabilities_model->get(NULL, $limit, $offset, $order_by) + ? $this->unavailabilities_model->get(null, $limit, $offset, $order_by) : $this->unavailabilities_model->search($keyword, $limit, $offset, $order_by); - foreach ($unavailabilities as &$unavailability) - { + foreach ($unavailabilities as &$unavailability) { $this->unavailabilities_model->api_encode($unavailability); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->unavailabilities_model->only($unavailability, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->unavailabilities_model->load($unavailability, $with); } } json_response($unavailabilities); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -82,10 +77,9 @@ public function index() * * @param int|null $id Unavailability ID. */ - public function show(int $id = NULL) + public function show(int $id = null) { - try - { + try { $fields = $this->api->request_fields(); $with = $this->api->request_with(); @@ -94,27 +88,22 @@ public function show(int $id = NULL) $this->unavailabilities_model->api_encode($unavailability); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->unavailabilities_model->only($unavailability, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->unavailabilities_model->load($unavailability, $with); } - if ( ! $unavailability) - { + if (!$unavailability) { response('', 404); return; } json_response($unavailability); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -124,14 +113,12 @@ public function show(int $id = NULL) */ public function store() { - try - { + try { $unavailability = request(); $this->unavailabilities_model->api_decode($unavailability); - if (array_key_exists('id', $unavailability)) - { + if (array_key_exists('id', $unavailability)) { unset($unavailability['id']); } @@ -142,9 +129,7 @@ public function store() $this->unavailabilities_model->api_encode($created_unavailability); json_response($created_unavailability, 201); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -156,12 +141,10 @@ public function store() */ public function update(int $id) { - try - { + try { $occurrences = $this->unavailabilities_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -180,9 +163,7 @@ public function update(int $id) $this->unavailabilities_model->api_encode($updated_unavailability); json_response($updated_unavailability); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -194,12 +175,10 @@ public function update(int $id) */ public function destroy(int $id) { - try - { + try { $occurrences = $this->unavailabilities_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -208,9 +187,7 @@ public function destroy(int $id) $this->unavailabilities_model->delete($id); response('', 204); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/controllers/api/v1/Webhooks_api_v1.php b/application/controllers/api/v1/Webhooks_api_v1.php index 338e878354..b7baa95478 100644 --- a/application/controllers/api/v1/Webhooks_api_v1.php +++ b/application/controllers/api/v1/Webhooks_api_v1.php @@ -16,7 +16,8 @@ * * @package Controllers */ -class Webhooks_api_v1 extends EA_Controller { +class Webhooks_api_v1 extends EA_Controller +{ /** * Webhooks_api_v1 constructor. */ @@ -36,8 +37,7 @@ public function __construct() */ public function index() { - try - { + try { $keyword = $this->api->request_keyword(); $limit = $this->api->request_limit(); @@ -47,32 +47,27 @@ public function index() $order_by = $this->api->request_order_by(); $fields = $this->api->request_fields(); - + $with = $this->api->request_with(); $webhooks = empty($keyword) - ? $this->webhooks_model->get(NULL, $limit, $offset, $order_by) + ? $this->webhooks_model->get(null, $limit, $offset, $order_by) : $this->webhooks_model->search($keyword, $limit, $offset, $order_by); - foreach ($webhooks as &$webhook) - { + foreach ($webhooks as &$webhook) { $this->webhooks_model->api_encode($webhook); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->webhooks_model->only($webhook, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->webhooks_model->load($webhook, $with); } } json_response($webhooks); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -82,39 +77,33 @@ public function index() * * @param int|null $id Webhook ID. */ - public function show(int $id = NULL) + public function show(int $id = null) { - try - { + try { $fields = $this->api->request_fields(); - + $with = $this->api->request_with(); $webhook = $this->webhooks_model->find($id); $this->webhooks_model->api_encode($webhook); - if ( ! empty($fields)) - { + if (!empty($fields)) { $this->webhooks_model->only($webhook, $fields); } - if ( ! empty($with)) - { + if (!empty($with)) { $this->webhooks_model->load($webhook, $with); } - if ( ! $webhook) - { + if (!$webhook) { response('', 404); return; } json_response($webhook); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -124,14 +113,12 @@ public function show(int $id = NULL) */ public function store() { - try - { + try { $webhook = request(); $this->webhooks_model->api_decode($webhook); - if (array_key_exists('id', $webhook)) - { + if (array_key_exists('id', $webhook)) { unset($webhook['id']); } @@ -142,9 +129,7 @@ public function store() $this->webhooks_model->api_encode($created_webhook); json_response($created_webhook, 201); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -156,12 +141,10 @@ public function store() */ public function update(int $id) { - try - { + try { $occurrences = $this->webhooks_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -180,9 +163,7 @@ public function update(int $id) $this->webhooks_model->api_encode($updated_webhook); json_response($updated_webhook); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } @@ -194,12 +175,10 @@ public function update(int $id) */ public function destroy(int $id) { - try - { + try { $occurrences = $this->webhooks_model->get(['id' => $id]); - if (empty($occurrences)) - { + if (empty($occurrences)) { response('', 404); return; @@ -208,9 +187,7 @@ public function destroy(int $id) $this->webhooks_model->delete($id); response('', 204); - } - catch (Throwable $e) - { + } catch (Throwable $e) { json_exception($e); } } diff --git a/application/core/EA_Benchmark.php b/application/core/EA_Benchmark.php index b8ea800eef..3671260b74 100644 --- a/application/core/EA_Benchmark.php +++ b/application/core/EA_Benchmark.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Benchmark extends CI_Benchmark { - // +class EA_Benchmark extends CI_Benchmark +{ + // } diff --git a/application/core/EA_Cache.php b/application/core/EA_Cache.php index 525515488a..5347104308 100644 --- a/application/core/EA_Cache.php +++ b/application/core/EA_Cache.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Cache extends CI_Cache { - // +class EA_Cache extends CI_Cache +{ + // } diff --git a/application/core/EA_Calendar.php b/application/core/EA_Calendar.php index bb66d848ad..6be1847609 100644 --- a/application/core/EA_Calendar.php +++ b/application/core/EA_Calendar.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Calendar extends CI_Calendar { - // +class EA_Calendar extends CI_Calendar +{ + // } diff --git a/application/core/EA_Config.php b/application/core/EA_Config.php index ae71134e2d..ec21792fc3 100644 --- a/application/core/EA_Config.php +++ b/application/core/EA_Config.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Config extends CI_Config { - // +class EA_Config extends CI_Config +{ + // } diff --git a/application/core/EA_Controller.php b/application/core/EA_Controller.php index a7a568a63c..831050a576 100644 --- a/application/core/EA_Controller.php +++ b/application/core/EA_Controller.php @@ -68,7 +68,8 @@ * @property Timezones $timezones * @property Webhooks_client $webhooks_client */ -class EA_Controller extends CI_Controller { +class EA_Controller extends CI_Controller +{ /** * EA_Controller constructor. */ @@ -89,6 +90,21 @@ public function __construct() rate_limit($this->input->ip_address()); } + private function ensure_user_exists() + { + $user_id = session('user_id'); + + if (!$user_id) { + return; + } + + if (!$this->accounts->does_account_exist($user_id)) { + session_destroy(); + + abort(403, 'Forbidden'); + } + } + /** * Configure the language. */ @@ -96,10 +112,9 @@ private function configure_language() { $session_language = session('language'); - if ($session_language) - { - $language_codes = config('language_codes'); - + if ($session_language) { + $language_codes = config('language_codes'); + config([ 'language' => $session_language, 'language_code' => array_search($session_language, $language_codes) ?: 'en' @@ -119,7 +134,7 @@ private function load_common_html_vars() 'index_page' => config('index_page'), 'available_languages' => config('available_languages'), 'language' => $this->lang->language, - 'csrf_token' => $this->security->get_csrf_hash(), + 'csrf_token' => $this->security->get_csrf_hash() ]); } @@ -134,24 +149,7 @@ private function load_common_script_vars() 'available_languages' => config('available_languages'), 'csrf_token' => $this->security->get_csrf_hash(), 'language' => config('language'), - 'language_code' => config('language_code'), + 'language_code' => config('language_code') ]); } - - private function ensure_user_exists() - { - $user_id = session('user_id'); - - if ( ! $user_id) - { - return; - } - - if ( ! $this->accounts->does_account_exist($user_id)) - { - session_destroy(); - - abort(403, 'Forbidden'); - } - } } diff --git a/application/core/EA_DB_forge.php b/application/core/EA_DB_forge.php index cce824ca4d..6a374795a9 100644 --- a/application/core/EA_DB_forge.php +++ b/application/core/EA_DB_forge.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_DB_forge extends CI_DB_forge { - // +class EA_DB_forge extends CI_DB_forge +{ + // } diff --git a/application/core/EA_DB_query_builder.php b/application/core/EA_DB_query_builder.php index 389e42a37a..0d977ef220 100644 --- a/application/core/EA_DB_query_builder.php +++ b/application/core/EA_DB_query_builder.php @@ -38,9 +38,10 @@ * @property EA_Session $session * @property EA_Upload $upload * @property EA_URI $uri - * + * * @method int insert_id() */ -class EA_DB_query_builder extends CI_DB_query_builder { - // +class EA_DB_query_builder extends CI_DB_query_builder +{ + // } diff --git a/application/core/EA_DB_utility.php b/application/core/EA_DB_utility.php index 5c40bce5bd..fea3f43a8e 100644 --- a/application/core/EA_DB_utility.php +++ b/application/core/EA_DB_utility.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_DB_utility extends CI_DB_utility { - // +class EA_DB_utility extends CI_DB_utility +{ + // } diff --git a/application/core/EA_Email.php b/application/core/EA_Email.php index 2b4ae7a645..be1b79abd0 100644 --- a/application/core/EA_Email.php +++ b/application/core/EA_Email.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Email extends CI_Email { - // +class EA_Email extends CI_Email +{ + // } diff --git a/application/core/EA_Encrypt.php b/application/core/EA_Encrypt.php index 85d759c69a..1363571fde 100644 --- a/application/core/EA_Encrypt.php +++ b/application/core/EA_Encrypt.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Encrypt extends CI_Encrypt { - // +class EA_Encrypt extends CI_Encrypt +{ + // } diff --git a/application/core/EA_Encryption.php b/application/core/EA_Encryption.php index f55ec1409b..cadd4ccb33 100644 --- a/application/core/EA_Encryption.php +++ b/application/core/EA_Encryption.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Encryption extends CI_Encryption { - // +class EA_Encryption extends CI_Encryption +{ + // } diff --git a/application/core/EA_Exceptions.php b/application/core/EA_Exceptions.php index be0d41d27d..a9ce4a0803 100644 --- a/application/core/EA_Exceptions.php +++ b/application/core/EA_Exceptions.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Exceptions extends CI_Exceptions { - // +class EA_Exceptions extends CI_Exceptions +{ + // } diff --git a/application/core/EA_Hooks.php b/application/core/EA_Hooks.php index 31fd950ff6..d1990a3b09 100644 --- a/application/core/EA_Hooks.php +++ b/application/core/EA_Hooks.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Hooks extends CI_Hooks { - // +class EA_Hooks extends CI_Hooks +{ + // } diff --git a/application/core/EA_Input.php b/application/core/EA_Input.php index 9e006d44bf..da7a52d7d5 100644 --- a/application/core/EA_Input.php +++ b/application/core/EA_Input.php @@ -41,7 +41,8 @@ * * @property string $raw_input_stream */ -class EA_Input extends CI_Input { +class EA_Input extends CI_Input +{ /** * Fetch an item from JSON data. * @@ -50,38 +51,33 @@ class EA_Input extends CI_Input { * * @return mixed */ - public function json(string $index = NULL, bool $xss_clean = FALSE) + public function json(string $index = null, bool $xss_clean = false) { /** @var EA_Controller $CI */ $CI = &get_instance(); - if (strpos((string)$CI->input->get_request_header('Content-Type'), 'application/json') === false) - { - return NULL; + if (strpos((string) $CI->input->get_request_header('Content-Type'), 'application/json') === false) { + return null; } $input_stream = $CI->input->raw_input_stream; - if (empty($input_stream)) - { + if (empty($input_stream)) { throw new RuntimeException('Cannot get JSON attribute from an empty input stream.'); } - $payload = json_decode($input_stream, TRUE); + $payload = json_decode($input_stream, true); - if ($xss_clean) - { - foreach ($payload as $name => $value) - { + if ($xss_clean) { + foreach ($payload as $name => $value) { $payload[$name] = $CI->security->xss_clean($value); } } - if (empty($index)) - { + if (empty($index)) { return $payload; } - return $payload[$index] ?? NULL; + return $payload[$index] ?? null; } } diff --git a/application/core/EA_Lang.php b/application/core/EA_Lang.php index ac21a3cf6e..0b7b2820ad 100644 --- a/application/core/EA_Lang.php +++ b/application/core/EA_Lang.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Lang extends CI_Lang { - // +class EA_Lang extends CI_Lang +{ + // } diff --git a/application/core/EA_Loader.php b/application/core/EA_Loader.php index 903192f90f..f4f397ff40 100644 --- a/application/core/EA_Loader.php +++ b/application/core/EA_Loader.php @@ -39,7 +39,8 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Loader extends CI_Loader { +class EA_Loader extends CI_Loader +{ /** * Override the original view loader method so that layouts are also supported. * @@ -49,19 +50,26 @@ class EA_Loader extends CI_Loader { * * @return object|string */ - public function view($view, $vars = [], $return = FALSE) + public function view($view, $vars = [], $return = false) { $layout = config('layout'); $is_layout_page = empty($layout); // This is a layout page if "layout" was undefined before the page got rendered. - - $result = $this->_ci_load(['_ci_view' => $view, '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return]); + + $result = $this->_ci_load([ + '_ci_view' => $view, + '_ci_vars' => $this->_ci_prepare_view_vars($vars), + '_ci_return' => $return + ]); $layout = config('layout'); - if ($layout && $is_layout_page) - { - $result = $this->_ci_load(['_ci_view' => $layout['filename'], '_ci_vars' => $this->_ci_prepare_view_vars($vars), '_ci_return' => $return]); + if ($layout && $is_layout_page) { + $result = $this->_ci_load([ + '_ci_view' => $layout['filename'], + '_ci_vars' => $this->_ci_prepare_view_vars($vars), + '_ci_return' => $return + ]); } return $result; diff --git a/application/core/EA_Log.php b/application/core/EA_Log.php index c1668ab23c..814cd40c49 100644 --- a/application/core/EA_Log.php +++ b/application/core/EA_Log.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Log extends CI_Log { - // +class EA_Log extends CI_Log +{ + // } diff --git a/application/core/EA_Migration.php b/application/core/EA_Migration.php index 8782f1f860..b1eee3d9fb 100644 --- a/application/core/EA_Migration.php +++ b/application/core/EA_Migration.php @@ -41,7 +41,8 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Migration extends CI_Migration { +class EA_Migration extends CI_Migration +{ /** * Get the current migration version. * diff --git a/application/core/EA_Model.php b/application/core/EA_Model.php index a877b5fce8..52be38f290 100644 --- a/application/core/EA_Model.php +++ b/application/core/EA_Model.php @@ -39,7 +39,8 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Model extends CI_Model { +class EA_Model extends CI_Model +{ /** * @var array */ @@ -67,8 +68,7 @@ public function __construct() */ public function get_value(string $field, int $record_id): string { - if (method_exists($this, 'value')) - { + if (method_exists($this, 'value')) { return $this->value($field, $record_id); } @@ -88,8 +88,7 @@ public function get_value(string $field, int $record_id): string */ public function get_row(int $record_id): array { - if (method_exists($this, 'find')) - { + if (method_exists($this, 'find')) { return $this->find($record_id); } @@ -106,7 +105,7 @@ public function get_row(int $record_id): array * * @return array Returns an array of records. */ - public function get_batch($where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function get_batch($where = null, int $limit = null, int $offset = null, string $order_by = null): array { return $this->get($where, $limit, $offset, $order_by); } @@ -135,29 +134,26 @@ public function add(array $record): int */ public function cast(array &$record) { - foreach ($this->casts as $attribute => $cast) - { - if ( ! isset($record[$attribute])) - { + foreach ($this->casts as $attribute => $cast) { + if (!isset($record[$attribute])) { continue; } - switch ($cast) - { + switch ($cast) { case 'integer': - $record[$attribute] = (int)$record[$attribute]; + $record[$attribute] = (int) $record[$attribute]; break; case 'float': - $record[$attribute] = (float)$record[$attribute]; + $record[$attribute] = (float) $record[$attribute]; break; case 'boolean': - $record[$attribute] = (bool)$record[$attribute]; + $record[$attribute] = (bool) $record[$attribute]; break; case 'string': - $record[$attribute] = (string)$record[$attribute]; + $record[$attribute] = (string) $record[$attribute]; break; default: @@ -174,14 +170,10 @@ public function cast(array &$record) */ public function only(array &$record, array $fields) { - if (is_assoc($record)) - { + if (is_assoc($record)) { $record = array_fields($record, $fields); - } - else - { - foreach ($record as &$record_item) - { + } else { + foreach ($record as &$record_item) { $record_item = array_fields($record_item, $fields); } } @@ -195,19 +187,13 @@ public function only(array &$record, array $fields) */ public function optional(array &$record, array $fields) { - if (is_assoc($record)) - { - foreach ($fields as $field => $default) - { + if (is_assoc($record)) { + foreach ($fields as $field => $default) { $record[$field] = $record[$field] ?? $default; } - } - else - { - foreach ($record as &$record_item) - { - foreach ($fields as $field => $default) - { + } else { + foreach ($record as &$record_item) { + foreach ($fields as $field => $default) { $record_item[$field] = $record_item[$field] ?? $default; } } @@ -223,6 +209,6 @@ public function optional(array &$record, array $fields) */ public function db_field(string $api_field): ?string { - return $this->api_resource[$api_field] ?? NULL; + return $this->api_resource[$api_field] ?? null; } } diff --git a/application/core/EA_Output.php b/application/core/EA_Output.php index 1707c0842a..57639452dc 100644 --- a/application/core/EA_Output.php +++ b/application/core/EA_Output.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Output extends CI_Output { - // +class EA_Output extends CI_Output +{ + // } diff --git a/application/core/EA_Profiler.php b/application/core/EA_Profiler.php index a1777656ca..2c3a978d89 100644 --- a/application/core/EA_Profiler.php +++ b/application/core/EA_Profiler.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Profiler extends CI_Profiler { - // +class EA_Profiler extends CI_Profiler +{ + // } diff --git a/application/core/EA_Router.php b/application/core/EA_Router.php index ce81d5e17d..b41e21ff09 100644 --- a/application/core/EA_Router.php +++ b/application/core/EA_Router.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Router extends CI_Router { - // +class EA_Router extends CI_Router +{ + // } diff --git a/application/core/EA_Security.php b/application/core/EA_Security.php index 2a54e2aab9..6a36091269 100644 --- a/application/core/EA_Security.php +++ b/application/core/EA_Security.php @@ -39,7 +39,8 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Security extends CI_Security { +class EA_Security extends CI_Security +{ /** * CSRF Verify * @@ -48,47 +49,43 @@ class EA_Security extends CI_Security { public function csrf_verify() { // If it's not a POST request we will set the CSRF cookie - if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST') - { + if (strtoupper($_SERVER['REQUEST_METHOD']) !== 'POST') { return $this->csrf_set_cookie(); } // Check if URI has been whitelisted from CSRF checks - if ($exclude_uris = config_item('csrf_exclude_uris')) - { + if ($exclude_uris = config_item('csrf_exclude_uris')) { $uri = load_class('URI', 'core'); - foreach ($exclude_uris as $excluded) - { - if (preg_match('#^' . $excluded . '$#i' . (UTF8_ENABLED ? 'u' : ''), $uri->uri_string())) - { + foreach ($exclude_uris as $excluded) { + if (preg_match('#^' . $excluded . '$#i' . (UTF8_ENABLED ? 'u' : ''), $uri->uri_string())) { return $this; } } } // Check CSRF token validity, but don't error on mismatch just yet - we'll want to regenerate - $csrf_token = $_POST[$this->_csrf_token_name] ?? $_SERVER['HTTP_X_CSRF'] ?? NULL; + $csrf_token = $_POST[$this->_csrf_token_name] ?? ($_SERVER['HTTP_X_CSRF'] ?? null); - $valid = isset($csrf_token, $_COOKIE[$this->_csrf_cookie_name]) - && is_string($csrf_token) && is_string($_COOKIE[$this->_csrf_cookie_name]) - && hash_equals($csrf_token, $_COOKIE[$this->_csrf_cookie_name]); + $valid = + isset($csrf_token, $_COOKIE[$this->_csrf_cookie_name]) && + is_string($csrf_token) && + is_string($_COOKIE[$this->_csrf_cookie_name]) && + hash_equals($csrf_token, $_COOKIE[$this->_csrf_cookie_name]); // We kill this since we're done and we don't want to pollute the _POST array unset($_POST[$this->_csrf_token_name]); // Regenerate on every submission? - if (config_item('csrf_regenerate')) - { + if (config_item('csrf_regenerate')) { // Nothing should last forever unset($_COOKIE[$this->_csrf_cookie_name]); - $this->_csrf_hash = NULL; + $this->_csrf_hash = null; } $this->_csrf_set_hash(); $this->csrf_set_cookie(); - if ($valid !== TRUE) - { + if ($valid !== true) { $this->csrf_show_error(); } diff --git a/application/core/EA_Session.php b/application/core/EA_Session.php index 43f5601df3..b19756b9bd 100644 --- a/application/core/EA_Session.php +++ b/application/core/EA_Session.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Session extends CI_Session { - // +class EA_Session extends CI_Session +{ + // } diff --git a/application/core/EA_URI.php b/application/core/EA_URI.php index 518ca200c9..83c607cb06 100644 --- a/application/core/EA_URI.php +++ b/application/core/EA_URI.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_URI extends CI_URI { - // +class EA_URI extends CI_URI +{ + // } diff --git a/application/core/EA_Upload.php b/application/core/EA_Upload.php index 6924af6a6c..1663bd953c 100644 --- a/application/core/EA_Upload.php +++ b/application/core/EA_Upload.php @@ -39,6 +39,7 @@ * @property EA_Upload $upload * @property EA_URI $uri */ -class EA_Upload extends CI_Upload { - // +class EA_Upload extends CI_Upload +{ + // } diff --git a/application/helpers/array_helper.php b/application/helpers/array_helper.php index f14f2233f3..433026f63f 100644 --- a/application/helpers/array_helper.php +++ b/application/helpers/array_helper.php @@ -11,8 +11,7 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('is_assoc')) -{ +if (!function_exists('is_assoc')) { /** * Check if an array is an associative array. * @@ -22,17 +21,15 @@ */ function is_assoc(array $array): bool { - if (empty($array)) - { - return FALSE; + if (empty($array)) { + return false; } return array_keys($array) !== range(0, count($array) - 1); } } -if ( ! function_exists('array_find')) -{ +if (!function_exists('array_find')) { /** * Find the first array element based on the provided function. * @@ -43,23 +40,19 @@ function is_assoc(array $array): bool */ function array_find(array $array, callable $callback): mixed { - if (empty($array)) - { - return NULL; + if (empty($array)) { + return null; } - if ( ! is_callable($callback)) - { + if (!is_callable($callback)) { throw new InvalidArgumentException('No filter function provided.'); } - return array_filter($array, $callback)[0] ?? NULL; - + return array_filter($array, $callback)[0] ?? null; } } -if ( ! function_exists('array_fields')) -{ +if (!function_exists('array_fields')) { /** * Keep only the provided fields of an array. * @@ -70,9 +63,12 @@ function array_find(array $array, callable $callback): mixed */ function array_fields(array $array, array $fields): array { - return array_filter($array, function ($field) use ($fields) { - return in_array($field, $fields); - }, ARRAY_FILTER_USE_KEY); + return array_filter( + $array, + function ($field) use ($fields) { + return in_array($field, $fields); + }, + ARRAY_FILTER_USE_KEY + ); } } - diff --git a/application/helpers/asset_helper.php b/application/helpers/asset_helper.php index 8599b56f32..a77fb2a965 100644 --- a/application/helpers/asset_helper.php +++ b/application/helpers/asset_helper.php @@ -22,19 +22,17 @@ * * @return string Returns the final asset URL. */ -function asset_url(string $uri = '', string $protocol = NULL): string +function asset_url(string $uri = '', string $protocol = null): string { $debug = config('debug'); - $cache_busting_token = ! $debug ? '?' . config('cache_busting_token') : ''; + $cache_busting_token = !$debug ? '?' . config('cache_busting_token') : ''; - if (str_contains(basename($uri), '.js') && ! str_contains(basename($uri), '.min.js') && ! $debug) - { + if (str_contains(basename($uri), '.js') && !str_contains(basename($uri), '.min.js') && !$debug) { $uri = str_replace('.js', '.min.js', $uri); } - if (str_contains(basename($uri), '.css') && ! str_contains(basename($uri), '.min.css') && ! $debug) - { + if (str_contains(basename($uri), '.css') && !str_contains(basename($uri), '.min.css') && !$debug) { $uri = str_replace('.css', '.min.css', $uri); } diff --git a/application/helpers/config_helper.php b/application/helpers/config_helper.php index 81414fbc23..be930c30b2 100644 --- a/application/helpers/config_helper.php +++ b/application/helpers/config_helper.php @@ -31,24 +31,21 @@ * * @throws InvalidArgumentException */ -function config(array|string $key, mixed $default = NULL): mixed +function config(array|string $key, mixed $default = null): mixed { /** @var EA_Controller $CI */ $CI = &get_instance(); - if (empty($key)) - { + if (empty($key)) { throw new InvalidArgumentException('The $key argument cannot be empty.'); } - if (is_array($key)) - { - foreach ($key as $item => $value) - { + if (is_array($key)) { + foreach ($key as $item => $value) { $CI->config->set_item($item, $value); } - return NULL; + return null; } $value = $CI->config->item($key); @@ -56,8 +53,7 @@ function config(array|string $key, mixed $default = NULL): mixed return $value ?? $default; } -if ( ! function_exists('script_vars')) -{ +if (!function_exists('script_vars')) { /** * Get / set the specified JS config value. * @@ -78,35 +74,31 @@ function config(array|string $key, mixed $default = NULL): mixed * * @throws InvalidArgumentException */ - function script_vars(array|string $key = NULL, mixed $default = NULL): mixed + function script_vars(array|string $key = null, mixed $default = null): mixed { $script_vars = config('script_vars', []); - if (empty($key)) - { + if (empty($key)) { return $script_vars; } - if (is_array($key)) - { - foreach ($key as $item => $value) - { + if (is_array($key)) { + foreach ($key as $item => $value) { $script_vars[$item] = $value; } config(['script_vars' => $script_vars]); - return NULL; + return null; } - $value = $script_vars[$key] ?? NULL; + $value = $script_vars[$key] ?? null; return $value ?? $default; } } -if ( ! function_exists('html_vars')) -{ +if (!function_exists('html_vars')) { /** * Get / set the specified HTML variable. * @@ -127,35 +119,31 @@ function script_vars(array|string $key = NULL, mixed $default = NULL): mixed * * @throws InvalidArgumentException */ - function html_vars(array|string $key = NULL, mixed $default = NULL): mixed + function html_vars(array|string $key = null, mixed $default = null): mixed { $html_vars = config('html_vars', []); - if (empty($key)) - { + if (empty($key)) { return $html_vars; } - if (is_array($key)) - { - foreach ($key as $item => $value) - { + if (is_array($key)) { + foreach ($key as $item => $value) { $html_vars[$item] = $value; } config(['html_vars' => $html_vars]); - return NULL; + return null; } - $value = $html_vars[$key] ?? NULL; + $value = $html_vars[$key] ?? null; return $value ?? $default; } } -if ( ! function_exists('vars')) -{ +if (!function_exists('vars')) { /** * Get / set the specified HTML & JS config value. * @@ -176,8 +164,8 @@ function html_vars(array|string $key = NULL, mixed $default = NULL): mixed * * @throws InvalidArgumentException */ - function vars(array|string $key = NULL, mixed $default = NULL): mixed + function vars(array|string $key = null, mixed $default = null): mixed { - return html_vars($key) ?? script_vars($key) ?? $default; + return html_vars($key) ?? (script_vars($key) ?? $default); } } diff --git a/application/helpers/date_helper.php b/application/helpers/date_helper.php index 3f3f4b1609..45a56ecf84 100644 --- a/application/helpers/date_helper.php +++ b/application/helpers/date_helper.php @@ -11,8 +11,7 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('get_date_format')) -{ +if (!function_exists('get_date_format')) { /** * Get the date format based on the current settings. * @@ -22,18 +21,16 @@ function get_date_format(): string { $date_format = setting('date_format'); - return match ($date_format) - { + return match ($date_format) { 'DMY' => 'd/m/Y', 'MDY' => 'm/d/Y', 'YMD' => 'Y/m/d', - default => throw new RuntimeException('Invalid date format value: ' . $date_format), + default => throw new RuntimeException('Invalid date format value: ' . $date_format) }; } } -if ( ! function_exists('get_time_format')) -{ +if (!function_exists('get_time_format')) { /** * Get the time format based on the current settings. * @@ -43,17 +40,15 @@ function get_time_format(): string { $time_format = setting('time_format'); - return match ($time_format) - { + return match ($time_format) { 'military' => 'H:i', 'regular' => 'g:i a', - default => throw new RuntimeException('Invalid time format value: ' . $time_format), + default => throw new RuntimeException('Invalid time format value: ' . $time_format) }; } } -if ( ! function_exists('get_date_time_format')) -{ +if (!function_exists('get_date_time_format')) { /** * Get the date-time format based on the current settings. * @@ -65,9 +60,7 @@ function get_date_time_format(): string } } - -if ( ! function_exists('format_date')) -{ +if (!function_exists('format_date')) { /** * Format a date string based on the current app settings. * @@ -79,19 +72,15 @@ function get_date_time_format(): string */ function format_date(DateTimeInterface|string $value): string { - try - { + try { $value_date_time = $value; - if (is_string($value_date_time)) - { + if (is_string($value_date_time)) { $value_date_time = new DateTime($value); } return $value_date_time->format(get_date_format()); - } - catch (Exception $e) - { + } catch (Exception $e) { log_message('error', 'Invalid date provided to the "format_date" helper function: ' . $e->getMessage()); return 'Invalid Date'; @@ -99,8 +88,7 @@ function format_date(DateTimeInterface|string $value): string } } -if ( ! function_exists('format_time')) -{ +if (!function_exists('format_time')) { /** * Format a time string based on the current app settings. * @@ -112,19 +100,15 @@ function format_date(DateTimeInterface|string $value): string */ function format_time(DateTimeInterface|string $value): string { - try - { + try { $value_date_time = $value; - if (is_string($value_date_time)) - { + if (is_string($value_date_time)) { $value_date_time = new DateTime($value); } return $value_date_time->format(get_time_format()); - } - catch (Exception $e) - { + } catch (Exception $e) { log_message('error', 'Invalid date provided to the format_time helper function: ' . $e->getMessage()); return 'Invalid Time'; @@ -132,8 +116,7 @@ function format_time(DateTimeInterface|string $value): string } } -if ( ! function_exists('format_date_time')) -{ +if (!function_exists('format_date_time')) { /** * Format a time string based on the current app settings. * @@ -143,20 +126,15 @@ function format_time(DateTimeInterface|string $value): string */ function format_date_time(DateTimeInterface|string $value): string { - try - { + try { $value_date_time = $value; - if (is_string($value_date_time)) - { - + if (is_string($value_date_time)) { $value_date_time = new DateTime($value); } return $value_date_time->format(get_date_time_format()); - } - catch (Exception $e) - { + } catch (Exception $e) { log_message('error', 'Invalid date provided to the format_date_time helper function: ' . $e->getMessage()); return 'Invalid Date-Time'; @@ -164,8 +142,7 @@ function format_date_time(DateTimeInterface|string $value): string } } -if ( ! function_exists('format_timezone')) -{ +if (!function_exists('format_timezone')) { /** * Format a timezone string based on the current app settings. * @@ -176,12 +153,10 @@ function format_date_time(DateTimeInterface|string $value): string function format_timezone(string $value): string { /** @var EA_Controller $CI */ - $CI =& get_instance(); + $CI = &get_instance(); $CI->load->library('timezones'); return $CI->timezones->get_timezone_name($value); } } - - diff --git a/application/helpers/debug_helper.php b/application/helpers/debug_helper.php index 4f1d248b8e..696be1831d 100644 --- a/application/helpers/debug_helper.php +++ b/application/helpers/debug_helper.php @@ -13,18 +13,18 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('dd')) -{ +if (!function_exists('dd')) { /** * Output the provided variables with "var_dump" and stop the execution. - * + * * Example: - * - * dd($appointment, $service, $provider, $customer); + * + * dd($appointment, $service, $provider, $customer); * * @param mixed ...$vars */ - #[NoReturn] function dd(...$vars): void + #[NoReturn] + function dd(...$vars): void { var_dump($vars); diff --git a/application/helpers/env_helper.php b/application/helpers/env_helper.php index d5984c0a1f..3ae819eb63 100644 --- a/application/helpers/env_helper.php +++ b/application/helpers/env_helper.php @@ -11,8 +11,7 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('env')) -{ +if (!function_exists('env')) { /** * Gets the value of an environment variable. * @@ -20,17 +19,16 @@ * * $debug = env('debug', FALSE); * - * @param string $key Environment key. + * @param string $key Environment key. * @param mixed|null $default Default value in case the requested variable has no value. * * @return mixed * * @throws InvalidArgumentException */ - function env(string $key, mixed $default = NULL): mixed + function env(string $key, mixed $default = null): mixed { - if (empty($key)) - { + if (empty($key)) { throw new InvalidArgumentException('The $key argument cannot be empty.'); } diff --git a/application/helpers/html_helper.php b/application/helpers/html_helper.php index 099064ade0..fe62ddf968 100644 --- a/application/helpers/html_helper.php +++ b/application/helpers/html_helper.php @@ -11,8 +11,7 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('e')) -{ +if (!function_exists('e')) { /** * HTML escape function for templates. * @@ -26,12 +25,11 @@ */ function e(mixed $string): string { - return htmlspecialchars((string)$string, ENT_QUOTES, 'UTF-8'); + return htmlspecialchars((string) $string, ENT_QUOTES, 'UTF-8'); } } -if ( ! function_exists('component')) -{ +if (!function_exists('component')) { /** * Render a component from the "views/components/*.php" directory. * @@ -50,7 +48,7 @@ function e(mixed $string): string * * @return string|object Return the HTML if the $return argument is TRUE or NULL. */ - function component(string $component, array $vars = [], bool $return = FALSE): string|object + function component(string $component, array $vars = [], bool $return = false): string|object { /** @var EA_Controller $CI */ $CI = get_instance(); @@ -59,8 +57,7 @@ function component(string $component, array $vars = [], bool $return = FALSE): s } } -if ( ! function_exists('extend')) -{ +if (!function_exists('extend')) { /** * Use this function at the top of view files to mark the layout you are extending from. * @@ -72,14 +69,13 @@ function extend($layout): void 'layout' => [ 'filename' => $layout, 'sections' => [], - 'tmp' => [], + 'tmp' => [] ] ]); } } -if ( ! function_exists('section')) -{ +if (!function_exists('section')) { /** * Use this function in view files to mark the beginning and/or end of a layout section. * @@ -103,8 +99,7 @@ function section(string $name): void { $layout = config('layout'); - if (array_key_exists($name, $layout['tmp'])) - { + if (array_key_exists($name, $layout['tmp'])) { $layout['sections'][$name][] = ob_get_clean(); unset($layout['tmp'][$name]); @@ -114,8 +109,7 @@ function section(string $name): void return; } - if (empty($layout['sections'][$name])) - { + if (empty($layout['sections'][$name])) { $layout['sections'][$name] = []; } @@ -127,8 +121,7 @@ function section(string $name): void } } -if ( ! function_exists('end_section')) -{ +if (!function_exists('end_section')) { /** * Use this function in view files to mark the end of a layout section. * @@ -152,8 +145,7 @@ function end_section(string $name): void { $layout = config('layout'); - if (array_key_exists($name, $layout['tmp'])) - { + if (array_key_exists($name, $layout['tmp'])) { $layout['sections'][$name][] = ob_get_clean(); unset($layout['tmp'][$name]); @@ -163,8 +155,7 @@ function end_section(string $name): void } } -if ( ! function_exists('slot')) -{ +if (!function_exists('slot')) { /** * Use this function in view files to mark a slot that sections can populate from within child templates. * @@ -174,15 +165,13 @@ function slot(string $name): void { $layout = config('layout'); - $section = $layout['sections'][$name] ?? NULL; + $section = $layout['sections'][$name] ?? null; - if ( ! $section) - { + if (!$section) { return; } - foreach ($section as $content) - { + foreach ($section as $content) { echo $content; } } diff --git a/application/helpers/http_helper.php b/application/helpers/http_helper.php index 3c396e7c6a..b04a37db95 100644 --- a/application/helpers/http_helper.php +++ b/application/helpers/http_helper.php @@ -11,8 +11,7 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('request')) -{ +if (!function_exists('request')) { /** * Gets the value of a request variable. * @@ -27,29 +26,26 @@ * * @throws InvalidArgumentException */ - function request(string $key = NULL, $default = NULL) + function request(string $key = null, $default = null) { /** @var EA_Controller $CI */ $CI = &get_instance(); - if (empty($key)) - { + if (empty($key)) { $payload = $CI->input->post_get($key); - if (empty($payload)) - { + if (empty($payload)) { $payload = $CI->input->json($key); } - + return $payload; } - return $CI->input->post_get($key) ?? $CI->input->json($key) ?? $default; + return $CI->input->post_get($key) ?? ($CI->input->json($key) ?? $default); } } -if ( ! function_exists('response')) -{ +if (!function_exists('response')) { /** * Return a new response from the application. * @@ -66,20 +62,15 @@ function response(string $content = '', int $status = 200, array $headers = []) /** @var EA_Controller $CI */ $CI = &get_instance(); - foreach ($headers as $header) - { + foreach ($headers as $header) { $CI->output->set_header($header); } - $CI - ->output - ->set_status_header($status) - ->set_output($content); + $CI->output->set_status_header($status)->set_output($content); } } -if ( ! function_exists('response')) -{ +if (!function_exists('response')) { /** * Return a new response from the application. * @@ -92,20 +83,15 @@ function response(string $content = '', int $status = 200, array $headers = []) /** @var EA_Controller $CI */ $CI = &get_instance(); - foreach ($headers as $header) - { + foreach ($headers as $header) { $CI->output->set_header($header); } - $CI - ->output - ->set_status_header($status) - ->set_output($content); + $CI->output->set_status_header($status)->set_output($content); } } -if ( ! function_exists('json_response')) -{ +if (!function_exists('json_response')) { /** * Return a new response from the application. * @@ -124,21 +110,18 @@ function json_response(array $content = [], int $status = 200, array $headers = /** @var EA_Controller $CI */ $CI = &get_instance(); - foreach ($headers as $header) - { + foreach ($headers as $header) { $CI->output->set_header($header); } - $CI - ->output + $CI->output ->set_status_header($status) ->set_content_type('application/json') ->set_output(json_encode($content)); } } -if ( ! function_exists('json_exception')) -{ +if (!function_exists('json_exception')) { /** * Return a new json exception from the application. * @@ -150,17 +133,18 @@ function json_response(array $content = [], int $status = 200, array $headers = */ function json_exception(Throwable $e) { - json_response([ - 'success' => FALSE, - 'message' => $e->getMessage(), - 'trace' => config('debug') ? $e->getTrace() : [] - ], 500); + json_response( + [ + 'success' => false, + 'message' => $e->getMessage(), + 'trace' => config('debug') ? $e->getTrace() : [] + ], + 500 + ); } } - -if ( ! function_exists('abort')) -{ +if (!function_exists('abort')) { /** * Throw an HttpException with the given data. * @@ -179,8 +163,7 @@ function abort(int $code, string $message = '', array $headers = []) /** @var EA_Controller $CI */ $CI = &get_instance(); - foreach ($headers as $header) - { + foreach ($headers as $header) { $CI->output->set_header($header); } diff --git a/application/helpers/installation_helper.php b/application/helpers/installation_helper.php index 535593a86a..0c4581fec3 100644 --- a/application/helpers/installation_helper.php +++ b/application/helpers/installation_helper.php @@ -23,7 +23,7 @@ */ function is_app_installed(): bool { - $CI =& get_instance(); + $CI = &get_instance(); return $CI->db->table_exists('users'); } diff --git a/application/helpers/language_helper.php b/application/helpers/language_helper.php index c79fa811a6..4cb3fbdb8f 100644 --- a/application/helpers/language_helper.php +++ b/application/helpers/language_helper.php @@ -11,9 +11,7 @@ * @since v1.1.0 * ---------------------------------------------------------------------------- */ - -if ( ! function_exists('lang')) -{ +if (!function_exists('lang')) { /** * Lang * @@ -32,8 +30,7 @@ function lang(string $line, string $for = '', array $attributes = []): string $result = $CI->lang->line($line); - if ($for !== '') - { + if ($for !== '') { $result = ''; } diff --git a/application/helpers/password_helper.php b/application/helpers/password_helper.php index 7dbe470758..3e75be0e15 100644 --- a/application/helpers/password_helper.php +++ b/application/helpers/password_helper.php @@ -27,17 +27,15 @@ */ function hash_password(string $salt, string $password): string { - if (strlen($password) > MAX_PASSWORD_LENGTH) - { + if (strlen($password) > MAX_PASSWORD_LENGTH) { throw new InvalidArgumentException('The provided password is too long, please use a shorter value.'); } - $half = (int)(strlen($salt) / 2); + $half = (int) (strlen($salt) / 2); $hash = hash('sha256', substr($salt, 0, $half) . $password . substr($salt, $half)); - for ($i = 0; $i < 100000; $i++) - { + for ($i = 0; $i < 100000; $i++) { $hash = hash('sha256', $hash); } @@ -56,7 +54,7 @@ function generate_salt(): string { $max_length = 100; - $salt = hash('sha256', (uniqid(rand(), TRUE))); + $salt = hash('sha256', uniqid(rand(), true)); return substr($salt, 0, $max_length); } diff --git a/application/helpers/path_helper.php b/application/helpers/path_helper.php index 6af1736962..32bdb1c023 100644 --- a/application/helpers/path_helper.php +++ b/application/helpers/path_helper.php @@ -11,8 +11,7 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('storage_path')) -{ +if (!function_exists('storage_path')) { /** * Get the path to the storage folder. * @@ -30,8 +29,7 @@ function storage_path(string $path = ''): string } } -if ( ! function_exists('base_path')) -{ +if (!function_exists('base_path')) { /** * Get the path to the base of the current installation. * @@ -46,4 +44,3 @@ function base_path(string $path = ''): string return FCPATH . trim($path); } } - diff --git a/application/helpers/permission_helper.php b/application/helpers/permission_helper.php index 9feebca09e..11a954061f 100644 --- a/application/helpers/permission_helper.php +++ b/application/helpers/permission_helper.php @@ -11,8 +11,7 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('can')) -{ +if (!function_exists('can')) { /** * Check if the currently logged-in user can perform an action * @@ -26,7 +25,7 @@ * * @return bool */ - function can(string $action, string $resource, int $user_id = NULL): bool + function can(string $action, string $resource, int $user_id = null): bool { /** @var EA_Controller $CI */ $CI = &get_instance(); @@ -34,30 +33,25 @@ function can(string $action, string $resource, int $user_id = NULL): bool $CI->load->model('roles_model'); $CI->load->model('users_model'); - if (empty($user_id)) - { + if (empty($user_id)) { $role_slug = session('role_slug'); - } - else - { + } else { $user = $CI->users_model->find($user_id); $role_slug = $CI->roles_model->value($user['id_roles'], 'slug'); } - if (empty($role_slug)) - { - return FALSE; + if (empty($role_slug)) { + return false; } $permissions = $CI->roles_model->get_permissions_by_slug($role_slug); - return $permissions[$resource][$action] ?? FALSE; + return $permissions[$resource][$action] ?? false; } } -if ( ! function_exists('cannot')) -{ +if (!function_exists('cannot')) { /** * Check if the currently logged-in user can perform an action * @@ -71,8 +65,8 @@ function can(string $action, string $resource, int $user_id = NULL): bool * * @return bool */ - function cannot(string $action, string $resource, int $user_id = NULL): bool + function cannot(string $action, string $resource, int $user_id = null): bool { - return ! can($action, $resource, $user_id); + return !can($action, $resource, $user_id); } } diff --git a/application/helpers/rate_limit_helper.php b/application/helpers/rate_limit_helper.php index 271b58ae73..1086f4e4ac 100644 --- a/application/helpers/rate_limit_helper.php +++ b/application/helpers/rate_limit_helper.php @@ -11,8 +11,7 @@ * @since v1.1.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('rate_limit')) -{ +if (!function_exists('rate_limit')) { /** * Rate-limit the application requests. * @@ -29,12 +28,11 @@ function rate_limit(string $ip, int $max_requests = 100, int $duration = 120): void { /** @var EA_Controller $CI */ - $CI =& get_instance(); + $CI = &get_instance(); $rate_limiting = $CI->config->item('rate_limiting'); - if ( ! $rate_limiting || is_cli()) - { + if (!$rate_limiting || is_cli()) { return; } @@ -46,39 +44,35 @@ function rate_limit(string $ip, int $max_requests = 100, int $duration = 120): v $current_time = date('Y-m-d H:i:s'); - if ($CI->cache->get($cache_key) === FALSE) // First request - { + if ($CI->cache->get($cache_key) === false) { + // First request $current_time_plus = date('Y-m-d H:i:s', strtotime('+' . $duration . ' seconds')); $CI->cache->save($cache_key, 1, $duration); $CI->cache->save($cache_remain_time_key, $current_time_plus, $duration * 2); } - else // Consequent request - { + // Consequent request + else { $requests = $CI->cache->get($cache_key); $time_lost = $CI->cache->get($cache_remain_time_key); - if ($current_time > $time_lost) - { + if ($current_time > $time_lost) { $current_time_plus = date('Y-m-d H:i:s', strtotime('+' . $duration . ' seconds')); $CI->cache->save($cache_key, 1, $duration); $CI->cache->save($cache_remain_time_key, $current_time_plus, $duration * 2); - } - else - { + } else { $CI->cache->save($cache_key, $requests + 1, $duration); } $requests = $CI->cache->get($cache_key); - if ($requests > $max_requests) - { + if ($requests > $max_requests) { header('HTTP/1.0 429 Too Many Requests'); - exit; + exit(); } } } diff --git a/application/helpers/routes_helper.php b/application/helpers/routes_helper.php index 3554e9f543..e653908753 100644 --- a/application/helpers/routes_helper.php +++ b/application/helpers/routes_helper.php @@ -11,8 +11,7 @@ * @since v1.3.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('route_api_resource')) -{ +if (!function_exists('route_api_resource')) { /** * Define a route for an API resource (includes index, store, update and delete callbacks). * @@ -30,20 +29,19 @@ function route_api_resource(array &$route, string $resource, string $prefix = '' } } -if ( ! function_exists('is_callback')) -{ +if (!function_exists('is_callback')) { /** * Check whether the current request matches the provided controller/method callback. * - * @param string $class Controller class name. + * @param string $class Controller class name. * @param string $method Controller method name. - * + * * @return bool */ function is_callback(string $class, string $method): bool { /** @var EA_Controller $CI */ - $CI =& get_instance(); + $CI = &get_instance(); return $CI->router->class === $class && $CI->router->method === $method; } diff --git a/application/helpers/session_helper.php b/application/helpers/session_helper.php index 0af7cf79ca..79f3f37b59 100644 --- a/application/helpers/session_helper.php +++ b/application/helpers/session_helper.php @@ -11,8 +11,7 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('session')) -{ +if (!function_exists('session')) { /** * Get / set the specified session value. * @@ -26,31 +25,28 @@ * * session(['logged_in' => FALSE]); * - * @param array|string|null $key Session item key. + * @param array|string|null $key Session item key. * @param mixed|null $default Default value in case the requested session item has no value. * * @return mixed|NULL Returns the requested value or NULL if you assign a new session value. * * @throws InvalidArgumentException */ - function session(array|string $key = NULL, mixed $default = NULL): mixed + function session(array|string $key = null, mixed $default = null): mixed { /** @var EA_Controller $CI */ $CI = &get_instance(); - if (empty($key)) - { + if (empty($key)) { throw new InvalidArgumentException('The $key argument cannot be empty.'); } - if (is_array($key)) - { - foreach ($key as $item => $value) - { + if (is_array($key)) { + foreach ($key as $item => $value) { $CI->session->set_userdata($item, $value); } - return NULL; + return null; } $value = $CI->session->userdata($key); diff --git a/application/helpers/setting_helper.php b/application/helpers/setting_helper.php index e1332bddb4..0f4efb2862 100644 --- a/application/helpers/setting_helper.php +++ b/application/helpers/setting_helper.php @@ -11,8 +11,7 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -if ( ! function_exists('setting')) -{ +if (!function_exists('setting')) { /** * Get / set the specified setting value. * @@ -33,28 +32,28 @@ * * @throws InvalidArgumentException */ - function setting(array|string $key = NULL, mixed $default = NULL): mixed + function setting(array|string $key = null, mixed $default = null): mixed { /** @var EA_Controller $CI */ $CI = &get_instance(); $CI->load->model('settings_model'); - if (empty($key)) - { + if (empty($key)) { throw new InvalidArgumentException('The $key argument cannot be empty.'); } - if (is_array($key)) - { - foreach ($key as $name => $value) - { - $setting = $CI->settings_model->query()->where('name', $name)->get()->row_array(); + if (is_array($key)) { + foreach ($key as $name => $value) { + $setting = $CI->settings_model + ->query() + ->where('name', $name) + ->get() + ->row_array(); - if (empty($setting)) - { + if (empty($setting)) { $setting = [ - 'name' => $name, + 'name' => $name ]; } @@ -63,10 +62,14 @@ function setting(array|string $key = NULL, mixed $default = NULL): mixed $CI->settings_model->save($setting); } - return NULL; + return null; } - $setting = $CI->settings_model->query()->where('name', $key)->get()->row_array(); + $setting = $CI->settings_model + ->query() + ->where('name', $key) + ->get() + ->row_array(); return $setting['value'] ?? $default; } diff --git a/application/helpers/validation_helper.php b/application/helpers/validation_helper.php index f8823fd1a6..34e32be463 100644 --- a/application/helpers/validation_helper.php +++ b/application/helpers/validation_helper.php @@ -22,5 +22,5 @@ function validate_datetime(string $value): bool { $date_time = DateTime::createFromFormat('Y-m-d H:i:s', $value); - return (bool)$date_time; + return (bool) $date_time; } diff --git a/application/index.html b/application/index.html index c942a79ce6..423d9d580e 100644 --- a/application/index.html +++ b/application/index.html @@ -1,10 +1,10 @@ - 403 Forbidden + 403 Forbidden

Directory access is forbidden.

- \ No newline at end of file + diff --git a/application/language/arabic/calendar_lang.php b/application/language/arabic/calendar_lang.php index ce838142e0..a60659fa6f 100644 --- a/application/language/arabic/calendar_lang.php +++ b/application/language/arabic/calendar_lang.php @@ -26,16 +26,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) - * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 1.0.0 + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ -defined('BASEPATH') OR exit('No direct script access allowed'); +defined('BASEPATH') or exit('No direct script access allowed'); $lang['cal_su'] = 'Su'; $lang['cal_mo'] = 'Mo'; diff --git a/application/language/arabic/date_lang.php b/application/language/arabic/date_lang.php index aa796b89f7..45de955173 100644 --- a/application/language/arabic/date_lang.php +++ b/application/language/arabic/date_lang.php @@ -26,16 +26,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) - * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 1.0.0 + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ -defined('BASEPATH') OR exit('No direct script access allowed'); +defined('BASEPATH') or exit('No direct script access allowed'); $lang['date_year'] = 'Year'; $lang['date_years'] = 'Years'; @@ -52,43 +52,43 @@ $lang['date_second'] = 'Second'; $lang['date_seconds'] = 'Seconds'; -$lang['UM12'] = '(UTC -12:00) Baker/Howland Island'; -$lang['UM11'] = '(UTC -11:00) Niue'; -$lang['UM10'] = '(UTC -10:00) Hawaii-Aleutian Standard Time, Cook Islands, Tahiti'; -$lang['UM95'] = '(UTC -9:30) Marquesas Islands'; -$lang['UM9'] = '(UTC -9:00) Alaska Standard Time, Gambier Islands'; -$lang['UM8'] = '(UTC -8:00) Pacific Standard Time, Clipperton Island'; -$lang['UM7'] = '(UTC -7:00) Mountain Standard Time'; -$lang['UM6'] = '(UTC -6:00) Central Standard Time'; -$lang['UM5'] = '(UTC -5:00) Eastern Standard Time, Western Caribbean Standard Time'; -$lang['UM45'] = '(UTC -4:30) Venezuelan Standard Time'; -$lang['UM4'] = '(UTC -4:00) Atlantic Standard Time, Eastern Caribbean Standard Time'; -$lang['UM35'] = '(UTC -3:30) Newfoundland Standard Time'; -$lang['UM3'] = '(UTC -3:00) Argentina, Brazil, French Guiana, Uruguay'; -$lang['UM2'] = '(UTC -2:00) South Georgia/South Sandwich Islands'; -$lang['UM1'] = '(UTC -1:00) Azores, Cape Verde Islands'; -$lang['UTC'] = '(UTC) Greenwich Mean Time, Western European Time'; -$lang['UP1'] = '(UTC +1:00) Central European Time, West Africa Time'; -$lang['UP2'] = '(UTC +2:00) Central Africa Time, Eastern European Time, Kaliningrad Time'; -$lang['UP3'] = '(UTC +3:00) Moscow Time, East Africa Time, Arabia Standard Time'; -$lang['UP35'] = '(UTC +3:30) Iran Standard Time'; -$lang['UP4'] = '(UTC +4:00) Azerbaijan Standard Time, Samara Time'; -$lang['UP45'] = '(UTC +4:30) Afghanistan'; -$lang['UP5'] = '(UTC +5:00) Pakistan Standard Time, Yekaterinburg Time'; -$lang['UP55'] = '(UTC +5:30) Indian Standard Time, Sri Lanka Time'; -$lang['UP575'] = '(UTC +5:45) Nepal Time'; -$lang['UP6'] = '(UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time'; -$lang['UP65'] = '(UTC +6:30) Cocos Islands, Myanmar'; -$lang['UP7'] = '(UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam'; -$lang['UP8'] = '(UTC +8:00) Australian Western Standard Time, Beijing Time, Irkutsk Time'; -$lang['UP875'] = '(UTC +8:45) Australian Central Western Standard Time'; -$lang['UP9'] = '(UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk Time'; -$lang['UP95'] = '(UTC +9:30) Australian Central Standard Time'; -$lang['UP10'] = '(UTC +10:00) Australian Eastern Standard Time, Vladivostok Time'; -$lang['UP105'] = '(UTC +10:30) Lord Howe Island'; -$lang['UP11'] = '(UTC +11:00) Srednekolymsk Time, Solomon Islands, Vanuatu'; -$lang['UP115'] = '(UTC +11:30) Norfolk Island'; -$lang['UP12'] = '(UTC +12:00) Fiji, Gilbert Islands, Kamchatka Time, New Zealand Standard Time'; -$lang['UP1275'] = '(UTC +12:45) Chatham Islands Standard Time'; -$lang['UP13'] = '(UTC +13:00) Samoa Time Zone, Phoenix Islands Time, Tonga'; -$lang['UP14'] = '(UTC +14:00) Line Islands'; +$lang['UM12'] = '(UTC -12:00) Baker/Howland Island'; +$lang['UM11'] = '(UTC -11:00) Niue'; +$lang['UM10'] = '(UTC -10:00) Hawaii-Aleutian Standard Time, Cook Islands, Tahiti'; +$lang['UM95'] = '(UTC -9:30) Marquesas Islands'; +$lang['UM9'] = '(UTC -9:00) Alaska Standard Time, Gambier Islands'; +$lang['UM8'] = '(UTC -8:00) Pacific Standard Time, Clipperton Island'; +$lang['UM7'] = '(UTC -7:00) Mountain Standard Time'; +$lang['UM6'] = '(UTC -6:00) Central Standard Time'; +$lang['UM5'] = '(UTC -5:00) Eastern Standard Time, Western Caribbean Standard Time'; +$lang['UM45'] = '(UTC -4:30) Venezuelan Standard Time'; +$lang['UM4'] = '(UTC -4:00) Atlantic Standard Time, Eastern Caribbean Standard Time'; +$lang['UM35'] = '(UTC -3:30) Newfoundland Standard Time'; +$lang['UM3'] = '(UTC -3:00) Argentina, Brazil, French Guiana, Uruguay'; +$lang['UM2'] = '(UTC -2:00) South Georgia/South Sandwich Islands'; +$lang['UM1'] = '(UTC -1:00) Azores, Cape Verde Islands'; +$lang['UTC'] = '(UTC) Greenwich Mean Time, Western European Time'; +$lang['UP1'] = '(UTC +1:00) Central European Time, West Africa Time'; +$lang['UP2'] = '(UTC +2:00) Central Africa Time, Eastern European Time, Kaliningrad Time'; +$lang['UP3'] = '(UTC +3:00) Moscow Time, East Africa Time, Arabia Standard Time'; +$lang['UP35'] = '(UTC +3:30) Iran Standard Time'; +$lang['UP4'] = '(UTC +4:00) Azerbaijan Standard Time, Samara Time'; +$lang['UP45'] = '(UTC +4:30) Afghanistan'; +$lang['UP5'] = '(UTC +5:00) Pakistan Standard Time, Yekaterinburg Time'; +$lang['UP55'] = '(UTC +5:30) Indian Standard Time, Sri Lanka Time'; +$lang['UP575'] = '(UTC +5:45) Nepal Time'; +$lang['UP6'] = '(UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time'; +$lang['UP65'] = '(UTC +6:30) Cocos Islands, Myanmar'; +$lang['UP7'] = '(UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam'; +$lang['UP8'] = '(UTC +8:00) Australian Western Standard Time, Beijing Time, Irkutsk Time'; +$lang['UP875'] = '(UTC +8:45) Australian Central Western Standard Time'; +$lang['UP9'] = '(UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk Time'; +$lang['UP95'] = '(UTC +9:30) Australian Central Standard Time'; +$lang['UP10'] = '(UTC +10:00) Australian Eastern Standard Time, Vladivostok Time'; +$lang['UP105'] = '(UTC +10:30) Lord Howe Island'; +$lang['UP11'] = '(UTC +11:00) Srednekolymsk Time, Solomon Islands, Vanuatu'; +$lang['UP115'] = '(UTC +11:30) Norfolk Island'; +$lang['UP12'] = '(UTC +12:00) Fiji, Gilbert Islands, Kamchatka Time, New Zealand Standard Time'; +$lang['UP1275'] = '(UTC +12:45) Chatham Islands Standard Time'; +$lang['UP13'] = '(UTC +13:00) Samoa Time Zone, Phoenix Islands Time, Tonga'; +$lang['UP14'] = '(UTC +14:00) Line Islands'; diff --git a/application/language/arabic/email_lang.php b/application/language/arabic/email_lang.php index 3229327e2a..a0d3fb3a0b 100644 --- a/application/language/arabic/email_lang.php +++ b/application/language/arabic/email_lang.php @@ -15,9 +15,12 @@ $lang['email_attachment_unreadable'] = 'غير قاد على فتح الملف المرفق: %s'; $lang['email_no_from'] = 'لا يمكن إرسال البريد الإلكتروني بدون تحديد المرسل.'; $lang['email_no_recipients'] = 'يجب إضافة مستقبلين: To, Cc, or Bcc'; -$lang['email_send_failure_phpmail'] = 'غير قادر على الإرسال باستخدام PHP mail(). قد يكون الخادم غير معد للإرسال باستخدام هذه الطريقة.'; -$lang['email_send_failure_sendmail'] = 'غير قادر على الإرسال باستخدام PHP Sendmail. قد يكون الخادم غير معد للإرسال باستخدام هذه الطريقة.'; -$lang['email_send_failure_smtp'] = 'غير قادر على الإرسال باستخدام PHP SMTP. قد يكون الخادم غير معد للإرسال باستخدام هذه الطريقة.'; +$lang['email_send_failure_phpmail'] = + 'غير قادر على الإرسال باستخدام PHP mail(). قد يكون الخادم غير معد للإرسال باستخدام هذه الطريقة.'; +$lang['email_send_failure_sendmail'] = + 'غير قادر على الإرسال باستخدام PHP Sendmail. قد يكون الخادم غير معد للإرسال باستخدام هذه الطريقة.'; +$lang['email_send_failure_smtp'] = + 'غير قادر على الإرسال باستخدام PHP SMTP. قد يكون الخادم غير معد للإرسال باستخدام هذه الطريقة.'; $lang['email_sent'] = 'تم إرسال الرسالة بنجاح باستخدام البروتوكول التالي: %s'; $lang['email_no_socket'] = 'غير قادر على فتح إتصال مع Sendmail. الرجاء التأكد من الإعدادات.'; $lang['email_no_hostname'] = 'لم تحدد إسم المضيف لـ SMTP.'; diff --git a/application/language/arabic/form_validation_lang.php b/application/language/arabic/form_validation_lang.php index bdb0254429..af5c0948b1 100644 --- a/application/language/arabic/form_validation_lang.php +++ b/application/language/arabic/form_validation_lang.php @@ -26,44 +26,49 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) - * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 1.0.0 + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ -defined('BASEPATH') OR exit('No direct script access allowed'); +defined('BASEPATH') or exit('No direct script access allowed'); -$lang['form_validation_required'] = 'The {field} field is required.'; -$lang['form_validation_isset'] = 'The {field} field must have a value.'; -$lang['form_validation_valid_email'] = 'The {field} field must contain a valid email address.'; -$lang['form_validation_valid_emails'] = 'The {field} field must contain all valid email addresses.'; -$lang['form_validation_valid_url'] = 'The {field} field must contain a valid URL.'; -$lang['form_validation_valid_ip'] = 'The {field} field must contain a valid IP.'; -$lang['form_validation_valid_base64'] = 'The {field} field must contain a valid Base64 string.'; -$lang['form_validation_min_length'] = 'The {field} field must be at least {param} characters in length.'; -$lang['form_validation_max_length'] = 'The {field} field cannot exceed {param} characters in length.'; -$lang['form_validation_exact_length'] = 'The {field} field must be exactly {param} characters in length.'; -$lang['form_validation_alpha'] = 'The {field} field may only contain alphabetical characters.'; -$lang['form_validation_alpha_numeric'] = 'The {field} field may only contain alpha-numeric characters.'; -$lang['form_validation_alpha_numeric_spaces'] = 'The {field} field may only contain alpha-numeric characters and spaces.'; -$lang['form_validation_alpha_dash'] = 'The {field} field may only contain alpha-numeric characters, underscores, and dashes.'; -$lang['form_validation_numeric'] = 'The {field} field must contain only numbers.'; -$lang['form_validation_is_numeric'] = 'The {field} field must contain only numeric characters.'; -$lang['form_validation_integer'] = 'The {field} field must contain an integer.'; -$lang['form_validation_regex_match'] = 'The {field} field is not in the correct format.'; -$lang['form_validation_matches'] = 'The {field} field does not match the {param} field.'; -$lang['form_validation_differs'] = 'The {field} field must differ from the {param} field.'; -$lang['form_validation_is_unique'] = 'The {field} field must contain a unique value.'; -$lang['form_validation_is_natural'] = 'The {field} field must only contain digits.'; -$lang['form_validation_is_natural_no_zero'] = 'The {field} field must only contain digits and must be greater than zero.'; -$lang['form_validation_decimal'] = 'The {field} field must contain a decimal number.'; -$lang['form_validation_less_than'] = 'The {field} field must contain a number less than {param}.'; -$lang['form_validation_less_than_equal_to'] = 'The {field} field must contain a number less than or equal to {param}.'; -$lang['form_validation_greater_than'] = 'The {field} field must contain a number greater than {param}.'; -$lang['form_validation_greater_than_equal_to'] = 'The {field} field must contain a number greater than or equal to {param}.'; -$lang['form_validation_error_message_not_set'] = 'Unable to access an error message corresponding to your field name {field}.'; -$lang['form_validation_in_list'] = 'The {field} field must be one of: {param}.'; +$lang['form_validation_required'] = 'The {field} field is required.'; +$lang['form_validation_isset'] = 'The {field} field must have a value.'; +$lang['form_validation_valid_email'] = 'The {field} field must contain a valid email address.'; +$lang['form_validation_valid_emails'] = 'The {field} field must contain all valid email addresses.'; +$lang['form_validation_valid_url'] = 'The {field} field must contain a valid URL.'; +$lang['form_validation_valid_ip'] = 'The {field} field must contain a valid IP.'; +$lang['form_validation_valid_base64'] = 'The {field} field must contain a valid Base64 string.'; +$lang['form_validation_min_length'] = 'The {field} field must be at least {param} characters in length.'; +$lang['form_validation_max_length'] = 'The {field} field cannot exceed {param} characters in length.'; +$lang['form_validation_exact_length'] = 'The {field} field must be exactly {param} characters in length.'; +$lang['form_validation_alpha'] = 'The {field} field may only contain alphabetical characters.'; +$lang['form_validation_alpha_numeric'] = 'The {field} field may only contain alpha-numeric characters.'; +$lang['form_validation_alpha_numeric_spaces'] = + 'The {field} field may only contain alpha-numeric characters and spaces.'; +$lang['form_validation_alpha_dash'] = + 'The {field} field may only contain alpha-numeric characters, underscores, and dashes.'; +$lang['form_validation_numeric'] = 'The {field} field must contain only numbers.'; +$lang['form_validation_is_numeric'] = 'The {field} field must contain only numeric characters.'; +$lang['form_validation_integer'] = 'The {field} field must contain an integer.'; +$lang['form_validation_regex_match'] = 'The {field} field is not in the correct format.'; +$lang['form_validation_matches'] = 'The {field} field does not match the {param} field.'; +$lang['form_validation_differs'] = 'The {field} field must differ from the {param} field.'; +$lang['form_validation_is_unique'] = 'The {field} field must contain a unique value.'; +$lang['form_validation_is_natural'] = 'The {field} field must only contain digits.'; +$lang['form_validation_is_natural_no_zero'] = + 'The {field} field must only contain digits and must be greater than zero.'; +$lang['form_validation_decimal'] = 'The {field} field must contain a decimal number.'; +$lang['form_validation_less_than'] = 'The {field} field must contain a number less than {param}.'; +$lang['form_validation_less_than_equal_to'] = 'The {field} field must contain a number less than or equal to {param}.'; +$lang['form_validation_greater_than'] = 'The {field} field must contain a number greater than {param}.'; +$lang['form_validation_greater_than_equal_to'] = + 'The {field} field must contain a number greater than or equal to {param}.'; +$lang['form_validation_error_message_not_set'] = + 'Unable to access an error message corresponding to your field name {field}.'; +$lang['form_validation_in_list'] = 'The {field} field must be one of: {param}.'; diff --git a/application/language/arabic/ftp_lang.php b/application/language/arabic/ftp_lang.php index 70f5b086d0..2401f16927 100644 --- a/application/language/arabic/ftp_lang.php +++ b/application/language/arabic/ftp_lang.php @@ -26,26 +26,27 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) - * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 1.0.0 + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ -defined('BASEPATH') OR exit('No direct script access allowed'); +defined('BASEPATH') or exit('No direct script access allowed'); -$lang['ftp_no_connection'] = 'Unable to locate a valid connection ID. Please make sure you are connected before performing any file routines.'; -$lang['ftp_unable_to_connect'] = 'Unable to connect to your FTP server using the supplied hostname.'; -$lang['ftp_unable_to_login'] = 'Unable to login to your FTP server. Please check your username and password.'; -$lang['ftp_unable_to_mkdir'] = 'Unable to create the directory you have specified.'; -$lang['ftp_unable_to_changedir'] = 'Unable to change directories.'; -$lang['ftp_unable_to_chmod'] = 'Unable to set file permissions. Please check your path.'; -$lang['ftp_unable_to_upload'] = 'Unable to upload the specified file. Please check your path.'; -$lang['ftp_unable_to_download'] = 'Unable to download the specified file. Please check your path.'; -$lang['ftp_no_source_file'] = 'Unable to locate the source file. Please check your path.'; -$lang['ftp_unable_to_rename'] = 'Unable to rename the file.'; -$lang['ftp_unable_to_delete'] = 'Unable to delete the file.'; -$lang['ftp_unable_to_move'] = 'Unable to move the file. Please make sure the destination directory exists.'; +$lang['ftp_no_connection'] = + 'Unable to locate a valid connection ID. Please make sure you are connected before performing any file routines.'; +$lang['ftp_unable_to_connect'] = 'Unable to connect to your FTP server using the supplied hostname.'; +$lang['ftp_unable_to_login'] = 'Unable to login to your FTP server. Please check your username and password.'; +$lang['ftp_unable_to_mkdir'] = 'Unable to create the directory you have specified.'; +$lang['ftp_unable_to_changedir'] = 'Unable to change directories.'; +$lang['ftp_unable_to_chmod'] = 'Unable to set file permissions. Please check your path.'; +$lang['ftp_unable_to_upload'] = 'Unable to upload the specified file. Please check your path.'; +$lang['ftp_unable_to_download'] = 'Unable to download the specified file. Please check your path.'; +$lang['ftp_no_source_file'] = 'Unable to locate the source file. Please check your path.'; +$lang['ftp_unable_to_rename'] = 'Unable to rename the file.'; +$lang['ftp_unable_to_delete'] = 'Unable to delete the file.'; +$lang['ftp_unable_to_move'] = 'Unable to move the file. Please make sure the destination directory exists.'; diff --git a/application/language/arabic/imglib_lang.php b/application/language/arabic/imglib_lang.php index c34b087c7f..aab35787d5 100644 --- a/application/language/arabic/imglib_lang.php +++ b/application/language/arabic/imglib_lang.php @@ -26,29 +26,36 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) - * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 1.0.0 + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ -defined('BASEPATH') OR exit('No direct script access allowed'); +defined('BASEPATH') or exit('No direct script access allowed'); $lang['imglib_source_image_required'] = 'You must specify a source image in your preferences.'; $lang['imglib_gd_required'] = 'The GD image library is required for this feature.'; -$lang['imglib_gd_required_for_props'] = 'Your server must support the GD image library in order to determine the image properties.'; -$lang['imglib_unsupported_imagecreate'] = 'Your server does not support the GD function required to process this type of image.'; -$lang['imglib_gif_not_supported'] = 'GIF images are often not supported due to licensing restrictions. You may have to use JPG or PNG images instead.'; +$lang['imglib_gd_required_for_props'] = + 'Your server must support the GD image library in order to determine the image properties.'; +$lang['imglib_unsupported_imagecreate'] = + 'Your server does not support the GD function required to process this type of image.'; +$lang['imglib_gif_not_supported'] = + 'GIF images are often not supported due to licensing restrictions. You may have to use JPG or PNG images instead.'; $lang['imglib_jpg_not_supported'] = 'JPG images are not supported.'; $lang['imglib_png_not_supported'] = 'PNG images are not supported.'; -$lang['imglib_jpg_or_png_required'] = 'The image resize protocol specified in your preferences only works with JPEG or PNG image types.'; -$lang['imglib_copy_error'] = 'An error was encountered while attempting to replace the file. Please make sure your file directory is writable.'; +$lang['imglib_jpg_or_png_required'] = + 'The image resize protocol specified in your preferences only works with JPEG or PNG image types.'; +$lang['imglib_copy_error'] = + 'An error was encountered while attempting to replace the file. Please make sure your file directory is writable.'; $lang['imglib_rotate_unsupported'] = 'Image rotation does not appear to be supported by your server.'; -$lang['imglib_libpath_invalid'] = 'The path to your image library is not correct. Please set the correct path in your image preferences.'; -$lang['imglib_image_process_failed'] = 'Image processing failed. Please verify that your server supports the chosen protocol and that the path to your image library is correct.'; +$lang['imglib_libpath_invalid'] = + 'The path to your image library is not correct. Please set the correct path in your image preferences.'; +$lang['imglib_image_process_failed'] = + 'Image processing failed. Please verify that your server supports the chosen protocol and that the path to your image library is correct.'; $lang['imglib_rotation_angle_required'] = 'An angle of rotation is required to rotate the image.'; $lang['imglib_invalid_path'] = 'The path to the image is not correct.'; $lang['imglib_invalid_image'] = 'The provided image is not valid.'; diff --git a/application/language/arabic/migration_lang.php b/application/language/arabic/migration_lang.php index 4deda43ad1..cb5161aed1 100644 --- a/application/language/arabic/migration_lang.php +++ b/application/language/arabic/migration_lang.php @@ -9,10 +9,10 @@ */ defined('BASEPATH') or exit('No direct script access allowed'); -$lang['migration_none_found'] = "لا يوجد أي عمليات ترحيل."; -$lang['migration_not_found'] = "تعذر العثور على عملية الترحيل هذه."; +$lang['migration_none_found'] = 'لا يوجد أي عمليات ترحيل.'; +$lang['migration_not_found'] = 'تعذر العثور على عملية الترحيل هذه.'; $lang['migration_sequence_gap'] = 'هناك فجوة بين تسلسل عمليات الترحيل عند الرقم : %s.'; -$lang['migration_multiple_version'] = "هناك عدة عمليات ترحيل لها نفس التعداد: %d."; +$lang['migration_multiple_version'] = 'هناك عدة عمليات ترحيل لها نفس التعداد: %d.'; $lang['migration_class_doesnt_exist'] = "تعذر العثور على صنف الترحيل \"%s\"."; $lang['migration_missing_up_method'] = "صنف الترحيل \"%s\" يفتقد إلى دالة 'up'."; $lang['migration_missing_down_method'] = "صنف الترحيل \"%s\" يفتقد إلى دالة 'down'."; diff --git a/application/language/arabic/number_lang.php b/application/language/arabic/number_lang.php index f1e50bd159..af3d06d1b6 100644 --- a/application/language/arabic/number_lang.php +++ b/application/language/arabic/number_lang.php @@ -26,16 +26,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) - * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 1.0.0 + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ -defined('BASEPATH') OR exit('No direct script access allowed'); +defined('BASEPATH') or exit('No direct script access allowed'); $lang['terabyte_abbr'] = 'TB'; $lang['gigabyte_abbr'] = 'GB'; diff --git a/application/language/arabic/pagination_lang.php b/application/language/arabic/pagination_lang.php index 1d113dfb68..9a62cf9419 100644 --- a/application/language/arabic/pagination_lang.php +++ b/application/language/arabic/pagination_lang.php @@ -26,16 +26,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) - * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 1.0.0 + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ -defined('BASEPATH') OR exit('No direct script access allowed'); +defined('BASEPATH') or exit('No direct script access allowed'); $lang['pagination_first_link'] = '‹ First'; $lang['pagination_next_link'] = '>'; diff --git a/application/language/arabic/profiler_lang.php b/application/language/arabic/profiler_lang.php index 157296725c..3b1f642ef6 100644 --- a/application/language/arabic/profiler_lang.php +++ b/application/language/arabic/profiler_lang.php @@ -26,16 +26,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * - * @package CodeIgniter - * @author EllisLab Dev Team - * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) - * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) - * @license https://opensource.org/licenses/MIT MIT License - * @link https://codeigniter.com - * @since Version 1.0.0 + * @package CodeIgniter + * @author EllisLab Dev Team + * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/) + * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/) + * @license https://opensource.org/licenses/MIT MIT License + * @link https://codeigniter.com + * @since Version 1.0.0 * @filesource */ -defined('BASEPATH') OR exit('No direct script access allowed'); +defined('BASEPATH') or exit('No direct script access allowed'); $lang['profiler_database'] = 'DATABASE'; $lang['profiler_controller_info'] = 'CLASS/METHOD'; diff --git a/application/language/arabic/translations_lang.php b/application/language/arabic/translations_lang.php index f115259a8a..aa65b94a4b 100755 --- a/application/language/arabic/translations_lang.php +++ b/application/language/arabic/translations_lang.php @@ -1,4 +1,4 @@ -CI =& get_instance(); + $this->CI = &get_instance(); $this->CI->load->model('users_model'); $this->CI->load->model('roles_model'); @@ -53,14 +53,15 @@ public function check_login(string $username, string $password): ?array $password = hash_password($salt, $password); - $user_settings = $this->CI->db->get_where('user_settings', [ - 'username' => $username, - 'password' => $password - ])->row_array(); + $user_settings = $this->CI->db + ->get_where('user_settings', [ + 'username' => $username, + 'password' => $password + ]) + ->row_array(); - if (empty($user_settings)) - { - return NULL; + if (empty($user_settings)) { + return null; } $user = $this->CI->users_model->find($user_settings['id_users']); @@ -73,9 +74,9 @@ public function check_login(string $username, string $password): ?array 'user_id' => $user['id'], 'user_email' => $user['email'], 'username' => $username, - 'timezone' => ! empty($user['timezone']) ? $user['timezone'] : $default_timezone, - 'language' => ! empty($user['language']) ? $user['language'] : Config::LANGUAGE, - 'role_slug' => $role['slug'], + 'timezone' => !empty($user['timezone']) ? $user['timezone'] : $default_timezone, + 'language' => !empty($user['language']) ? $user['language'] : Config::LANGUAGE, + 'role_slug' => $role['slug'] ]; } @@ -119,9 +120,7 @@ public function get_user_display_name(int $user_id): string */ public function regenerate_password(string $username, string $email): string { - $query = $this - ->CI - ->db + $query = $this->CI->db ->select('users.id') ->from('users') ->join('user_settings', 'user_settings.id_users = users.id', 'inner') @@ -129,8 +128,7 @@ public function regenerate_password(string $username, string $email): string ->where('user_settings.username', $username) ->get(); - if ( ! $query->num_rows()) - { + if (!$query->num_rows()) { throw new RuntimeException('The username was not found in the database: ' . $username); } @@ -157,6 +155,10 @@ public function regenerate_password(string $username, string $email): string */ public function does_account_exist(int $user_id): bool { - return $this->CI->users_model->query()->where(['id' => $user_id])->get()->num_rows() > 0; + return $this->CI->users_model + ->query() + ->where(['id' => $user_id]) + ->get() + ->num_rows() > 0; } } diff --git a/application/libraries/Api.php b/application/libraries/Api.php index 44df3c7139..4067c72703 100644 --- a/application/libraries/Api.php +++ b/application/libraries/Api.php @@ -13,7 +13,6 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ - /** * Api library. * @@ -21,7 +20,8 @@ * * @package Libraries */ -class Api { +class Api +{ /** * @var EA_Controller|CI_Controller */ @@ -42,7 +42,7 @@ class Api { */ public function __construct() { - $this->CI =& get_instance(); + $this->CI = &get_instance(); $this->CI->load->library('accounts'); } @@ -64,30 +64,29 @@ public function model(string $model): void */ public function auth(): void { - try - { - // Bearer token. + try { + // Bearer token. $api_token = setting('api_token'); - if ( ! empty($api_token) && $api_token === $this->get_bearer_token()) - { + if (!empty($api_token) && $api_token === $this->get_bearer_token()) { return; } - // Basic auth. - $username = $_SERVER['PHP_AUTH_USER'] ?? NULL; + // Basic auth. + $username = $_SERVER['PHP_AUTH_USER'] ?? null; - $password = $_SERVER['PHP_AUTH_PW'] ?? NULL; + $password = $_SERVER['PHP_AUTH_PW'] ?? null; $user_data = $this->CI->accounts->check_login($username, $password); - if (empty($user_data['role_slug']) || $user_data['role_slug'] !== DB_SLUG_ADMIN) - { - throw new RuntimeException('The provided credentials do not match any admin user!', 401, 'Unauthorized'); + if (empty($user_data['role_slug']) || $user_data['role_slug'] !== DB_SLUG_ADMIN) { + throw new RuntimeException( + 'The provided credentials do not match any admin user!', + 401, + 'Unauthorized' + ); } - } - catch (Throwable) - { + } catch (Throwable) { $this->request_authentication(); } } @@ -103,15 +102,13 @@ protected function get_bearer_token(): ?string // HEADER: Get the access token from the header - if ( ! empty($headers)) - { - if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) - { + if (!empty($headers)) { + if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) { return $matches[1]; } } - return NULL; + return null; } /** @@ -121,29 +118,25 @@ protected function get_bearer_token(): ?string */ protected function get_authorization_header(): ?string { - $headers = NULL; + $headers = null; - if (isset($_SERVER['Authorization'])) - { + if (isset($_SERVER['Authorization'])) { $headers = trim($_SERVER['Authorization']); - } - else - { - if (isset($_SERVER['HTTP_AUTHORIZATION'])) - { + } else { + if (isset($_SERVER['HTTP_AUTHORIZATION'])) { // Nginx or fast CGI $headers = trim($_SERVER['HTTP_AUTHORIZATION']); - } - elseif (function_exists('apache_request_headers')) - { + } elseif (function_exists('apache_request_headers')) { $requestHeaders = apache_request_headers(); // Server-side fix for bug in old Android versions (a nice side effect of this fix means we don't care // about capitalization for Authorization). - $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders)); + $requestHeaders = array_combine( + array_map('ucwords', array_keys($requestHeaders)), + array_values($requestHeaders) + ); - if (isset($requestHeaders['Authorization'])) - { + if (isset($requestHeaders['Authorization'])) { $headers = trim($requestHeaders['Authorization']); } } @@ -155,7 +148,8 @@ protected function get_authorization_header(): ?string /** * Sets request authentication headers. */ - #[NoReturn] public function request_authentication(): void + #[NoReturn] + public function request_authentication(): void { header('WWW-Authenticate: Basic realm="Easy!Appointments"'); header('HTTP/1.0 401 Unauthorized'); @@ -205,23 +199,20 @@ public function request_order_by(): ?string { $sort = request('sort'); - if ( ! $sort) - { - return NULL; + if (!$sort) { + return null; } $sort_tokens = array_map('trim', explode(',', $sort)); $order_by = []; - foreach ($sort_tokens as $sort_token) - { + foreach ($sort_tokens as $sort_token) { $api_field = substr($sort_token, 1); $direction_operator = substr($sort_token, 0, 1); - if ( ! in_array($direction_operator, ['-', '+'])) - { + if (!in_array($direction_operator, ['-', '+'])) { $direction_operator = '+'; $api_field = $sort_token; } @@ -245,9 +236,8 @@ public function request_fields(): ?array { $fields = request('fields'); - if ( ! $fields) - { - return NULL; + if (!$fields) { + return null; } return array_map('trim', explode(',', $fields)); @@ -262,9 +252,8 @@ public function request_with(): ?array { $with = request('with'); - if ( ! $with) - { - return NULL; + if (!$with) { + return null; } return array_map('trim', explode(',', $with)); diff --git a/application/libraries/Availability.php b/application/libraries/Availability.php index 41360f00a5..d9b72da71d 100644 --- a/application/libraries/Availability.php +++ b/application/libraries/Availability.php @@ -11,7 +11,6 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ - /** * Availability library. * @@ -19,7 +18,8 @@ * * @package Libraries */ -class Availability { +class Availability +{ /** * @var EA_Controller|CI_Controller */ @@ -30,7 +30,7 @@ class Availability { */ public function __construct() { - $this->CI =& get_instance(); + $this->CI = &get_instance(); $this->CI->load->model('admins_model'); $this->CI->load->model('appointments_model'); @@ -56,19 +56,19 @@ public function __construct() * * @throws Exception */ - public function get_available_hours(string $date, array $service, array $provider, int $exclude_appointment_id = NULL): array - { - if ($this->CI->blocked_periods_model->is_entire_date_blocked($date)) - { + public function get_available_hours( + string $date, + array $service, + array $provider, + int $exclude_appointment_id = null + ): array { + if ($this->CI->blocked_periods_model->is_entire_date_blocked($date)) { return []; } - if ($service['attendants_number'] > 1) - { + if ($service['attendants_number'] > 1) { $available_hours = $this->consider_multiple_attendants($date, $service, $provider, $exclude_appointment_id); - } - else - { + } else { $available_periods = $this->get_available_periods($date, $provider, $exclude_appointment_id); $available_hours = $this->generate_available_hours($date, $service, $available_periods); @@ -79,276 +79,6 @@ public function get_available_hours(string $date, array $service, array $provide return $this->consider_future_booking_limit($date, $available_hours, $provider); } - /** - * 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. It 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 string $date Selected date (Y-m-d). - * @param array $provider Provider data. - * @param int|null $exclude_appointment_id Exclude an appointment from the availability generation. - * - * @return array Returns an array with the available time periods of the provider. - * - * @throws Exception - */ - protected function get_available_periods(string $date, array $provider, int $exclude_appointment_id = NULL): array - { - // Get the service, provider's working plan and provider appointments. - $working_plan = json_decode($provider['settings']['working_plan'], TRUE); - - // Get the provider's working plan exceptions. - $working_plan_exceptions_json = $provider['settings']['working_plan_exceptions']; - - $working_plan_exceptions = $working_plan_exceptions_json ? json_decode($provider['settings']['working_plan_exceptions'], TRUE) : []; - - $escaped_provider_id = $this->CI->db->escape($provider['id']); - - $escaped_date = $this->CI->db->escape($date); - - $where = 'id_users_provider = ' . $escaped_provider_id - . ' AND DATE(start_datetime) <= ' . $escaped_date . ' AND DATE(end_datetime) >= ' . $escaped_date; - - // Sometimes it might be necessary to exclude an appointment from the calculation (e.g. when editing an - // existing appointment). - if ($exclude_appointment_id) - { - $escaped_exclude_appointment_id = $this->CI->db->escape($exclude_appointment_id); - $where .= ' AND id != ' . $escaped_exclude_appointment_id; - } - - $appointments = array_values( - array_merge( - $this->CI->appointments_model->get($where), - $this->CI->unavailabilities_model->get($where), - $this->CI->blocked_periods_model->get_for_period($date, $date) - ) - ); - - // Find the empty spaces on the plan. The first split between the plan is due to a break (if any). After that - // every reserved appointment is considered to be a taken space in the plan. - $working_day = strtolower(date('l', strtotime($date))); - - $date_working_plan = $working_plan[$working_day] ?? NULL; - - // Search if the $date is a custom availability period added outside the normal working plan. - if (array_key_exists($date, $working_plan_exceptions)) - { - $date_working_plan = $working_plan_exceptions[$date]; - } - - if ( ! $date_working_plan) - { - return []; - } - - $periods = []; - - if (isset($date_working_plan['breaks'])) - { - $periods[] = [ - 'start' => $date_working_plan['start'], - 'end' => $date_working_plan['end'] - ]; - - $day_start = new DateTime($date_working_plan['start']); - $day_end = new DateTime($date_working_plan['end']); - - // Split the working plan to available time periods that do not contain the breaks in them. - foreach ($date_working_plan['breaks'] as $break) - { - $break_start = new DateTime($break['start']); - $break_end = new DateTime($break['end']); - - if ($break_start < $day_start) - { - $break_start = $day_start; - } - - if ($break_end > $day_end) - { - $break_end = $day_end; - } - - if ($break_start >= $break_end) - { - continue; - } - - foreach ($periods as $key => $period) - { - $period_start = new DateTime($period['start']); - $period_end = new DateTime($period['end']); - - $remove_current_period = FALSE; - - if ($break_start > $period_start && $break_start < $period_end && $break_end > $period_start) - { - $periods[] = [ - 'start' => $period_start->format('H:i'), - 'end' => $break_start->format('H:i') - ]; - - $remove_current_period = TRUE; - } - - if ($break_start < $period_end && $break_end > $period_start && $break_end < $period_end) - { - $periods[] = [ - 'start' => $break_end->format('H:i'), - 'end' => $period_end->format('H:i') - ]; - - $remove_current_period = TRUE; - } - - if ($break_start == $period_start && $break_end == $period_end) - { - $remove_current_period = TRUE; - } - - if ($remove_current_period) - { - unset($periods[$key]); - } - } - } - } - - // Break the empty periods with the reserved appointments. - foreach ($appointments as $appointment) - { - foreach ($periods as $index => &$period) - { - $appointment_start = new DateTime($appointment['start_datetime']); - $appointment_end = new DateTime($appointment['end_datetime']); - - if ($appointment_start >= $appointment_end) - { - continue; - } - - $period_start = new DateTime($date . ' ' . $period['start']); - $period_end = new DateTime($date . ' ' . $period['end']); - - if ($appointment_start <= $period_start && $appointment_end <= $period_end && $appointment_end <= $period_start) - { - // The appointment does not belong in this time period, so we will not change anything. - continue; - } - else - { - if ($appointment_start <= $period_start && $appointment_end <= $period_end && $appointment_end >= $period_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'] = $appointment_end->format('H:i'); - } - else - { - if ($appointment_start >= $period_start && $appointment_end < $period_end) - { - // The appointment is inside the time period, so we will split the period into two new - // others. - unset($periods[$index]); - - $periods[] = [ - 'start' => $period_start->format('H:i'), - 'end' => $appointment_start->format('H:i') - ]; - - $periods[] = [ - 'start' => $appointment_end->format('H:i'), - 'end' => $period_end->format('H:i') - ]; - } - else if ($appointment_start == $period_start && $appointment_end == $period_end) - { - unset($periods[$index]); // The whole period is blocked so remove it from the available periods array. - } - else - { - if ($appointment_start >= $period_start && $appointment_end >= $period_start && $appointment_start <= $period_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'] = $appointment_start->format('H:i'); - } - else - { - if ($appointment_start >= $period_start && $appointment_end >= $period_end && $appointment_start >= $period_end) - { - // The appointment does not belong in the period so do not change anything. - continue; - } - else - { - if ($appointment_start <= $period_start && $appointment_end >= $period_end && $appointment_start <= $period_end) - { - // The appointment is bigger than the period, so this period needs to be removed. - unset($periods[$index]); - } - } - } - } - } - } - } - } - - return array_values($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 string $date Selected date (Y-m-d). - * @param array $service Service data. - * @param array $empty_periods Empty periods array. - * - * @return array Returns an array with the available hours for the appointment. - * - * @throws Exception - */ - protected function generate_available_hours( - string $date, - array $service, - array $empty_periods - ): array - { - $available_hours = []; - - foreach ($empty_periods as $period) - { - $start_hour = new DateTime($date . ' ' . $period['start']); - - $end_hour = new DateTime($date . ' ' . $period['end']); - - $interval = $service['availabilities_type'] === AVAILABILITIES_TYPE_FIXED ? (int)$service['duration'] : 15; - - $current_hour = $start_hour; - - $diff = $current_hour->diff($end_hour); - - while (($diff->h * 60 + $diff->i) >= (int)$service['duration'] && $diff->invert === 0) - { - $available_hours[] = $current_hour->format('H:i'); - - $current_hour->add(new DateInterval('PT' . $interval . 'M')); - - $diff = $current_hour->diff($end_hour); - } - } - - return $available_hours; - } - /** * Get multiple attendants hours. * @@ -367,32 +97,29 @@ protected function consider_multiple_attendants( string $date, array $service, array $provider, - int $exclude_appointment_id = NULL - ): array - { + int $exclude_appointment_id = null + ): array { $unavailability_events = $this->CI->unavailabilities_model->get([ - 'is_unavailability' => TRUE, + 'is_unavailability' => true, 'DATE(start_datetime) <=' => $date, 'DATE(end_datetime) >=' => $date, 'id_users_provider' => $provider['id'] ]); - $working_plan = json_decode($provider['settings']['working_plan'], TRUE); + $working_plan = json_decode($provider['settings']['working_plan'], true); - $working_plan_exceptions = json_decode($provider['settings']['working_plan_exceptions'], TRUE); + $working_plan_exceptions = json_decode($provider['settings']['working_plan_exceptions'], true); $working_day = strtolower(date('l', strtotime($date))); - $date_working_plan = $working_plan[$working_day] ?? NULL; + $date_working_plan = $working_plan[$working_day] ?? null; // Search if the $date is a custom availability period added outside the normal working plan. - if (array_key_exists($date, $working_plan_exceptions)) - { + if (array_key_exists($date, $working_plan_exceptions)) { $date_working_plan = $working_plan_exceptions[$date]; } - if ( ! $date_working_plan) - { + if (!$date_working_plan) { return []; } @@ -412,17 +139,15 @@ protected function consider_multiple_attendants( $hours = []; $interval_value = $service['availabilities_type'] == AVAILABILITIES_TYPE_FIXED ? $service['duration'] : '15'; - $interval = new DateInterval('PT' . (int)$interval_value . 'M'); - $duration = new DateInterval('PT' . (int)$service['duration'] . 'M'); + $interval = new DateInterval('PT' . (int) $interval_value . 'M'); + $duration = new DateInterval('PT' . (int) $service['duration'] . 'M'); - foreach ($periods as $period) - { + foreach ($periods as $period) { $slot_start = clone $period['start']; $slot_end = clone $slot_start; $slot_end->add($duration); - while ($slot_end <= $period['end']) - { + while ($slot_end <= $period['end']) { // Make sure there is no other service appointment for this time slot. $other_service_attendants_number = $this->CI->appointments_model->get_other_service_attendants_number( $slot_start, @@ -432,8 +157,7 @@ protected function consider_multiple_attendants( $exclude_appointment_id ); - if ($other_service_attendants_number > 0) - { + if ($other_service_attendants_number > 0) { $slot_start->add($interval); $slot_end->add($interval); continue; @@ -448,8 +172,7 @@ protected function consider_multiple_attendants( $exclude_appointment_id ); - if ($appointment_attendants_number < $service['attendants_number']) - { + if ($appointment_attendants_number < $service['attendants_number']) { $hours[] = $slot_start->format('H:i'); } @@ -474,32 +197,32 @@ protected function consider_multiple_attendants( */ public function remove_breaks(string $date, array $periods, array $breaks): array { - if ( ! $breaks) - { + if (!$breaks) { return $periods; } - foreach ($breaks as $break) - { + foreach ($breaks as $break) { $break_start = new DateTime($date . ' ' . $break['start']); $break_end = new DateTime($date . ' ' . $break['end']); - foreach ($periods as &$period) - { + foreach ($periods as &$period) { $period_start = $period['start']; $period_end = $period['end']; - if ($break_start <= $period_start && $break_end >= $period_start && $break_end <= $period_end) - { + if ($break_start <= $period_start && $break_end >= $period_start && $break_end <= $period_end) { // left $period['start'] = $break_end; continue; } - if ($break_start >= $period_start && $break_start <= $period_end && $break_end >= $period_start && $break_end <= $period_end) - { + if ( + $break_start >= $period_start && + $break_start <= $period_end && + $break_end >= $period_start && + $break_end <= $period_end + ) { // middle $period['end'] = $break_start; $periods[] = [ @@ -509,15 +232,13 @@ public function remove_breaks(string $date, array $periods, array $breaks): arra continue; } - if ($break_start >= $period_start && $break_start <= $period_end && $break_end >= $period_end) - { + if ($break_start >= $period_start && $break_start <= $period_end && $break_end >= $period_end) { // right $period['end'] = $break_start; continue; } - if ($break_start <= $period_start && $break_end >= $period_end) - { + if ($break_start <= $period_start && $break_end >= $period_end) { // break contains period $period['start'] = $break_end; } @@ -539,27 +260,32 @@ public function remove_breaks(string $date, array $periods, array $breaks): arra */ public function remove_unavailability_events(array $periods, array $unavailability_events): array { - foreach ($unavailability_events as $unavailability_event) - { + foreach ($unavailability_events as $unavailability_event) { $unavailability_start = new DateTime($unavailability_event['start_datetime']); $unavailability_end = new DateTime($unavailability_event['end_datetime']); - foreach ($periods as &$period) - { + foreach ($periods as &$period) { $period_start = $period['start']; $period_end = $period['end']; - if ($unavailability_start <= $period_start && $unavailability_end >= $period_start && $unavailability_end <= $period_end) - { + if ( + $unavailability_start <= $period_start && + $unavailability_end >= $period_start && + $unavailability_end <= $period_end + ) { // Left $period['start'] = $unavailability_end; continue; } - if ($unavailability_start >= $period_start && $unavailability_start <= $period_end && $unavailability_end >= $period_start && $unavailability_end <= $period_end) - { + if ( + $unavailability_start >= $period_start && + $unavailability_start <= $period_end && + $unavailability_end >= $period_start && + $unavailability_end <= $period_end + ) { // Middle $period['end'] = $unavailability_start; $periods[] = [ @@ -569,15 +295,17 @@ public function remove_unavailability_events(array $periods, array $unavailabili continue; } - if ($unavailability_start >= $period_start && $unavailability_start <= $period_end && $unavailability_end >= $period_end) - { + if ( + $unavailability_start >= $period_start && + $unavailability_start <= $period_end && + $unavailability_end >= $period_end + ) { // Right $period['end'] = $unavailability_start; continue; } - if ($unavailability_start <= $period_start && $unavailability_end >= $period_end) - { + if ($unavailability_start <= $period_start && $unavailability_end >= $period_end) { // Unavailability contains period $period['start'] = $unavailability_end; } @@ -587,6 +315,262 @@ public function remove_unavailability_events(array $periods, array $unavailabili return $periods; } + /** + * 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. It 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 string $date Selected date (Y-m-d). + * @param array $provider Provider data. + * @param int|null $exclude_appointment_id Exclude an appointment from the availability generation. + * + * @return array Returns an array with the available time periods of the provider. + * + * @throws Exception + */ + protected function get_available_periods(string $date, array $provider, int $exclude_appointment_id = null): array + { + // Get the service, provider's working plan and provider appointments. + $working_plan = json_decode($provider['settings']['working_plan'], true); + + // Get the provider's working plan exceptions. + $working_plan_exceptions_json = $provider['settings']['working_plan_exceptions']; + + $working_plan_exceptions = $working_plan_exceptions_json + ? json_decode($provider['settings']['working_plan_exceptions'], true) + : []; + + $escaped_provider_id = $this->CI->db->escape($provider['id']); + + $escaped_date = $this->CI->db->escape($date); + + $where = + 'id_users_provider = ' . + $escaped_provider_id . + ' AND DATE(start_datetime) <= ' . + $escaped_date . + ' AND DATE(end_datetime) >= ' . + $escaped_date; + + // Sometimes it might be necessary to exclude an appointment from the calculation (e.g. when editing an + // existing appointment). + if ($exclude_appointment_id) { + $escaped_exclude_appointment_id = $this->CI->db->escape($exclude_appointment_id); + $where .= ' AND id != ' . $escaped_exclude_appointment_id; + } + + $appointments = array_values( + array_merge( + $this->CI->appointments_model->get($where), + $this->CI->unavailabilities_model->get($where), + $this->CI->blocked_periods_model->get_for_period($date, $date) + ) + ); + + // Find the empty spaces on the plan. The first split between the plan is due to a break (if any). After that + // every reserved appointment is considered to be a taken space in the plan. + $working_day = strtolower(date('l', strtotime($date))); + + $date_working_plan = $working_plan[$working_day] ?? null; + + // Search if the $date is a custom availability period added outside the normal working plan. + if (array_key_exists($date, $working_plan_exceptions)) { + $date_working_plan = $working_plan_exceptions[$date]; + } + + if (!$date_working_plan) { + return []; + } + + $periods = []; + + if (isset($date_working_plan['breaks'])) { + $periods[] = [ + 'start' => $date_working_plan['start'], + 'end' => $date_working_plan['end'] + ]; + + $day_start = new DateTime($date_working_plan['start']); + $day_end = new DateTime($date_working_plan['end']); + + // Split the working plan to available time periods that do not contain the breaks in them. + foreach ($date_working_plan['breaks'] as $break) { + $break_start = new DateTime($break['start']); + $break_end = new DateTime($break['end']); + + if ($break_start < $day_start) { + $break_start = $day_start; + } + + if ($break_end > $day_end) { + $break_end = $day_end; + } + + if ($break_start >= $break_end) { + continue; + } + + foreach ($periods as $key => $period) { + $period_start = new DateTime($period['start']); + $period_end = new DateTime($period['end']); + + $remove_current_period = false; + + if ($break_start > $period_start && $break_start < $period_end && $break_end > $period_start) { + $periods[] = [ + 'start' => $period_start->format('H:i'), + 'end' => $break_start->format('H:i') + ]; + + $remove_current_period = true; + } + + if ($break_start < $period_end && $break_end > $period_start && $break_end < $period_end) { + $periods[] = [ + 'start' => $break_end->format('H:i'), + 'end' => $period_end->format('H:i') + ]; + + $remove_current_period = true; + } + + if ($break_start == $period_start && $break_end == $period_end) { + $remove_current_period = true; + } + + if ($remove_current_period) { + unset($periods[$key]); + } + } + } + } + + // Break the empty periods with the reserved appointments. + foreach ($appointments as $appointment) { + foreach ($periods as $index => &$period) { + $appointment_start = new DateTime($appointment['start_datetime']); + $appointment_end = new DateTime($appointment['end_datetime']); + + if ($appointment_start >= $appointment_end) { + continue; + } + + $period_start = new DateTime($date . ' ' . $period['start']); + $period_end = new DateTime($date . ' ' . $period['end']); + + if ( + $appointment_start <= $period_start && + $appointment_end <= $period_end && + $appointment_end <= $period_start + ) { + // The appointment does not belong in this time period, so we will not change anything. + continue; + } else { + if ( + $appointment_start <= $period_start && + $appointment_end <= $period_end && + $appointment_end >= $period_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'] = $appointment_end->format('H:i'); + } else { + if ($appointment_start >= $period_start && $appointment_end < $period_end) { + // The appointment is inside the time period, so we will split the period into two new + // others. + unset($periods[$index]); + + $periods[] = [ + 'start' => $period_start->format('H:i'), + 'end' => $appointment_start->format('H:i') + ]; + + $periods[] = [ + 'start' => $appointment_end->format('H:i'), + 'end' => $period_end->format('H:i') + ]; + } elseif ($appointment_start == $period_start && $appointment_end == $period_end) { + unset($periods[$index]); // The whole period is blocked so remove it from the available periods array. + } else { + if ( + $appointment_start >= $period_start && + $appointment_end >= $period_start && + $appointment_start <= $period_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'] = $appointment_start->format('H:i'); + } else { + if ( + $appointment_start >= $period_start && + $appointment_end >= $period_end && + $appointment_start >= $period_end + ) { + // The appointment does not belong in the period so do not change anything. + continue; + } else { + if ( + $appointment_start <= $period_start && + $appointment_end >= $period_end && + $appointment_start <= $period_end + ) { + // The appointment is bigger than the period, so this period needs to be removed. + unset($periods[$index]); + } + } + } + } + } + } + } + } + + return array_values($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 string $date Selected date (Y-m-d). + * @param array $service Service data. + * @param array $empty_periods Empty periods array. + * + * @return array Returns an array with the available hours for the appointment. + * + * @throws Exception + */ + protected function generate_available_hours(string $date, array $service, array $empty_periods): array + { + $available_hours = []; + + foreach ($empty_periods as $period) { + $start_hour = new DateTime($date . ' ' . $period['start']); + + $end_hour = new DateTime($date . ' ' . $period['end']); + + $interval = $service['availabilities_type'] === AVAILABILITIES_TYPE_FIXED ? (int) $service['duration'] : 15; + + $current_hour = $start_hour; + + $diff = $current_hour->diff($end_hour); + + while ($diff->h * 60 + $diff->i >= (int) $service['duration'] && $diff->invert === 0) { + $available_hours[] = $current_hour->format('H:i'); + + $current_hour->add(new DateInterval('PT' . $interval . 'M')); + + $diff = $current_hour->diff($end_hour); + } + } + + return $available_hours; + } + /** * Consider the book advance timeout and remove available hours that have passed the threshold. * @@ -610,12 +594,10 @@ protected function consider_book_advance_timeout(string $date, array $available_ $threshold = new DateTime('+' . $book_advance_timeout . ' minutes', $provider_timezone); - foreach ($available_hours as $index => $value) - { + foreach ($available_hours as $index => $value) { $available_hour = new DateTime($date . ' ' . $value, $provider_timezone); - if ($available_hour->getTimestamp() <= $threshold->getTimestamp()) - { + if ($available_hour->getTimestamp() <= $threshold->getTimestamp()) { unset($available_hours[$index]); } } @@ -638,8 +620,11 @@ protected function consider_book_advance_timeout(string $date, array $available_ * * @throws Exception */ - protected function consider_future_booking_limit(string $selected_date, array $available_hours, array $provider): array - { + protected function consider_future_booking_limit( + string $selected_date, + array $available_hours, + array $provider + ): array { $provider_timezone = new DateTimeZone($provider['timezone']); $future_booking_limit = setting('future_booking_limit'); // in days @@ -648,8 +633,7 @@ protected function consider_future_booking_limit(string $selected_date, array $a $selected_date_time = new DateTime($selected_date); - if ($threshold < $selected_date_time) - { + if ($threshold < $selected_date_time) { return []; } diff --git a/application/libraries/Captcha_builder.php b/application/libraries/Captcha_builder.php index cc7a689399..4b3cfb1668 100644 --- a/application/libraries/Captcha_builder.php +++ b/application/libraries/Captcha_builder.php @@ -19,93 +19,82 @@ * * This class replaces the Gregwar\Captcha\CaptchaBuilder so that it becomes PHP 8.1 compatible. */ -class Captcha_builder { +class Captcha_builder +{ + /** + * Temporary dir, for OCR check + */ + public $tempDir = 'temp/'; /** * @var array */ protected $fingerprint = []; - /** * @var bool */ - protected $useFingerprint = FALSE; - + protected $useFingerprint = false; /** * @var array */ protected $textColor = []; - /** * @var array */ - protected $lineColor = NULL; - + protected $lineColor = null; /** * @var array */ - protected $backgroundColor = NULL; - + protected $backgroundColor = null; /** * @var array */ protected $backgroundImages = []; - /** * @var resource */ - protected $contents = NULL; - + protected $contents = null; /** * @var string */ - protected $phrase = NULL; - + protected $phrase = null; /** * @var PhraseBuilderInterface */ protected $builder; - /** * @var bool */ - protected $distortion = TRUE; - + protected $distortion = true; /** * The maximum number of lines to draw in front of * the image. null - use default algorithm */ - protected $maxFrontLines = NULL; - + protected $maxFrontLines = null; /** * The maximum number of lines to draw behind * the image. null - use default algorithm */ - protected $maxBehindLines = NULL; - + protected $maxBehindLines = null; /** * The maximum angle of char */ protected $maxAngle = 8; - /** * The maximum offset of char */ protected $maxOffset = 5; - /** * Is the interpolation enabled ? * * @var bool */ - protected $interpolation = TRUE; - + protected $interpolation = true; /** * Ignore all effects * * @var bool */ - protected $ignoreAllEffects = FALSE; - + protected $ignoreAllEffects = false; /** * Allowed image types for the background images * @@ -113,41 +102,11 @@ class Captcha_builder { */ protected $allowedBackgroundImageTypes = ['image/png', 'image/jpeg', 'image/gif']; - /** - * The image contents - */ - public function getContents() - { - return $this->contents; - } - - /** - * Enable/Disables the interpolation - * - * @param $interpolate bool True to enable, false to disable - * - * @return Captcha_builder - */ - public function setInterpolation($interpolate = TRUE) - { - $this->interpolation = $interpolate; - - return $this; - } - - /** - * Temporary dir, for OCR check - */ - public $tempDir = 'temp/'; - - public function __construct($phrase = NULL, PhraseBuilderInterface $builder = NULL) + public function __construct($phrase = null, PhraseBuilderInterface $builder = null) { - if ($builder === NULL) - { - $this->builder = new PhraseBuilder; - } - else - { + if ($builder === null) { + $this->builder = new PhraseBuilder(); + } else { $this->builder = $builder; } @@ -155,157 +114,206 @@ public function __construct($phrase = NULL, PhraseBuilderInterface $builder = NU } /** - * Setting the phrase + * Generate the image */ - public function setPhrase($phrase) + public function build($width = 150, $height = 40, $font = null, $fingerprint = null) { - $this->phrase = (string)$phrase; - } + if (null !== $fingerprint) { + $this->fingerprint = $fingerprint; + $this->useFingerprint = true; + } else { + $this->fingerprint = []; + $this->useFingerprint = false; + } - /** - * Enables/disable distortion - */ - public function setDistortion($distortion) - { - $this->distortion = (bool)$distortion; + if ($font === null) { + $font = + __DIR__ . '/../../vendor/gregwar/captcha/src/Gregwar/Captcha/Font/captcha' . $this->rand(0, 5) . '.ttf'; + } - return $this; - } + if (empty($this->backgroundImages)) { + // if background images list is not set, use a color fill as a background + $image = imagecreatetruecolor($width, $height); + if ($this->backgroundColor == null) { + $bg = imagecolorallocate($image, $this->rand(200, 255), $this->rand(200, 255), $this->rand(200, 255)); + } else { + $color = $this->backgroundColor; + $bg = imagecolorallocate($image, $color[0], $color[1], $color[2]); + } + $this->background = $bg; + imagefill($image, 0, 0, $bg); + } else { + // use a random background image + $randomBackgroundImage = $this->backgroundImages[rand(0, count($this->backgroundImages) - 1)]; - public function setMaxBehindLines($maxBehindLines) - { - $this->maxBehindLines = $maxBehindLines; + $imageType = $this->validateBackgroundImage($randomBackgroundImage); - return $this; - } + $image = $this->createBackgroundImageFromType($randomBackgroundImage, $imageType); + } - public function setMaxFrontLines($maxFrontLines) - { - $this->maxFrontLines = $maxFrontLines; + // Apply effects + if (!$this->ignoreAllEffects) { + $square = $width * $height; + $effects = $this->rand($square / 3000, $square / 2000); - return $this; - } + // set the maximum number of lines to draw in front of the text + if ($this->maxBehindLines != null && $this->maxBehindLines > 0) { + $effects = min($this->maxBehindLines, $effects); + } - public function setMaxAngle($maxAngle) - { - $this->maxAngle = $maxAngle; + if ($this->maxBehindLines !== 0) { + for ($e = 0; $e < $effects; $e++) { + $this->drawLine($image, $width, $height); + } + } + } - return $this; - } + // Write CAPTCHA text + $color = $this->writePhrase($image, $this->phrase, $font, $width, $height); - public function setMaxOffset($maxOffset) - { - $this->maxOffset = $maxOffset; + // Apply effects + if (!$this->ignoreAllEffects) { + $square = $width * $height; + $effects = $this->rand($square / 3000, $square / 2000); - return $this; - } + // set the maximum number of lines to draw in front of the text + if ($this->maxFrontLines != null && $this->maxFrontLines > 0) { + $effects = min($this->maxFrontLines, $effects); + } - /** - * Gets the captcha phrase - */ - public function getPhrase() - { - return $this->phrase; - } + if ($this->maxFrontLines !== 0) { + for ($e = 0; $e < $effects; $e++) { + $this->drawLine($image, $width, $height, $color); + } + } + } - /** - * Returns true if the given phrase is good - */ - public function testPhrase($phrase) - { - return ($this->builder->niceize($phrase) == $this->builder->niceize($this->getPhrase())); - } + // Distort the image + if ($this->distortion && !$this->ignoreAllEffects) { + $image = $this->distort($image, $width, $height, $bg); + } - /** - * Instantiation - */ - public static function create($phrase = NULL) - { - return new self($phrase); - } + // Post effects + if (!$this->ignoreAllEffects) { + $this->postEffect($image); + } - /** - * Sets the text color to use - */ - public function setTextColor($r, $g, $b) - { - $this->textColor = [$r, $g, $b]; + $this->contents = $image; return $this; } /** - * Sets the background color to use + * Returns a random number or the next number in the + * fingerprint */ - public function setBackgroundColor($r, $g, $b) + protected function rand($min, $max) { - $this->backgroundColor = [$r, $g, $b]; - - return $this; - } + if (!is_array($this->fingerprint)) { + $this->fingerprint = []; + } - public function setLineColor($r, $g, $b) - { - $this->lineColor = [$r, $g, $b]; + if ($this->useFingerprint) { + $value = current($this->fingerprint); + next($this->fingerprint); + } else { + $value = mt_rand((int) $min, (int) $max); + $this->fingerprint[] = $value; + } - return $this; + return $value; } /** - * Sets the ignoreAllEffects value + * Validate the background image path. Return the image type if valid * - * @param bool $ignoreAllEffects - * @return Captcha_builder + * @param string $backgroundImage + * @return string + * @throws Exception */ - public function setIgnoreAllEffects($ignoreAllEffects) + protected function validateBackgroundImage($backgroundImage) { - $this->ignoreAllEffects = $ignoreAllEffects; + // check if file exists + if (!file_exists($backgroundImage)) { + $backgroundImageExploded = explode('/', $backgroundImage); + $imageFileName = + count($backgroundImageExploded) > 1 + ? $backgroundImageExploded[count($backgroundImageExploded) - 1] + : $backgroundImage; - return $this; + throw new Exception('Invalid background image: ' . $imageFileName); + } + + // check image type + $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension + $imageType = finfo_file($finfo, $backgroundImage); + finfo_close($finfo); + + if (!in_array($imageType, $this->allowedBackgroundImageTypes)) { + throw new Exception( + 'Invalid background image type! Allowed types are: ' . join(', ', $this->allowedBackgroundImageTypes) + ); + } + + return $imageType; } /** - * Sets the list of background images to use (one image is randomly selected) + * Create background image from type + * + * @param string $backgroundImage + * @param string $imageType + * @return resource + * @throws Exception */ - public function setBackgroundImages(array $backgroundImages) + protected function createBackgroundImageFromType($backgroundImage, $imageType) { - $this->backgroundImages = $backgroundImages; + switch ($imageType) { + case 'image/jpeg': + $image = imagecreatefromjpeg($backgroundImage); + break; + case 'image/png': + $image = imagecreatefrompng($backgroundImage); + break; + case 'image/gif': + $image = imagecreatefromgif($backgroundImage); + break; - return $this; + default: + throw new Exception('Not supported file type for background image!'); + break; + } + + return $image; } /** * Draw lines over the image */ - protected function drawLine($image, $width, $height, $tcol = NULL) + protected function drawLine($image, $width, $height, $tcol = null) { - if ($this->lineColor === NULL) - { + if ($this->lineColor === null) { $red = $this->rand(100, 255); $green = $this->rand(100, 255); $blue = $this->rand(100, 255); - } - else - { + } else { $red = $this->lineColor[0]; $green = $this->lineColor[1]; $blue = $this->lineColor[2]; } - if ($tcol === NULL) - { + if ($tcol === null) { $tcol = imagecolorallocate($image, $red, $green, $blue); } - if ($this->rand(0, 1)) - { // Horizontal + if ($this->rand(0, 1)) { + // Horizontal $Xa = $this->rand(0, $width / 2); $Ya = $this->rand(0, $height); $Xb = $this->rand($width / 2, $width); $Yb = $this->rand(0, $height); - } - else - { // Vertical + } else { + // Vertical $Xa = $this->rand(0, $width); $Ya = $this->rand(0, $height / 2); $Xb = $this->rand(0, $width); @@ -315,81 +323,39 @@ protected function drawLine($image, $width, $height, $tcol = NULL) imageline($image, $Xa, $Ya, $Xb, $Yb, $tcol); } - /** - * Apply some post effects - */ - protected function postEffect($image) - { - if ( ! function_exists('imagefilter')) - { - return; - } - - if ($this->backgroundColor != NULL || $this->textColor != NULL) - { - return; - } - - // Negate ? - if ($this->rand(0, 1) == 0) - { - imagefilter($image, IMG_FILTER_NEGATE); - } - - // Edge ? - if ($this->rand(0, 10) == 0) - { - imagefilter($image, IMG_FILTER_EDGEDETECT); - } - - // Contrast - imagefilter($image, IMG_FILTER_CONTRAST, $this->rand(-50, 10)); - - // Colorize - if ($this->rand(0, 5) == 0) - { - imagefilter($image, IMG_FILTER_COLORIZE, $this->rand(-80, 50), $this->rand(-80, 50), $this->rand(-80, 50)); - } - } - /** * Writes the phrase on the image */ protected function writePhrase($image, $phrase, $font, $width, $height) { $length = mb_strlen($phrase); - if ($length === 0) - { - return \imagecolorallocate($image, 0, 0, 0); + if ($length === 0) { + return imagecolorallocate($image, 0, 0, 0); } // Gets the text size and start position - $size = (int)round($width / $length) - $this->rand(0, 3) - 1; - $box = \imagettfbbox($size, 0, $font, $phrase); + $size = (int) round($width / $length) - $this->rand(0, 3) - 1; + $box = imagettfbbox($size, 0, $font, $phrase); $textWidth = $box[2] - $box[0]; $textHeight = $box[1] - $box[7]; - $x = (int)round(($width - $textWidth) / 2); - $y = (int)round(($height - $textHeight) / 2) + $size; + $x = (int) round(($width - $textWidth) / 2); + $y = (int) round(($height - $textHeight) / 2) + $size; - if ( ! $this->textColor) - { + if (!$this->textColor) { $textColor = [$this->rand(0, 150), $this->rand(0, 150), $this->rand(0, 150)]; - } - else - { + } else { $textColor = $this->textColor; } - $col = \imagecolorallocate($image, $textColor[0], $textColor[1], $textColor[2]); + $col = imagecolorallocate($image, $textColor[0], $textColor[1], $textColor[2]); // Write the letters one by one, with random angle - for ($i = 0; $i < $length; $i++) - { + for ($i = 0; $i < $length; $i++) { $symbol = mb_substr($phrase, $i, 1); - $box = \imagettfbbox($size, 0, $font, $symbol); + $box = imagettfbbox($size, 0, $font, $symbol); $w = $box[2] - $box[0]; $angle = $this->rand(-$this->maxAngle, $this->maxAngle); $offset = $this->rand(-$this->maxOffset, $this->maxOffset); - \imagettftext($image, $size, $angle, $x, $y + $offset, $col, $font, $symbol); + imagettftext($image, $size, $angle, $x, $y + $offset, $col, $font, $symbol); $x += $w; } @@ -397,182 +363,32 @@ protected function writePhrase($image, $phrase, $font, $width, $height) } /** - * Try to read the code against an OCR + * Distorts the image */ - public function isOCRReadable() - { - if ( ! is_dir($this->tempDir)) - { - @mkdir($this->tempDir, 0755, TRUE); - } - - $tempj = $this->tempDir . uniqid('captcha', TRUE) . '.jpg'; - $tempp = $this->tempDir . uniqid('captcha', TRUE) . '.pgm'; - - $this->save($tempj); - shell_exec("convert $tempj $tempp"); - $value = trim(strtolower(shell_exec("ocrad $tempp"))); - - @unlink($tempj); - @unlink($tempp); - - return $this->testPhrase($value); - } - - /** - * Builds while the code is readable against an OCR - */ - public function buildAgainstOCR($width = 150, $height = 40, $font = NULL, $fingerprint = NULL) - { - do - { - $this->build($width, $height, $font, $fingerprint); - } - while ($this->isOCRReadable()); - } - - /** - * Generate the image - */ - public function build($width = 150, $height = 40, $font = NULL, $fingerprint = NULL) - { - if (NULL !== $fingerprint) - { - $this->fingerprint = $fingerprint; - $this->useFingerprint = TRUE; - } - else - { - $this->fingerprint = []; - $this->useFingerprint = FALSE; - } - - if ($font === NULL) - { - $font = __DIR__ . '/../../vendor/gregwar/captcha/src/Gregwar/Captcha/Font/captcha' . $this->rand(0, 5) . '.ttf'; - } - - if (empty($this->backgroundImages)) - { - // if background images list is not set, use a color fill as a background - $image = imagecreatetruecolor($width, $height); - if ($this->backgroundColor == NULL) - { - $bg = imagecolorallocate($image, $this->rand(200, 255), $this->rand(200, 255), $this->rand(200, 255)); - } - else - { - $color = $this->backgroundColor; - $bg = imagecolorallocate($image, $color[0], $color[1], $color[2]); - } - $this->background = $bg; - imagefill($image, 0, 0, $bg); - } - else - { - // use a random background image - $randomBackgroundImage = $this->backgroundImages[rand(0, count($this->backgroundImages) - 1)]; - - $imageType = $this->validateBackgroundImage($randomBackgroundImage); - - $image = $this->createBackgroundImageFromType($randomBackgroundImage, $imageType); - } - - // Apply effects - if ( ! $this->ignoreAllEffects) - { - $square = $width * $height; - $effects = $this->rand($square / 3000, $square / 2000); - - // set the maximum number of lines to draw in front of the text - if ($this->maxBehindLines != NULL && $this->maxBehindLines > 0) - { - $effects = min($this->maxBehindLines, $effects); - } - - if ($this->maxBehindLines !== 0) - { - for ($e = 0; $e < $effects; $e++) - { - $this->drawLine($image, $width, $height); - } - } - } - - // Write CAPTCHA text - $color = $this->writePhrase($image, $this->phrase, $font, $width, $height); - - // Apply effects - if ( ! $this->ignoreAllEffects) - { - $square = $width * $height; - $effects = $this->rand($square / 3000, $square / 2000); - - // set the maximum number of lines to draw in front of the text - if ($this->maxFrontLines != NULL && $this->maxFrontLines > 0) - { - $effects = min($this->maxFrontLines, $effects); - } - - if ($this->maxFrontLines !== 0) - { - for ($e = 0; $e < $effects; $e++) - { - $this->drawLine($image, $width, $height, $color); - } - } - } - - // Distort the image - if ($this->distortion && ! $this->ignoreAllEffects) - { - $image = $this->distort($image, $width, $height, $bg); - } - - // Post effects - if ( ! $this->ignoreAllEffects) - { - $this->postEffect($image); - } - - $this->contents = $image; - - return $this; - } - - /** - * Distorts the image - */ - public function distort($image, $width, $height, $bg) + public function distort($image, $width, $height, $bg) { $contents = imagecreatetruecolor($width, $height); $X = $this->rand(0, $width); $Y = $this->rand(0, $height); $phase = $this->rand(0, 10); $scale = 1.1 + $this->rand(0, 10000) / 30000; - for ($x = 0; $x < $width; $x++) - { - for ($y = 0; $y < $height; $y++) - { + for ($x = 0; $x < $width; $x++) { + for ($y = 0; $y < $height; $y++) { $Vx = $x - $X; $Vy = $y - $Y; $Vn = sqrt($Vx * $Vx + $Vy * $Vy); - if ($Vn != 0) - { + if ($Vn != 0) { $Vn2 = $Vn + 4 * sin($Vn / 30); - $nX = $X + ($Vx * $Vn2 / $Vn); - $nY = $Y + ($Vy * $Vn2 / $Vn); - } - else - { + $nX = $X + ($Vx * $Vn2) / $Vn; + $nY = $Y + ($Vy * $Vn2) / $Vn; + } else { $nX = $X; $nY = $Y; } $nY = $nY + $scale * sin($phase + $nX * 0.2); - if ($this->interpolation) - { + if ($this->interpolation) { $p = $this->interpolate( $nX - floor($nX), $nY - floor($nY), @@ -581,14 +397,11 @@ public function distort($image, $width, $height, $bg) $this->getCol($image, floor($nX), ceil($nY), $bg), $this->getCol($image, ceil($nX), ceil($nY), $bg) ); - } - else - { + } else { $p = $this->getCol($image, round($nX), round($nY), $bg); } - if ($p == 0) - { + if ($p == 0) { $p = $bg; } @@ -600,207 +413,322 @@ public function distort($image, $width, $height, $bg) } /** - * Saves the Captcha to a jpeg file + * @param $x + * @param $y + * @param $nw + * @param $ne + * @param $sw + * @param $se + * + * @return int */ - public function save($filename, $quality = 90) + protected function interpolate($x, $y, $nw, $ne, $sw, $se) { - imagejpeg($this->contents, $filename, $quality); + [$r0, $g0, $b0] = $this->getRGB($nw); + [$r1, $g1, $b1] = $this->getRGB($ne); + [$r2, $g2, $b2] = $this->getRGB($sw); + [$r3, $g3, $b3] = $this->getRGB($se); + + $cx = 1.0 - $x; + $cy = 1.0 - $y; + + $m0 = $cx * $r0 + $x * $r1; + $m1 = $cx * $r2 + $x * $r3; + $r = (int) ($cy * $m0 + $y * $m1); + + $m0 = $cx * $g0 + $x * $g1; + $m1 = $cx * $g2 + $x * $g3; + $g = (int) ($cy * $m0 + $y * $m1); + + $m0 = $cx * $b0 + $x * $b1; + $m1 = $cx * $b2 + $x * $b3; + $b = (int) ($cy * $m0 + $y * $m1); + + return ($r << 16) | ($g << 8) | $b; } /** - * Gets the image GD + * @param $col + * + * @return array */ - public function getGd() + protected function getRGB($col) { - return $this->contents; + return [(int) ($col >> 16) & 0xff, (int) ($col >> 8) & 0xff, (int) $col & 0xff]; } /** - * Gets the image contents + * @param $image + * @param $x + * @param $y + * + * @return int */ - public function get($quality = 90) + protected function getCol($image, $x, $y, $background) { - ob_start(); - $this->output($quality); + $L = imagesx($image); + $H = imagesy($image); + if ($x < 0 || $x >= $L || $y < 0 || $y >= $H) { + return $background; + } - return ob_get_clean(); + return imagecolorat($image, $x, $y); } /** - * Gets the HTML inline base64 + * Apply some post effects */ - public function inline($quality = 90) + protected function postEffect($image) { - return 'data:image/jpeg;base64,' . base64_encode($this->get($quality)); + if (!function_exists('imagefilter')) { + return; + } + + if ($this->backgroundColor != null || $this->textColor != null) { + return; + } + + // Negate ? + if ($this->rand(0, 1) == 0) { + imagefilter($image, IMG_FILTER_NEGATE); + } + + // Edge ? + if ($this->rand(0, 10) == 0) { + imagefilter($image, IMG_FILTER_EDGEDETECT); + } + + // Contrast + imagefilter($image, IMG_FILTER_CONTRAST, $this->rand(-50, 10)); + + // Colorize + if ($this->rand(0, 5) == 0) { + imagefilter($image, IMG_FILTER_COLORIZE, $this->rand(-80, 50), $this->rand(-80, 50), $this->rand(-80, 50)); + } } /** - * Outputs the image + * Instantiation */ - public function output($quality = 90) + public static function create($phrase = null) { - imagejpeg($this->contents, NULL, $quality); + return new self($phrase); } /** - * @return array + * The image contents */ - public function getFingerprint() + public function getContents() { - return $this->fingerprint; + return $this->contents; } /** - * Returns a random number or the next number in the - * fingerprint + * Enable/Disables the interpolation + * + * @param $interpolate bool True to enable, false to disable + * + * @return Captcha_builder */ - protected function rand($min, $max) + public function setInterpolation($interpolate = true) { - if ( ! is_array($this->fingerprint)) - { - $this->fingerprint = []; - } + $this->interpolation = $interpolate; - if ($this->useFingerprint) - { - $value = current($this->fingerprint); - next($this->fingerprint); - } - else - { - $value = mt_rand((int)$min, (int)$max); - $this->fingerprint[] = $value; - } + return $this; + } - return $value; + /** + * Enables/disable distortion + */ + public function setDistortion($distortion) + { + $this->distortion = (bool) $distortion; + + return $this; + } + + public function setMaxBehindLines($maxBehindLines) + { + $this->maxBehindLines = $maxBehindLines; + + return $this; + } + + public function setMaxFrontLines($maxFrontLines) + { + $this->maxFrontLines = $maxFrontLines; + + return $this; + } + + public function setMaxAngle($maxAngle) + { + $this->maxAngle = $maxAngle; + + return $this; + } + + public function setMaxOffset($maxOffset) + { + $this->maxOffset = $maxOffset; + + return $this; } /** - * @param $x - * @param $y - * @param $nw - * @param $ne - * @param $sw - * @param $se - * - * @return int + * Sets the text color to use */ - protected function interpolate($x, $y, $nw, $ne, $sw, $se) + public function setTextColor($r, $g, $b) { - [$r0, $g0, $b0] = $this->getRGB($nw); - [$r1, $g1, $b1] = $this->getRGB($ne); - [$r2, $g2, $b2] = $this->getRGB($sw); - [$r3, $g3, $b3] = $this->getRGB($se); + $this->textColor = [$r, $g, $b]; - $cx = 1.0 - $x; - $cy = 1.0 - $y; + return $this; + } - $m0 = $cx * $r0 + $x * $r1; - $m1 = $cx * $r2 + $x * $r3; - $r = (int)($cy * $m0 + $y * $m1); + /** + * Sets the background color to use + */ + public function setBackgroundColor($r, $g, $b) + { + $this->backgroundColor = [$r, $g, $b]; - $m0 = $cx * $g0 + $x * $g1; - $m1 = $cx * $g2 + $x * $g3; - $g = (int)($cy * $m0 + $y * $m1); + return $this; + } - $m0 = $cx * $b0 + $x * $b1; - $m1 = $cx * $b2 + $x * $b3; - $b = (int)($cy * $m0 + $y * $m1); + public function setLineColor($r, $g, $b) + { + $this->lineColor = [$r, $g, $b]; - return ($r << 16) | ($g << 8) | $b; + return $this; } /** - * @param $image - * @param $x - * @param $y + * Sets the ignoreAllEffects value * - * @return int + * @param bool $ignoreAllEffects + * @return Captcha_builder */ - protected function getCol($image, $x, $y, $background) + public function setIgnoreAllEffects($ignoreAllEffects) { - $L = imagesx($image); - $H = imagesy($image); - if ($x < 0 || $x >= $L || $y < 0 || $y >= $H) - { - return $background; - } + $this->ignoreAllEffects = $ignoreAllEffects; - return imagecolorat($image, $x, $y); + return $this; } /** - * @param $col - * - * @return array + * Sets the list of background images to use (one image is randomly selected) */ - protected function getRGB($col) + public function setBackgroundImages(array $backgroundImages) { - return [ - (int)($col >> 16) & 0xff, - (int)($col >> 8) & 0xff, - (int)($col) & 0xff, - ]; + $this->backgroundImages = $backgroundImages; + + return $this; } /** - * Validate the background image path. Return the image type if valid - * - * @param string $backgroundImage - * @return string - * @throws Exception + * Builds while the code is readable against an OCR */ - protected function validateBackgroundImage($backgroundImage) + public function buildAgainstOCR($width = 150, $height = 40, $font = null, $fingerprint = null) { - // check if file exists - if ( ! file_exists($backgroundImage)) - { - $backgroundImageExploded = explode('/', $backgroundImage); - $imageFileName = count($backgroundImageExploded) > 1 ? $backgroundImageExploded[count($backgroundImageExploded) - 1] : $backgroundImage; + do { + $this->build($width, $height, $font, $fingerprint); + } while ($this->isOCRReadable()); + } - throw new Exception('Invalid background image: ' . $imageFileName); + /** + * Try to read the code against an OCR + */ + public function isOCRReadable() + { + if (!is_dir($this->tempDir)) { + @mkdir($this->tempDir, 0755, true); } - // check image type - $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension - $imageType = finfo_file($finfo, $backgroundImage); - finfo_close($finfo); + $tempj = $this->tempDir . uniqid('captcha', true) . '.jpg'; + $tempp = $this->tempDir . uniqid('captcha', true) . '.pgm'; - if ( ! in_array($imageType, $this->allowedBackgroundImageTypes)) - { - throw new Exception('Invalid background image type! Allowed types are: ' . join(', ', $this->allowedBackgroundImageTypes)); - } + $this->save($tempj); + shell_exec("convert $tempj $tempp"); + $value = trim(strtolower(shell_exec("ocrad $tempp"))); - return $imageType; + @unlink($tempj); + @unlink($tempp); + + return $this->testPhrase($value); } /** - * Create background image from type - * - * @param string $backgroundImage - * @param string $imageType - * @return resource - * @throws Exception + * Saves the Captcha to a jpeg file */ - protected function createBackgroundImageFromType($backgroundImage, $imageType) + public function save($filename, $quality = 90) { - switch ($imageType) - { - case 'image/jpeg': - $image = imagecreatefromjpeg($backgroundImage); - break; - case 'image/png': - $image = imagecreatefrompng($backgroundImage); - break; - case 'image/gif': - $image = imagecreatefromgif($backgroundImage); - break; + imagejpeg($this->contents, $filename, $quality); + } - default: - throw new Exception('Not supported file type for background image!'); - break; - } + /** + * Returns true if the given phrase is good + */ + public function testPhrase($phrase) + { + return $this->builder->niceize($phrase) == $this->builder->niceize($this->getPhrase()); + } - return $image; + /** + * Gets the captcha phrase + */ + public function getPhrase() + { + return $this->phrase; + } + + /** + * Setting the phrase + */ + public function setPhrase($phrase) + { + $this->phrase = (string) $phrase; + } + + /** + * Gets the image GD + */ + public function getGd() + { + return $this->contents; + } + + /** + * Gets the HTML inline base64 + */ + public function inline($quality = 90) + { + return 'data:image/jpeg;base64,' . base64_encode($this->get($quality)); + } + + /** + * Gets the image contents + */ + public function get($quality = 90) + { + ob_start(); + $this->output($quality); + + return ob_get_clean(); + } + + /** + * Outputs the image + */ + public function output($quality = 90) + { + imagejpeg($this->contents, null, $quality); + } + + /** + * @return array + */ + public function getFingerprint() + { + return $this->fingerprint; } } diff --git a/application/libraries/Email_messages.php b/application/libraries/Email_messages.php index b1dba5dbad..9643529d3b 100644 --- a/application/libraries/Email_messages.php +++ b/application/libraries/Email_messages.php @@ -18,7 +18,8 @@ * * @package Libraries */ -class Email_messages { +class Email_messages +{ /** * @var EA_Controller|CI_Controller */ @@ -29,7 +30,7 @@ class Email_messages { */ public function __construct() { - $this->CI =& get_instance(); + $this->CI = &get_instance(); $this->CI->load->model('admins_model'); $this->CI->load->model('appointments_model'); @@ -71,17 +72,15 @@ public function send_appointment_saved( string $appointment_link, string $recipient_email, string $ics_stream, - string $timezone = NULL - ): void - { + string $timezone = null + ): void { $appointment_timezone = new DateTimeZone($provider['timezone']); $appointment_start = new DateTime($appointment['start_datetime'], $appointment_timezone); $appointment_end = new DateTime($appointment['end_datetime'], $appointment_timezone); - if ($timezone && $timezone !== $provider['timezone']) - { + if ($timezone && $timezone !== $provider['timezone']) { $custom_timezone = new DateTimeZone($timezone); $appointment_start->setTimezone($custom_timezone); @@ -91,17 +90,21 @@ public function send_appointment_saved( $appointment['end_datetime'] = $appointment_end->format('Y-m-d H:i:s'); } - $html = $this->CI->load->view('emails/appointment_saved_email', [ - 'subject' => $subject, - 'message' => $message, - 'appointment' => $appointment, - 'service' => $service, - 'provider' => $provider, - 'customer' => $customer, - 'settings' => $settings, - 'timezone' => $timezone, - 'appointment_link' => $appointment_link, - ], TRUE); + $html = $this->CI->load->view( + 'emails/appointment_saved_email', + [ + 'subject' => $subject, + 'message' => $message, + 'appointment' => $appointment, + 'service' => $service, + 'provider' => $provider, + 'customer' => $customer, + 'settings' => $settings, + 'timezone' => $timezone, + 'appointment_link' => $appointment_link + ], + true + ); $this->CI->email->from($settings['company_email'], $settings['company_email']); @@ -113,8 +116,7 @@ public function send_appointment_saved( $this->CI->email->attach($ics_stream, 'attachment', 'invitation.ics', 'text/vcalendar'); - if ( ! $this->CI->email->send(FALSE)) - { + if (!$this->CI->email->send(false)) { throw new RuntimeException('Email was not sent: ' . $this->CI->email->print_debugger()); } } @@ -140,18 +142,16 @@ public function send_appointment_deleted( array $customer, array $settings, string $recipient_email, - string $reason = NULL, - string $timezone = NULL - ): void - { + string $reason = null, + string $timezone = null + ): void { $appointment_timezone = new DateTimeZone($provider['timezone']); $appointment_start = new DateTime($appointment['start_datetime'], $appointment_timezone); $appointment_end = new DateTime($appointment['end_datetime'], $appointment_timezone); - if ($timezone && $timezone !== $provider['timezone']) - { + if ($timezone && $timezone !== $provider['timezone']) { $custom_timezone = new DateTimeZone($timezone); $appointment_start->setTimezone($custom_timezone); @@ -161,15 +161,19 @@ public function send_appointment_deleted( $appointment['end_datetime'] = $appointment_end->format('Y-m-d H:i:s'); } - $html = $this->CI->load->view('emails/appointment_deleted_email', [ - 'appointment' => $appointment, - 'service' => $service, - 'provider' => $provider, - 'customer' => $customer, - 'settings' => $settings, - 'timezone' => $timezone, - 'reason' => $reason, - ], TRUE); + $html = $this->CI->load->view( + 'emails/appointment_deleted_email', + [ + 'appointment' => $appointment, + 'service' => $service, + 'provider' => $provider, + 'customer' => $customer, + 'settings' => $settings, + 'timezone' => $timezone, + 'reason' => $reason + ], + true + ); $this->CI->email->from($settings['company_email'], $settings['company_email']); @@ -179,8 +183,7 @@ public function send_appointment_deleted( $this->CI->email->message($html); - if ( ! $this->CI->email->send(FALSE)) - { + if (!$this->CI->email->send(false)) { throw new RuntimeException('Email was not sent: ' . $this->CI->email->print_debugger()); } } @@ -192,17 +195,17 @@ public function send_appointment_deleted( * @param string $recipient_email Recipient email address. * @param array $settings App settings. */ - public function send_password( - string $password, - string $recipient_email, - array $settings - ): void + public function send_password(string $password, string $recipient_email, array $settings): void { - $html = $this->CI->load->view('emails/account_recovery_email', [ - 'subject' => lang('new_account_password'), - 'message' => str_replace('$password', '' . $password . '', lang('new_password_is')), - 'settings' => $settings, - ], TRUE); + $html = $this->CI->load->view( + 'emails/account_recovery_email', + [ + 'subject' => lang('new_account_password'), + 'message' => str_replace('$password', '' . $password . '', lang('new_password_is')), + 'settings' => $settings + ], + true + ); $this->CI->email->from($settings['company_email'], $settings['company_email']); @@ -212,8 +215,7 @@ public function send_password( $this->CI->email->message($html); - if ( ! $this->CI->email->send(FALSE)) - { + if (!$this->CI->email->send(false)) { throw new RuntimeException('Email was not sent: ' . $this->CI->email->print_debugger()); } } diff --git a/application/libraries/Google_sync.php b/application/libraries/Google_sync.php index 71fc7a4d6d..312c8a941f 100644 --- a/application/libraries/Google_sync.php +++ b/application/libraries/Google_sync.php @@ -13,7 +13,6 @@ use Google\Service\Calendar\Event; use Google\Service\Calendar\Events; -use Google\Service\Calendar\Calendar; /** * Google sync library. @@ -22,7 +21,8 @@ * * @package Libraries */ -class Google_sync { +class Google_sync +{ /** * @var EA_Controller|CI_Controller */ @@ -46,7 +46,7 @@ class Google_sync { */ public function __construct() { - $this->CI =& get_instance(); + $this->CI = &get_instance(); $this->CI->load->model('appointments_model'); $this->CI->load->model('customers_model'); @@ -62,7 +62,7 @@ public function __construct() public function initialize_clients(): void { $http = new GuzzleHttp\Client([ - 'verify' => FALSE + 'verify' => false ]); $this->client = new Google_Client(); @@ -73,9 +73,7 @@ public function initialize_clients(): void $this->client->setRedirectUri(site_url('google/oauth_callback')); $this->client->setPrompt('consent'); $this->client->setAccessType('offline'); - $this->client->addScope([ - Google_Service_Calendar::CALENDAR, - ]); + $this->client->addScope([Google_Service_Calendar::CALENDAR]); $this->service = new Google_Service_Calendar($this->client); } @@ -109,9 +107,10 @@ public function authenticate(string $code): array { $response = $this->client->fetchAccessTokenWithAuthCode($code); - if (isset($response['error'])) - { - throw new RuntimeException('Google Authentication Error (' . $response['error'] . '): ' . $response['error_description']); + if (isset($response['error'])) { + throw new RuntimeException( + 'Google Authentication Error (' . $response['error'] . '): ' . $response['error_description'] + ); } return $response; @@ -151,17 +150,24 @@ public function refresh_token(string $refresh_token): void * * @throws Exception */ - public function add_appointment(array $appointment, array $provider, array $service, array $customer, array $settings): Event - { + public function add_appointment( + array $appointment, + array $provider, + array $service, + array $customer, + array $settings + ): Event { $event = new Google_Service_Calendar_Event(); - $event->setSummary(! empty($service) ? $service['name'] : 'Unavailable'); + $event->setSummary(!empty($service) ? $service['name'] : 'Unavailable'); $event->setDescription($appointment['notes']); $event->setLocation($appointment['location'] ?? $settings['company_name']); $timezone = new DateTimeZone($provider['timezone']); $start = new Google_Service_Calendar_EventDateTime(); - $start->setDateTime((new DateTime($appointment['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339)); + $start->setDateTime( + (new DateTime($appointment['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339) + ); $event->setStart($start); $end = new Google_Service_Calendar_EventDateTime(); @@ -171,13 +177,11 @@ public function add_appointment(array $appointment, array $provider, array $serv $event->attendees = []; $event_provider = new Google_Service_Calendar_EventAttendee(); - $event_provider->setDisplayName($provider['first_name'] . ' ' - . $provider['last_name']); + $event_provider->setDisplayName($provider['first_name'] . ' ' . $provider['last_name']); $event_provider->setEmail($provider['email']); $event->attendees[] = $event_provider; - if ( ! empty($customer)) - { + if (!empty($customer)) { $event_customer = new Google_Service_Calendar_EventAttendee(); $event_customer->setDisplayName($customer['first_name'] . ' ' . $customer['last_name']); $event_customer->setEmail($customer['email']); @@ -204,10 +208,17 @@ public function add_appointment(array $appointment, array $provider, array $serv * * @throws Exception */ - public function update_appointment(array $appointment, array $provider, array $service, array $customer, array $settings): Event - { - $event = $this->service->events->get($provider['settings']['google_calendar'], - $appointment['id_google_calendar']); + public function update_appointment( + array $appointment, + array $provider, + array $service, + array $customer, + array $settings + ): Event { + $event = $this->service->events->get( + $provider['settings']['google_calendar'], + $appointment['id_google_calendar'] + ); $event->setSummary($service['name']); $event->setDescription($appointment['notes']); @@ -216,7 +227,9 @@ public function update_appointment(array $appointment, array $provider, array $s $timezone = new DateTimeZone($provider['timezone']); $start = new Google_Service_Calendar_EventDateTime(); - $start->setDateTime((new DateTime($appointment['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339)); + $start->setDateTime( + (new DateTime($appointment['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339) + ); $event->setStart($start); $end = new Google_Service_Calendar_EventDateTime(); @@ -230,11 +243,9 @@ public function update_appointment(array $appointment, array $provider, array $s $event_provider->setEmail($provider['email']); $event->attendees[] = $event_provider; - if ( ! empty($customer)) - { + if (!empty($customer)) { $event_customer = new Google_Service_Calendar_EventAttendee(); - $event_customer->setDisplayName($customer['first_name'] . ' ' - . $customer['last_name']); + $event_customer->setDisplayName($customer['first_name'] . ' ' . $customer['last_name']); $event_customer->setEmail($customer['email']); $event->attendees[] = $event_customer; } @@ -272,16 +283,19 @@ public function add_unavailability(array $provider, array $unavailability): Goog $timezone = new DateTimeZone($provider['timezone']); $start = new Google_Service_Calendar_EventDateTime(); - $start->setDateTime((new DateTime($unavailability['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339)); + $start->setDateTime( + (new DateTime($unavailability['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339) + ); $event->setStart($start); $end = new Google_Service_Calendar_EventDateTime(); - $end->setDateTime((new DateTime($unavailability['end_datetime'], $timezone))->format(DateTimeInterface::RFC3339)); + $end->setDateTime( + (new DateTime($unavailability['end_datetime'], $timezone))->format(DateTimeInterface::RFC3339) + ); $event->setEnd($end); // Add the new event to the Google Calendar. return $this->service->events->insert($provider['settings']['google_calendar'], $event); - } /** @@ -296,7 +310,10 @@ public function add_unavailability(array $provider, array $unavailability): Goog */ public function update_unavailability(array $provider, array $unavailability): Google_Service_Calendar_Event { - $event = $this->service->events->get($provider['settings']['google_calendar'], $unavailability['id_google_calendar']); + $event = $this->service->events->get( + $provider['settings']['google_calendar'], + $unavailability['id_google_calendar'] + ); $event->setSummary('Unavailable'); $event->setDescription($unavailability['notes']); @@ -304,11 +321,15 @@ public function update_unavailability(array $provider, array $unavailability): G $timezone = new DateTimeZone($provider['timezone']); $start = new Google_Service_Calendar_EventDateTime(); - $start->setDateTime((new DateTime($unavailability['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339)); + $start->setDateTime( + (new DateTime($unavailability['start_datetime'], $timezone))->format(DateTimeInterface::RFC3339) + ); $event->setStart($start); $end = new Google_Service_Calendar_EventDateTime(); - $end->setDateTime((new DateTime($unavailability['end_datetime'], $timezone))->format(DateTimeInterface::RFC3339)); + $end->setDateTime( + (new DateTime($unavailability['end_datetime'], $timezone))->format(DateTimeInterface::RFC3339) + ); $event->setEnd($end); return $this->service->events->update($provider['settings']['google_calendar'], $event->getId(), $event); @@ -352,7 +373,7 @@ public function get_sync_events(string $google_calendar, string $start, string $ $params = [ 'timeMin' => date(DateTimeInterface::RFC3339, $start), 'timeMax' => date(DateTimeInterface::RFC3339, $end), - 'singleEvents' => TRUE, + 'singleEvents' => true ]; return $this->service->events->listEvents($google_calendar, $params); @@ -372,10 +393,8 @@ public function get_google_calendars(): array $calendars = []; - foreach ($calendar_list->getItems() as $google_calendar) - { - if ($google_calendar->getAccessRole() === 'reader') - { + foreach ($calendar_list->getItems() as $google_calendar) { + if ($google_calendar->getAccessRole() === 'reader') { continue; } @@ -419,19 +438,19 @@ public function get_add_to_google_url(int $appointment_id): string $appointment_end_instance->setTimezone($utc_timezone_instance); - $add = [ - $provider['email'] - ]; + $add = [$provider['email']]; - if ( ! empty($customer['email'])) - { + if (!empty($customer['email'])) { $add[] = $customer['email']; } $add_to_google_url_params = [ 'action' => 'TEMPLATE', 'text' => $service['name'], - 'dates' => $appointment_start_instance->format('Ymd\THis\Z') . '/' . $appointment_end_instance->format('Ymd\THis\Z'), + 'dates' => + $appointment_start_instance->format('Ymd\THis\Z') . + '/' . + $appointment_end_instance->format('Ymd\THis\Z'), 'location' => setting('company_name'), 'details' => 'View/Change Appointment: ' . site_url('appointments/index/' . $appointment['hash']), 'add' => implode(', ', $add) diff --git a/application/libraries/Ics_calendar.php b/application/libraries/Ics_calendar.php index 932fd12ff1..6b3a2c2f54 100644 --- a/application/libraries/Ics_calendar.php +++ b/application/libraries/Ics_calendar.php @@ -25,7 +25,8 @@ * * There is no other change to the original file. */ -class Ics_calendar extends Calendar { +class Ics_calendar extends Calendar +{ /** * @var string */ @@ -62,7 +63,7 @@ class Ics_calendar extends Calendar { private $customHeaders = []; /** - * @var \DateTimeZone + * @var DateTimeZone */ private $timezone; @@ -91,7 +92,7 @@ class Ics_calendar extends Calendar { */ public function __construct() { - $this->timezone = new \DateTimeZone('America/New_York'); + $this->timezone = new DateTimeZone('America/New_York'); $this->events = new Ics_provider(); $this->todos = new Ics_provider(); $this->freeBusy = new Ics_provider(); @@ -112,10 +113,10 @@ public function __construct() * //return an array of CalendarEvent objects * }) * - * @param \Closure $eventsProvider - * @return \Jsvrcek\ICS\Model\Calendar + * @param Closure $eventsProvider + * @return Calendar */ - public function setEventsProvider(\Closure $eventsProvider) + public function setEventsProvider(Closure $eventsProvider) { $this->events = new Ics_provider($eventsProvider); return $this; @@ -131,7 +132,7 @@ public function getVersion() /** * @param string $version - * @return \Jsvrcek\ICS\Model\Calendar + * @return Calendar */ public function setVersion($version) { @@ -149,7 +150,7 @@ public function getProdId() /** * @param string $prodId - * @return \Jsvrcek\ICS\Model\Calendar + * @return Calendar */ public function setProdId($prodId) { @@ -185,7 +186,7 @@ public function getCalendarScale() /** * @param string $calendarScale - * @return \Jsvrcek\ICS\Model\Calendar + * @return Calendar */ public function setCalendarScale($calendarScale) { @@ -203,7 +204,7 @@ public function getMethod() /** * @param string $method - * @return \Jsvrcek\ICS\Model\Calendar + * @return Calendar */ public function setMethod($method) { @@ -247,26 +248,19 @@ public function getImage() public function setImage($image) { // Do some validation on provided data. - if (array_key_exists('VALUE', $image) && in_array($image['VALUE'], ['URI', 'BINARY'])) - { - if ($image['VALUE'] == 'URI' && $image['URI']) - { + if (array_key_exists('VALUE', $image) && in_array($image['VALUE'], ['URI', 'BINARY'])) { + if ($image['VALUE'] == 'URI' && $image['URI']) { $new_image = [ 'VALUE' => 'URI', 'URI' => $image['URI'] ]; - - } - elseif ($image['VALUE'] == 'BINARY' && $image['ENCODING'] && $image['BINARY']) - { + } elseif ($image['VALUE'] == 'BINARY' && $image['ENCODING'] && $image['BINARY']) { $new_image = [ 'VALUE' => 'BINARY', 'ENCODING' => $image['ENCODING'], 'BINARY' => $image['BINARY'] ]; - } - else - { + } else { return; } $new_image['DISPLAY'] = isset($image['DISPLAY']) ? $image['DISPLAY'] : ''; @@ -288,7 +282,7 @@ public function getCustomHeaders() * Example: $customHeaders = array('X-WR-TIMEZONE' => 'America/New_York') * * @param array $customHeaders - * @return \Jsvrcek\ICS\Model\Calendar + * @return Calendar */ public function setCustomHeaders(array $customHeaders) { @@ -299,7 +293,7 @@ public function setCustomHeaders(array $customHeaders) /** * @param string $key * @param string $value - * @return \Jsvrcek\ICS\Model\Calendar + * @return Calendar */ public function addCustomHeader($key, $value) { @@ -308,7 +302,7 @@ public function addCustomHeader($key, $value) } /** - * @return \DateTimeZone + * @return DateTimeZone */ public function getTimezone() { @@ -316,10 +310,10 @@ public function getTimezone() } /** - * @param \DateTimeZone $timezone - * @return \Jsvrcek\ICS\Model\Calendar + * @param DateTimeZone $timezone + * @return Calendar */ - public function setTimezone(\DateTimeZone $timezone) + public function setTimezone(DateTimeZone $timezone) { $this->timezone = $timezone; return $this; @@ -335,7 +329,7 @@ public function getEvents() /** * @param CalendarEvent $event - * @return \Jsvrcek\ICS\Model\Calendar + * @return Calendar */ public function addEvent(CalendarEvent $event) { @@ -352,22 +346,22 @@ public function getTodos() } /** - * @param CalendarTodo $todo - * @return \Jsvrcek\ICS\Model\Calendar + * @param array $todos + * @return Calendar */ - public function addTodo(CalendarTodo $todo) + public function setTodos(array $todos) { - $this->todos[] = $todo; + $this->todos = $todos; return $this; } /** - * @param array $todos - * @return \Jsvrcek\ICS\Model\Calendar + * @param CalendarTodo $todo + * @return Calendar */ - public function setTodos(array $todos) + public function addTodo(CalendarTodo $todo) { - $this->todos = $todos; + $this->todos[] = $todo; return $this; } @@ -380,22 +374,22 @@ public function getFreeBusy() } /** - * @param CalendarFreeBusy $todo - * @return \Jsvrcek\ICS\Model\Calendar + * @param array $freeBusy + * @return Calendar */ - public function addFreeBusy(CalendarFreeBusy $todo) + public function setFreeBusy(array $freeBusy) { - $this->freeBusy[] = $todo; + $this->freeBusy = $freeBusy; return $this; } /** - * @param array $freeBusy - * @return \Jsvrcek\ICS\Model\Calendar + * @param CalendarFreeBusy $todo + * @return Calendar */ - public function setFreeBusy(array $freeBusy) + public function addFreeBusy(CalendarFreeBusy $todo) { - $this->freeBusy = $freeBusy; + $this->freeBusy[] = $todo; return $this; } @@ -407,12 +401,11 @@ public function getColor() return $this->color; } - /** * Set color as CSS3 string * * @param string $color - * @return \Jsvrcek\ICS\Model\Calendar + * @return Calendar */ public function setColor($color) { diff --git a/application/libraries/Ics_file.php b/application/libraries/Ics_file.php index fb9004462f..ff7067a002 100644 --- a/application/libraries/Ics_file.php +++ b/application/libraries/Ics_file.php @@ -28,10 +28,11 @@ * * An ICS file is a calendar file saved in a universal calendar format used by many email and calendar programs, * including Microsoft Outlook, Google Calendar, and Apple Calendar. - * + * * @package Libraries */ -class Ics_file { +class Ics_file +{ /** * @var EA_Controller|CI_Controller */ @@ -42,7 +43,7 @@ class Ics_file { */ public function __construct() { - $this->CI =& get_instance(); + $this->CI = &get_instance(); $this->CI->load->library('ics_provider'); $this->CI->load->library('ics_calendar'); @@ -79,10 +80,9 @@ public function get_stream(array $appointment, array $service, array $provider, ->setSummary($service['name']) ->setUid($appointment['id']); - if ( ! empty($service['location'])) - { + if (!empty($service['location'])) { $location = new Location(); - $location->setName((string)$service['location']); + $location->setName((string) $service['location']); $event->addLocation($location); } @@ -108,21 +108,21 @@ public function get_stream(array $appointment, array $service, array $provider, '', lang('notes'), '', - $appointment['notes'], + $appointment['notes'] ]; $event->setDescription(implode("\\n", $description)); $attendee = new Attendee(new Formatter()); - if (isset($customer['email']) && ! empty($customer['email'])) - { + if (isset($customer['email']) && !empty($customer['email'])) { $attendee->setValue($customer['email']); } // Add the event attendees. $attendee->setName($customer['first_name'] . ' ' . $customer['last_name']); - $attendee->setCalendarUserType('INDIVIDUAL') + $attendee + ->setCalendarUserType('INDIVIDUAL') ->setRole('REQ-PARTICIPANT') ->setParticipationStatus('NEEDS-ACTION') ->setRsvp('TRUE'); @@ -148,13 +148,13 @@ public function get_stream(array $appointment, array $service, array $provider, $attendee = new Attendee(new Formatter()); - if (isset($provider['email']) && ! empty($provider['email'])) - { + if (isset($provider['email']) && !empty($provider['email'])) { $attendee->setValue($provider['email']); } $attendee->setName($provider['first_name'] . ' ' . $provider['last_name']); - $attendee->setCalendarUserType('INDIVIDUAL') + $attendee + ->setCalendarUserType('INDIVIDUAL') ->setRole('REQ-PARTICIPANT') ->setParticipationStatus('ACCEPTED') ->setRsvp('FALSE'); @@ -163,9 +163,7 @@ public function get_stream(array $appointment, array $service, array $provider, // Set the organizer. $organizer = new Organizer(new Formatter()); - $organizer - ->setValue($provider['email']) - ->setName($provider['first_name'] . ' ' . $provider['last_name']); + $organizer->setValue($provider['email'])->setName($provider['first_name'] . ' ' . $provider['last_name']); $event->setOrganizer($organizer); @@ -178,7 +176,7 @@ public function get_stream(array $appointment, array $service, array $provider, ->addEvent($event); // Setup exporter. - $calendarExport = new CalendarExport(new CalendarStream, new Formatter()); + $calendarExport = new CalendarExport(new CalendarStream(), new Formatter()); $calendarExport->addCalendar($calendar); return $calendarExport->getStream(); diff --git a/application/libraries/Ics_provider.php b/application/libraries/Ics_provider.php index 717f4e5827..5675d28e8e 100644 --- a/application/libraries/Ics_provider.php +++ b/application/libraries/Ics_provider.php @@ -19,22 +19,20 @@ * Since the method signatures changed in PHP 8.1, the ReturnTypeWillChange attribute allows us to keep compatibility * between different PHP versions. */ -class Ics_provider implements \Iterator { - /** - * @var \Closure - */ - private $provider; - +class Ics_provider implements Iterator +{ /** * @var array */ public $data = []; - /** * @var array */ public $manuallyAddedData = []; - + /** + * @var Closure + */ + private $provider; /** * @var integer */ @@ -46,12 +44,12 @@ class Ics_provider implements \Iterator { private $first; /** - * @param \Closure $provider An optional closure for adding items in batches during iteration. The closure will be + * @param Closure $provider An optional closure for adding items in batches during iteration. The closure will be * called each time the end of the internal data array is reached during iteration, and the current data * array key value will be passed as an argument. The closure should return an array containing the next * batch of items. */ - public function __construct(\Closure $provider = NULL) + public function __construct(Closure $provider = null) { $this->provider = $provider; } @@ -111,35 +109,6 @@ public function rewind() $this->key = 0; } - /** - * get next batch from provider if data array is at the end - * - * @return bool - * @see Iterator::valid() - */ - #[ReturnTypeWillChange] - public function valid() - { - if (count($this->data) < 1) - { - if ($this->provider instanceof \Closure) - { - $this->data = $this->provider->__invoke($this->key); - if (isset($this->data[0])) - { - $this->first = $this->data[0]; - } - } - else - { - $this->data = $this->manuallyAddedData; - $this->manuallyAddedData = []; - } - } - - return count($this->data) > 0; - } - /** * Returns first event * @@ -148,28 +117,46 @@ public function valid() #[ReturnTypeWillChange] public function first() { - if (isset($this->first)) - { + if (isset($this->first)) { return $this->first; } - if ($this->provider instanceof \Closure) - { - if ($this->valid()) - { + if ($this->provider instanceof Closure) { + if ($this->valid()) { return $this->first; - } - else - { - return FALSE; + } else { + return false; } } - if ( ! isset($this->manuallyAddedData[0])) - { - return FALSE; + if (!isset($this->manuallyAddedData[0])) { + return false; } return $this->manuallyAddedData[0]; } + + /** + * get next batch from provider if data array is at the end + * + * @return bool + * @see Iterator::valid() + */ + #[ReturnTypeWillChange] + public function valid() + { + if (count($this->data) < 1) { + if ($this->provider instanceof Closure) { + $this->data = $this->provider->__invoke($this->key); + if (isset($this->data[0])) { + $this->first = $this->data[0]; + } + } else { + $this->data = $this->manuallyAddedData; + $this->manuallyAddedData = []; + } + } + + return count($this->data) > 0; + } } diff --git a/application/libraries/Instance.php b/application/libraries/Instance.php index 232853fe28..f74cd2a6c8 100644 --- a/application/libraries/Instance.php +++ b/application/libraries/Instance.php @@ -20,7 +20,8 @@ * * @package Libraries */ -class Instance { +class Instance +{ /** * @var EA_Controller|CI_Controller */ @@ -31,7 +32,7 @@ class Instance { */ public function __construct() { - $this->CI =& get_instance(); + $this->CI = &get_instance(); $this->CI->load->model('admins_model'); $this->CI->load->model('services_model'); @@ -51,33 +52,27 @@ public function migrate(string $type = ''): void { $current_version = $this->CI->migration->current_version(); - if ($type === 'up') - { - if ( ! $this->CI->migration->version($current_version + 1)) - { + if ($type === 'up') { + if (!$this->CI->migration->version($current_version + 1)) { show_error($this->CI->migration->error_string()); } return; } - if ($type === 'down') - { - if ( ! $this->CI->migration->version($current_version - 1)) - { + if ($type === 'down') { + if (!$this->CI->migration->version($current_version - 1)) { show_error($this->CI->migration->error_string()); } return; } - if ($type === 'fresh' && ! $this->CI->migration->version(0)) - { + if ($type === 'fresh' && !$this->CI->migration->version(0)) { show_error($this->CI->migration->error_string()); } - if ($this->CI->migration->latest() === FALSE) - { + if ($this->CI->migration->latest() === false) { show_error($this->CI->migration->error_string()); } } @@ -86,17 +81,17 @@ public function migrate(string $type = ''): void * Seed the database with test data. * * @return string Return's the administrator user password. - * + * * @throws Exception */ public function seed(): string { // Settings - + setting([ 'company_name' => 'Company Name', 'company_email' => 'info@example.org', - 'company_link' => 'https://example.org', + 'company_link' => 'https://example.org' ]); // Admin @@ -109,9 +104,9 @@ public function seed(): string 'settings' => [ 'username' => 'administrator', 'password' => 'administrator', - 'notifications' => TRUE, + 'notifications' => true, 'calendar_view' => CALENDAR_VIEW_DEFAULT - ], + ] ]); // Service @@ -132,20 +127,18 @@ public function seed(): string 'last_name' => 'Doe', 'email' => 'jane@example.org', 'phone_number' => '+10000000000', - 'services' => [ - $service_id - ], + 'services' => [$service_id], 'settings' => [ 'username' => 'janedoe', 'password' => random_string(), 'working_plan' => setting('company_working_plan'), 'working_plan_exceptions' => '{}', - 'notifications' => TRUE, - 'google_sync' => FALSE, + 'notifications' => true, + 'google_sync' => false, 'sync_past_days' => 30, 'sync_future_days' => 90, 'calendar_view' => CALENDAR_VIEW_DEFAULT - ], + ] ]); // Customer @@ -154,7 +147,7 @@ public function seed(): string 'first_name' => 'James', 'last_name' => 'Doe', 'email' => 'james@example.org', - 'phone_number' => '+10000000000', + 'phone_number' => '+10000000000' ]); return $password; @@ -167,17 +160,15 @@ public function seed(): string * * @throws Exception */ - public function backup(string $path = NULL): void + public function backup(string $path = null): void { $path = $path ?? APPPATH . '/../storage/backups'; - if ( ! file_exists($path)) - { + if (!file_exists($path)) { throw new InvalidArgumentException('The backup path does not exist: ' . $path); } - if ( ! is_writable($path)) - { + if (!is_writable($path)) { throw new RuntimeException('The backup path is not writable: ' . $path); } diff --git a/application/libraries/Notifications.php b/application/libraries/Notifications.php index 37cf95e007..9144121847 100644 --- a/application/libraries/Notifications.php +++ b/application/libraries/Notifications.php @@ -18,7 +18,8 @@ * * @package Libraries */ -class Notifications { +class Notifications +{ /** * @var EA_Controller|CI_Controller */ @@ -29,7 +30,7 @@ class Notifications { */ public function __construct() { - $this->CI =& get_instance(); + $this->CI = &get_instance(); $this->CI->load->model('admins_model'); $this->CI->load->model('appointments_model'); @@ -53,12 +54,16 @@ public function __construct() * @param array $settings Required settings. * @param bool|false $manage_mode Manage mode. */ - public function notify_appointment_saved(array $appointment, array $service, array $provider, array $customer, array $settings, bool $manage_mode = FALSE): void - { - try - { - if ($manage_mode) - { + public function notify_appointment_saved( + array $appointment, + array $service, + array $provider, + array $customer, + array $settings, + bool $manage_mode = false + ): void { + try { + if ($manage_mode) { $customer_subject = lang('appointment_details_changed'); $customer_message = ''; @@ -66,9 +71,7 @@ public function notify_appointment_saved(array $appointment, array $service, arr $provider_subject = lang('appointment_details_changed'); $provider_message = ''; - } - else - { + } else { $customer_subject = lang('appointment_booked'); $customer_message = lang('thank_you_for_appointment'); @@ -85,13 +88,10 @@ public function notify_appointment_saved(array $appointment, array $service, arr $ics_stream = $this->CI->ics_file->get_stream($appointment, $service, $provider, $customer); // Notify customer. - $send_customer = ! empty($customer['email']) && filter_var( - setting('customer_notifications'), - FILTER_VALIDATE_BOOLEAN - ); + $send_customer = + !empty($customer['email']) && filter_var(setting('customer_notifications'), FILTER_VALIDATE_BOOLEAN); - if ($send_customer === TRUE) - { + if ($send_customer === true) { $this->CI->email_messages->send_appointment_saved( $appointment, $provider, @@ -113,8 +113,7 @@ public function notify_appointment_saved(array $appointment, array $service, arr FILTER_VALIDATE_BOOLEAN ); - if ($send_provider === TRUE) - { + if ($send_provider === true) { $this->CI->email_messages->send_appointment_saved( $appointment, $provider, @@ -133,10 +132,8 @@ public function notify_appointment_saved(array $appointment, array $service, arr // Notify admins. $admins = $this->CI->admins_model->get(); - foreach ($admins as $admin) - { - if ($admin['settings']['notifications'] === '0') - { + foreach ($admins as $admin) { + if ($admin['settings']['notifications'] === '0') { continue; } @@ -158,15 +155,12 @@ public function notify_appointment_saved(array $appointment, array $service, arr // Notify secretaries. $secretaries = $this->CI->secretaries_model->get(); - foreach ($secretaries as $secretary) - { - if ($secretary['settings']['notifications'] === '0') - { + foreach ($secretaries as $secretary) { + if ($secretary['settings']['notifications'] === '0') { continue; } - if ( ! in_array($provider['id'], $secretary['providers'])) - { + if (!in_array($provider['id'], $secretary['providers'])) { continue; } @@ -184,10 +178,14 @@ public function notify_appointment_saved(array $appointment, array $service, arr $secretary['timezone'] ); } - } - catch (Throwable $e) - { - log_message('error', 'Notifications - Could not email confirmation details of appointment (' . ($appointment['id'] ?? '-') . ') : ' . $e->getMessage()); + } catch (Throwable $e) { + log_message( + 'error', + 'Notifications - Could not email confirmation details of appointment (' . + ($appointment['id'] ?? '-') . + ') : ' . + $e->getMessage() + ); log_message('error', $e->getTraceAsString()); } } @@ -201,18 +199,22 @@ public function notify_appointment_saved(array $appointment, array $service, arr * @param array $customer Customer data. * @param array $settings Required settings. */ - public function notify_appointment_deleted(array $appointment, array $service, array $provider, array $customer, array $settings, string $cancellation_reason = ''): void - { - try - { + public function notify_appointment_deleted( + array $appointment, + array $service, + array $provider, + array $customer, + array $settings, + string $cancellation_reason = '' + ): void { + try { // Notify provider. $send_provider = filter_var( $this->CI->providers_model->get_setting($provider['id'], 'notifications'), FILTER_VALIDATE_BOOLEAN ); - if ($send_provider === TRUE) - { + if ($send_provider === true) { $this->CI->email_messages->send_appointment_deleted( $appointment, $provider, @@ -226,13 +228,10 @@ public function notify_appointment_deleted(array $appointment, array $service, a } // Notify customer. - $send_customer = ! empty($customer['email']) && filter_var( - setting('customer_notifications'), - FILTER_VALIDATE_BOOLEAN - ); + $send_customer = + !empty($customer['email']) && filter_var(setting('customer_notifications'), FILTER_VALIDATE_BOOLEAN); - if ($send_customer === TRUE) - { + if ($send_customer === true) { $this->CI->email_messages->send_appointment_deleted( $appointment, $provider, @@ -248,10 +247,8 @@ public function notify_appointment_deleted(array $appointment, array $service, a // Notify admins. $admins = $this->CI->admins_model->get(); - foreach ($admins as $admin) - { - if ($admin['settings']['notifications'] === '0') - { + foreach ($admins as $admin) { + if ($admin['settings']['notifications'] === '0') { continue; } @@ -270,15 +267,12 @@ public function notify_appointment_deleted(array $appointment, array $service, a // Notify secretaries. $secretaries = $this->CI->secretaries_model->get(); - foreach ($secretaries as $secretary) - { - if ($secretary['settings']['notifications'] === '0') - { + foreach ($secretaries as $secretary) { + if ($secretary['settings']['notifications'] === '0') { continue; } - if ( ! in_array($provider['id'], $secretary['providers'])) - { + if (!in_array($provider['id'], $secretary['providers'])) { continue; } @@ -293,10 +287,14 @@ public function notify_appointment_deleted(array $appointment, array $service, a $secretary['timezone'] ); } - } - catch (Throwable $e) - { - log_message('error', 'Notifications - Could not email cancellation details of appointment (' . ($appointment['id'] ?? '-') . ') : ' . $e->getMessage()); + } catch (Throwable $e) { + log_message( + 'error', + 'Notifications - Could not email cancellation details of appointment (' . + ($appointment['id'] ?? '-') . + ') : ' . + $e->getMessage() + ); log_message('error', $e->getTraceAsString()); } } diff --git a/application/libraries/Permissions.php b/application/libraries/Permissions.php index 2dd12bab65..b9b64e5826 100644 --- a/application/libraries/Permissions.php +++ b/application/libraries/Permissions.php @@ -11,7 +11,6 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ - /** * Permissions library. * @@ -19,7 +18,8 @@ * * @package Libraries */ -class Permissions { +class Permissions +{ /** * @var EA_Controller|CI_Controller */ @@ -30,7 +30,7 @@ class Permissions { */ public function __construct() { - $this->CI =& get_instance(); + $this->CI = &get_instance(); $this->CI->load->model('appointments_model'); $this->CI->load->model('roles_model'); @@ -60,33 +60,37 @@ public function has_customer_access(int $user_id, int $customer_id): bool $limit_customer_access = setting('limit_customer_access'); - if ($role_slug === DB_SLUG_ADMIN || ! $limit_customer_access) - { - return TRUE; + if ($role_slug === DB_SLUG_ADMIN || !$limit_customer_access) { + return true; } - if ($role_slug === DB_SLUG_PROVIDER) - { - return $this->CI->appointments_model->query()->where(['id_users_provider' => $user_id, 'id_users_customer' => $customer_id])->get()->num_rows() > 0; + if ($role_slug === DB_SLUG_PROVIDER) { + return $this->CI->appointments_model + ->query() + ->where(['id_users_provider' => $user_id, 'id_users_customer' => $customer_id]) + ->get() + ->num_rows() > 0; } - if ($role_slug === DB_SLUG_SECRETARY) - { + if ($role_slug === DB_SLUG_SECRETARY) { $secretary = $this->CI->secretaries_model->find($user_id); - foreach ($secretary['providers'] as $secretary_provider_id) - { - $has_appointments_with_customer = $this->CI->appointments_model->query()->where(['id_users_provider' => $secretary_provider_id, 'id_users_customer' => $customer_id])->get()->num_rows() > 0; + foreach ($secretary['providers'] as $secretary_provider_id) { + $has_appointments_with_customer = + $this->CI->appointments_model + ->query() + ->where(['id_users_provider' => $secretary_provider_id, 'id_users_customer' => $customer_id]) + ->get() + ->num_rows() > 0; - if ($has_appointments_with_customer) - { - return TRUE; + if ($has_appointments_with_customer) { + return true; } } - return FALSE; + return false; } - return FALSE; + return false; } } diff --git a/application/libraries/Synchronization.php b/application/libraries/Synchronization.php index b1f460a026..fa874cf0c0 100644 --- a/application/libraries/Synchronization.php +++ b/application/libraries/Synchronization.php @@ -18,7 +18,8 @@ * * @package Libraries */ -class Synchronization { +class Synchronization +{ /** * @var EA_Controller|CI_Controller */ @@ -29,7 +30,7 @@ class Synchronization { */ public function __construct() { - $this->CI =& get_instance(); + $this->CI = &get_instance(); $this->CI->load->model('providers_model'); $this->CI->load->model('appointments_model'); @@ -46,26 +47,27 @@ public function __construct() * @param array $customer Customer record. * @param array $settings Required settings for the notification content. */ - public function sync_appointment_saved(array $appointment, array $service, array $provider, array $customer, array $settings): void - { - try - { - if ( ! $provider['settings']['google_sync']) - { + public function sync_appointment_saved( + array $appointment, + array $service, + array $provider, + array $customer, + array $settings + ): void { + try { + if (!$provider['settings']['google_sync']) { return; } - if (empty($provider['settings']['google_token'])) - { + if (empty($provider['settings']['google_token'])) { throw new RuntimeException('No google token available for the provider: ' . $provider['id']); } - $google_token = json_decode($provider['settings']['google_token'], TRUE); + $google_token = json_decode($provider['settings']['google_token'], true); $this->CI->google_sync->refresh_token($google_token['refresh_token']); - if (empty($appointment['id_google_calendar'])) - { + if (empty($appointment['id_google_calendar'])) { $google_event = $this->CI->google_sync->add_appointment( $appointment, $provider, @@ -77,55 +79,17 @@ public function sync_appointment_saved(array $appointment, array $service, array $appointment['id_google_calendar'] = $google_event->getId(); $this->CI->appointments_model->save($appointment); + } else { + $this->CI->google_sync->update_appointment($appointment, $provider, $service, $customer, $settings); } - else - { - $this->CI->google_sync->update_appointment( - $appointment, - $provider, - $service, - $customer, - $settings - ); - } - } - catch (Throwable $e) - { - log_message('error', 'Synchronization - Could not sync confirmation details of appointment (' . ($appointment['id'] ?? '-') . ') : ' . $e->getMessage()); - log_message('error', $e->getTraceAsString()); - } - } - - /** - * Synchronize removal of an appointment with external calendars. - * - * @param array $appointment Appointment record. - * @param array $provider Provider record. - */ - public function sync_appointment_deleted(array $appointment, array $provider): void - { - try - { - if ( ! $provider['settings']['google_sync'] || empty($appointment['id_google_calendar'])) - { - return; - } - - if (empty($provider['settings']['google_token'])) - { - throw new RuntimeException('No google token available for the provider: ' . $provider['id']); - } - - $google_token = json_decode($provider['settings']['google_token'], TRUE); - - $this->CI->google_sync->refresh_token($google_token['refresh_token']); - - $this->CI->google_sync->delete_appointment($provider, $appointment['id_google_calendar']); - - } - catch (Throwable $e) - { - log_message('error', 'Synchronization - Could not sync cancellation details of appointment (' . ($appointment['id'] ?? '-') . ') : ' . $e->getMessage()); + } catch (Throwable $e) { + log_message( + 'error', + 'Synchronization - Could not sync confirmation details of appointment (' . + ($appointment['id'] ?? '-') . + ') : ' . + $e->getMessage() + ); log_message('error', $e->getTraceAsString()); } } @@ -138,38 +102,36 @@ public function sync_appointment_deleted(array $appointment, array $provider): v */ public function sync_unavailability_saved(array $unavailability, array $provider): void { - try - { - if ( ! $provider['settings']['google_sync']) - { + try { + if (!$provider['settings']['google_sync']) { return; } - if (empty($provider['settings']['google_token'])) - { + if (empty($provider['settings']['google_token'])) { throw new RuntimeException('No google token available for the provider: ' . $provider['id']); } - $google_token = json_decode($provider['settings']['google_token'], TRUE); + $google_token = json_decode($provider['settings']['google_token'], true); $this->CI->google_sync->refresh_token($google_token['refresh_token']); - if (empty($unavailability['id_google_calendar'])) - { + if (empty($unavailability['id_google_calendar'])) { $google_event = $this->CI->google_sync->add_unavailability($provider, $unavailability); $unavailability['id_google_calendar'] = $google_event->getId(); $this->CI->unavailabilities_model->save($unavailability); - } - else - { + } else { $this->CI->google_sync->update_unavailability($provider, $unavailability); } - } - catch (Throwable $e) - { - log_message('error', 'Synchronization - Could not sync cancellation details of unavailability (' . ($appointment['id'] ?? '-') . ') : ' . $e->getMessage()); + } catch (Throwable $e) { + log_message( + 'error', + 'Synchronization - Could not sync cancellation details of unavailability (' . + ($appointment['id'] ?? '-') . + ') : ' . + $e->getMessage() + ); log_message('error', $e->getTraceAsString()); } } @@ -182,34 +144,35 @@ public function sync_unavailability_saved(array $unavailability, array $provider */ public function sync_unavailability_deleted(array $unavailability, array $provider): void { - try - { - if ( ! $provider['settings']['google_sync'] || empty($unavailability['id_google_calendar'])) - { + try { + if (!$provider['settings']['google_sync'] || empty($unavailability['id_google_calendar'])) { return; } - if (empty($provider['settings']['google_token'])) - { + if (empty($provider['settings']['google_token'])) { throw new RuntimeException('No google token available for the provider: ' . $provider['id']); } - $google_token = json_decode($provider['settings']['google_token'], TRUE); + $google_token = json_decode($provider['settings']['google_token'], true); $this->CI->google_sync->refresh_token($google_token['refresh_token']); $this->CI->google_sync->delete_unavailability($provider, $unavailability['id_google_calendar']); - } - catch (Throwable $e) - { - log_message('error', 'Synchronization - Could not sync cancellation details of unavailability (' . ($appointment['id'] ?? '-') . ') : ' . $e->getMessage()); + } catch (Throwable $e) { + log_message( + 'error', + 'Synchronization - Could not sync cancellation details of unavailability (' . + ($appointment['id'] ?? '-') . + ') : ' . + $e->getMessage() + ); log_message('error', $e->getTraceAsString()); } } /** - * Make sure a synced appointment is removed from Google Calendar, if its provider is changed. - * + * Make sure a synced appointment is removed from Google Calendar, if its provider is changed. + * * @throws Exception */ public function remove_appointment_on_provider_change($appointment_id): void @@ -220,14 +183,49 @@ public function remove_appointment_on_provider_change($appointment_id): void $existing_provider_id = $existing_appointment['id_users_provider']; - if ( ! empty($existing_google_id) && (int)$existing_provider_id !== (int)$existing_appointment['id_users_provider']) - { + if ( + !empty($existing_google_id) && + (int) $existing_provider_id !== (int) $existing_appointment['id_users_provider'] + ) { $existing_provider = $this->CI->providers_model->find($existing_provider_id); - if ($existing_provider['settings']['google_sync']) - { + if ($existing_provider['settings']['google_sync']) { $this->sync_appointment_deleted($existing_appointment, $existing_provider); } } } + + /** + * Synchronize removal of an appointment with external calendars. + * + * @param array $appointment Appointment record. + * @param array $provider Provider record. + */ + public function sync_appointment_deleted(array $appointment, array $provider): void + { + try { + if (!$provider['settings']['google_sync'] || empty($appointment['id_google_calendar'])) { + return; + } + + if (empty($provider['settings']['google_token'])) { + throw new RuntimeException('No google token available for the provider: ' . $provider['id']); + } + + $google_token = json_decode($provider['settings']['google_token'], true); + + $this->CI->google_sync->refresh_token($google_token['refresh_token']); + + $this->CI->google_sync->delete_appointment($provider, $appointment['id_google_calendar']); + } catch (Throwable $e) { + log_message( + 'error', + 'Synchronization - Could not sync cancellation details of appointment (' . + ($appointment['id'] ?? '-') . + ') : ' . + $e->getMessage() + ); + log_message('error', $e->getTraceAsString()); + } + } } diff --git a/application/libraries/Timezones.php b/application/libraries/Timezones.php index d041a53c33..d993362c7d 100644 --- a/application/libraries/Timezones.php +++ b/application/libraries/Timezones.php @@ -18,7 +18,8 @@ * * @package Libraries */ -class Timezones { +class Timezones +{ /** * @var EA_Controller|CI_Controller */ @@ -165,7 +166,7 @@ class Timezones { 'America/Sao_Paulo' => 'Sao_Paulo (-3:00)', 'America/Noronha' => 'Noronha (-2:00)', 'America/Scoresbysund' => 'Scoresbysund (-1:00)', - 'America/Danmarkshavn' => 'Danmarkshavn (+0:00)', + 'America/Danmarkshavn' => 'Danmarkshavn (+0:00)' ], 'Canada' => [ 'Canada/Pacific' => 'Pacific (-8:00)', @@ -176,16 +177,16 @@ class Timezones { 'Canada/Saskatchewan' => 'Saskatchewan (-6:00)', 'Canada/Eastern' => 'Eastern (-5:00)', 'Canada/Atlantic' => 'Atlantic (-4:00)', - 'Canada/Newfoundland' => 'Newfoundland (-3:-30)', + 'Canada/Newfoundland' => 'Newfoundland (-3:-30)' ], 'Mexico' => [ 'Mexico/BajaNorte' => 'BajaNorte (-8:00)', 'Mexico/BajaSur' => 'BajaSur (-7:00)', - 'Mexico/General' => 'General (-6:00)', + 'Mexico/General' => 'General (-6:00)' ], 'Chile' => [ 'Chile/EasterIsland' => 'EasterIsland (-6:00)', - 'Chile/Continental' => 'Continental (-4:00)', + 'Chile/Continental' => 'Continental (-4:00)' ], 'Antarctica' => [ 'Antarctica/Palmer' => 'Palmer (-4:00)', @@ -197,7 +198,7 @@ class Timezones { 'Antarctica/Casey' => 'Casey (+8:00)', 'Antarctica/DumontDUrville' => 'DumontDUrville (+10:00)', 'Antarctica/McMurdo' => 'McMurdo (+12:00)', - 'Antarctica/South_Pole' => 'South_Pole (+12:00)', + 'Antarctica/South_Pole' => 'South_Pole (+12:00)' ], 'Atlantic' => [ 'Atlantic/Bermuda' => 'Bermuda (-4:00)', @@ -211,13 +212,13 @@ class Timezones { 'Atlantic/Madeira' => 'Madeira (+0:00)', 'Atlantic/Reykjavik' => 'Reykjavik (+0:00)', 'Atlantic/St_Helena' => 'St_Helena (+0:00)', - 'Atlantic/Jan_Mayen' => 'Jan_Mayen (+1:00)', + 'Atlantic/Jan_Mayen' => 'Jan_Mayen (+1:00)' ], 'Brazil' => [ 'Brazil/Acre' => 'Acre (-4:00)', 'Brazil/West' => 'West (-4:00)', 'Brazil/East' => 'East (-3:00)', - 'Brazil/DeNoronha' => 'DeNoronha (-2:00)', + 'Brazil/DeNoronha' => 'DeNoronha (-2:00)' ], 'Africa' => [ 'Africa/Abidjan' => 'Abidjan (+0:00)', @@ -272,7 +273,7 @@ class Timezones { 'Africa/Kampala' => 'Kampala (+3:00)', 'Africa/Khartoum' => 'Khartoum (+3:00)', 'Africa/Mogadishu' => 'Mogadishu (+3:00)', - 'Africa/Nairobi' => 'Nairobi (+3:00)', + 'Africa/Nairobi' => 'Nairobi (+3:00)' ], 'Europe' => [ 'Europe/Belfast' => 'Belfast (+0:00)', @@ -332,10 +333,10 @@ class Timezones { 'Europe/Zaporozhye' => 'Zaporozhye (+2:00)', 'Europe/Moscow' => 'Moscow (+3:00)', 'Europe/Volgograd' => 'Volgograd (+3:00)', - 'Europe/Samara' => 'Samara (+4:00)', + 'Europe/Samara' => 'Samara (+4:00)' ], 'Arctic' => [ - 'Arctic/Longyearbyen' => 'Longyearbyen (+1:00)', + 'Arctic/Longyearbyen' => 'Longyearbyen (+1:00)' ], 'Asia' => [ 'Asia/Amman' => 'Amman (+2:00)', @@ -422,7 +423,7 @@ class Timezones { 'Asia/Vladivostok' => 'Vladivostok (+10:00)', 'Asia/Magadan' => 'Magadan (+11:00)', 'Asia/Anadyr' => 'Anadyr (+12:00)', - 'Asia/Kamchatka' => 'Kamchatka (+12:00)', + 'Asia/Kamchatka' => 'Kamchatka (+12:00)' ], 'Indian' => [ 'Indian/Antananarivo' => 'Antananarivo (+3:00)', @@ -435,7 +436,7 @@ class Timezones { 'Indian/Maldives' => 'Maldives (+5:00)', 'Indian/Chagos' => 'Chagos (+6:00)', 'Indian/Cocos' => 'Cocos (+6:30)', - 'Indian/Christmas' => 'Christmas (+7:00)', + 'Indian/Christmas' => 'Christmas (+7:00)' ], 'Australia' => [ 'Australia/Perth' => 'Perth (+8:00)', @@ -460,7 +461,7 @@ class Timezones { 'Australia/Tasmania' => 'Tasmania (+10:00)', 'Australia/Victoria' => 'Victoria (+10:00)', 'Australia/LHI' => 'LHI (+10:30)', - 'Australia/Lord_Howe' => 'Lord_Howe (+10:30)', + 'Australia/Lord_Howe' => 'Lord_Howe (+10:30)' ], 'Pacific' => [ 'Pacific/Apia' => 'Apia (+13:00)', @@ -498,8 +499,8 @@ class Timezones { 'Pacific/Tarawa' => 'Tarawa (+12:00)', 'Pacific/Tongatapu' => 'Tongatapu (+13:00)', 'Pacific/Wake' => 'Wake (+12:00)', - 'Pacific/Wallis' => 'Wallis (+12:00)', - ], + 'Pacific/Wallis' => 'Wallis (+12:00)' + ] ]; /** @@ -545,8 +546,7 @@ public function get_default_timezone(): string */ public function convert(string $value, string $from_timezone, string $to_timezone): string { - if ( ! $to_timezone || $from_timezone === $to_timezone) - { + if (!$to_timezone || $from_timezone === $to_timezone) { return $value; } @@ -572,7 +572,7 @@ public function get_timezone_name(string $value): ?string { $timezones = $this->to_array(); - return $timezones[$value] ?? NULL; + return $timezones[$value] ?? null; } /** diff --git a/application/libraries/Webhooks_client.php b/application/libraries/Webhooks_client.php index 8d4ad19c23..4bdec38e77 100644 --- a/application/libraries/Webhooks_client.php +++ b/application/libraries/Webhooks_client.php @@ -20,7 +20,8 @@ * * @package Libraries */ -class Webhooks_client { +class Webhooks_client +{ /** * @var EA_Controller|CI_Controller */ @@ -31,7 +32,7 @@ class Webhooks_client { */ public function __construct() { - $this->CI =& get_instance(); + $this->CI = &get_instance(); $this->CI->load->model('providers_model'); $this->CI->load->model('secretaries_model'); @@ -54,10 +55,8 @@ public function trigger(string $action, array $payload) { $webhooks = $this->CI->webhooks_model->get(); - foreach ($webhooks as $webhook) - { - if (str_contains($webhook['actions'], $action)) - { + foreach ($webhooks as $webhook) { + if (str_contains($webhook['actions'], $action)) { $this->call($webhook, $action, $payload); } } @@ -72,8 +71,7 @@ public function trigger(string $action, array $payload) */ private function call(array $webhook, string $action, array $payload): void { - try - { + try { $client = new Client(); $client->post($webhook['url'], [ @@ -83,10 +81,14 @@ private function call(array $webhook, string $action, array $payload): void 'payload' => $payload ] ]); - } - catch (Throwable $e) - { - log_message('error', 'Webhooks Client - The webhook (' . ($webhook['id'] ?? NULL) . ') request received an unexpected exception: ' . $e->getMessage()); + } catch (Throwable $e) { + log_message( + 'error', + 'Webhooks Client - The webhook (' . + ($webhook['id'] ?? null) . + ') request received an unexpected exception: ' . + $e->getMessage() + ); log_message('error', $e->getTraceAsString()); } } diff --git a/application/libraries/index.html b/application/libraries/index.html index c942a79ce6..423d9d580e 100644 --- a/application/libraries/index.html +++ b/application/libraries/index.html @@ -1,10 +1,10 @@ - 403 Forbidden + 403 Forbidden

Directory access is forbidden.

- \ No newline at end of file + diff --git a/application/migrations/001_specific_calendar_sync.php b/application/migrations/001_specific_calendar_sync.php index d5cbf0b17a..f71ffe185e 100644 --- a/application/migrations/001_specific_calendar_sync.php +++ b/application/migrations/001_specific_calendar_sync.php @@ -16,7 +16,8 @@ * SQL are not required. */ -class Migration_Specific_calendar_sync extends EA_Migration { +class Migration_Specific_calendar_sync extends EA_Migration +{ /** * Upgrade method. */ @@ -26,28 +27,28 @@ public function up() 'id' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, - 'auto_increment' => TRUE + 'unsigned' => true, + 'auto_increment' => true ], 'book_datetime' => [ 'type' => 'DATETIME', - 'null' => TRUE, + 'null' => true ], 'start_datetime' => [ 'type' => 'DATETIME', - 'null' => TRUE, + 'null' => true ], 'end_datetime' => [ 'type' => 'DATETIME', - 'null' => TRUE, + 'null' => true ], 'notes' => [ 'type' => 'TEXT', - 'null' => TRUE, + 'null' => true ], 'hash' => [ 'type' => 'TEXT', - 'null' => TRUE, + 'null' => true ], 'is_unavailability' => [ 'type' => 'TINYINT', @@ -57,415 +58,480 @@ public function up() 'id_users_provider' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, - 'null' => TRUE + 'unsigned' => true, + 'null' => true ], 'id_users_customer' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, - 'null' => TRUE + 'unsigned' => true, + 'null' => true ], 'id_services' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, - 'null' => TRUE + 'unsigned' => true, + 'null' => true ], 'id_google_calendar' => [ 'type' => 'TEXT', - 'null' => TRUE - ], + 'null' => true + ] ]); - $this->dbforge->add_key('id', TRUE); + $this->dbforge->add_key('id', true); $this->dbforge->add_key('id_users_provider'); $this->dbforge->add_key('id_users_customer'); $this->dbforge->add_key('id_services'); - $this->dbforge->create_table('appointments', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->create_table('appointments', true, ['engine' => 'InnoDB']); $this->dbforge->add_field([ 'id' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, - 'auto_increment' => TRUE + 'unsigned' => true, + 'auto_increment' => true ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE + 'null' => true ], 'slug' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE + 'null' => true ], 'is_admin' => [ 'type' => 'TINYINT', 'constraint' => '4', - 'null' => TRUE + 'null' => true ], 'appointments' => [ 'type' => 'INT', 'constraint' => '4', - 'null' => TRUE + 'null' => true ], 'customers' => [ 'type' => 'INT', 'constraint' => '4', - 'null' => TRUE + 'null' => true ], 'services' => [ 'type' => 'INT', 'constraint' => '4', - 'null' => TRUE + 'null' => true ], 'users' => [ 'type' => 'INT', 'constraint' => '4', - 'null' => TRUE + 'null' => true ], 'system_settings' => [ 'type' => 'INT', 'constraint' => '4', - 'null' => TRUE + 'null' => true ], 'user_settings' => [ 'type' => 'INT', 'constraint' => '4', - 'null' => TRUE - ], + 'null' => true + ] ]); - $this->dbforge->add_key('id', TRUE); - $this->dbforge->create_table('roles', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->add_key('id', true); + $this->dbforge->create_table('roles', true, ['engine' => 'InnoDB']); $this->dbforge->add_field([ 'id_users_secretary' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, + 'unsigned' => true ], 'id_users_provider' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, + 'unsigned' => true ] ]); - $this->dbforge->add_key('id_users_secretary', TRUE); - $this->dbforge->add_key('id_users_provider', TRUE); - $this->dbforge->create_table('secretaries_providers', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->add_key('id_users_secretary', true); + $this->dbforge->add_key('id_users_provider', true); + $this->dbforge->create_table('secretaries_providers', true, ['engine' => 'InnoDB']); $this->dbforge->add_field([ 'id' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, - 'auto_increment' => TRUE + 'unsigned' => true, + 'auto_increment' => true ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE + 'null' => true ], 'duration' => [ 'type' => 'INT', 'constraint' => '11', - 'null' => TRUE + 'null' => true ], 'price' => [ 'type' => 'DECIMAL', 'constraint' => '10,2', - 'null' => TRUE + 'null' => true ], 'currency' => [ 'type' => 'VARCHAR', 'constraint' => '32', - 'null' => TRUE + 'null' => true ], 'description' => [ 'type' => 'TEXT', - 'null' => TRUE + 'null' => true ], 'id_service_categories' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, - 'null' => TRUE - ], + 'unsigned' => true, + 'null' => true + ] ]); - $this->dbforge->add_key('id', TRUE); + $this->dbforge->add_key('id', true); $this->dbforge->add_key('id_service_categories'); - $this->dbforge->create_table('services', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->create_table('services', true, ['engine' => 'InnoDB']); $this->dbforge->add_field([ 'id_users' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, + 'unsigned' => true ], 'id_services' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, + 'unsigned' => true ] ]); - $this->dbforge->add_key('id_users', TRUE); - $this->dbforge->add_key('id_services', TRUE); - $this->dbforge->create_table('services_providers', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->add_key('id_users', true); + $this->dbforge->add_key('id_services', true); + $this->dbforge->create_table('services_providers', true, ['engine' => 'InnoDB']); $this->dbforge->add_field([ 'id' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, - 'auto_increment' => TRUE + 'unsigned' => true, + 'auto_increment' => true ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE + 'null' => true ], 'description' => [ 'type' => 'TEXT', - 'null' => TRUE - ], + 'null' => true + ] ]); - $this->dbforge->add_key('id', TRUE); + $this->dbforge->add_key('id', true); $this->dbforge->add_key('id_service_categories'); - $this->dbforge->create_table('service_categories', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->create_table('service_categories', true, ['engine' => 'InnoDB']); $this->dbforge->add_field([ 'id' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, - 'auto_increment' => TRUE + 'unsigned' => true, + 'auto_increment' => true ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '512', - 'null' => TRUE + 'null' => true ], 'value' => [ 'type' => 'LONGTEXT', - 'null' => TRUE - ], + 'null' => true + ] ]); - $this->dbforge->add_key('id', TRUE); - $this->dbforge->create_table('settings', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->add_key('id', true); + $this->dbforge->create_table('settings', true, ['engine' => 'InnoDB']); $this->dbforge->add_field([ 'id' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, - 'auto_increment' => TRUE + 'unsigned' => true, + 'auto_increment' => true ], 'first_name' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE + 'null' => true ], 'last_name' => [ 'type' => 'VARCHAR', 'constraint' => '512', - 'null' => TRUE + 'null' => true ], 'email' => [ 'type' => 'VARCHAR', 'constraint' => '512', - 'null' => TRUE + 'null' => true ], 'mobile_number' => [ 'type' => 'VARCHAR', 'constraint' => '128', - 'null' => TRUE + 'null' => true ], 'phone_number' => [ 'type' => 'VARCHAR', 'constraint' => '128', - 'null' => TRUE + 'null' => true ], 'address' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE + 'null' => true ], 'city' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE + 'null' => true ], 'state' => [ 'type' => 'VARCHAR', 'constraint' => '128', - 'null' => TRUE + 'null' => true ], 'zip_code' => [ 'type' => 'VARCHAR', 'constraint' => '64', - 'null' => TRUE + 'null' => true ], 'notes' => [ 'type' => 'TEXT', - 'null' => TRUE + 'null' => true ], 'id_roles' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE - ], + 'unsigned' => true + ] ]); - $this->dbforge->add_key('id', TRUE); + $this->dbforge->add_key('id', true); $this->dbforge->add_key('id_roles'); - $this->dbforge->create_table('users', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->create_table('users', true, ['engine' => 'InnoDB']); $this->dbforge->add_field([ 'id_users' => [ 'type' => 'BIGINT', 'constraint' => '20', - 'unsigned' => TRUE, + 'unsigned' => true ], 'username' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE + 'null' => true ], 'password' => [ 'type' => 'VARCHAR', 'constraint' => '512', - 'null' => TRUE + 'null' => true ], 'salt' => [ 'type' => 'VARCHAR', 'constraint' => '512', - 'null' => TRUE + 'null' => true ], 'working_plan' => [ 'type' => 'TEXT', - 'null' => TRUE + 'null' => true ], 'notifications' => [ 'type' => 'TINYINT', 'constraint' => '4', - 'null' => TRUE + 'null' => true ], 'google_sync' => [ 'type' => 'TINYINT', 'constraint' => '4', - 'null' => TRUE + 'null' => true ], 'google_token' => [ 'type' => 'TEXT', - 'null' => TRUE + 'null' => true ], 'google_calendar' => [ 'type' => 'VARCHAR', 'constraint' => '128', - 'null' => TRUE + 'null' => true ], 'sync_past_days' => [ 'type' => 'INT', 'constraint' => '11', - 'null' => TRUE, + 'null' => true, 'default' => '5' ], 'sync_future_days' => [ 'type' => 'INT', 'constraint' => '11', - 'null' => TRUE, + 'null' => true, 'default' => '5' - ], + ] ]); - $this->dbforge->add_key('id_users', TRUE); - $this->dbforge->create_table('user_settings', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->add_key('id_users', true); + $this->dbforge->create_table('user_settings', true, ['engine' => 'InnoDB']); - $this->db->query(' - ALTER TABLE `' . $this->db->dbprefix('appointments') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_2` FOREIGN KEY (`id_users_customer`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_3` FOREIGN KEY (`id_services`) REFERENCES `' . $this->db->dbprefix('services') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_4` FOREIGN KEY (`id_users_provider`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; - '); + $this->db->query( + ' + ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_2` FOREIGN KEY (`id_users_customer`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_3` FOREIGN KEY (`id_services`) REFERENCES `' . + $this->db->dbprefix('services') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_4` FOREIGN KEY (`id_users_provider`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; + ' + ); - $this->db->query(' - ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` - ADD CONSTRAINT `fk_' . $this->db->dbprefix('secretaries_providers') . '_1` FOREIGN KEY (`id_users_secretary`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `fk_' . $this->db->dbprefix('secretaries_providers') . '_2` FOREIGN KEY (`id_users_provider`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; - '); + $this->db->query( + ' + ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` + ADD CONSTRAINT `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_1` FOREIGN KEY (`id_users_secretary`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_2` FOREIGN KEY (`id_users_provider`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; + ' + ); - $this->db->query(' - ALTER TABLE `' . $this->db->dbprefix('services') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('services') . '_ibfk_1` FOREIGN KEY (`id_service_categories`) REFERENCES `' . $this->db->dbprefix('service_categories') . '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; - '); + $this->db->query( + ' + ALTER TABLE `' . + $this->db->dbprefix('services') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('services') . + '_ibfk_1` FOREIGN KEY (`id_service_categories`) REFERENCES `' . + $this->db->dbprefix('service_categories') . + '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE; + ' + ); - $this->db->query(' - ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('services_providers') . '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('services_providers') . '_ibfk_2` FOREIGN KEY (`id_services`) REFERENCES `' . $this->db->dbprefix('services') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; - '); + $this->db->query( + ' + ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('services_providers') . + '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('services_providers') . + '_ibfk_2` FOREIGN KEY (`id_services`) REFERENCES `' . + $this->db->dbprefix('services') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; + ' + ); - $this->db->query(' - ALTER TABLE `' . $this->db->dbprefix('users') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('users') . '_ibfk_1` FOREIGN KEY (`id_roles`) REFERENCES `' . $this->db->dbprefix('roles') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; - '); + $this->db->query( + ' + ALTER TABLE `' . + $this->db->dbprefix('users') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('users') . + '_ibfk_1` FOREIGN KEY (`id_roles`) REFERENCES `' . + $this->db->dbprefix('roles') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; + ' + ); - $this->db->query(' - ALTER TABLE `' . $this->db->dbprefix('user_settings') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('user_settings') . '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; + $this->db->query( + ' + ALTER TABLE `' . + $this->db->dbprefix('user_settings') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('user_settings') . + '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; - '); + ' + ); $this->db->insert('roles', [ 'name' => 'Administrator', 'slug' => 'admin', - 'is_admin' => TRUE, + 'is_admin' => true, 'appointments' => 15, 'customers' => 15, 'services' => 15, 'users' => 15, 'system_settings' => 15, - 'user_settings' => 15, + 'user_settings' => 15 ]); $this->db->insert('roles', [ 'name' => 'Provider', 'slug' => 'provider', - 'is_admin' => FALSE, + 'is_admin' => false, 'appointments' => 15, 'customers' => 15, 'services' => 0, 'users' => 0, 'system_settings' => 0, - 'user_settings' => 15, + 'user_settings' => 15 ]); $this->db->insert('roles', [ 'name' => 'Customer', 'slug' => 'customer', - 'is_admin' => FALSE, + 'is_admin' => false, 'appointments' => 0, 'customers' => 0, 'services' => 0, 'users' => 0, 'system_settings' => 0, - 'user_settings' => 0, + 'user_settings' => 0 ]); $this->db->insert('roles', [ 'name' => 'Secretary', 'slug' => 'secretary', - 'is_admin' => FALSE, + 'is_admin' => false, 'appointments' => 15, 'customers' => 15, 'services' => 0, 'users' => 0, 'system_settings' => 0, - 'user_settings' => 15, + 'user_settings' => 15 ]); $this->db->insert('settings', [ 'name' => 'company_working_plan', - 'value' => '{"monday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"tuesday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"wednesday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"thursday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"friday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"saturday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"sunday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]}}' + 'value' => + '{"monday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"tuesday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"wednesday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"thursday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"friday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"saturday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]},"sunday":{"start":"09:00","end":"18:00","breaks":[{"start":"14:30","end":"15:00"}]}}' ]); $this->db->insert('settings', [ @@ -479,16 +545,76 @@ public function up() */ public function down() { - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_3`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_4`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` DROP FOREIGN KEY `fk_' . $this->db->dbprefix('secretaries_providers') . '_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` DROP FOREIGN KEY `fk_' . $this->db->dbprefix('secretaries_providers') . '_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services_providers') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services_providers') . '_ibfk_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('users') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('users') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('user_settings') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('user_settings') . '_ibfk_1`'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_3`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_4`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` DROP FOREIGN KEY `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` DROP FOREIGN KEY `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services_providers') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services_providers') . + '_ibfk_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('users') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('users') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('user_settings') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('user_settings') . + '_ibfk_1`' + ); $this->dbforge->drop_table('appointments'); $this->dbforge->drop_table('roles'); diff --git a/application/migrations/002_add_google_analytics_setting.php b/application/migrations/002_add_google_analytics_setting.php index 8cc462cbc9..fb93bdcaeb 100644 --- a/application/migrations/002_add_google_analytics_setting.php +++ b/application/migrations/002_add_google_analytics_setting.php @@ -11,7 +11,8 @@ * @since v1.1.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_google_analytics_setting extends EA_Migration { +class Migration_Add_google_analytics_setting extends EA_Migration +{ /** * Upgrade method. * @@ -19,8 +20,7 @@ class Migration_Add_google_analytics_setting extends EA_Migration { */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'google_analytics_code'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'google_analytics_code'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'google_analytics_code', 'value' => '' @@ -35,8 +35,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'google_analytics_code'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'google_analytics_code'])->num_rows()) { $this->db->delete('settings', ['name' => 'google_analytics_code']); } } diff --git a/application/migrations/003_add_customer_notifications_setting.php b/application/migrations/003_add_customer_notifications_setting.php index 19e2f5e1a3..ea86bbdb44 100644 --- a/application/migrations/003_add_customer_notifications_setting.php +++ b/application/migrations/003_add_customer_notifications_setting.php @@ -11,7 +11,8 @@ * @since v1.1.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_customer_notifications_setting extends EA_Migration { +class Migration_Add_customer_notifications_setting extends EA_Migration +{ /** * Upgrade method. * @@ -19,8 +20,7 @@ class Migration_Add_customer_notifications_setting extends EA_Migration { */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'customer_notifications'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'customer_notifications'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'customer_notifications', 'value' => '1' @@ -35,8 +35,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'customer_notifications'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'customer_notifications'])->num_rows()) { $this->db->delete('settings', ['name' => 'customer_notifications']); } } diff --git a/application/migrations/004_add_date_format_setting.php b/application/migrations/004_add_date_format_setting.php index 5ac8a08368..b5594678da 100644 --- a/application/migrations/004_add_date_format_setting.php +++ b/application/migrations/004_add_date_format_setting.php @@ -11,7 +11,8 @@ * @since v1.1.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_date_format_setting extends EA_Migration { +class Migration_Add_date_format_setting extends EA_Migration +{ /** * Upgrade method. * @@ -19,8 +20,7 @@ class Migration_Add_date_format_setting extends EA_Migration { */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'date_format'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'date_format'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'date_format', 'value' => 'DMY' @@ -35,8 +35,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'date_format'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'date_format'])->num_rows()) { $this->db->delete('settings', ['name' => 'date_format']); } } diff --git a/application/migrations/005_add_require_captcha_setting.php b/application/migrations/005_add_require_captcha_setting.php index 14e8e21288..c27ccb1f0a 100644 --- a/application/migrations/005_add_require_captcha_setting.php +++ b/application/migrations/005_add_require_captcha_setting.php @@ -11,7 +11,8 @@ * @since v1.1.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_require_captcha_setting extends EA_Migration { +class Migration_Add_require_captcha_setting extends EA_Migration +{ /** * Upgrade method. * @@ -19,8 +20,7 @@ class Migration_Add_require_captcha_setting extends EA_Migration { */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'require_captcha'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'require_captcha'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'require_captcha', 'value' => '0' @@ -35,8 +35,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'require_captcha'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'require_captcha'])->num_rows()) { $this->db->delete('settings', ['name' => 'require_captcha']); } } diff --git a/application/migrations/006_add_calendar_view_setting.php b/application/migrations/006_add_calendar_view_setting.php index 08a78c26b9..6d87a9e0c0 100644 --- a/application/migrations/006_add_calendar_view_setting.php +++ b/application/migrations/006_add_calendar_view_setting.php @@ -11,14 +11,14 @@ * @since v1.2.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_calendar_view_setting extends EA_Migration { +class Migration_Add_calendar_view_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('calendar_view', 'user_settings')) - { + if (!$this->db->field_exists('calendar_view', 'user_settings')) { $fields = [ 'calendar_view' => [ 'type' => 'VARCHAR', @@ -38,8 +38,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('calendar_view', 'user_settings')) - { + if ($this->db->field_exists('calendar_view', 'user_settings')) { $this->dbforge->drop_column('user_settings', 'calendar_view'); } } diff --git a/application/migrations/007_add_service_availabilities_type.php b/application/migrations/007_add_service_availabilities_type.php index b6648cd28a..1399d78dd9 100644 --- a/application/migrations/007_add_service_availabilities_type.php +++ b/application/migrations/007_add_service_availabilities_type.php @@ -11,14 +11,14 @@ * @since v1.2.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_service_availabilities_type extends EA_Migration { +class Migration_Add_service_availabilities_type extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('availabilities_type', 'services')) - { + if (!$this->db->field_exists('availabilities_type', 'services')) { $fields = [ 'availabilities_type' => [ 'type' => 'VARCHAR', @@ -39,8 +39,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('availabilities_type', 'services')) - { + if ($this->db->field_exists('availabilities_type', 'services')) { $this->dbforge->drop_column('services', 'availabilities_type'); } } diff --git a/application/migrations/008_add_service_attendants_number.php b/application/migrations/008_add_service_attendants_number.php index e209694e91..6b5d38b451 100644 --- a/application/migrations/008_add_service_attendants_number.php +++ b/application/migrations/008_add_service_attendants_number.php @@ -11,14 +11,14 @@ * @since v1.2.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_service_attendants_number extends EA_Migration { +class Migration_Add_service_attendants_number extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('attendants_number', 'services')) - { + if (!$this->db->field_exists('attendants_number', 'services')) { $fields = [ 'attendants_number' => [ 'type' => 'INT', @@ -37,8 +37,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('attendants_number', 'services')) - { + if ($this->db->field_exists('attendants_number', 'services')) { $this->dbforge->drop_column('services', 'attendants_number'); } } diff --git a/application/migrations/009_change_column_types.php b/application/migrations/009_change_column_types.php index beeb25ca2e..24fc2c50aa 100644 --- a/application/migrations/009_change_column_types.php +++ b/application/migrations/009_change_column_types.php @@ -11,23 +11,84 @@ * @since v1.3.0 * ---------------------------------------------------------------------------- */ -class Migration_Change_column_types extends EA_Migration { +class Migration_Change_column_types extends EA_Migration +{ /** * Upgrade method. */ public function up() { // Drop table constraints. - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_3`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_4`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` DROP FOREIGN KEY `fk_' . $this->db->dbprefix('secretaries_providers') . '_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` DROP FOREIGN KEY `fk_' . $this->db->dbprefix('secretaries_providers') . '_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services_providers') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services_providers') . '_ibfk_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('users') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('users') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('user_settings') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('user_settings') . '_ibfk_1`'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_3`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_4`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` DROP FOREIGN KEY `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` DROP FOREIGN KEY `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services_providers') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services_providers') . + '_ibfk_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('users') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('users') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('user_settings') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('user_settings') . + '_ibfk_1`' + ); // Appointments $fields = [ @@ -35,7 +96,7 @@ public function up() 'name' => 'id', 'type' => 'int', 'constraint' => '11', - 'auto_increment' => TRUE + 'auto_increment' => true ], 'id_users_provider' => [ 'name' => 'id_users_provider', @@ -62,7 +123,7 @@ public function up() 'name' => 'id', 'type' => 'int', 'constraint' => '11', - 'auto_increment' => TRUE + 'auto_increment' => true ], 'appointments' => [ 'name' => 'appointments', @@ -120,7 +181,7 @@ public function up() 'name' => 'id', 'type' => 'int', 'constraint' => '11', - 'auto_increment' => TRUE + 'auto_increment' => true ], 'id_service_categories' => [ 'name' => 'id_service_categories', @@ -153,7 +214,7 @@ public function up() 'name' => 'id', 'type' => 'int', 'constraint' => '11', - 'auto_increment' => TRUE + 'auto_increment' => true ] ]; @@ -165,7 +226,7 @@ public function up() 'name' => 'id', 'type' => 'int', 'constraint' => '11', - 'auto_increment' => TRUE + 'auto_increment' => true ] ]; @@ -177,7 +238,7 @@ public function up() 'name' => 'id', 'type' => 'int', 'constraint' => '11', - 'auto_increment' => TRUE + 'auto_increment' => true ], 'id_roles' => [ 'name' => 'id_roles', @@ -200,30 +261,96 @@ public function up() $this->dbforge->modify_column('user_settings', $fields); // Add table constraints again. - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_2` FOREIGN KEY (`id_users_customer`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_3` FOREIGN KEY (`id_services`) REFERENCES `' . $this->db->dbprefix('services') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_4` FOREIGN KEY (`id_users_provider`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); - - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` - ADD CONSTRAINT `fk_' . $this->db->dbprefix('secretaries_providers') . '_1` FOREIGN KEY (`id_users_secretary`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `fk_' . $this->db->dbprefix('secretaries_providers') . '_2` FOREIGN KEY (`id_users_provider`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); - - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('services') . '_ibfk_1` FOREIGN KEY (`id_service_categories`) REFERENCES `' . $this->db->dbprefix('service_categories') . '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE'); - - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('services_providers') . '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('services_providers') . '_ibfk_2` FOREIGN KEY (`id_services`) REFERENCES `' . $this->db->dbprefix('services') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); - - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('users') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('users') . '_ibfk_1` FOREIGN KEY (`id_roles`) REFERENCES `' . $this->db->dbprefix('roles') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); - - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('user_settings') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('user_settings') . '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_2` FOREIGN KEY (`id_users_customer`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_3` FOREIGN KEY (`id_services`) REFERENCES `' . + $this->db->dbprefix('services') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_4` FOREIGN KEY (`id_users_provider`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); + + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` + ADD CONSTRAINT `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_1` FOREIGN KEY (`id_users_secretary`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_2` FOREIGN KEY (`id_users_provider`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); + + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('services') . + '_ibfk_1` FOREIGN KEY (`id_service_categories`) REFERENCES `' . + $this->db->dbprefix('service_categories') . + '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE' + ); + + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('services_providers') . + '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('services_providers') . + '_ibfk_2` FOREIGN KEY (`id_services`) REFERENCES `' . + $this->db->dbprefix('services') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); + + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('users') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('users') . + '_ibfk_1` FOREIGN KEY (`id_roles`) REFERENCES `' . + $this->db->dbprefix('roles') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); + + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('user_settings') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('user_settings') . + '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); // Change charset of ' . $this->db->dbprefix('secretaries_providers') . ' table for databases created with EA! 1.2.1 version - $this->db->query('ALTER TABLE ' . $this->db->dbprefix('secretaries_providers') . ' CONVERT TO CHARACTER SET utf8'); + $this->db->query( + 'ALTER TABLE ' . $this->db->dbprefix('secretaries_providers') . ' CONVERT TO CHARACTER SET utf8' + ); } /** @@ -232,16 +359,76 @@ public function up() public function down() { // Drop table constraints. - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_3`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_4`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` DROP FOREIGN KEY `fk_' . $this->db->dbprefix('secretaries_providers') . '_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` DROP FOREIGN KEY `fk_' . $this->db->dbprefix('secretaries_providers') . '_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services_providers') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services_providers') . '_ibfk_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('users') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('users') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('user_settings') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('user_settings') . '_ibfk_1`'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_3`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_4`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` DROP FOREIGN KEY `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` DROP FOREIGN KEY `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services_providers') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services_providers') . + '_ibfk_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('users') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('users') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('user_settings') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('user_settings') . + '_ibfk_1`' + ); // Appointments $fields = [ @@ -249,7 +436,7 @@ public function down() 'name' => 'id', 'type' => 'bigint', 'constraint' => '20', - 'auto_increment' => TRUE + 'auto_increment' => true ], 'id_users_provider' => [ 'name' => 'id_users_provider', @@ -276,7 +463,7 @@ public function down() 'name' => 'id', 'type' => 'bigint', 'constraint' => '20', - 'auto_increment' => TRUE + 'auto_increment' => true ], 'appointments' => [ 'name' => 'appointments', @@ -334,7 +521,7 @@ public function down() 'name' => 'id', 'type' => 'bigint', 'constraint' => '20', - 'auto_increment' => TRUE + 'auto_increment' => true ], 'id_service_categories' => [ 'name' => 'id_service_categories', @@ -367,7 +554,7 @@ public function down() 'name' => 'id', 'type' => 'bigint', 'constraint' => '20', - 'auto_increment' => TRUE + 'auto_increment' => true ] ]; @@ -379,7 +566,7 @@ public function down() 'name' => 'id', 'type' => 'bigint', 'constraint' => '20', - 'auto_increment' => TRUE + 'auto_increment' => true ] ]; @@ -391,7 +578,7 @@ public function down() 'name' => 'id', 'type' => 'bigint', 'constraint' => '20', - 'auto_increment' => TRUE + 'auto_increment' => true ], 'id_roles' => [ 'name' => 'id_roles', @@ -414,26 +601,90 @@ public function down() $this->dbforge->modify_column('user_settings', $fields); // Add database constraints. - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_2` FOREIGN KEY (`id_users_customer`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_3` FOREIGN KEY (`id_services`) REFERENCES `' . $this->db->dbprefix('services') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_4` FOREIGN KEY (`id_users_provider`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); - - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` - ADD CONSTRAINT `fk_' . $this->db->dbprefix('secretaries_providers') . '_1` FOREIGN KEY (`id_users_secretary`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `fk_' . $this->db->dbprefix('secretaries_providers') . '_2` FOREIGN KEY (`id_users_provider`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); - - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('services') . '_ibfk_1` FOREIGN KEY (`id_service_categories`) REFERENCES `' . $this->db->dbprefix('service_categories') . '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE'); - - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('services_providers') . '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('services_providers') . '_ibfk_2` FOREIGN KEY (`id_services`) REFERENCES `' . $this->db->dbprefix('services') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); - - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('users') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('users') . '_ibfk_1` FOREIGN KEY (`id_roles`) REFERENCES `' . $this->db->dbprefix('roles') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); - - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('user_settings') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('user_settings') . '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_2` FOREIGN KEY (`id_users_customer`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_3` FOREIGN KEY (`id_services`) REFERENCES `' . + $this->db->dbprefix('services') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_4` FOREIGN KEY (`id_users_provider`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); + + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` + ADD CONSTRAINT `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_1` FOREIGN KEY (`id_users_secretary`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_2` FOREIGN KEY (`id_users_provider`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); + + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('services') . + '_ibfk_1` FOREIGN KEY (`id_service_categories`) REFERENCES `' . + $this->db->dbprefix('service_categories') . + '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE' + ); + + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('services_providers') . + '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('services_providers') . + '_ibfk_2` FOREIGN KEY (`id_services`) REFERENCES `' . + $this->db->dbprefix('services') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); + + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('users') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('users') . + '_ibfk_1` FOREIGN KEY (`id_roles`) REFERENCES `' . + $this->db->dbprefix('roles') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); + + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('user_settings') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('user_settings') . + '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); } } diff --git a/application/migrations/010_add_time_format_setting.php b/application/migrations/010_add_time_format_setting.php index 917a097ee3..595ba67f15 100644 --- a/application/migrations/010_add_time_format_setting.php +++ b/application/migrations/010_add_time_format_setting.php @@ -11,14 +11,14 @@ * @since v1.3.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_time_format_setting extends EA_Migration { +class Migration_Add_time_format_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'time_format'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'time_format'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'time_format', 'value' => 'regular' @@ -31,8 +31,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'time_format'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'time_format'])->num_rows()) { $this->db->delete('settings', ['name' => 'time_format']); } } diff --git a/application/migrations/011_remove_prefix_from_fkey_constraints.php b/application/migrations/011_remove_prefix_from_fkey_constraints.php index 1d1b82e84d..5f9257a526 100644 --- a/application/migrations/011_remove_prefix_from_fkey_constraints.php +++ b/application/migrations/011_remove_prefix_from_fkey_constraints.php @@ -11,66 +11,171 @@ * @since v1.3.0 * ---------------------------------------------------------------------------- */ -class Migration_Remove_prefix_from_fkey_constraints extends EA_Migration { +class Migration_Remove_prefix_from_fkey_constraints extends EA_Migration +{ /** * Upgrade method. */ public function up() { // Drop table constraints. - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_3`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('appointments') . '_ibfk_4`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` DROP FOREIGN KEY `fk_' . $this->db->dbprefix('secretaries_providers') . '_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` DROP FOREIGN KEY `fk_' . $this->db->dbprefix('secretaries_providers') . '_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services_providers') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services_providers') . '_ibfk_2`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('services') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('users') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('users') . '_ibfk_1`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('user_settings') . '` DROP FOREIGN KEY `' . $this->db->dbprefix('user_settings') . '_ibfk_1`'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_3`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('appointments') . + '_ibfk_4`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` DROP FOREIGN KEY `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` DROP FOREIGN KEY `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services_providers') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services_providers') . + '_ibfk_2`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('services') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('users') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('users') . + '_ibfk_1`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('user_settings') . + '` DROP FOREIGN KEY `' . + $this->db->dbprefix('user_settings') . + '_ibfk_1`' + ); // Add table constraints again without the "ea" prefix. - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` - ADD CONSTRAINT `appointments_users_customer` FOREIGN KEY (`id_users_customer`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` + ADD CONSTRAINT `appointments_users_customer` FOREIGN KEY (`id_users_customer`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `appointments_services` FOREIGN KEY (`id_services`) REFERENCES `' . $this->db->dbprefix('services') . '` (`id`) + ADD CONSTRAINT `appointments_services` FOREIGN KEY (`id_services`) REFERENCES `' . + $this->db->dbprefix('services') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `appointments_users_provider` FOREIGN KEY (`id_users_provider`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) + ADD CONSTRAINT `appointments_users_provider` FOREIGN KEY (`id_users_provider`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE - ON UPDATE CASCADE'); + ON UPDATE CASCADE' + ); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` - ADD CONSTRAINT `secretaries_users_secretary` FOREIGN KEY (`id_users_secretary`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` + ADD CONSTRAINT `secretaries_users_secretary` FOREIGN KEY (`id_users_secretary`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `secretaries_users_provider` FOREIGN KEY (`id_users_provider`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) + ADD CONSTRAINT `secretaries_users_provider` FOREIGN KEY (`id_users_provider`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE - ON UPDATE CASCADE'); + ON UPDATE CASCADE' + ); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` - ADD CONSTRAINT `services_service_categories` FOREIGN KEY (`id_service_categories`) REFERENCES `' . $this->db->dbprefix('service_categories') . '` (`id`) + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services') . + '` + ADD CONSTRAINT `services_service_categories` FOREIGN KEY (`id_service_categories`) REFERENCES `' . + $this->db->dbprefix('service_categories') . + '` (`id`) ON DELETE SET NULL - ON UPDATE CASCADE'); + ON UPDATE CASCADE' + ); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` - ADD CONSTRAINT `services_providers_users_provider` FOREIGN KEY (`id_users`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` + ADD CONSTRAINT `services_providers_users_provider` FOREIGN KEY (`id_users`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `services_providers_services` FOREIGN KEY (`id_services`) REFERENCES `' . $this->db->dbprefix('services') . '` (`id`) + ADD CONSTRAINT `services_providers_services` FOREIGN KEY (`id_services`) REFERENCES `' . + $this->db->dbprefix('services') . + '` (`id`) ON DELETE CASCADE - ON UPDATE CASCADE'); + ON UPDATE CASCADE' + ); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('users') . '` - ADD CONSTRAINT `users_roles` FOREIGN KEY (`id_roles`) REFERENCES `' . $this->db->dbprefix('roles') . '` (`id`) + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('users') . + '` + ADD CONSTRAINT `users_roles` FOREIGN KEY (`id_roles`) REFERENCES `' . + $this->db->dbprefix('roles') . + '` (`id`) ON DELETE CASCADE - ON UPDATE CASCADE'); + ON UPDATE CASCADE' + ); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('user_settings') . '` - ADD CONSTRAINT `user_settings_users` FOREIGN KEY (`id_users`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('user_settings') . + '` + ADD CONSTRAINT `user_settings_users` FOREIGN KEY (`id_users`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE - ON UPDATE CASCADE'); + ON UPDATE CASCADE' + ); } /** @@ -79,38 +184,128 @@ public function up() public function down() { // Drop table constraints. - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `appointments_services`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `appointments_users_customer`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `appointments_users_provider`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` DROP FOREIGN KEY `secretaries_users_secretary`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` DROP FOREIGN KEY `secretaries_users_provider`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` DROP FOREIGN KEY `services_providers_users_provider`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` DROP FOREIGN KEY `services_providers_services`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `services_service_categories`'); + $this->db->query( + 'ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `appointments_services`' + ); + $this->db->query( + 'ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `appointments_users_customer`' + ); + $this->db->query( + 'ALTER TABLE `' . $this->db->dbprefix('appointments') . '` DROP FOREIGN KEY `appointments_users_provider`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` DROP FOREIGN KEY `secretaries_users_secretary`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` DROP FOREIGN KEY `secretaries_users_provider`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` DROP FOREIGN KEY `services_providers_users_provider`' + ); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` DROP FOREIGN KEY `services_providers_services`' + ); + $this->db->query( + 'ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `services_service_categories`' + ); $this->db->query('ALTER TABLE `' . $this->db->dbprefix('users') . '` DROP FOREIGN KEY `users_roles`'); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('user_settings') . '` DROP FOREIGN KEY `user_settings_users`'); + $this->db->query( + 'ALTER TABLE `' . $this->db->dbprefix('user_settings') . '` DROP FOREIGN KEY `user_settings_users`' + ); // Add table constraints again. - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('appointments') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_2` FOREIGN KEY (`id_users_customer`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_3` FOREIGN KEY (`id_services`) REFERENCES `' . $this->db->dbprefix('services') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('appointments') . '_ibfk_4` FOREIGN KEY (`id_users_provider`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('appointments') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_2` FOREIGN KEY (`id_users_customer`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_3` FOREIGN KEY (`id_services`) REFERENCES `' . + $this->db->dbprefix('services') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('appointments') . + '_ibfk_4` FOREIGN KEY (`id_users_provider`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('secretaries_providers') . '` - ADD CONSTRAINT `fk_' . $this->db->dbprefix('secretaries_providers') . '_1` FOREIGN KEY (`id_users_secretary`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `fk_' . $this->db->dbprefix('secretaries_providers') . '_2` FOREIGN KEY (`id_users_provider`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('secretaries_providers') . + '` + ADD CONSTRAINT `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_1` FOREIGN KEY (`id_users_secretary`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `fk_' . + $this->db->dbprefix('secretaries_providers') . + '_2` FOREIGN KEY (`id_users_provider`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('services') . '_ibfk_1` FOREIGN KEY (`id_service_categories`) REFERENCES `' . $this->db->dbprefix('service_categories') . '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('services') . + '_ibfk_1` FOREIGN KEY (`id_service_categories`) REFERENCES `' . + $this->db->dbprefix('service_categories') . + '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE' + ); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services_providers') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('services_providers') . '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - ADD CONSTRAINT `' . $this->db->dbprefix('services_providers') . '_ibfk_2` FOREIGN KEY (`id_services`) REFERENCES `' . $this->db->dbprefix('services') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('services_providers') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('services_providers') . + '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `' . + $this->db->dbprefix('services_providers') . + '_ibfk_2` FOREIGN KEY (`id_services`) REFERENCES `' . + $this->db->dbprefix('services') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('users') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('users') . '_ibfk_1` FOREIGN KEY (`id_roles`) REFERENCES `' . $this->db->dbprefix('roles') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('users') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('users') . + '_ibfk_1` FOREIGN KEY (`id_roles`) REFERENCES `' . + $this->db->dbprefix('roles') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('user_settings') . '` - ADD CONSTRAINT `' . $this->db->dbprefix('user_settings') . '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . $this->db->dbprefix('users') . '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'); + $this->db->query( + 'ALTER TABLE `' . + $this->db->dbprefix('user_settings') . + '` + ADD CONSTRAINT `' . + $this->db->dbprefix('user_settings') . + '_ibfk_1` FOREIGN KEY (`id_users`) REFERENCES `' . + $this->db->dbprefix('users') . + '` (`id`) ON DELETE CASCADE ON UPDATE CASCADE' + ); } } diff --git a/application/migrations/012_legal_contents.php b/application/migrations/012_legal_contents.php index 7011825449..9dbdd57961 100644 --- a/application/migrations/012_legal_contents.php +++ b/application/migrations/012_legal_contents.php @@ -11,107 +11,100 @@ * @since v1.3.2 * ---------------------------------------------------------------------------- */ -class Migration_Legal_contents extends EA_Migration { +class Migration_Legal_contents extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'display_cookie_notice'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'display_cookie_notice'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'display_cookie_notice', 'value' => '0' ]); } - if ( ! $this->db->get_where('settings', ['name' => 'cookie_notice_content'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'cookie_notice_content'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'cookie_notice_content', 'value' => 'Cookie notice content.' ]); } - if ( ! $this->db->get_where('settings', ['name' => 'display_terms_and_conditions'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'display_terms_and_conditions'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'display_terms_and_conditions', 'value' => '0' ]); } - if ( ! $this->db->get_where('settings', ['name' => 'terms_and_conditions_content'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'terms_and_conditions_content'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'terms_and_conditions_content', 'value' => 'Terms and conditions content.' ]); } - if ( ! $this->db->get_where('settings', ['name' => 'display_privacy_policy'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'display_privacy_policy'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'display_privacy_policy', 'value' => '0' ]); } - if ( ! $this->db->get_where('settings', ['name' => 'privacy_policy_content'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'privacy_policy_content'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'privacy_policy_content', 'value' => 'Privacy policy content.' ]); } - - if ( ! $this->db->table_exists('consents')) - { + if (!$this->db->table_exists('consents')) { $this->dbforge->add_field([ 'id' => [ 'type' => 'INT', 'constraint' => 11, - 'auto_increment' => TRUE + 'auto_increment' => true ], 'created' => [ 'type' => 'TIMESTAMP', - 'null' => TRUE + 'null' => true ], 'modified' => [ 'type' => 'TIMESTAMP', - 'null' => TRUE + 'null' => true ], 'first_name' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE, + 'null' => true ], 'last_name' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE, + 'null' => true ], 'email' => [ 'type' => 'VARCHAR', 'constraint' => '512', - 'null' => TRUE, + 'null' => true ], 'ip' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE, + 'null' => true ], 'type' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE, - ], + 'null' => true + ] ]); - $this->dbforge->add_key('id', TRUE); + $this->dbforge->add_key('id', true); - $this->dbforge->create_table('consents', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->create_table('consents', true, ['engine' => 'InnoDB']); } } @@ -120,50 +113,43 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'display_cookie_notice'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'display_cookie_notice'])->num_rows()) { $this->db->delete('settings', [ 'name' => 'display_cookie_notice' ]); } - if ($this->db->get_where('settings', ['name' => 'cookie_notice_content'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'cookie_notice_content'])->num_rows()) { $this->db->delete('settings', [ 'name' => 'cookie_notice_content' ]); } - if ($this->db->get_where('settings', ['name' => 'display_terms_and_conditions'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'display_terms_and_conditions'])->num_rows()) { $this->db->delete('settings', [ 'name' => 'display_terms_and_conditions' ]); } - if ($this->db->get_where('settings', ['name' => 'terms_and_conditions_content'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'terms_and_conditions_content'])->num_rows()) { $this->db->delete('settings', [ 'name' => 'terms_and_conditions_content' ]); } - if ($this->db->get_where('settings', ['name' => 'display_privacy_policy'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'display_privacy_policy'])->num_rows()) { $this->db->delete('settings', [ 'name' => 'display_privacy_policy' ]); } - if ($this->db->get_where('settings', ['name' => 'privacy_policy_content'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'privacy_policy_content'])->num_rows()) { $this->db->delete('settings', [ 'name' => 'privacy_policy_content' ]); } - if ($this->db->table_exists('consents')) - { + if ($this->db->table_exists('consents')) { $this->dbforge->drop_table('consents'); } } diff --git a/application/migrations/013_add_weekday_start_setting.php b/application/migrations/013_add_weekday_start_setting.php index 58fb94c0b9..0ac8d06b38 100644 --- a/application/migrations/013_add_weekday_start_setting.php +++ b/application/migrations/013_add_weekday_start_setting.php @@ -11,14 +11,14 @@ * @since v1.3.2 * ---------------------------------------------------------------------------- */ -class Migration_Add_weekday_start_setting extends EA_Migration { +class Migration_Add_weekday_start_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'first_weekday'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'first_weekday'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'first_weekday', 'value' => 'sunday' @@ -31,8 +31,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'first_weekday'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'first_weekday'])->num_rows()) { $this->db->delete('settings', ['name' => 'first_weekday']); } } diff --git a/application/migrations/014_create_appointment_location_column.php b/application/migrations/014_create_appointment_location_column.php index 83b641398e..6c2fd6ee52 100644 --- a/application/migrations/014_create_appointment_location_column.php +++ b/application/migrations/014_create_appointment_location_column.php @@ -11,18 +11,18 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Create_appointment_location_column extends EA_Migration { +class Migration_Create_appointment_location_column extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('location', 'appointments')) - { + if (!$this->db->field_exists('location', 'appointments')) { $fields = [ 'location' => [ 'type' => 'TEXT', - 'null' => TRUE, + 'null' => true, 'after' => 'end_datetime' ] ]; @@ -30,12 +30,11 @@ public function up() $this->dbforge->add_column('appointments', $fields); } - if ( ! $this->db->field_exists('location', 'services')) - { + if (!$this->db->field_exists('location', 'services')) { $fields = [ 'location' => [ 'type' => 'TEXT', - 'null' => TRUE, + 'null' => true, 'after' => 'description' ] ]; @@ -49,13 +48,11 @@ public function up() */ public function down() { - if ($this->db->field_exists('location', 'appointments')) - { + if ($this->db->field_exists('location', 'appointments')) { $this->dbforge->drop_column('appointments', 'location'); } - if ($this->db->field_exists('location', 'services')) - { + if ($this->db->field_exists('location', 'services')) { $this->dbforge->drop_column('services', 'location'); } } diff --git a/application/migrations/015_add_working_plan_exceptions_to_user_settings.php b/application/migrations/015_add_working_plan_exceptions_to_user_settings.php index 2f9253fc5f..62c43c56e1 100644 --- a/application/migrations/015_add_working_plan_exceptions_to_user_settings.php +++ b/application/migrations/015_add_working_plan_exceptions_to_user_settings.php @@ -11,18 +11,18 @@ * @since v1.2.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_working_plan_exceptions_to_user_settings extends EA_Migration { +class Migration_Add_working_plan_exceptions_to_user_settings extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('working_plan_exceptions', 'user_settings')) - { + if (!$this->db->field_exists('working_plan_exceptions', 'user_settings')) { $fields = [ 'working_plan_exceptions' => [ 'type' => 'TEXT', - 'null' => TRUE, + 'null' => true, 'after' => 'working_plan' ] ]; @@ -36,8 +36,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('working_plan_exceptions', 'user_settings')) - { + if ($this->db->field_exists('working_plan_exceptions', 'user_settings')) { $this->dbforge->drop_column('user_settings', 'working_plan_exceptions'); } } diff --git a/application/migrations/016_add_require_phone_number_setting.php b/application/migrations/016_add_require_phone_number_setting.php index 9f03194507..d5abe6bfd8 100644 --- a/application/migrations/016_add_require_phone_number_setting.php +++ b/application/migrations/016_add_require_phone_number_setting.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_require_phone_number_setting extends EA_Migration { +class Migration_Add_require_phone_number_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'require_phone_number'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'require_phone_number'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'require_phone_number', 'value' => '1' @@ -31,8 +31,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'require_phone_number'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'require_phone_number'])->num_rows()) { $this->db->delete('settings', ['name' => 'require_phone_number']); } } diff --git a/application/migrations/017_add_api_token_setting.php b/application/migrations/017_add_api_token_setting.php index afb2256147..34428ff643 100644 --- a/application/migrations/017_add_api_token_setting.php +++ b/application/migrations/017_add_api_token_setting.php @@ -11,7 +11,8 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_api_token_setting extends EA_Migration { +class Migration_Add_api_token_setting extends EA_Migration +{ /** * Upgrade method. * @@ -19,14 +20,12 @@ class Migration_Add_api_token_setting extends EA_Migration { */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'api_token'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'api_token'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'api_token', 'value' => '' ]); } - } /** @@ -36,8 +35,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'api_token'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'api_token'])->num_rows()) { $this->db->delete('settings', ['name' => 'api_token']); } } diff --git a/application/migrations/018_add_timezone_to_users.php b/application/migrations/018_add_timezone_to_users.php index 6a6612667a..66cb11e51b 100644 --- a/application/migrations/018_add_timezone_to_users.php +++ b/application/migrations/018_add_timezone_to_users.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_timezone_to_users extends EA_Migration { +class Migration_Add_timezone_to_users extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('timezone', 'users')) - { + if (!$this->db->field_exists('timezone', 'users')) { $fields = [ 'timezone' => [ 'type' => 'VARCHAR', diff --git a/application/migrations/019_add_display_any_provider_setting.php b/application/migrations/019_add_display_any_provider_setting.php index a39d5128d1..651c57e1c2 100644 --- a/application/migrations/019_add_display_any_provider_setting.php +++ b/application/migrations/019_add_display_any_provider_setting.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_display_any_provider_setting extends EA_Migration { +class Migration_Add_display_any_provider_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'display_any_provider'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'display_any_provider'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'display_any_provider', 'value' => '1' @@ -31,8 +31,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'display_any_provider'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'display_any_provider'])->num_rows()) { $this->db->delete('settings', ['name' => 'display_any_provider']); } } diff --git a/application/migrations/020_add_language_to_users.php b/application/migrations/020_add_language_to_users.php index 17fbc5baf9..f6a326abb9 100644 --- a/application/migrations/020_add_language_to_users.php +++ b/application/migrations/020_add_language_to_users.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_language_to_users extends EA_Migration { +class Migration_Add_language_to_users extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('language', 'users')) - { + if (!$this->db->field_exists('language', 'users')) { $fields = [ 'language' => [ 'type' => 'VARCHAR', diff --git a/application/migrations/021_modify_sync_period_columns.php b/application/migrations/021_modify_sync_period_columns.php index fe297db115..eef5a6708e 100644 --- a/application/migrations/021_modify_sync_period_columns.php +++ b/application/migrations/021_modify_sync_period_columns.php @@ -11,7 +11,8 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Modify_sync_period_columns extends EA_Migration { +class Migration_Modify_sync_period_columns extends EA_Migration +{ /** * Upgrade method. */ @@ -21,15 +22,15 @@ public function up() 'sync_past_days' => [ 'type' => 'INT', 'constraint' => '11', - 'null' => TRUE, + 'null' => true, 'default' => '30' ], 'sync_future_days' => [ 'type' => 'INT', 'constraint' => '11', - 'null' => TRUE, + 'null' => true, 'default' => '90' - ], + ] ]; $this->dbforge->modify_column('user_settings', $fields); @@ -64,15 +65,15 @@ public function down() 'sync_past_days' => [ 'type' => 'INT', 'constraint' => '11', - 'null' => TRUE, + 'null' => true, 'default' => '5' ], 'sync_future_days' => [ 'type' => 'INT', 'constraint' => '11', - 'null' => TRUE, + 'null' => true, 'default' => '5' - ], + ] ]; $this->dbforge->modify_column('user_settings', $fields); diff --git a/application/migrations/022_add_booking_field_settings.php b/application/migrations/022_add_booking_field_settings.php index 03fe5e2cd4..29579d9e87 100644 --- a/application/migrations/022_add_booking_field_settings.php +++ b/application/migrations/022_add_booking_field_settings.php @@ -11,43 +11,44 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_booking_field_settings extends EA_Migration { +class Migration_Add_booking_field_settings extends EA_Migration +{ /** * @var array */ private $fields = [ 'first_name' => [ 'display' => '1', - 'require' => '1', + 'require' => '1' ], 'last_name' => [ 'display' => '1', - 'require' => '1', + 'require' => '1' ], 'email' => [ 'display' => '1', - 'require' => '1', + 'require' => '1' ], 'phone_number' => [ 'display' => '1', - 'require' => '1', + 'require' => '1' ], 'address' => [ 'display' => '1', - 'require' => '0', + 'require' => '0' ], 'city' => [ 'display' => '1', - 'require' => '0', + 'require' => '0' ], 'zip_code' => [ 'display' => '1', - 'require' => '0', + 'require' => '0' ], 'notes' => [ 'display' => '1', - 'require' => '0', - ], + 'require' => '0' + ] ]; /** @@ -55,14 +56,11 @@ class Migration_Add_booking_field_settings extends EA_Migration { */ public function up() { - foreach ($this->fields as $field => $props) - { - foreach ($props as $prop => $value) - { + foreach ($this->fields as $field => $props) { + foreach ($props as $prop => $value) { $setting_name = $prop . '_' . $field; - if ($this->db->get_where('settings', ['name' => $setting_name])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => $setting_name])->num_rows()) { $setting = $this->db->get_where('settings', ['name' => $setting_name])->row_array(); $value = $setting['value']; // Use existing value. @@ -70,8 +68,7 @@ public function up() $this->db->delete('settings', ['name' => $setting_name]); } - if ( ! $this->db->get_where('settings', ['name' => $setting_name])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => $setting_name])->num_rows()) { $this->db->insert('settings', [ 'name' => $setting_name, 'value' => $value @@ -86,14 +83,11 @@ public function up() */ public function down() { - foreach ($this->fields as $field => $props) - { - foreach ($props as $prop => $value) - { + foreach ($this->fields as $field => $props) { + foreach ($props as $prop => $value) { $setting_name = $prop . '_' . $field; - if ($this->db->get_where('settings', ['name' => $setting_name])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => $setting_name])->num_rows()) { $this->db->delete('settings', ['name' => $setting_name]); } } diff --git a/application/migrations/023_rename_service_categories_table_to_categories.php b/application/migrations/023_rename_service_categories_table_to_categories.php index 7b002320f3..de65abd734 100644 --- a/application/migrations/023_rename_service_categories_table_to_categories.php +++ b/application/migrations/023_rename_service_categories_table_to_categories.php @@ -11,14 +11,14 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -class Migration_Rename_service_categories_table_to_categories extends EA_Migration { +class Migration_Rename_service_categories_table_to_categories extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ($this->db->table_exists('service_categories')) - { + if ($this->db->table_exists('service_categories')) { $this->dbforge->rename_table('service_categories', 'categories'); } } @@ -28,8 +28,7 @@ public function up() */ public function down() { - if ($this->db->table_exists('categories')) - { + if ($this->db->table_exists('categories')) { $this->dbforge->rename_table('categories', 'service_categories'); } } diff --git a/application/migrations/024_rename_id_service_categories_column_of_services_table.php b/application/migrations/024_rename_id_service_categories_column_of_services_table.php index 5ba005aa4e..431b69eaf0 100644 --- a/application/migrations/024_rename_id_service_categories_column_of_services_table.php +++ b/application/migrations/024_rename_id_service_categories_column_of_services_table.php @@ -11,15 +11,17 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -class Migration_Rename_id_service_categories_column_of_services_table extends EA_Migration { +class Migration_Rename_id_service_categories_column_of_services_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ($this->db->field_exists('id_service_categories', 'services')) - { - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `services_service_categories`'); + if ($this->db->field_exists('id_service_categories', 'services')) { + $this->db->query( + 'ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `services_service_categories`' + ); $fields = [ 'id_service_categories' => [ @@ -31,12 +33,18 @@ public function up() $this->dbforge->modify_column('services', $fields); - $this->db->query(' - ALTER TABLE `' . $this->db->dbprefix('services') . '` - ADD CONSTRAINT `services_categories` FOREIGN KEY (`id_categories`) REFERENCES `' . $this->db->dbprefix('categories') . '` (`id`) + $this->db->query( + ' + ALTER TABLE `' . + $this->db->dbprefix('services') . + '` + ADD CONSTRAINT `services_categories` FOREIGN KEY (`id_categories`) REFERENCES `' . + $this->db->dbprefix('categories') . + '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE - '); + ' + ); } } @@ -45,9 +53,10 @@ public function up() */ public function down() { - if ($this->db->field_exists('id_categories', 'services')) - { - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `services_categories`'); + if ($this->db->field_exists('id_categories', 'services')) { + $this->db->query( + 'ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `services_categories`' + ); $fields = [ 'id_categories' => [ @@ -59,12 +68,18 @@ public function down() $this->dbforge->modify_column('services', $fields); - $this->db->query(' - ALTER TABLE `' . $this->db->dbprefix('services') . '` - ADD CONSTRAINT `services_service_categories` FOREIGN KEY (`id_service_categories`) REFERENCES `' . $this->db->dbprefix('categories') . '` (`id`) + $this->db->query( + ' + ALTER TABLE `' . + $this->db->dbprefix('services') . + '` + ADD CONSTRAINT `services_service_categories` FOREIGN KEY (`id_service_categories`) REFERENCES `' . + $this->db->dbprefix('categories') . + '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE - '); + ' + ); } } } diff --git a/application/migrations/025_rename_is_unavailable_column_of_appointments_table.php b/application/migrations/025_rename_is_unavailable_column_of_appointments_table.php index f7ee4aea5f..dd4b9f8038 100644 --- a/application/migrations/025_rename_is_unavailable_column_of_appointments_table.php +++ b/application/migrations/025_rename_is_unavailable_column_of_appointments_table.php @@ -11,14 +11,14 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -class Migration_Rename_is_unavailable_column_of_appointments_table extends EA_Migration { +class Migration_Rename_is_unavailable_column_of_appointments_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ($this->db->field_exists('is_unavailable', 'appointments')) - { + if ($this->db->field_exists('is_unavailable', 'appointments')) { $fields = [ 'is_unavailable' => [ 'name' => 'is_unavailability', @@ -37,8 +37,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('is_unavailability', 'appointments')) - { + if ($this->db->field_exists('is_unavailability', 'appointments')) { $fields = [ 'is_unavailability' => [ 'name' => 'is_unavailable', diff --git a/application/migrations/026_add_color_column_to_services_table.php b/application/migrations/026_add_color_column_to_services_table.php index a767b9f5f7..1c15b326e8 100644 --- a/application/migrations/026_add_color_column_to_services_table.php +++ b/application/migrations/026_add_color_column_to_services_table.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_color_column_to_services_table extends EA_Migration { +class Migration_Add_color_column_to_services_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('color', 'services')) - { + if (!$this->db->field_exists('color', 'services')) { $fields = [ 'color' => [ 'type' => 'VARCHAR', @@ -37,8 +37,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('color', 'services')) - { + if ($this->db->field_exists('color', 'services')) { $this->dbforge->drop_column('services', 'color'); } } diff --git a/application/migrations/027_add_color_column_to_appointments_table.php b/application/migrations/027_add_color_column_to_appointments_table.php index fb978f85f3..e7e632d7e4 100644 --- a/application/migrations/027_add_color_column_to_appointments_table.php +++ b/application/migrations/027_add_color_column_to_appointments_table.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_color_column_to_appointments_table extends EA_Migration { +class Migration_Add_color_column_to_appointments_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('color', 'appointments')) - { + if (!$this->db->field_exists('color', 'appointments')) { $fields = [ 'color' => [ 'type' => 'VARCHAR', @@ -37,8 +37,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('color', 'appointments')) - { + if ($this->db->field_exists('color', 'appointments')) { $this->dbforge->drop_column('appointments', 'color'); } } diff --git a/application/migrations/028_add_matomo_analytics_url_setting.php b/application/migrations/028_add_matomo_analytics_url_setting.php index aa31e1b353..a590142f15 100644 --- a/application/migrations/028_add_matomo_analytics_url_setting.php +++ b/application/migrations/028_add_matomo_analytics_url_setting.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_matomo_analytics_url_setting extends EA_Migration { +class Migration_Add_matomo_analytics_url_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'matomo_analytics_url'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'matomo_analytics_url'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'matomo_analytics_url', 'value' => '' @@ -31,8 +31,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'matomo_analytics_url'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'matomo_analytics_url'])->num_rows()) { $this->db->delete('settings', ['name' => 'matomo_analytics_url']); } } diff --git a/application/migrations/029_add_display_delete_personal_information_setting.php b/application/migrations/029_add_display_delete_personal_information_setting.php index 2d9df62222..44d673a3b9 100644 --- a/application/migrations/029_add_display_delete_personal_information_setting.php +++ b/application/migrations/029_add_display_delete_personal_information_setting.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_display_delete_personal_information_setting extends EA_Migration { +class Migration_Add_display_delete_personal_information_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'display_delete_personal_information'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'display_delete_personal_information'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'display_delete_personal_information', 'value' => '0' @@ -31,8 +31,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'display_delete_personal_information'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'display_delete_personal_information'])->num_rows()) { $this->db->delete('settings', ['name' => 'display_delete_personal_information']); } } diff --git a/application/migrations/030_add_disable_booking_setting.php b/application/migrations/030_add_disable_booking_setting.php index d1253d3168..a6fee6f0ca 100644 --- a/application/migrations/030_add_disable_booking_setting.php +++ b/application/migrations/030_add_disable_booking_setting.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_disable_booking_setting extends EA_Migration { +class Migration_Add_disable_booking_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'disable_booking'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'disable_booking'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'disable_booking', 'value' => '0' @@ -31,8 +31,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'disable_booking'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'disable_booking'])->num_rows()) { $this->db->delete('settings', ['name' => 'disable_booking']); } } diff --git a/application/migrations/031_add_disable_booking_message_setting.php b/application/migrations/031_add_disable_booking_message_setting.php index adf82c777b..b6e83fdd0e 100644 --- a/application/migrations/031_add_disable_booking_message_setting.php +++ b/application/migrations/031_add_disable_booking_message_setting.php @@ -11,17 +11,18 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_disable_booking_message_setting extends EA_Migration { +class Migration_Add_disable_booking_message_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'disable_booking_message'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'disable_booking_message'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'disable_booking_message', - 'value' => '

Thanks for stopping by!

We are not accepting new appointments at the moment, please check back again later.

' + 'value' => + '

Thanks for stopping by!

We are not accepting new appointments at the moment, please check back again later.

' ]); } } @@ -31,8 +32,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'disable_booking_message'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'disable_booking_message'])->num_rows()) { $this->db->delete('settings', ['name' => 'disable_booking_message']); } } diff --git a/application/migrations/032_add_company_logo_setting.php b/application/migrations/032_add_company_logo_setting.php index 06e73e7b38..fca7d8e34c 100644 --- a/application/migrations/032_add_company_logo_setting.php +++ b/application/migrations/032_add_company_logo_setting.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_company_logo_setting extends EA_Migration { +class Migration_Add_company_logo_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'company_logo'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'company_logo'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'company_logo', 'value' => '' @@ -31,8 +31,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'company_logo'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'company_logo'])->num_rows()) { $this->db->delete('settings', ['name' => 'company_logo']); } } diff --git a/application/migrations/033_add_company_color_setting.php b/application/migrations/033_add_company_color_setting.php index 4264d86f2f..dadb6b11df 100644 --- a/application/migrations/033_add_company_color_setting.php +++ b/application/migrations/033_add_company_color_setting.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_company_color_setting extends EA_Migration { +class Migration_Add_company_color_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'company_color'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'company_color'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'company_color', 'value' => '#ffffff' @@ -31,8 +31,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'company_color'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'company_color'])->num_rows()) { $this->db->delete('settings', ['name' => 'company_color']); } } diff --git a/application/migrations/034_add_display_login_button_setting.php b/application/migrations/034_add_display_login_button_setting.php index 60b35ce276..5a4cdc8689 100644 --- a/application/migrations/034_add_display_login_button_setting.php +++ b/application/migrations/034_add_display_login_button_setting.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_display_login_button_setting extends EA_Migration { +class Migration_Add_display_login_button_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'display_login_button'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'display_login_button'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'display_login_button', 'value' => '1' @@ -31,8 +31,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'display_login_button'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'display_login_button'])->num_rows()) { $this->db->delete('settings', ['name' => 'display_login_button']); } } diff --git a/application/migrations/035_add_is_private_column_to_services_table.php b/application/migrations/035_add_is_private_column_to_services_table.php index f4329c9c3d..52230a1fb4 100644 --- a/application/migrations/035_add_is_private_column_to_services_table.php +++ b/application/migrations/035_add_is_private_column_to_services_table.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_is_private_column_to_services_table extends EA_Migration { +class Migration_Add_is_private_column_to_services_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('is_private', 'services')) - { + if (!$this->db->field_exists('is_private', 'services')) { $fields = [ 'is_private' => [ 'type' => 'TINYINT', @@ -37,8 +37,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('is_private', 'services')) - { + if ($this->db->field_exists('is_private', 'services')) { $this->dbforge->drop_column('services', 'is_private'); } } diff --git a/application/migrations/036_add_is_private_column_to_users_table.php b/application/migrations/036_add_is_private_column_to_users_table.php index 3d2df4dc01..7bfae21238 100644 --- a/application/migrations/036_add_is_private_column_to_users_table.php +++ b/application/migrations/036_add_is_private_column_to_users_table.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_is_private_column_to_users_table extends EA_Migration { +class Migration_Add_is_private_column_to_users_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('is_private', 'users')) - { + if (!$this->db->field_exists('is_private', 'users')) { $fields = [ 'is_private' => [ 'type' => 'TINYINT', @@ -37,8 +37,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('is_private', 'users')) - { + if ($this->db->field_exists('is_private', 'users')) { $this->dbforge->drop_column('users', 'is_private'); } } diff --git a/application/migrations/037_add_timestamp_columns.php b/application/migrations/037_add_timestamp_columns.php index 5199bd2b45..01c91ad3e5 100644 --- a/application/migrations/037_add_timestamp_columns.php +++ b/application/migrations/037_add_timestamp_columns.php @@ -11,45 +11,31 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_timestamp_columns extends EA_Migration { +class Migration_Add_timestamp_columns extends EA_Migration +{ /** * @var string[] */ - protected $tables = [ - 'appointments', - 'categories', - 'consents', - 'roles', - 'services', - 'settings', - 'users' - ]; + protected $tables = ['appointments', 'categories', 'consents', 'roles', 'services', 'settings', 'users']; /** * @var string[] */ - protected $columns = [ - 'delete_datetime', - 'update_datetime', - 'create_datetime', - ]; + protected $columns = ['delete_datetime', 'update_datetime', 'create_datetime']; /** * Upgrade method. */ public function up() { - foreach ($this->tables as $table) - { - foreach ($this->columns as $column) - { - if ( ! $this->db->field_exists($column, $table)) - { + foreach ($this->tables as $table) { + foreach ($this->columns as $column) { + if (!$this->db->field_exists($column, $table)) { $fields = [ $column => [ 'type' => 'DATETIME', - 'null' => TRUE, - 'after' => 'id', + 'null' => true, + 'after' => 'id' ] ]; @@ -64,12 +50,9 @@ public function up() */ public function down() { - foreach ($this->tables as $table) - { - foreach ($this->columns as $column) - { - if ($this->db->field_exists($column, $table)) - { + foreach ($this->tables as $table) { + foreach ($this->columns as $column) { + if ($this->db->field_exists($column, $table)) { $this->dbforge->drop_column($table, $column); } } diff --git a/application/migrations/038_add_theme_setting.php b/application/migrations/038_add_theme_setting.php index c73751d41f..3280c98569 100644 --- a/application/migrations/038_add_theme_setting.php +++ b/application/migrations/038_add_theme_setting.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_theme_setting extends EA_Migration { +class Migration_Add_theme_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'theme'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'theme'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'theme', 'value' => 'default' @@ -31,8 +31,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'theme'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'theme'])->num_rows()) { $this->db->delete('settings', ['name' => 'theme']); } } diff --git a/application/migrations/039_add_limit_customer_access_setting.php b/application/migrations/039_add_limit_customer_access_setting.php index 36bd1ac6b3..97bfd496c7 100644 --- a/application/migrations/039_add_limit_customer_access_setting.php +++ b/application/migrations/039_add_limit_customer_access_setting.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_limit_customer_access_setting extends EA_Migration { +class Migration_Add_limit_customer_access_setting extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'limit_customer_access'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'limit_customer_access'])->num_rows()) { $this->db->insert('settings', [ 'create_datetime' => date('Y-m-d H:i:s'), 'update_datetime' => date('Y-m-d H:i:s'), @@ -33,8 +33,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'limit_customer_access'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'limit_customer_access'])->num_rows()) { $this->db->delete('settings', ['name' => 'limit_customer_access']); } } diff --git a/application/migrations/040_create_webhooks_table.php b/application/migrations/040_create_webhooks_table.php index 8e839351c8..8a55e060f2 100644 --- a/application/migrations/040_create_webhooks_table.php +++ b/application/migrations/040_create_webhooks_table.php @@ -11,64 +11,64 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Create_webhooks_table extends EA_Migration { +class Migration_Create_webhooks_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->table_exists('webhooks')) - { + if (!$this->db->table_exists('webhooks')) { $this->dbforge->add_field([ 'id' => [ 'type' => 'INT', 'constraint' => 11, - 'auto_increment' => TRUE + 'auto_increment' => true ], 'create_datetime' => [ 'type' => 'DATETIME', - 'null' => TRUE + 'null' => true ], 'update_datetime' => [ 'type' => 'DATETIME', - 'null' => TRUE + 'null' => true ], 'delete_datetime' => [ 'type' => 'DATETIME', - 'null' => TRUE + 'null' => true ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE, + 'null' => true ], 'url' => [ 'type' => 'TEXT', - 'null' => TRUE, + 'null' => true ], 'actions' => [ 'type' => 'TEXT', - 'null' => TRUE, + 'null' => true ], 'secret_token' => [ 'type' => 'VARCHAR', 'constraint' => '512', - 'null' => TRUE, + 'null' => true ], 'is_ssl_verified' => [ 'type' => 'TINYINT', 'constraint' => '4', - 'default' => TRUE, + 'default' => true ], 'notes' => [ 'type' => 'TEXT', - 'null' => TRUE, - ], + 'null' => true + ] ]); - $this->dbforge->add_key('id', TRUE); + $this->dbforge->add_key('id', true); - $this->dbforge->create_table('webhooks', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->create_table('webhooks', true, ['engine' => 'InnoDB']); } } @@ -77,8 +77,7 @@ public function up() */ public function down() { - if ($this->db->table_exists('webhooks')) - { + if ($this->db->table_exists('webhooks')) { $this->dbforge->drop_table('webhooks'); } } diff --git a/application/migrations/041_add_webhooks_column_to_roles_table.php b/application/migrations/041_add_webhooks_column_to_roles_table.php index 6ea39a5eb1..70c866b426 100644 --- a/application/migrations/041_add_webhooks_column_to_roles_table.php +++ b/application/migrations/041_add_webhooks_column_to_roles_table.php @@ -11,19 +11,19 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_webhooks_column_to_roles_table extends EA_Migration { +class Migration_Add_webhooks_column_to_roles_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('webhooks', 'roles')) - { + if (!$this->db->field_exists('webhooks', 'roles')) { $fields = [ 'webhooks' => [ 'type' => 'INT', 'constraint' => '11', - 'null' => TRUE + 'null' => true ] ]; @@ -40,8 +40,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('webhooks', 'roles')) - { + if ($this->db->field_exists('webhooks', 'roles')) { $this->dbforge->drop_column('roles', 'webhooks'); } } diff --git a/application/migrations/042_add_future_booking_limit_setting.php b/application/migrations/042_add_future_booking_limit_setting.php index 75e62f7e45..5fe8137485 100644 --- a/application/migrations/042_add_future_booking_limit_setting.php +++ b/application/migrations/042_add_future_booking_limit_setting.php @@ -15,7 +15,8 @@ * @property CI_DB_query_builder $db * @property CI_DB_forge $dbforge */ -class Migration_Add_future_booking_limit_setting extends CI_Migration { +class Migration_Add_future_booking_limit_setting extends CI_Migration +{ /** * Upgrade method. * @@ -23,11 +24,10 @@ class Migration_Add_future_booking_limit_setting extends CI_Migration { */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'future_booking_limit'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'future_booking_limit'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'future_booking_limit', - 'value' => '90' // days + 'value' => '90' // days ]); } } @@ -39,8 +39,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'future_booking_limit'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'future_booking_limit'])->num_rows()) { $this->db->delete('settings', ['name' => 'future_booking_limit']); } } diff --git a/application/migrations/043_add_appointment_status_options_setting.php b/application/migrations/043_add_appointment_status_options_setting.php index efb50c10aa..c31b3daf4d 100644 --- a/application/migrations/043_add_appointment_status_options_setting.php +++ b/application/migrations/043_add_appointment_status_options_setting.php @@ -15,7 +15,8 @@ * @property CI_DB_query_builder $db * @property CI_DB_forge $dbforge */ -class Migration_Add_appointment_status_options_setting extends CI_Migration { +class Migration_Add_appointment_status_options_setting extends CI_Migration +{ /** * Upgrade method. * @@ -23,8 +24,7 @@ class Migration_Add_appointment_status_options_setting extends CI_Migration { */ public function up() { - if ( ! $this->db->get_where('settings', ['name' => 'appointment_status_options'])->num_rows()) - { + if (!$this->db->get_where('settings', ['name' => 'appointment_status_options'])->num_rows()) { $this->db->insert('settings', [ 'name' => 'appointment_status_options', 'value' => '["Booked", "Confirmed", "Rescheduled", "Cancelled", "Draft"]' @@ -39,8 +39,7 @@ public function up() */ public function down() { - if ($this->db->get_where('settings', ['name' => 'appointment_status_options'])->num_rows()) - { + if ($this->db->get_where('settings', ['name' => 'appointment_status_options'])->num_rows()) { $this->db->delete('settings', ['name' => 'status_options']); } } diff --git a/application/migrations/044_add_status_column_to_appointments_table.php b/application/migrations/044_add_status_column_to_appointments_table.php index 12bae422e1..33411be2cb 100644 --- a/application/migrations/044_add_status_column_to_appointments_table.php +++ b/application/migrations/044_add_status_column_to_appointments_table.php @@ -11,14 +11,14 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_status_column_to_appointments_table extends EA_Migration { +class Migration_Add_status_column_to_appointments_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('status', 'appointments')) - { + if (!$this->db->field_exists('status', 'appointments')) { $fields = [ 'status' => [ 'type' => 'VARCHAR', @@ -37,8 +37,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('status', 'appointments')) - { + if ($this->db->field_exists('status', 'appointments')) { $this->dbforge->drop_column('appointments', 'status'); } } diff --git a/application/migrations/045_drop_delete_datetime_column_from_all_tables.php b/application/migrations/045_drop_delete_datetime_column_from_all_tables.php index d3eb39f0dd..cb2044aa3e 100644 --- a/application/migrations/045_drop_delete_datetime_column_from_all_tables.php +++ b/application/migrations/045_drop_delete_datetime_column_from_all_tables.php @@ -11,7 +11,8 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Drop_delete_datetime_column_from_all_tables extends EA_Migration { +class Migration_Drop_delete_datetime_column_from_all_tables extends EA_Migration +{ /** * @var string[] */ @@ -31,10 +32,8 @@ class Migration_Drop_delete_datetime_column_from_all_tables extends EA_Migration */ public function up() { - foreach ($this->tables as $table) - { - if ($this->db->field_exists('delete_datetime', $table)) - { + foreach ($this->tables as $table) { + if ($this->db->field_exists('delete_datetime', $table)) { $this->dbforge->drop_column($table, 'delete_datetime'); } } @@ -45,15 +44,13 @@ public function up() */ public function down() { - foreach ($this->tables as $table) - { - if ( ! $this->db->field_exists('delete_datetime', $table)) - { + foreach ($this->tables as $table) { + if (!$this->db->field_exists('delete_datetime', $table)) { $fields = [ 'delete_datetime' => [ 'type' => 'DATETIME', - 'null' => TRUE, - 'after' => 'update_datetime', + 'null' => true, + 'after' => 'update_datetime' ] ]; diff --git a/application/migrations/046_revert_rename_service_categories_table_to_categories.php b/application/migrations/046_revert_rename_service_categories_table_to_categories.php index 220196caf9..466eb112eb 100644 --- a/application/migrations/046_revert_rename_service_categories_table_to_categories.php +++ b/application/migrations/046_revert_rename_service_categories_table_to_categories.php @@ -11,14 +11,14 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -class Migration_Revert_rename_service_categories_table_to_categories extends EA_Migration { +class Migration_Revert_rename_service_categories_table_to_categories extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ($this->db->table_exists('categories')) - { + if ($this->db->table_exists('categories')) { $this->dbforge->rename_table('categories', 'service_categories'); } } @@ -28,8 +28,7 @@ public function up() */ public function down() { - if ($this->db->table_exists('service_categories')) - { + if ($this->db->table_exists('service_categories')) { $this->dbforge->rename_table('service_categories', 'categories'); } } diff --git a/application/migrations/047_revert_rename_id_service_categories_column_of_services_table.php b/application/migrations/047_revert_rename_id_service_categories_column_of_services_table.php index 57a871d810..86ec8fe8bd 100644 --- a/application/migrations/047_revert_rename_id_service_categories_column_of_services_table.php +++ b/application/migrations/047_revert_rename_id_service_categories_column_of_services_table.php @@ -11,15 +11,17 @@ * @since v1.5.0 * ---------------------------------------------------------------------------- */ -class Migration_Revert_rename_id_service_categories_column_of_services_table extends EA_Migration { +class Migration_Revert_rename_id_service_categories_column_of_services_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ($this->db->field_exists('id_categories', 'services')) - { - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `services_categories`'); + if ($this->db->field_exists('id_categories', 'services')) { + $this->db->query( + 'ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `services_categories`' + ); $fields = [ 'id_categories' => [ @@ -31,12 +33,18 @@ public function up() $this->dbforge->modify_column('services', $fields); - $this->db->query(' - ALTER TABLE `' . $this->db->dbprefix('services') . '` - ADD CONSTRAINT `services_service_categories` FOREIGN KEY (`id_service_categories`) REFERENCES `' . $this->db->dbprefix('service_categories') . '` (`id`) + $this->db->query( + ' + ALTER TABLE `' . + $this->db->dbprefix('services') . + '` + ADD CONSTRAINT `services_service_categories` FOREIGN KEY (`id_service_categories`) REFERENCES `' . + $this->db->dbprefix('service_categories') . + '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE - '); + ' + ); } } @@ -45,9 +53,10 @@ public function up() */ public function down() { - if ($this->db->field_exists('id_service_categories', 'services')) - { - $this->db->query('ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `services_service_categories`'); + if ($this->db->field_exists('id_service_categories', 'services')) { + $this->db->query( + 'ALTER TABLE `' . $this->db->dbprefix('services') . '` DROP FOREIGN KEY `services_service_categories`' + ); $fields = [ 'id_service_categories' => [ @@ -59,12 +68,18 @@ public function down() $this->dbforge->modify_column('services', $fields); - $this->db->query(' - ALTER TABLE `' . $this->db->dbprefix('services') . '` - ADD CONSTRAINT `services_categories` FOREIGN KEY (`id_categories`) REFERENCES `' . $this->db->dbprefix('categories') . '` (`id`) + $this->db->query( + ' + ALTER TABLE `' . + $this->db->dbprefix('services') . + '` + ADD CONSTRAINT `services_categories` FOREIGN KEY (`id_categories`) REFERENCES `' . + $this->db->dbprefix('categories') . + '` (`id`) ON DELETE SET NULL ON UPDATE CASCADE - '); + ' + ); } } } diff --git a/application/migrations/048_create_blocked_periods_table.php b/application/migrations/048_create_blocked_periods_table.php index 4b262a5a0a..33cac59b60 100644 --- a/application/migrations/048_create_blocked_periods_table.php +++ b/application/migrations/048_create_blocked_periods_table.php @@ -11,50 +11,50 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Create_blocked_periods_table extends EA_Migration { +class Migration_Create_blocked_periods_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->table_exists('blocked_periods')) - { + if (!$this->db->table_exists('blocked_periods')) { $this->dbforge->add_field([ 'id' => [ 'type' => 'INT', 'constraint' => 11, - 'auto_increment' => TRUE + 'auto_increment' => true ], 'create_datetime' => [ 'type' => 'DATETIME', - 'null' => TRUE + 'null' => true ], 'update_datetime' => [ 'type' => 'DATETIME', - 'null' => TRUE + 'null' => true ], 'name' => [ 'type' => 'VARCHAR', 'constraint' => '256', - 'null' => TRUE, + 'null' => true ], 'start_datetime' => [ 'type' => 'DATETIME', - 'null' => TRUE, + 'null' => true ], 'end_datetime' => [ 'type' => 'DATETIME', - 'null' => TRUE, + 'null' => true ], 'notes' => [ 'type' => 'TEXT', - 'null' => TRUE, - ], + 'null' => true + ] ]); - $this->dbforge->add_key('id', TRUE); + $this->dbforge->add_key('id', true); - $this->dbforge->create_table('blocked_periods', TRUE, ['engine' => 'InnoDB']); + $this->dbforge->create_table('blocked_periods', true, ['engine' => 'InnoDB']); } } @@ -63,8 +63,7 @@ public function up() */ public function down() { - if ($this->db->table_exists('blocked_periods')) - { + if ($this->db->table_exists('blocked_periods')) { $this->dbforge->drop_table('blocked_periods'); } } diff --git a/application/migrations/049_add_blocked_periods_column_to_roles_table.php b/application/migrations/049_add_blocked_periods_column_to_roles_table.php index 62662df40b..46c002ad84 100644 --- a/application/migrations/049_add_blocked_periods_column_to_roles_table.php +++ b/application/migrations/049_add_blocked_periods_column_to_roles_table.php @@ -11,19 +11,19 @@ * @since v1.4.0 * ---------------------------------------------------------------------------- */ -class Migration_Add_blocked_periods_column_to_roles_table extends EA_Migration { +class Migration_Add_blocked_periods_column_to_roles_table extends EA_Migration +{ /** * Upgrade method. */ public function up() { - if ( ! $this->db->field_exists('blocked_periods', 'roles')) - { + if (!$this->db->field_exists('blocked_periods', 'roles')) { $fields = [ 'blocked_periods' => [ 'type' => 'INT', 'constraint' => '11', - 'null' => TRUE + 'null' => true ] ]; @@ -40,8 +40,7 @@ public function up() */ public function down() { - if ($this->db->field_exists('blocked_periods', 'roles')) - { + if ($this->db->field_exists('blocked_periods', 'roles')) { $this->dbforge->drop_column('roles', 'blocked_periods'); } } diff --git a/application/models/Admins_model.php b/application/models/Admins_model.php index 1a9319b5c7..2203aad870 100644 --- a/application/models/Admins_model.php +++ b/application/models/Admins_model.php @@ -18,13 +18,14 @@ * * @package Models */ -class Admins_model extends EA_Model { +class Admins_model extends EA_Model +{ /** * @var array */ protected array $casts = [ 'id' => 'integer', - 'id_roles' => 'integer', + 'id_roles' => 'integer' ]; /** @@ -44,7 +45,7 @@ class Admins_model extends EA_Model { 'timezone' => 'timezone', 'language' => 'language', 'notes' => 'notes', - 'roleId' => 'id_roles', + 'roleId' => 'id_roles' ]; /** @@ -61,12 +62,9 @@ public function save(array $admin): int { $this->validate($admin); - if (empty($admin['id'])) - { + if (empty($admin['id'])) { return $this->insert($admin); - } - else - { + } else { return $this->update($admin); } } @@ -81,73 +79,70 @@ public function save(array $admin): int public function validate(array $admin) { // If an admin ID is provided then check whether the record really exists in the database. - if ( ! empty($admin['id'])) - { + if (!empty($admin['id'])) { $count = $this->db->get_where('users', ['id' => $admin['id']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided admin ID does not exist in the database: ' . $admin['id']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided admin ID does not exist in the database: ' . $admin['id'] + ); } } // Make sure all required fields are provided. if ( - empty($admin['first_name']) - || empty($admin['last_name']) - || empty($admin['email']) - || empty($admin['phone_number']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($admin, TRUE)); + empty($admin['first_name']) || + empty($admin['last_name']) || + empty($admin['email']) || + empty($admin['phone_number']) + ) { + throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($admin, true)); } // Validate the email address. - if ( ! filter_var($admin['email'], FILTER_VALIDATE_EMAIL)) - { + if (!filter_var($admin['email'], FILTER_VALIDATE_EMAIL)) { throw new InvalidArgumentException('Invalid email address provided: ' . $admin['email']); } // Make sure the username is unique. - if ( ! empty($admin['settings']['username'])) - { - $admin_id = $admin['id'] ?? NULL; + if (!empty($admin['settings']['username'])) { + $admin_id = $admin['id'] ?? null; - if ( ! $this->validate_username($admin['settings']['username'], $admin_id)) - { - throw new InvalidArgumentException('The provided username is already in use, please use a different one.'); + if (!$this->validate_username($admin['settings']['username'], $admin_id)) { + throw new InvalidArgumentException( + 'The provided username is already in use, please use a different one.' + ); } } // Validate the password. - if ( ! empty($admin['settings']['password'])) - { - if (strlen($admin['settings']['password']) < MIN_PASSWORD_LENGTH) - { - throw new InvalidArgumentException('The admin password must be at least ' . MIN_PASSWORD_LENGTH . ' characters long.'); + if (!empty($admin['settings']['password'])) { + if (strlen($admin['settings']['password']) < MIN_PASSWORD_LENGTH) { + throw new InvalidArgumentException( + 'The admin password must be at least ' . MIN_PASSWORD_LENGTH . ' characters long.' + ); } } // New users must always have a password value set. - if (empty($admin['id']) && empty($admin['settings']['password'])) - { + if (empty($admin['id']) && empty($admin['settings']['password'])) { throw new InvalidArgumentException('The admin password cannot be empty when inserting a new record.'); } // Validate calendar view type value. if ( - ! empty($admin['settings']['calendar_view']) - && ! in_array($admin['settings']['calendar_view'], [CALENDAR_VIEW_DEFAULT, CALENDAR_VIEW_TABLE]) - ) - { - throw new InvalidArgumentException('The provided calendar view is invalid: ' . $admin['settings']['calendar_view']); + !empty($admin['settings']['calendar_view']) && + !in_array($admin['settings']['calendar_view'], [CALENDAR_VIEW_DEFAULT, CALENDAR_VIEW_TABLE]) + ) { + throw new InvalidArgumentException( + 'The provided calendar view is invalid: ' . $admin['settings']['calendar_view'] + ); } // Make sure the email address is unique. - $admin_id = $admin['id'] ?? NULL; + $admin_id = $admin['id'] ?? null; - $count = $this - ->db + $count = $this->db ->select() ->from('users') ->join('roles', 'roles.id = users.id_roles', 'inner') @@ -157,9 +152,10 @@ public function validate(array $admin) ->get() ->num_rows(); - if ($count > 0) - { - throw new InvalidArgumentException('The provided email address is already in use, please use a different one.'); + if ($count > 0) { + throw new InvalidArgumentException( + 'The provided email address is already in use, please use a different one.' + ); } } @@ -171,20 +167,73 @@ public function validate(array $admin) * * @return bool Returns the validation result. */ - public function validate_username(string $username, int $admin_id = NULL): bool + public function validate_username(string $username, int $admin_id = null): bool { - if ( ! empty($admin_id)) - { + if (!empty($admin_id)) { $this->db->where('id_users !=', $admin_id); } - return $this - ->db - ->from('users') - ->join('user_settings', 'user_settings.id_users = users.id', 'inner') - ->where(['username' => $username]) - ->get() - ->num_rows() === 0; + return $this->db + ->from('users') + ->join('user_settings', 'user_settings.id_users = users.id', 'inner') + ->where(['username' => $username]) + ->get() + ->num_rows() === 0; + } + + /** + * Get all admins that match the provided criteria. + * + * @param array|string|null $where Where conditions. + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. + * + * @return array Returns an array of admins. + */ + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + $role_id = $this->get_admin_role_id(); + + if ($where !== null) { + $this->db->where($where); + } + + if ($order_by !== null) { + $this->db->order_by($order_by); + } + + $admins = $this->db->get_where('users', ['id_roles' => $role_id], $limit, $offset)->result_array(); + + foreach ($admins as &$admin) { + $this->cast($admin); + + $admin['settings'] = $this->db->get_where('user_settings', ['id_users' => $admin['id']])->row_array(); + + unset($admin['settings']['id_users'], $admin['settings']['password'], $admin['settings']['salt']); + } + + return $admins; + } + + /** + * Get the admin role ID. + * + * @return int Returns the role ID. + */ + public function get_admin_role_id(): int + { + $role = $this->db->get_where('roles', ['slug' => DB_SLUG_ADMIN])->row_array(); + + if (empty($role)) { + throw new RuntimeException('The admin role was not found in the database.'); + } + + return $role['id']; } /** @@ -202,15 +251,12 @@ protected function insert(array $admin): int $settings = $admin['settings']; - unset( - $admin['settings'] - ); + unset($admin['settings']); $admin['create_datetime'] = date('Y-m-d H:i:s'); $admin['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->insert('users', $admin)) - { + if (!$this->db->insert('users', $admin)) { throw new RuntimeException('Could not insert admin.'); } @@ -223,6 +269,46 @@ protected function insert(array $admin): int return $admin['id']; } + /** + * Save the admin settings. + * + * @param int $admin_id Admin ID. + * @param array $settings Associative array with the settings data. + * + * @throws InvalidArgumentException + */ + protected function save_settings(int $admin_id, array $settings) + { + if (empty($settings)) { + throw new InvalidArgumentException('The settings argument cannot be empty.'); + } + + // Make sure the settings record exists in the database. + $count = $this->db->get_where('user_settings', ['id_users' => $admin_id])->num_rows(); + + if (!$count) { + $this->db->insert('user_settings', ['id_users' => $admin_id]); + } + + foreach ($settings as $name => $value) { + $this->set_setting($admin_id, $name, $value); + } + } + + /** + * Set the value of an admin setting. + * + * @param int $admin_id Admin ID. + * @param string $name Setting name. + * @param mixed|null $value Setting value. + */ + public function set_setting(int $admin_id, string $name, mixed $value = null) + { + if (!$this->db->update('user_settings', [$name => $value], ['id_users' => $admin_id])) { + throw new RuntimeException('Could not set the new admin setting value: ' . $name); + } + } + /** * Update an existing admin. * @@ -239,16 +325,12 @@ protected function update(array $admin): int $settings['id_users'] = $admin['id']; - unset( - $admin['settings'] - ); + unset($admin['settings']); - if ( ! empty($settings['password'])) - { + if (!empty($settings['password'])) { $existing_settings = $this->db->get_where('user_settings', ['id_users' => $admin['id']])->row_array(); - if (empty($existing_settings)) - { + if (empty($existing_settings)) { throw new RuntimeException('No settings record found for admin with ID: ' . $admin['id']); } @@ -257,8 +339,7 @@ protected function update(array $admin): int $admin['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->update('users', $admin, ['id' => $admin['id']])) - { + if (!$this->db->update('users', $admin, ['id' => $admin['id']])) { throw new RuntimeException('Could not update admin.'); } @@ -280,8 +361,7 @@ public function delete(int $admin_id): void $count = $this->db->get_where('users', ['id_roles' => $role_id])->num_rows(); - if ($count <= 1) - { + if ($count <= 1) { throw new RuntimeException('Record could not be deleted as the app requires at least one admin user.'); } @@ -301,8 +381,7 @@ public function find(int $admin_id): array { $admin = $this->db->get_where('users', ['id' => $admin_id])->row_array(); - if ( ! $admin) - { + if (!$admin) { throw new InvalidArgumentException('The provided admin ID was not found in the database: ' . $admin_id); } @@ -310,11 +389,7 @@ public function find(int $admin_id): array $admin['settings'] = $this->db->get_where('user_settings', ['id_users' => $admin_id])->row_array(); - unset( - $admin['settings']['id_users'], - $admin['settings']['password'], - $admin['settings']['salt'] - ); + unset($admin['settings']['id_users'], $admin['settings']['password'], $admin['settings']['salt']); return $admin; } @@ -331,21 +406,18 @@ public function find(int $admin_id): array */ public function value(int $admin_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($admin_id)) - { + if (empty($admin_id)) { throw new InvalidArgumentException('The admin ID argument cannot be empty.'); } // Check whether the admin exists. $query = $this->db->get_where('users', ['id' => $admin_id]); - if ( ! $query->num_rows()) - { + if (!$query->num_rows()) { throw new InvalidArgumentException('The provided admin ID was not found in the database: ' . $admin_id); } @@ -354,117 +426,13 @@ public function value(int $admin_id, string $field): mixed $this->cast($admin); - if ( ! array_key_exists($field, $admin)) - { + if (!array_key_exists($field, $admin)) { throw new InvalidArgumentException('The requested field was not found in the admin data: ' . $field); } return $admin[$field]; } - /** - * Get all admins that match the provided criteria. - * - * @param array|string|null $where Where conditions. - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. - * - * @return array Returns an array of admins. - */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - $role_id = $this->get_admin_role_id(); - - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by !== NULL) - { - $this->db->order_by($order_by); - } - - $admins = $this->db->get_where('users', ['id_roles' => $role_id], $limit, $offset)->result_array(); - - foreach ($admins as &$admin) - { - $this->cast($admin); - - $admin['settings'] = $this->db->get_where('user_settings', ['id_users' => $admin['id']])->row_array(); - - unset( - $admin['settings']['id_users'], - $admin['settings']['password'], - $admin['settings']['salt'] - ); - } - - return $admins; - } - - /** - * Get the admin role ID. - * - * @return int Returns the role ID. - */ - public function get_admin_role_id(): int - { - $role = $this->db->get_where('roles', ['slug' => DB_SLUG_ADMIN])->row_array(); - - if (empty($role)) - { - throw new RuntimeException('The admin role was not found in the database.'); - } - - return $role['id']; - } - - /** - * Save the admin settings. - * - * @param int $admin_id Admin ID. - * @param array $settings Associative array with the settings data. - * - * @throws InvalidArgumentException - */ - protected function save_settings(int $admin_id, array $settings) - { - if (empty($settings)) - { - throw new InvalidArgumentException('The settings argument cannot be empty.'); - } - - // Make sure the settings record exists in the database. - $count = $this->db->get_where('user_settings', ['id_users' => $admin_id])->num_rows(); - - if ( ! $count) - { - $this->db->insert('user_settings', ['id_users' => $admin_id]); - } - - foreach ($settings as $name => $value) - { - $this->set_setting($admin_id, $name, $value); - } - } - - /** - * Set the value of an admin setting. - * - * @param int $admin_id Admin ID. - * @param string $name Setting name. - * @param mixed|null $value Setting value. - */ - public function set_setting(int $admin_id, string $name, mixed $value = NULL) - { - if ( ! $this->db->update('user_settings', [$name => $value], ['id_users' => $admin_id])) - { - throw new RuntimeException('Could not set the new admin setting value: ' . $name); - } - } - /** * Get the value of an admin setting. * @@ -477,8 +445,7 @@ public function get_setting(int $admin_id, string $name): string { $settings = $this->db->get_where('user_settings', ['id_users' => $admin_id])->row_array(); - if ( ! array_key_exists($name, $settings)) - { + if (!array_key_exists($name, $settings)) { throw new RuntimeException('The requested setting value was not found: ' . $admin_id); } @@ -507,12 +474,11 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of admins. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { $role_id = $this->get_admin_role_id(); - $admins = $this - ->db + $admins = $this->db ->select() ->from('users') ->where('id_roles', $role_id) @@ -535,17 +501,12 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($admins as &$admin) - { + foreach ($admins as &$admin) { $this->cast($admin); $admin['settings'] = $this->db->get_where('user_settings', ['id_users' => $admin['id']])->row_array(); - unset( - $admin['settings']['id_users'], - $admin['settings']['password'], - $admin['settings']['salt'] - ); + unset($admin['settings']['id_users'], $admin['settings']['password'], $admin['settings']['salt']); } return $admins; @@ -572,7 +533,7 @@ public function load(array &$admin, array $resources) public function api_encode(array &$admin) { $encoded_resource = [ - 'id' => array_key_exists('id', $admin) ? (int)$admin['id'] : NULL, + 'id' => array_key_exists('id', $admin) ? (int) $admin['id'] : null, 'firstName' => $admin['first_name'], 'lastName' => $admin['last_name'], 'email' => $admin['email'], @@ -600,95 +561,79 @@ public function api_encode(array &$admin) * @param array $admin API resource. * @param array|null $base Base admin data to be overwritten with the provided values (useful for updates). */ - public function api_decode(array &$admin, array $base = NULL) + public function api_decode(array &$admin, array $base = null) { $decoded_resource = $base ?? []; - if (array_key_exists('id', $admin)) - { + if (array_key_exists('id', $admin)) { $decoded_resource['id'] = $admin['id']; } - if (array_key_exists('firstName', $admin)) - { + if (array_key_exists('firstName', $admin)) { $decoded_resource['first_name'] = $admin['firstName']; } - if (array_key_exists('lastName', $admin)) - { + if (array_key_exists('lastName', $admin)) { $decoded_resource['last_name'] = $admin['lastName']; } - if (array_key_exists('email', $admin)) - { + if (array_key_exists('email', $admin)) { $decoded_resource['email'] = $admin['email']; } - if (array_key_exists('mobile', $admin)) - { + if (array_key_exists('mobile', $admin)) { $decoded_resource['mobile_number'] = $admin['mobile']; } - if (array_key_exists('phone', $admin)) - { + if (array_key_exists('phone', $admin)) { $decoded_resource['phone_number'] = $admin['phone']; } - if (array_key_exists('address', $admin)) - { + if (array_key_exists('address', $admin)) { $decoded_resource['address'] = $admin['address']; } - if (array_key_exists('city', $admin)) - { + if (array_key_exists('city', $admin)) { $decoded_resource['city'] = $admin['city']; } - if (array_key_exists('state', $admin)) - { + if (array_key_exists('state', $admin)) { $decoded_resource['state'] = $admin['state']; } - if (array_key_exists('zip', $admin)) - { + if (array_key_exists('zip', $admin)) { $decoded_resource['zip_code'] = $admin['zip']; } - if (array_key_exists('notes', $admin)) - { + if (array_key_exists('notes', $admin)) { $decoded_resource['notes'] = $admin['notes']; } - if (array_key_exists('timezone', $admin)) - { + if (array_key_exists('timezone', $admin)) { $decoded_resource['timezone'] = $admin['timezone']; } - if (array_key_exists('settings', $admin)) - { - if (empty($decoded_resource['settings'])) - { + if (array_key_exists('settings', $admin)) { + if (empty($decoded_resource['settings'])) { $decoded_resource['settings'] = []; } - if (array_key_exists('username', $admin['settings'])) - { + if (array_key_exists('username', $admin['settings'])) { $decoded_resource['settings']['username'] = $admin['settings']['username']; } - if (array_key_exists('password', $admin['settings'])) - { + if (array_key_exists('password', $admin['settings'])) { $decoded_resource['settings']['password'] = $admin['settings']['password']; } - if (array_key_exists('notifications', $admin['settings'])) - { - $decoded_resource['settings']['notifications'] = filter_var($admin['settings']['notifications'], - FILTER_VALIDATE_BOOLEAN); + if (array_key_exists('notifications', $admin['settings'])) { + $decoded_resource['settings']['notifications'] = filter_var( + $admin['settings']['notifications'], + FILTER_VALIDATE_BOOLEAN + ); } - if (array_key_exists('calendarView', $admin['settings'])) - { + if (array_key_exists('calendarView', $admin['settings'])) { $decoded_resource['settings']['calendar_view'] = $admin['settings']['calendarView']; } } diff --git a/application/models/Appointments_model.php b/application/models/Appointments_model.php index 835ccd0346..dc0f283fae 100644 --- a/application/models/Appointments_model.php +++ b/application/models/Appointments_model.php @@ -16,7 +16,8 @@ * * @package Models */ -class Appointments_model extends EA_Model { +class Appointments_model extends EA_Model +{ /** * @var array */ @@ -25,7 +26,7 @@ class Appointments_model extends EA_Model { 'is_unavailability' => 'boolean', 'id_users_provider' => 'integer', 'id_users_customer' => 'integer', - 'id_services' => 'integer', + 'id_services' => 'integer' ]; /** @@ -44,10 +45,9 @@ class Appointments_model extends EA_Model { 'serviceId' => 'id_services', 'providerId' => 'id_users_provider', 'customerId' => 'id_users_customer', - 'googleCalendarId' => 'id_google_calendar', + 'googleCalendarId' => 'id_google_calendar' ]; - /** * Save (insert or update) an appointment. * @@ -61,12 +61,9 @@ public function save(array $appointment): int { $this->validate($appointment); - if (empty($appointment['id'])) - { + if (empty($appointment['id'])) { return $this->insert($appointment); - } - else - { + } else { return $this->update($appointment); } } @@ -81,13 +78,13 @@ public function save(array $appointment): int public function validate(array $appointment) { // If an appointment ID is provided then check whether the record really exists in the database. - if ( ! empty($appointment['id'])) - { + if (!empty($appointment['id'])) { $count = $this->db->get_where('appointments', ['id' => $appointment['id']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided appointment ID does not exist in the database: ' . $appointment['id']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided appointment ID does not exist in the database: ' . $appointment['id'] + ); } } @@ -96,39 +93,36 @@ public function validate(array $appointment) $require_notes = filter_var(setting('require_notes'), FILTER_VALIDATE_BOOLEAN); if ( - empty($appointment['start_datetime']) - || empty($appointment['end_datetime']) - || empty($appointment['id_services']) - || empty($appointment['id_users_provider']) - || empty($appointment['id_users_customer']) - || (empty($appointment['notes']) && $require_notes) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($appointment, TRUE)); + empty($appointment['start_datetime']) || + empty($appointment['end_datetime']) || + empty($appointment['id_services']) || + empty($appointment['id_users_provider']) || + empty($appointment['id_users_customer']) || + (empty($appointment['notes']) && $require_notes) + ) { + throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($appointment, true)); } // Make sure that the provided appointment date time values are valid. - if ( ! validate_datetime($appointment['start_datetime'])) - { + if (!validate_datetime($appointment['start_datetime'])) { throw new InvalidArgumentException('The appointment start date time is invalid.'); } - if ( ! validate_datetime($appointment['end_datetime'])) - { + if (!validate_datetime($appointment['end_datetime'])) { throw new InvalidArgumentException('The appointment end date time is invalid.'); } // Make the appointment lasts longer than the minimum duration (in minutes). $diff = (strtotime($appointment['end_datetime']) - strtotime($appointment['start_datetime'])) / 60; - if ($diff < EVENT_MINIMUM_DURATION) - { - throw new InvalidArgumentException('The appointment duration cannot be less than ' . EVENT_MINIMUM_DURATION . ' minutes.'); + if ($diff < EVENT_MINIMUM_DURATION) { + throw new InvalidArgumentException( + 'The appointment duration cannot be less than ' . EVENT_MINIMUM_DURATION . ' minutes.' + ); } // Make sure the provider ID really exists in the database. - $count = $this - ->db + $count = $this->db ->select() ->from('users') ->join('roles', 'roles.id = users.id_roles', 'inner') @@ -137,16 +131,15 @@ public function validate(array $appointment) ->get() ->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The appointment provider ID was not found in the database: ' . $appointment['id_users_provider']); + if (!$count) { + throw new InvalidArgumentException( + 'The appointment provider ID was not found in the database: ' . $appointment['id_users_provider'] + ); } - if ( ! filter_var($appointment['is_unavailability'], FILTER_VALIDATE_BOOLEAN)) - { + if (!filter_var($appointment['is_unavailability'], FILTER_VALIDATE_BOOLEAN)) { // Make sure the customer ID really exists in the database. - $count = $this - ->db + $count = $this->db ->select() ->from('users') ->join('roles', 'roles.id = users.id_roles', 'inner') @@ -155,21 +148,56 @@ public function validate(array $appointment) ->get() ->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The appointment customer ID was not found in the database: ' . $appointment['id_users_customer']); + if (!$count) { + throw new InvalidArgumentException( + 'The appointment customer ID was not found in the database: ' . $appointment['id_users_customer'] + ); } // Make sure the service ID really exists in the database. $count = $this->db->get_where('services', ['id' => $appointment['id_services']])->num_rows(); - if ( ! $count) - { + if (!$count) { throw new InvalidArgumentException('Appointment service id is invalid.'); } } } + /** + * Get all appointments that match the provided criteria. + * + * @param array|string|null $where Where conditions. + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. + * + * @return array Returns an array of appointments. + */ + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + if ($where !== null) { + $this->db->where($where); + } + + if ($order_by) { + $this->db->order_by($order_by); + } + + $appointments = $this->db + ->get_where('appointments', ['is_unavailability' => false], $limit, $offset) + ->result_array(); + + foreach ($appointments as &$appointment) { + $this->cast($appointment); + } + + return $appointments; + } + /** * Insert a new appointment into the database. * @@ -186,8 +214,7 @@ protected function insert(array $appointment): int $appointment['update_datetime'] = date('Y-m-d H:i:s'); $appointment['hash'] = random_string('alnum', 12); - if ( ! $this->db->insert('appointments', $appointment)) - { + if (!$this->db->insert('appointments', $appointment)) { throw new RuntimeException('Could not insert appointment.'); } @@ -207,8 +234,7 @@ protected function update(array $appointment): int { $appointment['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->update('appointments', $appointment, ['id' => $appointment['id']])) - { + if (!$this->db->update('appointments', $appointment, ['id' => $appointment['id']])) { throw new RuntimeException('Could not update appointment record.'); } @@ -240,9 +266,10 @@ public function find(int $appointment_id): array { $appointment = $this->db->get_where('appointments', ['id' => $appointment_id])->row_array(); - if ( ! $appointment) - { - throw new InvalidArgumentException('The provided appointment ID was not found in the database: ' . $appointment_id); + if (!$appointment) { + throw new InvalidArgumentException( + 'The provided appointment ID was not found in the database: ' . $appointment_id + ); } $this->cast($appointment); @@ -262,22 +289,21 @@ public function find(int $appointment_id): array */ public function value(int $appointment_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($appointment_id)) - { + if (empty($appointment_id)) { throw new InvalidArgumentException('The appointment ID argument cannot be empty.'); } // Check whether the appointment exists. $query = $this->db->get_where('appointments', ['id' => $appointment_id]); - if ( ! $query->num_rows()) - { - throw new InvalidArgumentException('The provided appointment ID was not found in the database: ' . $appointment_id); + if (!$query->num_rows()) { + throw new InvalidArgumentException( + 'The provided appointment ID was not found in the database: ' . $appointment_id + ); } // Check if the required field is part of the appointment data. @@ -285,46 +311,13 @@ public function value(int $appointment_id, string $field): mixed $this->cast($appointment); - if ( ! array_key_exists($field, $appointment)) - { + if (!array_key_exists($field, $appointment)) { throw new InvalidArgumentException('The requested field was not found in the appointment data: ' . $field); } return $appointment[$field]; } - /** - * Get all appointments that match the provided criteria. - * - * @param array|string|null $where Where conditions. - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. - * - * @return array Returns an array of appointments. - */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by) - { - $this->db->order_by($order_by); - } - - $appointments = $this->db->get_where('appointments', ['is_unavailability' => FALSE], $limit, $offset)->result_array(); - - foreach ($appointments as &$appointment) - { - $this->cast($appointment); - } - - return $appointments; - } - /** * Remove all the Google Calendar event IDs from appointment records. * @@ -332,7 +325,7 @@ public function get(array|string $where = NULL, int $limit = NULL, int $offset = */ public function clear_google_sync_ids(int $provider_id) { - $this->db->update('appointments', ['id_google_calendar' => NULL], ['id_users_provider' => $provider_id]); + $this->db->update('appointments', ['id_google_calendar' => null], ['id_users_provider' => $provider_id]); } /** @@ -346,15 +339,18 @@ public function clear_google_sync_ids(int $provider_id) * * @return int Returns the number of appointments that match the provided criteria. */ - public function get_attendants_number_for_period(DateTime $start, DateTime $end, int $service_id, int $provider_id, int $exclude_appointment_id = NULL): int - { - if ($exclude_appointment_id) - { + public function get_attendants_number_for_period( + DateTime $start, + DateTime $end, + int $service_id, + int $provider_id, + int $exclude_appointment_id = null + ): int { + if ($exclude_appointment_id) { $this->db->where('id !=', $exclude_appointment_id); } - $result = $this - ->db + $result = $this->db ->select('count(*) AS attendants_number') ->from('appointments') ->group_start() @@ -387,15 +383,18 @@ public function get_attendants_number_for_period(DateTime $start, DateTime $end, * * @return int Returns the number of appointments that match the provided criteria. */ - public function get_other_service_attendants_number(DateTime $start, DateTime $end, int $service_id, int $provider_id, int $exclude_appointment_id = NULL): int - { - if ($exclude_appointment_id) - { + public function get_other_service_attendants_number( + DateTime $start, + DateTime $end, + int $service_id, + int $provider_id, + int $exclude_appointment_id = null + ): int { + if ($exclude_appointment_id) { $this->db->where('id !=', $exclude_appointment_id); } - $result = $this - ->db + $result = $this->db ->select('count(*) AS attendants_number') ->from('appointments') ->group_start() @@ -436,16 +435,15 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of appointments. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { - $appointments = $this - ->db + $appointments = $this->db ->select('appointments.*') ->from('appointments') ->join('services', 'services.id = appointments.id_services', 'left') ->join('users AS providers', 'providers.id = appointments.id_users_provider', 'inner') ->join('users AS customers', 'customers.id = appointments.id_users_customer', 'left') - ->where('is_unavailability', FALSE) + ->where('is_unavailability', false) ->group_start() ->like('appointments.start_datetime', $keyword) ->or_like('appointments.end_datetime', $keyword) @@ -469,8 +467,7 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($appointments as &$appointment) - { + foreach ($appointments as &$appointment) { $this->cast($appointment); } @@ -487,44 +484,40 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s */ public function load(array &$appointment, array $resources) { - if (empty($appointment) || empty($resources)) - { + if (empty($appointment) || empty($resources)) { return; } - foreach ($resources as $resource) - { - switch ($resource) - { + foreach ($resources as $resource) { + switch ($resource) { case 'service': - $appointment['service'] = $this - ->db + $appointment['service'] = $this->db ->get_where('services', [ - 'id' => $appointment['id_services'] ?? $appointment['serviceId'] ?? NULL + 'id' => $appointment['id_services'] ?? ($appointment['serviceId'] ?? null) ]) ->row_array(); break; case 'provider': - $appointment['provider'] = $this - ->db + $appointment['provider'] = $this->db ->get_where('users', [ - 'id' => $appointment['id_users_provider'] ?? $appointment['providerId'] ?? NULL + 'id' => $appointment['id_users_provider'] ?? ($appointment['providerId'] ?? null) ]) ->row_array(); break; case 'customer': - $appointment['customer'] = $this - ->db + $appointment['customer'] = $this->db ->get_where('users', [ - 'id' => $appointment['id_users_customer'] ?? $appointment['customerId'] ?? NULL + 'id' => $appointment['id_users_customer'] ?? ($appointment['customerId'] ?? null) ]) ->row_array(); break; default: - throw new InvalidArgumentException('The requested appointment relation is not supported: ' . $resource); + throw new InvalidArgumentException( + 'The requested appointment relation is not supported: ' . $resource + ); } } } @@ -537,7 +530,7 @@ public function load(array &$appointment, array $resources) public function api_encode(array &$appointment) { $encoded_resource = [ - 'id' => array_key_exists('id', $appointment) ? (int)$appointment['id'] : NULL, + 'id' => array_key_exists('id', $appointment) ? (int) $appointment['id'] : null, 'book' => $appointment['book_datetime'], 'start' => $appointment['start_datetime'], 'end' => $appointment['end_datetime'], @@ -546,10 +539,11 @@ public function api_encode(array &$appointment) 'status' => $appointment['status'], 'location' => $appointment['location'], 'notes' => $appointment['notes'], - 'customerId' => $appointment['id_users_customer'] !== NULL ? (int)$appointment['id_users_customer'] : NULL, - 'providerId' => $appointment['id_users_provider'] !== NULL ? (int)$appointment['id_users_provider'] : NULL, - 'serviceId' => $appointment['id_services'] !== NULL ? (int)$appointment['id_services'] : NULL, - 'googleCalendarId' => $appointment['id_google_calendar'] !== NULL ? (int)$appointment['id_google_calendar'] : NULL + 'customerId' => $appointment['id_users_customer'] !== null ? (int) $appointment['id_users_customer'] : null, + 'providerId' => $appointment['id_users_provider'] !== null ? (int) $appointment['id_users_provider'] : null, + 'serviceId' => $appointment['id_services'] !== null ? (int) $appointment['id_services'] : null, + 'googleCalendarId' => + $appointment['id_google_calendar'] !== null ? (int) $appointment['id_google_calendar'] : null ]; $appointment = $encoded_resource; @@ -561,66 +555,55 @@ public function api_encode(array &$appointment) * @param array $appointment API resource. * @param array|null $base Base appointment data to be overwritten with the provided values (useful for updates). */ - public function api_decode(array &$appointment, array $base = NULL) + public function api_decode(array &$appointment, array $base = null) { $decoded_request = $base ?: []; - if (array_key_exists('id', $appointment)) - { + if (array_key_exists('id', $appointment)) { $decoded_request['id'] = $appointment['id']; } - if (array_key_exists('book', $appointment)) - { + if (array_key_exists('book', $appointment)) { $decoded_request['book_datetime'] = $appointment['book']; } - if (array_key_exists('start', $appointment)) - { + if (array_key_exists('start', $appointment)) { $decoded_request['start_datetime'] = $appointment['start']; } - if (array_key_exists('end', $appointment)) - { + if (array_key_exists('end', $appointment)) { $decoded_request['end_datetime'] = $appointment['end']; } - if (array_key_exists('hash', $appointment)) - { + if (array_key_exists('hash', $appointment)) { $decoded_request['hash'] = $appointment['hash']; } - if (array_key_exists('location', $appointment)) - { + if (array_key_exists('location', $appointment)) { $decoded_request['location'] = $appointment['location']; } - if (array_key_exists('notes', $appointment)) - { + if (array_key_exists('notes', $appointment)) { $decoded_request['notes'] = $appointment['notes']; } - if (array_key_exists('customerId', $appointment)) - { + if (array_key_exists('customerId', $appointment)) { $decoded_request['id_users_customer'] = $appointment['customerId']; } - if (array_key_exists('providerId', $appointment)) - { + if (array_key_exists('providerId', $appointment)) { $decoded_request['id_users_provider'] = $appointment['providerId']; } - if (array_key_exists('serviceId', $appointment)) - { + if (array_key_exists('serviceId', $appointment)) { $decoded_request['id_services'] = $appointment['serviceId']; } - if (array_key_exists('googleCalendarId', $appointment)) - { + if (array_key_exists('googleCalendarId', $appointment)) { $decoded_request['id_google_calendar'] = $appointment['googleCalendarId']; } - $decoded_request['is_unavailability'] = FALSE; + $decoded_request['is_unavailability'] = false; $appointment = $decoded_request; } diff --git a/application/models/Blocked_periods_model.php b/application/models/Blocked_periods_model.php index b7cdc9a941..9c2982d9f9 100644 --- a/application/models/Blocked_periods_model.php +++ b/application/models/Blocked_periods_model.php @@ -18,12 +18,13 @@ * * @package Models */ -class Blocked_periods_model extends EA_Model { +class Blocked_periods_model extends EA_Model +{ /** * @var array */ protected array $casts = [ - 'id' => 'integer', + 'id' => 'integer' ]; /** @@ -34,7 +35,7 @@ class Blocked_periods_model extends EA_Model { 'name' => 'name', 'start' => 'start_datetime', 'end' => 'end_datetime', - 'notes' => 'notes', + 'notes' => 'notes' ]; /** @@ -50,12 +51,9 @@ public function save(array $blocked_period): int { $this->validate($blocked_period); - if (empty($blocked_period['id'])) - { + if (empty($blocked_period['id'])) { return $this->insert($blocked_period); - } - else - { + } else { return $this->update($blocked_period); } } @@ -70,32 +68,32 @@ public function save(array $blocked_period): int public function validate(array $blocked_period) { // If a blocked-period ID is provided then check whether the record really exists in the database. - if ( ! empty($blocked_period['id'])) - { + if (!empty($blocked_period['id'])) { $count = $this->db->get_where('blocked_periods', ['id' => $blocked_period['id']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided blocked-period ID does not exist in the database: ' . $blocked_period['id']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided blocked-period ID does not exist in the database: ' . $blocked_period['id'] + ); } } // Make sure all required fields are provided. if ( - empty($blocked_period['name']) - || empty($blocked_period['start_datetime']) - || empty($blocked_period['end_datetime']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($blocked_period, TRUE)); + empty($blocked_period['name']) || + empty($blocked_period['start_datetime']) || + empty($blocked_period['end_datetime']) + ) { + throw new InvalidArgumentException( + 'Not all required fields are provided: ' . print_r($blocked_period, true) + ); } - // Make sure that the start date time is before the end. + // Make sure that the start date time is before the end. $start_date_time_object = new DateTime($blocked_period['start_datetime']); $end_date_time_object = new DateTime($blocked_period['end_datetime']); - if ($start_date_time_object >= $end_date_time_object) - { + if ($start_date_time_object >= $end_date_time_object) { throw new InvalidArgumentException('The start must be before the end date time value.'); } } @@ -114,8 +112,7 @@ protected function insert(array $blocked_period): int $blocked_period['create_datetime'] = date('Y-m-d H:i:s'); $blocked_period['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->insert('blocked_periods', $blocked_period)) - { + if (!$this->db->insert('blocked_periods', $blocked_period)) { throw new RuntimeException('Could not insert blocked-period.'); } @@ -135,8 +132,7 @@ protected function update(array $blocked_period): int { $blocked_period['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->update('blocked_periods', $blocked_period, ['id' => $blocked_period['id']])) - { + if (!$this->db->update('blocked_periods', $blocked_period, ['id' => $blocked_period['id']])) { throw new RuntimeException('Could not update blocked periods.'); } @@ -168,9 +164,10 @@ public function find(int $blocked_period_id): array { $blocked_period = $this->db->get_where('blocked_periods', ['id' => $blocked_period_id])->row_array(); - if ( ! $blocked_period) - { - throw new InvalidArgumentException('The provided blocked-period ID was not found in the database: ' . $blocked_period_id); + if (!$blocked_period) { + throw new InvalidArgumentException( + 'The provided blocked-period ID was not found in the database: ' . $blocked_period_id + ); } $this->cast($blocked_period); @@ -190,22 +187,21 @@ public function find(int $blocked_period_id): array */ public function value(int $blocked_period_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($blocked_period_id)) - { + if (empty($blocked_period_id)) { throw new InvalidArgumentException('The blocked-period ID argument cannot be empty.'); } // Check whether the service exists. $query = $this->db->get_where('blocked_periods', ['id' => $blocked_period_id]); - if ( ! $query->num_rows()) - { - throw new InvalidArgumentException('The provided blocked-period ID was not found in the database: ' . $blocked_period_id); + if (!$query->num_rows()) { + throw new InvalidArgumentException( + 'The provided blocked-period ID was not found in the database: ' . $blocked_period_id + ); } // Check if the required field is part of the blocked-period data. @@ -213,40 +209,41 @@ public function value(int $blocked_period_id, string $field): mixed $this->cast($blocked_period); - if ( ! array_key_exists($field, $blocked_period)) - { - throw new InvalidArgumentException('The requested field was not found in the blocked-period data: ' . $field); + if (!array_key_exists($field, $blocked_period)) { + throw new InvalidArgumentException( + 'The requested field was not found in the blocked-period data: ' . $field + ); } return $blocked_period[$field]; } /** - * Get all services that match the provided criteria. + * Search blocked periods by the provided keyword. * - * @param array|string|null $where Where conditions + * @param string $keyword Search keyword. * @param int|null $limit Record limit. * @param int|null $offset Record offset. * @param string|null $order_by Order by. * * @return array Returns an array of blocked periods. */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by !== NULL) - { - $this->db->order_by($order_by); - } - - $blocked_periods = $this->db->get('blocked_periods', $limit, $offset)->result_array(); + $blocked_periods = $this->db + ->select() + ->from('blocked_periods') + ->group_start() + ->like('name', $keyword) + ->or_like('notes', $keyword) + ->group_end() + ->limit($limit) + ->offset($offset) + ->order_by($order_by) + ->get() + ->result_array(); - foreach ($blocked_periods as &$blocked_period) - { + foreach ($blocked_periods as &$blocked_period) { $this->cast($blocked_period); } @@ -254,43 +251,32 @@ public function get(array|string $where = NULL, int $limit = NULL, int $offset = } /** - * Get the query builder interface, configured for use with the blocked periods table. - * - * @return CI_DB_query_builder - */ - public function query(): CI_DB_query_builder - { - return $this->db->from('blocked_periods'); - } - - /** - * Search blocked periods by the provided keyword. + * Get all services that match the provided criteria. * - * @param string $keyword Search keyword. + * @param array|string|null $where Where conditions * @param int|null $limit Record limit. * @param int|null $offset Record offset. * @param string|null $order_by Order by. * * @return array Returns an array of blocked periods. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - $blocked_periods = $this - ->db - ->select() - ->from('blocked_periods') - ->group_start() - ->like('name', $keyword) - ->or_like('notes', $keyword) - ->group_end() - ->limit($limit) - ->offset($offset) - ->order_by($order_by) - ->get() - ->result_array(); + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + if ($where !== null) { + $this->db->where($where); + } - foreach ($blocked_periods as &$blocked_period) - { + if ($order_by !== null) { + $this->db->order_by($order_by); + } + + $blocked_periods = $this->db->get('blocked_periods', $limit, $offset)->result_array(); + + foreach ($blocked_periods as &$blocked_period) { $this->cast($blocked_period); } @@ -307,7 +293,7 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s */ public function load(array &$blocked_period, array $resources) { - // Blocked periods do not currently have any related resources. + // Blocked periods do not currently have any related resources. } /** @@ -318,11 +304,11 @@ public function load(array &$blocked_period, array $resources) public function api_encode(array &$blocked_period) { $encoded_resource = [ - 'id' => array_key_exists('id', $blocked_period) ? (int)$blocked_period['id'] : NULL, + 'id' => array_key_exists('id', $blocked_period) ? (int) $blocked_period['id'] : null, 'name' => $blocked_period['name'], - 'start' => array_key_exists('start_datetime', $blocked_period) ? $blocked_period['start_datetime'] : NULL, - 'end' => array_key_exists('end_datetime', $blocked_period) ? $blocked_period['end_datetime'] : NULL, - 'notes' => array_key_exists('notes', $blocked_period) ? $blocked_period['notes'] : NULL + 'start' => array_key_exists('start_datetime', $blocked_period) ? $blocked_period['start_datetime'] : null, + 'end' => array_key_exists('end_datetime', $blocked_period) ? $blocked_period['end_datetime'] : null, + 'notes' => array_key_exists('notes', $blocked_period) ? $blocked_period['notes'] : null ]; $blocked_period = $encoded_resource; @@ -334,32 +320,27 @@ public function api_encode(array &$blocked_period) * @param array $blocked_period API resource. * @param array|null $base Base blocked-period data to be overwritten with the provided values (useful for updates). */ - public function api_decode(array &$blocked_period, array $base = NULL) + public function api_decode(array &$blocked_period, array $base = null) { $decoded_resource = $base ?: []; - if (array_key_exists('id', $blocked_period)) - { + if (array_key_exists('id', $blocked_period)) { $decoded_resource['id'] = $blocked_period['id']; } - if (array_key_exists('name', $blocked_period)) - { + if (array_key_exists('name', $blocked_period)) { $decoded_resource['name'] = $blocked_period['name']; } - if (array_key_exists('start', $blocked_period)) - { + if (array_key_exists('start', $blocked_period)) { $decoded_resource['start_datetime'] = $blocked_period['start']; } - if (array_key_exists('end', $blocked_period)) - { + if (array_key_exists('end', $blocked_period)) { $decoded_resource['end_datetime'] = $blocked_period['end']; } - if (array_key_exists('notes', $blocked_period)) - { + if (array_key_exists('notes', $blocked_period)) { $decoded_resource['notes'] = $blocked_period['notes']; } @@ -376,8 +357,7 @@ public function api_decode(array &$blocked_period, array $base = NULL) */ public function get_for_period(string $start_date, string $end_date): array { - return $this - ->query() + return $this->query() // ->group_start() ->where('DATE(start_datetime) <=', $start_date) @@ -403,6 +383,16 @@ public function get_for_period(string $start_date, string $end_date): array ->result_array(); } + /** + * Get the query builder interface, configured for use with the blocked periods table. + * + * @return CI_DB_query_builder + */ + public function query(): CI_DB_query_builder + { + return $this->db->from('blocked_periods'); + } + /** * Check if a date is blocked by a blocked period. * @@ -412,11 +402,10 @@ public function get_for_period(string $start_date, string $end_date): array */ public function is_entire_date_blocked(string $date): bool { - return $this - ->query() - ->where('DATE(start_datetime) <=', $date) - ->where('DATE(end_datetime) >=', $date) - ->get() - ->num_rows() > 1; + return $this->query() + ->where('DATE(start_datetime) <=', $date) + ->where('DATE(end_datetime) >=', $date) + ->get() + ->num_rows() > 1; } } diff --git a/application/models/Consents_model.php b/application/models/Consents_model.php index d34641de24..619032b503 100644 --- a/application/models/Consents_model.php +++ b/application/models/Consents_model.php @@ -18,12 +18,13 @@ * * @package Models */ -class Consents_model extends EA_Model { +class Consents_model extends EA_Model +{ /** * @var array */ protected array $casts = [ - 'id' => 'integer', + 'id' => 'integer' ]; /** @@ -39,17 +40,13 @@ public function save(array $consent): int { $this->validate($consent); - if (empty($consent['id'])) - { + if (empty($consent['id'])) { return $this->insert($consent); - } - else - { + } else { return $this->update($consent); } } - /** * Validate the consent data. * @@ -59,12 +56,8 @@ public function save(array $consent): int */ public function validate(array $consent) { - if ( - empty($consent['ip']) - || empty($consent['type']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($consent, TRUE)); + if (empty($consent['ip']) || empty($consent['type'])) { + throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($consent, true)); } } @@ -82,8 +75,7 @@ protected function insert(array $consent): int $consent['create_datetime'] = date('Y-m-d H:i:s'); $consent['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->insert('consents', $consent)) - { + if (!$this->db->insert('consents', $consent)) { throw new RuntimeException('Could not insert consent.'); } @@ -103,8 +95,7 @@ protected function update(array $consent): int { $consent['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->update('consents', $consent, ['id' => $consent['id']])) - { + if (!$this->db->update('consents', $consent, ['id' => $consent['id']])) { throw new RuntimeException('Could not update consent.'); } @@ -134,8 +125,7 @@ public function find(int $consent_id): array { $consent = $this->db->get_where('consents', ['id' => $consent_id])->row_array(); - if ( ! $consent) - { + if (!$consent) { throw new InvalidArgumentException('The provided consent ID was not found in the database: ' . $consent_id); } @@ -156,21 +146,18 @@ public function find(int $consent_id): array */ public function value(int $consent_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($consent_id)) - { + if (empty($consent_id)) { throw new InvalidArgumentException('The consent ID argument cannot be empty.'); } // Check whether the consent exists. $query = $this->db->get_where('consents', ['id' => $consent_id]); - if ( ! $query->num_rows()) - { + if (!$query->num_rows()) { throw new InvalidArgumentException('The provided consent ID was not found in the database: ' . $consent_id); } @@ -179,48 +166,13 @@ public function value(int $consent_id, string $field): mixed $this->cast($consent); - if ( ! array_key_exists($field, $consent)) - { + if (!array_key_exists($field, $consent)) { throw new InvalidArgumentException('The requested field was not found in the consent data: ' . $field); } return $consent[$field]; } - /** - * Get all consents that match the provided criteria. - * - * @param array|string|null $where Where conditions. - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. - * - * @return array Returns an array of consents. - */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by !== NULL) - { - $this->db->order_by($order_by); - } - - - - $consents = $this->db->get('consents', $limit, $offset)->result_array(); - - foreach ($consents as &$consent) - { - $this->cast($consent); - } - - return $consents; - } - /** * Get the query builder interface, configured for use with the consents table. * @@ -241,10 +193,9 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of consents. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { - $consents = $this - ->db + $consents = $this->db ->select() ->from('consents') ->group_start() @@ -259,8 +210,40 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($consents as &$consent) - { + foreach ($consents as &$consent) { + $this->cast($consent); + } + + return $consents; + } + + /** + * Get all consents that match the provided criteria. + * + * @param array|string|null $where Where conditions. + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. + * + * @return array Returns an array of consents. + */ + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + if ($where !== null) { + $this->db->where($where); + } + + if ($order_by !== null) { + $this->db->order_by($order_by); + } + + $consents = $this->db->get('consents', $limit, $offset)->result_array(); + + foreach ($consents as &$consent) { $this->cast($consent); } diff --git a/application/models/Providers_model.php b/application/models/Providers_model.php index abc1e662b2..0153d37e7d 100755 --- a/application/models/Providers_model.php +++ b/application/models/Providers_model.php @@ -18,14 +18,15 @@ * * @package Models */ -class Providers_model extends EA_Model { +class Providers_model extends EA_Model +{ /** * @var array */ protected array $casts = [ 'id' => 'integer', 'is_private' => 'boolean', - 'id_roles' => 'integer', + 'id_roles' => 'integer' ]; /** @@ -46,7 +47,7 @@ class Providers_model extends EA_Model { 'language' => 'language', 'notes' => 'notes', 'isPrivate' => 'is_private', - 'roleId' => 'id_roles', + 'roleId' => 'id_roles' ]; /** @@ -63,12 +64,9 @@ public function save(array $provider): int { $this->validate($provider); - if (empty($provider['id'])) - { + if (empty($provider['id'])) { return $this->insert($provider); - } - else - { + } else { return $this->update($provider); } } @@ -83,86 +81,82 @@ public function save(array $provider): int public function validate(array $provider) { // If a provider ID is provided then check whether the record really exists in the database. - if ( ! empty($provider['id'])) - { + if (!empty($provider['id'])) { $count = $this->db->get_where('users', ['id' => $provider['id']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided provider ID does not exist in the database: ' . $provider['id']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided provider ID does not exist in the database: ' . $provider['id'] + ); } } // Make sure all required fields are provided. if ( - empty($provider['first_name']) - || empty($provider['last_name']) - || empty($provider['email']) - || empty($provider['phone_number']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($provider, TRUE)); + empty($provider['first_name']) || + empty($provider['last_name']) || + empty($provider['email']) || + empty($provider['phone_number']) + ) { + throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($provider, true)); } // Validate the email address. - if ( ! filter_var($provider['email'], FILTER_VALIDATE_EMAIL)) - { + if (!filter_var($provider['email'], FILTER_VALIDATE_EMAIL)) { throw new InvalidArgumentException('Invalid email address provided: ' . $provider['email']); } // Validate provider services. - if ( ! empty($provider['services'])) - { + if (!empty($provider['services'])) { // Make sure the provided service entries are numeric values. - foreach ($provider['services'] as $service_id) - { - if ( ! is_numeric($service_id)) - { - throw new InvalidArgumentException('The provided provider services are invalid: ' . print_r($provider, TRUE)); + foreach ($provider['services'] as $service_id) { + if (!is_numeric($service_id)) { + throw new InvalidArgumentException( + 'The provided provider services are invalid: ' . print_r($provider, true) + ); } } } // Make sure the username is unique. - if ( ! empty($provider['settings']['username'])) - { - $provider_id = $provider['id'] ?? NULL; + if (!empty($provider['settings']['username'])) { + $provider_id = $provider['id'] ?? null; - if ( ! $this->validate_username($provider['settings']['username'], $provider_id)) - { - throw new InvalidArgumentException('The provided username is already in use, please use a different one.'); + if (!$this->validate_username($provider['settings']['username'], $provider_id)) { + throw new InvalidArgumentException( + 'The provided username is already in use, please use a different one.' + ); } } // Validate the password. - if ( ! empty($provider['settings']['password'])) - { - if (strlen($provider['settings']['password']) < MIN_PASSWORD_LENGTH) - { - throw new InvalidArgumentException('The provider password must be at least ' . MIN_PASSWORD_LENGTH . ' characters long.'); + if (!empty($provider['settings']['password'])) { + if (strlen($provider['settings']['password']) < MIN_PASSWORD_LENGTH) { + throw new InvalidArgumentException( + 'The provider password must be at least ' . MIN_PASSWORD_LENGTH . ' characters long.' + ); } } // New users must always have a password value set. - if (empty($provider['id']) && empty($provider['settings']['password'])) - { + if (empty($provider['id']) && empty($provider['settings']['password'])) { throw new InvalidArgumentException('The provider password cannot be empty when inserting a new record.'); } // Validate calendar view type value. if ( - ! empty($provider['settings']['calendar_view']) - && ! in_array($provider['settings']['calendar_view'], [CALENDAR_VIEW_DEFAULT, CALENDAR_VIEW_TABLE]) - ) - { - throw new InvalidArgumentException('The provided calendar view is invalid: ' . $provider['settings']['calendar_view']); + !empty($provider['settings']['calendar_view']) && + !in_array($provider['settings']['calendar_view'], [CALENDAR_VIEW_DEFAULT, CALENDAR_VIEW_TABLE]) + ) { + throw new InvalidArgumentException( + 'The provided calendar view is invalid: ' . $provider['settings']['calendar_view'] + ); } // Make sure the email address is unique. - $provider_id = $provider['id'] ?? NULL; + $provider_id = $provider['id'] ?? null; - $count = $this - ->db + $count = $this->db ->select() ->from('users') ->join('roles', 'roles.id = users.id_roles', 'inner') @@ -172,9 +166,10 @@ public function validate(array $provider) ->get() ->num_rows(); - if ($count > 0) - { - throw new InvalidArgumentException('The provided email address is already in use, please use a different one.'); + if ($count > 0) { + throw new InvalidArgumentException( + 'The provided email address is already in use, please use a different one.' + ); } } @@ -186,20 +181,83 @@ public function validate(array $provider) * * @return bool Returns the validation result. */ - public function validate_username(string $username, int $provider_id = NULL): bool + public function validate_username(string $username, int $provider_id = null): bool { - if ( ! empty($provider_id)) - { + if (!empty($provider_id)) { $this->db->where('id_users !=', $provider_id); } - return $this - ->db - ->from('users') - ->join('user_settings', 'user_settings.id_users = users.id', 'inner') - ->where(['username' => $username]) - ->get() - ->num_rows() === 0; + return $this->db + ->from('users') + ->join('user_settings', 'user_settings.id_users = users.id', 'inner') + ->where(['username' => $username]) + ->get() + ->num_rows() === 0; + } + + /** + * Get all providers that match the provided criteria. + * + * @param array|string|null $where Where conditions + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. + * + * @return array Returns an array of providers. + */ + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + $role_id = $this->get_provider_role_id(); + + if ($where !== null) { + $this->db->where($where); + } + + if ($order_by !== null) { + $this->db->order_by($order_by); + } + + $providers = $this->db->get_where('users', ['id_roles' => $role_id], $limit, $offset)->result_array(); + + foreach ($providers as &$provider) { + $this->cast($provider); + + $provider['settings'] = $this->db->get_where('user_settings', ['id_users' => $provider['id']])->row_array(); + + unset($provider['settings']['id_users'], $provider['settings']['password'], $provider['settings']['salt']); + + $provider['services'] = []; + + $service_provider_connections = $this->db + ->get_where('services_providers', ['id_users' => $provider['id']]) + ->result_array(); + + foreach ($service_provider_connections as $service_provider_connection) { + $provider['services'][] = (int) $service_provider_connection['id_services']; + } + } + + return $providers; + } + + /** + * Get the provider role ID. + * + * @return int Returns the role ID. + */ + public function get_provider_role_id(): int + { + $role = $this->db->get_where('roles', ['slug' => DB_SLUG_PROVIDER])->row_array(); + + if (empty($role)) { + throw new RuntimeException('The provider role was not found in the database.'); + } + + return $role['id']; } /** @@ -221,13 +279,9 @@ protected function insert(array $provider): int $settings = $provider['settings']; - unset( - $provider['services'], - $provider['settings'] - ); + unset($provider['services'], $provider['settings']); - if ( ! $this->db->insert('users', $provider)) - { + if (!$this->db->insert('users', $provider)) { throw new RuntimeException('Could not insert provider.'); } @@ -241,6 +295,59 @@ protected function insert(array $provider): int return $provider['id']; } + /** + * Save the provider settings. + * + * @param int $provider_id Provider ID. + * @param array $settings Associative array with the settings data. + * + * @throws InvalidArgumentException + */ + protected function save_settings(int $provider_id, array $settings) + { + if (empty($settings)) { + throw new InvalidArgumentException('The settings argument cannot be empty.'); + } + + // Make sure the settings record exists in the database. + $count = $this->db->get_where('user_settings', ['id_users' => $provider_id])->num_rows(); + + if (!$count) { + $this->db->insert('user_settings', ['id_users' => $provider_id]); + } + + foreach ($settings as $name => $value) { + // Sort working plans exceptions in descending order that they are easier to modify later on. + if ($name === 'working_plan_exceptions') { + $value = json_decode($value, true); + + if (!$value) { + $value = []; + } + + krsort($value); + + $value = json_encode(empty($value) ? new stdClass() : $value); + } + + $this->set_setting($provider_id, $name, $value); + } + } + + /** + * Set the value of a provider setting. + * + * @param int $provider_id Provider ID. + * @param string $name Setting name. + * @param mixed|null $value Setting value. + */ + public function set_setting(int $provider_id, string $name, mixed $value = null) + { + if (!$this->db->update('user_settings', [$name => $value], ['id_users' => $provider_id])) { + throw new RuntimeException('Could not set the new provider setting value: ' . $name); + } + } + /** * Update an existing provider. * @@ -258,25 +365,19 @@ protected function update(array $provider): int $settings = $provider['settings']; - unset( - $provider['services'], - $provider['settings'] - ); + unset($provider['services'], $provider['settings']); - if (isset($settings['password'])) - { + if (isset($settings['password'])) { $existing_settings = $this->db->get_where('user_settings', ['id_users' => $provider['id']])->row_array(); - if (empty($existing_settings)) - { + if (empty($existing_settings)) { throw new RuntimeException('No settings record found for provider with ID: ' . $provider['id']); } $settings['password'] = hash_password($existing_settings['salt'], $settings['password']); } - if ( ! $this->db->update('users', $provider, ['id' => $provider['id']])) - { + if (!$this->db->update('users', $provider, ['id' => $provider['id']])) { throw new RuntimeException('Could not update provider.'); } @@ -287,55 +388,36 @@ protected function update(array $provider): int } /** - * Remove an existing provider from the database. + * Save the provider service IDs. * * @param int $provider_id Provider ID. - * - * @throws RuntimeException + * @param array $service_ids Service IDs. */ - public function delete(int $provider_id): void + protected function save_service_ids(int $provider_id, array $service_ids) { - $this->db->delete('users', ['id' => $provider_id]); + // Re-insert the provider-service connections. + $this->db->delete('services_providers', ['id_users' => $provider_id]); + + foreach ($service_ids as $service_id) { + $service_provider_connection = [ + 'id_users' => $provider_id, + 'id_services' => $service_id + ]; + + $this->db->insert('services_providers', $service_provider_connection); + } } /** - * Get a specific provider from the database. - * - * @param int $provider_id The ID of the record to be returned. + * Remove an existing provider from the database. * - * @return array Returns an array with the provider data. + * @param int $provider_id Provider ID. * - * @throws InvalidArgumentException + * @throws RuntimeException */ - public function find(int $provider_id): array + public function delete(int $provider_id): void { - $provider = $this->db->get_where('users', ['id' => $provider_id])->row_array(); - - if ( ! $provider) - { - throw new InvalidArgumentException('The provided provider ID was not found in the database: ' . $provider_id); - } - - $this->cast($provider); - - $provider['settings'] = $this->db->get_where('user_settings', ['id_users' => $provider_id])->row_array(); - - unset( - $provider['settings']['id_users'], - $provider['settings']['password'], - $provider['settings']['salt'], - ); - - $service_provider_connections = $this->db->get_where('services_providers', ['id_users' => $provider_id])->result_array(); - - $provider['services'] = []; - - foreach ($service_provider_connections as $service_provider_connection) - { - $provider['services'][] = (int)$service_provider_connection['id_services']; - } - - return $provider; + $this->db->delete('users', ['id' => $provider_id]); } /** @@ -350,22 +432,21 @@ public function find(int $provider_id): array */ public function value(int $provider_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($provider_id)) - { + if (empty($provider_id)) { throw new InvalidArgumentException('The provider ID argument cannot be empty.'); } // Check whether the provider exists. $query = $this->db->get_where('users', ['id' => $provider_id]); - if ( ! $query->num_rows()) - { - throw new InvalidArgumentException('The provided provider ID was not found in the database: ' . $provider_id); + if (!$query->num_rows()) { + throw new InvalidArgumentException( + 'The provided provider ID was not found in the database: ' . $provider_id + ); } // Check if the required field is part of the provider data. @@ -373,143 +454,13 @@ public function value(int $provider_id, string $field): mixed $this->cast($provider); - if ( ! array_key_exists($field, $provider)) - { + if (!array_key_exists($field, $provider)) { throw new InvalidArgumentException('The requested field was not found in the provider data: ' . $field); } return $provider[$field]; } - /** - * Get all providers that match the provided criteria. - * - * @param array|string|null $where Where conditions - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. - * - * @return array Returns an array of providers. - */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - $role_id = $this->get_provider_role_id(); - - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by !== NULL) - { - $this->db->order_by($order_by); - } - - - $providers = $this->db->get_where('users', ['id_roles' => $role_id], $limit, $offset)->result_array(); - - foreach ($providers as &$provider) - { - $this->cast($provider); - - $provider['settings'] = $this->db->get_where('user_settings', ['id_users' => $provider['id']])->row_array(); - - unset( - $provider['settings']['id_users'], - $provider['settings']['password'], - $provider['settings']['salt'] - ); - - $provider['services'] = []; - - $service_provider_connections = $this->db->get_where('services_providers', ['id_users' => $provider['id']])->result_array(); - - foreach ($service_provider_connections as $service_provider_connection) - { - $provider['services'][] = (int)$service_provider_connection['id_services']; - } - } - - return $providers; - } - - - /** - * Get the provider role ID. - * - * @return int Returns the role ID. - */ - public function get_provider_role_id(): int - { - $role = $this->db->get_where('roles', ['slug' => DB_SLUG_PROVIDER])->row_array(); - - if (empty($role)) - { - throw new RuntimeException('The provider role was not found in the database.'); - } - - return $role['id']; - } - - /** - * Save the provider settings. - * - * @param int $provider_id Provider ID. - * @param array $settings Associative array with the settings data. - * - * @throws InvalidArgumentException - */ - protected function save_settings(int $provider_id, array $settings) - { - if (empty($settings)) - { - throw new InvalidArgumentException('The settings argument cannot be empty.'); - } - - // Make sure the settings record exists in the database. - $count = $this->db->get_where('user_settings', ['id_users' => $provider_id])->num_rows(); - - if ( ! $count) - { - $this->db->insert('user_settings', ['id_users' => $provider_id]); - } - - foreach ($settings as $name => $value) - { - // Sort working plans exceptions in descending order that they are easier to modify later on. - if ($name === 'working_plan_exceptions') - { - $value = json_decode($value, TRUE); - - if ( ! $value) - { - $value = []; - } - - krsort($value); - - $value = json_encode(empty($value) ? new stdClass() : $value); - } - - $this->set_setting($provider_id, $name, $value); - } - } - - /** - * Set the value of a provider setting. - * - * @param int $provider_id Provider ID. - * @param string $name Setting name. - * @param mixed|null $value Setting value. - */ - public function set_setting(int $provider_id, string $name, mixed $value = NULL) - { - if ( ! $this->db->update('user_settings', [$name => $value], ['id_users' => $provider_id])) - { - throw new RuntimeException('Could not set the new provider setting value: ' . $name); - } - } - /** * Get the value of a provider setting. * @@ -522,36 +473,13 @@ public function get_setting(int $provider_id, string $name): string { $settings = $this->db->get_where('user_settings', ['id_users' => $provider_id])->row_array(); - if ( ! array_key_exists($name, $settings)) - { + if (!array_key_exists($name, $settings)) { throw new RuntimeException('The requested setting value was not found: ' . $provider_id); } return $settings[$name]; } - /** - * Save the provider service IDs. - * - * @param int $provider_id Provider ID. - * @param array $service_ids Service IDs. - */ - protected function save_service_ids(int $provider_id, array $service_ids) - { - // Re-insert the provider-service connections. - $this->db->delete('services_providers', ['id_users' => $provider_id]); - - foreach ($service_ids as $service_id) - { - $service_provider_connection = [ - 'id_users' => $provider_id, - 'id_services' => $service_id - ]; - - $this->db->insert('services_providers', $service_provider_connection); - } - } - /** * Save a new or existing working plan exception. * @@ -562,15 +490,14 @@ protected function save_service_ids(int $provider_id, array $service_ids) * @throws InvalidArgumentException * @throws Exception */ - public function save_working_plan_exception(int $provider_id, string $date, array $working_plan_exception = NULL) + public function save_working_plan_exception(int $provider_id, string $date, array $working_plan_exception = null) { // Validate the working plan exception data. $start = date('H:i', strtotime($working_plan_exception['start'])); $end = date('H:i', strtotime($working_plan_exception['end'])); - if ($start > $end) - { + if ($start > $end) { throw new InvalidArgumentException('Working plan exception start date must be before the end date.'); } @@ -580,18 +507,16 @@ public function save_working_plan_exception(int $provider_id, string $date, arra 'id_roles' => $this->db->get_where('roles', ['slug' => DB_SLUG_PROVIDER])->row()->id ]; - if ($this->db->get_where('users', $where)->num_rows() === 0) - { + if ($this->db->get_where('users', $where)->num_rows() === 0) { throw new InvalidArgumentException('Provider ID was not found in the database: ' . $provider_id); } $provider = $this->find($provider_id); // Store the working plan exception. - $working_plan_exceptions = json_decode($provider['settings']['working_plan_exceptions'], TRUE); + $working_plan_exceptions = json_decode($provider['settings']['working_plan_exceptions'], true); - if (is_array($working_plan_exception) && ! isset($working_plan_exception['breaks'])) - { + if (is_array($working_plan_exception) && !isset($working_plan_exception['breaks'])) { $working_plan_exception['breaks'] = []; } @@ -602,6 +527,44 @@ public function save_working_plan_exception(int $provider_id, string $date, arra $this->update($provider); } + /** + * Get a specific provider from the database. + * + * @param int $provider_id The ID of the record to be returned. + * + * @return array Returns an array with the provider data. + * + * @throws InvalidArgumentException + */ + public function find(int $provider_id): array + { + $provider = $this->db->get_where('users', ['id' => $provider_id])->row_array(); + + if (!$provider) { + throw new InvalidArgumentException( + 'The provided provider ID was not found in the database: ' . $provider_id + ); + } + + $this->cast($provider); + + $provider['settings'] = $this->db->get_where('user_settings', ['id_users' => $provider_id])->row_array(); + + unset($provider['settings']['id_users'], $provider['settings']['password'], $provider['settings']['salt']); + + $service_provider_connections = $this->db + ->get_where('services_providers', ['id_users' => $provider_id]) + ->result_array(); + + $provider['services'] = []; + + foreach ($service_provider_connections as $service_provider_connection) { + $provider['services'][] = (int) $service_provider_connection['id_services']; + } + + return $provider; + } + /** * Delete a provider working plan exception. * @@ -614,16 +577,17 @@ public function delete_working_plan_exception(int $provider_id, string $date) { $provider = $this->find($provider_id); - $working_plan_exceptions = json_decode($provider['settings']['working_plan_exceptions'], TRUE); + $working_plan_exceptions = json_decode($provider['settings']['working_plan_exceptions'], true); - if ( ! array_key_exists($date, $working_plan_exceptions)) - { + if (!array_key_exists($date, $working_plan_exceptions)) { return; // The selected date does not exist in provider's settings. } unset($working_plan_exceptions[$date]); - $provider['settings']['working_plan_exceptions'] = empty($working_plan_exceptions) ? '{}' : $working_plan_exceptions; + $provider['settings']['working_plan_exceptions'] = empty($working_plan_exceptions) + ? '{}' + : $working_plan_exceptions; $this->update($provider); } @@ -635,15 +599,13 @@ public function delete_working_plan_exception(int $provider_id, string $date) * * @return array Returns an array of providers. */ - public function get_available_providers(bool $without_private = FALSE): array + public function get_available_providers(bool $without_private = false): array { - if ($without_private) - { - $this->db->where('users.is_private', FALSE); + if ($without_private) { + $this->db->where('users.is_private', false); } - $providers = $this - ->db + $providers = $this->db ->select('users.*') ->from('users') ->join('roles', 'roles.id = users.id_roles', 'inner') @@ -652,8 +614,7 @@ public function get_available_providers(bool $without_private = FALSE): array ->get() ->result_array(); - foreach ($providers as &$provider) - { + foreach ($providers as &$provider) { $provider['settings'] = $this->db->get_where('user_settings', ['id_users' => $provider['id']])->row_array(); unset( @@ -665,11 +626,12 @@ public function get_available_providers(bool $without_private = FALSE): array $provider['services'] = []; - $service_provider_connections = $this->db->get_where('services_providers', ['id_users' => $provider['id']])->result_array(); + $service_provider_connections = $this->db + ->get_where('services_providers', ['id_users' => $provider['id']]) + ->result_array(); - foreach ($service_provider_connections as $service_provider_connection) - { - $provider['services'][] = (int)$service_provider_connection['id_services']; + foreach ($service_provider_connections as $service_provider_connection) { + $provider['services'][] = (int) $service_provider_connection['id_services']; } } @@ -698,12 +660,11 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of providers. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { $role_id = $this->get_provider_role_id(); - $providers = $this - ->db + $providers = $this->db ->select() ->from('users') ->where('id_roles', $role_id) @@ -726,25 +687,21 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($providers as &$provider) - { + foreach ($providers as &$provider) { $this->cast($provider); $provider['settings'] = $this->db->get_where('user_settings', ['id_users' => $provider['id']])->row_array(); - unset( - $provider['settings']['id_users'], - $provider['settings']['password'], - $provider['settings']['salt'] - ); + unset($provider['settings']['id_users'], $provider['settings']['password'], $provider['settings']['salt']); $provider['services'] = []; - $service_provider_connections = $this->db->get_where('services_providers', ['id_users' => $provider['id']])->result_array(); + $service_provider_connections = $this->db + ->get_where('services_providers', ['id_users' => $provider['id']]) + ->result_array(); - foreach ($service_provider_connections as $service_provider_connection) - { - $provider['services'][] = (int)$service_provider_connection['id_services']; + foreach ($service_provider_connections as $service_provider_connection) { + $provider['services'][] = (int) $service_provider_connection['id_services']; } } @@ -761,24 +718,22 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s */ public function load(array &$provider, array $resources) { - if (empty($provider) || empty($resources)) - { + if (empty($provider) || empty($resources)) { return; } - foreach ($resources as $resource) - { - $provider['services'] = match ($resource) - { - 'services' => $this - ->db + foreach ($resources as $resource) { + $provider['services'] = match ($resource) { + 'services' => $this->db ->select('services.*') ->from('services') ->join('services_providers', 'services_providers.id_services = services.id', 'inner') ->where('id_users', $provider['id']) ->get() ->result_array(), - default => throw new InvalidArgumentException('The requested provider relation is not supported: ' . $resource), + default => throw new InvalidArgumentException( + 'The requested provider relation is not supported: ' . $resource + ) }; } } @@ -791,7 +746,7 @@ public function load(array &$provider, array $resources) public function api_encode(array &$provider) { $encoded_resource = [ - 'id' => array_key_exists('id', $provider) ? (int)$provider['id'] : NULL, + 'id' => array_key_exists('id', $provider) ? (int) $provider['id'] : null, 'firstName' => $provider['first_name'], 'lastName' => $provider['last_name'], 'email' => $provider['email'], @@ -802,41 +757,39 @@ public function api_encode(array &$provider) 'state' => $provider['state'], 'zip' => $provider['zip_code'], 'notes' => $provider['notes'], - 'timezone' => $provider['timezone'], + 'timezone' => $provider['timezone'] ]; - if (array_key_exists('services', $provider)) - { + if (array_key_exists('services', $provider)) { $encoded_resource['services'] = $provider['services']; } - if (array_key_exists('settings', $provider)) - { + if (array_key_exists('settings', $provider)) { $encoded_resource['settings'] = [ 'username' => $provider['settings']['username'], 'notifications' => filter_var($provider['settings']['notifications'], FILTER_VALIDATE_BOOLEAN), 'calendarView' => $provider['settings']['calendar_view'], 'googleSync' => array_key_exists('google_sync', $provider['settings']) ? filter_var($provider['settings']['google_sync'], FILTER_VALIDATE_BOOLEAN) - : NULL, + : null, 'googleCalendar' => array_key_exists('google_calendar', $provider['settings']) ? $provider['settings']['google_calendar'] - : NULL, + : null, 'googleToken' => array_key_exists('google_token', $provider['settings']) ? $provider['settings']['google_token'] - : NULL, + : null, 'syncFutureDays' => array_key_exists('sync_future_days', $provider['settings']) - ? (int)$provider['settings']['sync_future_days'] - : NULL, + ? (int) $provider['settings']['sync_future_days'] + : null, 'syncPastDays' => array_key_exists('sync_past_days', $provider['settings']) - ? (int)$provider['settings']['sync_past_days'] - : NULL, + ? (int) $provider['settings']['sync_past_days'] + : null, 'workingPlan' => array_key_exists('working_plan', $provider['settings']) - ? json_decode($provider['settings']['working_plan'], TRUE) - : NULL, + ? json_decode($provider['settings']['working_plan'], true) + : null, 'workingPlanExceptions' => array_key_exists('working_plan_exceptions', $provider['settings']) - ? json_decode($provider['settings']['working_plan_exceptions'], TRUE) - : NULL, + ? json_decode($provider['settings']['working_plan_exceptions'], true) + : null ]; } @@ -849,137 +802,117 @@ public function api_encode(array &$provider) * @param array $provider API resource. * @param array|null $base Base provider data to be overwritten with the provided values (useful for updates). */ - public function api_decode(array &$provider, array $base = NULL) + public function api_decode(array &$provider, array $base = null) { $decoded_resource = $base ?: []; - if (array_key_exists('id', $provider)) - { + if (array_key_exists('id', $provider)) { $decoded_resource['id'] = $provider['id']; } - if (array_key_exists('firstName', $provider)) - { + if (array_key_exists('firstName', $provider)) { $decoded_resource['first_name'] = $provider['firstName']; } - if (array_key_exists('lastName', $provider)) - { + if (array_key_exists('lastName', $provider)) { $decoded_resource['last_name'] = $provider['lastName']; } - if (array_key_exists('email', $provider)) - { + if (array_key_exists('email', $provider)) { $decoded_resource['email'] = $provider['email']; } - if (array_key_exists('mobile', $provider)) - { + if (array_key_exists('mobile', $provider)) { $decoded_resource['mobile_number'] = $provider['mobile']; } - if (array_key_exists('phone', $provider)) - { + if (array_key_exists('phone', $provider)) { $decoded_resource['phone_number'] = $provider['phone']; } - if (array_key_exists('address', $provider)) - { + if (array_key_exists('address', $provider)) { $decoded_resource['address'] = $provider['address']; } - if (array_key_exists('city', $provider)) - { + if (array_key_exists('city', $provider)) { $decoded_resource['city'] = $provider['city']; } - if (array_key_exists('state', $provider)) - { + if (array_key_exists('state', $provider)) { $decoded_resource['state'] = $provider['state']; } - if (array_key_exists('zip', $provider)) - { + if (array_key_exists('zip', $provider)) { $decoded_resource['zip_code'] = $provider['zip']; } - if (array_key_exists('notes', $provider)) - { + if (array_key_exists('notes', $provider)) { $decoded_resource['notes'] = $provider['notes']; } - if (array_key_exists('timezone', $provider)) - { + if (array_key_exists('timezone', $provider)) { $decoded_resource['timezone'] = $provider['timezone']; } - if (array_key_exists('services', $provider)) - { + if (array_key_exists('services', $provider)) { $decoded_resource['services'] = $provider['services']; } - if (array_key_exists('settings', $provider)) - { - if (empty($decoded_resource['settings'])) - { + if (array_key_exists('settings', $provider)) { + if (empty($decoded_resource['settings'])) { $decoded_resource['settings'] = []; } - if (array_key_exists('username', $provider['settings'])) - { + if (array_key_exists('username', $provider['settings'])) { $decoded_resource['settings']['username'] = $provider['settings']['username']; } - if (array_key_exists('password', $provider['settings'])) - { + if (array_key_exists('password', $provider['settings'])) { $decoded_resource['settings']['password'] = $provider['settings']['password']; } - if (array_key_exists('calendarView', $provider['settings'])) - { + if (array_key_exists('calendarView', $provider['settings'])) { $decoded_resource['settings']['calendar_view'] = $provider['settings']['calendarView']; } - if (array_key_exists('notifications', $provider['settings'])) - { - $decoded_resource['settings']['notifications'] = filter_var($provider['settings']['notifications'], - FILTER_VALIDATE_BOOLEAN); + if (array_key_exists('notifications', $provider['settings'])) { + $decoded_resource['settings']['notifications'] = filter_var( + $provider['settings']['notifications'], + FILTER_VALIDATE_BOOLEAN + ); } - if (array_key_exists('googleSync', $provider['settings'])) - { - $decoded_resource['settings']['google_sync'] = filter_var($provider['settings']['googleSync'], - FILTER_VALIDATE_BOOLEAN); + if (array_key_exists('googleSync', $provider['settings'])) { + $decoded_resource['settings']['google_sync'] = filter_var( + $provider['settings']['googleSync'], + FILTER_VALIDATE_BOOLEAN + ); } - if (array_key_exists('googleCalendar', $provider['settings'])) - { + if (array_key_exists('googleCalendar', $provider['settings'])) { $decoded_resource['settings']['google_calendar'] = $provider['settings']['googleCalendar']; } - if (array_key_exists('googleToken', $provider['settings'])) - { + if (array_key_exists('googleToken', $provider['settings'])) { $decoded_resource['settings']['google_token'] = $provider['settings']['googleToken']; } - if (array_key_exists('syncFutureDays', $provider['settings'])) - { + if (array_key_exists('syncFutureDays', $provider['settings'])) { $decoded_resource['settings']['sync_future_days'] = $provider['settings']['syncFutureDays']; } - if (array_key_exists('syncPastDays', $provider['settings'])) - { + if (array_key_exists('syncPastDays', $provider['settings'])) { $decoded_resource['settings']['sync_past_days'] = $provider['settings']['syncPastDays']; } - if (array_key_exists('workingPlan', $provider['settings'])) - { + if (array_key_exists('workingPlan', $provider['settings'])) { $decoded_resource['settings']['working_plan'] = json_encode($provider['settings']['workingPlan']); } - if (array_key_exists('workingPlanExceptions', $provider['settings'])) - { - $decoded_resource['settings']['working_plan_exceptions'] = json_encode($provider['settings']['workingPlanExceptions']); + if (array_key_exists('workingPlanExceptions', $provider['settings'])) { + $decoded_resource['settings']['working_plan_exceptions'] = json_encode( + $provider['settings']['workingPlanExceptions'] + ); } } diff --git a/application/models/Roles_model.php b/application/models/Roles_model.php index 7e86877313..c079639f1f 100644 --- a/application/models/Roles_model.php +++ b/application/models/Roles_model.php @@ -18,7 +18,8 @@ * * @package Models */ -class Roles_model extends EA_Model { +class Roles_model extends EA_Model +{ /** * @var array */ @@ -30,7 +31,7 @@ class Roles_model extends EA_Model { 'services' => 'integer', 'users' => 'integer', 'system_settings' => 'integer', - 'user_settings' => 'integer', + 'user_settings' => 'integer' ]; /** @@ -46,12 +47,9 @@ public function save(array $role): int { $this->validate($role); - if (empty($role['id'])) - { + if (empty($role['id'])) { return $this->insert($role); - } - else - { + } else { return $this->update($role); } } @@ -66,22 +64,19 @@ public function save(array $role): int public function validate(array $role) { // If a role ID is provided then check whether the record really exists in the database. - if ( ! empty($role['id'])) - { + if (!empty($role['id'])) { $count = $this->db->get_where('roles', ['id' => $role['id']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided role ID does not exist in the database: ' . $role['id']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided role ID does not exist in the database: ' . $role['id'] + ); } } // Make sure all required fields are provided. - if ( - empty($role['name']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($role, TRUE)); + if (empty($role['name'])) { + throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($role, true)); } } @@ -99,8 +94,7 @@ protected function insert(array $role): int $role['create_datetime'] = date('Y-m-d H:i:s'); $role['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->insert('roles', $role)) - { + if (!$this->db->insert('roles', $role)) { throw new RuntimeException('Could not insert role.'); } @@ -120,8 +114,7 @@ protected function update(array $role): int { $role['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->update('roles', $role, ['id' => $role['id']])) - { + if (!$this->db->update('roles', $role, ['id' => $role['id']])) { throw new RuntimeException('Could not update role.'); } @@ -153,8 +146,7 @@ public function find(int $role_id): array { $role = $this->db->get_where('roles', ['id' => $role_id])->row_array(); - if ( ! $role) - { + if (!$role) { throw new InvalidArgumentException('The provided role ID was not found in the database: ' . $role_id); } @@ -175,21 +167,18 @@ public function find(int $role_id): array */ public function value(int $role_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($role_id)) - { + if (empty($role_id)) { throw new InvalidArgumentException('The role ID argument cannot be empty.'); } // Check whether the role exists. $query = $this->db->get_where('roles', ['id' => $role_id]); - if ( ! $query->num_rows()) - { + if (!$query->num_rows()) { throw new InvalidArgumentException('The provided role ID was not found in the database: ' . $role_id); } @@ -198,46 +187,13 @@ public function value(int $role_id, string $field): mixed $this->cast($role); - if ( ! array_key_exists($field, $role)) - { + if (!array_key_exists($field, $role)) { throw new InvalidArgumentException('The requested field was not found in the role data: ' . $field); } return $role[$field]; } - /** - * Get all roles that match the provided criteria. - * - * @param array|string|null $where Where conditions - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. - * - * @return array Returns an array of roles. - */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by !== NULL) - { - $this->db->order_by($order_by); - } - - $roles = $this->db->get('roles', $limit, $offset)->result_array(); - - foreach ($roles as &$role) - { - $this->cast($role); - } - - return $roles; - } - /** * Get the permissions array by role slug. * @@ -260,46 +216,36 @@ public function get_permissions_by_slug(string $slug): array $this->cast($role); - unset( - $role['id'], - $role['name'], - $role['slug'], - $role['is_admin'] - ); + unset($role['id'], $role['name'], $role['slug'], $role['is_admin']); // Convert the integer values to boolean. $permissions = []; - foreach ($role as $resource => $value) - { + foreach ($role as $resource => $value) { $permissions[$resource] = [ - 'view' => FALSE, - 'add' => FALSE, - 'edit' => FALSE, - 'delete' => FALSE + 'view' => false, + 'add' => false, + 'edit' => false, + 'delete' => false ]; - if ($value > 0) - { - if ((int)($value / PRIV_DELETE) === 1) - { - $permissions[$resource]['delete'] = TRUE; + if ($value > 0) { + if ((int) ($value / PRIV_DELETE) === 1) { + $permissions[$resource]['delete'] = true; $value -= PRIV_DELETE; } - if ((int)($value / PRIV_EDIT) === 1) - { - $permissions[$resource]['edit'] = TRUE; + if ((int) ($value / PRIV_EDIT) === 1) { + $permissions[$resource]['edit'] = true; $value -= PRIV_EDIT; } - if ((int)($value / PRIV_ADD) === 1) - { - $permissions[$resource]['add'] = TRUE; + if ((int) ($value / PRIV_ADD) === 1) { + $permissions[$resource]['add'] = true; } - $permissions[$resource]['view'] = TRUE; + $permissions[$resource]['view'] = true; } } @@ -326,10 +272,9 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of roles. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { - $roles = $this - ->db + $roles = $this->db ->select() ->from('roles') ->group_start() @@ -342,8 +287,40 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($roles as &$role) - { + foreach ($roles as &$role) { + $this->cast($role); + } + + return $roles; + } + + /** + * Get all roles that match the provided criteria. + * + * @param array|string|null $where Where conditions + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. + * + * @return array Returns an array of roles. + */ + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + if ($where !== null) { + $this->db->where($where); + } + + if ($order_by !== null) { + $this->db->order_by($order_by); + } + + $roles = $this->db->get('roles', $limit, $offset)->result_array(); + + foreach ($roles as &$role) { $this->cast($role); } diff --git a/application/models/Secretaries_model.php b/application/models/Secretaries_model.php index 47141d0cb6..b7bb5cbac3 100644 --- a/application/models/Secretaries_model.php +++ b/application/models/Secretaries_model.php @@ -18,13 +18,14 @@ * * @package Models */ -class Secretaries_model extends EA_Model { +class Secretaries_model extends EA_Model +{ /** * @var array */ protected array $casts = [ 'id' => 'integer', - 'id_roles' => 'integer', + 'id_roles' => 'integer' ]; /** @@ -44,7 +45,7 @@ class Secretaries_model extends EA_Model { 'timezone' => 'timezone', 'language' => 'language', 'notes' => 'notes', - 'roleId' => 'id_roles', + 'roleId' => 'id_roles' ]; /** @@ -61,12 +62,9 @@ public function save(array $secretary): int { $this->validate($secretary); - if (empty($secretary['id'])) - { + if (empty($secretary['id'])) { return $this->insert($secretary); - } - else - { + } else { return $this->update($secretary); } } @@ -81,86 +79,82 @@ public function save(array $secretary): int public function validate(array $secretary) { // If a secretary ID is provided then check whether the record really exists in the database. - if ( ! empty($provider['id'])) - { + if (!empty($provider['id'])) { $count = $this->db->get_where('users', ['id' => $secretary['id']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided secretary ID does not exist in the database: ' . $secretary['id']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided secretary ID does not exist in the database: ' . $secretary['id'] + ); } } // Make sure all required fields are provided. if ( - empty($secretary['first_name']) - || empty($secretary['last_name']) - || empty($secretary['email']) - || empty($secretary['phone_number']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($secretary, TRUE)); + empty($secretary['first_name']) || + empty($secretary['last_name']) || + empty($secretary['email']) || + empty($secretary['phone_number']) + ) { + throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($secretary, true)); } // Validate the email address. - if ( ! filter_var($secretary['email'], FILTER_VALIDATE_EMAIL)) - { + if (!filter_var($secretary['email'], FILTER_VALIDATE_EMAIL)) { throw new InvalidArgumentException('Invalid email address provided: ' . $secretary['email']); } // Validate secretary providers. - if ( ! empty($secretary['providers'])) - { + if (!empty($secretary['providers'])) { // Make sure the provided provider entries are numeric values. - foreach ($secretary['providers'] as $secretary_id) - { - if ( ! is_numeric($secretary_id)) - { - throw new InvalidArgumentException('The provided secretary providers are invalid: ' . print_r($secretary, TRUE)); + foreach ($secretary['providers'] as $secretary_id) { + if (!is_numeric($secretary_id)) { + throw new InvalidArgumentException( + 'The provided secretary providers are invalid: ' . print_r($secretary, true) + ); } } } // Make sure the username is unique. - if ( ! empty($secretary['settings']['username'])) - { - $secretary_id = $secretary['id'] ?? NULL; + if (!empty($secretary['settings']['username'])) { + $secretary_id = $secretary['id'] ?? null; - if ( ! $this->validate_username($secretary['settings']['username'], $secretary_id)) - { - throw new InvalidArgumentException('The provided username is already in use, please use a different one.'); + if (!$this->validate_username($secretary['settings']['username'], $secretary_id)) { + throw new InvalidArgumentException( + 'The provided username is already in use, please use a different one.' + ); } } // Validate the password. - if ( ! empty($secretary['settings']['password'])) - { - if (strlen($secretary['settings']['password']) < MIN_PASSWORD_LENGTH) - { - throw new InvalidArgumentException('The secretary password must be at least ' . MIN_PASSWORD_LENGTH . ' characters long.'); + if (!empty($secretary['settings']['password'])) { + if (strlen($secretary['settings']['password']) < MIN_PASSWORD_LENGTH) { + throw new InvalidArgumentException( + 'The secretary password must be at least ' . MIN_PASSWORD_LENGTH . ' characters long.' + ); } } // New users must always have a password value set. - if (empty($secretary['id']) && empty($secretary['settings']['password'])) - { + if (empty($secretary['id']) && empty($secretary['settings']['password'])) { throw new InvalidArgumentException('The provider password cannot be empty when inserting a new record.'); } // Validate calendar view type value. if ( - ! empty($secretary['settings']['calendar_view']) - && ! in_array($secretary['settings']['calendar_view'], [CALENDAR_VIEW_DEFAULT, CALENDAR_VIEW_TABLE]) - ) - { - throw new InvalidArgumentException('The provided calendar view is invalid: ' . $secretary['settings']['calendar_view']); + !empty($secretary['settings']['calendar_view']) && + !in_array($secretary['settings']['calendar_view'], [CALENDAR_VIEW_DEFAULT, CALENDAR_VIEW_TABLE]) + ) { + throw new InvalidArgumentException( + 'The provided calendar view is invalid: ' . $secretary['settings']['calendar_view'] + ); } // Make sure the email address is unique. - $secretary_id = $secretary['id'] ?? NULL; + $secretary_id = $secretary['id'] ?? null; - $count = $this - ->db + $count = $this->db ->select() ->from('users') ->join('roles', 'roles.id = users.id_roles', 'inner') @@ -170,9 +164,10 @@ public function validate(array $secretary) ->get() ->num_rows(); - if ($count > 0) - { - throw new InvalidArgumentException('The provided email address is already in use, please use a different one.'); + if ($count > 0) { + throw new InvalidArgumentException( + 'The provided email address is already in use, please use a different one.' + ); } } @@ -184,20 +179,87 @@ public function validate(array $secretary) * * @return bool Returns the validation result. */ - public function validate_username(string $username, int $secretary_id = NULL): bool + public function validate_username(string $username, int $secretary_id = null): bool { - if ( ! empty($secretary_id)) - { + if (!empty($secretary_id)) { $this->db->where('id_users !=', $secretary_id); } - return $this - ->db - ->from('users') - ->join('user_settings', 'user_settings.id_users = users.id', 'inner') - ->where(['username' => $username]) - ->get() - ->num_rows() === 0; + return $this->db + ->from('users') + ->join('user_settings', 'user_settings.id_users = users.id', 'inner') + ->where(['username' => $username]) + ->get() + ->num_rows() === 0; + } + + /** + * Get all secretaries that match the provided criteria. + * + * @param array|string|null $where Where conditions + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. + * + * @return array Returns an array of secretaries. + */ + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + $role_id = $this->get_secretary_role_id(); + + if ($where !== null) { + $this->db->where($where); + } + + if ($order_by !== null) { + $this->db->order_by($order_by); + } + + $secretaries = $this->db->get_where('users', ['id_roles' => $role_id], $limit, $offset)->result_array(); + + foreach ($secretaries as &$secretary) { + $secretary['settings'] = $this->db + ->get_where('user_settings', ['id_users' => $secretary['id']]) + ->row_array(); + + unset( + $secretary['settings']['id_users'], + $secretary['settings']['password'], + $secretary['settings']['salt'] + ); + + $secretary_provider_connections = $this->db + ->get_where('secretaries_providers', ['id_users_secretary' => $secretary['id']]) + ->result_array(); + + $secretary['providers'] = []; + + foreach ($secretary_provider_connections as $secretary_provider_connection) { + $secretary['providers'][] = (int) $secretary_provider_connection['id_users_provider']; + } + } + + return $secretaries; + } + + /** + * Get the secretary role ID. + * + * @return int Returns the role ID. + */ + public function get_secretary_role_id(): int + { + $role = $this->db->get_where('roles', ['slug' => DB_SLUG_SECRETARY])->row_array(); + + if (empty($role)) { + throw new RuntimeException('The secretary role was not found in the database.'); + } + + return $role['id']; } /** @@ -220,13 +282,9 @@ protected function insert(array $secretary): int $settings = $secretary['settings']; - unset( - $secretary['providers'], - $secretary['settings'] - ); + unset($secretary['providers'], $secretary['settings']); - if ( ! $this->db->insert('users', $secretary)) - { + if (!$this->db->insert('users', $secretary)) { throw new RuntimeException('Could not insert secretary.'); } @@ -240,6 +298,46 @@ protected function insert(array $secretary): int return $secretary['id']; } + /** + * Save the secretary settings. + * + * @param int $secretary_id Secretary ID. + * @param array $settings Associative array with the settings data. + * + * @throws InvalidArgumentException + */ + protected function save_settings(int $secretary_id, array $settings) + { + if (empty($settings)) { + throw new InvalidArgumentException('The settings argument cannot be empty.'); + } + + // Make sure the settings record exists in the database. + $count = $this->db->get_where('user_settings', ['id_users' => $secretary_id])->num_rows(); + + if (!$count) { + $this->db->insert('user_settings', ['id_users' => $secretary_id]); + } + + foreach ($settings as $name => $value) { + $this->set_setting($secretary_id, $name, $value); + } + } + + /** + * Set the value of a secretary setting. + * + * @param int $secretary_id Secretary ID. + * @param string $name Setting name. + * @param mixed|null $value Setting value. + */ + public function set_setting(int $secretary_id, string $name, mixed $value = null) + { + if (!$this->db->update('user_settings', [$name => $value], ['id_users' => $secretary_id])) { + throw new RuntimeException('Could not set the new secretary setting value: ' . $name); + } + } + /** * Update an existing secretary. * @@ -257,82 +355,59 @@ protected function update(array $secretary): int $settings = $secretary['settings']; - unset( - $secretary['providers'], - $secretary['settings'] - ); + unset($secretary['providers'], $secretary['settings']); - if (isset($settings['password'])) - { + if (isset($settings['password'])) { $existing_settings = $this->db->get_where('user_settings', ['id_users' => $secretary['id']])->row_array(); - if (empty($existing_settings)) - { + if (empty($existing_settings)) { throw new RuntimeException('No settings record found for secretary with ID: ' . $secretary['id']); } $settings['password'] = hash_password($existing_settings['salt'], $settings['password']); } - if ( ! $this->db->update('users', $secretary, ['id' => $secretary['id']])) - { + if (!$this->db->update('users', $secretary, ['id' => $secretary['id']])) { throw new RuntimeException('Could not update secretary.'); } $this->save_settings($secretary['id'], $settings); $this->save_provider_ids($secretary['id'], $provider_ids); - return (int)$secretary['id']; + return (int) $secretary['id']; } /** - * Remove an existing secretary from the database. - * - * @param int $secretary_id Provider ID. + * Save the secretary provider IDs. * - * @throws RuntimeException + * @param int $secretary_id Secretary ID. + * @param array $provider_ids Provider IDs. */ - public function delete(int $secretary_id): void + protected function save_provider_ids(int $secretary_id, array $provider_ids) { - $this->db->delete('users', ['id' => $secretary_id]); + // Re-insert the secretary-provider connections. + $this->db->delete('secretaries_providers', ['id_users_secretary' => $secretary_id]); + + foreach ($provider_ids as $provider_id) { + $secretary_provider_connection = [ + 'id_users_secretary' => $secretary_id, + 'id_users_provider' => $provider_id + ]; + + $this->db->insert('secretaries_providers', $secretary_provider_connection); + } } /** - * Get a specific secretary from the database. - * - * @param int $secretary_id The ID of the record to be returned. + * Remove an existing secretary from the database. * - * @return array Returns an array with the secretary data. + * @param int $secretary_id Provider ID. * - * @throws InvalidArgumentException + * @throws RuntimeException */ - public function find(int $secretary_id): array + public function delete(int $secretary_id): void { - $secretary = $this->db->get_where('users', ['id' => $secretary_id])->row_array(); - - if ( ! $secretary) - { - throw new InvalidArgumentException('The provided secretary ID was not found in the database: ' . $secretary_id); - } - - $secretary['settings'] = $this->db->get_where('user_settings', ['id_users' => $secretary_id])->row_array(); - - unset( - $secretary['settings']['id_users'], - $secretary['settings']['password'], - $secretary['settings']['salt'] - ); - - $secretary_provider_connections = $this->db->get_where('secretaries_providers', ['id_users_secretary' => $secretary_id])->result_array(); - - $secretary['providers'] = []; - - foreach ($secretary_provider_connections as $secretary_provider_connection) - { - $secretary['providers'][] = (int)$secretary_provider_connection['id_users_provider']; - } - - return $secretary; + $this->db->delete('users', ['id' => $secretary_id]); } /** @@ -347,145 +422,33 @@ public function find(int $secretary_id): array */ public function value(int $secretary_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($secretary_id)) - { + if (empty($secretary_id)) { throw new InvalidArgumentException('The secretary ID argument cannot be empty.'); } // Check whether the secretary exists. $query = $this->db->get_where('users', ['id' => $secretary_id]); - if ( ! $query->num_rows()) - { - throw new InvalidArgumentException('The provided secretary ID was not found in the database: ' . $secretary_id); + if (!$query->num_rows()) { + throw new InvalidArgumentException( + 'The provided secretary ID was not found in the database: ' . $secretary_id + ); } // Check if the required field is part of the secretary data. $secretary = $query->row_array(); - if ( ! array_key_exists($field, $secretary)) - { + if (!array_key_exists($field, $secretary)) { throw new InvalidArgumentException('The requested field was not found in the secretary data: ' . $field); } return $secretary[$field]; } - /** - * Get all secretaries that match the provided criteria. - * - * @param array|string|null $where Where conditions - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. - * - * @return array Returns an array of secretaries. - */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - $role_id = $this->get_secretary_role_id(); - - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by !== NULL) - { - $this->db->order_by($order_by); - } - - $secretaries = $this->db->get_where('users', ['id_roles' => $role_id], $limit, $offset)->result_array(); - - foreach ($secretaries as &$secretary) - { - $secretary['settings'] = $this->db->get_where('user_settings', ['id_users' => $secretary['id']])->row_array(); - - unset( - $secretary['settings']['id_users'], - $secretary['settings']['password'], - $secretary['settings']['salt'] - ); - - $secretary_provider_connections = $this->db->get_where('secretaries_providers', ['id_users_secretary' => $secretary['id']])->result_array(); - - $secretary['providers'] = []; - - foreach ($secretary_provider_connections as $secretary_provider_connection) - { - $secretary['providers'][] = (int)$secretary_provider_connection['id_users_provider']; - } - } - - return $secretaries; - } - - /** - * Get the secretary role ID. - * - * @return int Returns the role ID. - */ - public function get_secretary_role_id(): int - { - $role = $this->db->get_where('roles', ['slug' => DB_SLUG_SECRETARY])->row_array(); - - if (empty($role)) - { - throw new RuntimeException('The secretary role was not found in the database.'); - } - - return $role['id']; - } - - /** - * Save the secretary settings. - * - * @param int $secretary_id Secretary ID. - * @param array $settings Associative array with the settings data. - * - * @throws InvalidArgumentException - */ - protected function save_settings(int $secretary_id, array $settings) - { - if (empty($settings)) - { - throw new InvalidArgumentException('The settings argument cannot be empty.'); - } - - // Make sure the settings record exists in the database. - $count = $this->db->get_where('user_settings', ['id_users' => $secretary_id])->num_rows(); - - if ( ! $count) - { - $this->db->insert('user_settings', ['id_users' => $secretary_id]); - } - - foreach ($settings as $name => $value) - { - $this->set_setting($secretary_id, $name, $value); - } - } - - /** - * Set the value of a secretary setting. - * - * @param int $secretary_id Secretary ID. - * @param string $name Setting name. - * @param mixed|null $value Setting value. - */ - public function set_setting(int $secretary_id, string $name, mixed $value = NULL) - { - if ( ! $this->db->update('user_settings', [$name => $value], ['id_users' => $secretary_id])) - { - throw new RuntimeException('Could not set the new secretary setting value: ' . $name); - } - } - /** * Get the value of a secretary setting. * @@ -498,36 +461,13 @@ public function get_setting(int $secretary_id, string $name): string { $settings = $this->db->get_where('user_settings', ['id_users' => $secretary_id])->row_array(); - if ( ! array_key_exists($name, $settings)) - { + if (!array_key_exists($name, $settings)) { throw new RuntimeException('The requested setting value was not found: ' . $secretary_id); } return $settings[$name]; } - /** - * Save the secretary provider IDs. - * - * @param int $secretary_id Secretary ID. - * @param array $provider_ids Provider IDs. - */ - protected function save_provider_ids(int $secretary_id, array $provider_ids) - { - // Re-insert the secretary-provider connections. - $this->db->delete('secretaries_providers', ['id_users_secretary' => $secretary_id]); - - foreach ($provider_ids as $provider_id) - { - $secretary_provider_connection = [ - 'id_users_secretary' => $secretary_id, - 'id_users_provider' => $provider_id - ]; - - $this->db->insert('secretaries_providers', $secretary_provider_connection); - } - } - /** * Get the query builder interface, configured for use with the users (secretary-filtered) table. * @@ -550,12 +490,11 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of secretaries. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { $role_id = $this->get_secretary_role_id(); - $secretaries = $this - ->db + $secretaries = $this->db ->select() ->from('users') ->where('id_roles', $role_id) @@ -578,9 +517,10 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($secretaries as &$secretary) - { - $secretary['settings'] = $this->db->get_where('user_settings', ['id_users' => $secretary['id']])->row_array(); + foreach ($secretaries as &$secretary) { + $secretary['settings'] = $this->db + ->get_where('user_settings', ['id_users' => $secretary['id']]) + ->row_array(); unset( $secretary['settings']['id_users'], @@ -588,13 +528,14 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s $secretary['settings']['salt'] ); - $secretary_provider_connections = $this->db->get_where('secretaries_providers', ['id_users_secretary' => $secretary['id']])->result_array(); + $secretary_provider_connections = $this->db + ->get_where('secretaries_providers', ['id_users_secretary' => $secretary['id']]) + ->result_array(); $secretary['providers'] = []; - foreach ($secretary_provider_connections as $secretary_provider_connection) - { - $secretary['providers'][] = (int)$secretary_provider_connection['id_users_provider']; + foreach ($secretary_provider_connections as $secretary_provider_connection) { + $secretary['providers'][] = (int) $secretary_provider_connection['id_users_provider']; } } @@ -611,24 +552,22 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s */ public function load(array &$secretary, array $resources) { - if (empty($secretary) || empty($resources)) - { + if (empty($secretary) || empty($resources)) { return; } - foreach ($resources as $resource) - { - $secretary['providers'] = match ($resource) - { - 'providers' => $this - ->db + foreach ($resources as $resource) { + $secretary['providers'] = match ($resource) { + 'providers' => $this->db ->select('users.*') ->from('users') ->join('secretaries_providers', 'secretaries_providers.id_users_provider = users.id', 'inner') ->where('id_users_secretary', $secretary['id']) ->get() ->result_array(), - default => throw new InvalidArgumentException('The requested secretary relation is not supported: ' . $resource), + default => throw new InvalidArgumentException( + 'The requested secretary relation is not supported: ' . $resource + ) }; } } @@ -641,7 +580,7 @@ public function load(array &$secretary, array $resources) public function api_encode(array &$secretary) { $encoded_resource = [ - 'id' => array_key_exists('id', $secretary) ? (int)$secretary['id'] : NULL, + 'id' => array_key_exists('id', $secretary) ? (int) $secretary['id'] : null, 'firstName' => $secretary['first_name'], 'lastName' => $secretary['last_name'], 'email' => $secretary['email'], @@ -670,100 +609,83 @@ public function api_encode(array &$secretary) * @param array $secretary API resource. * @param array|null $base Base secretary data to be overwritten with the provided values (useful for updates). */ - public function api_decode(array &$secretary, array $base = NULL) + public function api_decode(array &$secretary, array $base = null) { $decoded_resource = $base ?: []; - if (array_key_exists('id', $secretary)) - { + if (array_key_exists('id', $secretary)) { $decoded_resource['id'] = $secretary['id']; } - if (array_key_exists('firstName', $secretary)) - { + if (array_key_exists('firstName', $secretary)) { $decoded_resource['first_name'] = $secretary['firstName']; } - if (array_key_exists('lastName', $secretary)) - { + if (array_key_exists('lastName', $secretary)) { $decoded_resource['last_name'] = $secretary['lastName']; } - if (array_key_exists('email', $secretary)) - { + if (array_key_exists('email', $secretary)) { $decoded_resource['email'] = $secretary['email']; } - if (array_key_exists('mobile', $secretary)) - { + if (array_key_exists('mobile', $secretary)) { $decoded_resource['mobile_number'] = $secretary['mobile']; } - if (array_key_exists('phone', $secretary)) - { + if (array_key_exists('phone', $secretary)) { $decoded_resource['phone_number'] = $secretary['phone']; } - if (array_key_exists('address', $secretary)) - { + if (array_key_exists('address', $secretary)) { $decoded_resource['address'] = $secretary['address']; } - if (array_key_exists('city', $secretary)) - { + if (array_key_exists('city', $secretary)) { $decoded_resource['city'] = $secretary['city']; } - if (array_key_exists('state', $secretary)) - { + if (array_key_exists('state', $secretary)) { $decoded_resource['state'] = $secretary['state']; } - if (array_key_exists('zip', $secretary)) - { + if (array_key_exists('zip', $secretary)) { $decoded_resource['zip_code'] = $secretary['zip']; } - if (array_key_exists('notes', $secretary)) - { + if (array_key_exists('notes', $secretary)) { $decoded_resource['notes'] = $secretary['notes']; } - if (array_key_exists('timezone', $secretary)) - { + if (array_key_exists('timezone', $secretary)) { $decoded_resource['timezone'] = $secretary['timezone']; } - if (array_key_exists('providers', $secretary)) - { + if (array_key_exists('providers', $secretary)) { $decoded_resource['providers'] = $secretary['providers']; } - if (array_key_exists('settings', $secretary)) - { - if (empty($decoded_resource['settings'])) - { + if (array_key_exists('settings', $secretary)) { + if (empty($decoded_resource['settings'])) { $decoded_resource['settings'] = []; } - if (array_key_exists('username', $secretary['settings'])) - { + if (array_key_exists('username', $secretary['settings'])) { $decoded_resource['settings']['username'] = $secretary['settings']['username']; } - if (array_key_exists('password', $secretary['settings'])) - { + if (array_key_exists('password', $secretary['settings'])) { $decoded_resource['settings']['password'] = $secretary['settings']['password']; } - if (array_key_exists('notifications', $secretary['settings'])) - { - $decoded_resource['settings']['notifications'] = filter_var($secretary['settings']['notifications'], - FILTER_VALIDATE_BOOLEAN); + if (array_key_exists('notifications', $secretary['settings'])) { + $decoded_resource['settings']['notifications'] = filter_var( + $secretary['settings']['notifications'], + FILTER_VALIDATE_BOOLEAN + ); } - if (array_key_exists('calendarView', $secretary['settings'])) - { + if (array_key_exists('calendarView', $secretary['settings'])) { $decoded_resource['settings']['calendar_view'] = $secretary['settings']['calendarView']; } } @@ -785,4 +707,40 @@ public function is_provider_supported(int $secretary_id, int $provider_id): bool return in_array($provider_id, $secretary['providers']); } + + /** + * Get a specific secretary from the database. + * + * @param int $secretary_id The ID of the record to be returned. + * + * @return array Returns an array with the secretary data. + * + * @throws InvalidArgumentException + */ + public function find(int $secretary_id): array + { + $secretary = $this->db->get_where('users', ['id' => $secretary_id])->row_array(); + + if (!$secretary) { + throw new InvalidArgumentException( + 'The provided secretary ID was not found in the database: ' . $secretary_id + ); + } + + $secretary['settings'] = $this->db->get_where('user_settings', ['id_users' => $secretary_id])->row_array(); + + unset($secretary['settings']['id_users'], $secretary['settings']['password'], $secretary['settings']['salt']); + + $secretary_provider_connections = $this->db + ->get_where('secretaries_providers', ['id_users_secretary' => $secretary_id]) + ->result_array(); + + $secretary['providers'] = []; + + foreach ($secretary_provider_connections as $secretary_provider_connection) { + $secretary['providers'][] = (int) $secretary_provider_connection['id_users_provider']; + } + + return $secretary; + } } diff --git a/application/models/Service_categories_model.php b/application/models/Service_categories_model.php index b0fc1c3f55..210fbd29e7 100644 --- a/application/models/Service_categories_model.php +++ b/application/models/Service_categories_model.php @@ -18,12 +18,13 @@ * * @package Models */ -class Service_categories_model extends EA_Model { +class Service_categories_model extends EA_Model +{ /** * @var array */ protected array $casts = [ - 'id' => 'integer', + 'id' => 'integer' ]; /** @@ -32,7 +33,7 @@ class Service_categories_model extends EA_Model { protected array $api_resource = [ 'id' => 'id', 'name' => 'name', - 'description' => 'description', + 'description' => 'description' ]; /** @@ -48,12 +49,9 @@ public function save(array $service_category): int { $this->validate($service_category); - if (empty($service_category['id'])) - { + if (empty($service_category['id'])) { return $this->insert($service_category); - } - else - { + } else { return $this->update($service_category); } } @@ -68,22 +66,21 @@ public function save(array $service_category): int public function validate(array $service_category) { // If a service-category ID is provided then check whether the record really exists in the database. - if ( ! empty($service_category['id'])) - { + if (!empty($service_category['id'])) { $count = $this->db->get_where('service_categories', ['id' => $service_category['id']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided service-category ID does not exist in the database: ' . $service_category['id']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided service-category ID does not exist in the database: ' . $service_category['id'] + ); } } // Make sure all required fields are provided. - if ( - empty($service_category['name']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($service_category, TRUE)); + if (empty($service_category['name'])) { + throw new InvalidArgumentException( + 'Not all required fields are provided: ' . print_r($service_category, true) + ); } } @@ -100,9 +97,8 @@ protected function insert(array $service_category): int { $service_category['create_datetime'] = date('Y-m-d H:i:s'); $service_category['update_datetime'] = date('Y-m-d H:i:s'); - - if ( ! $this->db->insert('service_categories', $service_category)) - { + + if (!$this->db->insert('service_categories', $service_category)) { throw new RuntimeException('Could not insert service-category.'); } @@ -121,9 +117,8 @@ protected function insert(array $service_category): int protected function update(array $service_category): int { $service_category['update_datetime'] = date('Y-m-d H:i:s'); - - if ( ! $this->db->update('service_categories', $service_category, ['id' => $service_category['id']])) - { + + if (!$this->db->update('service_categories', $service_category, ['id' => $service_category['id']])) { throw new RuntimeException('Could not update service categories.'); } @@ -155,9 +150,10 @@ public function find(int $service_category_id): array { $service_category = $this->db->get_where('service_categories', ['id' => $service_category_id])->row_array(); - if ( ! $service_category) - { - throw new InvalidArgumentException('The provided service-category ID was not found in the database: ' . $service_category_id); + if (!$service_category) { + throw new InvalidArgumentException( + 'The provided service-category ID was not found in the database: ' . $service_category_id + ); } $this->cast($service_category); @@ -177,22 +173,21 @@ public function find(int $service_category_id): array */ public function value(int $service_category_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($service_category_id)) - { + if (empty($service_category_id)) { throw new InvalidArgumentException('The service-category ID argument cannot be empty.'); } // Check whether the service exists. $query = $this->db->get_where('service_categories', ['id' => $service_category_id]); - if ( ! $query->num_rows()) - { - throw new InvalidArgumentException('The provided service-category ID was not found in the database: ' . $service_category_id); + if (!$query->num_rows()) { + throw new InvalidArgumentException( + 'The provided service-category ID was not found in the database: ' . $service_category_id + ); } // Check if the required field is part of the service-category data. @@ -200,46 +195,15 @@ public function value(int $service_category_id, string $field): mixed $this->cast($service_category); - if ( ! array_key_exists($field, $service_category)) - { - throw new InvalidArgumentException('The requested field was not found in the service-category data: ' . $field); + if (!array_key_exists($field, $service_category)) { + throw new InvalidArgumentException( + 'The requested field was not found in the service-category data: ' . $field + ); } return $service_category[$field]; } - /** - * Get all services that match the provided criteria. - * - * @param array|string|null $where Where conditions - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. - * - * @return array Returns an array of service categories. - */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by !== NULL) - { - $this->db->order_by($order_by); - } - - $service_categories = $this->db->get('service_categories', $limit, $offset)->result_array(); - - foreach ($service_categories as &$service_category) - { - $this->cast($service_category); - } - - return $service_categories; - } - /** * Get the query builder interface, configured for use with the service categories table. * @@ -260,10 +224,9 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of service categories. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { - $service_categories = $this - ->db + $service_categories = $this->db ->select() ->from('service_categories') ->group_start() @@ -276,8 +239,40 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($service_categories as &$service_category) - { + foreach ($service_categories as &$service_category) { + $this->cast($service_category); + } + + return $service_categories; + } + + /** + * Get all services that match the provided criteria. + * + * @param array|string|null $where Where conditions + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. + * + * @return array Returns an array of service categories. + */ + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + if ($where !== null) { + $this->db->where($where); + } + + if ($order_by !== null) { + $this->db->order_by($order_by); + } + + $service_categories = $this->db->get('service_categories', $limit, $offset)->result_array(); + + foreach ($service_categories as &$service_category) { $this->cast($service_category); } @@ -294,7 +289,7 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s */ public function load(array &$service_category, array $resources) { - // Service categories do not currently have any related resources. + // Service categories do not currently have any related resources. } /** @@ -305,9 +300,11 @@ public function load(array &$service_category, array $resources) public function api_encode(array &$service_category) { $encoded_resource = [ - 'id' => array_key_exists('id', $service_category) ? (int)$service_category['id'] : NULL, + 'id' => array_key_exists('id', $service_category) ? (int) $service_category['id'] : null, 'name' => $service_category['name'], - 'description' => array_key_exists('description', $service_category) ? $service_category['description'] : NULL + 'description' => array_key_exists('description', $service_category) + ? $service_category['description'] + : null ]; $service_category = $encoded_resource; @@ -319,22 +316,19 @@ public function api_encode(array &$service_category) * @param array $service_category API resource. * @param array|null $base Base service-category data to be overwritten with the provided values (useful for updates). */ - public function api_decode(array &$service_category, array $base = NULL) + public function api_decode(array &$service_category, array $base = null) { $decoded_resource = $base ?: []; - if (array_key_exists('id', $service_category)) - { + if (array_key_exists('id', $service_category)) { $decoded_resource['id'] = $service_category['id']; } - if (array_key_exists('name', $service_category)) - { + if (array_key_exists('name', $service_category)) { $decoded_resource['name'] = $service_category['name']; } - if (array_key_exists('description', $service_category)) - { + if (array_key_exists('description', $service_category)) { $decoded_resource['description'] = $service_category['description']; } diff --git a/application/models/Services_model.php b/application/models/Services_model.php index 2d24633a61..5ad51894fa 100644 --- a/application/models/Services_model.php +++ b/application/models/Services_model.php @@ -18,7 +18,8 @@ * * @package Models */ -class Services_model extends EA_Model { +class Services_model extends EA_Model +{ /** * @var array */ @@ -27,7 +28,7 @@ class Services_model extends EA_Model { 'price' => 'float', 'attendants_number' => 'integer', 'is_private' => 'boolean', - 'id_service_categories' => 'integer', + 'id_service_categories' => 'integer' ]; /** @@ -45,7 +46,7 @@ class Services_model extends EA_Model { 'availabilitiesType' => 'availabilities_type', 'attendantsNumber' => 'attendants_number', 'isPrivate' => 'is_private', - 'serviceCategoryId' => 'id_service_categories', + 'serviceCategoryId' => 'id_service_categories' ]; /** @@ -61,12 +62,9 @@ public function save(array $service): int { $this->validate($service); - if (empty($service['id'])) - { + if (empty($service['id'])) { return $this->insert($service); - } - else - { + } else { return $this->update($service); } } @@ -81,65 +79,73 @@ public function save(array $service): int public function validate(array $service) { // If a service ID is provided then check whether the record really exists in the database. - if ( ! empty($service['id'])) - { + if (!empty($service['id'])) { $count = $this->db->get_where('services', ['id' => $service['id']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided service ID does not exist in the database: ' . $service['id']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided service ID does not exist in the database: ' . $service['id'] + ); } } // Make sure all required fields are provided. - if ( - empty($service['name']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($service, TRUE)); + if (empty($service['name'])) { + throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($service, true)); } - // If a category was provided then make sure it really exists in the database. - if ( ! empty($service['id_service_categories'])) - { + // If a category was provided then make sure it really exists in the database. + if (!empty($service['id_service_categories'])) { $count = $this->db->get_where('categories', ['id' => $service['id_service_categories']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided category ID was not found in the database: ' . $service['id_service_categories']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided category ID was not found in the database: ' . $service['id_service_categories'] + ); } } - // Make sure the duration value is valid. - if ( ! empty($service['duration'])) - { - if ((int)$service['duration'] < EVENT_MINIMUM_DURATION) - { - throw new InvalidArgumentException('The service duration cannot be less than ' . EVENT_MINIMUM_DURATION . ' minutes long.'); + // Make sure the duration value is valid. + if (!empty($service['duration'])) { + if ((int) $service['duration'] < EVENT_MINIMUM_DURATION) { + throw new InvalidArgumentException( + 'The service duration cannot be less than ' . EVENT_MINIMUM_DURATION . ' minutes long.' + ); } } // Availabilities type must have the correct value. - if ($service['availabilities_type'] !== NULL && $service['availabilities_type'] !== AVAILABILITIES_TYPE_FLEXIBLE - && $service['availabilities_type'] !== AVAILABILITIES_TYPE_FIXED) - { - throw new InvalidArgumentException('Service availabilities type must be either ' . AVAILABILITIES_TYPE_FLEXIBLE - . ' or ' . AVAILABILITIES_TYPE_FIXED . ' (given ' . $service['availabilities_type'] . ')'); + if ( + $service['availabilities_type'] !== null && + $service['availabilities_type'] !== AVAILABILITIES_TYPE_FLEXIBLE && + $service['availabilities_type'] !== AVAILABILITIES_TYPE_FIXED + ) { + throw new InvalidArgumentException( + 'Service availabilities type must be either ' . + AVAILABILITIES_TYPE_FLEXIBLE . + ' or ' . + AVAILABILITIES_TYPE_FIXED . + ' (given ' . + $service['availabilities_type'] . + ')' + ); } // Validate the availabilities type value. if ( - ! empty($service['availabilities_type']) - && ! in_array($service['availabilities_type'], [AVAILABILITIES_TYPE_FLEXIBLE, AVAILABILITIES_TYPE_FIXED]) - ) - { - throw new InvalidArgumentException('The provided availabilities type is invalid: ' . $service['availabilities_type']); + !empty($service['availabilities_type']) && + !in_array($service['availabilities_type'], [AVAILABILITIES_TYPE_FLEXIBLE, AVAILABILITIES_TYPE_FIXED]) + ) { + throw new InvalidArgumentException( + 'The provided availabilities type is invalid: ' . $service['availabilities_type'] + ); } - // Validate the attendants number value. - if (empty($service['attendants_number']) || (int)$service['attendants_number'] < 1) - { - throw new InvalidArgumentException('The provided attendants number is invalid: ' . $service['attendants_number']); + // Validate the attendants number value. + if (empty($service['attendants_number']) || (int) $service['attendants_number'] < 1) { + throw new InvalidArgumentException( + 'The provided attendants number is invalid: ' . $service['attendants_number'] + ); } } @@ -157,8 +163,7 @@ protected function insert(array $service): int $service['create_datetime'] = date('Y-m-d H:i:s'); $service['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->insert('services', $service)) - { + if (!$this->db->insert('services', $service)) { throw new RuntimeException('Could not insert service.'); } @@ -178,8 +183,7 @@ protected function update(array $service): int { $service['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->update('services', $service, ['id' => $service['id']])) - { + if (!$this->db->update('services', $service, ['id' => $service['id']])) { throw new RuntimeException('Could not update service.'); } @@ -211,8 +215,7 @@ public function find(int $service_id): array { $service = $this->db->get_where('services', ['id' => $service_id])->row_array(); - if ( ! $service) - { + if (!$service) { throw new InvalidArgumentException('The provided service ID was not found in the database: ' . $service_id); } @@ -233,21 +236,18 @@ public function find(int $service_id): array */ public function value(int $service_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($service_id)) - { + if (empty($service_id)) { throw new InvalidArgumentException('The service ID argument cannot be empty.'); } // Check whether the service exists. $query = $this->db->get_where('services', ['id' => $service_id]); - if ( ! $query->num_rows()) - { + if (!$query->num_rows()) { throw new InvalidArgumentException('The provided service ID was not found in the database: ' . $service_id); } @@ -256,8 +256,7 @@ public function value(int $service_id, string $field): mixed $this->cast($service); - if ( ! array_key_exists($field, $service)) - { + if (!array_key_exists($field, $service)) { throw new InvalidArgumentException('The requested field was not found in the service data: ' . $field); } @@ -265,31 +264,31 @@ public function value(int $service_id, string $field): mixed } /** - * Get all services that match the provided criteria. + * Get all the service records that are assigned to at least one provider. * - * @param array|string|null $where Where conditions - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. + * @param bool $without_private Only include the public services. * * @return array Returns an array of services. */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function get_available_services(bool $without_private = false): array { - if ($where !== NULL) - { - $this->db->where($where); + if ($without_private) { + $this->db->where('services.is_private', false); } - if ($order_by !== NULL) - { - $this->db->order_by($order_by); - } - - $services = $this->db->get('services', $limit, $offset)->result_array(); + $services = $this->db + ->distinct() + ->select( + 'services.*, service_categories.name AS service_category_name, service_categories.id AS service_category_id' + ) + ->from('services') + ->join('services_providers', 'services_providers.id_services = services.id', 'inner') + ->join('service_categories', 'service_categories.id = services.id_service_categories', 'left') + ->order_by('name ASC') + ->get() + ->result_array(); - foreach ($services as &$service) - { + foreach ($services as &$service) { $this->cast($service); } @@ -297,32 +296,32 @@ public function get(array|string $where = NULL, int $limit = NULL, int $offset = } /** - * Get all the service records that are assigned to at least one provider. + * Get all services that match the provided criteria. * - * @param bool $without_private Only include the public services. + * @param array|string|null $where Where conditions + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. * * @return array Returns an array of services. */ - public function get_available_services(bool $without_private = FALSE): array - { - if ($without_private) - { - $this->db->where('services.is_private', FALSE); + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + if ($where !== null) { + $this->db->where($where); } - $services = $this - ->db - ->distinct() - ->select('services.*, service_categories.name AS service_category_name, service_categories.id AS service_category_id') - ->from('services') - ->join('services_providers', 'services_providers.id_services = services.id', 'inner') - ->join('service_categories', 'service_categories.id = services.id_service_categories', 'left') - ->order_by('name ASC') - ->get() - ->result_array(); + if ($order_by !== null) { + $this->db->order_by($order_by); + } + + $services = $this->db->get('services', $limit, $offset)->result_array(); - foreach ($services as &$service) - { + foreach ($services as &$service) { $this->cast($service); } @@ -349,10 +348,9 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of services. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { - $services = $this - ->db + $services = $this->db ->select() ->from('services') ->group_start() @@ -365,8 +363,7 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($services as &$service) - { + foreach ($services as &$service) { $this->cast($service); } @@ -383,22 +380,20 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s */ public function load(array &$service, array $resources) { - if (empty($service) || empty($resources)) - { + if (empty($service) || empty($resources)) { return; } - foreach ($resources as $resource) - { - $service['category'] = match ($resource) - { - 'category' => $this - ->db + foreach ($resources as $resource) { + $service['category'] = match ($resource) { + 'category' => $this->db ->get_where('categories', [ - 'id' => $service['id_service_categories'] ?? $service['serviceCategoryId'] ?? NULL + 'id' => $service['id_service_categories'] ?? ($service['serviceCategoryId'] ?? null) ]) ->row_array(), - default => throw new InvalidArgumentException('The requested appointment relation is not supported: ' . $resource), + default => throw new InvalidArgumentException( + 'The requested appointment relation is not supported: ' . $resource + ) }; } } @@ -411,16 +406,17 @@ public function load(array &$service, array $resources) public function api_encode(array &$service) { $encoded_resource = [ - 'id' => array_key_exists('id', $service) ? (int)$service['id'] : NULL, + 'id' => array_key_exists('id', $service) ? (int) $service['id'] : null, 'name' => $service['name'], - 'duration' => (int)$service['duration'], - 'price' => (float)$service['price'], + 'duration' => (int) $service['duration'], + 'price' => (float) $service['price'], 'currency' => $service['currency'], 'description' => $service['description'], 'location' => $service['location'], 'availabilitiesType' => $service['availabilities_type'], - 'attendantsNumber' => (int)$service['attendants_number'], - 'serviceCategoryId' => $service['id_service_categories'] !== NULL ? (int)$service['id_service_categories'] : NULL + 'attendantsNumber' => (int) $service['attendants_number'], + 'serviceCategoryId' => + $service['id_service_categories'] !== null ? (int) $service['id_service_categories'] : null ]; $service = $encoded_resource; @@ -432,57 +428,47 @@ public function api_encode(array &$service) * @param array $service API resource. * @param array|null $base Base service data to be overwritten with the provided values (useful for updates). */ - public function api_decode(array &$service, array $base = NULL) + public function api_decode(array &$service, array $base = null) { $decoded_resource = $base ?: []; - if (array_key_exists('id', $service)) - { + if (array_key_exists('id', $service)) { $decoded_resource['id'] = $service['id']; } - if (array_key_exists('name', $service)) - { + if (array_key_exists('name', $service)) { $decoded_resource['name'] = $service['name']; } - if (array_key_exists('duration', $service)) - { + if (array_key_exists('duration', $service)) { $decoded_resource['duration'] = $service['duration']; } - if (array_key_exists('price', $service)) - { + if (array_key_exists('price', $service)) { $decoded_resource['price'] = $service['price']; } - if (array_key_exists('currency', $service)) - { + if (array_key_exists('currency', $service)) { $decoded_resource['currency'] = $service['currency']; } - if (array_key_exists('description', $service)) - { + if (array_key_exists('description', $service)) { $decoded_resource['description'] = $service['description']; } - if (array_key_exists('location', $service)) - { + if (array_key_exists('location', $service)) { $decoded_resource['location'] = $service['location']; } - if (array_key_exists('availabilitiesType', $service)) - { + if (array_key_exists('availabilitiesType', $service)) { $decoded_resource['availabilities_type'] = $service['availabilitiesType']; } - if (array_key_exists('attendantsNumber', $service)) - { + if (array_key_exists('attendantsNumber', $service)) { $decoded_resource['attendants_number'] = $service['attendantsNumber']; } - if (array_key_exists('serviceCategoryId', $service)) - { + if (array_key_exists('serviceCategoryId', $service)) { $decoded_resource['id_service_categories'] = $service['serviceCategoryId']; } diff --git a/application/models/Settings_model.php b/application/models/Settings_model.php index deff8953ce..f7a3943c51 100644 --- a/application/models/Settings_model.php +++ b/application/models/Settings_model.php @@ -18,12 +18,13 @@ * * @package Models */ -class Settings_model extends EA_Model { +class Settings_model extends EA_Model +{ /** * @var array */ protected array $casts = [ - 'id' => 'integer', + 'id' => 'integer' ]; /** @@ -31,7 +32,7 @@ class Settings_model extends EA_Model { */ protected array $api_resource = [ 'name' => 'name', - 'value' => 'value', + 'value' => 'value' ]; /** @@ -47,12 +48,9 @@ public function save(array $setting): int { $this->validate($setting); - if (empty($setting['id'])) - { + if (empty($setting['id'])) { return $this->insert($setting); - } - else - { + } else { return $this->update($setting); } } @@ -67,22 +65,19 @@ public function save(array $setting): int public function validate(array $setting) { // If a setting ID is provided then check whether the record really exists in the database. - if ( ! empty($setting['id'])) - { + if (!empty($setting['id'])) { $count = $this->db->get_where('settings', ['id' => $setting['id']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided setting ID does not exist in the database: ' . $setting['id']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided setting ID does not exist in the database: ' . $setting['id'] + ); } } // Make sure all required fields are provided. - if ( - empty($setting['name']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($setting, TRUE)); + if (empty($setting['name'])) { + throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($setting, true)); } } @@ -100,8 +95,7 @@ protected function insert(array $setting): int $setting['create_datetime'] = date('Y-m-d H:i:s'); $setting['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->insert('settings', $setting)) - { + if (!$this->db->insert('settings', $setting)) { throw new RuntimeException('Could not insert setting.'); } @@ -121,8 +115,7 @@ protected function update(array $setting): int { $setting['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->update('settings', $setting, ['id' => $setting['id']])) - { + if (!$this->db->update('settings', $setting, ['id' => $setting['id']])) { throw new RuntimeException('Could not update setting.'); } @@ -154,8 +147,7 @@ public function find(int $setting_id): array { $setting = $this->db->get_where('settings', ['id' => $setting_id])->row_array(); - if ( ! $setting) - { + if (!$setting) { throw new InvalidArgumentException('The provided setting ID was not found in the database: ' . $setting_id); } @@ -176,21 +168,18 @@ public function find(int $setting_id): array */ public function value(int $setting_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($setting_id)) - { + if (empty($setting_id)) { throw new InvalidArgumentException('The setting ID argument cannot be empty.'); } // Check whether the setting exists. $query = $this->db->get_where('settings', ['id' => $setting_id]); - if ( ! $query->num_rows()) - { + if (!$query->num_rows()) { throw new InvalidArgumentException('The provided setting ID was not found in the database: ' . $setting_id); } @@ -199,46 +188,13 @@ public function value(int $setting_id, string $field): mixed $this->cast($setting); - if ( ! array_key_exists($field, $setting)) - { + if (!array_key_exists($field, $setting)) { throw new InvalidArgumentException('The requested field was not found in the setting data: ' . $field); } return $setting[$field]; } - /** - * Get all settings that match the provided criteria. - * - * @param array|string|null $where Where conditions - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. - * - * @return array Returns an array of settings. - */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by !== NULL) - { - $this->db->order_by($order_by); - } - - $settings = $this->db->get('settings', $limit, $offset)->result_array(); - - foreach ($settings as &$setting) - { - $this->cast($setting); - } - - return $settings; - } - /** * Get the query builder interface, configured for use with the settings table. * @@ -259,10 +215,9 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of settings. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { - $settings = $this - ->db + $settings = $this->db ->select() ->from('settings') ->group_start() @@ -275,8 +230,40 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($settings as &$setting) - { + foreach ($settings as &$setting) { + $this->cast($setting); + } + + return $settings; + } + + /** + * Get all settings that match the provided criteria. + * + * @param array|string|null $where Where conditions + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. + * + * @return array Returns an array of settings. + */ + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + if ($where !== null) { + $this->db->where($where); + } + + if ($order_by !== null) { + $this->db->order_by($order_by); + } + + $settings = $this->db->get('settings', $limit, $offset)->result_array(); + + foreach ($settings as &$setting) { $this->cast($setting); } @@ -317,17 +304,15 @@ public function api_encode(array &$setting) * @param array $setting API resource. * @param array|null $base Base setting data to be overwritten with the provided values (useful for updates). */ - public function api_decode(array &$setting, array $base = NULL) + public function api_decode(array &$setting, array $base = null) { $decoded_resource = $base ?: []; - if (array_key_exists('name', $setting)) - { + if (array_key_exists('name', $setting)) { $decoded_resource['name'] = $setting['name']; } - if (array_key_exists('value', $setting)) - { + if (array_key_exists('value', $setting)) { $decoded_resource['value'] = $setting['value']; } diff --git a/application/models/Unavailabilities_model.php b/application/models/Unavailabilities_model.php index edd23d3981..ef9d0a3014 100644 --- a/application/models/Unavailabilities_model.php +++ b/application/models/Unavailabilities_model.php @@ -16,7 +16,8 @@ * * @package Models */ -class Unavailabilities_model extends EA_Model { +class Unavailabilities_model extends EA_Model +{ /** * @var array */ @@ -25,7 +26,7 @@ class Unavailabilities_model extends EA_Model { 'is_unavailability' => 'boolean', 'id_users_provider' => 'integer', 'id_users_customer' => 'integer', - 'id_services' => 'integer', + 'id_services' => 'integer' ]; /** @@ -42,7 +43,7 @@ class Unavailabilities_model extends EA_Model { 'notes' => 'notes', 'hash' => 'hash', 'providerId' => 'id_users_provider', - 'googleCalendarId' => 'id_google_calendar', + 'googleCalendarId' => 'id_google_calendar' ]; /** @@ -58,12 +59,9 @@ public function save(array $unavailability): int { $this->validate($unavailability); - if (empty($unavailability['id'])) - { + if (empty($unavailability['id'])) { return $this->insert($unavailability); - } - else - { + } else { return $this->update($unavailability); } } @@ -78,48 +76,47 @@ public function save(array $unavailability): int public function validate(array $unavailability) { // If an unavailability ID is provided then check whether the record really exists in the database. - if ( ! empty($unavailability['id'])) - { + if (!empty($unavailability['id'])) { $count = $this->db->get_where('appointments', ['id' => $unavailability['id']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided unavailability ID does not exist in the database: ' . $unavailability['id']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided unavailability ID does not exist in the database: ' . $unavailability['id'] + ); } } // Make sure all required fields are provided. if ( - empty($unavailability['start_datetime']) - || empty($unavailability['end_datetime']) - || empty($unavailability['id_users_provider']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($unavailability, TRUE)); + empty($unavailability['start_datetime']) || + empty($unavailability['end_datetime']) || + empty($unavailability['id_users_provider']) + ) { + throw new InvalidArgumentException( + 'Not all required fields are provided: ' . print_r($unavailability, true) + ); } // Make sure that the provided unavailability date time values are valid. - if ( ! validate_datetime($unavailability['start_datetime'])) - { + if (!validate_datetime($unavailability['start_datetime'])) { throw new InvalidArgumentException('The unavailability start date time is invalid.'); } - if ( ! validate_datetime($unavailability['end_datetime'])) - { + if (!validate_datetime($unavailability['end_datetime'])) { throw new InvalidArgumentException('The unavailability end date time is invalid.'); } // Make the unavailability lasts longer than the minimum duration (in minutes). $diff = (strtotime($unavailability['end_datetime']) - strtotime($unavailability['start_datetime'])) / 60; - if ($diff < EVENT_MINIMUM_DURATION) - { - throw new InvalidArgumentException('The unavailability duration cannot be less than ' . EVENT_MINIMUM_DURATION . ' minutes.'); + if ($diff < EVENT_MINIMUM_DURATION) { + throw new InvalidArgumentException( + 'The unavailability duration cannot be less than ' . EVENT_MINIMUM_DURATION . ' minutes.' + ); } // Make sure the provider ID really exists in the database. - $count = $this - ->db + $count = $this->db ->select() ->from('users') ->join('roles', 'roles.id = users.id_roles', 'inner') @@ -128,12 +125,48 @@ public function validate(array $unavailability) ->get() ->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The unavailability provider ID was not found in the database: ' . $unavailability['id_users_provider']); + if (!$count) { + throw new InvalidArgumentException( + 'The unavailability provider ID was not found in the database: ' . $unavailability['id_users_provider'] + ); } } + /** + * Get all unavailabilities that match the provided criteria. + * + * @param array|string|null $where Where conditions. + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. + * + * @return array Returns an array of unavailabilities. + */ + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + if ($where !== null) { + $this->db->where($where); + } + + if ($order_by) { + $this->db->order_by($order_by); + } + + $unavailabilities = $this->db + ->get_where('appointments', ['is_unavailability' => true], $limit, $offset) + ->result_array(); + + foreach ($unavailabilities as &$unavailability) { + $this->cast($unavailability); + } + + return $unavailabilities; + } + /** * Insert a new unavailability into the database. * @@ -149,10 +182,9 @@ protected function insert(array $unavailability): int $unavailability['create_datetime'] = date('Y-m-d H:i:s'); $unavailability['update_datetime'] = date('Y-m-d H:i:s'); $unavailability['hash'] = random_string('alnum', 12); - $unavailability['is_unavailability'] = TRUE; + $unavailability['is_unavailability'] = true; - if ( ! $this->db->insert('appointments', $unavailability)) - { + if (!$this->db->insert('appointments', $unavailability)) { throw new RuntimeException('Could not insert unavailability.'); } @@ -172,8 +204,7 @@ protected function update(array $unavailability): int { $unavailability['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->update('appointments', $unavailability, ['id' => $unavailability['id']])) - { + if (!$this->db->update('appointments', $unavailability, ['id' => $unavailability['id']])) { throw new RuntimeException('Could not update unavailability record.'); } @@ -205,9 +236,10 @@ public function find(int $unavailability_id): array { $unavailability = $this->db->get_where('appointments', ['id' => $unavailability_id])->row_array(); - if ( ! $unavailability) - { - throw new InvalidArgumentException('The provided unavailability ID was not found in the database: ' . $unavailability_id); + if (!$unavailability) { + throw new InvalidArgumentException( + 'The provided unavailability ID was not found in the database: ' . $unavailability_id + ); } $this->cast($unavailability); @@ -227,22 +259,21 @@ public function find(int $unavailability_id): array */ public function value(int $unavailability_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($unavailability_id)) - { + if (empty($unavailability_id)) { throw new InvalidArgumentException('The unavailability ID argument cannot be empty.'); } // Check whether the unavailability exists. $query = $this->db->get_where('appointments', ['id' => $unavailability_id]); - if ( ! $query->num_rows()) - { - throw new InvalidArgumentException('The provided unavailability ID was not found in the database: ' . $unavailability_id); + if (!$query->num_rows()) { + throw new InvalidArgumentException( + 'The provided unavailability ID was not found in the database: ' . $unavailability_id + ); } // Check if the required field is part of the unavailability data. @@ -250,46 +281,15 @@ public function value(int $unavailability_id, string $field): mixed $this->cast($unavailability); - if ( ! array_key_exists($field, $unavailability)) - { - throw new InvalidArgumentException('The requested field was not found in the unavailability data: ' . $field); + if (!array_key_exists($field, $unavailability)) { + throw new InvalidArgumentException( + 'The requested field was not found in the unavailability data: ' . $field + ); } return $unavailability[$field]; } - /** - * Get all unavailabilities that match the provided criteria. - * - * @param array|string|null $where Where conditions. - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. - * - * @return array Returns an array of unavailabilities. - */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by) - { - $this->db->order_by($order_by); - } - - $unavailabilities = $this->db->get_where('appointments', ['is_unavailability' => TRUE], $limit, $offset)->result_array(); - - foreach ($unavailabilities as &$unavailability) - { - $this->cast($unavailability); - } - - return $unavailabilities; - } - /** * Get the query builder interface, configured for use with the unavailabilities table. * @@ -310,14 +310,13 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of unavailabilities. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { - $unavailabilities = $this - ->db + $unavailabilities = $this->db ->select() ->from('appointments') ->join('users AS providers', 'providers.id = appointments.id_users_provider', 'inner') - ->where('is_unavailability', TRUE) + ->where('is_unavailability', true) ->group_start() ->like('appointments.start_datetime', $keyword) ->or_like('appointments.end_datetime', $keyword) @@ -335,8 +334,7 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($unavailabilities as &$unavailability) - { + foreach ($unavailabilities as &$unavailability) { $this->cast($unavailability); } @@ -353,22 +351,20 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s */ public function load(array &$unavailability, array $resources) { - if (empty($unavailability) || empty($resources)) - { + if (empty($unavailability) || empty($resources)) { return; } - foreach ($resources as $resource) - { - $unavailability['provider'] = match ($resource) - { - 'provider' => $this - ->db + foreach ($resources as $resource) { + $unavailability['provider'] = match ($resource) { + 'provider' => $this->db ->get_where('users', [ - 'id' => $unavailability['id_users_provider'] ?? $unavailability['providerId'] ?? NULL + 'id' => $unavailability['id_users_provider'] ?? ($unavailability['providerId'] ?? null) ]) ->row_array(), - default => throw new InvalidArgumentException('The requested unavailability relation is not supported: ' . $resource), + default => throw new InvalidArgumentException( + 'The requested unavailability relation is not supported: ' . $resource + ) }; } } @@ -381,15 +377,17 @@ public function load(array &$unavailability, array $resources) public function api_encode(array &$unavailability) { $encoded_resource = [ - 'id' => array_key_exists('id', $unavailability) ? (int)$unavailability['id'] : NULL, + 'id' => array_key_exists('id', $unavailability) ? (int) $unavailability['id'] : null, 'book' => $unavailability['book_datetime'], 'start' => $unavailability['start_datetime'], 'end' => $unavailability['end_datetime'], 'hash' => $unavailability['hash'], 'location' => $unavailability['location'], 'notes' => $unavailability['notes'], - 'providerId' => $unavailability['id_users_provider'] !== NULL ? (int)$unavailability['id_users_provider'] : NULL, - 'googleCalendarId' => $unavailability['id_google_calendar'] !== NULL ? (int)$unavailability['id_google_calendar'] : NULL + 'providerId' => + $unavailability['id_users_provider'] !== null ? (int) $unavailability['id_users_provider'] : null, + 'googleCalendarId' => + $unavailability['id_google_calendar'] !== null ? (int) $unavailability['id_google_calendar'] : null ]; $unavailability = $encoded_resource; @@ -401,56 +399,47 @@ public function api_encode(array &$unavailability) * @param array $unavailability API resource. * @param array|null $base Base unavailability data to be overwritten with the provided values (useful for updates). */ - public function api_decode(array &$unavailability, array $base = NULL) + public function api_decode(array &$unavailability, array $base = null) { $decoded_request = $base ?: []; - if (array_key_exists('id', $unavailability)) - { + if (array_key_exists('id', $unavailability)) { $decoded_request['id'] = $unavailability['id']; } - if (array_key_exists('book', $unavailability)) - { + if (array_key_exists('book', $unavailability)) { $decoded_request['book_datetime'] = $unavailability['book']; } - if (array_key_exists('start', $unavailability)) - { + if (array_key_exists('start', $unavailability)) { $decoded_request['start_datetime'] = $unavailability['start']; } - if (array_key_exists('end', $unavailability)) - { + if (array_key_exists('end', $unavailability)) { $decoded_request['end_datetime'] = $unavailability['end']; } - if (array_key_exists('hash', $unavailability)) - { + if (array_key_exists('hash', $unavailability)) { $decoded_request['hash'] = $unavailability['hash']; } - if (array_key_exists('location', $unavailability)) - { + if (array_key_exists('location', $unavailability)) { $decoded_request['location'] = $unavailability['location']; } - if (array_key_exists('notes', $unavailability)) - { + if (array_key_exists('notes', $unavailability)) { $decoded_request['notes'] = $unavailability['notes']; } - if (array_key_exists('providerId', $unavailability)) - { + if (array_key_exists('providerId', $unavailability)) { $decoded_request['id_users_provider'] = $unavailability['providerId']; } - if (array_key_exists('googleCalendarId', $unavailability)) - { + if (array_key_exists('googleCalendarId', $unavailability)) { $decoded_request['id_google_calendar'] = $unavailability['googleCalendarId']; } - $decoded_request['is_unavailability'] = TRUE; + $decoded_request['is_unavailability'] = true; $unavailability = $decoded_request; } diff --git a/application/models/Users_model.php b/application/models/Users_model.php index 0aefdea215..48c5df2955 100644 --- a/application/models/Users_model.php +++ b/application/models/Users_model.php @@ -18,13 +18,14 @@ * * @package Models */ -class Users_model extends EA_Model { +class Users_model extends EA_Model +{ /** * @var array */ protected array $casts = [ 'id' => 'integer', - 'id_roles' => 'integer', + 'id_roles' => 'integer' ]; /** @@ -44,7 +45,7 @@ class Users_model extends EA_Model { 'timezone' => 'timezone', 'language' => 'language', 'notes' => 'notes', - 'roleId' => 'id_roles', + 'roleId' => 'id_roles' ]; /** @@ -61,12 +62,9 @@ public function save(array $user): int { $this->validate($user); - if (empty($user['id'])) - { + if (empty($user['id'])) { return $this->insert($user); - } - else - { + } else { return $this->update($user); } } @@ -81,25 +79,24 @@ public function save(array $user): int public function validate(array $user) { // If a user ID is provided then check whether the record really exists in the database. - if ( ! empty($user['id'])) - { + if (!empty($user['id'])) { $count = $this->db->get_where('users', ['id' => $user['id']])->num_rows(); - if ( ! $count) - { - throw new InvalidArgumentException('The provided user ID does not exist in the database: ' . $user['id']); + if (!$count) { + throw new InvalidArgumentException( + 'The provided user ID does not exist in the database: ' . $user['id'] + ); } } // Make sure all required fields are provided. if ( - empty($user['first_name']) - || empty($user['last_name']) - || empty($user['email']) - || empty($user['phone_number']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($user, TRUE)); + empty($user['first_name']) || + empty($user['last_name']) || + empty($user['email']) || + empty($user['phone_number']) + ) { + throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($user, true)); } } @@ -120,8 +117,7 @@ protected function insert(array $user): int $settings = $user['settings']; unset($user['settings']); - if ( ! $this->db->insert('users', $user)) - { + if (!$this->db->insert('users', $user)) { throw new RuntimeException('Could not insert user.'); } @@ -134,6 +130,46 @@ protected function insert(array $user): int return $user['id']; } + /** + * Save the user settings. + * + * @param int $user_id User ID. + * @param array $settings Associative array with the settings data. + * + * @throws InvalidArgumentException + */ + protected function save_settings(int $user_id, array $settings) + { + if (empty($settings)) { + throw new InvalidArgumentException('The settings argument cannot be empty.'); + } + + // Make sure the settings record exists in the database. + $count = $this->db->get_where('user_settings', ['id_users' => $user_id])->num_rows(); + + if (!$count) { + $this->db->insert('user_settings', ['id_users' => $user_id]); + } + + foreach ($settings as $name => $value) { + $this->set_setting($user_id, $name, $value); + } + } + + /** + * Set the value of a user setting. + * + * @param int $user_id User ID. + * @param string $name Setting name. + * @param string $value Setting value. + */ + public function set_setting(int $user_id, string $name, string $value) + { + if (!$this->db->update('user_settings', [$name => $value], ['id_users' => $user_id])) { + throw new RuntimeException('Could not set the new user setting value: ' . $name); + } + } + /** * Update an existing user. * @@ -150,20 +186,17 @@ protected function update(array $user): int $settings = $user['settings']; unset($user['settings']); - if (isset($settings['password'])) - { + if (isset($settings['password'])) { $existing_settings = $this->db->get_where('user_settings', ['id_users' => $user['id']])->row_array(); - if (empty($existing_settings)) - { + if (empty($existing_settings)) { throw new RuntimeException('No settings record found for user with ID: ' . $user['id']); } $settings['password'] = hash_password($existing_settings['salt'], $settings['password']); } - if ( ! $this->db->update('users', $user, ['id' => $user['id']])) - { + if (!$this->db->update('users', $user, ['id' => $user['id']])) { throw new RuntimeException('Could not update user.'); } @@ -197,8 +230,7 @@ public function find(int $user_id): array { $user = $this->db->get_where('users', ['id' => $user_id])->row_array(); - if ( ! $user) - { + if (!$user) { throw new InvalidArgumentException('The provided user ID was not found in the database: ' . $user_id); } @@ -206,11 +238,7 @@ public function find(int $user_id): array $user['settings'] = $this->db->get_where('user_settings', ['id_users' => $user_id])->row_array(); - unset( - $user['settings']['id_users'], - $user['settings']['password'], - $user['settings']['salt'], - ); + unset($user['settings']['id_users'], $user['settings']['password'], $user['settings']['salt']); return $user; } @@ -227,21 +255,18 @@ public function find(int $user_id): array */ public function value(int $user_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($user_id)) - { + if (empty($user_id)) { throw new InvalidArgumentException('The user ID argument cannot be empty.'); } // Check whether the user exists. $query = $this->db->get_where('users', ['id' => $user_id]); - if ( ! $query->num_rows()) - { + if (!$query->num_rows()) { throw new InvalidArgumentException('The provided user ID was not found in the database: ' . $user_id); } @@ -250,98 +275,13 @@ public function value(int $user_id, string $field): mixed $this->cast($user); - if ( ! array_key_exists($field, $user)) - { + if (!array_key_exists($field, $user)) { throw new InvalidArgumentException('The requested field was not found in the user data: ' . $field); } return $user[$field]; } - /** - * Get all users that match the provided criteria. - * - * @param array|string|null $where Where conditions - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. - * - * @return array Returns an array of users. - */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by !== NULL) - { - $this->db->order_by($order_by); - } - - $users = $this->db->get('users', $limit, $offset)->result_array(); - - foreach ($users as &$user) - { - $this->cast($user); - - $user['settings'] = $this->db->get_where('user_settings', ['id_users' => $user['id']])->row_array(); - - unset( - $user['settings']['id_users'], - $user['settings']['password'], - $user['settings']['salt'] - ); - } - - return $users; - } - - /** - * Save the user settings. - * - * @param int $user_id User ID. - * @param array $settings Associative array with the settings data. - * - * @throws InvalidArgumentException - */ - protected function save_settings(int $user_id, array $settings) - { - if (empty($settings)) - { - throw new InvalidArgumentException('The settings argument cannot be empty.'); - } - - // Make sure the settings record exists in the database. - $count = $this->db->get_where('user_settings', ['id_users' => $user_id])->num_rows(); - - if ( ! $count) - { - $this->db->insert('user_settings', ['id_users' => $user_id]); - } - - foreach ($settings as $name => $value) - { - $this->set_setting($user_id, $name, $value); - } - } - - /** - * Set the value of a user setting. - * - * @param int $user_id User ID. - * @param string $name Setting name. - * @param string $value Setting value. - */ - public function set_setting(int $user_id, string $name, string $value) - { - if ( ! $this->db->update('user_settings', [$name => $value], ['id_users' => $user_id])) - { - throw new RuntimeException('Could not set the new user setting value: ' . $name); - } - } - /** * Get the value of a user setting. * @@ -354,8 +294,7 @@ public function get_setting(int $user_id, string $name): string { $settings = $this->db->get_where('user_settings', ['id_users' => $user_id])->row_array(); - if (empty($settings[$name])) - { + if (empty($settings[$name])) { throw new RuntimeException('The requested setting value was not found: ' . $user_id); } @@ -382,10 +321,9 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of settings. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { - $users = $this - ->db + $users = $this->db ->select() ->from('users') ->group_start() @@ -406,17 +344,49 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($users as &$user) - { + foreach ($users as &$user) { + $this->cast($user); + + $user['settings'] = $this->db->get_where('user_settings', ['id_users' => $user['id']])->row_array(); + + unset($user['settings']['id_users'], $user['settings']['password'], $user['settings']['salt']); + } + + return $users; + } + + /** + * Get all users that match the provided criteria. + * + * @param array|string|null $where Where conditions + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. + * + * @return array Returns an array of users. + */ + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + if ($where !== null) { + $this->db->where($where); + } + + if ($order_by !== null) { + $this->db->order_by($order_by); + } + + $users = $this->db->get('users', $limit, $offset)->result_array(); + + foreach ($users as &$user) { $this->cast($user); $user['settings'] = $this->db->get_where('user_settings', ['id_users' => $user['id']])->row_array(); - unset( - $user['settings']['id_users'], - $user['settings']['password'], - $user['settings']['salt'] - ); + unset($user['settings']['id_users'], $user['settings']['password'], $user['settings']['salt']); } return $users; @@ -443,10 +413,9 @@ public function load(array &$user, array $resources) * * @return bool Returns the validation result. */ - public function validate_username(string $username, int $user_id = NULL): bool + public function validate_username(string $username, int $user_id = null): bool { - if ( ! empty($user_id)) - { + if (!empty($user_id)) { $this->db->where('id_users !=', $user_id); } diff --git a/application/models/Webhooks_model.php b/application/models/Webhooks_model.php index ba9f8df77a..db21c8ab4b 100644 --- a/application/models/Webhooks_model.php +++ b/application/models/Webhooks_model.php @@ -18,14 +18,15 @@ * * @package Models */ -class Webhooks_model extends EA_Model { +class Webhooks_model extends EA_Model +{ /** * @var array */ protected array $casts = [ 'id' => 'integer', 'is_active' => 'boolean', - 'is_ssl_verified' => 'boolean', + 'is_ssl_verified' => 'boolean' ]; /** @@ -39,10 +40,9 @@ class Webhooks_model extends EA_Model { 'secretToken' => 'secret_token', 'isActive' => 'is_active', 'isSslVerified' => 'is_ssl_verified', - 'notes' => 'notes', + 'notes' => 'notes' ]; - /** * Save (insert or update) a webhook. * @@ -56,17 +56,13 @@ public function save(array $webhook): int { $this->validate($webhook); - if (empty($webhook['id'])) - { + if (empty($webhook['id'])) { return $this->insert($webhook); - } - else - { + } else { return $this->update($webhook); } } - /** * Validate the webhook data. * @@ -76,13 +72,8 @@ public function save(array $webhook): int */ public function validate(array $webhook) { - if ( - empty($webhook['name']) - || empty($webhook['url']) - || empty($webhook['actions']) - ) - { - throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($webhook, TRUE)); + if (empty($webhook['name']) || empty($webhook['url']) || empty($webhook['actions'])) { + throw new InvalidArgumentException('Not all required fields are provided: ' . print_r($webhook, true)); } } @@ -100,8 +91,7 @@ protected function insert(array $webhook): int $webhook['create_datetime'] = date('Y-m-d H:i:s'); $webhook['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->insert('webhooks', $webhook)) - { + if (!$this->db->insert('webhooks', $webhook)) { throw new RuntimeException('Could not insert webhook.'); } @@ -121,8 +111,7 @@ protected function update(array $webhook): int { $webhook['update_datetime'] = date('Y-m-d H:i:s'); - if ( ! $this->db->update('webhooks', $webhook, ['id' => $webhook['id']])) - { + if (!$this->db->update('webhooks', $webhook, ['id' => $webhook['id']])) { throw new RuntimeException('Could not update webhook.'); } @@ -152,8 +141,7 @@ public function find(int $webhook_id): array { $webhook = $this->db->get_where('webhooks', ['id' => $webhook_id])->row_array(); - if ( ! $webhook) - { + if (!$webhook) { throw new InvalidArgumentException('The provided webhook ID was not found in the database: ' . $webhook_id); } @@ -174,21 +162,18 @@ public function find(int $webhook_id): array */ public function value(int $webhook_id, string $field): mixed { - if (empty($field)) - { + if (empty($field)) { throw new InvalidArgumentException('The field argument is cannot be empty.'); } - if (empty($webhook_id)) - { + if (empty($webhook_id)) { throw new InvalidArgumentException('The webhook ID argument cannot be empty.'); } // Check whether the webhook exists. $query = $this->db->get_where('webhooks', ['id' => $webhook_id]); - if ( ! $query->num_rows()) - { + if (!$query->num_rows()) { throw new InvalidArgumentException('The provided webhook ID was not found in the database: ' . $webhook_id); } @@ -197,46 +182,13 @@ public function value(int $webhook_id, string $field): mixed $this->cast($webhook); - if ( ! array_key_exists($field, $webhook)) - { + if (!array_key_exists($field, $webhook)) { throw new InvalidArgumentException('The requested field was not found in the webhook data: ' . $field); } return $webhook[$field]; } - /** - * Get all webhooks that match the provided criteria. - * - * @param array|string|null $where Where conditions. - * @param int|null $limit Record limit. - * @param int|null $offset Record offset. - * @param string|null $order_by Order by. - * - * @return array Returns an array of webhooks. - */ - public function get(array|string $where = NULL, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array - { - if ($where !== NULL) - { - $this->db->where($where); - } - - if ($order_by !== NULL) - { - $this->db->order_by($order_by); - } - - $webhooks = $this->db->get('webhooks', $limit, $offset)->result_array(); - - foreach ($webhooks as &$webhook) - { - $this->cast($webhook); - } - - return $webhooks; - } - /** * Get the query builder interface, configured for use with the webhooks table. * @@ -257,10 +209,9 @@ public function query(): CI_DB_query_builder * * @return array Returns an array of webhooks. */ - public function search(string $keyword, int $limit = NULL, int $offset = NULL, string $order_by = NULL): array + public function search(string $keyword, int $limit = null, int $offset = null, string $order_by = null): array { - $webhooks = $this - ->db + $webhooks = $this->db ->select() ->from('webhooks') ->group_start() @@ -274,8 +225,40 @@ public function search(string $keyword, int $limit = NULL, int $offset = NULL, s ->get() ->result_array(); - foreach ($webhooks as &$webhook) - { + foreach ($webhooks as &$webhook) { + $this->cast($webhook); + } + + return $webhooks; + } + + /** + * Get all webhooks that match the provided criteria. + * + * @param array|string|null $where Where conditions. + * @param int|null $limit Record limit. + * @param int|null $offset Record offset. + * @param string|null $order_by Order by. + * + * @return array Returns an array of webhooks. + */ + public function get( + array|string $where = null, + int $limit = null, + int $offset = null, + string $order_by = null + ): array { + if ($where !== null) { + $this->db->where($where); + } + + if ($order_by !== null) { + $this->db->order_by($order_by); + } + + $webhooks = $this->db->get('webhooks', $limit, $offset)->result_array(); + + foreach ($webhooks as &$webhook) { $this->cast($webhook); } diff --git a/application/views/components/appointment_status_options.php b/application/views/components/appointment_status_options.php index 5f5df47492..cda81aed5b 100644 --- a/application/views/components/appointment_status_options.php +++ b/application/views/components/appointment_status_options.php @@ -15,8 +15,8 @@ - + - + diff --git a/application/views/components/backend_footer.php b/application/views/components/backend_footer.php index 2e4d5f770c..f7e8d734a1 100644 --- a/application/views/components/backend_footer.php +++ b/application/views/components/backend_footer.php @@ -1,24 +1,24 @@ - - + + - - + +
  • - > + >
  • - + - + - + - + @@ -175,9 +178,11 @@ class=" form-control" 'id="timezone" class="form-control required" disabled', 'grouped_timezones' => vars('grouped_timezones') - ]) ?> + ]); ?> + +
    - + - + @@ -209,4 +214,4 @@ class=" form-control" - + diff --git a/application/views/pages/general_settings.php b/application/views/pages/general_settings.php index 67c348b423..66eb6151ab 100755 --- a/application/views/pages/general_settings.php +++ b/application/views/pages/general_settings.php @@ -1,12 +1,12 @@ - + - +
    - +
    @@ -21,7 +21,7 @@ - +
    @@ -122,11 +122,11 @@ class="form-control">
    @@ -200,12 +200,12 @@ class="form-control">
    - + - + - + diff --git a/application/views/pages/google_analytics_settings.php b/application/views/pages/google_analytics_settings.php index f84bfbdd5d..ce47d6a411 100644 --- a/application/views/pages/google_analytics_settings.php +++ b/application/views/pages/google_analytics_settings.php @@ -1,11 +1,11 @@ - + - +
    - +
    @@ -26,7 +26,7 @@ - +
    @@ -52,12 +52,12 @@ class="form-control" data-field="google_analytics_code">
    - + - + - + diff --git a/application/views/pages/installation.php b/application/views/pages/installation.php index 49d27159d0..917e23eb72 100755 --- a/application/views/pages/installation.php +++ b/application/views/pages/installation.php @@ -25,14 +25,14 @@

    Welcome to the Easy!Appointments installation page.

    - This page will help you set the main settings of your Easy!Appointments installation. You will be able to - edit these settings and many more in the backend session of your system. Remember to use the - URL to connect to the backend section + This page will help you set the main settings of your Easy!Appointments installation. You will be able to + edit these settings and many more in the backend session of your system. Remember to use the + URL to connect to the backend section of Easy!Appointments. If you face any problems during the usage of Easy!Appointments you can always check the - Documentation and - Support Group for getting help. You may also + Documentation and + Support Group for getting help. You may also submit new issues on GitHub Issues in order to help our development process. @@ -113,7 +113,8 @@

    License

    - Easy!Appointments is licensed under the GPL-3.0 license. By using the code + Easy!Appointments is licensed under the GPL-3.0 license. By using the + code of Easy!Appointments in any way
    you agree with the terms described in the following url: https://www.gnu.org/licenses/gpl-3.0.en.html
    @@ -130,8 +131,8 @@ Powered by Easy!Appointments - - + + diff --git a/application/views/pages/integrations.php b/application/views/pages/integrations.php index b2f0030384..52d02e816c 100755 --- a/application/views/pages/integrations.php +++ b/application/views/pages/integrations.php @@ -1,11 +1,11 @@ - + - +
    - +

    @@ -55,7 +55,8 @@

    - + diff --git a/application/views/pages/legal_settings.php b/application/views/pages/legal_settings.php index c424bbc94e..91907a97c8 100755 --- a/application/views/pages/legal_settings.php +++ b/application/views/pages/legal_settings.php @@ -1,12 +1,12 @@ - + - + - + - + @@ -91,4 +96,4 @@ class="mb-3"> - + diff --git a/application/views/pages/login.php b/application/views/pages/login.php index c1bcda88ef..d54cff4a54 100644 --- a/application/views/pages/login.php +++ b/application/views/pages/login.php @@ -1,6 +1,6 @@ - + - +

    @@ -37,13 +37,13 @@
    - + - + - + diff --git a/application/views/pages/logout.php b/application/views/pages/logout.php index 4085a6e713..c2a15f81ff 100644 --- a/application/views/pages/logout.php +++ b/application/views/pages/logout.php @@ -1,6 +1,6 @@ - + - +

    @@ -15,13 +15,13 @@ - +
    - + diff --git a/application/views/pages/matomo_analytics_settings.php b/application/views/pages/matomo_analytics_settings.php index 9145df4d4b..1ad499502b 100644 --- a/application/views/pages/matomo_analytics_settings.php +++ b/application/views/pages/matomo_analytics_settings.php @@ -1,11 +1,11 @@ - + - +
    - +
    @@ -26,7 +26,7 @@ - +
    @@ -52,12 +52,12 @@
    - + - + - + diff --git a/application/views/pages/providers.php b/application/views/pages/providers.php index 09d57d744a..6fac8e4e52 100755 --- a/application/views/pages/providers.php +++ b/application/views/pages/providers.php @@ -1,6 +1,6 @@ - + - +
    @@ -19,7 +19,7 @@

    - +
    @@ -67,9 +67,9 @@ +// This form message is outside the details view, so that it can be +// visible when the user has working plan view active. +?> @@ -210,7 +210,7 @@ class="form-control required" maxlength="512" - +
    @@ -222,7 +222,7 @@ class="form-control required" maxlength="512" 'id="timezone" class="form-control required" disabled', 'grouped_timezones' => vars('grouped_timezones') - ]) ?> + ]); ?>
    @@ -270,7 +270,7 @@ class="form-control required" maxlength="512"

    - +
    - + - + @@ -371,7 +371,7 @@ class="form-control required" maxlength="512" - + diff --git a/application/views/pages/recovery.php b/application/views/pages/recovery.php index d73eaa887b..b1b397aa3a 100644 --- a/application/views/pages/recovery.php +++ b/application/views/pages/recovery.php @@ -1,6 +1,6 @@ - + - +

    @@ -21,7 +21,7 @@ - +
    - + - + @@ -51,4 +51,4 @@ - + diff --git a/application/views/pages/secretaries.php b/application/views/pages/secretaries.php index b1a2ebb380..73d8a1357a 100755 --- a/application/views/pages/secretaries.php +++ b/application/views/pages/secretaries.php @@ -1,6 +1,6 @@ - + - +
    @@ -186,7 +186,7 @@ - +
    @@ -198,7 +198,7 @@ 'id="timezone" class="form-control required" disabled', 'grouped_timezones' => vars('grouped_timezones') - ]) ?> + ]); ?>
    @@ -231,9 +231,9 @@
    - + - + @@ -242,5 +242,5 @@ - + diff --git a/application/views/pages/service_categories.php b/application/views/pages/service_categories.php index f699e8f744..def759e977 100644 --- a/application/views/pages/service_categories.php +++ b/application/views/pages/service_categories.php @@ -1,6 +1,6 @@ - + - +
    @@ -81,9 +81,9 @@
    - + - + @@ -91,4 +91,4 @@ - + diff --git a/application/views/pages/services.php b/application/views/pages/services.php index 4bbb98a7bd..b5f12e4825 100755 --- a/application/views/pages/services.php +++ b/application/views/pages/services.php @@ -1,6 +1,6 @@ - + - +
    @@ -131,7 +131,7 @@
    - 'id="color"']) ?> + 'id="color"']); ?>
    @@ -166,9 +166,9 @@
    - + - + @@ -177,4 +177,4 @@ - + diff --git a/application/views/pages/webhooks.php b/application/views/pages/webhooks.php index cd35d4f73c..558ff240ed 100755 --- a/application/views/pages/webhooks.php +++ b/application/views/pages/webhooks.php @@ -1,6 +1,6 @@ - + - +
    @@ -19,7 +19,7 @@

    - +
    @@ -95,7 +95,7 @@
    - +
    @@ -111,7 +111,7 @@
    - +
    @@ -120,7 +120,7 @@ - +
    @@ -141,9 +141,9 @@
    - + - + @@ -151,4 +151,4 @@ - + diff --git a/package-lock.json b/package-lock.json index 27bf88b487..fe8ff767a1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -25,6 +25,7 @@ "devDependencies": { "@babel/core": "^7.20.12", "@babel/preset-env": "^7.20.2", + "@prettier/plugin-php": "^0.21.0", "babel-preset-minify": "^0.5.2", "del": "^6.0.0", "fs-extra": "^11.1.0", @@ -37,7 +38,7 @@ "gulp-plumber": "^1.2.1", "gulp-rename": "^2.0.0", "gulp-sass": "^5.1.0", - "prettier": "^2.8.3", + "prettier": "^3.0.0", "sass": "^1.57.1", "zip-dir": "^2.0.0" }, @@ -1810,6 +1811,20 @@ "url": "https://opencollective.com/popperjs" } }, + "node_modules/@prettier/plugin-php": { + "version": "0.21.0", + "resolved": "https://registry.npmjs.org/@prettier/plugin-php/-/plugin-php-0.21.0.tgz", + "integrity": "sha512-vWC6HIUUfhvl/7F5IxVQ0ItGB/7ZY+jDlX7KsTqvfKMODW/zvzj8r1Ab4harS22+O3xxHykVVd5jvylmxMMctg==", + "dev": true, + "dependencies": { + "linguist-languages": "^7.21.0", + "mem": "^9.0.2", + "php-parser": "^3.1.5" + }, + "peerDependencies": { + "prettier": "^3.0.0" + } + }, "node_modules/abbrev": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", @@ -5168,6 +5183,12 @@ "node": ">=0.10.0" } }, + "node_modules/linguist-languages": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/linguist-languages/-/linguist-languages-7.27.0.tgz", + "integrity": "sha512-Wzx/22c5Jsv2ag+uKy+ITanGA5hzvBZngrNGDXLTC7ZjGM6FLCYGgomauTkxNJeP9of353OM0pWqngYA180xgw==", + "dev": true + }, "node_modules/load-json-file": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", @@ -5253,6 +5274,18 @@ "node": ">=0.10.0" } }, + "node_modules/map-age-cleaner": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/map-age-cleaner/-/map-age-cleaner-0.1.3.tgz", + "integrity": "sha512-bJzx6nMoP6PDLPBFmg7+xRKeFZvFboMrGlxmNj9ClvX53KrmvM5bXFXEWjbz4cz1AFn+jWJ9z/DJSz7hrs0w3w==", + "dev": true, + "dependencies": { + "p-defer": "^1.0.0" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/map-cache": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/map-cache/-/map-cache-0.2.2.tgz", @@ -5437,6 +5470,22 @@ "node": ">=0.10.0" } }, + "node_modules/mem": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/mem/-/mem-9.0.2.tgz", + "integrity": "sha512-F2t4YIv9XQUBHt6AOJ0y7lSmP1+cY7Fm1DRh9GClTGzKST7UWLMx6ly9WZdLH/G/ppM5RL4MlQfRT71ri9t19A==", + "dev": true, + "dependencies": { + "map-age-cleaner": "^0.1.3", + "mimic-fn": "^4.0.0" + }, + "engines": { + "node": ">=12.20" + }, + "funding": { + "url": "https://github.com/sindresorhus/mem?sponsor=1" + } + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -5504,6 +5553,18 @@ "node": ">=8.0" } }, + "node_modules/mimic-fn": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-4.0.0.tgz", + "integrity": "sha512-vqiC06CuhBTUdZH+RYl8sFrL096vA45Ok5ISO6sE/Mr1jRbGH4Csnhi8f3wKVl7x8mO4Au7Ir9D3Oyv1VYMFJw==", + "dev": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/minimatch": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", @@ -5948,6 +6009,15 @@ "node": ">=0.10.0" } }, + "node_modules/p-defer": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-defer/-/p-defer-1.0.0.tgz", + "integrity": "sha512-wB3wfAxZpk2AzOfUMJNL+d36xothRSyj8EXOa4f6GMqYDN9BJaaSISbsk+wS9abmnebVw95C2Kb5t85UmpCxuw==", + "dev": true, + "engines": { + "node": ">=4" + } + }, "node_modules/p-map": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", @@ -6085,6 +6155,12 @@ "node": ">=8" } }, + "node_modules/php-parser": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/php-parser/-/php-parser-3.1.5.tgz", + "integrity": "sha512-jEY2DcbgCm5aclzBdfW86GM6VEIWcSlhTBSHN1qhJguVePlYe28GhwS0yoeLYXpM2K8y6wzLwrbq814n2PHSoQ==", + "dev": true + }, "node_modules/picocolors": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz", @@ -6216,15 +6292,15 @@ } }, "node_modules/prettier": { - "version": "2.8.8", - "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.8.tgz", - "integrity": "sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.1.0.tgz", + "integrity": "sha512-TQLvXjq5IAibjh8EpBIkNKxO749UEWABoiIZehEPiY4GNpVdhaFKqSTu+QrlU6D2dPAfubRmtJTi4K4YkQ5eXw==", "dev": true, "bin": { - "prettier": "bin-prettier.js" + "prettier": "bin/prettier.cjs" }, "engines": { - "node": ">=10.13.0" + "node": ">=14" }, "funding": { "url": "https://github.com/prettier/prettier?sponsor=1" diff --git a/package.json b/package.json index 5dc19c82f1..ab0353fa20 100644 --- a/package.json +++ b/package.json @@ -42,6 +42,7 @@ "devDependencies": { "@babel/core": "^7.20.12", "@babel/preset-env": "^7.20.2", + "@prettier/plugin-php": "^0.21.0", "babel-preset-minify": "^0.5.2", "del": "^6.0.0", "fs-extra": "^11.1.0", @@ -54,7 +55,7 @@ "gulp-plumber": "^1.2.1", "gulp-rename": "^2.0.0", "gulp-sass": "^5.1.0", - "prettier": "^2.8.3", + "prettier": "^3.0.0", "sass": "^1.57.1", "zip-dir": "^2.0.0" },