From ffe8229d2661f60bd5a73d11434b966cc2673587 Mon Sep 17 00:00:00 2001 From: Sveneld Date: Sun, 25 Feb 2024 00:36:39 +0100 Subject: [PATCH 1/6] Database as new class with interface Add phpunit for test run Add github action for build project --- Dockerfile | 2 +- actions-sms.php | 82 ++++++++++++++------------- admin.php | 12 +++- agree.php | 10 +++- command.php | 14 +++-- common.php | 79 ++++++++++++++++---------- cron.php | 8 ++- db.class.php | 37 ------------ index.php | 10 +++- install/generate.php | 6 +- install/index.php | 36 ++++++++---- receive.php | 10 +++- scan.php | 12 ++-- src/Db/DbInterface.php | 50 ++++++++++++++++ src/Db/MysqliDb.php | 116 ++++++++++++++++++++++++++++++++++++++ tests/Db/MysqliDbTest.php | 87 ++++++++++++++++++++++++++++ 16 files changed, 430 insertions(+), 141 deletions(-) delete mode 100644 db.class.php create mode 100644 src/Db/DbInterface.php create mode 100644 src/Db/MysqliDb.php create mode 100644 tests/Db/MysqliDbTest.php diff --git a/Dockerfile b/Dockerfile index 11bd6fd8..d2e547ee 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ RUN sed -i '/security.debian.org/d' /etc/apt/sources.list \ RUN echo "deb http://archive.debian.org/debian/ stretch main" > /etc/apt/sources.list \ && echo "deb http://archive.debian.org/debian-security stretch/updates main" >> /etc/apt/sources.list -RUN apt-get update && apt-get install -y zlib1g-dev libicu-dev g++ wget git +RUN apt-get update && apt-get install -y zlib1g-dev libicu-dev g++ wget git zip RUN wget --no-check-certificate https://pecl.php.net/get/xdebug-2.5.5.tgz \ && pecl install --offline ./xdebug-2.5.5.tgz \ diff --git a/actions-sms.php b/actions-sms.php index 5f1e5726..66c954a5 100644 --- a/actions-sms.php +++ b/actions-sms.php @@ -1,4 +1,6 @@ conn->real_escape_string(trim($matches[1])); + else $userNote=$db->escape(trim($matches[1])); $result=$db->query("UPDATE bikes SET currentUser=NULL,currentStand=$standId WHERE bikeNum=$bikeNum"); if ($userNote) @@ -509,28 +511,30 @@ function freeBikes($number) function log_sms($sms_uuid, $sender, $receive_time, $sms_text, $ip) { - global $dbserver,$dbuser,$dbpassword,$dbname; - $localdb=new Database($dbserver,$dbuser,$dbpassword,$dbname); - $localdb->connect(); - $localdb->conn->autocommit(TRUE); - - $sms_uuid =$localdb->conn->real_escape_string($sms_uuid); - $sender =$localdb->conn->real_escape_string($sender); - $receive_time =$localdb->conn->real_escape_string($receive_time); - $sms_text =$localdb->conn->real_escape_string($sms_text); - $ip =$localdb->conn->real_escape_string($ip); - - $result =$localdb->query("SELECT sms_uuid FROM received WHERE sms_uuid='$sms_uuid'"); - if (DEBUG===FALSE AND $result->num_rows>=1) // sms already exists in DB, possible problem - { - notifyAdmins(_('Problem with SMS')." $sms_uuid!",1); - return FALSE; - } - else - { - $result =$localdb->query("INSERT INTO received SET sms_uuid='$sms_uuid',sender='$sender',receive_time='$receive_time',sms_text='$sms_text',ip='$ip'"); - } - + global $dbserver, $dbuser, $dbpassword, $dbname; + /** + * @var \Bikeshare\Db\DbInterface + */ + $localdb = new \Bikeshare\Db\MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); + $localdb->connect(); + + #TODO does it needed??? + $localdb->setAutocommit(true); + + $sms_uuid = $localdb->escape($sms_uuid); + $sender = $localdb->escape($sender); + $receive_time = $localdb->escape($receive_time); + $sms_text = $localdb->escape($sms_text); + $ip = $localdb->escape($ip); + + $result = $localdb->query("SELECT sms_uuid FROM received WHERE sms_uuid='$sms_uuid'"); + if (DEBUG === FALSE and $result->num_rows >= 1) { + // sms already exists in DB, possible problem + notifyAdmins(_('Problem with SMS') . " $sms_uuid!", 1); + return FALSE; + } else { + $result = $localdb->query("INSERT INTO received SET sms_uuid='$sms_uuid',sender='$sender',receive_time='$receive_time',sms_text='$sms_text',ip='$ip'"); + } } @@ -554,7 +558,7 @@ function delnote($number,$bikeNum,$message) } else { - sendSMS($number,_('Error in bike number / stand name specification:'.$db->conn->real_escape_string($bikeNum))); + sendSMS($number,_('Error in bike number / stand name specification:'.$db->escape($bikeNum))); return; } @@ -587,7 +591,7 @@ function delnote($number,$bikeNum,$message) $reportedBy=$row["userName"]; $matches=explode(" ",$message,3); - $userNote=$db->conn->real_escape_string(trim($matches[2])); + $userNote=$db->escape(trim($matches[2])); if($userNote=='') { @@ -595,7 +599,7 @@ function delnote($number,$bikeNum,$message) } $result=$db->query("UPDATE notes SET deleted=NOW() where bikeNum=$bikeNum and deleted is null and note like '%$userNote%'"); - $count = $db->conn->affected_rows; + $count = $db->getAffectedRows(); if($count == 0) { @@ -647,7 +651,7 @@ function untag($number,$standName,$message) $matches=explode(" ",$message,3); - $userNote=$db->conn->real_escape_string(trim($matches[2])); + $userNote=$db->escape(trim($matches[2])); if($userNote=='') { @@ -655,7 +659,7 @@ function untag($number,$standName,$message) } $result=$db->query("update notes join bikes on notes.bikeNum = bikes.bikeNum set deleted=now() where bikes.currentStand='$standId' and note like '%$userNote%' and deleted is null"); - $count = $db->conn->affected_rows; + $count = $db->getAffectedRows(); if($count == 0) { @@ -706,7 +710,7 @@ function delstandnote($number,$standName,$message) $matches=explode(" ",$message,3); - $userNote=$db->conn->real_escape_string(trim($matches[2])); + $userNote=$db->escape(trim($matches[2])); if($userNote=='') { @@ -714,7 +718,7 @@ function delstandnote($number,$standName,$message) } $result=$db->query("UPDATE notes SET deleted=NOW() where standId=$standId and deleted is null and note like '%$userNote%'"); - $count = $db->conn->affected_rows; + $count = $db->getAffectedRows(); if($count == 0) { @@ -765,7 +769,7 @@ function standNote($number,$standName,$message) $matches=explode(" ",$message,3); - $userNote=$db->conn->real_escape_string(trim($matches[2])); + $userNote=$db->escape(trim($matches[2])); if ($userNote=="") //deletemmm { @@ -781,7 +785,7 @@ function standNote($number,$standName,$message) else { $db->query("INSERT INTO notes SET standId='$standId',userId='$userId',note='$userNote'"); - $noteid=$db->conn->insert_id; + $noteid=$db->getLastInsertId(); sendSMS($number,_('Note for stand')." ".$standName." "._('saved')."."); notifyAdmins(_('Note #').$noteid.": "._("on stand")." ".$standName." "._('by')." ".$reportedBy." (".$number."):".$userNote); } @@ -813,7 +817,7 @@ function tag($number,$standName,$message) $matches=explode(" ",$message,3); - $userNote=$db->conn->real_escape_string(trim($matches[2])); + $userNote=$db->escape(trim($matches[2])); if ($userNote=="") //deletemmm { @@ -829,7 +833,7 @@ function tag($number,$standName,$message) else { $db->query("INSERT INTO notes (bikeNum,userId,note) SELECT bikeNum,'$userId','$userNote' FROM bikes where currentStand='$standId'"); - //$noteid=$db->conn->insert_id; + //$noteid=$db->getLastInsertId(); sendSMS($number,_('All bikes on stand')." ".$standName." "._('tagged')."."); notifyAdmins(_('All bikes on stand')." "."$standName".' '._('tagged by')." ".$reportedBy." (".$number.")". _("with note:").$userNote); } @@ -855,7 +859,7 @@ function note($number,$bikeNum,$message) } else { - sendSMS($number,_('Error in bike number / stand name specification:'.$db->conn->real_escape_string($bikeNum))); + sendSMS($number,_('Error in bike number / stand name specification:'.$db->escape($bikeNum))); return; } @@ -892,7 +896,7 @@ function note($number,$bikeNum,$message) else { $matches=explode(" ",$message,3); - $userNote=$db->conn->real_escape_string(trim($matches[2])); + $userNote=$db->escape(trim($matches[2])); } if ($userNote=="") @@ -911,7 +915,7 @@ function note($number,$bikeNum,$message) else { $db->query("INSERT INTO notes SET bikeNum='$bikeNum',userId='$userId',note='$userNote'"); - $noteid=$db->conn->insert_id; + $noteid=$db->getLastInsertId(); sendSMS($number,_('Note for bike')." ".$bikeNum." "._('saved')."."); notifyAdmins(_('Note #').$noteid.": b.".$bikeNum." (".$bikeStatus.") "._('by')." ".$reportedBy." (".$number."):".$userNote); } @@ -1028,8 +1032,8 @@ function add($number,$email,$phone,$message) sendSMS($number,_('Contact information is in incorrect format. Use:')." ADD king@earth.com 0901456789 Martin Luther King Jr."); return; } - $userName=$db->conn->real_escape_string(trim($matches[2])); - $email=$db->conn->real_escape_string(trim($matches[1])); + $userName=$db->escape(trim($matches[2])); + $email=$db->escape(trim($matches[1])); $result=$db->query("INSERT into users SET userName='$userName',number=$phone,mail='$email'"); diff --git a/admin.php b/admin.php index 821c15e3..1c781717 100644 --- a/admin.php +++ b/admin.php @@ -1,15 +1,21 @@ connect(); checksession(); if (isset($_COOKIE["loguserid"])) { - $userid = $db->conn->real_escape_string(trim($_COOKIE["loguserid"])); + $userid = $db->escape(trim($_COOKIE["loguserid"])); } else { $userid = 0; } diff --git a/agree.php b/agree.php index e22bdd4a..4e5d4329 100644 --- a/agree.php +++ b/agree.php @@ -1,9 +1,15 @@ connect(); ?> diff --git a/command.php b/command.php index 11e7c655..a74faea7 100644 --- a/command.php +++ b/command.php @@ -1,19 +1,25 @@ connect(); if (isset($_COOKIE["loguserid"])) { - $userid = $db->conn->real_escape_string(trim($_COOKIE["loguserid"])); + $userid = $db->escape(trim($_COOKIE["loguserid"])); } else { $userid = 0; } if (isset($_COOKIE["logsession"])) { - $session = $db->conn->real_escape_string(trim($_COOKIE["logsession"])); + $session = $db->escape(trim($_COOKIE["logsession"])); } else { $session = ''; } diff --git a/common.php b/common.php index 3031e7bb..d918d4f5 100644 --- a/common.php +++ b/common.php @@ -37,7 +37,7 @@ function error($message) { global $db; - $db->conn->rollback(); + $db->rollback(); exit($message); } @@ -73,14 +73,19 @@ function sendSMS($number,$text) function logSendsms($number, $text) { - global $dbserver,$dbuser,$dbpassword,$dbname; - $localdb=new Database($dbserver,$dbuser,$dbpassword,$dbname); - $localdb->connect(); - $localdb->conn->autocommit(TRUE); - $number = $localdb->conn->real_escape_string($number); - $text = $localdb->conn->real_escape_string($text); + global $dbserver, $dbuser, $dbpassword, $dbname; + /** + * @var \Bikeshare\Db\DbInterface + */ + $localdb = new \Bikeshare\Db\MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); + $localdb->connect(); - $result = $localdb->query("INSERT INTO sent SET number='$number',text='$text'"); + #TODO does it needed??? + $localdb->setAutocommit(true); + $number = $localdb->escape($number); + $text = $localdb->escape($text); + + $result = $localdb->query("INSERT INTO sent SET number='$number',text='$text'"); } @@ -165,8 +170,8 @@ function isloggedin() { global $db; if (isset($_COOKIE['loguserid']) and isset($_COOKIE['logsession'])) { - $userid = $db->conn->real_escape_string(trim($_COOKIE['loguserid'])); - $session = $db->conn->real_escape_string(trim($_COOKIE['logsession'])); + $userid = $db->escape(trim($_COOKIE['loguserid'])); + $session = $db->escape(trim($_COOKIE['logsession'])); $result = $db->query("SELECT sessionId FROM sessions WHERE userId='$userid' AND sessionId='$session' AND timeStamp>'" . time() . "'"); if ($result->num_rows == 1) { return 1; @@ -183,16 +188,16 @@ function checksession() $result = $db->query("DELETE FROM sessions WHERE timeStamp<='" . time() . "'"); if (isset($_COOKIE['loguserid']) and isset($_COOKIE['logsession'])) { - $userid = $db->conn->real_escape_string(trim($_COOKIE['loguserid'])); - $session = $db->conn->real_escape_string(trim($_COOKIE['logsession'])); + $userid = $db->escape(trim($_COOKIE['loguserid'])); + $session = $db->escape(trim($_COOKIE['logsession'])); $result = $db->query("SELECT sessionId FROM sessions WHERE userId='$userid' AND sessionId='$session' AND timeStamp>'" . time() . "'"); if ($result->num_rows == 1) { $timestamp = time() + 86400 * 14; $result = $db->query("UPDATE sessions SET timeStamp='$timestamp' WHERE userId='$userid' AND sessionId='$session'"); - $db->conn->commit(); + $db->commit(); } else { $result = $db->query("DELETE FROM sessions WHERE userId='$userid' OR sessionId='$session'"); - $db->conn->commit(); + $db->commit(); setcookie('loguserid', '', time() - 86400); setcookie('logsession', '', time() - 86400); header('HTTP/1.1 302 Found'); @@ -210,10 +215,15 @@ function checksession() function logrequest($userid) { - global $dbserver, $dbuser, $dbpassword, $dbname; - $localdb = new Database($dbserver, $dbuser, $dbpassword, $dbname); + global $dbserver,$dbuser,$dbpassword,$dbname; + /** + * @var \Bikeshare\Db\DbInterface + */ + $localdb = new \Bikeshare\Db\MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); $localdb->connect(); - $localdb->conn->autocommit(true); + + #TODO does it needed??? + $localdb->setAutocommit(true); $number = getphonenumber($userid); @@ -224,20 +234,29 @@ function logresult($userid, $text) { global $dbserver, $dbuser, $dbpassword, $dbname; - $localdb = new Database($dbserver, $dbuser, $dbpassword, $dbname); + /** + * @var \Bikeshare\Db\DbInterface + */ + $localdb = new \Bikeshare\Db\MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); $localdb->connect(); - $localdb->conn->autocommit(true); - $userid = $localdb->conn->real_escape_string($userid); - $logtext = ''; - if (is_array($text)) { - foreach ($text as $value) { - $logtext .= $value . '; '; - } - } else { - $logtext = $text; - } - $logtext = strip_tags($localdb->conn->real_escape_string($logtext)); + #TODO does it needed??? + $localdb->setAutocommit(true); + $userid = $localdb->escape($userid); + $logtext=""; + if (is_array($text)) + { + foreach ($text as $value) + { + $logtext.=$value."; "; + } + } + else + { + $logtext=$text; + } + + $logtext = strip_tags($localdb->escape($logtext)); $result = $localdb->query("INSERT INTO sent SET number='$userid',text='$logtext'"); } @@ -312,7 +331,7 @@ function sendConfirmationEmail($emailto) function confirmUser($userKey) { global $db, $limits; - $userKey = $db->conn->real_escape_string($userKey); + $userKey = $db->escape($userKey); $result = $db->query("SELECT userId FROM registration WHERE userKey='$userKey'"); if ($result->num_rows == 1) { diff --git a/cron.php b/cron.php index 5c4d482d..a83717c8 100644 --- a/cron.php +++ b/cron.php @@ -1,9 +1,13 @@ connect(); checklongrental(); diff --git a/db.class.php b/db.class.php deleted file mode 100644 index 8ec534f8..00000000 --- a/db.class.php +++ /dev/null @@ -1,37 +0,0 @@ -dbserver=$dbserver; - $this->dbuser=$dbuser; - $this->dbpassword=$dbpassword; - $this->dbname=$dbname; - } - - function connect() - { - $this->conn=new mysqli($this->dbserver,$this->dbuser,$this->dbpassword,$this->dbname); - $this->conn->set_charset("utf8"); - $this->conn->autocommit(FALSE); - if (!$this->conn OR $this->conn->connect_errno) error(_('DB connection error!')); - return $this->conn; - } - - function query($query) - { - $result=$this->conn->query($query); - if (!$result) error(_('DB error').' '.$this->conn->error.' '._('in').': '.$query); - return $result; - } - - function insertid() - { - return $this->conn->insert_id; - } - -} - -?> \ No newline at end of file diff --git a/index.php b/index.php index 28cac9f0..17e018df 100644 --- a/index.php +++ b/index.php @@ -1,11 +1,15 @@ connect(); ?> @@ -43,7 +47,7 @@ var mapzoom=; conn->real_escape_string(trim($_COOKIE["loguserid"])); + $userid = $db->escape(trim($_COOKIE["loguserid"])); } else { $userid = 0; } diff --git a/install/generate.php b/install/generate.php index 5623e4f2..c34049d9 100644 --- a/install/generate.php +++ b/install/generate.php @@ -6,9 +6,11 @@ } else { require "../config.php.example"; } -require "../db.class.php"; -$db=new Database($dbserver,$dbuser,$dbpassword,$dbname); +/** + * @var \Bikeshare\Db\DbInterface + */ +$db=new \Bikeshare\Db\MysqliDb($dbserver,$dbuser,$dbpassword,$dbname); $db->connect(); // create new PDF document diff --git a/install/index.php b/install/index.php index ee816828..6002f427 100644 --- a/install/index.php +++ b/install/index.php @@ -8,7 +8,6 @@ require_once '../vendor/autoload.php'; $configfilename = "../config.php.example"; require $configfilename; -require "../db.class.php"; function changeconfigvalue($configvar,$postvar) { @@ -205,7 +204,10 @@ function return_bytes($val) { else changeconfigvalue('countrycode',""); $newconfig=implode($configfile); file_put_contents($configfilename,$newconfig); -$db=new Database($_POST["dbserver"],$_POST["dbuser"],$_POST["dbpassword"],$_POST["dbname"]); +/** + * @var \Bikeshare\Db\DbInterface + */ +$db=new \Bikeshare\Db\MysqliDb($_POST["dbserver"],$_POST["dbuser"],$_POST["dbpassword"],$_POST["dbname"]); $db->connect(); $sql=file_get_contents("../docker-data/mysql/create-database.sql"); $sql=explode(";",$sql); @@ -233,16 +235,19 @@ function return_bytes($val) { connect(); $result=$db->query("REPLACE INTO users SET userName='".$_POST["username"]."',password=SHA2('".$_POST["password"]."',512),mail='".$_POST["email"]."',number='".$_POST["phone"]."',privileges=7"); -$userid=$db->conn->insert_id; +$userid=$db->getLastInsertId(); if (!$connectors["sms"]) { $result=$db->query("UPDATE users SET number='$userid' WHERE userId='$userid'"); } $result=$db->query("REPLACE INTO limits SET userId='$userid',userLimit='100'"); -$db->conn->commit(); +$db->commit(); ?>

