85 lines
2.5 KiB
PHP
85 lines
2.5 KiB
PHP
<?php
|
|
/******************************************************************************
|
|
* YMS - Yacht Management Software
|
|
* Copyright (C) 2024-2026 Thomas Hooge
|
|
*
|
|
* SPDX-License-Identifier: WTFPL
|
|
******************************************************************************
|
|
|
|
*/
|
|
|
|
function db_get_setting($sno, $userid, $autocreate=false, $default=NULL) {
|
|
global $pdo;
|
|
global $g_error;
|
|
global $g_warning;
|
|
$sql = "SELECT valint, valstr FROM settings WHERE userid=? AND sno=?";
|
|
$sth = $pdo->prepare($sql);
|
|
try {
|
|
$sth->execute([$userid, $sno]);
|
|
} catch (Exception $e) {
|
|
$g_error->Add('SQL-Error: '. $e->getMessage());
|
|
$g_error->Add($sql);
|
|
$g_error->Add("userid=$userid, sno=$sno", true);
|
|
return $default;
|
|
}
|
|
$row = $sth->fetch();
|
|
if ($row === false) {
|
|
if ($autocreate) {
|
|
// create empty settings record if it not exists
|
|
$p[':userid'] = $userid;
|
|
$p[':sno'] = $sno;
|
|
db_exec_insert('settings', $p);
|
|
$g_warning->Add("Added missing settings record with id=$sno");
|
|
}
|
|
return $default;
|
|
}
|
|
return $row;
|
|
}
|
|
|
|
function db_lock_acquire($table, $key, $userid) {
|
|
global $pdo;
|
|
$token = bin2hex(random_bytes(8));
|
|
// first try new lock
|
|
$sql = "INSERT INTO recordlock (lock_table, lock_key, token, userid) "
|
|
. "VALUES (?, ?, ?, ?)";
|
|
try {
|
|
$sth = $pdo->prepare($sql);
|
|
$sth->execute([$table, $key, $token, $userid]);
|
|
return $token;
|
|
} catch (PDOException $e) {
|
|
if ($e->errorInfo[1] != 1062) {
|
|
throw $e;
|
|
}
|
|
}
|
|
// lazy locking: lock exists but is old, so we use it
|
|
$sql = "UPDATE recordlock "
|
|
. "SET token=?, userid=?, "
|
|
. "created_at=CURRENT_TIMESTAMP, last_seen=CURRENT_TIMESTAMP "
|
|
. "WHERE lock_table=? AND lock_key=? "
|
|
. "AND last_seen<CURRENT_TIMESTAMP-INTERVAL 5 MINUTE";
|
|
$sth = $pdo->prepare($sql);
|
|
$sth->execute([$token, $userid, $table, $key]);
|
|
if ($stmt->rowCount() === 1) {
|
|
return $token;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function db_lock_refresh($token) {
|
|
global $pdo;
|
|
$sql = "UPDATE recordlock "
|
|
. "SET last_seen=CURRENT_TIMESTAMP "
|
|
. "WHERE token=?";
|
|
$sth = $pdo->prepare($sql);
|
|
$sth->execute([$token]);
|
|
return $sth->rowCount() === 1;
|
|
}
|
|
|
|
function db_lock_release($token) {
|
|
global $pdo;
|
|
$sql = "DELETE FROM recordlock WHERE token=?";
|
|
$sth = $pdo->prepare($sql);
|
|
$sth->execute([$token]);
|
|
return $sth->rowCount() === 1;
|
|
}
|