ordersprinter/webapp/php/commonutils.php

472 lines
14 KiB
PHP

<?php
require_once ('dbutils.php');
defined('T_ORDER') || define ('T_ORDER', 0);
defined('T_BILL') || define ('T_BILL', 1);
defined('T_REMOVE') || define ('T_REMOVE', 2);
defined('T_BILLSTORNO') || define ('T_BILLSTORNO', 3);
defined('T_BILLSTORNOREMOVE') || define ('T_BILLSTORNOREMOVE', 4);
defined('T_FROM_TABLE') || define ('T_FROM_TABLE', 5);
defined('T_TO_TABLE') || define ('T_TO_TABLE', 6);
class CommonUtils {
var $dbutils;
private static $plugins = null;
function __construct() {
$this->dbutils = new DbUtils();
// $this->products = new Products(); --> endless loop!
// $this->lastSettingOfDisplayMode = "all";
//error_reporting(E_ALL);
}
public static function setPluginConfig($plugins) {
self::$plugins = $plugins;
}
public static $g_units_arr =
array(
array("text" => "Stück","value" => 0,"id" => "piece"),
array("text" => "Eingabe","value" => 1,"id" => "piece"),
array("text" => "kg","value" => 2,"id" => "kg"),
array("text" => "gr","value" => 3,"id" => "gr"),
array("text" => "mg","value" => 4,"id" => "mg"),
array("text" => "l","value" => 5,"id" => "l"),
array("text" => "ml","value" => 6,"id" => "ml"),
array("text" => "m","value" => 7,"id" => "m")
);
public static function g_units_export_arr() {
return array();
}
function verifyLastBillId($pdo,$nextIdToUse) {
if ($nextIdToUse == 1) {
return true;
}
if (is_null($pdo)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
}
$nextIdToUse = intval($nextIdToUse);
$sql = "SELECT value,signature FROM %work% WHERE item=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array("lastbillid"));
$row =$stmt->fetchObject();
$lastBillid = intval($row->value);
$lastBillInc = $lastBillid+1;
if ($lastBillInc != $nextIdToUse) {
return false;
} else {
$sql = "SELECT id FROM %bill% WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($nextIdToUse));
if ($stmt->rowCount() > 0) {
return false;
} else {
// is there a gap or does the previous id exist?
$sql = "SELECT id FROM %bill% WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($nextIdToUse - 1));
if ($stmt->rowCount() != 1) {
return false;
} else {
return true;
}
}
}
}
function getKeyFromWorkTable($pdo,$key) {
$sql = "SELECT signature FROM %work% WHERE item=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($key));
$row =$stmt->fetchObject();
return($row->signature);
}
public static function setMd5OfLastBillidInWorkTable($pdo) {
$sql = "SELECT value FROM %work% where item=?";
$r = self::fetchSqlAll($pdo, $sql, array("lastbillid"));
if (count($r) > 0) {
$maxid = $r[0]["value"];
$signature = md5("B($maxid)");
$sql = "UPDATE %work% SET signature=? WHERE item=?";
self::execSql($pdo, $sql, array($signature,"lastbillid"));
}
}
function setLastBillIdInWorkTable($pdo,$lastBillId) {
if (is_null($pdo)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
}
$signature = md5("B($lastBillId)");
$sql = "UPDATE %work% SET value=?, signature=? WHERE item=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($lastBillId,$signature,"lastbillid"));
}
function verifyBill($pdo,$id) {
if (is_null($pdo)) {
$pdo = $this->dbutils->openDbAndReturnPdo();
}
$sql = "SELECT billdate,brutto,ROUND(netto,2) as netto,userid,IF(tax is not null, tax, '0.00') as tax,signature,status FROM %bill% WHERE id=?";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute(array($id));
$row = $stmt->fetchObject();
$billdate = $row->billdate;
$brutto = $row->brutto;
$netto = $row->netto;
$tax = $row->tax;
$userid = $row->userid;
$signature = $row->signature;
$status = $row->status;
return(self::verifyBillByValues($pdo,$billdate, $brutto, $netto, $userid, $signature, $status));
}
public static function verifyBillByValues($pdo,$billdate,$brutto,$netto,$userid,$signature,$status) {
if (($status == "c") && ($brutto == 0.00)) {
// workaround - the signature for cash inserts of vaue 0.00 are sometimes incorrect
return true;
}
if (is_null($signature)) {
return false;
}
if (is_null($pdo)) {
$pdo = DbUtils::openDbAndReturnPdoStatic();
}
$brutto = number_format($brutto, 2, ".", '');
$netto = number_format($netto, 2, ".", '');
$data = "D($billdate)B($brutto)N($netto)T(0)U($userid)";
$md5OfData = md5($data);
if ($signature != $md5OfData) {
return false;
} else {
return true;
}
}
public static function calcSignaturesForAllBills($pdo) {
$sql = "SELECT id,billdate,brutto,netto,userid FROM %bill%";
$r = CommonUtils::fetchSqlAll($pdo, $sql);
$sql = "UPDATE %bill% SET signature=? WHERE id=?";
foreach($r as $b) {
$bruttostr = number_format($b["brutto"], 2, ".", '');
$nettostr = number_format($b["netto"], 2, ".", '');
$theTime = $b["billdate"];
$userid = $b["userid"];
$data = md5("D($theTime)B($bruttostr)N($nettostr)T(0)U($userid)");
CommonUtils::execSql($pdo, $sql, array($data,$b["id"]));
}
}
public static function calcSignatureForBill($theTime,$brutto,$netto,$userid) {
// now calculate the signature for the bill entry
$bruttostr = number_format($brutto, 2, ".", '');
$nettostr = number_format($netto, 2, ".", '');
$data = "D($theTime)B($bruttostr)N($nettostr)T(0)U($userid)";
$signature = md5($data);
return $signature;
}
function createGridTableWithSqrtSizeOfButtons ($inputArray) {
// create a table that is optimal (sqrt-like size)
$numberOfIcons = count($inputArray);
if ($numberOfIcons == 0) {
// no items to display
return;
}
$numberOfCols = ceil(sqrt($numberOfIcons));
$porcentageWidth = floor(100/$numberOfCols);
echo '<table class=gridtable>';
$colcounter = 0;
for ($index=0;$index<$numberOfIcons;$index++) {
if ($colcounter == 0) {
echo "<tr><td>";
}
$anEntry = $inputArray[$index];
$textOfButton = $anEntry["textOfButton"]; #
$onClickMethod = $anEntry["onClickMethod"]; // With parameters!
$button = '<input type="button" value="' . $textOfButton . '"';
$button = $button . ' onclick="' . $onClickMethod . '"';
$button = $button . ' style="height: 50px; width:' . $porcentageWidth . '%; font-size:20px; background-color:#b3b3c9" />';
echo $button;
$colcounter++;
if ($colcounter == $numberOfCols) {
$colcounter = 0;
echo "</tr>";
}
}
echo "</tr>";
echo "</table>";
}
function createGridTableWithSqrtSizeOfStyleButtons($inputArray) {
$this->createGridTableWithSqrtSizeOfStyleButtonsAndHeader($inputArray,'','dummy');
}
function getTableNameFromId($pdo,$tableid) {
if (is_null($tableid) || ($tableid == 0)) {
return "-"; // togo
}
$sql = "SELECT tableno FROM %resttables% WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($tableid));
$row = $stmt->fetchObject();
return $row->tableno;
}
function getCurrentPriceLevel($pdo) {
$sql = "SELECT setting FROM %config% WHERE name='pricelevel'";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$row = $stmt->fetchObject();
$pricelevelid = $row->setting;
$sql = "SELECT id,name FROM %pricelevel% WHERE id=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($pricelevelid));
$row = $stmt->fetchObject();
$pricelevelname = $row->name;
return (array("id" => $pricelevelid, "name" => $pricelevelname));
}
function createGridTableWithSqrtSizeOfStyleButtonsAndHeader ($inputArray,$headline,$headercolor) {
// create a table that is optimal (sqrt-like size)
$numberOfIcons = count($inputArray);
if ($numberOfIcons == 0) {
// no items to display
return;
}
$numberOfCols = ceil(sqrt($numberOfIcons));
$porcentageWidth = floor(100.0/$numberOfCols);
echo '<table class=gridtable>';
// Headline
if ($headline <> '') {
echo '<tr><th style="background-color:#' . $headercolor . '">' . $headline . '</th>';
}
$colcounter = 0;
for ($index=0;$index<$numberOfIcons;$index++) {
if ($colcounter == 0) {
echo "<tr><td>";
}
$anEntry = $inputArray[$index];
$textOfButton = $anEntry["textOfButton"]; #
$onClickMethod = $anEntry["onClickMethod"]; // With parameters!
$style = $anEntry["style"];
$button = '<input type="button" value="' . $textOfButton . '"';
$button = $button . ' onclick="' . $onClickMethod . '"';
$button = $button . ' style="' . $style . '; width:' . $porcentageWidth . '%;" />';
echo $button;
$colcounter++;
if ($colcounter == $numberOfCols) {
$colcounter = 0;
echo "</tr>";
}
}
echo "</tr>";
echo "</table>";
}
function getCurrency() {
$pdo = $this->dbutils->openDbAndReturnPdo();
$sql = "SELECT setting from %config% where name='currency'";
$stmt = $pdo->prepare($this->dbutils->resolveTablenamesInSqlString($sql));
$stmt->execute();
$row =$stmt->fetchObject();
if ($row != null) {
return $row->setting;
} else {
return "Euro";
}
}
public static function getRowSqlObject($pdo,$sql,$params = null) {
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
if (is_null($params)) {
$stmt->execute();
} else {
$stmt->execute($params);
}
return ($stmt->fetchObject());
}
public static function fetchSqlAll($pdo,$sql,$params = null) {
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
if (is_null($params)) {
$stmt->execute();
} else {
$stmt->execute($params);
}
return ($stmt->fetchAll(PDO::FETCH_ASSOC));
}
public static function execSql($pdo,$sql,$params) {
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
if (is_null($params)) {
$stmt->execute();
} else {
$stmt->execute($params);
}
}
public static function getConfigValueStmt($pdo,$stmt,$item,$default) {
$stmt->execute(array($item));
$row =$stmt->fetchObject();
if ($row->countid == 0) {
return $default;
} else {
return self::getExistingConfigValue($pdo, $item);
}
}
public static function getConfigValue($pdo,$item,$default) {
$sql = "SELECT count(id) as countid FROM %config% WHERE name=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($item));
$row =$stmt->fetchObject();
if ($row->countid == 0) {
return $default;
} else {
return self::getExistingConfigValue($pdo, $item);
}
}
public static function getExistingConfigValue($pdo,$item) {
$sql = "SELECT setting FROM %config% WHERE name=?";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($item));
$row = $stmt->fetchObject();
return $row->setting;
}
public static function callPlugin($pdo,$fct,$condition) {
try {
if (!is_null(self::$plugins)) {
if (array_key_exists($fct,self::$plugins)) {
$plugin = self::$plugins->$fct;
if (($plugin->execution) === $condition) {
$cls = $plugin->PluginClass;
$fct=$plugin->PluginFct;
$call = "Plugin\\$cls::$fct";
call_user_func($call,$pdo);
return true;
}
}
}
} catch(Exception $e) { }
return false;
}
public static function log($pdo, $component, $message) {
$dblog = self::getConfigValue($pdo, "dblog", 1);
if ($dblog == 1) {
date_default_timezone_set(DbUtils::getTimeZone());
$currentTime = date('Y-m-d H:i:s');
$sql = "INSERT INTO %log% (date,component,message) VALUES(?,?,?)";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute(array($currentTime, $component, $message));
}
}
public static function getLog($pdo) {
$sql = "SELECT date,component,message FROM %log%";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result = $stmt->fetchAll();
$txt = "";
foreach ($result as $aLogLine) {
$txt .= $aLogLine["date"] . ";" . $aLogLine["component"] . ";" . $aLogLine["message"] . "\n";
}
return $txt;
}
public static function getLastLog($pdo) {
$sql = "SELECT date,component,message FROM %log% WHERE DATE_SUB(NOW(),INTERVAL 2 HOUR) <= date";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
$result = $stmt->fetchAll();
$txt = "";
foreach ($result as $aLogLine) {
$txt .= $aLogLine["date"] . ";" . $aLogLine["component"] . ";" . $aLogLine["message"] . "\n";
}
return $txt;
}
public static function keepOnlyLastLog($pdo) {
$sql = "DELETE FROM %log% WHERE DATE_SUB(NOW(),INTERVAL 2 HOUR) > date";
$stmt = $pdo->prepare(DbUtils::substTableAlias($sql));
$stmt->execute();
}
public static function strEndsWith($haystack, $needle)
{
return $needle === "" || substr($haystack, -strlen($needle)) === $needle;
}
public static function startsWith($aText, $needle)
{
return $needle === "" || strpos($aText, $needle) === 0;
}
public static function caseOfSqlUnitSelection($pdo) {
$decpoint = htmlspecialchars(CommonUtils::getConfigValue($pdo, "decpoint", "."));
$unit = "CASE ";
foreach(CommonUtils::$g_units_arr as $aUnit) {
if ($aUnit["value"] > 1) {
$unit .= " WHEN Q.unit='" . $aUnit["value"] . "' THEN CONCAT(REPLACE(unitamount,'.','$decpoint'),'" . $aUnit["text"] . "',' ') ";
}
}
$unit .= " ELSE '' ";
$unit .= "END";
return $unit;
}
public static function scaleImg($fn,$maxDim) {
list($width, $height, $type, $attr) = getimagesize($fn);
$size = getimagesize($fn);
$ratio = $size[0] / $size[1]; // width/height
if ($ratio > 1) {
$width = $maxDim;
$height = $maxDim / $ratio;
} else {
$width = $maxDim * $ratio;
$height = $maxDim;
}
$src = imagecreatefromstring(file_get_contents($fn));
$dst = imagecreatetruecolor($width, $height);
imagealphablending($dst, false);
imagesavealpha($dst, true);
$transparent = imagecolorallocatealpha($dst, 255, 255, 255, 127);
imagefilledrectangle($dst, 0, 0, $width, $height, $transparent);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $width, $height, $size[0], $size[1]);
imagedestroy($src);
ob_start();
imagepng($dst); // adjust format as needed
$imagedata = ob_get_contents();
ob_end_clean();
imagedestroy($dst);
return $imagedata;
}
}