From f7c09cb7ff84db1004a4fa83a70735475702023f Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Fri, 20 Jan 2017 21:12:19 +0100 Subject: Added exception handler --- src/Exceptions/Handler.php | 97 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 src/Exceptions/Handler.php (limited to 'src') diff --git a/src/Exceptions/Handler.php b/src/Exceptions/Handler.php new file mode 100644 index 00000000..a81900b6 --- /dev/null +++ b/src/Exceptions/Handler.php @@ -0,0 +1,97 @@ +environment = $environment; + + set_error_handler([$this, 'errorHandler']); + set_exception_handler([$this, 'exceptionHandler']); + } + + /** + * @param int $number + * @param string $string + * @param string $file + * @param int $line + * @param array $context + */ + public function errorHandler($number, $string, $file, $line, $context) + { + $this->handle('error', $number, $string, $file, $line, $context); + } + + /** + * @param Exception $e + */ + public function exceptionHandler(Exception $e) + { + $this->handle( + 'exception', + $e->getCode(), + get_class($e) . ': ' . $e->getMessage(), + $e->getFile(), + $e->getLine() + ); + } + + /** + * @param string $type + * @param int $number + * @param string $string + * @param string $file + * @param int $line + * @param array $context + */ + protected function handle($type, $number, $string, $file, $line, $context = []) + { + error_log(sprintf('%s: Number: %s, String: %s, File: %s:%u, Context: %s', + $type, + $number, + $string, + $file, + $line, + json_encode($context) + )); + + if ($this->environment == self::ENV_DEVELOPMENT || $this->environment == self::ENV_DEBUGGING) { + echo '
';
+            echo sprintf('%s: (%s)' . PHP_EOL, ucfirst($type), $number);
+            var_export([
+                'string'  => $string,
+                'file'    => $file . ':' . $line,
+                'context' => ($this->environment == self::ENV_DEBUGGING ? $context : null),
+            ]);
+            echo '
'; + die(); + } + + echo 'An unexpected error occurred, a team of untrained monkeys has been dispatched to deal with it.'; + die(); + } + + /** + * @param string $environment + */ + public function setEnvironment($environment) + { + $this->environment = $environment; + } +} -- cgit v1.2.3-54-g00ecf From 9a3ad8883403949a59e8935497a548ec536f1d40 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Sat, 21 Jan 2017 13:58:53 +0100 Subject: Changed from mysqli to PDO, some refactorings, faster sql queries --- config/config.default.php | 4 +- includes/controller/shift_entries_controller.php | 80 ++++-- includes/controller/shifts_controller.php | 22 +- includes/controller/shifttypes_controller.php | 11 +- includes/controller/user_angeltypes_controller.php | 3 - includes/controller/users_controller.php | 28 +- includes/engelsystem_provider.php | 13 +- includes/model/AngelType_model.php | 164 +++++++----- includes/model/EventConfig_model.php | 72 +++-- includes/model/LogEntries_model.php | 43 +-- includes/model/Message_model.php | 48 ++-- includes/model/NeededAngelTypes_model.php | 65 +++-- includes/model/Room_model.php | 60 +++-- includes/model/ShiftEntry_model.php | 200 +++++++++----- includes/model/ShiftTypes_model.php | 65 +++-- includes/model/Shifts_model.php | 251 ++++++++++------- includes/model/UserAngelTypes_model.php | 177 +++++++----- includes/model/UserDriverLicenses_model.php | 87 ++++-- includes/model/UserGroups_model.php | 20 +- includes/model/User_model.php | 296 ++++++++++++++------- includes/mysqli_provider.php | 250 ----------------- includes/pages/admin_active.php | 102 ++++--- includes/pages/admin_arrive.php | 18 +- includes/pages/admin_free.php | 50 ++-- includes/pages/admin_groups.php | 69 ++--- includes/pages/admin_import.php | 14 +- includes/pages/admin_news.php | 35 ++- includes/pages/admin_questions.php | 39 ++- includes/pages/admin_rooms.php | 41 ++- includes/pages/admin_shifts.php | 45 +++- includes/pages/admin_user.php | 144 ++++++---- includes/pages/guest_login.php | 95 ++++--- includes/pages/guest_stats.php | 12 +- includes/pages/user_atom.php | 8 +- includes/pages/user_messages.php | 44 ++- includes/pages/user_myshifts.php | 67 +++-- includes/pages/user_news.php | 81 +++--- includes/pages/user_questions.php | 34 ++- includes/pages/user_settings.php | 28 +- includes/pages/user_shifts.php | 67 ++--- includes/sys_auth.php | 76 +++--- includes/sys_log.php | 22 -- includes/sys_page.php | 8 +- includes/view/User_view.php | 21 +- src/Database/Db.php | 170 ++++++++++++ 45 files changed, 1948 insertions(+), 1301 deletions(-) delete mode 100644 includes/mysqli_provider.php create mode 100644 src/Database/Db.php (limited to 'src') diff --git a/config/config.default.php b/config/config.default.php index 5287b51b..bcfcc89c 100644 --- a/config/config.default.php +++ b/config/config.default.php @@ -1,6 +1,8 @@ 0 + && count(DB::select( + 'SELECT `id` FROM `AngelTypes` WHERE `id`=? LIMIT 1', + [$_REQUEST['angeltype_id']] + )) > 0 ) { $selected_type_id = $_REQUEST['angeltype_id']; } } - if (sql_num_query("SELECT * FROM `ShiftEntry` WHERE `SID`='" . sql_escape($shift['SID']) . "' AND `UID` = '" . sql_escape($user_id) . "'")) { + if (count(DB::select( + 'SELECT `id` FROM `ShiftEntry` WHERE `SID`= ? AND `UID` = ?', + [$shift['SID'], $user_id])) + ) { return error("This angel does already have an entry for this shift.", true); } - $freeloaded = $shift['freeloaded']; - $freeload_comment = $shift['freeload_comment']; + $freeloaded = isset($shift['freeloaded']) ? $shift['freeloaded'] : false; + $freeload_comment = isset($shift['freeload_comment']) ? $shift['freeload_comment'] : ''; if (in_array("user_shifts_admin", $privileges)) { $freeloaded = isset($_REQUEST['freeloaded']); $freeload_comment = strip_request_item_nl('freeload_comment'); @@ -132,27 +143,40 @@ function shift_entry_add_controller() if ( $type['restricted'] == 0 - && sql_num_query(" - SELECT * FROM `UserAngelTypes` + && count(DB::select(' + SELECT `id` FROM `UserAngelTypes` INNER JOIN `AngelTypes` ON `AngelTypes`.`id` = `UserAngelTypes`.`angeltype_id` - WHERE `angeltype_id` = '" . sql_escape($selected_type_id) . "' - AND `user_id` = '" . sql_escape($user_id) . "' - ") == 0 + WHERE `angeltype_id` = ? + AND `user_id` = ? + ', [$selected_type_id, $user_id])) == 0 ) { - sql_query("INSERT INTO `UserAngelTypes` (`user_id`, `angeltype_id`) VALUES ('" . sql_escape($user_id) . "', '" . sql_escape($selected_type_id) . "')"); + DB::insert( + 'INSERT INTO `UserAngelTypes` (`user_id`, `angeltype_id`) VALUES (?, ?)', + [$user_id, $selected_type_id] + ); } $user_source = User($user_id); - engelsystem_log('User ' . User_Nick_render($user_source) . ' signed up for shift ' . $shift['name'] . ' from ' . date('Y-m-d H:i', - $shift['start']) . ' to ' . date('Y-m-d H:i', $shift['end'])); + engelsystem_log( + 'User ' . User_Nick_render($user_source) + . ' signed up for shift ' . $shift['name'] + . ' from ' . date('Y-m-d H:i', $shift['start']) + . ' to ' . date('Y-m-d H:i', $shift['end']) + ); success(_('You are subscribed. Thank you!') . ' ' . _('My shifts') . ' »'); redirect(shift_link($shift)); } $angeltype_select = ''; if (in_array('user_shifts_admin', $privileges)) { - $users = sql_select(' - SELECT *, (SELECT count(*) FROM `ShiftEntry` WHERE `freeloaded`=1 AND `ShiftEntry`.`UID`=`User`.`UID`) AS `freeloaded` + $users = DB::select(' + SELECT *, + ( + SELECT count(*) + FROM `ShiftEntry` + WHERE `freeloaded`=1 + AND `ShiftEntry`.`UID`=`User`.`UID` + ) AS `freeloaded` FROM `User` ORDER BY `Nick` '); @@ -162,7 +186,7 @@ function shift_entry_add_controller() } $user_text = html_select_key('user_id', 'user_id', $users_select, $user['UID']); - $angeltypes_source = sql_select('SELECT * FROM `AngelTypes` ORDER BY `name`'); + $angeltypes_source = DB::select('SELECT `id`, `name` FROM `AngelTypes` ORDER BY `name`'); $angeltypes = []; foreach ($angeltypes_source as $angeltype) { $angeltypes[$angeltype['id']] = $angeltype['name']; @@ -218,7 +242,7 @@ function shift_entry_delete_controller() } $entry_id = $_REQUEST['entry_id']; - $shift_entry_source = sql_select(" + $shift_entry_source = DB::select(' SELECT `User`.`Nick`, `ShiftEntry`.`Comment`, @@ -234,9 +258,11 @@ function shift_entry_delete_controller() JOIN `Shifts` ON (`ShiftEntry`.`SID` = `Shifts`.`SID`) JOIN `ShiftTypes` ON (`ShiftTypes`.`id` = `Shifts`.`shifttype_id`) JOIN `Room` ON (`Shifts`.`RID` = `Room`.`RID`) - WHERE `ShiftEntry`.`id`='" . sql_escape($entry_id) . "'"); + WHERE `ShiftEntry`.`id`=?', + [$entry_id] + ); if (count($shift_entry_source) > 0) { - $shift_entry_source = $shift_entry_source[0]; + $shift_entry_source = array_shift($shift_entry_source); if (!in_array('user_shifts_admin', $privileges) && (!in_array('shiftentry_edit_angeltype_supporter', $privileges) || !User_is_AngelType_supporter($user, AngelType($shift_entry_source['angeltype_id']))) diff --git a/includes/controller/shifts_controller.php b/includes/controller/shifts_controller.php index 56ee1452..989f1a69 100644 --- a/includes/controller/shifts_controller.php +++ b/includes/controller/shifts_controller.php @@ -7,7 +7,11 @@ use Engelsystem\ShiftSignupState; */ function shift_link($shift) { - return page_link_to('shifts') . '&action=view&shift_id=' . $shift['SID']; + $link = page_link_to('shifts') . '&action=view'; + if (isset($shift['SID'])) { + $link .= '&shift_id=' . $shift['SID']; + } + return $link; } /** @@ -253,8 +257,15 @@ function shift_controller() $needed_angeltype = NeededAngeltype_by_Shift_and_Angeltype($shift, $angeltype); $shift_entries = ShiftEntries_by_shift_and_angeltype($shift['SID'], $angeltype['id']); - $angeltype_signup_state = Shift_signup_allowed($user, $shift, $angeltype, null, $user_shifts, $needed_angeltype, - $shift_entries); + $angeltype_signup_state = Shift_signup_allowed( + $user, + $shift, + $angeltype, + null, + $user_shifts, + $needed_angeltype, + $shift_entries + ); if ($shift_signup_state == null) { $shift_signup_state = $angeltype_signup_state; } else { @@ -304,11 +315,8 @@ function shift_next_controller() } $upcoming_shifts = ShiftEntries_upcoming_for_user($user); - if ($upcoming_shifts === false) { - return false; - } - if (count($upcoming_shifts) > 0) { + if (empty($upcoming_shifts)) { redirect(shift_link($upcoming_shifts[0])); } diff --git a/includes/controller/shifttypes_controller.php b/includes/controller/shifttypes_controller.php index 55bea389..e6ba716f 100644 --- a/includes/controller/shifttypes_controller.php +++ b/includes/controller/shifttypes_controller.php @@ -21,9 +21,6 @@ function shifttype_delete_controller() } $shifttype = ShiftType($_REQUEST['shifttype_id']); - if ($shifttype === false) { - engelsystem_error('Unable to load shifttype.'); - } if ($shifttype == null) { redirect(page_link_to('shifttypes')); @@ -31,7 +28,7 @@ function shifttype_delete_controller() if (isset($_REQUEST['confirmed'])) { $result = ShiftType_delete($shifttype['id']); - if ($result === false) { + if (empty($result)) { engelsystem_error('Unable to delete shifttype.'); } @@ -62,9 +59,6 @@ function shifttype_edit_controller() if (isset($_REQUEST['shifttype_id'])) { $shifttype = ShiftType($_REQUEST['shifttype_id']); - if ($shifttype === false) { - engelsystem_error('Unable to load shifttype.'); - } if ($shifttype == null) { error(_('Shifttype not found.')); redirect(page_link_to('shifttypes')); @@ -130,9 +124,6 @@ function shifttype_controller() redirect(page_link_to('shifttypes')); } $shifttype = ShiftType($_REQUEST['shifttype_id']); - if ($shifttype === false) { - engelsystem_error('Unable to load shifttype.'); - } if ($shifttype == null) { redirect(page_link_to('shifttypes')); } diff --git a/includes/controller/user_angeltypes_controller.php b/includes/controller/user_angeltypes_controller.php index 0855e4c9..cf2c0a3c 100644 --- a/includes/controller/user_angeltypes_controller.php +++ b/includes/controller/user_angeltypes_controller.php @@ -153,9 +153,6 @@ function user_angeltype_confirm_controller() if (isset($_REQUEST['confirmed'])) { $result = UserAngelType_confirm($user_angeltype['id'], $user); - if ($result === false) { - engelsystem_error('Unable to confirm user angeltype.'); - } engelsystem_log(sprintf( '%s confirmed for angeltype %s', diff --git a/includes/controller/users_controller.php b/includes/controller/users_controller.php index 72bddd14..b80fdb4d 100644 --- a/includes/controller/users_controller.php +++ b/includes/controller/users_controller.php @@ -1,4 +1,6 @@ setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + session_start(); gettext_init(); -sql_connect($config['host'], $config['user'], $config['pw'], $config['db']); - load_auth(); diff --git a/includes/model/AngelType_model.php b/includes/model/AngelType_model.php index c3270863..411c69ea 100644 --- a/includes/model/AngelType_model.php +++ b/includes/model/AngelType_model.php @@ -1,4 +1,6 @@ lastInsertId(); engelsystem_log( - 'Created angeltype: ' . $angeltype['name'] . ($angeltype['restricted'] ? ', restricted' : '') - . ($angeltype['requires_driver_license'] ? ', requires driver license' : '')); + 'Created angeltype: ' . $angeltype['name'] + . ($angeltype['restricted'] ? ', restricted' : '') + . ($angeltype['requires_driver_license'] ? ', requires driver license' : '') + ); return $angeltype; } @@ -167,19 +199,20 @@ function AngelType_validate_name($name, $angeltype) return new ValidationResult(false, ''); } if ($angeltype != null && isset($angeltype['id'])) { - $valid = sql_num_query(" - SELECT * - FROM `AngelTypes` - WHERE `name`='" . sql_escape($name) . "' - AND NOT `id`='" . sql_escape($angeltype['id']) . "' - LIMIT 1") == 0; + $valid = (count(DB::select(' + SELECT `id` + FROM `AngelTypes` + WHERE `name`=? + AND NOT `id`=? + LIMIT 1 + ', [$name, $angeltype['id']])) == 0); return new ValidationResult($valid, $name); } - $valid = sql_num_query(" + $valid = (count(DB::select(' SELECT `id` FROM `AngelTypes` - WHERE `name`='" . sql_escape($name) . "' - LIMIT 1") == 0; + WHERE `name`=? + LIMIT 1', [$name])) == 0); return new ValidationResult($valid, $name); } @@ -191,16 +224,17 @@ function AngelType_validate_name($name, $angeltype) */ function AngelTypes_with_user($user) { - $result = sql_select(" + $result = DB::select(' SELECT `AngelTypes`.*, `UserAngelTypes`.`id` AS `user_angeltype_id`, `UserAngelTypes`.`confirm_user_id`, `UserAngelTypes`.`supporter` FROM `AngelTypes` LEFT JOIN `UserAngelTypes` ON `AngelTypes`.`id`=`UserAngelTypes`.`angeltype_id` - AND `UserAngelTypes`.`user_id`=" . $user['UID'] . " - ORDER BY `name`"); - if ($result === false) { + AND `UserAngelTypes`.`user_id` = ? + ORDER BY `name`', [$user['UID']]); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load angeltypes.'); } return $result; @@ -213,11 +247,12 @@ function AngelTypes_with_user($user) */ function AngelTypes() { - $result = sql_select(" + $result = DB::select(' SELECT * FROM `AngelTypes` - ORDER BY `name`"); - if ($result === false) { + ORDER BY `name`'); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load angeltypes.'); } return $result; @@ -230,8 +265,9 @@ function AngelTypes() */ function AngelType_ids() { - $result = sql_select("SELECT `id` FROM `AngelTypes`"); - if ($result === false) { + $result = DB::select('SELECT `id` FROM `AngelTypes`'); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load angeltypes.'); } return select_array($result, 'id', 'id'); @@ -241,16 +277,22 @@ function AngelType_ids() * Returns angelType by id. * * @param int $angeltype_id angelType ID - * @return array + * @return array|null */ function AngelType($angeltype_id) { - $angelType_source = sql_select("SELECT * FROM `AngelTypes` WHERE `id`='" . sql_escape($angeltype_id) . "'"); - if ($angelType_source === false) { + $angelType_source = DB::select( + 'SELECT * FROM `AngelTypes` WHERE `id`=?', + [$angeltype_id] + ); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load angeltype.'); } - if (count($angelType_source) > 0) { - return $angelType_source[0]; + + if (empty($angelType_source)) { + return null; } - return null; + + return array_shift($angelType_source); } diff --git a/includes/model/EventConfig_model.php b/includes/model/EventConfig_model.php index 330863a9..773ee2e0 100644 --- a/includes/model/EventConfig_model.php +++ b/includes/model/EventConfig_model.php @@ -1,21 +1,25 @@ errorCode() != '00000') { engelsystem_error('Unable to load event config.'); - return false; + return null; } - if (count($event_config) > 0) { - return $event_config[0]; + + if (empty($event_config)) { + return null; } - return null; + + return array_shift($event_config); } /** @@ -27,7 +31,7 @@ function EventConfig() * @param int $event_end_date * @param int $teardown_end_date * @param string $event_welcome_msg - * @return mysqli_result|false + * @return bool */ function EventConfig_update( $event_name, @@ -38,20 +42,44 @@ function EventConfig_update( $event_welcome_msg ) { if (EventConfig() == null) { - return sql_query("INSERT INTO `EventConfig` SET - `event_name`=" . sql_null($event_name) . ", - `buildup_start_date`=" . sql_null($buildup_start_date) . ", - `event_start_date`=" . sql_null($event_start_date) . ", - `event_end_date`=" . sql_null($event_end_date) . ", - `teardown_end_date`=" . sql_null($teardown_end_date) . ", - `event_welcome_msg`=" . sql_null($event_welcome_msg)); + return DB::insert(' + INSERT INTO `EventConfig` ( + `event_name`, + `buildup_start_date`, + `event_start_date`, + `event_end_date`, + `teardown_end_date`, + `event_welcome_msg` + ) + VALUES (?, ?, ?, ?, ?, ?) + ', + [ + $event_name, + $buildup_start_date, + $event_start_date, + $event_end_date, + $teardown_end_date, + $event_welcome_msg + ] + ); } - return sql_query("UPDATE `EventConfig` SET - `event_name`=" . sql_null($event_name) . ", - `buildup_start_date`=" . sql_null($buildup_start_date) . ", - `event_start_date`=" . sql_null($event_start_date) . ", - `event_end_date`=" . sql_null($event_end_date) . ", - `teardown_end_date`=" . sql_null($teardown_end_date) . ", - `event_welcome_msg`=" . sql_null($event_welcome_msg)); + return (bool)DB::update(' + UPDATE `EventConfig` SET + `event_name` = ?, + `buildup_start_date` = ?, + `event_start_date` = ?, + `event_end_date` = ?, + `teardown_end_date` = ?, + `event_welcome_msg` = ? + ', + [ + $event_name, + $buildup_start_date, + $event_start_date, + $event_end_date, + $teardown_end_date, + $event_welcome_msg, + ] + ); } diff --git a/includes/model/LogEntries_model.php b/includes/model/LogEntries_model.php index 920b1945..0e11bf8e 100644 --- a/includes/model/LogEntries_model.php +++ b/includes/model/LogEntries_model.php @@ -1,59 +1,62 @@ 0) { - return $message_source[0]; + $message_source = DB::select('SELECT * FROM `Messages` WHERE `id`=? LIMIT 1', [$message_id]); + if (empty($message_source)) { + return null; } - return null; + return array_shift($message_source); } /** @@ -46,22 +45,25 @@ function Message_send($receiver_user_id, $text) if ( ($text != '' && is_numeric($receiver_user_id)) - && (sql_num_query(" - SELECT * + && count(DB::select(' + SELECT `UID` FROM `User` - WHERE `UID`='" . sql_escape($receiver_user_id) . "' - AND NOT `UID`='" . sql_escape($user['UID']) . "' + WHERE `UID` = ? + AND NOT `UID` = ? LIMIT 1 - ") > 0) + ', [$receiver_user_id, $user['UID']])) > 0 ) { - sql_query(" - INSERT INTO `Messages` - SET `Datum`='" . sql_escape(time()) . "', - `SUID`='" . sql_escape($user['UID']) . "', - `RUID`='" . sql_escape($receiver_user_id) . "', - `Text`='" . sql_escape($text) . "' - "); - return true; + return DB::insert(' + INSERT INTO `Messages` (`Datum`, `SUID`, `RUID`, `Text`) + VALUES(?, ?, ?, ?) + ', + [ + time(), + $user['UID'], + $receiver_user_id, + $text + ] + ); } return false; diff --git a/includes/model/NeededAngelTypes_model.php b/includes/model/NeededAngelTypes_model.php index f65efc41..97b085f0 100644 --- a/includes/model/NeededAngelTypes_model.php +++ b/includes/model/NeededAngelTypes_model.php @@ -1,5 +1,7 @@ lastInsertId(); } /** * Deletes all needed angel types from given shift. * * @param int $shift_id id of the shift - * @return mysqli_result|false + * @return int count of affected rows */ function NeededAngelTypes_delete_by_shift($shift_id) { - return sql_query("DELETE FROM `NeededAngelTypes` WHERE `shift_id`='" . sql_escape($shift_id) . "'"); + return (int)DB::delete('DELETE FROM `NeededAngelTypes` WHERE `shift_id` = ?', [$shift_id]); } /** * Deletes all needed angel types from given room. * * @param int $room_id id of the room - * @return mysqli_result|false + * @return int count of affected rows */ function NeededAngelTypes_delete_by_room($room_id) { - return sql_query("DELETE FROM `NeededAngelTypes` WHERE `room_id`='" . sql_escape($room_id) . "'"); + return (int)DB::delete( + 'DELETE FROM `NeededAngelTypes` WHERE `room_id` = ?', + [$room_id] + ); } /** @@ -61,30 +67,31 @@ function NeededAngelTypes_delete_by_room($room_id) */ function NeededAngelTypes_by_shift($shiftId) { - $needed_angeltypes_source = sql_select(" + $needed_angeltypes_source = DB::select(' SELECT `NeededAngelTypes`.*, `AngelTypes`.`id`, `AngelTypes`.`name`, `AngelTypes`.`restricted`, `AngelTypes`.`no_self_signup` FROM `NeededAngelTypes` JOIN `AngelTypes` ON `AngelTypes`.`id` = `NeededAngelTypes`.`angel_type_id` - WHERE `shift_id`='" . sql_escape($shiftId) . "' + WHERE `shift_id` = ? AND `count` > 0 - ORDER BY `room_id` DESC - "); - if ($needed_angeltypes_source === false) { + ORDER BY `room_id` DESC', + [$shiftId] + ); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load needed angeltypes.'); } // Use settings from room if (count($needed_angeltypes_source) == 0) { - $needed_angeltypes_source = sql_select(" + $needed_angeltypes_source = DB::select(' SELECT `NeededAngelTypes`.*, `AngelTypes`.`name`, `AngelTypes`.`restricted` FROM `NeededAngelTypes` JOIN `AngelTypes` ON `AngelTypes`.`id` = `NeededAngelTypes`.`angel_type_id` JOIN `Shifts` ON `Shifts`.`RID` = `NeededAngelTypes`.`room_id` - WHERE `Shifts`.`SID`='" . sql_escape($shiftId) . "' + WHERE `Shifts`.`SID` = ? AND `count` > 0 ORDER BY `room_id` DESC - "); - if ($needed_angeltypes_source === false) { + ', [$shiftId]); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load needed angeltypes.'); } } diff --git a/includes/model/Room_model.php b/includes/model/Room_model.php index 3eb9f452..c8399bc4 100644 --- a/includes/model/Room_model.php +++ b/includes/model/Room_model.php @@ -1,53 +1,56 @@ lastInsertId(); } /** @@ -59,18 +62,21 @@ function Room_create($name, $from_frab, $public, $number = null) */ function Room($room_id, $show_only = true) { - $room_source = sql_select(" + $room_source = DB::select(' SELECT * FROM `Room` - WHERE `RID`='" . sql_escape($room_id) . "' - " . ($show_only ? "AND `show` = 'Y'" : '') + WHERE `RID` = ? + ' . ($show_only ? 'AND `show` = \'Y\'' : ''), + [$room_id] ); - if ($room_source === false) { + if (DB::getStm()->errorCode() != '00000') { return false; } - if (count($room_source) > 0) { - return $room_source[0]; + + if (empty($room_source)) { + return null; } - return null; + + return array_shift($room_source); } diff --git a/includes/model/ShiftEntry_model.php b/includes/model/ShiftEntry_model.php index acdb4160..87e186ac 100644 --- a/includes/model/ShiftEntry_model.php +++ b/includes/model/ShiftEntry_model.php @@ -1,5 +1,7 @@ errorCode() == '00000'); } /** @@ -97,11 +132,11 @@ function ShiftEntry_update($shift_entry) */ function ShiftEntry($shift_entry_id) { - $shift_entry = sql_select("SELECT * FROM `ShiftEntry` WHERE `id`='" . sql_escape($shift_entry_id) . "'"); - if ($shift_entry === false) { + $shift_entry = DB::select('SELECT * FROM `ShiftEntry` WHERE `id` = ?', [$shift_entry_id]); + if (DB::getStm()->errorCode() != '00000') { return false; } - if (count($shift_entry) == 0) { + if (empty($shift_entry)) { return null; } return $shift_entry[0]; @@ -111,52 +146,62 @@ function ShiftEntry($shift_entry_id) * Delete a shift entry. * * @param int $shift_entry_id - * @return mysqli_result|false + * @return bool */ function ShiftEntry_delete($shift_entry_id) { $shift_entry = ShiftEntry($shift_entry_id); mail_shift_removed(User($shift_entry['UID']), Shift($shift_entry['SID'])); - return sql_query("DELETE FROM `ShiftEntry` WHERE `id`='" . sql_escape($shift_entry_id) . "'"); + return DB::delete('DELETE FROM `ShiftEntry` WHERE `id` = ?', [$shift_entry_id]); } /** * Returns next (or current) shifts of given user. * * @param array $user - * @return array|false + * @return array */ function ShiftEntries_upcoming_for_user($user) { - return sql_select(" - SELECT * - FROM `ShiftEntry` - JOIN `Shifts` ON (`Shifts`.`SID` = `ShiftEntry`.`SID`) - JOIN `ShiftTypes` ON `ShiftTypes`.`id` = `Shifts`.`shifttype_id` - WHERE `ShiftEntry`.`UID`=" . sql_escape($user['UID']) . " - AND `Shifts`.`end` > " . sql_escape(time()) . " - ORDER BY `Shifts`.`end` - "); + return DB::select(' + SELECT * + FROM `ShiftEntry` + JOIN `Shifts` ON (`Shifts`.`SID` = `ShiftEntry`.`SID`) + JOIN `ShiftTypes` ON `ShiftTypes`.`id` = `Shifts`.`shifttype_id` + WHERE `ShiftEntry`.`UID` = ? + AND `Shifts`.`end` > ? + ORDER BY `Shifts`.`end` + ', + [ + $user['UID'], + time(), + ] + ); } /** * Returns shifts completed by the given user. * * @param array $user - * @return array|false + * @return array */ function ShiftEntries_finished_by_user($user) { - return sql_select(" - SELECT * - FROM `ShiftEntry` - JOIN `Shifts` ON (`Shifts`.`SID` = `ShiftEntry`.`SID`) - JOIN `ShiftTypes` ON `ShiftTypes`.`id` = `Shifts`.`shifttype_id` - WHERE `ShiftEntry`.`UID`=" . sql_escape($user['UID']) . " - AND `Shifts`.`end` < " . sql_escape(time()) . " - AND `ShiftEntry`.`freeloaded` = 0 - ORDER BY `Shifts`.`end` - "); + return DB::select(' + SELECT * + FROM `ShiftEntry` + JOIN `Shifts` ON (`Shifts`.`SID` = `ShiftEntry`.`SID`) + JOIN `ShiftTypes` ON `ShiftTypes`.`id` = `Shifts`.`shifttype_id` + WHERE `ShiftEntry`.`UID` = ? + AND `Shifts`.`end` < ? + AND `ShiftEntry`.`freeloaded` = 0 + ORDER BY `Shifts`.`end` + ', + [ + $user['UID'], + time(), + ] + ); } /** @@ -164,17 +209,22 @@ function ShiftEntries_finished_by_user($user) * * @param int $shift_id * @param int $angeltype_id - * @return array|false + * @return array */ function ShiftEntries_by_shift_and_angeltype($shift_id, $angeltype_id) { - $result = sql_select(" - SELECT * - FROM `ShiftEntry` - WHERE `SID`=" . sql_escape($shift_id) . " - AND `TID`=" . sql_escape($angeltype_id) . " - "); - if ($result === false) { + $result = DB::select(' + SELECT * + FROM `ShiftEntry` + WHERE `SID` = ? + AND `TID` = ? + ', + [ + $shift_id, + $angeltype_id, + ] + ); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load shift entries.'); } return $result; @@ -184,12 +234,18 @@ function ShiftEntries_by_shift_and_angeltype($shift_id, $angeltype_id) * Returns all freeloaded shifts for given user. * * @param array $user - * @return array|false + * @return array */ function ShiftEntries_freeloaded_by_user($user) { - return sql_select("SELECT * - FROM `ShiftEntry` - WHERE `freeloaded` = 1 - AND `UID`=" . sql_escape($user['UID'])); + return DB::select(' + SELECT * + FROM `ShiftEntry` + WHERE `freeloaded` = 1 + AND `UID` = ? + ', + [ + $user['UID'] + ] + ); } diff --git a/includes/model/ShiftTypes_model.php b/includes/model/ShiftTypes_model.php index 03a98bd8..4919875b 100644 --- a/includes/model/ShiftTypes_model.php +++ b/includes/model/ShiftTypes_model.php @@ -1,14 +1,16 @@ errorCode() == '00000'; } /** @@ -41,16 +52,22 @@ function ShiftType_update($shifttype_id, $name, $angeltype_id, $description) */ function ShiftType_create($name, $angeltype_id, $description) { - $result = sql_query(" - INSERT INTO `ShiftTypes` SET - `name`='" . sql_escape($name) . "', - `angeltype_id`=" . sql_null($angeltype_id) . ", - `description`='" . sql_escape($description) . "' - "); + $result = DB::insert(' + INSERT INTO `ShiftTypes` (`name`, `angeltype_id`, `description`) + VALUES(?, ?, ?) + ', + [ + $name, + $angeltype_id, + $description + ] + ); + if ($result === false) { return false; } - return sql_id(); + + return DB::getPdo()->lastInsertId(); } /** @@ -61,14 +78,14 @@ function ShiftType_create($name, $angeltype_id, $description) */ function ShiftType($shifttype_id) { - $shifttype = sql_select("SELECT * FROM `ShiftTypes` WHERE `id`='" . sql_escape($shifttype_id) . "'"); - if ($shifttype === false) { + $shifttype = DB::select('SELECT * FROM `ShiftTypes` WHERE `id`=?', [$shifttype_id]); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load shift type.'); } - if ($shifttype == null) { + if (empty($shifttype)) { return null; } - return $shifttype[0]; + return array_shift($shifttype); } /** @@ -78,5 +95,11 @@ function ShiftType($shifttype_id) */ function ShiftTypes() { - return sql_select('SELECT * FROM `ShiftTypes` ORDER BY `name`'); + $result = DB::select('SELECT * FROM `ShiftTypes` ORDER BY `name`'); + + if (DB::getStm()->errorCode() != '00000') { + return false; + } + + return $result; } diff --git a/includes/model/Shifts_model.php b/includes/model/Shifts_model.php index 462b2f65..3f199803 100644 --- a/includes/model/Shifts_model.php +++ b/includes/model/Shifts_model.php @@ -1,4 +1,6 @@ errorCode() != '00000') { engelsystem_error('Unable to load shifts by filter.'); } return $result; @@ -56,11 +59,12 @@ function Shifts_by_ShiftsFilter(ShiftsFilter $shiftsFilter) /** * @param ShiftsFilter $shiftsFilter - * @return array + * @return array[] */ function NeededAngeltypes_by_ShiftsFilter(ShiftsFilter $shiftsFilter) { - $SQL = " + //@TODO + $sql = " SELECT `NeededAngelTypes`.*, `Shifts`.`SID`, @@ -90,8 +94,8 @@ function NeededAngeltypes_by_ShiftsFilter(ShiftsFilter $shiftsFilter) WHERE `Shifts`.`RID` IN (" . implode(',', $shiftsFilter->getRooms()) . ") AND `start` BETWEEN " . $shiftsFilter->getStartTime() . " AND " . $shiftsFilter->getEndTime() . " AND NOT `Shifts`.`PSID` IS NULL"; - $result = sql_select($SQL); - if ($result === false) { + $result = DB::select($sql); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load needed angeltypes by filter.'); } return $result; @@ -104,40 +108,48 @@ function NeededAngeltypes_by_ShiftsFilter(ShiftsFilter $shiftsFilter) */ function NeededAngeltype_by_Shift_and_Angeltype($shift, $angeltype) { - $result = sql_select(" - SELECT - `NeededAngelTypes`.*, - `Shifts`.`SID`, - `AngelTypes`.`id`, - `AngelTypes`.`name`, - `AngelTypes`.`restricted`, - `AngelTypes`.`no_self_signup` - FROM `Shifts` - JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`shift_id`=`Shifts`.`SID` - JOIN `AngelTypes` ON `AngelTypes`.`id`= `NeededAngelTypes`.`angel_type_id` - WHERE `Shifts`.`SID`=" . sql_escape($shift['SID']) . " - AND `AngelTypes`.`id`=" . sql_escape($angeltype['id']) . " - AND `Shifts`.`PSID` IS NULL - - UNION - - SELECT - `NeededAngelTypes`.*, - `Shifts`.`SID`, - `AngelTypes`.`id`, - `AngelTypes`.`name`, - `AngelTypes`.`restricted`, - `AngelTypes`.`no_self_signup` - FROM `Shifts` - JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`room_id`=`Shifts`.`RID` - JOIN `AngelTypes` ON `AngelTypes`.`id`= `NeededAngelTypes`.`angel_type_id` - WHERE `Shifts`.`SID`=" . sql_escape($shift['SID']) . " - AND `AngelTypes`.`id`=" . sql_escape($angeltype['id']) . " - AND NOT `Shifts`.`PSID` IS NULL"); - if ($result === false) { + $result = DB::select(' + SELECT + `NeededAngelTypes`.*, + `Shifts`.`SID`, + `AngelTypes`.`id`, + `AngelTypes`.`name`, + `AngelTypes`.`restricted`, + `AngelTypes`.`no_self_signup` + FROM `Shifts` + JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`shift_id`=`Shifts`.`SID` + JOIN `AngelTypes` ON `AngelTypes`.`id`= `NeededAngelTypes`.`angel_type_id` + WHERE `Shifts`.`SID`=? + AND `AngelTypes`.`id`=? + AND `Shifts`.`PSID` IS NULL + + UNION + + SELECT + `NeededAngelTypes`.*, + `Shifts`.`SID`, + `AngelTypes`.`id`, + `AngelTypes`.`name`, + `AngelTypes`.`restricted`, + `AngelTypes`.`no_self_signup` + FROM `Shifts` + JOIN `NeededAngelTypes` ON `NeededAngelTypes`.`room_id`=`Shifts`.`RID` + JOIN `AngelTypes` ON `AngelTypes`.`id`= `NeededAngelTypes`.`angel_type_id` + WHERE `Shifts`.`SID`=? + AND `AngelTypes`.`id`=? + AND NOT `Shifts`.`PSID` IS NULL + ', + [ + $shift['SID'], + $angeltype['id'], + $shift['SID'], + $angeltype['id'] + ] + ); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load needed angeltypes by filter.'); } - if (count($result) == 0) { + if (empty($result)) { return null; } return $result[0]; @@ -149,7 +161,8 @@ function NeededAngeltype_by_Shift_and_Angeltype($shift, $angeltype) */ function ShiftEntries_by_ShiftsFilter(ShiftsFilter $shiftsFilter) { - $SQL = " + // @TODO + $sql = " SELECT `User`.`Nick`, `User`.`email`, @@ -167,8 +180,8 @@ function ShiftEntries_by_ShiftsFilter(ShiftsFilter $shiftsFilter) WHERE `Shifts`.`RID` IN (" . implode(',', $shiftsFilter->getRooms()) . ") AND `start` BETWEEN " . $shiftsFilter->getStartTime() . " AND " . $shiftsFilter->getEndTime() . " ORDER BY `Shifts`.`start`"; - $result = sql_select($SQL); - if ($result === false) { + $result = DB::select($sql); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load shift entries by filter.'); } return $result; @@ -374,25 +387,31 @@ function Shift_signup_allowed( * Delete a shift by its external id. * * @param int $shift_psid - * @return mysqli_result|false + * @return bool */ function Shift_delete_by_psid($shift_psid) { - return sql_query("DELETE FROM `Shifts` WHERE `PSID`='" . sql_escape($shift_psid) . "'"); + DB::delete('DELETE FROM `Shifts` WHERE `PSID`=?', [$shift_psid]); + + if (DB::getStm()->errorCode() != '00000') { + return false; + } + + return true; } /** * Delete a shift. * * @param int $shift_id - * @return mysqli_result + * @return bool */ function Shift_delete($shift_id) { mail_shift_delete(Shift($shift_id)); - $result = sql_query("DELETE FROM `Shifts` WHERE `SID`='" . sql_escape($shift_id) . "'"); - if ($result === false) { + $result = DB::delete('DELETE FROM `Shifts` WHERE `SID`=?', [$shift_id]); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to delete shift.'); } return $result; @@ -402,7 +421,7 @@ function Shift_delete($shift_id) * Update a shift. * * @param array $shift - * @return mysqli_result|false + * @return bool */ function Shift_update($shift) { @@ -410,36 +429,51 @@ function Shift_update($shift) $shift['name'] = ShiftType($shift['shifttype_id'])['name']; mail_shift_change(Shift($shift['SID']), $shift); - return sql_query(" + return (bool)DB::update(' UPDATE `Shifts` SET - `shifttype_id`='" . sql_escape($shift['shifttype_id']) . "', - `start`='" . sql_escape($shift['start']) . "', - `end`='" . sql_escape($shift['end']) . "', - `RID`='" . sql_escape($shift['RID']) . "', - `title`=" . sql_null($shift['title']) . ", - `URL`=" . sql_null($shift['URL']) . ", - `PSID`=" . sql_null($shift['PSID']) . ", - `edited_by_user_id`='" . sql_escape($user['UID']) . "', - `edited_at_timestamp`=" . time() . " - WHERE `SID`='" . sql_escape($shift['SID']) . "' - "); + `shifttype_id` = ?, + `start` = ?, + `end` = ?, + `RID` = ?, + `title` = ?, + `URL` = ?, + `PSID` = ?, + `edited_by_user_id` = ?, + `edited_at_timestamp` = ? + WHERE `SID` = ? + ', + [ + $shift['shifttype_id'], + $shift['start'], + $shift['end'], + $shift['RID'], + $shift['title'], + $shift['URL'], + $shift['PSID'], + $user['UID'], + time(), + $shift['SID'] + ] + ); } /** * Update a shift by its external id. * * @param array $shift - * @return mysqli_result|false|null + * @return bool|null */ function Shift_update_by_psid($shift) { - $shift_source = sql_select("SELECT `SID` FROM `Shifts` WHERE `PSID`=" . $shift['PSID']); - if ($shift_source === false) { + $shift_source = DB::select('SELECT `SID` FROM `Shifts` WHERE `PSID`=?', [$shift['PSID']]); + if (DB::getStm()->errorCode() != '00000') { return false; } - if (count($shift_source) == 0) { + + if (empty($shift_source)) { return null; } + $shift['SID'] = $shift_source[0]['SID']; return Shift_update($shift); } @@ -453,22 +487,36 @@ function Shift_update_by_psid($shift) function Shift_create($shift) { global $user; - $result = sql_query(" - INSERT INTO `Shifts` SET - `shifttype_id`='" . sql_escape($shift['shifttype_id']) . "', - `start`='" . sql_escape($shift['start']) . "', - `end`='" . sql_escape($shift['end']) . "', - `RID`='" . sql_escape($shift['RID']) . "', - `title`=" . sql_null($shift['title']) . ", - `URL`=" . sql_null($shift['URL']) . ", - `PSID`=" . sql_null($shift['PSID']) . ", - `created_by_user_id`='" . sql_escape($user['UID']) . "', - `created_at_timestamp`=" . time() + DB::insert(' + INSERT INTO `Shifts` ( + `shifttype_id`, + `start`, + `end`, + `RID`, + `title`, + `URL`, + `PSID`, + `created_by_user_id`, + `created_at_timestamp` + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + ', + [ + $shift['shifttype_id'], + $shift['start'], + $shift['end'], + $shift['RID'], + $shift['title'], + $shift['URL'], + $shift['PSID'], + $user['UID'], + time(), + ] ); - if ($result === false) { + if (DB::getStm()->errorCode() != '00000') { return false; } - return sql_id(); + return DB::getPdo()->lastInsertId(); } /** @@ -480,7 +528,7 @@ function Shift_create($shift) */ function Shifts_by_user($user, $include_freeload_comments = false) { - $result = sql_select(' + $result = DB::select(' SELECT `ShiftTypes`.`id` AS `shifttype_id`, `ShiftTypes`.`name`, `ShiftEntry`.`id`, `ShiftEntry`.`SID`, `ShiftEntry`.`TID`, `ShiftEntry`.`UID`, `ShiftEntry`.`freeloaded`, `ShiftEntry`.`Comment`, ' . ($include_freeload_comments ? '`ShiftEntry`.`freeload_comment`, ' : '') . ' @@ -489,10 +537,14 @@ function Shifts_by_user($user, $include_freeload_comments = false) JOIN `Shifts` ON (`ShiftEntry`.`SID` = `Shifts`.`SID`) JOIN `ShiftTypes` ON (`ShiftTypes`.`id` = `Shifts`.`shifttype_id`) JOIN `Room` ON (`Shifts`.`RID` = `Room`.`RID`) - WHERE `UID`=\'' . sql_escape($user['UID']) . '\' + WHERE `UID` = ? ORDER BY `start` - '); - if ($result === false) { + ', + [ + $user['UID'] + ] + ); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load users shifts.'); } return $result; @@ -506,14 +558,13 @@ function Shifts_by_user($user, $include_freeload_comments = false) */ function Shift($shift_id) { - $shifts_source = sql_select(" + $shifts_source = DB::select(' SELECT `Shifts`.*, `ShiftTypes`.`name` FROM `Shifts` JOIN `ShiftTypes` ON (`ShiftTypes`.`id` = `Shifts`.`shifttype_id`) - WHERE `SID`='" . sql_escape($shift_id) . "'"); - $shiftsEntry_source = sql_select("SELECT `id`, `TID` , `UID` , `freeloaded` FROM `ShiftEntry` WHERE `SID`='" . sql_escape($shift_id) . "'"); + WHERE `SID`=?', [$shift_id]); - if ($shifts_source === false) { + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load shift.'); } @@ -523,16 +574,21 @@ function Shift($shift_id) $result = $shifts_source[0]; + $shiftsEntry_source = DB::select(' + SELECT `id`, `TID` , `UID` , `freeloaded` + FROM `ShiftEntry` + WHERE `SID`=?', [$shift_id]); + $result['ShiftEntry'] = $shiftsEntry_source; $result['NeedAngels'] = []; - $temp = NeededAngelTypes_by_shift($shift_id); - foreach ($temp as $e) { + $angelTypes = NeededAngelTypes_by_shift($shift_id); + foreach ($angelTypes as $type) { $result['NeedAngels'][] = [ - 'TID' => $e['angel_type_id'], - 'count' => $e['count'], - 'restricted' => $e['restricted'], - 'taken' => $e['taken'] + 'TID' => $type['angel_type_id'], + 'count' => $type['count'], + 'restricted' => $type['restricted'], + 'taken' => $type['taken'] ]; } @@ -546,22 +602,19 @@ function Shift($shift_id) */ function Shifts() { - $shifts_source = sql_select(' + $shifts_source = DB::select(' SELECT `ShiftTypes`.`name`, `Shifts`.*, `Room`.`RID`, `Room`.`Name` AS `room_name` FROM `Shifts` JOIN `ShiftTypes` ON (`ShiftTypes`.`id` = `Shifts`.`shifttype_id`) JOIN `Room` ON `Room`.`RID` = `Shifts`.`RID` '); - if ($shifts_source === false) { + + if (DB::getStm()->errorCode() != '00000') { return false; } foreach ($shifts_source as &$shift) { $needed_angeltypes = NeededAngelTypes_by_shift($shift['SID']); - if ($needed_angeltypes === false) { - return false; - } - $shift['angeltypes'] = $needed_angeltypes; } diff --git a/includes/model/UserAngelTypes_model.php b/includes/model/UserAngelTypes_model.php index 9ae21772..b27724c3 100644 --- a/includes/model/UserAngelTypes_model.php +++ b/includes/model/UserAngelTypes_model.php @@ -1,5 +1,7 @@ 0; + WHERE `UserAngelTypes`.`user_id`=? + AND `angeltype_id`=? + ', [$user['UID'], $angeltype['id']])) > 0; } /** @@ -29,16 +31,18 @@ function UserAngelType_exists($user, $angeltype) */ function User_angeltypes($user) { - $result = sql_select(" + $result = DB::select(' SELECT `AngelTypes`.*, `UserAngelTypes`.`confirm_user_id`, `UserAngelTypes`.`supporter` FROM `UserAngelTypes` JOIN `AngelTypes` ON `UserAngelTypes`.`angeltype_id` = `AngelTypes`.`id` - WHERE `UserAngelTypes`.`user_id`='" . sql_escape($user['UID']) . "' - "); - if ($result === false) { + WHERE `UserAngelTypes`.`user_id`=? + ', [$user['UID']]); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load user angeltypes.'); return false; } + return $result; } @@ -50,7 +54,7 @@ function User_angeltypes($user) */ function User_unconfirmed_AngelTypes($user) { - $result = sql_select(" + $result = DB::select(' SELECT `UserAngelTypes`.*, `AngelTypes`.`name`, @@ -58,16 +62,18 @@ function User_unconfirmed_AngelTypes($user) FROM `UserAngelTypes` JOIN `AngelTypes` ON `UserAngelTypes`.`angeltype_id`=`AngelTypes`.`id` JOIN `UserAngelTypes` AS `UnconfirmedMembers` ON `UserAngelTypes`.`angeltype_id`=`UnconfirmedMembers`.`angeltype_id` - WHERE `UserAngelTypes`.`user_id`='" . sql_escape($user['UID']) . "' + WHERE `UserAngelTypes`.`user_id`=? AND `UserAngelTypes`.`supporter`=TRUE AND `AngelTypes`.`restricted`=TRUE AND `UnconfirmedMembers`.`confirm_user_id` IS NULL GROUP BY `UserAngelTypes`.`angeltype_id` ORDER BY `AngelTypes`.`name` - "); - if ($result === false) { + ', [$user['UID']]); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load user angeltypes.'); } + return $result; } @@ -83,14 +89,20 @@ function User_is_AngelType_supporter(&$user, $angeltype) if (!isset($user['privileges'])) { $user['privileges'] = privileges_for_user($user['UID']); } - return (sql_num_query(" - SELECT `id` - FROM `UserAngelTypes` - WHERE `user_id`='" . sql_escape($user['UID']) . "' - AND `angeltype_id`='" . sql_escape($angeltype['id']) . "' - AND `supporter`=TRUE - LIMIT 1 - ") > 0) || in_array('admin_user_angeltypes', $user['privileges']); + return (count(DB::select(' + SELECT `id` + FROM `UserAngelTypes` + WHERE `user_id`=? + AND `angeltype_id`=? + AND `supporter`=TRUE + LIMIT 1 + ', + [ + $user['UID'], + $angeltype['id'] + ] + )) > 0) + || in_array('admin_user_angeltypes', $user['privileges']); } /** @@ -98,19 +110,21 @@ function User_is_AngelType_supporter(&$user, $angeltype) * * @param int $user_angeltype_id * @param bool $supporter - * @return mysqli_result + * @return int */ function UserAngelType_update($user_angeltype_id, $supporter) { - $result = sql_query(" + $result = DB::update(' UPDATE `UserAngelTypes` - SET `supporter`=" . sql_bool($supporter) . " - WHERE `id`='" . sql_escape($user_angeltype_id) . "' + SET `supporter`=? + WHERE `id`=? LIMIT 1 - "); - if ($result === false) { + ', [$supporter, $user_angeltype_id]); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to update supporter rights.'); } + return $result; } @@ -118,19 +132,21 @@ function UserAngelType_update($user_angeltype_id, $supporter) * Delete all unconfirmed UserAngelTypes for given Angeltype. * * @param int $angeltype_id - * @return mysqli_result + * @return bool */ function UserAngelTypes_delete_all($angeltype_id) { - $result = sql_query(" + DB::delete(' DELETE FROM `UserAngelTypes` - WHERE `angeltype_id`='" . sql_escape($angeltype_id) . "' + WHERE `angeltype_id`=? AND `confirm_user_id` IS NULL - "); - if ($result === false) { + ', [$angeltype_id]); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to delete all unconfirmed users.'); } - return $result; + + return true; } /** @@ -138,20 +154,22 @@ function UserAngelTypes_delete_all($angeltype_id) * * @param int $angeltype_id * @param array $confirm_user - * @return mysqli_result + * @return bool */ function UserAngelTypes_confirm_all($angeltype_id, $confirm_user) { - $result = sql_query(" + $result = DB::update(' UPDATE `UserAngelTypes` - SET `confirm_user_id`='" . sql_escape($confirm_user['UID']) . "' - WHERE `angeltype_id`='" . sql_escape($angeltype_id) . "' + SET `confirm_user_id`=? + WHERE `angeltype_id`=? AND `confirm_user_id` IS NULL - "); - if ($result === false) { + ', [$confirm_user['UID'], $angeltype_id]); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to confirm all users.'); } - return $result; + + return (bool)$result; } /** @@ -159,33 +177,33 @@ function UserAngelTypes_confirm_all($angeltype_id, $confirm_user) * * @param int $user_angeltype_id * @param array $confirm_user - * @return mysqli_result + * @return bool */ function UserAngelType_confirm($user_angeltype_id, $confirm_user) { - $result = sql_query(" + $result = DB::update(' UPDATE `UserAngelTypes` - SET `confirm_user_id`='" . sql_escape($confirm_user['UID']) . "' - WHERE `id`='" . sql_escape($user_angeltype_id) . "' - LIMIT 1"); - if ($result === false) { + SET `confirm_user_id`=? + WHERE `id`=? + LIMIT 1', [$confirm_user['UID'], $user_angeltype_id]); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to confirm user angeltype.'); } - return $result; + return (bool)$result; } /** * Delete an UserAngelType. * * @param array $user_angeltype - * @return mysqli_result|false + * @return bool */ function UserAngelType_delete($user_angeltype) { - return sql_query(" + return (bool)DB::delete(' DELETE FROM `UserAngelTypes` - WHERE `id`='" . sql_escape($user_angeltype['id']) . "' - LIMIT 1"); + WHERE `id`=? + LIMIT 1', [$user_angeltype['id']]); } /** @@ -197,14 +215,21 @@ function UserAngelType_delete($user_angeltype) */ function UserAngelType_create($user, $angeltype) { - $result = sql_query(" - INSERT INTO `UserAngelTypes` SET - `user_id`='" . sql_escape($user['UID']) . "', - `angeltype_id`='" . sql_escape($angeltype['id']) . "'"); - if ($result === false) { + DB::insert(' + INSERT INTO `UserAngelTypes` (`user_id`, `angeltype_id`) + VALUES (?, ?) + ', + [ + $user['UID'], + $angeltype['id'] + ] + ); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to create user angeltype.'); } - return sql_id(); + + return DB::getPdo()->lastInsertId(); } /** @@ -215,17 +240,20 @@ function UserAngelType_create($user, $angeltype) */ function UserAngelType($user_angeltype_id) { - $angeltype = sql_select(" + $angeltype = DB::select(' SELECT * FROM `UserAngelTypes` - WHERE `id`='" . sql_escape($user_angeltype_id) . "' - LIMIT 1"); - if ($angeltype === false) { + WHERE `id`=? + LIMIT 1', [$user_angeltype_id]); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load user angeltype.'); } - if (count($angeltype) == 0) { + + if (empty($angeltype)) { return null; } + return $angeltype[0]; } @@ -238,17 +266,26 @@ function UserAngelType($user_angeltype_id) */ function UserAngelType_by_User_and_AngelType($user, $angeltype) { - $angeltype = sql_select(" - SELECT * - FROM `UserAngelTypes` - WHERE `user_id`='" . sql_escape($user['UID']) . "' - AND `angeltype_id`='" . sql_escape($angeltype['id']) . "' - LIMIT 1"); - if ($angeltype === false) { + $angeltype = DB::select(' + SELECT * + FROM `UserAngelTypes` + WHERE `user_id`=? + AND `angeltype_id`=? + LIMIT 1 + ', + [ + $user['UID'], + $angeltype['id'] + ] + ); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load user angeltype.'); } - if (count($angeltype) == 0) { + + if (empty($angeltype)) { return null; } - return $angeltype[0]; + + return array_shift($angeltype); } diff --git a/includes/model/UserDriverLicenses_model.php b/includes/model/UserDriverLicenses_model.php index 8091736c..5ff4df35 100644 --- a/includes/model/UserDriverLicenses_model.php +++ b/includes/model/UserDriverLicenses_model.php @@ -1,5 +1,7 @@ errorCode() != '00000') { engelsystem_error('Unable to load user driver license.'); return false; } - if (count($user_driver_license) == 0) { + if (empty($user_driver_license)) { return null; } - return $user_driver_license[0]; + return array_shift($user_driver_license); } /** @@ -66,18 +72,32 @@ function UserDriverLicense($user_id) function UserDriverLicenses_create($user_driver_license, $user) { $user_driver_license['user_id'] = $user['UID']; - $result = sql_query(" - INSERT INTO `UserDriverLicenses` SET - `user_id`=" . sql_escape($user_driver_license['user_id']) . ", - `has_car`=" . sql_bool($user_driver_license['has_car']) . ", - `has_license_car`=" . sql_bool($user_driver_license['has_license_car']) . ", - `has_license_3_5t_transporter`=" . sql_bool($user_driver_license['has_license_3_5t_transporter']) . ", - `has_license_7_5t_truck`=" . sql_bool($user_driver_license['has_license_7_5t_truck']) . ", - `has_license_12_5t_truck`=" . sql_bool($user_driver_license['has_license_12_5t_truck']) . ", - `has_license_forklift`=" . sql_bool($user_driver_license['has_license_forklift'])); - if ($result === false) { + DB::insert(' + INSERT INTO `UserDriverLicenses` ( + `user_id`, + `has_car`, + `has_license_car`, + `has_license_3_5t_transporter`, + `has_license_7_5t_truck`, + `has_license_12_5t_truck`, + `has_license_forklift` + ) + VALUES (?, ?, ?, ?, ?, ?, ?) + ', + [ + $user_driver_license['user_id'], + (bool)$user_driver_license['has_car'], + (bool)$user_driver_license['has_license_car'], + (bool)$user_driver_license['has_license_3_5t_transporter'], + (bool)$user_driver_license['has_license_7_5t_truck'], + (bool)$user_driver_license['has_license_12_5t_truck'], + (bool)$user_driver_license['has_license_forklift'], + ] + ); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to create user driver license'); } + return $user_driver_license; } @@ -85,19 +105,32 @@ function UserDriverLicenses_create($user_driver_license, $user) * Update a user's driver license entry * * @param array $user_driver_license The UserDriverLicense to update - * @return mysqli_result + * @return bool */ function UserDriverLicenses_update($user_driver_license) { - $result = sql_query("UPDATE `UserDriverLicenses` SET - `has_car`=" . sql_bool($user_driver_license['has_car']) . ", - `has_license_car`=" . sql_bool($user_driver_license['has_license_car']) . ", - `has_license_3_5t_transporter`=" . sql_bool($user_driver_license['has_license_3_5t_transporter']) . ", - `has_license_7_5t_truck`=" . sql_bool($user_driver_license['has_license_7_5t_truck']) . ", - `has_license_12_5t_truck`=" . sql_bool($user_driver_license['has_license_12_5t_truck']) . ", - `has_license_forklift`=" . sql_bool($user_driver_license['has_license_forklift']) . " - WHERE `user_id`='" . sql_escape($user_driver_license['user_id']) . "'"); - if ($result === false) { + $result = DB::update(' + UPDATE `UserDriverLicenses` + SET + `has_car`=?, + `has_license_car`=?, + `has_license_3_5t_transporter`=?, + `has_license_7_5t_truck`=?, + `has_license_12_5t_truck`=?, + `has_license_forklift`=? + WHERE `user_id`=? + ', + [ + (bool)$user_driver_license['has_car'], + (bool)$user_driver_license['has_license_car'], + (bool)$user_driver_license['has_license_3_5t_transporter'], + (bool)$user_driver_license['has_license_7_5t_truck'], + (bool)$user_driver_license['has_license_12_5t_truck'], + (bool)$user_driver_license['has_license_forklift'], + $user_driver_license['user_id'], + ] + ); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to update user driver license information'); } return $result; @@ -107,12 +140,12 @@ function UserDriverLicenses_update($user_driver_license) * Delete a user's driver license entry * * @param int $user_id - * @return mysqli_result + * @return bool */ function UserDriverLicenses_delete($user_id) { - $result = sql_query("DELETE FROM `UserDriverLicenses` WHERE `user_id`=" . sql_escape($user_id)); - if ($result === false) { + $result = DB::delete('DELETE FROM `UserDriverLicenses` WHERE `user_id`=?', [$user_id]); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to remove user driver license information'); } return $result; diff --git a/includes/model/UserGroups_model.php b/includes/model/UserGroups_model.php index c390cd20..d4baf638 100644 --- a/includes/model/UserGroups_model.php +++ b/includes/model/UserGroups_model.php @@ -1,18 +1,22 @@ errorCode() == '00000'; } /** * Update user. * * @param array $user - * @return mysqli_result|false + * @return bool */ function User_update($user) { - return sql_query(" - UPDATE `User` SET - `Nick`='" . sql_escape($user['Nick']) . "', - `Name`='" . sql_escape($user['Name']) . "', - `Vorname`='" . sql_escape($user['Vorname']) . "', - `Alter`='" . sql_escape($user['Alter']) . "', - `Telefon`='" . sql_escape($user['Telefon']) . "', - `DECT`='" . sql_escape($user['DECT']) . "', - `Handy`='" . sql_escape($user['Handy']) . "', - `email`='" . sql_escape($user['email']) . "', - `email_shiftinfo`=" . sql_bool($user['email_shiftinfo']) . ", - `email_by_human_allowed`=" . sql_bool($user['email_by_human_allowed']) . ", - `jabber`='" . sql_escape($user['jabber']) . "', - `Size`='" . sql_escape($user['Size']) . "', - `Gekommen`='" . sql_escape($user['Gekommen']) . "', - `Aktiv`='" . sql_escape($user['Aktiv']) . "', - `force_active`=" . sql_bool($user['force_active']) . ", - `Tshirt`='" . sql_escape($user['Tshirt']) . "', - `color`='" . sql_escape($user['color']) . "', - `Sprache`='" . sql_escape($user['Sprache']) . "', - `Hometown`='" . sql_escape($user['Hometown']) . "', - `got_voucher`='" . sql_escape($user['got_voucher']) . "', - `arrival_date`='" . sql_escape($user['arrival_date']) . "', - `planned_arrival_date`='" . sql_escape($user['planned_arrival_date']) . "', - `planned_departure_date`=" . sql_null($user['planned_departure_date']) . " - WHERE `UID`='" . sql_escape($user['UID']) . "' - "); + return (bool)DB::update(" + UPDATE `User` SET + `Nick`=?, + `Name`=?, + `Vorname`=?, + `Alter`=?, + `Telefon`=?, + `DECT`=?, + `Handy`=?, + `email`=?, + `email_shiftinfo`=?, + `email_by_human_allowed`=?, + `jabber`=?, + `Size`=?, + `Gekommen`=?, + `Aktiv`=?, + `force_active`=?, + `Tshirt`=?, + `color`=?, + `Sprache`=?, + `Hometown`=?, + `got_voucher`=?, + `arrival_date`=?, + `planned_arrival_date`=?, + `planned_departure_date`=? + WHERE `UID`=? + ", + [ + $user['Nick'], + $user['Name'], + $user['Vorname'], + $user['Alter'], + $user['Telefon'], + $user['DECT'], + $user['Handy'], + $user['email'], + (bool)$user['email_shiftinfo'], + (bool)$user['email_by_human_allowed'], + $user['jabber'], + $user['Size'], + $user['Gekommen'], + $user['Aktiv'], + (bool)$user['force_active'], + $user['Tshirt'], + $user['color'], + $user['Sprache'], + $user['Hometown'], + $user['got_voucher'], + $user['arrival_date'], + $user['planned_arrival_date'], + $user['planned_departure_date'], + $user['UID'], + ] + ); } /** * Counts all forced active users. * - * @return string|null + * @return int */ function User_force_active_count() { - return sql_select_single_cell('SELECT COUNT(*) FROM `User` WHERE `force_active` = 1'); + $result = DB::select('SELECT COUNT(*) FROM `User` WHERE `force_active` = 1'); + $result = array_shift($result); + + if (empty($result)) { + return 0; + } + + return (int)array_shift($result); } /** - * @return string|null + * @return int */ function User_active_count() { - return sql_select_single_cell('SELECT COUNT(*) FROM `User` WHERE `Aktiv` = 1'); + $result = DB::select('SELECT COUNT(*) FROM `User` WHERE `Aktiv` = 1'); + $result = array_shift($result); + + if (empty($result)) { + return 0; + } + + return (int)array_shift($result); } /** - * @return string|null + * @return int */ function User_got_voucher_count() { - return sql_select_single_cell('SELECT SUM(`got_voucher`) FROM `User`'); + $result = DB::select('SELECT SUM(`got_voucher`) FROM `User`'); + $result = array_shift($result); + + if (empty($result)) { + return 0; + } + + return (int)array_shift($result); } /** - * @return string|null + * @return int */ function User_arrived_count() { - return sql_select_single_cell('SELECT COUNT(*) FROM `User` WHERE `Gekommen` = 1'); + $result = DB::select('SELECT COUNT(*) FROM `User` WHERE `Gekommen` = 1'); + $result = array_shift($result); + + if (empty($result)) { + return 0; + } + + return (int)array_shift($result); } /** - * @return string|null + * @return int */ function User_tshirts_count() { - return sql_select_single_cell('SELECT COUNT(*) FROM `User` WHERE `Tshirt` = 1'); + $result = DB::select('SELECT COUNT(*) FROM `User` WHERE `Tshirt` = 1'); + $result = array_shift($result); + + if (empty($result)) { + return 0; + } + + return (int)array_shift($result); } /** @@ -126,7 +192,19 @@ function User_sortable_columns() */ function Users($order_by = 'Nick') { - return sql_select("SELECT * FROM `User` ORDER BY `" . sql_escape($order_by) . "` ASC"); + $result = DB::select(sprintf(' + SELECT * + FROM `User` + ORDER BY `%s` ASC + ', + trim(DB::getPdo()->quote($order_by), '\'') + )); + + if (DB::getStm()->errorCode() != '00000') { + return false; + } + + return $result; } /** @@ -150,14 +228,19 @@ function User_is_freeloader($user) */ function Users_by_angeltype_inverted($angeltype) { - $result = sql_select(" - SELECT `User`.* - FROM `User` - LEFT JOIN `UserAngelTypes` - ON (`User`.`UID`=`UserAngelTypes`.`user_id` AND `angeltype_id`='" . sql_escape($angeltype['id']) . "') - WHERE `UserAngelTypes`.`id` IS NULL - ORDER BY `Nick`"); - if ($result === false) { + $result = DB::select(' + SELECT `User`.* + FROM `User` + LEFT JOIN `UserAngelTypes` + ON (`User`.`UID`=`UserAngelTypes`.`user_id` AND `angeltype_id`=?) + WHERE `UserAngelTypes`.`id` IS NULL + ORDER BY `Nick` + ', + [ + $angeltype['id'] + ] + ); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error("Unable to load users."); } return $result; @@ -171,19 +254,24 @@ function Users_by_angeltype_inverted($angeltype) */ function Users_by_angeltype($angeltype) { - $result = sql_select(" - SELECT - `User`.*, - `UserAngelTypes`.`id` AS `user_angeltype_id`, - `UserAngelTypes`.`confirm_user_id`, - `UserAngelTypes`.`supporter`, - `UserDriverLicenses`.* - FROM `User` - JOIN `UserAngelTypes` ON `User`.`UID`=`UserAngelTypes`.`user_id` - LEFT JOIN `UserDriverLicenses` ON `User`.`UID`=`UserDriverLicenses`.`user_id` - WHERE `UserAngelTypes`.`angeltype_id`='" . sql_escape($angeltype['id']) . "' - ORDER BY `Nick`"); - if ($result === false) { + $result = DB::select(' + SELECT + `User`.*, + `UserAngelTypes`.`id` AS `user_angeltype_id`, + `UserAngelTypes`.`confirm_user_id`, + `UserAngelTypes`.`supporter`, + `UserDriverLicenses`.* + FROM `User` + JOIN `UserAngelTypes` ON `User`.`UID`=`UserAngelTypes`.`user_id` + LEFT JOIN `UserDriverLicenses` ON `User`.`UID`=`UserDriverLicenses`.`user_id` + WHERE `UserAngelTypes`.`angeltype_id`=? + ORDER BY `Nick` + ', + [ + $angeltype['id'] + ] + ); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load members.'); } return $result; @@ -192,11 +280,11 @@ function Users_by_angeltype($angeltype) /** * Returns User id array * - * @return array|false + * @return array */ function User_ids() { - return sql_select('SELECT `UID` FROM `User`'); + return DB::select('SELECT `UID` FROM `User`'); } /** @@ -207,7 +295,7 @@ function User_ids() */ function User_validate_Nick($nick) { - return preg_replace('/([^a-z0-9üöäß. _+*-]{1,})/ui', '', $nick); + return preg_replace('/([^\wüöäß. +*-]{1,})/ui', '', $nick); } /** @@ -311,14 +399,17 @@ function User_validate_planned_departure_date($planned_arrival_date, $planned_de */ function User($user_id) { - $user_source = sql_select("SELECT * FROM `User` WHERE `UID`='" . sql_escape($user_id) . "' LIMIT 1"); - if ($user_source === false) { + $user_source = DB::select('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$user_id]); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load user.'); } - if (count($user_source) > 0) { - return $user_source[0]; + + if (empty($user_source)) { + return null; } - return null; + + return array_shift($user_source); } /** @@ -330,13 +421,16 @@ function User($user_id) */ function User_by_api_key($api_key) { - $user = sql_select("SELECT * FROM `User` WHERE `api_key`='" . sql_escape($api_key) . "' LIMIT 1"); - if ($user === false) { + $user = DB::select('SELECT * FROM `User` WHERE `api_key`=? LIMIT 1', [$api_key]); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to find user by api key.'); } - if (count($user) == 0) { + + if (empty($user)) { return null; } + return $user[0]; } @@ -348,14 +442,17 @@ function User_by_api_key($api_key) */ function User_by_email($email) { - $user = sql_select("SELECT * FROM `User` WHERE `email`='" . sql_escape($email) . "' LIMIT 1"); - if ($user === false) { + $user = DB::select('SELECT * FROM `User` WHERE `email`=? LIMIT 1', [$email]); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load user.'); } - if (count($user) == 0) { + + if (empty($user)) { return null; } - return $user[0]; + + return array_shift($user); } /** @@ -366,14 +463,17 @@ function User_by_email($email) */ function User_by_password_recovery_token($token) { - $user = sql_select("SELECT * FROM `User` WHERE `password_recovery_token`='" . sql_escape($token) . "' LIMIT 1"); - if ($user === false) { + $user = DB::select('SELECT * FROM `User` WHERE `password_recovery_token`=? LIMIT 1', [$token]); + + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to load user.'); } - if (count($user) == 0) { + + if (empty($user)) { return null; } - return $user[0]; + + return array_shift($user); } /** @@ -386,8 +486,19 @@ function User_by_password_recovery_token($token) function User_reset_api_key(&$user, $log = true) { $user['api_key'] = md5($user['Nick'] . time() . rand()); - $result = sql_query("UPDATE `User` SET `api_key`='" . sql_escape($user['api_key']) . "' WHERE `UID`='" . sql_escape($user['UID']) . "' LIMIT 1"); - if ($result === false) { + DB::update( + ' + UPDATE `User` + SET `api_key`=? + WHERE `UID`=? + LIMIT 1 + ', + [ + $user['api_key'], + $user['UID'] + ] + ); + if (DB::getStm()->errorCode() != '00000') { return false; } @@ -407,13 +518,18 @@ function User_reset_api_key(&$user, $log = true) function User_generate_password_recovery_token(&$user) { $user['password_recovery_token'] = md5($user['Nick'] . time() . rand()); - $result = sql_query(" - UPDATE `User` - SET `password_recovery_token`='" . sql_escape($user['password_recovery_token']) . "' - WHERE `UID`='" . sql_escape($user['UID']) . "' - LIMIT 1 - "); - if ($result === false) { + DB::update(' + UPDATE `User` + SET `password_recovery_token`=? + WHERE `UID`=? + LIMIT 1 + ', + [ + $user['password_recovery_token'], + $user['UID'], + ] + ); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to generate password recovery token.'); } engelsystem_log('Password recovery for ' . User_Nick_render($user) . ' started.'); diff --git a/includes/mysqli_provider.php b/includes/mysqli_provider.php deleted file mode 100644 index 0efb670a..00000000 --- a/includes/mysqli_provider.php +++ /dev/null @@ -1,250 +0,0 @@ -close(); -} - -/** - * Return NULL if given value is null. - * - * @param mixed $value - * @return bool - */ -function sql_null($value = null) -{ - return $value == null ? 'NULL' : ("'" . sql_escape($value) . "'"); -} - -/** - * Start new transaction. - * - * @return mysqli_result|bool - */ -function sql_transaction_start() -{ - global $sql_nested_transaction_level; - - if ($sql_nested_transaction_level++ == 0) { - return sql_query('BEGIN'); - } - - return true; -} - -/** - * Commit transaction. - * - * @return mysqli_result|bool - */ -function sql_transaction_commit() -{ - global $sql_nested_transaction_level; - - if (--$sql_nested_transaction_level == 0) { - return sql_query('COMMIT'); - } - - return true; -} - -/** - * Stop transaction, revert database. - * - * @return mysqli_result|bool - */ -function sql_transaction_rollback() -{ - global $sql_nested_transaction_level; - - if (--$sql_nested_transaction_level == 0) { - return sql_query('ROLLBACK'); - } - - return true; -} - -/** - * Logs an sql error. - * - * @param string $message - * @return false - */ -function sql_error($message) -{ - // @TODO: Bad idea.. - sql_close(); - - $message = trim($message) . "\n"; - $message .= debug_string_backtrace() . "\n"; - - error_log('mysql_provider error: ' . $message); - - return false; -} - -/** - * Connect to mysql server. - * - * @param string $host Host - * @param string $user Username - * @param string $pass Password - * @param string $db_name DB to select - * @return mysqli|false The connection handler - */ -function sql_connect($host, $user, $pass, $db_name) -{ - global $sql_connection; - - $sql_connection = new mysqli($host, $user, $pass, $db_name); - if ($sql_connection->connect_errno) { - error('Unable to connect to MySQL: ' . $sql_connection->connect_error); - return sql_error('Unable to connect to MySQL: ' . $sql_connection->connect_error); - } - - $result = $sql_connection->query('SET CHARACTER SET utf8;'); - if (!$result) { - return sql_error('Unable to set utf8 character set (' . $sql_connection->errno . ') ' . $sql_connection->error); - } - - $result = $sql_connection->set_charset('utf8'); - if (!$result) { - return sql_error('Unable to set utf8 names (' . $sql_connection->errno . ') ' . $sql_connection->error); - } - - return $sql_connection; -} - -/** - * Change the selected db in current mysql-connection. - * - * @param $db_name - * @return bool true on success, false on error - */ -function sql_select_db($db_name) -{ - global $sql_connection; - if (!$sql_connection->select_db($db_name)) { - return sql_error('No database selected.'); - } - return true; -} - -/** - * MySQL SELECT query - * - * @param string $query - * @return array|false Result array or false on error - */ -function sql_select($query) -{ - global $sql_connection; - - $result = $sql_connection->query($query); - if ($result) { - $data = []; - while ($line = $result->fetch_assoc()) { - array_push($data, $line); - } - return $data; - } - - return sql_error('MySQL-query error: ' . $query . ' (' . $sql_connection->errno . ') ' . $sql_connection->error); -} - -/** - * MySQL execute a query - * - * @param string $query - * @return mysqli_result|false boolean resource or false on error - */ -function sql_query($query) -{ - global $sql_connection; - - $result = $sql_connection->query($query); - if ($result) { - return $result; - } - - return sql_error('MySQL-query error: ' . $query . ' (' . $sql_connection->errno . ') ' . $sql_connection->error); -} - -/** - * Returns last inserted id. - * - * @return int - */ -function sql_id() -{ - global $sql_connection; - return $sql_connection->insert_id; -} - -/** - * Escape a string for a sql query. - * - * @param string $query - * @return string - */ -function sql_escape($query) -{ - global $sql_connection; - return $sql_connection->real_escape_string($query); -} - -/** - * Convert a boolean for mysql-queries. - * - * @param boolean $boolean - * @return string - */ -function sql_bool($boolean) -{ - return $boolean == true ? 'TRUE' : 'FALSE'; -} - -/** - * Count query result lines. - * - * @param string $query - * @return int Count of result lines - */ -function sql_num_query($query) -{ - return sql_query($query)->num_rows; -} - -function sql_select_single_col($query) -{ - $result = sql_select($query); - return array_map('array_shift', $result); -} - -/** - * @param string $query - * @return string|null - */ -function sql_select_single_cell($query) -{ - $result = sql_select($query); - if ($result == false) { - return null; - } - - $result = array_shift($result); - if (!is_array($result)) { - return null; - } - - return array_shift($result); -} diff --git a/includes/pages/admin_active.php b/includes/pages/admin_active.php index c4b6e119..d3b290f9 100644 --- a/includes/pages/admin_active.php +++ b/includes/pages/admin_active.php @@ -1,5 +1,7 @@ $size, - 'needed' => sql_select_single_cell( - "SELECT count(*) FROM `User` WHERE `Size`='" . sql_escape($size) . "' AND `Gekommen`=1" - ), - 'given' => sql_select_single_cell( - "SELECT count(*) FROM `User` WHERE `Size`='" . sql_escape($size) . "' AND `Tshirt`=1" - ) + 'needed' => (int)$sc, + 'given' => (int)$gc ]; } } + + $uc = DB::select('SELECT count(*) FROM `User` WHERE `Tshirt`=1'); + $uc = array_shift($uc); + $uc = array_shift($uc); + $shirt_statistics[] = [ 'size' => '' . _('Sum') . '', 'needed' => '' . User_arrived_count() . '', - 'given' => '' . sql_select_single_cell('SELECT count(*) FROM `User` WHERE `Tshirt`=1') . '' + 'given' => '' . (int)$uc . '' ]; return page_with_title(admin_active_title(), [ diff --git a/includes/pages/admin_arrive.php b/includes/pages/admin_arrive.php index a17408e7..0080ccf9 100644 --- a/includes/pages/admin_arrive.php +++ b/includes/pages/admin_arrive.php @@ -1,5 +1,7 @@ quote($_REQUEST['angeltype']) + . ' AND `UserAngelTypes`.`user_id` = `User`.`UID`'; if (isset($_REQUEST['confirmed_only'])) { - $angeltypesearch .= ' AND `UserAngelTypes`.`confirm_user_id`'; + $angelTypeSearch .= ' AND `UserAngelTypes`.`confirm_user_id`'; } - $angeltypesearch .= ') '; + $angelTypeSearch .= ') '; } - $angel_types_source = sql_select('SELECT `id`, `name` FROM `AngelTypes` ORDER BY `name`'); + $angel_types_source = DB::select('SELECT `id`, `name` FROM `AngelTypes` ORDER BY `name`'); $angel_types = [ '' => 'alle Typen' ]; @@ -40,20 +43,27 @@ function admin_free() $angel_types[$angel_type['id']] = $angel_type['name']; } - $users = sql_select(" - SELECT `User`.* - FROM `User` - ${angeltypesearch} - LEFT JOIN `ShiftEntry` ON `User`.`UID` = `ShiftEntry`.`UID` - LEFT JOIN `Shifts` - ON ( - `ShiftEntry`.`SID` = `Shifts`.`SID` - AND `Shifts`.`start` < '" . sql_escape(time()) . "' - AND `Shifts`.`end` > '" . sql_escape(time()) . "' - ) - WHERE `User`.`Gekommen` = 1 AND `Shifts`.`SID` IS NULL - GROUP BY `User`.`UID` - ORDER BY `Nick`"); + $users = DB::select(' + SELECT `User`.* + FROM `User` + ' . $angelTypeSearch . ' + LEFT JOIN `ShiftEntry` ON `User`.`UID` = `ShiftEntry`.`UID` + LEFT JOIN `Shifts` + ON ( + `ShiftEntry`.`SID` = `Shifts`.`SID` + AND `Shifts`.`start` < ? + AND `Shifts`.`end` > ? + ) + WHERE `User`.`Gekommen` = 1 + AND `Shifts`.`SID` IS NULL + GROUP BY `User`.`UID` + ORDER BY `Nick` + ', + [ + time(), + time(), + ] + ); $free_users_table = []; if ($search == '') { diff --git a/includes/pages/admin_groups.php b/includes/pages/admin_groups.php index 8e578cb2..bc33a2b0 100644 --- a/includes/pages/admin_groups.php +++ b/includes/pages/admin_groups.php @@ -1,5 +1,7 @@ 0) { - $privileges = sql_select(" + $group = DB::select('SELECT * FROM `Groups` WHERE `UID`=? LIMIT 1', [$group_id]); + if (!empty($group)) { + $privileges = DB::select(' SELECT `Privileges`.*, `GroupPrivileges`.`group_id` FROM `Privileges` LEFT OUTER JOIN `GroupPrivileges` ON ( `Privileges`.`id` = `GroupPrivileges`.`privilege_id` - AND `GroupPrivileges`.`group_id`='" . sql_escape($group_id) . "' + AND `GroupPrivileges`.`group_id`=? ) ORDER BY `Privileges`.`name` - "); + ', [$group_id]); $privileges_html = ''; $privileges_form = []; - foreach ($privileges as $priv) { + foreach ($privileges as $privilege) { $privileges_form[] = form_checkbox( 'privileges[]', - $priv['desc'] . ' (' . $priv['name'] . ')', - $priv['group_id'] != '', - $priv['id'] + $privilege['desc'] . ' (' . $privilege['name'] . ')', + $privilege['group_id'] != '', + $privilege['id'] ); $privileges_html .= sprintf( ' %s %s', - $priv['id'], - ($priv['group_id'] != '' ? 'checked="checked"' : ''), - $priv['name'], - $priv['desc'] + $privilege['id'], + ($privilege['group_id'] != '' ? 'checked="checked"' : ''), + $privilege['name'], + $privilege['desc'] ); } @@ -103,20 +105,27 @@ function admin_groups() return error('Incomplete call, missing Groups ID.', true); } - $group = sql_select("SELECT * FROM `Groups` WHERE `UID`='" . sql_escape($group_id) . "' LIMIT 1"); + $group = DB::select('SELECT * FROM `Groups` WHERE `UID`=? LIMIT 1', [$group_id]); if (!is_array($_REQUEST['privileges'])) { $_REQUEST['privileges'] = []; } - if (count($group) > 0) { - list($group) = $group; - sql_query("DELETE FROM `GroupPrivileges` WHERE `group_id`='" . sql_escape($group_id) . "'"); + if (!empty($group)) { + $group = array_shift($group); + DB::delete('DELETE FROM `GroupPrivileges` WHERE `group_id`=?', [$group_id]); $privilege_names = []; - foreach ($_REQUEST['privileges'] as $priv) { - if (preg_match("/^[0-9]{1,}$/", $priv)) { - $group_privileges_source = sql_select("SELECT * FROM `Privileges` WHERE `id`='" . sql_escape($priv) . "' LIMIT 1"); - if (count($group_privileges_source) > 0) { - sql_query("INSERT INTO `GroupPrivileges` SET `group_id`='" . sql_escape($group_id) . "', `privilege_id`='" . sql_escape($priv) . "'"); - $privilege_names[] = $group_privileges_source[0]['name']; + foreach ($_REQUEST['privileges'] as $privilege) { + if (preg_match("/^[0-9]{1,}$/", $privilege)) { + $group_privileges_source = DB::select( + 'SELECT `name` FROM `Privileges` WHERE `id`=? LIMIT 1', + [$privilege] + ); + if (!empty($group_privileges_source)) { + $group_privileges_source = array_shift($group_privileges_source); + DB::insert( + 'INSERT INTO `GroupPrivileges` (`group_id`, `privilege_id`) VALUES (?, ?)', + [$group_id, $privilege] + ); + $privilege_names[] = $group_privileges_source['name']; } } } diff --git a/includes/pages/admin_import.php b/includes/pages/admin_import.php index 2e37572f..7a246b4b 100644 --- a/includes/pages/admin_import.php +++ b/includes/pages/admin_import.php @@ -1,5 +1,7 @@ 0) { return '' . _('There are unanswered questions!') . ''; @@ -39,7 +41,7 @@ function admin_questions() if (!isset($_REQUEST['action'])) { $unanswered_questions_table = []; - $questions = sql_select("SELECT * FROM `Questions` WHERE `AID` IS NULL"); + $questions = DB::select('SELECT * FROM `Questions` WHERE `AID` IS NULL'); foreach ($questions as $question) { $user_source = User($question['UID']); @@ -59,7 +61,7 @@ function admin_questions() } $answered_questions_table = []; - $questions = sql_select("SELECT * FROM `Questions` WHERE NOT `AID` IS NULL"); + $questions = DB::select('SELECT * FROM `Questions` WHERE NOT `AID` IS NULL'); foreach ($questions as $question) { $user_source = User($question['UID']); $answer_user_source = User($question['AID']); @@ -102,7 +104,10 @@ function admin_questions() return error('Incomplete call, missing Question ID.', true); } - $question = sql_select("SELECT * FROM `Questions` WHERE `QID`='" . sql_escape($question_id) . "' LIMIT 1"); + $question = DB::select( + 'SELECT * FROM `Questions` WHERE `QID`=? LIMIT 1', + [$question_id] + ); if (count($question) > 0 && $question[0]['AID'] == null) { $answer = trim( preg_replace("/([^\p{L}\p{P}\p{Z}\p{N}\n]{1,})/ui", @@ -111,12 +116,19 @@ function admin_questions() )); if ($answer != '') { - sql_query(" - UPDATE `Questions` - SET `AID`='" . sql_escape($user['UID']) . "', `Answer`='" . sql_escape($answer) . "' - WHERE `QID`='" . sql_escape($question_id) . "' - LIMIT 1 - "); + DB::update( + ' + UPDATE `Questions` + SET `AID`=?, `Answer`=? + WHERE `QID`=? + LIMIT 1 + ', + [ + $user['UID'], + $answer, + $question_id, + ] + ); engelsystem_log('Question ' . $question[0]['Question'] . ' answered: ' . $answer); redirect(page_link_to('admin_questions')); } else { @@ -133,9 +145,12 @@ function admin_questions() return error('Incomplete call, missing Question ID.', true); } - $question = sql_select("SELECT * FROM `Questions` WHERE `QID`='" . sql_escape($question_id) . "' LIMIT 1"); + $question = DB::select( + 'SELECT * FROM `Questions` WHERE `QID`=? LIMIT 1', + [$question_id] + ); if (count($question) > 0) { - sql_query("DELETE FROM `Questions` WHERE `QID`='" . sql_escape($question_id) . "' LIMIT 1"); + DB::delete('DELETE FROM `Questions` WHERE `QID`=? LIMIT 1', [$question_id]); engelsystem_log('Question deleted: ' . $question[0]['Question']); redirect(page_link_to('admin_questions')); } else { diff --git a/includes/pages/admin_rooms.php b/includes/pages/admin_rooms.php index 61923689..50be15f3 100644 --- a/includes/pages/admin_rooms.php +++ b/includes/pages/admin_rooms.php @@ -1,5 +1,7 @@ 0) { $name = strip_request_item('name'); - if (isset($room) && sql_num_query("SELECT * FROM `Room` WHERE `Name`='" . sql_escape($name) . "' AND NOT `RID`=" . sql_escape($room_id)) > 0) { + if ( + isset($room) + && count(DB::select( + 'SELECT RID FROM `Room` WHERE `Name`=? AND NOT `RID`=?', + [$name, $room_id] + )) > 0 + ) { $valid = false; $msg .= error(_('This name is already in use.'), true); } @@ -111,17 +122,23 @@ function admin_rooms() } if ($valid) { - if (isset($room_id)) { - sql_query(" + if (!empty($room_id)) { + DB::update(' UPDATE `Room` SET - `Name`='" . sql_escape($name) . "', - `FromPentabarf`='" . sql_escape($from_pentabarf) . "', - `show`='" . sql_escape($public) . "', - `Number`='" . sql_escape($number) . "' - WHERE `RID`='" . sql_escape($room_id) . "' + `Name`=?, + `FromPentabarf`=?, + `show`=?, + `Number`=? + WHERE `RID`=? LIMIT 1 - "); + ', [ + $name, + $from_pentabarf, + $public, + $number, + $room_id, + ]); engelsystem_log( 'Room updated: ' . $name . ', pentabarf import: ' . $from_pentabarf diff --git a/includes/pages/admin_shifts.php b/includes/pages/admin_shifts.php index 1e19c5e4..c543e827 100644 --- a/includes/pages/admin_shifts.php +++ b/includes/pages/admin_shifts.php @@ -1,5 +1,7 @@ $count) { - $angel_type_source = sql_select("SELECT * FROM `AngelTypes` WHERE `id`='" . sql_escape($type_id) . "' LIMIT 1"); - if (count($angel_type_source) > 0) { - sql_query("INSERT INTO `NeededAngelTypes` SET `shift_id`='" . sql_escape($shift_id) . "', `angel_type_id`='" . sql_escape($type_id) . "', `count`='" . sql_escape($count) . "'"); - $needed_angel_types_info[] = $angel_type_source[0]['name'] . ": " . $count; + $angel_type_source = DB::select(' + SELECT * + FROM `AngelTypes` + WHERE `id` = ? + LIMIT 1', [$type_id]); + if (!empty($angel_type_source)) { + DB::insert(' + INSERT INTO `NeededAngelTypes` (`shift_id`, `angel_type_id`, `count`) + VALUES (?, ?, ?) + ', + [ + $shift_id, + $type_id, + $count + ] + ); + $needed_angel_types_info[] = $angel_type_source[0]['name'] . ': ' . $count; } } } diff --git a/includes/pages/admin_user.php b/includes/pages/admin_user.php index 8e11c5f3..192becb0 100644 --- a/includes/pages/admin_user.php +++ b/includes/pages/admin_user.php @@ -1,5 +1,7 @@ '; - $my_highest_group = sql_select("SELECT * FROM `UserGroups` WHERE `uid`='" . sql_escape($user['UID']) . "' ORDER BY `group_id` LIMIT 1"); + $my_highest_group = DB::select( + 'SELECT group_id FROM `UserGroups` WHERE `uid`=? ORDER BY `group_id` LIMIT 1', + [$user['UID']] + ); if (count($my_highest_group) > 0) { $my_highest_group = $my_highest_group[0]['group_id']; } - $his_highest_group = sql_select("SELECT * FROM `UserGroups` WHERE `uid`='" . sql_escape($user_id) . "' ORDER BY `group_id` LIMIT 1"); + $his_highest_group = DB::select( + 'SELECT `group_id` FROM `UserGroups` WHERE `uid`=? ORDER BY `group_id` LIMIT 1', + [$user_id] + ); if (count($his_highest_group) > 0) { $his_highest_group = $his_highest_group[0]['group_id']; } @@ -121,16 +129,21 @@ function admin_user() . page_link_to('admin_user') . '&action=save_groups&id=' . $user_id . '" method="post">' . "\n"; $html .= ''; - $groups = sql_select(" - SELECT * - FROM `Groups` - LEFT OUTER JOIN `UserGroups` ON ( - `UserGroups`.`group_id` = `Groups`.`UID` - AND `UserGroups`.`uid` = '" . sql_escape($user_id) . "' - ) - WHERE `Groups`.`UID` >= '" . sql_escape($my_highest_group) . "' - ORDER BY `Groups`.`Name` - "); + $groups = DB::select(' + SELECT * + FROM `Groups` + LEFT OUTER JOIN `UserGroups` ON ( + `UserGroups`.`group_id` = `Groups`.`UID` + AND `UserGroups`.`uid` = ? + ) + WHERE `Groups`.`UID` >= ? + ORDER BY `Groups`.`Name` + ', + [ + $user_id, + $my_highest_group, + ] + ); foreach ($groups as $group) { $html .= '
0 && (count($his_highest_group) == 0 || ($my_highest_group[0]['group_id'] <= $his_highest_group[0]['group_id']))) { - $groups_source = sql_select(" - SELECT * - FROM `Groups` - LEFT OUTER JOIN `UserGroups` ON ( - `UserGroups`.`group_id` = `Groups`.`UID` - AND `UserGroups`.`uid` = '" . sql_escape($user_id) . "' - ) - WHERE `Groups`.`UID` >= '" . sql_escape($my_highest_group[0]['group_id']) . "' - ORDER BY `Groups`.`Name` - "); + $my_highest_group = DB::select( + 'SELECT * FROM `UserGroups` WHERE `uid`=? ORDER BY `group_id`', + [$user['UID']] + ); + $his_highest_group = DB::select( + 'SELECT * FROM `UserGroups` WHERE `uid`=? ORDER BY `group_id`', + [$user_id] + ); + + if ( + count($my_highest_group) > 0 + && ( + count($his_highest_group) == 0 + || ($my_highest_group[0]['group_id'] <= $his_highest_group[0]['group_id']) + ) + ) { + $groups_source = DB::select(' + SELECT * + FROM `Groups` + LEFT OUTER JOIN `UserGroups` ON ( + `UserGroups`.`group_id` = `Groups`.`UID` + AND `UserGroups`.`uid` = ? + ) + WHERE `Groups`.`UID` >= ? + ORDER BY `Groups`.`Name` + ', + [ + $user_id, + $my_highest_group[0]['group_id'], + ] + ); $groups = []; $grouplist = []; foreach ($groups_source as $group) { @@ -179,11 +209,14 @@ function admin_user() $_REQUEST['groups'] = []; } - sql_query("DELETE FROM `UserGroups` WHERE `uid`='" . sql_escape($user_id) . "'"); + DB::delete('DELETE FROM `UserGroups` WHERE `uid`=?', [$user_id]); $user_groups_info = []; foreach ($_REQUEST['groups'] as $group) { if (in_array($group, $grouplist)) { - sql_query("INSERT INTO `UserGroups` SET `uid`='" . sql_escape($user_id) . "', `group_id`='" . sql_escape($group) . "'"); + DB::insert( + 'INSERT INTO `UserGroups` (`uid`, `group_id`) VALUES (?, ?)', + [$user_id, $group] + ); $user_groups_info[] = $groups[$group]['Name']; } } @@ -206,25 +239,42 @@ function admin_user() if (in_array('admin_active', $privileges)) { $force_active = $_REQUEST['force_active']; } - $SQL = "UPDATE `User` SET - `Nick` = '" . sql_escape($_POST["eNick"]) . "', - `Name` = '" . sql_escape($_POST["eName"]) . "', - `Vorname` = '" . sql_escape($_POST["eVorname"]) . "', - `Telefon` = '" . sql_escape($_POST["eTelefon"]) . "', - `Handy` = '" . sql_escape($_POST["eHandy"]) . "', - `Alter` = '" . sql_escape($_POST["eAlter"]) . "', - `DECT` = '" . sql_escape($_POST["eDECT"]) . "', - " . ($user_source['email_by_human_allowed'] ? "`email` = '" . sql_escape($_POST["eemail"]) . "'," : "") . " - `jabber` = '" . sql_escape($_POST["ejabber"]) . "', - `Size` = '" . sql_escape($_POST["eSize"]) . "', - `Gekommen`= '" . sql_escape($_POST["eGekommen"]) . "', - `Aktiv`= '" . sql_escape($_POST["eAktiv"]) . "', - `force_active`= " . sql_escape($force_active) . ", - `Tshirt` = '" . sql_escape($_POST["eTshirt"]) . "', - `Hometown` = '" . sql_escape($_POST["Hometown"]) . "' - WHERE `UID` = '" . sql_escape($user_id) . "' - LIMIT 1"; - sql_query($SQL); + $sql = ' + UPDATE `User` SET + `Nick` = ?, + `Name` = ?, + `Vorname` = ?, + `Telefon` = ?, + `Handy` = ?, + `Alter` =?, + `DECT` = ?, + ' . ($user_source['email_by_human_allowed'] ? '`email` = ' . DB::getPdo()->quote($_POST["eemail"]) . ',' : '') . ' + `jabber` = ?, + `Size` = ?, + `Gekommen`= ?, + `Aktiv`= ?, + `force_active`= ?, + `Tshirt` = ?, + `Hometown` = ? + WHERE `UID` = ? + LIMIT 1'; + DB::update($sql, [ + $_POST['eNick'], + $_POST['eName'], + $_POST['eVorname'], + $_POST['eTelefon'], + $_POST['eHandy'], + $_POST['eAlter'], + $_POST['eDECT'], + $_POST['ejabber'], + $_POST['eSize'], + $_POST['eGekommen'], + $_POST['eAktiv'], + $force_active, + $_POST['eTshirt'], + $_POST['Hometown'], + $user_id, + ]); engelsystem_log( 'Updated user: ' . $_POST['eNick'] . ', ' . $_POST['eSize'] . ', arrived: ' . $_POST['eGekommen'] diff --git a/includes/pages/guest_login.php b/includes/pages/guest_login.php index d202d92d..f08f9260 100644 --- a/includes/pages/guest_login.php +++ b/includes/pages/guest_login.php @@ -1,5 +1,7 @@ 1) { $nick = User_validate_Nick($_REQUEST['nick']); - if (sql_num_query("SELECT * FROM `User` WHERE `Nick`='" . sql_escape($nick) . "' LIMIT 1") > 0) { + if (count(DB::select('SELECT `UID` FROM `User` WHERE `Nick`=? LIMIT 1', [$nick])) > 0) { $valid = false; $msg .= error(sprintf(_('Your nick "%s" already exists.'), $nick), true); } @@ -148,10 +150,10 @@ function guest_register() // Trivia if (isset($_REQUEST['lastname'])) { - $lastname = strip_request_item('lastname'); + $lastName = strip_request_item('lastname'); } if (isset($_REQUEST['prename'])) { - $prename = strip_request_item('prename'); + $preName = strip_request_item('prename'); } if (isset($_REQUEST['age']) && preg_match("/^[0-9]{0,4}$/", $_REQUEST['age'])) { $age = strip_request_item('age'); @@ -173,38 +175,65 @@ function guest_register() } if ($valid) { - sql_query(" - INSERT INTO `User` SET - `color`='" . sql_escape($default_theme) . "', - `Nick`='" . sql_escape($nick) . "', - `Vorname`='" . sql_escape($prename) . "', - `Name`='" . sql_escape($lastname) . "', - `Alter`='" . sql_escape($age) . "', - `Telefon`='" . sql_escape($tel) . "', - `DECT`='" . sql_escape($dect) . "', - `Handy`='" . sql_escape($mobile) . "', - `email`='" . sql_escape($mail) . "', - `email_shiftinfo`=" . sql_bool($email_shiftinfo) . ", - `email_by_human_allowed`=" . sql_bool($email_by_human_allowed) . ", - `jabber`='" . sql_escape($jabber) . "', - `Size`='" . sql_escape($tshirt_size) . "', - `Passwort`='" . sql_escape($password_hash) . "', - `kommentar`='" . sql_escape($comment) . "', - `Hometown`='" . sql_escape($hometown) . "', - `CreateDate`=NOW(), - `Sprache`='" . sql_escape($_SESSION["locale"]) . "', - `arrival_date`=NULL, - `planned_arrival_date`='" . sql_escape($planned_arrival_date) . "'"); + DB::insert(' + INSERT INTO `User` ( + `color`, + `Nick`, + `Vorname`, + `Name`, + `Alter`, + `Telefon`, + `DECT`, + `Handy`, + `email`, + `email_shiftinfo`, + `email_by_human_allowed`, + `jabber`, + `Size`, + `Passwort`, + `kommentar`, + `Hometown`, + `CreateDate`, + `Sprache`, + `arrival_date`, + `planned_arrival_date` + ) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, NULL, ?) + ', + [ + $default_theme, + $nick, + $preName, + $lastName, + $age, + $tel, + $dect, + $mobile, + $mail, + (bool)$email_shiftinfo, + (bool)$email_by_human_allowed, + $jabber, + $tshirt_size, + $password_hash, + $comment, + $hometown, + $_SESSION['locale'], + $planned_arrival_date, + ] + ); // Assign user-group and set password - $user_id = sql_id(); - sql_query("INSERT INTO `UserGroups` SET `uid`='" . sql_escape($user_id) . "', `group_id`=-2"); + $user_id = DB::getPdo()->lastInsertId(); + DB::insert('INSERT INTO `UserGroups` (`uid`, `group_id`) VALUES (?, -2)', [$user_id]); set_password($user_id, $_REQUEST['password']); // Assign angel-types $user_angel_types_info = []; foreach ($selected_angel_types as $selected_angel_type_id) { - sql_query("INSERT INTO `UserAngelTypes` SET `user_id`='" . sql_escape($user_id) . "', `angeltype_id`='" . sql_escape($selected_angel_type_id) . "'"); + DB::insert( + 'INSERT INTO `UserAngelTypes` (`user_id`, `angeltype_id`) VALUES (?, ?)', + [$user_id, $selected_angel_type_id] + ); $user_angel_types_info[] = $angel_types[$selected_angel_type_id]; } @@ -316,10 +345,10 @@ function guest_register() form_text('jabber', _('Jabber'), $jabber), div('row', [ div('col-sm-6', [ - form_text('prename', _('First name'), $prename) + form_text('prename', _('First name'), $preName) ]), div('col-sm-6', [ - form_text('lastname', _('Last name'), $lastname) + form_text('lastname', _('Last name'), $lastName) ]) ]), div('row', [ @@ -361,7 +390,7 @@ function guest_login() if (isset($_REQUEST['submit'])) { if (isset($_REQUEST['nick']) && strlen(User_validate_Nick($_REQUEST['nick'])) > 0) { $nick = User_validate_Nick($_REQUEST['nick']); - $login_user = sql_select("SELECT * FROM `User` WHERE `Nick`='" . sql_escape($nick) . "'"); + $login_user = DB::select('SELECT * FROM `User` WHERE `Nick`=?', [$nick]); if (count($login_user) > 0) { $login_user = $login_user[0]; if (isset($_REQUEST['password'])) { diff --git a/includes/pages/guest_stats.php b/includes/pages/guest_stats.php index c4e1af74..4add3e97 100644 --- a/includes/pages/guest_stats.php +++ b/includes/pages/guest_stats.php @@ -1,5 +1,7 @@ 0) { return ' ' . $new_messages . ''; } @@ -32,7 +37,10 @@ function user_messages() global $user; if (!isset($_REQUEST['action'])) { - $users = sql_select("SELECT * FROM `User` WHERE NOT `UID`='" . sql_escape($user['UID']) . "' ORDER BY `Nick`"); + $users = DB::select( + 'SELECT `UID`, `Nick` FROM `User` WHERE NOT `UID`=? ORDER BY `Nick`', + [$user['UID']] + ); $to_select_data = [ '' => _('Select recipient...') @@ -44,13 +52,18 @@ function user_messages() $to_select = html_select_key('to', 'to', $to_select_data, ''); - $messages = sql_select(" + $messages = DB::select(' SELECT * FROM `Messages` - WHERE `SUID`='" . sql_escape($user['UID']) . "' - OR `RUID`='" . sql_escape($user['UID']) . "' + WHERE `SUID`=? + OR `RUID`=? ORDER BY `isRead`,`Datum` DESC - "); + ', + [ + $user['UID'], + $user['UID'], + ] + ); $messages_table = [ [ @@ -116,9 +129,15 @@ function user_messages() return error(_('Incomplete call, missing Message ID.'), true); } - $message = sql_select("SELECT * FROM `Messages` WHERE `id`='" . sql_escape($message_id) . "' LIMIT 1"); + $message = DB::select( + 'SELECT `RUID` FROM `Messages` WHERE `id`=? LIMIT 1', + [$message_id] + ); if (count($message) > 0 && $message[0]['RUID'] == $user['UID']) { - sql_query("UPDATE `Messages` SET `isRead`='Y' WHERE `id`='" . sql_escape($message_id) . "' LIMIT 1"); + DB::update( + 'UPDATE `Messages` SET `isRead`=\'Y\' WHERE `id`=? LIMIT 1', + [$message_id] + ); redirect(page_link_to('user_messages')); } else { return error(_('No Message found.'), true); @@ -132,9 +151,12 @@ function user_messages() return error(_('Incomplete call, missing Message ID.'), true); } - $message = sql_select("SELECT * FROM `Messages` WHERE `id`='" . sql_escape($message_id) . "' LIMIT 1"); + $message = DB::select( + 'SELECT `SUID` FROM `Messages` WHERE `id`=? LIMIT 1', + [$message_id] + ); if (count($message) > 0 && $message[0]['SUID'] == $user['UID']) { - sql_query("DELETE FROM `Messages` WHERE `id`='" . sql_escape($message_id) . "' LIMIT 1"); + DB::delete('DELETE FROM `Messages` WHERE `id`=? LIMIT 1', [$message_id]); redirect(page_link_to('user_messages')); } else { return error(_('No Message found.'), true); @@ -142,7 +164,7 @@ function user_messages() break; case 'send': - if (Message_send($_REQUEST['to'], $_REQUEST['text']) === true) { + if (Message_send($_REQUEST['to'], $_REQUEST['text'])) { redirect(page_link_to('user_messages')); } else { return error(_('Transmitting was terminated with an Error.'), true); diff --git a/includes/pages/user_myshifts.php b/includes/pages/user_myshifts.php index 2079c789..76b79032 100644 --- a/includes/pages/user_myshifts.php +++ b/includes/pages/user_myshifts.php @@ -1,5 +1,7 @@ 0 + && count(DB::select('SELECT `UID` FROM `User` WHERE `UID`=?', [$_REQUEST['id']])) > 0 ) { $user_id = $_REQUEST['id']; } else { $user_id = $user['UID']; } - list($shifts_user) = sql_select("SELECT * FROM `User` WHERE `UID`='" . sql_escape($user_id) . "' LIMIT 1"); + $shifts_user = DB::select('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$user_id]); + $shifts_user = array_shift($shifts_user); if (isset($_REQUEST['reset'])) { if ($_REQUEST['reset'] == 'ack') { @@ -46,24 +49,32 @@ function user_myshifts() ]); } elseif (isset($_REQUEST['edit']) && preg_match('/^[0-9]*$/', $_REQUEST['edit'])) { $user_id = $_REQUEST['edit']; - $shift = sql_select("SELECT - `ShiftEntry`.`freeloaded`, - `ShiftEntry`.`freeload_comment`, - `ShiftEntry`.`Comment`, - `ShiftEntry`.`UID`, - `ShiftTypes`.`name`, - `Shifts`.*, - `Room`.`Name`, - `AngelTypes`.`name` AS `angel_type` - FROM `ShiftEntry` - JOIN `AngelTypes` ON (`ShiftEntry`.`TID` = `AngelTypes`.`id`) - JOIN `Shifts` ON (`ShiftEntry`.`SID` = `Shifts`.`SID`) - JOIN `ShiftTypes` ON (`ShiftTypes`.`id` = `Shifts`.`shifttype_id`) - JOIN `Room` ON (`Shifts`.`RID` = `Room`.`RID`) - WHERE `ShiftEntry`.`id`='" . sql_escape($user_id) . "' - AND `UID`='" . sql_escape($shifts_user['UID']) . "' LIMIT 1"); + $shift = DB::select(' + SELECT + `ShiftEntry`.`freeloaded`, + `ShiftEntry`.`freeload_comment`, + `ShiftEntry`.`Comment`, + `ShiftEntry`.`UID`, + `ShiftTypes`.`name`, + `Shifts`.*, + `Room`.`Name`, + `AngelTypes`.`name` AS `angel_type` + FROM `ShiftEntry` + JOIN `AngelTypes` ON (`ShiftEntry`.`TID` = `AngelTypes`.`id`) + JOIN `Shifts` ON (`ShiftEntry`.`SID` = `Shifts`.`SID`) + JOIN `ShiftTypes` ON (`ShiftTypes`.`id` = `Shifts`.`shifttype_id`) + JOIN `Room` ON (`Shifts`.`RID` = `Room`.`RID`) + WHERE `ShiftEntry`.`id`=? + AND `UID`=? + LIMIT 1 + ', + [ + $user_id, + $shifts_user['UID'], + ] + ); if (count($shift) > 0) { - $shift = $shift[0]; + $shift = array_shift($shift); $freeloaded = $shift['freeloaded']; $freeload_comment = $shift['freeload_comment']; @@ -120,13 +131,19 @@ function user_myshifts() } } elseif (isset($_REQUEST['cancel']) && preg_match('/^[0-9]*$/', $_REQUEST['cancel'])) { $user_id = $_REQUEST['cancel']; - $shift = sql_select(" - SELECT * - FROM `Shifts` - INNER JOIN `ShiftEntry` USING (`SID`) - WHERE `ShiftEntry`.`id`='" . sql_escape($user_id) . "' AND `UID`='" . sql_escape($shifts_user['UID']) . "'"); + $shift = DB::select(' + SELECT * + FROM `Shifts` + INNER JOIN `ShiftEntry` USING (`SID`) + WHERE `ShiftEntry`.`id`=? AND `UID`=? + ', + [ + $user_id, + $shifts_user['UID'], + ] + ); if (count($shift) > 0) { - $shift = $shift[0]; + $shift = array_shift($shift); if (($shift['start'] > time() + $last_unsubscribe * 3600) || in_array('user_shifts_admin', $privileges)) { $result = ShiftEntry_delete($user_id); if ($result === false) { diff --git a/includes/pages/user_news.php b/includes/pages/user_news.php index ceed75f2..3828e293 100644 --- a/includes/pages/user_news.php +++ b/includes/pages/user_news.php @@ -1,5 +1,7 @@ ' . '
    '; for ($i = 0; $i < $dis_rows; $i++) { if (isset($_REQUEST['page']) && $i == $_REQUEST['page']) { @@ -98,7 +102,7 @@ function display_news($news) . ' ' . _('Comments') . ' » ' . '' - . sql_num_query("SELECT * FROM `NewsComments` WHERE `Refid`='" . sql_escape($news['ID']) . "'") + . count(DB::select('SELECT `ID` FROM `NewsComments` WHERE `Refid`=?', [$news['ID']])) . ''; } $html .= ''; @@ -117,28 +121,34 @@ function user_news_comments() if ( isset($_REQUEST['nid']) && preg_match('/^[0-9]{1,}$/', $_REQUEST['nid']) - && sql_num_query("SELECT * FROM `News` WHERE `ID`='" . sql_escape($_REQUEST['nid']) . "' LIMIT 1") > 0 + && count(DB::select('SELECT `ID` FROM `News` WHERE `ID`=? LIMIT 1', [$_REQUEST['nid']])) > 0 ) { $nid = $_REQUEST['nid']; - list($news) = sql_select("SELECT * FROM `News` WHERE `ID`='" . sql_escape($nid) . "' LIMIT 1"); + $news = DB::select('SELECT * FROM `News` WHERE `ID`=? LIMIT 1', [$nid]); + $news = array_shift($news); if (isset($_REQUEST['text'])) { $text = preg_replace("/([^\p{L}\p{P}\p{Z}\p{N}\n]{1,})/ui", '', strip_tags($_REQUEST['text'])); - sql_query(" - INSERT INTO `NewsComments` (`Refid`, `Datum`, `Text`, `UID`) - VALUES ( - '" . sql_escape($nid) . "', - '" . date("Y-m-d H:i:s") . "', - '" . sql_escape($text) . "', - '" . sql_escape($user["UID"]) . "' - ) - "); + DB::insert(' + INSERT INTO `NewsComments` (`Refid`, `Datum`, `Text`, `UID`) + VALUES (?, ?, ?, ?) + ', + [ + $nid, + date("Y-m-d H:i:s"), + $text, + $user["UID"], + ] + ); engelsystem_log('Created news_comment: ' . $text); $html .= success(_('Entry saved.'), true); } $html .= display_news($news); - $comments = sql_select("SELECT * FROM `NewsComments` WHERE `Refid`='" . sql_escape($nid) . "' ORDER BY 'ID'"); + $comments = DB::select( + 'SELECT * FROM `NewsComments` WHERE `Refid`=? ORDER BY \'ID\'', + [$nid] + ); foreach ($comments as $comment) { $user_source = User($comment['UID']); @@ -176,16 +186,18 @@ function user_news() if (!isset($_POST['treffen']) || !in_array('admin_news', $privileges)) { $_POST['treffen'] = 0; } - sql_query(" + DB::insert(' INSERT INTO `News` (`Datum`, `Betreff`, `Text`, `UID`, `Treffen`) - VALUES ( - '" . sql_escape(time()) . "', - '" . sql_escape($_POST["betreff"]) . "', - '" . sql_escape($_POST["text"]) . "', - '" . sql_escape($user['UID']) . "', - '" . sql_escape($_POST["treffen"]) . "' - ) - "); + VALUES (?, ?, ?, ?, ?) + ', + [ + time(), + $_POST['betreff'], + $_POST['text'], + $user['UID'], + $_POST['treffen'], + ] + ); engelsystem_log('Created news: ' . $_POST['betreff'] . ', treffen: ' . $_POST['treffen']); success(_('Entry saved.')); redirect(page_link_to('news')); @@ -197,17 +209,20 @@ function user_news() $page = 0; } - $news = sql_select(" - SELECT * - FROM `News` - ORDER BY `Datum` - DESC LIMIT " . sql_escape($page * $display_news) . ", " . sql_escape($display_news) - ); + $news = DB::select(sprintf(' + SELECT * + FROM `News` + ORDER BY `Datum` + DESC LIMIT %u, %u + ', + $page * $display_news, + $display_news + )); foreach ($news as $entry) { $html .= display_news($entry); } - $dis_rows = ceil(sql_num_query('SELECT * FROM `News`') / $display_news); + $dis_rows = ceil(count(DB::select('SELECT `ID` FROM `News`')) / $display_news); $html .= '
    ' . '
      '; for ($i = 0; $i < $dis_rows; $i++) { if (isset($_REQUEST['page']) && $i == $_REQUEST['page']) { diff --git a/includes/pages/user_questions.php b/includes/pages/user_questions.php index b8ebe92d..04ae8914 100644 --- a/includes/pages/user_questions.php +++ b/includes/pages/user_questions.php @@ -1,5 +1,7 @@ 0 && $question[0]['UID'] == $user['UID']) { - sql_query("DELETE FROM `Questions` WHERE `QID`='" . sql_escape($question_id) . "' LIMIT 1"); + DB::delete( + 'DELETE FROM `Questions` WHERE `QID`=? LIMIT 1', + [$question_id] + ); redirect(page_link_to('user_questions')); } else { return page_with_title(questions_title(), [ diff --git a/includes/pages/user_settings.php b/includes/pages/user_settings.php index b848ff5f..5d4ba368 100644 --- a/includes/pages/user_settings.php +++ b/includes/pages/user_settings.php @@ -1,5 +1,7 @@ 0) { // User ist eingeloggt, Datensatz zur Verfügung stellen und Timestamp updaten - list($user) = $user; - sql_query(" + $user = array_shift($user); + DB::update(' UPDATE `User` - SET " . "`lastLogIn` = '" . time() . "'" . " - WHERE `UID` = '" . sql_escape($_SESSION['uid']) . "' + SET `lastLogIn` = ? + WHERE `UID` = ? LIMIT 1 - "); + ', [ + time(), + $_SESSION['uid'], + ]); $privileges = privileges_for_user($user['UID']); return; } @@ -50,19 +55,24 @@ function generate_salt($length = 16) * * @param int $uid * @param string $password - * @return mysqli_result + * @return bool */ function set_password($uid, $password) { global $crypt_alg; - $result = sql_query(" + $result = DB::update(' UPDATE `User` - SET `Passwort` = '" . sql_escape(crypt($password, $crypt_alg . '$' . generate_salt(16) . '$')) . "', + SET `Passwort` = ?, `password_recovery_token`=NULL - WHERE `UID` = " . intval($uid) . " + WHERE `UID` = ? LIMIT 1 - "); - if ($result === false) { + ', + [ + crypt($password, $crypt_alg . '$' . generate_salt(16) . '$'), + $uid + ] + ); + if (DB::getStm()->errorCode() != '00000') { engelsystem_error('Unable to update password.'); } return $result; @@ -93,13 +103,19 @@ function verify_password($password, $salt, $uid = null) // this password is stored in another format than we want it to be. // let's update it! // we duplicate the query from the above set_password() function to have the extra safety of checking the old hash - sql_query(" - UPDATE `User` - SET `Passwort` = '" . sql_escape(crypt($password, $crypt_alg . '$' . generate_salt() . '$')) . "' - WHERE `UID` = " . intval($uid) . " - AND `Passwort` = '" . sql_escape($salt) . "' - LIMIT 1 - "); + DB::update(' + UPDATE `User` + SET `Passwort` = ? + WHERE `UID` = ? + AND `Passwort` = ? + LIMIT 1 + ', + [ + crypt($password, $crypt_alg . '$' . generate_salt() . '$'), + $uid, + $salt, + ] + ); } return $correct; } @@ -111,16 +127,16 @@ function verify_password($password, $salt, $uid = null) function privileges_for_user($user_id) { $privileges = []; - $user_privs = sql_select(" + $user_privileges = DB::select(' SELECT `Privileges`.`name` FROM `User` JOIN `UserGroups` ON (`User`.`UID` = `UserGroups`.`uid`) JOIN `GroupPrivileges` ON (`UserGroups`.`group_id` = `GroupPrivileges`.`group_id`) JOIN `Privileges` ON (`GroupPrivileges`.`privilege_id` = `Privileges`.`id`) - WHERE `User`.`UID`='" . sql_escape($user_id) . "' - "); - foreach ($user_privs as $user_priv) { - $privileges[] = $user_priv['name']; + WHERE `User`.`UID`=? + ', [$user_id]); + foreach ($user_privileges as $user_privilege) { + $privileges[] = $user_privilege['name']; } return $privileges; } @@ -132,14 +148,14 @@ function privileges_for_user($user_id) function privileges_for_group($group_id) { $privileges = []; - $groups_privs = sql_select(" - SELECT * + $groups_privileges = DB::select(' + SELECT `name` FROM `GroupPrivileges` JOIN `Privileges` ON (`GroupPrivileges`.`privilege_id` = `Privileges`.`id`) - WHERE `group_id`='" . sql_escape($group_id) . "' - "); - foreach ($groups_privs as $guest_priv) { - $privileges[] = $guest_priv['name']; + WHERE `group_id`=? + ', [$group_id]); + foreach ($groups_privileges as $guest_privilege) { + $privileges[] = $guest_privilege['name']; } return $privileges; } diff --git a/includes/sys_log.php b/includes/sys_log.php index b253d6ad..c4ef890e 100644 --- a/includes/sys_log.php +++ b/includes/sys_log.php @@ -16,25 +16,3 @@ function engelsystem_log($message) } LogEntry_create($nick, $message); } - -/** - * Generates a PHP Stacktrace. - * - * @return string - */ -function debug_string_backtrace() -{ - ob_start(); - debug_print_backtrace(); - $trace = ob_get_contents(); - ob_end_clean(); - - // Remove first item from backtrace as it's this function which - // is redundant. - $trace = preg_replace('/^#0\s+' . __FUNCTION__ . "[^\n]*\n/", '', $trace, 1); - - // Renumber backtrace items. - // $trace = preg_replace('/^#(\d+)/me', '\'#\' . ($1 - 1)', $trace); - - return $trace; -} diff --git a/includes/sys_page.php b/includes/sys_page.php index 7bc2b9cb..fd03e291 100644 --- a/includes/sys_page.php +++ b/includes/sys_page.php @@ -61,7 +61,7 @@ function redirect($url) * * @param String $output String to display */ -function raw_output($output) +function raw_output($output = '') { echo $output; die(); @@ -78,11 +78,11 @@ function raw_output($output) */ function select_array($data, $key_name, $value_name) { - $ret = []; + $return = []; foreach ($data as $value) { - $ret[$value[$key_name]] = $value[$value_name]; + $return[$value[$key_name]] = $value[$value_name]; } - return $ret; + return $return; } /** diff --git a/includes/view/User_view.php b/includes/view/User_view.php index ca32b80e..832569a6 100644 --- a/includes/view/User_view.php +++ b/includes/view/User_view.php @@ -282,26 +282,25 @@ function Users_table_header_link($column, $label, $order_by) function User_shift_state_render($user) { $upcoming_shifts = ShiftEntries_upcoming_for_user($user); - if ($upcoming_shifts === false) { - return false; - } - if (count($upcoming_shifts) == 0) { + if (empty($upcoming_shifts)) { return '' . _('Free') . ''; } - if ($upcoming_shifts[0]['start'] > time()) { - if ($upcoming_shifts[0]['start'] - time() > 3600) { - return '' . _('Next shift %c') . ''; + $nextShift = array_shift($upcoming_shifts); + + if ($nextShift['start'] > time()) { + if ($nextShift['start'] - time() > 3600) { + return '' . _('Next shift %c') . ''; } - return '' . _('Next shift %c') . ''; + return '' . _('Next shift %c') . ''; } - $halfway = ($upcoming_shifts[0]['start'] + $upcoming_shifts[0]['end']) / 2; + $halfway = ($nextShift['start'] + $nextShift['end']) / 2; if (time() < $halfway) { - return '' . _('Shift starts %c') . ''; + return '' . _('Shift starts %c') . ''; } - return '' . _('Shift ends %c') . ''; + return '' . _('Shift ends %c') . ''; } /** diff --git a/src/Database/Db.php b/src/Database/Db.php new file mode 100644 index 00000000..c1efa058 --- /dev/null +++ b/src/Database/Db.php @@ -0,0 +1,170 @@ +prepare($query); + self::$lastStatus = self::$stm->execute($bindings); + + return self::$stm; + } + + /** + * Run a sql query + * + * @param string $query + * @return bool + */ + public static function unprepared($query) + { + self::$stm = self::$db->query($query); + self::$lastStatus = (self::$stm instanceof PDOStatement); + + return self::$lastStatus; + } + + /** + * Run a select query + * + * @param string $query + * @param array $bindings + * @return array + */ + public static function select($query, array $bindings = []) + { + self::query($query, $bindings); + + return self::$stm->fetchAll(PDO::FETCH_ASSOC); + } + + /** + * Run a insert query + * + * @param string $query + * @param array $bindings + * @return bool + */ + public static function insert($query, array $bindings = []) + { + self::query($query, $bindings); + + return self::$lastStatus; + } + + /** + * Run a update query + * + * @param string $query + * @param array $bindings + * @return int|null + */ + public static function update($query, array $bindings = []) + { + self::query($query, $bindings); + + return (self::$lastStatus ? self::$stm->rowCount() : null); + } + + /** + * Run a delete query + * + * @param string $query + * @param array $bindings + * @return int|null + */ + public static function delete($query, array $bindings = []) + { + self::query($query, $bindings); + + return (self::$lastStatus ? self::$stm->rowCount() : null); + } + + /** + * Run a single statement + * + * @param string $query + * @param array $bindings + * @return bool + */ + public static function statement($query, array $bindings = []) + { + self::query($query, $bindings); + + return self::$lastStatus; + } + + /** + * Returns the last error + * + * @return array + */ + public static function getError() + { + if (!self::$stm instanceof PDOStatement) { + return [-1, null, null]; + } + + return self::$stm->errorInfo(); + } + + /** + * Get the PDO instance + * + * @return PDO + */ + public static function getPdo() + { + return self::$db; + } + + /** + * @return PDOStatement|false|null + */ + public static function getStm() + { + return self::$stm; + } +} -- cgit v1.2.3-54-g00ecf From 8506d6d27e3b926521007064abcdcc2f69c6aa06 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Sat, 21 Jan 2017 23:07:20 +0100 Subject: Refactoring: Config cleanup / moved to class --- composer.json | 5 +- config/config.default.php | 170 ++++++++++++++---------- includes/controller/shifts_controller.php | 4 +- includes/controller/users_controller.php | 6 +- includes/engelsystem_provider.php | 82 ++++++++---- includes/helper/internationalization_helper.php | 12 +- includes/model/User_model.php | 7 +- includes/pages/admin_active.php | 5 +- includes/pages/admin_user.php | 9 +- includes/pages/guest_login.php | 14 +- includes/pages/guest_stats.php | 4 +- includes/pages/user_atom.php | 4 +- includes/pages/user_myshifts.php | 6 +- includes/pages/user_news.php | 6 +- includes/pages/user_settings.php | 16 ++- includes/sys_auth.php | 5 +- includes/view/AngelTypes_view.php | 4 +- includes/view/User_view.php | 34 ++--- public/index.php | 6 +- src/Config/Config.php | 128 ++++++++++++++++++ src/Exceptions/Handler.php | 8 +- src/helpers.php | 24 ++++ 22 files changed, 393 insertions(+), 166 deletions(-) create mode 100644 src/Config/Config.php create mode 100644 src/helpers.php (limited to 'src') diff --git a/composer.json b/composer.json index bb21de23..7655275c 100644 --- a/composer.json +++ b/composer.json @@ -21,6 +21,9 @@ "autoload": { "psr-4": { "Engelsystem\\": "src/" - } + }, + "files": [ + "src/helpers.php" + ] } } diff --git a/config/config.default.php b/config/config.default.php index bcfcc89c..437399e3 100644 --- a/config/config.default.php +++ b/config/config.default.php @@ -1,70 +1,106 @@ 2 AND HOUR(FROM_UNIXTIME(`Shifts`.`end`)) < 6) - OR (HOUR(FROM_UNIXTIME(`Shifts`.`start`)) > 2 AND HOUR(FROM_UNIXTIME(`Shifts`.`start`)) < 6) - OR (HOUR(FROM_UNIXTIME(`Shifts`.`start`)) <= 2 AND HOUR(FROM_UNIXTIME(`Shifts`.`end`)) >= 6) - ))*(`Shifts`.`end` - `Shifts`.`start`)*(1 - 3 * `ShiftEntry`.`freeloaded`) -)'; - -// voucher calculation -$voucher_settings = [ - 'initial_vouchers' => 2, - 'shifts_per_voucher' => 1 -]; - -// weigh every shift the same -// $shift_sum_formula = 'SUM(`end` - `start`)'; - -// For accessing stats -$api_key = ''; - -// MySQL-Connection Settings -$config = [ - 'host' => 'localhost', - 'user' => 'root', - 'pw' => '', - 'db' => 'engelsystem' +// To change settings create a config.php + +return [ + // MySQL-Connection Settings + 'database' => [ + 'host' => 'localhost', + 'user' => 'root', + 'pw' => '', + 'db' => 'engelsystem', + ], + + // For accessing stats + 'api_key' => '', + + // Enable maintenance mode (show a static page) + 'maintenance' => false, + + // Set to development to enable debugging messages + 'environment' => 'production', + + // URL to the angel faq and job description + 'faq_url' => 'https://events.ccc.de/congress/2013/wiki/Static:Volunteers', + + // Contact email address, linked on every page + 'contact_email' => 'mailto:ticket@c3heaven.de', + + // Default theme of the start page, 1=style1.css + 'default_theme' => 1, + + // Number of News shown on one site + 'display_news' => 6, + + // Anzahl Stunden bis zum Austragen eigener Schichten + 'last_unsubscribe' => 3, + + // Setzt den zu verwendenden Crypto-Algorismus (entsprechend der Dokumentation von crypt()). + // Falls ein Benutzerpasswort in einem anderen Format gespeichert ist, + // wird es bei der ersten Benutzung des Klartext-Passworts in das neue Format + // konvertiert. + // MD5 '$1' + // Blowfish '$2y$13' + // SHA-256 '$5$rounds=5000' + // SHA-512 '$6$rounds=5000' + 'crypt_alg' => '$6$rounds=5000', // SHA-512 + + 'min_password_length' => 8, + + // Wenn Engel beim Registrieren oder in ihrem Profil eine T-Shirt Größe angeben sollen, auf true setzen: + 'enable_tshirt_size' => true, + + // Number of shifts to freeload until angel is locked for shift signup. + 'max_freeloadable_shifts' => 2, + + // local timezone + 'timezone' => 'Europe/Berlin', + + // multiply 'night shifts' and freeloaded shifts (start or end between 2 and 6 exclusive) by 2 + 'shift_sum_formula' => ' + SUM( + (1 + + ( + (HOUR(FROM_UNIXTIME(`Shifts`.`end`)) > 2 AND HOUR(FROM_UNIXTIME(`Shifts`.`end`)) < 6) + OR (HOUR(FROM_UNIXTIME(`Shifts`.`start`)) > 2 AND HOUR(FROM_UNIXTIME(`Shifts`.`start`)) < 6) + OR (HOUR(FROM_UNIXTIME(`Shifts`.`start`)) <= 2 AND HOUR(FROM_UNIXTIME(`Shifts`.`end`)) >= 6) + ) + ) + * (`Shifts`.`end` - `Shifts`.`start`) + * (1 - 3 * `ShiftEntry`.`freeloaded`) + ) + ', + // weigh every shift the same + //'shift_sum_formula' => 'SUM(`end` - `start`)', + + // voucher calculation + 'voucher_settings' => [ + 'initial_vouchers' => 2, + 'shifts_per_voucher' => 1, + ], + + // Available locales in /locale/ + 'locales' => [ + 'de_DE.UTF-8' => 'Deutsch', + 'en_US.UTF-8' => 'English', + ], + + 'default_locale' => 'en_US.UTF-8', + + // Available T-Shirt sizes, set value to null if not available + 'tshirt_sizes' => [ + '' => _('Please select...'), + 'S' => 'S', + 'M' => 'M', + 'L' => 'L', + 'XL' => 'XL', + '2XL' => '2XL', + '3XL' => '3XL', + '4XL' => '4XL', + '5XL' => '5XL', + 'S-G' => 'S Girl', + 'M-G' => 'M Girl', + 'L-G' => 'L Girl', + 'XL-G' => 'XL Girl', + ], ]; diff --git a/includes/controller/shifts_controller.php b/includes/controller/shifts_controller.php index 71459a10..a1801de6 100644 --- a/includes/controller/shifts_controller.php +++ b/includes/controller/shifts_controller.php @@ -329,9 +329,9 @@ function shift_next_controller() */ function shifts_json_export_all_controller() { - global $api_key; + $api_key = config('api_key'); - if ($api_key == '') { + if (empty($api_key)) { engelsystem_error('Config contains empty apikey.'); } diff --git a/includes/controller/users_controller.php b/includes/controller/users_controller.php index b80fdb4d..84b6bbda 100644 --- a/includes/controller/users_controller.php +++ b/includes/controller/users_controller.php @@ -282,7 +282,6 @@ function users_list_controller() */ function user_password_recovery_set_new_controller() { - global $min_password_length; $user_source = User_by_password_recovery_token($_REQUEST['token']); if ($user_source == null) { error(_('Token is not correct.')); @@ -292,7 +291,10 @@ function user_password_recovery_set_new_controller() if (isset($_REQUEST['submit'])) { $valid = true; - if (isset($_REQUEST['password']) && strlen($_REQUEST['password']) >= $min_password_length) { + if ( + isset($_REQUEST['password']) + && strlen($_REQUEST['password']) >= config('min_password_length') + ) { if ($_REQUEST['password'] != $_REQUEST['password2']) { $valid = false; error(_('Your passwords don\'t match.')); diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index 3537f100..8a5723ef 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -1,5 +1,6 @@ set(require __DIR__ . '/../config/config.default.php'); + +if (file_exists(__DIR__ . '/../config/config.php')) { + $config->set(array_replace_recursive( + $config->get(null), + require __DIR__ . '/../config/config.php' + )); +} + +date_default_timezone_set($config->get('timezone')); + + +/** + * Check for maintenance + */ +if ($config->get('maintenance')) { + echo file_get_contents(__DIR__ . '/../public/maintenance.html'); + die(); +} + + +/** + * Register error handler + */ +$errorHandler = new ExceptionHandler(); +if (config('environment') == 'development') { + $errorHandler->setEnvironment(ExceptionHandler::ENV_DEVELOPMENT); + ini_set('display_errors', true); + error_reporting(E_ALL); +} else { + ini_set('display_errors', false); +} + + +/** + * Connect to database + */ +Db::connect( + 'mysql:host=' . config('database')['host'] . ';dbname=' . config('database')['db'] . ';charset=utf8', + config('database')['user'], + config('database')['pw'] +) || die('Error: Unable to connect to database'); +Db::getPdo()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + +/** + * Include legacy code + */ require_once realpath(__DIR__ . '/../includes/sys_auth.php'); require_once realpath(__DIR__ . '/../includes/sys_form.php'); require_once realpath(__DIR__ . '/../includes/sys_log.php'); @@ -71,17 +126,6 @@ require_once realpath(__DIR__ . '/../includes/helper/email_helper.php'); require_once realpath(__DIR__ . '/../includes/mailer/shifts_mailer.php'); require_once realpath(__DIR__ . '/../includes/mailer/users_mailer.php'); -$config = []; -require_once realpath(__DIR__ . '/../config/config.default.php'); -if (file_exists(realpath(__DIR__ . '/../config/config.php'))) { - require_once realpath(__DIR__ . '/../config/config.php'); -} - -if ($maintenance_mode) { - echo file_get_contents(__DIR__ . '/../public/maintenance.html'); - die(); -} - require_once realpath(__DIR__ . '/../includes/pages/admin_active.php'); require_once realpath(__DIR__ . '/../includes/pages/admin_arrive.php'); require_once realpath(__DIR__ . '/../includes/pages/admin_free.php'); @@ -100,20 +144,10 @@ require_once realpath(__DIR__ . '/../includes/pages/user_questions.php'); require_once realpath(__DIR__ . '/../includes/pages/user_settings.php'); require_once realpath(__DIR__ . '/../includes/pages/user_shifts.php'); -$errorHandler = new ExceptionHandler( - ($environment == 'development' - ? ExceptionHandler::ENV_DEVELOPMENT - : ExceptionHandler::ENV_PRODUCTION - ) -); - -Db::connect( - 'mysql:host=' . $config['host'] . ';dbname=' . $config['db'] . ';charset=utf8', - $config['user'], - $config['pw'] -) || die('Error: Unable to connect to database'); -Db::getPdo()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); +/** + * Init application + */ session_start(); gettext_init(); diff --git a/includes/helper/internationalization_helper.php b/includes/helper/internationalization_helper.php index 7c04ebbd..ed16de15 100644 --- a/includes/helper/internationalization_helper.php +++ b/includes/helper/internationalization_helper.php @@ -1,10 +1,4 @@ 'Deutsch', - 'en_US.UTF-8' => 'English' -]; - -$default_locale = 'en_US.UTF-8'; /** * Return currently active locale @@ -31,7 +25,8 @@ function locale_short() */ function gettext_init() { - global $locales, $default_locale; + $locales = config('locales'); + $default_locale = config('default_locale'); if (isset($_REQUEST['set_locale']) && isset($locales[$_REQUEST['set_locale']])) { $_SESSION['locale'] = $_REQUEST['set_locale']; @@ -67,11 +62,10 @@ function gettext_locale($locale = null) */ function make_langselect() { - global $locales; $url = $_SERVER['REQUEST_URI'] . (strpos($_SERVER['REQUEST_URI'], '?') > 0 ? '&' : '?') . 'set_locale='; $items = []; - foreach ($locales as $locale => $name) { + foreach (config('locales') as $locale => $name) { $items[] = toolbar_item_link( htmlspecialchars($url) . $locale, '', diff --git a/includes/model/User_model.php b/includes/model/User_model.php index 097e8faf..53b4ce1e 100644 --- a/includes/model/User_model.php +++ b/includes/model/User_model.php @@ -215,9 +215,9 @@ function Users($order_by = 'Nick') */ function User_is_freeloader($user) { - global $max_freeloadable_shifts, $user; + global $user; - return count(ShiftEntries_freeloaded_by_user($user)) >= $max_freeloadable_shifts; + return count(ShiftEntries_freeloaded_by_user($user)) >= config('max_freeloadable_shifts'); } /** @@ -542,8 +542,7 @@ function User_generate_password_recovery_token(&$user) */ function User_get_eligable_voucher_count(&$user) { - global $voucher_settings; - + $voucher_settings = config('voucher_settings'); $shifts_done = count(ShiftEntries_finished_by_user($user)); $earned_vouchers = $user['got_voucher'] - $voucher_settings['initial_vouchers']; diff --git a/includes/pages/admin_active.php b/includes/pages/admin_active.php index 275f50ba..8cb66e6e 100644 --- a/includes/pages/admin_active.php +++ b/includes/pages/admin_active.php @@ -15,7 +15,8 @@ function admin_active_title() */ function admin_active() { - global $tshirt_sizes, $shift_sum_formula; + $tshirt_sizes = config('tshirt_sizes'); + $shift_sum_formula = config('shift_sum_formula'); $msg = ''; $search = ''; @@ -208,7 +209,7 @@ function admin_active() $shirt_statistics = []; foreach (array_keys($tshirt_sizes) as $size) { - if ($size != '') { + if (!empty($size)) { $sc = DB::select( 'SELECT count(*) FROM `User` WHERE `Size`=? AND `Gekommen`=1', [$size] diff --git a/includes/pages/admin_user.php b/includes/pages/admin_user.php index 192becb0..2ab40cca 100644 --- a/includes/pages/admin_user.php +++ b/includes/pages/admin_user.php @@ -15,7 +15,14 @@ function admin_user_title() */ function admin_user() { - global $user, $tshirt_sizes, $privileges; + global $user, $privileges; + $tshirt_sizes = config('tshirt_sizes'); + + foreach ($tshirt_sizes as $key => $size) { + if (empty($size)) { + unset($tshirt_sizes[$key]); + } + } $html = ''; diff --git a/includes/pages/guest_login.php b/includes/pages/guest_login.php index 66a06116..2ffa4b98 100644 --- a/includes/pages/guest_login.php +++ b/includes/pages/guest_login.php @@ -33,8 +33,10 @@ function logout_title() */ function guest_register() { - global $tshirt_sizes, $enable_tshirt_size, $default_theme, $user, $min_password_length; - + global $user; + $tshirt_sizes = config('tshirt_sizes'); + $enable_tshirt_size = config('enable_tshirt_size'); + $min_password_length = config('min_password_length'); $event_config = EventConfig(); $msg = ''; @@ -65,6 +67,12 @@ function guest_register() } } + foreach ($tshirt_sizes as $key => $size) { + if (empty($size)) { + unset($tshirt_sizes[$key]); + } + } + if (isset($_REQUEST['submit'])) { $valid = true; @@ -201,7 +209,7 @@ function guest_register() VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, NULL, ?) ', [ - $default_theme, + config('default_theme'), $nick, $preName, $lastName, diff --git a/includes/pages/guest_stats.php b/includes/pages/guest_stats.php index 4add3e97..6b6f0572 100644 --- a/includes/pages/guest_stats.php +++ b/includes/pages/guest_stats.php @@ -4,10 +4,10 @@ use Engelsystem\Database\DB; function guest_stats() { - global $api_key; + $apiKey = config('api_key'); if (isset($_REQUEST['api_key'])) { - if ($_REQUEST['api_key'] == $api_key) { + if ($_REQUEST['api_key'] == $apiKey && !empty($apiKey)) { $stats = []; list($user_count) = DB::select('SELECT count(*) AS `user_count` FROM `User`'); diff --git a/includes/pages/user_atom.php b/includes/pages/user_atom.php index 3c4b631d..5574e8eb 100644 --- a/includes/pages/user_atom.php +++ b/includes/pages/user_atom.php @@ -7,7 +7,7 @@ use Engelsystem\Database\DB; */ function user_atom() { - global $user, $display_news; + global $user; if (!isset($_REQUEST['key']) || !preg_match('/^[\da-f]{32}$/', $_REQUEST['key'])) { engelsystem_error('Missing key.'); @@ -27,7 +27,7 @@ function user_atom() FROM `News` ' . (empty($_REQUEST['meetings']) ? '' : 'WHERE `Treffen` = 1 ') . ' ORDER BY `ID` - DESC LIMIT ' . (int)$display_news + DESC LIMIT ' . (int)config('display_news') ); $output = make_atom_entries_from_news($news); diff --git a/includes/pages/user_myshifts.php b/includes/pages/user_myshifts.php index acb78875..62d87d27 100644 --- a/includes/pages/user_myshifts.php +++ b/includes/pages/user_myshifts.php @@ -17,7 +17,6 @@ function myshifts_title() */ function user_myshifts() { - global $last_unsubscribe; global $user, $privileges; if ( @@ -144,7 +143,10 @@ function user_myshifts() ); if (count($shift) > 0) { $shift = array_shift($shift); - if (($shift['start'] > time() + $last_unsubscribe * 3600) || in_array('user_shifts_admin', $privileges)) { + if ( + ($shift['start'] > time() + config('last_unsubscribe') * 3600) + || in_array('user_shifts_admin', $privileges) + ) { $result = ShiftEntry_delete($user_id); if ($result === false) { engelsystem_error('Unable to delete shift entry.'); diff --git a/includes/pages/user_news.php b/includes/pages/user_news.php index 69d20e69..b1e337b6 100644 --- a/includes/pages/user_news.php +++ b/includes/pages/user_news.php @@ -31,8 +31,7 @@ function meetings_title() */ function user_meetings() { - global $display_news; - + $display_news = config('display_news'); $html = '

      ' . meetings_title() . '

      ' . msg(); if (isset($_REQUEST['page']) && preg_match('/^\d{1,}$/', $_REQUEST['page'])) { @@ -178,7 +177,8 @@ function user_news_comments() */ function user_news() { - global $display_news, $privileges, $user; + global $privileges, $user; + $display_news = config('display_news'); $html = '

      ' . news_title() . '

      ' . msg(); diff --git a/includes/pages/user_settings.php b/includes/pages/user_settings.php index 5d4ba368..a2a486f4 100644 --- a/includes/pages/user_settings.php +++ b/includes/pages/user_settings.php @@ -97,13 +97,12 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) */ function user_settings_password($user_source) { - global $min_password_length; if ( !isset($_REQUEST['password']) || !verify_password($_REQUEST['password'], $user_source['Passwort'], $user_source['UID']) ) { error(_('-> not OK. Please try again.')); - } elseif (strlen($_REQUEST['new_password']) < $min_password_length) { + } elseif (strlen($_REQUEST['new_password']) < config('min_password_length')) { error(_('Your password is to short (please use at least 6 characters).')); } elseif ($_REQUEST['new_password'] != $_REQUEST['new_password2']) { error(_('Your passwords don\'t match.')); @@ -195,8 +194,11 @@ function user_settings_locale($user_source, $locales) */ function user_settings() { - global $enable_tshirt_size, $tshirt_sizes, $themes, $locales; - global $user; + global $themes, $user; + + $enable_tshirt_size = config('enable_tshirt_size'); + $tshirt_sizes = config('tshirt_sizes'); + $locales = config('locales'); $buildup_start_date = null; $teardown_end_date = null; @@ -210,6 +212,12 @@ function user_settings() } } + foreach ($tshirt_sizes as $key => $size) { + if (empty($size)) { + unset($tshirt_sizes[$key]); + } + } + $user_source = $user; if (isset($_REQUEST['submit'])) { diff --git a/includes/sys_auth.php b/includes/sys_auth.php index 083c1b8d..856ed4ab 100644 --- a/includes/sys_auth.php +++ b/includes/sys_auth.php @@ -59,7 +59,6 @@ function generate_salt($length = 16) */ function set_password($uid, $password) { - global $crypt_alg; $result = DB::update(' UPDATE `User` SET `Passwort` = ?, @@ -68,7 +67,7 @@ function set_password($uid, $password) LIMIT 1 ', [ - crypt($password, $crypt_alg . '$' . generate_salt(16) . '$'), + crypt($password, config('crypt_alg') . '$' . generate_salt(16) . '$'), $uid ] ); @@ -89,7 +88,7 @@ function set_password($uid, $password) */ function verify_password($password, $salt, $uid = null) { - global $crypt_alg; + $crypt_alg = config('crypt_alg'); $correct = false; if (substr($salt, 0, 1) == '$') { // new-style crypt() $correct = crypt($password, $salt) == $salt; diff --git a/includes/view/AngelTypes_view.php b/includes/view/AngelTypes_view.php index be866c9b..bd258d3a 100644 --- a/includes/view/AngelTypes_view.php +++ b/includes/view/AngelTypes_view.php @@ -443,14 +443,12 @@ function AngelTypes_about_view_angeltype($angeltype) */ function AngelTypes_about_view($angeltypes, $user_logged_in) { - global $faq_url; - $content = [ buttons([ !$user_logged_in ? button(page_link_to('register'), register_title()) : '', !$user_logged_in ? button(page_link_to('login'), login_title()) : '', $user_logged_in ? button(page_link_to('angeltypes'), angeltypes_title(), 'back') : '', - button($faq_url, _('FAQ'), 'btn-primary') + button(config('faq_url'), _('FAQ'), 'btn-primary') ]), '

      ' . _('Here is the list of teams and their tasks. If you have questions, read the FAQ.') . '

      ', '
      ' diff --git a/includes/view/User_view.php b/includes/view/User_view.php index 50c54f5a..932614a7 100644 --- a/includes/view/User_view.php +++ b/includes/view/User_view.php @@ -1,24 +1,5 @@ _('Please select...'), - 'S' => 'S', - 'M' => 'M', - 'L' => 'L', - 'XL' => 'XL', - '2XL' => '2XL', - '3XL' => '3XL', - '4XL' => '4XL', - '5XL' => '5XL', - 'S-G' => 'S Girl', - 'M-G' => 'M Girl', - 'L-G' => 'L Girl', - 'XL-G' => 'XL Girl' -]; - /** * Renders user settings page * @@ -335,7 +316,7 @@ function User_view_shiftentries($needed_angel_type) */ function User_view_myshift($shift, $user_source, $its_me) { - global $last_unsubscribe, $privileges; + global $privileges; $shift_info = '' . $shift['name'] . ''; if ($shift['title']) { @@ -371,7 +352,10 @@ function User_view_myshift($shift, $user_source, $its_me) 'btn-xs' ); } - if (($shift['start'] > time() + $last_unsubscribe * 3600) || in_array('user_shifts_admin', $privileges)) { + if ( + ($shift['start'] > time() + config('last_unsubscribe') * 3600) + || in_array('user_shifts_admin', $privileges) + ) { $myshift['actions'][] = button( page_link_to('user_myshifts') . ((!$its_me) ? '&id=' . $user_source['UID'] : '') . '&cancel=' . $shift['id'], glyph('trash') . _('sign off'), @@ -646,12 +630,12 @@ function render_user_departure_date_hint() */ function render_user_freeloader_hint() { - global $user, $max_freeloadable_shifts; + global $user; if (User_is_freeloader($user)) { return sprintf( _('You freeloaded at least %s shifts. Shift signup is locked. Please go to heavens desk to be unlocked again.'), - $max_freeloadable_shifts + config('max_freeloadable_shifts') ); } @@ -679,9 +663,9 @@ function render_user_arrived_hint() */ function render_user_tshirt_hint() { - global $enable_tshirt_size, $user; + global $user; - if ($enable_tshirt_size && $user['Size'] == '') { + if (config('enable_tshirt_size') && $user['Size'] == '') { return _('You need to specify a tshirt size in your settings!'); } diff --git a/public/index.php b/public/index.php index 12d6f744..4e5dab03 100644 --- a/public/index.php +++ b/public/index.php @@ -169,7 +169,7 @@ if ( $event_config = EventConfig(); echo template_render(__DIR__ . '/../templates/layout.html', [ - 'theme' => isset($user) ? $user['color'] : $default_theme, + 'theme' => isset($user) ? $user['color'] : config('default_theme'), 'title' => $title, 'atom_link' => ($page == 'news' || $page == 'user_meetings') ? ' '; echo sprintf('%s: (%s)' . PHP_EOL, ucfirst($type), $number); var_export([ 'string' => $string, 'file' => $file . ':' . $line, - 'context' => ($this->environment == self::ENV_DEBUGGING ? $context : null), + 'context' => ($this->environment == self::ENV_DEVELOPMENT ? $context : null), ]); echo ''; die(); diff --git a/src/helpers.php b/src/helpers.php new file mode 100644 index 00000000..aeb256e9 --- /dev/null +++ b/src/helpers.php @@ -0,0 +1,24 @@ +set($key); + } + + return Config::getInstance()->get($key, $default); +} -- cgit v1.2.3-54-g00ecf From 3a1e4602492cec1c8f3d2aabab2c866022f43bf1 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 18 Jul 2017 21:38:53 +0200 Subject: Changed $_GET, $_POST and $_REQUEST to use the Request object --- includes/controller/angeltypes_controller.php | 22 +++-- includes/controller/event_config_controller.php | 7 +- includes/controller/rooms_controller.php | 15 +-- includes/controller/shift_entries_controller.php | 30 +++--- includes/controller/shifts_controller.php | 54 +++++----- includes/controller/shifttypes_controller.php | 35 ++++--- includes/controller/user_angeltypes_controller.php | 49 ++++----- .../controller/user_driver_licenses_controller.php | 24 ++--- includes/controller/users_controller.php | 72 ++++++++------ includes/engelsystem_provider.php | 8 ++ includes/helper/internationalization_helper.php | 8 +- includes/pages/admin_active.php | 27 ++--- includes/pages/admin_arrive.php | 12 ++- includes/pages/admin_free.php | 16 +-- includes/pages/admin_groups.php | 21 ++-- includes/pages/admin_import.php | 48 ++++----- includes/pages/admin_log.php | 2 +- includes/pages/admin_news.php | 17 ++-- includes/pages/admin_questions.php | 15 +-- includes/pages/admin_rooms.php | 36 +++---- includes/pages/admin_shifts.php | 69 ++++++------- includes/pages/admin_user.php | 58 +++++------ includes/pages/guest_login.php | 63 ++++++------ includes/pages/guest_stats.php | 5 +- includes/pages/user_atom.php | 9 +- includes/pages/user_ical.php | 5 +- includes/pages/user_messages.php | 16 +-- includes/pages/user_myshifts.php | 25 ++--- includes/pages/user_news.php | 47 +++++---- includes/pages/user_questions.php | 9 +- includes/pages/user_settings.php | 55 ++++++----- includes/pages/user_shifts.php | 9 +- includes/sys_page.php | 35 ++++--- includes/sys_template.php | 6 +- public/index.php | 16 ++- src/Http/Request.php | 110 +++++++++++++++++++++ src/helpers.php | 17 ++++ 37 files changed, 643 insertions(+), 429 deletions(-) create mode 100644 src/Http/Request.php (limited to 'src') diff --git a/includes/controller/angeltypes_controller.php b/includes/controller/angeltypes_controller.php index daa754eb..346a4d73 100644 --- a/includes/controller/angeltypes_controller.php +++ b/includes/controller/angeltypes_controller.php @@ -81,7 +81,7 @@ function angeltype_delete_controller() $angeltype = load_angeltype(); - if (isset($_REQUEST['confirmed'])) { + if (request()->has('confirmed')) { AngelType_delete($angeltype); success(sprintf(_('Angeltype %s deleted.'), AngelType_name_render($angeltype))); redirect(page_link_to('angeltypes')); @@ -104,8 +104,9 @@ function angeltype_edit_controller() // In supporter mode only allow to modify description $supporter_mode = !in_array('admin_angel_types', $privileges); + $request = request(); - if (isset($_REQUEST['angeltype_id'])) { + if ($request->has('angeltype_id')) { // Edit existing angeltype $angeltype = load_angeltype(); @@ -121,12 +122,12 @@ function angeltype_edit_controller() $angeltype = AngelType_new(); } - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { $valid = true; if (!$supporter_mode) { - if (isset($_REQUEST['name'])) { - $result = AngelType_validate_name($_REQUEST['name'], $angeltype); + if ($request->has('name')) { + $result = AngelType_validate_name($request->get('name'), $angeltype); $angeltype['name'] = $result->getValue(); if (!$result->isValid()) { $valid = false; @@ -134,10 +135,10 @@ function angeltype_edit_controller() } } - $angeltype['restricted'] = isset($_REQUEST['restricted']); - $angeltype['no_self_signup'] = isset($_REQUEST['no_self_signup']); + $angeltype['restricted'] = $request->has('restricted'); + $angeltype['no_self_signup'] = $request->has('no_self_signup'); - $angeltype['requires_driver_license'] = isset($_REQUEST['requires_driver_license']); + $angeltype['requires_driver_license'] = $request->has('requires_driver_license'); } $angeltype['description'] = strip_request_item_nl('description', $angeltype['description']); @@ -262,11 +263,12 @@ function angeltypes_list_controller() */ function load_angeltype() { - if (!isset($_REQUEST['angeltype_id'])) { + $request = request(); + if (!$request->has('angeltype_id')) { redirect(page_link_to('angeltypes')); } - $angeltype = AngelType($_REQUEST['angeltype_id']); + $angeltype = AngelType($request->input('angeltype_id')); if ($angeltype == null) { error(_('Angeltype doesn\'t exist . ')); redirect(page_link_to('angeltypes')); diff --git a/includes/controller/event_config_controller.php b/includes/controller/event_config_controller.php index 06245c47..dcdcf54a 100644 --- a/includes/controller/event_config_controller.php +++ b/includes/controller/event_config_controller.php @@ -19,6 +19,7 @@ function event_config_edit_controller() redirect('?'); } + $request = request(); $event_name = null; $event_welcome_msg = null; $buildup_start_date = null; @@ -36,17 +37,17 @@ function event_config_edit_controller() $event_welcome_msg = $event_config['event_welcome_msg']; } - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { $valid = true; - if (isset($_REQUEST['event_name'])) { + if ($request->has('event_name')) { $event_name = strip_request_item('event_name'); } if ($event_name == '') { $event_name = null; } - if (isset($_REQUEST['event_welcome_msg'])) { + if ($request->has('event_welcome_msg')) { $event_welcome_msg = strip_request_item_nl('event_welcome_msg'); } if ($event_welcome_msg == '') { diff --git a/includes/controller/rooms_controller.php b/includes/controller/rooms_controller.php index 3082a28d..2d6f1a77 100644 --- a/includes/controller/rooms_controller.php +++ b/includes/controller/rooms_controller.php @@ -19,6 +19,7 @@ function room_controller() redirect(page_link_to()); } + $request = request(); $room = load_room(false); if ($room['show'] != 'Y' && !in_array('admin_rooms', $privileges)) { redirect(page_link_to()); @@ -42,8 +43,8 @@ function room_controller() if (!empty($days)) { $selected_day = $days[0]; } - if (isset($_REQUEST['shifts_filter_day'])) { - $selected_day = $_REQUEST['shifts_filter_day']; + if ($request->has('shifts_filter_day')) { + $selected_day = $request->input('shifts_filter_day'); } $shiftsFilter->setStartTime(parse_date('Y-m-d H:i', $selected_day . ' 00:00')); $shiftsFilter->setEndTime(parse_date('Y-m-d H:i', $selected_day . ' 23:59')); @@ -66,11 +67,13 @@ function room_controller() */ function rooms_controller() { - if (!isset($_REQUEST['action'])) { - $_REQUEST['action'] = 'list'; + $request = request(); + $action = $request->input('action'); + if (!$request->has('action')) { + $action = 'list'; } - switch ($_REQUEST['action']) { + switch ($action) { case 'view': return room_controller(); case 'list': @@ -112,7 +115,7 @@ function load_room($onlyVisible = true) redirect(page_link_to()); } - $room = Room($_REQUEST['room_id'], $onlyVisible); + $room = Room(request()->input('room_id'), $onlyVisible); if ($room == null) { redirect(page_link_to()); } diff --git a/includes/controller/shift_entries_controller.php b/includes/controller/shift_entries_controller.php index cb2d9bee..38aad5bb 100644 --- a/includes/controller/shift_entries_controller.php +++ b/includes/controller/shift_entries_controller.php @@ -11,9 +11,10 @@ function shift_entry_add_controller() { global $privileges, $user; + $request = request(); $shift_id = 0; - if (isset($_REQUEST['shift_id']) && preg_match('/^\d*$/', $_REQUEST['shift_id'])) { - $shift_id = $_REQUEST['shift_id']; + if ($request->has('shift_id') && preg_match('/^\d*$/', $request->input('shift_id'))) { + $shift_id = $request->input('shift_id'); } else { redirect(page_link_to('user_shifts')); } @@ -32,8 +33,8 @@ function shift_entry_add_controller() } $type_id = 0; - if (isset($_REQUEST['type_id']) && preg_match('/^\d*$/', $_REQUEST['type_id'])) { - $type_id = $_REQUEST['type_id']; + if ($request->has('type_id') && preg_match('/^\d*$/', $request->input('type_id'))) { + $type_id = $request->input('type_id'); } else { redirect(page_link_to('user_shifts')); } @@ -63,14 +64,14 @@ function shift_entry_add_controller() } if ( - isset($_REQUEST['user_id']) - && preg_match('/^\d*$/', $_REQUEST['user_id']) + $request->has('user_id') + && preg_match('/^\d*$/', $request->input('user_id')) && ( in_array('user_shifts_admin', $privileges) || in_array('shiftentry_edit_angeltype_supporter', $privileges) ) ) { - $user_id = $_REQUEST['user_id']; + $user_id = $request->input('user_id'); } else { $user_id = $user['UID']; } @@ -92,7 +93,7 @@ function shift_entry_add_controller() redirect(shift_link($shift)); } - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { $selected_type_id = $type_id; if (in_array('user_shifts_admin', $privileges) || in_array('shiftentry_edit_angeltype_supporter', $privileges) @@ -103,14 +104,14 @@ function shift_entry_add_controller() } if ( - isset($_REQUEST['angeltype_id']) + $request->has('angeltype_id') && test_request_int('angeltype_id') && count(DB::select( 'SELECT `id` FROM `AngelTypes` WHERE `id`=? LIMIT 1', - [$_REQUEST['angeltype_id']] + [$request->input('angeltype_id')] )) > 0 ) { - $selected_type_id = $_REQUEST['angeltype_id']; + $selected_type_id = $request->input('angeltype_id'); } } @@ -124,7 +125,7 @@ function shift_entry_add_controller() $freeloaded = isset($shift['freeloaded']) ? $shift['freeloaded'] : false; $freeload_comment = isset($shift['freeload_comment']) ? $shift['freeload_comment'] : ''; if (in_array('user_shifts_admin', $privileges)) { - $freeloaded = isset($_REQUEST['freeloaded']); + $freeloaded = $request->has('freeloaded'); $freeload_comment = strip_request_item_nl('freeload_comment'); } @@ -236,11 +237,12 @@ function shift_entry_add_controller() function shift_entry_delete_controller() { global $privileges, $user; + $request = request(); - if (!isset($_REQUEST['entry_id']) || !test_request_int('entry_id')) { + if (!$request->has('entry_id') || !test_request_int('entry_id')) { redirect(page_link_to('user_shifts')); } - $entry_id = $_REQUEST['entry_id']; + $entry_id = $request->input('entry_id'); $shift_entry_source = DB::select(' SELECT diff --git a/includes/controller/shifts_controller.php b/includes/controller/shifts_controller.php index c8b6932a..21c6e160 100644 --- a/includes/controller/shifts_controller.php +++ b/includes/controller/shifts_controller.php @@ -44,15 +44,16 @@ function shift_edit_controller() // Schicht bearbeiten $msg = ''; $valid = true; + $request = request(); if (!in_array('admin_shifts', $privileges)) { redirect(page_link_to('user_shifts')); } - if (!isset($_REQUEST['edit_shift']) || !test_request_int('edit_shift')) { + if (!$request->has('edit_shift') || !test_request_int('edit_shift')) { redirect(page_link_to('user_shifts')); } - $shift_id = $_REQUEST['edit_shift']; + $shift_id = $request->input('edit_shift'); $shift = Shift($shift_id); @@ -73,33 +74,37 @@ function shift_edit_controller() $start = $shift['start']; $end = $shift['end']; - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { // Name/Bezeichnung der Schicht, darf leer sein $title = strip_request_item('title'); // Auswahl der sichtbaren Locations für die Schichten - if (isset($_REQUEST['rid']) && preg_match('/^\d+$/', $_REQUEST['rid']) && isset($room[$_REQUEST['rid']])) { - $rid = $_REQUEST['rid']; + if ( + $request->has('rid') + && preg_match('/^\d+$/', $request->input('rid')) + && isset($room[$request->input('rid')]) + ) { + $rid = $request->input('rid'); } else { $valid = false; $msg .= error(_('Please select a room.'), true); } - if (isset($_REQUEST['shifttype_id']) && isset($shifttypes[$_REQUEST['shifttype_id']])) { - $shifttype_id = $_REQUEST['shifttype_id']; + if ($request->has('shifttype_id') && isset($shifttypes[$request->input('shifttype_id')])) { + $shifttype_id = $request->input('shifttype_id'); } else { $valid = false; $msg .= error(_('Please select a shifttype.'), true); } - if (isset($_REQUEST['start']) && $tmp = parse_date('Y-m-d H:i', $_REQUEST['start'])) { + if ($request->has('start') && $tmp = parse_date('Y-m-d H:i', $request->input('start'))) { $start = $tmp; } else { $valid = false; $msg .= error(_('Please enter a valid starting time for the shifts.'), true); } - if (isset($_REQUEST['end']) && $tmp = parse_date('Y-m-d H:i', $_REQUEST['end'])) { + if ($request->has('end') && $tmp = parse_date('Y-m-d H:i', $request->input('end'))) { $end = $tmp; } else { $valid = false; @@ -112,8 +117,8 @@ function shift_edit_controller() } foreach ($needed_angel_types as $needed_angeltype_id => $needed_angeltype_name) { - if (isset($_REQUEST['type_' . $needed_angeltype_id]) && test_request_int('type_' . $needed_angeltype_id)) { - $needed_angel_types[$needed_angeltype_id] = trim($_REQUEST['type_' . $needed_angeltype_id]); + if ($request->has('type_' . $needed_angeltype_id) && test_request_int('type_' . $needed_angeltype_id)) { + $needed_angel_types[$needed_angeltype_id] = trim($request->input('type_' . $needed_angeltype_id)); } else { $valid = false; $msg .= error(sprintf( @@ -186,16 +191,17 @@ function shift_edit_controller() function shift_delete_controller() { global $privileges; + $request = request(); if (!in_array('user_shifts_admin', $privileges)) { redirect(page_link_to('user_shifts')); } // Schicht komplett löschen (nur für admins/user mit user_shifts_admin privileg) - if (!isset($_REQUEST['delete_shift']) || !preg_match('/^\d*$/', $_REQUEST['delete_shift'])) { + if (!$request->has('delete_shift') || !preg_match('/^\d*$/', $request->input('delete_shift'))) { redirect(page_link_to('user_shifts')); } - $shift_id = $_REQUEST['delete_shift']; + $shift_id = $request->input('delete_shift'); $shift = Shift($shift_id); if ($shift == null) { @@ -203,7 +209,7 @@ function shift_delete_controller() } // Schicht löschen bestätigt - if (isset($_REQUEST['delete'])) { + if ($request->has('delete')) { Shift_delete($shift_id); engelsystem_log( @@ -232,16 +238,17 @@ function shift_delete_controller() function shift_controller() { global $user, $privileges; + $request = request(); if (!in_array('user_shifts', $privileges)) { redirect(page_link_to('?')); } - if (!isset($_REQUEST['shift_id'])) { + if (!$request->has('shift_id')) { redirect(page_link_to('user_shifts')); } - $shift = Shift($_REQUEST['shift_id']); + $shift = Shift($request->input('shift_id')); if ($shift == null) { error(_('Shift could not be found.')); redirect(page_link_to('user_shifts')); @@ -285,11 +292,12 @@ function shift_controller() */ function shifts_controller() { - if (!isset($_REQUEST['action'])) { + $request = request(); + if (!$request->has('action')) { redirect(page_link_to('user_shifts')); } - switch ($_REQUEST['action']) { + switch ($request->input('action')) { case 'view': return shift_controller(); case 'next': @@ -330,16 +338,17 @@ function shift_next_controller() function shifts_json_export_all_controller() { $api_key = config('api_key'); + $request = request(); if (empty($api_key)) { engelsystem_error('Config contains empty apikey.'); } - if (!isset($_REQUEST['api_key'])) { + if (!$request->has('api_key')) { engelsystem_error('Missing parameter api_key.'); } - if ($_REQUEST['api_key'] != $api_key) { + if ($request->input('api_key') != $api_key) { engelsystem_error('Invalid api_key.'); } @@ -359,12 +368,13 @@ function shifts_json_export_all_controller() function shifts_json_export_controller() { global $user; + $request = request(); - if (!isset($_REQUEST['key']) || !preg_match('/^[\da-f]{32}$/', $_REQUEST['key'])) { + if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) { engelsystem_error('Missing key.'); } - $key = $_REQUEST['key']; + $key = $request->input('key'); $user = User_by_api_key($key); if ($user == null) { diff --git a/includes/controller/shifttypes_controller.php b/includes/controller/shifttypes_controller.php index 9a470e29..acdeb982 100644 --- a/includes/controller/shifttypes_controller.php +++ b/includes/controller/shifttypes_controller.php @@ -16,17 +16,18 @@ function shifttype_link($shifttype) */ function shifttype_delete_controller() { - if (!isset($_REQUEST['shifttype_id'])) { + $request = request(); + if (!$request->has('shifttype_id')) { redirect(page_link_to('shifttypes')); } - $shifttype = ShiftType($_REQUEST['shifttype_id']); + $shifttype = ShiftType($request->input('shifttype_id')); if ($shifttype == null) { redirect(page_link_to('shifttypes')); } - if (isset($_REQUEST['confirmed'])) { + if ($request->has('confirmed')) { $result = ShiftType_delete($shifttype['id']); if (empty($result)) { engelsystem_error('Unable to delete shifttype.'); @@ -56,9 +57,10 @@ function shifttype_edit_controller() $description = ''; $angeltypes = AngelTypes(); + $request = request(); - if (isset($_REQUEST['shifttype_id'])) { - $shifttype = ShiftType($_REQUEST['shifttype_id']); + if ($request->has('shifttype_id')) { + $shifttype = ShiftType($request->input('shifttype_id')); if ($shifttype == null) { error(_('Shifttype not found.')); redirect(page_link_to('shifttypes')); @@ -69,23 +71,23 @@ function shifttype_edit_controller() $description = $shifttype['description']; } - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { $valid = true; - if (isset($_REQUEST['name']) && $_REQUEST['name'] != '') { + if ($request->has('name') && $request->input('name') != '') { $name = strip_request_item('name'); } else { $valid = false; error(_('Please enter a name.')); } - if (isset($_REQUEST['angeltype_id']) && preg_match('/^\d+$/', $_REQUEST['angeltype_id'])) { - $angeltype_id = $_REQUEST['angeltype_id']; + if ($request->has('angeltype_id') && preg_match('/^\d+$/', $request->input('angeltype_id'))) { + $angeltype_id = $request->input('angeltype_id'); } else { $angeltype_id = null; } - if (isset($_REQUEST['description'])) { + if ($request->has('description')) { $description = strip_request_item_nl('description'); } @@ -120,10 +122,11 @@ function shifttype_edit_controller() */ function shifttype_controller() { - if (!isset($_REQUEST['shifttype_id'])) { + $request = request(); + if (!$request->has('shifttype_id')) { redirect(page_link_to('shifttypes')); } - $shifttype = ShiftType($_REQUEST['shifttype_id']); + $shifttype = ShiftType($request->input('shifttype_id')); if ($shifttype == null) { redirect(page_link_to('shifttypes')); } @@ -174,11 +177,13 @@ function shifttypes_title() */ function shifttypes_controller() { - if (!isset($_REQUEST['action'])) { - $_REQUEST['action'] = 'list'; + $request = request(); + $action = 'list'; + if ($request->has('action')) { + $action = $request->input('action'); } - switch ($_REQUEST['action']) { + switch ($action) { case 'view': return shifttype_controller(); case 'edit': diff --git a/includes/controller/user_angeltypes_controller.php b/includes/controller/user_angeltypes_controller.php index f31aeecd..41185552 100644 --- a/includes/controller/user_angeltypes_controller.php +++ b/includes/controller/user_angeltypes_controller.php @@ -38,13 +38,14 @@ function user_angeltypes_unconfirmed_hint() function user_angeltypes_delete_all_controller() { global $user; + $request = request(); - if (!isset($_REQUEST['angeltype_id'])) { + if (!$request->has('angeltype_id')) { error(_('Angeltype doesn\'t exist.')); redirect(page_link_to('angeltypes')); } - $angeltype = AngelType($_REQUEST['angeltype_id']); + $angeltype = AngelType($request->input('angeltype_id')); if ($angeltype == null) { error(_('Angeltype doesn\'t exist.')); redirect(page_link_to('angeltypes')); @@ -55,7 +56,7 @@ function user_angeltypes_delete_all_controller() redirect(page_link_to('angeltypes')); } - if (isset($_REQUEST['confirmed'])) { + if ($request->has('confirmed')) { UserAngelTypes_delete_all($angeltype['id']); engelsystem_log(sprintf('Denied all users for angeltype %s', AngelType_name_render($angeltype))); @@ -77,13 +78,14 @@ function user_angeltypes_delete_all_controller() function user_angeltypes_confirm_all_controller() { global $user, $privileges; + $request = request(); - if (!isset($_REQUEST['angeltype_id'])) { + if (!$request->has('angeltype_id')) { error(_('Angeltype doesn\'t exist.')); redirect(page_link_to('angeltypes')); } - $angeltype = AngelType($_REQUEST['angeltype_id']); + $angeltype = AngelType($request->input('angeltype_id')); if ($angeltype == null) { error(_('Angeltype doesn\'t exist.')); redirect(page_link_to('angeltypes')); @@ -100,7 +102,7 @@ function user_angeltypes_confirm_all_controller() redirect(page_link_to('angeltypes')); } - if (isset($_REQUEST['confirmed'])) { + if ($request->has('confirmed')) { UserAngelTypes_confirm_all($angeltype['id'], $user); engelsystem_log(sprintf('Confirmed all users for angeltype %s', AngelType_name_render($angeltype))); @@ -122,13 +124,14 @@ function user_angeltypes_confirm_all_controller() function user_angeltype_confirm_controller() { global $user; + $request = request(); - if (!isset($_REQUEST['user_angeltype_id'])) { + if (!$request->has('user_angeltype_id')) { error(_('User angeltype doesn\'t exist.')); redirect(page_link_to('angeltypes')); } - $user_angeltype = UserAngelType($_REQUEST['user_angeltype_id']); + $user_angeltype = UserAngelType($request->input('user_angeltype_id')); if ($user_angeltype == null) { error(_('User angeltype doesn\'t exist.')); redirect(page_link_to('angeltypes')); @@ -151,7 +154,7 @@ function user_angeltype_confirm_controller() redirect(page_link_to('angeltypes')); } - if (isset($_REQUEST['confirmed'])) { + if ($request->has('confirmed')) { UserAngelType_confirm($user_angeltype['id'], $user); engelsystem_log(sprintf( @@ -181,13 +184,14 @@ function user_angeltype_confirm_controller() function user_angeltype_delete_controller() { global $user; + $request = request(); - if (!isset($_REQUEST['user_angeltype_id'])) { + if (!$request->has('user_angeltype_id')) { error(_('User angeltype doesn\'t exist.')); redirect(page_link_to('angeltypes')); } - $user_angeltype = UserAngelType($_REQUEST['user_angeltype_id']); + $user_angeltype = UserAngelType($request->input('user_angeltype_id')); if ($user_angeltype == null) { error(_('User angeltype doesn\'t exist.')); redirect(page_link_to('angeltypes')); @@ -210,7 +214,7 @@ function user_angeltype_delete_controller() redirect(page_link_to('angeltypes')); } - if (isset($_REQUEST['confirmed'])) { + if ($request->has('confirmed')) { $result = UserAngelType_delete($user_angeltype); if ($result === false) { engelsystem_error('Unable to delete user angeltype.'); @@ -238,25 +242,26 @@ function user_angeltype_update_controller() { global $privileges; $supporter = false; + $request = request(); if (!in_array('admin_angel_types', $privileges)) { error(_('You are not allowed to set supporter rights.')); redirect(page_link_to('angeltypes')); } - if (!isset($_REQUEST['user_angeltype_id'])) { + if (!$request->has('user_angeltype_id')) { error(_('User angeltype doesn\'t exist.')); redirect(page_link_to('angeltypes')); } - if (isset($_REQUEST['supporter']) && preg_match('/^[01]$/', $_REQUEST['supporter'])) { - $supporter = $_REQUEST['supporter'] == '1'; + if ($request->has('supporter') && preg_match('/^[01]$/', $request->input('supporter'))) { + $supporter = $request->input('supporter') == '1'; } else { error(_('No supporter update given.')); redirect(page_link_to('angeltypes')); } - $user_angeltype = UserAngelType($_REQUEST['user_angeltype_id']); + $user_angeltype = UserAngelType($request->input('user_angeltype_id')); if ($user_angeltype == null) { error(_('User angeltype doesn\'t exist.')); redirect(page_link_to('angeltypes')); @@ -274,7 +279,7 @@ function user_angeltype_update_controller() redirect(page_link_to('angeltypes')); } - if (isset($_REQUEST['confirmed'])) { + if ($request->has('confirmed')) { UserAngelType_update($user_angeltype['id'], $supporter); $success_message = sprintf( @@ -300,7 +305,6 @@ function user_angeltype_update_controller() function user_angeltype_add_controller() { global $user; - $angeltype = load_angeltype(); // User is joining by itself @@ -316,7 +320,7 @@ function user_angeltype_add_controller() // Load possible users, that are not in the angeltype already $users_source = Users_by_angeltype_inverted($angeltype); - if (isset($_REQUEST['submit'])) { + if (request()->has('submit')) { $user_source = load_user(); if (!UserAngelType_exists($user_source, $angeltype)) { @@ -366,7 +370,7 @@ function user_angeltype_join_controller($angeltype) redirect(page_link_to('angeltypes')); } - if (isset($_REQUEST['confirmed'])) { + if (request()->has('confirmed')) { $user_angeltype_id = UserAngelType_create($user, $angeltype); $success_message = sprintf(_('You joined %s.'), $angeltype['name']); @@ -398,11 +402,12 @@ function user_angeltype_join_controller($angeltype) */ function user_angeltypes_controller() { - if (!isset($_REQUEST['action'])) { + $request = request(); + if (!$request->has('action')) { redirect(page_link_to('angeltypes')); } - switch ($_REQUEST['action']) { + switch ($request->input('action')) { case 'delete_all': return user_angeltypes_delete_all_controller(); case 'confirm_all': diff --git a/includes/controller/user_driver_licenses_controller.php b/includes/controller/user_driver_licenses_controller.php index 3098c8ce..fef278dd 100644 --- a/includes/controller/user_driver_licenses_controller.php +++ b/includes/controller/user_driver_licenses_controller.php @@ -74,11 +74,11 @@ function user_driver_license_edit_link($user = null) function user_driver_license_load_user() { global $user; - + $request = request(); $user_source = $user; - if (isset($_REQUEST['user_id'])) { - $user_source = User($_REQUEST['user_id']); + if ($request->has('user_id')) { + $user_source = User($request->input('user_id')); if ($user_source == null) { redirect(user_driver_license_edit_link()); } @@ -95,7 +95,7 @@ function user_driver_license_load_user() function user_driver_license_edit_controller() { global $privileges, $user; - + $request = request(); $user_source = user_driver_license_load_user(); // only privilege admin_user can edit other users driver license information @@ -111,15 +111,15 @@ function user_driver_license_edit_controller() $wants_to_drive = true; } - if (isset($_REQUEST['submit'])) { - $wants_to_drive = isset($_REQUEST['wants_to_drive']); + if ($request->has('submit')) { + $wants_to_drive = $request->has('wants_to_drive'); if ($wants_to_drive) { - $user_driver_license['has_car'] = isset($_REQUEST['has_car']); - $user_driver_license['has_license_car'] = isset($_REQUEST['has_license_car']); - $user_driver_license['has_license_3_5t_transporter'] = isset($_REQUEST['has_license_3_5t_transporter']); - $user_driver_license['has_license_7_5t_truck'] = isset($_REQUEST['has_license_7_5t_truck']); - $user_driver_license['has_license_12_5t_truck'] = isset($_REQUEST['has_license_12_5t_truck']); - $user_driver_license['has_license_forklift'] = isset($_REQUEST['has_license_forklift']); + $user_driver_license['has_car'] = $request->has('has_car'); + $user_driver_license['has_license_car'] = $request->has('has_license_car'); + $user_driver_license['has_license_3_5t_transporter'] = $request->has('has_license_3_5t_transporter'); + $user_driver_license['has_license_7_5t_truck'] = $request->has('has_license_7_5t_truck'); + $user_driver_license['has_license_12_5t_truck'] = $request->has('has_license_12_5t_truck'); + $user_driver_license['has_license_forklift'] = $request->has('has_license_forklift'); if (UserDriverLicense_valid($user_driver_license)) { if ($user_driver_license['user_id'] == null) { diff --git a/includes/controller/users_controller.php b/includes/controller/users_controller.php index 84b6bbda..96e2c81b 100644 --- a/includes/controller/users_controller.php +++ b/includes/controller/users_controller.php @@ -12,16 +12,18 @@ use Engelsystem\ShiftsFilter; function users_controller() { global $user; + $request = request(); if (!isset($user)) { redirect(page_link_to('')); } - if (!isset($_REQUEST['action'])) { - $_REQUEST['action'] = 'list'; + $action = 'list'; + if ($request->has('action')) { + $action = $request->input('action'); } - switch ($_REQUEST['action']) { + switch ($action) { case 'view': return user_controller(); case 'delete': @@ -42,9 +44,10 @@ function users_controller() function user_delete_controller() { global $privileges, $user; + $request = request(); - if (isset($_REQUEST['user_id'])) { - $user_source = User($_REQUEST['user_id']); + if ($request->has('user_id')) { + $user_source = User($request->get('user_id')); } else { $user_source = $user; } @@ -59,11 +62,14 @@ function user_delete_controller() redirect(user_link($user)); } - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { $valid = true; - if (!(isset($_REQUEST['password']) && verify_password($_REQUEST['password'], $user['Passwort'], - $user['UID'])) + if ( + !( + $request->has('password') + && verify_password($request->input('password'), $user['Passwort'], $user['UID']) + ) ) { $valid = false; error(_('Your password is incorrect. Please try it again.')); @@ -130,9 +136,10 @@ function user_link($user) function user_edit_vouchers_controller() { global $privileges, $user; + $request = request(); - if (isset($_REQUEST['user_id'])) { - $user_source = User($_REQUEST['user_id']); + if ($request->has('user_id')) { + $user_source = User($request->input('user_id')); } else { $user_source = $user; } @@ -141,12 +148,16 @@ function user_edit_vouchers_controller() redirect(page_link_to('')); } - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { $valid = true; $vouchers = ''; - if (isset($_REQUEST['vouchers']) && test_request_int('vouchers') && trim($_REQUEST['vouchers']) >= 0) { - $vouchers = trim($_REQUEST['vouchers']); + if ( + $request->has('vouchers') + && test_request_int('vouchers') + && trim($request->input('vouchers')) >= 0 + ) { + $vouchers = trim($request->input('vouchers')); } else { $valid = false; error(_('Please enter a valid number of vouchers.')); @@ -180,10 +191,11 @@ function user_edit_vouchers_controller() function user_controller() { global $privileges, $user; + $request = request(); $user_source = $user; - if (isset($_REQUEST['user_id'])) { - $user_source = User($_REQUEST['user_id']); + if ($request->has('user_id')) { + $user_source = User($request->input('user_id')); if ($user_source == null) { error(_('User not found.')); redirect('?'); @@ -241,14 +253,15 @@ function user_controller() function users_list_controller() { global $privileges; + $request = request(); if (!in_array('admin_user', $privileges)) { redirect(page_link_to('')); } $order_by = 'Nick'; - if (isset($_REQUEST['OrderBy']) && in_array($_REQUEST['OrderBy'], User_sortable_columns())) { - $order_by = $_REQUEST['OrderBy']; + if ($request->has('OrderBy') && in_array($request->input('OrderBy'), User_sortable_columns())) { + $order_by = $request->input('OrderBy'); } $users = Users($order_by); @@ -282,20 +295,21 @@ function users_list_controller() */ function user_password_recovery_set_new_controller() { - $user_source = User_by_password_recovery_token($_REQUEST['token']); + $request = request(); + $user_source = User_by_password_recovery_token($request->input('token')); if ($user_source == null) { error(_('Token is not correct.')); redirect(page_link_to('login')); } - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { $valid = true; if ( - isset($_REQUEST['password']) - && strlen($_REQUEST['password']) >= config('min_password_length') + $request->has('password') + && strlen($request->post('password')) >= config('min_password_length') ) { - if ($_REQUEST['password'] != $_REQUEST['password2']) { + if ($request->post('password') != $request->post('password2')) { $valid = false; error(_('Your passwords don\'t match.')); } @@ -305,7 +319,7 @@ function user_password_recovery_set_new_controller() } if ($valid) { - set_password($user_source['UID'], $_REQUEST['password']); + set_password($user_source['UID'], $request->post('password')); success(_('Password saved.')); redirect(page_link_to('login')); } @@ -321,10 +335,11 @@ function user_password_recovery_set_new_controller() */ function user_password_recovery_start_controller() { - if (isset($_REQUEST['submit'])) { + $request = request(); + if ($request->has('submit')) { $valid = true; - if (isset($_REQUEST['email']) && strlen(strip_request_item('email')) > 0) { + if ($request->has('email') && strlen(strip_request_item('email')) > 0) { $email = strip_request_item('email'); if (check_email($email)) { $user_source = User_by_email($email); @@ -367,7 +382,7 @@ function user_password_recovery_start_controller() */ function user_password_recovery_controller() { - if (isset($_REQUEST['token'])) { + if (request()->has('token')) { return user_password_recovery_set_new_controller(); } @@ -391,11 +406,12 @@ function user_password_recovery_title() */ function load_user() { - if (!isset($_REQUEST['user_id'])) { + $request = request(); + if (!$request->has('user_id')) { redirect(page_link_to()); } - $user = User($_REQUEST['user_id']); + $user = User($request->input('user_id')); if ($user == null) { error(_('User doesn\'t exist.')); diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index a818e4cd..edfae705 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -3,6 +3,7 @@ use Engelsystem\Config\Config; use Engelsystem\Database\Db; use Engelsystem\Exceptions\Handler as ExceptionHandler; +use Engelsystem\Http\Request; /** * This file includes all needed functions, connects to the db etc. @@ -31,6 +32,13 @@ if (file_exists(__DIR__ . '/../config/config.php')) { date_default_timezone_set($config->get('timezone')); +/** + * Initialize Request + */ +$request = new Request(); +$request->create(); +$request::setInstance($request); + /** * Check for maintenance */ diff --git a/includes/helper/internationalization_helper.php b/includes/helper/internationalization_helper.php index ed16de15..d2dbcdbd 100644 --- a/includes/helper/internationalization_helper.php +++ b/includes/helper/internationalization_helper.php @@ -26,12 +26,12 @@ function locale_short() function gettext_init() { $locales = config('locales'); - $default_locale = config('default_locale'); + $request = request(); - if (isset($_REQUEST['set_locale']) && isset($locales[$_REQUEST['set_locale']])) { - $_SESSION['locale'] = $_REQUEST['set_locale']; + if ($request->has('set_locale') && isset($locales[$request->input('set_locale')])) { + $_SESSION['locale'] = $request->input('set_locale'); } elseif (!isset($_SESSION['locale'])) { - $_SESSION['locale'] = $default_locale; + $_SESSION['locale'] = config('default_locale'); } gettext_locale(); diff --git a/includes/pages/admin_active.php b/includes/pages/admin_active.php index d21afabe..2e06f90d 100644 --- a/includes/pages/admin_active.php +++ b/includes/pages/admin_active.php @@ -17,6 +17,7 @@ function admin_active() { $tshirt_sizes = config('tshirt_sizes'); $shift_sum_formula = config('shift_sum_formula'); + $request = request(); $msg = ''; $search = ''; @@ -25,16 +26,16 @@ function admin_active() $limit = ''; $set_active = ''; - if (isset($_REQUEST['search'])) { + if ($request->has('search')) { $search = strip_request_item('search'); } - $show_all_shifts = isset($_REQUEST['show_all_shifts']); + $show_all_shifts = $request->has('show_all_shifts'); - if (isset($_REQUEST['set_active'])) { + if ($request->has('set_active')) { $valid = true; - if (isset($_REQUEST['count']) && preg_match('/^\d+$/', $_REQUEST['count'])) { + if ($request->has('count') && preg_match('/^\d+$/', $request->input('count'))) { $count = strip_request_item('count'); if ($count < $forced_count) { error(sprintf( @@ -51,7 +52,7 @@ function admin_active() if ($valid) { $limit = ' LIMIT ' . $count; } - if (isset($_REQUEST['ack'])) { + if ($request->has('ack')) { DB::update('UPDATE `User` SET `Aktiv` = 0 WHERE `Tshirt` = 0'); $users = DB::select(sprintf(' SELECT @@ -89,8 +90,8 @@ function admin_active() } } - if (isset($_REQUEST['active']) && preg_match('/^\d+$/', $_REQUEST['active'])) { - $user_id = $_REQUEST['active']; + if ($request->has('active') && preg_match('/^\d+$/', $request->input('active'))) { + $user_id = $request->input('active'); $user_source = User($user_id); if ($user_source != null) { DB::update('UPDATE `User` SET `Aktiv`=1 WHERE `UID`=? LIMIT 1', [$user_id]); @@ -99,8 +100,8 @@ function admin_active() } else { $msg = error(_('Angel not found.'), true); } - } elseif (isset($_REQUEST['not_active']) && preg_match('/^\d+$/', $_REQUEST['not_active'])) { - $user_id = $_REQUEST['not_active']; + } elseif ($request->has('not_active') && preg_match('/^\d+$/', $request->input('not_active'))) { + $user_id = $request->input('not_active'); $user_source = User($user_id); if ($user_source != null) { DB::update('UPDATE `User` SET `Aktiv`=0 WHERE `UID`=? LIMIT 1', [$user_id]); @@ -109,8 +110,8 @@ function admin_active() } else { $msg = error(_('Angel not found.'), true); } - } elseif (isset($_REQUEST['tshirt']) && preg_match('/^\d+$/', $_REQUEST['tshirt'])) { - $user_id = $_REQUEST['tshirt']; + } elseif ($request->has('tshirt') && preg_match('/^\d+$/', $request->input('tshirt'))) { + $user_id = $request->input('tshirt'); $user_source = User($user_id); if ($user_source != null) { DB::update('UPDATE `User` SET `Tshirt`=1 WHERE `UID`=? LIMIT 1', [$user_id]); @@ -119,8 +120,8 @@ function admin_active() } else { $msg = error('Angel not found.', true); } - } elseif (isset($_REQUEST['not_tshirt']) && preg_match('/^\d+$/', $_REQUEST['not_tshirt'])) { - $user_id = $_REQUEST['not_tshirt']; + } elseif ($request->has('not_tshirt') && preg_match('/^\d+$/', $request->input('not_tshirt'))) { + $user_id = $request->input('not_tshirt'); $user_source = User($user_id); if ($user_source != null) { DB::update('UPDATE `User` SET `Tshirt`=0 WHERE `UID`=? LIMIT 1', [$user_id]); diff --git a/includes/pages/admin_arrive.php b/includes/pages/admin_arrive.php index 77155dae..ebeccb8c 100644 --- a/includes/pages/admin_arrive.php +++ b/includes/pages/admin_arrive.php @@ -17,12 +17,14 @@ function admin_arrive() { $msg = ''; $search = ''; - if (isset($_REQUEST['search'])) { + $request = request(); + + if ($request->has('search')) { $search = strip_request_item('search'); } - if (isset($_REQUEST['reset']) && preg_match('/^\d*$/', $_REQUEST['reset'])) { - $user_id = $_REQUEST['reset']; + if ($request->has('reset') && preg_match('/^\d*$/', $request->input('reset'))) { + $user_id = $request->input('reset'); $user_source = User($user_id); if ($user_source != null) { DB::update(' @@ -37,8 +39,8 @@ function admin_arrive() } else { $msg = error(_('Angel not found.'), true); } - } elseif (isset($_REQUEST['arrived']) && preg_match('/^\d*$/', $_REQUEST['arrived'])) { - $user_id = $_REQUEST['arrived']; + } elseif ($request->has('arrived') && preg_match('/^\d*$/', $request->input('arrived'))) { + $user_id = $request->input('arrived'); $user_source = User($user_id); if ($user_source != null) { DB::update(' diff --git a/includes/pages/admin_free.php b/includes/pages/admin_free.php index daaead22..ebf227a4 100644 --- a/includes/pages/admin_free.php +++ b/includes/pages/admin_free.php @@ -16,20 +16,20 @@ function admin_free_title() function admin_free() { global $privileges; + $request = request(); $search = ''; - if (isset($_REQUEST['search'])) { + if ($request->has('search')) { $search = strip_request_item('search'); } $angelTypeSearch = ''; - if (empty($_REQUEST['angeltype'])) { - $_REQUEST['angeltype'] = ''; - } else { + $angelType = $request->input('angeltype', ''); + if (!empty($angelType)) { $angelTypeSearch = ' INNER JOIN `UserAngelTypes` ON (`UserAngelTypes`.`angeltype_id` = ' - . DB::getPdo()->quote($_REQUEST['angeltype']) + . DB::getPdo()->quote($angelType) . ' AND `UserAngelTypes`.`user_id` = `User`.`UID`'; - if (isset($_REQUEST['confirmed_only'])) { + if ($request->has('confirmed_only')) { $angelTypeSearch .= ' AND `UserAngelTypes`.`confirm_user_id`'; } $angelTypeSearch .= ') '; @@ -105,10 +105,10 @@ function admin_free() form_text('search', _('Search'), $search) ]), div('col-md-4', [ - form_select('angeltype', _('Angeltype'), $angel_types, $_REQUEST['angeltype']) + form_select('angeltype', _('Angeltype'), $angel_types, $angelType) ]), div('col-md-2', [ - form_checkbox('confirmed_only', _('Only confirmed'), isset($_REQUEST['confirmed_only'])) + form_checkbox('confirmed_only', _('Only confirmed'), $request->has('confirmed_only')) ]), div('col-md-2', [ form_submit('submit', _('Search')) diff --git a/includes/pages/admin_groups.php b/includes/pages/admin_groups.php index 4011ccf1..c483a79d 100644 --- a/includes/pages/admin_groups.php +++ b/includes/pages/admin_groups.php @@ -16,8 +16,10 @@ function admin_groups_title() function admin_groups() { $html = ''; + $request = request(); $groups = DB::select('SELECT * FROM `Groups` ORDER BY `Name`'); - if (!isset($_REQUEST['action'])) { + + if (!$request->has('action')) { $groups_table = []; foreach ($groups as $group) { $privileges = DB::select(' @@ -51,10 +53,10 @@ function admin_groups() ], $groups_table) ]); } else { - switch ($_REQUEST['action']) { + switch ($request->input('action')) { case 'edit': - if (isset($_REQUEST['id']) && preg_match('/^-\d{1,11}$/', $_REQUEST['id'])) { - $group_id = $_REQUEST['id']; + if ($request->has('id') && preg_match('/^-\d{1,11}$/', $request->input('id'))) { + $group_id = $request->input('id'); } else { return error('Incomplete call, missing Groups ID.', true); } @@ -99,21 +101,22 @@ function admin_groups() break; case 'save': - if (isset($_REQUEST['id']) && preg_match('/^-\d{1,11}$/', $_REQUEST['id'])) { - $group_id = $_REQUEST['id']; + if ($request->has('id') && preg_match('/^-\d{1,11}$/', $request->input('id'))) { + $group_id = $request->input('id'); } else { return error('Incomplete call, missing Groups ID.', true); } $group = DB::select('SELECT * FROM `Groups` WHERE `UID`=? LIMIT 1', [$group_id]); - if (!is_array($_REQUEST['privileges'])) { - $_REQUEST['privileges'] = []; + $privileges = $request->get('privileges'); + if (!is_array($privileges)) { + $privileges = []; } if (!empty($group)) { $group = array_shift($group); DB::delete('DELETE FROM `GroupPrivileges` WHERE `group_id`=?', [$group_id]); $privilege_names = []; - foreach ($_REQUEST['privileges'] as $privilege) { + foreach ($privileges as $privilege) { if (preg_match('/^\d{1,}$/', $privilege)) { $group_privileges_source = DB::select( 'SELECT `name` FROM `Privileges` WHERE `id`=? LIMIT 1', diff --git a/includes/pages/admin_import.php b/includes/pages/admin_import.php index 7a246b4b..3cbed9f9 100644 --- a/includes/pages/admin_import.php +++ b/includes/pages/admin_import.php @@ -15,21 +15,21 @@ function admin_import_title() */ function admin_import() { - global $rooms_import; - global $user; + global $rooms_import, $user; $html = ''; $import_dir = __DIR__ . '/../../import'; + $request = request(); $step = 'input'; if ( - isset($_REQUEST['step']) - && in_array($step, [ + $request->has('step') + && in_array($request->input('step'), [ 'input', 'check', 'import' ]) ) { - $step = $_REQUEST['step']; + $step = $request->input('step'); } if ($test_handle = @fopen($import_dir . '/tmp', 'w')) { @@ -57,25 +57,25 @@ function admin_import() case 'input': $valid = false; - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { $valid = true; - if (isset($_REQUEST['shifttype_id']) && isset($shifttypes[$_REQUEST['shifttype_id']])) { - $shifttype_id = $_REQUEST['shifttype_id']; + if ($request->has('shifttype_id') && isset($shifttypes[$request->input('shifttype_id')])) { + $shifttype_id = $request->input('shifttype_id'); } else { $valid = false; error(_('Please select a shift type.')); } - if (isset($_REQUEST['add_minutes_start']) && is_numeric(trim($_REQUEST['add_minutes_start']))) { - $add_minutes_start = trim($_REQUEST['add_minutes_start']); + if ($request->has('add_minutes_start') && is_numeric(trim($request->input('add_minutes_start')))) { + $add_minutes_start = trim($request->input('add_minutes_start')); } else { $valid = false; error(_('Please enter an amount of minutes to add to a talk\'s begin.')); } - if (isset($_REQUEST['add_minutes_end']) && is_numeric(trim($_REQUEST['add_minutes_end']))) { - $add_minutes_end = trim($_REQUEST['add_minutes_end']); + if ($request->has('add_minutes_end') && is_numeric(trim($request->input('add_minutes_end')))) { + $add_minutes_end = trim($request->input('add_minutes_end')); } else { $valid = false; error(_('Please enter an amount of minutes to add to a talk\'s end.')); @@ -133,22 +133,22 @@ function admin_import() redirect(page_link_to('admin_import')); } - if (isset($_REQUEST['shifttype_id']) && isset($shifttypes[$_REQUEST['shifttype_id']])) { - $shifttype_id = $_REQUEST['shifttype_id']; + if ($request->has('shifttype_id') && isset($shifttypes[$request->input('shifttype_id')])) { + $shifttype_id = $request->input('shifttype_id'); } else { error(_('Please select a shift type.')); redirect(page_link_to('admin_import')); } - if (isset($_REQUEST['add_minutes_start']) && is_numeric(trim($_REQUEST['add_minutes_start']))) { - $add_minutes_start = trim($_REQUEST['add_minutes_start']); + if ($request->has('add_minutes_start') && is_numeric(trim($request->input('add_minutes_start')))) { + $add_minutes_start = trim($request->input('add_minutes_start')); } else { error(_('Please enter an amount of minutes to add to a talk\'s begin.')); redirect(page_link_to('admin_import')); } - if (isset($_REQUEST['add_minutes_end']) && is_numeric(trim($_REQUEST['add_minutes_end']))) { - $add_minutes_end = trim($_REQUEST['add_minutes_end']); + if ($request->has('add_minutes_end') && is_numeric(trim($request->input(('add_minutes_end'))))) { + $add_minutes_end = trim($request->input('add_minutes_end')); } else { error(_('Please enter an amount of minutes to add to a talk\'s end.')); redirect(page_link_to('admin_import')); @@ -227,22 +227,22 @@ function admin_import() redirect(page_link_to('admin_import')); } - if (isset($_REQUEST['shifttype_id']) && isset($shifttypes[$_REQUEST['shifttype_id']])) { - $shifttype_id = $_REQUEST['shifttype_id']; + if ($request->has('shifttype_id') && isset($shifttypes[$request->input('shifttype_id')])) { + $shifttype_id = $request->input('shifttype_id'); } else { error(_('Please select a shift type.')); redirect(page_link_to('admin_import')); } - if (isset($_REQUEST['add_minutes_start']) && is_numeric(trim($_REQUEST['add_minutes_start']))) { - $add_minutes_start = trim($_REQUEST['add_minutes_start']); + if ($request->has('add_minutes_start') && is_numeric(trim($request->input('add_minutes_start')))) { + $add_minutes_start = trim($request->input('add_minutes_start')); } else { error(_('Please enter an amount of minutes to add to a talk\'s begin.')); redirect(page_link_to('admin_import')); } - if (isset($_REQUEST['add_minutes_end']) && is_numeric(trim($_REQUEST['add_minutes_end']))) { - $add_minutes_end = trim($_REQUEST['add_minutes_end']); + if ($request->has('add_minutes_end') && is_numeric(trim($request->input('add_minutes_end')))) { + $add_minutes_end = trim($request->input('add_minutes_end')); } else { error(_('Please enter an amount of minutes to add to a talk\'s end.')); redirect(page_link_to('admin_import')); diff --git a/includes/pages/admin_log.php b/includes/pages/admin_log.php index 9e5e5827..03c9abb0 100644 --- a/includes/pages/admin_log.php +++ b/includes/pages/admin_log.php @@ -14,7 +14,7 @@ function admin_log_title() function admin_log() { $filter = ''; - if (isset($_REQUEST['keyword'])) { + if (request()->has('keyword')) { $filter = strip_request_item('keyword'); } $log_entries_source = LogEntries_filter($filter); diff --git a/includes/pages/admin_news.php b/includes/pages/admin_news.php index bc242831..7f8ca1ba 100644 --- a/includes/pages/admin_news.php +++ b/includes/pages/admin_news.php @@ -8,14 +8,15 @@ use Engelsystem\Database\DB; function admin_news() { global $user; + $request = request(); - if (!isset($_GET['action'])) { + if (!$request->has('action')) { redirect(page_link_to('news')); } $html = '

      ' . _('Edit news entry') . '

      ' . msg(); - if (isset($_REQUEST['id']) && preg_match('/^\d{1,11}$/', $_REQUEST['id'])) { - $news_id = $_REQUEST['id']; + if ($request->has('id') && preg_match('/^\d{1,11}$/', $request->input('id'))) { + $news_id = $request->input('id'); } else { return error('Incomplete call, missing News ID.', true); } @@ -25,7 +26,7 @@ function admin_news() return error('No News found.', true); } - switch ($_REQUEST['action']) { + switch ($request->input('action')) { case 'edit': $news = array_shift($news); $user_source = User($news['UID']); @@ -56,14 +57,14 @@ function admin_news() ', [ time(), - $_POST["eBetreff"], - $_POST["eText"], + $request->post('eBetreff'), + $request->post('eText'), $user['UID'], - isset($_POST["eTreffen"]) ? 1 : 0, + $request->has('eTreffen') ? 1 : 0, $news_id ] ); - engelsystem_log('News updated: ' . $_POST['eBetreff']); + engelsystem_log('News updated: ' . $request->post('eBetreff')); success(_('News entry updated.')); redirect(page_link_to('news')); break; diff --git a/includes/pages/admin_questions.php b/includes/pages/admin_questions.php index 098701e3..d05bace6 100644 --- a/includes/pages/admin_questions.php +++ b/includes/pages/admin_questions.php @@ -38,8 +38,9 @@ function admin_new_questions() function admin_questions() { global $user; + $request = request(); - if (!isset($_REQUEST['action'])) { + if (!$request->has('action')) { $unanswered_questions_table = []; $questions = DB::select('SELECT * FROM `Questions` WHERE `AID` IS NULL'); foreach ($questions as $question) { @@ -96,10 +97,10 @@ function admin_questions() ], $answered_questions_table) ]); } else { - switch ($_REQUEST['action']) { + switch ($request->input('action')) { case 'answer': - if (isset($_REQUEST['id']) && preg_match('/^\d{1,11}$/', $_REQUEST['id'])) { - $question_id = $_REQUEST['id']; + if ($request->has('id') && preg_match('/^\d{1,11}$/', $request->input('id'))) { + $question_id = $request->input('id'); } else { return error('Incomplete call, missing Question ID.', true); } @@ -112,7 +113,7 @@ function admin_questions() $answer = trim( preg_replace("/([^\p{L}\p{P}\p{Z}\p{N}\n]{1,})/ui", '', - strip_tags($_REQUEST['answer']) + strip_tags($request->input('answer')) )); if ($answer != '') { @@ -138,8 +139,8 @@ function admin_questions() } break; case 'delete': - if (isset($_REQUEST['id']) && preg_match('/^\d{1,11}$/', $_REQUEST['id'])) { - $question_id = $_REQUEST['id']; + if ($request->has('id') && preg_match('/^\d{1,11}$/', $request->input('id'))) { + $question_id = $request->input('id'); } else { return error('Incomplete call, missing Question ID.', true); } diff --git a/includes/pages/admin_rooms.php b/includes/pages/admin_rooms.php index d483f99e..3045242b 100644 --- a/includes/pages/admin_rooms.php +++ b/includes/pages/admin_rooms.php @@ -17,6 +17,8 @@ function admin_rooms() { $rooms_source = DB::select('SELECT * FROM `Room` ORDER BY `Name`'); $rooms = []; + $request = request(); + foreach ($rooms_source as $room) { $rooms[] = [ 'name' => Room_name_render($room), @@ -30,7 +32,7 @@ function admin_rooms() } $room = null; - if (isset($_REQUEST['show'])) { + if ($request->has('show')) { $msg = ''; $name = ''; $from_pentabarf = ''; @@ -47,7 +49,7 @@ function admin_rooms() } if (test_request_int('id')) { - $room = Room($_REQUEST['id'], false); + $room = Room($request->input('id'), false); if ($room === false) { engelsystem_error('Unable to load room.'); } @@ -55,7 +57,7 @@ function admin_rooms() redirect(page_link_to('admin_rooms')); } - $room_id = $_REQUEST['id']; + $room_id = $request->input('id'); $name = $room['Name']; $from_pentabarf = $room['FromPentabarf']; $public = $room['show']; @@ -70,11 +72,11 @@ function admin_rooms() } } - if ($_REQUEST['show'] == 'edit') { - if (isset($_REQUEST['submit'])) { + if ($request->input('show') == 'edit') { + if ($request->has('submit')) { $valid = true; - if (isset($_REQUEST['name']) && strlen(strip_request_item('name')) > 0) { + if ($request->has('name') && strlen(strip_request_item('name')) > 0) { $name = strip_request_item('name'); if ( isset($room) @@ -91,19 +93,17 @@ function admin_rooms() $msg .= error(_('Please enter a name.'), true); } - if (isset($_REQUEST['from_pentabarf'])) { + $from_pentabarf = ''; + if ($request->has('from_pentabarf')) { $from_pentabarf = 'Y'; - } else { - $from_pentabarf = ''; } - if (isset($_REQUEST['public'])) { + $public = ''; + if ($request->has('public')) { $public = 'Y'; - } else { - $public = ''; } - if (isset($_REQUEST['number'])) { + if ($request->has('number')) { $number = strip_request_item('number'); } else { $valid = false; @@ -111,10 +111,10 @@ function admin_rooms() foreach ($angeltypes as $angeltype_id => $angeltype) { if ( - isset($_REQUEST['angeltype_count_' . $angeltype_id]) - && preg_match('/^\d{1,4}$/', $_REQUEST['angeltype_count_' . $angeltype_id]) + $request->has('angeltype_count_' . $angeltype_id) + && preg_match('/^\d{1,4}$/', $request->input('angeltype_count_' . $angeltype_id)) ) { - $angeltypes_count[$angeltype_id] = $_REQUEST['angeltype_count_' . $angeltype_id]; + $angeltypes_count[$angeltype_id] = $request->input('angeltype_count_' . $angeltype_id); } else { $valid = false; $msg .= error(sprintf(_('Please enter needed angels for type %s.'), $angeltype), true); @@ -209,8 +209,8 @@ function admin_rooms() form_submit('submit', _('Save')) ]) ]); - } elseif ($_REQUEST['show'] == 'delete') { - if (isset($_REQUEST['ack'])) { + } elseif ($request->input('show') == 'delete') { + if ($request->has('ack')) { if (!Room_delete($room_id)) { engelsystem_error('Unable to delete room.'); } diff --git a/includes/pages/admin_shifts.php b/includes/pages/admin_shifts.php index 06071233..5b53f9cd 100644 --- a/includes/pages/admin_shifts.php +++ b/includes/pages/admin_shifts.php @@ -18,7 +18,7 @@ function admin_shifts_title() function admin_shifts() { $valid = true; - + $request = request(); $start = parse_date('Y-m-d H:i', date('Y-m-d') . ' 00:00'); $end = $start; $mode = 'single'; @@ -52,14 +52,14 @@ function admin_shifts() $shifttypes[$shifttype['id']] = $shifttype['name']; } - if (isset($_REQUEST['preview']) || isset($_REQUEST['back'])) { - if (isset($_REQUEST['shifttype_id'])) { - $shifttype = ShiftType($_REQUEST['shifttype_id']); + if ($request->has('preview') || $request->has('back')) { + if ($request->has('shifttype_id')) { + $shifttype = ShiftType($request->input('shifttype_id')); if ($shifttype == null) { $valid = false; error(_('Please select a shift type.')); } else { - $shifttype_id = $_REQUEST['shifttype_id']; + $shifttype_id = $request->input('shifttype_id'); } } else { $valid = false; @@ -71,25 +71,25 @@ function admin_shifts() // Auswahl der sichtbaren Locations für die Schichten if ( - isset($_REQUEST['rid']) - && preg_match('/^\d+$/', $_REQUEST['rid']) - && isset($room_array[$_REQUEST['rid']]) + $request->has('rid') + && preg_match('/^\d+$/', $request->input('rid')) + && isset($room_array[$request->input('rid')]) ) { - $rid = $_REQUEST['rid']; + $rid = $request->input('rid'); } else { $valid = false; $rid = $rooms[0]['RID']; error(_('Please select a location.')); } - if (isset($_REQUEST['start']) && $tmp = parse_date('Y-m-d H:i', $_REQUEST['start'])) { + if ($request->has('start') && $tmp = parse_date('Y-m-d H:i', $request->input('start'))) { $start = $tmp; } else { $valid = false; error(_('Please select a start time.')); } - if (isset($_REQUEST['end']) && $tmp = parse_date('Y-m-d H:i', $_REQUEST['end'])) { + if ($request->has('end') && $tmp = parse_date('Y-m-d H:i', $request->input('end'))) { $end = $tmp; } else { $valid = false; @@ -101,24 +101,24 @@ function admin_shifts() error(_('The shifts end has to be after its start.')); } - if (isset($_REQUEST['mode'])) { - if ($_REQUEST['mode'] == 'single') { + if ($request->has('mode')) { + if ($request->input('mode') == 'single') { $mode = 'single'; - } elseif ($_REQUEST['mode'] == 'multi') { - if (isset($_REQUEST['length']) && preg_match('/^\d+$/', trim($_REQUEST['length']))) { + } elseif ($request->input('mode') == 'multi') { + if ($request->has('length') && preg_match('/^\d+$/', trim($request->input('length')))) { $mode = 'multi'; - $length = trim($_REQUEST['length']); + $length = trim($request->input('length')); } else { $valid = false; error(_('Please enter a shift duration in minutes.')); } - } elseif ($_REQUEST['mode'] == 'variable') { + } elseif ($request->input('mode') == 'variable') { if ( - isset($_REQUEST['change_hours']) - && preg_match('/^(\d{2}(,|$))/', trim(str_replace(' ', '', $_REQUEST['change_hours']))) + $request->has('change_hours') + && preg_match('/^(\d{2}(,|$))/', trim(str_replace(' ', '', $request->input('change_hours')))) ) { $mode = 'variable'; - $change_hours = array_map('trim', explode(',', $_REQUEST['change_hours'])); + $change_hours = array_map('trim', explode(',', $request->input('change_hours'))); } else { $valid = false; error(_('Please split the shift-change hours by colons.')); @@ -129,17 +129,17 @@ function admin_shifts() error(_('Please select a mode.')); } - if (isset($_REQUEST['angelmode'])) { - if ($_REQUEST['angelmode'] == 'location') { + if ($request->has('angelmode')) { + if ($request->input('angelmode') == 'location') { $angelmode = 'location'; - } elseif ($_REQUEST['angelmode'] == 'manually') { + } elseif ($request->input('angelmode') == 'manually') { $angelmode = 'manually'; foreach ($types as $type) { if ( - isset($_REQUEST['type_' . $type['id']]) - && preg_match('/^\d+$/', trim($_REQUEST['type_' . $type['id']])) + $request->has('type_' . $type['id']) + && preg_match('/^\d+$/', trim($request->input('type_' . $type['id']))) ) { - $needed_angel_types[$type['id']] = trim($_REQUEST['type_' . $type['id']]); + $needed_angel_types[$type['id']] = trim($request->input('type_' . $type['id'])); } else { $valid = false; error(sprintf(_('Please check the needed angels for team %s.'), $type['name'])); @@ -159,7 +159,7 @@ function admin_shifts() } // Beim Zurück-Knopf das Formular zeigen - if (isset($_REQUEST['back'])) { + if ($request->has('back')) { $valid = false; } @@ -304,9 +304,9 @@ function admin_shifts() ]) ]); } - } elseif (isset($_REQUEST['submit'])) { + } elseif ($request->has('submit')) { if ( - !isset($_SESSION['admin_shifts_shifts']) + !$request->has('admin_shifts_shifts') || !isset($_SESSION['admin_shifts_types']) || !is_array($_SESSION['admin_shifts_shifts']) || !is_array($_SESSION['admin_shifts_types']) @@ -360,8 +360,9 @@ function admin_shifts() unset($_SESSION['admin_shifts_types']); } - if (!isset($_REQUEST['rid'])) { - $_REQUEST['rid'] = null; + $rid = null; + if ($request->has('rid')) { + $rid = $request->input('rid'); } $angel_types = ''; foreach ($types as $type) { @@ -378,7 +379,7 @@ function admin_shifts() form([ form_select('shifttype_id', _('Shifttype'), $shifttypes, $shifttype_id), form_text('title', _('Title'), $title), - form_select('rid', _('Room'), $room_array, $_REQUEST['rid']), + form_select('rid', _('Room'), $room_array, $rid), div('row', [ div('col-md-6', [ form_text('start', _('Start'), date('Y-m-d H:i', $start)), @@ -386,7 +387,7 @@ function admin_shifts() form_info(_('Mode'), ''), form_radio('mode', _('Create one shift'), $mode == 'single', 'single'), form_radio('mode', _('Create multiple shifts'), $mode == 'multi', 'multi'), - form_text('length', _('Length'), !empty($_REQUEST['length']) ? $_REQUEST['length'] : '120'), + form_text('length', _('Length'), $request->has('length') ? $request->input('length') : '120'), form_radio( 'mode', _('Create multiple shifts with variable length'), @@ -396,7 +397,7 @@ function admin_shifts() form_text( 'change_hours', _('Shift change hours'), - !empty($_REQUEST['change_hours']) ? $_REQUEST['change_hours'] : '00, 04, 08, 10, 12, 14, 16, 18, 20, 22' + $request->has('change_hours') ? $request->input('input') : '00, 04, 08, 10, 12, 14, 16, 18, 20, 22' ) ]), div('col-md-6', [ diff --git a/includes/pages/admin_user.php b/includes/pages/admin_user.php index 8f833087..510e2292 100644 --- a/includes/pages/admin_user.php +++ b/includes/pages/admin_user.php @@ -17,6 +17,7 @@ function admin_user() { global $user, $privileges; $tshirt_sizes = config('tshirt_sizes'); + $request = request(); foreach ($tshirt_sizes as $key => $size) { if (empty($size)) { @@ -26,12 +27,12 @@ function admin_user() $html = ''; - if (!isset($_REQUEST['id'])) { + if (!$request->has('id')) { redirect(users_link()); } - $user_id = $_REQUEST['id']; - if (!isset($_REQUEST['action'])) { + $user_id = $request->input('id'); + if (!$request->has('action')) { $user_source = User($user_id); if ($user_source == null) { error(_('This user does not exist.')); @@ -171,7 +172,7 @@ function admin_user() $html .= "
      "; } else { - switch ($_REQUEST['action']) { + switch ($request->input('action')) { case 'save_groups': if ($user_id != $user['UID']) { $my_highest_group = DB::select( @@ -212,13 +213,14 @@ function admin_user() $grouplist[] = $group['UID']; } - if (!is_array($_REQUEST['groups'])) { - $_REQUEST['groups'] = []; + $groupsRequest = $request->input('groups'); + if (!is_array($groupsRequest)) { + $groupsRequest = []; } DB::delete('DELETE FROM `UserGroups` WHERE `uid`=?', [$user_id]); $user_groups_info = []; - foreach ($_REQUEST['groups'] as $group) { + foreach ($groupsRequest as $group) { if (in_array($group, $grouplist)) { DB::insert( 'INSERT INTO `UserGroups` (`uid`, `group_id`) VALUES (?, ?)', @@ -244,7 +246,7 @@ function admin_user() $force_active = $user['force_active']; $user_source = User($user_id); if (in_array('admin_active', $privileges)) { - $force_active = $_REQUEST['force_active']; + $force_active = $request->input('force_active'); } $sql = ' UPDATE `User` SET @@ -255,7 +257,7 @@ function admin_user() `Handy` = ?, `Alter` =?, `DECT` = ?, - ' . ($user_source['email_by_human_allowed'] ? '`email` = ' . DB::getPdo()->quote($_POST["eemail"]) . ',' : '') . ' + ' . ($user_source['email_by_human_allowed'] ? '`email` = ' . DB::getPdo()->quote($request->post('eemail')) . ',' : '') . ' `jabber` = ?, `Size` = ?, `Gekommen`= ?, @@ -266,34 +268,34 @@ function admin_user() WHERE `UID` = ? LIMIT 1'; DB::update($sql, [ - $_POST['eNick'], - $_POST['eName'], - $_POST['eVorname'], - $_POST['eTelefon'], - $_POST['eHandy'], - $_POST['eAlter'], - $_POST['eDECT'], - $_POST['ejabber'], - $_POST['eSize'], - $_POST['eGekommen'], - $_POST['eAktiv'], + $request->post('eNick'), + $request->post('eName'), + $request->post('eVorname'), + $request->post('eTelefon'), + $request->post('eHandy'), + $request->post('eAlter'), + $request->post('eDECT'), + $request->post('ejabber'), + $request->post('eSize'), + $request->post('eGekommen'), + $request->post('eAktiv'), $force_active, - $_POST['eTshirt'], - $_POST['Hometown'], + $request->post('eTshirt'), + $request->post('Hometown'), $user_id, ]); engelsystem_log( - 'Updated user: ' . $_POST['eNick'] . ', ' . $_POST['eSize'] - . ', arrived: ' . $_POST['eGekommen'] - . ', active: ' . $_POST['eAktiv'] - . ', tshirt: ' . $_POST['eTshirt'] + 'Updated user: ' . $request->post('eNick') . ', ' . $request->post('eSize') + . ', arrived: ' . $request->post('eVorname') + . ', active: ' . $request->post('eAktiv') + . ', tshirt: ' . $request->post('eTshirt') ); $html .= success('Änderung wurde gespeichert...' . "\n", true); break; case 'change_pw': - if ($_REQUEST['new_pw'] != '' && $_REQUEST['new_pw'] == $_REQUEST['new_pw2']) { - set_password($user_id, $_REQUEST['new_pw']); + if ($request->post('new_pw') != '' && $request->post('new_pw') == $request->post('new_pw2')) { + set_password($user_id, $request->post('new_pw')); $user_source = User($user_id); engelsystem_log('Set new password for ' . User_Nick_render($user_source)); $html .= success('Passwort neu gesetzt.', true); diff --git a/includes/pages/guest_login.php b/includes/pages/guest_login.php index 99970a01..858ced80 100644 --- a/includes/pages/guest_login.php +++ b/includes/pages/guest_login.php @@ -38,6 +38,7 @@ function guest_register() $enable_tshirt_size = config('enable_tshirt_size'); $min_password_length = config('min_password_length'); $event_config = EventConfig(); + $request = request(); $msg = ''; $nick = ''; @@ -73,11 +74,11 @@ function guest_register() } } - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { $valid = true; - if (isset($_REQUEST['nick']) && strlen(User_validate_Nick($_REQUEST['nick'])) > 1) { - $nick = User_validate_Nick($_REQUEST['nick']); + if ($request->has('nick') && strlen(User_validate_Nick($request->input('nick'))) > 1) { + $nick = User_validate_Nick($request->input('nick')); if (count(DB::select('SELECT `UID` FROM `User` WHERE `Nick`=? LIMIT 1', [$nick])) > 0) { $valid = false; $msg .= error(sprintf(_('Your nick "%s" already exists.'), $nick), true); @@ -86,11 +87,11 @@ function guest_register() $valid = false; $msg .= error(sprintf( _('Your nick "%s" is too short (min. 2 characters).'), - User_validate_Nick($_REQUEST['nick']) + User_validate_Nick($request->input('nick')) ), true); } - if (isset($_REQUEST['mail']) && strlen(strip_request_item('mail')) > 0) { + if ($request->has('mail') && strlen(strip_request_item('mail')) > 0) { $mail = strip_request_item('mail'); if (!check_email($mail)) { $valid = false; @@ -101,15 +102,15 @@ function guest_register() $msg .= error(_('Please enter your e-mail.'), true); } - if (isset($_REQUEST['email_shiftinfo'])) { + if ($request->has('email_shiftinfo')) { $email_shiftinfo = true; } - if (isset($_REQUEST['email_by_human_allowed'])) { + if ($request->has('email_by_human_allowed')) { $email_by_human_allowed = true; } - if (isset($_REQUEST['jabber']) && strlen(strip_request_item('jabber')) > 0) { + if ($request->has('jabber') && strlen(strip_request_item('jabber')) > 0) { $jabber = strip_request_item('jabber'); if (!check_email($jabber)) { $valid = false; @@ -118,16 +119,16 @@ function guest_register() } if ($enable_tshirt_size) { - if (isset($_REQUEST['tshirt_size']) && isset($tshirt_sizes[$_REQUEST['tshirt_size']]) && $_REQUEST['tshirt_size'] != '') { - $tshirt_size = $_REQUEST['tshirt_size']; + if ($request->has('tshirt_size') && isset($tshirt_sizes[$request->input('tshirt_size')])) { + $tshirt_size = $request->input('tshirt_size'); } else { $valid = false; $msg .= error(_('Please select your shirt size.'), true); } } - if (isset($_REQUEST['password']) && strlen($_REQUEST['password']) >= $min_password_length) { - if ($_REQUEST['password'] != $_REQUEST['password2']) { + if ($request->has('password') && strlen($request->post('password')) >= $min_password_length) { + if ($request->post('password') != $request->post('password2')) { $valid = false; $msg .= error(_('Your passwords don\'t match.'), true); } @@ -139,8 +140,8 @@ function guest_register() ), true); } - if (isset($_REQUEST['planned_arrival_date'])) { - $tmp = parse_date('Y-m-d H:i', $_REQUEST['planned_arrival_date'] . ' 00:00'); + if ($request->has('planned_arrival_date')) { + $tmp = parse_date('Y-m-d H:i', $request->input('planned_arrival_date') . ' 00:00'); $result = User_validate_planned_arrival_date($tmp); $planned_arrival_date = $result->getValue(); if (!$result->isValid()) { @@ -151,34 +152,34 @@ function guest_register() $selected_angel_types = []; foreach (array_keys($angel_types) as $angel_type_id) { - if (isset($_REQUEST['angel_types_' . $angel_type_id])) { + if ($request->has('angel_types_' . $angel_type_id)) { $selected_angel_types[] = $angel_type_id; } } // Trivia - if (isset($_REQUEST['lastname'])) { + if ($request->has('lastname')) { $lastName = strip_request_item('lastname'); } - if (isset($_REQUEST['prename'])) { + if ($request->has('prename')) { $preName = strip_request_item('prename'); } - if (isset($_REQUEST['age']) && preg_match('/^\d{0,4}$/', $_REQUEST['age'])) { + if ($request->has('age') && preg_match('/^\d{0,4}$/', $request->input('age'))) { $age = strip_request_item('age'); } - if (isset($_REQUEST['tel'])) { + if ($request->has('tel')) { $tel = strip_request_item('tel'); } - if (isset($_REQUEST['dect'])) { + if ($request->has('dect')) { $dect = strip_request_item('dect'); } - if (isset($_REQUEST['mobile'])) { + if ($request->has('mobile')) { $mobile = strip_request_item('mobile'); } - if (isset($_REQUEST['hometown'])) { + if ($request->has('hometown')) { $hometown = strip_request_item('hometown'); } - if (isset($_REQUEST['comment'])) { + if ($request->has('comment')) { $comment = strip_request_item_nl('comment'); } @@ -233,7 +234,7 @@ function guest_register() // Assign user-group and set password $user_id = DB::getPdo()->lastInsertId(); DB::insert('INSERT INTO `UserGroups` (`uid`, `group_id`) VALUES (?, -2)', [$user_id]); - set_password($user_id, $_REQUEST['password']); + set_password($user_id, $request->post('password')); // Assign angel-types $user_angel_types_info = []; @@ -391,18 +392,18 @@ function guest_logout() function guest_login() { $nick = ''; - + $request = request(); unset($_SESSION['uid']); $valid = true; - if (isset($_REQUEST['submit'])) { - if (isset($_REQUEST['nick']) && strlen(User_validate_Nick($_REQUEST['nick'])) > 0) { - $nick = User_validate_Nick($_REQUEST['nick']); + if ($request->has('submit')) { + if ($request->has('nick') && strlen(User_validate_Nick($request->input('nick'))) > 0) { + $nick = User_validate_Nick($request->input('nick')); $login_user = DB::select('SELECT * FROM `User` WHERE `Nick`=?', [$nick]); if (count($login_user) > 0) { $login_user = $login_user[0]; - if (isset($_REQUEST['password'])) { - if (!verify_password($_REQUEST['password'], $login_user['Passwort'], $login_user['UID'])) { + if ($request->has('password')) { + if (!verify_password($request->post('password'), $login_user['Passwort'], $login_user['UID'])) { $valid = false; error(_('Your password is incorrect. Please try it again.')); } @@ -487,6 +488,6 @@ function get_register_hint() ]); } - //FIXME: return error(_('Registration is disabled.'), true); + //@TODO: FIXME: return error(_('Registration is disabled.'), true); return error('Registration is disabled.', true); } diff --git a/includes/pages/guest_stats.php b/includes/pages/guest_stats.php index 6b6f0572..8aa6f740 100644 --- a/includes/pages/guest_stats.php +++ b/includes/pages/guest_stats.php @@ -5,9 +5,10 @@ use Engelsystem\Database\DB; function guest_stats() { $apiKey = config('api_key'); + $request = request(); - if (isset($_REQUEST['api_key'])) { - if ($_REQUEST['api_key'] == $apiKey && !empty($apiKey)) { + if ($request->has('api_key')) { + if (!empty($apiKey) && $request->input('api_key') == $apiKey) { $stats = []; list($user_count) = DB::select('SELECT count(*) AS `user_count` FROM `User`'); diff --git a/includes/pages/user_atom.php b/includes/pages/user_atom.php index d7c77d52..a1e2580a 100644 --- a/includes/pages/user_atom.php +++ b/includes/pages/user_atom.php @@ -3,16 +3,17 @@ use Engelsystem\Database\DB; /** - * Publically available page to feed the news to feedreaders + * Publically available page to feed the news to feed readers */ function user_atom() { global $user; + $request = request(); - if (!isset($_REQUEST['key']) || !preg_match('/^[\da-f]{32}$/', $_REQUEST['key'])) { + if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) { engelsystem_error('Missing key.'); } - $key = $_REQUEST['key']; + $key = $request->input('key'); $user = User_by_api_key($key); if ($user == null) { @@ -25,7 +26,7 @@ function user_atom() $news = DB::select(' SELECT * FROM `News` - ' . (empty($_REQUEST['meetings']) ? '' : 'WHERE `Treffen` = 1 ') . ' + ' . (!$request->has('meetings') ? '' : 'WHERE `Treffen` = 1 ') . ' ORDER BY `ID` DESC LIMIT ' . (int)config('display_news') ); diff --git a/includes/pages/user_ical.php b/includes/pages/user_ical.php index ce474a9e..8d22c4eb 100644 --- a/includes/pages/user_ical.php +++ b/includes/pages/user_ical.php @@ -6,11 +6,12 @@ function user_ical() { global $user; + $request = request(); - if (!isset($_REQUEST['key']) || !preg_match('/^[\da-f]{32}$/', $_REQUEST['key'])) { + if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) { engelsystem_error('Missing key.'); } - $key = $_REQUEST['key']; + $key = $request->input('key'); $user = User_by_api_key($key); if ($user == null) { diff --git a/includes/pages/user_messages.php b/includes/pages/user_messages.php index dd22cd66..a811970d 100644 --- a/includes/pages/user_messages.php +++ b/includes/pages/user_messages.php @@ -35,8 +35,9 @@ function user_unread_messages() function user_messages() { global $user; + $request = request(); - if (!isset($_REQUEST['action'])) { + if (!$request->has('action')) { $users = DB::select( 'SELECT `UID`, `Nick` FROM `User` WHERE NOT `UID`=? ORDER BY `Nick`', [$user['UID']] @@ -121,10 +122,10 @@ function user_messages() ], page_link_to('user_messages') . '&action=send') ]); } else { - switch ($_REQUEST['action']) { + switch ($request->input('action')) { case 'read': - if (isset($_REQUEST['id']) && preg_match('/^\d{1,11}$/', $_REQUEST['id'])) { - $message_id = $_REQUEST['id']; + if ($request->has('id') && preg_match('/^\d{1,11}$/', $request->input('id'))) { + $message_id = $request->input('id'); } else { return error(_('Incomplete call, missing Message ID.'), true); } @@ -145,8 +146,8 @@ function user_messages() break; case 'delete': - if (isset($_REQUEST['id']) && preg_match('/^\d{1,11}$/', $_REQUEST['id'])) { - $message_id = $_REQUEST['id']; + if ($request->has('id') && preg_match('/^\d{1,11}$/', $request->input('id'))) { + $message_id = $request->input('id'); } else { return error(_('Incomplete call, missing Message ID.'), true); } @@ -164,7 +165,8 @@ function user_messages() break; case 'send': - if (Message_send($_REQUEST['to'], $_REQUEST['text'])) { + // @TODO: Validation? + if (Message_send($request->input('to'), $request->input('text'))) { redirect(page_link_to('user_messages')); } else { return error(_('Transmitting was terminated with an Error.'), true); diff --git a/includes/pages/user_myshifts.php b/includes/pages/user_myshifts.php index 6048093a..14b5b8ee 100644 --- a/includes/pages/user_myshifts.php +++ b/includes/pages/user_myshifts.php @@ -18,14 +18,15 @@ function myshifts_title() function user_myshifts() { global $user, $privileges; + $request = request(); if ( - isset($_REQUEST['id']) + $request->has('id') && in_array('user_shifts_admin', $privileges) - && preg_match('/^\d{1,}$/', $_REQUEST['id']) - && count(DB::select('SELECT `UID` FROM `User` WHERE `UID`=?', [$_REQUEST['id']])) > 0 + && preg_match('/^\d{1,}$/', $request->input('id')) + && count(DB::select('SELECT `UID` FROM `User` WHERE `UID`=?', [$request->input('id')])) > 0 ) { - $user_id = $_REQUEST['id']; + $user_id = $request->input('id'); } else { $user_id = $user['UID']; } @@ -33,8 +34,8 @@ function user_myshifts() $shifts_user = DB::select('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$user_id]); $shifts_user = array_shift($shifts_user); - if (isset($_REQUEST['reset'])) { - if ($_REQUEST['reset'] == 'ack') { + if ($request->has('reset')) { + if ($request->input('reset') == 'ack') { User_reset_api_key($user); success(_('Key changed.')); redirect(page_link_to('users') . '&action=view&user_id=' . $shifts_user['UID']); @@ -46,8 +47,8 @@ function user_myshifts() ), button(page_link_to('user_myshifts') . '&reset=ack', _('Continue'), 'btn-danger') ]); - } elseif (isset($_REQUEST['edit']) && preg_match('/^\d*$/', $_REQUEST['edit'])) { - $user_id = $_REQUEST['edit']; + } elseif ($request->has('edit') && preg_match('/^\d*$/', $request->input('edit'))) { + $user_id = $request->input('edit'); $shift = DB::select(' SELECT `ShiftEntry`.`freeloaded`, @@ -77,10 +78,10 @@ function user_myshifts() $freeloaded = $shift['freeloaded']; $freeload_comment = $shift['freeload_comment']; - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { $valid = true; if (in_array('user_shifts_admin', $privileges)) { - $freeloaded = isset($_REQUEST['freeloaded']); + $freeloaded = $request->has('freeloaded'); $freeload_comment = strip_request_item_nl('freeload_comment'); if ($freeloaded && $freeload_comment == '') { $valid = false; @@ -128,8 +129,8 @@ function user_myshifts() } else { redirect(page_link_to('user_myshifts')); } - } elseif (isset($_REQUEST['cancel']) && preg_match('/^\d*$/', $_REQUEST['cancel'])) { - $user_id = $_REQUEST['cancel']; + } elseif ($request->has('cancel') && preg_match('/^\d*$/', $request->input('cancel'))) { + $user_id = $request->input('cancel'); $shift = DB::select(' SELECT * FROM `Shifts` diff --git a/includes/pages/user_news.php b/includes/pages/user_news.php index b1e337b6..9bdcb6fb 100644 --- a/includes/pages/user_news.php +++ b/includes/pages/user_news.php @@ -33,9 +33,10 @@ function user_meetings() { $display_news = config('display_news'); $html = '

      ' . meetings_title() . '

      ' . msg(); + $request = request(); - if (isset($_REQUEST['page']) && preg_match('/^\d{1,}$/', $_REQUEST['page'])) { - $page = $_REQUEST['page']; + if ($request->has('page') && preg_match('/^\d{1,}$/', $request->input('page'))) { + $page = $request->input('page'); } else { $page = 0; } @@ -56,9 +57,9 @@ function user_meetings() $dis_rows = ceil(count(DB::select('SELECT `ID` FROM `News`')) / $display_news); $html .= '
      ' . '
        '; for ($i = 0; $i < $dis_rows; $i++) { - if (isset($_REQUEST['page']) && $i == $_REQUEST['page']) { + if ($request->has('page') && $i == $request->input('page')) { $html .= '
      • '; - } elseif (!isset($_REQUEST['page']) && $i == 0) { + } elseif (!$request->has('page') && $i == 0) { $html .= '
      • '; } else { $html .= '
      • '; @@ -116,17 +117,19 @@ function user_news_comments() { global $user; + $request = request(); + $html = '

        ' . user_news_comments_title() . '

        '; if ( - isset($_REQUEST['nid']) - && preg_match('/^\d{1,}$/', $_REQUEST['nid']) - && count(DB::select('SELECT `ID` FROM `News` WHERE `ID`=? LIMIT 1', [$_REQUEST['nid']])) > 0 + $request->has('nid') + && preg_match('/^\d{1,}$/', $request->input('nid')) + && count(DB::select('SELECT `ID` FROM `News` WHERE `ID`=? LIMIT 1', [$request->input('nid')])) > 0 ) { - $nid = $_REQUEST['nid']; + $nid = $request->input('nid'); $news = DB::select('SELECT * FROM `News` WHERE `ID`=? LIMIT 1', [$nid]); $news = array_shift($news); - if (isset($_REQUEST['text'])) { - $text = preg_replace("/([^\p{L}\p{P}\p{Z}\p{N}\n]{1,})/ui", '', strip_tags($_REQUEST['text'])); + if ($request->has('text')) { + $text = preg_replace("/([^\p{L}\p{P}\p{Z}\p{N}\n]{1,})/ui", '', strip_tags($request->input('text'))); DB::insert(' INSERT INTO `NewsComments` (`Refid`, `Datum`, `Text`, `UID`) VALUES (?, ?, ?, ?) @@ -179,12 +182,14 @@ function user_news() { global $privileges, $user; $display_news = config('display_news'); + $request = request(); $html = '

        ' . news_title() . '

        ' . msg(); - if (isset($_POST['text']) && isset($_POST['betreff']) && in_array('admin_news', $privileges)) { - if (!isset($_POST['treffen']) || !in_array('admin_news', $privileges)) { - $_POST['treffen'] = 0; + $isMeeting = $request->post('treffen'); + if ($request->has('text') && $request->has('betreff') && in_array('admin_news', $privileges)) { + if (!$request->has('treffen') || !in_array('admin_news', $privileges)) { + $isMeeting = 0; } DB::insert(' INSERT INTO `News` (`Datum`, `Betreff`, `Text`, `UID`, `Treffen`) @@ -192,19 +197,19 @@ function user_news() ', [ time(), - $_POST['betreff'], - $_POST['text'], + $request->post('betreff'), + $request->post('text'), $user['UID'], - $_POST['treffen'], + $isMeeting, ] ); - engelsystem_log('Created news: ' . $_POST['betreff'] . ', treffen: ' . $_POST['treffen']); + engelsystem_log('Created news: ' . $_POST['betreff'] . ', treffen: ' . $isMeeting); success(_('Entry saved.')); redirect(page_link_to('news')); } - if (isset($_REQUEST['page']) && preg_match('/^\d{1,}$/', $_REQUEST['page'])) { - $page = $_REQUEST['page']; + if ($request->has('page') && preg_match('/^\d{1,}$/', $request->input('page'))) { + $page = $request->input('page'); } else { $page = 0; } @@ -225,9 +230,9 @@ function user_news() $dis_rows = ceil(count(DB::select('SELECT `ID` FROM `News`')) / $display_news); $html .= '
        ' . '
          '; for ($i = 0; $i < $dis_rows; $i++) { - if (isset($_REQUEST['page']) && $i == $_REQUEST['page']) { + if ($request->has('page') && $i == $request->input('page')) { $html .= '
        • '; - } elseif (!isset($_REQUEST['page']) && $i == 0) { + } elseif (!$request->has('page') && $i == 0) { $html .= '
        • '; } else { $html .= '
        • '; diff --git a/includes/pages/user_questions.php b/includes/pages/user_questions.php index 5cb60db3..fdf76aee 100644 --- a/includes/pages/user_questions.php +++ b/includes/pages/user_questions.php @@ -16,8 +16,9 @@ function questions_title() function user_questions() { global $user; + $request = request(); - if (!isset($_REQUEST['action'])) { + if (!$request->has('action')) { $open_questions = DB::select( 'SELECT * FROM `Questions` WHERE `AID` IS NULL AND `UID`=?', [$user['UID']] @@ -34,7 +35,7 @@ function user_questions() return Questions_view($open_questions, $answered_questions, page_link_to('user_questions') . '&action=ask'); } else { - switch ($_REQUEST['action']) { + switch ($request->input('action')) { case 'ask': $question = strip_request_item_nl('question'); if ($question != '') { @@ -56,8 +57,8 @@ function user_questions() } break; case 'delete': - if (isset($_REQUEST['id']) && preg_match('/^\d{1,11}$/', $_REQUEST['id'])) { - $question_id = $_REQUEST['id']; + if ($request->has('id') && preg_match('/^\d{1,11}$/', $request->input('id'))) { + $question_id = $request->input('id'); } else { return error(_('Incomplete call, missing Question ID.'), true); } diff --git a/includes/pages/user_settings.php b/includes/pages/user_settings.php index a2a486f4..69e5a7fb 100644 --- a/includes/pages/user_settings.php +++ b/includes/pages/user_settings.php @@ -21,9 +21,10 @@ function settings_title() function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) { $valid = true; + $request = request(); - if (isset($_REQUEST['mail'])) { - $result = User_validate_mail($_REQUEST['mail']); + if ($request->has('mail')) { + $result = User_validate_mail($request->input('mail')); $user_source['email'] = $result->getValue(); if (!$result->isValid()) { $valid = false; @@ -34,11 +35,11 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) error(_('Please enter your e-mail.')); } - $user_source['email_shiftinfo'] = isset($_REQUEST['email_shiftinfo']); - $user_source['email_by_human_allowed'] = isset($_REQUEST['email_by_human_allowed']); + $user_source['email_shiftinfo'] = $request->has('email_shiftinfo'); + $user_source['email_by_human_allowed'] = $request->has('email_by_human_allowed'); - if (isset($_REQUEST['jabber'])) { - $result = User_validate_jabber($_REQUEST['jabber']); + if ($request->has('jabber')) { + $result = User_validate_jabber($request->input('jabber')); $user_source['jabber'] = $result->getValue(); if (!$result->isValid()) { $valid = false; @@ -46,14 +47,14 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) } } - if (isset($_REQUEST['tshirt_size']) && isset($tshirt_sizes[$_REQUEST['tshirt_size']])) { - $user_source['Size'] = $_REQUEST['tshirt_size']; + if ($request->has('tshirt_size') && isset($tshirt_sizes[$request->input('tshirt_size')])) { + $user_source['Size'] = $request->input('tshirt_size'); } elseif ($enable_tshirt_size) { $valid = false; } - if (isset($_REQUEST['planned_arrival_date'])) { - $tmp = parse_date('Y-m-d H:i', $_REQUEST['planned_arrival_date'] . ' 00:00'); + if ($request->has('planned_arrival_date')) { + $tmp = parse_date('Y-m-d H:i', $request->input('planned_arrival_date') . ' 00:00'); $result = User_validate_planned_arrival_date($tmp); $user_source['planned_arrival_date'] = $result->getValue(); if (!$result->isValid()) { @@ -62,8 +63,8 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) } } - if (isset($_REQUEST['planned_departure_date'])) { - $tmp = parse_date('Y-m-d H:i', $_REQUEST['planned_departure_date'] . ' 00:00'); + if ($request->has('planned_departure_date')) { + $tmp = parse_date('Y-m-d H:i', $request->input('planned_departure_date') . ' 00:00'); $result = User_validate_planned_departure_date($user_source['planned_arrival_date'], $tmp); $user_source['planned_departure_date'] = $result->getValue(); if (!$result->isValid()) { @@ -97,16 +98,17 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) */ function user_settings_password($user_source) { + $request = request(); if ( - !isset($_REQUEST['password']) - || !verify_password($_REQUEST['password'], $user_source['Passwort'], $user_source['UID']) + !$request->has('password') + || !verify_password($request->post('password'), $user_source['Passwort'], $user_source['UID']) ) { error(_('-> not OK. Please try again.')); - } elseif (strlen($_REQUEST['new_password']) < config('min_password_length')) { + } elseif (strlen($request->post('new_password')) < config('min_password_length')) { error(_('Your password is to short (please use at least 6 characters).')); - } elseif ($_REQUEST['new_password'] != $_REQUEST['new_password2']) { + } elseif ($request->post('new_password') != $request->post('new_password2')) { error(_('Your passwords don\'t match.')); - } elseif (set_password($user_source['UID'], $_REQUEST['new_password'])) { + } elseif (set_password($user_source['UID'], $request->post('new_password'))) { success(_('Password saved.')); } else { error(_('Failed setting password.')); @@ -124,9 +126,10 @@ function user_settings_password($user_source) function user_settings_theme($user_source, $themes) { $valid = true; + $request = request(); - if (isset($_REQUEST['theme']) && isset($themes[$_REQUEST['theme']])) { - $user_source['color'] = $_REQUEST['theme']; + if ($request->has('theme') && isset($themes[$request->input('theme')])) { + $user_source['color'] = $request->input('theme'); } else { $valid = false; } @@ -160,9 +163,10 @@ function user_settings_theme($user_source, $themes) function user_settings_locale($user_source, $locales) { $valid = true; + $request = request(); - if (isset($_REQUEST['language']) && isset($locales[$_REQUEST['language']])) { - $user_source['Sprache'] = $_REQUEST['language']; + if ($request->has('language') && isset($locales[$request->input('language')])) { + $user_source['Sprache'] = $request->input('language'); } else { $valid = false; } @@ -195,6 +199,7 @@ function user_settings_locale($user_source, $locales) function user_settings() { global $themes, $user; + $request = request(); $enable_tshirt_size = config('enable_tshirt_size'); $tshirt_sizes = config('tshirt_sizes'); @@ -220,13 +225,13 @@ function user_settings() $user_source = $user; - if (isset($_REQUEST['submit'])) { + if ($request->has('submit')) { $user_source = user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes); - } elseif (isset($_REQUEST['submit_password'])) { + } elseif ($request->has('submit_password')) { user_settings_password($user_source); - } elseif (isset($_REQUEST['submit_theme'])) { + } elseif ($request->has('submit_theme')) { $user_source = user_settings_theme($user_source, $themes); - } elseif (isset($_REQUEST['submit_language'])) { + } elseif ($request->has('submit_language')) { $user_source = user_settings_locale($user_source, $locales); } diff --git a/includes/pages/user_shifts.php b/includes/pages/user_shifts.php index 55e49e4f..4dabdfb5 100644 --- a/includes/pages/user_shifts.php +++ b/includes/pages/user_shifts.php @@ -23,20 +23,21 @@ function shifts_title() function user_shifts() { global $user; + $request = request(); if (User_is_freeloader($user)) { redirect(page_link_to('user_myshifts')); } // Löschen einzelner Schicht-Einträge (Also Belegung einer Schicht von Engeln) durch Admins - if (isset($_REQUEST['entry_id'])) { + if ($request->has('entry_id')) { shift_entry_delete_controller(); return ''; - } elseif (isset($_REQUEST['edit_shift'])) { + } elseif ($request->has('edit_shift')) { return shift_edit_controller(); - } elseif (isset($_REQUEST['delete_shift'])) { + } elseif ($request->has('delete_shift')) { return shift_delete_controller(); - } elseif (isset($_REQUEST['shift_id'])) { + } elseif ($request->has('shift_id')) { return shift_entry_add_controller(); } return view_user_shifts(); diff --git a/includes/sys_page.php b/includes/sys_page.php index b2199988..501106ff 100644 --- a/includes/sys_page.php +++ b/includes/sys_page.php @@ -18,12 +18,14 @@ function check_request_datetime($date_name, $time_name, $allowed_days, $default_ { $time = date('H:i', $default_value); $day = date('Y-m-d', $default_value); + $request = request(); - if (isset($_REQUEST[$time_name]) && preg_match('#^\d{1,2}:\d\d$#', trim($_REQUEST[$time_name]))) { - $time = trim($_REQUEST[$time_name]); + if ($request->has($time_name) && preg_match('#^\d{1,2}:\d\d$#', trim($request->input($time_name)))) { + $time = trim($request->input($time_name)); } - if (isset($_REQUEST[$date_name]) && in_array($_REQUEST[$date_name], $allowed_days)) { - $day = $_REQUEST[$date_name]; + + if ($request->has($date_name) && in_array($request->input($date_name), $allowed_days)) { + $day = $request->input($date_name); } return parse_date('Y-m-d H:i', $day . ' ' . $time); @@ -94,8 +96,9 @@ function select_array($data, $key_name, $value_name) */ function check_request_int_array($name, $default = []) { - if (isset($_REQUEST[$name]) && is_array($_REQUEST[$name])) { - return array_filter($_REQUEST[$name], 'is_numeric'); + $request = request(); + if ($request->has($name) && is_array($request->input($name))) { + return array_filter($request->input($name), 'is_numeric'); } return $default; } @@ -111,10 +114,11 @@ function check_request_int_array($name, $default = []) */ function check_request_date($name, $error_message = null, $null_allowed = false) { - if (!isset($_REQUEST[$name])) { + $request = request(); + if (!$request->has($name)) { return new ValidationResult($null_allowed, null); } - return check_date($_REQUEST[$name], $error_message, $null_allowed); + return check_date($request->input($name), $error_message, $null_allowed); } /** @@ -148,8 +152,9 @@ function check_date($input, $error_message = null, $null_allowed = false) */ function strip_request_item($name, $default_value = null) { - if (isset($_REQUEST[$name])) { - return strip_item($_REQUEST[$name]); + $request = request(); + if ($request->has($name)) { + return strip_item($request->input($name)); } return $default_value; } @@ -163,8 +168,9 @@ function strip_request_item($name, $default_value = null) */ function test_request_int($name) { - if (isset($_REQUEST[$name])) { - return preg_match('/^\d*$/', $_REQUEST[$name]); + $request = request(); + if ($request->has($name)) { + return preg_match('/^\d*$/', $request->input($name)); } return false; } @@ -178,8 +184,9 @@ function test_request_int($name) */ function strip_request_item_nl($name, $default_value = null) { - if (isset($_REQUEST[$name])) { - return preg_replace("/([^\p{L}\p{S}\p{P}\p{Z}\p{N}+\n]{1,})/ui", '', strip_tags($_REQUEST[$name])); + $request = request(); + if ($request->has($name)) { + return preg_replace("/([^\p{L}\p{S}\p{P}\p{Z}\p{N}+\n]{1,})/ui", '', strip_tags($request->get($name))); } return $default_value; } diff --git a/includes/sys_template.php b/includes/sys_template.php index 7aa458b8..1d3943b7 100644 --- a/includes/sys_template.php +++ b/includes/sys_template.php @@ -335,11 +335,11 @@ function table_buttons($buttons = []) /** * Load and render template * - * @param string $file - * @param string $data + * @param string $file + * @param string[] $data * @return string */ -function template_render($file, $data) +function template_render($file, $data = []) { if (file_exists($file)) { $template = file_get_contents($file); diff --git a/public/index.php b/public/index.php index 895b4fe0..52f32438 100644 --- a/public/index.php +++ b/public/index.php @@ -24,24 +24,22 @@ $page = ''; $title = ''; $content = ''; -if (!isset($_REQUEST['p'])) { - $_REQUEST['p'] = isset($user) ? 'news' : 'login'; +$page = $request->input('p'); +if (empty($page)) { + $page = isset($user) ? 'news' : 'login'; } if ( - isset($_REQUEST['p']) - && preg_match('/^\w*$/i', $_REQUEST['p']) + preg_match('/^\w*$/i', $page) && ( - in_array($_REQUEST['p'], $free_pages) - || (isset($privileges) && in_array($_REQUEST['p'], $privileges)) + in_array($page, $free_pages) + || (isset($privileges) && in_array($page, $privileges)) ) ) { - $page = $_REQUEST['p']; - $title = $page; if ($page == 'api') { - error('Api disabled temporily.'); + error('Api disabled temporarily.'); redirect(page_link_to()); require_once realpath(__DIR__ . '/../includes/controller/api.php'); api_controller(); diff --git a/src/Http/Request.php b/src/Http/Request.php new file mode 100644 index 00000000..2efd1e1d --- /dev/null +++ b/src/Http/Request.php @@ -0,0 +1,110 @@ +request = $_POST; + $this->query = $_GET; + } + + /** + * Get GET input + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function get($key, $default = null) + { + if (!empty($this->query[$key])) { + return $this->query[$key]; + } + + return $default; + } + + /** + * Get POST input + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function post($key, $default = null) + { + if (!empty($this->request[$key])) { + return $this->request[$key]; + } + + return $default; + } + + /** + * Get input data + * + * @param string $key + * @param mixed $default + * @return mixed + */ + public function input($key, $default = null) + { + $data = $this->request + $this->query; + + if (!empty($data[$key])) { + return $data[$key]; + } + + return $default; + } + + /** + * Checks if the input exists + * + * @param string $key + * @return bool + */ + public function has($key) + { + $value = $this->input($key); + + return !empty($value); + } + + /** + * @return self + * @throws ErrorException + */ + public static function getInstance() + { + if (!self::$instance instanceof self) { + throw new ErrorException('Request not initialized'); + } + + return self::$instance; + } + + /** + * @param self $instance + */ + public static function setInstance($instance) + { + self::$instance = $instance; + } +} diff --git a/src/helpers.php b/src/helpers.php index aeb256e9..a410b27e 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -2,6 +2,7 @@ // Some useful functions use Engelsystem\Config\Config; +use Engelsystem\Http\Request; /** * Get or set config values @@ -22,3 +23,19 @@ function config($key = null, $default = null) return Config::getInstance()->get($key, $default); } + +/** + * @param string $key + * @param mixed $default + * @return Request|mixed + */ +function request($key = null, $default = null) +{ + $request = Request::getInstance(); + + if (is_null($key)) { + return $request; + } + + return $request->input($key, $default); +} -- cgit v1.2.3-54-g00ecf From e93dd774a5c8338b6c29b8b39b6d883925b9ac61 Mon Sep 17 00:00:00 2001 From: msquare Date: Wed, 19 Jul 2017 21:28:26 +0200 Subject: fix small issues on checking success of a db query --- includes/model/EventConfig_model.php | 2 +- src/Database/Db.php | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/includes/model/EventConfig_model.php b/includes/model/EventConfig_model.php index f5846870..112ad457 100644 --- a/includes/model/EventConfig_model.php +++ b/includes/model/EventConfig_model.php @@ -64,7 +64,7 @@ function EventConfig_update( ); } - return (bool)DB::update(' + return DB::update(' UPDATE `EventConfig` SET `event_name` = ?, `buildup_start_date` = ?, diff --git a/src/Database/Db.php b/src/Database/Db.php index c1efa058..4116ffda 100644 --- a/src/Database/Db.php +++ b/src/Database/Db.php @@ -81,31 +81,31 @@ class Db } /** - * Run a insert query + * Run an insert query * * @param string $query * @param array $bindings - * @return bool + * @return int|bool */ public static function insert($query, array $bindings = []) { self::query($query, $bindings); - return self::$lastStatus; + return (self::$lastStatus ? self::$stm->rowCount() : false); } /** - * Run a update query + * Run an update query * * @param string $query * @param array $bindings - * @return int|null + * @return int|bool */ public static function update($query, array $bindings = []) { self::query($query, $bindings); - return (self::$lastStatus ? self::$stm->rowCount() : null); + return (self::$lastStatus ? self::$stm->rowCount() : false); } /** @@ -113,13 +113,13 @@ class Db * * @param string $query * @param array $bindings - * @return int|null + * @return int|bool */ public static function delete($query, array $bindings = []) { self::query($query, $bindings); - return (self::$lastStatus ? self::$stm->rowCount() : null); + return (self::$lastStatus ? self::$stm->rowCount() : false); } /** -- cgit v1.2.3-54-g00ecf From e1762e7764d4ee4f37757ecd2630f62a440dbf0e Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Thu, 20 Jul 2017 02:22:18 +0200 Subject: replaced template_render with dynamic renderer class --- includes/engelsystem_provider.php | 12 +++++- includes/pages/guest_credits.php | 2 +- includes/pages/user_shifts.php | 2 +- includes/sys_template.php | 22 ---------- public/index.php | 2 +- public/maintenance.html | 86 --------------------------------------- src/Renderer/EngineInterface.php | 21 ++++++++++ src/Renderer/HtmlEngine.php | 34 ++++++++++++++++ src/Renderer/Renderer.php | 62 ++++++++++++++++++++++++++++ src/helpers.php | 17 ++++++++ templates/maintenance.html | 86 +++++++++++++++++++++++++++++++++++++++ 11 files changed, 234 insertions(+), 112 deletions(-) delete mode 100644 public/maintenance.html create mode 100644 src/Renderer/EngineInterface.php create mode 100644 src/Renderer/HtmlEngine.php create mode 100644 src/Renderer/Renderer.php create mode 100644 templates/maintenance.html (limited to 'src') diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index edfae705..ff682871 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -4,6 +4,8 @@ use Engelsystem\Config\Config; use Engelsystem\Database\Db; use Engelsystem\Exceptions\Handler as ExceptionHandler; use Engelsystem\Http\Request; +use Engelsystem\Renderer\HtmlEngine; +use Engelsystem\Renderer\Renderer; /** * This file includes all needed functions, connects to the db etc. @@ -43,11 +45,19 @@ $request::setInstance($request); * Check for maintenance */ if ($config->get('maintenance')) { - echo file_get_contents(__DIR__ . '/../public/maintenance.html'); + echo file_get_contents(__DIR__ . '/../templates/maintenance.html'); die(); } +/** + * Initialize renderer + */ +$renderer = new Renderer(); +$renderer->addRenderer(new HtmlEngine()); +Renderer::setInstance($renderer); + + /** * Register error handler */ diff --git a/includes/pages/guest_credits.php b/includes/pages/guest_credits.php index d9224cbb..db86132d 100644 --- a/includes/pages/guest_credits.php +++ b/includes/pages/guest_credits.php @@ -13,5 +13,5 @@ function credits_title() */ function guest_credits() { - return template_render(__DIR__ . '/../../templates/guest_credits.html', []); + return view(__DIR__ . '/../../templates/guest_credits.html'); } diff --git a/includes/pages/user_shifts.php b/includes/pages/user_shifts.php index 4dabdfb5..813cb9b3 100644 --- a/includes/pages/user_shifts.php +++ b/includes/pages/user_shifts.php @@ -206,7 +206,7 @@ function view_user_shifts() return page([ div('col-md-12', [ msg(), - template_render(__DIR__ . '/../../templates/user_shifts.html', [ + view(__DIR__ . '/../../templates/user_shifts.html', [ 'title' => shifts_title(), 'room_select' => make_select($rooms, $shiftsFilter->getRooms(), 'rooms', _('Rooms')), 'start_select' => html_select_key('start_day', 'start_day', array_combine($days, $days), $start_day), diff --git a/includes/sys_template.php b/includes/sys_template.php index bcf462d7..a659a7f3 100644 --- a/includes/sys_template.php +++ b/includes/sys_template.php @@ -321,28 +321,6 @@ function table_buttons($buttons = []) return '
          ' . join(' ', $buttons) . '
          '; } -/** - * Load and render template - * - * @param string $file - * @param string[] $data - * @return string - */ -function template_render($file, $data = []) -{ - if (file_exists($file)) { - $template = file_get_contents($file); - if (is_array($data)) { - foreach ($data as $name => $content) { - $template = str_replace('%' . $name . '%', $content, $template); - } - } - return $template; - } - engelsystem_error('Cannot find template file «' . $file . '».'); - return ''; -} - /** * @param string $str * @param int $length diff --git a/public/index.php b/public/index.php index 52f32438..f22721c8 100644 --- a/public/index.php +++ b/public/index.php @@ -166,7 +166,7 @@ if ( $event_config = EventConfig(); -echo template_render(__DIR__ . '/../templates/layout.html', [ +echo view(__DIR__ . '/../templates/layout.html', [ 'theme' => isset($user) ? $user['color'] : config('theme'), 'title' => $title, 'atom_link' => ($page == 'news' || $page == 'user_meetings') diff --git a/public/maintenance.html b/public/maintenance.html deleted file mode 100644 index 3f7dae8a..00000000 --- a/public/maintenance.html +++ /dev/null @@ -1,86 +0,0 @@ - - - - Maintenance - Engelsystem - - - - - - - - - - -
          -
          -
          -
          -

          - - - -

          -
          -

          - The ENGELSYSTEM is in maintenance mode. -

          -

          This may be due to...

          -

          - ...archangels closing the gates of heaven.
          - ...somebody's stolen the power chord and now the battery is empty.
          - ...DHCP decided to give me another ip address. -

          -
          -
          - -
          -
          -
          -
          - -
          - - - - - - - - - - diff --git a/src/Renderer/EngineInterface.php b/src/Renderer/EngineInterface.php new file mode 100644 index 00000000..ca468db5 --- /dev/null +++ b/src/Renderer/EngineInterface.php @@ -0,0 +1,21 @@ + $content) { + $template = str_replace('%' . $name . '%', $content, $template); + } + } + + return $template; + } + + /** + * @param string $path + * @return bool + */ + public function canRender($path) + { + return strpos($path, '.html') && file_exists($path); + } +} diff --git a/src/Renderer/Renderer.php b/src/Renderer/Renderer.php new file mode 100644 index 00000000..bf3d5609 --- /dev/null +++ b/src/Renderer/Renderer.php @@ -0,0 +1,62 @@ +renderer as $renderer) { + if (!$renderer->canRender($template)) { + continue; + } + + return $renderer->get($template, $data); + } + + engelsystem_error('Unable to find a renderer for template file «' . $template . '».'); + return ''; + } + + /** + * Add a new renderer engine + * + * @param EngineInterface $renderer + */ + public function addRenderer(EngineInterface $renderer) + { + $this->renderer[] = $renderer; + } + + /** + * @return self + * @throws ErrorException + */ + public static function getInstance() + { + return self::$instance; + } + + /** + * @param self $instance + */ + public static function setInstance($instance) + { + self::$instance = $instance; + } +} diff --git a/src/helpers.php b/src/helpers.php index a410b27e..d44d1d21 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -3,6 +3,7 @@ use Engelsystem\Config\Config; use Engelsystem\Http\Request; +use Engelsystem\Renderer\Renderer; /** * Get or set config values @@ -39,3 +40,19 @@ function request($key = null, $default = null) return $request->input($key, $default); } + +/** + * @param string $template + * @param mixed[] $data + * @return Renderer|string + */ +function view($template = null, $data = null) +{ + $renderer = Renderer::getInstance(); + + if (is_null($template)) { + return $renderer; + } + + return $renderer->render($template, $data); +} diff --git a/templates/maintenance.html b/templates/maintenance.html new file mode 100644 index 00000000..3f7dae8a --- /dev/null +++ b/templates/maintenance.html @@ -0,0 +1,86 @@ + + + + Maintenance - Engelsystem + + + + + + + + + + +
          +
          +
          +
          +

          + + + +

          +
          +

          + The ENGELSYSTEM is in maintenance mode. +

          +

          This may be due to...

          +

          + ...archangels closing the gates of heaven.
          + ...somebody's stolen the power chord and now the battery is empty.
          + ...DHCP decided to give me another ip address. +

          +
          +
          + +
          +
          +
          +
          + +
          + + + + + + + + + + -- cgit v1.2.3-54-g00ecf From a157004f4aefaa5e2265f852f9432becedee1d66 Mon Sep 17 00:00:00 2001 From: msquare Date: Sun, 23 Jul 2017 11:46:54 +0200 Subject: handle failed db queries in Db class --- includes/controller/event_config_controller.php | 6 +---- includes/controller/shift_entries_controller.php | 5 +---- includes/controller/shifts_controller.php | 5 +---- includes/controller/shifttypes_controller.php | 10 +++------ includes/controller/users_controller.php | 5 +---- includes/model/AngelType_model.php | 14 ++++-------- includes/model/EventConfig_model.php | 2 +- includes/model/NeededAngelTypes_model.php | 5 +---- includes/model/Room_model.php | 5 +---- includes/model/ShiftEntry_model.php | 3 --- includes/model/ShiftTypes_model.php | 9 +------- includes/model/Shifts_model.php | 4 ++-- includes/model/UserAngelTypes_model.php | 28 +++--------------------- includes/model/UserDriverLicenses_model.php | 10 +-------- includes/model/User_model.php | 12 +--------- includes/pages/admin_import.php | 4 +--- includes/pages/admin_rooms.php | 4 +--- includes/pages/user_myshifts.php | 5 +---- includes/pages/user_questions.php | 6 ++--- includes/pages/user_settings.php | 6 ++--- includes/sys_auth.php | 7 +----- src/Database/Db.php | 8 +++---- 22 files changed, 35 insertions(+), 128 deletions(-) (limited to 'src') diff --git a/includes/controller/event_config_controller.php b/includes/controller/event_config_controller.php index dcdcf54a..7d11ecb4 100644 --- a/includes/controller/event_config_controller.php +++ b/includes/controller/event_config_controller.php @@ -91,7 +91,7 @@ function event_config_edit_controller() } if ($valid) { - $result = EventConfig_update( + EventConfig_update( $event_name, $buildup_start_date, $event_start_date, @@ -100,10 +100,6 @@ function event_config_edit_controller() $event_welcome_msg ); - if ($result === false) { - engelsystem_error('Unable to update event config.'); - } - engelsystem_log( 'Changed event config: $event_name, $event_welcome_msg, ' . date('Y-m-d', $buildup_start_date) . ', ' . date('Y-m-d', $event_start_date) . ', ' diff --git a/includes/controller/shift_entries_controller.php b/includes/controller/shift_entries_controller.php index 38aad5bb..54c57332 100644 --- a/includes/controller/shift_entries_controller.php +++ b/includes/controller/shift_entries_controller.php @@ -130,7 +130,7 @@ function shift_entry_add_controller() } $comment = strip_request_item_nl('comment'); - $result = ShiftEntry_create([ + ShiftEntry_create([ 'SID' => $shift_id, 'TID' => $selected_type_id, 'UID' => $user_id, @@ -138,9 +138,6 @@ function shift_entry_add_controller() 'freeloaded' => $freeloaded, 'freeload_comment' => $freeload_comment ]); - if ($result === false) { - engelsystem_error('Unable to create shift entry.'); - } if ( $type['restricted'] == 0 diff --git a/includes/controller/shifts_controller.php b/includes/controller/shifts_controller.php index 21c6e160..b3ebd18b 100644 --- a/includes/controller/shifts_controller.php +++ b/includes/controller/shifts_controller.php @@ -135,10 +135,7 @@ function shift_edit_controller() $shift['start'] = $start; $shift['end'] = $end; - $result = Shift_update($shift); - if ($result === false) { - engelsystem_error('Unable to update shift.'); - } + Shift_update($shift); NeededAngelTypes_delete_by_shift($shift_id); $needed_angel_types_info = []; foreach ($needed_angel_types as $type_id => $count) { diff --git a/includes/controller/shifttypes_controller.php b/includes/controller/shifttypes_controller.php index acdeb982..790bbb56 100644 --- a/includes/controller/shifttypes_controller.php +++ b/includes/controller/shifttypes_controller.php @@ -93,17 +93,13 @@ function shifttype_edit_controller() if ($valid) { if ($shifttype_id) { - $result = ShiftType_update($shifttype_id, $name, $angeltype_id, $description); - if ($result === false) { - engelsystem_error('Unable to update shifttype.'); - } + ShiftType_update($shifttype_id, $name, $angeltype_id, $description); + engelsystem_log('Updated shifttype ' . $name); success(_('Updated shifttype.')); } else { $shifttype_id = ShiftType_create($name, $angeltype_id, $description); - if ($shifttype_id === false) { - engelsystem_error('Unable to create shifttype.'); - } + engelsystem_log('Created shifttype ' . $name); success(_('Created shifttype.')); } diff --git a/includes/controller/users_controller.php b/includes/controller/users_controller.php index b747cc83..f441c8af 100644 --- a/includes/controller/users_controller.php +++ b/includes/controller/users_controller.php @@ -166,10 +166,7 @@ function user_edit_vouchers_controller() if ($valid) { $user_source['got_voucher'] = $vouchers; - $result = User_update($user_source); - if ($result === false) { - engelsystem_error('Unable to update user.'); - } + User_update($user_source); success(_('Saved the number of vouchers.')); engelsystem_log(User_Nick_render($user_source) . ': ' . sprintf('Got %s vouchers', diff --git a/includes/model/AngelType_model.php b/includes/model/AngelType_model.php index d437f526..af213432 100644 --- a/includes/model/AngelType_model.php +++ b/includes/model/AngelType_model.php @@ -97,11 +97,10 @@ function AngelType_delete($angeltype) * Update Angeltype. * * @param array $angeltype The angeltype - * @return bool */ function AngelType_update($angeltype) { - $result = DB::update(' + DB::update(' UPDATE `AngelTypes` SET `name` = ?, `restricted` = ?, @@ -126,15 +125,12 @@ function AngelType_update($angeltype) $angeltype['id'], ] ); - if (is_null($result)) { - engelsystem_error('Unable to update angeltype.'); - } + engelsystem_log( 'Updated angeltype: ' . $angeltype['name'] . ($angeltype['restricted'] ? ', restricted' : '') . ($angeltype['no_self_signup'] ? ', no_self_signup' : '') . ($angeltype['requires_driver_license'] ? ', requires driver license' : '') ); - return true; } /** @@ -145,7 +141,7 @@ function AngelType_update($angeltype) */ function AngelType_create($angeltype) { - $result = DB::insert(' + DB::insert(' INSERT INTO `AngelTypes` ( `name`, `restricted`, @@ -171,9 +167,7 @@ function AngelType_create($angeltype) $angeltype['contact_email'], ] ); - if (is_null($result)) { - engelsystem_error('Unable to create angeltype.'); - } + $angeltype['id'] = DB::getPdo()->lastInsertId(); engelsystem_log( 'Created angeltype: ' . $angeltype['name'] diff --git a/includes/model/EventConfig_model.php b/includes/model/EventConfig_model.php index 112ad457..b5d3cc73 100644 --- a/includes/model/EventConfig_model.php +++ b/includes/model/EventConfig_model.php @@ -31,7 +31,7 @@ function EventConfig() * @param int $event_end_date * @param int $teardown_end_date * @param string $event_welcome_msg - * @return bool + * @return int Rows updated */ function EventConfig_update( $event_name, diff --git a/includes/model/NeededAngelTypes_model.php b/includes/model/NeededAngelTypes_model.php index 97b085f0..e77c715f 100644 --- a/includes/model/NeededAngelTypes_model.php +++ b/includes/model/NeededAngelTypes_model.php @@ -17,7 +17,7 @@ use Engelsystem\Database\DB; */ function NeededAngelType_add($shift_id, $angeltype_id, $room_id, $count) { - $result = DB::insert(' + DB::insert(' INSERT INTO `NeededAngelTypes` ( `shift_id`, `angel_type_id`, `room_id`, `count`) VALUES (?, ?, ?, ?) ', @@ -27,9 +27,6 @@ function NeededAngelType_add($shift_id, $angeltype_id, $room_id, $count) $room_id, $count, ]); - if ($result === false) { - return false; - } return DB::getPdo()->lastInsertId(); } diff --git a/includes/model/Room_model.php b/includes/model/Room_model.php index 17617b39..fdd9dddc 100644 --- a/includes/model/Room_model.php +++ b/includes/model/Room_model.php @@ -35,7 +35,7 @@ function Room_delete($room_id) */ function Room_create($name, $from_frab, $public, $number = null) { - $result = DB::insert(' + DB::insert(' INSERT INTO `Room` (`Name`, `FromPentabarf`, `show`, `Number`) VALUES (?, ?, ?, ?) ', @@ -46,9 +46,6 @@ function Room_create($name, $from_frab, $public, $number = null) (int)$number, ] ); - if (!$result) { - return false; - } return DB::getPdo()->lastInsertId(); } diff --git a/includes/model/ShiftEntry_model.php b/includes/model/ShiftEntry_model.php index d7810feb..3a282efc 100644 --- a/includes/model/ShiftEntry_model.php +++ b/includes/model/ShiftEntry_model.php @@ -102,7 +102,6 @@ function ShiftEntry_create($shift_entry) * Update a shift entry. * * @param array $shift_entry - * @return bool */ function ShiftEntry_update($shift_entry) { @@ -120,8 +119,6 @@ function ShiftEntry_update($shift_entry) $shift_entry['id'] ] ); - - return (DB::getStm()->errorCode() == '00000'); } /** diff --git a/includes/model/ShiftTypes_model.php b/includes/model/ShiftTypes_model.php index 96a823d4..12fe38be 100644 --- a/includes/model/ShiftTypes_model.php +++ b/includes/model/ShiftTypes_model.php @@ -20,7 +20,6 @@ function ShiftType_delete($shifttype_id) * @param string $name * @param int $angeltype_id * @param string $description - * @return bool */ function ShiftType_update($shifttype_id, $name, $angeltype_id, $description) { @@ -38,8 +37,6 @@ function ShiftType_update($shifttype_id, $name, $angeltype_id, $description) $shifttype_id, ] ); - - return DB::getStm()->errorCode() == '00000'; } /** @@ -52,7 +49,7 @@ function ShiftType_update($shifttype_id, $name, $angeltype_id, $description) */ function ShiftType_create($name, $angeltype_id, $description) { - $result = DB::insert(' + DB::insert(' INSERT INTO `ShiftTypes` (`name`, `angeltype_id`, `description`) VALUES(?, ?, ?) ', @@ -63,10 +60,6 @@ function ShiftType_create($name, $angeltype_id, $description) ] ); - if ($result === false) { - return false; - } - return DB::getPdo()->lastInsertId(); } diff --git a/includes/model/Shifts_model.php b/includes/model/Shifts_model.php index 21abc888..6e69fe35 100644 --- a/includes/model/Shifts_model.php +++ b/includes/model/Shifts_model.php @@ -436,7 +436,7 @@ function Shift_delete($shift_id) * Update a shift. * * @param array $shift - * @return bool + * @return int Updated row count */ function Shift_update($shift) { @@ -444,7 +444,7 @@ function Shift_update($shift) $shift['name'] = ShiftType($shift['shifttype_id'])['name']; mail_shift_change(Shift($shift['SID']), $shift); - return (bool)DB::update(' + return DB::update(' UPDATE `Shifts` SET `shifttype_id` = ?, `start` = ?, diff --git a/includes/model/UserAngelTypes_model.php b/includes/model/UserAngelTypes_model.php index 82f390ee..f8277fd9 100644 --- a/includes/model/UserAngelTypes_model.php +++ b/includes/model/UserAngelTypes_model.php @@ -110,22 +110,15 @@ function User_is_AngelType_supporter(&$user, $angeltype) * * @param int $user_angeltype_id * @param bool $supporter - * @return int */ function UserAngelType_update($user_angeltype_id, $supporter) { - $result = DB::update(' + DB::update(' UPDATE `UserAngelTypes` SET `supporter`=? WHERE `id`=? LIMIT 1 ', [$supporter, $user_angeltype_id]); - - if (DB::getStm()->errorCode() != '00000') { - engelsystem_error('Unable to update supporter rights.'); - } - - return $result; } /** @@ -154,22 +147,15 @@ function UserAngelTypes_delete_all($angeltype_id) * * @param int $angeltype_id * @param array $confirm_user - * @return bool */ function UserAngelTypes_confirm_all($angeltype_id, $confirm_user) { - $result = DB::update(' + DB::update(' UPDATE `UserAngelTypes` SET `confirm_user_id`=? WHERE `angeltype_id`=? AND `confirm_user_id` IS NULL ', [$confirm_user['UID'], $angeltype_id]); - - if (DB::getStm()->errorCode() != '00000') { - engelsystem_error('Unable to confirm all users.'); - } - - return (bool)$result; } /** @@ -181,15 +167,11 @@ function UserAngelTypes_confirm_all($angeltype_id, $confirm_user) */ function UserAngelType_confirm($user_angeltype_id, $confirm_user) { - $result = DB::update(' + DB::update(' UPDATE `UserAngelTypes` SET `confirm_user_id`=? WHERE `id`=? LIMIT 1', [$confirm_user['UID'], $user_angeltype_id]); - if (DB::getStm()->errorCode() != '00000') { - engelsystem_error('Unable to confirm user angeltype.'); - } - return (bool)$result; } /** @@ -225,10 +207,6 @@ function UserAngelType_create($user, $angeltype) ] ); - if (DB::getStm()->errorCode() != '00000') { - engelsystem_error('Unable to create user angeltype.'); - } - return DB::getPdo()->lastInsertId(); } diff --git a/includes/model/UserDriverLicenses_model.php b/includes/model/UserDriverLicenses_model.php index 525d2016..ee93ac95 100644 --- a/includes/model/UserDriverLicenses_model.php +++ b/includes/model/UserDriverLicenses_model.php @@ -94,9 +94,6 @@ function UserDriverLicenses_create($user_driver_license, $user) (bool)$user_driver_license['has_license_forklift'], ] ); - if (DB::getStm()->errorCode() != '00000') { - engelsystem_error('Unable to create user driver license'); - } return $user_driver_license; } @@ -105,11 +102,10 @@ function UserDriverLicenses_create($user_driver_license, $user) * Update a user's driver license entry * * @param array $user_driver_license The UserDriverLicense to update - * @return bool */ function UserDriverLicenses_update($user_driver_license) { - $result = DB::update(' + DB::update(' UPDATE `UserDriverLicenses` SET `has_car`=?, @@ -130,10 +126,6 @@ function UserDriverLicenses_update($user_driver_license) $user_driver_license['user_id'], ] ); - if (DB::getStm()->errorCode() != '00000') { - engelsystem_error('Unable to update user driver license information'); - } - return $result; } /** diff --git a/includes/model/User_model.php b/includes/model/User_model.php index 2913c1a1..9f767b74 100644 --- a/includes/model/User_model.php +++ b/includes/model/User_model.php @@ -24,11 +24,10 @@ function User_delete($user_id) * Update user. * * @param array $user - * @return bool */ function User_update($user) { - return (bool)DB::update(' + DB::update(' UPDATE `User` SET `Nick`=?, `Name`=?, @@ -481,7 +480,6 @@ function User_by_password_recovery_token($token) * * @param array $user * @param bool $log - * @return bool */ function User_reset_api_key(&$user, $log = true) { @@ -497,15 +495,10 @@ function User_reset_api_key(&$user, $log = true) $user['UID'] ] ); - if (DB::getStm()->errorCode() != '00000') { - return false; - } if ($log) { engelsystem_log(sprintf('API key resetted (%s).', User_Nick_render($user))); } - - return true; } /** @@ -528,9 +521,6 @@ function User_generate_password_recovery_token(&$user) $user['UID'], ] ); - if (DB::getStm()->errorCode() != '00000') { - engelsystem_error('Unable to generate password recovery token.'); - } engelsystem_log('Password recovery for ' . User_Nick_render($user) . ' started.'); return $user['password_recovery_token']; } diff --git a/includes/pages/admin_import.php b/includes/pages/admin_import.php index 3cbed9f9..959a9d2e 100644 --- a/includes/pages/admin_import.php +++ b/includes/pages/admin_import.php @@ -251,9 +251,7 @@ function admin_import() list($rooms_new, $rooms_deleted) = prepare_rooms($import_file); foreach ($rooms_new as $room) { $result = Room_create($room, true, true); - if ($result === false) { - engelsystem_error('Unable to create room.'); - } + $rooms_import[trim($room)] = $result; } foreach ($rooms_deleted as $room) { diff --git a/includes/pages/admin_rooms.php b/includes/pages/admin_rooms.php index 3045242b..ad8eab83 100644 --- a/includes/pages/admin_rooms.php +++ b/includes/pages/admin_rooms.php @@ -147,9 +147,7 @@ function admin_rooms() ); } else { $room_id = Room_create($name, $from_pentabarf, $public, $number); - if ($room_id === false) { - engelsystem_error('Unable to create room.'); - } + engelsystem_log( 'Room created: ' . $name . ', pentabarf import: ' diff --git a/includes/pages/user_myshifts.php b/includes/pages/user_myshifts.php index 14b5b8ee..94116fc9 100644 --- a/includes/pages/user_myshifts.php +++ b/includes/pages/user_myshifts.php @@ -93,15 +93,12 @@ function user_myshifts() $user_source = User($shift['UID']); if ($valid) { - $result = ShiftEntry_update([ + ShiftEntry_update([ 'id' => $user_id, 'Comment' => $comment, 'freeloaded' => $freeloaded, 'freeload_comment' => $freeload_comment ]); - if ($result === false) { - engelsystem_error('Unable to update shift entry.'); - } engelsystem_log( 'Updated ' . User_Nick_render($user_source) . '\'s shift ' . $shift['name'] diff --git a/includes/pages/user_questions.php b/includes/pages/user_questions.php index fdf76aee..e90ea011 100644 --- a/includes/pages/user_questions.php +++ b/includes/pages/user_questions.php @@ -39,15 +39,13 @@ function user_questions() case 'ask': $question = strip_request_item_nl('question'); if ($question != '') { - $result = DB::insert(' + DB::insert(' INSERT INTO `Questions` (`UID`, `Question`) VALUES (?, ?) ', [$user['UID'], $question] ); - if (!$result) { - engelsystem_error(_('Unable to save question.')); - } + success(_('You question was saved.')); redirect(page_link_to('user_questions')); } else { diff --git a/includes/pages/user_settings.php b/includes/pages/user_settings.php index 667e73d9..7edee7b5 100644 --- a/includes/pages/user_settings.php +++ b/includes/pages/user_settings.php @@ -84,6 +84,7 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) if ($valid) { User_update($user_source); + success(_('Settings saved.')); redirect(page_link_to('user_settings')); } @@ -108,10 +109,9 @@ function user_settings_password($user_source) error(_('Your password is to short (please use at least 6 characters).')); } elseif ($request->post('new_password') != $request->post('new_password2')) { error(_('Your passwords don\'t match.')); - } elseif (set_password($user_source['UID'], $request->post('new_password'))) { - success(_('Password saved.')); } else { - error(_('Failed setting password.')); + set_password($user_source['UID'], $request->post('new_password')); + success(_('Password saved.')); } redirect(page_link_to('user_settings')); } diff --git a/includes/sys_auth.php b/includes/sys_auth.php index 856ed4ab..f1ec3192 100644 --- a/includes/sys_auth.php +++ b/includes/sys_auth.php @@ -55,11 +55,10 @@ function generate_salt($length = 16) * * @param int $uid * @param string $password - * @return bool */ function set_password($uid, $password) { - $result = DB::update(' + DB::update(' UPDATE `User` SET `Passwort` = ?, `password_recovery_token`=NULL @@ -71,10 +70,6 @@ function set_password($uid, $password) $uid ] ); - if (DB::getStm()->errorCode() != '00000') { - engelsystem_error('Unable to update password.'); - } - return $result; } /** diff --git a/src/Database/Db.php b/src/Database/Db.php index 4116ffda..46edc96b 100644 --- a/src/Database/Db.php +++ b/src/Database/Db.php @@ -85,13 +85,13 @@ class Db * * @param string $query * @param array $bindings - * @return int|bool + * @return int Row count */ public static function insert($query, array $bindings = []) { self::query($query, $bindings); - return (self::$lastStatus ? self::$stm->rowCount() : false); + return self::$stm->rowCount(); } /** @@ -99,13 +99,13 @@ class Db * * @param string $query * @param array $bindings - * @return int|bool + * @return int */ public static function update($query, array $bindings = []) { self::query($query, $bindings); - return (self::$lastStatus ? self::$stm->rowCount() : false); + return self::$stm->rowCount(); } /** -- cgit v1.2.3-54-g00ecf From 908f5712cc97f9476de7a9530b5b3289c5deaf1d Mon Sep 17 00:00:00 2001 From: msquare Date: Sun, 23 Jul 2017 12:02:37 +0200 Subject: fix problem where 0 is not recognized as get value --- src/Http/Request.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Http/Request.php b/src/Http/Request.php index 2efd1e1d..3ff027d5 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -67,7 +67,7 @@ class Request { $data = $this->request + $this->query; - if (!empty($data[$key])) { + if (isset($data[$key])) { return $data[$key]; } @@ -84,7 +84,7 @@ class Request { $value = $this->input($key); - return !empty($value); + return !(empty($value) && strlen($value) == 0); } /** -- cgit v1.2.3-54-g00ecf From 2b834ba7f1fb585deb5a2e27186ba799e61e35ba Mon Sep 17 00:00:00 2001 From: msquare Date: Sun, 23 Jul 2017 12:11:50 +0200 Subject: fix problem where empty string is not recognized as get value --- src/Http/Request.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Http/Request.php b/src/Http/Request.php index 3ff027d5..fcfc2600 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -82,9 +82,9 @@ class Request */ public function has($key) { - $value = $this->input($key); + $data = $this->request + $this->query; - return !(empty($value) && strlen($value) == 0); + return isset($data[$key]); } /** -- cgit v1.2.3-54-g00ecf From 144b453bc6b594ea16838a006eb20b04e5b5ec19 Mon Sep 17 00:00:00 2001 From: msquare Date: Sun, 23 Jul 2017 12:18:32 +0200 Subject: fix unreadable exception --- src/Exceptions/Handler.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Exceptions/Handler.php b/src/Exceptions/Handler.php index 0532a7d8..942e11d6 100644 --- a/src/Exceptions/Handler.php +++ b/src/Exceptions/Handler.php @@ -72,7 +72,7 @@ class Handler )); if ($this->environment == self::ENV_DEVELOPMENT) { - echo '
          ';
          +            echo '
          ';
                       echo sprintf('%s: (%s)' . PHP_EOL, ucfirst($type), $number);
                       var_export([
                           'string'  => $string,
          -- 
          cgit v1.2.3-54-g00ecf
          
          
          From 5794c4cab8f6ef0529dfc51343b5ec78b134fb2a Mon Sep 17 00:00:00 2001
          From: msquare 
          Date: Fri, 28 Jul 2017 18:50:00 +0200
          Subject: clear delete queries from false resuls
          
          ---
           includes/controller/shift_entries_controller.php   |  5 +----
           includes/controller/shifttypes_controller.php      |  5 +----
           includes/controller/user_angeltypes_controller.php |  5 +----
           includes/controller/users_controller.php           |  5 +----
           includes/model/AngelType_model.php                 |  7 +------
           includes/model/NeededAngelTypes_model.php          |  6 ++----
           includes/model/Room_model.php                      |  3 +--
           includes/model/ShiftEntry_model.php                |  3 +--
           includes/model/ShiftTypes_model.php                |  3 +--
           includes/model/Shifts_model.php                    | 14 +-------------
           includes/model/UserAngelTypes_model.php            | 10 +---------
           includes/model/UserDriverLicenses_model.php        |  7 +------
           includes/model/User_model.php                      |  3 ---
           includes/pages/admin_import.php                    |  5 +----
           includes/pages/admin_rooms.php                     |  4 +---
           includes/pages/user_myshifts.php                   |  6 ++----
           src/Database/Db.php                                |  4 ++--
           17 files changed, 19 insertions(+), 76 deletions(-)
          
          (limited to 'src')
          
          diff --git a/includes/controller/shift_entries_controller.php b/includes/controller/shift_entries_controller.php
          index 54c57332..03d7a27f 100644
          --- a/includes/controller/shift_entries_controller.php
          +++ b/includes/controller/shift_entries_controller.php
          @@ -269,10 +269,7 @@ function shift_entry_delete_controller()
                       redirect(page_link_to('user_shifts'));
                   }
           
          -        $result = ShiftEntry_delete($entry_id);
          -        if ($result === false) {
          -            engelsystem_error('Unable to delete shift entry.');
          -        }
          +        ShiftEntry_delete($entry_id);
           
                   engelsystem_log(
                       'Deleted ' . User_Nick_render($shift_entry_source) . '\'s shift: ' . $shift_entry_source['name']
          diff --git a/includes/controller/shifttypes_controller.php b/includes/controller/shifttypes_controller.php
          index 790bbb56..f4791511 100644
          --- a/includes/controller/shifttypes_controller.php
          +++ b/includes/controller/shifttypes_controller.php
          @@ -28,10 +28,7 @@ function shifttype_delete_controller()
               }
           
               if ($request->has('confirmed')) {
          -        $result = ShiftType_delete($shifttype['id']);
          -        if (empty($result)) {
          -            engelsystem_error('Unable to delete shifttype.');
          -        }
          +        ShiftType_delete($shifttype['id']);
           
                   engelsystem_log('Deleted shifttype ' . $shifttype['name']);
                   success(sprintf(_('Shifttype %s deleted.'), $shifttype['name']));
          diff --git a/includes/controller/user_angeltypes_controller.php b/includes/controller/user_angeltypes_controller.php
          index 41185552..ab16139a 100644
          --- a/includes/controller/user_angeltypes_controller.php
          +++ b/includes/controller/user_angeltypes_controller.php
          @@ -215,10 +215,7 @@ function user_angeltype_delete_controller()
               }
           
               if ($request->has('confirmed')) {
          -        $result = UserAngelType_delete($user_angeltype);
          -        if ($result === false) {
          -            engelsystem_error('Unable to delete user angeltype.');
          -        }
          +        UserAngelType_delete($user_angeltype);
           
                   $success_message = sprintf(_('User %s removed from %s.'), User_Nick_render($user_source), $angeltype['name']);
                   engelsystem_log($success_message);
          diff --git a/includes/controller/users_controller.php b/includes/controller/users_controller.php
          index f441c8af..05b97716 100644
          --- a/includes/controller/users_controller.php
          +++ b/includes/controller/users_controller.php
          @@ -76,10 +76,7 @@ function user_delete_controller()
                   }
           
                   if ($valid) {
          -            $result = User_delete($user_source['UID']);
          -            if ($result === false) {
          -                engelsystem_error('Unable to delete user.');
          -            }
          +            User_delete($user_source['UID']);
           
                       mail_user_delete($user_source);
                       success(_('User deleted.'));
          diff --git a/includes/model/AngelType_model.php b/includes/model/AngelType_model.php
          index af213432..b9238467 100644
          --- a/includes/model/AngelType_model.php
          +++ b/includes/model/AngelType_model.php
          @@ -77,20 +77,15 @@ function AngelType_contact_info($angeltype)
            * Delete an Angeltype.
            *
            * @param array $angeltype
          - * @return bool
            */
           function AngelType_delete($angeltype)
           {
          -    $result = DB::delete('
          +    DB::delete('
                 DELETE FROM `AngelTypes`
                 WHERE `id`=?
                 LIMIT 1
               ', [$angeltype['id']]);
          -    if (is_null($result)) {
          -        engelsystem_error('Unable to delete angeltype.');
          -    }
               engelsystem_log('Deleted angeltype: ' . AngelType_name_render($angeltype));
          -    return true;
           }
           
           /**
          diff --git a/includes/model/NeededAngelTypes_model.php b/includes/model/NeededAngelTypes_model.php
          index e77c715f..981c100a 100644
          --- a/includes/model/NeededAngelTypes_model.php
          +++ b/includes/model/NeededAngelTypes_model.php
          @@ -35,22 +35,20 @@ function NeededAngelType_add($shift_id, $angeltype_id, $room_id, $count)
            * Deletes all needed angel types from given shift.
            *
            * @param int $shift_id id of the shift
          - * @return int count of affected rows
            */
           function NeededAngelTypes_delete_by_shift($shift_id)
           {
          -    return (int)DB::delete('DELETE FROM `NeededAngelTypes` WHERE `shift_id` = ?', [$shift_id]);
          +    DB::delete('DELETE FROM `NeededAngelTypes` WHERE `shift_id` = ?', [$shift_id]);
           }
           
           /**
            * Deletes all needed angel types from given room.
            *
            * @param int $room_id id of the room
          - * @return int count of affected rows
            */
           function NeededAngelTypes_delete_by_room($room_id)
           {
          -    return (int)DB::delete(
          +    DB::delete(
                   'DELETE FROM `NeededAngelTypes` WHERE `room_id` = ?',
                   [$room_id]
               );
          diff --git a/includes/model/Room_model.php b/includes/model/Room_model.php
          index fdd9dddc..d76e6036 100644
          --- a/includes/model/Room_model.php
          +++ b/includes/model/Room_model.php
          @@ -17,11 +17,10 @@ function Rooms($show_all = false)
            * Delete a room
            *
            * @param int $room_id
          - * @return bool
            */
           function Room_delete($room_id)
           {
          -    return DB::delete('DELETE FROM `Room` WHERE `RID` = ?', [$room_id]);
          +    DB::delete('DELETE FROM `Room` WHERE `RID` = ?', [$room_id]);
           }
           
           /**
          diff --git a/includes/model/ShiftEntry_model.php b/includes/model/ShiftEntry_model.php
          index 3a282efc..bca63774 100644
          --- a/includes/model/ShiftEntry_model.php
          +++ b/includes/model/ShiftEntry_model.php
          @@ -143,13 +143,12 @@ function ShiftEntry($shift_entry_id)
            * Delete a shift entry.
            *
            * @param int $shift_entry_id
          - * @return bool
            */
           function ShiftEntry_delete($shift_entry_id)
           {
               $shift_entry = ShiftEntry($shift_entry_id);
               mail_shift_removed(User($shift_entry['UID']), Shift($shift_entry['SID']));
          -    return DB::delete('DELETE FROM `ShiftEntry` WHERE `id` = ?', [$shift_entry_id]);
          +    DB::delete('DELETE FROM `ShiftEntry` WHERE `id` = ?', [$shift_entry_id]);
           }
           
           /**
          diff --git a/includes/model/ShiftTypes_model.php b/includes/model/ShiftTypes_model.php
          index 12fe38be..d6efe117 100644
          --- a/includes/model/ShiftTypes_model.php
          +++ b/includes/model/ShiftTypes_model.php
          @@ -6,11 +6,10 @@ use Engelsystem\Database\DB;
            * Delete a shift type.
            *
            * @param int $shifttype_id
          - * @return bool
            */
           function ShiftType_delete($shifttype_id)
           {
          -    return DB::delete('DELETE FROM `ShiftTypes` WHERE `id`=?', [$shifttype_id]);
          +    DB::delete('DELETE FROM `ShiftTypes` WHERE `id`=?', [$shifttype_id]);
           }
           
           /**
          diff --git a/includes/model/Shifts_model.php b/includes/model/Shifts_model.php
          index 6e69fe35..2288e3cc 100644
          --- a/includes/model/Shifts_model.php
          +++ b/includes/model/Shifts_model.php
          @@ -402,34 +402,22 @@ function Shift_signup_allowed(
            * Delete a shift by its external id.
            *
            * @param int $shift_psid
          - * @return bool
            */
           function Shift_delete_by_psid($shift_psid)
           {
               DB::delete('DELETE FROM `Shifts` WHERE `PSID`=?', [$shift_psid]);
          -
          -    if (DB::getStm()->errorCode() != '00000') {
          -        return false;
          -    }
          -
          -    return true;
           }
           
           /**
            * Delete a shift.
            *
            * @param int $shift_id
          - * @return bool
            */
           function Shift_delete($shift_id)
           {
               mail_shift_delete(Shift($shift_id));
           
          -    $result = DB::delete('DELETE FROM `Shifts` WHERE `SID`=?', [$shift_id]);
          -    if (DB::getStm()->errorCode() != '00000') {
          -        engelsystem_error('Unable to delete shift.');
          -    }
          -    return $result;
          +    DB::delete('DELETE FROM `Shifts` WHERE `SID`=?', [$shift_id]);
           }
           
           /**
          diff --git a/includes/model/UserAngelTypes_model.php b/includes/model/UserAngelTypes_model.php
          index f8277fd9..43bd23bc 100644
          --- a/includes/model/UserAngelTypes_model.php
          +++ b/includes/model/UserAngelTypes_model.php
          @@ -125,7 +125,6 @@ function UserAngelType_update($user_angeltype_id, $supporter)
            * Delete all unconfirmed UserAngelTypes for given Angeltype.
            *
            * @param int $angeltype_id
          - * @return bool
            */
           function UserAngelTypes_delete_all($angeltype_id)
           {
          @@ -134,12 +133,6 @@ function UserAngelTypes_delete_all($angeltype_id)
                 WHERE `angeltype_id`=?
                 AND `confirm_user_id` IS NULL
               ', [$angeltype_id]);
          -
          -    if (DB::getStm()->errorCode() != '00000') {
          -        engelsystem_error('Unable to delete all unconfirmed users.');
          -    }
          -
          -    return true;
           }
           
           /**
          @@ -178,11 +171,10 @@ function UserAngelType_confirm($user_angeltype_id, $confirm_user)
            * Delete an UserAngelType.
            *
            * @param array $user_angeltype
          - * @return bool
            */
           function UserAngelType_delete($user_angeltype)
           {
          -    return (bool)DB::delete('
          +    DB::delete('
                 DELETE FROM `UserAngelTypes`
                 WHERE `id`=?
                 LIMIT 1', [$user_angeltype['id']]);
          diff --git a/includes/model/UserDriverLicenses_model.php b/includes/model/UserDriverLicenses_model.php
          index ee93ac95..bc9b6516 100644
          --- a/includes/model/UserDriverLicenses_model.php
          +++ b/includes/model/UserDriverLicenses_model.php
          @@ -132,13 +132,8 @@ function UserDriverLicenses_update($user_driver_license)
            * Delete a user's driver license entry
            *
            * @param int $user_id
          - * @return bool
            */
           function UserDriverLicenses_delete($user_id)
           {
          -    $result = DB::delete('DELETE FROM `UserDriverLicenses` WHERE `user_id`=?', [$user_id]);
          -    if (DB::getStm()->errorCode() != '00000') {
          -        engelsystem_error('Unable to remove user driver license information');
          -    }
          -    return $result;
          +    DB::delete('DELETE FROM `UserDriverLicenses` WHERE `user_id`=?', [$user_id]);
           }
          diff --git a/includes/model/User_model.php b/includes/model/User_model.php
          index 9f767b74..adf81393 100644
          --- a/includes/model/User_model.php
          +++ b/includes/model/User_model.php
          @@ -11,13 +11,10 @@ use Engelsystem\ValidationResult;
            * Delete a user
            *
            * @param int $user_id
          - * @return bool
            */
           function User_delete($user_id)
           {
               DB::delete('DELETE FROM `User` WHERE `UID`=?', [$user_id]);
          -
          -    return DB::getStm()->errorCode() == '00000';
           }
           
           /**
          diff --git a/includes/pages/admin_import.php b/includes/pages/admin_import.php
          index 959a9d2e..506a9dbe 100644
          --- a/includes/pages/admin_import.php
          +++ b/includes/pages/admin_import.php
          @@ -279,10 +279,7 @@ function admin_import()
                       }
           
                       foreach ($events_deleted as $event) {
          -                $result = Shift_delete_by_psid($event['PSID']);
          -                if ($result === false) {
          -                    engelsystem_error('Unable to delete shift.');
          -                }
          +                Shift_delete_by_psid($event['PSID']);
                       }
           
                       engelsystem_log('Frab import done');
          diff --git a/includes/pages/admin_rooms.php b/includes/pages/admin_rooms.php
          index ad8eab83..d49db707 100644
          --- a/includes/pages/admin_rooms.php
          +++ b/includes/pages/admin_rooms.php
          @@ -209,9 +209,7 @@ function admin_rooms()
                       ]);
                   } elseif ($request->input('show') == 'delete') {
                       if ($request->has('ack')) {
          -                if (!Room_delete($room_id)) {
          -                    engelsystem_error('Unable to delete room.');
          -                }
          +                Room_delete($room_id);
           
                           engelsystem_log('Room deleted: ' . $name);
                           success(sprintf(_('Room %s deleted.'), $name));
          diff --git a/includes/pages/user_myshifts.php b/includes/pages/user_myshifts.php
          index 94116fc9..a10e6f82 100644
          --- a/includes/pages/user_myshifts.php
          +++ b/includes/pages/user_myshifts.php
          @@ -145,10 +145,8 @@ function user_myshifts()
                           ($shift['start'] > time() + config('last_unsubscribe') * 3600)
                           || in_array('user_shifts_admin', $privileges)
                       ) {
          -                $result = ShiftEntry_delete($user_id);
          -                if ($result === false) {
          -                    engelsystem_error('Unable to delete shift entry.');
          -                }
          +                ShiftEntry_delete($user_id);
          +
                           $room = Room($shift['RID']);
                           $angeltype = AngelType($shift['TID']);
                           $shifttype = ShiftType($shift['shifttype_id']);
          diff --git a/src/Database/Db.php b/src/Database/Db.php
          index 46edc96b..b433f40d 100644
          --- a/src/Database/Db.php
          +++ b/src/Database/Db.php
          @@ -113,13 +113,13 @@ class Db
                *
                * @param string $query
                * @param array  $bindings
          -     * @return int|bool
          +     * @return int
                */
               public static function delete($query, array $bindings = [])
               {
                   self::query($query, $bindings);
           
          -        return (self::$lastStatus ? self::$stm->rowCount() : false);
          +        return self::$stm->rowCount();
               }
           
               /**
          -- 
          cgit v1.2.3-54-g00ecf
          
          
          From 440ed74cd7a0bde035a93fde36b08b9a5aca557d Mon Sep 17 00:00:00 2001
          From: msquare 
          Date: Fri, 28 Jul 2017 19:28:00 +0200
          Subject: exception handler should handle throwables instead of exceptions
          
          ---
           src/Exceptions/Handler.php | 6 +++---
           1 file changed, 3 insertions(+), 3 deletions(-)
          
          (limited to 'src')
          
          diff --git a/src/Exceptions/Handler.php b/src/Exceptions/Handler.php
          index 942e11d6..e52549e7 100644
          --- a/src/Exceptions/Handler.php
          +++ b/src/Exceptions/Handler.php
          @@ -2,7 +2,7 @@
           
           namespace Engelsystem\Exceptions;
           
          -use Exception;
          +use Throwable;
           
           class Handler
           {
          @@ -38,9 +38,9 @@ class Handler
               }
           
               /**
          -     * @param Exception $e
          +     * @param Throwable $e
                */
          -    public function exceptionHandler(Exception $e)
          +    public function exceptionHandler(Throwable $e)
               {
                   $this->handle(
                       'exception',
          -- 
          cgit v1.2.3-54-g00ecf
          
          
          From f82e5456d22af7e39a22a9a64e74072cf01e0a31 Mon Sep 17 00:00:00 2001
          From: msquare 
          Date: Fri, 28 Jul 2017 20:11:09 +0200
          Subject: dried code by introducing selectOne for select queries with only one
           result line expected
          
          ---
           includes/controller/shift_entries_controller.php |  9 ++---
           includes/model/AngelType_model.php               |  8 +---
           includes/model/EventConfig_model.php             |  8 +---
           includes/model/Message_model.php                 |  6 +--
           includes/model/Room_model.php                    |  8 +---
           includes/model/ShiftEntry_model.php              | 13 ++-----
           includes/model/ShiftTypes_model.php              |  8 +---
           includes/model/Shifts_model.php                  | 18 +++------
           includes/model/UserAngelTypes_model.php          | 16 +-------
           includes/model/UserDriverLicenses_model.php      |  8 +---
           includes/model/User_model.php                    | 49 +++++-------------------
           includes/pages/admin_active.php                  |  9 ++---
           includes/pages/admin_groups.php                  |  6 +--
           includes/pages/admin_news.php                    |  4 +-
           includes/pages/admin_questions.php               | 12 +++---
           includes/pages/admin_shifts.php                  |  4 +-
           includes/pages/admin_user.php                    | 16 ++++----
           includes/pages/guest_login.php                   |  5 +--
           includes/pages/guest_stats.php                   |  3 +-
           includes/pages/user_messages.php                 |  8 ++--
           includes/pages/user_myshifts.php                 |  9 ++---
           includes/pages/user_news.php                     |  3 +-
           includes/pages/user_questions.php                |  4 +-
           includes/sys_auth.php                            |  5 +--
           src/Database/Db.php                              | 17 ++++++++
           25 files changed, 83 insertions(+), 173 deletions(-)
          
          (limited to 'src')
          
          diff --git a/includes/controller/shift_entries_controller.php b/includes/controller/shift_entries_controller.php
          index 03d7a27f..72189869 100644
          --- a/includes/controller/shift_entries_controller.php
          +++ b/includes/controller/shift_entries_controller.php
          @@ -43,7 +43,7 @@ function shift_entry_add_controller()
                   $type = AngelType($type_id);
               } else {
                   // TODO: Move queries to model
          -        $type = DB::select('
          +        $type = DB::selectOne('
                       SELECT *
                       FROM `UserAngelTypes`
                       JOIN `AngelTypes` ON (`UserAngelTypes`.`angeltype_id` = `AngelTypes`.`id`)
          @@ -56,7 +56,6 @@ function shift_entry_add_controller()
                           )
                       )
                   ', [$type_id, $user['UID']]);
          -        $type = array_shift($type);
               }
           
               if (empty($type)) {
          @@ -241,7 +240,7 @@ function shift_entry_delete_controller()
               }
               $entry_id = $request->input('entry_id');
           
          -    $shift_entry_source = DB::select('
          +    $shift_entry_source = DB::selectOne('
                   SELECT
                       `User`.`Nick`,
                       `ShiftEntry`.`Comment`,
          @@ -260,9 +259,7 @@ function shift_entry_delete_controller()
                   WHERE `ShiftEntry`.`id`=?',
                   [$entry_id]
               );
          -    if (count($shift_entry_source) > 0) {
          -        $shift_entry_source = array_shift($shift_entry_source);
          -
          +    if (!empty($shift_entry_source)) {
                   if (!in_array('user_shifts_admin', $privileges) && (!in_array('shiftentry_edit_angeltype_supporter',
                               $privileges) || !User_is_AngelType_supporter($user, AngelType($shift_entry_source['angeltype_id'])))
                   ) {
          diff --git a/includes/model/AngelType_model.php b/includes/model/AngelType_model.php
          index f08733d5..bc535667 100644
          --- a/includes/model/AngelType_model.php
          +++ b/includes/model/AngelType_model.php
          @@ -256,14 +256,8 @@ function AngelType_ids()
            */
           function AngelType($angeltype_id)
           {
          -    $angelType_source = DB::select(
          +    return DB::selectOne(
                   'SELECT * FROM `AngelTypes` WHERE `id`=?',
                   [$angeltype_id]
               );
          -
          -    if (empty($angelType_source)) {
          -        return null;
          -    }
          -
          -    return array_shift($angelType_source);
           }
          diff --git a/includes/model/EventConfig_model.php b/includes/model/EventConfig_model.php
          index c5caf4d5..646d19c5 100644
          --- a/includes/model/EventConfig_model.php
          +++ b/includes/model/EventConfig_model.php
          @@ -9,13 +9,7 @@ use Engelsystem\Database\DB;
            */
           function EventConfig()
           {
          -    $event_config = DB::select('SELECT * FROM `EventConfig` LIMIT 1');
          -
          -    if (empty($event_config)) {
          -        return null;
          -    }
          -
          -    return array_shift($event_config);
          +    return DB::selectOne('SELECT * FROM `EventConfig` LIMIT 1');
           }
           
           /**
          diff --git a/includes/model/Message_model.php b/includes/model/Message_model.php
          index ebd4b37e..9bb037af 100644
          --- a/includes/model/Message_model.php
          +++ b/includes/model/Message_model.php
          @@ -20,11 +20,7 @@ function Message_ids()
            */
           function Message($message_id)
           {
          -    $message_source = DB::select('SELECT * FROM `Messages` WHERE `id`=? LIMIT 1', [$message_id]);
          -    if (empty($message_source)) {
          -        return null;
          -    }
          -    return array_shift($message_source);
          +    return DB::selectOne('SELECT * FROM `Messages` WHERE `id`=? LIMIT 1', [$message_id]);
           }
           
           /**
          diff --git a/includes/model/Room_model.php b/includes/model/Room_model.php
          index 08e0f7bf..8425e5ad 100644
          --- a/includes/model/Room_model.php
          +++ b/includes/model/Room_model.php
          @@ -58,17 +58,11 @@ function Room_create($name, $from_frab, $public, $number = null)
            */
           function Room($room_id, $onlyVisible = true)
           {
          -    $room_source = DB::select('
          +    return DB::selectOne('
                   SELECT *
                   FROM `Room`
                   WHERE `RID` = ?
                   ' . ($onlyVisible ? 'AND `show` = \'Y\'' : ''),
                   [$room_id]
               );
          -
          -    if (empty($room_source)) {
          -        return null;
          -    }
          -
          -    return array_shift($room_source);
           }
          diff --git a/includes/model/ShiftEntry_model.php b/includes/model/ShiftEntry_model.php
          index 563a611f..3a7254ad 100644
          --- a/includes/model/ShiftEntry_model.php
          +++ b/includes/model/ShiftEntry_model.php
          @@ -28,10 +28,9 @@ function ShiftEntry_new()
            */
           function ShiftEntries_freeleaded_count()
           {
          -    $result = DB::select('SELECT COUNT(*) FROM `ShiftEntry` WHERE `freeloaded` = 1');
          -    $result = array_shift($result);
          +    $result = DB::selectOne('SELECT COUNT(*) FROM `ShiftEntry` WHERE `freeloaded` = 1');
           
          -    if (!is_array($result)) {
          +    if (empty($result)) {
                   return 0;
               }
           
          @@ -129,13 +128,7 @@ function ShiftEntry_update($shift_entry)
            */
           function ShiftEntry($shift_entry_id)
           {
          -    $shift_entry = DB::select('SELECT * FROM `ShiftEntry` WHERE `id` = ?', [$shift_entry_id]);
          -
          -    if (empty($shift_entry)) {
          -        return null;
          -    }
          -
          -    return $shift_entry[0];
          +    return DB::selectOne('SELECT * FROM `ShiftEntry` WHERE `id` = ?', [$shift_entry_id]);
           }
           
           /**
          diff --git a/includes/model/ShiftTypes_model.php b/includes/model/ShiftTypes_model.php
          index 05c1a949..227df367 100644
          --- a/includes/model/ShiftTypes_model.php
          +++ b/includes/model/ShiftTypes_model.php
          @@ -70,13 +70,7 @@ function ShiftType_create($name, $angeltype_id, $description)
            */
           function ShiftType($shifttype_id)
           {
          -    $shifttype = DB::select('SELECT * FROM `ShiftTypes` WHERE `id`=?', [$shifttype_id]);
          -
          -    if (empty($shifttype)) {
          -        return null;
          -    }
          -
          -    return array_shift($shifttype);
          +    return DB::selectOne('SELECT * FROM `ShiftTypes` WHERE `id`=?', [$shifttype_id]);
           }
           
           /**
          diff --git a/includes/model/Shifts_model.php b/includes/model/Shifts_model.php
          index 939a4f4e..88b28998 100644
          --- a/includes/model/Shifts_model.php
          +++ b/includes/model/Shifts_model.php
          @@ -112,7 +112,7 @@ function NeededAngeltypes_by_ShiftsFilter(ShiftsFilter $shiftsFilter)
            */
           function NeededAngeltype_by_Shift_and_Angeltype($shift, $angeltype)
           {
          -    $result = DB::select('
          +    return DB::selectOne('
                     SELECT
                         `NeededAngelTypes`.*,
                         `Shifts`.`SID`,
          @@ -150,12 +150,6 @@ function NeededAngeltype_by_Shift_and_Angeltype($shift, $angeltype)
                       $angeltype['id']
                   ]
               );
          -
          -    if (empty($result)) {
          -        return null;
          -    }
          -
          -    return $result[0];
           }
           
           /**
          @@ -453,13 +447,13 @@ function Shift_update($shift)
            */
           function Shift_update_by_psid($shift)
           {
          -    $shift_source = DB::select('SELECT `SID` FROM `Shifts` WHERE `PSID`=?', [$shift['PSID']]);
          +    $shift_source = DB::selectOne('SELECT `SID` FROM `Shifts` WHERE `PSID`=?', [$shift['PSID']]);
           
               if (empty($shift_source)) {
                   throw new Exception('Shift not found.');
               }
           
          -    $shift['SID'] = $shift_source[0]['SID'];
          +    $shift['SID'] = $shift_source['SID'];
               return Shift_update($shift);
           }
           
          @@ -537,18 +531,16 @@ function Shifts_by_user($user, $include_freeload_comments = false)
            */
           function Shift($shift_id)
           {
          -    $shifts_source = DB::select('
          +    $result = DB::selectOne('
                 SELECT `Shifts`.*, `ShiftTypes`.`name`
                 FROM `Shifts`
                 JOIN `ShiftTypes` ON (`ShiftTypes`.`id` = `Shifts`.`shifttype_id`)
                 WHERE `SID`=?', [$shift_id]);
           
          -    if (empty($shifts_source)) {
          +    if (empty($result)) {
                   return null;
               }
           
          -    $result = $shifts_source[0];
          -
               $shiftsEntry_source = DB::select('
                   SELECT `id`, `TID` , `UID` , `freeloaded`
                   FROM `ShiftEntry`
          diff --git a/includes/model/UserAngelTypes_model.php b/includes/model/UserAngelTypes_model.php
          index 3ec151fb..5b0caf98 100644
          --- a/includes/model/UserAngelTypes_model.php
          +++ b/includes/model/UserAngelTypes_model.php
          @@ -197,17 +197,11 @@ function UserAngelType_create($user, $angeltype)
            */
           function UserAngelType($user_angeltype_id)
           {
          -    $angeltype = DB::select('
          +    return DB::selectOne('
                 SELECT *
                 FROM `UserAngelTypes`
                 WHERE `id`=?
                 LIMIT 1', [$user_angeltype_id]);
          -
          -    if (empty($angeltype)) {
          -        return null;
          -    }
          -
          -    return $angeltype[0];
           }
           
           /**
          @@ -219,7 +213,7 @@ function UserAngelType($user_angeltype_id)
            */
           function UserAngelType_by_User_and_AngelType($user, $angeltype)
           {
          -    $angeltype = DB::select('
          +    return DB::selectOne('
                     SELECT *
                     FROM `UserAngelTypes`
                     WHERE `user_id`=?
          @@ -231,10 +225,4 @@ function UserAngelType_by_User_and_AngelType($user, $angeltype)
                       $angeltype['id']
                   ]
               );
          -
          -    if (empty($angeltype)) {
          -        return null;
          -    }
          -
          -    return array_shift($angeltype);
           }
          diff --git a/includes/model/UserDriverLicenses_model.php b/includes/model/UserDriverLicenses_model.php
          index 515a2701..798aa6ab 100644
          --- a/includes/model/UserDriverLicenses_model.php
          +++ b/includes/model/UserDriverLicenses_model.php
          @@ -45,16 +45,10 @@ function UserDriverLicense_valid($user_driver_license)
            */
           function UserDriverLicense($user_id)
           {
          -    $user_driver_license = DB::select('
          +    return DB::selectOne('
                   SELECT *
                   FROM `UserDriverLicenses`
                   WHERE `user_id`=?', [$user_id]);
          -
          -    if (empty($user_driver_license)) {
          -        return null;
          -    }
          -
          -    return array_shift($user_driver_license);
           }
           
           /**
          diff --git a/includes/model/User_model.php b/includes/model/User_model.php
          index f86d5bf6..4757ed3c 100644
          --- a/includes/model/User_model.php
          +++ b/includes/model/User_model.php
          @@ -87,8 +87,7 @@ function User_update($user)
            */
           function User_force_active_count()
           {
          -    $result = DB::select('SELECT COUNT(*) FROM `User` WHERE `force_active` = 1');
          -    $result = array_shift($result);
          +    $result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `force_active` = 1');
           
               if (empty($result)) {
                   return 0;
          @@ -102,8 +101,7 @@ function User_force_active_count()
            */
           function User_active_count()
           {
          -    $result = DB::select('SELECT COUNT(*) FROM `User` WHERE `Aktiv` = 1');
          -    $result = array_shift($result);
          +    $result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `Aktiv` = 1');
           
               if (empty($result)) {
                   return 0;
          @@ -117,8 +115,7 @@ function User_active_count()
            */
           function User_got_voucher_count()
           {
          -    $result = DB::select('SELECT SUM(`got_voucher`) FROM `User`');
          -    $result = array_shift($result);
          +    $result = DB::selectOne('SELECT SUM(`got_voucher`) FROM `User`');
           
               if (empty($result)) {
                   return 0;
          @@ -132,8 +129,7 @@ function User_got_voucher_count()
            */
           function User_arrived_count()
           {
          -    $result = DB::select('SELECT COUNT(*) FROM `User` WHERE `Gekommen` = 1');
          -    $result = array_shift($result);
          +    $result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `Gekommen` = 1');
           
               if (empty($result)) {
                   return 0;
          @@ -147,8 +143,7 @@ function User_arrived_count()
            */
           function User_tshirts_count()
           {
          -    $result = DB::select('SELECT COUNT(*) FROM `User` WHERE `Tshirt` = 1');
          -    $result = array_shift($result);
          +    $result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `Tshirt` = 1');
           
               if (empty($result)) {
                   return 0;
          @@ -382,13 +377,7 @@ function User_validate_planned_departure_date($planned_arrival_date, $planned_de
            */
           function User($user_id)
           {
          -    $user_source = DB::select('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$user_id]);
          -
          -    if (empty($user_source)) {
          -        return null;
          -    }
          -
          -    return array_shift($user_source);
          +    return DB::selectOne('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$user_id]);
           }
           
           /**
          @@ -400,13 +389,7 @@ function User($user_id)
            */
           function User_by_api_key($api_key)
           {
          -    $user = DB::select('SELECT * FROM `User` WHERE `api_key`=? LIMIT 1', [$api_key]);
          -
          -    if (empty($user)) {
          -        return null;
          -    }
          -
          -    return $user[0];
          +    return DB::selectOne('SELECT * FROM `User` WHERE `api_key`=? LIMIT 1', [$api_key]);
           }
           
           /**
          @@ -417,30 +400,18 @@ function User_by_api_key($api_key)
            */
           function User_by_email($email)
           {
          -    $user = DB::select('SELECT * FROM `User` WHERE `email`=? LIMIT 1', [$email]);
          -
          -    if (empty($user)) {
          -        return null;
          -    }
          -
          -    return array_shift($user);
          +    return DB::selectOne('SELECT * FROM `User` WHERE `email`=? LIMIT 1', [$email]);
           }
           
           /**
            * Returns User by password token.
            *
            * @param string $token
          - * @return array|null Matching user, null or false on error
          + * @return array|null Matching user, null when not found
            */
           function User_by_password_recovery_token($token)
           {
          -    $user = DB::select('SELECT * FROM `User` WHERE `password_recovery_token`=? LIMIT 1', [$token]);
          -
          -    if (empty($user)) {
          -        return null;
          -    }
          -
          -    return array_shift($user);
          +    return DB::selectOne('SELECT * FROM `User` WHERE `password_recovery_token`=? LIMIT 1', [$token]);
           }
           
           /**
          diff --git a/includes/pages/admin_active.php b/includes/pages/admin_active.php
          index 2e06f90d..be1217ff 100644
          --- a/includes/pages/admin_active.php
          +++ b/includes/pages/admin_active.php
          @@ -210,19 +210,17 @@ function admin_active()
               $shirt_statistics = [];
               foreach (array_keys($tshirt_sizes) as $size) {
                   if (!empty($size)) {
          -            $sc = DB::select(
          +            $sc = DB::selectOne(
                           'SELECT count(*) FROM `User` WHERE `Size`=? AND `Gekommen`=1',
                           [$size]
                       );
                       $sc = array_shift($sc);
          -            $sc = array_shift($sc);
           
          -            $gc = DB::select(
          +            $gc = DB::selectOne(
                           'SELECT count(*) FROM `User` WHERE `Size`=? AND `Tshirt`=1',
                           [$size]
                       );
                       $gc = array_shift($gc);
          -            $gc = array_shift($gc);
           
                       $shirt_statistics[] = [
                           'size'   => $size,
          @@ -232,8 +230,7 @@ function admin_active()
                   }
               }
           
          -    $uc = DB::select('SELECT count(*) FROM `User` WHERE `Tshirt`=1');
          -    $uc = array_shift($uc);
          +    $uc = DB::selectOne('SELECT count(*) FROM `User` WHERE `Tshirt`=1');
               $uc = array_shift($uc);
           
               $shirt_statistics[] = [
          diff --git a/includes/pages/admin_groups.php b/includes/pages/admin_groups.php
          index c483a79d..ea0d4dbc 100644
          --- a/includes/pages/admin_groups.php
          +++ b/includes/pages/admin_groups.php
          @@ -107,23 +107,21 @@ function admin_groups()
                               return error('Incomplete call, missing Groups ID.', true);
                           }
           
          -                $group = DB::select('SELECT * FROM `Groups` WHERE `UID`=? LIMIT 1', [$group_id]);
          +                $group = DB::selectOne('SELECT * FROM `Groups` WHERE `UID`=? LIMIT 1', [$group_id]);
                           $privileges = $request->get('privileges');
                           if (!is_array($privileges)) {
                               $privileges = [];
                           }
                           if (!empty($group)) {
          -                    $group = array_shift($group);
                               DB::delete('DELETE FROM `GroupPrivileges` WHERE `group_id`=?', [$group_id]);
                               $privilege_names = [];
                               foreach ($privileges as $privilege) {
                                   if (preg_match('/^\d{1,}$/', $privilege)) {
          -                            $group_privileges_source = DB::select(
          +                            $group_privileges_source = DB::selectOne(
                                           'SELECT `name` FROM `Privileges` WHERE `id`=? LIMIT 1',
                                           [$privilege]
                                       );
                                       if (!empty($group_privileges_source)) {
          -                                $group_privileges_source = array_shift($group_privileges_source);
                                           DB::insert(
                                               'INSERT INTO `GroupPrivileges` (`group_id`, `privilege_id`) VALUES (?, ?)',
                                               [$group_id, $privilege]
          diff --git a/includes/pages/admin_news.php b/includes/pages/admin_news.php
          index 7f8ca1ba..4eafd3e2 100644
          --- a/includes/pages/admin_news.php
          +++ b/includes/pages/admin_news.php
          @@ -21,14 +21,13 @@ function admin_news()
                   return error('Incomplete call, missing News ID.', true);
               }
           
          -    $news = DB::select('SELECT * FROM `News` WHERE `ID`=? LIMIT 1', [$news_id]);
          +    $news = DB::selectOne('SELECT * FROM `News` WHERE `ID`=? LIMIT 1', [$news_id]);
               if (empty($news)) {
                   return error('No News found.', true);
               }
           
               switch ($request->input('action')) {
                   case 'edit':
          -            $news = array_shift($news);
                       $user_source = User($news['UID']);
           
                       $html .= form([
          @@ -70,7 +69,6 @@ function admin_news()
                       break;
           
                   case 'delete':
          -            $news = array_shift($news);
                       DB::delete('DELETE FROM `News` WHERE `ID`=? LIMIT 1', [$news_id]);
                       engelsystem_log('News deleted: ' . $news['Betreff']);
                       success(_('News entry deleted.'));
          diff --git a/includes/pages/admin_questions.php b/includes/pages/admin_questions.php
          index d05bace6..2b61b055 100644
          --- a/includes/pages/admin_questions.php
          +++ b/includes/pages/admin_questions.php
          @@ -105,11 +105,11 @@ function admin_questions()
                               return error('Incomplete call, missing Question ID.', true);
                           }
           
          -                $question = DB::select(
          +                $question = DB::selectOne(
                               'SELECT * FROM `Questions` WHERE `QID`=? LIMIT 1',
                               [$question_id]
                           );
          -                if (count($question) > 0 && $question[0]['AID'] == null) {
          +                if (!empty($question) && $question['AID'] == null) {
                               $answer = trim(
                                   preg_replace("/([^\p{L}\p{P}\p{Z}\p{N}\n]{1,})/ui",
                                       '',
          @@ -129,7 +129,7 @@ function admin_questions()
                                           $question_id,
                                       ]
                                   );
          -                        engelsystem_log('Question ' . $question[0]['Question'] . ' answered: ' . $answer);
          +                        engelsystem_log('Question ' . $question['Question'] . ' answered: ' . $answer);
                                   redirect(page_link_to('admin_questions'));
                               } else {
                                   return error('Enter an answer!', true);
          @@ -145,13 +145,13 @@ function admin_questions()
                               return error('Incomplete call, missing Question ID.', true);
                           }
           
          -                $question = DB::select(
          +                $question = DB::selectOne(
                               'SELECT * FROM `Questions` WHERE `QID`=? LIMIT 1',
                               [$question_id]
                           );
          -                if (count($question) > 0) {
          +                if (!empty($question)) {
                               DB::delete('DELETE FROM `Questions` WHERE `QID`=? LIMIT 1', [$question_id]);
          -                    engelsystem_log('Question deleted: ' . $question[0]['Question']);
          +                    engelsystem_log('Question deleted: ' . $question['Question']);
                               redirect(page_link_to('admin_questions'));
                           } else {
                               return error('No question found.', true);
          diff --git a/includes/pages/admin_shifts.php b/includes/pages/admin_shifts.php
          index 36028792..b5079ed1 100644
          --- a/includes/pages/admin_shifts.php
          +++ b/includes/pages/admin_shifts.php
          @@ -325,7 +325,7 @@ function admin_shifts()
                       );
           
                       foreach ($_SESSION['admin_shifts_types'] as $type_id => $count) {
          -                $angel_type_source = DB::select('
          +                $angel_type_source = DB::selectOne('
                                 SELECT *
                                 FROM `AngelTypes`
                                 WHERE `id` = ?
          @@ -341,7 +341,7 @@ function admin_shifts()
                                       $count
                                   ]
                               );
          -                    $needed_angel_types_info[] = $angel_type_source[0]['name'] . ': ' . $count;
          +                    $needed_angel_types_info[] = $angel_type_source['name'] . ': ' . $count;
                           }
                       }
                   }
          diff --git a/includes/pages/admin_user.php b/includes/pages/admin_user.php
          index 510e2292..6bdc8d71 100644
          --- a/includes/pages/admin_user.php
          +++ b/includes/pages/admin_user.php
          @@ -116,20 +116,20 @@ function admin_user()
           
                   $html .= '
          '; - $my_highest_group = DB::select( + $my_highest_group = DB::selectOne( 'SELECT group_id FROM `UserGroups` WHERE `uid`=? ORDER BY `group_id` LIMIT 1', [$user['UID']] ); - if (count($my_highest_group) > 0) { - $my_highest_group = $my_highest_group[0]['group_id']; + if (!empty($my_highest_group)) { + $my_highest_group = $my_highest_group['group_id']; } - $his_highest_group = DB::select( + $his_highest_group = DB::selectOne( 'SELECT `group_id` FROM `UserGroups` WHERE `uid`=? ORDER BY `group_id` LIMIT 1', [$user_id] ); - if (count($his_highest_group) > 0) { - $his_highest_group = $his_highest_group[0]['group_id']; + if (!empty($his_highest_group)) { + $his_highest_group = $his_highest_group['group_id']; } if ($user_id != $user['UID'] && $my_highest_group <= $his_highest_group) { @@ -188,7 +188,7 @@ function admin_user() count($my_highest_group) > 0 && ( count($his_highest_group) == 0 - || ($my_highest_group[0]['group_id'] <= $his_highest_group[0]['group_id']) + || ($my_highest_group['group_id'] <= $his_highest_group['group_id']) ) ) { $groups_source = DB::select(' @@ -203,7 +203,7 @@ function admin_user() ', [ $user_id, - $my_highest_group[0]['group_id'], + $my_highest_group['group_id'], ] ); $groups = []; diff --git a/includes/pages/guest_login.php b/includes/pages/guest_login.php index 106db33a..f8c52767 100644 --- a/includes/pages/guest_login.php +++ b/includes/pages/guest_login.php @@ -399,9 +399,8 @@ function guest_login() if ($request->has('submit')) { if ($request->has('nick') && strlen(User_validate_Nick($request->input('nick'))) > 0) { $nick = User_validate_Nick($request->input('nick')); - $login_user = DB::select('SELECT * FROM `User` WHERE `Nick`=?', [$nick]); - if (count($login_user) > 0) { - $login_user = $login_user[0]; + $login_user = DB::selectOne('SELECT * FROM `User` WHERE `Nick`=?', [$nick]); + if (!empty($login_user)) { if ($request->has('password')) { if (!verify_password($request->post('password'), $login_user['Passwort'], $login_user['UID'])) { $valid = false; diff --git a/includes/pages/guest_stats.php b/includes/pages/guest_stats.php index 8aa6f740..bf1814a3 100644 --- a/includes/pages/guest_stats.php +++ b/includes/pages/guest_stats.php @@ -17,13 +17,12 @@ function guest_stats() list($arrived_user_count) = DB::select('SELECT count(*) AS `user_count` FROM `User` WHERE `Gekommen`=1'); $stats['arrived_user_count'] = $arrived_user_count['user_count']; - $done_shifts_seconds = DB::select(' + $done_shifts_seconds = DB::selectOne(' SELECT SUM(`Shifts`.`end` - `Shifts`.`start`) FROM `ShiftEntry` JOIN `Shifts` USING (`SID`) WHERE `Shifts`.`end` < UNIX_TIMESTAMP() '); - $done_shifts_seconds = array_shift($done_shifts_seconds); $done_shifts_seconds = (int)array_shift($done_shifts_seconds); $stats['done_work_hours'] = round($done_shifts_seconds / (60 * 60), 0); diff --git a/includes/pages/user_messages.php b/includes/pages/user_messages.php index a811970d..2dea6207 100644 --- a/includes/pages/user_messages.php +++ b/includes/pages/user_messages.php @@ -130,11 +130,11 @@ function user_messages() return error(_('Incomplete call, missing Message ID.'), true); } - $message = DB::select( + $message = DB::selectOne( 'SELECT `RUID` FROM `Messages` WHERE `id`=? LIMIT 1', [$message_id] ); - if (count($message) > 0 && $message[0]['RUID'] == $user['UID']) { + if (!empty($message) && $message['RUID'] == $user['UID']) { DB::update( 'UPDATE `Messages` SET `isRead`=\'Y\' WHERE `id`=? LIMIT 1', [$message_id] @@ -152,11 +152,11 @@ function user_messages() return error(_('Incomplete call, missing Message ID.'), true); } - $message = DB::select( + $message = DB::selectOne( 'SELECT `SUID` FROM `Messages` WHERE `id`=? LIMIT 1', [$message_id] ); - if (count($message) > 0 && $message[0]['SUID'] == $user['UID']) { + if (!empty($message) && $message['SUID'] == $user['UID']) { DB::delete('DELETE FROM `Messages` WHERE `id`=? LIMIT 1', [$message_id]); redirect(page_link_to('user_messages')); } else { diff --git a/includes/pages/user_myshifts.php b/includes/pages/user_myshifts.php index a10e6f82..81f8f505 100644 --- a/includes/pages/user_myshifts.php +++ b/includes/pages/user_myshifts.php @@ -31,8 +31,7 @@ function user_myshifts() $user_id = $user['UID']; } - $shifts_user = DB::select('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$user_id]); - $shifts_user = array_shift($shifts_user); + $shifts_user = DB::selectOne('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$user_id]); if ($request->has('reset')) { if ($request->input('reset') == 'ack') { @@ -49,7 +48,7 @@ function user_myshifts() ]); } elseif ($request->has('edit') && preg_match('/^\d*$/', $request->input('edit'))) { $user_id = $request->input('edit'); - $shift = DB::select(' + $shift = DB::selectOne(' SELECT `ShiftEntry`.`freeloaded`, `ShiftEntry`.`freeload_comment`, @@ -74,7 +73,6 @@ function user_myshifts() ] ); if (count($shift) > 0) { - $shift = array_shift($shift); $freeloaded = $shift['freeloaded']; $freeload_comment = $shift['freeload_comment']; @@ -128,7 +126,7 @@ function user_myshifts() } } elseif ($request->has('cancel') && preg_match('/^\d*$/', $request->input('cancel'))) { $user_id = $request->input('cancel'); - $shift = DB::select(' + $shift = DB::selectOne(' SELECT * FROM `Shifts` INNER JOIN `ShiftEntry` USING (`SID`) @@ -140,7 +138,6 @@ function user_myshifts() ] ); if (count($shift) > 0) { - $shift = array_shift($shift); if ( ($shift['start'] > time() + config('last_unsubscribe') * 3600) || in_array('user_shifts_admin', $privileges) diff --git a/includes/pages/user_news.php b/includes/pages/user_news.php index 9bdcb6fb..3cf11a6b 100644 --- a/includes/pages/user_news.php +++ b/includes/pages/user_news.php @@ -126,8 +126,7 @@ function user_news_comments() && count(DB::select('SELECT `ID` FROM `News` WHERE `ID`=? LIMIT 1', [$request->input('nid')])) > 0 ) { $nid = $request->input('nid'); - $news = DB::select('SELECT * FROM `News` WHERE `ID`=? LIMIT 1', [$nid]); - $news = array_shift($news); + $news = DB::selectOne('SELECT * FROM `News` WHERE `ID`=? LIMIT 1', [$nid]); if ($request->has('text')) { $text = preg_replace("/([^\p{L}\p{P}\p{Z}\p{N}\n]{1,})/ui", '', strip_tags($request->input('text'))); DB::insert(' diff --git a/includes/pages/user_questions.php b/includes/pages/user_questions.php index e90ea011..e4f35577 100644 --- a/includes/pages/user_questions.php +++ b/includes/pages/user_questions.php @@ -61,11 +61,11 @@ function user_questions() return error(_('Incomplete call, missing Question ID.'), true); } - $question = DB::select( + $question = DB::selectOne( 'SELECT `UID` FROM `Questions` WHERE `QID`=? LIMIT 1', [$question_id] ); - if (count($question) > 0 && $question[0]['UID'] == $user['UID']) { + if (!empty($question) && $question['UID'] == $user['UID']) { DB::delete( 'DELETE FROM `Questions` WHERE `QID`=? LIMIT 1', [$question_id] diff --git a/includes/sys_auth.php b/includes/sys_auth.php index f1ec3192..e0ed67e5 100644 --- a/includes/sys_auth.php +++ b/includes/sys_auth.php @@ -11,10 +11,9 @@ function load_auth() $user = null; if (isset($_SESSION['uid'])) { - $user = DB::select('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$_SESSION['uid']]); - if (count($user) > 0) { + $user = DB::selectOne('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$_SESSION['uid']]); + if (!empty($user)) { // User ist eingeloggt, Datensatz zur Verfügung stellen und Timestamp updaten - $user = array_shift($user); DB::update(' UPDATE `User` SET `lastLogIn` = ? diff --git a/src/Database/Db.php b/src/Database/Db.php index b433f40d..9422ae77 100644 --- a/src/Database/Db.php +++ b/src/Database/Db.php @@ -79,6 +79,23 @@ class Db return self::$stm->fetchAll(PDO::FETCH_ASSOC); } + + /** + * Run a select query and return only the first result or null if no result is found. + * @param string $query + * @param array $bindings + * @return array|null + */ + public static function selectOne($query, array $bindings = []) + { + $result = self::select($query); + + if(empty($result)) { + return null; + } + + return array_shift($result); + } /** * Run an insert query -- cgit v1.2.3-54-g00ecf From 26515d75827c18655c0e2e2ed174cdbf7419a7b9 Mon Sep 17 00:00:00 2001 From: msquare Date: Fri, 28 Jul 2017 20:12:40 +0200 Subject: forgott to include query bindings into selectOne --- src/Database/Db.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/Database/Db.php b/src/Database/Db.php index 9422ae77..777b16a2 100644 --- a/src/Database/Db.php +++ b/src/Database/Db.php @@ -88,7 +88,7 @@ class Db */ public static function selectOne($query, array $bindings = []) { - $result = self::select($query); + $result = self::select($query, $bindings); if(empty($result)) { return null; -- cgit v1.2.3-54-g00ecf From 73175e2b64c85c7a8c528c76452cd82ffa99f925 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Mon, 28 Aug 2017 16:21:10 +0200 Subject: #337: Added routing --- config/config.default.php | 3 + includes/autoload.php | 9 + includes/controller/angeltypes_controller.php | 24 +- includes/controller/rooms_controller.php | 5 +- includes/controller/shifts_controller.php | 11 +- includes/controller/shifttypes_controller.php | 4 +- includes/controller/user_angeltypes_controller.php | 17 +- .../controller/user_driver_licenses_controller.php | 2 +- includes/controller/users_controller.php | 8 +- includes/engelsystem_provider.php | 8 +- includes/pages/admin_active.php | 52 ++-- includes/pages/admin_arrive.php | 10 +- includes/pages/admin_free.php | 2 +- includes/pages/admin_groups.php | 8 +- includes/pages/admin_news.php | 23 +- includes/pages/admin_questions.php | 6 +- includes/pages/admin_rooms.php | 8 +- includes/pages/admin_user.php | 30 ++- includes/pages/guest_login.php | 7 +- includes/pages/user_atom.php | 4 +- includes/pages/user_messages.php | 6 +- includes/pages/user_myshifts.php | 8 +- includes/pages/user_news.php | 22 +- includes/pages/user_questions.php | 6 +- includes/pages/user_shifts.php | 8 +- includes/sys_menu.php | 22 +- includes/view/AngelTypes_view.php | 71 ++++-- includes/view/Questions_view.php | 12 +- includes/view/ShiftCalendarShiftRenderer.php | 14 +- includes/view/ShiftTypes_view.php | 34 ++- includes/view/Shifts_view.php | 9 +- includes/view/UserAngelTypes_view.php | 73 ++++-- includes/view/User_view.php | 46 ++-- public/.htaccess | 8 + public/index.php | 282 ++++++++++++--------- src/Http/Request.php | 108 +++++++- templates/layout.html | 4 +- templates/maintenance.html | 2 +- 38 files changed, 661 insertions(+), 315 deletions(-) create mode 100644 includes/autoload.php create mode 100644 public/.htaccess (limited to 'src') diff --git a/config/config.default.php b/config/config.default.php index ffa030db..c3a939cd 100644 --- a/config/config.default.php +++ b/config/config.default.php @@ -20,6 +20,9 @@ return [ // Set to development to enable debugging messages 'environment' => 'production', + // Site URL, used to generate links on page (https://example.com/[sub-dir/]) + 'url' => null, + // URL to the angel faq and job description 'faq_url' => 'https://events.ccc.de/congress/2013/wiki/Static:Volunteers', diff --git a/includes/autoload.php b/includes/autoload.php new file mode 100644 index 00000000..f51f89e4 --- /dev/null +++ b/includes/autoload.php @@ -0,0 +1,9 @@ + 'view', 'angeltype_id' => $angeltype_id]); } /** @@ -211,17 +211,21 @@ function angeltypes_list_controller() foreach ($angeltypes as &$angeltype) { $actions = [ - button(page_link_to('angeltypes') . '&action=view&angeltype_id=' . $angeltype['id'], _('view'), 'btn-xs') + button( + page_link_to('angeltypes', ['action' => 'view', 'angeltype_id' => $angeltype['id']]), + _('view'), + 'btn-xs' + ) ]; if (in_array('admin_angel_types', $privileges)) { $actions[] = button( - page_link_to('angeltypes') . '&action=edit&angeltype_id=' . $angeltype['id'], + page_link_to('angeltypes', ['action' => 'edit', 'angeltype_id' => $angeltype['id']]), _('edit'), 'btn-xs' ); $actions[] = button( - page_link_to('angeltypes') . '&action=delete&angeltype_id=' . $angeltype['id'], + page_link_to('angeltypes', ['action' => 'delete', 'angeltype_id' => $angeltype['id']]), _('delete'), 'btn-xs' ); @@ -230,13 +234,15 @@ function angeltypes_list_controller() $angeltype['membership'] = AngelType_render_membership($angeltype); if ($angeltype['user_angeltype_id'] != null) { $actions[] = button( - page_link_to('user_angeltypes') . '&action=delete&user_angeltype_id=' . $angeltype['user_angeltype_id'], + page_link_to('user_angeltypes', + ['action' => 'delete', 'user_angeltype_id' => $angeltype['user_angeltype_id']] + ), _('leave'), 'btn-xs' ); } else { $actions[] = button( - page_link_to('user_angeltypes') . '&action=add&angeltype_id=' . $angeltype['id'], + page_link_to('user_angeltypes', ['action' => 'add', 'angeltype_id' => $angeltype['id']]), _('join'), 'btn-xs' ); @@ -245,7 +251,11 @@ function angeltypes_list_controller() $angeltype['restricted'] = $angeltype['restricted'] ? glyph('lock') : ''; $angeltype['no_self_signup'] = $angeltype['no_self_signup'] ? '' : glyph('share'); - $angeltype['name'] = '' . $angeltype['name'] . ''; + $angeltype['name'] = '' + . $angeltype['name'] + . ''; $angeltype['actions'] = table_buttons($actions); } diff --git a/includes/controller/rooms_controller.php b/includes/controller/rooms_controller.php index 2d6f1a77..81b0113e 100644 --- a/includes/controller/rooms_controller.php +++ b/includes/controller/rooms_controller.php @@ -1,4 +1,5 @@ 'view', 'room_id' => $room['RID']]); } /** @@ -100,7 +101,7 @@ function room_link($room) */ function room_edit_link($room) { - return page_link_to('admin_rooms') . '&show=edit&id=' . $room['RID']; + return page_link_to('admin_rooms', ['show' => 'edit', 'id' => $room['RID']]); } /** diff --git a/includes/controller/shifts_controller.php b/includes/controller/shifts_controller.php index 21c6e160..f4f3f119 100644 --- a/includes/controller/shifts_controller.php +++ b/includes/controller/shifts_controller.php @@ -1,4 +1,5 @@ 'view']); if (isset($shift['SID'])) { $link .= '&shift_id=' . $shift['SID']; } @@ -20,7 +21,7 @@ function shift_link($shift) */ function shift_delete_link($shift) { - return page_link_to('user_shifts') . '&delete_shift=' . $shift['SID']; + return page_link_to('user_shifts', ['delete_shift' => $shift['SID']]); } /** @@ -29,7 +30,7 @@ function shift_delete_link($shift) */ function shift_edit_link($shift) { - return page_link_to('user_shifts') . '&edit_shift=' . $shift['SID']; + return page_link_to('user_shifts', ['edit_shift' => $shift['SID']]); } /** @@ -228,7 +229,9 @@ function shift_delete_controller() date('Y-m-d H:i', $shift['start']), date('H:i', $shift['end']) ), true), - '' . _('delete') . '' + '' . _('delete') . '' ]); } diff --git a/includes/controller/shifttypes_controller.php b/includes/controller/shifttypes_controller.php index acdeb982..3ef2675f 100644 --- a/includes/controller/shifttypes_controller.php +++ b/includes/controller/shifttypes_controller.php @@ -6,7 +6,7 @@ */ function shifttype_link($shifttype) { - return page_link_to('shifttypes') . '&action=view&shifttype_id=' . $shifttype['id']; + return page_link_to('shifttypes', ['action' => 'view', 'shifttype_id' => $shifttype['id']]); } /** @@ -107,7 +107,7 @@ function shifttype_edit_controller() engelsystem_log('Created shifttype ' . $name); success(_('Created shifttype.')); } - redirect(page_link_to('shifttypes') . '&action=view&shifttype_id=' . $shifttype_id); + redirect(page_link_to('shifttypes', ['action' => 'view', 'shifttype_id' => $shifttype_id])); } } diff --git a/includes/controller/user_angeltypes_controller.php b/includes/controller/user_angeltypes_controller.php index 41185552..b427e868 100644 --- a/includes/controller/user_angeltypes_controller.php +++ b/includes/controller/user_angeltypes_controller.php @@ -17,8 +17,7 @@ function user_angeltypes_unconfirmed_hint() $unconfirmed_links = []; foreach ($unconfirmed_user_angeltypes as $user_angeltype) { $unconfirmed_links[] = '' . $user_angeltype['name'] . ' (+' . $user_angeltype['count'] . ')' . ''; @@ -61,7 +60,7 @@ function user_angeltypes_delete_all_controller() engelsystem_log(sprintf('Denied all users for angeltype %s', AngelType_name_render($angeltype))); success(sprintf(_('Denied all users for angeltype %s.'), AngelType_name_render($angeltype))); - redirect(page_link_to('angeltypes') . '&action=view&angeltype_id=' . $angeltype['id']); + redirect(page_link_to('angeltypes', ['action' => 'view', 'angeltype_id' => $angeltype['id']])); } return [ @@ -107,7 +106,7 @@ function user_angeltypes_confirm_all_controller() engelsystem_log(sprintf('Confirmed all users for angeltype %s', AngelType_name_render($angeltype))); success(sprintf(_('Confirmed all users for angeltype %s.'), AngelType_name_render($angeltype))); - redirect(page_link_to('angeltypes') . '&action=view&angeltype_id=' . $angeltype['id']); + redirect(page_link_to('angeltypes', ['action' => 'view', 'angeltype_id' => $angeltype['id']])); } return [ @@ -167,7 +166,7 @@ function user_angeltype_confirm_controller() User_Nick_render($user_source), AngelType_name_render($angeltype) )); - redirect(page_link_to('angeltypes') . '&action=view&angeltype_id=' . $angeltype['id']); + redirect(page_link_to('angeltypes', ['action' => 'view', 'angeltype_id' => $angeltype['id']])); } return [ @@ -224,7 +223,7 @@ function user_angeltype_delete_controller() engelsystem_log($success_message); success($success_message); - redirect(page_link_to('angeltypes') . '&action=view&angeltype_id=' . $angeltype['id']); + redirect(page_link_to('angeltypes', ['action' => 'view', 'angeltype_id' => $angeltype['id']])); } return [ @@ -290,7 +289,7 @@ function user_angeltype_update_controller() engelsystem_log($success_message); success($success_message); - redirect(page_link_to('angeltypes') . '&action=view&angeltype_id=' . $angeltype['id']); + redirect(page_link_to('angeltypes', ['action' => 'view', 'angeltype_id' => $angeltype['id']])); } return [ @@ -344,7 +343,7 @@ function user_angeltype_add_controller() AngelType_name_render($angeltype) )); - redirect(page_link_to('angeltypes') . '&action=view&angeltype_id=' . $angeltype['id']); + redirect(page_link_to('angeltypes', ['action' => 'view', 'angeltype_id' => $angeltype['id']])); } } @@ -386,7 +385,7 @@ function user_angeltype_join_controller($angeltype) )); } - redirect(page_link_to('angeltypes') . '&action=view&angeltype_id=' . $angeltype['id']); + redirect(page_link_to('angeltypes', ['action' => 'view', 'angeltype_id' => $angeltype['id']])); } return [ diff --git a/includes/controller/user_driver_licenses_controller.php b/includes/controller/user_driver_licenses_controller.php index fef278dd..3db31eff 100644 --- a/includes/controller/user_driver_licenses_controller.php +++ b/includes/controller/user_driver_licenses_controller.php @@ -63,7 +63,7 @@ function user_driver_license_edit_link($user = null) if ($user == null) { return page_link_to('user_driver_licenses'); } - return page_link_to('user_driver_licenses') . '&user_id=' . $user['UID']; + return page_link_to('user_driver_licenses', ['user_id' => $user['UID']]); } /** diff --git a/includes/controller/users_controller.php b/includes/controller/users_controller.php index b747cc83..6dc74d68 100644 --- a/includes/controller/users_controller.php +++ b/includes/controller/users_controller.php @@ -109,7 +109,7 @@ function users_link() */ function user_edit_link($user) { - return page_link_to('admin_user') . '&user_id=' . $user['UID']; + return page_link_to('admin_user', ['user_id' => $user['UID']]); } /** @@ -118,7 +118,7 @@ function user_edit_link($user) */ function user_delete_link($user) { - return page_link_to('users') . '&action=delete&user_id=' . $user['UID']; + return page_link_to('users', ['action' => 'delete', 'user_id' => $user['UID']]); } /** @@ -127,7 +127,7 @@ function user_delete_link($user) */ function user_link($user) { - return page_link_to('users') . '&action=view&user_id=' . $user['UID']; + return page_link_to('users', ['action' => 'view', 'user_id' => $user['UID']]); } /** @@ -363,7 +363,7 @@ function user_password_recovery_start_controller() _('Password recovery'), sprintf( _('Please visit %s to recover your password.'), - page_link_to_absolute('user_password_recovery') . '&token=' . $token + page_link_to_absolute('user_password_recovery', ['token' => $token]) ) ); success(_('We sent an email containing your password recovery link.')); diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index ff682871..c065d332 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -11,11 +11,7 @@ use Engelsystem\Renderer\Renderer; * This file includes all needed functions, connects to the db etc. */ -if (!is_readable(__DIR__ . '/../vendor/autoload.php')) { - die('Please run composer.phar install'); -} -require __DIR__ . '/../vendor/autoload.php'; - +require_once __DIR__ . '/autoload.php'; /** * Load configuration @@ -38,7 +34,7 @@ date_default_timezone_set($config->get('timezone')); * Initialize Request */ $request = new Request(); -$request->create(); +$request->create($_GET, $_POST, $_SERVER, config('url')); $request::setInstance($request); /** diff --git a/includes/pages/admin_active.php b/includes/pages/admin_active.php index 2e06f90d..5b91e413 100644 --- a/includes/pages/admin_active.php +++ b/includes/pages/admin_active.php @@ -82,9 +82,13 @@ function admin_active() $limit = ''; $msg = success(_('Marked angels.'), true); } else { - $set_active = '« ' - . _('back') . ' | ' + $set_active = '« ' + . _('back') + . ' | ' . _('apply') . ''; } @@ -176,28 +180,46 @@ function admin_active() $actions = []; if ($usr['Aktiv'] == 0) { - $actions[] = '' + $parameters = [ + 'active' => $usr['UID'], + 'search' => $search, + ]; + if ($show_all_shifts) { + $parameters['show_all_shifts'] = 1; + } + $actions[] = '' . _('set active') . ''; } if ($usr['Aktiv'] == 1 && $usr['Tshirt'] == 0) { - $actions[] = '' + $parametersRemove = [ + 'not_active' => $usr['UID'], + 'search' => $search, + ]; + $parametersShirt = [ + 'tshirt' => $usr['UID'], + 'search' => $search, + ]; + if ($show_all_shifts) { + $parametersRemove['show_all_shifts'] = 1; + $parametersShirt['show_all_shifts'] = 1; + } + $actions[] = '' . _('remove active') . ''; - $actions[] = '' + $actions[] = '' . _('got t-shirt') . ''; } if ($usr['Tshirt'] == 1) { - $actions[] = '' + $parameters = [ + 'not_tshirt' => $usr['UID'], + 'search' => $search, + ]; + if ($show_all_shifts) { + $parameters['show_all_shifts'] = 1; + } + $actions[] = '' . _('remove t-shirt') . ''; } diff --git a/includes/pages/admin_arrive.php b/includes/pages/admin_arrive.php index ebeccb8c..2f312b1f 100644 --- a/includes/pages/admin_arrive.php +++ b/includes/pages/admin_arrive.php @@ -92,8 +92,14 @@ function admin_arrive() $usr['rendered_arrival_date'] = $usr['arrival_date'] > 0 ? date('Y-m-d', $usr['arrival_date']) : '-'; $usr['arrived'] = $usr['Gekommen'] == 1 ? _('yes') : ''; $usr['actions'] = $usr['Gekommen'] == 1 - ? '' . _('reset') . '' - : '' . _('arrived') . ''; + ? '' . _('reset') . '' + : '' . _('arrived') . ''; if ($usr['arrival_date'] > 0) { $day = date('Y-m-d', $usr['arrival_date']); diff --git a/includes/pages/admin_free.php b/includes/pages/admin_free.php index ebf227a4..a3c0d17f 100644 --- a/includes/pages/admin_free.php +++ b/includes/pages/admin_free.php @@ -94,7 +94,7 @@ function admin_free() 'email' => $usr['email_by_human_allowed'] ? $usr['email'] : glyph('eye-close'), 'actions' => in_array('admin_user', $privileges) - ? button(page_link_to('admin_user') . '&id=' . $usr['UID'], _('edit'), 'btn-xs') + ? button(page_link_to('admin_user', ['id' => $usr['UID']]), _('edit'), 'btn-xs') : '' ]; } diff --git a/includes/pages/admin_groups.php b/includes/pages/admin_groups.php index c483a79d..d64afe76 100644 --- a/includes/pages/admin_groups.php +++ b/includes/pages/admin_groups.php @@ -38,7 +38,8 @@ function admin_groups() 'name' => $group['Name'], 'privileges' => join(', ', $privileges_html), 'actions' => button( - page_link_to('admin_groups') . '&action=edit&id=' . $group['UID'], + page_link_to('admin_groups', + ['action' => 'edit', 'id' => $group['UID']]), _('edit'), 'btn-xs' ) @@ -93,7 +94,10 @@ function admin_groups() $privileges_form[] = form_submit('submit', _('Save')); $html .= page_with_title(_('Edit group'), [ - form($privileges_form, page_link_to('admin_groups') . '&action=save&id=' . $group_id) + form( + $privileges_form, + page_link_to('admin_groups', ['action' => 'save', 'id' => $group_id]) + ) ]); } else { return error('No Group found.', true); diff --git a/includes/pages/admin_news.php b/includes/pages/admin_news.php index 7f8ca1ba..a5354da7 100644 --- a/includes/pages/admin_news.php +++ b/includes/pages/admin_news.php @@ -31,16 +31,21 @@ function admin_news() $news = array_shift($news); $user_source = User($news['UID']); - $html .= form([ - form_info(_('Date'), date('Y-m-d H:i', $news['Datum'])), - form_info(_('Author'), User_Nick_render($user_source)), - form_text('eBetreff', _('Subject'), $news['Betreff']), - form_textarea('eText', _('Message'), $news['Text']), - form_checkbox('eTreffen', _('Meeting'), $news['Treffen'] == 1, 1), - form_submit('submit', _('Save')) - ], page_link_to('admin_news&action=save&id=' . $news_id)); + $html .= form( + [ + form_info(_('Date'), date('Y-m-d H:i', $news['Datum'])), + form_info(_('Author'), User_Nick_render($user_source)), + form_text('eBetreff', _('Subject'), $news['Betreff']), + form_textarea('eText', _('Message'), $news['Text']), + form_checkbox('eTreffen', _('Meeting'), $news['Treffen'] == 1, 1), + form_submit('submit', _('Save')) + ], + page_link_to('admin_news', ['action' => 'save', 'id' => $news_id]) + ); - $html .= '' + $html .= '' . ' ' . _('Delete') . ''; break; diff --git a/includes/pages/admin_questions.php b/includes/pages/admin_questions.php index d05bace6..938e63a9 100644 --- a/includes/pages/admin_questions.php +++ b/includes/pages/admin_questions.php @@ -52,9 +52,9 @@ function admin_questions() 'answer' => form([ form_textarea('answer', '', ''), form_submit('submit', _('Save')) - ], page_link_to('admin_questions') . '&action=answer&id=' . $question['QID']), + ], page_link_to('admin_questions', ['action' => 'answer', 'id' => $question['QID']])), 'actions' => button( - page_link_to('admin_questions') . '&action=delete&id=' . $question['QID'], + page_link_to('admin_questions', ['action' => 'delete', 'id' => $question['QID']]), _('delete'), 'btn-xs' ) @@ -72,7 +72,7 @@ function admin_questions() 'answered_by' => User_Nick_render($answer_user_source), 'answer' => str_replace("\n", '
          ', $question['Answer']), 'actions' => button( - page_link_to('admin_questions') . '&action=delete&id=' . $question['QID'], + page_link_to('admin_questions', ['action' => 'delete', 'id' => $question['QID']]), _('delete'), 'btn-xs' ) diff --git a/includes/pages/admin_rooms.php b/includes/pages/admin_rooms.php index 3045242b..8a7720d8 100644 --- a/includes/pages/admin_rooms.php +++ b/includes/pages/admin_rooms.php @@ -25,8 +25,8 @@ function admin_rooms() 'from_pentabarf' => $room['FromPentabarf'] == 'Y' ? '✓' : '', 'public' => $room['show'] == 'Y' ? '✓' : '', 'actions' => table_buttons([ - button(page_link_to('admin_rooms') . '&show=edit&id=' . $room['RID'], _('edit'), 'btn-xs'), - button(page_link_to('admin_rooms') . '&show=delete&id=' . $room['RID'], _('delete'), 'btn-xs') + button(page_link_to('admin_rooms', ['show' => 'edit', 'id' => $room['RID']]), _('edit'), 'btn-xs'), + button(page_link_to('admin_rooms', ['show' => 'delete', 'id' => $room['RID']]), _('delete'), 'btn-xs') ]) ]; } @@ -227,7 +227,7 @@ function admin_rooms() sprintf(_('Do you want to delete room %s?'), $name), buttons([ button( - page_link_to('admin_rooms') . '&show=delete&id=' . $room_id . '&ack', + page_link_to('admin_rooms', ['show' => 'delete', 'id' => $room_id, 'ack' => 1]), _('Delete'), 'delete btn-danger' ) @@ -238,7 +238,7 @@ function admin_rooms() return page_with_title(admin_rooms_title(), [ buttons([ - button(page_link_to('admin_rooms') . '&show=edit', _('add')) + button(page_link_to('admin_rooms', ['show' => 'edit']), _('add')) ]), msg(), table([ diff --git a/includes/pages/admin_user.php b/includes/pages/admin_user.php index 510e2292..00113507 100644 --- a/includes/pages/admin_user.php +++ b/includes/pages/admin_user.php @@ -46,25 +46,27 @@ function admin_user() . 'Wenn T-Shirt ein \'Ja\' enthält, bedeutet dies, dass der Engel ' . 'bereits sein T-Shirt erhalten hat.

          ' . "\n"; - $html .= '
          ' . "\n"; + $html .= '' . "\n"; $html .= '' . "\n"; $html .= '' . "\n"; $html .= ''; @@ -105,7 +107,8 @@ function admin_user() $html .= form_info('', _('Please visit the angeltypes page or the users profile to manage users angeltypes.')); $html .= 'Hier kannst Du das Passwort dieses Engels neu setzen:' . "\n"; + . page_link_to('admin_user', ['action' => 'change_pw', 'id' => $user_id]) + . '" method="post">' . "\n"; $html .= '
          ' . "\n"; $html .= '' . "\n"; - $html .= ' ' . "\n"; + $html .= ' ' . "\n"; $html .= ' ' . "\n"; - $html .= ' ' . "\n"; - $html .= ' ' . "\n"; - $html .= ' ' . "\n"; - $html .= ' ' . "\n"; - $html .= ' ' . "\n"; - $html .= ' ' . "\n"; + $html .= ' ' . "\n"; + $html .= ' ' . "\n"; + $html .= ' ' . "\n"; + $html .= ' ' . "\n"; + $html .= ' ' . "\n"; + $html .= ' ' . "\n"; if ($user_source['email_by_human_allowed']) { - $html .= " ' . "\n"; + $html .= " ' . "\n"; } - $html .= " ' . "\n"; + $html .= " ' . "\n"; $html .= ' ' . "\n"; @@ -91,7 +93,7 @@ function admin_user() $html .= ' ' . "\n"; - $html .= ' ' . "\n"; + $html .= ' ' . "\n"; $html .= '
          Nick' . '
          Nick' . '
          Last login

          ' . date('Y-m-d H:i', $user_source['lastLogIn']) . '

          Name' . '
          Vorname' . '
          Alter' . '
          Telefon' . '
          Handy' . '
          DECT' . '
          Name' . '
          Vorname' . '
          Alter' . '
          Telefon' . '
          Handy' . '
          DECT' . '
          email" . '
          email" . '
          jabber" . '
          jabber" . '
          Size' . html_select_key('size', 'eSize', $tshirt_sizes, $user_source['Size']) . '
          T-Shirt' . "\n"; $html .= html_options('eTshirt', $options, $user_source['Tshirt']) . '
          Hometown' . '
          Hometown' . '
          ' . "\n" . '
          ' . "\n"; $html .= ' ' . "\n"; $html .= ' ' . "\n"; @@ -134,7 +137,8 @@ function admin_user() if ($user_id != $user['UID'] && $my_highest_group <= $his_highest_group) { $html .= 'Hier kannst Du die Benutzergruppen des Engels festlegen:' . "\n"; + . page_link_to('admin_user', ['action' => 'save_groups', 'id' => $user_id]) + . '" method="post">' . "\n"; $html .= '
          Passwort' . '
          Wiederholung' . '
          '; $groups = DB::select(' diff --git a/includes/pages/guest_login.php b/includes/pages/guest_login.php index 106db33a..b83b8382 100644 --- a/includes/pages/guest_login.php +++ b/includes/pages/guest_login.php @@ -328,7 +328,7 @@ function guest_register() 'angel_types', _('What do you want to do?') . sprintf( ' (%s)', - page_link_to('angeltypes') . '&action=about', + page_link_to('angeltypes', ['action' => 'about']), _('Description of job types') ), $angel_types, @@ -467,7 +467,10 @@ function guest_login() heading(_('What can I do?'), 2), '

          ' . _('Please read about the jobs you can do to help us.') . '

          ', buttons([ - button(page_link_to('angeltypes') . '&action=about', _('Teams/Job description') . ' »') + button( + page_link_to('angeltypes', ['action' => 'about']), + _('Teams/Job description') . ' »' + ) ]) ]) ]) diff --git a/includes/pages/user_atom.php b/includes/pages/user_atom.php index a1e2580a..98ace9cc 100644 --- a/includes/pages/user_atom.php +++ b/includes/pages/user_atom.php @@ -66,9 +66,9 @@ function make_atom_entry_from_news($news_entry) { return ' ' . htmlspecialchars($news_entry['Betreff']) . ' - + ' . preg_replace('#^https?://#', '', page_link_to_absolute('news')) . '-' . $news_entry['ID'] . ' ' . date('Y-m-d\TH:i:sP', $news_entry['Datum']) . ' - ' . htmlspecialchars($news_entry['Text']) . ' + ' . htmlspecialchars($news_entry['Text']) . ' ' . "\n"; } diff --git a/includes/pages/user_messages.php b/includes/pages/user_messages.php index a811970d..320af9df 100644 --- a/includes/pages/user_messages.php +++ b/includes/pages/user_messages.php @@ -92,14 +92,14 @@ function user_messages() if ($message['RUID'] == $user['UID']) { if ($message['isRead'] == 'N') { $messages_table_entry['actions'] = button( - page_link_to('user_messages') . '&action=read&id=' . $message['id'], + page_link_to('user_messages', ['action' => 'read', 'id' => $message['id']]), _('mark as read'), 'btn-xs' ); } } else { $messages_table_entry['actions'] = button( - page_link_to('user_messages') . '&action=delete&id=' . $message['id'], + page_link_to('user_messages', ['action' => 'delete', 'id' => $message['id']]), _('delete message'), 'btn-xs' ); @@ -119,7 +119,7 @@ function user_messages() 'text' => _('Message'), 'actions' => '' ], $messages_table) - ], page_link_to('user_messages') . '&action=send') + ], page_link_to('user_messages', ['action' => 'send'])) ]); } else { switch ($request->input('action')) { diff --git a/includes/pages/user_myshifts.php b/includes/pages/user_myshifts.php index 14b5b8ee..572b777a 100644 --- a/includes/pages/user_myshifts.php +++ b/includes/pages/user_myshifts.php @@ -38,14 +38,14 @@ function user_myshifts() if ($request->input('reset') == 'ack') { User_reset_api_key($user); success(_('Key changed.')); - redirect(page_link_to('users') . '&action=view&user_id=' . $shifts_user['UID']); + redirect(page_link_to('users', ['action' => 'view', 'user_id' => $shifts_user['UID']])); } return page_with_title(_('Reset API key'), [ error( _('If you reset the key, the url to your iCal- and JSON-export and your atom feed changes! You have to update it in every application using one of these exports.'), true ), - button(page_link_to('user_myshifts') . '&reset=ack', _('Continue'), 'btn-danger') + button(page_link_to('user_myshifts', ['reset' => 'ack']), _('Continue'), 'btn-danger') ]); } elseif ($request->has('edit') && preg_match('/^\d*$/', $request->input('edit'))) { $user_id = $request->input('edit'); @@ -111,7 +111,7 @@ function user_myshifts() . '. Freeloaded: ' . ($freeloaded ? 'YES Comment: ' . $freeload_comment : 'NO') ); success(_('Shift saved.')); - redirect(page_link_to('users') . '&action=view&user_id=' . $shifts_user['UID']); + redirect(page_link_to('users', ['action' => 'view', 'user_id' => $shifts_user['UID']])); } } @@ -172,6 +172,6 @@ function user_myshifts() } } - redirect(page_link_to('users') . '&action=view&user_id=' . $shifts_user['UID']); + redirect(page_link_to('users', ['action' => 'view', 'user_id' => $shifts_user['UID']])); return ''; } diff --git a/includes/pages/user_news.php b/includes/pages/user_news.php index 9bdcb6fb..2dd141ec 100644 --- a/includes/pages/user_news.php +++ b/includes/pages/user_news.php @@ -35,8 +35,8 @@ function user_meetings() $html = '

          ' . meetings_title() . '

          ' . msg(); $request = request(); - if ($request->has('page') && preg_match('/^\d{1,}$/', $request->input('page'))) { - $page = $request->input('page'); + if (preg_match('/^\d{1,}$/', $request->input('page', 0))) { + $page = $request->input('page', 0); } else { $page = 0; } @@ -57,14 +57,14 @@ function user_meetings() $dis_rows = ceil(count(DB::select('SELECT `ID` FROM `News`')) / $display_news); $html .= '
          ' . '
            '; for ($i = 0; $i < $dis_rows; $i++) { - if ($request->has('page') && $i == $request->input('page')) { + if ($request->has('page') && $i == $request->input('page', 0)) { $html .= '
          • '; } elseif (!$request->has('page') && $i == 0) { $html .= '
          • '; } else { $html .= '
          • '; } - $html .= '' . ($i + 1) . '
          • '; + $html .= '' . ($i + 1) . ''; } $html .= '
          '; @@ -89,7 +89,7 @@ function display_news($news) $html .= ' @@ -38,7 +38,7 @@ · Contact · Bugs / Features · Development Platform - · Credits + · Credits diff --git a/templates/maintenance.html b/templates/maintenance.html index 3f7dae8a..bd73bd74 100644 --- a/templates/maintenance.html +++ b/templates/maintenance.html @@ -21,7 +21,7 @@ - + ENGELSYSTEM -- cgit v1.2.3-54-g00ecf From cc01c906ba63b3797bf2b9ef92a6854fe2ddbefb Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 29 Aug 2017 16:21:25 +0200 Subject: #336: Integration of symfony/http-foundation request --- composer.json | 5 +- config/config.default.php | 5 +- includes/controller/angeltypes_controller.php | 2 +- includes/controller/shift_entries_controller.php | 2 +- includes/controller/shifts_controller.php | 25 ++-- includes/controller/users_controller.php | 12 +- includes/engelsystem_provider.php | 5 +- includes/helper/internationalization_helper.php | 14 ++- includes/pages/admin_groups.php | 5 +- includes/pages/admin_news.php | 7 +- includes/pages/admin_rooms.php | 13 ++- includes/pages/admin_shifts.php | 10 +- includes/pages/admin_user.php | 40 +++---- includes/pages/guest_login.php | 8 +- includes/pages/user_atom.php | 17 +-- includes/pages/user_news.php | 10 +- includes/pages/user_settings.php | 8 +- includes/pages/user_shifts.php | 4 +- includes/sys_form.php | 9 +- includes/sys_menu.php | 18 +-- includes/sys_page.php | 14 ++- phpunit.xml | 15 +-- public/index.php | 8 +- src/Exceptions/Handler.php | 56 ++++++++- src/Http/Request.php | 138 ++--------------------- src/Routing/UrlGenerator.php | 27 +++++ src/helpers.php | 11 ++ 27 files changed, 230 insertions(+), 258 deletions(-) create mode 100644 src/Routing/UrlGenerator.php (limited to 'src') diff --git a/composer.json b/composer.json index d2e0108b..e6d20108 100644 --- a/composer.json +++ b/composer.json @@ -16,10 +16,11 @@ "require": { "php": ">=5.6.4", "erusev/parsedown": "1.6.*", - "twbs/bootstrap": "^3.3" + "twbs/bootstrap": "^3.3", + "symfony/http-foundation": "^3.3" }, "require-dev": { - "phpunit/phpunit": "^6.2" + "phpunit/phpunit": "^6.3" }, "autoload": { "psr-4": { diff --git a/config/config.default.php b/config/config.default.php index c3a939cd..a0303b15 100644 --- a/config/config.default.php +++ b/config/config.default.php @@ -20,9 +20,6 @@ return [ // Set to development to enable debugging messages 'environment' => 'production', - // Site URL, used to generate links on page (https://example.com/[sub-dir/]) - 'url' => null, - // URL to the angel faq and job description 'faq_url' => 'https://events.ccc.de/congress/2013/wiki/Static:Volunteers', @@ -58,7 +55,7 @@ return [ // Blowfish '$2y$13' // SHA-256 '$5$rounds=5000' // SHA-512 '$6$rounds=5000' - 'crypt_alg' => '$6$rounds=5000', // SHA-512 + 'crypt_alg' => '$6$rounds=5000', 'min_password_length' => 8, diff --git a/includes/controller/angeltypes_controller.php b/includes/controller/angeltypes_controller.php index d60b6fc7..8c1cbe5d 100644 --- a/includes/controller/angeltypes_controller.php +++ b/includes/controller/angeltypes_controller.php @@ -127,7 +127,7 @@ function angeltype_edit_controller() if (!$supporter_mode) { if ($request->has('name')) { - $result = AngelType_validate_name($request->get('name'), $angeltype); + $result = AngelType_validate_name($request->postData('name'), $angeltype); $angeltype['name'] = $result->getValue(); if (!$result->isValid()) { $valid = false; diff --git a/includes/controller/shift_entries_controller.php b/includes/controller/shift_entries_controller.php index 38aad5bb..3890241d 100644 --- a/includes/controller/shift_entries_controller.php +++ b/includes/controller/shift_entries_controller.php @@ -27,10 +27,10 @@ function shift_entry_add_controller() } $shift = Shift($shift_id); - $shift['Name'] = $room_array[$shift['RID']]; if ($shift == null) { redirect(page_link_to('user_shifts')); } + $shift['Name'] = $room_array[$shift['RID']]; $type_id = 0; if ($request->has('type_id') && preg_match('/^\d*$/', $request->input('type_id'))) { diff --git a/includes/controller/shifts_controller.php b/includes/controller/shifts_controller.php index f4f3f119..f68f64fe 100644 --- a/includes/controller/shifts_controller.php +++ b/includes/controller/shifts_controller.php @@ -62,7 +62,7 @@ function shift_edit_controller() $angeltypes = select_array(AngelTypes(), 'id', 'name'); $shifttypes = select_array(ShiftTypes(), 'id', 'name'); - $needed_angel_types = select_array(NeededAngelTypes_by_shift($shift_id), 'id', 'count'); + $needed_angel_types = select_array(NeededAngelTypes_by_shift($shift_id), 'angel_type_id', 'count'); foreach (array_keys($angeltypes) as $angeltype_id) { if (!isset($needed_angel_types[$angeltype_id])) { $needed_angel_types[$angeltype_id] = 0; @@ -117,15 +117,20 @@ function shift_edit_controller() $msg .= error(_('The ending time has to be after the starting time.'), true); } - foreach ($needed_angel_types as $needed_angeltype_id => $needed_angeltype_name) { - if ($request->has('type_' . $needed_angeltype_id) && test_request_int('type_' . $needed_angeltype_id)) { - $needed_angel_types[$needed_angeltype_id] = trim($request->input('type_' . $needed_angeltype_id)); - } else { - $valid = false; - $msg .= error(sprintf( - _('Please check your input for needed angels of type %s.'), - $needed_angeltype_name - ), true); + foreach ($needed_angel_types as $needed_angeltype_id => $count) { + $needed_angel_types[$needed_angeltype_id] = 0; + + $queryKey = 'type_' . $needed_angeltype_id; + if ($request->has($queryKey)) { + if (test_request_int($queryKey)) { + $needed_angel_types[$needed_angeltype_id] = trim($request->input($queryKey)); + } else { + $valid = false; + $msg .= error(sprintf( + _('Please check your input for needed angels of type %s.'), + $angeltypes[$needed_angeltype_id] + ), true); + } } } diff --git a/includes/controller/users_controller.php b/includes/controller/users_controller.php index 6dc74d68..b8a1fdbd 100644 --- a/includes/controller/users_controller.php +++ b/includes/controller/users_controller.php @@ -47,7 +47,7 @@ function user_delete_controller() $request = request(); if ($request->has('user_id')) { - $user_source = User($request->get('user_id')); + $user_source = User($request->query->get('user_id')); } else { $user_source = $user; } @@ -68,7 +68,7 @@ function user_delete_controller() if ( !( $request->has('password') - && verify_password($request->post('password'), $user['Passwort'], $user['UID']) + && verify_password($request->postData('password'), $user['Passwort'], $user['UID']) ) ) { $valid = false; @@ -307,9 +307,9 @@ function user_password_recovery_set_new_controller() if ( $request->has('password') - && strlen($request->post('password')) >= config('min_password_length') + && strlen($request->postData('password')) >= config('min_password_length') ) { - if ($request->post('password') != $request->post('password2')) { + if ($request->postData('password') != $request->postData('password2')) { $valid = false; error(_('Your passwords don\'t match.')); } @@ -319,7 +319,7 @@ function user_password_recovery_set_new_controller() } if ($valid) { - set_password($user_source['UID'], $request->post('password')); + set_password($user_source['UID'], $request->postData('password')); success(_('Password saved.')); redirect(page_link_to('login')); } @@ -363,7 +363,7 @@ function user_password_recovery_start_controller() _('Password recovery'), sprintf( _('Please visit %s to recover your password.'), - page_link_to_absolute('user_password_recovery', ['token' => $token]) + page_link_to('user_password_recovery', ['token' => $token]) ) ); success(_('We sent an email containing your password recovery link.')); diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index c065d332..e6b457d9 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -32,9 +32,10 @@ date_default_timezone_set($config->get('timezone')); /** * Initialize Request + * + * @var Request $request */ -$request = new Request(); -$request->create($_GET, $_POST, $_SERVER, config('url')); +$request = Request::createFromGlobals(); $request::setInstance($request); /** diff --git a/includes/helper/internationalization_helper.php b/includes/helper/internationalization_helper.php index d2dbcdbd..83faabb0 100644 --- a/includes/helper/internationalization_helper.php +++ b/includes/helper/internationalization_helper.php @@ -1,5 +1,7 @@ 0 ? '&' : '?') . 'set_locale='; + $request = Request::getInstance(); $items = []; foreach (config('locales') as $locale => $name) { + $url = url($request->getPathInfo(), ['set_locale' => $locale]); + $items[] = toolbar_item_link( - htmlspecialchars($url) . $locale, + htmlspecialchars($url), '', - '' . $name . ' ' . $name + sprintf( + '%s %2$s', + url('pic/flag/' . $locale . '.png'), + $name + ) ); } return $items; diff --git a/includes/pages/admin_groups.php b/includes/pages/admin_groups.php index d64afe76..1de8bfb7 100644 --- a/includes/pages/admin_groups.php +++ b/includes/pages/admin_groups.php @@ -81,7 +81,8 @@ function admin_groups() 'privileges[]', $privilege['desc'] . ' (' . $privilege['name'] . ')', $privilege['group_id'] != '', - $privilege['id'] + $privilege['id'], + 'privilege-' . $privilege['name'] ); $privileges_html .= sprintf( '', @@ -112,7 +113,7 @@ function admin_groups() } $group = DB::select('SELECT * FROM `Groups` WHERE `UID`=? LIMIT 1', [$group_id]); - $privileges = $request->get('privileges'); + $privileges = $request->postData('privileges'); if (!is_array($privileges)) { $privileges = []; } diff --git a/includes/pages/admin_news.php b/includes/pages/admin_news.php index a5354da7..64a54f4b 100644 --- a/includes/pages/admin_news.php +++ b/includes/pages/admin_news.php @@ -62,14 +62,15 @@ function admin_news() ', [ time(), - $request->post('eBetreff'), - $request->post('eText'), + $request->postData('eBetreff'), + $request->postData('eText'), $user['UID'], $request->has('eTreffen') ? 1 : 0, $news_id ] ); - engelsystem_log('News updated: ' . $request->post('eBetreff')); + + engelsystem_log('News updated: ' . $request->postData('eBetreff')); success(_('News entry updated.')); redirect(page_link_to('news')); break; diff --git a/includes/pages/admin_rooms.php b/includes/pages/admin_rooms.php index 8a7720d8..457114a0 100644 --- a/includes/pages/admin_rooms.php +++ b/includes/pages/admin_rooms.php @@ -110,11 +110,14 @@ function admin_rooms() } foreach ($angeltypes as $angeltype_id => $angeltype) { - if ( - $request->has('angeltype_count_' . $angeltype_id) - && preg_match('/^\d{1,4}$/', $request->input('angeltype_count_' . $angeltype_id)) - ) { - $angeltypes_count[$angeltype_id] = $request->input('angeltype_count_' . $angeltype_id); + $angeltypes_count[$angeltype_id] = 0; + $queryKey = 'angeltype_count_' . $angeltype_id; + if (!$request->has($queryKey)) { + continue; + } + + if (preg_match('/^\d{1,4}$/', $request->input($queryKey))) { + $angeltypes_count[$angeltype_id] = $request->input($queryKey); } else { $valid = false; $msg .= error(sprintf(_('Please enter needed angels for type %s.'), $angeltype), true); diff --git a/includes/pages/admin_shifts.php b/includes/pages/admin_shifts.php index 5b53f9cd..d36635f7 100644 --- a/includes/pages/admin_shifts.php +++ b/includes/pages/admin_shifts.php @@ -135,16 +135,14 @@ function admin_shifts() } elseif ($request->input('angelmode') == 'manually') { $angelmode = 'manually'; foreach ($types as $type) { - if ( - $request->has('type_' . $type['id']) - && preg_match('/^\d+$/', trim($request->input('type_' . $type['id']))) - ) { - $needed_angel_types[$type['id']] = trim($request->input('type_' . $type['id'])); + if (preg_match('/^\d+$/', trim($request->input('type_' . $type['id'], 0)))) { + $needed_angel_types[$type['id']] = trim($request->input('type_' . $type['id'], 0)); } else { $valid = false; error(sprintf(_('Please check the needed angels for team %s.'), $type['name'])); } } + if (array_sum($needed_angel_types) == 0) { $valid = false; error(_('There are 0 angels needed. Please enter the amounts of needed angels.')); @@ -306,7 +304,7 @@ function admin_shifts() } } elseif ($request->has('submit')) { if ( - !$request->has('admin_shifts_shifts') + !isset($_SESSION['admin_shifts_shifts']) || !isset($_SESSION['admin_shifts_types']) || !is_array($_SESSION['admin_shifts_shifts']) || !is_array($_SESSION['admin_shifts_types']) diff --git a/includes/pages/admin_user.php b/includes/pages/admin_user.php index 00113507..aea68f52 100644 --- a/includes/pages/admin_user.php +++ b/includes/pages/admin_user.php @@ -261,7 +261,7 @@ function admin_user() `Handy` = ?, `Alter` =?, `DECT` = ?, - ' . ($user_source['email_by_human_allowed'] ? '`email` = ' . DB::getPdo()->quote($request->post('eemail')) . ',' : '') . ' + ' . ($user_source['email_by_human_allowed'] ? '`email` = ' . DB::getPdo()->quote($request->postData('eemail')) . ',' : '') . ' `jabber` = ?, `Size` = ?, `Gekommen`= ?, @@ -272,34 +272,34 @@ function admin_user() WHERE `UID` = ? LIMIT 1'; DB::update($sql, [ - $request->post('eNick'), - $request->post('eName'), - $request->post('eVorname'), - $request->post('eTelefon'), - $request->post('eHandy'), - $request->post('eAlter'), - $request->post('eDECT'), - $request->post('ejabber'), - $request->post('eSize'), - $request->post('eGekommen'), - $request->post('eAktiv'), + $request->postData('eNick'), + $request->postData('eName'), + $request->postData('eVorname'), + $request->postData('eTelefon'), + $request->postData('eHandy'), + $request->postData('eAlter'), + $request->postData('eDECT'), + $request->postData('ejabber'), + $request->postData('eSize'), + $request->postData('eGekommen'), + $request->postData('eAktiv'), $force_active, - $request->post('eTshirt'), - $request->post('Hometown'), + $request->postData('eTshirt'), + $request->postData('Hometown'), $user_id, ]); engelsystem_log( - 'Updated user: ' . $request->post('eNick') . ', ' . $request->post('eSize') - . ', arrived: ' . $request->post('eVorname') - . ', active: ' . $request->post('eAktiv') - . ', tshirt: ' . $request->post('eTshirt') + 'Updated user: ' . $request->postData('eNick') . ', ' . $request->postData('eSize') + . ', arrived: ' . $request->postData('eVorname') + . ', active: ' . $request->postData('eAktiv') + . ', tshirt: ' . $request->postData('eTshirt') ); $html .= success('Änderung wurde gespeichert...' . "\n", true); break; case 'change_pw': - if ($request->post('new_pw') != '' && $request->post('new_pw') == $request->post('new_pw2')) { - set_password($user_id, $request->post('new_pw')); + if ($request->postData('new_pw') != '' && $request->postData('new_pw') == $request->postData('new_pw2')) { + set_password($user_id, $request->postData('new_pw')); $user_source = User($user_id); engelsystem_log('Set new password for ' . User_Nick_render($user_source)); $html .= success('Passwort neu gesetzt.', true); diff --git a/includes/pages/guest_login.php b/includes/pages/guest_login.php index b83b8382..3966b55c 100644 --- a/includes/pages/guest_login.php +++ b/includes/pages/guest_login.php @@ -127,8 +127,8 @@ function guest_register() } } - if ($request->has('password') && strlen($request->post('password')) >= $min_password_length) { - if ($request->post('password') != $request->post('password2')) { + if ($request->has('password') && strlen($request->postData('password')) >= $min_password_length) { + if ($request->postData('password') != $request->postData('password2')) { $valid = false; $msg .= error(_('Your passwords don\'t match.'), true); } @@ -234,7 +234,7 @@ function guest_register() // Assign user-group and set password $user_id = DB::getPdo()->lastInsertId(); DB::insert('INSERT INTO `UserGroups` (`uid`, `group_id`) VALUES (?, -2)', [$user_id]); - set_password($user_id, $request->post('password')); + set_password($user_id, $request->postData('password')); // Assign angel-types $user_angel_types_info = []; @@ -403,7 +403,7 @@ function guest_login() if (count($login_user) > 0) { $login_user = $login_user[0]; if ($request->has('password')) { - if (!verify_password($request->post('password'), $login_user['Passwort'], $login_user['UID'])) { + if (!verify_password($request->postData('password'), $login_user['Passwort'], $login_user['UID'])) { $valid = false; error(_('Your password is incorrect. Please try it again.')); } diff --git a/includes/pages/user_atom.php b/includes/pages/user_atom.php index 98ace9cc..2991bdbf 100644 --- a/includes/pages/user_atom.php +++ b/includes/pages/user_atom.php @@ -1,6 +1,7 @@ Engelsystem - ' . $_SERVER['HTTP_HOST'] + ' . $request->getHttpHost() . htmlspecialchars(preg_replace( '#[&?]key=[a-f\d]{32}#', '', - $_SERVER['REQUEST_URI'] + $request->getRequestUri() )) . ' ' . date('Y-m-d\TH:i:sP', $news_entries[0]['Datum']) . '' . "\n"; @@ -64,11 +66,12 @@ function make_atom_entries_from_news($news_entries) function make_atom_entry_from_news($news_entry) { - return ' + return ' + ' . htmlspecialchars($news_entry['Betreff']) . ' - - ' . preg_replace('#^https?://#', '', page_link_to_absolute('news')) . '-' . $news_entry['ID'] . ' - ' . date('Y-m-d\TH:i:sP', $news_entry['Datum']) . ' + + ' . preg_replace('#^https?://#', '', page_link_to('news_comments', ['nid' => $news_entry['ID']])) . ' + ' . date('Y-m-d\TH:i:sP', $news_entry['Datum']) . ' ' . htmlspecialchars($news_entry['Text']) . ' - ' . "\n"; + ' . "\n"; } diff --git a/includes/pages/user_news.php b/includes/pages/user_news.php index 2dd141ec..bdbb0645 100644 --- a/includes/pages/user_news.php +++ b/includes/pages/user_news.php @@ -186,9 +186,9 @@ function user_news() $html = '

          ' . news_title() . '

          ' . msg(); - $isMeeting = $request->post('treffen'); + $isMeeting = $request->postData('treffen'); if ($request->has('text') && $request->has('betreff') && in_array('admin_news', $privileges)) { - if (!$request->has('treffen') || !in_array('admin_news', $privileges)) { + if (!$request->has('treffen')) { $isMeeting = 0; } DB::insert(' @@ -197,13 +197,13 @@ function user_news() ', [ time(), - $request->post('betreff'), - $request->post('text'), + $request->postData('betreff'), + $request->postData('text'), $user['UID'], $isMeeting, ] ); - engelsystem_log('Created news: ' . $_POST['betreff'] . ', treffen: ' . $isMeeting); + engelsystem_log('Created news: ' . $request->postData('betreff') . ', treffen: ' . $isMeeting); success(_('Entry saved.')); redirect(page_link_to('news')); } diff --git a/includes/pages/user_settings.php b/includes/pages/user_settings.php index 667e73d9..9a43f5ce 100644 --- a/includes/pages/user_settings.php +++ b/includes/pages/user_settings.php @@ -101,14 +101,14 @@ function user_settings_password($user_source) $request = request(); if ( !$request->has('password') - || !verify_password($request->post('password'), $user_source['Passwort'], $user_source['UID']) + || !verify_password($request->postData('password'), $user_source['Passwort'], $user_source['UID']) ) { error(_('-> not OK. Please try again.')); - } elseif (strlen($request->post('new_password')) < config('min_password_length')) { + } elseif (strlen($request->postData('new_password')) < config('min_password_length')) { error(_('Your password is to short (please use at least 6 characters).')); - } elseif ($request->post('new_password') != $request->post('new_password2')) { + } elseif ($request->postData('new_password') != $request->postData('new_password2')) { error(_('Your passwords don\'t match.')); - } elseif (set_password($user_source['UID'], $request->post('new_password'))) { + } elseif (set_password($user_source['UID'], $request->postData('new_password'))) { success(_('Password saved.')); } else { error(_('Failed setting password.')); diff --git a/includes/pages/user_shifts.php b/includes/pages/user_shifts.php index cd18a037..db0bb193 100644 --- a/includes/pages/user_shifts.php +++ b/includes/pages/user_shifts.php @@ -229,8 +229,8 @@ function view_user_shifts() 'shifts_table' => msg() . $shiftCalendarRenderer->render(), 'ical_text' => '

          ' . _('iCal export') . '

          ' . sprintf( _('Export of shown shifts. iCal format or JSON format available (please keep secret, otherwise reset the api key).'), - page_link_to_absolute('ical', ['key' => $user['api_key']]), - page_link_to_absolute('shifts_json_export', ['key' => $user['api_key']]), + page_link_to('ical', ['key' => $user['api_key']]), + page_link_to('shifts_json_export', ['key' => $user['api_key']]), page_link_to('user_myshifts', ['reset' => 1]) ) . '

          ', 'filter' => _('Filter') diff --git a/includes/sys_form.php b/includes/sys_form.php index 936e3203..78e97792 100644 --- a/includes/sys_form.php +++ b/includes/sys_form.php @@ -144,10 +144,15 @@ function form_multi_checkboxes($names, $label, $items, $selected, $disabled = [] * @param string $label * @param string $selected * @param string $value + * @param string $id * @return string */ -function form_checkbox($name, $label, $selected, $value = 'checked') +function form_checkbox($name, $label, $selected, $value = 'checked', $id = null) { + if (is_null($id)) { + $id = $name; + } + return '
          -- cgit v1.2.3-54-g00ecf From 2bd127c011846aad69731d1d63535a3d4f100af0 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Wed, 30 Aug 2017 19:57:01 +0200 Subject: Use symfony session --- includes/engelsystem_provider.php | 5 ++++- includes/helper/internationalization_helper.php | 11 ++++++----- includes/helper/message_helper.php | 21 +++++++++++---------- includes/pages/admin_shifts.php | 19 +++++++++---------- includes/pages/guest_login.php | 25 ++++++++++++++++++++----- includes/pages/user_settings.php | 3 ++- includes/pages/user_shifts.php | 11 +++++++---- includes/sys_auth.php | 11 +++++++---- src/helpers.php | 17 +++++++++++++++++ 9 files changed, 83 insertions(+), 40 deletions(-) (limited to 'src') diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index 65a319e9..aed331d4 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -6,6 +6,7 @@ use Engelsystem\Exceptions\Handler as ExceptionHandler; use Engelsystem\Http\Request; use Engelsystem\Renderer\HtmlEngine; use Engelsystem\Renderer\Renderer; +use Symfony\Component\HttpFoundation\Session\Session; /** * This file includes all needed functions, connects to the db etc. @@ -169,7 +170,9 @@ foreach ($includeFiles as $file) { /** * Init application */ -session_start(); +$session = new Session(); +$session->start(); +$request->setSession($session); gettext_init(); diff --git a/includes/helper/internationalization_helper.php b/includes/helper/internationalization_helper.php index 83faabb0..131941e9 100644 --- a/includes/helper/internationalization_helper.php +++ b/includes/helper/internationalization_helper.php @@ -9,7 +9,7 @@ use Engelsystem\Http\Request; */ function locale() { - return $_SESSION['locale']; + return session()->get('locale'); } /** @@ -29,11 +29,12 @@ function gettext_init() { $locales = config('locales'); $request = request(); + $session = session(); if ($request->has('set_locale') && isset($locales[$request->input('set_locale')])) { - $_SESSION['locale'] = $request->input('set_locale'); - } elseif (!isset($_SESSION['locale'])) { - $_SESSION['locale'] = config('default_locale'); + $session->set('locale', $request->input('set_locale')); + } elseif (!$session->has('locale')) { + $session->set('locale', config('default_locale')); } gettext_locale(); @@ -50,7 +51,7 @@ function gettext_init() function gettext_locale($locale = null) { if ($locale == null) { - $locale = $_SESSION['locale']; + $locale = session()->get('locale'); } putenv('LC_ALL=' . $locale); diff --git a/includes/helper/message_helper.php b/includes/helper/message_helper.php index 1f429c27..7a42a7b7 100644 --- a/includes/helper/message_helper.php +++ b/includes/helper/message_helper.php @@ -7,12 +7,12 @@ */ function msg() { - if (!isset($_SESSION['msg'])) { - return ''; - } - $msg = $_SESSION['msg']; - $_SESSION['msg'] = ''; - return $msg; + $session = session(); + + $message = $session->get('msg', ''); + $session->set('msg', ''); + + return $message; } /** @@ -61,6 +61,8 @@ function success($msg, $immediately = false) */ function alert($class, $msg, $immediately = false) { + $session = session(); + if ($immediately) { if ($msg == '') { return ''; @@ -68,10 +70,9 @@ function alert($class, $msg, $immediately = false) return '
          ' . $msg . '
          '; } - if (!isset($_SESSION['msg'])) { - $_SESSION['msg'] = ''; - } - $_SESSION['msg'] .= alert($class, $msg, true); + $message = $session->get('msg', ''); + $message .= alert($class, $msg, true); + $session->set('msg', $message); return null; } diff --git a/includes/pages/admin_shifts.php b/includes/pages/admin_shifts.php index 04d88a4f..c77bd46d 100644 --- a/includes/pages/admin_shifts.php +++ b/includes/pages/admin_shifts.php @@ -19,6 +19,7 @@ function admin_shifts() { $valid = true; $request = request(); + $session = session(); $start = parse_date('Y-m-d H:i', date('Y-m-d') . ' 00:00'); $end = $start; $mode = 'single'; @@ -270,8 +271,8 @@ function admin_shifts() } // Fürs Anlegen zwischenspeichern: - $_SESSION['admin_shifts_shifts'] = $shifts; - $_SESSION['admin_shifts_types'] = $needed_angel_types; + $session->set('admin_shifts_shifts', $shifts); + $session->set('admin_shifts_types', $needed_angel_types); $hidden_types = ''; foreach ($needed_angel_types as $type_id => $count) { @@ -301,16 +302,14 @@ function admin_shifts() } } elseif ($request->has('submit')) { if ( - !isset($_SESSION['admin_shifts_shifts']) - || !isset($_SESSION['admin_shifts_types']) - || !is_array($_SESSION['admin_shifts_shifts']) - || !is_array($_SESSION['admin_shifts_types']) + !is_array($session->get('admin_shifts_shifts')) + || !is_array($session->get('admin_shifts_types')) ) { redirect(page_link_to('admin_shifts')); } $needed_angel_types_info = []; - foreach ($_SESSION['admin_shifts_shifts'] as $shift) { + foreach ($session->get('admin_shifts_shifts', []) as $shift) { $shift['URL'] = null; $shift['PSID'] = null; $shift_id = Shift_create($shift); @@ -322,7 +321,7 @@ function admin_shifts() . ' to ' . date('Y-m-d H:i', $shift['end']) ); - foreach ($_SESSION['admin_shifts_types'] as $type_id => $count) { + foreach ($session->get('admin_shifts_types', []) as $type_id => $count) { $angel_type_source = DB::selectOne(' SELECT * FROM `AngelTypes` @@ -348,8 +347,8 @@ function admin_shifts() success('Schichten angelegt.'); redirect(page_link_to('admin_shifts')); } else { - unset($_SESSION['admin_shifts_shifts']); - unset($_SESSION['admin_shifts_types']); + $session->remove('admin_shifts_shifts'); + $session->remove('admin_shifts_types'); } $rid = null; diff --git a/includes/pages/guest_login.php b/includes/pages/guest_login.php index 4a77b40c..9179c6c4 100644 --- a/includes/pages/guest_login.php +++ b/includes/pages/guest_login.php @@ -39,6 +39,7 @@ function guest_register() $min_password_length = config('min_password_length'); $event_config = EventConfig(); $request = request(); + $session = session(); $msg = ''; $nick = ''; @@ -226,7 +227,7 @@ function guest_register() $password_hash, $comment, $hometown, - $_SESSION['locale'], + $session->get('locale'), $planned_arrival_date, ] ); @@ -377,25 +378,36 @@ function guest_register() ]); } +/** + * @return string + */ function entry_required() { return ''; } +/** + * @return bool + */ function guest_logout() { - session_destroy(); + session()->invalidate(); redirect(page_link_to('start')); return true; } +/** + * @return string + */ function guest_login() { $nick = ''; $request = request(); - unset($_SESSION['uid']); + $session = session(); $valid = true; + $session->remove('uid'); + if ($request->has('submit')) { if ($request->has('nick') && strlen(User_validate_Nick($request->input('nick'))) > 0) { $nick = User_validate_Nick($request->input('nick')); @@ -420,8 +432,8 @@ function guest_login() } if ($valid && !empty($login_user)) { - $_SESSION['uid'] = $login_user['UID']; - $_SESSION['locale'] = $login_user['Sprache']; + $session->set('uid', $login_user['UID']); + $session->set('locale', $login_user['Sprache']); redirect(page_link_to('news')); } @@ -477,6 +489,9 @@ function guest_login() ]); } +/** + * @return string + */ function get_register_hint() { global $privileges; diff --git a/includes/pages/user_settings.php b/includes/pages/user_settings.php index 03621a45..0ba8bbcb 100644 --- a/includes/pages/user_settings.php +++ b/includes/pages/user_settings.php @@ -164,6 +164,7 @@ function user_settings_locale($user_source, $locales) { $valid = true; $request = request(); + $session = session(); if ($request->has('language') && isset($locales[$request->input('language')])) { $user_source['Sprache'] = $request->input('language'); @@ -182,7 +183,7 @@ function user_settings_locale($user_source, $locales) $user_source['UID'], ] ); - $_SESSION['locale'] = $user_source['Sprache']; + $session->set('locale', $user_source['Sprache']); success('Language changed.'); redirect(page_link_to('user_settings')); diff --git a/includes/pages/user_shifts.php b/includes/pages/user_shifts.php index db0bb193..30abbde6 100644 --- a/includes/pages/user_shifts.php +++ b/includes/pages/user_shifts.php @@ -167,20 +167,23 @@ function view_user_shifts() { global $user, $privileges, $ical_shifts; + $session = session(); $ical_shifts = []; $days = load_days(); $rooms = load_rooms(); $types = load_types(); - if (!isset($_SESSION['ShiftsFilter'])) { + if (!$session->has('ShiftsFilter')) { $room_ids = [ $rooms[0]['id'] ]; $type_ids = array_map('get_ids_from_array', $types); - $_SESSION['ShiftsFilter'] = new ShiftsFilter(in_array('user_shifts_admin', $privileges), $room_ids, $type_ids); + $shiftsFilter = new ShiftsFilter(in_array('user_shifts_admin', $privileges), $room_ids, $type_ids); + $session->set('ShiftsFilter', $shiftsFilter); } - update_ShiftsFilter($_SESSION['ShiftsFilter'], in_array('user_shifts_admin', $privileges), $days); - $shiftsFilter = $_SESSION['ShiftsFilter']; + + $shiftsFilter = $session->get('ShiftsFilter'); + update_ShiftsFilter($shiftsFilter, in_array('user_shifts_admin', $privileges), $days); $shiftCalendarRenderer = shiftCalendarRendererByShiftFilter($shiftsFilter); diff --git a/includes/sys_auth.php b/includes/sys_auth.php index 36f0f935..4242261b 100644 --- a/includes/sys_auth.php +++ b/includes/sys_auth.php @@ -10,8 +10,10 @@ function load_auth() global $user, $privileges; $user = null; - if (isset($_SESSION['uid'])) { - $user = DB::selectOne('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$_SESSION['uid']]); + $session = session(); + + if ($session->has('uid')) { + $user = DB::selectOne('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$session->get('uid')]); if (!empty($user)) { // User ist eingeloggt, Datensatz zur Verfügung stellen und Timestamp updaten DB::update(' @@ -21,12 +23,13 @@ function load_auth() LIMIT 1 ', [ time(), - $_SESSION['uid'], + $session->get('uid'), ]); $privileges = privileges_for_user($user['UID']); return; } - unset($_SESSION['uid']); + + $session->remove('uid'); } // guest privileges diff --git a/src/helpers.php b/src/helpers.php index af0e802b..24f93f2c 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -5,6 +5,7 @@ use Engelsystem\Config\Config; use Engelsystem\Http\Request; use Engelsystem\Renderer\Renderer; use Engelsystem\Routing\UrlGenerator; +use Symfony\Component\HttpFoundation\Session\SessionInterface; /** * Get or set config values @@ -42,6 +43,22 @@ function request($key = null, $default = null) return $request->input($key, $default); } +/** + * @param string $key + * @param mixed $default + * @return SessionInterface|mixed + */ +function session($key = null, $default = null) +{ + $session = request()->getSession(); + + if (is_null($key)) { + return $session; + } + + return $session->get($key, $default); +} + /** * @param string $template * @param mixed[] $data -- cgit v1.2.3-54-g00ecf From 8c81adc8e83969e90b4c54daf4a396b1094134ff Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Thu, 31 Aug 2017 17:30:54 +0200 Subject: Implemented container --- .gitignore | 3 +- composer.json | 3 +- includes/engelsystem_provider.php | 20 ++++- includes/helper/internationalization_helper.php | 4 +- includes/pages/user_atom.php | 3 +- public/index.php | 3 - src/Config/Config.php | 28 ------- src/Container/Container.php | 105 ++++++++++++++++++++++++ src/Container/ContainerException.php | 11 +++ src/Container/NotFoundException.php | 10 +++ src/Http/Request.php | 25 ------ src/Renderer/Renderer.php | 24 +----- src/Routing/UrlGenerator.php | 4 +- src/helpers.php | 29 +++++-- 14 files changed, 175 insertions(+), 97 deletions(-) create mode 100644 src/Container/Container.php create mode 100644 src/Container/ContainerException.php create mode 100644 src/Container/NotFoundException.php (limited to 'src') diff --git a/.gitignore b/.gitignore index d712148b..eb3f8939 100644 --- a/.gitignore +++ b/.gitignore @@ -14,8 +14,9 @@ Thumbs.db _vimrc_local.vim .sass-cache -# PHPstorm config +# PHPstorm files /.idea/ +/.phpstorm.meta.php # Project files /config/config.php diff --git a/composer.json b/composer.json index 45dce626..0769a6b6 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,8 @@ "php": ">=7.0.0", "erusev/parsedown": "1.6.*", "twbs/bootstrap": "^3.3", - "symfony/http-foundation": "^3.3" + "symfony/http-foundation": "^3.3", + "psr/container": "^1.0" }, "require-dev": { "phpunit/phpunit": "^6.3" diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index aed331d4..f3c161a6 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -1,11 +1,13 @@ instance('container', $container); +$container->instance(ContainerInterface::class, $container); + + /** * Load configuration */ $config = new Config(); -Config::setInstance($config); +$container->instance('config', $config); $config->set(require __DIR__ . '/../config/config.default.php'); if (file_exists(__DIR__ . '/../config/config.php')) { @@ -37,7 +48,8 @@ date_default_timezone_set($config->get('timezone')); * @var Request $request */ $request = Request::createFromGlobals(); -$request::setInstance($request); +$container->instance('request', $request); + /** * Check for maintenance @@ -52,14 +64,15 @@ if ($config->get('maintenance')) { * Initialize renderer */ $renderer = new Renderer(); +$container->instance('renderer', $renderer); $renderer->addRenderer(new HtmlEngine()); -Renderer::setInstance($renderer); /** * Register error handler */ $errorHandler = new ExceptionHandler(); +$container->instance('error.handler', $errorHandler); if (config('environment') == 'development') { $errorHandler->setEnvironment(ExceptionHandler::ENV_DEVELOPMENT); ini_set('display_errors', true); @@ -171,6 +184,7 @@ foreach ($includeFiles as $file) { * Init application */ $session = new Session(); +$container->instance('session', $session); $session->start(); $request->setSession($session); diff --git a/includes/helper/internationalization_helper.php b/includes/helper/internationalization_helper.php index 131941e9..efbe5db5 100644 --- a/includes/helper/internationalization_helper.php +++ b/includes/helper/internationalization_helper.php @@ -1,7 +1,5 @@ $name) { diff --git a/includes/pages/user_atom.php b/includes/pages/user_atom.php index 2991bdbf..c9d9398e 100644 --- a/includes/pages/user_atom.php +++ b/includes/pages/user_atom.php @@ -1,7 +1,6 @@ Engelsystem diff --git a/public/index.php b/public/index.php index b44e1491..c65dbdf8 100644 --- a/public/index.php +++ b/public/index.php @@ -1,7 +1,5 @@ query->get('p'); if (empty($page)) { $page = $request->path(); diff --git a/src/Config/Config.php b/src/Config/Config.php index 02080de4..34c21a78 100644 --- a/src/Config/Config.php +++ b/src/Config/Config.php @@ -2,15 +2,8 @@ namespace Engelsystem\Config; -use ErrorException; - class Config { - /** - * @var self - */ - protected static $instance; - /** * The config values * @@ -104,25 +97,4 @@ class Config { $this->remove($key); } - - /** - * @return Config - * @throws ErrorException - */ - public static function getInstance() - { - if (!self::$instance instanceof self) { - throw new ErrorException('Config not initialized'); - } - - return self::$instance; - } - - /** - * @param self $instance - */ - public static function setInstance($instance) - { - self::$instance = $instance; - } } diff --git a/src/Container/Container.php b/src/Container/Container.php new file mode 100644 index 00000000..df2f92fe --- /dev/null +++ b/src/Container/Container.php @@ -0,0 +1,105 @@ +has($id)) { + return $this->resolve($id); + } + + throw new NotFoundException(sprintf('The entry with the id "%s" could not be found')); + } + + /** + * Register a shared entry in the container + * + * @param string $abstract Identifier of the entry to set + * @param mixed $instance Entry + */ + public function instance($abstract, $instance) + { + $this->instances[$abstract] = $instance; + } + + /** + * Returns true if the container can return an entry for the given identifier + * Returns false otherwise + * + * `has($id)` returning true does not mean that `get($id)` will not throw an exception + * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface` + * + * @param string $id Identifier of the entry to look for + * + * @return bool + */ + public function has($id) + { + return isset($this->instances[$id]); + } + + /** + * Get the globally available instance of the container + * + * @return Container + */ + public static function getInstance() + { + if (is_null(static::$instance)) { + static::$instance = new static; + } + + return static::$instance; + } + + /** + * Set the globally available instance of the container + * + * @param Container $container + */ + public static function setInstance(Container $container) + { + static::$instance = $container; + } + + /** + * Resolve the requested object + * + * @param string $abstract + * @return mixed + */ + protected function resolve($abstract) + { + return $this->instances[$abstract]; + } +} diff --git a/src/Container/ContainerException.php b/src/Container/ContainerException.php new file mode 100644 index 00000000..3cdde506 --- /dev/null +++ b/src/Container/ContainerException.php @@ -0,0 +1,11 @@ +getUri()), '/'); } - - /** - * @return self - * @throws ErrorException - */ - public static function getInstance() - { - if (!self::$instance instanceof self) { - throw new ErrorException('Request not initialized'); - } - - return self::$instance; - } - - /** - * @param self $instance - */ - public static function setInstance($instance) - { - self::$instance = $instance; - } } diff --git a/src/Renderer/Renderer.php b/src/Renderer/Renderer.php index bf3d5609..5ed7cf31 100644 --- a/src/Renderer/Renderer.php +++ b/src/Renderer/Renderer.php @@ -2,13 +2,8 @@ namespace Engelsystem\Renderer; -use ErrorException; - class Renderer { - /** @var self */ - protected static $instance; - /** @var EngineInterface[] */ protected $renderer = []; @@ -29,7 +24,7 @@ class Renderer return $renderer->get($template, $data); } - engelsystem_error('Unable to find a renderer for template file «' . $template . '».'); + engelsystem_error('Unable to find a renderer for template file "' . $template . '".'); return ''; } @@ -42,21 +37,4 @@ class Renderer { $this->renderer[] = $renderer; } - - /** - * @return self - * @throws ErrorException - */ - public static function getInstance() - { - return self::$instance; - } - - /** - * @param self $instance - */ - public static function setInstance($instance) - { - self::$instance = $instance; - } } diff --git a/src/Routing/UrlGenerator.php b/src/Routing/UrlGenerator.php index 8dc464c6..33eef7b0 100644 --- a/src/Routing/UrlGenerator.php +++ b/src/Routing/UrlGenerator.php @@ -2,8 +2,6 @@ namespace Engelsystem\Routing; -use Engelsystem\Http\Request; - class UrlGenerator { /** @@ -14,7 +12,7 @@ class UrlGenerator public static function to($path, $parameters = []) { $path = '/' . ltrim($path, '/'); - $request = Request::getInstance(); + $request = app('request'); $uri = $request->getUriForPath($path); if (!empty($parameters) && is_array($parameters)) { diff --git a/src/helpers.php b/src/helpers.php index 24f93f2c..733b902d 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -2,11 +2,27 @@ // Some useful functions use Engelsystem\Config\Config; +use Engelsystem\Container\Container; use Engelsystem\Http\Request; use Engelsystem\Renderer\Renderer; use Engelsystem\Routing\UrlGenerator; use Symfony\Component\HttpFoundation\Session\SessionInterface; +/** + * Get the global container instance + * + * @param string $id + * @return mixed + */ +function app($id = null) +{ + if (is_null($id)) { + return Container::getInstance(); + } + + return Container::getInstance()->get($id); +} + /** * Get or set config values * @@ -16,15 +32,18 @@ use Symfony\Component\HttpFoundation\Session\SessionInterface; */ function config($key = null, $default = null) { + $config = app('config'); + if (empty($key)) { - return Config::getInstance(); + return $config; } if (is_array($key)) { - Config::getInstance()->set($key); + $config->set($key); + return true; } - return Config::getInstance()->get($key, $default); + return $config->get($key, $default); } /** @@ -34,7 +53,7 @@ function config($key = null, $default = null) */ function request($key = null, $default = null) { - $request = Request::getInstance(); + $request = app('request'); if (is_null($key)) { return $request; @@ -66,7 +85,7 @@ function session($key = null, $default = null) */ function view($template = null, $data = null) { - $renderer = Renderer::getInstance(); + $renderer = app('renderer'); if (is_null($template)) { return $renderer; -- cgit v1.2.3-54-g00ecf From 0ac981876432ff8f7f76ffee8c5102b633d760d4 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 19 Sep 2017 14:50:20 +0200 Subject: Added Application --- includes/engelsystem_provider.php | 19 ++++++++----------- src/Application.php | 25 +++++++++++++++++++++++++ src/Container/Container.php | 35 +++++++++++++++++++++++------------ src/helpers.php | 8 ++++---- 4 files changed, 60 insertions(+), 27 deletions(-) create mode 100644 src/Application.php (limited to 'src') diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index f3c161a6..e10fdba0 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -1,13 +1,12 @@ instance('container', $container); -$container->instance(ContainerInterface::class, $container); +$app = Application::getInstance(); /** * Load configuration */ $config = new Config(); -$container->instance('config', $config); +$app->instance('config', $config); $config->set(require __DIR__ . '/../config/config.default.php'); if (file_exists(__DIR__ . '/../config/config.php')) { @@ -48,7 +45,7 @@ date_default_timezone_set($config->get('timezone')); * @var Request $request */ $request = Request::createFromGlobals(); -$container->instance('request', $request); +$app->instance('request', $request); /** @@ -64,7 +61,7 @@ if ($config->get('maintenance')) { * Initialize renderer */ $renderer = new Renderer(); -$container->instance('renderer', $renderer); +$app->instance('renderer', $renderer); $renderer->addRenderer(new HtmlEngine()); @@ -72,7 +69,7 @@ $renderer->addRenderer(new HtmlEngine()); * Register error handler */ $errorHandler = new ExceptionHandler(); -$container->instance('error.handler', $errorHandler); +$app->instance('error.handler', $errorHandler); if (config('environment') == 'development') { $errorHandler->setEnvironment(ExceptionHandler::ENV_DEVELOPMENT); ini_set('display_errors', true); @@ -184,7 +181,7 @@ foreach ($includeFiles as $file) { * Init application */ $session = new Session(); -$container->instance('session', $session); +$app->instance('session', $session); $session->start(); $request->setSession($session); diff --git a/src/Application.php b/src/Application.php new file mode 100644 index 00000000..674b3869 --- /dev/null +++ b/src/Application.php @@ -0,0 +1,25 @@ +registerBaseBindings(); + } + + protected function registerBaseBindings() + { + self::setInstance($this); + Container::setInstance($this); + $this->instance('app', $this); + $this->instance('container', $this); + $this->instance(Container::class, $this); + $this->instance(Application::class, $this); + $this->instance(ContainerInterface::class, $this); + } +} diff --git a/src/Container/Container.php b/src/Container/Container.php index df2f92fe..9af5c1e6 100644 --- a/src/Container/Container.php +++ b/src/Container/Container.php @@ -48,6 +48,17 @@ class Container implements ContainerInterface * @param mixed $instance Entry */ public function instance($abstract, $instance) + { + $this->singleton($abstract, $instance); + } + + /** + * Register a shared entry as singleton in the container + * + * @param string $abstract + * @param mixed $instance + */ + public function singleton($abstract, $instance) { $this->instances[$abstract] = $instance; } @@ -68,10 +79,21 @@ class Container implements ContainerInterface return isset($this->instances[$id]); } + /** + * Resolve the requested object + * + * @param string $abstract + * @return mixed + */ + protected function resolve($abstract) + { + return $this->instances[$abstract]; + } + /** * Get the globally available instance of the container * - * @return Container + * @return self */ public static function getInstance() { @@ -91,15 +113,4 @@ class Container implements ContainerInterface { static::$instance = $container; } - - /** - * Resolve the requested object - * - * @param string $abstract - * @return mixed - */ - protected function resolve($abstract) - { - return $this->instances[$abstract]; - } } diff --git a/src/helpers.php b/src/helpers.php index 733b902d..b942068f 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -1,15 +1,15 @@ get($id); + return Application::getInstance()->get($id); } /** -- cgit v1.2.3-54-g00ecf From b3b65743cdc534f7632c8e04e80d3489eec9677c Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 19 Sep 2017 18:30:42 +0200 Subject: Added Logger --- composer.json | 3 +- includes/engelsystem_provider.php | 14 ++++ src/Logger/EngelsystemLogger.php | 74 ++++++++++++++++++++ test/Logger/EngelsystemLoggerTest.php | 126 ++++++++++++++++++++++++++++++++++ 4 files changed, 216 insertions(+), 1 deletion(-) create mode 100644 src/Logger/EngelsystemLogger.php create mode 100644 test/Logger/EngelsystemLoggerTest.php (limited to 'src') diff --git a/composer.json b/composer.json index 0769a6b6..35956e20 100644 --- a/composer.json +++ b/composer.json @@ -18,7 +18,8 @@ "erusev/parsedown": "1.6.*", "twbs/bootstrap": "^3.3", "symfony/http-foundation": "^3.3", - "psr/container": "^1.0" + "psr/container": "^1.0", + "psr/log": "^1.0" }, "require-dev": { "phpunit/phpunit": "^6.3" diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index c7734a7c..a9305df5 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -5,9 +5,12 @@ use Engelsystem\Config\Config; use Engelsystem\Database\Db; use Engelsystem\Exceptions\Handler as ExceptionHandler; use Engelsystem\Http\Request; +use Engelsystem\Logger\EngelsystemLogger; use Engelsystem\Renderer\HtmlEngine; use Engelsystem\Renderer\Renderer; +use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Session\Session; +use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; /** * This file includes all needed functions, connects to the db etc. @@ -89,6 +92,14 @@ Db::connect( Db::getPdo()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); Db::getPdo()->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); +/** + * Init logger + */ +$logger = new EngelsystemLogger(); +$app->instance('logger', $logger); +$app->instance(LoggerInterface::class, $logger); +$app->instance(EngelsystemLogger::class, $logger); + /** * Include legacy code @@ -180,6 +191,9 @@ foreach ($includeFiles as $file) { * Init application */ $session = new Session(); +if (PHP_SAPI == 'cli') { + $session = new Session(new MockArraySessionStorage()); +} $app->instance('session', $session); $session->start(); $request->setSession($session); diff --git a/src/Logger/EngelsystemLogger.php b/src/Logger/EngelsystemLogger.php new file mode 100644 index 00000000..db46215c --- /dev/null +++ b/src/Logger/EngelsystemLogger.php @@ -0,0 +1,74 @@ +checkLevel($level)) { + throw new InvalidArgumentException(); + } + + $message = $this->interpolate($message, $context); + + LogEntry_create('Logger: ' . $level, $message); + } + + /** + * Interpolates context values into the message placeholders. + * + * @param string $message + * @param array $context + * @return string + */ + protected function interpolate($message, array $context = []) + { + foreach ($context as $key => $val) { + // check that the value can be casted to string + if (is_array($val) || (is_object($val) && !method_exists($val, '__toString'))) { + continue; + } + + // replace the values of the message + $message = str_replace('{' . $key . '}', $val, $message); + } + + return $message; + } + + /** + * @param string $level + * @return bool + */ + protected function checkLevel($level) + { + return in_array($level, $this->allowedLevels); + } +} diff --git a/test/Logger/EngelsystemLoggerTest.php b/test/Logger/EngelsystemLoggerTest.php new file mode 100644 index 00000000..da10800d --- /dev/null +++ b/test/Logger/EngelsystemLoggerTest.php @@ -0,0 +1,126 @@ +assertInstanceOf('Psr\Log\LoggerInterface', $this->getLogger()); + } + + /** + * @dataProvider provideLogLevels + * @param string $level + */ + public function testAllLevels($level) + { + $logger = $this->getLogger(); + + LogEntries_clear_all(); + + $logger->log($level, 'First log message'); + $logger->{$level}('Second log message'); + + $entries = LogEntries(); + $this->assertCount(2, $entries); + } + + /** + * @return string[] + */ + public function provideLogLevels() + { + return [ + [LogLevel::ALERT], + [LogLevel::CRITICAL], + [LogLevel::DEBUG], + [LogLevel::EMERGENCY], + [LogLevel::ERROR], + [LogLevel::INFO], + [LogLevel::NOTICE], + [LogLevel::WARNING], + ]; + } + + public function testContextReplacement() + { + $logger = $this->getLogger(); + LogEntries_clear_all(); + + $logger->log(LogLevel::INFO, 'My username is {username}', ['username' => 'Foo']); + + $entry = $this->getLastEntry(); + $this->assertEquals('My username is Foo', $entry['message']); + $this->assertContains(LogLevel::INFO, $entry['nick'], '', true); + + foreach ( + [ + ['Data and {context}', []], + ['Data and ', ['context' => null]], + ['Data and {context}', ['context' => new \stdClass()]], + ] as $data + ) { + list($result, $context) = $data; + + $logger->log(LogLevel::INFO, 'Data and {context}', $context); + + $entry = $this->getLastEntry(); + $this->assertEquals($result, $entry['message']); + } + } + + public function testContextToString() + { + $logger = $this->getLogger(); + LogEntries_clear_all(); + + $mock = $this->getMockBuilder('someDataProvider') + ->setMethods(['__toString']) + ->getMock(); + + $mock->expects($this->atLeastOnce()) + ->method('__toString') + ->will($this->returnValue('FooBar')); + + $logger->log(LogLevel::INFO, 'Some data and {context}', ['context' => $mock]); + + $entry = $this->getLastEntry(); + $this->assertEquals('Some data and FooBar', $entry['message']); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testThrowExceptionOnInvalidLevel() + { + $logger = $this->getLogger(); + + $logger->log('This log level should never be defined', 'Some message'); + } + + /** + * @return array + */ + public function getLastEntry() + { + $entries = LogEntries(); + $entry = array_pop($entries); + + return $entry; + } +} -- cgit v1.2.3-54-g00ecf From e6ed8a30171b86b452cec21a283373fc14dd5330 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 19 Sep 2017 19:33:24 +0200 Subject: Changed LogEntries table: Use log level instead of nick name --- db/update.sql | 3 +++ includes/model/LogEntries_model.php | 12 ++++++------ includes/pages/admin_log.php | 8 +++----- includes/sys_log.php | 6 ++++-- phpunit.xml | 3 +++ src/Logger/EngelsystemLogger.php | 2 +- test/Logger/EngelsystemLoggerTest.php | 7 ++++++- test/model/LogEntriesModelTest.php | 29 ++++++++++++----------------- test/model/RoomModelTest.php | 17 +++++++---------- 9 files changed, 45 insertions(+), 42 deletions(-) (limited to 'src') diff --git a/db/update.sql b/db/update.sql index 5d93e230..3ed37ceb 100644 --- a/db/update.sql +++ b/db/update.sql @@ -28,3 +28,6 @@ UPDATE `Groups` SET UID = UID * 10; INSERT INTO `Groups` (Name, UID) VALUES ('News Admin', -65); INSERT INTO `Privileges` (id, name, `desc`) VALUES (42, 'admin_news_html', 'Use HTML in news'); INSERT INTO `GroupPrivileges` (group_id, privilege_id) VALUES (-65, 14), (-65, 42); + +-- Add log level to LogEntries +ALTER TABLE `LogEntries` CHANGE COLUMN `nick` `level` VARCHAR(20) NOT NULL; diff --git a/includes/model/LogEntries_model.php b/includes/model/LogEntries_model.php index 0e11bf8e..f0ee6673 100644 --- a/includes/model/LogEntries_model.php +++ b/includes/model/LogEntries_model.php @@ -5,16 +5,16 @@ use Engelsystem\Database\DB; /** * Creates a log entry. * - * @param string $nick Username - * @param string $message Log Message + * @param string $logLevel Log level + * @param string $message Log Message * @return bool */ -function LogEntry_create($nick, $message) +function LogEntry_create($logLevel, $message) { return DB::insert(' - INSERT INTO `LogEntries` (`timestamp`, `nick`, `message`) + INSERT INTO `LogEntries` (`timestamp`, `level`, `message`) VALUES(?, ?, ?) - ', [time(), $nick, $message]); + ', [time(), $logLevel, $message]); } /** @@ -43,7 +43,7 @@ function LogEntries_filter($keyword) return DB::select(' SELECT * FROM `LogEntries` - WHERE `nick` LIKE ? + WHERE `level` LIKE ? OR `message` LIKE ? ORDER BY `timestamp` DESC ', diff --git a/includes/pages/admin_log.php b/includes/pages/admin_log.php index 03c9abb0..694b1d5a 100644 --- a/includes/pages/admin_log.php +++ b/includes/pages/admin_log.php @@ -17,12 +17,10 @@ function admin_log() if (request()->has('keyword')) { $filter = strip_request_item('keyword'); } - $log_entries_source = LogEntries_filter($filter); + $log_entries = LogEntries_filter($filter); - $log_entries = []; - foreach ($log_entries_source as $log_entry) { + foreach ($log_entries as &$log_entry) { $log_entry['date'] = date('d.m.Y H:i', $log_entry['timestamp']); - $log_entries[] = $log_entry; } return page_with_title(admin_log_title(), [ @@ -33,7 +31,7 @@ function admin_log() ]), table([ 'date' => 'Time', - 'nick' => 'Angel', + 'level' => 'Type', 'message' => 'Log Entry' ], $log_entries) ]); diff --git a/includes/sys_log.php b/includes/sys_log.php index c4ef890e..513586e6 100644 --- a/includes/sys_log.php +++ b/includes/sys_log.php @@ -9,10 +9,12 @@ function engelsystem_log($message) { global $user; - $nick = "Guest"; + $logger = app('logger'); + if (isset($user)) { $nick = User_Nick_render($user); } - LogEntry_create($nick, $message); + + $logger->info('{nick}: {message}', ['nick' => $nick, 'message' => $message]); } diff --git a/phpunit.xml b/phpunit.xml index ff6eb120..ee5ae3e8 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -7,6 +7,9 @@ ./test/model/ + + ./test/Logger/ + diff --git a/src/Logger/EngelsystemLogger.php b/src/Logger/EngelsystemLogger.php index db46215c..1f255b69 100644 --- a/src/Logger/EngelsystemLogger.php +++ b/src/Logger/EngelsystemLogger.php @@ -38,7 +38,7 @@ class EngelsystemLogger extends AbstractLogger $message = $this->interpolate($message, $context); - LogEntry_create('Logger: ' . $level, $message); + LogEntry_create($level, $message); } /** diff --git a/test/Logger/EngelsystemLoggerTest.php b/test/Logger/EngelsystemLoggerTest.php index da10800d..2219cdb2 100644 --- a/test/Logger/EngelsystemLoggerTest.php +++ b/test/Logger/EngelsystemLoggerTest.php @@ -66,7 +66,7 @@ class EngelsystemLoggerTest extends TestCase $entry = $this->getLastEntry(); $this->assertEquals('My username is Foo', $entry['message']); - $this->assertContains(LogLevel::INFO, $entry['nick'], '', true); + $this->assertEquals(LogLevel::INFO, $entry['level']); foreach ( [ @@ -123,4 +123,9 @@ class EngelsystemLoggerTest extends TestCase return $entry; } + + public function tearDown() + { + LogEntries_clear_all(); + } } diff --git a/test/model/LogEntriesModelTest.php b/test/model/LogEntriesModelTest.php index 25d46fc4..761725c4 100644 --- a/test/model/LogEntriesModelTest.php +++ b/test/model/LogEntriesModelTest.php @@ -1,37 +1,32 @@ assertNotFalse(LogEntry_create('test', 'test_LogEntry_create')); - + $this->assertNotFalse(LogEntry_create(LogLevel::WARNING, 'test_LogEntry_create')); + // There should be one more log entry now $this->assertEquals(count(LogEntries()), $count + 1); } - public function test_LogEntries_clear_all() + public function testClearAllLogEntries() { - $this->create_LogEntry(); + LogEntry_create(LogLevel::WARNING, 'test'); $this->assertTrue(count(LogEntries()) > 0); + $this->assertNotFalse(LogEntries_clear_all()); - $this->assertEquals(count(LogEntries()), 0); + $this->assertCount(0, LogEntries()); } - /** - * @after - */ - public function teardown() + public function tearDown() { LogEntries_clear_all(); } diff --git a/test/model/RoomModelTest.php b/test/model/RoomModelTest.php index 135a6108..4205845b 100644 --- a/test/model/RoomModelTest.php +++ b/test/model/RoomModelTest.php @@ -1,11 +1,11 @@ create_Room(); - + $room = Room($this->room_id); - + $this->assertNotFalse($room); $this->assertNotNull($room); $this->assertEquals($room['Name'], 'test'); - - $this->assertNull(Room(- 1)); + + $this->assertNull(Room(-1)); } - /** - * @after - */ - public function teardown() + public function tearDown() { if ($this->room_id != null) { Room_delete($this->room_id); -- cgit v1.2.3-54-g00ecf From 2cb636b651c889243919d99eda8fa724d5c08392 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 19 Sep 2017 21:50:22 +0200 Subject: Added Container unit test --- src/Container/Container.php | 2 +- tests/Unit/Container/ContainerTest.php | 98 ++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 tests/Unit/Container/ContainerTest.php (limited to 'src') diff --git a/src/Container/Container.php b/src/Container/Container.php index 9af5c1e6..59a17a04 100644 --- a/src/Container/Container.php +++ b/src/Container/Container.php @@ -38,7 +38,7 @@ class Container implements ContainerInterface return $this->resolve($id); } - throw new NotFoundException(sprintf('The entry with the id "%s" could not be found')); + throw new NotFoundException(sprintf('The entry with the id "%s" could not be found', $id)); } /** diff --git a/tests/Unit/Container/ContainerTest.php b/tests/Unit/Container/ContainerTest.php new file mode 100644 index 00000000..f0ba24e7 --- /dev/null +++ b/tests/Unit/Container/ContainerTest.php @@ -0,0 +1,98 @@ +instance('foo', $class); + $this->assertSame($class, $container->get('foo')); + } + + /** + * @covers \Engelsystem\Container\Container::get + * @expectedException \Engelsystem\Container\NotFoundException + */ + public function testGetException() + { + $container = new Container(); + + $container->get('not.registered.service'); + } + + /** + * @covers \Engelsystem\Container\Container::instance + * @covers \Engelsystem\Container\Container::resolve + */ + public function testInstance() + { + $container = new Container(); + $class = new class + { + }; + + $container->instance('foo', $class); + $this->assertSame($class, $container->get('foo')); + } + + /** + * @covers \Engelsystem\Container\Container::has + */ + public function testHas() + { + $container = new Container(); + + $this->assertFalse($container->has('test')); + + $class = new class + { + }; + + $container->instance('test', $class); + $this->assertTrue($container->has('test')); + } + + /** + * @covers \Engelsystem\Container\Container::singleton + */ + public function testSingleton() + { + $container = new Container(); + $class = new class + { + }; + + $container->singleton('foo', $class); + $this->assertSame($class, $container->get('foo')); + $this->assertSame($class, $container->get('foo')); + } + + /** + * @covers \Engelsystem\Container\Container::setInstance + * @covers \Engelsystem\Container\Container::getInstance + */ + public function testContainerSingleton() + { + $container0 = new Container(); + $container = Container::getInstance(); + + $this->assertNotSame($container0, $container); + + $container1 = new Container; + Container::setInstance($container1); + + $this->assertSame($container1, Container::getInstance()); + } +} -- cgit v1.2.3-54-g00ecf From 1e267ce3b133299f82661a37d82c0f50e8575e1e Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 19 Sep 2017 23:55:24 +0200 Subject: Added Renderer unit test --- src/Renderer/HtmlEngine.php | 2 +- src/Renderer/Renderer.php | 9 ++++- tests/Unit/Renderer/HtmlEngineTest.php | 67 ++++++++++++++++++++++++++++++++++ tests/Unit/Renderer/RendererTest.php | 55 ++++++++++++++++++++++++++++ 4 files changed, 131 insertions(+), 2 deletions(-) create mode 100644 tests/Unit/Renderer/HtmlEngineTest.php create mode 100644 tests/Unit/Renderer/RendererTest.php (limited to 'src') diff --git a/src/Renderer/HtmlEngine.php b/src/Renderer/HtmlEngine.php index 4a48e1f0..75343bbd 100644 --- a/src/Renderer/HtmlEngine.php +++ b/src/Renderer/HtmlEngine.php @@ -29,6 +29,6 @@ class HtmlEngine implements EngineInterface */ public function canRender($path) { - return strpos($path, '.html') && file_exists($path); + return strpos($path, '.htm') && file_exists($path); } } diff --git a/src/Renderer/Renderer.php b/src/Renderer/Renderer.php index 5ed7cf31..de31ca74 100644 --- a/src/Renderer/Renderer.php +++ b/src/Renderer/Renderer.php @@ -2,8 +2,12 @@ namespace Engelsystem\Renderer; +use Psr\Log\LoggerAwareTrait; + class Renderer { + use LoggerAwareTrait; + /** @var EngineInterface[] */ protected $renderer = []; @@ -24,7 +28,10 @@ class Renderer return $renderer->get($template, $data); } - engelsystem_error('Unable to find a renderer for template file "' . $template . '".'); + if ($this->logger) { + $this->logger->error('Unable to find a renderer for template file "{file}"', ['file' => $template]); + } + return ''; } diff --git a/tests/Unit/Renderer/HtmlEngineTest.php b/tests/Unit/Renderer/HtmlEngineTest.php new file mode 100644 index 00000000..0b317b72 --- /dev/null +++ b/tests/Unit/Renderer/HtmlEngineTest.php @@ -0,0 +1,67 @@ +createTempFile('
          %main_content%
          '); + + $data = $engine->get($file, ['main_content' => 'Lorem ipsum dolor sit']); + $this->assertEquals('
          Lorem ipsum dolor sit
          ', $data); + } + + /** + * @covers \Engelsystem\Renderer\HtmlEngine::canRender + */ + public function testCanRender() + { + $engine = new HtmlEngine(); + + $this->assertFalse($engine->canRender('/dev/null')); + + $file = $this->createTempFile(); + $this->assertTrue($engine->canRender($file)); + + $htmFile = $this->createTempFile('', '.htm'); + $this->assertTrue($engine->canRender($htmFile)); + } + + /** + * @param string $content + * @param string $extension + * @return string + */ + protected function createTempFile($content = '', $extension = '.html') + { + $tmpFileName = tempnam(sys_get_temp_dir(), 'EngelsystemUnitTest'); + + $fileName = $tmpFileName . $extension; + rename($tmpFileName, $fileName); + + file_put_contents($fileName, $content); + + $this->tmpFileNames[] = $fileName; + + return $fileName; + } + + public function tearDown() + { + foreach ($this->tmpFileNames as $fileName) { + unlink($fileName); + } + } +} diff --git a/tests/Unit/Renderer/RendererTest.php b/tests/Unit/Renderer/RendererTest.php new file mode 100644 index 00000000..b0238078 --- /dev/null +++ b/tests/Unit/Renderer/RendererTest.php @@ -0,0 +1,55 @@ +getMockForAbstractClass(EngineInterface::class); + + $nullRenderer->expects($this->atLeastOnce()) + ->method('canRender') + ->willReturn(false); + $renderer->addRenderer($nullRenderer); + + $mockRenderer = $this->getMockForAbstractClass(EngineInterface::class); + + $mockRenderer->expects($this->atLeastOnce()) + ->method('canRender') + ->with('foo.template') + ->willReturn(true); + + $mockRenderer->expects($this->atLeastOnce()) + ->method('get') + ->with('foo.template', ['lorem' => 'ipsum']) + ->willReturn('Rendered content'); + + $renderer->addRenderer($mockRenderer); + $data = $renderer->render('foo.template', ['lorem' => 'ipsum']); + + $this->assertEquals('Rendered content', $data); + } + + public function testError() + { + $renderer = new Renderer(); + + $loggerMock = $this->getMockForAbstractClass(LoggerInterface::class); + $loggerMock + ->expects($this->once()) + ->method('error'); + + $renderer->setLogger($loggerMock); + + $data = $renderer->render('testing.template'); + $this->assertEquals('', $data); + } +} -- cgit v1.2.3-54-g00ecf From 86c0713baa2f616bf1dff6d9dbe0ea68b1c00e91 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Wed, 20 Sep 2017 01:09:11 +0200 Subject: Added helpers unit test --- includes/engelsystem_provider.php | 8 ++ src/Routing/UrlGenerator.php | 2 +- src/helpers.php | 14 ++- tests/Unit/HelpersTest.php | 152 ++++++++++++++++++++++++++++++++ tests/Unit/Routing/UrlGeneratorTest.php | 3 +- 5 files changed, 173 insertions(+), 6 deletions(-) create mode 100644 tests/Unit/HelpersTest.php (limited to 'src') diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index a9305df5..cd22f6a7 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -8,6 +8,7 @@ use Engelsystem\Http\Request; use Engelsystem\Logger\EngelsystemLogger; use Engelsystem\Renderer\HtmlEngine; use Engelsystem\Renderer\Renderer; +use Engelsystem\Routing\UrlGenerator; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; @@ -59,6 +60,13 @@ if ($config->get('maintenance')) { } +/** + * Register UrlGenerator + */ +$urlGenerator = new UrlGenerator(); +$app->instance('routing.urlGenerator', $urlGenerator); + + /** * Initialize renderer */ diff --git a/src/Routing/UrlGenerator.php b/src/Routing/UrlGenerator.php index 33eef7b0..6df52425 100644 --- a/src/Routing/UrlGenerator.php +++ b/src/Routing/UrlGenerator.php @@ -9,7 +9,7 @@ class UrlGenerator * @param array $parameters * @return string */ - public static function to($path, $parameters = []) + public function to($path, $parameters = []) { $path = '/' . ltrim($path, '/'); $request = app('request'); diff --git a/src/helpers.php b/src/helpers.php index b942068f..de303963 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -69,7 +69,7 @@ function request($key = null, $default = null) */ function session($key = null, $default = null) { - $session = request()->getSession(); + $session = app('session'); if (is_null($key)) { return $session; @@ -97,9 +97,15 @@ function view($template = null, $data = null) /** * @param string $path * @param array $parameters - * @return string + * @return UrlGenerator|string */ -function url($path, $parameters = []) +function url($path = null, $parameters = []) { - return UrlGenerator::to($path, $parameters); + $urlGenerator = app('routing.urlGenerator'); + + if (is_null($path)) { + return $urlGenerator; + } + + return $urlGenerator->to($path, $parameters); } diff --git a/tests/Unit/HelpersTest.php b/tests/Unit/HelpersTest.php new file mode 100644 index 00000000..d9782888 --- /dev/null +++ b/tests/Unit/HelpersTest.php @@ -0,0 +1,152 @@ +getAppMock('some.name', $class); + + $this->assertEquals($appMock, app()); + $this->assertEquals($class, app('some.name')); + } + + /** + * @covers \config + */ + public function testConfig() + { + $configMock = $this->getMockBuilder(Config::class) + ->getMock(); + + $this->getAppMock('config', $configMock); + $this->assertEquals($configMock, config()); + + $configMock->expects($this->once()) + ->method('set') + ->with(['foo' => 'bar']); + + $this->assertTrue(config(['foo' => 'bar'])); + + $configMock->expects($this->once()) + ->method('get') + ->with('mail') + ->willReturn(['user' => 'FooBar']); + + $this->assertEquals(['user' => 'FooBar'], config('mail')); + } + + /** + * @covers \request + */ + public function testRequest() + { + $requestMock = $this->getMockBuilder(Request::class) + ->getMock(); + + $this->getAppMock('request', $requestMock); + $this->assertEquals($requestMock, request()); + + $requestMock->expects($this->once()) + ->method('input') + ->with('requestKey') + ->willReturn('requestValue'); + + $this->assertEquals('requestValue', request('requestKey')); + } + + /** + * @covers \session + */ + public function testSession() + { + $sessionMock = $this->getMockBuilder(Session::class) + ->getMock(); + + $this->getAppMock('session', $sessionMock); + $this->assertEquals($sessionMock, session()); + + $sessionMock->expects($this->once()) + ->method('get') + ->with('someKey') + ->willReturn('someValue'); + + $this->assertEquals('someValue', session('someKey')); + } + + /** + * @covers \view + */ + public function testView() + { + $rendererMock = $this->getMockBuilder(Renderer::class) + ->getMock(); + + $this->getAppMock('renderer', $rendererMock); + $this->assertEquals($rendererMock, view()); + + $rendererMock->expects($this->once()) + ->method('render') + ->with('template.name', ['template' => 'data']) + ->willReturn('rendered template'); + + $this->assertEquals('rendered template', view('template.name', ['template' => 'data'])); + } + + /** + * @covers \url + */ + public function testUrl() + { + $urlGeneratorMock = $this->getMockBuilder(UrlGenerator::class) + ->getMock(); + + $this->getAppMock('routing.urlGenerator', $urlGeneratorMock); + $this->assertEquals($urlGeneratorMock, url()); + + $urlGeneratorMock->expects($this->once()) + ->method('to') + ->with('foo/bar', ['param' => 'value']) + ->willReturn('http://lorem.ipsum/foo/bar?param=value'); + + $this->assertEquals('http://lorem.ipsum/foo/bar?param=value', url('foo/bar', ['param' => 'value'])); + } + + /** + * @param string $alias + * @param object $object + * @return Application|\PHPUnit_Framework_MockObject_MockObject + */ + protected function getAppMock($alias, $object) + { + $appMock = $this->getMockBuilder(Container::class) + ->getMock(); + + $appMock->expects($this->atLeastOnce()) + ->method('get') + ->with($alias) + ->willReturn($object); + + /** @var $appMock Application */ + Application::setInstance($appMock); + + return $appMock; + } +} diff --git a/tests/Unit/Routing/UrlGeneratorTest.php b/tests/Unit/Routing/UrlGeneratorTest.php index 5b53a04e..fc23520a 100644 --- a/tests/Unit/Routing/UrlGeneratorTest.php +++ b/tests/Unit/Routing/UrlGeneratorTest.php @@ -32,6 +32,7 @@ class UrlGeneratorTest extends TestCase public function testTo($urlToPath, $path, $willReturn, $arguments, $expectedUrl) { $app = new Container(); + $urlGenerator = new UrlGenerator(); Application::setInstance($app); $request = $this->getMockBuilder(Request::class) @@ -44,7 +45,7 @@ class UrlGeneratorTest extends TestCase $app->instance('request', $request); - $url = UrlGenerator::to($urlToPath, $arguments); + $url = $urlGenerator->to($urlToPath, $arguments); $this->assertEquals($expectedUrl, $url); } } -- cgit v1.2.3-54-g00ecf From 31414905d710ed53796d67759dec24baf2eeefc7 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Wed, 20 Sep 2017 01:29:04 +0200 Subject: Fixed exceptionHandler to catch PdoExceptions, formatting --- .gitignore | 1 + public/.htaccess | 1 + src/Exceptions/Handler.php | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/.gitignore b/.gitignore index eb3f8939..eb12eae7 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ _vimrc_local.vim # Project files /config/config.php /test/coverage +/public/coverage # Composer files /vendor/ diff --git a/public/.htaccess b/public/.htaccess index c9d40187..2b1d3a7a 100644 --- a/public/.htaccess +++ b/public/.htaccess @@ -1,3 +1,4 @@ + RewriteEngine on diff --git a/src/Exceptions/Handler.php b/src/Exceptions/Handler.php index c4fb639c..95bcd132 100644 --- a/src/Exceptions/Handler.php +++ b/src/Exceptions/Handler.php @@ -42,7 +42,7 @@ class Handler /** * @param Throwable $e */ - public function exceptionHandler(Throwable $e) + public function exceptionHandler($e) { $this->handle( 'exception', -- cgit v1.2.3-54-g00ecf From 212760d4c93ce14e9ae34ef207bbb8f48a7dd9a7 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Thu, 21 Sep 2017 18:37:37 +0200 Subject: Changed Container to Illuminate/Container @see https://laravel.com/docs/5.5/container @see https://davejamesmiller.com/2017/06/15/laravel-illuminate-container-in-depth --- composer.json | 9 +-- includes/engelsystem_provider.php | 4 +- src/Application.php | 4 +- src/Container/Container.php | 110 +-------------------------------- src/Container/ContainerException.php | 11 ---- src/Container/NotFoundException.php | 10 --- tests/Unit/ApplicationTest.php | 1 + tests/Unit/Container/ContainerTest.php | 104 ------------------------------- 8 files changed, 12 insertions(+), 241 deletions(-) delete mode 100644 src/Container/ContainerException.php delete mode 100644 src/Container/NotFoundException.php delete mode 100644 tests/Unit/Container/ContainerTest.php (limited to 'src') diff --git a/composer.json b/composer.json index 35956e20..6467fc1c 100644 --- a/composer.json +++ b/composer.json @@ -15,11 +15,12 @@ ], "require": { "php": ">=7.0.0", - "erusev/parsedown": "1.6.*", - "twbs/bootstrap": "^3.3", - "symfony/http-foundation": "^3.3", + "erusev/parsedown": "^1.6", + "illuminate/container": "^5.*", "psr/container": "^1.0", - "psr/log": "^1.0" + "psr/log": "^1.0", + "symfony/http-foundation": "^3.3", + "twbs/bootstrap": "^3.3" }, "require-dev": { "phpunit/phpunit": "^6.3" diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index 0de5e0f5..33422bfc 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -106,8 +106,8 @@ Db::getPdo()->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); */ $logger = new EngelsystemLogger(); $app->instance('logger', $logger); -$app->instance(LoggerInterface::class, $logger); -$app->instance(EngelsystemLogger::class, $logger); +$app->bind(LoggerInterface::class, 'logger'); +$app->bind(EngelsystemLogger::class, 'logger'); /** diff --git a/src/Application.php b/src/Application.php index 674b3869..fa895d77 100644 --- a/src/Application.php +++ b/src/Application.php @@ -14,12 +14,12 @@ class Application extends Container protected function registerBaseBindings() { - self::setInstance($this); + static::setInstance($this); Container::setInstance($this); $this->instance('app', $this); $this->instance('container', $this); $this->instance(Container::class, $this); $this->instance(Application::class, $this); - $this->instance(ContainerInterface::class, $this); + $this->bind(ContainerInterface::class, Application::class); } } diff --git a/src/Container/Container.php b/src/Container/Container.php index 59a17a04..44c57b6f 100644 --- a/src/Container/Container.php +++ b/src/Container/Container.php @@ -2,115 +2,9 @@ namespace Engelsystem\Container; -use Psr\Container\ContainerExceptionInterface; +use Illuminate\Container\Container as IlluminateContainer; use Psr\Container\ContainerInterface; -use Psr\Container\NotFoundExceptionInterface; -class Container implements ContainerInterface +class Container extends IlluminateContainer implements ContainerInterface { - /** - * The globally available container - * - * @var static - */ - protected static $instance; - - /** - * Contains the shared instances - * - * @var mixed[] - */ - protected $instances = []; - - /** - * Finds an entry of the container by its identifier and returns it - * - * @param string $id Identifier of the entry to look for - * - * @throws NotFoundExceptionInterface No entry was found for **this** identifier - * @throws ContainerExceptionInterface Error while retrieving the entry - * - * @return mixed Entry - */ - public function get($id) - { - if ($this->has($id)) { - return $this->resolve($id); - } - - throw new NotFoundException(sprintf('The entry with the id "%s" could not be found', $id)); - } - - /** - * Register a shared entry in the container - * - * @param string $abstract Identifier of the entry to set - * @param mixed $instance Entry - */ - public function instance($abstract, $instance) - { - $this->singleton($abstract, $instance); - } - - /** - * Register a shared entry as singleton in the container - * - * @param string $abstract - * @param mixed $instance - */ - public function singleton($abstract, $instance) - { - $this->instances[$abstract] = $instance; - } - - /** - * Returns true if the container can return an entry for the given identifier - * Returns false otherwise - * - * `has($id)` returning true does not mean that `get($id)` will not throw an exception - * It does however mean that `get($id)` will not throw a `NotFoundExceptionInterface` - * - * @param string $id Identifier of the entry to look for - * - * @return bool - */ - public function has($id) - { - return isset($this->instances[$id]); - } - - /** - * Resolve the requested object - * - * @param string $abstract - * @return mixed - */ - protected function resolve($abstract) - { - return $this->instances[$abstract]; - } - - /** - * Get the globally available instance of the container - * - * @return self - */ - public static function getInstance() - { - if (is_null(static::$instance)) { - static::$instance = new static; - } - - return static::$instance; - } - - /** - * Set the globally available instance of the container - * - * @param Container $container - */ - public static function setInstance(Container $container) - { - static::$instance = $container; - } } diff --git a/src/Container/ContainerException.php b/src/Container/ContainerException.php deleted file mode 100644 index 3cdde506..00000000 --- a/src/Container/ContainerException.php +++ /dev/null @@ -1,11 +0,0 @@ -assertSame($app, $app->get(Container::class)); $this->assertSame($app, $app->get(Application::class)); $this->assertSame($app, $app->get(ContainerInterface::class)); + $this->assertSame($app, Application::getInstance()); $this->assertSame($app, Container::getInstance()); } } diff --git a/tests/Unit/Container/ContainerTest.php b/tests/Unit/Container/ContainerTest.php deleted file mode 100644 index 89c34209..00000000 --- a/tests/Unit/Container/ContainerTest.php +++ /dev/null @@ -1,104 +0,0 @@ -instance('foo', $class); - $this->assertSame($class, $container->get('foo')); - } - - /** - * @covers \Engelsystem\Container\Container::get - * @expectedException \Engelsystem\Container\NotFoundException - */ - public function testGetException() - { - $container = new Container(); - - $container->get('not.registered.service'); - } - - /** - * @covers \Engelsystem\Container\Container::instance - * @covers \Engelsystem\Container\Container::resolve - */ - public function testInstance() - { - $container = new Container(); - $class = new class - { - }; - - $container->instance('foo', $class); - $this->assertSame($class, $container->get('foo')); - } - - /** - * @covers \Engelsystem\Container\Container::has - */ - public function testHas() - { - $container = new Container(); - - $this->assertFalse($container->has('test')); - - $class = new class - { - }; - - $container->instance('test', $class); - $this->assertTrue($container->has('test')); - } - - /** - * @covers \Engelsystem\Container\Container::singleton - */ - public function testSingleton() - { - $container = new Container(); - $class = new class - { - }; - - $container->singleton('foo', $class); - $this->assertSame($class, $container->get('foo')); - $this->assertSame($class, $container->get('foo')); - } - - /** - * @covers \Engelsystem\Container\Container::setInstance - * @covers \Engelsystem\Container\Container::getInstance - */ - public function testContainerSingleton() - { - // Ensure that no container has been initialized - $reflection = new \ReflectionProperty(Container::class, 'instance'); - $reflection->setAccessible(true); - $reflection->setValue(null, null); - $reflection->setAccessible(false); - - $container0 = new Container(); - $container = Container::getInstance(); - - $this->assertNotSame($container0, $container); - - $container1 = new Container; - Container::setInstance($container1); - - $this->assertSame($container1, Container::getInstance()); - } -} -- cgit v1.2.3-54-g00ecf From 783c58611ada88460ba670d51ebf4013563e1197 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Thu, 21 Sep 2017 20:52:19 +0200 Subject: Added app path to container --- includes/engelsystem_provider.php | 2 +- src/Application.php | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index 33422bfc..e1669c57 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -23,7 +23,7 @@ require_once __DIR__ . '/autoload.php'; /** * Initialize the application */ -$app = Application::getInstance(); +$app = new Application(realpath(__DIR__ . DIRECTORY_SEPARATOR . '..')); /** diff --git a/src/Application.php b/src/Application.php index fa895d77..80538396 100644 --- a/src/Application.php +++ b/src/Application.php @@ -7,8 +7,20 @@ use Psr\Container\ContainerInterface; class Application extends Container { - public function __construct() + /** @var string|null */ + protected $appPath = null; + + /** + * Application constructor. + * + * @param string $appPath + */ + public function __construct($appPath = null) { + if (!is_null($appPath)) { + $this->setAppPath($appPath); + } + $this->registerBaseBindings(); } @@ -22,4 +34,26 @@ class Application extends Container $this->instance(Application::class, $this); $this->bind(ContainerInterface::class, Application::class); } + + /** + * @param string $appPath + * @return static + */ + public function setAppPath($appPath) + { + $appPath = rtrim($appPath, DIRECTORY_SEPARATOR); + + $this->appPath = $appPath; + $this->instance('path', $appPath); + + return $this; + } + + /** + * @return string|null + */ + public function path() + { + return $this->appPath; + } } -- cgit v1.2.3-54-g00ecf From d49e49c364c1b73e4e4e3b52dc10ee9d0150e447 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Fri, 22 Sep 2017 14:02:02 +0200 Subject: Implemented service provider functionality --- config/app.php | 9 ++ includes/engelsystem_provider.php | 13 ++- includes/helper/internationalization_helper.php | 2 +- src/Application.php | 80 ++++++++++++- src/Container/ServiceProvider.php | 31 +++++ src/helpers.php | 50 +++++--- tests/Unit/ApplicationTest.php | 147 +++++++++++++++++++++++- 7 files changed, 310 insertions(+), 22 deletions(-) create mode 100644 config/app.php create mode 100644 src/Container/ServiceProvider.php (limited to 'src') diff --git a/config/app.php b/config/app.php new file mode 100644 index 00000000..fe0a97c1 --- /dev/null +++ b/config/app.php @@ -0,0 +1,9 @@ + [ + ], +]; diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index e1669c57..3067ab62 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -26,6 +26,13 @@ require_once __DIR__ . '/autoload.php'; $app = new Application(realpath(__DIR__ . DIRECTORY_SEPARATOR . '..')); +/** + * Bootstrap application + */ +$appConfig = $app->make(Config::class); +$appConfig->set(app('path.config') . '/app.php'); +$app->bootstrap($appConfig); + /** * Load configuration */ @@ -40,6 +47,10 @@ if (file_exists(__DIR__ . '/../config/config.php')) { )); } + +/** + * Configure application + */ date_default_timezone_set($config->get('timezone')); @@ -55,7 +66,7 @@ $app->instance('request', $request); /** * Check for maintenance */ -if ($config->get('maintenance')) { +if ($app->get('config')->get('maintenance')) { echo file_get_contents(__DIR__ . '/../templates/maintenance.html'); die(); } diff --git a/includes/helper/internationalization_helper.php b/includes/helper/internationalization_helper.php index efbe5db5..7fa6518b 100644 --- a/includes/helper/internationalization_helper.php +++ b/includes/helper/internationalization_helper.php @@ -36,7 +36,7 @@ function gettext_init() } gettext_locale(); - bindtextdomain('default', realpath(__DIR__ . '/../../locale')); + bindtextdomain('default', app('path.lang')); bind_textdomain_codeset('default', 'UTF-8'); textdomain('default'); } diff --git a/src/Application.php b/src/Application.php index 80538396..b62b28a9 100644 --- a/src/Application.php +++ b/src/Application.php @@ -2,7 +2,9 @@ namespace Engelsystem; +use Engelsystem\Config\Config; use Engelsystem\Container\Container; +use Engelsystem\Container\ServiceProvider; use Psr\Container\ContainerInterface; class Application extends Container @@ -10,6 +12,16 @@ class Application extends Container /** @var string|null */ protected $appPath = null; + /** @var bool */ + protected $isBootstrapped = false; + + /** + * Registered service providers + * + * @var array + */ + protected $serviceProviders = []; + /** * Application constructor. * @@ -36,15 +48,73 @@ class Application extends Container } /** + * @param string|ServiceProvider $provider + * @return ServiceProvider + */ + public function register($provider) + { + if (is_string($provider)) { + $provider = $this->get($provider); + } + + $this->serviceProviders[] = $provider; + + $provider->register(); + + if ($this->isBootstrapped) { + $this->call([$provider, 'boot']); + } + + return $provider; + } + + /** + * Boot service providers + * + * @param Config|null $config + */ + public function bootstrap(Config $config = null) + { + if ($this->isBootstrapped) { + return; + } + + if ($config instanceof Config) { + foreach ($config->get('providers', []) as $provider) { + $this->register($provider); + } + } + + foreach ($this->serviceProviders as $provider) { + $this->call([$provider, 'boot']); + } + + $this->isBootstrapped = true; + } + + protected function registerPaths() + { + $appPath = $this->appPath; + + $this->instance('path', $appPath); + $this->instance('path.config', $appPath . DIRECTORY_SEPARATOR . 'config'); + $this->instance('path.lang', $appPath . DIRECTORY_SEPARATOR . 'locale'); + } + + /** + * Set app base path + * * @param string $appPath * @return static */ public function setAppPath($appPath) { + $appPath = realpath($appPath); $appPath = rtrim($appPath, DIRECTORY_SEPARATOR); $this->appPath = $appPath; - $this->instance('path', $appPath); + + $this->registerPaths(); return $this; } @@ -56,4 +126,12 @@ class Application extends Container { return $this->appPath; } + + /** + * @return bool + */ + public function isBooted() + { + return $this->isBootstrapped; + } } diff --git a/src/Container/ServiceProvider.php b/src/Container/ServiceProvider.php new file mode 100644 index 00000000..2a1bbebf --- /dev/null +++ b/src/Container/ServiceProvider.php @@ -0,0 +1,31 @@ +app = $app; + } + + /** + * Register container bindings + */ + public function register() { } + + /** + * Called after other services had been registered + */ + public function boot() { } +} diff --git a/src/helpers.php b/src/helpers.php index de303963..c3c727ec 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -23,6 +23,15 @@ function app($id = null) return Application::getInstance()->get($id); } +/** + * @param string $path + * @return string + */ +function base_path($path = '') +{ + return app('path') . (empty($path) ? '' : DIRECTORY_SEPARATOR . $path); +} + /** * Get or set config values * @@ -46,6 +55,15 @@ function config($key = null, $default = null) return $config->get($key, $default); } +/** + * @param string $path + * @return string + */ +function config_path($path = '') +{ + return app('path.config') . (empty($path) ? '' : DIRECTORY_SEPARATOR . $path); +} + /** * @param string $key * @param mixed $default @@ -78,22 +96,6 @@ function session($key = null, $default = null) return $session->get($key, $default); } -/** - * @param string $template - * @param mixed[] $data - * @return Renderer|string - */ -function view($template = null, $data = null) -{ - $renderer = app('renderer'); - - if (is_null($template)) { - return $renderer; - } - - return $renderer->render($template, $data); -} - /** * @param string $path * @param array $parameters @@ -109,3 +111,19 @@ function url($path = null, $parameters = []) return $urlGenerator->to($path, $parameters); } + +/** + * @param string $template + * @param mixed[] $data + * @return Renderer|string + */ +function view($template = null, $data = null) +{ + $renderer = app('renderer'); + + if (is_null($template)) { + return $renderer; + } + + return $renderer->render($template, $data); +} diff --git a/tests/Unit/ApplicationTest.php b/tests/Unit/ApplicationTest.php index 53fe3109..78310134 100644 --- a/tests/Unit/ApplicationTest.php +++ b/tests/Unit/ApplicationTest.php @@ -3,19 +3,23 @@ namespace Engelsystem\Test\Config; use Engelsystem\Application; +use Engelsystem\Config\Config; use Engelsystem\Container\Container; +use Engelsystem\Container\ServiceProvider; use PHPUnit\Framework\TestCase; +use PHPUnit_Framework_MockObject_MockObject; use Psr\Container\ContainerInterface; +use ReflectionClass; class ApplicationTest extends TestCase { /** - * @covers \Engelsystem\Application::__construct - * @covers \Engelsystem\Application::registerBaseBindings + * @covers \Engelsystem\Application::__construct + * @covers \Engelsystem\Application::registerBaseBindings */ public function testConstructor() { - $app = new Application(); + $app = new Application('.'); $this->assertInstanceOf(Container::class, $app); $this->assertInstanceOf(ContainerInterface::class, $app); @@ -27,4 +31,141 @@ class ApplicationTest extends TestCase $this->assertSame($app, Application::getInstance()); $this->assertSame($app, Container::getInstance()); } + + /** + * @covers \Engelsystem\Application::setAppPath + * @covers \Engelsystem\Application::registerPaths + * @covers \Engelsystem\Application::path + */ + public function testAppPath() + { + $app = new Application(); + + $this->assertFalse($app->has('path')); + + $app->setAppPath('.'); + $this->assertTrue($app->has('path')); + $this->assertTrue($app->has('path.config')); + $this->assertTrue($app->has('path.lang')); + + $this->assertEquals(realpath('.'), $app->path()); + $this->assertEquals(realpath('.') . '/config', $app->get('path.config')); + + $app->setAppPath('./../'); + $this->assertEquals(realpath('../') . '/config', $app->get('path.config')); + } + + /** + * @covers \Engelsystem\Application::register + */ + public function testRegister() + { + $app = new Application(); + + $serviceProvider = $this->mockServiceProvider($app, ['register']); + $serviceProvider->expects($this->once()) + ->method('register'); + + $app->register($serviceProvider); + + $anotherServiceProvider = $this->mockServiceProvider($app, ['register', 'boot']); + $anotherServiceProvider->expects($this->once()) + ->method('register'); + $anotherServiceProvider->expects($this->once()) + ->method('boot'); + + $app->bootstrap(); + $app->register($anotherServiceProvider); + } + + /** + * @covers \Engelsystem\Application::register + */ + public function testRegisterBoot() + { + $app = new Application(); + $app->bootstrap(); + + $serviceProvider = $this->mockServiceProvider($app, ['register', 'boot']); + $serviceProvider->expects($this->once()) + ->method('register'); + $serviceProvider->expects($this->once()) + ->method('boot'); + + $app->register($serviceProvider); + } + + /** + * @covers \Engelsystem\Application::register + */ + public function testRegisterClassName() + { + $app = new Application(); + + $mockClassName = $this->getMockClass(ServiceProvider::class); + $serviceProvider = $this->getMockBuilder($mockClassName) + ->setConstructorArgs([$app]) + ->setMethods(['register']) + ->getMock(); + + $serviceProvider->expects($this->once()) + ->method('register'); + + $app->instance($mockClassName, $serviceProvider); + $app->register($mockClassName); + } + + /** + * @covers \Engelsystem\Application::bootstrap + * @covers \Engelsystem\Application::isBooted + */ + public function testBootstrap() + { + /** @var PHPUnit_Framework_MockObject_MockObject|Application $app */ + $app = $this->getMockBuilder(Application::class) + ->setMethods(['register']) + ->getMock(); + + $serviceProvider = $this->mockServiceProvider($app, ['boot']); + $serviceProvider->expects($this->once()) + ->method('boot'); + + $app->expects($this->once()) + ->method('register') + ->with($serviceProvider); + + $config = $this->getMockBuilder(Config::class) + ->getMock(); + + $config->expects($this->once()) + ->method('get') + ->with('providers') + ->willReturn([$serviceProvider]); + + $property = (new ReflectionClass($app))->getProperty('serviceProviders'); + $property->setAccessible(true); + $property->setValue($app, [$serviceProvider]); + + $app->bootstrap($config); + + $this->assertTrue($app->isBooted()); + + // Run bootstrap another time to ensure that providers are registered only once + $app->bootstrap($config); + } + + /** + * @param Application $app + * @param array $methods + * @return PHPUnit_Framework_MockObject_MockObject|ServiceProvider + */ + protected function mockServiceProvider(Application $app, $methods = []) + { + $serviceProvider = $this->getMockBuilder(ServiceProvider::class) + ->setConstructorArgs([$app]) + ->setMethods($methods) + ->getMockForAbstractClass(); + + return $serviceProvider; + } } -- cgit v1.2.3-54-g00ecf From 449e2cdd00632acff63bb75c5282c3aa2642b59f Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Mon, 25 Sep 2017 00:03:22 +0200 Subject: Added env function, added GitLab CI code coverage config --- .gitlab-ci.yml | 47 ++++++++++++++++++++++++++++++++++++++++++++++ config/config.default.php | 8 ++++---- src/helpers.php | 15 +++++++++++++++ tests/Unit/HelpersTest.php | 14 ++++++++++++++ 4 files changed, 80 insertions(+), 4 deletions(-) create mode 100644 .gitlab-ci.yml (limited to 'src') diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 00000000..c44507b1 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,47 @@ +image: php + +cache: + paths: + - .composer + +services: + - mysql:5.6 + +variables: + MYSQL_DATABASE: engelsystem + MYSQL_USER: engel + MYSQL_PASSWORD: engelsystem + COMPOSER_HOME: .composer + MYSQL_RANDOM_ROOT_PASSWORD: "yes" + +before_script: + # Install required Packages + - apt-get update -yqq + - apt-get install -yqq git unzip mysql-client + - docker-php-ext-install pdo pdo_mysql gettext + # Install xdebug + - pecl install xdebug + - docker-php-ext-enable xdebug + # MySQL DB + - mysql -h mysql -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE" < db/install.sql + - mysql -h mysql -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE" < db/update.sql + # Install Composer + - curl -sS https://getcomposer.org/installer | php -- --no-ansi --install-dir /usr/local/bin/ --filename composer + - /usr/local/bin/composer --no-ansi install + +.test_template: &test_definition + artifacts: + name: "${CI_JOB_NAME}_${CI_PROJECT_ID}_${PHP_VERSION}" + expire_in: 1 week + paths: + - ./coverage/ + coverage: '/^\s*Lines:\s*(\d+(?:\.\d+)?%)/' + script: vendor/bin/phpunit --colors=never --coverage-text --coverage-html ./coverage/ + +test:7.0: + image: php:7.0 + <<: *test_definition + +test:7.1: + image: php:7.1 + <<: *test_definition diff --git a/config/config.default.php b/config/config.default.php index c2d742ef..1bad9668 100644 --- a/config/config.default.php +++ b/config/config.default.php @@ -5,10 +5,10 @@ return [ // MySQL-Connection Settings 'database' => [ - 'host' => 'localhost', - 'user' => 'root', - 'pw' => '', - 'db' => 'engelsystem', + 'host' => env('MYSQL_HOST', (env('CI', false) ? 'mysql' : 'localhost')), + 'user' => env('MYSQL_USER', 'root'), + 'pw' => env('MYSQL_PASSWORD', ''), + 'db' => env('MYSQL_DATABASE', 'engelsystem'), ], // For accessing stats diff --git a/src/helpers.php b/src/helpers.php index c3c727ec..5a48498a 100644 --- a/src/helpers.php +++ b/src/helpers.php @@ -64,6 +64,21 @@ function config_path($path = '') return app('path.config') . (empty($path) ? '' : DIRECTORY_SEPARATOR . $path); } +/** + * @param string $key + * @param mixed $default + * @return mixed + */ +function env($key, $default = null) +{ + $value = getenv($key); + if ($value === false) { + return $default; + } + + return $value; +} + /** * @param string $key * @param mixed $default diff --git a/tests/Unit/HelpersTest.php b/tests/Unit/HelpersTest.php index d9782888..9ec824af 100644 --- a/tests/Unit/HelpersTest.php +++ b/tests/Unit/HelpersTest.php @@ -53,6 +53,20 @@ class HelpersTest extends TestCase $this->assertEquals(['user' => 'FooBar'], config('mail')); } + /** + * @covers \env + */ + public function testEnv() + { + putenv('envTestVar=someContent'); + + $env = env('envTestVar'); + $this->assertEquals('someContent', $env); + + $env = env('someRandomEnvVarThatShouldNeverExist', 'someDefaultValue'); + $this->assertEquals('someDefaultValue', $env); + } + /** * @covers \request */ -- cgit v1.2.3-54-g00ecf From 60fd72cd1a1e4e53b9af87e00a8c27687c6b5385 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Tue, 31 Oct 2017 13:40:13 +0100 Subject: Added service providers --- config/app.php | 6 ++ includes/autoload.php | 2 +- includes/engelsystem_provider.php | 95 ++++------------------ src/Application.php | 2 +- src/Config/ConfigServiceProvider.php | 26 ++++++ src/Database/DatabaseServiceProvider.php | 31 +++++++ src/Exceptions/ExceptionsServiceProvider.php | 15 ++++ src/Logger/LoggerServiceProvider.php | 18 ++++ src/Renderer/RendererServiceProvider.php | 36 ++++++++ src/Routing/RoutingServiceProvider.php | 14 ++++ .../DatabaseServiceProviderConnectionTest.php | 53 ++++++++++++ tests/Unit/Config/ConfigServiceProviderTest.php | 54 ++++++++++++ .../Unit/Database/DatabaseServiceProviderTest.php | 49 +++++++++++ .../Exceptions/ExceptionsServiceProviderTest.php | 39 +++++++++ tests/Unit/Logger/LoggerServiceProviderTest.php | 47 +++++++++++ .../Unit/Renderer/RendererServiceProviderTest.php | 81 ++++++++++++++++++ tests/Unit/Routing/RoutingServiceProviderTest.php | 39 +++++++++ tests/Unit/ServiceProviderTest.php | 39 +++++++++ tests/autoload.php | 8 ++ 19 files changed, 572 insertions(+), 82 deletions(-) create mode 100644 src/Config/ConfigServiceProvider.php create mode 100644 src/Database/DatabaseServiceProvider.php create mode 100644 src/Exceptions/ExceptionsServiceProvider.php create mode 100644 src/Logger/LoggerServiceProvider.php create mode 100644 src/Renderer/RendererServiceProvider.php create mode 100644 src/Routing/RoutingServiceProvider.php create mode 100644 tests/Feature/Database/DatabaseServiceProviderConnectionTest.php create mode 100644 tests/Unit/Config/ConfigServiceProviderTest.php create mode 100644 tests/Unit/Database/DatabaseServiceProviderTest.php create mode 100644 tests/Unit/Exceptions/ExceptionsServiceProviderTest.php create mode 100644 tests/Unit/Logger/LoggerServiceProviderTest.php create mode 100644 tests/Unit/Renderer/RendererServiceProviderTest.php create mode 100644 tests/Unit/Routing/RoutingServiceProviderTest.php create mode 100644 tests/Unit/ServiceProviderTest.php create mode 100644 tests/autoload.php (limited to 'src') diff --git a/config/app.php b/config/app.php index fe0a97c1..8037479b 100644 --- a/config/app.php +++ b/config/app.php @@ -5,5 +5,11 @@ return [ // Service providers 'providers' => [ + \Engelsystem\Logger\LoggerServiceProvider::class, + \Engelsystem\Exceptions\ExceptionsServiceProvider::class, + \Engelsystem\Config\ConfigServiceProvider::class, + \Engelsystem\Routing\RoutingServiceProvider::class, + \Engelsystem\Renderer\RendererServiceProvider::class, + \Engelsystem\Database\DatabaseServiceProvider::class, ], ]; diff --git a/includes/autoload.php b/includes/autoload.php index f51f89e4..0cd9d355 100644 --- a/includes/autoload.php +++ b/includes/autoload.php @@ -6,4 +6,4 @@ if (!is_readable(__DIR__ . '/../vendor/autoload.php')) { } // Include composer autoloader -require_once __DIR__ . '/../vendor/autoload.php'; +$loader = require __DIR__ . '/../vendor/autoload.php'; diff --git a/includes/engelsystem_provider.php b/includes/engelsystem_provider.php index 3067ab62..48206cb6 100644 --- a/includes/engelsystem_provider.php +++ b/includes/engelsystem_provider.php @@ -2,14 +2,8 @@ use Engelsystem\Application; use Engelsystem\Config\Config; -use Engelsystem\Database\Db; use Engelsystem\Exceptions\Handler as ExceptionHandler; use Engelsystem\Http\Request; -use Engelsystem\Logger\EngelsystemLogger; -use Engelsystem\Renderer\HtmlEngine; -use Engelsystem\Renderer\Renderer; -use Engelsystem\Routing\UrlGenerator; -use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; @@ -21,78 +15,21 @@ require_once __DIR__ . '/autoload.php'; /** - * Initialize the application + * Initialize and bootstrap the application */ $app = new Application(realpath(__DIR__ . DIRECTORY_SEPARATOR . '..')); - - -/** - * Bootstrap application - */ $appConfig = $app->make(Config::class); -$appConfig->set(app('path.config') . '/app.php'); +$appConfig->set(require config_path('app.php')); $app->bootstrap($appConfig); -/** - * Load configuration - */ -$config = new Config(); -$app->instance('config', $config); -$config->set(require __DIR__ . '/../config/config.default.php'); - -if (file_exists(__DIR__ . '/../config/config.php')) { - $config->set(array_replace_recursive( - $config->get(null), - require __DIR__ . '/../config/config.php' - )); -} - /** * Configure application */ -date_default_timezone_set($config->get('timezone')); - - -/** - * Initialize Request - * - * @var Request $request - */ -$request = Request::createFromGlobals(); -$app->instance('request', $request); - - -/** - * Check for maintenance - */ -if ($app->get('config')->get('maintenance')) { - echo file_get_contents(__DIR__ . '/../templates/maintenance.html'); - die(); -} - - -/** - * Register UrlGenerator - */ -$urlGenerator = new UrlGenerator(); -$app->instance('routing.urlGenerator', $urlGenerator); +date_default_timezone_set($app->get('config')->get('timezone')); - -/** - * Initialize renderer - */ -$renderer = new Renderer(); -$app->instance('renderer', $renderer); -$renderer->addRenderer(new HtmlEngine()); - - -/** - * Register error handler - */ -$errorHandler = new ExceptionHandler(); -$app->instance('error.handler', $errorHandler); if (config('environment') == 'development') { + $errorHandler = $app->get('error.handler'); $errorHandler->setEnvironment(ExceptionHandler::ENV_DEVELOPMENT); ini_set('display_errors', true); error_reporting(E_ALL); @@ -102,23 +39,21 @@ if (config('environment') == 'development') { /** - * Connect to database + * Check for maintenance */ -Db::connect( - 'mysql:host=' . config('database')['host'] . ';dbname=' . config('database')['db'] . ';charset=utf8', - config('database')['user'], - config('database')['pw'] -) || die('Error: Unable to connect to database'); -Db::getPdo()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); -Db::getPdo()->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); +if ($app->get('config')->get('maintenance')) { + echo file_get_contents(__DIR__ . '/../templates/maintenance.html'); + die(); +} + /** - * Init logger + * Initialize Request + * + * @var Request $request */ -$logger = new EngelsystemLogger(); -$app->instance('logger', $logger); -$app->bind(LoggerInterface::class, 'logger'); -$app->bind(EngelsystemLogger::class, 'logger'); +$request = Request::createFromGlobals(); +$app->instance('request', $request); /** diff --git a/src/Application.php b/src/Application.php index b62b28a9..c9023c7b 100644 --- a/src/Application.php +++ b/src/Application.php @@ -54,7 +54,7 @@ class Application extends Container public function register($provider) { if (is_string($provider)) { - $provider = $this->get($provider); + $provider = $this->make($provider); } $this->serviceProviders[] = $provider; diff --git a/src/Config/ConfigServiceProvider.php b/src/Config/ConfigServiceProvider.php new file mode 100644 index 00000000..01b648df --- /dev/null +++ b/src/Config/ConfigServiceProvider.php @@ -0,0 +1,26 @@ +app->make(Config::class); + $this->app->instance('config', $config); + + $config->set(require $defaultConfigFile); + + if (file_exists($configFile)) { + $config->set(array_replace_recursive( + $config->get(null), + require $configFile + )); + } + } +} diff --git a/src/Database/DatabaseServiceProvider.php b/src/Database/DatabaseServiceProvider.php new file mode 100644 index 00000000..364816cc --- /dev/null +++ b/src/Database/DatabaseServiceProvider.php @@ -0,0 +1,31 @@ +app->get('config'); + Db::connect( + 'mysql:host=' . $config->get('database')['host'] . ';dbname=' . $config->get('database')['db'] . ';charset=utf8', + $config->get('database')['user'], + $config->get('database')['pw'] + ) || $this->exitOnError(); + + Db::getPdo()->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + Db::getPdo()->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); + } + + /** + * @throws Exception + */ + protected function exitOnError() + { + throw new Exception('Error: Unable to connect to database'); + } +} diff --git a/src/Exceptions/ExceptionsServiceProvider.php b/src/Exceptions/ExceptionsServiceProvider.php new file mode 100644 index 00000000..7755e1e7 --- /dev/null +++ b/src/Exceptions/ExceptionsServiceProvider.php @@ -0,0 +1,15 @@ +app->make(ExceptionHandler::class); + $this->app->instance('error.handler', $errorHandler); + } +} diff --git a/src/Logger/LoggerServiceProvider.php b/src/Logger/LoggerServiceProvider.php new file mode 100644 index 00000000..cf22f383 --- /dev/null +++ b/src/Logger/LoggerServiceProvider.php @@ -0,0 +1,18 @@ +app->make(EngelsystemLogger::class); + $this->app->instance('logger', $logger); + + $this->app->bind(LoggerInterface::class, 'logger'); + $this->app->bind(EngelsystemLogger::class, 'logger'); + } +} diff --git a/src/Renderer/RendererServiceProvider.php b/src/Renderer/RendererServiceProvider.php new file mode 100644 index 00000000..3e8d69bc --- /dev/null +++ b/src/Renderer/RendererServiceProvider.php @@ -0,0 +1,36 @@ +registerRenderer(); + $this->registerHtmlEngine(); + } + + public function boot() + { + $renderer = $this->app->get('renderer'); + + foreach ($this->app->tagged('renderer.engine') as $engine) { + $renderer->addRenderer($engine); + } + } + + protected function registerRenderer() + { + $renderer = $this->app->make(Renderer::class); + $this->app->instance('renderer', $renderer); + } + + protected function registerHtmlEngine() + { + $htmlEngine = $this->app->make(HtmlEngine::class); + $this->app->instance('renderer.htmlEngine', $htmlEngine); + $this->app->tag('renderer.htmlEngine', ['renderer.engine']); + } +} diff --git a/src/Routing/RoutingServiceProvider.php b/src/Routing/RoutingServiceProvider.php new file mode 100644 index 00000000..b7db1383 --- /dev/null +++ b/src/Routing/RoutingServiceProvider.php @@ -0,0 +1,14 @@ +app->make(UrlGenerator::class); + $this->app->instance('routing.urlGenerator', $urlGenerator); + } +} diff --git a/tests/Feature/Database/DatabaseServiceProviderConnectionTest.php b/tests/Feature/Database/DatabaseServiceProviderConnectionTest.php new file mode 100644 index 00000000..dd1ce729 --- /dev/null +++ b/tests/Feature/Database/DatabaseServiceProviderConnectionTest.php @@ -0,0 +1,53 @@ +getMockBuilder(Config::class) + ->getMock(); + + /** @var PHPUnit_Framework_MockObject_MockObject|Application $app */ + $app = $this->getMockBuilder(Application::class) + ->setMethods(['get']) + ->getMock(); + Application::setInstance($app); + + $app->expects($this->once()) + ->method('get') + ->with('config') + ->willReturn($config); + + $config->expects($this->atLeastOnce()) + ->method('get') + ->with('database') + ->willReturn($this->getDbConfig()); + + $serviceProvider = new DatabaseServiceProvider($app); + $serviceProvider->register(); + } + + private function getDbConfig() + { + $configValues = require __DIR__ . '/../../../config/config.default.php'; + $configFile = __DIR__ . '/../../../config/config.php'; + + if (file_exists($configFile)) { + $configValues = array_replace_recursive($configValues, require $configFile); + } + + return $configValues['database']; + } +} diff --git a/tests/Unit/Config/ConfigServiceProviderTest.php b/tests/Unit/Config/ConfigServiceProviderTest.php new file mode 100644 index 00000000..26128e79 --- /dev/null +++ b/tests/Unit/Config/ConfigServiceProviderTest.php @@ -0,0 +1,54 @@ +getMockBuilder(Config::class) + ->getMock(); + + /** @var PHPUnit_Framework_MockObject_MockObject|Application $app */ + $app = $this->getMockBuilder(Application::class) + ->setMethods(['make', 'instance', 'get']) + ->getMock(); + Application::setInstance($app); + + $app->expects($this->once()) + ->method('make') + ->with(Config::class) + ->willReturn($config); + + $app->expects($this->once()) + ->method('instance') + ->with('config', $config); + + $app->expects($this->atLeastOnce()) + ->method('get') + ->with('path.config') + ->willReturn(__DIR__ . '/../../../config'); + + $config->expects($this->exactly(2)) + ->method('set') + ->withAnyParameters(); + + $config->expects($this->once()) + ->method('get') + ->with(null) + ->willReturn([]); + + $serviceProvider = new ConfigServiceProvider($app); + $serviceProvider->register(); + } +} diff --git a/tests/Unit/Database/DatabaseServiceProviderTest.php b/tests/Unit/Database/DatabaseServiceProviderTest.php new file mode 100644 index 00000000..d0e3e164 --- /dev/null +++ b/tests/Unit/Database/DatabaseServiceProviderTest.php @@ -0,0 +1,49 @@ +getMockBuilder(Config::class) + ->getMock(); + + /** @var PHPUnit_Framework_MockObject_MockObject|Application $app */ + $app = $this->getMockBuilder(Application::class) + ->setMethods(['get']) + ->getMock(); + + $app->expects($this->once()) + ->method('get') + ->with('config') + ->willReturn($config); + + $config->expects($this->atLeastOnce()) + ->method('get') + ->with('database') + ->willReturn([ + 'host' => 'localhost', + 'db' => 'database', + 'user' => 'user', + 'pw' => 'password', + ]); + + $serviceProvider = new DatabaseServiceProvider($app); + $this->expectException(Exception::class); + + $serviceProvider->register(); + } +} diff --git a/tests/Unit/Exceptions/ExceptionsServiceProviderTest.php b/tests/Unit/Exceptions/ExceptionsServiceProviderTest.php new file mode 100644 index 00000000..26eddb75 --- /dev/null +++ b/tests/Unit/Exceptions/ExceptionsServiceProviderTest.php @@ -0,0 +1,39 @@ +getMockBuilder(ExceptionHandler::class) + ->getMock(); + + /** @var PHPUnit_Framework_MockObject_MockObject|Application $app */ + $app = $this->getMockBuilder(Application::class) + ->setMethods(['make', 'instance']) + ->getMock(); + + $app->expects($this->once()) + ->method('make') + ->with(ExceptionHandler::class) + ->willReturn($exceptionHandler); + + $app->expects($this->once()) + ->method('instance') + ->with('error.handler', $exceptionHandler); + + $serviceProvider = new ExceptionsServiceProvider($app); + $serviceProvider->register(); + } +} diff --git a/tests/Unit/Logger/LoggerServiceProviderTest.php b/tests/Unit/Logger/LoggerServiceProviderTest.php new file mode 100644 index 00000000..5143d236 --- /dev/null +++ b/tests/Unit/Logger/LoggerServiceProviderTest.php @@ -0,0 +1,47 @@ +getMockBuilder(EngelsystemLogger::class) + ->getMock(); + + /** @var PHPUnit_Framework_MockObject_MockObject|Application $app */ + $app = $this->getMockBuilder(Application::class) + ->setMethods(['make', 'instance', 'bind']) + ->getMock(); + + $app->expects($this->once()) + ->method('make') + ->with(EngelsystemLogger::class) + ->willReturn($logger); + + $app->expects($this->once()) + ->method('instance') + ->with('logger', $logger); + + $app->expects($this->atLeastOnce()) + ->method('bind') + ->withConsecutive( + [LoggerInterface::class, 'logger'], + [EngelsystemLogger::class, 'logger'] + ); + + $serviceProvider = new LoggerServiceProvider($app); + $serviceProvider->register(); + } +} diff --git a/tests/Unit/Renderer/RendererServiceProviderTest.php b/tests/Unit/Renderer/RendererServiceProviderTest.php new file mode 100644 index 00000000..f9044d8b --- /dev/null +++ b/tests/Unit/Renderer/RendererServiceProviderTest.php @@ -0,0 +1,81 @@ +getMockBuilder(Renderer::class) + ->getMock(); + /** @var PHPUnit_Framework_MockObject_MockObject|HtmlEngine $htmlEngine */ + $htmlEngine = $this->getMockBuilder(HtmlEngine::class) + ->getMock(); + + $app = $this->getApp(['make', 'instance', 'tag']); + + $app->expects($this->exactly(2)) + ->method('make') + ->withConsecutive( + [Renderer::class], + [HtmlEngine::class] + )->willReturnOnConsecutiveCalls( + $renderer, + $htmlEngine + ); + + $app->expects($this->exactly(2)) + ->method('instance') + ->withConsecutive( + ['renderer', $renderer], + ['renderer.htmlEngine', $htmlEngine] + ); + + $this->setExpects($app, 'tag', ['renderer.htmlEngine', ['renderer.engine']]); + + $serviceProvider = new RendererServiceProvider($app); + $serviceProvider->register(); + } + + /** + * @covers \Engelsystem\Renderer\RendererServiceProvider::boot() + */ + public function testBoot() + { + /** @var PHPUnit_Framework_MockObject_MockObject|Renderer $renderer */ + $renderer = $this->getMockBuilder(Renderer::class) + ->getMock(); + /** @var PHPUnit_Framework_MockObject_MockObject|EngineInterface $engine1 */ + $engine1 = $this->getMockForAbstractClass(EngineInterface::class); + /** @var PHPUnit_Framework_MockObject_MockObject|EngineInterface $engine2 */ + $engine2 = $this->getMockForAbstractClass(EngineInterface::class); + + $app = $this->getApp(['get', 'tagged']); + + $engines = [$engine1, $engine2]; + + $this->setExpects($app, 'get', ['renderer'], $renderer); + $this->setExpects($app, 'tagged', ['renderer.engine'], $engines); + + $invocation = $renderer + ->expects($this->exactly(count($engines))) + ->method('addRenderer'); + call_user_func_array([$invocation, 'withConsecutive'], $engines); + + $serviceProvider = new RendererServiceProvider($app); + $serviceProvider->boot(); + } +} diff --git a/tests/Unit/Routing/RoutingServiceProviderTest.php b/tests/Unit/Routing/RoutingServiceProviderTest.php new file mode 100644 index 00000000..4f1cd5fc --- /dev/null +++ b/tests/Unit/Routing/RoutingServiceProviderTest.php @@ -0,0 +1,39 @@ +getMockBuilder(UrlGenerator::class) + ->getMock(); + + /** @var PHPUnit_Framework_MockObject_MockObject|Application $app */ + $app = $this->getMockBuilder(Application::class) + ->setMethods(['make', 'instance']) + ->getMock(); + + $app->expects($this->once()) + ->method('make') + ->with(UrlGenerator::class) + ->willReturn($urlGenerator); + + $app->expects($this->once()) + ->method('instance') + ->with('routing.urlGenerator', $urlGenerator); + + $serviceProvider = new RoutingServiceProvider($app); + $serviceProvider->register(); + } +} diff --git a/tests/Unit/ServiceProviderTest.php b/tests/Unit/ServiceProviderTest.php new file mode 100644 index 00000000..be843742 --- /dev/null +++ b/tests/Unit/ServiceProviderTest.php @@ -0,0 +1,39 @@ +getMockBuilder(Application::class) + ->setMethods($methods) + ->getMock(); + } + + /** + * @param PHPUnit_Framework_MockObject_MockObject $object + * @param string $method + * @param array $arguments + * @param mixed $return + */ + protected function setExpects($object, $method, $arguments, $return = null) + { + $invocation = $object->expects($this->once()) + ->method($method); + call_user_func_array([$invocation, 'with'], $arguments); + + if (!is_null($return)) { + $invocation->willReturn($return); + } + } +} diff --git a/tests/autoload.php b/tests/autoload.php new file mode 100644 index 00000000..3168ce3d --- /dev/null +++ b/tests/autoload.php @@ -0,0 +1,8 @@ +addPsr4('Engelsystem\\Test\\', __DIR__ . '/'); -- cgit v1.2.3-54-g00ecf From ad948bdd3201e922b626a736b0122533bdd37cae Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Wed, 1 Nov 2017 14:47:09 +0100 Subject: Added RequestServiceProvider and SessionServiceProvider --- config/app.php | 2 + includes/engelsystem.php | 34 ++----- src/Http/RequestServiceProvider.php | 14 +++ src/Http/SessionServiceProvider.php | 52 ++++++++++ tests/Unit/Database/DbTest.php | 2 +- tests/Unit/Http/RequestServiceProviderTest.php | 29 ++++++ tests/Unit/Http/SessionServiceProviderTest.php | 126 +++++++++++++++++++++++++ 7 files changed, 233 insertions(+), 26 deletions(-) create mode 100644 src/Http/RequestServiceProvider.php create mode 100644 src/Http/SessionServiceProvider.php create mode 100644 tests/Unit/Http/RequestServiceProviderTest.php create mode 100644 tests/Unit/Http/SessionServiceProviderTest.php (limited to 'src') diff --git a/config/app.php b/config/app.php index 8037479b..74eb2991 100644 --- a/config/app.php +++ b/config/app.php @@ -11,5 +11,7 @@ return [ \Engelsystem\Routing\RoutingServiceProvider::class, \Engelsystem\Renderer\RendererServiceProvider::class, \Engelsystem\Database\DatabaseServiceProvider::class, + \Engelsystem\Http\RequestServiceProvider::class, + \Engelsystem\Http\SessionServiceProvider::class, ], ]; diff --git a/includes/engelsystem.php b/includes/engelsystem.php index f9535847..97076895 100644 --- a/includes/engelsystem.php +++ b/includes/engelsystem.php @@ -3,10 +3,6 @@ use Engelsystem\Application; use Engelsystem\Config\Config; use Engelsystem\Exceptions\Handler as ExceptionHandler; -use Engelsystem\Http\Request; -use Symfony\Component\HttpFoundation\Session\Session; -use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; -use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; /** * This file includes all needed functions, connects to the db etc. @@ -14,6 +10,12 @@ use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage; require_once __DIR__ . '/autoload.php'; +/** + * Include legacy code + */ +require __DIR__ . '/includes.php'; + + /** * Initialize and bootstrap the application */ @@ -48,30 +50,12 @@ if ($app->get('config')->get('maintenance')) { /** - * Initialize Request - * - * @var Request $request + * Init translations */ -$request = Request::createFromGlobals(); -$app->instance('request', $request); - - -/** - * Include legacy code - */ -require __DIR__ . '/includes.php'; +gettext_init(); /** - * Init application + * Init authorization */ -$sessionStorage = (PHP_SAPI != 'cli' ? new NativeSessionStorage(['cookie_httponly' => true]) : new MockArraySessionStorage()); -$session = new Session($sessionStorage); -$app->instance('session', $session); -$session->start(); -$request->setSession($session); - - -gettext_init(); - load_auth(); diff --git a/src/Http/RequestServiceProvider.php b/src/Http/RequestServiceProvider.php new file mode 100644 index 00000000..077e9ecc --- /dev/null +++ b/src/Http/RequestServiceProvider.php @@ -0,0 +1,14 @@ +app->call([Request::class, 'createFromGlobals']); + $this->app->instance('request', $request); + } +} diff --git a/src/Http/SessionServiceProvider.php b/src/Http/SessionServiceProvider.php new file mode 100644 index 00000000..55e3f48b --- /dev/null +++ b/src/Http/SessionServiceProvider.php @@ -0,0 +1,52 @@ +getSessionStorage(); + $this->app->instance('session.storage', $sessionStorage); + $this->app->bind(SessionStorageInterface::class, 'session.storage'); + + $session = $this->app->make(Session::class); + $this->app->instance('session', $session); + + /** @var Request $request */ + $request = $this->app->get('request'); + $request->setSession($session); + + $session->start(); + } + + /** + * Returns the session storage + * + * @return SessionStorageInterface + */ + protected function getSessionStorage() + { + if ($this->isCli()) { + return $this->app->make(MockArraySessionStorage::class); + } + + return $this->app->make(NativeSessionStorage::class, ['options' => ['cookie_httponly' => true]]); + } + + /** + * Test if is called from cli + * + * @return bool + */ + protected function isCli() + { + return PHP_SAPI == 'cli'; + } +} diff --git a/tests/Unit/Database/DbTest.php b/tests/Unit/Database/DbTest.php index 4529cd6b..63607cad 100644 --- a/tests/Unit/Database/DbTest.php +++ b/tests/Unit/Database/DbTest.php @@ -19,7 +19,7 @@ class DbTest extends TestCase $result = Db::connect('mysql:host=localhost;dbname=someTestDatabaseThatDoesNotExist;charset=utf8'); $this->assertFalse($result); - $result = Db::connect('sqlite::memory'); + $result = Db::connect('sqlite::memory:'); $this->assertTrue($result); } diff --git a/tests/Unit/Http/RequestServiceProviderTest.php b/tests/Unit/Http/RequestServiceProviderTest.php new file mode 100644 index 00000000..a137b0ac --- /dev/null +++ b/tests/Unit/Http/RequestServiceProviderTest.php @@ -0,0 +1,29 @@ +getMockBuilder(Request::class) + ->getMock(); + + $app = $this->getApp(['call', 'instance']); + + $this->setExpects($app, 'call', [[Request::class, 'createFromGlobals']], $request); + $this->setExpects($app, 'instance', ['request', $request]); + + $serviceProvider = new RequestServiceProvider($app); + $serviceProvider->register(); + } +} diff --git a/tests/Unit/Http/SessionServiceProviderTest.php b/tests/Unit/Http/SessionServiceProviderTest.php new file mode 100644 index 00000000..0f17a1af --- /dev/null +++ b/tests/Unit/Http/SessionServiceProviderTest.php @@ -0,0 +1,126 @@ +getApp(['make', 'instance', 'bind', 'get']); + + $sessionStorage = $this->getMockForAbstractClass(StorageInterface::class); + $sessionStorage2 = $this->getMockForAbstractClass(StorageInterface::class); + + $session = $this->getSessionMock(); + $request = $this->getRequestMock(); + + /** @var MockObject|SessionServiceProvider $serviceProvider */ + $serviceProvider = $this->getMockBuilder(SessionServiceProvider::class) + ->setConstructorArgs([$app]) + ->setMethods(['isCli']) + ->getMock(); + $serviceProvider->expects($this->exactly(2)) + ->method('isCli') + ->willReturnOnConsecutiveCalls(true, false); + + $app->expects($this->exactly(4)) + ->method('make') + ->withConsecutive( + [MockArraySessionStorage::class], + [Session::class], + [NativeSessionStorage::class, ['options' => ['cookie_httponly' => true]]], + [Session::class] + ) + ->willReturnOnConsecutiveCalls( + $sessionStorage, + $session, + $sessionStorage2, + $session + ); + $app->expects($this->atLeastOnce()) + ->method('instance') + ->withConsecutive( + ['session.storage', $sessionStorage], + ['session', $session] + ); + + $this->setExpects($app, 'bind', [StorageInterface::class, 'session.storage'], null, $this->atLeastOnce()); + $this->setExpects($app, 'get', ['request'], $request, $this->atLeastOnce()); + $this->setExpects($request, 'setSession', [$session], null, $this->atLeastOnce()); + $this->setExpects($session, 'start', null, null, $this->atLeastOnce()); + + $serviceProvider->register(); + $serviceProvider->register(); + } + + /** + * @covers \Engelsystem\Http\SessionServiceProvider::isCli() + */ + public function testIsCli() + { + $app = $this->getApp(['make', 'instance', 'bind', 'get']); + + $sessionStorage = $this->getMockForAbstractClass(StorageInterface::class); + + $session = $this->getSessionMock(); + $request = $this->getRequestMock(); + + $app->expects($this->exactly(2)) + ->method('make') + ->withConsecutive( + [MockArraySessionStorage::class], + [Session::class] + ) + ->willReturnOnConsecutiveCalls( + $sessionStorage, + $session + ); + $app->expects($this->exactly(2)) + ->method('instance') + ->withConsecutive( + ['session.storage', $sessionStorage], + ['session', $session] + ); + + $this->setExpects($app, 'bind', [StorageInterface::class, 'session.storage']); + $this->setExpects($app, 'get', ['request'], $request); + $this->setExpects($request, 'setSession', [$session]); + $this->setExpects($session, 'start'); + + $serviceProvider = new SessionServiceProvider($app); + $serviceProvider->register(); + } + + /** + * @return MockObject + */ + private function getSessionMock() + { + return $this->getMockBuilder(Session::class) + ->setMethods(['start']) + ->getMock(); + } + + /** + * @return MockObject + */ + private function getRequestMock() + { + return $this->getMockBuilder(Request::class) + ->setMethods(['setSession']) + ->getMock(); + } +} -- cgit v1.2.3-54-g00ecf From f8807c4efbbddd02c69d0af63a1bf348b051d078 Mon Sep 17 00:00:00 2001 From: msquare Date: Sun, 19 Nov 2017 14:47:32 +0100 Subject: fix behaviour of HTTP/Request get --- src/Http/Request.php | 4 ++-- tests/Unit/Http/RequestTest.php | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/Http/Request.php b/src/Http/Request.php index e7850c8b..585fb5e9 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -38,9 +38,9 @@ class Request extends SymfonyRequest */ public function has($key) { - $value = $this->input($key); + $value = $this->input($key, null); - return !empty($value); + return !($value === null); } /** diff --git a/tests/Unit/Http/RequestTest.php b/tests/Unit/Http/RequestTest.php index 3f317367..a68f8b8f 100644 --- a/tests/Unit/Http/RequestTest.php +++ b/tests/Unit/Http/RequestTest.php @@ -47,7 +47,8 @@ class RequestTest extends TestCase ]); $this->assertTrue($request->has('foo')); - $this->assertFalse($request->has('bar')); + $this->assertTrue($request->has('bar')); + $this->assertFalse($request->has('baz')); } /** -- cgit v1.2.3-54-g00ecf From 0ee7df4883f6fab471aaa9130017483d4b91a754 Mon Sep 17 00:00:00 2001 From: msquare Date: Sun, 19 Nov 2017 15:16:01 +0100 Subject: change behaviour of HTTP/Request get --- src/Http/Request.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/Http/Request.php b/src/Http/Request.php index 585fb5e9..c6a9e5ad 100644 --- a/src/Http/Request.php +++ b/src/Http/Request.php @@ -38,9 +38,9 @@ class Request extends SymfonyRequest */ public function has($key) { - $value = $this->input($key, null); + $value = $this->input($key); - return !($value === null); + return !is_null($value); } /** -- cgit v1.2.3-54-g00ecf From 6eea072376cc9fd1034342a0e1d2173681268138 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Mon, 20 Nov 2017 17:08:05 +0100 Subject: Added ExceptionHandler Interface --- includes/engelsystem.php | 2 +- src/Exceptions/BasicHandler.php | 119 +++++++++++++++++++++ src/Exceptions/ExceptionsServiceProvider.php | 5 +- src/Exceptions/Handler.php | 112 ++----------------- .../Exceptions/ExceptionsServiceProviderTest.php | 6 +- tests/Unit/Exceptions/HandlerTest.php | 38 +++++++ 6 files changed, 173 insertions(+), 109 deletions(-) create mode 100644 src/Exceptions/BasicHandler.php create mode 100644 tests/Unit/Exceptions/HandlerTest.php (limited to 'src') diff --git a/includes/engelsystem.php b/includes/engelsystem.php index 97076895..688ce49f 100644 --- a/includes/engelsystem.php +++ b/includes/engelsystem.php @@ -2,7 +2,7 @@ use Engelsystem\Application; use Engelsystem\Config\Config; -use Engelsystem\Exceptions\Handler as ExceptionHandler; +use Engelsystem\Exceptions\BasicHandler as ExceptionHandler; /** * This file includes all needed functions, connects to the db etc. diff --git a/src/Exceptions/BasicHandler.php b/src/Exceptions/BasicHandler.php new file mode 100644 index 00000000..2ba960a2 --- /dev/null +++ b/src/Exceptions/BasicHandler.php @@ -0,0 +1,119 @@ +exceptionHandler($exception); + } + + /** + * @param Throwable $e + */ + public function exceptionHandler($e) + { + $this->handle( + $e->getCode(), + get_class($e) . ': ' . $e->getMessage(), + $e->getFile(), + $e->getLine(), + ['exception' => $e] + ); + } + + /** + * @param int $number + * @param string $string + * @param string $file + * @param int $line + * @param array $context + * @param array $trace + */ + protected function handle($number, $string, $file, $line, $context = [], $trace = []) + { + error_log(sprintf('Exception: Number: %s, String: %s, File: %s:%u, Context: %s', + $number, + $string, + $file, + $line, + json_encode($context) + )); + + $file = $this->stripBasePath($file); + + if ($this->environment == self::ENV_DEVELOPMENT) { + echo '
          ';
          +            echo sprintf('%s: (%s)' . PHP_EOL, ucfirst($type), $number);
          +            var_export([
          +                'string'     => $string,
          +                'file'       => $file . ':' . $line,
          +                'context'    => $context,
          +                'stacktrace' => $this->formatStackTrace($trace),
          +            ]);
          +            echo '
          '; + die(); + } + + echo 'An unexpected error occurred, a team of untrained monkeys has been dispatched to deal with it.'; + die(); + } + + /** + * @param array $stackTrace + * @return array + */ + protected function formatStackTrace($stackTrace) + { + $return = []; + + foreach ($stackTrace as $trace) { + $path = ''; + $line = ''; + + if (isset($trace['file']) && isset($trace['line'])) { + $path = $this->stripBasePath($trace['file']); + $line = $trace['line']; + } + + $functionName = $trace['function']; + + $return[] = [ + 'file' => $path . ':' . $line, + $functionName => $trace['args'], + ]; + } + + return $return; + } + + /** + * @param string $path + * @return string + */ + protected function stripBasePath($path) + { + $basePath = realpath(__DIR__ . '/../..') . '/'; + return str_replace($basePath, '', $path); + } +} diff --git a/src/Exceptions/ExceptionsServiceProvider.php b/src/Exceptions/ExceptionsServiceProvider.php index 7755e1e7..8eeccf61 100644 --- a/src/Exceptions/ExceptionsServiceProvider.php +++ b/src/Exceptions/ExceptionsServiceProvider.php @@ -3,13 +3,14 @@ namespace Engelsystem\Exceptions; use Engelsystem\Container\ServiceProvider; -use Engelsystem\Exceptions\Handler as ExceptionHandler; class ExceptionsServiceProvider extends ServiceProvider { public function register() { - $errorHandler = $this->app->make(ExceptionHandler::class); + $errorHandler = $this->app->make(BasicHandler::class); + $errorHandler->register(); $this->app->instance('error.handler', $errorHandler); + $this->app->bind(Handler::class, 'error.handler'); } } diff --git a/src/Exceptions/Handler.php b/src/Exceptions/Handler.php index 95bcd132..cdf94e32 100644 --- a/src/Exceptions/Handler.php +++ b/src/Exceptions/Handler.php @@ -2,9 +2,7 @@ namespace Engelsystem\Exceptions; -use Throwable; - -class Handler +abstract class Handler { /** @var string */ protected $environment; @@ -20,122 +18,28 @@ class Handler public function __construct($environment = self::ENV_PRODUCTION) { $this->environment = $environment; - - set_error_handler([$this, 'errorHandler']); - set_exception_handler([$this, 'exceptionHandler']); - } - - /** - * @param int $number - * @param string $string - * @param string $file - * @param int $line - * @param array $context - */ - public function errorHandler($number, $string, $file, $line, $context) - { - $trace = array_reverse(debug_backtrace()); - - $this->handle('error', $number, $string, $file, $line, $context, $trace); } /** - * @param Throwable $e + * Activate the error handler */ - public function exceptionHandler($e) + public function register() { - $this->handle( - 'exception', - $e->getCode(), - get_class($e) . ': ' . $e->getMessage(), - $e->getFile(), - $e->getLine(), - ['exception' => $e] - ); - } - - /** - * @param string $type - * @param int $number - * @param string $string - * @param string $file - * @param int $line - * @param array $context - * @param array $trace - */ - protected function handle($type, $number, $string, $file, $line, $context = [], $trace = []) - { - error_log(sprintf('%s: Number: %s, String: %s, File: %s:%u, Context: %s', - $type, - $number, - $string, - $file, - $line, - json_encode($context) - )); - - $file = $this->stripBasePath($file); - - if ($this->environment == self::ENV_DEVELOPMENT) { - echo '
          ';
          -            echo sprintf('%s: (%s)' . PHP_EOL, ucfirst($type), $number);
          -            var_export([
          -                'string'     => $string,
          -                'file'       => $file . ':' . $line,
          -                'context'    => $context,
          -                'stacktrace' => $this->formatStackTrace($trace),
          -            ]);
          -            echo '
          '; - die(); - } - - echo 'An unexpected error occurred, a team of untrained monkeys has been dispatched to deal with it.'; - die(); } /** - * @param array $stackTrace - * @return array + * @param string $environment */ - protected function formatStackTrace($stackTrace) + public function setEnvironment($environment) { - $return = []; - - foreach ($stackTrace as $trace) { - $path = ''; - $line = ''; - - if (isset($trace['file']) && isset($trace['line'])) { - $path = $this->stripBasePath($trace['file']); - $line = $trace['line']; - } - - $functionName = $trace['function']; - - $return[] = [ - 'file' => $path . ':' . $line, - $functionName => $trace['args'], - ]; - } - - return $return; + $this->environment = $environment; } /** - * @param string $path * @return string */ - protected function stripBasePath($path) + public function getEnvironment() { - $basePath = realpath(__DIR__ . '/../..') . '/'; - return str_replace($basePath, '', $path); - } - - /** - * @param string $environment - */ - public function setEnvironment($environment) - { - $this->environment = $environment; + return $this->environment; } } diff --git a/tests/Unit/Exceptions/ExceptionsServiceProviderTest.php b/tests/Unit/Exceptions/ExceptionsServiceProviderTest.php index 9c943d52..01fb2f11 100644 --- a/tests/Unit/Exceptions/ExceptionsServiceProviderTest.php +++ b/tests/Unit/Exceptions/ExceptionsServiceProviderTest.php @@ -2,8 +2,9 @@ namespace Engelsystem\Test\Unit\Exceptions; +use Engelsystem\Exceptions\BasicHandler as ExceptionHandler; use Engelsystem\Exceptions\ExceptionsServiceProvider; -use Engelsystem\Exceptions\Handler as ExceptionHandler; +use Engelsystem\Exceptions\Handler; use Engelsystem\Test\Unit\ServiceProviderTest; use PHPUnit_Framework_MockObject_MockObject; @@ -18,10 +19,11 @@ class ExceptionsServiceProviderTest extends ServiceProviderTest $exceptionHandler = $this->getMockBuilder(ExceptionHandler::class) ->getMock(); - $app = $this->getApp(); + $app = $this->getApp(['make', 'instance', 'bind']); $this->setExpects($app, 'make', [ExceptionHandler::class], $exceptionHandler); $this->setExpects($app, 'instance', ['error.handler', $exceptionHandler]); + $this->setExpects($app, 'bind', [Handler::class, 'error.handler']); $serviceProvider = new ExceptionsServiceProvider($app); $serviceProvider->register(); diff --git a/tests/Unit/Exceptions/HandlerTest.php b/tests/Unit/Exceptions/HandlerTest.php new file mode 100644 index 00000000..29759be7 --- /dev/null +++ b/tests/Unit/Exceptions/HandlerTest.php @@ -0,0 +1,38 @@ +getMockForAbstractClass(Handler::class); + $this->assertInstanceOf(Handler::class, $handler); + $handler->register(); + } + + /** + * @covers \Engelsystem\Exceptions\Handler::setEnvironment() + * @covers \Engelsystem\Exceptions\Handler::getEnvironment() + */ + public function testEnvironment() + { + /** @var Handler|Mock $handler */ + $handler = $this->getMockForAbstractClass(Handler::class); + + $handler->setEnvironment(Handler::ENV_DEVELOPMENT); + $this->assertEquals(Handler::ENV_DEVELOPMENT, $handler->getEnvironment()); + + $handler->setEnvironment(Handler::ENV_PRODUCTION); + $this->assertEquals(Handler::ENV_PRODUCTION, $handler->getEnvironment()); + } +} -- cgit v1.2.3-54-g00ecf From 25e434bce4986b48bd72729a55aa1096e5a76be3 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Fri, 24 Nov 2017 15:08:43 +0100 Subject: Refactored ExceptionHandler --- composer.json | 4 +- includes/engelsystem.php | 6 +- src/Exceptions/BasicHandler.php | 119 --------------------- src/Exceptions/ExceptionsServiceProvider.php | 46 +++++++- src/Exceptions/Handler.php | 100 ++++++++++++++++- src/Exceptions/Handlers/HandlerInterface.php | 21 ++++ src/Exceptions/Handlers/Legacy.php | 42 ++++++++ src/Exceptions/Handlers/LegacyDevelopment.php | 57 ++++++++++ src/Exceptions/Handlers/Whoops.php | 85 +++++++++++++++ .../Exceptions/ExceptionsServiceProviderTest.php | 94 ++++++++++++++-- tests/Unit/Exceptions/HandlerTest.php | 108 ++++++++++++++++++- .../Exceptions/Handlers/LegacyDevelopmentTest.php | 35 ++++++ tests/Unit/Exceptions/Handlers/LegacyTest.php | 55 ++++++++++ tests/Unit/Exceptions/Handlers/WhoopsTest.php | 83 ++++++++++++++ 14 files changed, 715 insertions(+), 140 deletions(-) delete mode 100644 src/Exceptions/BasicHandler.php create mode 100644 src/Exceptions/Handlers/HandlerInterface.php create mode 100644 src/Exceptions/Handlers/Legacy.php create mode 100644 src/Exceptions/Handlers/LegacyDevelopment.php create mode 100644 src/Exceptions/Handlers/Whoops.php create mode 100644 tests/Unit/Exceptions/Handlers/LegacyDevelopmentTest.php create mode 100644 tests/Unit/Exceptions/Handlers/LegacyTest.php create mode 100644 tests/Unit/Exceptions/Handlers/WhoopsTest.php (limited to 'src') diff --git a/composer.json b/composer.json index a8f0b0d6..ed34ba03 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,9 @@ "twbs/bootstrap": "^3.3" }, "require-dev": { - "phpunit/phpunit": "^6.3" + "filp/whoops": "^2.1", + "phpunit/phpunit": "^6.3", + "symfony/var-dumper": "^3.3" }, "autoload": { "psr-4": { diff --git a/includes/engelsystem.php b/includes/engelsystem.php index 688ce49f..07abbb42 100644 --- a/includes/engelsystem.php +++ b/includes/engelsystem.php @@ -2,7 +2,8 @@ use Engelsystem\Application; use Engelsystem\Config\Config; -use Engelsystem\Exceptions\BasicHandler as ExceptionHandler; +use Engelsystem\Exceptions\Handler; +use Engelsystem\Exceptions\Handlers\HandlerInterface; /** * This file includes all needed functions, connects to the db etc. @@ -32,7 +33,8 @@ date_default_timezone_set($app->get('config')->get('timezone')); if (config('environment') == 'development') { $errorHandler = $app->get('error.handler'); - $errorHandler->setEnvironment(ExceptionHandler::ENV_DEVELOPMENT); + $errorHandler->setEnvironment(Handler::ENV_DEVELOPMENT); + $app->bind(HandlerInterface::class, 'error.handler.development'); ini_set('display_errors', true); error_reporting(E_ALL); } else { diff --git a/src/Exceptions/BasicHandler.php b/src/Exceptions/BasicHandler.php deleted file mode 100644 index 2ba960a2..00000000 --- a/src/Exceptions/BasicHandler.php +++ /dev/null @@ -1,119 +0,0 @@ -exceptionHandler($exception); - } - - /** - * @param Throwable $e - */ - public function exceptionHandler($e) - { - $this->handle( - $e->getCode(), - get_class($e) . ': ' . $e->getMessage(), - $e->getFile(), - $e->getLine(), - ['exception' => $e] - ); - } - - /** - * @param int $number - * @param string $string - * @param string $file - * @param int $line - * @param array $context - * @param array $trace - */ - protected function handle($number, $string, $file, $line, $context = [], $trace = []) - { - error_log(sprintf('Exception: Number: %s, String: %s, File: %s:%u, Context: %s', - $number, - $string, - $file, - $line, - json_encode($context) - )); - - $file = $this->stripBasePath($file); - - if ($this->environment == self::ENV_DEVELOPMENT) { - echo '
          ';
          -            echo sprintf('%s: (%s)' . PHP_EOL, ucfirst($type), $number);
          -            var_export([
          -                'string'     => $string,
          -                'file'       => $file . ':' . $line,
          -                'context'    => $context,
          -                'stacktrace' => $this->formatStackTrace($trace),
          -            ]);
          -            echo '
          '; - die(); - } - - echo 'An unexpected error occurred, a team of untrained monkeys has been dispatched to deal with it.'; - die(); - } - - /** - * @param array $stackTrace - * @return array - */ - protected function formatStackTrace($stackTrace) - { - $return = []; - - foreach ($stackTrace as $trace) { - $path = ''; - $line = ''; - - if (isset($trace['file']) && isset($trace['line'])) { - $path = $this->stripBasePath($trace['file']); - $line = $trace['line']; - } - - $functionName = $trace['function']; - - $return[] = [ - 'file' => $path . ':' . $line, - $functionName => $trace['args'], - ]; - } - - return $return; - } - - /** - * @param string $path - * @return string - */ - protected function stripBasePath($path) - { - $basePath = realpath(__DIR__ . '/../..') . '/'; - return str_replace($basePath, '', $path); - } -} diff --git a/src/Exceptions/ExceptionsServiceProvider.php b/src/Exceptions/ExceptionsServiceProvider.php index 8eeccf61..a9bc2b17 100644 --- a/src/Exceptions/ExceptionsServiceProvider.php +++ b/src/Exceptions/ExceptionsServiceProvider.php @@ -3,14 +3,56 @@ namespace Engelsystem\Exceptions; use Engelsystem\Container\ServiceProvider; +use Engelsystem\Exceptions\Handlers\HandlerInterface; +use Engelsystem\Exceptions\Handlers\Legacy; +use Engelsystem\Exceptions\Handlers\LegacyDevelopment; +use Engelsystem\Exceptions\Handlers\Whoops; +use Whoops\Run as WhoopsRunner; class ExceptionsServiceProvider extends ServiceProvider { public function register() { - $errorHandler = $this->app->make(BasicHandler::class); - $errorHandler->register(); + $errorHandler = $this->app->make(Handler::class); + $this->addProductionHandler($errorHandler); + $this->addDevelopmentHandler($errorHandler); $this->app->instance('error.handler', $errorHandler); $this->app->bind(Handler::class, 'error.handler'); + $errorHandler->register(); + } + + public function boot() + { + /** @var Handler $handler */ + $handler = $this->app->get('error.handler'); + $request = $this->app->get('request'); + + $handler->setRequest($request); + } + + /** + * @param Handler $errorHandler + */ + protected function addProductionHandler($errorHandler) + { + $handler = $this->app->make(Legacy::class); + $this->app->instance('error.handler.production', $handler); + $errorHandler->setHandler(Handler::ENV_PRODUCTION, $handler); + $this->app->bind(HandlerInterface::class, 'error.handler.production'); + } + + /** + * @param Handler $errorHandler + */ + protected function addDevelopmentHandler($errorHandler) + { + $handler = $this->app->make(LegacyDevelopment::class); + + if (class_exists(WhoopsRunner::class)) { + $handler = $this->app->make(Whoops::class); + } + + $this->app->instance('error.handler.development', $handler); + $errorHandler->setHandler(Handler::ENV_DEVELOPMENT, $handler); } } diff --git a/src/Exceptions/Handler.php b/src/Exceptions/Handler.php index cdf94e32..ee15717a 100644 --- a/src/Exceptions/Handler.php +++ b/src/Exceptions/Handler.php @@ -2,18 +2,29 @@ namespace Engelsystem\Exceptions; -abstract class Handler +use Engelsystem\Exceptions\Handlers\HandlerInterface; +use Engelsystem\Http\Request; +use ErrorException; +use Throwable; + +class Handler { /** @var string */ protected $environment; + /** @var HandlerInterface[] */ + protected $handler = []; + + /** @var Request */ + protected $request; + const ENV_PRODUCTION = 'prod'; const ENV_DEVELOPMENT = 'dev'; /** * Handler constructor. * - * @param string $environment production|development + * @param string $environment prod|dev */ public function __construct($environment = self::ENV_PRODUCTION) { @@ -25,14 +36,47 @@ abstract class Handler */ public function register() { + set_error_handler([$this, 'errorHandler']); + set_exception_handler([$this, 'exceptionHandler']); } /** - * @param string $environment + * @param int $number + * @param string $message + * @param string $file + * @param int $line */ - public function setEnvironment($environment) + public function errorHandler($number, $message, $file, $line) { - $this->environment = $environment; + $exception = new ErrorException($message, 0, $number, $file, $line); + $this->exceptionHandler($exception); + } + + /** + * @param Throwable $e + */ + public function exceptionHandler($e) + { + if (!$this->request instanceof Request) { + $this->request = new Request(); + } + + $handler = $this->handler[$this->environment]; + $handler->report($e); + $handler->render($this->request, $e); + $this->die(); + } + + /** + * Exit the application + * + * @codeCoverageIgnore + * @param string $message + */ + protected function die($message = '') + { + echo $message; + die(); } /** @@ -42,4 +86,50 @@ abstract class Handler { return $this->environment; } + + /** + * @param string $environment + */ + public function setEnvironment($environment) + { + $this->environment = $environment; + } + + /** + * @param string $environment + * @return HandlerInterface|HandlerInterface[] + */ + public function getHandler($environment = null) + { + if (!is_null($environment)) { + return $this->handler[$environment]; + } + + return $this->handler; + } + + /** + * @param string $environment + * @param HandlerInterface $handler + */ + public function setHandler($environment, HandlerInterface $handler) + { + $this->handler[$environment] = $handler; + } + + /** + * @return Request + */ + public function getRequest() + { + return $this->request; + } + + /** + * @param Request $request + */ + public function setRequest(Request $request) + { + $this->request = $request; + } } diff --git a/src/Exceptions/Handlers/HandlerInterface.php b/src/Exceptions/Handlers/HandlerInterface.php new file mode 100644 index 00000000..9de33e1f --- /dev/null +++ b/src/Exceptions/Handlers/HandlerInterface.php @@ -0,0 +1,21 @@ +unexpected error occurred, a team of untrained monkeys has been dispatched to deal with it.'; + } + + /** + * @param Throwable $e + */ + public function report(Throwable $e) + { + error_log(sprintf('Exception: Code: %s, Message: %s, File: %s:%u, Trace: %s', + $e->getCode(), + $e->getMessage(), + $this->stripBasePath($e->getFile()), + $e->getLine(), + json_encode($e->getTrace()) + )); + } + + /** + * @param string $path + * @return string + */ + protected function stripBasePath($path) + { + $basePath = realpath(__DIR__ . '/../../..') . '/'; + return str_replace($basePath, '', $path); + } +} diff --git a/src/Exceptions/Handlers/LegacyDevelopment.php b/src/Exceptions/Handlers/LegacyDevelopment.php new file mode 100644 index 00000000..86f86f4c --- /dev/null +++ b/src/Exceptions/Handlers/LegacyDevelopment.php @@ -0,0 +1,57 @@ +stripBasePath($e->getFile()); + + echo '
          ';
          +        echo sprintf('%s: (%s)' . PHP_EOL, get_class($e), $e->getCode());
          +        $data = [
          +            'string'     => $e->getMessage(),
          +            'file'       => $file . ':' . $e->getLine(),
          +            'stacktrace' => $this->formatStackTrace($e->getTrace()),
          +        ];
          +        var_dump($data);
          +        echo '
          '; + } + + /** + * @param array $stackTrace + * @return array + */ + protected function formatStackTrace($stackTrace) + { + $return = []; + $stackTrace = array_reverse($stackTrace); + + foreach ($stackTrace as $trace) { + $path = ''; + $line = ''; + + if (isset($trace['file']) && isset($trace['line'])) { + $path = $this->stripBasePath($trace['file']); + $line = $trace['line']; + } + + $functionName = $trace['function']; + + $return[] = [ + 'file' => $path . ':' . $line, + $functionName => isset($trace['args']) ? $trace['args'] : null, + ]; + } + + return $return; + } +} diff --git a/src/Exceptions/Handlers/Whoops.php b/src/Exceptions/Handlers/Whoops.php new file mode 100644 index 00000000..807f5eb0 --- /dev/null +++ b/src/Exceptions/Handlers/Whoops.php @@ -0,0 +1,85 @@ +app = $app; + } + + /** + * @param Request $request + * @param Throwable $e + */ + public function render($request, Throwable $e) + { + $whoops = $this->app->make(WhoopsRunner::class); + $handler = $this->getPrettyPageHandler($e); + $whoops->pushHandler($handler); + + if ($request->isXmlHttpRequest()) { + $handler = $this->getJsonResponseHandler(); + $whoops->pushHandler($handler); + } + + echo $whoops->handleException($e); + } + + /** + * @param Throwable $e + * @return PrettyPageHandler + */ + protected function getPrettyPageHandler(Throwable $e) + { + $handler = $this->app->make(PrettyPageHandler::class); + + $handler->setPageTitle('Just another ' . get_class($e) . ' to fix :('); + $handler->setApplicationPaths([realpath(__DIR__ . '/../..')]); + + $data = $this->getData(); + $handler->addDataTable('Application', $data); + + return $handler; + } + + /** + * @return JsonResponseHandler + */ + protected function getJsonResponseHandler() + { + $handler = $this->app->make(JsonResponseHandler::class); + $handler->setJsonApi(true); + $handler->addTraceToOutput(true); + + return $handler; + } + + /** + * Aggregate application data + * + * @return array + */ + protected function getData() + { + global $user; + + $data = []; + $data['user'] = $user; + $data['Booted'] = $this->app->isBooted(); + + return $data; + } +} diff --git a/tests/Unit/Exceptions/ExceptionsServiceProviderTest.php b/tests/Unit/Exceptions/ExceptionsServiceProviderTest.php index 01fb2f11..4f2ae654 100644 --- a/tests/Unit/Exceptions/ExceptionsServiceProviderTest.php +++ b/tests/Unit/Exceptions/ExceptionsServiceProviderTest.php @@ -2,30 +2,108 @@ namespace Engelsystem\Test\Unit\Exceptions; -use Engelsystem\Exceptions\BasicHandler as ExceptionHandler; use Engelsystem\Exceptions\ExceptionsServiceProvider; use Engelsystem\Exceptions\Handler; +use Engelsystem\Exceptions\Handlers\HandlerInterface; +use Engelsystem\Exceptions\Handlers\Legacy; +use Engelsystem\Exceptions\Handlers\LegacyDevelopment; +use Engelsystem\Exceptions\Handlers\Whoops; +use Engelsystem\Http\Request; use Engelsystem\Test\Unit\ServiceProviderTest; -use PHPUnit_Framework_MockObject_MockObject; +use PHPUnit_Framework_MockObject_MockObject as MockObject; class ExceptionsServiceProviderTest extends ServiceProviderTest { /** * @covers \Engelsystem\Exceptions\ExceptionsServiceProvider::register() + * @covers \Engelsystem\Exceptions\ExceptionsServiceProvider::addProductionHandler() + * @covers \Engelsystem\Exceptions\ExceptionsServiceProvider::addDevelopmentHandler() */ public function testRegister() { - /** @var PHPUnit_Framework_MockObject_MockObject|ExceptionHandler $exceptionHandler */ - $exceptionHandler = $this->getMockBuilder(ExceptionHandler::class) + $app = $this->getApp(['make', 'instance', 'bind']); + + /** @var MockObject|Handler $handler */ + $handler = $this->createMock(Handler::class); + $this->setExpects($handler, 'register'); + /** @var Legacy|MockObject $legacyHandler */ + $legacyHandler = $this->createMock(Legacy::class); + /** @var LegacyDevelopment|MockObject $developmentHandler */ + $developmentHandler = $this->createMock(LegacyDevelopment::class); + + $whoopsHandler = $this->getMockBuilder(Whoops::class) + ->setConstructorArgs([$app]) ->getMock(); - $app = $this->getApp(['make', 'instance', 'bind']); + $app->expects($this->exactly(3)) + ->method('instance') + ->withConsecutive( + ['error.handler.production', $legacyHandler], + ['error.handler.development', $whoopsHandler], + ['error.handler', $handler] + ); - $this->setExpects($app, 'make', [ExceptionHandler::class], $exceptionHandler); - $this->setExpects($app, 'instance', ['error.handler', $exceptionHandler]); - $this->setExpects($app, 'bind', [Handler::class, 'error.handler']); + $app->expects($this->exactly(4)) + ->method('make') + ->withConsecutive( + [Handler::class], + [Legacy::class], + [LegacyDevelopment::class], + [Whoops::class] + ) + ->willReturnOnConsecutiveCalls( + $handler, + $legacyHandler, + $developmentHandler, + $whoopsHandler + ); + + $app->expects($this->exactly(2)) + ->method('bind') + ->withConsecutive( + [HandlerInterface::class, 'error.handler.production'], + [Handler::class, 'error.handler'] + ); + + $handler->expects($this->exactly(2)) + ->method('setHandler') + ->withConsecutive( + [Handler::ENV_PRODUCTION, $legacyHandler], + [Handler::ENV_DEVELOPMENT, $whoopsHandler] + ); $serviceProvider = new ExceptionsServiceProvider($app); $serviceProvider->register(); } + + /** + * @covers \Engelsystem\Exceptions\ExceptionsServiceProvider::boot() + */ + public function testBoot() + { + /** @var MockObject|Handler $handler */ + $handler = $this->createMock(Handler::class); + + /** @var MockObject|Request $request */ + $request = $this->createMock(Request::class); + + $handler->expects($this->once()) + ->method('setRequest') + ->with($request); + + $app = $this->getApp(['get']); + $app->expects($this->exactly(2)) + ->method('get') + ->withConsecutive( + ['error.handler'], + ['request'] + ) + ->willReturnOnConsecutiveCalls( + $handler, + $request + ); + + $provider = new ExceptionsServiceProvider($app); + $provider->boot(); + } } diff --git a/tests/Unit/Exceptions/HandlerTest.php b/tests/Unit/Exceptions/HandlerTest.php index 29759be7..40202be8 100644 --- a/tests/Unit/Exceptions/HandlerTest.php +++ b/tests/Unit/Exceptions/HandlerTest.php @@ -3,6 +3,10 @@ namespace Engelsystem\Test\Unit\Exceptions; use Engelsystem\Exceptions\Handler; +use Engelsystem\Exceptions\Handlers\HandlerInterface; +use Engelsystem\Http\Request; +use ErrorException; +use Exception; use PHPUnit\Framework\TestCase; use PHPUnit_Framework_MockObject_MockObject as Mock; @@ -10,14 +14,80 @@ class HandlerTest extends TestCase { /** * @covers \Engelsystem\Exceptions\Handler::__construct() + */ + public function testCreate() + { + /** @var Handler|Mock $handler */ + $handler = new Handler(); + $this->assertInstanceOf(Handler::class, $handler); + $this->assertEquals(Handler::ENV_PRODUCTION, $handler->getEnvironment()); + + $anotherHandler = new Handler(Handler::ENV_DEVELOPMENT); + $this->assertEquals(Handler::ENV_DEVELOPMENT, $anotherHandler->getEnvironment()); + } + + /** + * @covers \Engelsystem\Exceptions\Handler::errorHandler() + */ + public function testErrorHandler() + { + /** @var Handler|Mock $handler */ + $handler = $this->getMockBuilder(Handler::class) + ->setMethods(['exceptionHandler']) + ->getMock(); + + $handler->expects($this->once()) + ->method('exceptionHandler') + ->with($this->isInstanceOf(ErrorException::class)); + + $handler->errorHandler(1, 'Foo and bar!', '/lo/rem.php', 123); + } + + /** + * @covers \Engelsystem\Exceptions\Handler::exceptionHandler() + */ + public function testExceptionHandler() + { + $exception = new Exception(); + + /** @var HandlerInterface|Mock $handlerMock */ + $handlerMock = $this->getMockForAbstractClass(HandlerInterface::class); + $handlerMock->expects($this->once()) + ->method('report') + ->with($exception); + $handlerMock->expects($this->once()) + ->method('render') + ->with($this->isInstanceOf(Request::class), $exception); + + /** @var Handler|Mock $handler */ + $handler = $this->getMockBuilder(Handler::class) + ->setMethods(['die']) + ->getMock(); + $handler->expects($this->once()) + ->method('die'); + + $handler->setHandler(Handler::ENV_PRODUCTION, $handlerMock); + + $handler->exceptionHandler($exception); + } + + /** * @covers \Engelsystem\Exceptions\Handler::register() */ public function testRegister() { /** @var Handler|Mock $handler */ $handler = $this->getMockForAbstractClass(Handler::class); - $this->assertInstanceOf(Handler::class, $handler); $handler->register(); + + set_error_handler($errorHandler = set_error_handler('var_dump')); + $this->assertEquals($handler, array_shift($errorHandler)); + + set_exception_handler($exceptionHandler = set_error_handler('var_dump')); + $this->assertEquals($handler, array_shift($exceptionHandler)); + + restore_error_handler(); + restore_exception_handler(); } /** @@ -26,8 +96,7 @@ class HandlerTest extends TestCase */ public function testEnvironment() { - /** @var Handler|Mock $handler */ - $handler = $this->getMockForAbstractClass(Handler::class); + $handler = new Handler(); $handler->setEnvironment(Handler::ENV_DEVELOPMENT); $this->assertEquals(Handler::ENV_DEVELOPMENT, $handler->getEnvironment()); @@ -35,4 +104,37 @@ class HandlerTest extends TestCase $handler->setEnvironment(Handler::ENV_PRODUCTION); $this->assertEquals(Handler::ENV_PRODUCTION, $handler->getEnvironment()); } + + /** + * @covers \Engelsystem\Exceptions\Handler::setHandler() + * @covers \Engelsystem\Exceptions\Handler::getHandler() + */ + public function testHandler() + { + $handler = new Handler(); + /** @var HandlerInterface|Mock $devHandler */ + $devHandler = $this->getMockForAbstractClass(HandlerInterface::class); + /** @var HandlerInterface|Mock $prodHandler */ + $prodHandler = $this->getMockForAbstractClass(HandlerInterface::class); + + $handler->setHandler(Handler::ENV_DEVELOPMENT, $devHandler); + $handler->setHandler(Handler::ENV_PRODUCTION, $prodHandler); + $this->assertEquals($devHandler, $handler->getHandler(Handler::ENV_DEVELOPMENT)); + $this->assertEquals($prodHandler, $handler->getHandler(Handler::ENV_PRODUCTION)); + $this->assertCount(2, $handler->getHandler()); + } + + /** + * @covers \Engelsystem\Exceptions\Handler::setRequest() + * @covers \Engelsystem\Exceptions\Handler::getRequest() + */ + public function testRequest() + { + $handler = new Handler(); + /** @var Request|Mock $request */ + $request = $this->createMock(Request::class); + + $handler->setRequest($request); + $this->assertEquals($request, $handler->getRequest()); + } } diff --git a/tests/Unit/Exceptions/Handlers/LegacyDevelopmentTest.php b/tests/Unit/Exceptions/Handlers/LegacyDevelopmentTest.php new file mode 100644 index 00000000..d5390c9e --- /dev/null +++ b/tests/Unit/Exceptions/Handlers/LegacyDevelopmentTest.php @@ -0,0 +1,35 @@ +createMock(Request::class); + $exception = new ErrorException('Lorem Ipsum', 4242, 1, 'foo.php', 9999); + + $regex = sprintf( + '%%.*ErrorException.*4242.*Lorem Ipsum.*%s.*%s.*%s.*%%is', + 'foo.php', + 9999, + __FUNCTION__ + ); + $this->expectOutputRegex($regex); + + $handler->render($request, $exception); + } +} diff --git a/tests/Unit/Exceptions/Handlers/LegacyTest.php b/tests/Unit/Exceptions/Handlers/LegacyTest.php new file mode 100644 index 00000000..04b214f2 --- /dev/null +++ b/tests/Unit/Exceptions/Handlers/LegacyTest.php @@ -0,0 +1,55 @@ +createMock(Request::class); + /** @var Exception|Mock $exception */ + $exception = $this->createMock(Exception::class); + + $this->expectOutputRegex('/.*error occurred.*/i'); + + $handler->render($request, $exception); + } + + /** + * @covers \Engelsystem\Exceptions\Handlers\Legacy::report() + * @covers \Engelsystem\Exceptions\Handlers\Legacy::stripBasePath() + */ + public function testReport() + { + $handler = new Legacy(); + $exception = new Exception('Lorem Ipsum', 4242); + $line = __LINE__ - 1; + + $log = tempnam(sys_get_temp_dir(), 'engelsystem-log'); + $errorLog = ini_get('error_log'); + ini_set('error_log', $log); + $handler->report($exception); + ini_set('error_log', $errorLog); + $logContent = file_get_contents($log); + unset($log); + + $this->assertContains('4242', $logContent); + $this->assertContains('Lorem Ipsum', $logContent); + $this->assertContains(basename(__FILE__), $logContent); + $this->assertContains((string)$line, $logContent); + $this->assertContains(__FUNCTION__, $logContent); + $this->assertContains(json_encode(__CLASS__), $logContent); + } +} diff --git a/tests/Unit/Exceptions/Handlers/WhoopsTest.php b/tests/Unit/Exceptions/Handlers/WhoopsTest.php new file mode 100644 index 00000000..261ee83f --- /dev/null +++ b/tests/Unit/Exceptions/Handlers/WhoopsTest.php @@ -0,0 +1,83 @@ +createMock(Application::class); + /** @var Request|Mock $request */ + $request = $this->createMock(Request::class); + $request->expects($this->once()) + ->method('isXmlHttpRequest') + ->willReturn(true); + /** @var WhoopsRunnerInterface|Mock $whoopsRunner */ + $whoopsRunner = $this->getMockForAbstractClass(WhoopsRunnerInterface::class); + /** @var PrettyPageHandler|Mock $prettyPageHandler */ + $prettyPageHandler = $this->createMock(PrettyPageHandler::class); + $prettyPageHandler + ->expects($this->atLeastOnce()) + ->method('setApplicationPaths'); + $prettyPageHandler + ->expects($this->once()) + ->method('setApplicationPaths'); + $prettyPageHandler + ->expects($this->once()) + ->method('addDataTable'); + /** @var JsonResponseHandler|Mock $jsonResponseHandler */ + $jsonResponseHandler = $this->createMock(JsonResponseHandler::class); + $jsonResponseHandler->expects($this->once()) + ->method('setJsonApi') + ->with(true); + $jsonResponseHandler->expects($this->once()) + ->method('addTraceToOutput') + ->with(true); + /** @var Exception|Mock $exception */ + $exception = $this->createMock(Exception::class); + + $app->expects($this->exactly(3)) + ->method('make') + ->withConsecutive( + [WhoopsRunner::class], + [PrettyPageHandler::class], + [JsonResponseHandler::class] + ) + ->willReturnOnConsecutiveCalls( + $whoopsRunner, + $prettyPageHandler, + $jsonResponseHandler + ); + + $whoopsRunner + ->expects($this->exactly(2)) + ->method('pushHandler') + ->withConsecutive( + [$prettyPageHandler], + [$jsonResponseHandler] + ); + $whoopsRunner + ->expects($this->once()) + ->method('handleException') + ->with($exception); + + $handler = new Whoops($app); + $handler->render($request, $exception); + } +} -- cgit v1.2.3-54-g00ecf
          %s %s