',_('Admin user'),' ',$_POST["username"],' ',_('created with password:'),' ',$_POST["password"]; if (!$connectors["sms"]) { echo '. ',_('Use number'),' ',$userid,' ',_('for login'),'.'; } echo ''; ?> @@ -254,7 +259,10 @@ function return_bytes($val) { connect(); $stands=explode(",",$_POST["stands"]); foreach ($stands as $stand) @@ -267,7 +275,7 @@ function return_bytes($val) { $code=sprintf("%04d",rand(100,9900)); //do not create a code with more than one leading zero or more than two leading 9s (kind of unusual/unsafe). $result=$db->query("REPLACE INTO bikes SET bikeNum='".$i."',currentStand=1,currentCode='".$code."'"); } -$db->conn->commit(); +$db->commit(); ?>

connect(); ?>

Set system options

@@ -333,7 +344,7 @@ function return_bytes($val) { } if (isset($_POST["placename"][$standid])) $result=$db->query("UPDATE stands SET placeName='".$_POST["placename"][$standid]."' WHERE standId='$standid'"); } -$db->conn->commit(); +$db->commit(); echo ''; ?>
@@ -386,7 +397,10 @@ function return_bytes($val) {
connect(); $configfile=file($configfilename); foreach ($_POST as $variable=>$value) @@ -413,7 +427,7 @@ function return_bytes($val) { $row=$result->fetch_assoc(); $result=$db->query("REPLACE INTO credit SET userId='".$row["userId"]."',credit='$newcredit'"); } -$db->conn->commit(); +$db->commit(); ?>

Installation finished

diff --git a/receive.php b/receive.php index fde61b74..83addecd 100644 --- a/receive.php +++ b/receive.php @@ -4,9 +4,13 @@ require_once 'vendor/autoload.php'; require("config.php"); -require("db.class.php"); -$db=new Database($dbserver,$dbuser,$dbpassword,$dbname); + +/** + * @var \Bikeshare\Db\DbInterface + */ +$db=new \Bikeshare\Db\MysqliDb($dbserver,$dbuser,$dbpassword,$dbname); $db->connect(); + require("actions-sms.php"); /** @@ -112,7 +116,7 @@ } } -$db->conn->commit(); +$db->commit(); $sms->respond(); ?> \ No newline at end of file diff --git a/scan.php b/scan.php index 20f39192..f2a9de67 100644 --- a/scan.php +++ b/scan.php @@ -1,19 +1,23 @@ connect(); if (isset($_COOKIE["loguserid"])) { - $userid = $db->conn->real_escape_string(trim($_COOKIE["loguserid"])); + $userid = $db->escape(trim($_COOKIE["loguserid"])); } else { $userid = 0; } if (isset($_COOKIE["logsession"])) { - $session = $db->conn->real_escape_string(trim($_COOKIE["logsession"])); + $session = $db->escape(trim($_COOKIE["logsession"])); } else { $session = ''; } diff --git a/src/Db/DbInterface.php b/src/Db/DbInterface.php new file mode 100644 index 00000000..3bc01267 --- /dev/null +++ b/src/Db/DbInterface.php @@ -0,0 +1,50 @@ +dbserver = $dbserver; + $this->dbuser = $dbuser; + $this->dbpassword = $dbpassword; + $this->dbname = $dbname; + $this->throwException = $throwException; + } + + public function connect() + { + $this->conn = new \mysqli($this->dbserver, $this->dbuser, $this->dbpassword, $this->dbname); + if (!$this->conn || $this->conn->connect_errno) { + if ($this->throwException) { + throw new \RuntimeException('DB connection error!', !empty($this->conn->connect_errno ) ? $this->conn->connect_errno : 0); + } else { + die(_('DB connection error!')); + } + + } + $this->conn->set_charset("utf8"); + $this->conn->autocommit(FALSE); + } + + public function query($query, $params = array()) + { + $result = $this->conn->query($query); + if (!$result) { + $this->conn->rollback(); + if ($this->throwException) { + throw new \RuntimeException('DB error in : ' . $query); + } else { + die(_('DB error') . ' ' . $this->conn->error . ' ' . _('in') . ': ' . $query); + } + } + + return $result; + } + + /** + * @return int + */ + public function getAffectedRows() + { + return $this->conn->affected_rows; + } + + public function getLastInsertId() + { + return (int)$this->conn->insert_id; + } + + public function escape($string) + { + return $this->conn->real_escape_string($string); + } + + /** + * TODO does it needed??? + * @param bool $mode + * @return bool + */ + public function setAutocommit($mode = true) + { + return $this->conn->autocommit($mode); + } + + /** + * TODO does it needed??? + * @return bool + */ + public function commit() + { + return $this->conn->commit(); + } + + /** + * TODO does it needed??? + * @return bool + */ + public function rollback() + { + return $this->conn->rollback(); + } +} \ No newline at end of file diff --git a/tests/Db/MysqliDbTest.php b/tests/Db/MysqliDbTest.php new file mode 100644 index 00000000..182c1326 --- /dev/null +++ b/tests/Db/MysqliDbTest.php @@ -0,0 +1,87 @@ +createMock(\mysqli::class); + + $reflection = new \ReflectionClass($db); + $reflection_property = $reflection->getProperty('conn'); + $reflection_property->setAccessible(true); + $reflection_property->setValue($db, $mysqliMock); + + $this->db = $db; + $this->conn = $mysqliMock; + } + + public function testQuery() + { + $query = 'SELECT * FROM table'; + $result = $this->createMock(\mysqli_result::class); + $this->conn->expects($this->once()) + ->method('query') + ->with($query) + ->willReturn($result); + + $this->assertSame($result, $this->db->query($query)); + } + public function testQueryError() + { + $query = 'SELECT * FROM table'; + $result = $this->createMock(\mysqli_result::class); + $this->conn->expects($this->once()) + ->method('query') + ->with($query) + ->willReturn(false); + $this->conn->expects($this->once()) + ->method('rollback'); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('DB error in : ' . $query); + + $this->assertSame($result, $this->db->query($query)); + } + + public function testEscape() + { + $string = "string"; + $escapedString = "escapedString"; + $this->conn->expects($this->once()) + ->method('real_escape_string') + ->with($string) + ->willReturn($escapedString); + + $this->assertSame($escapedString, $this->db->escape($string)); + } + public function testSetAutocommit() + { + $this->conn->expects($this->once()) + ->method('autocommit') + ->with(false); + + $this->db->setAutocommit(false); + } + + public function testCommit() + { + $this->conn->expects($this->once()) + ->method('commit'); + + $this->db->commit(); + } + + public function testRollback() + { + $this->conn->expects($this->once()) + ->method('rollback'); + + $this->db->rollback(); + } +} \ No newline at end of file From 8497ba7ae6cca7c95a33518108ca1f7d7d6434b9 Mon Sep 17 00:00:00 2001 From: Sveneld Date: Sun, 25 Feb 2024 18:27:27 +0100 Subject: [PATCH 2/6] fix namespace --- actions-sms.php | 7 +++++-- admin.php | 5 +++-- agree.php | 5 +++-- command.php | 5 +++-- common.php | 14 +++++++------ cron.php | 7 +++++-- index.php | 5 +++-- install/generate.php | 7 +++++-- install/index.php | 23 ++++++++++++---------- receive.php | 6 ++++-- scan.php | 7 +++++-- src/Db/DbInterface.php | 2 +- src/Db/MysqliDb.php | 2 +- src/SmsConnector/SmsGatewayConnector.php | 2 +- tests/Db/MysqliDbTest.php | 4 ++-- tests/SmsConnector/SmsConnectorFactory.php | 2 +- 16 files changed, 63 insertions(+), 40 deletions(-) diff --git a/actions-sms.php b/actions-sms.php index 66c954a5..832c7464 100644 --- a/actions-sms.php +++ b/actions-sms.php @@ -1,5 +1,8 @@ connect(); #TODO does it needed??? diff --git a/admin.php b/admin.php index 1c781717..819726b7 100644 --- a/admin.php +++ b/admin.php @@ -1,13 +1,14 @@ connect(); diff --git a/agree.php b/agree.php index 4e5d4329..463f91cc 100644 --- a/agree.php +++ b/agree.php @@ -1,13 +1,14 @@ connect(); diff --git a/command.php b/command.php index a74faea7..0d954e4d 100644 --- a/command.php +++ b/command.php @@ -1,13 +1,14 @@ connect(); diff --git a/common.php b/common.php index d918d4f5..c0288143 100644 --- a/common.php +++ b/common.php @@ -3,6 +3,8 @@ use BikeShare\Mail\DebugMailSender; use BikeShare\Mail\MailSenderInterface; use BikeShare\Mail\PHPMailerMailSender; +use BikeShare\Db\DbInterface; +use BikeShare\Db\MysqliDb; use BikeShare\SmsConnector\SmsConnectorFactory; require_once 'vendor/autoload.php'; @@ -75,9 +77,9 @@ function logSendsms($number, $text) { global $dbserver, $dbuser, $dbpassword, $dbname; /** - * @var \Bikeshare\Db\DbInterface + * @var DbInterface */ - $localdb = new \Bikeshare\Db\MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); + $localdb = new MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); $localdb->connect(); #TODO does it needed??? @@ -217,9 +219,9 @@ function logrequest($userid) { global $dbserver,$dbuser,$dbpassword,$dbname; /** - * @var \Bikeshare\Db\DbInterface + * @var DbInterface */ - $localdb = new \Bikeshare\Db\MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); + $localdb = new MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); $localdb->connect(); #TODO does it needed??? @@ -235,9 +237,9 @@ function logresult($userid, $text) global $dbserver, $dbuser, $dbpassword, $dbname; /** - * @var \Bikeshare\Db\DbInterface + * @var DbInterface */ - $localdb = new \Bikeshare\Db\MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); + $localdb = new MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); $localdb->connect(); #TODO does it needed??? diff --git a/cron.php b/cron.php index a83717c8..e123fa7a 100644 --- a/cron.php +++ b/cron.php @@ -1,13 +1,16 @@ connect(); checklongrental(); diff --git a/index.php b/index.php index 17e018df..caae893b 100644 --- a/index.php +++ b/index.php @@ -1,13 +1,14 @@ connect(); diff --git a/install/generate.php b/install/generate.php index c34049d9..8ff5e624 100644 --- a/install/generate.php +++ b/install/generate.php @@ -1,5 +1,8 @@ connect(); // create new PDF document diff --git a/install/index.php b/install/index.php index 6002f427..e853737e 100644 --- a/install/index.php +++ b/install/index.php @@ -1,6 +1,9 @@ connect(); $sql=file_get_contents("../docker-data/mysql/create-database.sql"); $sql=explode(";",$sql); @@ -236,9 +239,9 @@ function return_bytes($val) { connect(); $result=$db->query("REPLACE INTO users SET userName='".$_POST["username"]."',password=SHA2('".$_POST["password"]."',512),mail='".$_POST["email"]."',number='".$_POST["phone"]."',privileges=7"); $userid=$db->getLastInsertId(); @@ -260,9 +263,9 @@ function return_bytes($val) { connect(); $stands=explode(",",$_POST["stands"]); foreach ($stands as $stand) @@ -326,9 +329,9 @@ function return_bytes($val) { connect(); ?>

