Rewrote database stuff.

This commit is contained in:
flash 2019-09-29 00:38:39 +02:00
parent 0661ca5918
commit d47052d1b4
47 changed files with 1116 additions and 1114 deletions

View file

@ -6,4 +6,5 @@ host = localhost
port = 3306
username = username
password = password
database = database
dbname = database
charset = utf8mb4

View file

@ -1,6 +1,9 @@
<?php
namespace Misuzu;
use Misuzu\Database\{ Database, DatabaseMigrationManager };
use PDO;
define('MSZ_STARTUP', microtime(true));
define('MSZ_ROOT', __DIR__);
define('MSZ_DEBUG', is_file(MSZ_ROOT . '/.debug'));
@ -39,7 +42,6 @@ require_once 'src/colour.php';
require_once 'src/comments.php';
require_once 'src/config.php';
require_once 'src/csrf.php';
require_once 'src/db.php';
require_once 'src/emotes.php';
require_once 'src/general.php';
require_once 'src/git.php';
@ -85,8 +87,19 @@ if(empty($dbConfig)) {
exit;
}
db_settings([
'mysql-main' => $dbConfig['Database'] ?? $dbConfig['Database.mysql-main'] ?? [],
$dbConfig = $dbConfig['Database'] ?? $dbConfig['Database.mysql-main'] ?? [];
DB::init(DB::buildDSN($dbConfig), $dbConfig['username'] ?? '', $dbConfig['password'] ?? '', [
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
PDO::ATTR_STRINGIFY_FETCHES => false,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::MYSQL_ATTR_INIT_COMMAND => "
SET SESSION
sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION',
time_zone = '+00:00';
",
]);
config_init();
@ -250,7 +263,7 @@ if(PHP_SAPI === 'cli') {
switch($cronTask['type']) {
case 'sql':
db_exec($cronTask['command']);
DB::exec($cronTask['command']);
break;
case 'func':
@ -262,45 +275,34 @@ if(PHP_SAPI === 'cli') {
break;
case 'migrate':
$migrationTargets = [
'mysql-main' => MSZ_ROOT . '/database',
];
$doRollback = !empty($argv[2]) && $argv[2] === 'rollback';
$targetDb = isset($argv[$doRollback ? 3 : 2]) ? $argv[$doRollback ? 3 : 2] : null;
if($targetDb !== null && !array_key_exists($targetDb, $migrationTargets)) {
echo 'Invalid target database connection.' . PHP_EOL;
break;
}
touch(MSZ_ROOT . '/.migrating');
foreach($migrationTargets as $db => $path) {
echo "Creating migration manager for '{$db}'..." . PHP_EOL;
$migrationManager = new DatabaseMigrationManager(db_connection($db), $path);
$migrationManager->setLogger(function ($log) {
echo $log . PHP_EOL;
});
echo "Creating migration manager.." . PHP_EOL;
$migrationManager = new DatabaseMigrationManager(DB::getPDO(), $path);
$migrationManager->setLogger(function ($log) {
echo $log . PHP_EOL;
});
if($doRollback) {
echo "Rolling back last migrations for '{$db}'..." . PHP_EOL;
$migrationManager->rollback();
} else {
echo "Running migrations for '{$db}'..." . PHP_EOL;
$migrationManager->migrate();
}
if($doRollback) {
echo "Rolling back last migrations..." . PHP_EOL;
$migrationManager->rollback();
} else {
echo "Running migrations..." . PHP_EOL;
$migrationManager->migrate();
}
$errors = $migrationManager->getErrors();
$errorCount = count($errors);
$errors = $migrationManager->getErrors();
$errorCount = count($errors);
if($errorCount < 1) {
echo 'Completed with no errors!' . PHP_EOL;
} else {
echo PHP_EOL . "There were {$errorCount} errors during the migrations..." . PHP_EOL;
if($errorCount < 1) {
echo 'Completed with no errors!' . PHP_EOL;
} else {
echo PHP_EOL . "There were {$errorCount} errors during the migrations..." . PHP_EOL;
foreach($errors as $error) {
echo $error . PHP_EOL;
}
foreach($errors as $error) {
echo $error . PHP_EOL;
}
}
@ -446,7 +448,7 @@ MIG;
$cookieData = user_session_cookie_unpack(base64url_decode($_COOKIE['msz_auth']));
if(!empty($cookieData) && user_session_start($cookieData['user_id'], $cookieData['session_token'])) {
$getUserDisplayInfo = db_prepare('
$userDisplayInfo = DB::prepare('
SELECT
u.`user_id`, u.`username`, u.`user_background_settings`, u.`user_deleted`,
COALESCE(u.`user_colour`, r.`role_colour`) AS `user_colour`
@ -455,8 +457,8 @@ MIG;
ON u.`display_role` = r.`role_id`
WHERE `user_id` = :user_id
');
$getUserDisplayInfo->bindValue('user_id', $cookieData['user_id']);
$userDisplayInfo = db_fetch($getUserDisplayInfo);
$userDisplayInfo->bind('user_id', $cookieData['user_id']);
$userDisplayInfo = $userDisplayInfo->fetch();
if($userDisplayInfo) {
if(!is_null($userDisplayInfo['user_deleted'])) {

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
require_once '../misuzu.php';
$showActivityFeed = false; /*user_session_active()
@ -18,7 +20,7 @@ if($showActivityFeed) {
$news = news_posts_get(0, 5, null, true);
$stats = db_fetch(db_query('
$stats = DB::query('
SELECT
(
SELECT COUNT(`user_id`)
@ -50,9 +52,9 @@ if($showActivityFeed) {
FROM `msz_forum_posts`
WHERE `post_deleted` IS NULL
) AS `count_forum_posts`
'));
')->fetch();
$changelog = db_fetch_all(db_query('
$changelog = DB::query('
SELECT
`change_id`, `change_log`, `change_action`,
DATE(`change_created`) AS `change_date`,
@ -60,11 +62,11 @@ if($showActivityFeed) {
FROM `msz_changelog_changes`
ORDER BY `change_created` DESC
LIMIT 10
'));
')->fetchAll();
$birthdays = user_session_active() ? user_get_birthdays() : [];
$latestUser = db_fetch(db_query('
$latestUser = DB::query('
SELECT
u.`user_id`, u.`username`, u.`user_created`,
COALESCE(u.`user_colour`, r.`role_colour`) as `user_colour`
@ -74,9 +76,9 @@ if($showActivityFeed) {
WHERE `user_deleted` IS NULL
ORDER BY u.`user_id` DESC
LIMIT 1
'));
')->fetch();
$onlineUsers = db_fetch_all(db_query('
$onlineUsers = DB::query('
SELECT
u.`user_id`, u.`username`,
COALESCE(u.`user_colour`, r.`role_colour`) as `user_colour`
@ -86,7 +88,7 @@ if($showActivityFeed) {
WHERE u.`user_active` >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
ORDER BY u.`user_active` DESC
LIMIT 104
'));
')->fetchAll();
tpl_vars([
'statistics' => $stats,

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
require_once '../../../misuzu.php';
if(!perms_check_user(MSZ_PERMS_CHANGELOG, user_session_current('user_id'), MSZ_PERM_CHANGELOG_MANAGE_CHANGES)) {
@ -11,7 +13,7 @@ $changeId = (int)($_GET['c'] ?? 0);
if($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify_request()) {
if(!empty($_POST['change']) && is_array($_POST['change'])) {
if($changeId > 0) {
$postChange = db_prepare('
$postChange = DB::prepare('
UPDATE `msz_changelog_changes`
SET `change_log` = :log,
`change_text` = :text,
@ -20,9 +22,9 @@ if($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify_request()) {
`change_created` = :created
WHERE `change_id` = :change_id
');
$postChange->bindValue('change_id', $changeId);
$postChange->bind('change_id', $changeId);
} else {
$postChange = db_prepare('
$postChange = DB::prepare('
INSERT INTO `msz_changelog_changes`
(
`change_log`, `change_text`, `change_action`,
@ -33,21 +35,21 @@ if($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify_request()) {
');
}
$postChange->bindValue('log', $_POST['change']['log']);
$postChange->bindValue('action', $_POST['change']['action']);
$postChange->bindValue('text', strlen($_POST['change']['text'])
$postChange->bind('log', $_POST['change']['log']);
$postChange->bind('action', $_POST['change']['action']);
$postChange->bind('text', strlen($_POST['change']['text'])
? $_POST['change']['text']
: null);
$postChange->bindValue('user', is_numeric($_POST['change']['user'])
$postChange->bind('user', is_numeric($_POST['change']['user'])
? $_POST['change']['user']
: null);
$postChange->bindValue('created', strlen($_POST['change']['created'])
$postChange->bind('created', strlen($_POST['change']['created'])
? $_POST['change']['created']
: null);
$postChange->execute();
if($changeId < 1) {
$changeId = db_last_insert_id();
$changeId = DB::lastId();
audit_log(MSZ_AUDIT_CHANGELOG_ENTRY_CREATE, user_session_current('user_id', 0), [$changeId]);
} else {
audit_log(MSZ_AUDIT_CHANGELOG_ENTRY_EDIT, user_session_current('user_id', 0), [$changeId]);
@ -57,24 +59,24 @@ if($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify_request()) {
if(!empty($_POST['tags']) && is_array($_POST['tags']) && array_test($_POST['tags'], 'ctype_digit')) {
$setTags = array_apply($_POST['tags'], 'intval');
$removeTags = db_prepare(sprintf('
$removeTags = DB::prepare(sprintf('
DELETE FROM `msz_changelog_change_tags`
WHERE `change_id` = :change_id
AND `tag_id` NOT IN (%s)
', implode(',', $setTags)));
$removeTags->bindValue('change_id', $changeId);
$removeTags->bind('change_id', $changeId);
$removeTags->execute();
$addTag = db_prepare('
$addTag = DB::prepare('
INSERT IGNORE INTO `msz_changelog_change_tags`
(`change_id`, `tag_id`)
VALUES
(:change_id, :tag_id)
');
$addTag->bindValue('change_id', $changeId);
$addTag->bind('change_id', $changeId);
foreach($setTags as $role) {
$addTag->bindValue('tag_id', $role);
$addTag->bind('tag_id', $role);
$addTag->execute();
}
}
@ -90,15 +92,15 @@ $actions = [
];
if($changeId > 0) {
$getChange = db_prepare('
$getChange = DB::prepare('
SELECT
`change_id`, `change_log`, `change_text`, `user_id`,
`change_action`, `change_created`
FROM `msz_changelog_changes`
WHERE `change_id` = :change_id
');
$getChange->bindValue('change_id', $changeId);
$change = db_fetch($getChange);
$getChange->bind('change_id', $changeId);
$change = $getChange->fetch();
if(!$change) {
url_redirect('manage-changelog-changes');
@ -106,7 +108,7 @@ if($changeId > 0) {
}
}
$getChangeTags = db_prepare('
$getChangeTags = DB::prepare('
SELECT
ct.`tag_id`, ct.`tag_name`,
(
@ -117,8 +119,8 @@ $getChangeTags = db_prepare('
) AS `has_tag`
FROM `msz_changelog_tags` AS ct
');
$getChangeTags->bindValue('change_id', $change['change_id'] ?? 0);
$changeTags = db_fetch_all($getChangeTags);
$getChangeTags->bind('change_id', $change['change_id'] ?? 0);
$changeTags = $getChangeTags->fetchAll();
echo tpl_render('manage.changelog.change', [
'change' => $change ?? null,

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
require_once '../../../misuzu.php';
if(!perms_check_user(MSZ_PERMS_CHANGELOG, user_session_current('user_id'), MSZ_PERM_CHANGELOG_MANAGE_CHANGES)) {
@ -6,7 +8,7 @@ if(!perms_check_user(MSZ_PERMS_CHANGELOG, user_session_current('user_id'), MSZ_P
return;
}
$changesCount = (int)db_query('
$changesCount = (int)DB::query('
SELECT COUNT(`change_id`)
FROM `msz_changelog_changes`
')->fetchColumn();
@ -19,7 +21,7 @@ if(!pagination_is_valid_offset($changelogOffset)) {
return;
}
$getChanges = db_prepare('
$getChanges = DB::prepare('
SELECT
c.`change_id`, c.`change_log`, c.`change_created`, c.`change_action`,
u.`user_id`, u.`username`,
@ -34,11 +36,11 @@ $getChanges = db_prepare('
ORDER BY c.`change_id` DESC
LIMIT :offset, :take
');
$getChanges->bindValue('take', $changelogPagination['range']);
$getChanges->bindValue('offset', $changelogOffset);
$changes = db_fetch_all($getChanges);
$getChanges->bind('take', $changelogPagination['range']);
$getChanges->bind('offset', $changelogOffset);
$changes = $getChanges->fetchAll();
$getTags = db_prepare('
$getTags = DB::prepare('
SELECT
t.`tag_id`, t.`tag_name`, t.`tag_description`
FROM `msz_changelog_change_tags` as ct
@ -49,8 +51,8 @@ $getTags = db_prepare('
// grab tags
for($i = 0; $i < count($changes); $i++) {
$getTags->bindValue('change_id', $changes[$i]['change_id']);
$changes[$i]['tags'] = db_fetch_all($getTags);
$getTags->bind('change_id', $changes[$i]['change_id']);
$changes[$i]['tags'] = $getTags->fetchAll();
}
echo tpl_render('manage.changelog.changes', [

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
require_once '../../../misuzu.php';
if(!perms_check_user(MSZ_PERMS_CHANGELOG, user_session_current('user_id'), MSZ_PERM_CHANGELOG_MANAGE_TAGS)) {
@ -10,16 +12,16 @@ $tagId = (int)($_GET['t'] ?? 0);
if(!empty($_POST['tag']) && is_array($_POST['tag']) && csrf_verify_request()) {
if($tagId > 0) {
$updateTag = db_prepare('
$updateTag = DB::prepare('
UPDATE `msz_changelog_tags`
SET `tag_name` = :name,
`tag_description` = :description,
`tag_archived` = :archived
WHERE `tag_id` = :id
');
$updateTag->bindValue('id', $tagId);
$updateTag->bind('id', $tagId);
} else {
$updateTag = db_prepare('
$updateTag = DB::prepare('
INSERT INTO `msz_changelog_tags`
(`tag_name`, `tag_description`, `tag_archived`)
VALUES
@ -27,13 +29,13 @@ if(!empty($_POST['tag']) && is_array($_POST['tag']) && csrf_verify_request()) {
');
}
$updateTag->bindValue('name', $_POST['tag']['name']);
$updateTag->bindValue('description', $_POST['tag']['description']);
$updateTag->bindValue('archived', empty($_POST['tag']['archived']) ? null : date('Y-m-d H:i:s'));
$updateTag->bind('name', $_POST['tag']['name']);
$updateTag->bind('description', $_POST['tag']['description']);
$updateTag->bind('archived', empty($_POST['tag']['archived']) ? null : date('Y-m-d H:i:s'));
$updateTag->execute();
if($tagId < 1) {
$tagId = db_last_insert_id();
$tagId = DB::lastId();
audit_log(MSZ_AUDIT_CHANGELOG_TAG_EDIT, user_session_current('user_id', 0), [$tagId]);
url_redirect('manage-changelog-tag', ['tag' => $tagId]);
return;
@ -43,13 +45,13 @@ if(!empty($_POST['tag']) && is_array($_POST['tag']) && csrf_verify_request()) {
}
if($tagId > 0) {
$getTag = db_prepare('
$getTag = DB::prepare('
SELECT `tag_id`, `tag_name`, `tag_description`, `tag_archived`, `tag_created`
FROM `msz_changelog_tags`
WHERE `tag_id` = :tag_id
');
$getTag->bindValue('tag_id', $tagId);
$tag = db_fetch($getTag);
$getTag->bind('tag_id', $tagId);
$tag = $getTag->fetch();
if($tag) {
tpl_var('edit_tag', $tag);

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
require_once '../../../misuzu.php';
if(!perms_check_user(MSZ_PERMS_CHANGELOG, user_session_current('user_id'), MSZ_PERM_CHANGELOG_MANAGE_TAGS)) {
@ -6,7 +8,7 @@ if(!perms_check_user(MSZ_PERMS_CHANGELOG, user_session_current('user_id'), MSZ_P
return;
}
$getTags = db_prepare('
$getTags = DB::prepare('
SELECT
t.`tag_id`, t.`tag_name`, t.`tag_description`, t.`tag_created`,
(
@ -19,5 +21,5 @@ $getTags = db_prepare('
');
echo tpl_render('manage.changelog.tags', [
'changelog_tags' => db_fetch_all($getTags),
'changelog_tags' => $getTags->fetchAll(),
]);

View file

@ -6,13 +6,13 @@ if(!perms_check_user(MSZ_PERMS_GENERAL, user_session_current('user_id'), MSZ_PER
return;
}
$getForum = db_prepare('
$getForum = DB::prepare('
SELECT *
FROM `msz_forum_categories`
WHERE `forum_id` = :forum_id
');
$getForum->bindValue('forum_id', (int)($_GET['f'] ?? 0));
$forum = db_fetch($getForum);
$getForum->bind('forum_id', (int)($_GET['f'] ?? 0));
$forum = $getForum->fetch();
if(!$forum) {
echo render_error(404);

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
require_once '../../../misuzu.php';
if(!perms_check_user(MSZ_PERMS_GENERAL, user_session_current('user_id'), MSZ_PERM_FORUM_MANAGE_FORUMS)) {
@ -6,7 +8,7 @@ if(!perms_check_user(MSZ_PERMS_GENERAL, user_session_current('user_id'), MSZ_PER
return;
}
$forums = db_query('SELECT * FROM `msz_forum_categories`');
$forums = DB::query('SELECT * FROM `msz_forum_categories`')->fetchAll();
$rawPerms = perms_create(MSZ_FORUM_PERM_MODES);
$perms = manage_forum_perms_list($rawPerms);

View file

@ -1,173 +1,175 @@
<?php
namespace Misuzu;
require_once '../../../misuzu.php';
$statistics = db_fetch(db_query('
$statistics = DB::query('
SELECT
(
SELECT COUNT(`user_id`)
FROM `msz_users`
) AS `stat_users_total`,
(
SELECT COUNT(`user_id`)
FROM `msz_users`
WHERE `user_deleted` IS NOT NULL
) AS `stat_users_deleted`,
(
SELECT COUNT(`user_id`)
FROM `msz_users`
WHERE `user_active` IS NOT NULL
AND `user_deleted` IS NULL
) AS `stat_users_active`,
(
SELECT COUNT(`log_id`)
FROM `msz_audit_log`
) AS `stat_audit_logs`,
(
SELECT COUNT(`change_id`)
FROM `msz_changelog_changes`
) AS `stat_changelog_entries`,
(
SELECT COUNT(`category_id`)
FROM `msz_comments_categories`
) AS `stat_comment_categories_total`,
(
SELECT COUNT(`category_id`)
FROM `msz_comments_categories`
WHERE `category_locked` IS NOT NULL
) AS `stat_comment_categories_locked`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
) AS `stat_comment_posts_total`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
WHERE `comment_deleted` IS NOT NULL
) AS `stat_comment_posts_deleted`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
WHERE `comment_reply_to` IS NOT NULL
) AS `stat_comment_posts_replies`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
WHERE `comment_pinned` IS NOT NULL
) AS `stat_comment_posts_pinned`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
WHERE `comment_edited` IS NOT NULL
) AS `stat_comment_posts_edited`,
(
SELECT COUNT(`user_id`)
FROM `msz_comments_votes`
WHERE `comment_vote` > 0
) AS `stat_comment_likes`,
(
SELECT COUNT(`user_id`)
FROM `msz_comments_votes`
WHERE `comment_vote` < 0
) AS `stat_comment_dislikes`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
) AS `stat_forum_posts_total`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_deleted` IS NOT NULL
) AS `stat_forum_posts_deleted`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_edited` IS NOT NULL
) AS `stat_forum_posts_edited`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_parse` = 0
) AS `stat_forum_posts_plain`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_parse` = 1
) AS `stat_forum_posts_bbcode`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_parse` = 2
) AS `stat_forum_posts_markdown`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_display_signature` != 0
) AS `stat_forum_posts_signature`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
) AS `stat_forum_topics_total`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_type` = 0
) AS `stat_forum_topics_normal`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_type` = 1
) AS `stat_forum_topics_pinned`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_type` = 2
) AS `stat_forum_topics_announce`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_type` = 3
) AS `stat_forum_topics_global_announce`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_deleted` IS NOT NULL
) AS `stat_forum_topics_deleted`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_locked` IS NOT NULL
) AS `stat_forum_topics_locked`,
(
SELECT COUNT(*)
FROM `msz_ip_blacklist`
) AS `stat_blacklist`,
(
SELECT COUNT(`attempt_id`)
FROM `msz_login_attempts`
) AS `stat_login_attempts_total`,
(
SELECT COUNT(`attempt_id`)
FROM `msz_login_attempts`
WHERE `attempt_success` = 0
) AS `stat_login_attempts_failed`,
(
SELECT COUNT(`session_id`)
FROM `msz_sessions`
) AS `stat_user_sessions`,
(
SELECT COUNT(`user_id`)
FROM `msz_users_password_resets`
) AS `stat_user_password_resets`,
(
SELECT COUNT(`user_id`)
FROM `msz_user_relations`
) AS `stat_user_relations`,
(
SELECT COUNT(`warning_id`)
FROM `msz_user_warnings`
WHERE `warning_type` != 0
) AS `stat_user_warnings`
'));
(
SELECT COUNT(`user_id`)
FROM `msz_users`
) AS `stat_users_total`,
(
SELECT COUNT(`user_id`)
FROM `msz_users`
WHERE `user_deleted` IS NOT NULL
) AS `stat_users_deleted`,
(
SELECT COUNT(`user_id`)
FROM `msz_users`
WHERE `user_active` IS NOT NULL
AND `user_deleted` IS NULL
) AS `stat_users_active`,
(
SELECT COUNT(`log_id`)
FROM `msz_audit_log`
) AS `stat_audit_logs`,
(
SELECT COUNT(`change_id`)
FROM `msz_changelog_changes`
) AS `stat_changelog_entries`,
(
SELECT COUNT(`category_id`)
FROM `msz_comments_categories`
) AS `stat_comment_categories_total`,
(
SELECT COUNT(`category_id`)
FROM `msz_comments_categories`
WHERE `category_locked` IS NOT NULL
) AS `stat_comment_categories_locked`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
) AS `stat_comment_posts_total`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
WHERE `comment_deleted` IS NOT NULL
) AS `stat_comment_posts_deleted`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
WHERE `comment_reply_to` IS NOT NULL
) AS `stat_comment_posts_replies`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
WHERE `comment_pinned` IS NOT NULL
) AS `stat_comment_posts_pinned`,
(
SELECT COUNT(`comment_id`)
FROM `msz_comments_posts`
WHERE `comment_edited` IS NOT NULL
) AS `stat_comment_posts_edited`,
(
SELECT COUNT(`user_id`)
FROM `msz_comments_votes`
WHERE `comment_vote` > 0
) AS `stat_comment_likes`,
(
SELECT COUNT(`user_id`)
FROM `msz_comments_votes`
WHERE `comment_vote` < 0
) AS `stat_comment_dislikes`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
) AS `stat_forum_posts_total`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_deleted` IS NOT NULL
) AS `stat_forum_posts_deleted`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_edited` IS NOT NULL
) AS `stat_forum_posts_edited`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_parse` = 0
) AS `stat_forum_posts_plain`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_parse` = 1
) AS `stat_forum_posts_bbcode`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_parse` = 2
) AS `stat_forum_posts_markdown`,
(
SELECT COUNT(`post_id`)
FROM `msz_forum_posts`
WHERE `post_display_signature` != 0
) AS `stat_forum_posts_signature`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
) AS `stat_forum_topics_total`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_type` = 0
) AS `stat_forum_topics_normal`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_type` = 1
) AS `stat_forum_topics_pinned`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_type` = 2
) AS `stat_forum_topics_announce`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_type` = 3
) AS `stat_forum_topics_global_announce`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_deleted` IS NOT NULL
) AS `stat_forum_topics_deleted`,
(
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics`
WHERE `topic_locked` IS NOT NULL
) AS `stat_forum_topics_locked`,
(
SELECT COUNT(*)
FROM `msz_ip_blacklist`
) AS `stat_blacklist`,
(
SELECT COUNT(`attempt_id`)
FROM `msz_login_attempts`
) AS `stat_login_attempts_total`,
(
SELECT COUNT(`attempt_id`)
FROM `msz_login_attempts`
WHERE `attempt_success` = 0
) AS `stat_login_attempts_failed`,
(
SELECT COUNT(`session_id`)
FROM `msz_sessions`
) AS `stat_user_sessions`,
(
SELECT COUNT(`user_id`)
FROM `msz_users_password_resets`
) AS `stat_user_password_resets`,
(
SELECT COUNT(`user_id`)
FROM `msz_user_relations`
) AS `stat_user_relations`,
(
SELECT COUNT(`warning_id`)
FROM `msz_user_warnings`
WHERE `warning_type` != 0
) AS `stat_user_warnings`
')->fetch();
if(!empty($_GET['poll'])) {
header('Content-Type: application/json; charset=utf-8');

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
require_once '../../../misuzu.php';
if(!perms_check_user(MSZ_PERMS_USER, user_session_current('user_id'), MSZ_PERM_USER_MANAGE_USERS)) {
@ -6,7 +8,7 @@ if(!perms_check_user(MSZ_PERMS_USER, user_session_current('user_id'), MSZ_PERM_U
return;
}
$manageUsersCount = db_query('
$manageUsersCount = (int)DB::query('
SELECT COUNT(`user_id`)
FROM `msz_users`
')->fetchColumn();
@ -19,7 +21,7 @@ if(!pagination_is_valid_offset($usersOffset)) {
return;
}
$getManageUsers = db_prepare('
$getManageUsers = DB::prepare('
SELECT
u.`user_id`, u.`username`, u.`user_country`, r.`role_id`,
u.`user_created`, u.`user_active`, u.`user_deleted`,
@ -32,9 +34,9 @@ $getManageUsers = db_prepare('
ORDER BY `user_id`
LIMIT :offset, :take
');
$getManageUsers->bindValue('offset', $usersOffset);
$getManageUsers->bindValue('take', $usersPagination['range']);
$manageUsers = db_fetch_all($getManageUsers);
$getManageUsers->bind('offset', $usersOffset);
$getManageUsers->bind('take', $usersPagination['range']);
$manageUsers = $getManageUsers->fetchAll();
echo tpl_render('manage.users.users', [
'manage_users' => $manageUsers,

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
// TODO: UNFUCK THIS FILE
require_once '../../../misuzu.php';
@ -87,7 +89,7 @@ if(!empty($_POST['role']) && is_array($_POST['role']) && csrf_verify_request())
}
if($roleId < 1) {
$updateRole = db_prepare('
$updateRole = DB::prepare('
INSERT INTO `msz_roles`
(
`role_name`, `role_hierarchy`, `role_hidden`, `role_colour`,
@ -100,7 +102,7 @@ if(!empty($_POST['role']) && is_array($_POST['role']) && csrf_verify_request())
)
');
} else {
$updateRole = db_prepare('
$updateRole = DB::prepare('
UPDATE `msz_roles`
SET `role_name` = :role_name,
`role_hierarchy` = :role_hierarchy,
@ -110,19 +112,19 @@ if(!empty($_POST['role']) && is_array($_POST['role']) && csrf_verify_request())
`role_title` = :role_title
WHERE `role_id` = :role_id
');
$updateRole->bindValue('role_id', $roleId);
$updateRole->bind('role_id', $roleId);
}
$updateRole->bindValue('role_name', $roleName);
$updateRole->bindValue('role_hierarchy', $roleHierarchy);
$updateRole->bindValue('role_hidden', $roleSecret ? 1 : 0);
$updateRole->bindValue('role_colour', $roleColour);
$updateRole->bindValue('role_description', $roleDescription);
$updateRole->bindValue('role_title', $roleTitle);
$updateRole->bind('role_name', $roleName);
$updateRole->bind('role_hierarchy', $roleHierarchy);
$updateRole->bind('role_hidden', $roleSecret ? 1 : 0);
$updateRole->bind('role_colour', $roleColour);
$updateRole->bind('role_description', $roleDescription);
$updateRole->bind('role_title', $roleTitle);
$updateRole->execute();
if($roleId < 1) {
$roleId = (int)db_last_insert_id();
$roleId = DB::lastId();
}
if(!empty($permissions) && !empty($_POST['perms']) && is_array($_POST['perms'])) {
@ -130,26 +132,26 @@ if(!empty($_POST['role']) && is_array($_POST['role']) && csrf_verify_request())
if($perms !== null) {
$permKeys = array_keys($perms);
$setPermissions = db_prepare('
$setPermissions = DB::prepare('
REPLACE INTO `msz_permissions`
(`role_id`, `user_id`, `' . implode('`, `', $permKeys) . '`)
VALUES
(:role_id, NULL, :' . implode(', :', $permKeys) . ')
');
$setPermissions->bindValue('role_id', $roleId);
$setPermissions->bind('role_id', $roleId);
foreach($perms as $key => $value) {
$setPermissions->bindValue($key, $value);
$setPermissions->bind($key, $value);
}
$setPermissions->execute();
} else {
$deletePermissions = db_prepare('
$deletePermissions = DB::prepare('
DELETE FROM `msz_permissions`
WHERE `role_id` = :role_id
AND `user_id` IS NULL
');
$deletePermissions->bindValue('role_id', $roleId);
$deletePermissions->bind('role_id', $roleId);
$deletePermissions->execute();
}
}
@ -164,13 +166,13 @@ if($roleId !== null) {
return;
}
$getEditRole = db_prepare('
$getEditRole = DB::prepare('
SELECT *
FROM `msz_roles`
WHERE `role_id` = :role_id
');
$getEditRole->bindValue('role_id', $roleId);
$editRole = db_fetch($getEditRole);
$getEditRole->bind('role_id', $roleId);
$editRole = $getEditRole->fetch();
if(empty($editRole)) {
echo 'invalid role';

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
require_once '../../../misuzu.php';
if(!perms_check_user(MSZ_PERMS_USER, user_session_current('user_id'), MSZ_PERM_USER_MANAGE_ROLES)) {
@ -6,7 +8,7 @@ if(!perms_check_user(MSZ_PERMS_USER, user_session_current('user_id'), MSZ_PERM_U
return;
}
$manageRolesCount = db_query('
$manageRolesCount = (int)DB::query('
SELECT COUNT(`role_id`)
FROM `msz_roles`
')->fetchColumn();
@ -19,7 +21,7 @@ if(!pagination_is_valid_offset($rolesOffset)) {
return;
}
$getManageRoles = db_prepare('
$getManageRoles = DB::prepare('
SELECT
`role_id`, `role_colour`, `role_name`, `role_title`,
(
@ -30,9 +32,9 @@ $getManageRoles = db_prepare('
FROM `msz_roles` as r
LIMIT :offset, :take
');
$getManageRoles->bindValue('offset', $rolesOffset);
$getManageRoles->bindValue('take', $rolesPagination['range']);
$manageRoles = db_fetch_all($getManageRoles);
$getManageRoles->bind('offset', $rolesOffset);
$getManageRoles->bind('take', $rolesPagination['range']);
$manageRoles = $getManageRoles->fetchAll();
echo tpl_render('manage.users.roles', [
'manage_roles' => $manageRoles,

View file

@ -23,13 +23,13 @@ $permissions = manage_perms_list(perms_get_user_raw($userId));
if(csrf_verify_request() && $canEdit) {
if(!empty($_POST['roles']) && is_array($_POST['roles']) && array_test($_POST['roles'], 'ctype_digit')) {
// Fetch existing roles
$existingRoles = db_prepare('
$existingRoles = DB::prepare('
SELECT `role_id`
FROM `msz_user_roles`
WHERE `user_id` = :user_id
');
$existingRoles->bindValue('user_id', $userId);
$existingRoles = db_fetch_all($existingRoles);
$existingRoles->bind('user_id', $userId);
$existingRoles = $existingRoles->fetchAll();
// Initialise set array with existing role ids
$setRoles = array_column($existingRoles, 'role_id');
@ -70,24 +70,24 @@ if(csrf_verify_request() && $canEdit) {
if(!empty($setRoles)) {
// The implode here probably sets off alarm bells, but the array is
// guaranteed to only contain integers so it's probably fine.
$removeRanks = db_prepare(sprintf('
$removeRanks = DB::prepare(sprintf('
DELETE FROM `msz_user_roles`
WHERE `user_id` = :user_id
AND `role_id` NOT IN (%s)
', implode(',', $setRoles)));
$removeRanks->bindValue('user_id', $userId);
$removeRanks->bind('user_id', $userId);
$removeRanks->execute();
$addRank = db_prepare('
$addRank = DB::prepare('
INSERT IGNORE INTO `msz_user_roles`
(`user_id`, `role_id`)
VALUES
(:user_id, :role_id)
');
$addRank->bindValue('user_id', $userId);
$addRank->bind('user_id', $userId);
foreach($setRoles as $role) {
$addRank->bindValue('role_id', $role);
$addRank->bind('role_id', $role);
$addRank->execute();
}
}
@ -166,7 +166,7 @@ if(csrf_verify_request() && $canEdit) {
}
if(empty($notices) && !empty($setUserInfo)) {
$userUpdate = db_prepare(sprintf(
$userUpdate = DB::prepare(sprintf(
'
UPDATE `msz_users`
SET %s
@ -174,10 +174,10 @@ if(csrf_verify_request() && $canEdit) {
',
pdo_prepare_array_update($setUserInfo, true)
));
$userUpdate->bindValue('set_user_id', $userId);
$userUpdate->bind('set_user_id', $userId);
foreach($setUserInfo as $key => $value) {
$userUpdate->bindValue($key, $value);
$userUpdate->bind($key, $value);
}
if(!$userUpdate->execute()) {
@ -203,7 +203,7 @@ if(csrf_verify_request() && $canEdit) {
}
}
$getUser = db_prepare('
$getUser = DB::prepare('
SELECT
u.*,
INET6_NTOA(u.`register_ip`) as `register_ip_decoded`,
@ -215,15 +215,15 @@ $getUser = db_prepare('
WHERE `user_id` = :user_id
ORDER BY `user_id`
');
$getUser->bindValue('user_id', $userId);
$manageUser = db_fetch($getUser);
$getUser->bind('user_id', $userId);
$manageUser = $getUser->fetch();
if(empty($manageUser)) {
echo render_error(404);
return;
}
$getRoles = db_prepare('
$getRoles = DB::prepare('
SELECT
r.`role_id`, r.`role_name`, r.`role_hierarchy`, r.`role_colour`,
(
@ -234,8 +234,8 @@ $getRoles = db_prepare('
) AS `has_role`
FROM `msz_roles` AS r
');
$getRoles->bindValue('user_id', $manageUser['user_id']);
$roles = db_fetch_all($getRoles);
$getRoles->bind('user_id', $manageUser['user_id']);
$roles = $getRoles->fetchAll();
echo tpl_render('manage.users.user', [
'manage_user' => $manageUser,

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
require_once '../misuzu.php';
$roleId = !empty($_GET['r']) && is_string($_GET['r']) ? (int)$_GET['r'] : MSZ_ROLE_MAIN;
@ -95,7 +97,7 @@ if(!pagination_is_valid_offset($usersOffset)) {
$roles = user_role_all();
$getUsers = db_prepare(sprintf(
$getUsers = DB::prepare(sprintf(
'
SELECT
:current_user_id AS `current_user_id`,
@ -154,11 +156,11 @@ $getUsers = db_prepare(sprintf(
$orderDir,
MSZ_USER_RELATION_FOLLOW
));
$getUsers->bindValue('role_id', $role['role_id']);
$getUsers->bindValue('offset', $usersOffset);
$getUsers->bindValue('take', $usersPagination['range']);
$getUsers->bindValue('current_user_id', user_session_current('user_id', 0));
$users = db_fetch_all($getUsers);
$getUsers->bind('role_id', $role['role_id']);
$getUsers->bind('offset', $usersOffset);
$getUsers->bind('take', $usersPagination['range']);
$getUsers->bind('current_user_id', user_session_current('user_id', 0));
$users = $getUsers->fetchAll();
echo tpl_render('user.listing', [
'roles' => $roles,

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
require_once '../misuzu.php';
$searchQuery = !empty($_GET['q']) && is_string($_GET['q']) ? $_GET['q'] : '';
@ -8,7 +10,7 @@ if(!empty($searchQuery)) {
$forumPosts = forum_post_search($searchQuery);
$newsPosts = news_posts_search($searchQuery);
$findUsers = db_prepare(sprintf(
$findUsers = DB::prepare(sprintf(
'
SELECT
:current_user_id AS `current_user_id`,
@ -62,9 +64,9 @@ if(!empty($searchQuery)) {
',
MSZ_USER_RELATION_FOLLOW
));
$findUsers->bindValue('query', $searchQuery);
$findUsers->bindValue('current_user_id', user_session_current('user_id', 0));
$users = db_fetch_all($findUsers);
$findUsers->bind('query', $searchQuery);
$findUsers->bind('current_user_id', user_session_current('user_id', 0));
$users = $findUsers->fetchAll();
}
echo tpl_render('home.search', [

View file

@ -1,4 +1,6 @@
<?php
namespace Misuzu;
require_once '../../misuzu.php';
if(!user_session_active()) {
@ -7,17 +9,17 @@ if(!user_session_active()) {
}
function db_to_zip(ZipArchive $archive, int $userId, string $filename, string $query, int $params = 1): void {
$prepare = db_prepare($query);
$prepare = DB::prepare($query);
if($params < 2) {
$prepare->bindValue('user_id', $userId);
$prepare->bind('user_id', $userId);
} else {
for($i = 1; $i <= $params; $i++) {
$prepare->bindValue('user_id_' . $i, $userId);
$prepare->bind('user_id_' . $i, $userId);
}
}
$archive->addFromString($filename, json_encode(db_fetch_all($prepare), JSON_PRETTY_PRINT));
$archive->addFromString($filename, json_encode($prepare->fetchAll(), JSON_PRETTY_PRINT));
}
$errors = [];

49
src/Database/Database.php Normal file
View file

@ -0,0 +1,49 @@
<?php
namespace Misuzu\Database;
use PDO;
class Database {
public $pdo;
private $stmts = [];
public function __construct(string $dsn, string $username = '', string $password = '', array $options = []) {
$this->pdo = new PDO($dsn, $username, $password, $options);
}
public function getPDO(): PDO {
return $this->pdo;
}
public function queries(): int {
return (int)$this->query('SHOW SESSION STATUS LIKE "Questions"')->fetchColumn(1);
}
public function exec(string $stmt): int {
return $this->pdo->exec($stmt);
}
public function prepare(string $stmt, array $options = []): DatabaseStatement {
$encodedOptions = serialize($options);
if(empty($this->stmts[$stmt][$encodedOptions])) {
$this->stmts[$stmt][$encodedOptions] = $this->pdo->prepare($stmt, $options);
}
return new DatabaseStatement($this->stmts[$stmt][$encodedOptions], $this->pdo, false);
}
public function query(string $stmt, ?int $fetchMode = null, ...$args): DatabaseStatement {
if($fetchMode === null) {
$pdoStmt = $this->pdo->query($stmt);
} else {
$pdoStmt = $this->pdo->query($stmt, $fetchMode, ...$args);
}
return new DatabaseStatement($pdoStmt, $this->pdo, true);
}
public function lastId(): int {
return $this->pdo->lastInsertId();
}
}

View file

@ -1,5 +1,5 @@
<?php
namespace Misuzu;
namespace Misuzu\Database;
use Exception;
use PDO;

View file

@ -0,0 +1,45 @@
<?php
namespace Misuzu\Database;
use PDO;
use PDOStatement;
class DatabaseStatement {
public $pdo;
public $stmt;
private $isQuery;
public function __construct(PDOStatement $stmt, PDO $pdo, bool $isQuery) {
$this->stmt = $stmt;
$this->pdo = $pdo;
$this->isQuery = $isQuery;
}
public function bind($param, $value, int $dataType = PDO::PARAM_STR): DatabaseStatement {
$this->stmt->bindValue($param, $value, $dataType);
return $this;
}
public function execute(array $params = []): bool {
return count($params) ? $this->stmt->execute($params) : $this->stmt->execute();
}
public function executeGetId(array $params = []): int {
return $this->execute($params) ? $this->pdo->lastInsertId() : 0;
}
public function fetch($default = []) {
$out = $this->isQuery || $this->execute() ? $this->stmt->fetch(PDO::FETCH_ASSOC) : false;
return $out ? $out : $default;
}
public function fetchAll($default = []) {
$out = $this->isQuery || $this->execute() ? $this->stmt->fetchAll(PDO::FETCH_ASSOC) : false;
return $out ? $out : $default;
}
public function fetchColumn(int $num = 0, $default = null) {
$out = $this->isQuery || $this->execute() ? $this->stmt->fetchColumn($num) : false;
return $out ? $out : $default;
}
}

View file

@ -99,7 +99,7 @@ function forum_has_priority_voting(int $forumType): bool {
}
function forum_get(int $forumId, bool $showDeleted = false): array {
$getForum = db_prepare(sprintf(
$getForum = \Misuzu\DB::prepare(sprintf(
'
SELECT
`forum_id`, `forum_name`, `forum_type`, `forum_link`, `forum_archived`,
@ -115,12 +115,12 @@ function forum_get(int $forumId, bool $showDeleted = false): array {
',
$showDeleted ? '' : 'AND `topic_deleted` IS NULL'
));
$getForum->bindValue('forum_id', $forumId);
return db_fetch($getForum);
$getForum->bind('forum_id', $forumId);
return $getForum->fetch();
}
function forum_get_root_categories(int $userId): array {
$getCategories = db_prepare(sprintf(
$getCategories = \Misuzu\DB::prepare(sprintf(
'
SELECT
f.`forum_id`, f.`forum_name`, f.`forum_type`, f.`forum_colour`, f.`forum_icon`,
@ -138,9 +138,9 @@ function forum_get_root_categories(int $userId): array {
',
MSZ_FORUM_TYPE_CATEGORY
));
$categories = array_merge([MSZ_FORUM_ROOT_DATA], db_fetch_all($getCategories));
$categories = array_merge([MSZ_FORUM_ROOT_DATA], $getCategories->fetchAll());
$getRootForumCount = db_prepare(sprintf(
$getRootForumCount = \Misuzu\DB::prepare(sprintf(
"
SELECT COUNT(`forum_id`)
FROM `msz_forum_categories`
@ -150,7 +150,7 @@ function forum_get_root_categories(int $userId): array {
MSZ_FORUM_ROOT,
MSZ_FORUM_TYPE_CATEGORY
));
$categories[0]['forum_children'] = (int)($getRootForumCount->execute() ? $getRootForumCount->fetchColumn() : 0);
$categories[0]['forum_children'] = (int)$getRootForumCount->fetchColumn();
foreach($categories as $key => $category) {
$categories[$key]['forum_permissions'] = $perms = forum_perms_get_user($category['forum_id'], $userId)[MSZ_FORUM_PERMS_GENERAL];
@ -177,15 +177,15 @@ function forum_get_breadcrumbs(
array $indexLink = ['Forums' => '/forum/']
): array {
$breadcrumbs = [];
$getBreadcrumb = db_prepare('
$getBreadcrumb = \Misuzu\DB::prepare('
SELECT `forum_id`, `forum_name`, `forum_type`, `forum_parent`
FROM `msz_forum_categories`
WHERE `forum_id` = :forum_id
');
while($forumId > 0) {
$getBreadcrumb->bindValue('forum_id', $forumId);
$breadcrumb = db_fetch($getBreadcrumb);
$getBreadcrumb->bind('forum_id', $forumId);
$breadcrumb = $getBreadcrumb->fetch();
if(empty($breadcrumb)) {
break;
@ -205,15 +205,15 @@ function forum_get_breadcrumbs(
}
function forum_get_colour(int $forumId): int {
$getColours = db_prepare('
$getColours = \Misuzu\DB::prepare('
SELECT `forum_id`, `forum_parent`, `forum_colour`
FROM `msz_forum_categories`
WHERE `forum_id` = :forum_id
');
while($forumId > 0) {
$getColours->bindValue('forum_id', $forumId);
$colourInfo = db_fetch($getColours);
$getColours->bind('forum_id', $forumId);
$colourInfo = $getColours->fetch();
if(empty($colourInfo)) {
break;
@ -230,14 +230,14 @@ function forum_get_colour(int $forumId): int {
}
function forum_increment_clicks(int $forumId): void {
$incrementLinkClicks = db_prepare(sprintf('
$incrementLinkClicks = \Misuzu\DB::prepare(sprintf('
UPDATE `msz_forum_categories`
SET `forum_link_clicks` = `forum_link_clicks` + 1
WHERE `forum_id` = :forum_id
AND `forum_type` = %d
AND `forum_link_clicks` IS NOT NULL
', MSZ_FORUM_TYPE_LINK));
$incrementLinkClicks->bindValue('forum_id', $forumId);
$incrementLinkClicks->bind('forum_id', $forumId);
$incrementLinkClicks->execute();
}
@ -252,14 +252,14 @@ function forum_get_parent_id(int $forumId): int {
return $memoized[$forumId];
}
$getParent = db_prepare('
$getParent = \Misuzu\DB::prepare('
SELECT `forum_parent`
FROM `msz_forum_categories`
WHERE `forum_id` = :forum_id
');
$getParent->bindValue('forum_id', $forumId);
$getParent->bind('forum_id', $forumId);
return (int)($getParent->execute() ? $getParent->fetchColumn() : 0);
return (int)$getParent->fetchColumn();
}
function forum_get_child_ids(int $forumId): array {
@ -273,13 +273,13 @@ function forum_get_child_ids(int $forumId): array {
return $memoized[$forumId];
}
$getChildren = db_prepare('
$getChildren = \Misuzu\DB::prepare('
SELECT `forum_id`
FROM `msz_forum_categories`
WHERE `forum_parent` = :forum_id
');
$getChildren->bindValue('forum_id', $forumId);
$children = db_fetch_all($getChildren);
$getChildren->bind('forum_id', $forumId);
$children = $getChildren->fetchAll();
return $memoized[$forumId] = array_column($children, 'forum_id');
}
@ -304,7 +304,7 @@ function forum_topics_unread(int $forumId, int $userId): int {
}
if(forum_perms_check_user(MSZ_FORUM_PERMS_GENERAL, $forumId, $userId, MSZ_FORUM_PERM_SET_READ)) {
$countUnread = db_prepare('
$countUnread = \Misuzu\DB::prepare('
SELECT COUNT(ti.`topic_id`)
FROM `msz_forum_topics` AS ti
LEFT JOIN `msz_forum_topics_track` AS tt
@ -317,9 +317,9 @@ function forum_topics_unread(int $forumId, int $userId): int {
OR tt.`track_last_read` < ti.`topic_bumped`
)
');
$countUnread->bindValue('forum_id', $forumId);
$countUnread->bindValue('user_id', $userId);
$memoized[$memoId] += (int)($countUnread->execute() ? $countUnread->fetchColumn() : 0);
$countUnread->bind('forum_id', $forumId);
$countUnread->bind('user_id', $userId);
$memoized[$memoId] += (int)$countUnread->fetchColumn();
}
return $memoized[$memoId];
@ -341,7 +341,7 @@ function forum_latest_post(int $forumId, int $userId): array {
return $memoized[$memoId] = [];
}
$getLastPost = db_prepare('
$getLastPost = \Misuzu\DB::prepare('
SELECT
p.`post_id` AS `recent_post_id`, t.`topic_id` AS `recent_topic_id`,
t.`topic_title` AS `recent_topic_title`, t.`topic_bumped` AS `recent_topic_bumped`,
@ -361,8 +361,8 @@ function forum_latest_post(int $forumId, int $userId): array {
AND p.`post_deleted` IS NULL
ORDER BY p.`post_id` DESC
');
$getLastPost->bindValue('forum_id', $forumId);
$currentLast = db_fetch($getLastPost);
$getLastPost->bind('forum_id', $forumId);
$currentLast = $getLastPost->fetch();
$children = forum_get_child_ids($forumId);
@ -378,7 +378,7 @@ function forum_latest_post(int $forumId, int $userId): array {
}
function forum_get_children(int $parentId, int $userId): array {
$getListing = db_prepare(sprintf(
$getListing = \Misuzu\DB::prepare(sprintf(
'
SELECT
:user_id AS `target_user_id`,
@ -399,10 +399,10 @@ function forum_get_children(int $parentId, int $userId): array {
MSZ_FORUM_TYPE_CATEGORY
));
$getListing->bindValue('user_id', $userId);
$getListing->bindValue('parent_id', $parentId);
$getListing->bind('user_id', $userId);
$getListing->bind('parent_id', $parentId);
$listing = db_fetch_all($getListing);
$listing = $getListing->fetchAll();
foreach($listing as $key => $forum) {
$listing[$key]['forum_permissions'] = $perms = forum_perms_get_user($forum['forum_id'], $userId)[MSZ_FORUM_PERMS_GENERAL];
@ -423,16 +423,16 @@ function forum_get_children(int $parentId, int $userId): array {
}
function forum_timeout(int $forumId, int $userId): int {
$checkTimeout = db_prepare('
$checkTimeout = \Misuzu\DB::prepare('
SELECT TIMESTAMPDIFF(SECOND, COALESCE(MAX(`post_created`), NOW() - INTERVAL 1 YEAR), NOW())
FROM `msz_forum_posts`
WHERE `forum_id` = :forum_id
AND `user_id` = :user_id
');
$checkTimeout->bindValue('forum_id', $forumId);
$checkTimeout->bindValue('user_id', $userId);
$checkTimeout->bind('forum_id', $forumId);
$checkTimeout->bind('user_id', $userId);
return (int)($checkTimeout->execute() ? $checkTimeout->fetchColumn() : 0);
return (int)$checkTimeout->fetchColumn();
}
// $forumId == null marks all forums as read
@ -451,7 +451,7 @@ function forum_mark_read(?int $forumId, int $userId): void {
}
}
$doMark = db_prepare(sprintf(
$doMark = \Misuzu\DB::prepare(sprintf(
'
INSERT INTO `msz_forum_topics_track`
(`user_id`, `topic_id`, `forum_id`, `track_last_read`)
@ -468,17 +468,17 @@ function forum_mark_read(?int $forumId, int $userId): void {
',
$entireForum ? '' : 'AND t.`forum_id` = :forum'
));
$doMark->bindValue('user', $userId);
$doMark->bind('user', $userId);
if(!$entireForum) {
$doMark->bindValue('forum', $forumId);
$doMark->bind('forum', $forumId);
}
$doMark->execute();
}
function forum_posting_info(int $userId): array {
$getPostingInfo = db_prepare('
$getPostingInfo = \Misuzu\DB::prepare('
SELECT
u.`user_country`, u.`user_created`,
(
@ -498,12 +498,12 @@ function forum_posting_info(int $userId): array {
FROM `msz_users` as u
WHERE `user_id` = :user_id
');
$getPostingInfo->bindValue('user_id', $userId);
return db_fetch($getPostingInfo);
$getPostingInfo->bind('user_id', $userId);
return $getPostingInfo->fetch();
}
function forum_count_increase(int $forumId, bool $topic = false): void {
$increaseCount = db_prepare(sprintf(
$increaseCount = \Misuzu\DB::prepare(sprintf(
'
UPDATE `msz_forum_categories`
SET `forum_count_posts` = `forum_count_posts` + 1
@ -512,7 +512,7 @@ function forum_count_increase(int $forumId, bool $topic = false): void {
',
$topic ? ',`forum_count_topics` = `forum_count_topics` + 1' : ''
));
$increaseCount->bindValue('forum', $forumId);
$increaseCount->bind('forum', $forumId);
$increaseCount->execute();
}
@ -522,7 +522,7 @@ function forum_count_synchronise(int $forumId = MSZ_FORUM_ROOT, bool $save = tru
static $setCounts = null;
if(is_null($getChildren)) {
$getChildren = db_prepare('
$getChildren = \Misuzu\DB::prepare('
SELECT `forum_id`, `forum_parent`
FROM `msz_forum_categories`
WHERE `forum_parent` = :parent
@ -530,7 +530,7 @@ function forum_count_synchronise(int $forumId = MSZ_FORUM_ROOT, bool $save = tru
}
if(is_null($getCounts)) {
$getCounts = db_prepare('
$getCounts = \Misuzu\DB::prepare('
SELECT :forum as `target_forum_id`,
(
SELECT COUNT(`topic_id`)
@ -548,7 +548,7 @@ function forum_count_synchronise(int $forumId = MSZ_FORUM_ROOT, bool $save = tru
}
if($save && is_null($setCounts)) {
$setCounts = db_prepare('
$setCounts = \Misuzu\DB::prepare('
UPDATE `msz_forum_categories`
SET `forum_count_topics` = :topics,
`forum_count_posts` = :posts
@ -556,8 +556,8 @@ function forum_count_synchronise(int $forumId = MSZ_FORUM_ROOT, bool $save = tru
');
}
$getChildren->bindValue('parent', $forumId);
$children = db_fetch_all($getChildren);
$getChildren->bind('parent', $forumId);
$children = $getChildren->fetchAll();
$topics = 0;
$posts = 0;
@ -568,15 +568,15 @@ function forum_count_synchronise(int $forumId = MSZ_FORUM_ROOT, bool $save = tru
$posts += $childCount['posts'];
}
$getCounts->bindValue('forum', $forumId);
$counts = db_fetch($getCounts);
$getCounts->bind('forum', $forumId);
$counts = $getCounts->fetch();
$topics += $counts['count_topics'];
$posts += $counts['count_posts'];
if($forumId > 0 && $save) {
$setCounts->bindValue('forum_id', $forumId);
$setCounts->bindValue('topics', $topics);
$setCounts->bindValue('posts', $posts);
$setCounts->bind('forum_id', $forumId);
$setCounts->bind('topics', $topics);
$setCounts->bind('posts', $posts);
$setCounts->execute();
}

View file

@ -56,7 +56,7 @@ function forum_leaderboard_listing(
$unrankedForums = implode(',', $unrankedForums);
$unrankedTopics = implode(',', $unrankedTopics);
$rawLeaderboard = db_fetch_all(db_query(sprintf(
$rawLeaderboard = \Misuzu\DB::query(sprintf(
'
SELECT
u.`user_id`, u.`username`,
@ -78,7 +78,7 @@ function forum_leaderboard_listing(
$hasMonth ? $month : 1,
$hasMonth ? $month : 12
)
)));
))->fetchAll();
$leaderboard = [];
$ranking = 0;

View file

@ -26,7 +26,7 @@ function forum_perms_get_user(?int $forum, int $user): array {
);
}
$getPerms = db_prepare(sprintf(
$getPerms = \Misuzu\DB::prepare(sprintf(
'
SELECT %s
FROM `msz_forum_permissions`
@ -46,11 +46,11 @@ function forum_perms_get_user(?int $forum, int $user): array {
',
perms_get_select(MSZ_FORUM_PERM_MODES)
));
$getPerms->bindValue('forum_id', $forum);
$getPerms->bindValue('user_id_1', $user);
$getPerms->bindValue('user_id_2', $user);
$getPerms->bind('forum_id', $forum);
$getPerms->bind('user_id_1', $user);
$getPerms->bind('user_id_2', $user);
return $memo[$memoId] = array_bit_or($perms, db_fetch($getPerms));
return $memo[$memoId] = array_bit_or($perms, $getPerms->fetch());
}
function forum_perms_get_role(?int $forum, int $role): array {
@ -74,7 +74,7 @@ function forum_perms_get_role(?int $forum, int $role): array {
);
}
$getPerms = db_prepare(sprintf(
$getPerms = \Misuzu\DB::prepare(sprintf(
'
SELECT %s
FROM `msz_forum_permissions`
@ -84,10 +84,10 @@ function forum_perms_get_role(?int $forum, int $role): array {
',
perms_get_select(MSZ_FORUM_PERM_MODES)
));
$getPerms->bindValue('forum_id', $forum);
$getPerms->bindValue('role_id', $role);
$getPerms->bind('forum_id', $forum);
$getPerms->bind('role_id', $role);
return $memo[$memoId] = array_bit_or($perms, db_fetch($getPerms));
return $memo[$memoId] = array_bit_or($perms, $getPerms->fetch());
}
function forum_perms_get_user_raw(?int $forum, int $user): array {
@ -95,7 +95,7 @@ function forum_perms_get_user_raw(?int $forum, int $user): array {
return perms_create(MSZ_FORUM_PERM_MODES);
}
$getPerms = db_prepare(sprintf(
$getPerms = \Misuzu\DB::prepare(sprintf(
'
SELECT `%s`
FROM `msz_forum_permissions`
@ -108,11 +108,11 @@ function forum_perms_get_user_raw(?int $forum, int $user): array {
));
if($forum !== null) {
$getPerms->bindValue('forum_id', $forum);
$getPerms->bind('forum_id', $forum);
}
$getPerms->bindValue('user_id', $user);
$perms = db_fetch($getPerms);
$getPerms->bind('user_id', $user);
$perms = $getPerms->fetch();
if(empty($perms)) {
return perms_create(MSZ_FORUM_PERM_MODES);
@ -126,7 +126,7 @@ function forum_perms_get_role_raw(?int $forum, ?int $role): array {
return perms_create(MSZ_FORUM_PERM_MODES);
}
$getPerms = db_prepare(sprintf(
$getPerms = \Misuzu\DB::prepare(sprintf(
'
SELECT `%s`
FROM `msz_forum_permissions`
@ -140,14 +140,14 @@ function forum_perms_get_role_raw(?int $forum, ?int $role): array {
));
if($forum !== null) {
$getPerms->bindValue('forum_id', $forum);
$getPerms->bind('forum_id', $forum);
}
if($role !== null) {
$getPerms->bindValue('role_id', $role);
$getPerms->bind('role_id', $role);
}
$perms = db_fetch($getPerms);
$perms = $getPerms->fetch();
if(empty($perms)) {
return perms_create(MSZ_FORUM_PERM_MODES);

View file

@ -4,7 +4,7 @@ function forum_poll_get(int $poll): array {
return [];
}
$getPoll = db_prepare("
$getPoll = \Misuzu\DB::prepare("
SELECT fp.`poll_id`, fp.`poll_max_votes`, fp.`poll_expires`, fp.`poll_preview_results`, fp.`poll_change_vote`,
(fp.`poll_expires` < CURRENT_TIMESTAMP) AS `poll_expired`,
(
@ -15,8 +15,8 @@ function forum_poll_get(int $poll): array {
FROM `msz_forum_polls` AS fp
WHERE fp.`poll_id` = :poll
");
$getPoll->bindValue('poll', $poll);
return db_fetch($getPoll);
$getPoll->bind('poll', $poll);
return $getPoll->fetch();
}
function forum_poll_create(int $maxVotes = 1): int {
@ -24,14 +24,14 @@ function forum_poll_create(int $maxVotes = 1): int {
return -1;
}
$createPoll = db_prepare("
$createPoll = \Misuzu\DB::prepare("
INSERT INTO `msz_forum_polls`
(`poll_max_votes`)
VALUES
(:max_votes)
");
$createPoll->bindValue('max_votes', $maxVotes);
return (int)($createPoll->execute() ? db_last_insert_id() : -1);
$createPoll->bind('max_votes', $maxVotes);
return $createPoll->execute() ? \Misuzu\DB::lastId() : -1;
}
function forum_poll_get_options(int $poll): array {
@ -45,7 +45,7 @@ function forum_poll_get_options(int $poll): array {
return $polls[$poll];
}
$getOptions = db_prepare('
$getOptions = \Misuzu\DB::prepare('
SELECT `option_id`, `option_text`,
(
SELECT COUNT(*)
@ -55,9 +55,9 @@ function forum_poll_get_options(int $poll): array {
FROM `msz_forum_polls_options` AS fpo
WHERE `poll_id` = :poll
');
$getOptions->bindValue('poll', $poll);
$getOptions->bind('poll', $poll);
return $polls[$poll] = db_fetch_all($getOptions);
return $polls[$poll] = $getOptions->fetchAll();
}
function forum_poll_get_user_answers(int $poll, int $user): array {
@ -65,15 +65,15 @@ function forum_poll_get_user_answers(int $poll, int $user): array {
return [];
}
$getAnswers = db_prepare("
$getAnswers = \Misuzu\DB::prepare("
SELECT `option_id`
FROM `msz_forum_polls_answers`
WHERE `poll_id` = :poll
AND `user_id` = :user
");
$getAnswers->bindValue('poll', $poll);
$getAnswers->bindValue('user', $user);
return array_column(db_fetch_all($getAnswers), 'option_id');
$getAnswers->bind('poll', $poll);
$getAnswers->bind('user', $user);
return array_column($getAnswers->fetchAll(), 'option_id');
}
function forum_poll_reset_answers(int $poll): void {
@ -81,11 +81,11 @@ function forum_poll_reset_answers(int $poll): void {
return;
}
$resetAnswers = db_prepare("
$resetAnswers = \Misuzu\DB::prepare("
DELETE FROM `msz_forum_polls_answers`
WHERE `poll_id` = :poll
");
$resetAnswers->bindValue('poll', $poll);
$resetAnswers->bind('poll', $poll);
$resetAnswers->execute();
}
@ -94,15 +94,15 @@ function forum_poll_option_add(int $poll, string $text): int {
return -1;
}
$addOption = db_prepare("
$addOption = \Misuzu\DB::prepare("
INSERT INTO `msz_forum_polls_options`
(`poll_id`, `option_text`)
VALUES
(:poll, :text)
");
$addOption->bindValue('poll', $poll);
$addOption->bindValue('text', $text);
return (int)($createPoll->execute() ? db_last_insert_id() : -1);
$addOption->bind('poll', $poll);
$addOption->bind('text', $text);
return $addOption->execute() ? \Misuzu\DB::lastId() : -1;
}
function forum_poll_option_remove(int $option): void {
@ -110,11 +110,11 @@ function forum_poll_option_remove(int $option): void {
return;
}
$removeOption = db_prepare("
$removeOption = \Misuzu\DB::prepare("
DELETE FROM `msz_forum_polls_options`
WHERE `option_id` = :option
");
$removeOption->bindValue('option', $option);
$removeOption->bind('option', $option);
$removeOption->execute();
}
@ -123,13 +123,13 @@ function forum_poll_vote_remove(int $user, int $poll): void {
return;
}
$purgeVote = db_prepare("
$purgeVote = \Misuzu\DB::prepare("
DELETE FROM `msz_forum_polls_answers`
WHERE `user_id` = :user
AND `poll_id` = :poll
");
$purgeVote->bindValue('user', $user);
$purgeVote->bindValue('poll', $poll);
$purgeVote->bind('user', $user);
$purgeVote->bind('poll', $poll);
$purgeVote->execute();
}
@ -138,15 +138,15 @@ function forum_poll_vote_cast(int $user, int $poll, int $option): void {
return;
}
$castVote = db_prepare("
$castVote = \Misuzu\DB::prepare("
INSERT INTO `msz_forum_polls_answers`
(`user_id`, `poll_id`, `option_id`)
VALUES
(:user, :poll, :option)
");
$castVote->bindValue('user', $user);
$castVote->bindValue('poll', $poll);
$castVote->bindValue('option', $option);
$castVote->bind('user', $user);
$castVote->bind('poll', $poll);
$castVote->bind('option', $option);
$castVote->execute();
}
@ -155,16 +155,16 @@ function forum_poll_validate_option(int $poll, int $option): bool {
return false;
}
$checkVote = db_prepare("
$checkVote = \Misuzu\DB::prepare("
SELECT COUNT(`option_id`) > 0
FROM `msz_forum_polls_options`
WHERE `poll_id` = :poll
AND `option_id` = :option
");
$checkVote->bindValue('poll', $poll);
$checkVote->bindValue('option', $option);
$checkVote->bind('poll', $poll);
$checkVote->bind('option', $option);
return (bool)($checkVote->execute() ? $checkVote->fetchColumn() : false);
return (bool)$checkVote->fetchColumn();
}
function forum_poll_has_voted(int $user, int $poll): bool {
@ -172,16 +172,16 @@ function forum_poll_has_voted(int $user, int $poll): bool {
return false;
}
$getAnswers = db_prepare("
$getAnswers = \Misuzu\DB::prepare("
SELECT COUNT(`user_id`) > 0
FROM `msz_forum_polls_answers`
WHERE `poll_id` = :poll
AND `user_id` = :user
");
$getAnswers->bindValue('poll', $poll);
$getAnswers->bindValue('user', $user);
$getAnswers->bind('poll', $poll);
$getAnswers->bind('user', $user);
return (bool)($getAnswers->execute() ? $getAnswers->fetchColumn() : false);
return (bool)$getAnswers->fetchColumn();
}
function forum_poll_get_topic(int $poll): array {
@ -189,12 +189,12 @@ function forum_poll_get_topic(int $poll): array {
return [];
}
$getTopic = db_prepare("
$getTopic = \Misuzu\DB::prepare("
SELECT `forum_id`, `topic_id`, `topic_locked`
FROM `msz_forum_topics`
WHERE `poll_id` = :poll
");
$getTopic->bindValue('poll', $poll);
$getTopic->bind('poll', $poll);
return db_fetch($getTopic);
return $getTopic->fetch();
}

View file

@ -10,21 +10,21 @@ function forum_post_create(
int $parser = MSZ_PARSER_PLAIN,
bool $displaySignature = true
): int {
$createPost = db_prepare('
$createPost = \Misuzu\DB::prepare('
INSERT INTO `msz_forum_posts`
(`topic_id`, `forum_id`, `user_id`, `post_ip`, `post_text`, `post_parse`, `post_display_signature`)
VALUES
(:topic_id, :forum_id, :user_id, INET6_ATON(:post_ip), :post_text, :post_parse, :post_display_signature)
');
$createPost->bindValue('topic_id', $topicId);
$createPost->bindValue('forum_id', $forumId);
$createPost->bindValue('user_id', $userId);
$createPost->bindValue('post_ip', $ipAddress);
$createPost->bindValue('post_text', $text);
$createPost->bindValue('post_parse', $parser);
$createPost->bindValue('post_display_signature', $displaySignature ? 1 : 0);
$createPost->bind('topic_id', $topicId);
$createPost->bind('forum_id', $forumId);
$createPost->bind('user_id', $userId);
$createPost->bind('post_ip', $ipAddress);
$createPost->bind('post_text', $text);
$createPost->bind('post_parse', $parser);
$createPost->bind('post_display_signature', $displaySignature ? 1 : 0);
return $createPost->execute() ? db_last_insert_id() : 0;
return $createPost->execute() ? \Misuzu\DB::lastId() : 0;
}
function forum_post_update(
@ -39,7 +39,7 @@ function forum_post_update(
return false;
}
$updatePost = db_prepare('
$updatePost = \Misuzu\DB::prepare('
UPDATE `msz_forum_posts`
SET `post_ip` = INET6_ATON(:post_ip),
`post_text` = :post_text,
@ -48,18 +48,18 @@ function forum_post_update(
`post_edited` = IF(:bump, NOW(), `post_edited`)
WHERE `post_id` = :post_id
');
$updatePost->bindValue('post_id', $postId);
$updatePost->bindValue('post_ip', $ipAddress);
$updatePost->bindValue('post_text', $text);
$updatePost->bindValue('post_parse', $parser);
$updatePost->bindValue('post_display_signature', $displaySignature ? 1 : 0);
$updatePost->bindValue('bump', $bumpUpdate ? 1 : 0);
$updatePost->bind('post_id', $postId);
$updatePost->bind('post_ip', $ipAddress);
$updatePost->bind('post_text', $text);
$updatePost->bind('post_parse', $parser);
$updatePost->bind('post_display_signature', $displaySignature ? 1 : 0);
$updatePost->bind('bump', $bumpUpdate ? 1 : 0);
return $updatePost->execute();
}
function forum_post_find(int $postId, int $userId): array {
$getPostInfo = db_prepare(sprintf(
$getPostInfo = \Misuzu\DB::prepare(sprintf(
'
SELECT
p.`post_id`, p.`topic_id`,
@ -82,12 +82,12 @@ function forum_post_find(int $postId, int $userId): array {
FROM `msz_forum_posts` AS p
WHERE p.`post_id` = :post_id
'));
$getPostInfo->bindValue('post_id', $postId);
return db_fetch($getPostInfo);
$getPostInfo->bind('post_id', $postId);
return $getPostInfo->fetch();
}
function forum_post_get(int $postId, bool $allowDeleted = false): array {
$getPost = db_prepare(sprintf(
$getPost = \Misuzu\DB::prepare(sprintf(
'
SELECT
p.`post_id`, p.`post_text`, p.`post_created`, p.`post_parse`, p.`post_display_signature`,
@ -125,12 +125,12 @@ function forum_post_get(int $postId, bool $allowDeleted = false): array {
',
$allowDeleted ? '' : 'AND `post_deleted` IS NULL'
));
$getPost->bindValue('post_id', $postId);
return db_fetch($getPost);
$getPost->bind('post_id', $postId);
return $getPost->fetch();
}
function forum_post_search(string $query): array {
$searchPosts = db_prepare('
$searchPosts = \Misuzu\DB::prepare('
SELECT
p.`post_id`, p.`post_text`, p.`post_created`, p.`post_parse`, p.`post_display_signature`,
p.`topic_id`, p.`post_deleted`, p.`post_edited`, p.`topic_id`, p.`forum_id`,
@ -168,12 +168,12 @@ function forum_post_search(string $query): array {
AND `post_deleted` IS NULL
ORDER BY `post_id`
');
$searchPosts->bindValue('query', $query);
return db_fetch_all($searchPosts);
$searchPosts->bind('query', $query);
return $searchPosts->fetchAll();
}
function forum_post_count_user(int $userId, bool $showDeleted = false): int {
$getPosts = db_prepare(sprintf(
$getPosts = \Misuzu\DB::prepare(sprintf(
'
SELECT COUNT(p.`post_id`)
FROM `msz_forum_posts` AS p
@ -182,9 +182,9 @@ function forum_post_count_user(int $userId, bool $showDeleted = false): int {
',
$showDeleted ? '' : 'AND `post_deleted` IS NULL'
));
$getPosts->bindValue('user_id', $userId);
$getPosts->bind('user_id', $userId);
return (int)($getPosts->execute() ? $getPosts->fetchColumn() : 0);
return (int)$getPosts->fetchColumn();
}
function forum_post_listing(
@ -195,7 +195,7 @@ function forum_post_listing(
bool $selectAuthor = false
): array {
$hasPagination = $offset >= 0 && $take > 0;
$getPosts = db_prepare(sprintf(
$getPosts = \Misuzu\DB::prepare(sprintf(
'
SELECT
p.`post_id`, p.`post_text`, p.`post_created`, p.`post_parse`,
@ -238,14 +238,14 @@ function forum_post_listing(
$hasPagination ? 'LIMIT :offset, :take' : '',
$selectAuthor ? 'p.`user_id`' : 'p.`topic_id`'
));
$getPosts->bindValue('topic_id', $topicId);
$getPosts->bind('topic_id', $topicId);
if($hasPagination) {
$getPosts->bindValue('offset', $offset);
$getPosts->bindValue('take', $take);
$getPosts->bind('offset', $offset);
$getPosts->bind('take', $take);
}
return db_fetch_all($getPosts);
return $getPosts->fetchAll();
}
define('MSZ_E_FORUM_POST_DELETE_OK', 0); // deleting is fine
@ -321,13 +321,13 @@ function forum_post_delete(int $postId): bool {
return false;
}
$markDeleted = db_prepare('
$markDeleted = \Misuzu\DB::prepare('
UPDATE `msz_forum_posts`
SET `post_deleted` = NOW()
WHERE `post_id` = :post
AND `post_deleted` IS NULL
');
$markDeleted->bindValue('post', $postId);
$markDeleted->bind('post', $postId);
return $markDeleted->execute();
}
@ -336,13 +336,13 @@ function forum_post_restore(int $postId): bool {
return false;
}
$markDeleted = db_prepare('
$markDeleted = \Misuzu\DB::prepare('
UPDATE `msz_forum_posts`
SET `post_deleted` = NULL
WHERE `post_id` = :post
AND `post_deleted` IS NOT NULL
');
$markDeleted->bindValue('post', $postId);
$markDeleted->bind('post', $postId);
return $markDeleted->execute();
}
@ -351,10 +351,10 @@ function forum_post_nuke(int $postId): bool {
return false;
}
$markDeleted = db_prepare('
$markDeleted = \Misuzu\DB::prepare('
DELETE FROM `msz_forum_posts`
WHERE `post_id` = :post
');
$markDeleted->bindValue('post', $postId);
$markDeleted->bind('post', $postId);
return $markDeleted->execute();
}

View file

@ -30,18 +30,18 @@ function forum_topic_create(
return 0;
}
$createTopic = db_prepare('
$createTopic = \Misuzu\DB::prepare('
INSERT INTO `msz_forum_topics`
(`forum_id`, `user_id`, `topic_title`, `topic_type`)
VALUES
(:forum_id, :user_id, :topic_title, :topic_type)
');
$createTopic->bindValue('forum_id', $forumId);
$createTopic->bindValue('user_id', $userId);
$createTopic->bindValue('topic_title', $title);
$createTopic->bindValue('topic_type', $type);
$createTopic->bind('forum_id', $forumId);
$createTopic->bind('user_id', $userId);
$createTopic->bind('topic_title', $title);
$createTopic->bind('topic_type', $type);
return $createTopic->execute() ? (int)db_last_insert_id() : 0;
return $createTopic->execute() ? \Misuzu\DB::lastId() : 0;
}
function forum_topic_update(int $topicId, ?string $title, ?int $type = null): bool {
@ -58,21 +58,21 @@ function forum_topic_update(int $topicId, ?string $title, ?int $type = null): bo
return false;
}
$updateTopic = db_prepare('
$updateTopic = \Misuzu\DB::prepare('
UPDATE `msz_forum_topics`
SET `topic_title` = COALESCE(:topic_title, `topic_title`),
`topic_type` = COALESCE(:topic_type, `topic_type`)
WHERE `topic_id` = :topic_id
');
$updateTopic->bindValue('topic_id', $topicId);
$updateTopic->bindValue('topic_title', $title);
$updateTopic->bindValue('topic_type', $type);
$updateTopic->bind('topic_id', $topicId);
$updateTopic->bind('topic_title', $title);
$updateTopic->bind('topic_type', $type);
return $updateTopic->execute();
}
function forum_topic_get(int $topicId, bool $allowDeleted = false): array {
$getTopic = db_prepare(sprintf(
$getTopic = \Misuzu\DB::prepare(sprintf(
'
SELECT
t.`topic_id`, t.`forum_id`, t.`topic_title`, t.`topic_type`, t.`topic_locked`, t.`topic_created`,
@ -113,18 +113,18 @@ function forum_topic_get(int $topicId, bool $allowDeleted = false): array {
',
$allowDeleted ? '' : 'AND t.`topic_deleted` IS NULL'
));
$getTopic->bindValue('topic_id', $topicId);
return db_fetch($getTopic);
$getTopic->bind('topic_id', $topicId);
return $getTopic->fetch();
}
function forum_topic_bump(int $topicId): bool {
$bumpTopic = db_prepare('
$bumpTopic = \Misuzu\DB::prepare('
UPDATE `msz_forum_topics`
SET `topic_bumped` = NOW()
WHERE `topic_id` = :topic_id
AND `topic_deleted` IS NULL
');
$bumpTopic->bindValue('topic_id', $topicId);
$bumpTopic->bind('topic_id', $topicId);
return $bumpTopic->execute();
}
@ -133,12 +133,12 @@ function forum_topic_views_increment(int $topicId): void {
return;
}
$bumpViews = db_prepare('
$bumpViews = \Misuzu\DB::prepare('
UPDATE `msz_forum_topics`
SET `topic_count_views` = `topic_count_views` + 1
WHERE `topic_id` = :topic_id
');
$bumpViews->bindValue('topic_id', $topicId);
$bumpViews->bind('topic_id', $topicId);
$bumpViews->execute();
}
@ -151,34 +151,34 @@ function forum_topic_mark_read(int $userId, int $topicId, int $forumId): void {
// but those explode when running on a lot of queries (like forum_mark_read() does)
// so instead we get to live with this garbage now
try {
$markAsRead = db_prepare('
$markAsRead = \Misuzu\DB::prepare('
INSERT INTO `msz_forum_topics_track`
(`user_id`, `topic_id`, `forum_id`, `track_last_read`)
VALUES
(:user_id, :topic_id, :forum_id, NOW())
');
$markAsRead->bindValue('user_id', $userId);
$markAsRead->bindValue('topic_id', $topicId);
$markAsRead->bindValue('forum_id', $forumId);
$markAsRead->bind('user_id', $userId);
$markAsRead->bind('topic_id', $topicId);
$markAsRead->bind('forum_id', $forumId);
if($markAsRead->execute()) {
forum_topic_views_increment($topicId);
}
} catch(PDOException $ex) {
if($ex->getCode() !== MSZ_DATABASE_DUPLICATE_KEY) {
if($ex->getCode() != '23000') {
throw $ex;
}
$markAsRead = db_prepare('
$markAsRead = \Misuzu\DB::prepare('
UPDATE `msz_forum_topics_track`
SET `track_last_read` = NOW(),
`forum_id` = :forum_id
WHERE `user_id` = :user_id
AND `topic_id` = :topic_id
');
$markAsRead->bindValue('user_id', $userId);
$markAsRead->bindValue('topic_id', $topicId);
$markAsRead->bindValue('forum_id', $forumId);
$markAsRead->bind('user_id', $userId);
$markAsRead->bind('topic_id', $topicId);
$markAsRead->bind('forum_id', $forumId);
$markAsRead->execute();
}
}
@ -189,7 +189,7 @@ function forum_topic_listing(
bool $showDeleted = false, bool $sortByPriority = false
): array {
$hasPagination = $offset >= 0 && $take > 0;
$getTopics = db_prepare(sprintf(
$getTopics = \Misuzu\DB::prepare(sprintf(
'
SELECT
:user_id AS `target_user_id`,
@ -276,19 +276,19 @@ function forum_topic_listing(
MSZ_FORUM_POSTS_PER_PAGE,
$sortByPriority ? '`topic_priority` DESC,' : ''
));
$getTopics->bindValue('forum_id', $forumId);
$getTopics->bindValue('user_id', $userId);
$getTopics->bind('forum_id', $forumId);
$getTopics->bind('user_id', $userId);
if($hasPagination) {
$getTopics->bindValue('offset', $offset);
$getTopics->bindValue('take', $take);
$getTopics->bind('offset', $offset);
$getTopics->bind('take', $take);
}
return db_fetch_all($getTopics);
return $getTopics->fetchAll();
}
function forum_topic_count_user(int $authorId, int $userId, bool $showDeleted = false): int {
$getTopics = db_prepare(sprintf(
$getTopics = \Misuzu\DB::prepare(sprintf(
'
SELECT COUNT(`topic_id`)
FROM `msz_forum_topics` AS t
@ -297,10 +297,10 @@ function forum_topic_count_user(int $authorId, int $userId, bool $showDeleted =
',
$showDeleted ? '' : 'AND t.`topic_deleted` IS NULL'
));
$getTopics->bindValue('author_id', $authorId);
//$getTopics->bindValue('user_id', $userId);
$getTopics->bind('author_id', $authorId);
//$getTopics->bind('user_id', $userId);
return (int)($getTopics->execute() ? $getTopics->fetchColumn() : 0);
return (int)$getTopics->fetchColumn();
}
// Remove unneccesary stuff from the sql stmt
@ -312,7 +312,7 @@ function forum_topic_listing_user(
bool $showDeleted = false
): array {
$hasPagination = $offset >= 0 && $take > 0;
$getTopics = db_prepare(sprintf(
$getTopics = \Misuzu\DB::prepare(sprintf(
'
SELECT
:user_id AS `target_user_id`,
@ -391,19 +391,19 @@ function forum_topic_listing_user(
$showDeleted ? '' : 'AND `post_deleted` IS NULL',
MSZ_FORUM_POSTS_PER_PAGE
));
$getTopics->bindValue('author_id', $authorId);
$getTopics->bindValue('user_id', $userId);
$getTopics->bind('author_id', $authorId);
$getTopics->bind('user_id', $userId);
if($hasPagination) {
$getTopics->bindValue('offset', $offset);
$getTopics->bindValue('take', $take);
$getTopics->bind('offset', $offset);
$getTopics->bind('take', $take);
}
return db_fetch_all($getTopics);
return $getTopics->fetchAll();
}
function forum_topic_listing_search(string $query, int $userId): array {
$getTopics = db_prepare(sprintf(
$getTopics = \Misuzu\DB::prepare(sprintf(
'
SELECT
:user_id AS `target_user_id`,
@ -478,10 +478,10 @@ function forum_topic_listing_search(string $query, int $userId): array {
implode(',', array_reverse(MSZ_TOPIC_TYPE_ORDER)),
MSZ_FORUM_POSTS_PER_PAGE
));
$getTopics->bindValue('query', $query);
$getTopics->bindValue('user_id', $userId);
$getTopics->bind('query', $query);
$getTopics->bind('user_id', $userId);
return db_fetch_all($getTopics);
return $getTopics->fetchAll();
}
function forum_topic_lock(int $topicId): bool {
@ -489,13 +489,13 @@ function forum_topic_lock(int $topicId): bool {
return false;
}
$markLocked = db_prepare('
$markLocked = \Misuzu\DB::prepare('
UPDATE `msz_forum_topics`
SET `topic_locked` = NOW()
WHERE `topic_id` = :topic
AND `topic_locked` IS NULL
');
$markLocked->bindValue('topic', $topicId);
$markLocked->bind('topic', $topicId);
return $markLocked->execute();
}
@ -505,13 +505,13 @@ function forum_topic_unlock(int $topicId): bool {
return false;
}
$markUnlocked = db_prepare('
$markUnlocked = \Misuzu\DB::prepare('
UPDATE `msz_forum_topics`
SET `topic_locked` = NULL
WHERE `topic_id` = :topic
AND `topic_locked` IS NOT NULL
');
$markUnlocked->bindValue('topic', $topicId);
$markUnlocked->bind('topic', $topicId);
return $markUnlocked->execute();
}
@ -594,19 +594,19 @@ function forum_topic_delete(int $topicId): bool {
return false;
}
$markTopicDeleted = db_prepare('
$markTopicDeleted = \Misuzu\DB::prepare('
UPDATE `msz_forum_topics`
SET `topic_deleted` = NOW()
WHERE `topic_id` = :topic
AND `topic_deleted` IS NULL
');
$markTopicDeleted->bindValue('topic', $topicId);
$markTopicDeleted->bind('topic', $topicId);
if(!$markTopicDeleted->execute()) {
return false;
}
$markPostsDeleted = db_prepare('
$markPostsDeleted = \Misuzu\DB::prepare('
UPDATE `msz_forum_posts` as p
SET p.`post_deleted` = (
SELECT `topic_deleted`
@ -616,7 +616,7 @@ function forum_topic_delete(int $topicId): bool {
WHERE p.`topic_id` = :topic
AND p.`post_deleted` IS NULL
');
$markPostsDeleted->bindValue('topic', $topicId);
$markPostsDeleted->bind('topic', $topicId);
return $markPostsDeleted->execute();
}
@ -626,7 +626,7 @@ function forum_topic_restore(int $topicId): bool {
return false;
}
$markPostsRestored = db_prepare('
$markPostsRestored = \Misuzu\DB::prepare('
UPDATE `msz_forum_posts` as p
SET p.`post_deleted` = NULL
WHERE p.`topic_id` = :topic
@ -636,19 +636,19 @@ function forum_topic_restore(int $topicId): bool {
WHERE `topic_id` = p.`topic_id`
)
');
$markPostsRestored->bindValue('topic', $topicId);
$markPostsRestored->bind('topic', $topicId);
if(!$markPostsRestored->execute()) {
return false;
}
$markTopicRestored = db_prepare('
$markTopicRestored = \Misuzu\DB::prepare('
UPDATE `msz_forum_topics`
SET `topic_deleted` = NULL
WHERE `topic_id` = :topic
AND `topic_deleted` IS NOT NULL
');
$markTopicRestored->bindValue('topic', $topicId);
$markTopicRestored->bind('topic', $topicId);
return $markTopicRestored->execute();
}
@ -658,11 +658,11 @@ function forum_topic_nuke(int $topicId): bool {
return false;
}
$nukeTopic = db_prepare('
$nukeTopic = \Misuzu\DB::prepare('
DELETE FROM `msz_forum_topics`
WHERE `topic_id` = :topic
');
$nukeTopic->bindValue('topic', $topicId);
$nukeTopic->bind('topic', $topicId);
return $nukeTopic->execute();
}
@ -671,7 +671,7 @@ function forum_topic_priority(int $topic): array {
return [];
}
$getPriority = db_prepare('
$getPriority = \Misuzu\DB::prepare('
SELECT
tp.`topic_id`, tp.`topic_priority`,
u.`user_id`, u.`username`,
@ -683,9 +683,9 @@ function forum_topic_priority(int $topic): array {
ON u.`display_role` = r.`role_id`
WHERE `topic_id` = :topic
');
$getPriority->bindValue('topic', $topic);
$getPriority->bind('topic', $topic);
return db_fetch_all($getPriority);
return $getPriority->fetchAll();
}
function forum_topic_priority_increase(int $topic, int $user, int $bump = 1): void {
@ -693,7 +693,7 @@ function forum_topic_priority_increase(int $topic, int $user, int $bump = 1): vo
return;
}
$bumpPriority = db_prepare('
$bumpPriority = \Misuzu\DB::prepare('
INSERT INTO `msz_forum_topics_priority`
(`topic_id`, `user_id`, `topic_priority`)
VALUES
@ -701,9 +701,9 @@ function forum_topic_priority_increase(int $topic, int $user, int $bump = 1): vo
ON DUPLICATE KEY UPDATE
`topic_priority` = `topic_priority` + :bump2
');
$bumpPriority->bindValue('topic', $topic);
$bumpPriority->bindValue('user', $user);
$bumpPriority->bindValue('bump1', $bump);
$bumpPriority->bindValue('bump2', $bump);
$bumpPriority->bind('topic', $topic);
$bumpPriority->bind('user', $user);
$bumpPriority->bind('bump1', $bump);
$bumpPriority->bind('bump2', $bump);
$bumpPriority->execute();
}

View file

@ -103,16 +103,16 @@ function ip_cidr_to_raw(string $cidr): ?array {
}
function ip_blacklist_check(string $address): bool {
$checkBlacklist = db_prepare("
$checkBlacklist = \Misuzu\DB::prepare("
SELECT COUNT(*) > 0
FROM `msz_ip_blacklist`
WHERE LENGTH(`ip_subnet`) = LENGTH(INET6_ATON(:ip1))
AND `ip_subnet` & LPAD('', LENGTH(`ip_subnet`), X'FF') << LENGTH(`ip_subnet`) * 8 - `ip_mask`
= INET6_ATON(:ip2) & LPAD('', LENGTH(`ip_subnet`), X'FF') << LENGTH(`ip_subnet`) * 8 - `ip_mask`
");
$checkBlacklist->bindValue('ip1', $address);
$checkBlacklist->bindValue('ip2', $address);
return (bool)($checkBlacklist->execute() ? $checkBlacklist->fetchColumn() : false);
$checkBlacklist->bind('ip1', $address);
$checkBlacklist->bind('ip2', $address);
return (bool)$checkBlacklist->fetchColumn();
}
function ip_blacklist_add_raw(string $subnet, ?int $mask = null): bool {
@ -130,14 +130,15 @@ function ip_blacklist_add_raw(string $subnet, ?int $mask = null): bool {
return false;
}
$addBlacklist = db_prepare('
// TODO: don't use REPLACE INTO
$addBlacklist = \Misuzu\DB::prepare('
REPLACE INTO `msz_ip_blacklist`
(`ip_subnet`, `ip_mask`)
VALUES
(:subnet, :mask)
');
$addBlacklist->bindValue('subnet', $subnet);
$addBlacklist->bindValue('mask', $mask);
$addBlacklist->bind('subnet', $subnet);
$addBlacklist->bind('mask', $mask);
return $addBlacklist->execute();
}
@ -152,13 +153,13 @@ function ip_blacklist_add(string $cidr): bool {
}
function ip_blacklist_remove_raw(string $subnet, ?int $mask = null): bool {
$removeBlacklist = db_prepare('
$removeBlacklist = \Misuzu\DB::prepare('
DELETE FROM `msz_ip_blacklist`
WHERE `ip_subnet` = :subnet
AND `ip_mask` = :mask
');
$removeBlacklist->bindValue('subnet', $subnet);
$removeBlacklist->bindValue('mask', $mask);
$removeBlacklist->bind('subnet', $subnet);
$removeBlacklist->bind('mask', $mask);
return $removeBlacklist->execute();
}
@ -173,13 +174,12 @@ function ip_blacklist_remove(string $cidr): bool {
}
function ip_blacklist_list(): array {
$getBlacklist = db_query("
return \Misuzu\DB::query("
SELECT
INET6_NTOA(`ip_subnet`) AS `ip_subnet`,
`ip_mask`,
LENGTH(`ip_subnet`) AS `ip_bytes`,
CONCAT(INET6_NTOA(`ip_subnet`), '/', `ip_mask`) as `ip_cidr`
FROM `msz_ip_blacklist`
");
return db_fetch_all($getBlacklist);
")->fetchAll();
}

View file

@ -37,7 +37,6 @@ final class TwigMisuzu extends Twig_Extension {
new Twig_Function('git_branch', 'git_branch'),
new Twig_Function('csrf_token', 'csrf_token'),
new Twig_Function('csrf_input', 'csrf_html'),
new Twig_Function('sql_query_count', 'db_query_count'),
new Twig_Function('url_construct', 'url_construct'),
new Twig_Function('warning_has_duration', 'user_warning_has_duration'),
new Twig_Function('url', 'url'),
@ -48,9 +47,12 @@ final class TwigMisuzu extends Twig_Extension {
new Twig_Function('forum_may_have_children', 'forum_may_have_children'),
new Twig_Function('forum_may_have_topics', 'forum_may_have_topics'),
new Twig_Function('forum_has_priority_voting', 'forum_has_priority_voting'),
new Twig_Function('startup_time', function (float $time = MSZ_STARTUP) {
new Twig_Function('startup_time', function(float $time = MSZ_STARTUP) {
return microtime(true) - $time;
}),
new Twig_Function('sql_query_count', function() {
return DB::queries();
}),
];
}

View file

@ -12,14 +12,14 @@ function user_auth_tfa_token_create(int $userId): string {
$token = user_auth_tfa_token_generate();
$createToken = db_prepare('
$createToken = \Misuzu\DB::prepare('
INSERT INTO `msz_auth_tfa`
(`user_id`, `tfa_token`)
VALUES
(:user_id, :token)
');
$createToken->bindValue('user_id', $userId);
$createToken->bindValue('token', $token);
$createToken->bind('user_id', $userId);
$createToken->bind('token', $token);
if(!$createToken->execute()) {
return '';
@ -29,16 +29,16 @@ function user_auth_tfa_token_create(int $userId): string {
}
function user_auth_tfa_token_invalidate(string $token): void {
$deleteToken = db_prepare('
$deleteToken = \Misuzu\DB::prepare('
DELETE FROM `msz_auth_tfa`
WHERE `tfa_token` = :token
');
$deleteToken->bindValue('token', $token);
$deleteToken->bind('token', $token);
$deleteToken->execute();
}
function user_auth_tfa_token_info(string $token): array {
$getTokenInfo = db_prepare('
$getTokenInfo = \Misuzu\DB::prepare('
SELECT
at.`user_id`, at.`tfa_token`, at.`tfa_created`, u.`user_totp_key`
FROM `msz_auth_tfa` AS at
@ -47,6 +47,6 @@ function user_auth_tfa_token_info(string $token): array {
WHERE at.`tfa_token` = :token
AND at.`tfa_created` >= NOW() - INTERVAL 15 MINUTE
');
$getTokenInfo->bindValue('token', $token);
return db_fetch($getTokenInfo);
$getTokenInfo->bind('token', $token);
return $getTokenInfo->fetch();
}

View file

@ -63,13 +63,13 @@ function user_background_set_settings(int $userId, int $settings): void {
return;
}
$setAttrs = db_prepare('
$setAttrs = \Misuzu\DB::prepare('
UPDATE `msz_users`
SET `user_background_settings` = :settings
WHERE `user_id` = :user
');
$setAttrs->bindValue('settings', $settings & 0xFF);
$setAttrs->bindValue('user', $userId);
$setAttrs->bind('settings', $settings & 0xFF);
$setAttrs->bind('user', $userId);
$setAttrs->execute();
}

View file

@ -1,54 +1,52 @@
<?php
function user_login_attempt_record(bool $success, ?int $userId, string $ipAddress, string $userAgent): void {
$storeAttempt = db_prepare('
$storeAttempt = \Misuzu\DB::prepare('
INSERT INTO `msz_login_attempts`
(`attempt_success`, `attempt_ip`, `attempt_country`, `user_id`, `attempt_user_agent`)
VALUES
(:attempt_success, INET6_ATON(:attempt_ip), :attempt_country, :user_id, :attempt_user_agent)
');
$storeAttempt->bindValue('attempt_success', $success ? 1 : 0);
$storeAttempt->bindValue('attempt_ip', $ipAddress);
$storeAttempt->bindValue('attempt_country', ip_country_code($ipAddress));
$storeAttempt->bindValue('attempt_user_agent', $userAgent);
$storeAttempt->bindValue('user_id', $userId, $userId === null ? PDO::PARAM_NULL : PDO::PARAM_INT);
$storeAttempt->bind('attempt_success', $success ? 1 : 0);
$storeAttempt->bind('attempt_ip', $ipAddress);
$storeAttempt->bind('attempt_country', ip_country_code($ipAddress));
$storeAttempt->bind('attempt_user_agent', $userAgent);
$storeAttempt->bind('user_id', $userId, $userId === null ? PDO::PARAM_NULL : PDO::PARAM_INT);
$storeAttempt->execute();
}
function user_login_attempts_remaining(string $ipAddress): int {
$getRemaining = db_prepare('
$getRemaining = \Misuzu\DB::prepare('
SELECT 5 - COUNT(`attempt_id`)
FROM `msz_login_attempts`
WHERE `attempt_success` = 0
AND `attempt_created` > NOW() - INTERVAL 1 HOUR
AND `attempt_ip` = INET6_ATON(:remote_ip)
');
$getRemaining->bindValue('remote_ip', $ipAddress);
$getRemaining->bind('remote_ip', $ipAddress);
return $getRemaining->execute()
? (int)$getRemaining->fetchColumn()
: 0;
return (int)$getRemaining->fetchColumn();
}
function user_login_attempts_count($userId = 0): int {
$getCount = db_prepare(sprintf('
$getCount = \Misuzu\DB::prepare(sprintf('
SELECT COUNT(`attempt_id`)
FROM `msz_login_attempts`
WHERE %s
', $userId < 1 ? '1' : '`user_id` = :user_id'));
if($userId >= 1) {
$getCount->bindValue('user_id', $userId);
$getCount->bind('user_id', $userId);
}
return $getCount->execute() ? (int)$getCount->fetchColumn() : 0;
return (int)$getCount->fetchColumn();
}
function user_login_attempts_list(int $offset, int $take, int $userId = 0): array {
$offset = max(0, $offset);
$take = max(1, $take);
$getAttempts = db_prepare(sprintf('
$getAttempts = \Misuzu\DB::prepare(sprintf('
SELECT
`attempt_id`, `attempt_country`, `attempt_success`, `attempt_user_agent`, `attempt_created`,
INET6_NTOA(`attempt_ip`) as `attempt_ip`
@ -59,11 +57,11 @@ function user_login_attempts_list(int $offset, int $take, int $userId = 0): arra
', $userId < 1 ? '1' : '`user_id` = :user_id'));
if($userId > 0) {
$getAttempts->bindValue('user_id', $userId);
$getAttempts->bind('user_id', $userId);
}
$getAttempts->bindValue('offset', $offset);
$getAttempts->bindValue('take', $take);
$getAttempts->bind('offset', $offset);
$getAttempts->bind('take', $take);
return db_fetch_all($getAttempts);
return $getAttempts->fetchAll();
}

View file

@ -144,7 +144,7 @@ function user_profile_fields_set(int $userId, array $fields): array {
}
if(count($values) > 0) {
$updateFields = db_prepare('
$updateFields = \Misuzu\DB::prepare('
UPDATE `msz_users`
SET ' . pdo_prepare_array_update($values, true) . '
WHERE `user_id` = :user_id
@ -197,7 +197,7 @@ function user_profile_fields_display(array $user, bool $hideEmpty = true): array
}
function user_profile_get(int $userId): array {
$getProfile = db_prepare(
$getProfile = \Misuzu\DB::prepare(
sprintf(
'
SELECT
@ -259,6 +259,6 @@ function user_profile_get(int $userId): array {
MSZ_USER_RELATION_FOLLOW
)
);
$getProfile->bindValue('user_id', $userId);
return db_fetch($getProfile);
$getProfile->bind('user_id', $userId);
return $getProfile->fetch();
}

View file

@ -2,7 +2,7 @@
define('MSZ_USER_RECOVERY_TOKEN_LENGTH', 6); // * 2
function user_recovery_token_sent(int $userId, string $ipAddress): bool {
$tokenSent = db_prepare('
$tokenSent = \Misuzu\DB::prepare('
SELECT COUNT(`verification_code`) > 0
FROM `msz_users_password_resets`
WHERE `user_id` = :user
@ -11,14 +11,14 @@ function user_recovery_token_sent(int $userId, string $ipAddress): bool {
AND `verification_code` IS NOT NULL
');
$tokenSent->bindValue('user', $userId);
$tokenSent->bindValue('ip', $ipAddress);
$tokenSent->bind('user', $userId);
$tokenSent->bind('ip', $ipAddress);
return $tokenSent->execute() ? (bool)$tokenSent->fetchColumn() : false;
return (bool)$tokenSent->fetchColumn();
}
function user_recovery_token_validate(int $userId, string $token): bool {
$validateToken = db_prepare('
$validateToken = \Misuzu\DB::prepare('
SELECT COUNT(`user_id`) > 0
FROM `msz_users_password_resets`
WHERE `user_id` = :user
@ -27,10 +27,10 @@ function user_recovery_token_validate(int $userId, string $token): bool {
AND `reset_requested` > NOW() - INTERVAL 1 HOUR
');
$validateToken->bindValue('user', $userId);
$validateToken->bindValue('code', $token);
$validateToken->bind('user', $userId);
$validateToken->bind('code', $token);
return $validateToken->execute() ? (bool)$validateToken->fetchColumn() : false;
return (bool)$validateToken->fetchColumn();
}
function user_recovery_token_generate(): string {
@ -40,28 +40,28 @@ function user_recovery_token_generate(): string {
function user_recovery_token_create(int $userId, string $ipAddress): string {
$code = user_recovery_token_generate();
$insertResetKey = db_prepare('
$insertResetKey = \Misuzu\DB::prepare('
REPLACE INTO `msz_users_password_resets`
(`user_id`, `reset_ip`, `verification_code`)
VALUES
(:user, INET6_ATON(:ip), :code)
');
$insertResetKey->bindValue('user', $userId);
$insertResetKey->bindValue('ip', $ipAddress);
$insertResetKey->bindValue('code', $code);
$insertResetKey->bind('user', $userId);
$insertResetKey->bind('ip', $ipAddress);
$insertResetKey->bind('code', $code);
return $insertResetKey->execute() ? $code : '';
}
function user_recovery_token_invalidate(int $userId, string $token): void {
$invalidateCode = db_prepare('
$invalidateCode = \Misuzu\DB::prepare('
UPDATE `msz_users_password_resets`
SET `verification_code` = NULL
WHERE `verification_code` = :code
AND `user_id` = :user
');
$invalidateCode->bindValue('user', $userId);
$invalidateCode->bindValue('code', $token);
$invalidateCode->bind('user', $userId);
$invalidateCode->bind('code', $token);
$invalidateCode->execute();
}

View file

@ -22,15 +22,16 @@ function user_relation_set(int $userId, int $subjectId, int $type = MSZ_USER_REL
return false;
}
$addRelation = db_prepare('
// TODO: don't use REPLACE INTO
$addRelation = \Misuzu\DB::prepare('
REPLACE INTO `msz_user_relations`
(`user_id`, `subject_id`, `relation_type`)
VALUES
(:user_id, :subject_id, :type)
');
$addRelation->bindValue('user_id', $userId);
$addRelation->bindValue('subject_id', $subjectId);
$addRelation->bindValue('type', $type);
$addRelation->bind('user_id', $userId);
$addRelation->bind('subject_id', $subjectId);
$addRelation->bind('type', $type);
$addRelation->execute();
return $addRelation->execute();
@ -41,19 +42,19 @@ function user_relation_remove(int $userId, int $subjectId): bool {
return false;
}
$removeRelation = db_prepare('
$removeRelation = \Misuzu\DB::prepare('
DELETE FROM `msz_user_relations`
WHERE `user_id` = :user_id
AND `subject_id` = :subject_id
');
$removeRelation->bindValue('user_id', $userId);
$removeRelation->bindValue('subject_id', $subjectId);
$removeRelation->bind('user_id', $userId);
$removeRelation->bind('subject_id', $subjectId);
return $removeRelation->execute();
}
function user_relation_info(int $userId, int $subjectId): array {
$getRelationInfo = db_prepare('
$getRelationInfo = \Misuzu\DB::prepare('
SELECT
:user_id as `user_id_arg`, :subject_id as `subject_id_arg`,
(
@ -75,9 +76,9 @@ function user_relation_info(int $userId, int $subjectId): array {
OR (`user_id` = `subject_id_arg` AND `subject_id` = `user_id_arg`)
) as `relation_created`
');
$getRelationInfo->bindValue('user_id', $userId);
$getRelationInfo->bindValue('subject_id', $subjectId);
return db_fetch($getRelationInfo);
$getRelationInfo->bind('user_id', $userId);
$getRelationInfo->bind('subject_id', $subjectId);
return $getRelationInfo->fetch();
}
function user_relation_count(int $userId, int $type, bool $from): int {
@ -89,7 +90,7 @@ function user_relation_count(int $userId, int $type, bool $from): int {
$fetchCount = $getCount[$from] ?? null;
if(empty($fetchCount)) {
$getCount[$from] = $fetchCount = db_prepare(sprintf(
$getCount[$from] = $fetchCount = \Misuzu\DB::prepare(sprintf(
'
SELECT COUNT(`%1$s`)
FROM `msz_user_relations`
@ -101,10 +102,10 @@ function user_relation_count(int $userId, int $type, bool $from): int {
));
}
$fetchCount->bindValue('user_id', $userId);
$fetchCount->bindValue('type', $type);
$fetchCount->bind('user_id', $userId);
$fetchCount->bind('type', $type);
return (int)($fetchCount->execute() ? $fetchCount->fetchColumn() : 0);
return (int)$fetchCount->fetchColumn();
}
function user_relation_count_to(int $userId, int $type): int {
@ -134,7 +135,7 @@ function user_relation_users(
$fetchUsers = $prepared[$key] ?? null;
if(empty($fetchUsers)) {
$prepared[$key] = $fetchUsers = db_prepare(sprintf(
$prepared[$key] = $fetchUsers = \Misuzu\DB::prepare(sprintf(
'
SELECT
:current_user_id AS `current_user_id`,
@ -194,16 +195,16 @@ function user_relation_users(
));
}
$fetchUsers->bindValue('user_id', $userId);
$fetchUsers->bindValue('current_user_id', $requestingUserId);
$fetchUsers->bindValue('type', $type);
$fetchUsers->bind('user_id', $userId);
$fetchUsers->bind('current_user_id', $requestingUserId);
$fetchUsers->bind('type', $type);
if(!$fetchAll) {
$fetchUsers->bindValue('take', $take);
$fetchUsers->bindValue('offset', $offset);
$fetchUsers->bind('take', $take);
$fetchUsers->bind('offset', $offset);
}
return db_fetch_all($fetchUsers);
return $fetchUsers->fetchAll();
}
function user_relation_users_to(

View file

@ -2,48 +2,48 @@
define('MSZ_ROLE_MAIN', 1);
function user_role_add(int $userId, int $roleId): bool {
$addRole = db_prepare('
$addRole = \Misuzu\DB::prepare('
INSERT INTO `msz_user_roles`
(`user_id`, `role_id`)
VALUES
(:user_id, :role_id)
');
$addRole->bindValue('user_id', $userId);
$addRole->bindValue('role_id', $roleId);
$addRole->bind('user_id', $userId);
$addRole->bind('role_id', $roleId);
return $addRole->execute();
}
function user_role_remove(int $userId, int $roleId): bool {
$removeRole = db_prepare('
$removeRole = \Misuzu\DB::prepare('
DELETE FROM `msz_user_roles`
WHERE `user_id` = :user_id
AND `role_id` = :role_id
');
$removeRole->bindValue('user_id', $userId);
$removeRole->bindValue('role_id', $roleId);
$removeRole->bind('user_id', $userId);
$removeRole->bind('role_id', $roleId);
return $removeRole->execute();
}
function user_role_can_leave(int $roleId): bool {
$canLeaveRole = db_prepare('
$canLeaveRole = \Misuzu\DB::prepare('
SELECT `role_can_leave` != 0
FROM `msz_roles`
WHERE `role_id` = :role_id
');
$canLeaveRole->bindValue('role_id', $roleId);
return $canLeaveRole->execute() ? (bool)$canLeaveRole->fetchColumn() : false;
$canLeaveRole->bind('role_id', $roleId);
return (bool)$canLeaveRole->fetchColumn();
}
function user_role_has(int $userId, int $roleId): bool {
$hasRole = db_prepare('
$hasRole = \Misuzu\DB::prepare('
SELECT COUNT(`role_id`) > 0
FROM `msz_user_roles`
WHERE `user_id` = :user_id
AND `role_id` = :role_id
');
$hasRole->bindValue('user_id', $userId);
$hasRole->bindValue('role_id', $roleId);
return $hasRole->execute() ? (bool)$hasRole->fetchColumn() : false;
$hasRole->bind('user_id', $userId);
$hasRole->bind('role_id', $roleId);
return (bool)$hasRole->fetchColumn();
}
function user_role_set_display(int $userId, int $roleId): bool {
@ -51,13 +51,13 @@ function user_role_set_display(int $userId, int $roleId): bool {
return false;
}
$setDisplay = db_prepare('
$setDisplay = \Misuzu\DB::prepare('
UPDATE `msz_users`
SET `display_role` = :role_id
WHERE `user_id` = :user_id
');
$setDisplay->bindValue('user_id', $userId);
$setDisplay->bindValue('role_id', $roleId);
$setDisplay->bind('user_id', $userId);
$setDisplay->bind('role_id', $roleId);
return $setDisplay->execute();
}
@ -67,17 +67,17 @@ function user_role_get_display(int $userId): int {
return MSZ_ROLE_MAIN;
}
$fetchRole = db_prepare('
$fetchRole = \Misuzu\DB::prepare('
SELECT `display_role`
FROM `msz_users`
WHERE `user_id` = :user_id
');
$fetchRole->bindValue('user_id', $userId);
return $fetchRole->execute() ? (int)$fetchRole->fetchColumn() : MSZ_ROLE_MAIN;
$fetchRole->bind('user_id', $userId);
return (int)$fetchRole->fetchColumn(0, MSZ_ROLE_MAIN);
}
function user_role_all_user(int $userId): array {
$getUserRoles = db_prepare('
$getUserRoles = \Misuzu\DB::prepare('
SELECT
r.`role_id`, r.`role_name`, r.`role_description`,
r.`role_colour`, r.`role_can_leave`, r.`role_created`
@ -87,12 +87,12 @@ function user_role_all_user(int $userId): array {
WHERE ur.`user_id` = :user_id
ORDER BY r.`role_hierarchy` DESC
');
$getUserRoles->bindValue('user_id', $userId);
return db_fetch_all($getUserRoles);
$getUserRoles->bind('user_id', $userId);
return $getUserRoles->fetchAll();
}
function user_role_all(bool $withHidden = false) {
return db_query(sprintf(
return \Misuzu\DB::query(sprintf(
'
SELECT
r.`role_id`, r.`role_name`, r.`role_description`,
@ -107,11 +107,11 @@ function user_role_all(bool $withHidden = false) {
ORDER BY `role_id`
',
$withHidden ? '' : 'WHERE `role_hidden` = 0'
))->fetchAll(PDO::FETCH_ASSOC);
))->fetchAll();
}
function user_role_get(int $roleId): array {
$getRole = db_prepare('
$getRole = \Misuzu\DB::prepare('
SELECT
r.`role_id`, r.`role_name`, r.`role_description`,
r.`role_colour`, r.`role_can_leave`, r.`role_created`,
@ -123,12 +123,12 @@ function user_role_get(int $roleId): array {
FROM `msz_roles` AS r
WHERE `role_id` = :role_id
');
$getRole->bindValue('role_id', $roleId);
return db_fetch($getRole);
$getRole->bind('role_id', $roleId);
return $getRole->fetch();
}
function user_role_check_authority(int $userId, int $roleId): bool {
$checkHierarchy = db_prepare('
$checkHierarchy = \Misuzu\DB::prepare('
SELECT (
SELECT MAX(r.`role_hierarchy`)
FROM `msz_roles` AS r
@ -141,7 +141,7 @@ function user_role_check_authority(int $userId, int $roleId): bool {
WHERE `role_id` = :role_id
)
');
$checkHierarchy->bindValue('user_id', $userId);
$checkHierarchy->bindValue('role_id', $roleId);
return (bool)($checkHierarchy->execute() ? $checkHierarchy->fetchColumn() : false);
$checkHierarchy->bind('user_id', $userId);
$checkHierarchy->bind('role_id', $roleId);
return (bool)$checkHierarchy->fetchColumn();
}

View file

@ -8,7 +8,7 @@ function user_session_create(
): string {
$sessionKey = user_session_generate_key();
$createSession = db_prepare('
$createSession = \Misuzu\DB::prepare('
INSERT INTO `msz_sessions`
(
`user_id`, `session_ip`, `session_country`,
@ -20,11 +20,11 @@ function user_session_create(
:session_user_agent, :session_key, NOW(), NOW() + INTERVAL 1 MONTH
)
');
$createSession->bindValue('user_id', $userId);
$createSession->bindValue('session_ip', $ipAddress);
$createSession->bindValue('session_country', ip_country_code($ipAddress));
$createSession->bindValue('session_user_agent', $userAgent);
$createSession->bindValue('session_key', $sessionKey);
$createSession->bind('user_id', $userId);
$createSession->bind('session_ip', $ipAddress);
$createSession->bind('session_country', ip_country_code($ipAddress));
$createSession->bind('session_user_agent', $userAgent);
$createSession->bind('session_key', $sessionKey);
return $createSession->execute() ? $sessionKey : '';
}
@ -34,7 +34,7 @@ function user_session_find($sessionId, bool $byKey = false): array {
return [];
}
$findSession = db_prepare(sprintf('
$findSession = \Misuzu\DB::prepare(sprintf('
SELECT
`session_id`, `user_id`,
INET6_NTOA(`session_ip`) as `session_ip`,
@ -44,16 +44,16 @@ function user_session_find($sessionId, bool $byKey = false): array {
FROM `msz_sessions`
WHERE `%s` = :session_id
', $byKey ? 'session_key' : 'session_id'));
$findSession->bindValue('session_id', $sessionId);
return db_fetch($findSession);
$findSession->bind('session_id', $sessionId);
return $findSession->fetch();
}
function user_session_delete(int $sessionId): void {
$deleteSession = db_prepare('
$deleteSession = \Misuzu\DB::prepare('
DELETE FROM `msz_sessions`
WHERE `session_id` = :session_id
');
$deleteSession->bindValue('session_id', $sessionId);
$deleteSession->bind('session_id', $sessionId);
$deleteSession->execute();
}
@ -62,7 +62,7 @@ function user_session_generate_key(): string {
}
function user_session_purge_all(int $userId): void {
db_prepare('
\Misuzu\DB::prepare('
DELETE FROM `msz_sessions`
WHERE `user_id` = :user_id
')->execute([
@ -71,24 +71,24 @@ function user_session_purge_all(int $userId): void {
}
function user_session_count($userId = 0): int {
$getCount = db_prepare(sprintf('
$getCount = \Misuzu\DB::prepare(sprintf('
SELECT COUNT(`session_id`)
FROM `msz_sessions`
%s
', $userId < 1 ? '' : 'WHERE `user_id` = :user_id'));
if($userId >= 1) {
$getCount->bindValue('user_id', $userId);
$getCount->bind('user_id', $userId);
}
return $getCount->execute() ? (int)$getCount->fetchColumn() : 0;
return (int)$getCount->fetchColumn();
}
function user_session_list(int $offset, int $take, int $userId = 0): array {
$offset = max(0, $offset);
$take = max(1, $take);
$getSessions = db_prepare(sprintf('
$getSessions = \Misuzu\DB::prepare(sprintf('
SELECT
`session_id`, `session_country`, `session_user_agent`, `session_created`,
`session_expires`, `session_active`, `session_expires_bump`,
@ -101,13 +101,13 @@ function user_session_list(int $offset, int $take, int $userId = 0): array {
', $userId < 1 ? '1' : '`user_id` = :user_id'));
if($userId > 0) {
$getSessions->bindValue('user_id', $userId);
$getSessions->bind('user_id', $userId);
}
$getSessions->bindValue('offset', $offset);
$getSessions->bindValue('take', $take);
$getSessions->bind('offset', $offset);
$getSessions->bind('take', $take);
return db_fetch_all($getSessions);
return $getSessions->fetchAll();
}
function user_session_bump_active(int $sessionId, string $ipAddress = null): void {
@ -115,15 +115,15 @@ function user_session_bump_active(int $sessionId, string $ipAddress = null): voi
return;
}
$bump = db_prepare('
$bump = \Misuzu\DB::prepare('
UPDATE `msz_sessions`
SET `session_active` = NOW(),
`session_ip_last` = INET6_ATON(:last_ip),
`session_expires` = IF(`session_expires_bump`, NOW() + INTERVAL 1 MONTH, `session_expires`)
WHERE `session_id` = :session_id
');
$bump->bindValue('session_id', $sessionId);
$bump->bindValue('last_ip', $ipAddress ?? ip_remote_address());
$bump->bind('session_id', $sessionId);
$bump->bind('last_ip', $ipAddress ?? ip_remote_address());
$bump->execute();
}

View file

@ -34,7 +34,7 @@ function user_create(
string $email,
string $ipAddress
): int {
$createUser = db_prepare('
$createUser = \Misuzu\DB::prepare('
INSERT INTO `msz_users`
(
`username`, `password`, `email`, `register_ip`,
@ -46,41 +46,41 @@ function user_create(
INET6_ATON(:last_ip), :user_country, 1
)
');
$createUser->bindValue('username', $username);
$createUser->bindValue('password', user_password_hash($password));
$createUser->bindValue('email', $email);
$createUser->bindValue('register_ip', $ipAddress);
$createUser->bindValue('last_ip', $ipAddress);
$createUser->bindValue('user_country', ip_country_code($ipAddress));
$createUser->bind('username', $username);
$createUser->bind('password', user_password_hash($password));
$createUser->bind('email', $email);
$createUser->bind('register_ip', $ipAddress);
$createUser->bind('last_ip', $ipAddress);
$createUser->bind('user_country', ip_country_code($ipAddress));
return $createUser->execute() ? (int)db_last_insert_id() : 0;
return $createUser->execute() ? \Misuzu\DB::lastId() : 0;
}
function user_find_for_login(string $usernameOrMail): array {
$getUser = db_prepare('
$getUser = \Misuzu\DB::prepare('
SELECT `user_id`, `password`, `user_totp_key` IS NOT NULL AS `totp_enabled`, `user_deleted`
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);
$getUser->bind('email', $usernameOrMail);
$getUser->bind('username', $usernameOrMail);
return $getUser->fetch();
}
function user_find_for_reset(string $email): array {
$getUser = db_prepare('
$getUser = \Misuzu\DB::prepare('
SELECT `user_id`, `username`, `email`
FROM `msz_users`
WHERE LOWER(`email`) = LOWER(:email)
AND `user_deleted` IS NULL
');
$getUser->bindValue('email', $email);
return db_fetch($getUser);
$getUser->bind('email', $email);
return $getUser->fetch();
}
function user_find_for_profile(string $idOrUsername): int {
$getUserId = db_prepare('
$getUserId = \Misuzu\DB::prepare('
SELECT
:user_id as `input_id`,
(
@ -91,8 +91,8 @@ function user_find_for_profile(string $idOrUsername): int {
LIMIT 1
) as `user_id`
');
$getUserId->bindValue('user_id', $idOrUsername);
return (int)($getUserId->execute() ? $getUserId->fetchColumn(1) : 0);
$getUserId->bind('user_id', $idOrUsername);
return (int)$getUserId->fetchColumn(1, 0);
}
function user_password_hash(string $password): string {
@ -104,13 +104,13 @@ function user_password_needs_rehash(string $hash): bool {
}
function user_password_set(int $userId, string $password): bool {
$updatePassword = db_prepare('
$updatePassword = \Misuzu\DB::prepare('
UPDATE `msz_users`
SET `password` = :password
WHERE `user_id` = :user
');
$updatePassword->bindValue('user', $userId);
$updatePassword->bindValue('password', user_password_hash($password));
$updatePassword->bind('user', $userId);
$updatePassword->bind('password', user_password_hash($password));
return $updatePassword->execute();
}
@ -119,16 +119,16 @@ function user_totp_info(int $userId): array {
return [];
}
$getTwoFactorInfo = db_prepare('
$getTwoFactorInfo = \Misuzu\DB::prepare('
SELECT
`username`, `user_totp_key`,
`user_totp_key` IS NOT NULL AS `totp_enabled`
FROM `msz_users`
WHERE `user_id` = :user_id
');
$getTwoFactorInfo->bindValue('user_id', $userId);
$getTwoFactorInfo->bind('user_id', $userId);
return db_fetch($getTwoFactorInfo);
return $getTwoFactorInfo->fetch();
}
function user_totp_update(int $userId, ?string $key): void {
@ -138,13 +138,13 @@ function user_totp_update(int $userId, ?string $key): void {
$key = empty($key) ? null : $key;
$updateTotpKey = db_prepare('
$updateTotpKey = \Misuzu\DB::prepare('
UPDATE `msz_users`
SET `user_totp_key` = :key
WHERE `user_id` = :user_id
');
$updateTotpKey->bindValue('user_id', $userId);
$updateTotpKey->bindValue('key', $key);
$updateTotpKey->bind('user_id', $userId);
$updateTotpKey->bind('key', $key);
$updateTotpKey->execute();
}
@ -153,23 +153,23 @@ function user_email_get(int $userId): string {
return '';
}
$fetchMail = db_prepare('
$fetchMail = \Misuzu\DB::prepare('
SELECT `email`
FROM `msz_users`
WHERE `user_id` = :user_id
');
$fetchMail->bindValue('user_id', $userId);
return $fetchMail->execute() ? (string)$fetchMail->fetchColumn() : '';
$fetchMail->bind('user_id', $userId);
return (string)$fetchMail->fetchColumn(0, '');
}
function user_email_set(int $userId, string $email): bool {
$updateMail = db_prepare('
$updateMail = \Misuzu\DB::prepare('
UPDATE `msz_users`
SET `email` = LOWER(:email)
WHERE `user_id` = :user
');
$updateMail->bindValue('user', $userId);
$updateMail->bindValue('email', $email);
$updateMail->bind('user', $userId);
$updateMail->bind('email', $email);
return $updateMail->execute();
}
@ -178,13 +178,13 @@ function user_password_verify_db(int $userId, string $password): bool {
return false;
}
$fetchPassword = db_prepare('
$fetchPassword = \Misuzu\DB::prepare('
SELECT `password`
FROM `msz_users`
WHERE `user_id` = :user_id
');
$fetchPassword->bindValue('user_id', $userId);
$currentPassword = $fetchPassword->execute() ? $fetchPassword->fetchColumn() : '';
$fetchPassword->bind('user_id', $userId);
$currentPassword = $fetchPassword->fetchColumn(0, '');
return !empty($currentPassword) && password_verify($password, $currentPassword);
}
@ -201,62 +201,62 @@ function user_exists(int $userId): bool {
return $exists[$userId];
}
$check = db_prepare('
$check = \Misuzu\DB::prepare('
SELECT COUNT(`user_id`) > 0
FROM `msz_users`
WHERE `user_id` = :user_id
');
$check->bindValue('user_id', $userId);
$check->bind('user_id', $userId);
return $exists[$userId] = (bool)($check->execute() ? $check->fetchColumn() : false);
return $exists[$userId] = (bool)$check->fetchColumn(0, false);
}
function user_id_from_username(string $username): int {
$getId = db_prepare('SELECT `user_id` FROM `msz_users` WHERE LOWER(`username`) = LOWER(:username)');
$getId->bindValue('username', $username);
return $getId->execute() ? (int)$getId->fetchColumn() : 0;
$getId = \Misuzu\DB::prepare('SELECT `user_id` FROM `msz_users` WHERE LOWER(`username`) = LOWER(:username)');
$getId->bind('username', $username);
return (int)$getId->fetchColumn(0, 0);
}
function user_username_from_id(int $userId): string {
$getName = db_prepare('SELECT `username` FROM `msz_users` WHERE `user_id` = :user_id');
$getName->bindValue('user_id', $userId);
return $getName->execute() ? $getName->fetchColumn() : '';
$getName = \Misuzu\DB::prepare('SELECT `username` FROM `msz_users` WHERE `user_id` = :user_id');
$getName->bind('user_id', $userId);
return $getName->fetchColumn(0, '');
}
function user_bump_last_active(int $userId, string $ipAddress = null): void {
$bumpUserLast = db_prepare('
$bumpUserLast = \Misuzu\DB::prepare('
UPDATE `msz_users`
SET `user_active` = NOW(),
`last_ip` = INET6_ATON(:last_ip)
WHERE `user_id` = :user_id
');
$bumpUserLast->bindValue('last_ip', $ipAddress ?? ip_remote_address());
$bumpUserLast->bindValue('user_id', $userId);
$bumpUserLast->bind('last_ip', $ipAddress ?? ip_remote_address());
$bumpUserLast->bind('user_id', $userId);
$bumpUserLast->execute();
}
function user_get_last_ip(int $userId): string {
$getAddress = db_prepare('
$getAddress = \Misuzu\DB::prepare('
SELECT INET6_NTOA(`last_ip`)
FROM `msz_users`
WHERE `user_id` = :user_id
');
$getAddress->bindValue('user_id', $userId);
return $getAddress->execute() ? $getAddress->fetchColumn() : '';
$getAddress->bind('user_id', $userId);
return $getAddress->fetchColumn(0, '');
}
function user_check_super(int $userId): bool {
static $superUsers = [];
if(!isset($superUsers[$userId])) {
$checkSuperUser = db_prepare("
$checkSuperUser = \Misuzu\DB::prepare("
SELECT `user_super`
FROM `msz_users`
WHERE `user_id` = :user_id
");
$checkSuperUser->bindValue('user_id', $userId);
$superUsers[$userId] = (bool)($checkSuperUser->execute() ? $checkSuperUser->fetchColumn() : false);
$checkSuperUser->bind('user_id', $userId);
$superUsers[$userId] = (bool)$checkSuperUser->fetchColumn(0, false);
}
return $superUsers[$userId];
@ -267,7 +267,7 @@ function user_check_authority(int $userId, int $subjectId, bool $canManageSelf =
return true;
}
$checkHierarchy = db_prepare('
$checkHierarchy = \Misuzu\DB::prepare('
SELECT (
SELECT MAX(r.`role_hierarchy`)
FROM `msz_roles` AS r
@ -282,21 +282,21 @@ function user_check_authority(int $userId, int $subjectId, bool $canManageSelf =
WHERE ur.`user_id` = :subject_id
)
');
$checkHierarchy->bindValue('user_id', $userId);
$checkHierarchy->bindValue('subject_id', $subjectId);
return (bool)($checkHierarchy->execute() ? $checkHierarchy->fetchColumn() : false);
$checkHierarchy->bind('user_id', $userId);
$checkHierarchy->bind('subject_id', $subjectId);
return (bool)$checkHierarchy->fetchColumn(0, false);
}
function user_get_hierarchy(int $userId): int {
$getHierarchy = db_prepare('
$getHierarchy = \Misuzu\DB::prepare('
SELECT MAX(r.`role_hierarchy`)
FROM `msz_roles` AS r
LEFT JOIN `msz_user_roles` AS ur
ON ur.`role_id` = r.`role_id`
WHERE ur.`user_id` = :user_id
');
$getHierarchy->bindValue('user_id', $userId);
return (int)($getHierarchy->execute() ? $getHierarchy->fetchColumn() : 0);
$getHierarchy->bind('user_id', $userId);
return (int)$getHierarchy->fetchColumn(0, 0);
}
define('MSZ_E_USER_BIRTHDATE_OK', 0);
@ -327,13 +327,13 @@ function user_set_birthdate(int $userId, int $day, int $month, int $year, int $y
}
$birthdate = $unset ? null : implode('-', [$year, $month, $day]);
$setBirthdate = db_prepare('
$setBirthdate = \Misuzu\DB::prepare('
UPDATE `msz_users`
SET `user_birthdate` = :birthdate
WHERE `user_id` = :user
');
$setBirthdate->bindValue('birthdate', $birthdate);
$setBirthdate->bindValue('user', $userId);
$setBirthdate->bind('birthdate', $birthdate);
$setBirthdate->bind('user', $userId);
return $setBirthdate->execute()
? MSZ_E_USER_BIRTHDATE_OK
@ -347,15 +347,15 @@ function user_get_birthdays(int $day = 0, int $month = 0) {
$date = "%-{$month}-{$day}";
}
$getBirthdays = db_prepare('
$getBirthdays = \Misuzu\DB::prepare('
SELECT `user_id`, `username`, `user_birthdate`,
IF(YEAR(`user_birthdate`) < 1, NULL, YEAR(NOW()) - YEAR(`user_birthdate`)) AS `user_age`
FROM `msz_users`
WHERE `user_deleted` IS NULL
AND `user_birthdate` LIKE :birthdate
');
$getBirthdays->bindValue('birthdate', $date);
return db_fetch_all($getBirthdays);
$getBirthdays->bind('birthdate', $date);
return $getBirthdays->fetchAll();
}
define('MSZ_USER_ABOUT_MAX_LENGTH', 0xFFFF);
@ -381,15 +381,15 @@ function user_set_about_page(int $userId, string $content, int $parser = MSZ_PAR
return MSZ_E_USER_ABOUT_TOO_LONG;
}
$setAbout = db_prepare('
$setAbout = \Misuzu\DB::prepare('
UPDATE `msz_users`
SET `user_about_content` = :content,
`user_about_parser` = :parser
WHERE `user_id` = :user
');
$setAbout->bindValue('user', $userId);
$setAbout->bindValue('content', $length < 1 ? null : $content);
$setAbout->bindValue('parser', $parser);
$setAbout->bind('user', $userId);
$setAbout->bind('content', $length < 1 ? null : $content);
$setAbout->bind('parser', $parser);
return $setAbout->execute()
? MSZ_E_USER_ABOUT_OK
@ -419,15 +419,15 @@ function user_set_signature(int $userId, string $content, int $parser = MSZ_PARS
return MSZ_E_USER_SIGNATURE_TOO_LONG;
}
$setSignature = db_prepare('
$setSignature = \Misuzu\DB::prepare('
UPDATE `msz_users`
SET `user_signature_content` = :content,
`user_signature_parser` = :parser
WHERE `user_id` = :user
');
$setSignature->bindValue('user', $userId);
$setSignature->bindValue('content', $length < 1 ? null : $content);
$setSignature->bindValue('parser', $parser);
$setSignature->bind('user', $userId);
$setSignature->bind('content', $length < 1 ? null : $content);
$setSignature->bind('parser', $parser);
return $setSignature->execute()
? MSZ_E_USER_SIGNATURE_OK

View file

@ -32,13 +32,13 @@ function user_validate_username(string $username, bool $checkInUse = false): str
}
if($checkInUse) {
$getUser = db_prepare('
$getUser = \Misuzu\DB::prepare('
SELECT COUNT(`user_id`)
FROM `msz_users`
WHERE LOWER(`username`) = LOWER(:username)
');
$getUser->bindValue('username', $username);
$userId = $getUser->execute() ? $getUser->fetchColumn() : 0;
$getUser->bind('username', $username);
$userId = $getUser->fetchColumn(0, 0);
if($userId > 0) {
return 'in-use';
@ -63,13 +63,13 @@ function user_validate_email(string $email, bool $checkInUse = false): string {
}
if($checkInUse) {
$getUser = db_prepare('
$getUser = \Misuzu\DB::prepare('
SELECT COUNT(`user_id`)
FROM `msz_users`
WHERE LOWER(`email`) = LOWER(:email)
');
$getUser->bindValue('email', $email);
$userId = $getUser->execute() ? $getUser->fetchColumn() : 0;
$getUser->bind('email', $email);
$userId = $getUser->fetchColumn(0, 0);
if($userId > 0) {
return 'in-use';

View file

@ -74,26 +74,26 @@ function user_warning_add(
$duration = 0;
}
$addWarning = db_prepare('
$addWarning = \Misuzu\DB::prepare('
INSERT INTO `msz_user_warnings`
(`user_id`, `user_ip`, `issuer_id`, `issuer_ip`, `warning_type`, `warning_note`, `warning_note_private`, `warning_duration`)
VALUES
(:user_id, INET6_ATON(:user_ip), :issuer_id, INET6_ATON(:issuer_ip), :type, :note, :note_private, :duration)
');
$addWarning->bindValue('user_id', $userId);
$addWarning->bindValue('user_ip', $userIp);
$addWarning->bindValue('issuer_id', $issuerId);
$addWarning->bindValue('issuer_ip', $issuerIp);
$addWarning->bindValue('type', $type);
$addWarning->bindValue('note', $publicNote);
$addWarning->bindValue('note_private', $privateNote);
$addWarning->bindValue('duration', $duration < 1 ? null : date('Y-m-d H:i:s', $duration));
$addWarning->bind('user_id', $userId);
$addWarning->bind('user_ip', $userIp);
$addWarning->bind('issuer_id', $issuerId);
$addWarning->bind('issuer_ip', $issuerIp);
$addWarning->bind('type', $type);
$addWarning->bind('note', $publicNote);
$addWarning->bind('note_private', $privateNote);
$addWarning->bind('duration', $duration < 1 ? null : date('Y-m-d H:i:s', $duration));
if(!$addWarning->execute()) {
return MSZ_E_WARNING_ADD_DB;
}
return (int)db_last_insert_id();
return \Misuzu\DB::lastId();
}
function user_warning_count(int $userId): int {
@ -101,13 +101,13 @@ function user_warning_count(int $userId): int {
return 0;
}
$countWarnings = db_prepare('
$countWarnings = \Misuzu\DB::prepare('
SELECT COUNT(`warning_id`)
FROM `msz_user_warnings`
WHERE `user_id` = :user_id
');
$countWarnings->bindValue('user_id', $userId);
return (int)($countWarnings->execute() ? $countWarnings->fetchColumn() : 0);
$countWarnings->bind('user_id', $userId);
return (int)$countWarnings->fetchColumn(0, 0);
}
function user_warning_remove(int $warningId): bool {
@ -115,11 +115,11 @@ function user_warning_remove(int $warningId): bool {
return false;
}
$removeWarning = db_prepare('
$removeWarning = \Misuzu\DB::prepare('
DELETE FROM `msz_user_warnings`
WHERE `warning_id` = :warning_id
');
$removeWarning->bindValue('warning_id', $warningId);
$removeWarning->bind('warning_id', $warningId);
return $removeWarning->execute();
}
@ -128,7 +128,7 @@ function user_warning_fetch(
?int $days = null,
array $displayTypes = MSZ_WARN_TYPES
): array {
$fetchWarnings = db_prepare(sprintf(
$fetchWarnings = \Misuzu\DB::prepare(sprintf(
'
SELECT
uw.`warning_id`, uw.`warning_created`, uw.`warning_type`, uw.`warning_note`,
@ -146,31 +146,31 @@ function user_warning_fetch(
implode(',', array_apply($displayTypes, 'intval')),
$days !== null ? 'AND (uw.`warning_created` >= NOW() - INTERVAL :days DAY OR (uw.`warning_duration` IS NOT NULL AND uw.`warning_duration` > NOW()))' : ''
));
$fetchWarnings->bindValue('user_id', $userId);
$fetchWarnings->bind('user_id', $userId);
if($days !== null) {
$fetchWarnings->bindValue('days', $days);
$fetchWarnings->bind('days', $days);
}
return db_fetch_all($fetchWarnings);
return $fetchWarnings->fetchAll();
}
function user_warning_global_count(?int $userId = null): int {
$countWarnings = db_prepare(sprintf('
$countWarnings = \Misuzu\DB::prepare(sprintf('
SELECT COUNT(`warning_id`)
FROM `msz_user_warnings`
%s
', $userId > 0 ? 'WHERE `user_id` = :user_id' : ''));
if($userId > 0) {
$countWarnings->bindValue('user_id', $userId);
$countWarnings->bind('user_id', $userId);
}
return (int)($countWarnings->execute() ? $countWarnings->fetchColumn() : 0);
return (int)$countWarnings->fetchColumn(0, 0);
}
function user_warning_global_fetch(int $offset = 0, int $take = 50, ?int $userId = null): array {
$fetchWarnings = db_prepare(sprintf(
$fetchWarnings = \Misuzu\DB::prepare(sprintf(
'
SELECT
uw.`warning_id`, uw.`warning_created`, uw.`warning_type`, uw.`warning_note`,
@ -188,18 +188,18 @@ function user_warning_global_fetch(int $offset = 0, int $take = 50, ?int $userId
',
$userId > 0 ? 'WHERE uw.`user_id` = :user_id' : ''
));
$fetchWarnings->bindValue('offset', $offset);
$fetchWarnings->bindValue('take', $take);
$fetchWarnings->bind('offset', $offset);
$fetchWarnings->bind('take', $take);
if($userId > 0) {
$fetchWarnings->bindValue('user_id', $userId);
$fetchWarnings->bind('user_id', $userId);
}
return db_fetch_all($fetchWarnings);
return $fetchWarnings->fetchAll();
}
function user_warning_check_ip(string $address): bool {
$checkAddress = db_prepare(sprintf(
$checkAddress = \Misuzu\DB::prepare(sprintf(
'
SELECT COUNT(`warning_id`) > 0
FROM `msz_user_warnings`
@ -210,8 +210,8 @@ function user_warning_check_ip(string $address): bool {
',
implode(',', MSZ_WARN_TYPES_HAS_DURATION)
));
$checkAddress->bindValue('address', $address);
return (bool)($checkAddress->execute() ? $checkAddress->fetchColumn() : false);
$checkAddress->bind('address', $address);
return (bool)$checkAddress->fetchColumn(0, false);
}
function user_warning_check_expiration(int $userId, int $type): int {
@ -226,7 +226,7 @@ function user_warning_check_expiration(int $userId, int $type): int {
return $memo[$memoId];
}
$getExpiration = db_prepare('
$getExpiration = \Misuzu\DB::prepare('
SELECT `warning_duration`
FROM `msz_user_warnings`
WHERE `warning_type` = :type
@ -236,9 +236,9 @@ function user_warning_check_expiration(int $userId, int $type): int {
ORDER BY `warning_duration` DESC
LIMIT 1
');
$getExpiration->bindValue('type', $type);
$getExpiration->bindValue('user', $userId);
$expiration = $getExpiration->execute() ? $getExpiration->fetchColumn() : '';
$getExpiration->bind('type', $type);
$getExpiration->bind('user', $userId);
$expiration = $getExpiration->fetchColumn(0, '');
return $memo[$memoId] = (empty($expiration) ? 0 : strtotime($expiration));
}
@ -254,7 +254,7 @@ function user_warning_check_restriction(int $userId): bool {
return $memo[$userId];
}
$checkAddress = db_prepare(sprintf(
$checkAddress = \Misuzu\DB::prepare(sprintf(
'
SELECT COUNT(`warning_id`) > 0
FROM `msz_user_warnings`
@ -265,6 +265,6 @@ function user_warning_check_restriction(int $userId): bool {
',
implode(',', MSZ_WARN_TYPES_HAS_DURATION)
));
$checkAddress->bindValue('user', $userId);
return $memo[$userId] = (bool)($checkAddress->execute() ? $checkAddress->fetchColumn() : false);
$checkAddress->bind('user', $userId);
return $memo[$userId] = (bool)$checkAddress->fetchColumn(0, false);
}

View file

@ -84,32 +84,32 @@ function audit_log(
}
}
$addLog = db_prepare('
$addLog = \Misuzu\DB::prepare('
INSERT INTO `msz_audit_log`
(`log_action`, `user_id`, `log_params`, `log_ip`, `log_country`)
VALUES
(:action, :user, :params, INET6_ATON(:ip), :country)
');
$addLog->bindValue('action', $action);
$addLog->bindValue('user', $userId < 1 ? null : $userId);
$addLog->bindValue('params', json_encode($params));
$addLog->bindValue('ip', $ipAddress);
$addLog->bindValue('country', ip_country_code($ipAddress));
$addLog->bind('action', $action);
$addLog->bind('user', $userId < 1 ? null : $userId);
$addLog->bind('params', json_encode($params));
$addLog->bind('ip', $ipAddress);
$addLog->bind('country', ip_country_code($ipAddress));
$addLog->execute();
}
function audit_log_count($userId = 0): int {
$getCount = db_prepare(sprintf('
$getCount = \Misuzu\DB::prepare(sprintf('
SELECT COUNT(`log_id`)
FROM `msz_audit_log`
%s
', $userId < 1 ? '' : 'WHERE `user_id` = :user_id'));
if($userId >= 1) {
$getCount->bindValue('user_id', $userId);
$getCount->bind('user_id', $userId);
}
return $getCount->execute() ? (int)$getCount->fetchColumn() : 0;
return (int)$getCount->fetchColumn();
}
function audit_log_list(int $offset, int $take, int $userId = 0): array {
@ -117,7 +117,7 @@ function audit_log_list(int $offset, int $take, int $userId = 0): array {
$take = max(1, $take);
$isGlobal = $userId < 1;
$getLogs = db_prepare(sprintf(
$getLogs = \Misuzu\DB::prepare(sprintf(
'
SELECT
l.`log_id`, l.`log_action`, l.`log_params`, l.`log_created`, l.`log_country`,
@ -137,10 +137,10 @@ function audit_log_list(int $offset, int $take, int $userId = 0): array {
));
if(!$isGlobal) {
$getLogs->bindValue('user_id', $userId);
$getLogs->bind('user_id', $userId);
}
$getLogs->bindValue('offset', $offset);
$getLogs->bindValue('take', $take);
return db_fetch_all($getLogs);
$getLogs->bind('offset', $offset);
$getLogs->bind('take', $take);
return $getLogs->fetchAll();
}

View file

@ -31,18 +31,18 @@ function changelog_entry_create(int $userId, int $action, string $log, string $t
return -1;
}
$createChange = db_prepare('
$createChange = \Misuzu\DB::prepare('
INSERT INTO `msz_changelog_changes`
(`user_id`, `change_action`, `change_log`, `change_text`)
VALUES
(:user_id, :action, :change_log, :change_text)
');
$createChange->bindValue('user_id', $userId);
$createChange->bindValue('action', $action);
$createChange->bindValue('change_log', $log);
$createChange->bindValue('change_text', $text);
$createChange->bind('user_id', $userId);
$createChange->bind('action', $action);
$createChange->bind('change_log', $log);
$createChange->bind('change_text', $text);
return $createChange->execute() ? (int)db_last_insert_id() : 0;
return $createChange->execute() ? \Misuzu\DB::lastId() : 0;
}
define('MSZ_CHANGELOG_GET_QUERY', '
@ -75,20 +75,20 @@ function changelog_get_changes(string $date, int $user, int $offset, int $take):
!$hasDate ? 'LIMIT :offset, :take' : ''
);
$prep = db_prepare($query);
$prep = \Misuzu\DB::prepare($query);
if(!$hasDate) {
$prep->bindValue('offset', $offset);
$prep->bindValue('take', $take);
$prep->bind('offset', $offset);
$prep->bind('take', $take);
} else {
$prep->bindValue('date', $date);
$prep->bind('date', $date);
}
if($hasUser) {
$prep->bindValue('user', $user);
$prep->bind('user', $user);
}
return db_fetch_all($prep);
return $prep->fetchAll();
}
define('MSZ_CHANGELOG_COUNT_QUERY', '
@ -108,21 +108,21 @@ function changelog_count_changes(string $date, int $user): int {
$hasUser ? '`user_id` = :user' : '1'
);
$prep = db_prepare($query);
$prep = \Misuzu\DB::prepare($query);
if($hasDate) {
$prep->bindValue('date', $date);
$prep->bind('date', $date);
}
if($hasUser) {
$prep->bindValue('user', $user);
$prep->bind('user', $user);
}
return $prep->execute() ? (int)$prep->fetchColumn() : 0;
return (int)$prep->fetchColumn();
}
function changelog_change_get(int $changeId): array {
$getChange = db_prepare('
$getChange = \Misuzu\DB::prepare('
SELECT
c.`change_id`, c.`change_created`, c.`change_log`, c.`change_text`, c.`change_action`,
u.`user_id`, u.`username`, u.`display_role` AS `user_role`,
@ -136,12 +136,12 @@ function changelog_change_get(int $changeId): array {
ON r.`role_id` = u.`display_role`
WHERE `change_id` = :change_id
');
$getChange->bindValue('change_id', $changeId);
return db_fetch($getChange);
$getChange->bind('change_id', $changeId);
return $getChange->fetch();
}
function changelog_change_tags_get(int $changeId): array {
$getTags = db_prepare('
$getTags = \Misuzu\DB::prepare('
SELECT
t.`tag_id`, t.`tag_name`, t.`tag_description`
FROM `msz_changelog_tags` as t
@ -149,6 +149,6 @@ function changelog_change_tags_get(int $changeId): array {
ON ct.`tag_id` = t.`tag_id`
WHERE ct.`change_id` = :change_id
');
$getTags->bindValue('change_id', $changeId);
return db_fetch_all($getTags);
$getTags->bind('change_id', $changeId);
return $getTags->fetchAll();
}

View file

@ -54,7 +54,7 @@ function comments_parse_for_display(string $text): string {
);
$text = preg_replace_callback(MSZ_COMMENTS_MARKUP_USER_ID, function ($matches) {
$getInfo = db_prepare('
$getInfo = DB::prepare('
SELECT
u.`user_id`, u.`username`,
COALESCE(u.`user_colour`, r.`role_colour`) as `user_colour`
@ -63,8 +63,8 @@ function comments_parse_for_display(string $text): string {
ON u.`display_role` = r.`role_id`
WHERE `user_id` = :user_id
');
$getInfo->bindValue('user_id', $matches[1]);
$info = db_fetch($getInfo);
$getInfo->bind('user_id', $matches[1]);
$info = $getInfo->fetch();
if(empty($info)) {
return $matches[0];
@ -102,14 +102,14 @@ function comments_pin_status(int $comment, bool $mode): ?string {
$status = $mode ? date('Y-m-d H:i:s') : null;
$setPinStatus = db_prepare('
$setPinStatus = \Misuzu\DB::prepare('
UPDATE `msz_comments_posts`
SET `comment_pinned` = :status
WHERE `comment_id` = :comment
AND `comment_reply_to` IS NULL
');
$setPinStatus->bindValue('comment', $comment);
$setPinStatus->bindValue('status', $status);
$setPinStatus->bind('comment', $comment);
$setPinStatus->bind('status', $status);
return $setPinStatus->execute() ? $status : null;
}
@ -119,20 +119,20 @@ function comments_vote_add(int $comment, int $user, int $vote = MSZ_COMMENTS_VOT
return false;
}
$setVote = db_prepare('
$setVote = \Misuzu\DB::prepare('
REPLACE INTO `msz_comments_votes`
(`comment_id`, `user_id`, `comment_vote`)
VALUES
(:comment, :user, :vote)
');
$setVote->bindValue('comment', $comment);
$setVote->bindValue('user', $user);
$setVote->bindValue('vote', $vote);
$setVote->bind('comment', $comment);
$setVote->bind('user', $user);
$setVote->bind('vote', $vote);
return $setVote->execute();
}
function comments_votes_get(int $commentId): array {
$getVotes = db_prepare(sprintf(
$getVotes = \Misuzu\DB::prepare(sprintf(
'
SELECT :id as `id`,
(
@ -151,31 +151,31 @@ function comments_votes_get(int $commentId): array {
MSZ_COMMENTS_VOTE_LIKE,
MSZ_COMMENTS_VOTE_DISLIKE
));
$getVotes->bindValue('id', $commentId);
return db_fetch($getVotes);
$getVotes->bind('id', $commentId);
return $getVotes->fetch();
}
function comments_category_create(string $name): array {
$create = db_prepare('
$create = \Misuzu\DB::prepare('
INSERT INTO `msz_comments_categories`
(`category_name`)
VALUES
(LOWER(:name))
');
$create->bindValue('name', $name);
$create->bind('name', $name);
return $create->execute()
? comments_category_info((int)db_last_insert_id(), false)
? comments_category_info(\Misuzu\DB::lastId(), false)
: [];
}
function comments_category_lock(int $category, bool $lock): void {
$setLock = db_prepare('
$setLock = \Misuzu\DB::prepare('
UPDATE `msz_comments_categories`
SET `category_locked` = IF(:lock, NOW(), NULL)
WHERE `category_id` = :category
');
$setLock->bindValue('category', $category);
$setLock->bindValue('lock', $lock);
$setLock->bind('category', $category);
$setLock->bind('lock', $lock);
$setLock->execute();
}
@ -198,16 +198,16 @@ define('MSZ_COMMENTS_CATEGORY_INFO_NAME', sprintf(
function comments_category_info($category, bool $createIfNone = false): array {
if(is_int($category)) {
$getCategory = db_prepare(MSZ_COMMENTS_CATEGORY_INFO_ID);
$getCategory = \Misuzu\DB::prepare(MSZ_COMMENTS_CATEGORY_INFO_ID);
$createIfNone = false;
} elseif(is_string($category)) {
$getCategory = db_prepare(MSZ_COMMENTS_CATEGORY_INFO_NAME);
$getCategory = \Misuzu\DB::prepare(MSZ_COMMENTS_CATEGORY_INFO_NAME);
} else {
return [];
}
$getCategory->bindValue('category', $category);
$categoryInfo = db_fetch($getCategory);
$getCategory->bind('category', $category);
$categoryInfo = $getCategory->fetch();
return $categoryInfo
? $categoryInfo
: (
@ -258,19 +258,19 @@ define('MSZ_COMMENTS_CATEGORY_QUERY', sprintf(
// The $parent param should never be used outside of this function itself and should always remain the last of the list.
function comments_category_get(int $category, int $user, ?int $parent = null): array {
$isParent = $parent === null;
$getComments = db_prepare(sprintf(
$getComments = \Misuzu\DB::prepare(sprintf(
MSZ_COMMENTS_CATEGORY_QUERY,
$isParent ? 'AND p.`comment_reply_to` IS NULL' : 'AND p.`comment_reply_to` = :parent',
$isParent ? 'DESC' : 'ASC'
));
if(!$isParent) {
$getComments->bindValue('parent', $parent);
$getComments->bind('parent', $parent);
}
$getComments->bindValue('user', $user);
$getComments->bindValue('category', $category);
$comments = db_fetch_all($getComments);
$getComments->bind('user', $user);
$getComments->bind('category', $category);
$comments = $getComments->fetchAll();
$commentsCount = count($comments);
for($i = 0; $i < $commentsCount; $i++) {
@ -293,33 +293,33 @@ function comments_post_create(
$text = comments_parse_for_store($text);
}
$create = db_prepare('
$create = \Misuzu\DB::prepare('
INSERT INTO `msz_comments_posts`
(`user_id`, `category_id`, `comment_text`, `comment_pinned`, `comment_reply_to`)
VALUES
(:user, :category, :text, IF(:pin, NOW(), NULL), :reply)
');
$create->bindValue('user', $user);
$create->bindValue('category', $category);
$create->bindValue('text', $text);
$create->bindValue('pin', $pinned ? 1 : 0);
$create->bindValue('reply', $reply < 1 ? null : $reply);
return $create->execute() ? db_last_insert_id() : 0;
$create->bind('user', $user);
$create->bind('category', $category);
$create->bind('text', $text);
$create->bind('pin', $pinned ? 1 : 0);
$create->bind('reply', $reply < 1 ? null : $reply);
return $create->execute() ? \Misuzu\DB::lastId() : 0;
}
function comments_post_delete(int $commentId, bool $delete = true): bool {
$deleteComment = db_prepare('
$deleteComment = \Misuzu\DB::prepare('
UPDATE `msz_comments_posts`
SET `comment_deleted` = IF(:del, NOW(), NULL)
WHERE `comment_id` = :id
');
$deleteComment->bindValue('id', $commentId);
$deleteComment->bindValue('del', $delete ? 1 : 0);
$deleteComment->bind('id', $commentId);
$deleteComment->bind('del', $delete ? 1 : 0);
return $deleteComment->execute();
}
function comments_post_get(int $commentId, bool $parse = true): array {
$fetch = db_prepare('
$fetch = \Misuzu\DB::prepare('
SELECT
p.`comment_id`, p.`category_id`, p.`comment_text`,
p.`comment_created`, p.`comment_edited`, p.`comment_deleted`,
@ -333,8 +333,8 @@ function comments_post_get(int $commentId, bool $parse = true): array {
ON r.`role_id` = u.`display_role`
WHERE `comment_id` = :id
');
$fetch->bindValue('id', $commentId);
$comment = db_fetch($fetch);
$fetch->bind('id', $commentId);
$comment = $fetch->fetch();
if($comment && $parse) {
$comment['comment_html'] = nl2br(comments_parse_for_display(htmlentities($comment['comment_text'])));
@ -344,17 +344,17 @@ function comments_post_get(int $commentId, bool $parse = true): array {
}
function comments_post_exists(int $commentId): bool {
$fetch = db_prepare('
$fetch = \Misuzu\DB::prepare('
SELECT COUNT(`comment_id`) > 0
FROM `msz_comments_posts`
WHERE `comment_id` = :id
');
$fetch->bindValue('id', $commentId);
return $fetch->execute() ? (bool)$fetch->fetchColumn() : false;
$fetch->bind('id', $commentId);
return (bool)$fetch->fetchColumn();
}
function comments_post_replies(int $commentId): array {
$getComments = db_prepare('
$getComments = \Misuzu\DB::prepare('
SELECT
p.`comment_id`, p.`category_id`, p.`comment_text`,
p.`comment_created`, p.`comment_edited`, p.`comment_deleted`,
@ -368,6 +368,6 @@ function comments_post_replies(int $commentId): array {
ON r.`role_id` = u.`display_role`
WHERE `comment_reply_to` = :id
');
$getComments->bindValue('id', $commentId);
return db_fetch_all($getComments);
$getComments->bind('id', $commentId);
return $getComments->fetchAll();
}

View file

@ -25,7 +25,7 @@ function config_store(?array $append = null): array {
function config_init(): void {
try {
$dbconfig = db_fetch_all(db_prepare('SELECT * FROM `msz_config`'));
$dbconfig = \Misuzu\DB::prepare('SELECT * FROM `msz_config`')->fetchAll();
} catch (PDOException $ex) {
return;
}
@ -54,7 +54,7 @@ function config_set(string $key, $value, bool $soft = false): void {
return;
$value = serialize($value);
$saveVal = db_prepare('
$saveVal = \Misuzu\DB::prepare('
INSERT INTO `msz_config`
(`config_name`, `config_value`)
VALUES
@ -62,8 +62,8 @@ function config_set(string $key, $value, bool $soft = false): void {
ON DUPLICATE KEY UPDATE
`config_value` = :value_2
');
$saveVal->bindValue('name', $key);
$saveVal->bindValue('value_1', $value);
$saveVal->bindValue('value_2', $value);
$saveVal->bind('name', $key);
$saveVal->bind('value_1', $value);
$saveVal->bind('value_2', $value);
$saveVal->execute();
}

View file

@ -1,153 +1,31 @@
<?php
define('MSZ_DATABASE_SUPPORTED', [
'mysql',
'sqlite',
]);
define('MSZ_DATABASE_MYSQL_DEFAULTS', [
'host' => '127.0.0.1',
'port' => 3306,
]);
namespace Misuzu;
// Output of PDOException::getCode() is string for god knows what reason
define('MSZ_DATABASE_DUPLICATE_KEY', '23000');
use Misuzu\Database\Database;
function db_settings(?array $databases = [], ?string $default = null): array {
static $settings = [];
final class DB {
private static $instance;
if(!empty($databases)) {
$settings['databases'] = array_merge_recursive($settings['databases'] ?? [], $databases);
$settings['default'] = $default ?? $settings['default'] ?? array_key_first($settings['databases']);
public static function init(...$args) {
self::$instance = new Database(...$args);
}
return $settings;
}
public static function __callStatic(string $name, array $args) {
return self::$instance->{$name}(...$args);
}
function db_connection(?string $name = null, bool $skipConnect = false, ?PDO $object = null): ?PDO {
static $connections = [];
public static function buildDSN(array $vars): string {
$dsn = ($vars['driver'] ?? 'mysql') . ':';
$settings = db_settings();
$name = $name ?? $settings['default'] ?? '';
foreach($vars as $key => $value) {
if($key === 'driver' || $key === 'username' || $key === 'password')
continue;
if($key === 'database')
$key = 'dbname';
if(!$skipConnect && empty($connections[$name])) {
if(!empty($object)) {
$connections[$name] = $object;
} elseif(!empty($settings['databases'][$name])) {
return db_connect($name, $settings['databases'][$name]);
$dsn .= $key . '=' . $value . ';';
}
return $dsn;
}
return $connections[$name] ?? null;
}
function db_prepare(string $statement, ?string $connection = null, $options = []): PDOStatement {
static $stmts = [];
$encodedOptions = serialize($options);
if(!empty($stmts[$connection][$statement][$encodedOptions])) {
return $stmts[$connection][$statement][$encodedOptions];
}
return $stmts[$connection][$statement][$encodedOptions] = db_prepare_direct($statement, $connection, $options);
}
function db_prepare_direct(string $statement, ?string $connection = null, $options = []): PDOStatement {
return db_connection($connection)->prepare($statement, $options);
}
function db_query(string $statement, ?string $connection = null): PDOStatement {
return db_connection($connection)->query($statement);
}
function db_exec(string $statement, ?string $connection = null) {
return db_connection($connection)->exec($statement);
}
function db_last_insert_id(?string $name = null, ?string $connection = null): string {
return db_connection($connection)->lastInsertId($name);
}
function db_query_count(?string $connection = null): int {
return (int)db_query('SHOW SESSION STATUS LIKE "Questions"', $connection)->fetchColumn(1);
}
function db_fetch(PDOStatement $stmt, $default = []) {
$out = $stmt->execute() ? $stmt->fetch(PDO::FETCH_ASSOC) : false;
return $out ? $out : $default;
}
function db_fetch_all(PDOStatement $stmt, $default = []) {
$out = $stmt->execute() ? $stmt->fetchAll(PDO::FETCH_ASSOC) : false;
return $out ? $out : $default;
}
// starting at 2
define('MSZ_DATABASE_CONNECT_UNSUPPORTED', 2);
define('MSZ_DATABASE_CONNECT_NO_DATABASE', 3);
function db_connect(string $name, ?array $options = null) {
$existing = db_connection($name, true);
if(!empty($existing)) {
return $existing;
}
if($options === null) {
$options = db_settings()['databases'][$name] ?? [];
}
if(!in_array($options['driver'], MSZ_DATABASE_SUPPORTED)) {
return MSZ_DATABASE_CONNECT_UNSUPPORTED;
}
$dsn = "{$options['driver']}:";
$pdoOptions = [
PDO::ATTR_CASE => PDO::CASE_NATURAL,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
PDO::ATTR_STRINGIFY_FETCHES => false,
PDO::ATTR_EMULATE_PREPARES => false,
];
switch($options['driver']) {
case 'sqlite':
if($options['memory']) {
$dsn .= ':memory:';
} else {
$databasePath = realpath($options['database'] ?? MSZ_ROOT . '/store/misuzu.db');
if($databasePath === false) {
return MSZ_DATABASE_CONNECT_NO_DATABASE;
}
}
break;
case 'mysql':
$options = array_merge(MSZ_DATABASE_MYSQL_DEFAULTS, $options);
$dsn .= empty($options['unix_socket'])
? sprintf('host=%s;port=%d;', $options['host'], $options['port'])
: sprintf('unix_socket=%s;', $options['unix_socket']);
$dsn .= sprintf(
'charset=%s;dbname=%s;',
$options['charset'] ?? 'utf8mb4',
$options['database'] ?? 'misuzu'
);
$pdoOptions[PDO::MYSQL_ATTR_INIT_COMMAND] = "
SET SESSION
sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION',
time_zone = '+00:00';
";
break;
}
$connection = new PDO(
$dsn,
$options['username'] ?? null,
$options['password'] ?? null,
$pdoOptions
);
return db_connection($name, false, $connection);
}

View file

@ -1,15 +1,15 @@
<?php
function emotes_list(int $hierarchy = PHP_INT_MAX, bool $unique = false, bool $order = true): array {
$getEmotes = db_prepare('
$getEmotes = \Misuzu\DB::prepare('
SELECT `emote_id`, `emote_order`, `emote_hierarchy`,
`emote_string`, `emote_url`
FROM `msz_emoticons`
WHERE `emote_hierarchy` <= :hierarchy
ORDER BY IF(:order, `emote_order`, `emote_id`)
');
$getEmotes->bindValue('hierarchy', $hierarchy);
$getEmotes->bindValue('order', $order);
$emotes = db_fetch_all($getEmotes);
$getEmotes->bind('hierarchy', $hierarchy);
$getEmotes->bind('order', $order);
$emotes = $getEmotes->fetchAll();
// Removes aliases, emote with lowest ordering is considered the main
if($unique) {
@ -32,14 +32,14 @@ function emotes_get_by_id(int $emoteId): array {
return [];
}
$getEmote = db_prepare('
$getEmote = \Misuzu\DB::prepare('
SELECT `emote_id`, `emote_order`, `emote_hierarchy`,
`emote_string`, `emote_url`
FROM `msz_emoticons`
WHERE `emote_id` = :id
');
$getEmote->bindValue('id', $emoteId);
return db_fetch($getEmote);
$getEmote->bind('id', $emoteId);
return $getEmote->fetch();
}
function emotes_add(string $string, string $url, int $hierarchy = 0, int $order = 0): int {
@ -47,7 +47,7 @@ function emotes_add(string $string, string $url, int $hierarchy = 0, int $order
return -1;
}
$insertEmote = db_prepare('
$insertEmote = \Misuzu\DB::prepare('
INSERT INTO `msz_emoticons` (
`emote_order`, `emote_hierarchy`, `emote_string`, `emote_url`
)
@ -55,16 +55,16 @@ function emotes_add(string $string, string $url, int $hierarchy = 0, int $order
:order, :hierarchy, :string, :url
)
');
$insertEmote->bindValue('order', $order);
$insertEmote->bindValue('hierarchy', $hierarchy);
$insertEmote->bindValue('string', $string);
$insertEmote->bindValue('url', $url);
$insertEmote->bind('order', $order);
$insertEmote->bind('hierarchy', $hierarchy);
$insertEmote->bind('string', $string);
$insertEmote->bind('url', $url);
if(!$insertEmote->execute()) {
return -2;
}
return db_last_insert_id();
return \Misuzu\DB::lastId();
}
function emotes_add_alias(int $emoteId, string $alias): int {
@ -72,7 +72,7 @@ function emotes_add_alias(int $emoteId, string $alias): int {
return -1;
}
$createAlias = db_prepare('
$createAlias = \Misuzu\DB::prepare('
INSERT INTO `msz_emoticons` (
`emote_order`, `emote_hierarchy`, `emote_string`, `emote_url`
)
@ -80,14 +80,14 @@ function emotes_add_alias(int $emoteId, string $alias): int {
FROM `msz_emoticons`
WHERE `emote_id` = :id
');
$createAlias->bindValue('id', $emoteId);
$createAlias->bindValue('alias', $alias);
$createAlias->bind('id', $emoteId);
$createAlias->bind('alias', $alias);
if(!$createAlias->execute()) {
return -2;
}
return db_last_insert_id();
return \Misuzu\DB::lastId();
}
function emotes_update_url(string $existingUrl, string $url, int $hierarchy = 0, int $order = 0): void {
@ -95,17 +95,17 @@ function emotes_update_url(string $existingUrl, string $url, int $hierarchy = 0,
return;
}
$updateByUrl = db_prepare('
$updateByUrl = \Misuzu\DB::prepare('
UPDATE `msz_emoticons`
SET `emote_url` = :url,
`emote_hierarchy` = :hierarchy,
`emote_order` = :order
WHERE `emote_url` = :existing_url
');
$updateByUrl->bindValue('existing_url', $existingUrl);
$updateByUrl->bindValue('url', $url);
$updateByUrl->bindValue('hierarchy', $hierarchy);
$updateByUrl->bindValue('order', $order);
$updateByUrl->bind('existing_url', $existingUrl);
$updateByUrl->bind('url', $url);
$updateByUrl->bind('hierarchy', $hierarchy);
$updateByUrl->bind('order', $order);
$updateByUrl->execute();
}
@ -114,43 +114,43 @@ function emotes_update_string(string $id, string $string): void {
return;
}
$updateString = db_prepare('
$updateString = \Misuzu\DB::prepare('
UPDATE `msz_emoticons`
SET `emote_string` = :string
WHERE `emote_id` = :id
');
$updateString->bindValue('id', $id);
$updateString->bindValue('string', $string);
$updateString->bind('id', $id);
$updateString->bind('string', $string);
$updateString->execute();
}
// use this for actually removing emoticons
function emotes_remove_url(string $url): void {
$removeByUrl = db_prepare('
$removeByUrl = \Misuzu\DB::prepare('
DELETE FROM `msz_emoticons`
WHERE `emote_url` = :url
');
$removeByUrl->bindValue('url', $url);
$removeByUrl->bind('url', $url);
$removeByUrl->execute();
}
// use this for removing single aliases
function emotes_remove_id(int $emoteId): void {
$removeById = db_prepare('
$removeById = \Misuzu\DB::prepare('
DELETE FROM `msz_emoticons`
WHERE `emote_id` = :id
');
$removeById->bindValue('id', $emoteId);
$removeById->bind('id', $emoteId);
$removeById->execute();
}
function emotes_order_change(int $id, bool $increase): void {
$increaseOrder = db_prepare('
$increaseOrder = \Misuzu\DB::prepare('
UPDATE `msz_emoticons`
SET `emote_order` = IF(:increase, `emote_order` + 1, `emote_order` - 1)
WHERE `emote_id` = :id
');
$increaseOrder->bindValue('id', $id);
$increaseOrder->bindValue('increase', $increase ? 1 : 0);
$increaseOrder->bind('id', $id);
$increaseOrder->bind('increase', $increase ? 1 : 0);
$increaseOrder->execute();
}

View file

@ -12,14 +12,14 @@ function news_post_create(
?int $postId = null
): int {
if($postId < 1) {
$post = db_prepare('
$post = \Misuzu\DB::prepare('
INSERT INTO `msz_news_posts`
(`category_id`, `user_id`, `post_is_featured`, `post_title`, `post_text`, `post_scheduled`)
VALUES
(:category, :user, :featured, :title, :text, COALESCE(:scheduled, CURRENT_TIMESTAMP))
');
} else {
$post = db_prepare('
$post = \Misuzu\DB::prepare('
UPDATE `msz_news_posts`
SET `category_id` = :category,
`user_id` = :user,
@ -29,43 +29,43 @@ function news_post_create(
`post_scheduled` = COALESCE(:scheduled, `post_scheduled`)
WHERE `post_id` = :id
');
$post->bindValue('id', $postId);
$post->bind('id', $postId);
}
$post->bindValue('title', $title);
$post->bindValue('text', $text);
$post->bindValue('category', $category);
$post->bindValue('user', $user);
$post->bindValue('featured', $featured ? 1 : 0);
$post->bindValue('scheduled', empty($scheduled) ? null : date('Y-m-d H:i:s', $scheduled));
$post->bind('title', $title);
$post->bind('text', $text);
$post->bind('category', $category);
$post->bind('user', $user);
$post->bind('featured', $featured ? 1 : 0);
$post->bind('scheduled', empty($scheduled) ? null : date('Y-m-d H:i:s', $scheduled));
return $post->execute() ? ($postId < 1 ? (int)db_last_insert_id() : $postId) : 0;
return $post->execute() ? ($postId < 1 ? \Misuzu\DB::lastId() : $postId) : 0;
}
function news_category_create(string $name, string $description, bool $isHidden, ?int $categoryId = null): int {
if($categoryId < 1) {
$category = db_prepare('
$category = \Misuzu\DB::prepare('
INSERT INTO `msz_news_categories`
(`category_name`, `category_description`, `category_is_hidden`)
VALUES
(:name, :description, :hidden)
');
} else {
$category = db_prepare('
$category = \Misuzu\DB::prepare('
UPDATE `msz_news_categories`
SET `category_name` = :name,
`category_description` = :description,
`category_is_hidden` = :hidden
WHERE `category_id` = :id
');
$category->bindValue('id', $categoryId);
$category->bind('id', $categoryId);
}
$category->bindValue('name', $name);
$category->bindValue('description', $description);
$category->bindValue('hidden', $isHidden ? 1 : 0);
$category->bind('name', $name);
$category->bind('description', $description);
$category->bind('hidden', $isHidden ? 1 : 0);
return $category->execute() ? ($categoryId < 1 ? (int)db_last_insert_id() : $categoryId) : 0;
return $category->execute() ? ($categoryId < 1 ? \Misuzu\DB::lastId() : $categoryId) : 0;
}
function news_categories_get(
@ -118,24 +118,24 @@ function news_categories_get(
);
}
$getCats = db_prepare($query);
$getCats = \Misuzu\DB::prepare($query);
if(!$getAll) {
$getCats->bindValue('offset', $offset);
$getCats->bindValue('take', $take);
$getCats->bind('offset', $offset);
$getCats->bind('take', $take);
}
return db_fetch_all($getCats);
return $getCats->fetchAll();
}
function news_categories_count(bool $includeHidden = false): int {
$countCats = db_prepare(sprintf('
$countCats = \Misuzu\DB::prepare(sprintf('
SELECT COUNT(`category_id`)
FROM `msz_news_categories`
%s
', $includeHidden ? '' : 'WHERE `category_is_hidden` = 0'));
return $countCats->execute() ? (int)$countCats->fetchColumn() : 0;
return (int)$countCats->fetchColumn();
}
function news_category_get(
@ -175,9 +175,9 @@ function news_category_get(
';
}
$getCategory = db_prepare($query);
$getCategory->bindValue('category', $category);
return db_fetch($getCategory);
$getCategory = \Misuzu\DB::prepare($query);
$getCategory->bind('category', $category);
return $getCategory->fetch();
}
function news_posts_count(
@ -188,7 +188,7 @@ function news_posts_count(
): int {
$hasCategory= $category !== null;
$countPosts = db_prepare(sprintf(
$countPosts = \Misuzu\DB::prepare(sprintf(
'
SELECT COUNT(`post_id`)
FROM `msz_news_posts`
@ -201,10 +201,10 @@ function news_posts_count(
));
if($hasCategory) {
$countPosts->bindValue('category', $category);
$countPosts->bind('category', $category);
}
return $countPosts->execute() ? (int)$countPosts->fetchColumn() : 0;
return (int)$countPosts->fetchColumn();
}
function news_posts_get(
@ -218,7 +218,7 @@ function news_posts_get(
$getAll = $offset < 0 || $take < 1;
$hasCategory = $category !== null;
$getPosts = db_prepare(sprintf(
$getPosts = \Misuzu\DB::prepare(sprintf(
'
SELECT
p.`post_id`, p.`post_is_featured`, p.`post_title`, p.`post_text`, p.`comment_section_id`,
@ -251,19 +251,19 @@ function news_posts_get(
));
if($hasCategory) {
$getPosts->bindValue('category', $category);
$getPosts->bind('category', $category);
}
if(!$getAll) {
$getPosts->bindValue('take', $take);
$getPosts->bindValue('offset', $offset);
$getPosts->bind('take', $take);
$getPosts->bind('offset', $offset);
}
return db_fetch_all($getPosts);
return $getPosts->fetchAll();
}
function news_posts_search(string $query): array {
$searchPosts = db_prepare('
$searchPosts = \Misuzu\DB::prepare('
SELECT
p.`post_id`, p.`post_is_featured`, p.`post_title`, p.`post_text`, p.`comment_section_id`,
p.`post_created`, p.`post_updated`, p.`post_deleted`, p.`post_scheduled`,
@ -289,13 +289,13 @@ function news_posts_search(string $query): array {
AND p.`post_scheduled` < NOW()
ORDER BY p.`post_created` DESC
');
$searchPosts->bindValue('query', $query);
$searchPosts->bind('query', $query);
return db_fetch_all($searchPosts);
return $searchPosts->fetchAll();
}
function news_post_comments_set(int $postId, int $sectionId): void {
db_prepare('
\Misuzu\DB::prepare('
UPDATE `msz_news_posts`
SET `comment_section_id` = :comment_section_id
WHERE `post_id` = :post_id
@ -306,7 +306,7 @@ function news_post_comments_set(int $postId, int $sectionId): void {
}
function news_post_get(int $postId): array {
$getPost = db_prepare('
$getPost = \Misuzu\DB::prepare('
SELECT
p.`post_id`, p.`post_title`, p.`post_text`, p.`post_is_featured`, p.`post_scheduled`,
p.`post_created`, p.`post_updated`, p.`post_deleted`, p.`comment_section_id`,
@ -322,8 +322,8 @@ function news_post_get(int $postId): array {
ON u.`display_role` = r.`role_id`
WHERE `post_id` = :post_id
');
$getPost->bindValue(':post_id', $postId);
return db_fetch($getPost);
$getPost->bind(':post_id', $postId);
return $getPost->fetch();
}
define('MSZ_NEWS_FEED_ATOM', 'atom');

View file

@ -65,7 +65,7 @@ function perms_get_user(int $user): array {
return $memo[$user];
}
$getPerms = db_prepare(sprintf(
$getPerms = \Misuzu\DB::prepare(sprintf(
'
SELECT %s
FROM `msz_permissions`
@ -81,10 +81,10 @@ function perms_get_user(int $user): array {
',
perms_get_select()
));
$getPerms->bindValue('user_id_1', $user);
$getPerms->bindValue('user_id_2', $user);
$getPerms->bind('user_id_1', $user);
$getPerms->bind('user_id_2', $user);
return $memo[$user] = db_fetch($getPerms);
return $memo[$user] = $getPerms->fetch();
}
function perms_delete_user(int $user): bool {
@ -92,12 +92,12 @@ function perms_delete_user(int $user): bool {
return false;
}
$deletePermissions = db_prepare('
$deletePermissions = \Misuzu\DB::prepare('
DELETE FROM `msz_permissions`
WHERE `role_id` IS NULL
AND `user_id` = :user_id
');
$deletePermissions->bindValue('user_id', $user);
$deletePermissions->bind('user_id', $user);
return $deletePermissions->execute();
}
@ -112,7 +112,7 @@ function perms_get_role(int $role): array {
return $memo[$role];
}
$getPerms = db_prepare(sprintf(
$getPerms = \Misuzu\DB::prepare(sprintf(
'
SELECT %s
FROM `msz_permissions`
@ -121,9 +121,9 @@ function perms_get_role(int $role): array {
',
perms_get_select()
));
$getPerms->bindValue('role_id', $role);
$getPerms->bind('role_id', $role);
return $memo[$role] = db_fetch($getPerms);
return $memo[$role] = $getPerms->fetch();
}
function perms_get_user_raw(int $user): array {
@ -131,14 +131,14 @@ function perms_get_user_raw(int $user): array {
return perms_create();
}
$getPerms = db_prepare(sprintf('
$getPerms = \Misuzu\DB::prepare(sprintf('
SELECT `%s`
FROM `msz_permissions`
WHERE `user_id` = :user_id
AND `role_id` IS NULL
', implode('`, `', perms_get_keys())));
$getPerms->bindValue('user_id', $user);
$perms = db_fetch($getPerms);
$getPerms->bind('user_id', $user);
$perms = $getPerms->fetch();
if(empty($perms)) {
return perms_create();
@ -159,7 +159,7 @@ function perms_set_user_raw(int $user, array $perms): bool {
$realPerms[$perm] = (int)($perms[$perm] ?? 0);
}
$setPermissions = db_prepare(sprintf(
$setPermissions = \Misuzu\DB::prepare(sprintf(
'
REPLACE INTO `msz_permissions`
(`role_id`, `user_id`, `%s`)
@ -169,10 +169,10 @@ function perms_set_user_raw(int $user, array $perms): bool {
implode('`, `', $permKeys),
implode(', :', $permKeys)
));
$setPermissions->bindValue('user_id', $user);
$setPermissions->bind('user_id', $user);
foreach($realPerms as $key => $value) {
$setPermissions->bindValue($key, $value);
$setPermissions->bind($key, $value);
}
return $setPermissions->execute();
@ -183,14 +183,14 @@ function perms_get_role_raw(int $role): array {
return perms_create();
}
$getPerms = db_prepare(sprintf('
$getPerms = \Misuzu\DB::prepare(sprintf('
SELECT `%s`
FROM `msz_permissions`
WHERE `user_id` IS NULL
AND `role_id` = :role_id
', implode('`, `', perms_get_keys())));
$getPerms->bindValue('role_id', $role);
$perms = db_fetch($getPerms);
$getPerms->bind('role_id', $role);
$perms = $getPerms->fetch();
if(empty($perms)) {
return perms_create();