From 743ba1bcfbe3e797f4af2358f9fc7711c0d76fa3 Mon Sep 17 00:00:00 2001 From: Jens Zahner Date: Fri, 13 Jul 2018 12:27:49 +0200 Subject: [PATCH 1/5] Refactor function genTicket(...) to use PDOStatement --- htdocs/include/ticketfuncs.php | 41 ++++++++++++++++++---------------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/htdocs/include/ticketfuncs.php b/htdocs/include/ticketfuncs.php index 0aab8b4..283bf2c 100644 --- a/htdocs/include/ticketfuncs.php +++ b/htdocs/include/ticketfuncs.php @@ -111,25 +111,28 @@ function genTicket($upload, $params) // prepare data $sql = "INSERT INTO ticket (id, user_id, name, path, size, cmt, pass_ph, pass_send" - . ", time, expire, last_time, expire_dln, notify_email, sent_email, locale) VALUES ("; - $sql .= $db->quote($upload['id']); - $sql .= ", " . $auth['id']; - $sql .= ", " . $db->quote($upload['name']); - $sql .= ", " . $db->quote($upload['path']); - $sql .= ", " . $upload['size']; - $sql .= ", " . (empty($params["comment"])? 'NULL': $db->quote($params["comment"])); - $sql .= ", " . (empty($params["pass"])? 'NULL': $db->quote(hashPassword($params["pass"]))); - $sql .= ", " . (!isset($params["pass_send"])? '1': (int)to_boolean($params["pass_send"])); - $sql .= ", " . time(); - $sql .= ", " . $total; - $sql .= ", " . $lastdl; - $sql .= ", " . $maxdl; - $sql .= ", " . (empty($params["notify"])? 'NULL': $db->quote(fixEMailAddrs($params["notify"]))); - $sql .= ", " . (empty($params["send_to"])? 'NULL': $db->quote(fixEMailAddrs($params["send_to"]))); - $sql .= ", " . $db->quote($locale); - $sql .= ")"; - - try { $db->exec($sql); } + . ", time, expire, last_time, expire_dln, notify_email, sent_email, locale) ". + "VALUES (:id,:user_id,:name,:path,:size,:cmt,:pass_ph, :pass_send,:time,:expire,". + ":last_time,:expire_dln,:notify_email,:sent_email,:locale)"; + try { + $statement = $db->prepare($sql); + if (!$statement) { throw new Exception("failed to prepare SQL query"); } + $result = $statement->execute( array( ":id" => $upload['id'], + ":user_id" => $auth['id'], + ":name" => $upload['name'], + ":path" => $upload['path'], + ":size" => $upload['size'], + ":cmt" => $params["comment"], + ":pass_ph" => (empty($params["pass"]) ? NULL : hashPassword($params["pass"])), + ":pass_send" => $params["pass_send"], + ":time" => time(), + ":expire" => $total, + ":last_time" => $lastdl, + ":expire_dln" => $maxdl, + ":notify_email" => (empty($params["notify"])? 'NULL': fixEMailAddrs($params["notify"])), + ":sent_email" => (empty($params["send_to"])? 'NULL': fixEMailAddrs($params["send_to"])), + ":locale" => $locale ) ); + } catch(PDOException $e) { logDBError($db, "cannot commit new ticket to database"); From d775a26dab8f6da443404118dc2154522a5a068b Mon Sep 17 00:00:00 2001 From: Jens Zahner Date: Mon, 16 Jul 2018 12:06:21 +0200 Subject: [PATCH 2/5] started integration of Doctrine DBAL update Hook Code --- htdocs/include/admfuncs.php | 38 +++++---------- htdocs/include/dbfuncs.php | 87 ++++++++++++++++++++++++++++++++++ htdocs/include/hooks.php | 49 +++++++++++++++++++ htdocs/include/ticketfuncs.php | 63 +++++++++--------------- 4 files changed, 170 insertions(+), 67 deletions(-) diff --git a/htdocs/include/admfuncs.php b/htdocs/include/admfuncs.php index 00dccb7..6cfc4c5 100644 --- a/htdocs/include/admfuncs.php +++ b/htdocs/include/admfuncs.php @@ -13,22 +13,18 @@ function restart_session() function ticketPurge($DATA, $auto = true) { - global $db; - - if($db->exec("DELETE FROM ticket WHERE id = ". $db->quote($DATA["id"])) == 1) - { - unlink($DATA["path"]); - onTicketPurge($DATA, $auto); + if (DBConnection::getInstance()->purgeTicketById($DATA['id'])) { + unlink($DATA["path"]); + Hooks::getInstance()->callHook('onTicketPurge',$DATA,$auto); } } function grantPurge($DATA, $auto = true) { - global $db; - - if($db->exec("DELETE FROM \"grant\" WHERE id = ". $db->quote($DATA["id"])) == 1) - onGrantPurge($DATA, $auto); + if (DBConnection::getInstance()->purgeGrantById($DATA['id'])) { + Hooks::getInstance()->callHook('onGrantPurge',$DATA,$auto); + } } @@ -45,24 +41,14 @@ function init() function runGc() { - global $db, $gcLimit; - - $now = time(); - - $sql = "SELECT * FROM ticket WHERE (expire + time) < $now"; - $sql .= " OR (last_stamp + last_time) < $now"; - $sql .= " OR expire_dln <= downloads"; - if($gcLimit) $sql .= " LIMIT $gcLimit"; - foreach($db->query($sql)->fetchAll() as $DATA) + global $gcLimit; + foreach(DBConnection::getInstance()->getTicketsToPurge(time(),$gcLimit) as $DATA) { ticketPurge($DATA); - - // expire grants - $sql = "SELECT * FROM \"grant\" WHERE (grant_expire + time) < $now"; - $sql .= " OR (last_stamp + grant_last_time) < $now"; - $sql .= " OR grant_expire_uln <= uploads"; - if($gcLimit) $sql .= " LIMIT $gcLimit"; - foreach($db->query($sql)->fetchAll() as $DATA) + } + + foreach(DBConnection::getInstance()->getGrantsToPurge(time(),$gcLimit) as $DATA) { grantPurge($DATA); + } } diff --git a/htdocs/include/dbfuncs.php b/htdocs/include/dbfuncs.php index 18e514f..549cd69 100644 --- a/htdocs/include/dbfuncs.php +++ b/htdocs/include/dbfuncs.php @@ -2,6 +2,93 @@ // database handling functions require_once("confwrap.php"); +require_once(__DIR__."/../../vendor/autoload.php"); + +final class DBConnection { + protected static $instance = null; + protected $conn; + protected $queries; + + public static function getInstance() { + if (!isset(static::$instance)) { + static::$instance = new static; + } + return static::$instance; + } + + protected function __construct() { + GLOBAL $dsn2; + $this->conn = \Doctrine\DBAL\DriverManager::getConnection([ 'url' => $dsn2 ], new \Doctrine\DBAL\Configuration()); + } + + /** + * Me not like clones! Me smash clones! + */ + protected function __clone() { } + + /** + * + */ + public function getGenTicketQuery() { + return $this->conn->createQueryBuilder()->insert("ticket")-> + values([ 'id' => '?', + 'user_id' => '?', + 'name' => '?', + 'path' => '?', + 'size' => '?', + 'cmt' => '?', + 'pass_ph' => '?', + 'pass_send' => '?', + 'time' => '?', + 'expire' => '?', + 'last_time' => '?', + 'expire_dln'=> '?', + 'notify_email'=>'?', + 'sent_email' => '?', + 'locale' => '?']); + } + + public function getTicketById($id) { + return $this->conn->createQueryBuilder()->select("*")-> + from("ticket")-> + where("id = ?")-> + setParameter(0,$id)->execute()->fetch(); + } + + public function purgeTicketById($id) { + return (1===$this->conn->createQueryBuilder()->delete("ticket") + ->where("id = ?") + ->setParameter(0,$id)->execute() ); + } + + public function purgeGrantById($id) { + return (1===$this->conn->createQueryBuilder()->delete("grant") + ->where("id = ?") + ->setParameter(0,$id)->execute() ); + } + + public function getTicketsToPurge($now,$limit) { + return $this->conn->createQueryBuilder()->select("*")-> + from("ticket")-> + where("(expire + time) < ?")-> + or("(last_stamp + last_time) < ?")-> + or("OR expire_dln <= downloads")-> + setMaxResults($limit)-> + setParameter(0,$now)-> + setParameter(1,$now)->execute()->fetchAll(); + } + public function getGrantsToPurge($now,$limit) { + return $this->conn->createQueryBuilder()->select("*")-> + from("grant")-> + where("(grant_expire + time) < ?")-> + or("(last_stamp + grant_last_time) < ?")-> + or("OR grant_expire_uln <= uploads")-> + setMaxResults($limit)-> + setParameter(0,$now)-> + setParameter(1,$now)->execute()->fetchAll(); + } +} + // a simple wrapper to handle some DB issues uniformly class XPDO extends PDO diff --git a/htdocs/include/hooks.php b/htdocs/include/hooks.php index d5ded6f..93d00b9 100644 --- a/htdocs/include/hooks.php +++ b/htdocs/include/hooks.php @@ -2,6 +2,55 @@ // dl ticket event hooks require_once("msg.php"); +final class Hooks { + protected static $instance = null; + protected $hooks; + + public static function getInstance() { + if (!isset(static::$instance)) { + static::$instance = new static; + } + return static::$instance; + } + + protected function __construct() { + $this->hooks = + [ + 'onTicketCreate' => [onTicketCreate], + 'onTicketUpdate' => [], + 'onTicketDownload' => [onTicketDownload], + 'onTicketPurge' => [onTicketPurge], + 'onGrantCreate' => [onGrantCreate], + 'onGrantUpdate' => [], + 'onGrantPurge' => [onGrantPurge], + 'onGrantUse' => [onGrantUse] + ]; + } + + /** + * Me not like clones! Me smash clones! + */ + protected function __clone() { } + + public function registerHook($hookName, $callable) { + if (!in_array($hookName,array_keys($this->hooks))) { + throw new \Exception("Hook name unkown"); + } + $this->hooks[$hookName][] = $callable; + return $this; + } + + public function callHook($hookName,$DATA1,$DATA2 = null,$DATA3 = null) { + if (!in_array($hookName,array_keys($this->hooks))) { + throw new \Exception("Hook name unkown"); + } + foreach($this->hooks[$hookName] as $a) { + $a($DATA1,$DATA2,$DATA3); + } + } +} + + function onTicketCreate($DATA) { diff --git a/htdocs/include/ticketfuncs.php b/htdocs/include/ticketfuncs.php index 283bf2c..1dd6d42 100644 --- a/htdocs/include/ticketfuncs.php +++ b/htdocs/include/ticketfuncs.php @@ -2,7 +2,6 @@ // new ticket shared functions require_once("funcs.php"); - function isTicketExpired($DATA, $now = NULL) { if(!isset($now)) $now = time(); @@ -98,7 +97,7 @@ function ticketExpirationParams($params) function genTicket($upload, $params) { - global $auth, $locale, $db; + global $auth, $locale; // populate comment with file list when empty if(!empty($params["comment"])) @@ -109,45 +108,27 @@ function genTicket($upload, $params) // expiration values list($total, $lastdl, $maxdl) = ticketExpirationParams($params); - // prepare data - $sql = "INSERT INTO ticket (id, user_id, name, path, size, cmt, pass_ph, pass_send" - . ", time, expire, last_time, expire_dln, notify_email, sent_email, locale) ". - "VALUES (:id,:user_id,:name,:path,:size,:cmt,:pass_ph, :pass_send,:time,:expire,". - ":last_time,:expire_dln,:notify_email,:sent_email,:locale)"; - try { - $statement = $db->prepare($sql); - if (!$statement) { throw new Exception("failed to prepare SQL query"); } - $result = $statement->execute( array( ":id" => $upload['id'], - ":user_id" => $auth['id'], - ":name" => $upload['name'], - ":path" => $upload['path'], - ":size" => $upload['size'], - ":cmt" => $params["comment"], - ":pass_ph" => (empty($params["pass"]) ? NULL : hashPassword($params["pass"])), - ":pass_send" => $params["pass_send"], - ":time" => time(), - ":expire" => $total, - ":last_time" => $lastdl, - ":expire_dln" => $maxdl, - ":notify_email" => (empty($params["notify"])? 'NULL': fixEMailAddrs($params["notify"])), - ":sent_email" => (empty($params["send_to"])? 'NULL': fixEMailAddrs($params["send_to"])), - ":locale" => $locale ) ); - } - catch(PDOException $e) - { - logDBError($db, "cannot commit new ticket to database"); - return false; - } - - // fetch defaults - $sql = "SELECT * FROM ticket WHERE id = " . $db->quote($upload['id']); - $DATA = $db->query($sql)->fetch(); - $DATA['pass'] = (empty($params["pass"])? NULL: $params["pass"]); - - // trigger creation hooks - onTicketCreate($DATA); - - return $DATA; + $success = DBConnection::getInstance()->getGenTicketQuery()->setParameter(0,$upload['id'])-> + setParameter(1,$auth['id'])-> + setParameter(2,$upload['name'])-> + setParameter(3,$upload['path'])-> + setParameter(4,$upload['size'])-> + setParameter(5,$params["comment"])-> + setParameter(6, (empty($params["pass"]) ? NULL : hashPassword($params["pass"])))-> + setParameter(7,$params["pass_send"])-> + setParameter(8,time())-> + setParameter(9,$total)-> + setParameter(10,$lastdl)-> + setParameter(11,$maxdl)-> + setParameter(12,(empty($params["notify"])? NULL : fixEMailAddrs($params["notify"])))-> + setParameter(13,(empty($params["send_to"])? NULL : fixEMailAddrs($params["send_to"])))-> + setParameter(14,$locale)->execute(); + $DATA = DBConnection::getInstance()->getTicketById($upload['id']); + $DATA['pass'] = (empty($params["pass"])? NULL : $params["pass"]); + + Hooks::getInstance()->callHook('onTicketCreate',$DATA); + + return $DATA; } From 2c9ab71f81bda085b04cfe32f26e468a106a7ab7 Mon Sep 17 00:00:00 2001 From: Jens Zahner Date: Mon, 16 Jul 2018 16:14:30 +0200 Subject: [PATCH 3/5] completed refactoring to DBAL --- htdocs/include/admfuncs.php | 143 +++++++++++++----------------------- 1 file changed, 51 insertions(+), 92 deletions(-) diff --git a/htdocs/include/admfuncs.php b/htdocs/include/admfuncs.php index 6cfc4c5..eaf4b25 100644 --- a/htdocs/include/admfuncs.php +++ b/htdocs/include/admfuncs.php @@ -75,17 +75,13 @@ function genTicketId() function genGrantId() { - global $db, $maxUUTries; + global $maxUUTries; - $q = $db->prepare('SELECT id FROM "grant" WHERE id = :id'); $tries = $maxUUTries; - do - { + do { $id = randomToken(); - $q->closeCursor(); - $q->execute(array(':id' => $id)); } - while($q->fetch() !== FALSE && --$tries); + while((DBConnection::getInstance()->getGrantById($id)!==false) && --$tries); if(!$tries) { logError("cannot generate unique grant ID"); @@ -98,70 +94,72 @@ function genGrantId() function userAdd($user, $pass, $admin, $email = false) { - global $db, $maxUserLen, $maxPassLen; + global $maxUserLen, $maxPassLen; // validate user/password sizes if(strlen($user) > $maxUserLen || strlen($pass) > $maxPassLen) return false; - - // prepare the SQL - $sql = 'INSERT INTO "user" (name, pass_ph, role_id, email) VALUES ('; - $sql .= $db->quote($user); - $sql .= ", " . (empty($pass)? 'NULL': $db->quote(hashPassword($pass))); - $sql .= ", (SELECT id FROM role WHERE name = '" - . ($admin? 'admin': 'user') . "')"; - $sql .= ", " . (empty($email)? 'NULL': $db->quote($email)); - $sql .= ")"; - - $ret = ($db->exec($sql) == 1); - logEvent("adding user $user: " . ($ret? "success": "fail"), - ($ret? LOG_INFO: LOG_ERR)); - return $ret; + + if ($admin) { + $role = DBConnection::getInstance()->getRoleByName('admin'); + } + else { + $role = DBConnection::getInstance()->getRoleByName('user'); + } + if ($role===FALSE) { + throw new \Exception("Could not find role"); + } + + if (empty($pass)) { + $pass = null; + } + else { + $pass = hashPassword($pass); + } + + $result = DBConnection::getInstance()->createUser($user, + (empty($pass)? NULL : hashPassword($pass)), + $role['id'], + (empty($email)? NULL : $email)); + logEvent("adding user $user: " . ($result? "success": "fail"), + ($result? LOG_INFO: LOG_ERR)); + return $result; } function userDel($user) { - global $db; - $sql = 'DELETE FROM "user" WHERE name = ' . $db->quote($user); - $ret = ($db->exec($sql) == 1); - logEvent("deleting user $user: " . ($ret? "success": "fail"), - ($ret? LOG_INFO: LOG_ERR)); + $result = DBConnection::getInstance()->deleteUser($user); + logEvent("deleting user $user: " . ($result? "success": "fail"), + ($result? LOG_INFO: LOG_ERR)); return $ret; } function userUpd($user, $pass = null, $admin = null, $email = null) { - global $db, $maxUserLen, $maxPassLen; + global $maxUserLen, $maxPassLen; // validate user/password sizes if(strlen($user) > $maxUserLen || strlen($pass) > $maxPassLen) return false; // prepare the SQL - $fields = array(); + $ret = true; if(!is_null($pass)) { - $fields[] = "pass_md5 = NULL"; - $fields[] = "pass_ph = " . (empty($pass)? 'NULL': $db->quote(hashPassword($pass))); + $ret |= DBConnection::getInstance()->updateUserPassword($user,hashPassword($pass)); } if(!is_null($admin)) { - $fields[] = "role_id = (SELECT id FROM role WHERE name = '" - . ($admin? 'admin': 'user') . "')"; + $role = DBConnection::getInstance()->getRoleByName(($admin? 'admin': 'user')); + $ret |= DBConnection::getInstance()->updateUserRole($user,$role['id']); } if(!is_null($email)) { - $fields[] = "email = " . (empty($email)? 'NULL': $db->quote($email)); + $ret |= DBConnection::getInstance()->updateUserEmail($user,(empty($email)? NULL: $email)); } - if(!count($fields)) - return false; - - $sql = 'UPDATE "user" SET ' . implode(", ", $fields) - . " WHERE name = " . $db->quote($user); - $ret = ($db->exec($sql) == 1); - + $msg = array(); if(!is_null($pass)) $msg[] = "password"; if(!is_null($admin)) $msg[] = "role"; @@ -174,14 +172,7 @@ function userUpd($user, $pass = null, $admin = null, $email = null) function userAdm($user) { - global $db; - - $sql = 'SELECT u.name, admin FROM "user" u' - . " LEFT JOIN role r ON r.id = u.role_id" - . " WHERE u.name = " . $db->quote($user); - $DATA = $db->query($sql)->fetch(); - - return ($DATA? $DATA['admin']: null); + return DBConnection::getInstance()->userIsAdmin($user); } @@ -193,13 +184,12 @@ function userCheck($user, $pass) function hasPassHash($DATA) { - return (isset($DATA['pass_ph']) || isset($DATA['pass_md5'])); + return isset($DATA['pass_ph']); } - function checkPassHash($table, $DATA, $pass) { - global $db, $maxPassLen; + global $maxPassLen; // validate password size if(strlen($pass) > $maxPassLen) @@ -208,64 +198,33 @@ function checkPassHash($table, $DATA, $pass) if(!$DATA || empty($pass) || isset($DATA['pass_ph'])) { $hash = ($DATA !== false? $DATA['pass_ph']: '*'); - $okpass = password_verify($pass, $hash); + return password_verify($pass, $hash); } - else - { - // legacy upgrade - $okpass = (md5($pass) === $DATA['pass_md5']); - if($okpass) - { - $id = $DATA['id']; - $DATA['pass_md5'] = NULL; - $DATA['pass_ph'] = hashPassword($pass); - $sql = "UPDATE $table" - . " SET pass_ph = " . $db->quote($DATA['pass_ph']) - . ", pass_md5 = NULL WHERE id = " . $db->quote($id); - $ret = ($db->exec($sql) == 1); - logEvent("upgrading password hash of $table/$id: " - . ($ret? "success": "fail"), ($ret? LOG_INFO: LOG_ERR)); - } - } - - return $okpass; + return false; } function userLogin($user, $pass, $rmt, $email = false) { - global $db, $maxUserLen, $maxPassLen; + global $maxUserLen, $maxPassLen; // validate user/password sizes if(strlen($user) > $maxUserLen || strlen($pass) > $maxPassLen) return false; // fetch the user - $sql = 'SELECT u.id, u.name, pass_md5, pass_ph, admin, email FROM "user" u' - . " LEFT JOIN role r ON r.id = u.role_id" - . " WHERE u.name = " . $db->quote($user); - $DATA = $db->query($sql)->fetch(); - + $DATA = DBConnection::getInstance()->getUserByName($user); // remote auth doesn't check pass, but still needs an id stub if($rmt) { if(!$DATA) { - // create a stub user and get the id - $sql = 'INSERT INTO "user" (name, role_id, email) VALUES ('; - $sql .= $db->quote($user); - $sql .= ", (SELECT id FROM role WHERE name = 'user')"; - $sql .= ", " . (empty($email)? 'NULL': $db->quote($email)); - $sql .= ")"; - if($db->exec($sql) != 1) return false; - - // fetch defaults - $sql = 'SELECT u.id, u.name, admin, email FROM "user" u'; - $sql .= " LEFT JOIN role r ON r.id = u.role_id"; - $sql .= " WHERE u.name = " . $db->quote($user); - $DATA = $db->query($sql)->fetch(); + $role = DBConnection::getInstance()->getRoleByName('user'); + if (!DBConnection::getInstance()->createUser($user,null,$role['id'],$email)) { + return false; + } + $DATA = DBConnection::getInstance()->getUserByName($user); } - return $DATA; } From 1594458781dad813ec7ec6bc85a6e452dca5e5d1 Mon Sep 17 00:00:00 2001 From: Jens Zahner Date: Mon, 16 Jul 2018 16:22:37 +0200 Subject: [PATCH 4/5] Refactored useradmin.php to use DBAL --- htdocs/include/dbfuncs.php | 157 +++++++++++++++++++++++---- htdocs/include/scripts/useradmin.php | 4 +- 2 files changed, 134 insertions(+), 27 deletions(-) diff --git a/htdocs/include/dbfuncs.php b/htdocs/include/dbfuncs.php index 549cd69..5097693 100644 --- a/htdocs/include/dbfuncs.php +++ b/htdocs/include/dbfuncs.php @@ -30,8 +30,8 @@ protected function __clone() { } * */ public function getGenTicketQuery() { - return $this->conn->createQueryBuilder()->insert("ticket")-> - values([ 'id' => '?', + return $this->conn->createQueryBuilder()->insert("ticket") + ->values([ 'id' => '?', 'user_id' => '?', 'name' => '?', 'path' => '?', @@ -49,43 +49,152 @@ public function getGenTicketQuery() { } public function getTicketById($id) { - return $this->conn->createQueryBuilder()->select("*")-> - from("ticket")-> - where("id = ?")-> - setParameter(0,$id)->execute()->fetch(); + return $this->conn->createQueryBuilder()->select("*") + ->from("ticket") + ->where("id = ?") + ->setParameter(0,$id) + ->execute() + ->fetch(); } + public function getGrantById($id) { + return $this->conn->createQueryBuilder()->select("*") + ->from("grant") + ->where("id = ?") + ->setParameter(0,$id) + ->execute() + ->fetch(); + } + + + public function purgeTicketById($id) { return (1===$this->conn->createQueryBuilder()->delete("ticket") ->where("id = ?") - ->setParameter(0,$id)->execute() ); + ->setParameter(0,$id) + ->execute() ); } public function purgeGrantById($id) { return (1===$this->conn->createQueryBuilder()->delete("grant") ->where("id = ?") - ->setParameter(0,$id)->execute() ); + ->setParameter(0,$id) + ->execute() ); } public function getTicketsToPurge($now,$limit) { - return $this->conn->createQueryBuilder()->select("*")-> - from("ticket")-> - where("(expire + time) < ?")-> - or("(last_stamp + last_time) < ?")-> - or("OR expire_dln <= downloads")-> - setMaxResults($limit)-> - setParameter(0,$now)-> - setParameter(1,$now)->execute()->fetchAll(); + $queryBuilder = $this->conn->createQueryBuilder(); + return $queryBuilder->select("*")->from("ticket") + ->where($queryBuilder->expr()->orX( + $queryBuilder->expr()->lt('(expire + time)','?'), + $queryBuilder->expr()->lt('(last_stamp + last_time)','?'), + $queryBuilder->expr()->lte('expire_dln','downloads'))) + ->setMaxResults($limit) + ->setParameter(0,$now) + ->setParameter(1,$now) + ->execute()->fetchAll(); } public function getGrantsToPurge($now,$limit) { - return $this->conn->createQueryBuilder()->select("*")-> - from("grant")-> - where("(grant_expire + time) < ?")-> - or("(last_stamp + grant_last_time) < ?")-> - or("OR grant_expire_uln <= uploads")-> - setMaxResults($limit)-> - setParameter(0,$now)-> - setParameter(1,$now)->execute()->fetchAll(); + $queryBuilder = $this->conn->createQueryBuilder(); + return $queryBuilder->select("*")->from("grant") + ->where( + $queryBuilder->expr()->orX( + $queryBuilder->expr()->lt('(grant_expire + time)','?'), + $queryBuilder->expr()->lt('(last_stamp + grant_last_time)','?'), + $queryBuilder->expr()->lte('grant_expire_uln','uploads'))) + ->setMaxResults($limit) + ->setParameter(0,$now) + ->setParameter(1,$now) + ->execute() + ->fetchAll(); + } + + public function getRoleByName($name) { + return $this->conn->createQueryBuilder()->select("*") + ->from("role") + ->where("name = ?") + ->setParameter(0,$name) + ->execute() + ->fetch(); + } + + public function createUser($user,$password,$role_id,$email) { + return (1===$this->conn->createQueryBuilder()->insert("user") + ->values(['name' => '?', + 'pass_ph' => '?', + 'role_id' => '?', + 'email' => '?'] ) + ->setParameter(0,$user) + ->setParameter(1,$password) + ->setParameter(2,$role_id) + ->setParameter(3,$email) + ->execute()); + } + + public function deleteUser($user) { + return (1===$this->conn->createQueryBuilder()->delete("user") + ->where("name = ?") + ->setParameter(0,$user) + ->execute() ); + } + + public function updateUserPassword($user,$password) { + return (1===$this->conn->createQueryBuilder()->update("user") + ->set('pass_ph','?') + ->where('name => ?') + ->setParameter(0,$password) + ->setParameter(1,$user) + ->execute()); + } + + public function updateUserRole($user,$role_id) { + return (1===$this->conn->createQueryBuilder()->update("user") + ->set('role_id','?') + ->where('name = ?') + ->setParameter(0,$role_id) + ->setParameter(1,$user) + ->execute()); + } + + public function updateUserEmail($user,$email) { + return (1===$this->conn->createQueryBuilder()->update("user") + ->set('email','?') + ->where('name = ?') + ->setParameter(0,$email) + ->setParameter(1,$user) + ->execute()); + } + + public function userIsAdmin($user) { + $result = $this->conn->createQueryBuilder()->select("u.name","r.admin") + ->from('user', 'u') + ->innerJoin('u','role','r','u.role_id = r.id') + ->where('u.name = ?') + ->setParameter(0,$user) + ->execute() + ->fetch(); + if (!$result) { + return null; + } + return $result['admin']; + } + + public function getUserByName($user) { + return $this->conn->createQueryBuilder()->select("u.id","u.name","u.pass_ph","admin","r.admin", "u.email") + ->from('user', 'u') + ->innerJoin('u','role','r','u.role_id = r.id') + ->where('u.name = ?') + ->setParameter(0,$user) + ->execute() + ->fetch(); + } + + public function getAllUsers() { + return $this->conn->createQueryBuilder()->select("u.id","u.name","u.pass_ph","admin","r.admin", "u.email") + ->from('user', 'u') + ->innerJoin('u','role','r','u.role_id = r.id') + ->execute() + ->fetchAll(); } } diff --git a/htdocs/include/scripts/useradmin.php b/htdocs/include/scripts/useradmin.php index 2a2d11b..79c1e97 100755 --- a/htdocs/include/scripts/useradmin.php +++ b/htdocs/include/scripts/useradmin.php @@ -29,9 +29,7 @@ if($argv[1] == 'list') { echo "#user\tadm\n"; - - $sql = 'SELECT u.name, admin FROM "user" u LEFT JOIN role r ON r.id = u.role_id'; - foreach($db->query($sql) as $DATA) + foreach(DBConnection::getInstance()->getAllUsers() as $DATA) echo $DATA["name"] . "\t" . ($DATA["admin"]? "true": "false") . "\n"; exit(0); From 72ceeac268ac99f549113c06983247694b6ade14 Mon Sep 17 00:00:00 2001 From: Jens Zahner Date: Tue, 17 Jul 2018 16:52:44 +0200 Subject: [PATCH 5/5] finished integration of Doctrine DBAL into dl-service --- htdocs/include/admfuncs.php | 19 +- htdocs/include/dbfuncs.php | 529 ++++++++++++++++++++++------- htdocs/include/editgrant.php | 51 ++- htdocs/include/editgrants.php | 6 +- htdocs/include/editticket.php | 52 ++- htdocs/include/edittickets.php | 4 +- htdocs/include/grant.php | 104 +++--- htdocs/include/grantfuncs.php | 63 ++-- htdocs/include/grantl.php | 13 +- htdocs/include/grantla.php | 9 +- htdocs/include/hooks.php | 46 ++- htdocs/include/init.php | 3 - htdocs/include/restpurgeticket.php | 5 +- htdocs/include/sessauth.php | 2 +- htdocs/include/ticket.php | 3 +- htdocs/include/ticketfuncs.php | 41 +-- htdocs/include/ticketl.php | 11 +- htdocs/include/ticketla.php | 9 +- htdocs/include/ticketlr.php | 13 +- htdocs/include/ticketr.php | 15 +- htdocs/include/users.php | 22 +- 21 files changed, 613 insertions(+), 407 deletions(-) diff --git a/htdocs/include/admfuncs.php b/htdocs/include/admfuncs.php index eaf4b25..ac46c41 100644 --- a/htdocs/include/admfuncs.php +++ b/htdocs/include/admfuncs.php @@ -13,9 +13,10 @@ function restart_session() function ticketPurge($DATA, $auto = true) { + error_log(print_r($DATA,true)); if (DBConnection::getInstance()->purgeTicketById($DATA['id'])) { unlink($DATA["path"]); - Hooks::getInstance()->callHook('onTicketPurge',$DATA,$auto); + Hooks::getInstance()->callHook('onTicketPurge',['ticket' => $DATA,'auto' => $auto]); } } @@ -23,7 +24,7 @@ function ticketPurge($DATA, $auto = true) function grantPurge($DATA, $auto = true) { if (DBConnection::getInstance()->purgeGrantById($DATA['id'])) { - Hooks::getInstance()->callHook('onGrantPurge',$DATA,$auto); + Hooks::getInstance()->callHook('onGrantPurge',['grant' => $DATA,'auto' => $auto]); } } @@ -43,6 +44,7 @@ function runGc() { global $gcLimit; foreach(DBConnection::getInstance()->getTicketsToPurge(time(),$gcLimit) as $DATA) { + print_r($DATA); ticketPurge($DATA); } @@ -145,21 +147,26 @@ function userUpd($user, $pass = null, $admin = null, $email = null) return false; // prepare the SQL - $ret = true; + $values = array(); if(!is_null($pass)) { - $ret |= DBConnection::getInstance()->updateUserPassword($user,hashPassword($pass)); + $values['pass_ph'] = hashPassword($pass); } if(!is_null($admin)) { $role = DBConnection::getInstance()->getRoleByName(($admin? 'admin': 'user')); - $ret |= DBConnection::getInstance()->updateUserRole($user,$role['id']); + $values['role_id'] = $role['id']; } if(!is_null($email)) { - $ret |= DBConnection::getInstance()->updateUserEmail($user,(empty($email)? NULL: $email)); + $values['email'] = (empty($email)? NULL: $email); } + if (count(array_keys($values))==0) { + return false; + } + $ret = DBConnection::getInstance()->updateUser($user, $values); + $msg = array(); if(!is_null($pass)) $msg[] = "password"; if(!is_null($admin)) $msg[] = "role"; diff --git a/htdocs/include/dbfuncs.php b/htdocs/include/dbfuncs.php index 5097693..e96ed96 100644 --- a/htdocs/include/dbfuncs.php +++ b/htdocs/include/dbfuncs.php @@ -9,6 +9,10 @@ final class DBConnection { protected $conn; protected $queries; + /** + * + * @return DBConnection + */ public static function getInstance() { if (!isset(static::$instance)) { static::$instance = new static; @@ -16,38 +20,101 @@ public static function getInstance() { return static::$instance; } + /** + * protected constructor for Singleton + */ protected function __construct() { - GLOBAL $dsn2; - $this->conn = \Doctrine\DBAL\DriverManager::getConnection([ 'url' => $dsn2 ], new \Doctrine\DBAL\Configuration()); + GLOBAL $dsn; + $this->conn = \Doctrine\DBAL\DriverManager::getConnection([ 'url' => $dsn ], new \Doctrine\DBAL\Configuration()); + + $this->checkDBVersion(); } /** - * Me not like clones! Me smash clones! + * Checks the database version using the config table, and the parameter "version" + */ + protected function checkDBVersion() { + GLOBAL $schemaVersion; + $version = $this->conn->createQueryBuilder()->select('value') + ->from('config') + ->where('name = ?') + ->setParameter(0,'version') + ->execute() + ->fetchColumn(); + if(version_compare($version, $schemaVersion, "!=")) { + die("database requires schema upgrade\n"); + } + } + + + /** + * Singletons may not be cloned */ protected function __clone() { } /** * + * @param string $id + * @param integer $user_id + * @param string $name + * @param string $path + * @param integer $size + * @param string $cmt + * @param string|null $pass_ph + * @param boolean $pass_send + * @param integer $time + * @param integer $expire + * @param integer $last_time + * @param integer $expire_dln + * @param string|null $notify_email + * @param string|null $sent_email + * @param string $locale + * @param string|null $from_grant + * @return boolean */ - public function getGenTicketQuery() { - return $this->conn->createQueryBuilder()->insert("ticket") - ->values([ 'id' => '?', - 'user_id' => '?', - 'name' => '?', - 'path' => '?', - 'size' => '?', - 'cmt' => '?', - 'pass_ph' => '?', - 'pass_send' => '?', - 'time' => '?', - 'expire' => '?', - 'last_time' => '?', - 'expire_dln'=> '?', - 'notify_email'=>'?', - 'sent_email' => '?', - 'locale' => '?']); + public function generateTicket($id,$user_id,$name,$path,$size,$cmt,$pass_ph,$pass_send,$time,$expire,$last_time,$expire_dln,$notify_email,$sent_email,$locale,$from_grant = null) { + return (1===$this->conn->createQueryBuilder()->insert("ticket") + ->values([ 'id' => '?', + 'user_id' => '?', + 'name' => '?', + 'path' => '?', + 'size' => '?', + 'cmt' => '?', + 'pass_ph' => '?', + 'pass_send' => '?', + 'time' => '?', + 'expire' => '?', + 'last_time' => '?', + 'expire_dln'=> '?', + 'notify_email'=>'?', + 'sent_email' => '?', + 'locale' => '?', + 'from_grant' => '?' + ]) + ->setParameter(0,$id) + ->setParameter(1,$user_id) + ->setParameter(2,$name) + ->setParameter(3,$path) + ->setParameter(4,$size) + ->setParameter(5,$cmt) + ->setParameter(6,$pass_ph) + ->setParameter(7,$pass_send) + ->setParameter(8,$time) + ->setParameter(9,$expire) + ->setParameter(10,$last_time) + ->setParameter(11,$expire_dln) + ->setParameter(12,$notify_email) + ->setParameter(13,$sent_email) + ->setParameter(14,$locale) + ->setParameter(15,$from_grant) + ->execute()); } + /** + * + * @param string $id + * @return array|null + */ public function getTicketById($id) { return $this->conn->createQueryBuilder()->select("*") ->from("ticket") @@ -57,6 +124,11 @@ public function getTicketById($id) { ->fetch(); } + /** + * + * @param string $id + * @return array|null + */ public function getGrantById($id) { return $this->conn->createQueryBuilder()->select("*") ->from("grant") @@ -67,7 +139,11 @@ public function getGrantById($id) { } - + /** + * + * @param string $id + * @return boolean + */ public function purgeTicketById($id) { return (1===$this->conn->createQueryBuilder()->delete("ticket") ->where("id = ?") @@ -75,6 +151,11 @@ public function purgeTicketById($id) { ->execute() ); } + /** + * + * @param string $id + * @return boolean + */ public function purgeGrantById($id) { return (1===$this->conn->createQueryBuilder()->delete("grant") ->where("id = ?") @@ -82,6 +163,12 @@ public function purgeGrantById($id) { ->execute() ); } + /** + * + * @param integer $now + * @param integer $limit + * @return array + */ public function getTicketsToPurge($now,$limit) { $queryBuilder = $this->conn->createQueryBuilder(); return $queryBuilder->select("*")->from("ticket") @@ -94,6 +181,13 @@ public function getTicketsToPurge($now,$limit) { ->setParameter(1,$now) ->execute()->fetchAll(); } + + /** + * + * @param integer $now + * @param integer $limit + * @return array + */ public function getGrantsToPurge($now,$limit) { $queryBuilder = $this->conn->createQueryBuilder(); return $queryBuilder->select("*")->from("grant") @@ -109,6 +203,11 @@ public function getGrantsToPurge($now,$limit) { ->fetchAll(); } + /** + * + * @param string $name + * @return array|null + */ public function getRoleByName($name) { return $this->conn->createQueryBuilder()->select("*") ->from("role") @@ -118,6 +217,14 @@ public function getRoleByName($name) { ->fetch(); } + /** + * + * @param string $user + * @param string $password + * @param integer $role_id + * @param string $email + * @return boolean + */ public function createUser($user,$password,$role_id,$email) { return (1===$this->conn->createQueryBuilder()->insert("user") ->values(['name' => '?', @@ -131,40 +238,23 @@ public function createUser($user,$password,$role_id,$email) { ->execute()); } + /** + * + * @param string $user + * @return boolean + */ public function deleteUser($user) { return (1===$this->conn->createQueryBuilder()->delete("user") ->where("name = ?") ->setParameter(0,$user) ->execute() ); } - - public function updateUserPassword($user,$password) { - return (1===$this->conn->createQueryBuilder()->update("user") - ->set('pass_ph','?') - ->where('name => ?') - ->setParameter(0,$password) - ->setParameter(1,$user) - ->execute()); - } - - public function updateUserRole($user,$role_id) { - return (1===$this->conn->createQueryBuilder()->update("user") - ->set('role_id','?') - ->where('name = ?') - ->setParameter(0,$role_id) - ->setParameter(1,$user) - ->execute()); - } - public function updateUserEmail($user,$email) { - return (1===$this->conn->createQueryBuilder()->update("user") - ->set('email','?') - ->where('name = ?') - ->setParameter(0,$email) - ->setParameter(1,$user) - ->execute()); - } - + /** + * + * @param string $user + * @return NULL|boolean + */ public function userIsAdmin($user) { $result = $this->conn->createQueryBuilder()->select("u.name","r.admin") ->from('user', 'u') @@ -176,9 +266,14 @@ public function userIsAdmin($user) { if (!$result) { return null; } - return $result['admin']; + return $result[0]['admin']; } + /** + * + * @param string $user + * @return array|null + */ public function getUserByName($user) { return $this->conn->createQueryBuilder()->select("u.id","u.name","u.pass_ph","admin","r.admin", "u.email") ->from('user', 'u') @@ -189,79 +284,275 @@ public function getUserByName($user) { ->fetch(); } - public function getAllUsers() { + /** + * + * @param integer $user + * @return array|null + */ + public function getUserById($id) { return $this->conn->createQueryBuilder()->select("u.id","u.name","u.pass_ph","admin","r.admin", "u.email") - ->from('user', 'u') - ->innerJoin('u','role','r','u.role_id = r.id') - ->execute() - ->fetchAll(); + ->from('user', 'u') + ->innerJoin('u','role','r','u.role_id = r.id') + ->where('u.id = ?') + ->setParameter(0,$id) + ->execute() + ->fetch(); } -} - - -// a simple wrapper to handle some DB issues uniformly -class XPDO extends PDO -{ - public function driver() - { - return $this->getAttribute(PDO::ATTR_DRIVER_NAME); - } - - public function __construct($dns, $dbUser, $dbPassword) - { - parent::__construct($dns, $dbUser, $dbPassword); - - // make errors exceptional - $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - - switch($this->driver()) - { - case "sqlite": - // enforce foreign keys by default - $this->exec('PRAGMA foreign_keys = ON'); - break; - - case "mysql": - // put MySQL into ANSI mode - $this->exec('SET SQL_MODE = ANSI'); - break; + + /** + * + * @return array + */ + public function getAllUsers() { + return $this->conn->createQueryBuilder()->select("u.id","u.name","u.pass_ph","r.admin", "u.email") + ->from('user', 'u') + ->innerJoin('u','role','r','u.role_id = r.id') + ->execute() + ->fetchAll(); } - } - - public function ping() - { - try { return (@$this->exec('SELECT 1') == 1); } - catch(PDOException $e) { return false; } - } -} - - -// initialize the database connection -function connectDB($checkSchema = True) -{ - global $db, $dsn, $dbUser, $dbPassword, $schemaVersion; - - // initialize the db - try { $db = new XPDO($dsn, $dbUser, $dbPassword); } - catch(PDOException $e) { die("cannot initialize database\n"); } - - if($checkSchema) - { - // check schema version - $sql = "SELECT value FROM config WHERE name = 'version'"; - if(!($q = $db->query($sql))) - die("cannot initialize database\n"); - $version = $q->fetchColumn(); - if(version_compare($version, $schemaVersion, "!=")) - die("database requires schema upgrade\n"); - } -} + + /** + * + * @return array + */ + public function getAllUsersIncludingStats() { + $sql = <<conn->executeQuery($sql); + } + + /** + * + * @return boolean + */ + public function beginTransaction() { + return $this->conn->beginTransaction(); + } + + /** + * + * @return boolean + */ + public function commit() { + return $this->conn->commit(); + } + + /** + * + * @return boolean + */ + public function rollBack() { + return $this->conn->rollBack(); + } + + /** + * + * @param string $id + * @param integer $now + * @param integer $downloadCount + * @return boolean + */ + public function updateGrantUsage($id,$now,$updateCount) { + return (1===$this->conn->createQueryBuilder()->update("grant") + ->set('last_stamp','?') + ->set('uploads', '(uploads + ?)') + ->where('id = ?') + ->setParameter(0,$now) + ->setParameter(1,$updateCount) + ->setParameter(2,$id) + ->execute()); + } + + /** + * + * @param string $id + * @param integer $now + * @param integer $downloadCount + * @return boolean + */ + public function updateTicketUsage($id,$now,$downloadCount) { + return (1===$this->conn->createQueryBuilder()->update("ticket") + ->set('last_stamp','?') + ->set('downloads', '(downloads + ?)') + ->where('id = ?') + ->setParameter(0,$now) + ->setParameter(1,$downloadCount) + ->setParameter(2,$id) + ->execute()); + + } + + /** + * + * @param string $id + * @param array $values + * @return boolean + */ + public function updateGrant($id,$values) { + $q = $this->conn->createQueryBuilder()->update("grant"); + + $fields = array_keys($values); + + foreach($fields as $f) { + $q = $q->set($f,'?'); + } + for($i=0;$i < count($fields);$i++) { + $q = $q->setParameter($i,$values[$fields[$i]]); + } + return (1===$q->where('id = ?') + ->setParameter(count($values),$id) + ->execute()); + } -// check an existing DB connection for liveness and re-connect if needed -function reconnectDB() -{ - global $db; - if(!$db->ping()) - connectDB(false); + /** + * Updates user Information based on array $values + * @param string $user + * @param array $values + * @return boolean + */ + public function updateUser($user,$values) { + $q = $this->conn->createQueryBuilder()->update("user"); + + $fields = array_keys($values); + + //TODO: Sanity check here - check if all passed columns are valid + + foreach($fields as $f) { + $q = $q->set($f,'?'); + } + for($i=0;$i < count($fields);$i++) { + $q = $q->setParameter($i,$values[$fields[$i]]); + } + return (1===$q->where('name = ?') + ->setParameter(count($values),$user) + ->execute()); + } + + /** + * Updates user Information based on array $values + * @param string $user + * @param array $values + * @return boolean + */ + public function updateTicket($id,$values) { + $q = $this->conn->createQueryBuilder()->update("ticket"); + + $fields = array_keys($values); + foreach($fields as $f) { + $q = $q->set($f,'?'); + } + for($i=0;$i < count($fields);$i++) { + $q = $q->setParameter($i,$values[$fields[$i]]); + } + return (1===$q->where('id = ?') + ->setParameter(count($values),$id) + ->execute()); + } + + + public function createGrant($id,$user_id,$grant_expire,$grant_last_time,$grant_expire_dln,$cmt,$pass_ph,$pass_send,$time,$expire,$last_time,$expire_dln, $notify_email, $sent_email, $locale) { + return (1===$this->conn->createQueryBuilder()->insert("grant") + ->values(['id' => '?', + 'user_id' => '?', + 'grant_expire' => '?', + 'grant_last_time' => '?', + 'grant_expire_uln' => '?', + 'cmt' => '?', + 'pass_ph' => '?', + 'pass_send' => '?', + 'time' => '?', + 'expire' => '?', + 'last_time' => '?', + 'expire_dln' => '?', + 'notify_email' => '?', + 'sent_email' => '?', + 'locale' => '?' + ]) + ->setParameter(0,$id) + ->setParameter(1,$user_id) + ->setParameter(2,$grant_expire) + ->setParameter(3,$grant_last_time) + ->setParameter(4,$grant_expire_uln) + ->setParameter(5,$cmt) + ->setParameter(6,$pass_ph) + ->setParameter(7,$pass_send) + ->setParameter(8,$time) + ->setParameter(9,$expire) + ->setParameter(10,$last_time) + ->setParameter(11,$expire_dln) + ->setParameter(12,$notify_email) + ->setParameter(13,$sent_email) + ->setParameter(14,$locale) + ->execute()); + } + + /** + * + * @param string $user_id + * @return array + */ + public function getActiveGrantsByUser($user_id) { + return $this->conn->createQueryBuilder()->select("*") + ->from("grant") + ->where("user_id = ?") + ->orderBy('time','DESC') + ->setParameter(0,$user_id) + ->execute() + ->fetchAll(); + } + + public function getAllActiveGrants() { + $sql = 'SELECT g.*, u.name AS "user" FROM "grant" g' + . ' LEFT JOIN "user" u ON u.id = g.user_id' + . ' ORDER BY time DESC'; + return $this->conn->executeQuery($sql); + } + + public function getActiveTicketsForUser($user_id) { + $queryBuilder = $this->conn->createQueryBuilder(); + return $queryBuilder->select("*") + ->from("ticket") + ->where( + $queryBuilder->expr()->andX($queryBuilder->expr()->eq('user_id','?'), + $queryBuilder->expr()->isNull('from_grant') ) ) + ->orderBy('time','DESC') + ->setParameter(0,$user_id) + ->execute() + ->fetchAll(); + } + + public function getReceivedFilesForUser($user_id) { + $sql = 'SELECT t.*, g.cmt AS grant_cmt FROM ticket t' + . ' LEFT JOIN "grant" g ON g.id = t.from_grant' + . ' WHERE t.user_id = ' . $user_id + . ' AND t.from_grant IS NOT NULL' + . ' ORDER BY t.time DESC'; + return $this->conn->executeQuery($sql); + } + + public function getAllActiveTickets() { + $sql = 'SELECT t.*, u.name AS "user", t.from_grant FROM ticket t' + . ' LEFT JOIN "user" u ON u.id = t.user_id' + . ' ORDER BY time DESC'; + return $this->conn->executeQuery($sql); + } + + } diff --git a/htdocs/include/editgrant.php b/htdocs/include/editgrant.php index 22699f9..0c3ddf1 100644 --- a/htdocs/include/editgrant.php +++ b/htdocs/include/editgrant.php @@ -5,44 +5,40 @@ function handleUpdate($DATA, $params) { - global $db; - // handle parameters $values = array(); - $values['notify_email'] = $db->quote(fixEMailAddrs($params["notify"])); + $values['notify_email'] = fixEMailAddrs($params["notify"]); if(isset($params['comment'])) { $comment = trim($params['comment']); - $values['cmt'] = (empty($comment)? 'NULL': $db->quote($comment)); + $values['cmt'] = (empty($comment)? NULL: $comment); } if(isset($params['pass_clear']) && $params['pass_clear']) { - $values['pass_md5'] = 'NULL'; - $values['pass_ph'] = 'NULL'; + $values['pass_ph'] = NULL; } elseif(!empty($params['pass'])) { - $values['pass_md5'] = 'NULL'; - $values['pass_ph'] = $db->quote(hashPassword($params['pass'])); + $values['pass_ph'] = hashPassword($params['pass']); } if(isset($params['pass_send']) && $params['pass_send']) - $values['pass_send'] = 1; + $values['pass_send'] = true; else - $values['pass_send'] = 0; + $values['pass_send'] = false; if(isset($params['grant_permanent']) && $params['grant_permanent']) { - $values['grant_last_time'] = 'NULL'; - $values['grant_expire'] = 'NULL'; - $values['grant_expire_uln'] = 'NULL'; + $values['grant_last_time'] = NULL; + $values['grant_expire'] = NULL; + $values['grant_expire_uln'] = NULL; } else { if(empty($params['grant_totaldays'])) - $values['grant_expire'] = 'NULL'; + $values['grant_expire'] = NULL; elseif(isset($params['grant_totaldays'])) $values['grant_expire'] = (time() - $DATA["time"]) + $params["grant_totaldays"] * 3600 * 24; if(isset($params['grant_lastuldays'])) @@ -53,9 +49,9 @@ function handleUpdate($DATA, $params) if(isset($params['ticket_permanent']) && $params['ticket_permanent']) { - $values['last_time'] = 'NULL'; - $values['expire'] = 'NULL'; - $values['expire_dln'] = 'NULL'; + $values['last_time'] = NULL; + $values['expire'] = NULL; + $values['expire_dln'] = NULL; } else { @@ -70,21 +66,15 @@ function handleUpdate($DATA, $params) } // prepare the query - $tmp = array(); - foreach($values as $k => $v) $tmp[] = "$k = $v"; - $sql = "UPDATE \"grant\" SET " . join(", ", $tmp) - . " WHERE id = " . $db->quote($DATA["id"]); - if($db->exec($sql) != 1) - return false; - - // fetch defaults - $sql = "SELECT * FROM \"grant\" WHERE id = " . $db->quote($DATA["id"]); - $DATA = $db->query($sql)->fetch(); + if (!DBConnection::getInstance()->updateGrant($id,$values)) { + return false; + } + + $DATA = DBConnection::getInstance()->getGrantById($id); $DATA['pass'] = (empty($params["pass"])? NULL: $_POST["pass"]); // trigger update hooks - onGrantUpdate($DATA); - + Hooks::getInstance()->callHook('onGrantUpdate',['grant' => $DATA]); return $DATA; } @@ -96,8 +86,7 @@ function handleUpdate($DATA, $params) $id = false; else { - $sql = "SELECT * FROM \"grant\" WHERE id = " . $db->quote($id); - $DATA = $db->query($sql)->fetch(); + $DATA = DBConnection::getInstance()->getGrantById($id); if($DATA === false || isGrantExpired($DATA) || (!$auth["admin"] && $DATA["user_id"] != $auth["id"])) $DATA = false; diff --git a/htdocs/include/editgrants.php b/htdocs/include/editgrants.php index b0a428b..431f040 100644 --- a/htdocs/include/editgrants.php +++ b/htdocs/include/editgrants.php @@ -79,9 +79,9 @@ // owner if($DATA["user_id"] != $auth["id"]) { - $sql = 'SELECT name FROM "user"' - . " WHERE id = " . $db->quote($DATA["user_id"]); - $user = $db->query($sql)->fetch(); + $user = DBConnection::getInstance()->getUserById($DATA["user_id"]); + + $details[T_('Created by')] = htmlEntUTF8($user["name"]); } diff --git a/htdocs/include/editticket.php b/htdocs/include/editticket.php index a7decdb..0c00ac8 100644 --- a/htdocs/include/editticket.php +++ b/htdocs/include/editticket.php @@ -5,73 +5,62 @@ function handleUpdate($DATA, $params) { - global $db; - // handle parameters $values = array(); if(!empty($params['name'])) - $values['name'] = $db->quote(mb_sanitize($params['name'])); + $values['name'] = mb_sanitize($params['name']); if(isset($params['comment'])) { $comment = trim($params['comment']); - $values['cmt'] = (empty($comment)? 'NULL': $db->quote($comment)); + $values['cmt'] = (empty($comment)? 'NULL': $comment); } if(isset($params['pass_clear']) && $params['pass_clear']) { - $values['pass_md5'] = 'NULL'; - $values['pass_ph'] = 'NULL'; + $values['pass_ph'] = NULL; } elseif(!empty($params['pass'])) { - $values['pass_md5'] = 'NULL'; - $values['pass_ph'] = $db->quote(hashPassword($params['pass'])); + $values['pass_ph'] = hashPassword($params['pass']); } if(isset($params['pass_send']) && $params['pass_send']) - $values['pass_send'] = 1; + $values['pass_send'] = true; else - $values['pass_send'] = 0; + $values['pass_send'] = 0false; if(isset($params['ticket_permanent']) && $params['ticket_permanent']) { - $values['last_time'] = 'NULL'; - $values['expire'] = 'NULL'; - $values['expire_dln'] = 'NULL'; + $values['last_time'] = NULL; + $values['expire'] = NULL; + $values['expire_dln'] = NULL; } else { if(empty($params['ticket_totaldays'])) - $values['expire'] = 'NULL'; + $values['expire'] = NULL; elseif(isset($params['ticket_totaldays'])) $values['expire'] = (time() - $DATA["time"]) + $params["ticket_totaldays"] * 3600 * 24; if(isset($params['ticket_lastdldays'])) - $values['last_time'] = (empty($params['ticket_lastdldays'])? 'NULL': $params["ticket_lastdldays"] * 3600 * 24); + $values['last_time'] = (empty($params['ticket_lastdldays'])? NULL: $params["ticket_lastdldays"] * 3600 * 24); if(isset($params['ticket_maxdl'])) - $values['expire_dln'] = (empty($params['ticket_maxdl'])? 'NULL': $DATA["downloads"] + (int)$params['ticket_maxdl']); + $values['expire_dln'] = (empty($params['ticket_maxdl'])? NULL: $DATA["downloads"] + (int)$params['ticket_maxdl']); } if(isset($params['notify'])) - $values['notify_email'] = (empty($params['notify'])? 'NULL': $db->quote(fixEMailAddrs($params["notify"]))); - - // prepare the query - $tmp = array(); - foreach($values as $k => $v) $tmp[] = "$k = $v"; - $sql = "UPDATE ticket SET " . join(", ", $tmp) - . " WHERE id = " . $db->quote($DATA["id"]); - if($db->exec($sql) != 1) + $values['notify_email'] = (empty($params['notify'])? NULL: fixEMailAddrs($params["notify"])); + + if (!DBConnection::getInstance()->updateTicket($DATA["id"],$values)) { return false; - - // fetch defaults - $sql = "SELECT * FROM ticket WHERE id = " . $db->quote($DATA["id"]); - $DATA = $db->query($sql)->fetch(); + } + + $DATA = DBConnection::getInstance()->getTicketById($DATA["id"]); $DATA['pass'] = (empty($params["pass"])? NULL: $_POST["pass"]); // trigger update hooks - onTicketUpdate($DATA); - + Hooks::getInstance()->callHook('onTicketUpdate',['ticket' => $DATA]); return $DATA; } @@ -83,8 +72,7 @@ function handleUpdate($DATA, $params) $id = false; else { - $sql = "SELECT * FROM ticket WHERE id = " . $db->quote($id); - $DATA = $db->query($sql)->fetch(); + $DATA = DBConnection::getInstance()->getTicketById($DATA["id"]); if($DATA === false || isTicketExpired($DATA) || (!$auth["admin"] && $DATA["user_id"] != $auth["id"])) $DATA = false; diff --git a/htdocs/include/edittickets.php b/htdocs/include/edittickets.php index c4cdded..2934c56 100644 --- a/htdocs/include/edittickets.php +++ b/htdocs/include/edittickets.php @@ -57,9 +57,7 @@ // owner if($DATA["user_id"] != $auth["id"]) { - $sql = 'SELECT name FROM "user"' - . " WHERE id = " . $db->quote($DATA["user_id"]); - $user = $db->query($sql)->fetch(); + $user = DBConnection::getInstance()->getUserById($DATA["user_id"]); $details[T_('Created by')] = htmlEntUTF8($user["name"]); } diff --git a/htdocs/include/grant.php b/htdocs/include/grant.php index e74c9b8..9885dc9 100644 --- a/htdocs/include/grant.php +++ b/htdocs/include/grant.php @@ -11,8 +11,7 @@ } else { - $sql = "SELECT * FROM \"grant\" WHERE id = " . $db->quote($id); - $GRANT = $db->query($sql)->fetch(); + $GRANT = DBConnection::getInstance()->getGrantById($id) ; } $ref = "$masterPath?g=$id"; @@ -49,72 +48,59 @@ // upload handler function useGrant($upload, $GRANT, $DATA) { - global $db; - // populate comment with file list when empty if(!empty($DATA["cmt"])) $DATA["cmt"] = trim($DATA["cmt"]); if(empty($DATA["cmt"]) && count($upload['files']) > 1) $DATA["cmt"] = T_("Archive contents:") . "\n " . implode("\n ", $upload['files']); - // convert the upload to a ticket - $db->beginTransaction(); - - $sql = "INSERT INTO ticket (id, user_id, name, path, size, cmt, pass_ph, pass_send" - . ", time, last_time, expire, expire_dln, locale, from_grant) VALUES ("; - $sql .= $db->quote($upload['id']); - $sql .= ", " . $GRANT['user_id']; - $sql .= ", " . $db->quote($upload["name"]); - $sql .= ", " . $db->quote($upload["path"]); - $sql .= ", " . $upload["size"]; - $sql .= ", " . (empty($DATA["cmt"])? 'NULL': $db->quote($DATA["cmt"])); - $sql .= ", " . (empty($GRANT["pass_ph"])? 'NULL': $db->quote($GRANT["pass_ph"])); - $sql .= ", " . (int)$GRANT["pass_send"]; - $sql .= ", " . time(); - $sql .= ", " . (empty($GRANT["last_time"])? 'NULL': $GRANT['last_time']); - $sql .= ", " . (empty($GRANT["expire"])? 'NULL': $GRANT['expire']); - $sql .= ", " . (empty($GRANT["expire_dln"])? 'NULL': $GRANT['expire_dln']); - $sql .= ", " . (empty($GRANT["locale"])? 'NULL': $db->quote($GRANT['locale'])); - $sql .= ", " . $db->quote($GRANT['id']); - $sql .= ")"; - - try { $db->exec($sql); } - catch(PDOException $e) - { - logDBError($db, "cannot commit new ticket to database"); - return false; + // start Transaction + try { + DBConnection::getInstance()->beginTansaction(); + $success = DBConnection::getInstance()->generateTicket($upload['id'], + $GRANT['user_id'], + $upload["name"], + $upload["path"], + $upload["size"], + (empty($DATA["cmt"])? NULL: $DATA["cmt"]), + (empty($GRANT["pass_ph"])? NULL: $GRANT["pass_ph"]), + $GRANT["pass_send"], + time(), + (empty($GRANT["expire"])? NULL: $GRANT['expire']), + (empty($GRANT["last_time"])? NULL: $GRANT['last_time']), + (empty($GRANT["expire_dln"])? NULL: $GRANT['expire_dln']), + NULL, + NULL, + (empty($GRANT["locale"])? NULL: $GRANT['locale']), + $GRANT['id']); + if (!$success) { + logDBError(null, "cannot commit new ticket to database"); + return false; + } + + // update grant + ++$GRANT["uploads"]; + if(isGrantExpired($GRANT)) + { + DBConnection::getInstance()->purgeGrantById($GRANT['id']); + } + else + { + DBConnection::getInstance()->updateGrantUsage(time(),1); + } + DBConnection::getInstance()->commit(); } - - // check for validity after upload - ++$GRANT["uploads"]; - if(isGrantExpired($GRANT)) - { - $sql = "DELETE FROM \"grant\" WHERE id = " . $db->quote($GRANT['id']); - $db->exec($sql); + catch (\Exception $e) { + DBConnection::getInstance()->rollBack(); + return false; } - else - { - $now = time(); - $sql = "UPDATE \"grant\" SET last_stamp = $now" - . ", uploads = uploads + 1 WHERE id = " . $db->quote($GRANT['id']); - $db->exec($sql); - } - - try { $db->commit(); } - catch(PDOException $e) - { - logDBError($db, "cannot commit new ticket to database"); - return false; + + $TICKET = DBConnection::getInstance()->getTicketById($$upload['id']); + if(!empty($GRANT['pass'])) { + $TICKET['pass'] = $GRANT['pass']; } - - // fetch defaults - $sql = "SELECT * FROM ticket WHERE id = " . $db->quote($upload['id']); - $TICKET = $db->query($sql)->fetch(); - if(!empty($GRANT['pass'])) $TICKET['pass'] = $GRANT['pass']; - - // trigger use hooks - onGrantUse($GRANT, $TICKET); - + + Hooks::getInstance()->callHook('onGrantUse',['grant' => $GRANT, 'ticket' => $TICKET]); return array($GRANT, $TICKET); } diff --git a/htdocs/include/grantfuncs.php b/htdocs/include/grantfuncs.php index a1fac77..f55d93d 100644 --- a/htdocs/include/grantfuncs.php +++ b/htdocs/include/grantfuncs.php @@ -7,9 +7,10 @@ function isGrantExpired($DATA, $now = NULL) { if(!isset($now)) $now = time(); - return (($DATA["grant_expire"] && ($DATA["grant_expire"] + $DATA["time"]) < $now) - || ($DATA["last_stamp"] && $DATA["grant_last_time"] && ($DATA["last_stamp"] + $DATA["grant_last_time"]) < $now) - || ($DATA["grant_expire_uln"] && $DATA["grant_expire_uln"] <= $DATA["uploads"])); + $expire1 = (($DATA["grant_expire"]<>0) && ($DATA["grant_expire"] + $DATA["time"]) < $now); + $expire2 = (($DATA["last_stamp"]<>0) && $DATA["grant_last_time"] && ($DATA["last_stamp"] + $DATA["grant_last_time"]) < $now); + $expire3 = (($DATA["grant_expire_uln"]<>0) && $DATA["grant_expire_uln"] <= $DATA["uploads"]); + return $expire1 || $expire2 || $expire3; } @@ -96,7 +97,7 @@ function grantExpirationParams($params) function genGrant($params) { - global $auth, $locale, $db; + global $auth, $locale; // generate new unique id $id = genGrantId(); @@ -108,43 +109,33 @@ function genGrant($params) // expiration values list($grant_total, $grant_lastul, $grant_maxul) = grantExpirationParams($params); list($ticket_total, $ticket_lastdl, $ticket_maxdl) = ticketExpirationParams($params); - - // prepare data - $sql = "INSERT INTO \"grant\" (id, user_id, grant_expire, grant_last_time" - . ", grant_expire_uln, cmt, pass_ph, pass_send, time, expire, last_time" - . ", expire_dln, notify_email, sent_email, locale) VALUES ("; - $sql .= $db->quote($id); - $sql .= ", " . $auth['id']; - $sql .= ", " . $grant_total; - $sql .= ", " . $grant_lastul; - $sql .= ", " . $grant_maxul; - $sql .= ", " . (empty($params["comment"])? 'NULL': $db->quote($params["comment"])); - $sql .= ", " . (empty($params["pass"])? 'NULL': $db->quote(hashPassword($params["pass"]))); - $sql .= ", " . (!isset($params["pass_send"])? '1': (int)to_boolean($params["pass_send"])); - $sql .= ", " . time(); - $sql .= ", " . $ticket_total; - $sql .= ", " . $ticket_lastdl; - $sql .= ", " . $ticket_maxdl; - $sql .= ", " . (empty($params["notify"])? 'NULL': $db->quote(fixEMailAddrs($params["notify"]))); - $sql .= ", " . (empty($params["send_to"])? 'NULL': $db->quote(fixEMailAddrs($params["send_to"]))); - $sql .= ", " . $db->quote($locale); - $sql .= ")"; - - try { $db->exec($sql); } - catch(PDOException $e) - { - logDBError($db, "cannot commit new grant to database"); + + $ret = DBConnection::getInstance()->createGrant($id, + $auth['id'], + $grant_total, + $grant_lastul, + $grant_maxul, + (empty($params["comment"])? NULL:$params["comment"]), + (empty($params["pass"])? NULL: hashPassword($params["pass"])), + (!isset($params["pass_send"])? true: to_boolean($params["pass_send"])), + time(), + $ticket_total, + $ticket_lastdl, /* 10 */ + $ticket_maxdl, + (empty($params["notify"])? NULL: fixEMailAddrs($params["notify"])), + (empty($params["send_to"])? NULL: fixEMailAddrs($params["send_to"])), + $locale); + if (!$ret) { + logDBError(null, "cannot commit new grant to database"); return false; } - - // fetch defaults - $sql = "SELECT * FROM \"grant\" WHERE id = " . $db->quote($id); - $DATA = $db->query($sql)->fetch(); + + $DATA = DBConnection::getInstance()->getGrantById($id); $DATA['pass'] = (empty($params["pass"])? NULL: $params["pass"]); // trigger creation hooks - onGrantCreate($DATA); - + Hooks::getInstance()->callHook('onGrantCreate',['grant' => $DATA]); + return $DATA; } diff --git a/htdocs/include/grantl.php b/htdocs/include/grantl.php index 9dfe4e8..d957ff0 100644 --- a/htdocs/include/grantl.php +++ b/htdocs/include/grantl.php @@ -16,9 +16,8 @@ foreach($sel as $id) { if(!isGrantId($id)) continue; - $sql = "SELECT * FROM \"grant\" WHERE id = " . $db->quote($id); - $DATA = $db->query($sql)->fetch(); - if($DATA === false) continue; + $DATA = DBConnection::getInstance()->getGrantById($id); + if ($DATA === false) continue; // check for permissions if($DATA["user_id"] != $auth["id"]) @@ -33,11 +32,6 @@ infoMessage(T_("Purged"), $list); } -// list active grants -$sql = 'SELECT * FROM "grant" g' - . ' WHERE user_id = ' . $auth["id"] - . ' ORDER BY time DESC'; - ?>
@@ -54,8 +48,7 @@ query($sql) as $DATA) +foreach(DBConnection::getInstance()->getActiveGrantsByUser($auth["id"]) as $DATA) { if(isGrantExpired($DATA)) continue; diff --git a/htdocs/include/grantla.php b/htdocs/include/grantla.php index d5e3b5d..e941cd8 100644 --- a/htdocs/include/grantla.php +++ b/htdocs/include/grantla.php @@ -16,8 +16,8 @@ foreach($sel as $id) { if(!isGrantId($id)) continue; - $sql = "SELECT * FROM \"grant\" WHERE id = " . $db->quote($id); - $DATA = $db->query($sql)->fetch(); + + $DATA = DBConnection::getInstance()->getGrantById($id); if($DATA === false) continue; // actually purge the grant @@ -30,9 +30,6 @@ } // list active grants -$sql = 'SELECT g.*, u.name AS "user" FROM "grant" g' - . ' LEFT JOIN "user" u ON u.id = g.user_id' - . ' ORDER BY time DESC'; ?> @@ -52,7 +49,7 @@ query($sql) as $DATA) +foreach(DBConnection::getInstance()->getAllActiveGrants() as $DATA) { if(isGrantExpired($DATA)) continue; diff --git a/htdocs/include/hooks.php b/htdocs/include/hooks.php index 93d00b9..f93aea9 100644 --- a/htdocs/include/hooks.php +++ b/htdocs/include/hooks.php @@ -16,14 +16,14 @@ public static function getInstance() { protected function __construct() { $this->hooks = [ - 'onTicketCreate' => [onTicketCreate], - 'onTicketUpdate' => [], - 'onTicketDownload' => [onTicketDownload], - 'onTicketPurge' => [onTicketPurge], - 'onGrantCreate' => [onGrantCreate], - 'onGrantUpdate' => [], - 'onGrantPurge' => [onGrantPurge], - 'onGrantUse' => [onGrantUse] + 'onTicketCreate' => ['onTicketCreate'], + 'onTicketUpdate' => [], + 'onTicketDownload' => ['onTicketDownload'], + 'onTicketPurge' => ['onTicketPurge'], + 'onGrantCreate' => ['onGrantCreate'], + 'onGrantUpdate' => [], + 'onGrantPurge' => ['onGrantPurge'], + 'onGrantUse' => ['onGrantUse'] ]; } @@ -40,18 +40,21 @@ public function registerHook($hookName, $callable) { return $this; } - public function callHook($hookName,$DATA1,$DATA2 = null,$DATA3 = null) { + public function callHook($hookName,$arrData) { if (!in_array($hookName,array_keys($this->hooks))) { throw new \Exception("Hook name unkown"); } foreach($this->hooks[$hookName] as $a) { - $a($DATA1,$DATA2,$DATA3); + if (is_callable($a)) { + $a($arrData); + } + else { + throw new \Exception("Hook: " . $a . " is not callable"); + } } } } - - function onTicketCreate($DATA) { global $fromAddr; @@ -96,9 +99,12 @@ function onTicketDownload($DATA) } -function onTicketPurge($DATA, $auto) +function onTicketPurge($args) { global $fromAddr; + + $DATA = $args['ticket']; + $auto = $args['auto']; // log $reason = ($auto? "automatically": "manually"); @@ -117,9 +123,11 @@ function onTicketPurge($DATA, $auto) } -function onGrantCreate($DATA) +function onGrantCreate($args) { global $fromAddr; + + $DATA = $args['grant']; // log $type = (!$DATA["expire"]? "permanent": "temporary"); @@ -144,9 +152,12 @@ function onGrantUpdate($DATA) } -function onGrantPurge($DATA, $auto) +function onGrantPurge($args) { global $fromAddr; + + $DATA = $args['grant']; + $auto = $args['auto']; // log $reason = ($auto? "automatically": "manually"); @@ -164,9 +175,12 @@ function onGrantPurge($DATA, $auto) } -function onGrantUse($GRANT, $TICKET) +function onGrantUse($args) { global $fromAddr; + + $GRANT = $args['grant']; + $TICKET = $args['ticket']; // log logGrantEvent($GRANT, "genenerated ticket " . $TICKET['id'] diff --git a/htdocs/include/init.php b/htdocs/include/init.php index c44e883..4681fc2 100644 --- a/htdocs/include/init.php +++ b/htdocs/include/init.php @@ -22,9 +22,6 @@ if(@$ret === false) die("cannot initialize logging\n"); -// initialize the db -connectDB(); - // initial state $UPLOAD_ERRNO = UPLOAD_ERR_OK; diff --git a/htdocs/include/restpurgeticket.php b/htdocs/include/restpurgeticket.php index 6b55c8b..d3d20ba 100644 --- a/htdocs/include/restpurgeticket.php +++ b/htdocs/include/restpurgeticket.php @@ -4,15 +4,14 @@ function purgeticket($msg, $id = null) { - global $db, $auth; + global $auth; // check id validity if(empty($id) || !isTicketId($id)) return array('httpBadRequest', 'bad parameters'); // fetch the ticket id - $sql = "SELECT * FROM ticket WHERE id = " . $db->quote($id); - $DATA = $db->query($sql)->fetch(); + $DATA = DBConnection::getInstance()->getTicketById($id); if($DATA === false || isTicketExpired($DATA)) return array('httpNotFound', 'not found'); diff --git a/htdocs/include/sessauth.php b/htdocs/include/sessauth.php index f71b462..4b2a9c0 100644 --- a/htdocs/include/sessauth.php +++ b/htdocs/include/sessauth.php @@ -4,7 +4,7 @@ function authenticate() { - global $db, $authRealm, $style; + global $authRealm, $style; $rmt = ($authRealm != false); $extAuth = externalAuth(); diff --git a/htdocs/include/ticket.php b/htdocs/include/ticket.php index 292f969..fa6ba8c 100644 --- a/htdocs/include/ticket.php +++ b/htdocs/include/ticket.php @@ -11,8 +11,7 @@ } else { - $sql = "SELECT * FROM ticket WHERE id = " . $db->quote($id); - $DATA = $db->query($sql)->fetch(); + $DATA = DBConnection::getInstance()->getTicketById($id); } $ref = "$masterPath?t=$id"; diff --git a/htdocs/include/ticketfuncs.php b/htdocs/include/ticketfuncs.php index 1dd6d42..13a50be 100644 --- a/htdocs/include/ticketfuncs.php +++ b/htdocs/include/ticketfuncs.php @@ -5,9 +5,11 @@ function isTicketExpired($DATA, $now = NULL) { if(!isset($now)) $now = time(); - return (($DATA["expire"] && ($DATA["expire"] + $DATA["time"]) < $now) - || ($DATA["last_stamp"] && $DATA["last_time"] && ($DATA["last_stamp"] + $DATA["last_time"]) < $now) - || ($DATA["expire_dln"] && $DATA["expire_dln"] <= $DATA["downloads"])); + + $expire1 = (($DATA["expire"]<>0) && ($DATA["expire"] + $DATA["time"]) < $now); + $expire2 = ($DATA["last_stamp"]<>0) && ($DATA["last_time"]<>0) && (($DATA["last_stamp"] + $DATA["last_time"]) < $now); + $expire3 = ($DATA["expire_dln"]<>0) && ($DATA["expire_dln"] <= $DATA["downloads"]); + return $expire1 || $expire2 || $expire3; } @@ -108,25 +110,26 @@ function genTicket($upload, $params) // expiration values list($total, $lastdl, $maxdl) = ticketExpirationParams($params); - $success = DBConnection::getInstance()->getGenTicketQuery()->setParameter(0,$upload['id'])-> - setParameter(1,$auth['id'])-> - setParameter(2,$upload['name'])-> - setParameter(3,$upload['path'])-> - setParameter(4,$upload['size'])-> - setParameter(5,$params["comment"])-> - setParameter(6, (empty($params["pass"]) ? NULL : hashPassword($params["pass"])))-> - setParameter(7,$params["pass_send"])-> - setParameter(8,time())-> - setParameter(9,$total)-> - setParameter(10,$lastdl)-> - setParameter(11,$maxdl)-> - setParameter(12,(empty($params["notify"])? NULL : fixEMailAddrs($params["notify"])))-> - setParameter(13,(empty($params["send_to"])? NULL : fixEMailAddrs($params["send_to"])))-> - setParameter(14,$locale)->execute(); + $success = DBConnection::getInstance()->generateTicket($upload['id'], + $auth['id'], + $upload['name'], + $upload['path'], + $upload['size'], + $params["comment"], + (empty($params["pass"]) ? NULL : hashPassword($params["pass"])), + $params["pass_send"], + time(), + $total, + $lastdl, + $maxdl, + (empty($params["notify"])? NULL : fixEMailAddrs($params["notify"])), + (empty($params["send_to"])? NULL : fixEMailAddrs($params["send_to"])), + $locale); + $DATA = DBConnection::getInstance()->getTicketById($upload['id']); $DATA['pass'] = (empty($params["pass"])? NULL : $params["pass"]); - Hooks::getInstance()->callHook('onTicketCreate',$DATA); + Hooks::getInstance()->callHook('onTicketCreate',['ticket' => $DATA]); return $DATA; } diff --git a/htdocs/include/ticketl.php b/htdocs/include/ticketl.php index 93e7105..f15a506 100644 --- a/htdocs/include/ticketl.php +++ b/htdocs/include/ticketl.php @@ -16,8 +16,7 @@ foreach($sel as $id) { if(!isTicketId($id)) continue; - $sql = "SELECT * FROM ticket WHERE id = " . $db->quote($id); - $DATA = $db->query($sql)->fetch(); + $DATA = DBConnection::getInstance()->getTicketById($id); if($DATA === false) continue; // check for permissions @@ -35,12 +34,6 @@ // list active tickets $totalSize = 0; - -$sql = 'SELECT * FROM ticket t' - . ' WHERE user_id = ' . $auth["id"] - . ' AND from_grant IS NULL' - . ' ORDER BY time DESC'; - ?>
@@ -59,7 +52,7 @@ query($sql) as $DATA) +foreach(DBConnection::getInstance()->getActiveTicketsForUser($auth["id"]) as $DATA) { if(isTicketExpired($DATA)) continue; diff --git a/htdocs/include/ticketla.php b/htdocs/include/ticketla.php index b7e4764..d5bd23c 100644 --- a/htdocs/include/ticketla.php +++ b/htdocs/include/ticketla.php @@ -16,8 +16,7 @@ foreach($sel as $id) { if(!isTicketId($id)) continue; - $sql = "SELECT * FROM ticket WHERE id = " . $db->quote($id); - $DATA = $db->query($sql)->fetch(); + $DATA = DBConnection::getInstance()->getTicketById($id); if($DATA === false) continue; // actually purge the ticket @@ -32,10 +31,6 @@ // list active tickets $totalSize = 0; -$sql = 'SELECT t.*, u.name AS "user", t.from_grant FROM ticket t' - . ' LEFT JOIN "user" u ON u.id = t.user_id' - . ' ORDER BY time DESC'; - ?>
@@ -55,7 +50,7 @@ query($sql) as $DATA) +foreach(DBConnection::getInstance()->getAllActiveTickets() as $DATA) { if(isTicketExpired($DATA)) continue; diff --git a/htdocs/include/ticketlr.php b/htdocs/include/ticketlr.php index dd500c2..a60ca45 100644 --- a/htdocs/include/ticketlr.php +++ b/htdocs/include/ticketlr.php @@ -16,8 +16,8 @@ foreach($sel as $id) { if(!isTicketId($id)) continue; - $sql = "SELECT * FROM ticket WHERE id = " . $db->quote($id); - $DATA = $db->query($sql)->fetch(); + + $DATA = DBConnection::getInstance()->getTicketById($id); if($DATA === false) continue; // check for permissions @@ -35,13 +35,6 @@ // list active tickets $totalSize = 0; - -$sql = 'SELECT t.*, g.cmt AS grant_cmt FROM ticket t' - . ' LEFT JOIN "grant" g ON g.id = t.from_grant' - . ' WHERE t.user_id = ' . $auth["id"] - . ' AND t.from_grant IS NOT NULL' - . ' ORDER BY t.time DESC'; - ?>
@@ -61,7 +54,7 @@ query($sql) as $DATA) +foreach(DBConnection::getInstance()->getReceivedFilesForUser($auth['id']) as $DATA) { if(isTicketExpired($DATA)) continue; diff --git a/htdocs/include/ticketr.php b/htdocs/include/ticketr.php index 11d1620..792db20 100644 --- a/htdocs/include/ticketr.php +++ b/htdocs/include/ticketr.php @@ -18,8 +18,8 @@ } // try to fetch the id -$sql = "SELECT * FROM ticket WHERE id = " . $db->quote($id); -$DATA = $db->query($sql)->fetch(); +$DATA = DBConnection::getInstance()->getTicketById($id); + if($DATA === false || isTicketExpired($DATA)) { $category = ($DATA === false? 'unknown': 'expired'); @@ -54,10 +54,7 @@ $last = ($range[2] == $DATA["size"] - 1); // update the record for the next query -$now = time(); -$sql = "UPDATE ticket SET last_stamp = $now" - . " WHERE id = " . $db->quote($id); -$db->exec($sql); +DBConnection::getInstance()->updateTicketUsage($id,time(),0); // disable mod_deflate if(function_exists('apache_setenv')) @@ -94,7 +91,6 @@ if($last && !connection_aborted()) { ++$DATA["downloads"]; - reconnectDB(); // set default locale for notifications switchLocale($defLocale); @@ -108,10 +104,7 @@ else { // update download count - $now = time(); - $sql = "UPDATE ticket SET last_stamp = $now" - . ", downloads = downloads + 1 WHERE id = " . $db->quote($id); - $db->exec($sql); + DBConnection::getInstance()->updateTicketUsage($id,time(),1); } // kill the session ASAP diff --git a/htdocs/include/users.php b/htdocs/include/users.php index d0a0d11..bf32166 100644 --- a/htdocs/include/users.php +++ b/htdocs/include/users.php @@ -77,26 +77,6 @@ function htmlRole($name, $selected) return $ret; } -// list users -$sql = <<
@@ -114,7 +94,7 @@ function htmlRole($name, $selected) query($sql) as $DATA) +foreach(DBConnection::getInstance()->getAllUsersIncludingStats() as $DATA) { // selection echo "