ordersprinter/webapp/php/admin.php

2028 lines
67 KiB
PHP
Raw Normal View History

2020-11-19 22:47:44 +01:00
<?php
// Datenbank-Verbindungsparameter
require_once ('dbutils.php');
require_once ('globals.php');
require_once ('utilities/TypeAndProducts/TypeAndProductFileManager.php');
require_once ('utilities/userrights.php');
require_once ('utilities/HistFiller.php');
require_once ('utilities/basedb.php');
require_once ('utilities/sorter.php');
require_once ('utilities/Logger.php');
require_once ('utilities/Emailer.php');
class Admin {
var $dbutils;
var $userrights;
var $histfiller;
private static $timezone = null;
function __construct() {
$this->dbutils = new DbUtils();
$this->userrights = new Userrights();
$this->histfiller = new HistFiller();
}
function handleCommand($command) {
// these command are only allowed for user with manager or admin rights
$cmdArray = array('createNewUser', 'updateUser', 'deleteUser','changepassword' , 'changeConfig', 'readlogo','deletelogo');
if (in_array($command, $cmdArray)) {
if (!($this->userrights->hasCurrentUserRight('right_manager')) && !($this->userrights->hasCurrentUserRight('is_admin'))) {
echo "Benutzerrechte nicht ausreichend!";
return false;
}
}
if ($command == 'tryAuthenticate') {
$this->tryAuthenticate($_POST['userid'],$_POST['password'],$_POST['day'],$_POST['month'],$_POST['year'],$_POST['hour'],$_POST['minute'],$_POST["time"]);
} else if ($command == 'setLastModuleOfUser') {
$this->setLastModuleOfUser($_POST['view']);
} else if ($command == 'getViewAfterLogin') {
$this->getViewAfterLogin();
} else if ($command == 'isUserAlreadyLoggedIn') {
$this->isUserAlreadyLoggedIn();
} else if ($command == 'logout') {
$this->logout();
} else if ($command == 'getCurrentUser') {
$this->getCurrentUser();
} else if ($command == 'isLoggedinUserAdmin') {
$this->isLoggedinUserAdmin();
} else if ($command == 'isLoggedinUserKitchen') {
$this->isLoggedinUserKitchen();
} else if ($command == 'isLoggedinUserBar') {
$this->isLoggedinUserBar();
} else if ($command == 'isLoggedinUserAdminOrManager') {
$this->isLoggedinUserAdminOrManager();
} else if ($command == 'hasUserPaydeskRight') {
$this->hasUserPaydeskRight();
} else if ($command == 'getJsonMenuItemsAndVersion') {
$this->getJsonMenuItemsAndVersion();
} else if ($command == 'getUserList') {
$this->getUserList();
} else if ($command == 'setTime') {
$this->setTime($_POST['day'],$_POST['month'],$_POST['year'],$_POST['hour'],$_POST['minute']);
} else if ($command == 'createNewUser') {
$this->createNewUser(
$_POST['username'],
$_POST['password'],
$_POST['isAdmin'],
$_POST['rWaiter'],
$_POST['rKitchen'],
$_POST['rBar'],
$_POST['rSupply'],
$_POST['rPayDesk'],
$_POST['rStat'],
$_POST['rBill'],
$_POST['rProducts'],
$_POST['rReservation'],
$_POST['rRating'],
$_POST['rChangeprice'],
$_POST['rManager']
);
} else if ($command == 'updateUser') {
$this->updateUser(
$_POST['userid'],
$_POST['isAdmin'],
$_POST['rWaiter'],
$_POST['rKitchen'],
$_POST['rBar'],
$_POST['rSupply'],
$_POST['rPayDesk'],
$_POST['rStat'],
$_POST['rBill'],
$_POST['rProducts'],
$_POST['rReservation'],
$_POST['rRating'],
$_POST['rChangeprice'],
$_POST['rManager']
);
} else if ($command == 'deleteUser') {
$this->deleteUser($_POST['userid']);
} else if ($command == 'changepassword') {
$this->changepassword($_POST['userid'],$_POST['password']);
} else if ($command == 'changeOwnPassword') {
$this->changeOwnPassword($_POST['oldPass'],$_POST['newPass']);
} else if ($command == 'setUserLanguage') {
$this->setUserLanguage($_POST['language']);
} else if ($command == 'setUserReceiptPrinter') {
$this->setUserReceiptPrinter($_POST['printer']);
} else if ($command == 'setBtnSize') {
$this->setBtnSize($_POST['btn'],$_POST['size']);
} else if ($command == 'changeConfig') {
$this->changeConfig($_POST['changed']);
} else if ($command == 'readlogo') {
$this->readlogo();
} else if ($command == 'deletelogo') {
$this->deletelogo();
} else if ($command == 'getGeneralConfigItems') {
$this->getGeneralConfigItems(true,null);
} else if ($command == 'getWaiterSettings') {
$this->getWaiterSettings();
// from here on admin rights are needed
} else if ($command == 'getPayPrintType') {
$this->getPayPrintType();
} else if ($command == 'getPayments') {
$this->getPayments();
2020-11-19 22:55:09 +01:00
} else if ($command == 'autobackup') {
$this->backup('auto',$_POST['remoteaccesscode']);
2020-11-19 22:47:44 +01:00
} else if (($command == 'new') || ($command == 'shutdown') || ($command == 'backup') || ($command == 'restore') || ($command == 'drop') || ($command == 'fill') || ($command == 'fillSampleProdType') || ($command == 'fillSpeisekarte') || ($command == 'assignTaxes')) {
if ($this->isCurrentUserAdmin()) {
if ($command == 'fill') {
$this->fillSampleContent();
echo json_encode(array("status" => "OK"));
} else if ($command == 'fillSampleProdType') {
$this->fillSampleProdType("samples/speisekarte.txt");
echo json_encode(array("status" => "OK"));
} else if ($command == 'fillSpeisekarte') {
$this->fillSpeisekarte($_POST['speisekarte']);
} else if ($command == 'backup') {
2020-11-19 22:55:09 +01:00
$this->backup($_GET['type'],null);
2020-11-19 22:47:44 +01:00
return;
} else if ($command == 'restore') {
$this->restore();
return;
} else if ($command == 'shutdown') {
$this->shutdown();
return;
} else if ($command == 'assignTaxes') {
$this->assignTaxes($_POST['food'],$_POST['drinks']);
return;
}
} else {
echo json_encode(array("status" => "ERROR", "code" => ERROR_NOT_AUTHOTRIZED, "msg" => ERROR_NOT_AUTHOTRIZED_MSG));
}
// end area for admins
} else if ($command == 'exportConfigCsv') {
if ($this->isCurrentUserAdmin() || $this->hasCurrentUserRight('right_manager')) {
$this->exportConfigCsv();
}
} else if ($command == 'exportUserCsv') {
if ($this->isCurrentUserAdmin() || $this->hasCurrentUserRight('right_manager')) {
$this->exportUserCsv();
}
} else if ($command == 'setOrderVolume') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setOrderVolume($_POST['volume']);
}
} else if ($command == 'setPreferTableMap') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setPreferTableMap($_POST['prefertablemap']);
}
2020-11-19 22:48:24 +01:00
} else if ($command == 'setKeepTypeLevel') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setKeepTypeLevel($_POST['keeptypelevel']);
}
2020-11-19 22:53:50 +01:00
} else if ($command == 'setApplyExtrasBtnPos') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setExtrasApplyBtnPos($_POST['applyextrasbtnpos']);
}
2020-11-19 22:47:44 +01:00
} else if ($command == 'getOrderVolume') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getOrderVolume();
}
} else if ($command == 'getButtonSizes') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getButtonSizes();
}
} else if ($command == 'getPreferTableMap') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getPreferTableMap();
}
2020-11-19 22:48:24 +01:00
} else if ($command == 'getKeepTypeLevel') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getKeepTypeLevel();
}
2020-11-19 22:53:50 +01:00
} else if ($command == 'getApplyExtrasBtnPos') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getApplyExtrasBtnPos();
}
2020-11-19 22:47:44 +01:00
} else if ($command == 'isInstalled') {
$this->isInstalled();
}
else {
echo "Command not supported.";
}
}
/***
* Is the installation already done? Or was the html/php code overwritten, i.e. a new or updated version to install?
*/
private function isInstalled() {
if(defined('INSTALLSTATUS')){
if (INSTALLSTATUS == 'new') {
echo json_encode("No");
} else {
echo json_encode("Yes");
}
} else {
// not defined -> it must be version 1.0.3 or lower --> since this is file of 1.0.4: not installed...
echo json_encode("No");
}
}
function isUserAlreadyLoggedInForPhp() {
if(session_id() == '') {
session_start();
}
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
return false;
} else {
return true;
}
}
function isUserAlreadyLoggedIn() {
if(session_id() == '') {
session_start();
}
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
// no user logged in
echo json_encode("NO");
} else {
echo json_encode("YES");
}
}
function logout() {
if(session_id() == '') {
session_start();
session_destroy();
}
echo json_encode("OK");
}
static function isOnlyRatingUser($rightArr,$right_rating,$comparisonVal) {
foreach($rightArr as $aRight) {
if ($aRight == $comparisonVal) {
return false;
}
}
if ($right_rating == $comparisonVal) {
return true;
} else {
return false;
}
}
// for the login mask - if user is authenticated then the first page works different
function tryAuthenticate($userid,$password,$day,$month,$year,$hour,$minute,$unixtime) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$authenticated = false;
$sql = "SELECT * FROM %user% WHERE id=? AND active='1'";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($userid));
$result = $stmt->fetchAll();
$numberOfEntries = count($result);
if ($numberOfEntries == 1) {
$zeile = $result[0];
$pass_hash = $zeile['userpassword'];
2020-11-19 22:54:12 +01:00
if ($zeile['is_admin'] == 0) {
// authentication-check
}
2020-11-19 22:47:44 +01:00
// password_verify requires PHP > 5.5, so let's use MD5 instead
// (it is no banking software...)
if (md5($password) == $pass_hash) {
$authenticated = true;
}
}
if ($authenticated) {
date_default_timezone_set(DbUtils::getTimeZone());
$now = getdate();
$serverDay = $now["mday"];
$serverMonth = $now["mon"];
$serverYear = $now["year"];
$serverHour = $now["hours"];
$serverMinute = $now["minutes"];
$serverTime = $now["0"];
$timeDiff = 0;
if (abs($serverTime - $unixtime) > (60*60*2)) {
$timeDiff = 1;
}
ini_set('session.gc_maxlifetime',65535);
session_set_cookie_params(65535);
if(session_id() == '') {
session_start();
}
$username = $zeile["username"];
$_SESSION['angemeldet'] = true;
// now read the rights of the user
$_SESSION['userid'] = $zeile['id'];
$_SESSION['currentuser'] = $username;
$workflow = $this->getConfigItemsAsString($pdo, "workflowconfig");
$rights = array($zeile['is_admin'],$zeile['right_waiter'],$zeile['right_kitchen'],
$zeile['right_bar'],$zeile['right_supply'],$zeile['right_paydesk'],
$zeile['right_statistics'],$zeile['right_bill'],$zeile['right_products'],
$zeile['right_reservation'],$zeile['right_changeprice'],$zeile['right_manager']);
$right_rating = $zeile['right_rating'];
if (self::isOnlyRatingUser($rights,$right_rating, 1)) {
$_SESSION['right_rating'] = true;
$_SESSION['is_admin'] = false;
$_SESSION['right_waiter'] = false;
$_SESSION['right_kitchen'] = false;
$_SESSION['right_bar'] = false;
$_SESSION['right_supply'] = false;
$_SESSION['right_paydesk'] = false;
$_SESSION['right_statistics'] = false;
$_SESSION['right_bill'] = false;
$_SESSION['right_products'] = false;
$_SESSION['right_reservation'] = false;
$_SESSION['right_changeprice'] = false;
$_SESSION['right_manager'] = false;
2020-11-19 22:48:24 +01:00
$_SESSION['keeptypelevel'] = false;
2020-11-19 22:47:44 +01:00
} else {
$_SESSION['is_admin'] = ($zeile['is_admin'] == 1 ? true : false);
$_SESSION['right_waiter'] = ($zeile['right_waiter'] == 1 ? true : false);
2020-11-19 22:55:30 +01:00
if (($workflow == 2) || ($workflow == 3)) {
2020-11-19 22:47:44 +01:00
$_SESSION['right_kitchen'] = false;
$_SESSION['right_bar'] = false;
$_SESSION['right_supply'] = false;
} else {
$_SESSION['right_kitchen'] = ($zeile['right_kitchen'] == 1 ? true : false);
$_SESSION['right_bar'] = ($zeile['right_bar'] == 1 ? true : false);
$_SESSION['right_supply'] = ($zeile['right_supply'] == 1 ? true : false);
}
$_SESSION['right_paydesk'] = ($zeile['right_paydesk'] == 1 ? true : false);
$_SESSION['right_statistics'] = ($zeile['right_statistics'] == 1 ? true : false);
$_SESSION['right_bill'] = ($zeile['right_bill'] == 1 ? true : false);
$_SESSION['right_products'] = ($zeile['right_products'] == 1 ? true : false);
$_SESSION['right_reservation'] = ($zeile['right_reservation'] == 1 ? true : false);
$_SESSION['right_rating'] = ($zeile['right_rating'] == 1 ? true : false);
$_SESSION['right_changeprice'] = ($zeile['right_changeprice'] == 1 ? true : false);
$_SESSION['right_manager'] = ($zeile['right_manager'] == 1 ? true : false);
2020-11-19 22:48:24 +01:00
$_SESSION['keeptypelevel'] = ($zeile['keeptypelevel'] == 1 ? true : false);
2020-11-19 22:47:44 +01:00
}
$this->userrights->setSession($_SESSION['is_admin'], $_SESSION['right_waiter'], $_SESSION['right_kitchen'],
$_SESSION['right_bar'], $_SESSION['right_supply'], $_SESSION['right_paydesk'], $_SESSION['right_statistics'],
$_SESSION['right_bill'], $_SESSION['right_products'], $_SESSION['right_reservation'], $_SESSION['right_rating'], $_SESSION['right_changeprice'], $_SESSION['right_manager']);
$assoc = array ("0" => "roombtnsize","1" => "tablebtnsize","2" => "prodbtnsize");
$_SESSION["roombtnsize"] = $zeile['roombtnsize'];
$_SESSION["tablebtnsize"] = $zeile['tablebtnsize'];
$_SESSION["prodbtnsize"] = $zeile['prodbtnsize'];
$language = $zeile['language'];
if (is_null($language)) {
$language = 0;
}
$_SESSION['language'] = intval($language);
$receiptprinter = $zeile['receiptprinter'];
if (is_null($receiptprinter)) {
$receiptprinter = 1;
}
$_SESSION['receiptprinter'] = intval($receiptprinter);
$preferTm = $zeile['prefertablemap'];
if (is_null($preferTm)) {
$preferTm = 1;
}
$_SESSION['prefertm'] = intval($preferTm);
$pdo = DbUtils::openDbAndReturnPdoStatic();
$_SESSION['timezone'] = $this->getTimeZone($pdo);
}
if ($authenticated) {
Logger::logcmd("admin","authentication","Login $username successful");
$loginMessage = $this->getMessage(null,'loginmessage');
echo json_encode(array("status" => "YES","loginmessage" => $loginMessage, "timediff" => $timeDiff, "isadmin" => $zeile['is_admin'],"lang" => $_SESSION["language"]));
} else {
Logger::logcmd("admin","authentication","Login with id $userid failed");
echo json_encode(array("status" => "NO"));
}
}
private function getMessage($pdo,$messageType) {
if (is_null($pdo)) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
}
$sql = "SELECT value FROM %work% WHERE item=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($messageType));
$row = $stmt->fetchObject();
$msg = "";
if ($stmt->rowCount() > 0) {
$msg = $row->value;
}
return $msg;
}
function getButtonSizes() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
echo json_encode(self::getButtonSizesCore($pdo));
}
private static function getButtonSizesCore($pdo) {
$userid = $_SESSION['userid'];
$sql = "SELECT roombtnsize,tablebtnsize,prodbtnsize FROM %user% WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($userid));
$row =$stmt->fetchObject();
$roombtnsize = $row->roombtnsize;
if (is_null($roombtnsize)) {
$roombtnsize = 0;
}
$tablebtnsize = $row->tablebtnsize;
if (is_null($tablebtnsize)) {
$tablebtnsize = 0;
}
$prodbtnsize = $row->prodbtnsize;
if (is_null($prodbtnsize)) {
$prodbtnsize = 0;
}
return(array("roombtnsize" => $roombtnsize,"tablebtnsize" => $tablebtnsize,"prodbtnsize" => $prodbtnsize));
}
private static function getUserValue($item,$defaultvalue) {
$userid = $_SESSION['userid'];
$sql = "SELECT $item AS result FROM %user% WHERE id=?";
$pdo = DbUtils::openDbAndReturnPdoStatic();
$stmt = $pdo->prepare(Dbutils::substTableAlias($sql));
$stmt->execute(array($userid));
if ($stmt->rowCount() == 0) {
return $defaultvalue;
}
$row = $stmt->fetchObject();
$aVal = 0;
if ($row != null) {
$aVal = $row->result;
if ($aVal == null) {
$aVal = $defaultvalue;
}
}
echo json_encode($aVal);
}
function getPreferTableMap() {
self::getUserValue('prefertablemap',1);
}
2020-11-19 22:48:24 +01:00
function getKeepTypeLevel() {
self::getUserValue('keeptypelevel',1);
}
2020-11-19 22:53:50 +01:00
function getApplyExtrasBtnPos() {
self::getUserValue('extrasapplybtnpos', 1);
}
2020-11-19 22:47:44 +01:00
function getOrderVolume() {
self::getUserValue('ordervolume',0);
}
private static function setUserValue($item,$theValue) {
$userid = $_SESSION['userid'];
$sql = "UPDATE %user% SET $item=? WHERE id=?";
$pdo = DbUtils::openDbAndReturnPdoStatic();
$pdo->beginTransaction();
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($theValue,$userid));
$pdo->commit();
echo json_encode(array("status" => "OK"));
}
function setOrderVolume($volume) {
2020-11-19 22:48:24 +01:00
self::setUserValue('ordervolume', $volume);
2020-11-19 22:47:44 +01:00
}
function setPreferTableMap($preferValue) {
self::setUserValue('prefertablemap',$preferValue);
}
2020-11-19 22:48:24 +01:00
function setKeepTypeLevel($preferValue) {
self::setUserValue('keeptypelevel',$preferValue);
}
2020-11-19 22:53:50 +01:00
function setExtrasApplyBtnPos($preferValue) {
self::setUserValue('extrasapplybtnpos',$preferValue);
}
2020-11-19 22:47:44 +01:00
function setLastModuleOfUser($view) {
if ($this->isUserAlreadyLoggedInForPhp()) {
if ($view != "logout.php") {
$userid = $_SESSION['userid'];
2020-11-19 22:52:55 +01:00
$questPos = strpos($view,'?');
if ($questPos != false) {
$view = substr($view,0,$questPos);
}
2020-11-19 22:47:44 +01:00
$sql = "UPDATE %user% SET lastmodule=? WHERE id=? AND active='1'";
$pdo = $this->dbutils->openDbAndReturnPdo();
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($view,$userid));
}
echo json_encode(array("status" => "OK"));
2020-11-19 22:55:20 +01:00
} else {
echo json_encode(array("status" => "Error","msg" => "Benutzer nicht eingeloggt"));
2020-11-19 22:47:44 +01:00
}
}
public function getConfigItemsAsString($pdo,$key) {
$sql = "SELECT setting FROM %config% WHERE name=?";
if (is_null($pdo)) {
return "";
}
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($key));
$row = $stmt->fetchObject();
if ($stmt->rowCount() == 0) {
return "";
}
$theValue = $row->setting;
if (is_null($theValue)) {
return "";
} else {
return $theValue;
}
}
public static function overruleTimeZone($timezone) {
self::$timezone = $timezone;
DbUtils::overruleTimeZone($timezone);
}
public function getTimeZone($pdo) {
if (is_null(self::$timezone)) {
$timezone = $this->getConfigItemsAsString($pdo, "timezone");
if ($timezone == "") {
$timezone = "Europe/Berlin";
}
return $timezone;
} else {
return self::$timezone;
}
}
public function getEnv($pdo) {
$installdate = $this->getConfigItemsAsString($pdo, "installdate");
$lastupdate = $this->getConfigItemsAsString($pdo, "lastupdate");
$version = $this->getConfigItemsAsString($pdo, "version");
return(array("version" => $version, "installdate" => $installdate, "lastupdate" => $lastupdate));
}
private function getWaiterSettings() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$userLoggedIn = $this->isUserAlreadyLoggedInForPhp();
if (!$userLoggedIn) {
$retVal = array("isUserLoggedIn" => 0);
echo json_encode($retVal);
return;
}
2020-11-19 22:58:42 +01:00
$configItems = join(",",array("'decpoint'","'version'","'cancelunpaidcode'","'tax'","'togotax'","'currency'","'workflowconfig'","'prominentsearch'","'discount1'","'discount2'","'discount3'","'waitergopayprint'"));
2020-11-19 22:47:44 +01:00
$sql = "select name,setting FROM %config% WHERE name in ($configItems)";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$configitems = $stmt->fetchAll();
$configresult = array();
foreach($configitems as $item) {
$configresult[$item["name"]] = $item["setting"];
}
$userlang = 0;
$right_changeprice = 0;
$supplyRight = 0;
if ($userLoggedIn) {
2020-11-19 22:53:50 +01:00
$sql = "SELECT language,right_supply,right_changeprice,keeptypelevel,extrasapplybtnpos FROM %user% WHERE id=?";
2020-11-19 22:48:24 +01:00
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($_SESSION['userid']));
$row = $stmt->fetchObject();
2020-11-19 22:47:44 +01:00
}
$buttonSizes = self::getButtonSizesCore($pdo);
$jsonMenuItems = $this->getJsonMenuItemsAndVersionCore();
$retVal = array("config" => $configresult,
2020-11-19 22:48:24 +01:00
"rightchangeprice" => $row->right_changeprice,
"supplyright" => $row->right_supply,
"userlanguage" => $row->language,
2020-11-19 22:47:44 +01:00
"buttonsizes" => $buttonSizes,
2020-11-19 22:48:24 +01:00
"keeptypelevel" => $row->keeptypelevel,
2020-11-19 22:53:50 +01:00
"extrasapplybtnpos" => $row->extrasapplybtnpos,
2020-11-19 22:47:44 +01:00
"isUserLoggedIn" => 1,
"jsonMenuItemsAndVersion" => $jsonMenuItems
);
echo json_encode($retVal);
}
public function getGeneralConfigItems($forHtml,$pdo) {
$userLoggedIn = $this->isUserAlreadyLoggedInForPhp();
if ($userLoggedIn || (!$forHtml)) {
$sql = "SELECT count(id) as number,setting FROM %config% WHERE name=?";
if (is_null($pdo)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
}
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array("companyinfo"));
$row = $stmt->fetchObject();
2020-11-19 22:58:39 +01:00
$companyInfo = $row->setting;
$stmt->execute(array("rectemplate"));
$row = $stmt->fetchObject();
$rectemplate = $row->setting;
2020-11-19 22:47:44 +01:00
$stmt->execute(array("decpoint"));
$row = $stmt->fetchObject();
$decpoint = $row->setting;
$stmt->execute(array("version"));
$row = $stmt->fetchObject();
$version = $row->setting;
$stmt->execute(array("payprinttype"));
$row = $stmt->fetchObject();
$payprinttype = $row->setting;
$stmt->execute(array("cancelunpaidcode"));
$row = $stmt->fetchObject();
$cancelunpaidcode = $row->setting;
$stmt->execute(array("tax"));
$row = $stmt->fetchObject();
$tax = $row->setting;
$stmt->execute(array("togotax"));
$row = $stmt->fetchObject();
$togotax = $row->setting;
$stmt->execute(array("serverurl"));
$row = $stmt->fetchObject();
$serverurl = $row->setting;
$stmt->execute(array("email"));
$row = $stmt->fetchObject();
$email = $row->setting;
2020-11-19 22:48:24 +01:00
$stmt->execute(array("bigfontworkreceipt"));
$row = $stmt->fetchObject();
$bigfontworkreceipt = $row->setting;
2020-11-19 22:52:25 +01:00
$stmt->execute(array("prominentsearch"));
$row = $stmt->fetchObject();
$prominentsearch = $row->setting;
2020-11-19 22:58:17 +01:00
$stmt->execute(array("discount1"));
$row = $stmt->fetchObject();
$discount1 = $row->setting;
$stmt->execute(array("discount2"));
$row = $stmt->fetchObject();
$discount2 = $row->setting;
$stmt->execute(array("discount3"));
$row = $stmt->fetchObject();
$discount3 = $row->setting;
$stmt->execute(array("austria"));
$row = $stmt->fetchObject();
$austria = $row->setting;
2020-11-19 22:58:36 +01:00
$stmt->execute(array("digigopaysetready"));
$row = $stmt->fetchObject();
$digigopaysetready = $row->setting;
if (is_null($digigopaysetready)) {
$digigopaysetready = 1;
}
2020-11-19 22:58:42 +01:00
$stmt->execute(array("waitergopayprint"));
$row = $stmt->fetchObject();
$waitergopayprint = $row->setting;
if (is_null($waitergopayprint)) {
$waitergopayprint = 0;
}
2020-11-19 22:58:17 +01:00
2020-11-19 22:53:50 +01:00
$stmt->execute(array("groupworkitems"));
$row = $stmt->fetchObject();
$groupworkitems = $row->setting;
if (is_null($groupworkitems)) {
$groupworkitems = 1;
}
2020-11-19 22:47:44 +01:00
// for update reasons check for null
$stmt->execute(array("receiveremail"));
$row = $stmt->fetchObject();
$receiveremail = "";
if (!is_null($row)) {
$receiveremail = $row->setting;
}
set_error_handler(function() { /* ignore errors */ });
try {
$stmt->execute(array("emailbadrating"));
$row = $stmt->fetchObject();
$emailbadrating = "";
if (!is_null($row)) {
$emailbadrating = $row->setting;
}
} catch (Exception $e) {
// in previous version this was not configurable
$emailbadrating = "";
}
try {
$stmt->execute(array("emailratingcontact"));
$row = $stmt->fetchObject();
$emailratingcontact = "";
if (!is_null($row)) {
$emailratingcontact = $row->setting;
}
} catch (Exception $e) {
// in previous version this was not configurable
$emailratingcontact = "";
}
restore_error_handler();
$stmt->execute(array("billlanguage"));
$row = $stmt->fetchObject();
$billlanguage = $row->setting;
$stmt->execute(array("currency"));
$row = $stmt->fetchObject();
$currency = $row->setting;
$stmt->execute(array("receiptfontsize"));
$row = $stmt->fetchObject();
$receiptfontsize = $row->setting;
$stmt->execute(array("reservationnote"));
$row = $stmt->fetchObject();
$reservationnote = $row->setting;
set_error_handler(function() { /* ignore errors */ });
$paymentconfig = $this->getConfigItemOrDefault("paymentconfig", $stmt, 0);
$workflowconfig = $this->getConfigItemOrDefault("workflowconfig", $stmt, 0);
$smtphost = "";
$smtpauth = 1;
$smtpuser = "";
$smtppass = "";
$smtpsecure = 1;
$smtpport = "";
if ($_SESSION['is_admin'] || $_SESSION['right_manager']) {
$smtphost = $this->getConfigItemOrDefault("smtphost",$stmt,"");
$smtpauth = $this->getConfigItemOrDefault("smtpauth",$stmt,1);
$smtpuser = $this->getConfigItemOrDefault("smtpuser",$stmt,"");
$smtppass = $this->getConfigItemOrDefault("smtppass",$stmt,"");
$smtpsecure = $this->getConfigItemOrDefault("smtpsecure",$stmt,1);
$smtpport = $this->getConfigItemOrDefault("smtpport",$stmt,"");
}
2020-11-19 22:58:20 +01:00
$paydeskid = $this->getConfigItemOrDefault("paydeskid",$stmt,"");
$aeskey = $this->getConfigItemOrDefault("aeskey",$stmt,"");
$certificatesn = $this->getConfigItemOrDefault("certificatesn", $stmt, "");
2020-11-19 22:47:44 +01:00
$webimpressum = $this->getConfigItemOrDefault("webimpressum",$stmt,"");
restore_error_handler();
$userlang = 0; // of no interest, if not called from web
$receiptprinter = 1; // of no interest, if not called from web
$right_changeprice = 0;
if ($userLoggedIn) {
$userlang = $_SESSION["language"];
$receiptprinter = $_SESSION['receiptprinter'];
$right_changeprice = ($_SESSION['right_changeprice'] ? 1 : 0);
}
date_default_timezone_set(DbUtils::getTimeZone());
$now = getdate();
2020-11-19 22:58:39 +01:00
$retVal = array("companyinfo" => $companyInfo, "rectemplate" => $rectemplate, "version" => $version, "decpoint" => $decpoint,
2020-11-19 22:47:44 +01:00
"serverurl" => $serverurl, "email" => $email, "receiveremail" => $receiveremail, "billlanguage" => $billlanguage,
"payprinttype" => $payprinttype, "tax" => $tax, "togotax" => $togotax, "currency" => $currency,
"userlanguage" => $userlang, "receiptprinter" => $receiptprinter,
"receiptfontsize" => $receiptfontsize, "reservationnote" => $reservationnote, "paymentconfig" => $paymentconfig,
"workflowconfig" => $workflowconfig, "emailratingcontact" => $emailratingcontact,"emailbadrating" => $emailbadrating,
2020-11-19 22:53:50 +01:00
"rightchangeprice" => $right_changeprice, "bigfontworkreceipt" => $bigfontworkreceipt, "prominentsearch" => $prominentsearch,"groupworkitems" => $groupworkitems,
2020-11-19 22:47:44 +01:00
"sday" => $now["mday"],"smonth" => $now["mon"], "syear" => $now["year"], "shour" => $now["hours"], "smin" => $now["minutes"],
"smtphost" => $smtphost,"smtpauth" => $smtpauth,"smtpuser" => $smtpuser,"smtppass" => $smtppass,"smtpsecure" => $smtpsecure,"smtpport" => $smtpport,
2020-11-19 22:58:17 +01:00
"webimpressum" => $webimpressum, "cancelunpaidcode" => $cancelunpaidcode, "discount1" => $discount1,"discount2" => $discount2,"discount3" => $discount3,
2020-11-19 22:58:42 +01:00
"austria" => $austria, "digigopaysetready" => $digigopaysetready, "waitergopayprint" => $waitergopayprint,
"paydeskid" => $paydeskid, "aeskey" => $aeskey, "certificatesn" => $certificatesn
2020-11-19 22:58:17 +01:00
);
2020-11-19 22:47:44 +01:00
if ($forHtml) {
echo json_encode(array("status" => "OK", "msg" => $retVal));
} else {
return $retVal;
}
} else {
if ($forHtml) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_NOT_AUTHOTRIZED, "msg" => ERROR_NOT_AUTHOTRIZED_MSG));
} else {
return null;
}
}
}
function getConfigItemOrDefault($item,$stmt,$default) {
try {
$stmt->execute(array($item));
$row = $stmt->fetchObject();
$ret = $default;
if ($row) {
if (($row->number) > 0) {
$ret = $row->setting;
} else {
$ret = $default;
}
}
} catch (Exception $e) {
$ret = $default;
}
return $ret;
}
function getViewAfterLogin() {
if ($this->isUserAlreadyLoggedInForPhp()) {
$userid = $_SESSION['userid'];
$rights = array($_SESSION['is_admin'],$_SESSION['right_waiter'],$_SESSION['right_kitchen'],
$_SESSION['right_bar'],$_SESSION['right_supply'],$_SESSION['right_paydesk'],
$_SESSION['right_statistics'],$_SESSION['right_bill'],$_SESSION['right_products'],
$_SESSION['right_reservation'],$_SESSION['right_changeprice'],$_SESSION['right_manager']);
$right_rating = $_SESSION['right_rating'];
if (self::isOnlyRatingUser($rights, $right_rating, true)) {
// rating user always goes into that view - important setting after creation of user
echo json_encode("rating.html");
return;
}
$sql = "SELECT lastmodule FROM %user% WHERE id=? AND active='1'";
$pdo = $this->dbutils->openDbAndReturnPdo();
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($userid));
$row =$stmt->fetchObject();
$view = "preferences.html";
if ($row != null) {
$newView = $row->lastmodule;
if ($newView != null) {
$view = $newView;
}
}
// test if user has still the right to go into that view
$mapping = array (
"waiter.html" => 'right_waiter',
"kitchen.html" => 'right_kitchen',
"bar.html" => 'right_bar',
"supplydesk.html" => 'right_supply',
"paydesk.html" => 'right_paydesk',
"reports.html" => 'right_statistics',
"bill.html" => 'right_bill',
"products.html" => 'right_products',
"reservation.html" => 'right_reservation',
"rating.html" => 'right_rating'
);
$valid = false;
2020-11-19 22:52:55 +01:00
if (($view == 'preferences.html') || ($view == 'feedback.html')) {
2020-11-19 22:47:44 +01:00
// always ok
$valid = true;
} else if ($view == 'manager.html') {
if (($_SESSION['is_admin'] == 1) || ($_SESSION['right_manager'] == 1)) {
$valid = true;
}
} else {
if (($view == "index.html") || ($_SESSION[$mapping[$view]] == 1)) {
$valid = true;
}
}
if ($valid == false) {
$view = "preferences.html";
}
echo json_encode($view);
}
}
// for client request
function isLoggedinUserAdmin() {
if ($this->isCurrentUserAdmin()) {
echo json_encode(YES);
} else {
echo json_encode(NO);
}
}
function isLoggedinUserAdminOrManager() {
if ($this->hasCurrentUserRight('is_admin') || $this->hasCurrentUserRight('right_manager')) {
echo json_encode(YES);
} else {
echo json_encode(NO);
}
}
function isLoggedinUserKitchen() {
if ($this->hasCurrentUserRight('right_kitchen')) {
echo json_encode(YES);
} else {
echo json_encode(NO);
}
}
function isLoggedinUserBar() {
if ($this->hasCurrentUserRight('right_bar')) {
echo json_encode(YES);
} else {
echo json_encode(NO);
}
}
function hasUserPaydeskRight() {
if ($this->hasCurrentUserRight('right_paydesk')) {
echo json_encode(YES);
} else {
echo json_encode(NO);
}
}
function hasUserReservationRight() {
if ($this->hasCurrentUserRight('right_reservation')) {
echo json_encode(YES);
} else {
echo json_encode(NO);
}
}
function hasCurrentUserRight($whichRight) {
if(session_id() == '') {
session_start();
}
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
// no user logged in
return false;
} else {
return ($_SESSION[$whichRight]);
}
}
// for internal request
function isCurrentUserAdmin() {
return $this->hasCurrentUserRight('is_admin');
}
2020-11-19 22:54:51 +01:00
function fillSampleContentBySqlFile($pdo,$sqlFile) {
2020-11-19 22:47:44 +01:00
$handle = fopen ($sqlFile, "r");
while (!feof($handle)) {
2020-11-19 22:54:51 +01:00
$sql = fgets($handle);
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
2020-11-19 22:47:44 +01:00
}
fclose ($handle);
}
private function fillSampleProdType($fileName) {
$speisekartenHandler = new TypeAndProductFileManager();
$speisekartenHandler->manageSpeisekarteFile($fileName);
$this->histfiller->readProdTableAndSendToHist();
}
private function assignTaxes($foodTax,$drinksTax) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$pdo->beginTransaction();
try {
if ($foodTax < 0) {
$foodTax = null;
} else {
$foodTax = str_replace(",",".",$foodTax);
}
if ($drinksTax < 0) {
$drinksTax = null;
} else {
$drinksTax = str_replace(",",".",$drinksTax);
}
$sql = "UPDATE %products%,%prodtype% SET %products%.tax=? WHERE %products%.category=%prodtype%.id AND %prodtype%.kind=? AND %products%.removed is null AND %prodtype%.removed is null";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($foodTax,0));
$stmt->execute(array($drinksTax,1));
$this->histfiller->readAllProdsAndFillHistByDb($pdo);
$pdo->commit();
echo json_encode (array("status" => "OK"));
} catch (Exception $e) {
$pdo->rollBack();
echo json_encode(array("status" => "ERROR", "code" => NUMBERFORMAT_ERROR, "msg" => NUMBERFORMAT_ERROR_MSG));
}
}
private function fillSpeisekarte($speisekarte) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$pdo->beginTransaction();
$ret = $this->fillSpeisekarteCore($pdo,$speisekarte);
if ($ret["status"] != "OK") {
$pdo->rollBack();
} else {
$pdo->commit();
}
echo json_encode($ret);
}
public function fillSpeisekarteCore($pdo,$speisekarte) {
$sql = "DELETE FROM %extrasprods%";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute();
$speisekartenHandler = new TypeAndProductFileManager();
$ret = $speisekartenHandler->manageSpeisekarte($pdo,$speisekarte);
if ($ret["status"] == "OK") {
$sorter = new Sorter();
$sorter->initSortCurrentProductTable($pdo);
}
return $ret;
}
private function fillSampleContent()
{
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
2020-11-19 22:47:44 +01:00
// first remove previous content, then fill the SQL file
$sql = "DELETE FROM `%queue%`";
2020-11-19 22:54:51 +01:00
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$this->fillSampleContentBySqlFile($pdo,"samples/queuecontent.txt");
2020-11-19 22:47:44 +01:00
$sql = "DELETE FROM `%hist%` WHERE action='3' OR action='7' OR action='8'";
2020-11-19 22:54:51 +01:00
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
2020-11-19 22:47:44 +01:00
$sql = "DELETE FROM `%histuser%`";
2020-11-19 22:54:51 +01:00
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
2020-11-19 22:47:44 +01:00
$sql = "DELETE FROM `%user%`";
2020-11-19 22:54:51 +01:00
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$this->fillSampleContentBySqlFile($pdo,"samples/usercontent.txt");
2020-11-19 22:47:44 +01:00
2020-11-19 22:54:51 +01:00
$this->histfiller->readUserTableAndSendToHist($pdo);
2020-11-19 22:47:44 +01:00
}
function getJsonMenuItemsAndVersion() {
echo json_encode($this->getJsonMenuItemsAndVersionCore());
}
/*
* Return all the entries for the main menu (the modules)
*/
private function getJsonMenuItemsAndVersionCore() {
if(session_id() == '') {
session_start();
}
$mainMenu = array();
$currentUser = "";
$waiterMessage = "";
$loggedIn = true;
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
// no user logged in
$mainMenu[] = array("name" => "Startseite", "link" => "index.html");
$loggedIn = false;
} else {
$lang = $_SESSION['language'];
$kitchentxt = array("K&uuml;che","Kitchen","Cocina");
$waitertxt = array("Kellner","Waiter","Camarero");
$paydesktxt = array("Kasse","Paydesk","Caja");
$settingtxt = array("Einstellungen","Preferences","Propriedades");
$admintxt = array("Verwaltung","Administration","Administrar");
$supplytxt = array("Bereitstellung","Supply desk","Preparado");
$prodtxt = array("Angebot","Products","Productos");
$restxt = array("Reservierung","Reservation","Reserva");
$bontxt = array("Kassenbons","Receipts","Tiques");
$stattxt = array("Statistik","Statistics","Estadisticas");
$ratingtxt = array("Bewertung","Rating","Valoración");
$logout = array("Abmelden","Log out","Adios");
$rights = array($_SESSION['is_admin'],$_SESSION['right_waiter'],$_SESSION['right_kitchen'],
$_SESSION['right_bar'],$_SESSION['right_supply'],$_SESSION['right_paydesk'],
$_SESSION['right_statistics'],$_SESSION['right_bill'],$_SESSION['right_products'],
$_SESSION['right_reservation'],$_SESSION['right_changeprice'],$_SESSION['right_manager']);
$right_rating = $_SESSION['right_rating'];
if (!self::isOnlyRatingUser($rights, $right_rating, true)) {
2020-11-19 22:58:42 +01:00
if ($_SESSION['right_waiter']) { $mainMenu[] = array("name" => $waitertxt[$lang], "link" => "waiter.html?v=1.1.29"); };
if ($_SESSION['right_kitchen']) { $mainMenu[] = array("name" => $kitchentxt[$lang], "link" => "kitchen.html?v=1.1.29"); };
if ($_SESSION['right_bar']) { $mainMenu[] = array("name" => "Bar", "link" => "bar.html?v=1.1.29"); };
if ($_SESSION['right_supply']) { $mainMenu[] = array("name" => $supplytxt[$lang], "link" => "supplydesk.html?v=1.1.29"); };
if ($_SESSION['right_paydesk']) { $mainMenu[] = array("name" => $paydesktxt[$lang], "link" => "paydesk.html?v=1.1.29"); };
if ($_SESSION['right_statistics']) { $mainMenu[] = array("name" => $stattxt[$lang], "link" => "reports.html?v=1.1.29"); };
if ($_SESSION['right_bill']) { $mainMenu[] = array("name" => $bontxt[$lang], "link" => "bill.html?v=1.1.29"); };
if ($_SESSION['right_products']) { $mainMenu[] = array("name" => $prodtxt[$lang], "link" => "products.html?v=1.1.29"); };
if ($_SESSION['right_reservation']) { $mainMenu[] = array("name" => $restxt[$lang], "link" => "reservation.html?v=1.1.29"); };
if ($_SESSION['right_rating']) { $mainMenu[] = array("name" => $ratingtxt[$lang], "link" => "rating.html?v=1.1.29"); };
if ($_SESSION['right_manager'] || $_SESSION['is_admin']) { $mainMenu[] = array("name" => $admintxt[$lang], "link" => "manager.html?v=1.1.29"); };
$mainMenu[] = array("name" => $settingtxt[$lang], "link" => "preferences.html?v=1.1.29");
$mainMenu[] = array("name" => "Feedback", "link" => "feedback.html?v=1.1.29");
2020-11-19 22:47:44 +01:00
}
$mainMenu[] = array("name" => $logout[$lang], "link" => "logout.php");
$currentUser = $_SESSION['currentuser'];
$waiterMessage = $this->getMessage(null, "waitermessage");
}
// CAUTION: change version also in config.txt!!!
2020-11-19 22:58:42 +01:00
$mainMenuAndVersion = array ("version" => "OrderSprinter 1.1.29",
2020-11-19 22:47:44 +01:00
"user" => $currentUser,
"menu" => $mainMenu,
"waitermessage" => $waiterMessage,
"loggedin" => ($loggedIn ? 1:0)
);
return($mainMenuAndVersion);
}
function getUserList() {
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT * FROM %user% WHERE active='1' ORDER BY is_admin";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result = $stmt->fetchAll();
echo json_encode($result);
2020-11-19 22:47:44 +01:00
}
function setTime($day,$month,$year,$hour,$min) {
if (!($this->userrights->hasCurrentUserRight('is_admin'))) {
echo json_encode (array("status" => "ERROR","msg" => "Benutzerrechte nicht ausreichend!"));
return false;
} else {
$txt = sprintf("%02d", $month) . sprintf("%02d", $day) . sprintf("%02d", $hour) . sprintf("%02d", $min) . $year = substr($year, -2);;
try {
if (substr(php_uname(), 0, 7) == "Windows"){
echo json_encode (array("status" => "ERROR","msg" => "Zeit auf Windows-Server kann nicht gesetzt werden!"));
return false;
}
else {
$cmd = "date \"$txt\"";
shell_exec($cmd . " > /dev/null &");
}
} catch(Exception $e) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_SCRIPT_NOT_EXECUTABLE, "msg" => ERROR_SCRIPT_NOT_EXECUTABLE_MSG));
}
$this->getGeneralConfigItems(true,null);
}
}
function createNewUser($username, $password, $isAdmin, $rWaiter, $rKitchen, $rBar, $rSupply, $rPayDesk, $rStat, $rBill, $rProducts, $rReservation, $rRating, $rChangeprice, $rManager) {
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT count(id) as countid FROM %user% WHERE active='1' AND username=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($username));
$row = $stmt->fetchObject();
if ($row->countid > 0) {
2020-11-19 22:47:44 +01:00
echo json_encode("exists");
return;
} else {
// create the new user
if(session_id() == '') {
session_start();
}
$lang = $_SESSION['language'];
if ($isAdmin && !($this->isCurrentUserAdmin())) {
echo json_encode("noadmin");
return;
2020-11-19 22:54:12 +01:00
} else {
2020-11-19 22:47:44 +01:00
// instead if password_hash (PHP > 5.5) use MD5...
$password_hash = md5($password);
2020-11-19 22:54:12 +01:00
$userInsertSql = "INSERT INTO `%user%` (`id` , `username` , `userpassword`, `is_admin`, `right_waiter`,`right_kitchen`,`right_bar`,`right_supply`,`right_paydesk`,`right_statistics`,`right_bill`,`right_products`,`right_reservation`,`right_rating`,`right_changeprice`,`right_manager`,`language`,`receiptprinter`,`prefertablemap`,`keeptypelevel`,`extrasapplybtnpos`,`active`) VALUES (";
2020-11-19 22:54:51 +01:00
$userInsertSql .= " NULL, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$stmt = $pdo->prepare(DbUtils::substTableAlias($userInsertSql));
2020-11-19 22:55:20 +01:00
$stmt->execute(array($username,$password_hash,$isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rReservation,$rRating,$rChangeprice,$rManager,$lang,1,1,0,1,1));
2020-11-19 22:54:51 +01:00
$lastId = $pdo->lastInsertId();
2020-11-19 22:47:44 +01:00
echo json_encode("OK");
}
}
// now this has to be logged in the history tables...
2020-11-19 22:54:51 +01:00
$this->histfiller->createUserInHist($pdo,$lastId,$username,
2020-11-19 22:47:44 +01:00
$isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rReservation,$rRating,$rChangeprice,$rManager);
}
function getPayPrintType() {
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
$this->sendJsonValueFromConfigTable($pdo,'payprinttype');
2020-11-19 22:47:44 +01:00
}
function getPayments() {
if(session_id() == '') {
session_start();
}
$pdo = $this->dbutils->openDbAndReturnPdo();
$lang = $_SESSION['language'];
$sql = "SELECT id,name FROM %payment%";
if ($lang == 1) {
$sql = "SELECT id,name_en as name FROM %payment%";
} else if ($lang == 2) {
$sql = "SELECT id,name_esp as name FROM %payment%";
}
$stmt_query = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt_query->execute();
$result = $stmt_query->fetchAll();
$retArray = array();
foreach($result as $row) {
$entry = array("id"=> $row['id'], "name" => $row['name']);
$retArray[] = $entry;
}
echo json_encode($retArray);
}
2020-11-19 22:54:51 +01:00
function sendJsonValueFromConfigTable($pdo,$whichValue) {
$theVal = $this->getValueFromConfigTable($pdo,$whichValue);
2020-11-19 22:47:44 +01:00
if ($theVal == null) {
echo json_encode("");
} else {
echo json_encode($theVal);
}
}
2020-11-19 22:54:51 +01:00
function getValueFromConfigTable($pdo,$whichValue) {
$sql = "SELECT count(id) as countid,setting FROM %config% WHERE name=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($whichValue));
$row = $stmt->fetchObject();
$numberOfEntries = $row->countid;
2020-11-19 22:47:44 +01:00
$theValue = null;
if ($numberOfEntries == 1) {
2020-11-19 22:54:51 +01:00
$theValue = $row->setting;
2020-11-19 22:47:44 +01:00
}
return $theValue;
}
private function deletelogo() {
$pdo = $this->dbutils->openDbAndReturnPdo();
$this->changeOneConfigDbItem($pdo, "logoimg", null,"%logo%",false);
echo json_encode("OK");
}
private function readlogo() {
if ($_FILES['logofile']['error'] != UPLOAD_ERR_OK //checks for errors
&& is_uploaded_file($_FILES['logofile']['tmp_name'])) { //checks that file is uploaded
header("Location: ../infopage.html?e=manager.html=Kann_Datei_nicht_laden.");
exit();
}
if(!file_exists($_FILES['logofile']['tmp_name']) || !is_uploaded_file($_FILES['logofile']['tmp_name'])) {
header("Location: ../infopage.html?e=manager.html=Datei_nicht_angegeben.");
exit();
}
$content = file_get_contents($_FILES['logofile']['tmp_name']);
if ($_FILES['logofile']['error'] != UPLOAD_ERR_OK //checks for errors
2020-11-19 22:52:55 +01:00
&& is_uploaded_file($_FILES['logofile']['tmp_name'])) { //checks that file is uploaded
2020-11-19 22:47:44 +01:00
header("Location: ../infopage.html?e=manager.html=Kann_Datei_nicht_laden.");
exit();
}
if (strlen($content) > 65535) {
header("Location: ../infopage.html?e=manager.html=Logobild_muss_kleiner_als_64_Kilobytes_sein!");
exit();
}
$pdo = $this->dbutils->openDbAndReturnPdo();
$this->changeOneConfigDbItem($pdo, "logoimg", $content,"%logo%",false);
header("Location: ../infopage.html?i=manager.html=Import_war_erfolgreich."); /* Browser umleiten */
exit;
}
function changeConfig($changedValues) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$assoc_vals = array(
"usstval" => array("dbcol" => "tax","checknum" => 1),
"togotaxval" => array("dbcol" => "togotax","checknum" => 1),
"stornocode" => array("dbcol" => "stornocode","checknum" => 0),
"printpass" => array("dbcol" => "printpass","checknum" => 0),
"companyinfo" => array("dbcol" => "companyinfo","checknum" => 0),
2020-11-19 22:58:39 +01:00
"rectemplate" => array("dbcol" => "rectemplate","checknum" => 0),
2020-11-19 22:47:44 +01:00
"serverUrl" => array("dbcol" => "serverurl","checknum" => 0),
"email" => array("dbcol" => "email","checknum" => 0),
"emailbadrating" => array("dbcol" => "emailbadrating","checknum" => 0),
"emailratingcontact" => array("dbcol" => "emailratingcontact","checknum" => 0),
"receiveremail" => array("dbcol" => "receiveremail","checknum" => 0),
"payprinttype" => array("dbcol" => "payprinttype","checknum" => 0),
"paymentconfig" => array("dbcol" => "paymentconfig","checknum" => 0),
2020-11-19 22:48:24 +01:00
"bigfontworkreceipt" => array("dbcol" => "bigfontworkreceipt","checknum" => 0),
2020-11-19 22:52:25 +01:00
"prominentsearch" => array("dbcol" => "prominentsearch","checknum" => 0),
2020-11-19 22:58:17 +01:00
"discount1" => array("dbcol" => "discount1","checknum" => 0),
"discount2" => array("dbcol" => "discount2","checknum" => 0),
"discount3" => array("dbcol" => "discount3","checknum" => 0),
"austria" => array("dbcol" => "austria","checknum" => 0),
2020-11-19 22:58:36 +01:00
"digigopaysetready" => array("dbcol" => "digigopaysetready","checknum" => 0),
2020-11-19 22:58:42 +01:00
"waitergopayprint" => array("dbcol" => "waitergopayprint","checknum" => 0),
2020-11-19 22:53:50 +01:00
"groupworkitems" => array("dbcol" => "groupworkitems","checknum" => 0),
2020-11-19 22:47:44 +01:00
"workflowconfig" => array("dbcol" => "workflowconfig","checknum" => 0),
"receiptfontsize" => array("dbcol" => "receiptfontsize","checknum" => 0),
"billlanguage" => array("dbcol" => "billlanguage","checknum" => 0),
"reservationnote" => array("dbcol" => "reservationnote","checknum" => 0),
"remoteaccesscode" => array("dbcol" => "remoteaccesscode","checknum" => 0),
"webimpressum" => array("dbcol" => "webimpressum","checknum" => 0),
"cancelunpaidcode" => array("dbcol" => "cancelunpaidcode","checknum" => 0),
"smtphost" => array("dbcol" => "smtphost","checknum" => 0),
"smtpauth" => array("dbcol" => "smtpauth","checknum" => 1),
"smtpuser" => array("dbcol" => "smtpuser","checknum" => 0),
"smtppass" => array("dbcol" => "smtppass","checknum" => 0),
"smtpsecure" => array("dbcol" => "smtpsecure","checknum" => 1),
"smtpport" => array("dbcol" => "smtpport","checknum" => 0),
2020-11-19 22:58:20 +01:00
"paydeskid" => array("dbcol" => "paydeskid","checknum" => 0),
"aeskey" => array("dbcol" => "aeskey","checknum" => 0),
"certificatesn" => array("dbcol" => "certificatesn","checksum" => 0)
2020-11-19 22:47:44 +01:00
);
$problem = false;
foreach ($changedValues as $aChangeSet) {
$name = $aChangeSet['name'];
$aVal = $aChangeSet['value'];
if ($name == "payprinttype") {
// special care: 1->l 2->s
if (((string)$aVal) == "1") {
$aVal = "l";
}
if (((string)$aVal) == "2") {
$aVal = "s";
}
}
if ($name == "remoteaccesscode") {
if (((string)$aVal) == "") {
$aVal = null;
} else {
$aVal = md5($aVal);
}
}
if ($name == "printpass") {
$aVal = md5($aVal);
}
$association = $assoc_vals[$name];
$dbcol = $association["dbcol"];
$check = $association["checknum"];
if ($check == 1) {
if (is_numeric($aVal)) {
$this->changeOneConfigDbItem($pdo,$dbcol,$aVal,"%config%",true);
} else {
$problem = true;
}
} else {
$this->changeOneConfigDbItem($pdo,$dbcol,$aVal,"%config%",true);
}
}
if ($problem) {
echo json_encode("FAILED");
} else {
echo json_encode("OK");
}
}
function changeOneConfigDbItem($pdo,$theItem,$theValue,$table,$doHist) {
// is the value already there, or has it to be created?
$sql = "SELECT setting from $table WHERE name=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($theItem));
$row = $stmt->fetchObject();
if ($stmt->rowCount() > 0) {
$sql = "UPDATE $table SET setting=? WHERE name=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($theValue,$theItem));
} else {
$sql = "INSERT INTO `$table` (`id` , `name`,`setting`) VALUES (NULL , ? , ?)";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($theItem,$theValue));
}
if ($doHist) {
// now this has to be logged in the history tables...
$this->histfiller->updateConfigInHist($pdo,$theItem, $theValue);
}
}
private function findActiveUserWithName($username) {
$sql_find_id = "SELECT id FROM %user% WHERE active='1' AND username='$username'";
$pdo = $this->dbutils->openDbAndReturnPdo();
$stmt_query = $pdo->query($this->dbutils->resolveTablenamesInSqlString($sql_find_id));
$row =$stmt_query->fetchObject();
$theUserId = $row->id;
return $theUserId;
}
function updateUser($theUserId, $isAdmin, $rWaiter, $rKitchen, $rBar, $rSupply, $rPayDesk, $rStat, $rBill, $rProducts, $rReservation, $rRat, $rChangeprice, $rManager) {
// get the name of the user
$pdo = $this->dbutils->openDbAndReturnPdo();
$sql = "SELECT username,is_admin FROM %user% WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($theUserId));
2020-11-19 22:54:51 +01:00
$row = $stmt->fetchObject();
2020-11-19 22:47:44 +01:00
$username = $row->username;
$userToModIsAdmin = $row->is_admin;
$doChangeAdminRights = false;
if ($isAdmin != $userToModIsAdmin) {
$doChangeAdminRights = true;
}
if ($doChangeAdminRights && !($this->isCurrentUserAdmin())) {
echo json_encode("noadmin");
} else {
$sql = "UPDATE %user% SET is_admin=?, right_waiter=?,right_kitchen=?,right_bar=?,right_supply=?,right_paydesk=?,right_statistics=?,right_bill=?,right_products=?,right_reservation=?,right_rating=?,right_changeprice=?,right_manager=? WHERE active='1' AND id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rReservation,$rRat,$rChangeprice,$rManager,$theUserId));
// now this has to be logged in the history tables...
2020-11-19 22:54:51 +01:00
$this->histfiller->updateUserInHist($pdo,$theUserId,$username,
2020-11-19 22:47:44 +01:00
$isAdmin,$rWaiter,$rKitchen,$rBar,$rSupply,$rPayDesk,$rStat,$rBill,$rProducts,$rReservation,$rRat,$rChangeprice,$rManager,'1');
echo json_encode("OK");
}
}
function deleteUser($theUserId) {
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT is_admin FROM %user% WHERE active='1' AND id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($theUserId));
$row =$stmt->fetchObject();
$userToDelIsAdmin = ($row->is_admin == 1 ? true : false);
2020-11-19 22:47:44 +01:00
if ($userToDelIsAdmin && !($this->isCurrentUserAdmin())) {
echo json_encode("noadmin");
} else {
2020-11-19 22:54:51 +01:00
$sql = "SELECT count(id) as countid FROM %user% WHERE active='1' AND is_admin='1' AND id <> ?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($theUserId));
$row = $stmt->fetchObject();
$numberOfOtherAdmins = $row->countid;
2020-11-19 22:47:44 +01:00
if (($numberOfOtherAdmins == 0) && $userToDelIsAdmin) {
echo json_encode("lastadmin");
} else {
2020-11-19 22:54:51 +01:00
$userSql = "UPDATE %user% set active='0' WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($userSql));
$stmt->execute(array($theUserId));
2020-11-19 22:47:44 +01:00
2020-11-19 22:54:51 +01:00
$this->histfiller->updateOneUser($pdo,$theUserId);
2020-11-19 22:47:44 +01:00
echo json_encode("OK");
}
}
}
function getCurrentUser() {
if(session_id() == '') {
session_start();
}
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
// no user logged in
echo json_encode("Nobody");
} else {
echo json_encode($_SESSION['currentuser']);
}
}
function changepassword($userid,$password) {
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT count(id) as countid, is_admin FROM %user% WHERE active='1' AND id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($userid));
$row = $stmt->fetchObject();
2020-11-19 22:47:44 +01:00
$userToChgPassIsAdm = false;
2020-11-19 22:54:51 +01:00
if ($row->countid == 1) {
if ($row->is_admin == 1) {
2020-11-19 22:47:44 +01:00
$userToChgPassIsAdm = true;
}
}
2020-11-19 22:54:51 +01:00
2020-11-19 22:47:44 +01:00
if(session_id() == '') {
session_start();
}
$otherUser = false;
if ($_SESSION['userid'] != $userid) {
$otherUser = true;
}
if ($otherUser && $userToChgPassIsAdm && !($this->isCurrentUserAdmin())) {
echo json_encode("noadmin");
} else {
$password_hash = md5($password);
2020-11-19 22:54:51 +01:00
$userSql = "UPDATE %user% set userpassword=? WHERE active='1' AND id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($userSql));
$stmt->execute(array($password_hash,$userid));
2020-11-19 22:47:44 +01:00
echo json_encode("OK");
}
}
function setUserLanguage($language) {
if(session_id() == '') {
session_start();
}
2020-11-19 22:54:51 +01:00
$currentuserid = $_SESSION['userid'];
2020-11-19 22:47:44 +01:00
$_SESSION['language'] = intval($language);
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "UPDATE %user% set language=? WHERE active='1' AND id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($language,$currentuserid));
2020-11-19 22:47:44 +01:00
echo json_encode("OK");
}
function setUserReceiptPrinter($printer) {
if(session_id() == '') {
session_start();
}
2020-11-19 22:54:51 +01:00
$currentuserid = $_SESSION['userid'];
2020-11-19 22:47:44 +01:00
$_SESSION['receiptprinter'] = intval($printer);
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "UPDATE %user% set receiptprinter=? WHERE active='1' AND id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($printer,$currentuserid));
2020-11-19 22:47:44 +01:00
echo json_encode("OK");
}
function setBtnSize($btn,$size) {
if(session_id() == '') {
session_start();
}
2020-11-19 22:54:51 +01:00
$currentuserid = $_SESSION['userid'];
2020-11-19 22:47:44 +01:00
$assoc = array ("0" => "roombtnsize","1" => "tablebtnsize","2" => "prodbtnsize");
$_SESSION[$assoc[$btn]] = intval($size);
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "UPDATE %user% set " . $assoc[$btn] . "=? WHERE active='1' AND id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($size,$currentuserid));
2020-11-19 22:47:44 +01:00
echo json_encode("OK");
}
function changeOwnPassword($oldpassword,$newpassword) {
if(session_id() == '') {
session_start();
}
$currentuser = $_SESSION['currentuser'];
$oldp_hash = md5($oldpassword);
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
2020-11-19 22:47:44 +01:00
$ok = true;
// is old password correct?
2020-11-19 22:54:51 +01:00
$sql = "SELECT count(id) as countid,userpassword FROM %user% WHERE username=? AND active='1'";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($currentuser));
$row = $stmt->fetchObject();
$numberOfEntries = $row->countid;
2020-11-19 22:47:44 +01:00
if ($numberOfEntries == 1) {
2020-11-19 22:54:51 +01:00
if ($row->userpassword != $oldp_hash) {
2020-11-19 22:47:44 +01:00
$ok = false;
}
} else {
// user not found
$ok = false;
2020-11-19 22:54:51 +01:00
}
2020-11-19 22:47:44 +01:00
if ($ok) {
// allowed to change password
$newp_hash = md5($newpassword);
2020-11-19 22:54:51 +01:00
$sql = "UPDATE %user% set userpassword=? WHERE active='1' AND username=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($newp_hash,$currentuser));
2020-11-19 22:47:44 +01:00
echo json_encode("OK");
} else {
echo json_encode("FAILED");
}
}
private function writeCsvHeader($defaultFilename) {
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=$defaultFilename");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
header("Expires: 0");
}
private function exportConfigCsv() {
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
2020-11-19 22:47:44 +01:00
$this->writeCsvHeader("datenexport-config.csv");
echo("Eintragsid; Datum ; Konfiguration; Wert;Beschreibung\n");
$sql = "SELECT DISTINCT %hist%.id as id,date,";
$sql .= "%config%.name as configitem,%histconfig%.setting as setting,description ";
$sql .= " FROM %hist%, %histconfig%, %histactions%, %config% ";
$sql .= " WHERE (refid=%histconfig%.id) ";
$sql .= " AND %histconfig%.configid = %config%.id ";
$sql .= " AND (action='2' OR action='6') ";
$sql .= " AND (action=%histactions%.id) ";
$sql .= " ORDER BY date,id";
2020-11-19 22:54:51 +01:00
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $zeile) {
2020-11-19 22:47:44 +01:00
$val1 = $zeile['id'];
$val2 = $zeile['date'];
$val3 = $zeile['configitem'];
$val4 = str_replace("\r\n","<CR>",$zeile['setting']);
$val4 = str_replace("\n","<CR>",$val4);
$val5 = $zeile['description'];
echo "$val1; $val2; \"$val3\"; \"$val4\"; \"$val5\"\n";
2020-11-19 22:54:51 +01:00
}
2020-11-19 22:47:44 +01:00
}
private function exportUserCsv() {
2020-11-19 22:54:51 +01:00
$pdo = DbUtils::openDbAndReturnPdoStatic();
2020-11-19 22:47:44 +01:00
$this->writeCsvHeader("datenexport-benutzer.csv");
echo("Eintragsid; Datum ; Benutzerid; Benutzername; Adminrechte; Kellnerrechte;Kuechenrechte; Barrechte; Bereitstellungsrechte; Kassenrechte; Reportrechte; Kassenbonrechte; Angebotsrechte; Beurteilungsrechte; Preisänderungsrechte; Managerrechte; Aktiviert\n");
$sql = "SELECT DISTINCT %hist%.id as id,date,";
$sql .= "userid,username,is_admin,right_waiter,right_kitchen,right_bar,right_supply,";
$sql .= "right_paydesk,right_statistics,right_bill,right_products,right_rating,right_changeprice,right_manager,active,";
$sql .= "description ";
$sql .= " FROM %hist%, %histuser%, %histactions% ";
$sql .= " WHERE (refid=%histuser%.id) ";
$sql .= " AND (action='3' OR action='7' OR action='8') ";
$sql .= " AND (action=%histactions%.id) ";
$sql .= " ORDER BY date,id";
2020-11-19 22:54:51 +01:00
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $zeile) {
2020-11-19 22:47:44 +01:00
$val1 = $zeile['id'];
$val2 = $zeile['date'];
$val3 = $zeile['userid'];
$val4 = $zeile['username'];
$val5 = ($zeile['is_admin'] == '1' ? "Ja" : "Nein");
$val6 = ($zeile['right_waiter'] == '1' ? "Ja" : "Nein");
$val7 = ($zeile['right_kitchen'] == '1' ? "Ja" : "Nein");
$val8 = ($zeile['right_bar'] == '1' ? "Ja" : "Nein");
$val9 = ($zeile['right_supply'] == '1' ? "Ja" : "Nein");
$val10 = ($zeile['right_paydesk'] == '1' ? "Ja" : "Nein");
$val11 = ($zeile['right_statistics'] == '1' ? "Ja" : "Nein");
$val12 = ($zeile['right_bill'] == '1' ? "Ja" : "Nein");
$val13 = ($zeile['right_products'] == '1' ? "Ja" : "Nein");
$val14 = ($zeile['right_rating'] == '1' ? "Ja" : "Nein");
$val15 = ($zeile['right_changeprice'] == '1' ? "Ja" : "Nein");
$val16 = ($zeile['right_manager'] == '1' ? "Ja" : "Nein");
$val17 = ($zeile['active'] == '1' ? "Ja" : "Nein");
$val18 = $zeile['description'];
echo "$val1; $val2; $val3; $val4; $val5; $val6; $val7; $val8; $val9; $val10;";
echo "$val11;$val12;$val13;$val14;$val15;$val16;$val17;$val18\n";
}
}
/**
* Create a temporary directory in PHP's temp folder
*/
private function createDirectoryInTemp($tmpFolder) {
$tmpFolder = trim($tmpFolder);
if ($tmpFolder == "") {
$tempfile=tempnam(sys_get_temp_dir(),'');
} else {
$tempfile=tempnam($tmpFolder,'');
}
if (is_null($tempfile) || ($tempfile== "")) {
return null;
}
if (file_exists($tempfile)) { unlink($tempfile); }
mkdir($tempfile);
if (is_dir($tempfile)) {
$tempfile = str_replace('\\','/',$tempfile);
return $tempfile;
} else {
return null;
}
}
private function getConfigTablesToBackupRestore() {
return array("logo","work","payment","room","resttables","tablepos","tablemaps","pricelevel","prodtype","products","config","user","comments","histprod","histconfig","histuser","histactions","hist","extras","extrasprods");
}
private function getAllTablesToBackupRestore() {
return array("closing","logo","printjobs","ratings","work","payment","room","resttables","tablepos","tablemaps","pricelevel","prodtype","products","config",
"user","reservations","bill","queue","billproducts","comments","histprod","histconfig","histuser","histactions","hist","extras","extrasprods","queueextras");
}
2020-11-19 22:55:09 +01:00
public function backup($theType,$remoteaccesscode) {
2020-11-19 22:47:44 +01:00
date_default_timezone_set(DbUtils::getTimeZone());
$nowtime = date('Y-m-d');
2020-11-19 22:51:46 +01:00
2020-11-19 22:47:44 +01:00
ini_set('memory_limit', '1000M');
$pdo = DButils::openDbAndReturnPdoStatic();
2020-11-19 22:55:09 +01:00
if ($theType == "auto") {
$sql = "SELECT count(id) as number,setting FROM %config% WHERE name=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array("remoteaccesscode"));
$row = $stmt->fetchObject();
if ($row->number == 0) {
echo "No remote access code available - backup not allowed";
return;
}
$code = $row->setting;
if (is_null($code) || (trim($code) == "")) {
echo "No remote access code set - backup not allowed";
return;
}
if ($code != md5($remoteaccesscode)) {
echo "Wrong remote access code used - backup not allowed";
return;
}
}
2020-11-19 22:47:44 +01:00
$pdo->beginTransaction();
2020-11-19 22:51:46 +01:00
$genInfo = $this->getGeneralConfigItems(false, $pdo);
$version = $genInfo["version"];
$fileName = "backup-" . $version . "_" . $nowtime . "-configuration.json";
if ($theType == "all") {
$fileName = "backup-" . $version . "_" . $nowtime . "-all.json";
}
2020-11-19 22:47:44 +01:00
if ($theType == "configuration") {
$tables = $this->getConfigTablesToBackupRestore();
} else {
$histFiller = new HistFiller();
$histFiller->insertSaveHistEntry($pdo);
$tables = $this->getAllTablesToBackupRestore();
}
$binaryFields = array("signature","img","setting","content");
$dbcontent = array();
foreach($tables as $table) {
$sql = "DESCRIBE %$table%";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$fields = $stmt->fetchAll(PDO::FETCH_COLUMN);
$fieldstr = implode(",",$fields);
$sql = "SELECT $fieldstr from %$table%";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result = $stmt->fetchAll();
$tableContent = array();
foreach($result as $row) {
$fieldContent = array();
foreach($fields as $field) {
if (in_array($field,$binaryFields)) {
$aFieldEntry = array("fieldname" => $field,"value" => base64_encode($row[$field]));
} else {
$aFieldEntry = array("fieldname" => $field,"value" => $row[$field]);
}
$fieldContent[] = $aFieldEntry;
};
$tableContent[] = $fieldContent;
}
$dbcontent[] = array("table" => $table, "content" => $tableContent);
}
$pdo->commit();
$retStr = json_encode($dbcontent);
ob_start();
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$fileName\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ". strlen($retStr));
echo $retStr;
ob_end_flush();
}
private function restore() {
2020-11-19 22:55:09 +01:00
ini_set('memory_limit', '1000M');
set_time_limit(60*5);
2020-11-19 22:47:44 +01:00
if ($_FILES['userfile']['error'] != UPLOAD_ERR_OK //checks for errors
&& is_uploaded_file($_FILES['userfile']['tmp_name'])) { //checks that file is uploaded
header("Location: ../infopage.html?e=manager.html=Kann_Datei_nicht_laden.");
exit();
}
2020-11-19 22:55:09 +01:00
if(!file_exists($_FILES['userfile']['tmp_name'])) {
header("Location: ../infopage.html?e=manager.html=Datei_existiert_nicht._Bitte_PHP-Variable_upload_max_filesize_checken.");
2020-11-19 22:47:44 +01:00
exit();
}
2020-11-19 22:55:09 +01:00
if(!is_uploaded_file($_FILES['userfile']['tmp_name'])) {
header("Location: ../infopage.html?e=manager.html=Datei_konnte_nicht_hochgeladen_werden.");
exit();
}
2020-11-19 22:47:44 +01:00
$binaryFields = array("signature","img","setting","content");
$content = file_get_contents($_FILES['userfile']['tmp_name']);
$basedb = new Basedb();
$basedb->setPrefix(TAB_PREFIX);
$basedb->setTimeZone(DbUtils::getTimeZone());
$pdo = DbUtils::openDbAndReturnPdoStatic();
$pdo->beginTransaction();
$genInfo = $this->getGeneralConfigItems(false, $pdo);
$version = $genInfo["version"];
$timezone = DbUtils::getTimeZone();
$basedb->dropTables($pdo);
$basedb->createEmptyTables($pdo);
$dbContent = json_decode($content,true);
$typeIsOnlyConfig = true;
foreach($dbContent as $table) {
$tablename = "%" . $table['table'] . "%";
$tablecontent = $table['content'];
if ($table['table'] == "queue") {
$typeIsOnlyConfig = false;
}
2020-11-19 22:51:46 +01:00
if ($table['table'] == "bill") {
$sql = "SET FOREIGN_KEY_CHECKS = 0";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
}
2020-11-19 22:47:44 +01:00
foreach($tablecontent as $row) {
$cols = array();
$vals = array();
$quests = array();
foreach ($row as $field) {
$fieldname = $field['fieldname'];
$cols[] = $fieldname;
if (in_array($fieldname, $binaryFields)) {
$vals[] = base64_decode($field['value']);
} else {
$vals[] = $field['value'];
}
$quests[] = '?';
}
$colstr = implode(",",$cols);
2020-11-19 22:51:46 +01:00
2020-11-19 22:47:44 +01:00
$queststr = implode(",",$quests);
$sql = "INSERT INTO $tablename ($colstr) VALUES ($queststr)";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute($vals);
}
2020-11-19 22:51:46 +01:00
if ($table['table'] == "bill") {
$sql = "SET FOREIGN_KEY_CHECKS = 1";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
}
2020-11-19 22:47:44 +01:00
}
if (!$typeIsOnlyConfig) {
$histFiller = new HistFiller();
$histFiller->insertRestoreHistEntry($pdo);
}
$basedb->signLastBillid($pdo);
$setVersion = "update %config% set setting=? where name='version'";
$stmt = $pdo->prepare($basedb->resolveTablenamesInSqlString($setVersion));
$stmt->execute(array($version));
2020-11-19 22:50:09 +01:00
2020-11-19 22:47:44 +01:00
$sql = "SELECT name FROM %config% WHERE name=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array("timezone"));
$row = $stmt->fetchObject();
if ($stmt->rowCount() == 0) {
$this->changeOneConfigDbItem($pdo, "timezone", $timezone, "%config%", true);
}
$pdo->commit();
2020-11-19 22:50:09 +01:00
2020-11-19 22:47:44 +01:00
// logout (by the restore other user or rights may have been applied)
if(session_id() == '') {
session_start();
}
$_SESSION = array();
// Swipe via memory
if (ini_get("session.use_cookies")) {
// Prepare and swipe cookies
$params = session_get_cookie_params();
// clear cookies and sessions
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
ini_set('session.gc_max_lifetime', 0);
ini_set('session.gc_probability', 1);
ini_set('session.gc_divisor', 1);
session_destroy();
header("Location: ../infopage.html?i=index.html=Import_war_erfolgreich."); /* Browser umleiten */
exit;
}
private function shutdown() {
try {
if (substr(php_uname(), 0, 7) == "Windows"){
$comd = "shutdown /s /t 10";
pclose(popen("start /B ". $cmd, "r"));
}
else {
chmod("shutdown.bat", "700");
$cmd = "sh < shutdown.bat";
exec($cmd . " > /dev/null &");
}
echo json_encode(array("status" => "OK"));
} catch(Exception $e) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_SCRIPT_NOT_EXECUTABLE, "msg" => ERROR_SCRIPT_NOT_EXECUTABLE_MSG));
}
}
}
?>