ordersprinter/webapp/php/admin.php

3603 lines
128 KiB
PHP

<?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/decimaldefs.php');
require_once ('utilities/sorter.php');
require_once ('utilities/Logger.php');
require_once ('utilities/Emailer.php');
require_once ('utilities/version.php');
require_once ('hotelinterface.php');
class Admin {
var $dbutils;
var $userrights;
var $histfiller;
private static $timezone = null;
private static $rights = array(
"createNewUser" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"createNewRole" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"updateUser" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"updateRole" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"deleteUser" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"deleteRole" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"changepassword" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"changeConfig" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"readlogo" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"deletelogo" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"getCurrentUser" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"tryAuthenticate" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"setLastModuleOfUser" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getViewAfterLogin" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"isUserAlreadyLoggedIn" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"isLoggedinUserAdmin" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"isLoggedinUserKitchen" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"isLoggedinUserBar" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"isLoggedinUserAdminOrManagerOrTE" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"hasUserPaydeskRight" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getJsonMenuItemsAndVersion" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"getUserList" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"getRoleList" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"setTime" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"changeOwnPassword" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setUserLanguage" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setUserReceiptPrinter" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setBtnSize" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getGeneralConfigItems" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getGeneralConfigItemsAndUsers" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getWaiterSettings" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getPayPrintType" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getPayments" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"autobackup" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"autoftpbackup" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"shutdown" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"optimize" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"ftpbackup" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"backup" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"restore" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"restoreDemoFromZip" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"golive" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"drop" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"fill" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"fillSpeisekarte" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"assignTaxes" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"getDbStat" => array("loggedin" => 1, "isadmin" => 1, "rights" => null),
"exportConfigCsv" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"exportUserCsv" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"exportLog" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"setOrderVolume" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setPreferTableMap" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setKeepTypeLevel" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setMobileTheme" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setApplyExtrasBtnPos" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setTablesAfterSend" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setPreferimgdesk" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setPreferimgmobile" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setPrefershowplusminus" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setPreferfixbtns" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"setPreferCalc" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getOrderVolume" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getButtonSizes" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getPreferTableMap" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getKeepTypeLevel" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getMobileTheme" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getApplyExtrasBtnPos" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getTablesAfterSend" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getPreferCalc" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getPreferimgdesk" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getPreferimgmobile" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getPrefershowplusminus" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getPreferfixbtns" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"isInstalled" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"isPrinterServerActive" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getWaiterMessage" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"getmobilecss" => array("loggedin" => 0, "isadmin" => 0, "rights" => null),
"getprinterinstances" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"setprinterinstances" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("manager_or_admin")),
"getdashreports" => array("loggedin" => 1, "isadmin" => 0, "rights" => array("dash")),
"getDailycode" => array("loggedin" => 1, "isadmin" => 0, "rights" => null),
"askforcompanyinfo" => array("loggedin" => 0, "isadmin" => 0, "rights" => null)
);
function __construct() {
$this->dbutils = new DbUtils();
$this->userrights = new Userrights();
$this->histfiller = new HistFiller();
}
private static function checkRights($command) {
if(session_id() == '') {
session_start();
}
if (!array_key_exists($command, self::$rights)) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_NOT_FOUND, "msg" => ERROR_COMMAND_NOT_FOUND_MSG));
return false;
}
$cmdRights = self::$rights[$command];
if ($cmdRights["loggedin"] == 1) {
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_NOT_AUTHOTRIZED, "msg" => ERROR_NOT_AUTHOTRIZED_MSG));
return false;
}
}
if ($cmdRights["isadmin"] == 1) {
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_NOT_AUTHOTRIZED, "msg" => ERROR_NOT_AUTHOTRIZED_MSG));
return false;
} else {
if ($_SESSION['is_admin'] == false) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_NOT_ADMIN, "msg" => ERROR_COMMAND_NOT_ADMIN_MSG));
return false;
}
}
}
if (!is_null($cmdRights["rights"])) {
foreach($cmdRights["rights"] as $aRight) {
if ($aRight == 'manager_or_admin') {
if (($_SESSION['is_admin']) || ($_SESSION['right_manager'])) {
return true;
}
} else if ($aRight == 'dash') {
if ($_SESSION['right_dash']) {
return true;
}
}
}
echo json_encode(array("status" => "ERROR", "code" => ERROR_NOT_AUTHOTRIZED, "msg" => ERROR_NOT_AUTHOTRIZED_MSG));
return false;
}
return true;
}
function handleCommand($command) {
if (!self::checkRights($command)) {
return false;
}
if ($command == 'tryAuthenticate') {
$this->tryAuthenticate($_POST['userid'],$_POST['password'],$_POST['modus'],$_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 == 'isLoggedinUserAdminOrManagerOrTE') {
$this->isLoggedinUserAdminOrManagerOrTE();
} else if ($command == 'hasUserPaydeskRight') {
$this->hasUserPaydeskRight();
} else if ($command == 'getJsonMenuItemsAndVersion') {
$this->getJsonMenuItemsAndVersion();
} else if ($command == 'getUserList') {
$this->getUserList();
} else if ($command == 'getRoleList') {
$this->getRoleList();
} else if ($command == 'setTime') {
$this->setTime($_POST['day'],$_POST['month'],$_POST['year'],$_POST['hour'],$_POST['minute']);
} else if ($command == 'createNewUser') {
$this->createNewUser();
} else if ($command == 'createNewRole') {
$this->createNewRole();
} else if ($command == 'updateUser') {
$this->updateUser();
} else if ($command == 'updateRole') {
$this->updateRole();
} else if ($command == 'deleteUser') {
$this->deleteUser($_POST['userid']);
} else if ($command == 'deleteRole') {
$this->deleteRole($_POST['roleid']);
} 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 == 'getGeneralConfigItemsAndUsers') {
$this->getGeneralConfigItemsAndUsers(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();
} else if ($command == 'autobackup') {
$this->backup('auto',$_POST['remoteaccesscode'],false);
} else if ($command == 'autoftpbackup') {
$this->ftpbackup('auto',$_POST['remoteaccesscode']);
} else if ($command == 'fill') {
$this->fillSampleContent();
echo json_encode(array("status" => "OK"));
} else if ($command == 'fillSpeisekarte') {
$this->fillSpeisekarte($_POST['speisekarte']);
} else if ($command == 'backup') {
$this->backup($_GET['type'],null,false);
return;
} else if ($command == 'ftpbackup') {
$this->ftpbackup($_GET['type'],null);
return;
} else if ($command == 'restore') {
$this->restore();
return;
} else if ($command == 'restoreDemoFromZip') {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$this->restoreDemoFromZip($pdo);
return;
} else if ($command == 'golive') {
$this->golive();
return;
} else if ($command == 'shutdown') {
$this->shutdown();
return;
} else if ($command == 'optimize') {
$this->optimize();
return;
} else if ($command == 'assignTaxes') {
$this->assignTaxes($_POST['food'],$_POST['drinks']);
return;
} 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 == 'exportLog') {
if ($this->isCurrentUserAdmin() || $this->hasCurrentUserRight('right_manager')) {
$this->exportLog();
}
} else if ($command == 'setOrderVolume') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setOrderVolume($_POST['volume']);
}
} else if ($command == 'setPreferTableMap') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setPreferTableMap($_POST['prefertablemap']);
}
} else if ($command == 'setPreferimgdesk') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setPreferimgdesk($_POST['preferredvalue']);
}
} else if ($command == 'setPreferimgmobile') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setPreferimgmobile($_POST['preferredvalue']);
}
} else if ($command == 'setPrefershowplusminus') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setShowplusminus($_POST['preferredvalue']);
}
} else if ($command == 'setPreferfixbtns') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setPreferfixbtns($_POST['preferredvalue']);
}
} else if ($command == 'setPreferCalc') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setPreferCalc($_POST['preferredvalue']);
}
} else if ($command == 'setKeepTypeLevel') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setKeepTypeLevel($_POST['keeptypelevel']);
}
} else if ($command == 'setMobileTheme') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setMobileTheme($_POST['mobiletheme']);
}
} else if ($command == 'setApplyExtrasBtnPos') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setExtrasApplyBtnPos($_POST['applyextrasbtnpos']);
}
} else if ($command == 'setTablesAfterSend') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->setTablesAfterSend($_POST['tablesaftersend']);
}
} 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();
}
} else if ($command == 'getPreferimgdesk') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getPreferimgdesk();
}
} else if ($command == 'getPreferimgmobile') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getPreferimgmobile();
}
} else if ($command == 'getPrefershowplusminus') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getShowplusminus();
}
} else if ($command == 'getPreferfixbtns') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getPreferfixbtns();
}
} else if ($command == 'getKeepTypeLevel') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getKeepTypeLevel();
}
} else if ($command == 'getmobilecss') {
$this->getmobilecss();
} else if ($command == 'getMobileTheme') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getMobileTheme();
}
} else if ($command == 'getApplyExtrasBtnPos') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getApplyExtrasBtnPos();
}
} else if ($command == 'getTablesAfterSend') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getTablesAfterSend();
}
} else if ($command == 'getPreferCalc') {
if ($this->isUserAlreadyLoggedInForPhp()) {
$this->getPreferCalc();
}
} else if ($command == 'isInstalled') {
$this->isInstalled();
} else if ($command == 'isPrinterServerActive') {
$this->isPrinterServerActive();
} else if ($command == 'getWaiterMessage') {
$this->getWaiterMessage();
} else if ($command == 'getDbStat') {
$this->getDbStat();
} else if ($command == 'getprinterinstances') {
$this->getPrinterInstances();
} else if ($command == 'setprinterinstances') {
$this->setprinterinstances($_POST["k1"],$_POST["k2"],$_POST["k3"],$_POST["k4"],$_POST["k5"],$_POST["k6"],$_POST["f1"],$_POST["f2"],$_POST["f3"],$_POST["f4"],$_POST["d1"],$_POST["d2"],$_POST["d3"],$_POST["d4"],$_POST["p1"]);
} else if ($command == 'getdashreports') {
$this->getdashreports();
} else if ($command == 'getDailycode') {
$this->getDailycode();
} else if ($command == 'askforcompanyinfo') {
self::askforcompanyinfo();
}
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 {
echo json_encode("No");
}
}
private function isPrinterServerActive() {
$active = json_encode(array("status" => "OK", "msg" => 1, "tasksforme" => $tasksForMe));
$notActive = json_encode(array("status" => "OK", "msg" => 0, "tasksforme" => $tasksForMe));
$pdo = DbUtils::openDbAndReturnPdoStatic(false);
if (is_null($pdo)) {
echo $notActive;
return;
}
Hotelinterface::hs3sync($pdo);
Guestsync::sync($pdo);
$tasksForMe = Tasks::areThereTasksForMe($pdo);
$TIMEOUT = 40;
// check printmode
$printMode = CommonUtils::getConfigValue($pdo, 'payprinttype', "s");
if ($printMode != "s") {
echo $active;
return;
}
$sql = "SELECT count(id) as countid FROM %work% WHERE item=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array('lastprtserveraccess'));
$row = $stmt->fetchObject();
if ($row->countid == 0) {
echo $notActive;
} else {
$sql = "SELECT value FROM %work% WHERE item=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array('lastprtserveraccess'));
$row = $stmt->fetchObject();
$lastaccess = $row->value;
date_default_timezone_set(DbUtils::getTimeZone());
$date = new DateTime();
$currentTimeStamp = $date->getTimestamp();
if (($currentTimeStamp - $lastaccess) > $TIMEOUT) {
echo $notActive;
} else {
echo $active;
}
}
}
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']) {
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;
}
}
function tryAuthenticate($userid,$password,$modus,$day,$month,$year,$hour,$minute,$unixtime) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$authenticated = false;
$isLoginAllowed = self::checkIsLoginAllowed($pdo,$userid);
if (!$isLoginAllowed) {
Logger::logcmd("admin","authentication","Login with id $userid failed");
echo json_encode(array("status" => "WAIT"));
return;
}
$sql = "SELECT *,%user%.id as id FROM %user%,%roles% WHERE %user%.id=? AND active='1' AND %user%.roleid=%roles%.id";
$result = CommonUtils::fetchSqlAll($pdo, $sql, array($userid));
$numberOfEntries = count($result);
if ($numberOfEntries == 1) {
$zeile = $result[0];
$pass_hash = $zeile['userpassword'];
if ($zeile['is_admin'] == 0) {
// authentication-check
}
// 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;
}
if(session_id() == '') {
session_start();
}
$username = $zeile["username"];
$_SESSION['angemeldet'] = true;
$_SESSION['userid'] = $zeile['id'];
$_SESSION['currentuser'] = $username;
$_SESSION['modus'] = $modus;
$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_customers'],$zeile['right_pickups'],$zeile['right_manager'],
$zeile['right_closing'],$zeile['right_dash'],$zeile['right_timetracking'],$zeile['right_timemanager'],
$zeile['right_tasks'],$zeile['right_tasksmanagement']);
$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_customers'] = false;
$_SESSION['right_pickups'] = false;
$_SESSION['right_manager'] = false;
$_SESSION['right_closing'] = false;
$_SESSION['right_dash'] = false;
$_SESSION['right_timetracking'] = false;
$_SESSION['right_timemanager'] = false;
$_SESSION['right_tasks'] = false;
$_SESSION['right_tasksmanagement'] = false;
$_SESSION['keeptypelevel'] = false;
} else {
$extendedPickupPermission = false;
if (($zeile['right_pickups'] == 1) && ( ($zeile['right_kitchen'] == 1) || ($zeile['right_bar'] == 1))) {
$extendedPickupPermission = true;
}
$_SESSION['right_extendedpickup'] = $extendedPickupPermission;
$_SESSION['is_admin'] = ($zeile['is_admin'] == 1 ? true : false);
$_SESSION['right_waiter'] = ($zeile['right_waiter'] == 1 ? true : false);
if (($workflow == 2) || ($workflow == 3)) {
$_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_customers'] = ($zeile['right_customers'] == 1 ? true : false);
$_SESSION['right_pickups'] = ($zeile['right_pickups'] == 1 ? true : false);
$_SESSION['right_manager'] = ($zeile['right_manager'] == 1 ? true : false);
$_SESSION['right_closing'] = ($zeile['right_closing'] == 1 ? true : false);
$_SESSION['right_dash'] = ($zeile['right_dash'] == 1 ? true : false);
$_SESSION['right_timetracking'] = ($zeile['right_timetracking'] == 1 ? true : false);
$_SESSION['right_timemanager'] = ($zeile['right_timemanager'] == 1 ? true : false);
$_SESSION['right_tasks'] = ($zeile['right_tasks'] == 1 ? true : false);
$_SESSION['right_tasksmanagement'] = ($zeile['right_tasksmanagement'] == 1 ? true : false);
$_SESSION['keeptypelevel'] = ($zeile['keeptypelevel'] == 1 ? true : false);
}
$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_customers'],$_SESSION['right_pickups'],$_SESSION['right_manager'], $_SESSION['right_closing'],
$_SESSION['right_dash'],$_SESSION['right_timetracking'],$_SESSION['right_timemanager']);
$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");
self::clearFailedLogins($pdo, $userid);
$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");
self::increaseFailedLogins($pdo,$userid);
echo json_encode(array("status" => "NO"));
}
}
private static function checkIsLoginAllowed($pdo,$userid) {
date_default_timezone_set(DbUtils::getTimeZone());
$now = getdate();
$serverTime = $now["0"];
$sql = "SELECT failedlogins FROM %user% WHERE id=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($userid));
if (is_null($row) || is_null($row->failedlogins)) {
return true;
} else {
$lastFailure = explode("_",$row->failedlogins)[0];
$attempt = intval(explode("_",$row->failedlogins)[1]);
if ($attempt >= 5) {
if (abs($serverTime - $lastFailure) > (60*3)) {
self::clearFailedLogins($pdo, $userid);
return true;
} else {
return false;
}
} else {
return true;
}
}
}
private static function increaseFailedLogins($pdo,$userid) {
date_default_timezone_set(DbUtils::getTimeZone());
$now = getdate();
$serverTime = $now["0"];
$lastFailure = (string) $serverTime . "_";
$sql = "SELECT failedlogins FROM %user% WHERE id=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($userid));
if (is_null($row) || is_null($row->failedlogins)) {
$lastFailure .= "1";
} else {
$attempt = intval(explode("_",$row->failedlogins)[1]);
$lastFailure .= ($attempt + 1);
}
$sql = "UPDATE %user% SET failedlogins=? WHERE id=?";
CommonUtils::execSql($pdo, $sql, array($lastFailure,$userid));
}
private static function clearFailedLogins($pdo,$userid) {
$sql = "UPDATE %user% SET failedlogins=? WHERE id=?";
CommonUtils::execSql($pdo, $sql, array(null,$userid));
}
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);
}
function getPreferimgdesk() {
self::getUserValue('preferimgdesk', 0);
}
function getPreferimgmobile() {
self::getUserValue('preferimgmobile', 0);
}
function getShowplusminus() {
echo json_encode(self::getUserValueAllowNull("showplusminus"));
}
function getPreferfixbtns() {
echo json_encode(self::getUserValueAllowNull("preferfixbtns"));
}
public static function getUserValueAllowNull($col) {
$userid = $_SESSION['userid'];
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT IFNULL($col,0) AS result FROM %user% WHERE id=?";
$row = CommonUtils::getRowSqlObject($pdo, $sql, array($userid));
$pdo = null;
return $row->result;
}
function getKeepTypeLevel() {
self::getUserValue('keeptypelevel',1);
}
private function getUsersMobileTheme($pdo) {
if (isset($_SESSION['userid'])) {
$userid = $_SESSION['userid'];
$sql = "SELECT mobiletheme FROM %user% WHERE id=?";
$res = CommonUtils::fetchSqlAll($pdo, $sql, array($userid));
if (count($res) > 0) {
return $res[0]["mobiletheme"];
} else {
return 0;
}
}
return 0;
}
function getmobilecss() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$mobileTheme = $this->getUsersMobileTheme($pdo);
$cssFile = "orderstyle.min.css";
$cssAppend = ".opentable { color:black;} .timeline { color:black;}";
$cssFile = "orderstyle.min.css";
if ($mobileTheme == 1) {
$cssFile = "orderstyle-pale.min.css";
$cssAppend = ".opentable { color:black;} .timeline { color:black;}";
$cssAppend .= "#tmpdirtxt,#tmpdirhint,#closingcreationtxt,#urlpath { color:black;}";
$cssAppend .= ".groundplan input[type=text] {color:black;}";
} else if ($mobileTheme == 2) {
$cssFile = "orderstyle-darksoul.min.css";
$cssAppend = ".opentable { color:white;} .timeline { color:black;}";
$cssAppend .= "#tmpdirtxt,#tmpdirhint,#closingcreationtxt,#urlpath { color:black;}";
$cssAppend .= ".groundplan input[type=text] {color:black;}";
}
$file = "3rdparty/orderstyle/$cssFile";
header('Content-type: text/css');
readfile($file);
echo $cssAppend;
}
function getMobileTheme() {
self::getUserValue('mobiletheme', 0);
}
function getApplyExtrasBtnPos() {
self::getUserValue('extrasapplybtnpos', 1);
}
function getTablesAfterSend() {
self::getUserValue('tablesaftersend', 1);
}
function getPreferCalc() {
self::getUserValue('calcpref', 1);
}
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) {
self::setUserValue('ordervolume', $volume);
}
function setPreferTableMap($preferValue) {
self::setUserValue('prefertablemap',$preferValue);
}
function setPreferimgdesk($preferValue) {
if ($preferValue == 0) {
$preferValue = null;
}
self::setUserValue('preferimgdesk',$preferValue);
}
function setPreferimgmobile($preferValue) {
if ($preferValue == 0) {
$preferValue = null;
}
self::setUserValue('preferimgmobile',$preferValue);
}
function setShowplusminus($preferValue) {
if ($preferValue == 0) {
$preferValue = null;
}
self::setUserValue('showplusminus',$preferValue);
}
function setPreferfixbtns($preferValue) {
if ($preferValue == 0) {
$preferValue = null;
}
self::setUserValue('preferfixbtns',$preferValue);
}
function setPreferCalc($preferValue) {
self::setUserValue('calcpref',$preferValue);
}
function setKeepTypeLevel($preferValue) {
self::setUserValue('keeptypelevel',$preferValue);
}
function setMobileTheme($preferValue) {
self::setUserValue('mobiletheme', $preferValue);
}
function setExtrasApplyBtnPos($preferValue) {
self::setUserValue('extrasapplybtnpos',$preferValue);
}
function setTablesAfterSend($preferValue) {
if ($preferValue == 1) {
$preferValue = null;
}
self::setUserValue('tablesaftersend',$preferValue);
}
function setLastModuleOfUser($view) {
if ($this->isUserAlreadyLoggedInForPhp()) {
if ($view != "logout.php") {
$userid = $_SESSION['userid'];
$questPos = strpos($view,'?');
if ($questPos != false) {
$view = substr($view,0,$questPos);
}
$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"));
} else {
echo json_encode(array("status" => "Error","msg" => "Benutzer nicht eingeloggt"));
}
}
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;
}
$configItems = join(",",array("'decpoint'","'version'","'cancelunpaidcode'","'tax'","'togotax'","'taxaustrianormal'","'taxaustriaerm1'","'taxaustriaerm2'","'taxaustriaspecial'","'currency'","'workflowconfig'","'prominentsearch'","'discount1'","'discount2'","'discount3'","'discountname1'","'discountname2'","'discountname3'","'waitergopayprint'","'cashenabled'","'returntoorder'","'restaurantmode'","'usebarcode'","'startprodsearch'","'priceinlist'","'showdaycode'","'dailycode'","'showtogo'","'billprintjobs'","'showtransferbtns'"));
$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) {
$sql = "SELECT language,right_supply,right_changeprice,keeptypelevel,extrasapplybtnpos,right_paydesk,IFNULL(preferimgdesk,0) as preferimgdesk,IFNULL(preferimgmobile,0) as preferimgmobile,IFNULL(showplusminus,0) as showplusminus,IFNULL(preferfixbtns,0) as preferfixbtns,IFNULL(tablesaftersend,1) as tablesaftersend FROM %user%,%roles% WHERE %user%.id=? AND %user%.roleid=%roles%.id";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($_SESSION['userid']));
$row = $stmt->fetchObject();
}
$buttonSizes = self::getButtonSizesCore($pdo);
$jsonMenuItems = $this->getJsonMenuItemsAndVersionCore($pdo);
$retVal = array("config" => $configresult,
"rightchangeprice" => $row->right_changeprice,
"rightpaydesk" => $row->right_paydesk,
"supplyright" => $row->right_supply,
"userlanguage" => $row->language,
"buttonsizes" => $buttonSizes,
"keeptypelevel" => $row->keeptypelevel,
"extrasapplybtnpos" => $row->extrasapplybtnpos,
"tablesaftersend" => $row->tablesaftersend,
"isUserLoggedIn" => 1,
"jsonMenuItemsAndVersion" => $jsonMenuItems,
"preferimgdesk" => $row->preferimgdesk,
"preferimgmobile" => $row->preferimgmobile,
"showplusminus" => $row->showplusminus,
"preferfixbtns" => $row->preferfixbtns
);
echo json_encode($retVal);
}
private function getGeneralConfigItemsAndUsers($forHtml,$pdo) {
return $this->getGeneralConfigItems($forHtml, $pdo, true);
}
public function getGeneralConfigItems($forHtml,$pdo,$includeUserInfo = false) {
$userLoggedIn = $this->isUserAlreadyLoggedInForPhp();
if ($userLoggedIn || (!$forHtml)) {
$items = array(
array("companyinfo",null,false),
array("hosttext",null,false),
array("rectemplate",null,false),
array("foodtemplate",null,false),
array("drinktemplate",null,false),
array("canceltemplate",null,false),
array("clostemplate",null,false),
array("pickuptemplate",null,false),
array("decpoint",null,false),
array("version",null,false),
array("payprinttype",null,false),
array("cancelunpaidcode",null,false),
array("cancelguestcode",null,false),
array("tax",null,false),
array("togotax",null,false),
array("taxaustrianormal",null,false),
array("taxaustriaerm1",null,false),
array("taxaustriaerm2",null,false),
array("taxaustriaspecial",null,false),
array("serverurl",null,false),
array("guesturl",null,false),
array("guestcode",null,false),
array("dailycode",null,false),
array("email",null,false),
array("bigfontworkreceipt",null,false),
array("prominentsearch",null,false),
array("guestjobprint",null,false),
array("askdaycode",null,false),
array("showdaycode",null,false),
array("asktablecode",null,false),
array("guesttimeout",5,false),
array("discount1",null,false),
array("discount2",null,false),
array("discount3",null,false),
array("austria",null,false),
array("digigopaysetready",1,false),
array("waitergopayprint",0,false),
array("oneprodworkrecf",0,false),
array("oneprodworkrecd",0,false),
array("digiprintwork",1,false),
array("groupworkitemsf",1,false),
array("groupworkitemsd",1,false),
array("receiveremail","",false),
array("smtpsecure",1,false),
array("smtpauth",1,false),
array("emailbadrating","",false),
array("emailratingcontact","",false),
array("billlanguage",null,false),
array("hotelinterface",0,false),
array("hsinfile",null,false),
array("hsoutfile",null,false),
array("hscurrency",null,false),
array("currency",null,false),
array("receiptfontsize",null,false),
array("reservationnote",null,false),
array("paymentconfig",0,false),
array("workflowconfig",0,false),
array("dashslot1",1,false),
array("dashslot2",2,false),
array("dashslot3",3,false),
array("addreceipttoprinter","",false),
array("printandqueuejobs",0,false),
array("cashenabled",1,false),
array("returntoorder",1,false),
array("beepcooked",0,false),
array("beepordered",0,false),
array("taskallassign",0,false),
array("taskifempty",0,false),
array("taskownerempty",0,false),
array("showtogo",1,false),
array("closshowci",1,false),
array("closshowpaytaxes",1,false),
array("closshowprods",1,false),
array("showpayments",1,false),
array("showpayment2",1,false),
array("showpayment3",1,false),
array("showpayment4",1,false),
array("showpayment5",1,false),
array("showpayment6",1,false),
array("showpayment7",1,false),
array("showpayment8",1,false),
array("restaurantmode",1,false),
array("usebarcode",0,false),
array("defaultview",0,false),
array("dblog",1,false),
array("showtransferbtns",1,false),
array("printpickups",0,false),
array("billprintjobs",2,false),
array("printextras",0,false),
array("forceprint",0,false),
array("priceinlist",0,false),
array("startprodsearch",3,false),
array("discountname1","",true),
array("discountname2","",true),
array("discountname3","",true),
array("memorylimit",256,false),
array("minbeforecome",0,false),
array("minaftergo",0,false),
array("updateurl","",false),
array("tmpdir","",false),
array("hs3refresh",60,false),
array("paydeskid","",false),
array("aeskey","",false),
array("cbirdfolder","",false),
array("certificatesn","",false),
array("rksvserver","",false),
array("webimpressum","",false),
array("showprepinwaiter",1,false),
array("pollbills",2,false),
array("pollworksf",2,false),
array("pollworksd",2,false),
array("pollclosings",2,false),
array("pollpickups",2,false),
array("showpickupsno",20,false),
array("showhostprint",1,false),
array("oneclickcooked",0,false),
array("showpickupdelbtn",1,false),
array("showpickhelp",1,false),
array("sumupforcard",0,false),
array("affiliatekey",'',true),
array("appid",'',true),
array("sumupfailuretext","",false),
array("printcash",0,false),
array("showerrorlog",1,false),
array("logolocation",1,false),
array("austriabind",0,false),
array("doublereceipt",0,false),
array("printextraprice",1,false)
);
if (is_null($pdo)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
}
$sql = "SELECT count(id) as countid FROM %config% WHERE name=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$retVal = array();
foreach($items as $anItem) {
$v = CommonUtils::getConfigValueStmt($pdo, $stmt, $anItem[0], $anItem[1]);
if ($anItem[2]) {
$v = trim($v);
}
$retVal[$anItem[0]] = $v;
}
$smtphost = "";
$smtpuser = "";
$smtppass = "";
$smtpport = "";
$ftphost = "";
$ftpuser = "";
$ftppass = "";
if ( (isset($_SESSION['is_admin']) && ($_SESSION['is_admin'] == 1)) || (isset($_SESSION['right_manager']) && ($_SESSION['right_manager']))) {
$smtphost = CommonUtils::getConfigValueStmt($pdo,$stmt,"smtphost","");
$smtpuser = CommonUtils::getConfigValueStmt($pdo,$stmt,"smtpuser","");
$smtppass = CommonUtils::getConfigValueStmt($pdo,$stmt,"smtppass","");
$smtpport = CommonUtils::getConfigValueStmt($pdo,$stmt,"smtpport","");
$ftphost = CommonUtils::getConfigValueStmt($pdo,$stmt,"ftphost","");
$ftpuser = CommonUtils::getConfigValueStmt($pdo,$stmt,"ftpuser","");
$ftppass = CommonUtils::getConfigValueStmt($pdo,$stmt,"ftppass","");
}
$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);
}
$defaultTmp = sys_get_temp_dir();
date_default_timezone_set(DbUtils::getTimeZone());
$now = getdate();
$retVal["userlanguage"] = $userlang;
$retVal["receiptprinter"] = $receiptprinter;
$retVal["rightchangeprice"] = $right_changeprice;
$retVal["sday"] = $now["mday"];
$retVal["smonth"] = $now["mon"];
$retVal["syear"] = $now["year"];
$retVal["shour"] = $now["hours"];
$retVal["smin"] = $now["minutes"];
$retVal["smtphost"] = $smtphost;
$retVal["smtpuser"] = $smtpuser;
$retVal["smtppass"] = $smtppass;
$retVal["smtpport"] = $smtpport;
$retVal["ftphost"] = $ftphost;
$retVal["ftpuser"] = $ftpuser;
$retVal["ftppass"] = $ftppass;
$retVal["defaulttmp"] = $defaultTmp;
$taskownerempty = $retVal["taskownerempty"];
if ($taskownerempty == "") {
$taskownerempty = 0;
}
if (is_null($taskownerempty)) {
$taskownerempty = 0;
}
$sql = "SELECT active FROM %user% WHERE id=?";
$result = CommonUtils::fetchSqlAll($pdo, $sql,array($taskownerempty));
if (count($result) > 0) {
$active = $result[0]["active"];
if ($active != 1) {
$taskownerempty = 0;
}
}
$retVal["taskownerempty"] = $taskownerempty;
if ($includeUserInfo) {
$sql = "SELECT U.id as id,username,is_admin,right_manager FROM %user% U,%roles% R WHERE active='1' ";
$sql .= " AND U.roleid=R.id AND (R.right_tasks=? OR R.right_tasksmanagement=?) ";
$sql .= " ORDER BY is_admin,right_manager";
$activeUsers = CommonUtils::fetchSqlAll($pdo, $sql,array(1,1));
$retVal["activeusers"] = $activeUsers;
}
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 getViewAfterLogin() {
if ($this->isUserAlreadyLoggedInForPhp()) {
$userid = $_SESSION['userid'];
$modus = $_SESSION['modus'];
$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_customers'],$_SESSION['right_pickups'],
$_SESSION['right_manager'],$_SESSION['right_closing'],$_SESSION['right_dash']);
$right_rating = $_SESSION['right_rating'];
if (self::isOnlyRatingUser($rights, $right_rating, true)) {
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;
if ($modus == 1) {
if ($view == "waiter.html") {
$view = "waiterdesktop.php";
} else if ($view == "paydesk.html") {
$view = "waiterdesktop.php";
}
} else {
if ($view == "waiterdesktop.php") {
$view = "waiter.html";
}
}
}
}
$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',
"customers.html" => 'right_customers',
"pickups.html" => 'right_pickups',
"waiterdesktop.php" => 'right_waiter',
"dash.php" => 'right_dash',
"timetracking.html" => 'right_timetracking',
"tasks.html" => 'right_tasks'
);
$valid = false;
if (($view == 'preferences.html') || ($view == 'feedback.html') || ($view == 'help.php')) {
$valid = true;
} else if ($view == 'manager.html') {
if (($_SESSION['is_admin']) || ($_SESSION['right_manager']) || ($_SESSION['right_closing'])) {
$valid = true;
}
} else {
if (($view == "index.html") || ($_SESSION[$mapping[$view]])) {
$valid = true;
}
}
if ($valid == false) {
$view = "preferences.html";
}
echo json_encode($view . "?v=1.5.28");
}
}
function isLoggedinUserAdmin() {
if ($this->isCurrentUserAdmin()) {
echo json_encode(YES);
} else {
echo json_encode(NO);
}
}
// public static function startsWith($txt,$key) {
// $ret = (substr($txt, 0, strlen($key)) === $key);
// return (substr($txt, 0, strlen($key)) === $key);
// }
function isLoggedinUserAdminOrManagerOrTE() {
if ($this->hasCurrentUserRight('is_admin')) {
echo json_encode("admin");
} else if ($this->hasCurrentUserRight('right_manager')) {
echo json_encode("manager");
} else if ($this->hasCurrentUserRight('right_closing')) {
echo json_encode("closing");
} 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']) {
return false;
} else {
return ($_SESSION[$whichRight]);
}
}
function isCurrentUserAdmin() {
return $this->hasCurrentUserRight('is_admin');
}
function fillSampleContentBySqlFile($pdo,$sqlFile) {
$handle = fopen ($sqlFile, "r");
while (!feof($handle)) {
$sql = fgets($handle);
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
}
fclose ($handle);
}
private function assignTaxes($foodTax,$drinksTax) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$pdo->beginTransaction();
try {
$sql = "UPDATE %products%,%prodtype% SET %products%.taxaustria=? 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));
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,$doCleanProdImages = true) {
$sql = "DELETE FROM %extrasprods%";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute();
$speisekartenHandler = new TypeAndProductFileManager();
$ret = $speisekartenHandler->manageSpeisekarte($pdo,$speisekarte);
if ($doCleanProdImages) {
Products::cleanProdImagesTable($pdo);
}
$basedb = new Basedb();
$basedb->sortProdTypes($pdo);
return $ret;
}
private function fillSampleContent()
{
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "DELETE FROM `%queue%`";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$this->fillSampleContentBySqlFile($pdo,"samples/queuecontent.txt");
$sql = "DELETE FROM `%hist%` WHERE action='3' OR action='7' OR action='8'";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$sql = "DELETE FROM `%histuser%`";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$sql = "DELETE FROM `%user%`";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$this->fillSampleContentBySqlFile($pdo,"samples/usercontent.txt");
$this->histfiller->readUserTableAndSendToHist($pdo);
}
function getJsonMenuItemsAndVersion() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
echo json_encode($this->getJsonMenuItemsAndVersionCore($pdo));
}
/*
* Return all the entries for the main menu (the modules)
*/
private function getJsonMenuItemsAndVersionCore($pdo) {
if(session_id() == '') {
session_start();
}
$mainMenu = array();
$currentUser = "";
$waiterMessage = "";
$loggedIn = true;
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
$mainMenu[] = array("name" => "Startseite", "link" => "index.html");
$loggedIn = false;
} else {
$lang = $_SESSION['language'];
$waiterdesktxt = array("Kellneransicht","Waiter's View","Vista de camareros");
$kitchentxt = array("K&uuml;che","Kitchen","Cocina");
$timetrackingtxt = array("Zeiterfassung","Time tracking","Tiempos");
$taskstxt = array("Aufgaben","Tasks","Tareas");
$waitertxt = array("Bestellung","Orderdesk","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");
$customerstxt = array("Gäste","Guests","Clientes");
$pickupstxt = array("Abholanzeige","Pickup display","Vista de recogidos");
$dashtxt = array("Dashboard","Dashboard","Dashboard");
$logout = array("Abmelden","Log out","Adios");
$restmode = CommonUtils::getConfigValue($pdo, "restaurantmode", 0);
if ($restmode == 0) {
$waiterdesktxt = array("Bestellung/Kasse","Orderdesk/Paydesk","Camarero");
}
$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_customers'],$_SESSION['right_pickups'],
$_SESSION['right_manager'],$_SESSION['right_closing'],$_SESSION['right_dash'],
$_SESSION['right_timetracking'],$_SESSION['right_timemanager'],
$_SESSION['right_tasks'],$_SESSION['right_tasksmanagement']);
$right_rating = $_SESSION['right_rating'];
if (!self::isOnlyRatingUser($rights, $right_rating, true)) {
if ($_SESSION['modus'] == 0) {
if ($_SESSION['right_waiter']) { $mainMenu[] = array("name" => $waitertxt[$lang], "link" => "waiter.html?v=1.5.28"); }
} else {
if ($_SESSION['right_waiter']) { $mainMenu[] = array("name" => $waiterdesktxt[$lang], "link" => "waiterdesktop.php?v=1.5.28"); }
}
if ($_SESSION['right_kitchen']) { $mainMenu[] = array("name" => $kitchentxt[$lang], "link" => "kitchen.html?v=1.5.28"); }
if ($_SESSION['right_bar']) { $mainMenu[] = array("name" => "Bar", "link" => "bar.html?v=1.5.28"); }
if ($_SESSION['right_supply']) { $mainMenu[] = array("name" => $supplytxt[$lang], "link" => "supplydesk.html?v=1.5.28"); }
if ($_SESSION['modus'] == 0) {
if ($_SESSION['right_paydesk']) { $mainMenu[] = array("name" => $paydesktxt[$lang], "link" => "paydesk.html?v=1.5.28"); }
}
if ($_SESSION['right_statistics']) { $mainMenu[] = array("name" => $stattxt[$lang], "link" => "reports.html?v=1.5.28"); }
if ($_SESSION['right_bill']) { $mainMenu[] = array("name" => $bontxt[$lang], "link" => "bill.html?v=1.5.28"); }
if ($_SESSION['right_products']) { $mainMenu[] = array("name" => $prodtxt[$lang], "link" => "products.html?v=1.5.28"); }
if ($_SESSION['right_reservation']) { $mainMenu[] = array("name" => $restxt[$lang], "link" => "reservation.html?v=1.5.28"); }
if ($_SESSION['right_tasks'] || $_SESSION['right_tasksmanagement']) { $mainMenu[] = array("name" => $taskstxt[$lang], "link" => "tasks.html?v=1.5.28"); }
if ($_SESSION['right_rating']) { $mainMenu[] = array("name" => $ratingtxt[$lang], "link" => "rating.html?v=1.5.28"); }
if ($_SESSION['right_customers']) { $mainMenu[] = array("name" => $customerstxt[$lang], "link" => "customers.html?v=1.5.28"); }
if ($_SESSION['right_pickups']) { $mainMenu[] = array("name" => $pickupstxt[$lang], "link" => "pickups.html?v=1.5.28"); }
if ($_SESSION['right_dash']) { $mainMenu[] = array("name" => $dashtxt[$lang], "link" => "dash.php?v=1.5.28"); }
if ($_SESSION['right_manager'] || $_SESSION['is_admin'] || $_SESSION['right_closing']) { $mainMenu[] = array("name" => $admintxt[$lang], "link" => "manager.html?v=1.5.28"); }
$mainMenu[] = array("name" => $settingtxt[$lang], "link" => "preferences.html?v=1.5.28");
if ($_SESSION['right_timetracking'] || $_SESSION['right_timemanager']) { $mainMenu[] = array("name" => $timetrackingtxt[$lang], "link" => "timetracking.html?v=1.5.28"); }
$mainMenu[] = array("name" => "Hilfe", "link" => "help.php?v=1.5.28");
$mainMenu[] = array("name" => "Feedback", "link" => "feedback.html?v=1.5.28");
}
$mainMenu[] = array("name" => $logout[$lang], "link" => "logout.php");
$currentUser = $_SESSION['currentuser'];
$waiterMessage = $this->getMessage(null, "waitermessage");
}
$installedVersion = CommonUtils::getConfigValue($pdo, 'version', '?');
$mainMenuAndVersion = array ("version" => "OrderSprinter $installedVersion",
"user" => $currentUser,
"menu" => $mainMenu,
"waitermessage" => $waiterMessage,
"loggedin" => ($loggedIn ? 1:0)
);
return($mainMenuAndVersion);
}
private function getPrinterInstances() {
try {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$k1 = CommonUtils::getConfigValue($pdo, 'k1prinstance', 1);
$k2 = CommonUtils::getConfigValue($pdo, 'k2prinstance', 1);
$k3 = CommonUtils::getConfigValue($pdo, 'k3prinstance', 1);
$k4 = CommonUtils::getConfigValue($pdo, 'k4prinstance', 1);
$k5 = CommonUtils::getConfigValue($pdo, 'k5prinstance', 1);
$k6 = CommonUtils::getConfigValue($pdo, 'k6prinstance', 1);
$f1 = CommonUtils::getConfigValue($pdo, 'f1prinstance', 1);
$f2 = CommonUtils::getConfigValue($pdo, 'f2prinstance', 1);
$f3 = CommonUtils::getConfigValue($pdo, 'f3prinstance', 1);
$f4 = CommonUtils::getConfigValue($pdo, 'f4prinstance', 1);
$d1 = CommonUtils::getConfigValue($pdo, 'd1prinstance', 1);
$d2 = CommonUtils::getConfigValue($pdo, 'd2prinstance', 1);
$d3 = CommonUtils::getConfigValue($pdo, 'd3prinstance', 1);
$d4 = CommonUtils::getConfigValue($pdo, 'd4prinstance', 1);
$p1 = CommonUtils::getConfigValue($pdo, 'p1prinstance', 1);
$ret = array("k1" => $k1,"k2" => $k2,"k3" => $k3, "k4" => $k4,"k5" => $k5,"k6" => $k6,"d1" => $d1,"d2" => $d2,"d3" => $d3,"d4" => $d4,"f1" => $f1,"f2" => $f2,"f3" => $f3,"f4" => $f4,"p1" => $p1);
echo json_encode(array("status" => "OK","msg" => $ret));
} catch (Exception $ex) {
echo json_encode(array("status" => "ERROR","msg" => "Error: " . $ex->getMessage()));
return;
}
}
private function setprinterinstances($k1,$k2,$k3,$k4,$k5,$k6,$f1,$f2,$f3,$f4,$d1,$d2,$d3,$d4,$p1) {
try {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "UPDATE %config% SET setting=? WHERE name=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($k1,"k1prinstance"));
$stmt->execute(array($k2,"k2prinstance"));
$stmt->execute(array($k3,"k3prinstance"));
$stmt->execute(array($k4,"k4prinstance"));
$stmt->execute(array($k5,"k5prinstance"));
$stmt->execute(array($k6,"k6prinstance"));
$stmt->execute(array($f1,"f1prinstance"));
$stmt->execute(array($f2,"f2prinstance"));
$stmt->execute(array($f3,"f3prinstance"));
$stmt->execute(array($f4,"f4prinstance"));
$stmt->execute(array($d1,"d1prinstance"));
$stmt->execute(array($d2,"d2prinstance"));
$stmt->execute(array($d3,"d3prinstance"));
$stmt->execute(array($d4,"d4prinstance"));
$stmt->execute(array($p1,"p1prinstance"));
echo json_encode(array("status" => "OK"));
} catch (Exception $ex) {
}
}
private function getdashreports() {
try {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$reports = new Reports();
$stat = $reports->getStatsCore($pdo,true);
echo json_encode(array("status" => "OK","msg" => array("stat" => $stat)));
} catch (Exception $ex) {
echo json_encode(array("status" => "ERROR","msg" => "Error: " . $ex->getMessage()));
return;
}
}
private function getDailycode() {
try {
$pdo = DbUtils::openDbAndReturnPdoStatic(false);
if (is_null($pdo)) {
echo json_encode(array("status" => "ERROR","msg" => "Error: " . $ex->getMessage()));
return;
}
$dailycode = CommonUtils::getConfigValue($pdo, 'dailycode', "");
echo json_encode(array("status" => "OK","msg" => $dailycode));
} catch (Exception $ex) {
echo json_encode(array("status" => "ERROR","msg" => "Error: " . $ex->getMessage()));
return;
}
}
private function getDbStat() {
try {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT table_name, round(sum( data_length + index_length ) / 1024) as tablesizeinmb FROM information_schema.TABLES ";
$sql .= " WHERE table_schema=? AND table_name like ? group by table_name order by table_name";
$result = CommonUtils::fetchSqlAll($pdo, $sql, array(MYSQL_DB,TAB_PREFIX . "%"));
$max = 0;
foreach ($result as $aTableResult) {
$size = intval($aTableResult["tablesizeinmb"]);
if ($max < $size) {
$max = $size;
}
}
echo json_encode(array("status" => "OK","msg" => array("max" => $max,"tablesizes" => $result)));
} catch (Exception $e) {
echo json_encode(array("status" => "ERROR","msg" => "Error: $e"));
return;
}
}
private function getWaiterMessage() {
try {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$waiterMessage = $this->getMessage(null, "waitermessage");
echo json_encode(array("status" => "OK","msg" => $waiterMessage));
} catch (Exception $e) {
echo json_encode(array("status" => "ERROR","msg" => "Error: $e"));
return;
}
}
private function getHotelInfo($pdo) {
try {
$hotelinterface = CommonUtils::getConfigValue($pdo, "hotelinterface", 0);
$guests = array();
if ($hotelinterface == 1) {
$sql = "SELECT reservationid,object,guest FROM %hsout%";
$guests = CommonUtils::fetchSqlAll($pdo, $sql, null);
}
return(array("status" => "OK","hotelinterface" => $hotelinterface,"guests" => $guests));
} catch (Exception $e) {
return(array("status" => "ERROR","hotelinterface" => 0,"guests" => array()));
}
}
private function getGuestInfo($pdo) {
try {
$sql = "SELECT %customers%.id as id,%customers%.id as object,CONCAT(IFNULL(name,''),' - ',IFNULL(room,'')) as guest ";
$sql .= " FROM %customers%,%vacations% ";
$sql .= " WHERE %customers%.id=%vacations%.customerid AND (";
$sql .= " ((checkin <= CURDATE()) AND (CURDATE() <= checkout)) ";
$sql .= " OR (checkin is null AND (CURDATE() <= checkout)) ";
$sql .= " OR ((checkin <= CURDATE()) AND checkout is null) ";
$sql .= ") GROUP BY id,object,guest";
$guests = CommonUtils::fetchSqlAll($pdo, $sql, null);
return(array("status" => "OK","guests" => $guests));
} catch (Exception $ex) {
return(array("status" => "ERROR"));
}
}
function getRoleList() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$roles = $this->getRoleListCore($pdo);
echo json_encode(array("status" => "OK","msg" => $roles));
}
function getRoleListCore($pdo) {
$sql = "SELECT * from %roles% ORDER BY is_admin,right_manager,right_waiter DESC,right_kitchen DESC,right_bar DESC,right_paydesk DESC,right_bill DESC,right_supply DESC,right_tasks DESC,right_tasksmanagement DESC";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $roles;
}
function getUserList() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT *,%user%.id as id,is_admin,right_manager,IFNULL(%user%.area,'0') as tablearea FROM %user%,%roles% WHERE active='1' AND %user%.roleid=%roles%.id ORDER BY is_admin,right_manager,right_waiter DESC,right_kitchen DESC,right_bar DESC,right_paydesk DESC,right_bill DESC,right_supply DESC,right_tasks DESC,right_tasksmanagement DESC,username";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
$roles = $this->getRoleListCore($pdo);
$defaultview = CommonUtils::getConfigValue($pdo, "defaultview", 0);
echo json_encode(array("users" => $users,"roles" => $roles,"defaultview" => $defaultview));
}
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 updateRole() {
if(session_id() == '') {
session_start();
}
$pdo = DbUtils::openDbAndReturnPdoStatic();
if (($_POST["isAdmin"] == 1) && (!$_SESSION['is_admin'])) {
echo json_encode(array("status" => "ERROR","msg" => "Nicht-Admins dürfen keine Rollen mit Admin-Rechten setzen!"));
return;
}
$roleid = $_POST["roleid"];
$roleIsAdmin = self::isRoleAdmin($pdo, $roleid);
if ($roleIsAdmin && !($this->isCurrentUserAdmin())) {
echo json_encode(array("status" => "ERROR","msg" => "Benutzer ist kein Admin und darf keine Admin-Rollen bearbeiten!"));
return;
}
$sql = "SELECT id FROM %user% WHERE roleid=? AND active='1'";
$effectedUsers = CommonUtils::fetchSqlAll($pdo, $sql, array($roleid));
$keys = array();
$vals = array();
foreach(DbUtils::$userCols as $userCol) {
if (!is_null($userCol["update"])) {
$key = $userCol["col"];
$keys[] = $key . "=?";
$vals[] = $_POST[$userCol["update"]];
}
}
$keys[] = "name=?";
$vals[] = $_POST["username"];
$vals[] = $roleid;
$keysStr = join(",",$keys);
$sql = "UPDATE %roles% SET " . $keysStr . " WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute($vals);
foreach( $effectedUsers as $aUser) {
$userid = $aUser["id"];
HistFiller::updateUserInHist($pdo, $userid);
}
echo json_encode(array("status" => "OK"));
}
function createNewRole() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$keys = array();
$vals = array();
$quests = array();
foreach(DbUtils::$userCols as $userCol) {
if (!is_null($userCol["new"])) {
$quests[] = '?';
$key = $userCol["col"];
if ($key == "username") {
$key = "name";
}
$keys[] = $key;
$vals[] = $_POST[$userCol['new']];
}
}
$keysStr = join(",",$keys);
$questsStr = join(",",$quests);
$sql = "INSERT INTO %roles% (" . $keysStr . ") VALUES(" . $questsStr . ")";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute($vals);
echo json_encode(array("status" => "OK"));
}
function createNewUser() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$username = $_POST['name'];
$password = $_POST['password'];
$roleid = $_POST['roleid'];
$area = $_POST['area'];
if ($area == 0) {
$area = null;
}
$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) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_NAME_EXISTS_ALREADY, "msg" => ERROR_NAME_EXISTS_ALREADY_MSG));
return;
} else {
if(session_id() == '') {
session_start();
}
$lang = $_SESSION['language'];
$roleIsAdmin = self::isRoleAdmin($pdo, $roleid);
if ($roleIsAdmin && !($this->isCurrentUserAdmin())) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_NOT_ADMIN, "msg" => ERROR_COMMAND_NOT_ADMIN_MSG));
return;
} else {
$password_hash = md5($password);
$sql = "INSERT INTO %user% (username,userpassword,roleid,area,language,showplusminus,keeptypelevel,extrasapplybtnpos,prefertablemap,preferimgdesk,preferimgmobile,active) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($username,$password_hash,$roleid,$area,$lang,1,1,1,1,1,1,1));
$lastId = $pdo->lastInsertId();
HistFiller::createUserInHist($pdo, $lastId);
echo json_encode(array("status" => "OK"));
}
}
}
function getPayPrintType() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$this->sendJsonValueFromConfigTable($pdo,'payprinttype');
}
function getPayments() {
if(session_id() == '') {
session_start();
}
$pdo = $this->dbutils->openDbAndReturnPdo();
$hotelinterface = CommonUtils::getConfigValue($pdo, "hotelinterface", 0);
$where = " WHERE id <> 7";
if ($hotelinterface != 0) {
$where = "";
}
$lang = $_SESSION['language'];
$sql = "SELECT id,name FROM %payment% $where";
if ($lang == 1) {
$sql = "SELECT id,name_en as name FROM %payment% $where";
} else if ($lang == 2) {
$sql = "SELECT id,name_esp as name FROM %payment% $where";
}
$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;
}
$hotelinfo = $this->getHotelInfo($pdo);
$internalguests = $this->getGuestInfo($pdo);
echo json_encode(array("payments" => $retArray, "hotelinterface" => $hotelinfo["hotelinterface"],"guests" => $hotelinfo["guests"],"internalguests" => $internalguests["guests"]));
}
function sendJsonValueFromConfigTable($pdo,$whichValue) {
$theVal = CommonUtils::getConfigValue($pdo, $whichValue, "");
if ($theVal == null) {
echo json_encode("");
} else {
echo json_encode($theVal);
}
}
private static function changeItemInTable($pdo,$theItem,$theValue,$theTable) {
$sql = "SELECT id FROM $theTable WHERE name=?";
$result = CommonUtils::fetchSqlAll($pdo, $sql, array($theItem));
if (count($result) == 0) {
$sql = "INSERT INTO $theTable (name,setting) VALUES(?,?)";
CommonUtils::execSql($pdo, $sql, array($theItem,$theValue));
} else {
$sql = "UPDATE $theTable SET setting=? WHERE name=?";
CommonUtils::execSql($pdo, $sql, array($theValue,$theItem));
}
}
private function deletelogo() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
self::changeItemInTable($pdo, "logoimg", null, "%logo%");
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();
}
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();
}
$pdo = DbUtils::openDbAndReturnPdoStatic();
$imageScaled = CommonUtils::scaleImg($_FILES['logofile']['tmp_name'], 300);
self::changeItemInTable($pdo, "logoimg", $imageScaled, "%logo%");
header("Location: ../infopage.html?i=manager.html=Import_war_erfolgreich."); /* Browser umleiten */
exit;
}
private static function returnInRange($aVal,$min,$max, $default) {
$aVal = trim($aVal);
if (!ctype_digit($aVal)) {
$aVal = $default;
}
$aVal = intval($aVal);
if (($aVal < $min) || ($aVal > $max)) {
$aVal = $default;
}
return $aVal;
}
function changeConfig($changedValues) {
$pdo = $this->dbutils->openDbAndReturnPdo();
$assoc_vals = array(
"usstval" => array("dbcol" => "tax","checknum" => 1),
"togotaxval" => array("dbcol" => "togotax","checknum" => 1),
"taxaustrianormalval" => array("dbcol" => "taxaustrianormal","checknum" => 1),
"taxaustriaerm1val" => array("dbcol" => "taxaustriaerm1","checknum" => 1),
"taxaustriaerm2val" => array("dbcol" => "taxaustriaerm2","checknum" => 1),
"taxaustriaspecialval" => array("dbcol" => "taxaustriaspecial","checknum" => 1),
"stornocode" => array("dbcol" => "stornocode","checknum" => 0),
"printpass" => array("dbcol" => "printpass","checknum" => 0),
"companyinfo" => array("dbcol" => "companyinfo","checknum" => 0),
"hosttext" => array("dbcol" => "hosttext","checknum" => 0),
"rectemplate" => array("dbcol" => "rectemplate","checknum" => 0),
"foodtemplate" => array("dbcol" => "foodtemplate","checknum" => 0),
"drinktemplate" => array("dbcol" => "drinktemplate","checknum" => 0),
"canceltemplate" => array("dbcol" => "canceltemplate","checknum" => 0),
"clostemplate" => array("dbcol" => "clostemplate","checknum" => 0),
"pickuptemplate" => array("dbcol" => "pickuptemplate","checknum" => 0),
"serverUrl" => array("dbcol" => "serverurl","checknum" => 0),
"guesturl" => array("dbcol" => "guesturl","checknum" => 0),
"guestcode" => array("dbcol" => "guestcode","checknum" => 0),
"dailycode" => array("dbcol" => "dailycode","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),
"addreceipttoprinter" => array("dbcol" => "addreceipttoprinter", "checknum" => 0),
"bigfontworkreceipt" => array("dbcol" => "bigfontworkreceipt","checknum" => 0),
"prominentsearch" => array("dbcol" => "prominentsearch","checknum" => 0),
"guestjobprint" => array("dbcol" => "guestjobprint","checknum" => 0),
"askdaycode" => array("dbcol" => "askdaycode","checknum" => 0),
"asktablecode" => array("dbcol" => "asktablecode","checknum" => 0),
"showdaycode" => array("dbcol" => "showdaycode","checknum" => 0),
"guesttimeout"=> array("dbcol" => "guesttimeout","checknum" => 0),
"discount1" => array("dbcol" => "discount1","checknum" => 0),
"discount2" => array("dbcol" => "discount2","checknum" => 0),
"discount3" => array("dbcol" => "discount3","checknum" => 0),
"austria" => array("dbcol" => "austria","checknum" => 0),
"digigopaysetready" => array("dbcol" => "digigopaysetready","checknum" => 0),
"waitergopayprint" => array("dbcol" => "waitergopayprint","checknum" => 0),
"oneprodworkrecf" => array("dbcol" => "oneprodworkrecf","checknum" => 0),
"oneprodworkrecd" => array("dbcol" => "oneprodworkrecd","checknum" => 0),
"digiprintwork" => array("dbcol" => "digiprintwork","checknum" => 0),
"groupworkitemsf" => array("dbcol" => "groupworkitemsf","checknum" => 0),
"groupworkitemsd" => array("dbcol" => "groupworkitemsd","checknum" => 0),
"workflowconfig" => array("dbcol" => "workflowconfig","checknum" => 0),
"dashslot1" => array("dbcol" => "dashslot1","checknum" => 0),
"dashslot2" => array("dbcol" => "dashslot2","checknum" => 0),
"dashslot3" => array("dbcol" => "dashslot3","checknum" => 0),
"receiptfontsize" => array("dbcol" => "receiptfontsize","checknum" => 0),
"billlanguage" => array("dbcol" => "billlanguage","checknum" => 0),
"hotelinterface" => array("dbcol" => "hotelinterface","checknum" => 0),
"hsinfile" => array("dbcol" => "hsinfile","checknum" => 0),
"hsoutfile" => array("dbcol" => "hsoutfile","checknum" => 0),
"hscurrency" => array("dbcol" => "hscurrency","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),
"cancelguestcode" => array("dbcol" => "cancelguestcode","checknum" => 0),
"printandqueuejobs" => array("dbcol" => "printandqueuejobs","checknum" => 0),
"cashenabled" => array("dbcol" => "cashenabled","checknum" => 0),
"returntoorder" => array("dbcol" => "returntoorder","checknum" => 0),
"beepcooked" => array("dbcol" => "beepcooked","checknum" => 0),
"beepordered" => array("dbcol" => "beepordered","checknum" => 0),
"taskallassign" => array("dbcol" => "taskallassign","checknum" => 0),
"taskifempty" => array("dbcol" => "taskifempty","checknum" => 0),
"taskownerempty" => array("dbcol" => "taskownerempty","checknum" => 0),
"showtogo" => array("dbcol" => "showtogo","checknum" => 0),
"showhostprint" => array("dbcol" => "showhostprint","checknum" => 0),
"oneclickcooked" => array("dbcol" => "oneclickcooked","checknum" => 0),
"showpickupdelbtn" => array("dbcol" => "showpickupdelbtn","checknum" => 0),
"showpickhelp" => array("dbcol" => "showpickhelp","checknum" => 0),
"closshowci" => array("dbcol" => "closshowci","checknum" => 0),
"closshowpaytaxes" => array("dbcol" => "closshowpaytaxes","checknum" => 0),
"closshowprods" => array("dbcol" => "closshowprods","checknum" => 0),
"showpayments" => array("dbcol" => "showpayments","checknum" => 0),
"showpayment2" => array("dbcol" => "showpayment2","checknum" => 0),
"showpayment3" => array("dbcol" => "showpayment3","checknum" => 0),
"showpayment4" => array("dbcol" => "showpayment4","checknum" => 0),
"showpayment5" => array("dbcol" => "showpayment5","checknum" => 0),
"showpayment6" => array("dbcol" => "showpayment6","checknum" => 0),
"showpayment7" => array("dbcol" => "showpayment7","checknum" => 0),
"showpayment8" => array("dbcol" => "showpayment8","checknum" => 0),
"restaurantmode" => array("dbcol" => "restaurantmode","checknum" => 0),
"usebarcode" => array("dbcol" => "usebarcode","checknum" => 0),
"defaultview" => array("dbcol" => "defaultview", "checknum" => 0),
"dblog" => array("dbcol" => "dblog","checknum" => 0),
"showtransferbtns" => array("dbcol" => "showtransferbtns","checknum" => 0),
"printpickups" => array("dbcol" => "printpickups","checknum" => 0),
"billprintjobs" => array("dbcol" => "billprintjobs","checknum" => 0),
"printextras" => array("dbcol" => "printextras","checknum" => 0),
"forceprint" => array("dbcol" => "forceprint","checknum" => 0),
"priceinlist" => array("dbcol" => "priceinlist","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),
"startprodsearch" => array("dbcol" => "startprodsearch","checknum" => 1),
"discountname1" => array("dbcol" => "discountname1","checknum" => 0),
"discountname2" => array("dbcol" => "discountname2","checknum" => 0),
"discountname3" => array("dbcol" => "discountname3","checknum" => 0),
"memorylimit" => array("dbcol" => "memorylimit","checknum" => 0),
"minbeforecome" => array("dbcol" => "minbeforecome","checknum" => 0),
"minaftergo" => array("dbcol" => "minaftergo","checknum" => 0),
"updateurl" => array("dbcol" => "updateurl","checknum" => 0),
"tmpdir" => array("dbcol" => "tmpdir","checknum" => 0),
"ftphost" => array("dbcol" => "ftphost","checknum" => 0),
"ftpuser" => array("dbcol" => "ftpuser","checknum" => 0),
"ftppass" => array("dbcol" => "ftppass","checknum" => 0),
"hs3refresh" => array("dbcol" => "hs3refresh","checknum" => 0),
"pollbills" => array("dbcol" => "pollbills","checknum" => 0),
"pollworksf" => array("dbcol" => "pollworksf","checknum" => 0),
"pollworksd" => array("dbcol" => "pollworksd","checknum" => 0),
"pollclosings" => array("dbcol" => "pollclosings","checknum" => 0),
"pollpickups" => array("dbcol" => "pollpickups","checknum" => 0),
"showpickupsno" => array("dbcol" => "showpickupsno","checknum" => 0),
"paydeskid" => array("dbcol" => "paydeskid","checknum" => 0),
"aeskey" => array("dbcol" => "aeskey","checknum" => 0),
"certificatesn" => array("dbcol" => "certificatesn","checksum" => 0),
"rksvserver" => array("dbcol" => "rksvserver","checksum" => 0),
"showprepinwaiter" => array("dbcol" => "showprepinwaiter","checksum" => 0),
"cbirdfolder" => array("dbcol" => "cbirdfolder","checknum" => 0),
"sumupforcard" => array("dbcol" => "sumupforcard","checknum" => 0),
"affiliatekey" => array("dbcol" => "affiliatekey","checknum" => 0),
"appid" => array("dbcol" => "appid","checknum" => 0),
"sumupfailuretext" => array("dbcol" => "sumupfailuretext","checknum" => 0),
"printcash" => array("dbcol" => "printcash","checknum" => 0),
"showerrorlog" => array("dbcol" => "showerrorlog","checknum" => 0),
"logolocation" => array("dbcol" => "logolocation","checknum" => 1),
"austriabind" => array("dbcol" => "austriabind","checknum" => 0),
"doublereceipt" => array("dbcol" => "doublereceipt","checknum" => 0),
"printextraprice" => array("dbcol" => "printextraprice","checknum" => 0)
);
$problem = false;
foreach ($changedValues as $aChangeSet) {
$name = $aChangeSet['name'];
$aVal = $aChangeSet['value'];
if ($name == "payprinttype") {
if (((string)$aVal) == "1") {
$aVal = "l";
}
if (((string)$aVal) == "2") {
$aVal = "s";
}
}
if ($name == 'addreceipttoprinter') {
if ((((string)$aVal) == "0") || (!is_numeric($aVal))) {
$aVal = null;
}
}
if ($name == "remoteaccesscode") {
if (((string)$aVal) == "") {
$aVal = null;
} else {
$aVal = md5($aVal);
}
}
if ($name == "printpass") {
$aVal = md5($aVal);
}
if ($name == "startprodsearch") {
if (is_numeric($aVal)) {
$aVal = round($aVal);
}
}
if ($name == "memorylimit") {
$aVal = trim($aVal);
if ($aVal != "-1") {
if (!ctype_digit($aVal)) {
$aVal = "256";
}
$aVal = intval($aVal);
if (($aVal < 64) || ($aVal > 65535)) {
$aVal = 256;
}
}
}
if (($name == "pollbills") || ($name == "pollworksf") || ($name == "pollworksd") || ($name == "pollclosings") || ($name == "pollpickups")) {
$aVal = self::returnInRange($aVal, 1, 30, 2);
}
if ($name == "showpickupsno") {
$aVal = self::returnInRange($aVal, 1, 200, 20);
}
if ($name == "minbeforecome") {
$aVal = trim($aVal);
if ($aVal != "-1") {
if (!ctype_digit($aVal)) {
$aVal = "0";
}
$aVal = intval($aVal);
if ($aVal < 0) {
$aVal = 0;
}
}
}
if ($name == "minaftergo") {
$aVal = trim($aVal);
if ($aVal != "-1") {
if (!ctype_digit($aVal)) {
$aVal = "0";
}
$aVal = intval($aVal);
if ($aVal < 0) {
$aVal = 0;
}
}
}
if ($name == "guesttimeout") {
if (is_numeric($aVal)) {
$aVal = round($aVal);
if ($aVal < 0) {
$aVal = 0;
}
} else {
$aVal = 5;
}
}
if (($name == "updateurl") || ($name == "tmpdir") || ($name == "ftphost") || ($name == "ftpuser") || ($name == "sumupfailuretext")) {
$aVal = trim($aVal);
}
if ($name == "hs3refresh") {
$aVal = trim($aVal);
if (!ctype_digit($aVal)) {
$aVal = "60";
}
$aVal = intval($aVal);
if ($aVal < 5) {
$aVal = 60;
}
}
$association = $assoc_vals[$name];
$dbcol = $association["dbcol"];
$check = $association["checknum"];
if ($check == 1) {
if (is_numeric($aVal)) {
$this->changeOneConfigDbItem($pdo,$dbcol,$aVal);
} else {
$problem = true;
}
} else {
$this->changeOneConfigDbItem($pdo,$dbcol,$aVal);
}
}
if (!$problem) {
echo json_encode(array("status" => "OK"));
} else {
echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_ERROR, "msg" => ERROR_COMMAND_ERROR_MSG));
}
}
function changeOneConfigDbItem($pdo,$theItem,$theValue) {
$histFiller = new HistFiller();
$histFiller->updateConfigInHist($pdo, $theItem, $theValue);
}
public static function isRoleAdmin($pdo,$roleid) {
$sql = "SELECT is_admin FROM %roles% WHERE id=?";
$is_admin_role = CommonUtils::getRowSqlObject($pdo, $sql, array($roleid));
return ($is_admin_role->is_admin == 1 ? true : false);
}
public static function isRoleOfUserAdmin($pdo,$userid) {
$sql = "SELECT roleid FROM %user% WHERE id=?";
$role = CommonUtils::getRowSqlObject($pdo, $sql, array($userid));
$roleid = $role->roleid;
return self::isRoleAdmin($pdo, $roleid);
}
function updateUser() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$theUserId = $_POST['userid'];
$username = $_POST['username'];
$roleid = $_POST['roleid'];
$area = $_POST['area'];
if ($area == 0) {
$area = null;
}
$is_admin_role = self::isRoleAdmin($pdo, $roleid);
$isRoleOfUserAdmin = self::isRoleOfUserAdmin($pdo, $theUserId);
if (!$this->isCurrentUserAdmin() && ($is_admin_role || $isRoleOfUserAdmin)) {
echo json_encode("noadmin");
} else {
$sql = "UPDATE %user% SET username=?,roleid=?,area=? WHERE id=?";
CommonUtils::execSql($pdo, $sql, array($username,$roleid,$area,$theUserId));
HistFiller::updateUserInHist($pdo,$theUserId);
echo json_encode("OK");
}
}
function deleteRole($roleid) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT id FROM %user% WHERE roleid=? AND active='1'";
$result = CommonUtils::fetchSqlAll($pdo, $sql, array($roleid));
if (count($result) > 0) {
echo json_encode(array("status" => "ERROR","msg" => "Rolle ist noch Benutzern zugewiesen!"));
} else {
$sql = "DELETE FROM %roles% WHERE id=?";
CommonUtils::execSql($pdo, $sql, array($roleid));
echo json_encode(array("status" => "OK"));
}
}
function deleteUser($theUserId) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$is_admin_role = self::isRoleOfUserAdmin($pdo, $theUserId);
if (!$this->isCurrentUserAdmin() && $is_admin_role) {
echo json_encode("noadmin");
} else {
$sql = "UPDATE %user% set active='0' WHERE id=?";
CommonUtils::execSql($pdo, $sql, array($theUserId));
HistFiller::updateUserInHist($pdo,$theUserId);
$sql = "UPDATE %user% set roleid=? WHERE id=?";
CommonUtils::execSql($pdo, $sql, array(null,$theUserId));
echo json_encode("OK");
}
}
function getCurrentUser() {
if (!isset($_SESSION['angemeldet']) || !$_SESSION['angemeldet']) {
echo json_encode("Nobody");
} else {
echo json_encode($_SESSION['currentuser']);
}
}
function changepassword($userid,$password) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "SELECT count(id) as countid FROM %user% WHERE active='1' AND id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($userid));
$row = $stmt->fetchObject();
if ($row->countid == 0) {
echo json_encode("ERROR");
return;
}
$userToChgPassIsAdm = self::isRoleOfUserAdmin($pdo, $userid);
$currentUserAdmin = $this->isCurrentUserAdmin();
if (!$currentUserAdmin && $userToChgPassIsAdm) {
echo json_encode("noadmin");
} else {
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);
$sql = "UPDATE %user% set userpassword=? WHERE active='1' AND id=?";
CommonUtils::execSql($pdo, $sql, array($password_hash,$userid));
echo json_encode("OK");
}
}
}
function setUserLanguage($language) {
if(session_id() == '') {
session_start();
}
$currentuserid = $_SESSION['userid'];
$_SESSION['language'] = intval($language);
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "UPDATE %user% set language=? WHERE active='1' AND id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($language,$currentuserid));
echo json_encode("OK");
}
function setUserReceiptPrinter($printer) {
if(session_id() == '') {
session_start();
}
$currentuserid = $_SESSION['userid'];
$_SESSION['receiptprinter'] = intval($printer);
$pdo = DbUtils::openDbAndReturnPdoStatic();
$sql = "UPDATE %user% set receiptprinter=? WHERE active='1' AND id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($printer,$currentuserid));
echo json_encode("OK");
}
function setBtnSize($btn,$size) {
if(session_id() == '') {
session_start();
}
$currentuserid = $_SESSION['userid'];
$assoc = array ("0" => "roombtnsize","1" => "tablebtnsize","2" => "prodbtnsize");
$_SESSION[$assoc[$btn]] = intval($size);
$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));
echo json_encode("OK");
}
function changeOwnPassword($oldpassword,$newpassword) {
if(session_id() == '') {
session_start();
}
$currentuser = $_SESSION['currentuser'];
$oldp_hash = md5($oldpassword);
$pdo = DbUtils::openDbAndReturnPdoStatic();
$ok = true;
$sql = "SELECT count(id) as countid FROM %user% WHERE username=? AND active='1'";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($currentuser));
$row = $stmt->fetchObject();
if ($row->countid == 0) {
echo json_encode("FAILED");
return;
}
$sql = "SELECT userpassword FROM %user% WHERE username=? AND active='1'";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($currentuser));
$row = $stmt->fetchObject();
if ($row->userpassword != $oldp_hash) {
$ok = false;
}
if ($ok) {
$newp_hash = md5($newpassword);
$sql = "UPDATE %user% set userpassword=? WHERE active='1' AND username=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($newp_hash,$currentuser));
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() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$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";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $zeile) {
$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";
}
}
private function exportLog() {
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=server.log");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Pragma: no-cache");
header("Expires: 0");
$pdo = DbUtils::openDbAndReturnPdoStatic();
echo CommonUtils::getLog($pdo);
}
private function exportUserCsv() {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$this->writeCsvHeader("datenexport-benutzer.csv");
echo("Eintragsid; Datum ; Benutzerid; Benutzername; Adminrechte; Kellnerrechte;Kuechenrechte; Barrechte; Bereitstellungsrechte; Kassenrechte; Reportrechte; Kassenbonrechte; Angebotsrechte; Beurteilungsrechte; Preisänderungsrechte; Gästerechte; Abholanzeige; Tageserfassungsrecht; Dashboardrechte; Zeiterfassung; Zeitmanagement; Aufgaben; Aufgabenmanagement; Managerrechte; Tischbereich; Aktiviert\n");
$sql = "SELECT DISTINCT %hist%.id as id,date,";
$sql .= "IFNULL(userid,'') as userid,IFNULL(username,'') as 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_customers,right_pickups,right_closing,right_dash,right_timetracking,right_timemanager,right_tasks,right_tasksmanagement,right_manager,active,";
$sql .= "IFNULL(area,'-') as area,";
$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";
$result = CommonUtils::fetchSqlAll($pdo, $sql,null);
foreach($result as $zeile) {
$vals = array();
$vals[] = $zeile['id'];
$vals[] = $zeile['date'];
$vals[] = $zeile['userid'];
$vals[] = $zeile['username'];
$vals[] = ($zeile['is_admin'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_waiter'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_kitchen'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_bar'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_supply'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_paydesk'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_statistics'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_bill'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_products'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_rating'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_changeprice'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_customers'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_pickups'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_closing'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_dash'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_timetracking'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_timemanager'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_tasks'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_tasksmanagement'] == '1' ? "Ja" : "Nein");
$vals[] = ($zeile['right_manager'] == '1' ? "Ja" : "Nein");
$area = $zeile["area"];
$character = $area;
if ($area != '-') {
$character = chr(intval($area) + 64);
}
$vals[] = $character;
$vals[] = ($zeile['active'] == '1' ? "Ja" : "Nein");
$vals[] = $zeile['description'];
$valsTxt = join(';', $vals);
echo "$valsTxt\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","prodimages","products","config","roles","user","comments","histprod","histconfig","histuser","histactions","hist","extras","extrasprods");
}
private function getConfigGuestsTablesToBackupRestore() {
return array("logo","work","payment","room","resttables","tablepos","tablemaps","pricelevel","prodtype","prodimages","products","config","roles","user","comments","histprod","histconfig","histuser","histactions","hist","extras","extrasprods","customers","groups","groupcustomer","vacations");
}
private function getAllTablesToBackupRestore() {
return array("closing","logo","printjobs","ratings","work","payment","room","resttables","tablepos","tablemaps","pricelevel","prodtype","prodimages","products","config",
"roles","user","reservations","customers","groups","groupcustomer","vacations","bill","customerlog","queue","times","records","recordsqueue","billproducts","hsin","hsout","comments","histprod","histconfig","histuser","histactions","hist",
"extras","extrasprods","queueextras","tasks","taskhist");
}
private function getAllWithLogsTablesToBackupRestore() {
return array("log","closing","logo","printjobs","ratings","work","payment","room","resttables","tablepos","tablemaps","pricelevel","prodtype","prodimages","products","config",
"roles","user","reservations","customers","groups","groupcustomer","vacations","bill","customerlog","queue","times","records","recordsqueue","billproducts","hsin","hsout","comments","histprod","histconfig","histuser","histactions","hist",
"extras","extrasprods","queueextras","tasks","taskhist");
}
public function ftpbackup($theType,$remoteaccesscode) {
if (!extension_loaded("ftp")) {
echo json_encode(array("status" => "ERROR","msg" => "PHP-Extension ftp ist nicht installiert"));
return;
}
$pdo = DbUtils::openDbAndReturnPdoStatic();
$ftphost = CommonUtils::getConfigValue($pdo, 'ftphost', '');
$ftpuser = CommonUtils::getConfigValue($pdo, 'ftpuser', '');
$ftppass = CommonUtils::getConfigValue($pdo, 'ftppass', '');
$pdo = null;
if (($ftphost == '') || ($ftpuser == '') || ($ftppass = '')) {
echo json_encode(array("status" => "ERROR","msg" => "Ftp-Verbindung wurde nicht konfiguriert"));
} else {
$ok = $this->backup($theType, $remoteaccesscode,true);
echo json_encode($ok);
}
}
private static function getKeysOfDataLine($dataline) {
$html = "<tr>";
$keys = array_keys($dataline);
foreach ($keys as $k) {
$html .= "<th>" . htmlspecialchars($k);
}
$html .= "</tr>";
return $html;
}
private static function showDataLineAsHtml($dataline) {
$html = "<tr>";
$keys = array_keys($dataline);
foreach ($keys as $k) {
$val = $dataline[$k];
if (!is_null($val)) {
$html .= "<td>" . htmlspecialchars($dataline[$k]);
} else {
$html .= "<td><i>NULL</i>";
}
}
$html .= "</tr>";
return $html;
}
private static function exportdebugdata() {
$pdo = DButils::openDbAndReturnPdoStatic();
$timeLimitedTables = array(
array('config',null,array('printpass','cancelguestcode','cancelunpaidcode','dailycode','ftppass','guestcode','remoteaccesscode','smtppass','stornocode'),null),
array('queue','ordertime',null,null),
array('bill','billdate',null,null),
array('closing','closingdate',null,null),
array('extras',null,null,null),
array('queueextras',null,null,100),
array('printjobs',null,null,null),
array('log','date',null,null));
$html = self::debugDataStyle();
foreach($timeLimitedTables as $t) {
$tablename = $t[0];
$datecol = $t[1];
$notins = $t[2];
$maxLines = $t[3];
$where = "";
$limit = "";
if (!is_null($datecol)) {
$where = " WHERE DATE(`$datecol`) >= ( CURDATE() - INTERVAL 2 DAY )";
}
if (!is_null($maxLines)) {
$limit = " ORDER BY id DESC LIMIT $maxLines";
}
$sql = "SELECT * from `%$tablename%` $where $limit";
$result = CommonUtils::fetchSqlAll($pdo, $sql);
$html .= "<h2>Tabelle " . htmlspecialchars($tablename) . ":</h2>";
if (count($result) > 0) {
$html .= "<table class='viewtable'>";
$html .= self::getKeysOfDataLine($result[0]);
foreach($result as $aLine) {
if (!is_null($notins)) {
if (in_array($aLine["name"],$notins)) {
continue;
}
}
$html .= self::showDataLineAsHtml($aLine);
}
$html .= "</table><p>";
}
}
echo $html;
}
private static function debugDataStyle() {
$css = "<style>" . file_get_contents(__DIR__ . "/../css/bestformat.css") . "</style>";
return $css;
}
public function backup($theType,$remoteaccesscode,$doFtp = false) {
if ($theType == "debugdata") {
self::exportdebugdata();
return;
}
set_time_limit(60*60);
date_default_timezone_set(DbUtils::getTimeZone());
$nowtime = date('Y-m-d');
$zipExtension = true;
if (!extension_loaded("zip")) {
$zipExtension = false;
}
$pdo = DButils::openDbAndReturnPdoStatic();
$tmpdir = CommonUtils::getConfigValue($pdo, 'tmpdir', '');
if ($theType == "auto") {
$code = CommonUtils::getConfigValue($pdo, 'remoteaccesscode', null);
if (is_null($code)) {
echo "No remote access code available - backup not allowed";
return;
}
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;
}
}
$pdo->beginTransaction();
$genInfo = $this->getGeneralConfigItems(false, $pdo);
$version = $genInfo["version"];
$extension = "json";
if (($tmpdir != '') && $zipExtension) {
$extension = "zip";
}
$fileName = "backup-" . $version . "_" . $nowtime . "-configuration.$extension";
if ($theType == "all") {
$fileName = "backup-" . $version . "_" . $nowtime . "-all.$extension";
} else if ($theType == "alllogs") {
$fileName = "backup-" . $version . "_" . $nowtime . "-all-logs.$extension";
} else if ($theType == "confandguests") {
$fileName = "backup-" . $version . "_" . $nowtime . "-guests.$extension";
}
if ($theType == "configuration") {
$tables = $this->getConfigTablesToBackupRestore();
} else if ($theType == "confandguests") {
$tables = $this->getConfigGuestsTablesToBackupRestore();
} else if (($theType == "all") || ($theType == "auto")) {
HistFiller::insertSaveHistEntry($pdo);
$tables = $this->getAllTablesToBackupRestore();
} else {
HistFiller::insertSaveHistEntry($pdo);
$tables = $this->getAllWithLogsTablesToBackupRestore();
}
$binaryFields = array("signature","img","setting","content");
$dbcontent = array();
$filenames = array();
foreach($tables as $table) {
set_time_limit(60*60);
$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(PDO::FETCH_ASSOC);
$tableContent = array();
foreach($result as $row) {
$fieldContent = array();
foreach($fields as $field) {
if (in_array($field,$binaryFields) && (!is_null($row[$field]))) {
$aFieldEntry = array("f" => $field,"v" => base64_encode($row[$field]));
} else {
$aFieldEntry = array("f" => $field,"v" => $row[$field]);
}
$fieldContent[] = $aFieldEntry;
};
$tableContent[] = $fieldContent;
}
if (($tmpdir == '') || !$zipExtension) {
$dbcontent[] = array("t" => $table, "c" => $tableContent);
} else {
try {
$tempfile=tempnam($tmpdir,"$table");
$contentToWrite = json_encode($tableContent);
$success = file_put_contents($tempfile, $contentToWrite);
if ($success == FALSE) {
echo "Fehler: Ist das PHP-Tmp-Verzeichnis richtig gesetzt?";
}
$filenames[] = array("table" => $table,"file" => $tempfile);
} catch (Exception $ex) {
echo "Fehler: " . $ex->getMessage() . " - Ist das PHP-Tmp-Verzeichnis richtig gesetzt?";
}
}
}
$pdo->commit();
if (($tmpdir == '') || !$zipExtension) {
$retStr = json_encode($dbcontent);
if ($doFtp) {
return $this->doFtp($pdo, $fileName, $retStr, null);
} else {
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();
}
} else {
$zipfile = tempnam($tmpdir,"zip");
$zip = new ZipArchive();
if ($zip->open($zipfile, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$zipfile>\n");
}
foreach($filenames as $afilename) {
$theTable = $afilename["table"];
$theFilename = $afilename["file"];
$str = file_get_contents($theFilename);
$substr = substr($str, 1,10);
$zip->addFile($theFilename,$theTable);
}
$zip->addFromString("version",$version);
$zip->close();
if ($doFtp) {
return $this->doFtp($pdo, $fileName, null,$zipfile);
} else {
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="'.basename($fileName).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($zipfile));
readfile($zipfile);
}
foreach($filenames as $afilename) {
unlink($afilename["file"]);
}
unlink($zipfile);
exit;
}
}
private function doFtp($pdo,$filename,$content,$zipfile) {
try {
$ftphost = CommonUtils::getConfigValue($pdo, 'ftphost', '');
$ftpuser = CommonUtils::getConfigValue($pdo, 'ftpuser', '');
$ftppass = CommonUtils::getConfigValue($pdo, 'ftppass', '');
$conn_id = ftp_connect($ftphost);
$login_result = ftp_login($conn_id, $ftpuser, $ftppass);
ftp_pasv($conn_id, true);
if ((!$conn_id) || (!$login_result)) {
return array("status" => "ERROR","msg" => "Ftp-Verbindung zum Server $ftphost konnte nicht hergestellt werden!");
}
if (is_null($zipfile)) {
$fp = fopen('php://temp', 'r+');
//fwrite($fp, $content);
fwrite($fp,$content);
rewind($fp);
$upload = ftp_fput($conn_id, $filename, $fp, FTP_BINARY);
} else {
$upload = ftp_put($conn_id, $filename, $zipfile, FTP_BINARY);
}
ftp_close($conn_id);
if (!$upload) {
return array("status" => "ERROR","msg" => "Ftp-Upload war nicht erfolgreich");
} else {
return array("status" => "OK");
}
} catch (Exception $ex) {
return array("status" => "ERROR","msg" => "Ftp-Upload war nicht erfolgreich: " . $ex->getMessage());
}
}
private function restore() {
set_time_limit(60*60);
if ($_FILES['userfile']['error'] != UPLOAD_ERR_OK //checks for errors
&& is_uploaded_file($_FILES['userfile']['tmp_name'])) { //checks that file is uploaded
echo json_encode(array("status" => "ERROR","msg" => "Kann Datei nicht laden."));
exit();
}
if(!file_exists($_FILES['userfile']['tmp_name'])) {
echo json_encode(array("status" => "ERROR","msg" => "Datei existiert nicht. Bitte PHP-Variablen upload_max_filesize und post_max_size_checken."));
exit();
}
if(!is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo json_encode(array("status" => "ERROR","msg" => "Datei konnte nicht hochgeladen werden."));
exit();
}
$zipExtension = true;
if (!extension_loaded("zip")) {
$zipExtension = false;
}
$origname = $_FILES['userfile']['name'];
$pdo = DbUtils::openDbAndReturnPdoStatic();
if (CommonUtils::strEndsWith($origname, '.zip')) {
if ($zipExtension) {
$zipFile = $_FILES['userfile']['tmp_name'];
$this->restoreFromZip($pdo,$zipFile);
} else {
echo json_encode(array("status" => "ERROR","msg" => "PHP-Zip-Extension ist nicht installiert."));
exit();
}
} else {
$content = file_get_contents($_FILES['userfile']['tmp_name']);
$this->restoreFromJson($pdo,$content);
}
}
private function getContextOfImportedJsonFile($dbContent) {
$tableKey = 'table';
$fieldKey = 'fieldname';
$contentKey = 'content';
$valueKey = 'value';
if (count($dbContent) > 0) {
$sampleTable = $dbContent[0];
if (isset($sampleTable['t'])) {
$fieldKey = 'f';
$contentKey = 'c';
$tableKey = 't';
$valueKey = 'v';
}
}
foreach($dbContent as $table) {
if ($table[$tableKey] == 'config') {
$foundConfigItem = null;
foreach($table[$contentKey] as $aConfigItem) {
foreach($aConfigItem as $aConfigDbPart) {
if (($aConfigDbPart[$fieldKey] == 'name') && ($aConfigDbPart[$valueKey] == 'version')) {
$foundConfigItem = $aConfigItem;
break;
}
}
}
if (!is_null($foundConfigItem)) {
foreach($foundConfigItem as $aConfigDbPart) {
if ($aConfigDbPart[$fieldKey] == 'setting') {
$bakVersion = base64_decode($aConfigDbPart[$valueKey]);
return array($bakVersion,$tableKey,$fieldKey,$contentKey,$valueKey);
}
}
}
}
}
return array("0",$tableKey,$fieldKey,$contentKey,$valueKey);
}
private function completeImportProcess($pdo) {
if(session_id() == '') {
session_start();
}
$_SESSION = array();
session_destroy();
// 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);
$ok = Version::runUpdateProcess($pdo, TAB_PREFIX, MYSQL_DB, null,false);
if ($ok["status"] != "OK") {
echo json_encode($ok);
return;
}
$sql = "SELECT name FROM %config% WHERE name=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array("timezone"));
$row = $stmt->fetchObject();
if ($stmt->rowCount() == 0) {
$timezone = DbUtils::getTimeZone();
$this->changeOneConfigDbItem($pdo, "timezone", $timezone);
}
echo json_encode(self::optimizeCore($pdo));
}
private function createTablesAndUpdateUntilVersion($pdo,$basedb,$version) {
$basedb->dropTables($pdo);
$basedb->createAndIntializeTables($pdo,'.',0,'Euro', DbUtils::getTimeZone());
Version::runUpdateProcess($pdo, TAB_PREFIX, MYSQL_DB, $version,false);
}
private function restoreDemoFromZip($pdo) {
// TO BE RELACED BY DEMO
}
private function restoreFromJson($pdo,$content) {
$binaryFields = array("signature","img","setting","content");
$basedb = new Basedb();
$basedb->setPrefix(TAB_PREFIX);
$basedb->setTimeZone(DbUtils::getTimeZone());
$pdo->beginTransaction();
$dbContent = json_decode($content,true);
$context = $this->getContextOfImportedJsonFile($dbContent);
$bakVersion = $context[0];
$tableKey = $context[1];
$fieldKey = $context[2];
$contentKey = $context[3];
$valueKey = $context[4];
if ((CommonUtils::startsWith($bakVersion, "1.0")) || (CommonUtils::startsWith($bakVersion, "1.1")) || (CommonUtils::startsWith($bakVersion, "1.2"))) {
echo json_encode(array("status" => "ERROR","msg" => "Backup hat eine zu frühe Version zum Import ($bakVersion)."));
exit();
}
$this->createTablesAndUpdateUntilVersion($pdo, $basedb, $bakVersion);
$typeIsOnlyConfig = true;
self::doSql($pdo, "SET foreign_key_checks = 0", null);
foreach($dbContent as $table) {
$tablename = "`%" . $table[$tableKey] . "%`";
$sql = "DELETE FROM $tablename";
CommonUtils::execSql($pdo, $sql, null);
$tablecontent = $table[$contentKey];
if ($table[$tableKey] == "queue") {
$typeIsOnlyConfig = false;
}
foreach($tablecontent as $row) {
set_time_limit(60*60);
$cols = array();
$vals = array();
$quests = array();
foreach ($row as $field) {
$fieldname = $field[$fieldKey];
$cols[] = $fieldname;
if (in_array($fieldname, $binaryFields) && (!is_null($field[$valueKey])) ) {
$vals[] = base64_decode($field[$valueKey]);
} else {
$vals[] = $field[$valueKey];
}
$quests[] = '?';
}
$colstr = implode(",",$cols);
$queststr = implode(",",$quests);
$sql = "INSERT INTO $tablename ($colstr) VALUES ($queststr)";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
try {
$stmt->execute($vals);
} catch (Exception $e) {
$errorMsg = $e->getMessage();
}
}
}
if (!$typeIsOnlyConfig) {
HistFiller::insertRestoreHistEntry($pdo);
}
$basedb->signLastBillid($pdo);
self::doSql($pdo, "SET foreign_key_checks = 1", null);
$pdo->commit();
$this->completeImportProcess($pdo);
}
private function restoreFromZip($pdo,$zipFile) {
$tmpdir = CommonUtils::getConfigValue($pdo, 'tmpdir', '');
if ($tmpdir == '') {
echo json_encode(array("status" => "ERROR","msg" => "Zip-Files können nur importiert werden, wenn ein PHP Temp. Directory konfiguriert ist."));
exit();
}
$zip = new ZipArchive;
$jsonFiles = array();
if ($zip->open($zipFile) == TRUE) {
for ($i = 0; $i < $zip->numFiles; $i++) {
$jsonFiles[] = $zip->getNameIndex($i);
}
$zip->extractTo($tmpdir, $jsonFiles);
$zip->close();
} else {
echo json_encode(array("status" => "ERROR","msg" => "Hochgeladenes Zip-File kann nicht geöffnet werden."));
exit();
}
$binaryFields = array("signature","img","setting","content");
$basedb = new Basedb();
$basedb->setPrefix(TAB_PREFIX);
$basedb->setTimeZone(DbUtils::getTimeZone());
$bakVersion = file_get_contents($tmpdir . "/version");
if ((CommonUtils::startsWith($bakVersion, "1.0")) || (CommonUtils::startsWith($bakVersion, "1.1")) || (CommonUtils::startsWith($bakVersion, "1.2"))) {
echo json_encode(array("status" => "ERROR","msg" => "Backup hat eine zu frühe Version zum Import ($bakVersion)."));
exit();
}
$pdo->beginTransaction();
$this->createTablesAndUpdateUntilVersion($pdo, $basedb, $bakVersion);
$typeIsOnlyConfig = true;
self::doSql($pdo, "SET foreign_key_checks = 0", null);
foreach($jsonFiles as $table) {
if ($table == "version") {
continue;
}
$tablename = "`%" . $table . "%`";
$sql = "DELETE FROM $tablename";
CommonUtils::execSql($pdo, $sql, null);
$tablecontent = json_decode(file_get_contents($tmpdir . "/" . $table),true);
if ($table == "queue") {
$typeIsOnlyConfig = false;
}
foreach($tablecontent as $row) {
set_time_limit(60*60);
$cols = array();
$vals = array();
$quests = array();
foreach ($row as $field) {
try {
$fieldname = $field['f'];
$cols[] = $fieldname;
if (in_array($fieldname, $binaryFields) && (!is_null($field['v']))) {
$vals[] = base64_decode($field['v']);
} else {
$vals[] = $field['v'];
}
$quests[] = '?';
} catch (Exception $ex) {
echo $ex->getMessage();
exit;
}
}
$colstr = implode(",",$cols);
$queststr = implode(",",$quests);
$sql = "INSERT INTO $tablename ($colstr) VALUES ($queststr)";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
try {
$stmt->execute($vals);
} catch (Exception $e) {
$errorMsg = $e->getMessage();
}
}
}
foreach($jsonFiles as $table) {
unlink($tmpdir . "/" . $table);
}
if (!$typeIsOnlyConfig) {
HistFiller::insertRestoreHistEntry($pdo);
}
self::doSql($pdo, "SET foreign_key_checks = 1", null);
$basedb->signLastBillid($pdo);
$pdo->commit();
$this->completeImportProcess($pdo);
}
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));
}
}
public static function optimizeCore($pdo) {
set_time_limit(60 * 20);
try {
self::doSql($pdo, "OPTIMIZE TABLE %queue%", null);
self::doSql($pdo, "OPTIMIZE TABLE %billproducts%", null);
self::doSql($pdo, "OPTIMIZE TABLE %products%", null);
self::doSql($pdo, "OPTIMIZE TABLE %prodimages%", null);
self::doSql($pdo, "OPTIMIZE TABLE %extrasprods%", null);
self::doSql($pdo, "OPTIMIZE TABLE %queueextras%", null);
self::doSql($pdo, "OPTIMIZE TABLE %log%", null);
self::doSql($pdo, "OPTIMIZE TABLE %roles%", null);
return array("status" => "OK");
} catch (Exception $ex) {
return array("status" => "ERROR", "code" => ERROR_COMMAND_ERROR, "msg" => ERROR_COMMAND_ERROR_MSG);
}
}
private function optimize() {
$pdo = DButils::openDbAndReturnPdoStatic();
$ok = self::optimizeCore($pdo);
echo json_encode($ok);
}
private static function getForeignKeyName($pdo,$fromtable,$totable,$dbname,$default = null) {
$foreignKey = null;
try {
$sql = "SELECT constraint_name as foreignkey FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE constraint_schema = '$dbname' AND table_name = '%$fromtable%' AND REFERENCED_TABLE_NAME='%$totable%'";
$test = DbUtils::substTableAlias($sql);
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) != 1) {
return $default;
}
$foreignKey = $result[0]["foreignkey"];
} catch (Exception $e) {
return $default;
}
return $foreignKey;
}
private function golive() {
set_time_limit(60*10);
$pdo = DButils::openDbAndReturnPdoStatic();
try {
$billprodref_fk = self::getForeignKeyName($pdo, 'billproducts', 'bill', MYSQL_DB);
$queuebillref_fk = self::getForeignKeyName($pdo, 'queue', 'bill', MYSQL_DB);
$queueclosingref_fk = self::getForeignKeyName($pdo, 'queue', 'closing', MYSQL_DB);
$billclosingref_fk = self::getForeignKeyName($pdo, 'bill', 'closing', MYSQL_DB);
$billbillref_fk = self::getForeignKeyName($pdo, 'bill', 'bill', MYSQL_DB);
$cuslogbillref_fk = self::getForeignKeyName($pdo, 'customerlog', 'bill', MYSQL_DB);
} catch (Exception $ex) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_ERROR, "msg" => ERROR_COMMAND_ERROR_MSG . " - impossible to get foreign keys: $e"));
}
try {
self::doSql($pdo, "DELETE FROM %taskhist%", null);
self::doSql($pdo, "DELETE FROM %tasks%", null);
self::doSql($pdo, "DELETE FROM %customerlog%", null);
self::doSql($pdo, "DELETE FROM %times%", null);
self::doSql($pdo, "DELETE FROM %recordsqueue%", null);
self::doSql($pdo, "DELETE FROM %records%", null);
self::doSql($pdo, "DELETE FROM %hist%", null);
self::doSql($pdo, "DELETE FROM %histprod%", null);
self::doSql($pdo, "DELETE FROM %histconfig%", null);
self::doSql($pdo, "DELETE FROM %histuser%", null);
HistFiller::readUserTableAndSendToHist($pdo);
$products = new Products();
$menu = $products->getSpeisekarte($pdo);
if ($menu['status'] != "OK") {
echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_ERROR, "msg" => ERROR_COMMAND_ERROR_MSG));
return;
} else {
self::doSql($pdo, "SET foreign_key_checks = 0;", null);
self::doSql($pdo, "DELETE FROM %queueextras%", null);
self::doSql($pdo, "DELETE FROM %extrasprods%", null);
self::doSql($pdo, "DELETE FROM %extras%", null);
self::doSql($pdo, "DELETE FROM %billproducts%", null);
self::doSql($pdo, "DELETE FROM %queue%", null);
self::doSql($pdo, "DELETE FROM %printjobs%", null);
self::doSql($pdo, "DELETE FROM %bill%", null);
self::doSql($pdo, "DELETE FROM %ratings%", null);
self::doSql($pdo, "DELETE FROM %closing%", null);
self::doSql($pdo, "SET foreign_key_checks = 1;", null);
$ret = $this->fillSpeisekarteCore($pdo, $menu['msg']);
self::doSql($pdo, "DELETE FROM %products% WHERE removed is not null", null);
self::doSql($pdo, "SET foreign_key_checks = 0;", null);
self::doSql($pdo, "DELETE FROM %prodtype% WHERE removed is not null", null);
self::doSql($pdo, "SET foreign_key_checks = 1;", null);
if ($ret["status"] != "OK") {
echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_ERROR, "msg" => ERROR_COMMAND_ERROR_MSG));
return;
}
HistFiller::readAllProdsAndFillHistByDb($pdo);
self::doSql($pdo, "DELETE w FROM %histprod% w INNER JOIN %hist% e ON refid=w.id WHERE action='4'", null);
self::doSql($pdo, "DELETE FROM %hist% where action='4'", null);
}
self::doSql($pdo, "alter table %bill% drop foreign key $billbillref_fk", null);
self::doSql($pdo, "alter table %customerlog% drop foreign key $cuslogbillref_fk", null);
self::doSql($pdo, "alter table %billproducts% drop foreign key $billprodref_fk", null);
self::doSql($pdo, "alter table %queue% drop foreign key $queuebillref_fk", null);
self::doSql($pdo, "alter table %queue% drop foreign key $queueclosingref_fk", null);
self::doSql($pdo, "ALTER TABLE %bill% DROP id", null);
self::doSql($pdo, "ALTER TABLE %bill% ADD id INT (10) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST", null);
self::doSql($pdo, "ALTER TABLE %bill% ADD CONSTRAINT $billbillref_fk FOREIGN KEY (ref) REFERENCES %bill%(id)", null);
self::doSql($pdo, "ALTER TABLE %customerlog% ADD CONSTRAINT $cuslogbillref_fk FOREIGN KEY (billid) REFERENCES %bill%(id)", null);
self::doSql($pdo, "ALTER TABLE %billproducts% ADD CONSTRAINT $billprodref_fk FOREIGN KEY (billid) REFERENCES %bill%(id)", null);
self::doSql($pdo, "ALTER TABLE %queue% ADD CONSTRAINT $queuebillref_fk FOREIGN KEY (billid) REFERENCES %bill%(id)", null);
self::doSql($pdo, "alter table %bill% drop foreign key $billclosingref_fk", null);
self::doSql($pdo, "ALTER TABLE %closing% DROP id", null);
self::doSql($pdo, "ALTER TABLE %closing% ADD id INT (10) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST", null);
self::doSql($pdo, "ALTER TABLE %bill% ADD CONSTRAINT $billclosingref_fk FOREIGN KEY (closingid) REFERENCES %closing%(id)", null);
self::doSql($pdo, "ALTER TABLE %queue% ADD CONSTRAINT $queueclosingref_fk FOREIGN KEY (clsid) REFERENCES %closing%(id)", null);
$basedb = new Basedb();
$basedb->setPrefix(TAB_PREFIX);
$basedb->setTimeZone(DbUtils::getTimeZone());
$basedb->signLastBillid($pdo);
$histFiller = new HistFiller();
$histFiller->readConfigTableAndSendToHist();
self::doSql($pdo, "DELETE FROM %resttables% WHERE removed is not null", null);
self::doSql($pdo, "DELETE FROM %room% WHERE removed is not null", null);
self::doSql($pdo, "DELETE FROM %reservations%", null);
self::doSql($pdo, "DELETE FROM %groupcustomer%", null);
self::doSql($pdo, "DELETE FROM %vacations%", null);
self::doSql($pdo, "DELETE FROM `%groups%`", null);
self::doSql($pdo, "DELETE FROM %customers%", null);
self::doSql($pdo, "DELETE FROM %work% WHERE item='lastclosing'", null);
self::doSql($pdo, "UPDATE %work% SET value='0' WHERE item='newfoodtocook'", null);
self::doSql($pdo, "UPDATE %work% SET value='0' WHERE item='newdrinktocook'", null);
self::doSql($pdo, "UPDATE %work% SET value='0' WHERE item='indexunclosedqueue'", null);
Workreceipts::resetWorkReceiptId($pdo);
echo json_encode(array("status" => "OK"));
} catch(Exception $e) {
echo json_encode(array("status" => "ERROR", "code" => ERROR_COMMAND_ERROR, "msg" => ERROR_COMMAND_ERROR_MSG . " - Error message: $e"));
}
}
private static function doSql($pdo,$sql,$params) {
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
if (is_null($params)) {
$stmt->execute();
} else {
$stmt->execute($params);
}
}
private static function askforcompanyinfo() {
try {
$pdo = DbUtils::openDbAndReturnPdoStatic();
$companyInfo = CommonUtils::getConfigValue($pdo, 'companyinfo', '');
$logolocation = CommonUtils::getConfigValue($pdo, 'logolocation', 1);
echo json_encode(array("status" => "OK","msg" => array("companyinfo" => $companyInfo,"logolocation" => $logolocation)));
} catch (Exception $ex) {
echo json_encode(array("status" => "ERROR","msg" => $ex->getMessage()));
}
}
}