Files
xxx/open_db.lib.php
tim 3df88e0b4c Check editor accounts.
A new editor needs a username and a password of at least 12 characters. A persistent login needs an unexpired key and an existing account. Removing an account revokes its persistent logins, and its sessions end.
2026-09-26 15:27:51 +02:00

71 lines
2.1 KiB
PHP

<?php
require_once(__DIR__ . '/config.lib.php');
global $db;
/*
* The class of the connection that open_db() makes. It is always mysqli
* on the site; the tests put a fake class in the global $db_class.
*/
function open_db($state) {
global $db, $db_class;
if ($state == 'open') {
if (!$db) {
$hostname = config('DB_HOST', 'localhost');
$view_user = config('DB_USER');
$view_pass = config('DB_PASS');
$db_name = config('DB_NAME');
// PHP 8.1+ throws exceptions by default; keep the old return-value checks working
mysqli_report(MYSQLI_REPORT_OFF);
$class = $db_class ?? 'mysqli';
$db = new $class($hostname, $view_user, $view_pass, $db_name);
if ($db->connect_error) {
$detail = 'connect error (' . $db->connect_errno . ') ' . $db->connect_error;
$db = NULL;
db_fail($detail);
}
return TRUE;
} else
return FALSE;
}
else if ($state == 'close') {
if ($db) {
$db->close();
$db = NULL;
return TRUE;
} else
return FALSE;
}
}
/*
* TRUE if an editor account named $username exists. A session or a
* persistent login of an editor whose account was removed ends with it.
*/
function editor_exists($username) {
global $db;
if (!is_string($username) || $username === '')
return FALSE;
$opened = open_db('open');
$result = $db->execute_query("SELECT username FROM editors WHERE username = ?", array($username)) or db_fail();
$row = $result->fetch_assoc();
if ($opened)
open_db('close');
return (bool)$row;
}
/*
* Stop the page after a database error. The details, with the file and
* line of the failed call, go to the PHP error log; the visitor only
* sees a short apology.
*/
function db_fail($detail = NULL) {
global $db;
if ($detail === NULL)
$detail = $db ? $db->error : 'no database connection';
$caller = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1)[0];
error_log('xxx: database error at ' . basename($caller['file']) . ':' . $caller['line'] . ': ' . $detail);
if (!headers_sent())
header('HTTP/1.1 500 Internal Server Error');
die('<p>Sorry, something went wrong. Please try again later.</p>');
}
?>