Set system options

@@ -398,9 +401,9 @@ function return_bytes($val) { connect(); $configfile=file($configfilename); foreach ($_POST as $variable=>$value) diff --git a/receive.php b/receive.php index 83addecd..14830cb8 100644 --- a/receive.php +++ b/receive.php @@ -1,14 +1,16 @@ connect(); require("actions-sms.php"); diff --git a/scan.php b/scan.php index f2a9de67..489987ad 100644 --- a/scan.php +++ b/scan.php @@ -1,13 +1,16 @@ connect(); if (isset($_COOKIE["loguserid"])) { diff --git a/src/Db/DbInterface.php b/src/Db/DbInterface.php index 3bc01267..8ce314c9 100644 --- a/src/Db/DbInterface.php +++ b/src/Db/DbInterface.php @@ -1,6 +1,6 @@ Date: Wed, 28 Feb 2024 20:49:11 +0100 Subject: [PATCH 3/6] Database as new class with interface Add phpunit for test run Add github action for build project --- src/Db/DbInterface.php | 2 +- src/Db/MysqliDb.php | 10 ++++++---- tests/Db/MysqliDbTest.php | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/Db/DbInterface.php b/src/Db/DbInterface.php index 8ce314c9..292fba40 100644 --- a/src/Db/DbInterface.php +++ b/src/Db/DbInterface.php @@ -47,4 +47,4 @@ public function commit(); * @return bool */ public function rollback(); -} \ No newline at end of file +} diff --git a/src/Db/MysqliDb.php b/src/Db/MysqliDb.php index 3c11c9ff..2f9a5fb3 100644 --- a/src/Db/MysqliDb.php +++ b/src/Db/MysqliDb.php @@ -43,14 +43,16 @@ public function connect() $this->conn = new \mysqli($this->dbserver, $this->dbuser, $this->dbpassword, $this->dbname); if (!$this->conn || $this->conn->connect_errno) { if ($this->throwException) { - throw new \RuntimeException('DB connection error!', !empty($this->conn->connect_errno ) ? $this->conn->connect_errno : 0); + throw new \RuntimeException( + 'DB connection error!', + !empty($this->conn->connect_errno) ? $this->conn->connect_errno : 0 + ); } else { die(_('DB connection error!')); } - } $this->conn->set_charset("utf8"); - $this->conn->autocommit(FALSE); + $this->conn->autocommit(false); } public function query($query, $params = array()) @@ -113,4 +115,4 @@ public function rollback() { return $this->conn->rollback(); } -} \ No newline at end of file +} diff --git a/tests/Db/MysqliDbTest.php b/tests/Db/MysqliDbTest.php index 295d8664..1fb8d43a 100644 --- a/tests/Db/MysqliDbTest.php +++ b/tests/Db/MysqliDbTest.php @@ -84,4 +84,4 @@ public function testRollback() $this->db->rollback(); } -} \ No newline at end of file +} From 7113bb68188d345ebc8fc30d0b49d4d495234e22 Mon Sep 17 00:00:00 2001 From: Sveneld Date: Wed, 28 Feb 2024 21:16:50 +0100 Subject: [PATCH 4/6] new DbInterface usage --- actions-qrcode.php | 4 ++-- actions-web.php | 48 +++++++++++++++++++++++----------------------- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/actions-qrcode.php b/actions-qrcode.php index bffbf97d..9d4bb4f0 100644 --- a/actions-qrcode.php +++ b/actions-qrcode.php @@ -8,13 +8,13 @@ function response($message,$error=0,$log=1) { if (isset($_COOKIE["loguserid"])) { - $userid=$db->conn->real_escape_string(trim($_COOKIE["loguserid"])); + $userid=$db->escape(trim($_COOKIE["loguserid"])); } else $userid=0; $number=getphonenumber($userid); logresult($number,$message); } - $db->conn->commit(); + $db->commit(); echo '',$systemname,''; echo ''; echo ''; diff --git a/actions-web.php b/actions-web.php index 652a5a65..71e62e98 100644 --- a/actions-web.php +++ b/actions-web.php @@ -13,7 +13,7 @@ function response($message, $error = 0, $additional = '', $log = 1) $json = json_encode($json); if ($log == 1 and $message) { if (isset($_COOKIE['loguserid'])) { - $userid = $db->conn->real_escape_string(trim($_COOKIE['loguserid'])); + $userid = $db->escape(trim($_COOKIE['loguserid'])); } else { $userid = 0; } @@ -21,7 +21,7 @@ function response($message, $error = 0, $additional = '', $log = 1) $number = getphonenumber($userid); logresult($number, $message); } - $db->conn->commit(); + $db->commit(); echo $json; exit; } @@ -204,7 +204,7 @@ function where($userId, $bike) function addnote($userId, $bikeNum, $message) { global $db; - $userNote = $db->conn->real_escape_string(trim($message)); + $userNote = $db->escape(trim($message)); $result = $db->query("SELECT userName,number from users where userId='$userId'"); $row = $result->fetch_assoc(); @@ -219,7 +219,7 @@ function addnote($userId, $bikeNum, $message) $bikeStatus = _('used by') . ' ' . $userName . ' +' . $phone; } $db->query("INSERT INTO notes SET bikeNum='$bikeNum',userId='$userId',note='$userNote'"); - $noteid = $db->conn->insert_id; + $noteid = $db->getLastInsertId(); notifyAdmins(_('Note #') . $noteid . ': b.' . $bikeNum . ' (' . $bikeStatus . ') ' . _('by') . ' ' . $userName . '/' . $phone . ':' . $userNote); } @@ -228,7 +228,7 @@ function listbikes($stand) global $db, $forcestack; $stacktopbike = false; - $stand = $db->conn->real_escape_string($stand); + $stand = $db->escape($stand); if ($forcestack) { $result = $db->query("SELECT standId FROM stands WHERE standName='$stand'"); $row = $result->fetch_assoc(); @@ -437,14 +437,14 @@ function register($number, $code, $checkcode, $fullname, $email, $password, $pas { global $db, $dbpassword, $countrycode, $systemURL; - $number = $db->conn->real_escape_string(trim($number)); - $code = $db->conn->real_escape_string(trim($code)); - $checkcode = $db->conn->real_escape_string(trim($checkcode)); - $fullname = $db->conn->real_escape_string(trim($fullname)); - $email = $db->conn->real_escape_string(trim($email)); - $password = $db->conn->real_escape_string(trim($password)); - $password2 = $db->conn->real_escape_string(trim($password2)); - $existing = $db->conn->real_escape_string(trim($existing)); + $number = $db->escape(trim($number)); + $code = $db->escape(trim($code)); + $checkcode = $db->escape(trim($checkcode)); + $fullname = $db->escape(trim($fullname)); + $email = $db->escape(trim($email)); + $password = $db->escape(trim($password)); + $password2 = $db->escape(trim($password2)); + $existing = $db->escape(trim($existing)); $parametercheck = $number . ';' . str_replace(' ', '', $code) . ';' . $checkcode; if ($password != $password2) { response(_('Password do not match. Please correct and try again.'), ERROR); @@ -454,7 +454,7 @@ function register($number, $code, $checkcode, $fullname, $email, $password, $pas if ($result->num_rows == 1) { if (!$existing) { // new user registration $result = $db->query("INSERT INTO users SET userName='$fullname',password=SHA2('$password',512),mail='$email',number='$number',privileges=0"); - $userId = $db->conn->insert_id; + $userId = $db->getLastInsertId(); sendConfirmationEmail($email); response(_('You have been successfully registered. Please, check your email and read the instructions to finish your registration.')); } else { // existing user, password change @@ -469,7 +469,7 @@ function register($number, $code, $checkcode, $fullname, $email, $password, $pas } } else { // SMS system disabled $result = $db->query("INSERT INTO users SET userName='$fullname',password=SHA2('$password',512),mail='$email',number='',privileges=0"); - $userId = $db->conn->insert_id; + $userId = $db->getLastInsertId(); $result = $db->query("UPDATE users SET number='$userId' WHERE userId='$userId'"); sendConfirmationEmail($email); response(_('You have been successfully registered. Please, check your email and read the instructions to finish your registration. Your number for login is:') . ' ' . $userId); @@ -480,8 +480,8 @@ function login($number, $password) { global $db, $systemURL, $countrycode; - $number = $db->conn->real_escape_string(trim($number)); - $password = $db->conn->real_escape_string(trim($password)); + $number = $db->escape(trim($number)); + $password = $db->escape(trim($password)); $number = str_replace(' ', '', $number); $number = str_replace('-', '', $number); $number = str_replace('/', '', $number); @@ -497,7 +497,7 @@ function login($number, $password) $timeStamp = time() + 86400 * 14; // 14 days to keep user logged in $result = $db->query("DELETE FROM sessions WHERE userId='$userId'"); $result = $db->query("INSERT INTO sessions SET userId='$userId',sessionId='$sessionId',timeStamp='$timeStamp'"); - $db->conn->commit(); + $db->commit(); setcookie('loguserid', $userId, time() + 86400 * 14); setcookie('logsession', $sessionId, time() + 86400 * 14); header('HTTP/1.1 302 Found'); @@ -516,10 +516,10 @@ function logout() { global $db, $systemURL; if (isset($_COOKIE['loguserid']) and isset($_COOKIE['logsession'])) { - $userid = $db->conn->real_escape_string(trim($_COOKIE['loguserid'])); - $session = $db->conn->real_escape_string(trim($_COOKIE['logsession'])); + $userid = $db->escape(trim($_COOKIE['loguserid'])); + $session = $db->escape(trim($_COOKIE['logsession'])); $result = $db->query("DELETE FROM sessions WHERE userId='$userid'"); - $db->conn->commit(); + $db->commit(); } header('HTTP/1.1 302 Found'); header('Location: ' . $systemURL); @@ -543,7 +543,7 @@ function smscode($number) srand(); $number = normalizephonenumber($number); - $number = $db->conn->real_escape_string($number); + $number = $db->escape($number); $userexists = 0; $result = $db->query("SELECT userId FROM users WHERE number='$number'"); if ($result->num_rows) { @@ -559,7 +559,7 @@ function smscode($number) $text = _('Enter this code to change password:') . ' ' . $smscode; } - $text = $db->conn->real_escape_string($text); + $text = $db->escape($text); if (!issmssystemenabled()) { $result = $db->query("INSERT INTO sent SET number='$number',text='$text'"); @@ -742,7 +742,7 @@ function resetpassword($number) { global $db, $mailer, $systemname, $systemrules, $systemURL; - $number = $db->conn->real_escape_string(trim($number)); + $number = $db->escape(trim($number)); $result = $db->query("SELECT mail,userName FROM users WHERE number='$number'"); if (!$result->num_rows) { From 9fb249b8a241843b8d2633030f5b5178c5ff0bb6 Mon Sep 17 00:00:00 2001 From: Sveneld Date: Wed, 28 Feb 2024 22:21:18 +0100 Subject: [PATCH 5/6] Add SmsSenderInterface Small fixes --- actions-sms.php | 178 +++++++++++----------- actions-web.php | 8 +- admin.php | 2 +- agree.php | 2 +- command.php | 2 +- common.php | 74 +++------ config.php.example | 5 + cron.php | 2 +- docker-data/mysql/create-database.sql | 1 + index.php | 2 +- install/generate.php | 2 +- install/index.php | 10 +- receive.php | 4 +- scan.php | 2 +- src/Sms/SmsSender.php | 49 ++++++ src/Sms/SmsSenderInterface.php | 8 + src/SmsConnector/DebugConnector.php | 18 +++ tests/Sms/SmsSenderTest.php | 69 +++++++++ tests/SmsConnector/DebugConnectorTest.php | 16 ++ 19 files changed, 295 insertions(+), 159 deletions(-) create mode 100644 src/Sms/SmsSender.php create mode 100644 src/Sms/SmsSenderInterface.php create mode 100644 src/SmsConnector/DebugConnector.php create mode 100644 tests/Sms/SmsSenderTest.php create mode 100644 tests/SmsConnector/DebugConnectorTest.php diff --git a/actions-sms.php b/actions-sms.php index 832c7464..64126871 100644 --- a/actions-sms.php +++ b/actions-sms.php @@ -8,7 +8,7 @@ function help($number) { - global $db; + global $db, $smsSender; $userid=getUser($number); $privileges=getprivileges($userid); if ($privileges>0) @@ -16,21 +16,21 @@ function help($number) $message="Commands:\nHELP\n"; if (iscreditenabled()) $message.="CREDIT\n"; $message.="FREE\nRENT bikenumber\nRETURN bikeno stand\nWHERE bikeno\nINFO stand\nNOTE bikeno problem\n---\nFORCERENT bikenumber\nFORCERETURN bikeno stand\nLIST stand\nLAST bikeno\nREVERT bikeno\nADD email phone fullname\nDELNOTE bikeno [pattern]\nTAG stand note for all bikes\nUNTAG stand [pattern]"; - sendSMS($number,$message); + $smsSender->send($number,$message); } else { $message="Commands:\nHELP\n"; if (iscreditenabled()) $message.="CREDIT\n"; $message.="FREE\nRENT bikeno\nRETURN bikeno stand\nWHERE bikeno\nINFO stand\nNOTE bikeno problem description\nNOTE stand problem description"; - sendSMS($number,$message); + $smsSender->send($number,$message); } } function unknownCommand($number,$command) { - global $db; - sendSMS($number,_('Error. The command')." ".$command." "._('does not exist. If you need help, send:')." HELP"); + global $smsSender; + $smsSender->send($number,_('Error. The command')." ".$command." "._('does not exist. If you need help, send:')." HELP"); } /** @@ -51,18 +51,18 @@ function validateNumber($number) function info($number,$stand) { - global $db; + global $db, $smsSender; $stand = strtoupper($stand); if (!preg_match("/^[A-Z]+[0-9]*$/",$stand)) { - sendSMS($number,_('Stand name')." '".$stand."' "._('has not been recognized. Stands are marked by CAPITALLETTERS.')); + $smsSender->send($number,_('Stand name')." '".$stand."' "._('has not been recognized. Stands are marked by CAPITALLETTERS.')); return; } $result=$db->query("SELECT standId FROM stands where standName='$stand'"); if ($result->num_rows!=1) { - sendSMS($number,_('Stand')." '$stand' "._('does not exist.')); + $smsSender->send($number,_('Stand')." '$stand' "._('does not exist.')); return; } $row =$result->fetch_assoc(); @@ -76,7 +76,7 @@ function info($number,$stand) $message=$stand." - ".$standDescription; if ($standLong AND $standLat) $message.=", GPS: ".$standLat.",".$standLong; if ($standPhoto) $message.=", ".$standPhoto; - sendSMS($number,$message); + $smsSender->send($number,$message); } @@ -88,10 +88,10 @@ function info($number,$stand) **/ function validateReceivedSMS($number,$receivedargumentno,$requiredargumentno,$errormessage) { - global $db, $sms; + global $db, $sms, $smsSender; if ($receivedargumentno<$requiredargumentno) { - sendSMS($number,_('Error. More arguments needed, use command')." ".$errormessage); + $smsSender->send($number,_('Error. More arguments needed, use command')." ".$errormessage); $sms->respond(); exit; } @@ -101,16 +101,16 @@ function validateReceivedSMS($number,$receivedargumentno,$requiredargumentno,$er function credit($number) { - global $db; + global $db, $smsSender; $userid=getUser($number); $usercredit=getusercredit($userid).getcreditcurrency(); - sendSMS($number,_('Your remaining credit:')." ".$usercredit); + $smsSender->send($number,_('Your remaining credit:')." ".$usercredit); } function rent($number,$bike,$force=FALSE) { - global $db,$forcestack,$watches,$credit; + global $db,$forcestack,$watches,$credit, $smsSender; $stacktopbike=FALSE; $userId = getUser($number); $bikeNum = intval($bike); @@ -123,7 +123,7 @@ function rent($number,$bike,$force=FALSE) { $result=$db->query("SELECT credit FROM credit WHERE userId=$userId"); $row=$result->fetch_assoc(); - sendSMS($number,_('Please, recharge your credit:')." ".$row["credit"].$credit["currency"].". "._('Credit required:')." ".$requiredcredit.$credit["currency"]."."); + $smsSender->send($number,_('Please, recharge your credit:')." ".$row["credit"].$credit["currency"].". "._('Credit required:')." ".$requiredcredit.$credit["currency"]."."); return; } @@ -141,15 +141,15 @@ function rent($number,$bike,$force=FALSE) { if ($limit==0) { - sendSMS($number,_('You can not rent any bikes. Contact the admins to lift the ban.')); + $smsSender->send($number,_('You can not rent any bikes. Contact the admins to lift the ban.')); } elseif ($limit==1) { - sendSMS($number,_('You can only rent')." ".sprintf(ngettext('%d bike','%d bikes',$limit),$limit)." "._('at once')."."); + $smsSender->send($number,_('You can only rent')." ".sprintf(ngettext('%d bike','%d bikes',$limit),$limit)." "._('at once')."."); } else { - sendSMS($number,_('You can only rent')." ".sprintf(ngettext('%d bike','%d bikes',$limit),$limit)." "._('at once')." "._('and you have already rented')." ".$limit."."); + $smsSender->send($number,_('You can only rent')." ".sprintf(ngettext('%d bike','%d bikes',$limit),$limit)." "._('at once')." "._('and you have already rented')." ".$limit."."); } return; @@ -169,7 +169,7 @@ function rent($number,$bike,$force=FALSE) if ( $serviceTag <> 0 ) { - sendSMS($number,"Renting from service stands is not allowed: The bike probably waits for a repair."); + $smsSender->send($number,"Renting from service stands is not allowed: The bike probably waits for a repair."); return; } @@ -192,7 +192,7 @@ function rent($number,$bike,$force=FALSE) $result=$db->query("SELECT currentUser,currentCode FROM bikes WHERE bikeNum=$bikeNum"); if($result->num_rows!=1) { - sendSMS($number,"Bike $bikeNum does not exist."); + $smsSender->send($number,"Bike $bikeNum does not exist."); return; } $row =$result->fetch_assoc(); @@ -215,12 +215,12 @@ function rent($number,$bike,$force=FALSE) { if ($currentUser==$userId) { - sendSMS($number,_('You have already rented the bike')." ".$bikeNum.". "._('Code is')." ".$currentCode.". "._('Return bike with command:')." RETURN "._('bikenumber')." "._('standname')."."); + $smsSender->send($number,_('You have already rented the bike')." ".$bikeNum.". "._('Code is')." ".$currentCode.". "._('Return bike with command:')." RETURN "._('bikenumber')." "._('standname')."."); return; } if ($currentUser!=0) { - sendSMS($number,_('Bike')." ".$bikeNum." "._('is already rented')."."); + $smsSender->send($number,_('Bike')." ".$bikeNum." "._('is already rented')."."); return; } } @@ -230,7 +230,7 @@ function rent($number,$bike,$force=FALSE) { $message.="("._('bike note').":".$note.")"; } - sendSMS($number,$message); + $smsSender->send($number,$message); $result=$db->query("UPDATE bikes SET currentUser=$userId,currentCode=$newCode,currentStand=NULL WHERE bikeNum=$bikeNum"); @@ -241,7 +241,7 @@ function rent($number,$bike,$force=FALSE) else { $result=$db->query("INSERT INTO history SET userId=$userId,bikeNum=$bikeNum,action='FORCERENT',parameter=$newCode"); - if ($currentUser) { sendSMS($number,_('System override').": "._('Your rented bike')." ".$bikeNum." "._('has been rented by admin')."."); } + if ($currentUser) { $smsSender->send($number,_('System override').": "._('Your rented bike')." ".$bikeNum." "._('has been rented by admin')."."); } } @@ -250,7 +250,7 @@ function rent($number,$bike,$force=FALSE) function returnBike($number,$bike,$stand,$message="",$force=FALSE) { - global $db; + global $db, $smsSender; $userId = getUser($number); $bikeNum = intval($bike); $stand = strtoupper($stand); @@ -258,7 +258,7 @@ function returnBike($number,$bike,$stand,$message="",$force=FALSE) $result=$db->query("SELECT standId FROM stands WHERE standName='$stand'"); if (!$result->num_rows) { - sendSMS($number,_('Stand name')." '".$stand."' "._('does not exist. Stands are marked by CAPITALLETTERS.')); + $smsSender->send($number,_('Stand name')." '".$stand."' "._('does not exist. Stands are marked by CAPITALLETTERS.')); return; } $row=$result->fetch_assoc(); @@ -271,7 +271,7 @@ function returnBike($number,$bike,$stand,$message="",$force=FALSE) if ($bikenumber==0) { - sendSMS($number,_('You have no rented bikes currently.')); + $smsSender->send($number,_('You have no rented bikes currently.')); return; } @@ -288,7 +288,7 @@ function returnBike($number,$bike,$stand,$message="",$force=FALSE) $result=$db->query("SELECT currentCode FROM bikes WHERE currentUser=$userId AND bikeNum=$bikeNum"); if ($result->num_rows!=1) { - sendSMS($number,_('You does not have bike')." ".$bikeNum." rented. "._('You have rented the following')." ".sprintf(ngettext('%d bike','%d bikes',$bikenumber),$bikenumber).": $listBikes"); + $smsSender->send($number,_('You does not have bike')." ".$bikeNum." rented. "._('You have rented the following')." ".sprintf(ngettext('%d bike','%d bikes',$bikenumber),$bikenumber).": $listBikes"); return; } @@ -303,7 +303,7 @@ function returnBike($number,$bike,$stand,$message="",$force=FALSE) $result=$db->query("SELECT currentCode,currentUser FROM bikes WHERE bikeNum=$bikeNum"); if ($result->num_rows!=1) { - sendSMS($number,_('Bike')." ".$bikeNum." "._('is not rented. Saint Thomas, the patronus of all unrented bikes, prohibited returning unrented bikes.')); + $smsSender->send($number,_('Bike')." ".$bikeNum." "._('is not rented. Saint Thomas, the patronus of all unrented bikes, prohibited returning unrented bikes.')); return; } @@ -369,7 +369,7 @@ function returnBike($number,$bike,$stand,$message="",$force=FALSE) $result=$db->query("INSERT INTO history SET userId=$userId,bikeNum=$bikeNum,action='FORCERETURN',parameter=$standId"); /*if($currentUserNumber) { - sendSMS($currentUserNumber,_('System override').": "._('Your rented bike')." ".$bikeNum." "._('has been returned by admin')."."); + $smsSender->send($currentUserNumber,_('System override').": "._('Your rented bike')." ".$bikeNum." "._('has been returned by admin')."."); }*/ } @@ -379,7 +379,7 @@ function returnBike($number,$bike,$stand,$message="",$force=FALSE) if ($creditchange) $message.=" (-".$creditchange.")"; $message.="."; } - sendSMS($number,$message); + $smsSender->send($number,$message); } @@ -387,14 +387,14 @@ function returnBike($number,$bike,$stand,$message="",$force=FALSE) function where($number,$bike) { - global $db; + global $db, $smsSender; $userId = getUser($number); $bikeNum = intval($bike); $result=$db->query("SELECT number,userName,stands.standName FROM bikes LEFT JOIN users on bikes.currentUser=users.userID LEFT JOIN stands on bikes.currentStand=stands.standId where bikeNum=$bikeNum"); if ($result->num_rows!=1) { - sendSMS($number,_('Bike')." ".$bikeNum." "._('does not exist')."."); + $smsSender->send($number,_('Bike')." ".$bikeNum." "._('does not exist')."."); return; } $row =$result->fetch_assoc(); @@ -411,11 +411,11 @@ function where($number,$bike) if ($standName!=NULL) { - sendSMS($number,_('Bike')." ".$bikeNum." "._('is at stand')." ".$standName.$note); + $smsSender->send($number,_('Bike')." ".$bikeNum." "._('is at stand')." ".$standName.$note); } else { - sendSMS($number,_('Bike')." ".$bikeNum." "._('is rented by')." ".$userName." (+".$phone.").".$note); + $smsSender->send($number,_('Bike')." ".$bikeNum." "._('is rented by')." ".$userName." (+".$phone.").".$note); } } @@ -424,21 +424,21 @@ function where($number,$bike) function listBikes($number,$stand) { - global $db,$forcestack; + global $db,$forcestack, $smsSender; $stacktopbike=FALSE; $userId = getUser($number); $stand = strtoupper($stand); if (!preg_match("/^[A-Z]+[0-9]*$/",$stand)) { - sendSMS($number,_('Stand name')." '$stand' "._('has not been recognized. Stands are marked by CAPITALLETTERS.')); + $smsSender->send($number,_('Stand name')." '$stand' "._('has not been recognized. Stands are marked by CAPITALLETTERS.')); return; } $result=$db->query("SELECT standId FROM stands WHERE standName='$stand'"); if ($result->num_rows!=1) { - sendSMS($number,_('Stand')." '$stand' "._('does not exist')."."); + $smsSender->send($number,_('Stand')." '$stand' "._('does not exist')."."); return; } $row=$result->fetch_assoc(); @@ -454,7 +454,7 @@ function listBikes($number,$stand) if ($rentedBikes==0) { - sendSMS($number,_('Stand')." ".$stand." "._('is empty')."."); + $smsSender->send($number,_('Stand')." ".$stand." "._('is empty')."."); return; } @@ -467,14 +467,14 @@ function listBikes($number,$stand) } if ($rentedBikes>1) $listBikes=substr($listBikes,0,strlen($listBikes)-1); - sendSMS($number,sprintf(ngettext('%d bike','%d bikes',$rentedBikes),$rentedBikes)." "._('on stand')." ".$stand.": ".$listBikes); + $smsSender->send($number,sprintf(ngettext('%d bike','%d bikes',$rentedBikes),$rentedBikes)." "._('on stand')." ".$stand.": ".$listBikes); } function freeBikes($number) { - global $db; + global $db, $smsSender; $userId = getUser($number); $result=$db->query("SELECT count(bikeNum) as bikeCount,placeName from bikes join stands on bikes.currentStand=stands.standId where stands.serviceTag=0 group by placeName having bikeCount>0 order by placeName"); @@ -509,7 +509,7 @@ function freeBikes($number) } if ($rentedBikes>1) $listBikes=substr($listBikes,0,strlen($listBikes)-1); - sendSMS($number,$listBikes); + $smsSender->send($number,$listBikes); } function log_sms($sms_uuid, $sender, $receive_time, $sms_text, $ip) @@ -545,7 +545,7 @@ function log_sms($sms_uuid, $sender, $receive_time, $sms_text, $ip) function delnote($number,$bikeNum,$message) { - global $db; + global $db, $smsSender; $userId = getUser($number); $bikeNum=trim($bikeNum); @@ -561,7 +561,7 @@ function delnote($number,$bikeNum,$message) } else { - sendSMS($number,_('Error in bike number / stand name specification:'.$db->escape($bikeNum))); + $smsSender->send($number,_('Error in bike number / stand name specification:'.$db->escape($bikeNum))); return; } @@ -572,7 +572,7 @@ function delnote($number,$bikeNum,$message) $result=$db->query("SELECT number,userName,stands.standName FROM bikes LEFT JOIN users on bikes.currentUser=users.userID LEFT JOIN stands ON bikes.currentStand=stands.standId WHERE bikeNum=$bikeNum"); if ($result->num_rows!=1) { - sendSMS($number,_('Bike')." ".$bikeNum." "._('does not exist')."."); + $smsSender->send($number,_('Bike')." ".$bikeNum." "._('does not exist')."."); return; } $row =$result->fetch_assoc(); @@ -608,17 +608,17 @@ function delnote($number,$bikeNum,$message) { if($userNote=="%") { - sendSMS($number,_('No notes found for bike')." ".$bikeNum." "._('to delete')."."); + $smsSender->send($number,_('No notes found for bike')." ".$bikeNum." "._('to delete')."."); } else { - sendSMS($number,_('No notes matching pattern')." '".$userNote."' "._('found for bike')." ".$bikeNum." "._('to delete')."."); + $smsSender->send($number,_('No notes matching pattern')." '".$userNote."' "._('found for bike')." ".$bikeNum." "._('to delete')."."); } } else { //only admins can delete and those will receive the confirmation in the next step. - //sendSMS($number,"Note for bike $bikeNum deleted."); + //$smsSender->send($number,"Note for bike $bikeNum deleted."); if($userNote=="%") { notifyAdmins(_('All')." ".sprintf(ngettext('%d note','%d notes',$count),$count)." "._('for bike')." ".$bikeNum." "._('deleted by')." ".$reportedBy."."); @@ -634,14 +634,14 @@ function delnote($number,$bikeNum,$message) function untag($number,$standName,$message) { - global $db; + global $db, $smsSender; $userId = getUser($number); checkUserPrivileges($number); $result=$db->query("SELECT standId FROM stands where standName='$standName'"); if ($result->num_rows!=1) { - sendSMS($number,_("Stand")." ".$standName._("does not exist")."."); + $smsSender->send($number,_("Stand")." ".$standName._("does not exist")."."); return; } @@ -668,17 +668,17 @@ function untag($number,$standName,$message) { if($userNote=="%") { - sendSMS($number,_('No bikes with notes found for stand')." ".$standName." "._('to delete')."."); + $smsSender->send($number,_('No bikes with notes found for stand')." ".$standName." "._('to delete')."."); } else { - sendSMS($number,_('No notes matching pattern')." '".$userNote."' "._('found for bikes on stand')." ".$standName." "._('to delete')."."); + $smsSender->send($number,_('No notes matching pattern')." '".$userNote."' "._('found for bikes on stand')." ".$standName." "._('to delete')."."); } } else { //only admins can delete and those will receive the confirmation in the next step. - //sendSMS($number,"Note for bike $bikeNum deleted."); + //$smsSender->send($number,"Note for bike $bikeNum deleted."); if($userNote=="%") { notifyAdmins(_('All')." ".sprintf(ngettext('%d note','%d notes',$count),$count)." "._('for bikes on stand')." ".$standName." "._('deleted by')." ".$reportedBy."."); @@ -693,14 +693,14 @@ function untag($number,$standName,$message) function delstandnote($number,$standName,$message) { - global $db; + global $db, $smsSender; $userId = getUser($number); checkUserPrivileges($number); $result=$db->query("SELECT standId FROM stands where standName='$standName'"); if ($result->num_rows!=1) { - sendSMS($number,_("Stand")." ".$standName._("does not exist")."."); + $smsSender->send($number,_("Stand")." ".$standName._("does not exist")."."); return; } @@ -727,17 +727,17 @@ function delstandnote($number,$standName,$message) { if($userNote=="%") { - sendSMS($number,_('No notes found for stand')." ".$standName." "._('to delete')."."); + $smsSender->send($number,_('No notes found for stand')." ".$standName." "._('to delete')."."); } else { - sendSMS($number,_('No notes matching pattern')." '".$userNote."' "._('found on stand')." ".$standName." "._('to delete')."."); + $smsSender->send($number,_('No notes matching pattern')." '".$userNote."' "._('found on stand')." ".$standName." "._('to delete')."."); } } else { //only admins can delete and those will receive the confirmation in the next step. - //sendSMS($number,"Note for bike $bikeNum deleted."); + //$smsSender->send($number,"Note for bike $bikeNum deleted."); if($userNote=="%") { notifyAdmins(_('All')." ".sprintf(ngettext('%d note','%d notes',$count),$count)." "._('on stand')." ".$standName." "._('deleted by')." ".$reportedBy."."); @@ -752,14 +752,14 @@ function delstandnote($number,$standName,$message) function standNote($number,$standName,$message) { - global $db; + global $db, $smsSender; $userId = getUser($number); $result=$db->query("SELECT standId FROM stands where standName='$standName'"); if ($result->num_rows!=1) { - sendSMS($number,_("Stand")." ".$standName._("does not exist")."."); + $smsSender->send($number,_("Stand")." ".$standName._("does not exist")."."); return; } @@ -776,20 +776,20 @@ function standNote($number,$standName,$message) if ($userNote=="") //deletemmm { - sendSMS($number,_('Empty note for stand')." ".$standName." "._('not saved, for deleting notes use DELNOTE (for admins)')."."); + $smsSender->send($number,_('Empty note for stand')." ".$standName." "._('not saved, for deleting notes use DELNOTE (for admins)')."."); //checkUserPrivileges($number); // @TODO remove SMS from deleting completely? //$result=$db->query("UPDATE bikes SET note=NULL where bikeNum=$bikeNum"); //only admins can delete and those will receive the confirmation in the next step. - //sendSMS($number,"Note for bike $bikeNum deleted."); + //$smsSender->send($number,"Note for bike $bikeNum deleted."); //notifyAdmins("Note for bike $bikeNum deleted by $reportedBy."); } else { $db->query("INSERT INTO notes SET standId='$standId',userId='$userId',note='$userNote'"); $noteid=$db->getLastInsertId(); - sendSMS($number,_('Note for stand')." ".$standName." "._('saved')."."); + $smsSender->send($number,_('Note for stand')." ".$standName." "._('saved')."."); notifyAdmins(_('Note #').$noteid.": "._("on stand")." ".$standName." "._('by')." ".$reportedBy." (".$number."):".$userNote); } @@ -800,14 +800,14 @@ function standNote($number,$standName,$message) function tag($number,$standName,$message) { - global $db; + global $db, $smsSender; $userId = getUser($number); $result=$db->query("SELECT standId FROM stands where standName='$standName'"); if ($result->num_rows!=1) { - sendSMS($number,_("Stand")." ".$standName._("does not exist")."."); + $smsSender->send($number,_("Stand")." ".$standName._("does not exist")."."); return; } @@ -824,20 +824,20 @@ function tag($number,$standName,$message) if ($userNote=="") //deletemmm { - sendSMS($number,_('Empty tag for stand')." ".$standName." "._('not saved, for deleting notes for all bikes on stand use UNTAG (for admins)')."."); + $smsSender->send($number,_('Empty tag for stand')." ".$standName." "._('not saved, for deleting notes for all bikes on stand use UNTAG (for admins)')."."); //checkUserPrivileges($number); // @TODO remove SMS from deleting completely? //$result=$db->query("UPDATE bikes SET note=NULL where bikeNum=$bikeNum"); //only admins can delete and those will receive the confirmation in the next step. - //sendSMS($number,"Note for bike $bikeNum deleted."); + //$smsSender->send($number,"Note for bike $bikeNum deleted."); //notifyAdmins("Note for bike $bikeNum deleted by $reportedBy."); } else { $db->query("INSERT INTO notes (bikeNum,userId,note) SELECT bikeNum,'$userId','$userNote' FROM bikes where currentStand='$standId'"); //$noteid=$db->getLastInsertId(); - sendSMS($number,_('All bikes on stand')." ".$standName." "._('tagged')."."); + $smsSender->send($number,_('All bikes on stand')." ".$standName." "._('tagged')."."); notifyAdmins(_('All bikes on stand')." "."$standName".' '._('tagged by')." ".$reportedBy." (".$number.")". _("with note:").$userNote); } } @@ -846,7 +846,7 @@ function tag($number,$standName,$message) function note($number,$bikeNum,$message) { - global $db; + global $db, $smsSender; $userId = getUser($number); $bikeNum=trim($bikeNum); @@ -862,7 +862,7 @@ function note($number,$bikeNum,$message) } else { - sendSMS($number,_('Error in bike number / stand name specification:'.$db->escape($bikeNum))); + $smsSender->send($number,_('Error in bike number / stand name specification:'.$db->escape($bikeNum))); return; } @@ -871,7 +871,7 @@ function note($number,$bikeNum,$message) $result=$db->query("SELECT number,userName,stands.standName FROM bikes LEFT JOIN users on bikes.currentUser=users.userID LEFT JOIN stands on bikes.currentStand=stands.standId where bikeNum=$bikeNum"); if ($result->num_rows!=1) { - sendSMS($number,_('Bike')." ".$bikeNum." "._('does not exist')."."); + $smsSender->send($number,_('Bike')." ".$bikeNum." "._('does not exist')."."); return; } $row =$result->fetch_assoc(); @@ -904,14 +904,14 @@ function note($number,$bikeNum,$message) if ($userNote=="") { - sendSMS($number,_('Empty note for bike')." ".$bikeNum." "._('not saved, for deleting notes use DELNOTE (for admins)')."."); + $smsSender->send($number,_('Empty note for bike')." ".$bikeNum." "._('not saved, for deleting notes use DELNOTE (for admins)')."."); /*checkUserPrivileges($number); - sendSMS($number,_('Empty note for bike')." ".$bikeNum." "._('not saved, for deleting notes use DELNOTE.')."."); + $smsSender->send($number,_('Empty note for bike')." ".$bikeNum." "._('not saved, for deleting notes use DELNOTE.')."."); // @TODO remove SMS from deleting completely? $result=$db->query("UPDATE bikes SET note=NULL where bikeNum=$bikeNum"); //only admins can delete and those will receive the confirmation in the next step. - //sendSMS($number,"Note for bike $bikeNum deleted."); + //$smsSender->send($number,"Note for bike $bikeNum deleted."); notifyAdmins(_('Note for bike')." ".$bikeNum." "._('deleted by')." ".$reportedBy."."); */ } @@ -919,7 +919,7 @@ function note($number,$bikeNum,$message) { $db->query("INSERT INTO notes SET bikeNum='$bikeNum',userId='$userId',note='$userNote'"); $noteid=$db->getLastInsertId(); - sendSMS($number,_('Note for bike')." ".$bikeNum." "._('saved')."."); + $smsSender->send($number,_('Note for bike')." ".$bikeNum." "._('saved')."."); notifyAdmins(_('Note #').$noteid.": b.".$bikeNum." (".$bikeStatus.") "._('by')." ".$reportedBy." (".$number."):".$userNote); } @@ -928,14 +928,14 @@ function note($number,$bikeNum,$message) function last($number,$bike) { - global $db; + global $db, $smsSender; $userId = getUser($number); $bikeNum = intval($bike); $result=$db->query("SELECT bikeNum FROM bikes where bikeNum=$bikeNum"); if ($result->num_rows!=1) { - sendSMS($number,_('Bike')." ".$bikeNum." "._('does not exist')."."); + $smsSender->send($number,_('Bike')." ".$bikeNum." "._('does not exist')."."); return; } @@ -957,7 +957,7 @@ function last($number,$bike) } if ($rentedBikes>1) $historyInfo=substr($historyInfo,0,strlen($historyInfo)-1); - sendSMS($number,$historyInfo); + $smsSender->send($number,$historyInfo); } @@ -965,13 +965,13 @@ function last($number,$bike) function revert($number,$bikeNum) { - global $db; + global $db, $smsSender; $userId = getUser($number); $result=$db->query("SELECT currentUser FROM bikes WHERE bikeNum=$bikeNum AND currentUser<>'NULL'"); if (!$result->num_rows) { - sendSMS($number,_('Bike')." ".$bikeNum." "._('is not rented right now. Revert not successful!')); + $smsSender->send($number,_('Bike')." ".$bikeNum." "._('is not rented right now. Revert not successful!')); return; } else @@ -999,12 +999,12 @@ function revert($number,$bikeNum) $result=$db->query("INSERT INTO history SET userId=$userId,bikeNum=$bikeNum,action='REVERT',parameter='$standId|$code'"); $result=$db->query("INSERT INTO history SET userId=0,bikeNum=$bikeNum,action='RENT',parameter=$code"); $result=$db->query("INSERT INTO history SET userId=0,bikeNum=$bikeNum,action='RETURN',parameter=$standId"); - sendSMS($number,_('Bike')." ".$bikeNum." "._('reverted to stand')." ".$stand." "._('with code')." ".$code."."); - sendSMS($revertusernumber,_('Bike')." ".$bikeNum." "._('has been returned. You can now rent a new bicycle.')); + $smsSender->send($number,_('Bike')." ".$bikeNum." "._('reverted to stand')." ".$stand." "._('with code')." ".$code."."); + $smsSender->send($revertusernumber,_('Bike')." ".$bikeNum." "._('has been returned. You can now rent a new bicycle.')); } else { - sendSMS($number,_('No last code for bicycle')." ".$bikeNum." "._('found. Revert not successful!')); + $smsSender->send($number,_('No last code for bicycle')." ".$bikeNum." "._('found. Revert not successful!')); } } @@ -1012,7 +1012,7 @@ function revert($number,$bikeNum) function add($number,$email,$phone,$message) { - global $db, $countrycode; + global $db, $countrycode, $smsSender; $userId = getUser($number); $phone=normalizephonenumber($phone); @@ -1026,13 +1026,13 @@ function add($number,$email,$phone,$message) $oldName=$row["userName"]; $oldMail=$row["mail"]; - sendSMS($number,_('Contact information conflict: This number already registered:')." ".$oldMail." +".$oldPhone." ".$oldName); + $smsSender->send($number,_('Contact information conflict: This number already registered:')." ".$oldMail." +".$oldPhone." ".$oldName); return; } if ($phone < $countrycode."000000000" || $phone > ($countrycode+1)."000000000" || !preg_match("/add\s+([a-z0-9._%+-]+@[a-z0-9.-]+)\s+\+?[0-9]+\s+(.{2,}\s.{2,})/i",$message ,$matches)) { - sendSMS($number,_('Contact information is in incorrect format. Use:')." ADD king@earth.com 0901456789 Martin Luther King Jr."); + $smsSender->send($number,_('Contact information is in incorrect format. Use:')." ADD king@earth.com 0901456789 Martin Luther King Jr."); return; } $userName=$db->escape(trim($matches[2])); @@ -1042,19 +1042,19 @@ function add($number,$email,$phone,$message) sendConfirmationEmail($email); - sendSMS($number,_('User')." ".$userName." "._('added. They need to read email and agree to rules before using the system.')); + $smsSender->send($number,_('User')." ".$userName." "._('added. They need to read email and agree to rules before using the system.')); } function checkUserPrivileges($number) { - global $db, $sms; + global $db, $sms, $smsSender; $userId=getUser($number); $privileges=getPrivileges($userId); if ($privileges==0) { - sendSMS($number,_('Sorry, this command is only available for the privileged users.')); + $smsSender->send($number,_('Sorry, this command is only available for the privileged users.')); $sms->respond(); exit; } diff --git a/actions-web.php b/actions-web.php index 71e62e98..0dd8e603 100644 --- a/actions-web.php +++ b/actions-web.php @@ -399,7 +399,7 @@ function userbikes($userId) function revert($userId, $bikeNum) { - global $db; + global $db, $smsSender; $standId = 0; $result = $db->query("SELECT currentUser FROM bikes WHERE bikeNum=$bikeNum AND currentUser IS NOT NULL"); @@ -427,7 +427,7 @@ function revert($userId, $bikeNum) $result = $db->query("INSERT INTO history SET userId=0,bikeNum=$bikeNum,action='RENT',parameter=$code"); $result = $db->query("INSERT INTO history SET userId=0,bikeNum=$bikeNum,action='RETURN',parameter=$standId"); response('

' . _('Bicycle') . ' ' . $bikeNum . ' ' . _('reverted to') . ' ' . $stand . ' ' . _('with code') . ' ' . $code . '.

'); - sendSMS($revertusernumber, _('Bike') . ' ' . $bikeNum . ' ' . _('has been returned. You can now rent a new bicycle.')); + $smsSender->send($revertusernumber, _('Bike') . ' ' . $bikeNum . ' ' . _('has been returned. You can now rent a new bicycle.')); } else { response(_('No last stand or code for bicycle') . ' ' . $bikeNum . ' ' . _('found. Revert not successful!'), ERROR); } @@ -539,7 +539,7 @@ function checkprivileges($userid) function smscode($number) { - global $db, $gatewayId, $gatewayKey, $gatewaySenderNumber, $connectors; + global $db, $gatewayId, $gatewayKey, $gatewaySenderNumber, $connectors, $smsSender; srand(); $number = normalizephonenumber($number); @@ -570,7 +570,7 @@ function smscode($number) if (DEBUG === true) { response($number, 0, array('checkcode' => $checkcode, 'smscode' => $smscode, 'existing' => $userexists)); } else { - sendSMS($number, $text); + $smsSender->send($number, $text); if (issmssystemenabled() == true) { response($number, 0, array('checkcode' => $checkcode, 'existing' => $userexists)); } else { diff --git a/admin.php b/admin.php index 819726b7..8954dbc5 100644 --- a/admin.php +++ b/admin.php @@ -8,7 +8,7 @@ require('actions-web.php'); /** - * @var DbInterface + * @var DbInterface $db */ $db=new MysqliDb($dbserver,$dbuser,$dbpassword,$dbname); $db->connect(); diff --git a/agree.php b/agree.php index 463f91cc..2686d362 100644 --- a/agree.php +++ b/agree.php @@ -8,7 +8,7 @@ require('actions-web.php'); /** - * @var DbInterface + * @var DbInterface $db */ $db=new MysqliDb($dbserver,$dbuser,$dbpassword,$dbname); $db->connect(); diff --git a/command.php b/command.php index 0d954e4d..7267633f 100644 --- a/command.php +++ b/command.php @@ -8,7 +8,7 @@ require('actions-web.php'); /** - * @var DbInterface + * @var DbInterface $db */ $db=new MysqliDb($dbserver,$dbuser,$dbpassword,$dbname); $db->connect(); diff --git a/common.php b/common.php index c0288143..f96fa0d7 100644 --- a/common.php +++ b/common.php @@ -5,6 +5,9 @@ use BikeShare\Mail\PHPMailerMailSender; use BikeShare\Db\DbInterface; use BikeShare\Db\MysqliDb; +use BikeShare\Sms\SmsSender; +use BikeShare\Sms\SmsSenderInterface; +use BikeShare\SmsConnector\DebugConnector; use BikeShare\SmsConnector\SmsConnectorFactory; require_once 'vendor/autoload.php'; @@ -21,10 +24,16 @@ DEBUG ); +/** + * @var DbInterface $db + */ +$db = new MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); +$db->connect(); + /** * @var MailSenderInterface $mailer */ -if (DEBUG===TRUE) { +if (DEBUG === TRUE) { $mailer = new DebugMailSender(); } else { $mailer = new PHPMailerMailSender( @@ -35,6 +44,14 @@ ); } +/** + * @var SmsSenderInterface $smsSender + */ +$smsSender = new SmsSender( + DEBUG === TRUE ? new DebugConnector() : $sms, + $db +); + function error($message) { @@ -43,53 +60,6 @@ function error($message) exit($message); } -function sendSMS($number,$text) -{ - - global $sms; - - $message = $text; - if (strlen($message) > 160) { - $message = chunk_split($message, 160, '|'); - $message = explode('|', $message); - foreach ($message as $text) { - $text = trim($text); - if ($text) { - logSendsms($number, $text); - if (DEBUG === true) { - echo $number, ' -> ', $text, '
'; - } else { - $sms->send($number, $text); - } - } - } - } else { - logSendsms($number, $text); - if (DEBUG === true) { - echo $number, ' -> ', $text, '
'; - } else { - $sms->send($number, $text); - } - } -} - -function logSendsms($number, $text) -{ - global $dbserver, $dbuser, $dbpassword, $dbname; - /** - * @var DbInterface - */ - $localdb = new MysqliDb($dbserver, $dbuser, $dbpassword, $dbname); - $localdb->connect(); - - #TODO does it needed??? - $localdb->setAutocommit(true); - $number = $localdb->escape($number); - $text = $localdb->escape($text); - - $result = $localdb->query("INSERT INTO sent SET number='$number',text='$text'"); - -} function generatecodes($numcodes,$codelength,$wastage=25) { @@ -288,12 +258,12 @@ function checkstandname($stand) **/ function notifyAdmins($message, $notificationtype = 0) { - global $db, $systemname, $watches, $mailer; + global $db, $systemname, $watches, $mailer, $smsSender; $result = $db->query('SELECT number,mail FROM users where privileges & 2 != 0'); while ($row = $result->fetch_assoc()) { if ($notificationtype == 0) { - sendSMS($row['number'], $message); + $smsSender->send($row['number'], $message); $mailer->send($watches['email'], $systemname . ' ' . _('notification'), $message); } else { $mailer->send($row['mail'], $systemname . ' ' . _('notification'), $message); @@ -373,7 +343,7 @@ function checktopofstack($standid) function checklongrental() { - global $db, $watches, $notifyuser; + global $db, $smsSender, $watches, $notifyuser; $abusers = ''; $found = 0; @@ -392,7 +362,7 @@ function checklongrental() $abusers .= ' b' . $bikenum . ' ' . _('by') . ' ' . $username . ','; $found = 1; if ($notifyuser) { - sendSMS($userphone, _('Please, return your bike ') . $bikenum . _(' immediately to the closest stand! Ignoring this warning can get you banned from the system.')); + $smsSender->send($userphone, _('Please, return your bike ') . $bikenum . _(' immediately to the closest stand! Ignoring this warning can get you banned from the system.')); } } } diff --git a/config.php.example b/config.php.example index 87e0e008..c540ad03 100755 --- a/config.php.example +++ b/config.php.example @@ -53,6 +53,11 @@ $connectors["sms"]=""; // API connector used for SMS operations (connectors/ dir $connectors["config"]["disabled"]="{}"; //json string for configuration of sms service $countrycode=""; // international dialing code (country code prefix), no plus sign +$cities = ['Bratislava']; //avalible in cities +$citiesGPS = [ + 'Bratislava' => ['48.148154', '17.117232'] +]; + /*** geoJSON files - uncomment line below to use, any number of geoJSON files can be included ***/ // $geojson[]="http://example.com/poi.json"; // example geojson file with points of interests to be displayed on the map diff --git a/cron.php b/cron.php index e123fa7a..76d47adf 100644 --- a/cron.php +++ b/cron.php @@ -8,7 +8,7 @@ require("actions-web.php"); /** - * @var DbInterface + * @var DbInterface $db */ $db=new MysqliDb($dbserver,$dbuser,$dbpassword,$dbname); $db->connect(); diff --git a/docker-data/mysql/create-database.sql b/docker-data/mysql/create-database.sql index af11278c..aa1727af 100644 --- a/docker-data/mysql/create-database.sql +++ b/docker-data/mysql/create-database.sql @@ -135,6 +135,7 @@ CREATE TABLE `users` ( `mail` varchar(30) NOT NULL, `number` varchar(30) NOT NULL, `privileges` int(11) NOT NULL DEFAULT '0', + `city` varchar(45) NOT NULL DEFAULT 'Bratisalva', PRIMARY KEY (`userId`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/index.php b/index.php index caae893b..a0cd8422 100644 --- a/index.php +++ b/index.php @@ -8,7 +8,7 @@ require "actions-web.php"; /** - * @var DbInterface + * @var DbInterface $db */ $db=new MysqliDb($dbserver,$dbuser,$dbpassword,$dbname); $db->connect(); diff --git a/install/generate.php b/install/generate.php index 8ff5e624..fe7b606d 100644 --- a/install/generate.php +++ b/install/generate.php @@ -11,7 +11,7 @@ } /** - * @var DbInterface + * @var DbInterface $db */ $db=new MysqliDb($dbserver,$dbuser,$dbpassword,$dbname); $db->connect(); diff --git a/install/index.php b/install/index.php index e853737e..44cb4bce 100644 --- a/install/index.php +++ b/install/index.php @@ -208,7 +208,7 @@ function return_bytes($val) { $newconfig=implode($configfile); file_put_contents($configfilename,$newconfig); /** - * @var DbInterface + * @var DbInterface $db */ $db=new MysqliDb($_POST["dbserver"],$_POST["dbuser"],$_POST["dbpassword"],$_POST["dbname"]); $db->connect(); @@ -239,7 +239,7 @@ function return_bytes($val) { connect(); @@ -263,7 +263,7 @@ function return_bytes($val) { connect(); @@ -329,7 +329,7 @@ function return_bytes($val) { connect(); @@ -401,7 +401,7 @@ function return_bytes($val) { connect(); diff --git a/receive.php b/receive.php index 14830cb8..f2ecf930 100644 --- a/receive.php +++ b/receive.php @@ -8,7 +8,7 @@ require("config.php"); /** - * @var DbInterface + * @var DbInterface $db */ $db=new MysqliDb($dbserver,$dbuser,$dbpassword,$dbname); $db->connect(); @@ -25,7 +25,7 @@ if(!validateNumber($sms->getNumber())) { #### - #sendSMS($sms->getNumber(),_('Your number is not registered.')); + #$smsSender->send($sms->getNumber(),_('Your number is not registered.')); } else { diff --git a/scan.php b/scan.php index 489987ad..30f4573a 100644 --- a/scan.php +++ b/scan.php @@ -8,7 +8,7 @@ require('actions-qrcode.php'); /** - * @var DbInterface + * @var DbInterface $db */ $db=new MysqliDb($dbserver,$dbuser,$dbpassword,$dbname); $db->connect(); diff --git a/src/Sms/SmsSender.php b/src/Sms/SmsSender.php new file mode 100644 index 00000000..9460b749 --- /dev/null +++ b/src/Sms/SmsSender.php @@ -0,0 +1,49 @@ +smsConnector = $smsConnector; + $this->db = $db; + } + + public function send($number,$message) + { + if (strlen($message) > 160) { + $messageParts = str_split($message, 160); + foreach ($messageParts as $text) { + $text = trim($text); + if ($text) { + $this->log($number, $text); + $this->smsConnector->send($number, $text); + } + } + } else { + $this->log($number, $message); + $this->smsConnector->send($number, $message); + } + } + + private function log($number, $message) + { + $this->db->query("INSERT INTO sent SET number='$number', text='$message'"); + $this->db->commit(); + } +} diff --git a/src/Sms/SmsSenderInterface.php b/src/Sms/SmsSenderInterface.php new file mode 100644 index 00000000..1d3684dd --- /dev/null +++ b/src/Sms/SmsSenderInterface.php @@ -0,0 +1,8 @@ +smsConnector = $this->createMock(SmsConnectorInterface::class); + $this->db = $this->createMock(DbInterface::class); + $this->smsSender = new SmsSender($this->smsConnector, $this->db); + } + + protected function tearDown() + { + unset( + $this->smsConnector, + $this->db, + $this->smsSender + ); + } + + public function testSendShort() + { + $number = '123456789'; + $message = 'Hello, World!'; + $this->smsConnector + ->expects($this->once()) + ->method('send') + ->with($number, $message); + $this->db + ->expects($this->once()) + ->method('query') + ->with("INSERT INTO sent SET number='$number', text='$message'"); + $this->db + ->expects($this->once()) + ->method('commit'); + $this->smsSender->send($number, $message); + } + + public function testSendBig() + { + $number = '123456789'; + $message = 'Hello, World! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla nec purus euismod mi fermentum sollicitudin. Vivamus euismod, tellus ac euismod ultricies, justo risus luctus ipsum, quis condimentum orci lacus id tellus. Sed ut ultrices mi. Nullam id orci ut mauris tincidunt tincidunt. '; + $this->smsConnector + ->expects($this->exactly(2)) + ->method('send') + ->withConsecutive( + [$number, 'Hello, World! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla nec purus euismod mi fermentum sollicitudin. Vivamus euismod, tellus ac euismod'], + [$number, 'ultricies, justo risus luctus ipsum, quis condimentum orci lacus id tellus. Sed ut ultrices mi. Nullam id orci ut mauris tincidunt tincidunt.'] + ); + $this->db + ->expects($this->exactly(2)) + ->method('query') + ->withConsecutive( + ["INSERT INTO sent SET number='$number', text='Hello, World! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla nec purus euismod mi fermentum sollicitudin. Vivamus euismod, tellus ac euismod'"], + ["INSERT INTO sent SET number='$number', text='ultricies, justo risus luctus ipsum, quis condimentum orci lacus id tellus. Sed ut ultrices mi. Nullam id orci ut mauris tincidunt tincidunt.'"] + ); + $this->db + ->expects($this->exactly(2)) + ->method('commit'); + $this->smsSender->send($number, $message); + } +} diff --git a/tests/SmsConnector/DebugConnectorTest.php b/tests/SmsConnector/DebugConnectorTest.php new file mode 100644 index 00000000..0d1eb358 --- /dev/null +++ b/tests/SmsConnector/DebugConnectorTest.php @@ -0,0 +1,16 @@ +send('123456789', 'Hello, World!'); + $this->expectOutputString('123456789 -> Hello, World!'.PHP_EOL); + } +} From 989c63acd098d4440b2543dc951a78cd78765fec Mon Sep 17 00:00:00 2001 From: Sveneld Date: Wed, 28 Feb 2024 22:36:53 +0100 Subject: [PATCH 6/6] Add SmsSenderInterface Small fixes --- src/Sms/SmsSender.php | 2 +- src/SmsConnector/DebugConnector.php | 3 ++- tests/Sms/SmsSenderTest.php | 7 +++++++ tests/SmsConnector/DebugConnectorTest.php | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Sms/SmsSender.php b/src/Sms/SmsSender.php index 9460b749..626b1a15 100644 --- a/src/Sms/SmsSender.php +++ b/src/Sms/SmsSender.php @@ -24,7 +24,7 @@ public function __construct( $this->db = $db; } - public function send($number,$message) + public function send($number, $message) { if (strlen($message) > 160) { $messageParts = str_split($message, 160); diff --git a/src/SmsConnector/DebugConnector.php b/src/SmsConnector/DebugConnector.php index d878f459..027378b4 100644 --- a/src/SmsConnector/DebugConnector.php +++ b/src/SmsConnector/DebugConnector.php @@ -11,8 +11,9 @@ public function checkConfig(array $config) public function respond() { } + public function send($number, $text) { - echo $number. ' -> ' . $text .PHP_EOL; + echo $number . ' -> ' . $text . PHP_EOL; } } diff --git a/tests/Sms/SmsSenderTest.php b/tests/Sms/SmsSenderTest.php index e1b1de80..f7d8817b 100644 --- a/tests/Sms/SmsSenderTest.php +++ b/tests/Sms/SmsSenderTest.php @@ -43,23 +43,30 @@ public function testSendShort() $this->smsSender->send($number, $message); } + public function testSendBig() { $number = '123456789'; + // @codingStandardsIgnoreStart $message = 'Hello, World! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla nec purus euismod mi fermentum sollicitudin. Vivamus euismod, tellus ac euismod ultricies, justo risus luctus ipsum, quis condimentum orci lacus id tellus. Sed ut ultrices mi. Nullam id orci ut mauris tincidunt tincidunt. '; + // @codingStandardsIgnoreEnd $this->smsConnector ->expects($this->exactly(2)) ->method('send') ->withConsecutive( + // @codingStandardsIgnoreStart [$number, 'Hello, World! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla nec purus euismod mi fermentum sollicitudin. Vivamus euismod, tellus ac euismod'], [$number, 'ultricies, justo risus luctus ipsum, quis condimentum orci lacus id tellus. Sed ut ultrices mi. Nullam id orci ut mauris tincidunt tincidunt.'] + // @codingStandardsIgnoreEnd ); $this->db ->expects($this->exactly(2)) ->method('query') ->withConsecutive( + // @codingStandardsIgnoreStart ["INSERT INTO sent SET number='$number', text='Hello, World! Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla nec purus euismod mi fermentum sollicitudin. Vivamus euismod, tellus ac euismod'"], ["INSERT INTO sent SET number='$number', text='ultricies, justo risus luctus ipsum, quis condimentum orci lacus id tellus. Sed ut ultrices mi. Nullam id orci ut mauris tincidunt tincidunt.'"] + // @codingStandardsIgnoreEnd ); $this->db ->expects($this->exactly(2)) diff --git a/tests/SmsConnector/DebugConnectorTest.php b/tests/SmsConnector/DebugConnectorTest.php index 0d1eb358..61c033c0 100644 --- a/tests/SmsConnector/DebugConnectorTest.php +++ b/tests/SmsConnector/DebugConnectorTest.php @@ -11,6 +11,6 @@ public function testSend() { $debugConnector = new DebugConnector(); $debugConnector->send('123456789', 'Hello, World!'); - $this->expectOutputString('123456789 -> Hello, World!'.PHP_EOL); + $this->expectOutputString('123456789 -> Hello, World!' . PHP_EOL); } }