Replaced more user related stuff

(Contains some buggy stuff too...)
This commit is contained in:
Igor Scheller 2018-10-11 01:26:34 +02:00 committed by msquare
parent 7c6afc2bfe
commit 4e09ee3eb2
29 changed files with 470 additions and 656 deletions

View File

@ -111,10 +111,10 @@ function shift_entry_create_controller_admin($shift, $angeltype)
redirect(shift_link($shift)); redirect(shift_link($shift));
} }
$users = Users(); $users = User::all();
$users_select = []; $users_select = [];
foreach ($users as $u) { foreach ($users as $u) {
$users_select[$u['UID']] = $u['Nick']; $users_select[$u->id] = $u->name;
} }
$angeltypes_select = []; $angeltypes_select = [];
@ -185,7 +185,7 @@ function shift_entry_create_controller_supporter($shift, $angeltype)
$users = Users_by_angeltype($angeltype); $users = Users_by_angeltype($angeltype);
$users_select = []; $users_select = [];
foreach ($users as $u) { foreach ($users as $u) {
$users_select[$u['UID']] = $u['Nick']; $users_select[$u->id] = $u->name;
} }
$room = Room($shift['RID']); $room = Room($shift['RID']);

View File

@ -353,20 +353,17 @@ function shift_next_controller()
*/ */
function shifts_json_export_controller() function shifts_json_export_controller()
{ {
global $user;
$request = request(); $request = request();
if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) { if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) {
engelsystem_error('Missing key.'); engelsystem_error('Missing key.');
} }
$key = $request->input('key'); $user = auth()->apiUser('key');
if (!$user) {
$user = User_by_api_key($key);
if (empty($user)) {
engelsystem_error('Key invalid.'); engelsystem_error('Key invalid.');
} }
if (!in_array('shifts_json_export', privileges_for_user($user['UID']))) { if (!in_array('shifts_json_export', privileges_for_user($user->id))) {
engelsystem_error('No privilege for shifts_json_export.'); engelsystem_error('No privilege for shifts_json_export.');
} }

View File

