Cleaned up random queries, closes #132.

This commit is contained in:
flash 2019-01-18 18:08:19 +01:00
parent feea91f89e
commit 96c665bfd5
13 changed files with 249 additions and 182 deletions

View file

@ -75,20 +75,20 @@ switch ($authMode) {
return;
}
$resetUser = (int)($_POST['user'] ?? $_GET['u'] ?? 0);
$getResetUser = db_prepare('
SELECT `user_id`, `username`
FROM `msz_users`
WHERE `user_id` = :user_id
');
$getResetUser->bindValue('user_id', $resetUser);
$resetUser = db_fetch($getResetUser);
$resetUserId = (int)($_POST['user'] ?? $_GET['u'] ?? 0);
if (empty($resetUser)) {
if (empty($resetUserId)) {
header('Location: /auth.php?m=forgot');
break;
}
$resetUsername = user_username_from_id($resetUserId);
if (empty($resetUsername)) {
header('Location: /auth.php');
break;
}
tpl_var('auth_reset_message', "A verification code should've been sent to your e-mail address.");
while ($isSubmission) {
@ -97,7 +97,7 @@ switch ($authMode) {
break;
}
if (!user_recovery_token_validate($resetUser['user_id'], $authVerification)) {
if (!user_recovery_token_validate($resetUserId, $authVerification)) {
tpl_var('auth_reset_error', 'Invalid verification code!');
break;
}
@ -116,20 +116,23 @@ switch ($authMode) {
break;
}
if (user_password_set($resetUser['user_id'], $authPassword['new'])) {
audit_log(MSZ_AUDIT_PASSWORD_RESET, $resetUser['user_id']);
if (user_password_set($resetUserId, $authPassword['new'])) {
audit_log(MSZ_AUDIT_PASSWORD_RESET, $resetUserId);
} else {
throw new UnexpectedValueException('Password reset failed.');
}
user_recovery_token_invalidate($resetUser['user_id'], $authVerification);
user_recovery_token_invalidate($resetUserId, $authVerification);
header("Location: /auth.php?m=login&u={$resetUser['user_id']}");
header("Location: /auth.php?m=login&u={$resetUserId}");
break;
}
echo tpl_render('auth.password', [
'reset_user' => $resetUser,
'reset_user' => [
'user_id' => $resetUserId,
'username' => $resetUsername,
],
]);
break;
@ -150,13 +153,7 @@ switch ($authMode) {
break;
}
$forgotUser = db_prepare('
SELECT `user_id`, `username`, `email`
FROM `msz_users`
WHERE LOWER(`email`) = LOWER(:email)
');
$forgotUser->bindValue('email', $authEmail);
$forgotUser = db_fetch($forgotUser);
$forgotUser = user_find_for_reset($authEmail);
if (empty($forgotUser)) {
tpl_var('auth_forgot_error', 'This user is not registered with us.');
@ -231,16 +228,7 @@ MSG;
break;
}
$getUser = db_prepare('
SELECT `user_id`, `password`
FROM `msz_users`
WHERE LOWER(`email`) = LOWER(:email)
OR LOWER(`username`) = LOWER(:username)
');
$getUser->bindValue('email', $authUsername);
$getUser->bindValue('username', $authUsername);
$userData = db_fetch($getUser);
$userId = (int)($userData['user_id'] ?? 0);
$userData = user_find_for_login($authUsername);
$loginFailedError = sprintf(
"Invalid username or password, %d attempt%s remaining.",
@ -248,22 +236,22 @@ MSG;
$remainingAttempts === 2 ? '' : 's'
);
if ($userId < 1) {
if ($userData['user_id'] < 1) {
user_login_attempt_record(false, null, $ipAddress, $userAgent);
$authLoginError = $loginFailedError;
break;
}
if (!password_verify($authPassword, $userData['password'])) {
user_login_attempt_record(false, $userId, $ipAddress, $userAgent);
user_login_attempt_record(false, $userData['user_id'], $ipAddress, $userAgent);
$authLoginError = $loginFailedError;
break;
}
user_login_attempt_record(true, $userId, $ipAddress, $userAgent);
user_login_attempt_record(true, $userData['user_id'], $ipAddress, $userAgent);
if ($loginPermission > 0) {
$generalPerms = perms_get_user(MSZ_PERMS_GENERAL, $userId);
$generalPerms = perms_get_user(MSZ_PERMS_GENERAL, $userData['user_id']);
if (!perms_check($generalPerms, $loginPermission)) {
$authLoginError = 'Your credentials were correct, but your account lacks the proper permissions to use this website.';
@ -271,16 +259,16 @@ MSG;
}
}
$sessionKey = user_session_create($userId, $ipAddress, $userAgent);
$sessionKey = user_session_create($userData['user_id'], $ipAddress, $userAgent);
if ($sessionKey === '') {
$authLoginError = 'Unable to create new session, contact an administrator ASAP.';
break;
}
user_session_start($userId, $sessionKey);
user_session_start($userData['user_id'], $sessionKey);
$cookieLife = strtotime(user_session_current('session_expires'));
set_cookie_m('uid', $userId, $cookieLife);
set_cookie_m('uid', $userData['user_id'], $cookieLife);
set_cookie_m('sid', $sessionKey, $cookieLife);
if (!is_local_url($authRedirect)) {

View file

@ -9,44 +9,16 @@ $changelogTags = $_GET['t'] ?? '';
tpl_var('comments_perms', $commentPerms = comments_get_perms(user_session_current('user_id', 0)));
if ($changelogChange > 0) {
$getChange = db_prepare('
SELECT
c.`change_id`, c.`change_created`, c.`change_log`, c.`change_text`,
a.`action_name`, a.`action_colour`, a.`action_class`,
u.`user_id`, u.`username`, u.`display_role` as `user_role`,
DATE(`change_created`) as `change_date`,
COALESCE(u.`user_title`, r.`role_title`) as `user_title`,
COALESCE(u.`user_colour`, r.`role_colour`) as `user_colour`
FROM `msz_changelog_changes` as c
LEFT JOIN `msz_users` as u
ON u.`user_id` = c.`user_id`
LEFT JOIN `msz_roles` as r
ON r.`role_id` = u.`display_role`
LEFT JOIN `msz_changelog_actions` as a
ON a.`action_id` = c.`action_id`
WHERE `change_id` = :change_id
');
$getChange->bindValue('change_id', $changelogChange);
$change = db_fetch($getChange);
$change = changelog_change_get($changelogChange);
if (!$change) {
echo render_error(404);
return;
} else {
$getTags = db_prepare('
SELECT
t.`tag_id`, t.`tag_name`, t.`tag_description`
FROM `msz_changelog_tags` as t
LEFT JOIN `msz_changelog_change_tags` as ct
ON ct.`tag_id` = t.`tag_id`
WHERE ct.`change_id` = :change_id
');
$getTags->bindValue('change_id', $change['change_id']);
tpl_var('tags', db_fetch_all($getTags));
}
echo tpl_render('changelog.change', [
'change' => $change,
'tags' => changelog_change_tags_get($change['change_id']),
'comments_category' => $commentsCategory = comments_category_info(
"changelog-date-{$change['change_date']}",
true

View file

@ -8,7 +8,7 @@ if ($forumId === 0) {
exit;
}
$forum = forum_fetch($forumId);
$forum = forum_get($forumId);
$forumUserId = user_session_current('user_id', 0);
if (empty($forum) || ($forum['forum_type'] == MSZ_FORUM_TYPE_LINK && empty($forum['forum_link']))) {

View file

@ -54,13 +54,7 @@ if (!empty($topicId)) {
}
if (!empty($forumId)) {
$getForum = db_prepare('
SELECT `forum_id`, `forum_name`, `forum_type`, `forum_archived`
FROM `msz_forum_categories`
WHERE `forum_id` = :forum_id
');
$getForum->bindValue('forum_id', $forumId);
$forum = db_fetch($getForum);
$forum = forum_get($forumId);
}
if (empty($forum)) {
@ -223,19 +217,7 @@ if ($mode === 'edit') { // $post is pretty much sure to be populated at this poi
tpl_var('posting_post', $post);
}
// fetches additional data for simulating a forum post
$getDisplayInfo = db_prepare('
SELECT u.`user_country`, u.`user_created`, (
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `user_id` = u.`user_id`
AND `post_deleted` IS NULL
) AS `user_forum_posts`
FROM `msz_users` as u
WHERE `user_id` = :user_id
');
$getDisplayInfo->bindValue('user_id', user_session_current('user_id'));
$displayInfo = db_fetch($getDisplayInfo);
$displayInfo = forum_posting_info(user_session_current('user_id'));
echo tpl_render('forum.posting', [
'posting_breadcrumbs' => forum_get_breadcrumbs($forumId),

View file

@ -58,19 +58,7 @@ $canManageUsers = perms_check(
MSZ_PERM_USER_MANAGE_USERS
);
$getRole = db_prepare('
SELECT
`role_id`, `role_name`, `role_colour`, `role_description`, `role_created`,
(
SELECT COUNT(`user_id`)
FROM `msz_user_roles`
WHERE `role_id` = r.`role_id`
) as `role_user_count`
FROM `msz_roles` as r
WHERE `role_id` = :role_id
');
$getRole->bindValue('role_id', $roleId);
$role = db_fetch($getRole);
$role = user_role_get($roleId);
if (empty($role)) {
echo render_error(404);
@ -85,18 +73,13 @@ if (!pagination_is_valid_offset($usersOffset)) {
return;
}
$roles = db_query('
SELECT `role_id`, `role_name`, `role_colour`
FROM `msz_roles`
WHERE `role_hidden` = 0
ORDER BY `role_id`
')->fetchAll(PDO::FETCH_ASSOC);
$roles = user_role_all();
$getUsers = db_prepare(sprintf(
'
SELECT
u.`user_id`, u.`username`, u.`user_country`, r.`role_id`,
COALESCE(u.`user_title`, r.`role_title`, r.`role_name`) as `user_title`,
COALESCE(u.`user_title`, r.`role_title`) as `user_title`,
COALESCE(u.`user_colour`, r.`role_colour`) as `user_colour`
FROM `msz_users` as u
LEFT JOIN `msz_roles` as r

View file

@ -89,19 +89,7 @@ switch ($mode) {
break;
default:
$getUserId = db_prepare('
SELECT
:user_id as `input_id`,
(
SELECT `user_id`
FROM `msz_users`
WHERE `user_id` = `input_id`
OR LOWER(`username`) = LOWER(`input_id`)
LIMIT 1
) as `user_id`
');
$getUserId->bindValue('user_id', $_GET['u'] ?? 0);
$userId = (int)($getUserId->execute() ? $getUserId->fetchColumn(1) : 0);
$userId = user_find_for_profile($_GET['u'] ?? 0);
if ($userId < 1) {
http_response_code(404);
@ -335,52 +323,7 @@ switch ($mode) {
}
}
$getProfile = db_prepare(
sprintf(
'
SELECT
u.`user_id`, u.`username`, u.`user_country`, u.`user_birthdate`,
u.`user_created`, u.`user_active`,
u.`user_about_parser`, u.`user_about_content`, u.`user_background_settings`,
%1$s,
COALESCE(u.`user_title`, r.`role_title`) as `user_title`,
COALESCE(u.`user_colour`, r.`role_colour`) as `user_colour`,
`user_background_settings` & 0x0F as `user_background_attachment`,
(`user_background_settings` & %2$d) > 0 as `user_background_blend`,
(`user_background_settings` & %3$d) > 0 as `user_background_slide`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `user_id` = u.`user_id`
) as `forum_topic_count`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `user_id` = u.`user_id`
) as `forum_post_count`,
(
SELECT COUNT(`change_id`)
FROM `msz_changelog_changes`
WHERE `user_id` = u.`user_id`
) as `changelog_count`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
WHERE `user_id` = u.`user_id`
) as `comments_count`
FROM `msz_users` as u
LEFT JOIN `msz_roles` as r
ON r.`role_id` = u.`display_role`
WHERE `user_id` = :user_id
LIMIT 1
',
pdo_prepare_array(user_profile_fields_get(), true, 'u.`user_%s`'),
MSZ_USER_BACKGROUND_ATTRIBUTE_BLEND,
MSZ_USER_BACKGROUND_ATTRIBUTE_SLIDE
)
);
$getProfile->bindValue('user_id', $userId);
$profile = db_fetch($getProfile);
$profile = user_profile_get($userId);
$backgroundPath = build_path(MSZ_STORAGE, 'backgrounds/original', "{$profile['user_id']}.msz");

View file

@ -173,16 +173,7 @@ $logs['list'] = audit_log_list(
user_session_current('user_id')
);
$getUserRoles = db_prepare('
SELECT r.`role_id`, r.`role_name`, r.`role_description`, r.`role_colour`, r.`role_can_leave`
FROM `msz_user_roles` as ur
LEFT JOIN `msz_roles` as r
ON r.`role_id` = ur.`role_id`
WHERE ur.`user_id` = :user_id
ORDER BY r.`role_hierarchy` DESC
');
$getUserRoles->bindValue('user_id', user_session_current('user_id'));
$userRoles = db_fetch_all($getUserRoles);
$userRoles = user_role_all_user(user_session_current('user_id'));
echo tpl_render('user.settings', [
'errors' => $errors,

View file

@ -80,7 +80,7 @@ function forum_may_have_topics(int $forumType): bool
return in_array($forumType, MSZ_FORUM_MAY_HAVE_TOPICS);
}
function forum_fetch(int $forumId, bool $showDeleted = false): array
function forum_get(int $forumId, bool $showDeleted = false): array
{
$getForum = db_prepare(sprintf(
'
@ -429,3 +429,29 @@ function forum_mark_read(?int $forumId, int $userId): bool
return $doMark->execute();
}
function forum_posting_info(int $userId): array
{
$getPostingInfo = db_prepare('
SELECT
u.`user_country`, u.`user_created`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `user_id` = u.`user_id`
AND `post_deleted` IS NULL
) AS `user_forum_posts`,
(
SELECT `post_parse`
FROM `msz_forum_posts`
WHERE `user_id` = u.`user_id`
AND `post_deleted` IS NULL
ORDER BY `post_id` DESC
LIMIT 1
) AS `user_post_parse`
FROM `msz_users` as u
WHERE `user_id` = :user_id
');
$getPostingInfo->bindValue('user_id', $userId);
return db_fetch($getPostingInfo);
}

View file

@ -203,3 +203,53 @@ function user_profile_fields_display(array $user, bool $hideEmpty = true): array
return $output;
}
function user_profile_get(int $userId): array
{
$getProfile = db_prepare(
sprintf(
'
SELECT
u.`user_id`, u.`username`, u.`user_country`, u.`user_birthdate`,
u.`user_created`, u.`user_active`,
u.`user_about_parser`, u.`user_about_content`, u.`user_background_settings`,
%1$s,
COALESCE(u.`user_title`, r.`role_title`) as `user_title`,
COALESCE(u.`user_colour`, r.`role_colour`) as `user_colour`,
`user_background_settings` & 0x0F as `user_background_attachment`,
(`user_background_settings` & %2$d) > 0 as `user_background_blend`,
(`user_background_settings` & %3$d) > 0 as `user_background_slide`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `user_id` = u.`user_id`
) as `forum_topic_count`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `user_id` = u.`user_id`
) as `forum_post_count`,
(
SELECT COUNT(`change_id`)
FROM `msz_changelog_changes`
WHERE `user_id` = u.`user_id`
) as `changelog_count`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
WHERE `user_id` = u.`user_id`
) as `comments_count`
FROM `msz_users` as u
LEFT JOIN `msz_roles` as r
ON r.`role_id` = u.`display_role`
WHERE `user_id` = :user_id
LIMIT 1
',
pdo_prepare_array(user_profile_fields_get(), true, 'u.`user_%s`'),
MSZ_USER_BACKGROUND_ATTRIBUTE_BLEND,
MSZ_USER_BACKGROUND_ATTRIBUTE_SLIDE
)
);
$getProfile->bindValue('user_id', $userId);
return db_fetch($getProfile);
}

View file

@ -81,3 +81,57 @@ function user_role_get_display(int $userId): int
$fetchRole->bindValue('user_id', $userId);
return $fetchRole->execute() ? (int)$fetchRole->fetchColumn() : MSZ_ROLE_MAIN;
}
function user_role_all_user(int $userId): array
{
$getUserRoles = db_prepare('
SELECT
r.`role_id`, r.`role_name`, r.`role_description`,
r.`role_colour`, r.`role_can_leave`, r.`role_created`
FROM `msz_user_roles` AS ur
LEFT JOIN `msz_roles` AS r
ON r.`role_id` = ur.`role_id`
WHERE ur.`user_id` = :user_id
ORDER BY r.`role_hierarchy` DESC
');
$getUserRoles->bindValue('user_id', $userId);
return db_fetch_all($getUserRoles);
}
function user_role_all(bool $withHidden = false)
{
return db_query(sprintf(
'
SELECT
r.`role_id`, r.`role_name`, r.`role_description`,
r.`role_colour`, r.`role_can_leave`, r.`role_created`,
(
SELECT COUNT(`user_id`)
FROM `msz_user_roles`
WHERE `role_id` = r.`role_id`
) AS `role_user_count`
FROM `msz_roles` AS r
%s
ORDER BY `role_id`
',
$withHidden ? '' : 'WHERE `role_hidden` = 0'
))->fetchAll(PDO::FETCH_ASSOC);
}
function user_role_get(int $roleId): array
{
$getRole = db_prepare('
SELECT
r.`role_id`, r.`role_name`, r.`role_description`,
r.`role_colour`, r.`role_can_leave`, r.`role_created`,
(
SELECT COUNT(`user_id`)
FROM `msz_user_roles`
WHERE `role_id` = r.`role_id`
) AS `role_user_count`
FROM `msz_roles` AS r
WHERE `role_id` = :role_id
');
$getRole->bindValue('role_id', $roleId);
return db_fetch($getRole);
}

View file

@ -55,6 +55,47 @@ function user_create(
return $createUser->execute() ? (int)db_last_insert_id() : 0;
}
function user_find_for_login(string $usernameOrMail): array
{
$getUser = db_prepare('
SELECT `user_id`, `password`
FROM `msz_users`
WHERE LOWER(`email`) = LOWER(:email)
OR LOWER(`username`) = LOWER(:username)
');
$getUser->bindValue('email', $usernameOrMail);
$getUser->bindValue('username', $usernameOrMail);
return db_fetch($getUser);
}
function user_find_for_reset(string $email): array
{
$getUser = db_prepare('
SELECT `user_id`, `username`, `email`
FROM `msz_users`
WHERE LOWER(`email`) = LOWER(:email)
');
$getUser->bindValue('email', $email);
return db_fetch($getUser);
}
function user_find_for_profile(string $idOrUsername): int
{
$getUserId = db_prepare('
SELECT
:user_id as `input_id`,
(
SELECT `user_id`
FROM `msz_users`
WHERE `user_id` = `input_id`
OR LOWER(`username`) = LOWER(`input_id`)
LIMIT 1
) as `user_id`
');
$getUserId->bindValue('user_id', $idOrUsername);
return (int)($getUserId->execute() ? $getUserId->fetchColumn(1) : 0);
}
function user_password_hash(string $password): string
{
return password_hash($password, MSZ_USERS_PASSWORD_HASH_ALGO);

View file

@ -120,3 +120,40 @@ function changelog_count_changes(string $date, int $user): int
return $prep->execute() ? (int)$prep->fetchColumn() : 0;
}
function changelog_change_get(int $changeId): array
{
$getChange = db_prepare('
SELECT
c.`change_id`, c.`change_created`, c.`change_log`, c.`change_text`,
a.`action_name`, a.`action_colour`, a.`action_class`,
u.`user_id`, u.`username`, u.`display_role` as `user_role`,
DATE(`change_created`) as `change_date`,
COALESCE(u.`user_title`, r.`role_title`) as `user_title`,
COALESCE(u.`user_colour`, r.`role_colour`) as `user_colour`
FROM `msz_changelog_changes` as c
LEFT JOIN `msz_users` as u
ON u.`user_id` = c.`user_id`
LEFT JOIN `msz_roles` as r
ON r.`role_id` = u.`display_role`
LEFT JOIN `msz_changelog_actions` as a
ON a.`action_id` = c.`action_id`
WHERE `change_id` = :change_id
');
$getChange->bindValue('change_id', $changeId);
return db_fetch($getChange);
}
function changelog_change_tags_get(int $changeId): array
{
$getTags = db_prepare('
SELECT
t.`tag_id`, t.`tag_name`, t.`tag_description`
FROM `msz_changelog_tags` as t
LEFT JOIN `msz_changelog_change_tags` as ct
ON ct.`tag_id` = t.`tag_id`
WHERE ct.`change_id` = :change_id
');
$getTags->bindValue('change_id', $changeId);
return db_fetch_all($getTags);
}

View file

@ -69,8 +69,8 @@
{{ input_select(
'post[parser]',
constant('MSZ_PARSERS_NAMES'),
posting_defaults.parser|default(posting_post.post_parse|default(constant('MSZ_PARSER_BBCODE'))),
null, null, null, 'forum__post__dropdown'
posting_defaults.parser|default(posting_post.post_parse|default(posting_info.user_post_parse|default(constant('MSZ_PARSER_BBCODE')))),
null, null, false, 'forum__post__dropdown'
) }}
{% if is_opening and posting_types|length > 1 %}
{{ input_select(