@ -362,16 +362,17 @@ function user_angeltype_add_controller()
*/ */
function user_angeltype_join_controller($angeltype) function user_angeltype_join_controller($angeltype)
{ {
global $user, $privileges; global $privileges;
$user = auth()->user();
$user_angeltype = UserAngelType_by_User_and_AngelType($user['UID'], $angeltype); $user_angeltype = UserAngelType_by_User_and_AngelType($user->id, $angeltype);
if (!empty($user_angeltype)) { if (!empty($user_angeltype)) {
error(sprintf(__('You are already a %s.'), $angeltype['name'])); error(sprintf(__('You are already a %s.'), $angeltype['name']));
redirect(page_link_to('angeltypes')); redirect(page_link_to('angeltypes'));
} }
if (request()->has('confirmed')) { if (request()->has('confirmed')) {
$user_angeltype_id = UserAngelType_create($user['UID'], $angeltype); $user_angeltype_id = UserAngelType_create($user->id, $angeltype);
$success_message = sprintf(__('You joined %s.'), $angeltype['name']); $success_message = sprintf(__('You joined %s.'), $angeltype['name']);
engelsystem_log(sprintf( engelsystem_log(sprintf(
@ -382,7 +383,7 @@ function user_angeltype_join_controller($angeltype)
success($success_message); success($success_message);
if (in_array('admin_user_angeltypes', $privileges)) { if (in_array('admin_user_angeltypes', $privileges)) {
UserAngelType_confirm($user_angeltype_id, $user['UID']); UserAngelType_confirm($user_angeltype_id, $user->id);
engelsystem_log(sprintf( engelsystem_log(sprintf(
'User %s confirmed as %s.', 'User %s confirmed as %s.',
User_Nick_render($user), User_Nick_render($user),

View File

@ -2,6 +2,7 @@
use Engelsystem\Database\DB; use Engelsystem\Database\DB;
use Engelsystem\Models\User\PasswordReset; use Engelsystem\Models\User\PasswordReset;
use Engelsystem\Models\User\State;
use Engelsystem\Models\User\User; use Engelsystem\Models\User\User;
use Engelsystem\ShiftCalendarRenderer; use Engelsystem\ShiftCalendarRenderer;
use Engelsystem\ShiftsFilter; use Engelsystem\ShiftsFilter;
@ -79,7 +80,7 @@ function user_delete_controller()
} }
if ($valid) { if ($valid) {
User_delete($user_source->id); $user_source->delete();
mail_user_delete($user_source); mail_user_delete($user_source);
success(__('User deleted.')); success(__('User deleted.'));
@ -268,13 +269,28 @@ function users_list_controller()
} }
$order_by = 'Nick'; $order_by = 'Nick';
if ($request->has('OrderBy') && in_array($request->input('OrderBy'), User_sortable_columns())) { if ($request->has('OrderBy') && in_array($request->input('OrderBy'), [
'Nick',
'Name',
'Vorname',
'DECT',
'email',
'Size',
'Gekommen',
'Aktiv',
'force_active',
'Tshirt',
'lastLogIn'
])) {
$order_by = $request->input('OrderBy'); $order_by = $request->input('OrderBy');
} }
$users = Users($order_by); /** @var User[] $users */
foreach ($users as &$user) { $users = User::query()
$user['freeloads'] = count(ShiftEntries_freeloaded_by_user($user['UID'])); ->orderBy($order_by)
->get();
foreach ($users as $user) {
$user->setAttribute('freeloads', count(ShiftEntries_freeloaded_by_user($user->id)));
} }
return [ return [
@ -282,12 +298,12 @@ function users_list_controller()
Users_view( Users_view(
$users, $users,
$order_by, $order_by,
User_arrived_count(), State::whereArrived(true)->count(),
User_active_count(), State::whereActive(true)->count(),
User_force_active_count(), State::whereForceActive(true)->count(),
ShiftEntries_freeloaded_count(), ShiftEntries_freeloaded_count(),
User_tshirts_count(), State::whereGotShirt(true)->count(),
User_got_voucher_count() State::query()->sum('got_voucher')
) )
]; ];
} }
@ -300,7 +316,7 @@ function users_list_controller()
function user_password_recovery_set_new_controller() function user_password_recovery_set_new_controller()
{ {
$request = request(); $request = request();
$passwordReset = PasswordReset::whereToken($request->input('token')); $passwordReset = PasswordReset::whereToken($request->input('token'))->first();
if (!$passwordReset) { if (!$passwordReset) {
error(__('Token is not correct.')); error(__('Token is not correct.'));
redirect(page_link_to('login')); redirect(page_link_to('login'));
@ -344,11 +360,13 @@ function user_password_recovery_start_controller()
if ($request->has('submit')) { if ($request->has('submit')) {
$valid = true; $valid = true;
$user_source = null;
if ($request->has('email') && strlen(strip_request_item('email')) > 0) { if ($request->has('email') && strlen(strip_request_item('email')) > 0) {
$email = strip_request_item('email'); $email = strip_request_item('email');
if (check_email($email)) { if (check_email($email)) {
$user_source = User_by_email($email); /** @var User $user_source */
if (empty($user_source)) { $user_source = User::whereEmail($email)->first();
if (!$user_source) {
$valid = false; $valid = false;
error(__('E-mail address is not correct.')); error(__('E-mail address is not correct.'));
} }

View File

@ -27,7 +27,6 @@ function Message($message_id)
/** /**
* TODO: use validation functions, return new message id * TODO: use validation functions, return new message id
* TODO: global $user can't be used in model!
* send message * send message
* *
* @param int $receiver_user_id User ID of Receiver * @param int $receiver_user_id User ID of Receiver

View File

@ -77,7 +77,6 @@ function ShiftEntry_create($shift_entry)
{ {
$user = User::find($shift_entry['UID']); $user = User::find($shift_entry['UID']);
$shift = Shift($shift_entry['SID']); $shift = Shift($shift_entry['SID']);
mail_shift_assign($user, $shift);
$result = DB::insert(' $result = DB::insert('
INSERT INTO `ShiftEntry` ( INSERT INTO `ShiftEntry` (
`SID`, `SID`,
@ -104,6 +103,7 @@ function ShiftEntry_create($shift_entry)
. ' from ' . date('Y-m-d H:i', $shift['start']) . ' from ' . date('Y-m-d H:i', $shift['start'])
. ' to ' . date('Y-m-d H:i', $shift['end']) . ' to ' . date('Y-m-d H:i', $shift['end'])
); );
mail_shift_assign($user, $shift);
return $result; return $result;
} }
@ -151,7 +151,6 @@ function ShiftEntry($shift_entry_id)
*/ */
function ShiftEntry_delete($shiftEntry) function ShiftEntry_delete($shiftEntry)
{ {
mail_shift_removed(User::find($shiftEntry['UID']), Shift($shiftEntry['SID']));
DB::delete('DELETE FROM `ShiftEntry` WHERE `id` = ?', [$shiftEntry['id']]); DB::delete('DELETE FROM `ShiftEntry` WHERE `id` = ?', [$shiftEntry['id']]);
$signout_user = User::find($shiftEntry['UID']); $signout_user = User::find($shiftEntry['UID']);
@ -167,6 +166,8 @@ function ShiftEntry_delete($shiftEntry)
. ' to ' . date('Y-m-d H:i', $shift['end']) . ' to ' . date('Y-m-d H:i', $shift['end'])
. ' as ' . $angeltype['name'] . ' as ' . $angeltype['name']
); );
mail_shift_removed(User::find($shiftEntry['UID']), Shift($shiftEntry['SID']));
} }
/** /**

View File

@ -2,23 +2,15 @@
use Carbon\Carbon; use Carbon\Carbon;
use Engelsystem\Database\DB; use Engelsystem\Database\DB;
use Engelsystem\Models\User\PasswordReset;
use Engelsystem\Models\User\User; use Engelsystem\Models\User\User;
use Engelsystem\ValidationResult; use Engelsystem\ValidationResult;
use Illuminate\Database\Query\JoinClause;
/** /**
* User model * User model
*/ */
/**
* Delete a user
*
* @param int $user_id
*/
function User_delete($user_id)
{
DB::delete('DELETE FROM `User` WHERE `UID`=?', [$user_id]);
}
/** /**
* Returns the tshirt score (number of hours counted for tshirt). * Returns the tshirt score (number of hours counted for tshirt).
* Accounts only ended shifts. * Accounts only ended shifts.
@ -29,14 +21,14 @@ function User_delete($user_id)
function User_tshirt_score($userId) function User_tshirt_score($userId)
{ {
$shift_sum_formula = User_get_shifts_sum_query(); $shift_sum_formula = User_get_shifts_sum_query();
$result_shifts = DB::selectOne(' $result_shifts = DB::selectOne(sprintf('
SELECT ROUND((' . $shift_sum_formula . ') / 3600, 2) AS `tshirt_score` SELECT ROUND((%s) / 3600, 2) AS `tshirt_score`
FROM `User` LEFT JOIN `ShiftEntry` ON `User`.`UID` = `ShiftEntry`.`UID` FROM `users` LEFT JOIN `ShiftEntry` ON `users`.`id` = `ShiftEntry`.`UID`
LEFT JOIN `Shifts` ON `ShiftEntry`.`SID` = `Shifts`.`SID` LEFT JOIN `Shifts` ON `ShiftEntry`.`SID` = `Shifts`.`SID`
WHERE `User`.`UID` = ? WHERE `users`.`id` = ?
AND `Shifts`.`end` < ? AND `Shifts`.`end` < ?
GROUP BY `User`.`UID` GROUP BY `users`.`id`
', [ ', $shift_sum_formula), [
$userId, $userId,
time() time()
]); ]);
@ -46,9 +38,9 @@ function User_tshirt_score($userId)
$result_worklog = DB::selectOne(' $result_worklog = DB::selectOne('
SELECT SUM(`work_hours`) AS `tshirt_score` SELECT SUM(`work_hours`) AS `tshirt_score`
FROM `User` FROM `users`
LEFT JOIN `UserWorkLog` ON `User`.`UID` = `UserWorkLog`.`user_id` LEFT JOIN `UserWorkLog` ON `users`.`id` = `UserWorkLog`.`user_id`
WHERE `User`.`UID` = ? WHERE `users`.`id` = ?
AND `UserWorkLog`.`work_timestamp` < ? AND `UserWorkLog`.`work_timestamp` < ?
', [ ', [
$userId, $userId,
@ -61,181 +53,6 @@ function User_tshirt_score($userId)
return $result_shifts['tshirt_score'] + $result_worklog['tshirt_score']; return $result_shifts['tshirt_score'] + $result_worklog['tshirt_score'];
} }
/**
* Update user.
*
* @param array $user
*/
function User_update($user)
{
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'],
(int)$user['email_shiftinfo'],
(int)$user['email_by_human_allowed'],
$user['jabber'],
$user['Size'],
$user['Gekommen'],
$user['Aktiv'],
(int)$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 int
*/
function User_force_active_count()
{
$result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `force_active` = 1');
if (empty($result)) {
return 0;
}
return (int)array_shift($result);
}
/**
* @return int
*/
function User_active_count()
{
$result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `Aktiv` = 1');
if (empty($result)) {
return 0;
}
return (int)array_shift($result);
}
/**
* @return int
*/
function User_got_voucher_count()
{
$result = DB::selectOne('SELECT SUM(`got_voucher`) FROM `User`');
if (empty($result)) {
return 0;
}
return (int)array_shift($result);
}
/**
* @return int
*/
function User_arrived_count()
{
$result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `Gekommen` = 1');
if (empty($result)) {
return 0;
}
return (int)array_shift($result);
}
/**
* @return int
*/
function User_tshirts_count()
{
$result = DB::selectOne('SELECT COUNT(*) FROM `User` WHERE `Tshirt` = 1');
if (empty($result)) {
return 0;
}
return (int)array_shift($result);
}
/**
* Returns all column names for sorting in an array.
*
* @return array
*/
function User_sortable_columns()
{
return [
'Nick',
'Name',
'Vorname',
'Alter',
'DECT',
'email',
'Size',
'Gekommen',
'Aktiv',
'force_active',
'Tshirt',
'lastLogIn'
];
}
/**
* Get all users, ordered by Nick by default or by given param.
*
* @param string $order_by
* @return array
*/
function Users($order_by = 'Nick')
{
return DB::select(sprintf('
SELECT *
FROM `User`
ORDER BY `%s` ASC
',
trim(DB::getPdo()->quote($order_by), '\'')
));
}
/** /**
* Returns true if user is freeloader * Returns true if user is freeloader
* *
@ -251,60 +68,43 @@ function User_is_freeloader($user)
* Returns all users that are not member of given angeltype. * Returns all users that are not member of given angeltype.
* *
* @param array $angeltype Angeltype * @param array $angeltype Angeltype
* @return array[] * @return User[]
*/ */
function Users_by_angeltype_inverted($angeltype) function Users_by_angeltype_inverted($angeltype)
{ {
return DB::select(' return User::query()
SELECT `User`.* ->leftJoin('UserAngelTypes', 'users.id', '=', 'UserAngelTypes.user_id')
FROM `User` ->leftJoin('UserAngelTypes', function ($query) use ($angeltype) {
LEFT JOIN `UserAngelTypes` /** @var JoinClause $query */
ON (`User`.`UID`=`UserAngelTypes`.`user_id` AND `angeltype_id`=?) $query
WHERE `UserAngelTypes`.`id` IS NULL ->on('users.id', '=', 'UserAngelTypes.user_id')
ORDER BY `Nick` ->on('UserAngelTypes.angeltype_id', '=', $angeltype['id']);
', })
[ ->whereNull('UserAngelTypes.id')
$angeltype['id'] ->orderBy('users.name')
] ->get('users.*');
);
} }
/** /**
* Returns all members of given angeltype. * Returns all members of given angeltype.
* *
* @param array $angeltype * @param array $angeltype
* @return array[] * @return User[]
*/ */
function Users_by_angeltype($angeltype) function Users_by_angeltype($angeltype)
{ {
return DB::select(' return User::query()
SELECT ->join('UserAngelTypes', 'users.id', '=', 'UserAngelTypes.user_id')
`User`.*, ->leftJoin('UserDriverLicenses', 'users.id', '=', 'UserDriverLicenses.user_id')
`UserAngelTypes`.`id` AS `user_angeltype_id`, ->where('UserAngelTypes.angeltype_id', '=', $angeltype['id'])
`UserAngelTypes`.`confirm_user_id`, ->get([
`UserAngelTypes`.`supporter`, 'users.*',
(`UserDriverLicenses`.`user_id` IS NOT NULL) AS `wants_to_drive`, '`UserAngelTypes`.`id` AS `user_angeltype_id`',
`UserDriverLicenses`.* '`UserAngelTypes`.`confirm_user_id`',
FROM `User` '`UserAngelTypes`.`supporter`',
JOIN `UserAngelTypes` ON `User`.`UID`=`UserAngelTypes`.`user_id` '(`UserDriverLicenses`.`user_id` IS NOT NULL) AS `wants_to_drive`',
LEFT JOIN `UserDriverLicenses` ON `User`.`UID`=`UserDriverLicenses`.`user_id` '`UserDriverLicenses`.*',
WHERE `UserAngelTypes`.`angeltype_id`=? ]);
ORDER BY `Nick`
',
[
$angeltype['id']
]
);
}
/**
* Returns User id array
*
* @return array[]
*/
function User_ids()
{
return DB::select('SELECT `UID` FROM `User`');
} }
/** /**
@ -331,22 +131,6 @@ function User_validate_mail($mail)
return new ValidationResult(check_email($mail), $mail); return new ValidationResult(check_email($mail), $mail);
} }
/**
* Validate user jabber address
*
* @param string $jabber Jabber-ID to validate
* @return ValidationResult
*/
function User_validate_jabber($jabber)
{
$jabber = strip_item($jabber);
if ($jabber == '') {
// Empty is ok
return new ValidationResult(true, '');
}
return new ValidationResult(check_email($jabber), $jabber);
}
/** /**
* Validate the planned arrival date * Validate the planned arrival date
* *
@ -417,45 +201,6 @@ function User_validate_planned_departure_date($planned_arrival_date, $planned_de
return new ValidationResult(true, $planned_departure_date); return new ValidationResult(true, $planned_departure_date);
} }
/**
* Returns User by api_key.
*
* @param string $api_key User api key
* @return array|null Matching user, null if not found
*/
function User_by_api_key($api_key)
{
$user = DB::selectOne('SELECT * FROM `User` WHERE `api_key`=? LIMIT 1', [$api_key]);
return empty($user) ? null : $user;
}
/**
* Returns User by email.
*
* @param string $email
* @return array|null Matching user, null when not found
*/
function User_by_email($email)
{
$user = DB::selectOne('SELECT * FROM `User` WHERE `email`=? LIMIT 1', [$email]);
return empty($user) ? null : $user;
}
/**
* Returns User by password token.
*
* @param string $token
* @return array|null Matching user, null when not found
*/
function User_by_password_recovery_token($token)
{
$user = DB::selectOne('SELECT * FROM `User` WHERE `password_recovery_token`=? LIMIT 1', [$token]);
return empty($user) ? null : $user;
}
/** /**
* Generates a new api key for given user. * Generates a new api key for given user.
* *
@ -475,27 +220,18 @@ function User_reset_api_key($user, $log = true)
/** /**
* Generates a new password recovery token for given user. * Generates a new password recovery token for given user.
* *
* @param array $user * @param User $user
* @return string * @return string
*/ */
function User_generate_password_recovery_token(&$user) function User_generate_password_recovery_token($user)
{ {
$user['password_recovery_token'] = md5($user['Nick'] . time() . rand()); $reset = PasswordReset::findOrNew($user->id);
DB::update(' $reset->token = md5($user->name . time() . rand());
UPDATE `User` $reset->save();
SET `password_recovery_token`=?
WHERE `UID`=?
LIMIT 1
',
[
$user['password_recovery_token'],
$user['UID'],
]
);
engelsystem_log('Password recovery for ' . User_Nick_render($user) . ' started.'); engelsystem_log('Password recovery for ' . User_Nick_render($user) . ' started.');
return $user['password_recovery_token']; return $reset->token;
} }
/** /**

View File

@ -1,6 +1,6 @@
<?php <?php
use Engelsystem\Database\DB; use Engelsystem\Models\User\State;
use Engelsystem\Models\User\User; use Engelsystem\Models\User\User;
/** /**
@ -22,7 +22,7 @@ function admin_active()
$msg = ''; $msg = '';
$search = ''; $search = '';
$forced_count = count(DB::select('SELECT `UID` FROM `User` WHERE `force_active`=1')); $forced_count = State::whereForceActive(true)->count();
$count = $forced_count; $count = $forced_count;
$limit = ''; $limit = '';
$set_active = ''; $set_active = '';
@ -54,21 +54,26 @@ function admin_active()
$limit = ' LIMIT ' . $count; $limit = ' LIMIT ' . $count;
} }
if ($request->has('ack')) { if ($request->has('ack')) {
DB::update('UPDATE `User` SET `Aktiv` = 0 WHERE `Tshirt` = 0'); State::query()
$users = DB::select(sprintf(' ->where('got_shirt', '=', false)
->update(['active' => false]);
/** @var User[] $users */
$users = User::query()->raw(sprintf('
SELECT SELECT
`User`.*, `users`.*,
COUNT(`ShiftEntry`.`id`) AS `shift_count`, COUNT(`ShiftEntry`.`id`) AS `shift_count`,
(%s + ( (%s + (
SELECT COALESCE(SUM(`work_hours`) * 3600, 0) FROM `UserWorkLog` WHERE `user_id`=`User`.`UID` SELECT COALESCE(SUM(`work_hours`) * 3600, 0) FROM `UserWorkLog` WHERE `user_id`=`users`.`id`
AND `work_timestamp` < %s AND `work_timestamp` < %s
)) AS `shift_length` )) AS `shift_length`
FROM `User` FROM `users`
LEFT JOIN `ShiftEntry` ON `User`.`UID` = `ShiftEntry`.`UID` LEFT JOIN `ShiftEntry` ON `users`.`id` = `ShiftEntry`.`UID`
LEFT JOIN `Shifts` ON `ShiftEntry`.`SID` = `Shifts`.`SID` LEFT JOIN `Shifts` ON `ShiftEntry`.`SID` = `Shifts`.`SID`
WHERE `User`.`Gekommen` = 1 LEFT JOIN `users_state` ON `users`.`id` = `users_state`.`user_id`
AND `User`.`force_active`=0 WHERE `users_state`.`arrived` = 1
GROUP BY `User`.`UID` AND `users_state`.`force_active` = 0
GROUP BY `users`.`id`
ORDER BY `force_active` DESC, `shift_length` DESC ORDER BY `force_active` DESC, `shift_length` DESC
%s %s
', ',
@ -78,10 +83,12 @@ function admin_active()
)); ));
$user_nicks = []; $user_nicks = [];
foreach ($users as $usr) { foreach ($users as $usr) {
DB::update('UPDATE `User` SET `Aktiv` = 1 WHERE `UID`=?', [$usr['UID']]); $usr->state->active = true;
$usr->state->save();
$user_nicks[] = User_Nick_render($usr); $user_nicks[] = User_Nick_render($usr);
} }
DB::update('UPDATE `User` SET `Aktiv`=1 WHERE `force_active`=TRUE');
State::whereForceActive(true)->update(['active' => 'true']);
engelsystem_log('These angels are active now: ' . join(', ', $user_nicks)); engelsystem_log('These angels are active now: ' . join(', ', $user_nicks));
$limit = ''; $limit = '';
@ -103,7 +110,8 @@ function admin_active()
$user_id = $request->input('active'); $user_id = $request->input('active');
$user_source = User::find($user_id); $user_source = User::find($user_id);
if ($user_source) { if ($user_source) {
DB::update('UPDATE `User` SET `Aktiv`=1 WHERE `UID`=? LIMIT 1', [$user_id]); $user_source->state->active = true;
$user_source->state->save();
engelsystem_log('User ' . User_Nick_render($user_source) . ' is active now.'); engelsystem_log('User ' . User_Nick_render($user_source) . ' is active now.');
$msg = success(__('Angel has been marked as active.'), true); $msg = success(__('Angel has been marked as active.'), true);
} else { } else {
@ -113,7 +121,8 @@ function admin_active()
$user_id = $request->input('not_active'); $user_id = $request->input('not_active');
$user_source = User::find($user_id); $user_source = User::find($user_id);
if (!$user_source) { if (!$user_source) {
DB::update('UPDATE `User` SET `Aktiv`=0 WHERE `UID`=? LIMIT 1', [$user_id]); $user_source->state->active = false;
$user_source->state->save();
engelsystem_log('User ' . User_Nick_render($user_source) . ' is NOT active now.'); engelsystem_log('User ' . User_Nick_render($user_source) . ' is NOT active now.');
$msg = success(__('Angel has been marked as not active.'), true); $msg = success(__('Angel has been marked as not active.'), true);
} else { } else {
@ -123,7 +132,8 @@ function admin_active()
$user_id = $request->input('tshirt'); $user_id = $request->input('tshirt');
$user_source = User::find($user_id); $user_source = User::find($user_id);
if (!$user_source) { if (!$user_source) {
DB::update('UPDATE `User` SET `Tshirt`=1 WHERE `UID`=? LIMIT 1', [$user_id]); $user_source->state->got_shirt = true;
$user_source->state->save();
engelsystem_log('User ' . User_Nick_render($user_source) . ' has tshirt now.'); engelsystem_log('User ' . User_Nick_render($user_source) . ' has tshirt now.');
$msg = success(__('Angel has got a t-shirt.'), true); $msg = success(__('Angel has got a t-shirt.'), true);
} else { } else {
@ -133,7 +143,8 @@ function admin_active()
$user_id = $request->input('not_tshirt'); $user_id = $request->input('not_tshirt');
$user_source = User::find($user_id); $user_source = User::find($user_id);
if (!$user_source) { if (!$user_source) {
DB::update('UPDATE `User` SET `Tshirt`=0 WHERE `UID`=? LIMIT 1', [$user_id]); $user_source->state->got_shirt = false;
$user_source->state->save();
engelsystem_log('User ' . User_Nick_render($user_source) . ' has NO tshirt.'); engelsystem_log('User ' . User_Nick_render($user_source) . ' has NO tshirt.');
$msg = success(__('Angel has got no t-shirt.'), true); $msg = success(__('Angel has got no t-shirt.'), true);
} else { } else {
@ -141,20 +152,22 @@ function admin_active()
} }
} }
$users = DB::select(sprintf(' $users = User::query()->raw(sprintf('
SELECT SELECT
`User`.*, `users`.*,
COUNT(`ShiftEntry`.`id`) AS `shift_count`, COUNT(`ShiftEntry`.`id`) AS `shift_count`,
(%s + ( (%s + (
SELECT COALESCE(SUM(`work_hours`) * 3600, 0) FROM `UserWorkLog` WHERE `user_id`=`User`.`UID` SELECT COALESCE(SUM(`work_hours`) * 3600, 0) FROM `UserWorkLog` WHERE `user_id`=`users`.`id`
AND `work_timestamp` < %s AND `work_timestamp` < %s
)) AS `shift_length` )) AS `shift_length`
FROM `User` LEFT JOIN `ShiftEntry` ON `User`.`UID` = `ShiftEntry`.`UID` FROM `users`
LEFT JOIN `users_state` ON `users`.`id` = `users_state`.`user_id`
LEFT JOIN `ShiftEntry` ON `users`.`id` = `ShiftEntry`.`UID`
LEFT JOIN `Shifts` ON `ShiftEntry`.`SID` = `Shifts`.`SID` ' LEFT JOIN `Shifts` ON `ShiftEntry`.`SID` = `Shifts`.`SID` '
. ($show_all_shifts ? '' : 'AND (`Shifts`.`end` < ' . time() . " OR `Shifts`.`end` IS NULL)") . ' . ($show_all_shifts ? '' : 'AND (`Shifts`.`end` < ' . time() . " OR `Shifts`.`end` IS NULL)") . '
WHERE `User`.`Gekommen` = 1 WHERE `users_state`.`arrived` = 1
GROUP BY `User`.`UID` GROUP BY `users`.`id`
ORDER BY `force_active` DESC, `shift_length` DESC ORDER BY `users_state`.`force_active` DESC, `shift_length` DESC
%s %s
', ',
$shift_sum_formula, $shift_sum_formula,
@ -167,11 +180,11 @@ function admin_active()
} else { } else {
$tokens = explode(' ', $search); $tokens = explode(' ', $search);
} }
foreach ($users as &$usr) { foreach ($users as $usr) {
if (count($tokens) > 0) { if (count($tokens) > 0) {
$match = false; $match = false;
foreach ($tokens as $t) { foreach ($tokens as $t) {
if (stristr($usr['Nick'], trim($t))) { if (stristr($usr->name, trim($t))) {
$match = true; $match = true;
break; break;
} }
@ -180,18 +193,20 @@ function admin_active()
continue; continue;
} }
} }
$usr['nick'] = User_Nick_render($usr);
$usr['shirt_size'] = $tshirt_sizes[$usr['Size']]; $userData = [];
$usr['work_time'] = round($usr['shift_length'] / 60) $userData['nick'] = User_Nick_render($usr);
$userData['shirt_size'] = $tshirt_sizes[$usr->personalData->shirt_size];
$userData['work_time'] = round($usr['shift_length'] / 60)
. ' min (' . sprintf('%.2f', $usr['shift_length'] / 3600) . '&nbsp;h)'; . ' min (' . sprintf('%.2f', $usr['shift_length'] / 3600) . '&nbsp;h)';
$usr['active'] = glyph_bool($usr['Aktiv'] == 1); $userData['active'] = glyph_bool($usr->state->active == 1);
$usr['force_active'] = glyph_bool($usr['force_active'] == 1); $userData['force_active'] = glyph_bool($usr->state->force_active == 1);
$usr['tshirt'] = glyph_bool($usr['Tshirt'] == 1); $userData['tshirt'] = glyph_bool($usr->state->got_shirt == 1);
$actions = []; $actions = [];
if ($usr['Aktiv'] == 0) { if (!$usr->state->active) {
$parameters = [ $parameters = [
'active' => $usr['UID'], 'active' => $usr->id,
'search' => $search, 'search' => $search,
]; ];
if ($show_all_shifts) { if ($show_all_shifts) {
@ -201,9 +216,9 @@ function admin_active()
. __('set active') . __('set active')
. '</a>'; . '</a>';
} }
if ($usr['Aktiv'] == 1) { if ($usr->state->active) {
$parametersRemove = [ $parametersRemove = [
'not_active' => $usr['UID'], 'not_active' => $usr->id,
'search' => $search, 'search' => $search,
]; ];
if ($show_all_shifts) { if ($show_all_shifts) {
@ -213,9 +228,9 @@ function admin_active()
. __('remove active') . __('remove active')
. '</a>'; . '</a>';
} }
if ($usr['Tshirt'] == 0) { if (!$usr->state->got_shirt) {
$parametersShirt = [ $parametersShirt = [
'tshirt' => $usr['UID'], 'tshirt' => $usr->id,
'search' => $search, 'search' => $search,
]; ];
if ($show_all_shifts) { if ($show_all_shifts) {
@ -225,9 +240,9 @@ function admin_active()
. __('got t-shirt') . __('got t-shirt')
. '</a>'; . '</a>';
} }
if ($usr['Tshirt'] == 1) { if ($usr->state->got_shirt) {
$parameters = [ $parameters = [
'not_tshirt' => $usr['UID'], 'not_tshirt' => $usr->id,
'search' => $search, 'search' => $search,
]; ];
if ($show_all_shifts) { if ($show_all_shifts) {
@ -238,30 +253,27 @@ function admin_active()
. '</a>'; . '</a>';
} }
$usr['actions'] = join(' ', $actions); $userData['actions'] = join(' ', $actions);
$matched_users[] = $usr; $matched_users[] = $userData;
} }
$shirt_statistics = []; $shirt_statistics = [];
foreach (array_keys($tshirt_sizes) as $size) { foreach (array_keys($tshirt_sizes) as $size) {
$gc = DB::selectOne( $gc = State::query()
'SELECT count(*) FROM `User` WHERE `Size`=? AND `Tshirt`=1', ->leftJoin('users_settings', 'users_state.user_id', '=', 'users_settings.user_id')
[$size] ->where('users_state.got_shirt', '=', true)
); ->where('users_personal_data.shirt_size', '=', $size)
$gc = array_shift($gc); ->count();
$shirt_statistics[] = [ $shirt_statistics[] = [
'size' => $size, 'size' => $size,
'given' => (int)$gc 'given' => $gc
]; ];
} }
$shirtCount = User_tshirts_count();
$shirt_statistics[] = [ $shirt_statistics[] = [
'size' => '<b>' . __('Sum') . '</b>', 'size' => '<b>' . __('Sum') . '</b>',
'given' => '<b>' . $shirtCount . '</b>' 'given' => '<b>' . State::whereGotShirt(true)->count() . '</b>'
]; ];
return page_with_title(admin_active_title(), [ return page_with_title(admin_active_title(), [

View File

@ -1,6 +1,5 @@
<?php <?php
use Engelsystem\Database\DB;
use Engelsystem\Models\User\User; use Engelsystem\Models\User\User;
/** /**
@ -29,12 +28,11 @@ function admin_arrive()
$user_id = $request->input('reset'); $user_id = $request->input('reset');
$user_source = User::find($user_id); $user_source = User::find($user_id);
if ($user_source) { if ($user_source) {
DB::update(' $user_source->state->arrived = false;
UPDATE `User` $user_source->state->save();
SET `Gekommen`=0, `arrival_date` = NULL $user_source->personalData->arrival_date = null;
WHERE `UID`=? $user_source->personalData->save();
LIMIT 1
', [$user_id]);
engelsystem_log('User set to not arrived: ' . User_Nick_render($user_source)); engelsystem_log('User set to not arrived: ' . User_Nick_render($user_source));
success(__('Reset done. Angel has not arrived.')); success(__('Reset done. Angel has not arrived.'));
redirect(user_link($user_source->id)); redirect(user_link($user_source->id));
@ -45,12 +43,11 @@ function admin_arrive()
$user_id = $request->input('arrived'); $user_id = $request->input('arrived');
$user_source = User::find($user_id); $user_source = User::find($user_id);
if ($user_source) { if ($user_source) {
DB::update(' $user_source->state->arrived = true;
UPDATE `User` $user_source->state->save();
SET `Gekommen`=1, `arrival_date`=? $user_source->personalData->arrival_date = new Carbon\Carbon();
WHERE `UID`=? $user_source->personalData->save();
LIMIT 1
', [time(), $user_id]);
engelsystem_log('User set has arrived: ' . User_Nick_render($user_source)); engelsystem_log('User set has arrived: ' . User_Nick_render($user_source));
success(__('Angel has been marked as arrived.')); success(__('Angel has been marked as arrived.'));
redirect(user_link($user_source->id)); redirect(user_link($user_source->id));
@ -59,7 +56,8 @@ function admin_arrive()
} }
} }
$users = DB::select('SELECT * FROM `User` ORDER BY `Nick`'); /** @var User[] $users */
$users = User::query()->orderBy('name')->get();
$arrival_count_at_day = []; $arrival_count_at_day = [];
$planned_arrival_count_at_day = []; $planned_arrival_count_at_day = [];
$planned_departure_count_at_day = []; $planned_departure_count_at_day = [];
@ -72,7 +70,7 @@ function admin_arrive()
foreach ($users as $usr) { foreach ($users as $usr) {
if (count($tokens) > 0) { if (count($tokens) > 0) {
$match = false; $match = false;
$index = join(' ', $usr); $index = join(' ', $usr->toArray());
foreach ($tokens as $t) { foreach ($tokens as $t) {
if (stristr($index, trim($t))) { if (stristr($index, trim($t))) {
$match = true; $match = true;
@ -84,43 +82,43 @@ function admin_arrive()
} }
} }
$usr['nick'] = User_Nick_render($usr); $usr->name = User_Nick_render($usr);
if (!is_null($usr['planned_departure_date'])) { if ($usr->personalData->planned_departure_date) {
$usr['rendered_planned_departure_date'] = date('Y-m-d', $usr['planned_departure_date']); $usr['rendered_planned_departure_date'] = $usr->personalData->planned_departure_date->format('Y-m-d');
} else { } else {
$usr['rendered_planned_departure_date'] = '-'; $usr['rendered_planned_departure_date'] = '-';
} }
$usr['rendered_planned_arrival_date'] = date('Y-m-d', $usr['planned_arrival_date']); $usr['rendered_planned_arrival_date'] = $usr->personalData->planned_arrival_date->format('Y-m-d');
$usr['rendered_arrival_date'] = $usr['arrival_date'] > 0 ? date('Y-m-d', $usr['arrival_date']) : '-'; $usr['rendered_arrival_date'] = $usr->personalData->arrival_date ? $usr->personalData->arrival_date->format('Y-m-d') : '-';
$usr['arrived'] = $usr['Gekommen'] == 1 ? __('yes') : ''; $usr['arrived'] = $usr->state->arrived ? __('yes') : '';
$usr['actions'] = $usr['Gekommen'] == 1 $usr['actions'] = $usr->state->arrived == 1
? '<a href="' . page_link_to( ? '<a href="' . page_link_to(
'admin_arrive', 'admin_arrive',
['reset' => $usr['UID'], 'search' => $search] ['reset' => $usr->id, 'search' => $search]
) . '">' . __('reset') . '</a>' ) . '">' . __('reset') . '</a>'
: '<a href="' . page_link_to( : '<a href="' . page_link_to(
'admin_arrive', 'admin_arrive',
['arrived' => $usr['UID'], 'search' => $search] ['arrived' => $usr->id, 'search' => $search]
) . '">' . __('arrived') . '</a>'; ) . '">' . __('arrived') . '</a>';
if ($usr['arrival_date'] > 0) { if ($usr->personalData->arrival_date) {
$day = date('Y-m-d', $usr['arrival_date']); $day = $usr->personalData->arrival_date->format('Y-m-d');
if (!isset($arrival_count_at_day[$day])) { if (!isset($arrival_count_at_day[$day])) {
$arrival_count_at_day[$day] = 0; $arrival_count_at_day[$day] = 0;
} }
$arrival_count_at_day[$day]++; $arrival_count_at_day[$day]++;
} }
if (!is_null($usr['planned_arrival_date'])) { if ($usr->personalData->planned_arrival_date) {
$day = date('Y-m-d', $usr['planned_arrival_date']); $day = $usr->personalData->planned_arrival_date->format('Y-m-d');
if (!isset($planned_arrival_count_at_day[$day])) { if (!isset($planned_arrival_count_at_day[$day])) {
$planned_arrival_count_at_day[$day] = 0; $planned_arrival_count_at_day[$day] = 0;
} }
$planned_arrival_count_at_day[$day]++; $planned_arrival_count_at_day[$day]++;
} }
if (!is_null($usr['planned_departure_date']) && $usr['Gekommen'] == 1) { if ($usr->personalData->planned_departure_date && $usr->state->arrived) {
$day = date('Y-m-d', $usr['planned_departure_date']); $day = $usr->personalData->planned_departure_date->format('Y-m-d');
if (!isset($planned_departure_count_at_day[$day])) { if (!isset($planned_departure_count_at_day[$day])) {
$planned_departure_count_at_day[$day] = 0; $planned_departure_count_at_day[$day] = 0;
} }

View File

@ -1,6 +1,7 @@
<?php <?php
use Engelsystem\Database\DB; use Engelsystem\Database\DB;
use Engelsystem\Models\User\User;
/** /**
* @return string * @return string
@ -28,7 +29,7 @@ function admin_free()
if (!empty($angelType)) { if (!empty($angelType)) {
$angelTypeSearch = ' INNER JOIN `UserAngelTypes` ON (`UserAngelTypes`.`angeltype_id` = ' $angelTypeSearch = ' INNER JOIN `UserAngelTypes` ON (`UserAngelTypes`.`angeltype_id` = '
. DB::getPdo()->quote($angelType) . DB::getPdo()->quote($angelType)
. ' AND `UserAngelTypes`.`user_id` = `User`.`UID`'; . ' AND `UserAngelTypes`.`user_id` = `users`.`id`';
if ($request->has('confirmed_only')) { if ($request->has('confirmed_only')) {
$angelTypeSearch .= ' AND `UserAngelTypes`.`confirm_user_id`'; $angelTypeSearch .= ' AND `UserAngelTypes`.`confirm_user_id`';
} }
@ -43,26 +44,25 @@ function admin_free()
$angel_types[$angel_type['id']] = $angel_type['name']; $angel_types[$angel_type['id']] = $angel_type['name'];
} }
$users = DB::select(' /** @var User[] $users */
SELECT `User`.* $users = User::query()->raw(sprintf('
FROM `User` SELECT `users`.*
' . $angelTypeSearch . ' FROM `users`
LEFT JOIN `ShiftEntry` ON `User`.`UID` = `ShiftEntry`.`UID` %s
LEFT JOIN `ShiftEntry` ON `users`.`id` = `ShiftEntry`.`UID`
LEFT JOIN `users_state` ON `users`.`id` = `users_state`.`user_id`
LEFT JOIN `Shifts` LEFT JOIN `Shifts`
ON ( ON (
`ShiftEntry`.`SID` = `Shifts`.`SID` `ShiftEntry`.`SID` = `Shifts`.`SID`
AND `Shifts`.`start` < ? AND `Shifts`.`start` < %u
AND `Shifts`.`end` > ? AND `Shifts`.`end` > %u
) )
WHERE `User`.`Gekommen` = 1 WHERE `users_state`.`arrived` = 1
AND `Shifts`.`SID` IS NULL AND `Shifts`.`SID` IS NULL
GROUP BY `User`.`UID` GROUP BY `users`.`id`
ORDER BY `Nick` ORDER BY `users`
', ', $angelTypeSearch, time(), time()
[ )
time(),
time(),
]
); );
$free_users_table = []; $free_users_table = [];
@ -74,7 +74,7 @@ function admin_free()
foreach ($users as $usr) { foreach ($users as $usr) {
if (count($tokens) > 0) { if (count($tokens) > 0) {
$match = false; $match = false;
$index = join('', $usr); $index = join('', $usr->toArray());
foreach ($tokens as $t) { foreach ($tokens as $t) {
if (stristr($index, trim($t))) { if (stristr($index, trim($t))) {
$match = true; $match = true;
@ -89,12 +89,11 @@ function admin_free()
$free_users_table[] = [ $free_users_table[] = [
'name' => User_Nick_render($usr), 'name' => User_Nick_render($usr),
'shift_state' => User_shift_state_render($usr), 'shift_state' => User_shift_state_render($usr),
'dect' => $usr['DECT'], 'dect' => $usr->contact->dect,
'jabber' => $usr['jabber'], 'email' => $usr->settings->email_human ? ($usr->contact->email ? $usr->contact->email : $usr->email) : glyph('eye-close'),
'email' => $usr['email_by_human_allowed'] ? $usr['email'] : glyph('eye-close'),
'actions' => 'actions' =>
in_array('admin_user', $privileges) 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->id]), __('edit'), 'btn-xs')
: '' : ''
]; ];
} }
@ -119,7 +118,6 @@ function admin_free()
'name' => __('Nick'), 'name' => __('Nick'),
'shift_state' => '', 'shift_state' => '',
'dect' => __('DECT'), 'dect' => __('DECT'),
'jabber' => __('Jabber'),
'email' => __('E-Mail'), 'email' => __('E-Mail'),
'actions' => '' 'actions' => ''
], $free_users_table) ], $free_users_table)

View File

@ -431,7 +431,7 @@ function guest_login()
if ($request->has('submit')) { if ($request->has('submit')) {
if ($request->has('nick') && strlen(User_validate_Nick($request->input('nick'))) > 0) { if ($request->has('nick') && strlen(User_validate_Nick($request->input('nick'))) > 0) {
$nick = User_validate_Nick($request->input('nick')); $nick = User_validate_Nick($request->input('nick'));
$login_user = User::whereName($nick); $login_user = User::whereName($nick)->first();
if ($login_user) { if ($login_user) {
if ($request->has('password')) { if ($request->has('password')) {
if (!verify_password($request->postData('password'), $login_user->password, $login_user->id)) { if (!verify_password($request->postData('password'), $login_user->password, $login_user->id)) {

View File

@ -7,19 +7,17 @@ use Engelsystem\Database\DB;
*/ */
function user_atom() function user_atom()
{ {
global $user;
$request = request(); $request = request();
if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) { if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) {
engelsystem_error('Missing key.'); engelsystem_error('Missing key.');
} }
$key = $request->input('key');
$user = User_by_api_key($key); $user = auth()->apiUser('key');
if (empty($user)) { if (empty($user)) {
engelsystem_error('Key invalid.'); engelsystem_error('Key invalid.');
} }
if (!in_array('atom', privileges_for_user($user['UID']))) { if (!in_array('atom', privileges_for_user($user->id))) {
engelsystem_error('No privilege for atom.'); engelsystem_error('No privilege for atom.');
} }

View File

@ -5,20 +5,17 @@
*/ */
function user_ical() function user_ical()
{ {
global $user;
$request = request(); $request = request();
if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) { if (!$request->has('key') || !preg_match('/^[\da-f]{32}$/', $request->input('key'))) {
engelsystem_error('Missing key.'); engelsystem_error('Missing key.');
} }
$key = $request->input('key');
$user = User_by_api_key($key); $user = auth()->apiUser('key');
if (empty($user)) { if (!$user) {
engelsystem_error('Key invalid.'); engelsystem_error('Key invalid.');
} }
if (!in_array('ical', privileges_for_user($user->id))) {
if (!in_array('ical', privileges_for_user($user['UID']))) {
engelsystem_error('No privilege for ical.'); engelsystem_error('No privilege for ical.');
} }

View File

@ -39,17 +39,18 @@ function user_messages()
$request = request(); $request = request();
if (!$request->has('action')) { if (!$request->has('action')) {
$users = DB::select( /** @var User[] $users */
'SELECT `UID`, `Nick` FROM `User` WHERE NOT `UID`=? ORDER BY `Nick`', $users = User::query()
[$user->id] ->whereKeyNot($user->id)
); ->orderBy('name')
->get(['id', 'name']);
$to_select_data = [ $to_select_data = [
'' => __('Select recipient...') '' => __('Select recipient...')
]; ];
foreach ($users as $u) { foreach ($users as $u) {
$to_select_data[$u['UID']] = $u['Nick']; $to_select_data[$u->id] = $u->name;
} }
$to_select = html_select_key('to', 'to', $to_select_data, ''); $to_select = html_select_key('to', 'to', $to_select_data, '');

View File

@ -1,7 +1,7 @@
<?php <?php
use Carbon\Carbon; use Carbon\Carbon;
use Engelsystem\Database\DB; use Engelsystem\Models\User\User;
/** /**
* @return string * @return string
@ -14,10 +14,10 @@ function settings_title()
/** /**
* Change user main attributes (name, dates, etc.) * Change user main attributes (name, dates, etc.)
* *
* @param array $user_source The user * @param User $user_source The user
* @param bool $enable_tshirt_size * @param bool $enable_tshirt_size
* @param array $tshirt_sizes * @param array $tshirt_sizes
* @return array * @return User
*/ */
function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes) function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes)
{ {
@ -26,7 +26,7 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes)
if ($request->has('mail')) { if ($request->has('mail')) {
$result = User_validate_mail($request->input('mail')); $result = User_validate_mail($request->input('mail'));
$user_source['email'] = $result->getValue(); $user_source->email = $result->getValue();
if (!$result->isValid()) { if (!$result->isValid()) {
$valid = false; $valid = false;
error(__('E-mail address is not correct.')); error(__('E-mail address is not correct.'));
@ -36,20 +36,11 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes)
error(__('Please enter your e-mail.')); error(__('Please enter your e-mail.'));
} }
$user_source['email_shiftinfo'] = $request->has('email_shiftinfo'); $user_source->settings->email_shiftinfo = $request->has('email_shiftinfo');
$user_source['email_by_human_allowed'] = $request->has('email_by_human_allowed'); $user_source->settings->email_human = $request->has('email_by_human_allowed');
if ($request->has('jabber')) {
$result = User_validate_jabber($request->input('jabber'));
$user_source['jabber'] = $result->getValue();
if (!$result->isValid()) {
$valid = false;
error(__('Please check your jabber account information.'));
}
}
if ($request->has('tshirt_size') && isset($tshirt_sizes[$request->input('tshirt_size')])) { if ($request->has('tshirt_size') && isset($tshirt_sizes[$request->input('tshirt_size')])) {
$user_source['Size'] = $request->input('tshirt_size'); $user_source->personalData->shirt_size = $request->input('tshirt_size');
} elseif ($enable_tshirt_size) { } elseif ($enable_tshirt_size) {
$valid = false; $valid = false;
} }
@ -57,7 +48,7 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes)
if ($request->has('planned_arrival_date')) { if ($request->has('planned_arrival_date')) {
$tmp = parse_date('Y-m-d H:i', $request->input('planned_arrival_date') . ' 00:00'); $tmp = parse_date('Y-m-d H:i', $request->input('planned_arrival_date') . ' 00:00');
$result = User_validate_planned_arrival_date($tmp); $result = User_validate_planned_arrival_date($tmp);
$user_source['planned_arrival_date'] = $result->getValue(); $user_source->personalData->planned_arrival_date = Carbon::createFromTimestamp($result->getValue());
if (!$result->isValid()) { if (!$result->isValid()) {
$valid = false; $valid = false;
error(__('Please enter your planned date of arrival. It should be after the buildup start date and before teardown end date.')); error(__('Please enter your planned date of arrival. It should be after the buildup start date and before teardown end date.'));
@ -66,8 +57,8 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes)
if ($request->has('planned_departure_date')) { if ($request->has('planned_departure_date')) {
$tmp = parse_date('Y-m-d H:i', $request->input('planned_departure_date') . ' 00:00'); $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); $result = User_validate_planned_departure_date($user_source->personalData->arrival_date->getTimestamp(), $tmp);
$user_source['planned_departure_date'] = $result->getValue(); $user_source->personalData->planned_departure_date = Carbon::createFromTimestamp($result->getValue());
if (!$result->isValid()) { if (!$result->isValid()) {
$valid = false; $valid = false;
error(__('Please enter your planned date of departure. It should be after your planned arrival date and after buildup start date and before teardown end date.')); error(__('Please enter your planned date of departure. It should be after your planned arrival date and after buildup start date and before teardown end date.'));
@ -75,21 +66,21 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes)
} }
// Trivia // Trivia
$user_source['Name'] = strip_request_item('lastname', $user_source['Name']); $user_source->name = strip_request_item('lastname', $user_source['Name']);
$user_source['Vorname'] = strip_request_item('prename', $user_source['Vorname']); $user_source->personalData->first_name = strip_request_item('prename', $user_source['Vorname']);
$user_source['Alter'] = strip_request_item('age', $user_source['Alter']);
$user_source['Telefon'] = strip_request_item('tel', $user_source['Telefon']);
if (strlen(strip_request_item('dect')) <= 5) { if (strlen(strip_request_item('dect')) <= 5) {
$user_source['DECT'] = strip_request_item('dect', $user_source['DECT']); $user_source->contact->dect = strip_request_item('dect', $user_source['DECT']);
} else { } else {
$valid = false; $valid = false;
error(__('For dect numbers are only 5 digits allowed.')); error(__('For dect numbers are only 5 digits allowed.'));
} }
$user_source['Handy'] = strip_request_item('mobile', $user_source['Handy']); $user_source->contact->mobile = strip_request_item('mobile', $user_source['Handy']);
$user_source['Hometown'] = strip_request_item('hometown', $user_source['Hometown']);
if ($valid) { if ($valid) {
User_update($user_source); $user_source->save();
$user_source->contact->save();
$user_source->personalData->save();
$user_source->settings->save();
success(__('Settings saved.')); success(__('Settings saved.'));
redirect(page_link_to('user_settings')); redirect(page_link_to('user_settings'));
@ -101,14 +92,14 @@ function user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes)
/** /**
* Change user password. * Change user password.
* *
* @param array $user_source The user * @param User $user_source The user
*/ */
function user_settings_password($user_source) function user_settings_password($user_source)
{ {
$request = request(); $request = request();
if ( if (
!$request->has('password') !$request->has('password')
|| !verify_password($request->postData('password'), $user_source['Passwort'], $user_source['UID']) || !verify_password($request->postData('password'), $user_source->password, $user_source->id)
) { ) {
error(__('-> not OK. Please try again.')); error(__('-> not OK. Please try again.'));
} elseif (strlen($request->postData('new_password')) < config('min_password_length')) { } elseif (strlen($request->postData('new_password')) < config('min_password_length')) {
@ -116,7 +107,7 @@ function user_settings_password($user_source)
} elseif ($request->postData('new_password') != $request->postData('new_password2')) { } elseif ($request->postData('new_password') != $request->postData('new_password2')) {
error(__('Your passwords don\'t match.')); error(__('Your passwords don\'t match.'));
} else { } else {
set_password($user_source['UID'], $request->postData('new_password')); set_password($user_source->id, $request->postData('new_password'));
success(__('Password saved.')); success(__('Password saved.'));
} }
redirect(page_link_to('user_settings')); redirect(page_link_to('user_settings'));
@ -125,9 +116,9 @@ function user_settings_password($user_source)
/** /**
* Change user theme * Change user theme
* *
* @param array $user_source The user * @param User $user_source The user
* @param array $themes List of available themes * @param array $themes List of available themes
* @return array * @return User
*/ */
function user_settings_theme($user_source, $themes) function user_settings_theme($user_source, $themes)
{ {
@ -135,22 +126,13 @@ function user_settings_theme($user_source, $themes)
$request = request(); $request = request();
if ($request->has('theme') && isset($themes[$request->input('theme')])) { if ($request->has('theme') && isset($themes[$request->input('theme')])) {
$user_source['color'] = $request->input('theme'); $user_source->settings->theme = $request->input('theme');
} else { } else {
$valid = false; $valid = false;
} }
if ($valid) { if ($valid) {
DB::update(' $user_source->settings->save();
UPDATE `User`
SET `color`=?
WHERE `UID`=?
',
[
$user_source['color'],
$user_source['UID'],
]
);
success(__('Theme changed.')); success(__('Theme changed.'));
redirect(page_link_to('user_settings')); redirect(page_link_to('user_settings'));
@ -162,9 +144,9 @@ function user_settings_theme($user_source, $themes)
/** /**
* Change use locale * Change use locale
* *
* @param array $user_source The user * @param User $user_source The user
* @param array $locales List of available locales * @param array $locales List of available locales
* @return array * @return User
*/ */
function user_settings_locale($user_source, $locales) function user_settings_locale($user_source, $locales)
{ {
@ -173,23 +155,14 @@ function user_settings_locale($user_source, $locales)
$session = session(); $session = session();
if ($request->has('language') && isset($locales[$request->input('language')])) { if ($request->has('language') && isset($locales[$request->input('language')])) {
$user_source['Sprache'] = $request->input('language'); $user_source->settings->language = $request->input('language');
} else { } else {
$valid = false; $valid = false;
} }
if ($valid) { if ($valid) {
DB::update(' $user_source->settings->save();
UPDATE `User` $session->set('locale', $user_source->settings->language);
SET `Sprache`=?
WHERE `UID`=?
',
[
$user_source['Sprache'],
$user_source['UID'],
]
);
$session->set('locale', $user_source['Sprache']);
success('Language changed.'); success('Language changed.');
redirect(page_link_to('user_settings')); redirect(page_link_to('user_settings'));
@ -205,7 +178,6 @@ function user_settings_locale($user_source, $locales)
*/ */
function user_settings() function user_settings()
{ {
global $user;
$request = request(); $request = request();
$config = config(); $config = config();
$themes = config('available_themes'); $themes = config('available_themes');
@ -227,8 +199,7 @@ function user_settings()
$teardown_end_date = $teardown->getTimestamp(); $teardown_end_date = $teardown->getTimestamp();
} }
$user_source = $user; $user_source = auth()->user();
if ($request->has('submit')) { if ($request->has('submit')) {
$user_source = user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes); $user_source = user_settings_main($user_source, $enable_tshirt_size, $tshirt_sizes);
} elseif ($request->has('submit_password')) { } elseif ($request->has('submit_password')) {

View File

@ -1,31 +1,25 @@
<?php <?php
use Carbon\Carbon;
use Engelsystem\Database\DB; use Engelsystem\Database\DB;
use Engelsystem\Models\User\User;
/** /**
* Testet ob ein User eingeloggt ist und lädt die entsprechenden Privilegien * Testet ob ein User eingeloggt ist und lädt die entsprechenden Privilegien
*/ */
function load_auth() function load_auth()
{ {
global $user, $privileges; global $privileges;
$user = null;
$session = session(); $session = session();
if ($session->has('uid')) { if ($session->has('uid')) {
$user = DB::selectOne('SELECT * FROM `User` WHERE `UID`=? LIMIT 1', [$session->get('uid')]); $user = auth()->user();
if (!empty($user)) {
// User ist eingeloggt, Datensatz zur Verfügung stellen und Timestamp updaten if ($user) {
DB::update(' $user->last_login_at = new Carbon();
UPDATE `User` $user->save();
SET `lastLogIn` = ?
WHERE `UID` = ? $privileges = privileges_for_user($user->id);
LIMIT 1
', [
time(),
$session->get('uid'),
]);
$privileges = privileges_for_user($user['UID']);
return; return;
} }
@ -60,18 +54,9 @@ function generate_salt($length = 16)
*/ */
function set_password($uid, $password) function set_password($uid, $password)
{ {
DB::update(' $user = User::find($uid);
UPDATE `User` $user->password = crypt($password, config('crypt_alg') . '$' . generate_salt(16) . '$');
SET `Passwort` = ?, $user->save();
`password_recovery_token`=NULL
WHERE `UID` = ?
LIMIT 1
',
[
crypt($password, config('crypt_alg') . '$' . generate_salt(16) . '$'),
$uid
]
);
} }
/** /**
@ -103,19 +88,11 @@ function verify_password($password, $salt, $uid = null)
// let's update it! // let's update it!
// we duplicate the query from the above set_password() function to have the extra safety of checking // we duplicate the query from the above set_password() function to have the extra safety of checking
// the old hash // the old hash
DB::update(' $user = User::find($uid);
UPDATE `User` if ($user->password == $salt) {
SET `Passwort` = ? $user->password = crypt($password, $crypt_alg . '$' . generate_salt() . '$');
WHERE `UID` = ? $user->save();
AND `Passwort` = ? }
LIMIT 1
',
[
crypt($password, $crypt_alg . '$' . generate_salt() . '$'),
$uid,
$salt,
]
);
} }
return $correct; return $correct;
} }
@ -129,11 +106,11 @@ function privileges_for_user($user_id)
$privileges = []; $privileges = [];
$user_privileges = DB::select(' $user_privileges = DB::select('
SELECT `Privileges`.`name` SELECT `Privileges`.`name`
FROM `User` FROM `users`
JOIN `UserGroups` ON (`User`.`UID` = `UserGroups`.`uid`) JOIN `UserGroups` ON (`users`.`id` = `UserGroups`.`uid`)
JOIN `GroupPrivileges` ON (`UserGroups`.`group_id` = `GroupPrivileges`.`group_id`) JOIN `GroupPrivileges` ON (`UserGroups`.`group_id` = `GroupPrivileges`.`group_id`)
JOIN `Privileges` ON (`GroupPrivileges`.`privilege_id` = `Privileges`.`id`) JOIN `Privileges` ON (`GroupPrivileges`.`privilege_id` = `Privileges`.`id`)
WHERE `User`.`UID`=? WHERE `users`.`id`=?
', [$user_id]); ', [$user_id]);
foreach ($user_privileges as $user_privilege) { foreach ($user_privileges as $user_privilege) {
$privileges[] = $user_privilege['name']; $privileges[] = $user_privilege['name'];

View File

@ -190,10 +190,10 @@ function AngelType_view_buttons($angeltype, $user_angeltype, $admin_angeltypes,
/** /**
* Renders and sorts the members of an angeltype into supporters, members and unconfirmed members. * Renders and sorts the members of an angeltype into supporters, members and unconfirmed members.
* *
* @param array $angeltype * @param array $angeltype
* @param array $members * @param User[] $members
* @param bool $admin_user_angeltypes * @param bool $admin_user_angeltypes
* @param bool $admin_angeltypes * @param bool $admin_angeltypes
* @return array [supporters, members, unconfirmed members] * @return array [supporters, members, unconfirmed members]
*/ */
function AngelType_view_members($angeltype, $members, $admin_user_angeltypes, $admin_angeltypes) function AngelType_view_members($angeltype, $members, $admin_user_angeltypes, $admin_angeltypes)
@ -202,7 +202,7 @@ function AngelType_view_members($angeltype, $members, $admin_user_angeltypes, $a
$members_confirmed = []; $members_confirmed = [];
$members_unconfirmed = []; $members_unconfirmed = [];
foreach ($members as $member) { foreach ($members as $member) {
$member['Nick'] = User_Nick_render($member); $member->name = User_Nick_render($member);
if ($angeltype['requires_driver_license']) { if ($angeltype['requires_driver_license']) {
$member['wants_to_drive'] = glyph_bool($member['wants_to_drive']); $member['wants_to_drive'] = glyph_bool($member['wants_to_drive']);
$member['has_car'] = glyph_bool($member['has_car']); $member['has_car'] = glyph_bool($member['has_car']);
@ -317,7 +317,7 @@ function AngelType_view_table_headers($angeltype, $supporter, $admin_angeltypes)
* Render an angeltype page containing the member lists. * Render an angeltype page containing the member lists.
* *
* @param array $angeltype * @param array $angeltype
* @param array[] $members * @param User[] $members
* @param array $user_angeltype * @param array $user_angeltype
* @param bool $admin_user_angeltypes * @param bool $admin_user_angeltypes
* @param bool $admin_angeltypes * @param bool $admin_angeltypes
@ -380,11 +380,11 @@ function AngelType_view_shifts($angeltype, $shiftsFilterRenderer, $shiftCalendar
} }
/** /**
* @param array $angeltype * @param array $angeltype
* @param array $members * @param User[] $members
* @param bool $admin_user_angeltypes * @param bool $admin_user_angeltypes
* @param bool $admin_angeltypes * @param bool $admin_angeltypes
* @param bool $supporter * @param bool $supporter
* @return string HTML * @return string HTML
*/ */
function AngelType_view_info( function AngelType_view_info(

View File

@ -76,7 +76,7 @@ function ShiftEntry_delete_title()
* @param array $room * @param array $room
* @param array $angeltype * @param array $angeltype
* @param array $angeltypes_select * @param array $angeltypes_select
* @param array $signup_user * @param User $signup_user
* @param array $users_select * @param array $users_select
* @return string * @return string
*/ */
@ -90,7 +90,7 @@ function ShiftEntry_create_view_admin($shift, $room, $angeltype, $angeltypes_sel
info(__('Do you want to sign up the following user for this shift?'), true), info(__('Do you want to sign up the following user for this shift?'), true),
form([ form([
form_select('angeltype_id', __('Angeltype'), $angeltypes_select, $angeltype['id']), form_select('angeltype_id', __('Angeltype'), $angeltypes_select, $angeltype['id']),
form_select('user_id', __('User'), $users_select, $signup_user['UID']), form_select('user_id', __('User'), $users_select, $signup_user->id),
form_submit('submit', glyph('ok') . __('Save')) form_submit('submit', glyph('ok') . __('Save'))
]) ])
]); ]);

View File

@ -147,7 +147,7 @@ function UserAngelType_delete_view($user_angeltype, $user, $angeltype)
/** /**
* @param array $angeltype * @param array $angeltype
* @param array[] $users_source * @param User[] $users_source
* @param int $user_id * @param int $user_id
* @return string * @return string
*/ */
@ -155,7 +155,7 @@ function UserAngelType_add_view($angeltype, $users_source, $user_id)
{ {
$users = []; $users = [];
foreach ($users_source as $user_source) { foreach ($users_source as $user_source) {
$users[$user_source['UID']] = User_Nick_render($user_source); $users[$user_source->id] = User_Nick_render($user_source);
} }
return page_with_title(__('Add user to angeltype'), [ return page_with_title(__('Add user to angeltype'), [
@ -176,7 +176,7 @@ function UserAngelType_add_view($angeltype, $users_source, $user_id)
} }
/** /**
* @param array $user * @param User $user
* @param array $angeltype * @param array $angeltype
* @return string * @return string
*/ */
@ -194,7 +194,7 @@ function UserAngelType_join_view($user, $angeltype)
button( button(
page_link_to( page_link_to(
'user_angeltypes', 'user_angeltypes',
['action' => 'add', 'angeltype_id' => $angeltype['id'], 'user_id' => $user['UID'], 'confirmed' => 1] ['action' => 'add', 'angeltype_id' => $angeltype['id'], 'user_id' => $user->id, 'confirmed' => 1]
), ),
glyph('ok') . __('save'), glyph('ok') . __('save'),
'btn-primary' 'btn-primary'

View File

@ -6,7 +6,7 @@ use Engelsystem\Models\User\User;
/** /**
* Renders user settings page * Renders user settings page
* *
* @param array $user_source The user * @param User $user_source The user
* @param array $locales Available languages * @param array $locales Available languages
* @param array $themes Available themes * @param array $themes Available themes
* @param int $buildup_start_date Unix timestamp * @param int $buildup_start_date Unix timestamp
@ -24,6 +24,7 @@ function User_settings_view(
$enable_tshirt_size, $enable_tshirt_size,
$tshirt_sizes $tshirt_sizes
) { ) {
$personalData = $user_source->personalData;
return page_with_title(settings_title(), [ return page_with_title(settings_title(), [
msg(), msg(),
div('row', [ div('row', [
@ -31,48 +32,44 @@ function User_settings_view(
form([ form([
form_info('', __('Here you can change your user details.')), form_info('', __('Here you can change your user details.')),
form_info(entry_required() . ' = ' . __('Entry required!')), form_info(entry_required() . ' = ' . __('Entry required!')),
form_text('nick', __('Nick'), $user_source['Nick'], true), form_text('nick', __('Nick'), $user_source->name, true),
form_text('lastname', __('Last name'), $user_source['Name']), form_text('lastname', __('Last name'), $user_source->personalData->last_name),
form_text('prename', __('First name'), $user_source['Vorname']), form_text('prename', __('First name'), $user_source->personalData->first_name),
form_date( form_date(
'planned_arrival_date', 'planned_arrival_date',
__('Planned date of arrival') . ' ' . entry_required(), __('Planned date of arrival') . ' ' . entry_required(),
$user_source['planned_arrival_date'], $personalData->arrival_date ? $personalData->arrival_date->getTimestamp() : '',
$buildup_start_date, $buildup_start_date,
$teardown_end_date $teardown_end_date
), ),
form_date( form_date(
'planned_departure_date', 'planned_departure_date',
__('Planned date of departure'), __('Planned date of departure'),
$user_source['planned_departure_date'], $personalData->planned_departure_date ? $personalData->planned_departure_date->getTimestamp() : '',
$buildup_start_date, $buildup_start_date,
$teardown_end_date $teardown_end_date
), ),
form_text('age', __('Age'), $user_source['Alter']), form_text('dect', __('DECT'), $user_source->contact->dect),
form_text('tel', __('Phone'), $user_source['Telefon']), form_text('mobile', __('Mobile'), $user_source->contact->mobile),
form_text('dect', __('DECT'), $user_source['DECT']), form_text('mail', __('E-Mail') . ' ' . entry_required(), $user_source->contact->email),
form_text('mobile', __('Mobile'), $user_source['Handy']),
form_text('mail', __('E-Mail') . ' ' . entry_required(), $user_source['email']),
form_checkbox( form_checkbox(
'email_shiftinfo', 'email_shiftinfo',
__( __(
'The %s is allowed to send me an email (e.g. when my shifts change)', 'The %s is allowed to send me an email (e.g. when my shifts change)',
[config('app_name')] [config('app_name')]
), ),
$user_source['email_shiftinfo'] $user_source->settings->email_shiftinfo
), ),
form_checkbox( form_checkbox(
'email_by_human_allowed', 'email_by_human_allowed',
__('Humans are allowed to send me an email (e.g. for ticket vouchers)'), __('Humans are allowed to send me an email (e.g. for ticket vouchers)'),
$user_source['email_by_human_allowed'] $user_source->settings->email_human
), ),
form_text('jabber', __('Jabber'), $user_source['jabber']),
form_text('hometown', __('Hometown'), $user_source['Hometown']),
$enable_tshirt_size ? form_select( $enable_tshirt_size ? form_select(
'tshirt_size', 'tshirt_size',
__('Shirt size'), __('Shirt size'),
$tshirt_sizes, $tshirt_sizes,
$user_source['Size'], $user_source->personalData->shirt_size,
__('Please select...') __('Please select...')
) : '', ) : '',
form_info('', __('Please visit the angeltypes page to manage your angeltypes.')), form_info('', __('Please visit the angeltypes page to manage your angeltypes.')),
@ -89,12 +86,12 @@ function User_settings_view(
]), ]),
form([ form([
form_info(__('Here you can choose your color settings:')), form_info(__('Here you can choose your color settings:')),
form_select('theme', __('Color settings:'), $themes, $user_source['color']), form_select('theme', __('Color settings:'), $themes, $user_source->settings->theme),
form_submit('submit_theme', __('Save')) form_submit('submit_theme', __('Save'))
]), ]),
form([ form([
form_info(__('Here you can choose your language:')), form_info(__('Here you can choose your language:')),
form_select('language', __('Language:'), $locales, $user_source['Sprache']), form_select('language', __('Language:'), $locales, $user_source->settings->language),
form_submit('submit_language', __('Save')) form_submit('submit_language', __('Save'))
]) ])
]) ])
@ -194,14 +191,14 @@ function User_edit_vouchers_view($user)
} }
/** /**
* @param array[] $users * @param User[] $users
* @param string $order_by * @param string $order_by
* @param int $arrived_count * @param int $arrived_count
* @param int $active_count * @param int $active_count
* @param int $force_active_count * @param int $force_active_count
* @param int $freeloads_count * @param int $freeloads_count
* @param int $tshirts_count * @param int $tshirts_count
* @param int $voucher_count * @param int $voucher_count
* @return string * @return string
*/ */
function Users_view( function Users_view(
@ -214,18 +211,28 @@ function Users_view(
$tshirts_count, $tshirts_count,
$voucher_count $voucher_count
) { ) {
foreach ($users as &$user) {
$user['Nick'] = User_Nick_render($user); $usersList = [];
$user['Gekommen'] = glyph_bool($user['Gekommen']); foreach ($users as $user) {
$user['Aktiv'] = glyph_bool($user['Aktiv']); $u = [];
$user['force_active'] = glyph_bool($user['force_active']); $u['Nick'] = User_Nick_render($user);
$user['Tshirt'] = glyph_bool($user['Tshirt']); $u['Vorname'] = $user->personalData->first_name;
$user['lastLogIn'] = date(__('m/d/Y h:i a'), $user['lastLogIn']); $u['Name'] = $user->personalData->last_name;
$user['actions'] = table_buttons([ $u['DECT'] = $user->contact->dect;
button_glyph(page_link_to('admin_user', ['id' => $user['UID']]), 'edit', 'btn-xs') $u['Gekommen'] = glyph_bool($user->state->arrived);
$u['got_voucher'] = glyph_bool($user->state->got_voucher);
$u['freeloads'] = $user->getAttribute('freeloads');
$u['Aktiv'] = glyph_bool($user->state->active);
$u['force_active'] = glyph_bool($user->state->force_active);
$u['Tshirt'] = glyph_bool($user->state->got_shirt);
$u['Size'] = $user->personalData->shirt_size;
$u['lastLogIn'] = $user->last_login_at ? $user->last_login_at->format(__('m/d/Y h:i a')) : '';
$u['actions'] = table_buttons([
button_glyph(page_link_to('admin_user', ['id' => $user->id]), 'edit', 'btn-xs')
]); ]);
$usersList[] = $u;
} }
$users[] = [ $usersList[] = [
'Nick' => '<strong>' . __('Sum') . '</strong>', 'Nick' => '<strong>' . __('Sum') . '</strong>',
'Gekommen' => $arrived_count, 'Gekommen' => $arrived_count,
'got_voucher' => $voucher_count, 'got_voucher' => $voucher_count,
@ -233,7 +240,7 @@ function Users_view(
'force_active' => $force_active_count, 'force_active' => $force_active_count,
'freeloads' => $freeloads_count, 'freeloads' => $freeloads_count,
'Tshirt' => $tshirts_count, 'Tshirt' => $tshirts_count,
'actions' => '<strong>' . count($users) . '</strong>' 'actions' => '<strong>' . count($usersList) . '</strong>'
]; ];
return page_with_title(__('All users'), [ return page_with_title(__('All users'), [
@ -255,7 +262,7 @@ function Users_view(
'Size' => Users_table_header_link('Size', __('Size'), $order_by), 'Size' => Users_table_header_link('Size', __('Size'), $order_by),
'lastLogIn' => Users_table_header_link('lastLogIn', __('Last login'), $order_by), 'lastLogIn' => Users_table_header_link('lastLogIn', __('Last login'), $order_by),
'actions' => '' 'actions' => ''
], $users) ], $usersList)
]); ]);
} }
@ -281,19 +288,18 @@ function Users_table_header_link($column, $label, $order_by)
function User_shift_state_render($user) function User_shift_state_render($user)
{ {
if ($user instanceof User) { if ($user instanceof User) {
$userModel = $user; $id = $user->id;
$user = [ $arrived = $user->state->arrived;
'Gekommen' => $userModel->state->arrived, } else {
'UID' => $user->id, $arrived = $user['Gekommen'];
]; $id = $user['UID'];
} }
if (!$user['Gekommen']) { if (!$arrived) {
return ''; return '';
} }
$upcoming_shifts = ShiftEntries_upcoming_for_user($user['UID']); $upcoming_shifts = ShiftEntries_upcoming_for_user($id);
if (empty($upcoming_shifts)) { if (empty($upcoming_shifts)) {
return '<span class="text-success">' . __('Free') . '</span>'; return '<span class="text-success">' . __('Free') . '</span>';
} }
@ -424,7 +430,7 @@ function User_view_myshift($shift, $user_source, $its_me)
* @param int $tshirt_score * @param int $tshirt_score
* @param bool $tshirt_admin * @param bool $tshirt_admin
* @param array[] $user_worklogs * @param array[] $user_worklogs
* @param $admin_user_worklog_privilege * @param bool $admin_user_worklog_privilege
* @return array * @return array
*/ */
function User_view_myshifts( function User_view_myshifts(
@ -437,19 +443,19 @@ function User_view_myshifts(
$admin_user_worklog_privilege $admin_user_worklog_privilege
) { ) {
$myshifts_table = []; $myshifts_table = [];
$timesum = 0; $timeSum = 0;
foreach ($shifts as $shift) { foreach ($shifts as $shift) {
$myshifts_table[$shift['start']] = User_view_myshift($shift, $user_source, $its_me); $myshifts_table[$shift['start']] = User_view_myshift($shift, $user_source, $its_me);
if (!$shift['freeloaded']) { if (!$shift['freeloaded']) {
$timesum += ($shift['end'] - $shift['start']); $timeSum += ($shift['end'] - $shift['start']);
} }
} }
if ($its_me || $admin_user_worklog_privilege) { if ($its_me || $admin_user_worklog_privilege) {
foreach ($user_worklogs as $worklog) { foreach ($user_worklogs as $worklog) {
$myshifts_table[$worklog['work_timestamp']] = User_view_worklog($worklog, $admin_user_worklog_privilege); $myshifts_table[$worklog['work_timestamp']] = User_view_worklog($worklog, $admin_user_worklog_privilege);
$timesum += $worklog['work_hours'] * 3600; $timeSum += $worklog['work_hours'] * 3600;
} }
} }
@ -457,7 +463,7 @@ function User_view_myshifts(
ksort($myshifts_table); ksort($myshifts_table);
$myshifts_table[] = [ $myshifts_table[] = [
'date' => '<b>' . __('Sum:') . '</b>', 'date' => '<b>' . __('Sum:') . '</b>',
'duration' => '<b>' . sprintf('%.2f', round($timesum / 3600, 2)) . '&nbsp;h</b>', 'duration' => '<b>' . sprintf('%.2f', round($timeSum / 3600, 2)) . '&nbsp;h</b>',
'room' => '', 'room' => '',
'shift_info' => '', 'shift_info' => '',
'comment' => '', 'comment' => '',

View File

@ -2,33 +2,40 @@
namespace Engelsystem\Helpers; namespace Engelsystem\Helpers;
use Engelsystem\Models\BaseModel;
use Engelsystem\Models\User\User; use Engelsystem\Models\User\User;
use Engelsystem\Models\User\User as UserRepository; use Engelsystem\Models\User\User as UserRepository;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Session;
class Authenticator class Authenticator
{ {
/** @var UserRepository */ /** @var User */
protected $user = null; protected $user = null;
/** @var ServerRequestInterface */
protected $request;
/** @var Session */ /** @var Session */
protected $session; protected $session;
/** @var BaseModel */ /** @var UserRepository */
protected $userRepository; protected $userRepository;
/** /**
* @param Session $session * @param ServerRequestInterface $request
* @param UserRepository $userRepository * @param Session $session
* @param UserRepository $userRepository
*/ */
public function __construct(Session $session, UserRepository $userRepository) public function __construct(ServerRequestInterface $request, Session $session, UserRepository $userRepository)
{ {
$this->request = $request;
$this->session = $session; $this->session = $session;
$this->userRepository = $userRepository; $this->userRepository = $userRepository;
} }
/** /**
* Load the user from session
*
* @return User|null * @return User|null
*/ */
public function user() public function user()
@ -51,6 +58,36 @@ class Authenticator
$this->user = $user; $this->user = $user;
return $user; return $this->user;
}
/**
* Get the user by his api key
*
* @param string $parameter
* @return User|null
*/
public function apiUser($parameter = 'api_key')
{
if ($this->user) {
return $this->user;
}
$params = $this->request->getQueryParams();
if (!isset($params[$parameter])) {
return null;
}
$user = $this
->userRepository
->whereApiKey($params[$parameter])
->first();
if (!$user) {
return $this->user();
}
$this->user = $user;
return $this->user;
} }
} }

View File

@ -7,9 +7,9 @@ namespace Engelsystem\Models\User;
* @property string $email * @property string $email
* @property string $mobile * @property string $mobile
* *
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact whereDect($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact[] whereDect($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact whereEmail($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact[] whereEmail($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact whereMobile($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Contact[] whereMobile($value)
*/ */
class Contact extends HasUserModel class Contact extends HasUserModel
{ {

View File

@ -6,8 +6,8 @@ namespace Engelsystem\Models\User;
* @property string $token * @property string $token
* @property \Carbon\Carbon $created_at * @property \Carbon\Carbon $created_at
* *
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\PasswordReset whereToken($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\PasswordReset[] whereToken($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\PasswordReset whereCreatedAt($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\PasswordReset[] whereCreatedAt($value)
*/ */
class PasswordReset extends HasUserModel class PasswordReset extends HasUserModel
{ {

View File

@ -8,10 +8,10 @@ namespace Engelsystem\Models\User;
* @property bool $email_human * @property bool $email_human
* @property bool $email_shiftinfo * @property bool $email_shiftinfo
* *
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings whereLanguage($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings[] whereLanguage($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings whereTheme($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings[] whereTheme($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings whereEmailHuman($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings[] whereEmailHuman($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings whereEmailShiftinfo($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\Settings[] whereEmailShiftinfo($value)
*/ */
class Settings extends HasUserModel class Settings extends HasUserModel
{ {

View File

@ -9,11 +9,11 @@ namespace Engelsystem\Models\User;
* @property bool $got_shirt * @property bool $got_shirt
* @property int $got_voucher * @property int $got_voucher
* *
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State whereArrived($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State[] whereArrived($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State whereActive($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State[] whereActive($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State whereForceActive($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State[] whereForceActive($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State whereGotShirt($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State[] whereGotShirt($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State whereGotVoucher($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State[] whereGotVoucher($value)
*/ */
class State extends HasUserModel class State extends HasUserModel
{ {

View File

@ -21,13 +21,13 @@ use Illuminate\Database\Eloquent\Relations\HasOne;
* @property-read \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State $state * @property-read \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\State $state
* *
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereId($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereId($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereName($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereName($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereEmail($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereEmail($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User wherePassword($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] wherePassword($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereApiKey($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereApiKey($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereLastLoginAt($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereLastLoginAt($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereCreatedAt($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereCreatedAt($value)
* @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User whereUpdatedAt($value) * @method static \Illuminate\Database\Query\Builder|\Engelsystem\Models\User\User[] whereUpdatedAt($value)
*/ */
class User extends BaseModel class User extends BaseModel
{ {

View File

@ -5,7 +5,9 @@ namespace Engelsystem\Test\Unit\Helpers;
use Engelsystem\Application; use Engelsystem\Application;
use Engelsystem\Helpers\Authenticator; use Engelsystem\Helpers\Authenticator;
use Engelsystem\Helpers\AuthenticatorServiceProvider; use Engelsystem\Helpers\AuthenticatorServiceProvider;
use Engelsystem\Http\Request;
use Engelsystem\Test\Unit\ServiceProviderTest; use Engelsystem\Test\Unit\ServiceProviderTest;
use Psr\Http\Message\ServerRequestInterface;
class AuthenticatorServiceProviderTest extends ServiceProviderTest class AuthenticatorServiceProviderTest extends ServiceProviderTest
{ {
@ -15,6 +17,7 @@ class AuthenticatorServiceProviderTest extends ServiceProviderTest
public function testRegister() public function testRegister()
{ {
$app = new Application(); $app = new Application();
$app->bind(ServerRequestInterface::class, Request::class);
$serviceProvider = new AuthenticatorServiceProvider($app); $serviceProvider = new AuthenticatorServiceProvider($app);
$serviceProvider->register(); $serviceProvider->register();

View File

@ -7,6 +7,7 @@ use Engelsystem\Models\User\User;
use Engelsystem\Test\Unit\Helpers\Stub\UserModelImplementation; use Engelsystem\Test\Unit\Helpers\Stub\UserModelImplementation;
use Engelsystem\Test\Unit\ServiceProviderTest; use Engelsystem\Test\Unit\ServiceProviderTest;
use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\MockObject;
use Psr\Http\Message\ServerRequestInterface;
use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\Session\Session;
class AuthenticatorTest extends ServiceProviderTest class AuthenticatorTest extends ServiceProviderTest
@ -17,6 +18,8 @@ class AuthenticatorTest extends ServiceProviderTest
*/ */
public function testUser() public function testUser()
{ {
/** @var ServerRequestInterface|MockObject $request */
$request = $this->getMockForAbstractClass(ServerRequestInterface::class);
/** @var Session|MockObject $session */ /** @var Session|MockObject $session */
$session = $this->createMock(Session::class); $session = $this->createMock(Session::class);
/** @var UserModelImplementation|MockObject $userRepository */ /** @var UserModelImplementation|MockObject $userRepository */
@ -33,7 +36,7 @@ class AuthenticatorTest extends ServiceProviderTest
1337 1337
); );
$auth = new Authenticator($session, $userRepository); $auth = new Authenticator($request, $session, $userRepository);
// Not in session // Not in session
$this->assertEquals(null, $auth->user()); $this->assertEquals(null, $auth->user());
@ -52,4 +55,48 @@ class AuthenticatorTest extends ServiceProviderTest
UserModelImplementation::$user = null; UserModelImplementation::$user = null;
$this->assertEquals($user, $auth->user()); $this->assertEquals($user, $auth->user());
} }
/**
* @covers \Engelsystem\Helpers\Authenticator::apiUser
*/
public function testApiUser()
{
/** @var ServerRequestInterface|MockObject $request */
$request = $this->getMockForAbstractClass(ServerRequestInterface::class);
/** @var Session|MockObject $session */
$session = $this->createMock(Session::class);
/** @var UserModelImplementation|MockObject $userRepository */
$userRepository = new UserModelImplementation();
/** @var User|MockObject $user */
$user = $this->createMock(User::class);
$request->expects($this->exactly(3))
->method('getQueryParams')
->with()
->willReturnOnConsecutiveCalls(
[],
['api_key' => 'iMaNot3xiSt1nGAp1Key!'],
['foo_key' => 'SomeSecretApiKey']
);
/** @var Authenticator|MockObject $auth */
$auth = new Authenticator($request, $session, $userRepository);
// No key
$this->assertEquals(null, $auth->apiUser());
// Unknown user
UserModelImplementation::$apiKey = 'iMaNot3xiSt1nGAp1Key!';
$this->assertEquals(null, $auth->apiUser());
// User found
UserModelImplementation::$apiKey = 'SomeSecretApiKey';
UserModelImplementation::$user = $user;
$this->assertEquals($user, $auth->apiUser('foo_key'));
// User cached
UserModelImplementation::$apiKey = null;
UserModelImplementation::$user = null;
$this->assertEquals($user, $auth->apiUser());
}
} }

View File

@ -3,6 +3,7 @@
namespace Engelsystem\Test\Unit\Helpers\Stub; namespace Engelsystem\Test\Unit\Helpers\Stub;
use Engelsystem\Models\User\User; use Engelsystem\Models\User\User;
use Illuminate\Database\Eloquent\Collection;
use InvalidArgumentException; use InvalidArgumentException;
class UserModelImplementation extends User class UserModelImplementation extends User
@ -13,6 +14,9 @@ class UserModelImplementation extends User
/** @var int */ /** @var int */
public static $id = null; public static $id = null;
/** @var int */
public static $apiKey = null;
/** /**
* @param mixed $id * @param mixed $id
* @param array $columns * @param array $columns
@ -26,4 +30,17 @@ class UserModelImplementation extends User
return self::$user; return self::$user;
} }
/**
* @param string $apiKey
* @return User[]|Collection|\Illuminate\Database\Query\Builder
*/
public static function whereApiKey($apiKey)
{
if ($apiKey != static::$apiKey) {
throw new InvalidArgumentException('Wrong api key searched');
}
return new Collection([self::$user]);
}
} }