app=$app;
if(empty($this->app->erp)){
$this->app->erp = $this;
}
$this->firstlogtime = microtime(true);
$this->logtime = microtime(true);
if(defined('SCRIPT_START_TIME'))
{
$this->firstlogtime = SCRIPT_START_TIME;
}
$this->cache = null;
$this->menuquery = null;
$this->BriefpapierHintergrunddisable = false;
}
/**
* @param string $category
* @param string $name
* @param string $status
* @param string $message
*/
public function setSystemHealth($category, $name, $status, $message = '') {
/** @var Systemhealth $obj */
$obj = $this->LoadModul('systemhealth');
if(empty($obj)) {
return;
}
$obj->changeStatus($category, $name, $status, $message);
}
public function loadCronjobObj()
{
$dbName = $this->app->Conf->WFdbname;
/** @var Prozessstarter cronjobObj */
if(empty($this->cronjobObj) || empty($this->cronjobObjDb) || $this->cronjobObjDb !== $dbName) {
$this->cronjobObj = $this->app->loadModule('prozessstarter', true);
$this->cronjobObjDb = $this->app->Conf->WFdbname;
}
}
/**
* @param string $status
* @param null|int $prozessstarter
*/
public function ProzessstarterStatus($status, $prozessstarter = null)
{
$this->loadCronjobObj();
if(empty($this->cronjobObj)) {
return;
}
if(method_exists($this->cronjobObj,'setCronjobStatus')) {
$this->cronjobObj->setCronjobStatus($status, $prozessstarter);
}
}
/**
* @param array $output
* @param array $task
*/
public function checkCronjobMemory($output, $task)
{
$this->loadCronjobObj();
if(method_exists($this->cronjobObj,'checkCronjobMemory')) {
$this->cronjobObj->checkCronjobMemory($output, $task);
}
}
public function checkIfCronjobRunning($uid, $task)
{
$this->loadCronjobObj();
if(method_exists($this->cronjobObj,'checkIfCronjobRunning')) {
$this->cronjobObj->checkIfCronjobRunning($uid, $task);
}
}
public function checkCronjobRunning($uid, $task) {
$this->loadCronjobObj();
if(empty($this->cronjobObj)) {
return;
}
if(method_exists($this->cronjobObj,'checkCronjobRunning')) {
return $this->cronjobObj->checkCronjobRunning($uid, $task);
}
return true;
}
public function closeAndLogCronjob($uid, $fromStarter2 = false)
{
$this->loadCronjobObj();
if(method_exists($this->cronjobObj,'closeAndLogCronjob')) {
$this->cronjobObj->closeAndLogCronjob($uid, $fromStarter2);
}
}
public function setCronjobRunning($uid, $task = null, $active = true) {
$this->loadCronjobObj();
if(empty($this->cronjobObj)) {
return;
}
if(method_exists($this->cronjobObj,'setCronjobRunning')) {
$this->cronjobObj->setCronjobRunning($uid, $task, $active);
}
}
// @bruno
public function TrackingCSV($datei, $versand, $append = false, $uebertragung = 0)
{
if((int)$versand <= 0 || $datei == ''){
return false;
}
$arr = $this->app->DB->SelectRow("SELECT ".($uebertragung?" am.id_ext as auftragextid, ":"")." v.tracking, l.belegnr, if(ifnull(l.sprache,'') = '',ifnull(a.sprache,''),l.sprache) as tracking_sprache, l.name, v.versandart FROM versand v INNER JOIN lieferschein l ON v.lieferschein = l.id AND v.id = '$versand'
LEFT JOIN auftrag a ON l.auftragid = a.id
".($uebertragung?"
LEFT JOIN api_mapping am ON am.tabelle = 'auftrag' AND am.uebertragung_account = '$uebertragung' AND id_int = a.id
":"")."
LIMIT 1");
if($arr)
{
$file_ex = @is_file($datei);
$handle = @fopen($datei, $append?'a':'w');
if($handle)
{
if(!$append || !$file_ex)
{
$output = "";
foreach($arr as $k => $v)$output .= $k.';';
$output .= "\r\n";
fputs($handle, $output);
}
$output = "";
foreach($arr as $k2 => $v2)
{
$output .= '"'.$v2.'"'.';';
}
$output .= "\r\n";
fputs($handle, $output);
fclose($handle);
return true;
}
}
return false;
}
/**
* @bruno Prüfen ob es weg kann
*
* @deprecated
*
* @param $beleg
*
* @return void
*/
public function checkPDFClass($beleg)
{
if(empty($beleg))
{
return;
}
$classcustom = ucfirst($beleg).'PDFCustom';
$class = ucfirst($beleg).'PDF';
if(class_exists($classcustom) || class_exists($class) || !file_exists(__DIR__.'/dokumente/class.'.$beleg.'.php')){
return;
}
if(!defined('FPDF_FONTPATH')){
define('FPDF_FONTPATH',__DIR__.'/pdf/font/');
}
if(!class_exists('FPDFWAWISION'))
{
if(file_exists(dirname(dirname(__DIR__)).'/conf/user_defined.php')){
include_once dirname(dirname(__DIR__)).'/conf/user_defined.php';
}
if(defined('USEFPDF3') && USEFPDF3 && file_exists(__DIR__ .'/pdf/fpdf_3.php'))
{
require_once __DIR__ .'/pdf/fpdf_3.php';
}
else if(defined('USEFPDF2') && USEFPDF2 && file_exists(__DIR__ .'/pdf/fpdf_2.php'))
{
require_once __DIR__ .'/pdf/fpdf_2.php';
} else {
require_once __DIR__ .'/pdf/fpdf.php';
}
}
if(!class_exists('PDF_EPS')){
include_once __DIR__.'/pdf/fpdf_final.php';
}
if(!class_exists('SuperFPDF')){
require_once __DIR__.'/dokumente/class.superfpdf.php';
}
if(!class_exists('Briefpapier'))
{
if(file_exists(__DIR__.'/dokumente/class.briefpapier_custom.php'))
{
require_once __DIR__.'/dokumente/class.briefpapier_custom.php';
}else{
require_once __DIR__.'/dokumente/class.briefpapier.php';
}
}
if(file_exists(__DIR__.'/dokumente/class.'.$beleg.'_custom.php'))
{
include_once __DIR__.'/dokumente/class.'.$beleg.'_custom.php';
}elseif(file_exists(__DIR__.'/dokumente/class.'.$beleg.'.php'))
{
include_once __DIR__.'/dokumente/class.'.$beleg.'.php';
}
if(!class_exists('image')){
require __DIR__ . '/class.image.php';
}
}
function ArtikelUebertragen($datei, $artikelarr, $uebertragung = 0)
{
/** @var Uebertragungen $obj */
$obj = $this->app->erp->LoadModul('uebertragungen');
if(!empty($obj) && method_exists($obj, 'ArtikelUebertragen')) {
return $obj->ArtikelUebertragen($datei, $artikelarr, $uebertragung);
}
return false;
}
/** @deprecated */
function LagerzahlenCSV($datei, $artikel, $lager = 0, $lager_platz = 0, $append = false)
{
if((int)$artikel <= 0 || $datei == '')return false;
if($lager || $lager_platz)
{
$artikelarr = $this->app->DB->SelectRow("SELECT art.nummer, art.herstellernummer, art.ean, ifnull(lag.menge,0) as lager_menge_total, lag.lager_platz
FROM artikel art
LEFT JOIN (
SELECT lpi.artikel,lp.kurzbezeichnung as lager_platz, trim(ifnull(sum(lpi.menge),0))+0 as menge FROM lager_platz_inhalt lpi
INNER JOIN lager_platz lp ON lpi.lager_platz = lp.id AND lp.geloescht = 0 ".($lager_platz?" AND lp.id = '$lager_platz' ":"")."
".($lager?" AND lp.lager = '$lager' ":"")."
WHERE lpi.artikel = '$artikel' GROUP BY lp.id
) lag ON art.id = lag.artikel WHERE art.id = '$artikel' LIMIT 1");
}else{
$artikelarr = $this->app->DB->SelectRow("SELECT art.nummer, art.herstellernummer, art.ean FROM artikel art
WHERE art.id = '$artikel' LIMIT 1");
if($artikelarr)$artikelarr['lager_menge_total'] = floor($this->ArtikelAnzahlVerkaufbar($artikel));
}
if($artikelarr){
$file_ex = @is_file($datei);
$handle = @fopen($datei, $append?'a':'w');
if($handle)
{
if(!$append || !$file_ex)
{
$output = "";
foreach($artikelarr as $k => $v)$output .= $k.';';
$output .= "\r\n";
fputs($handle, $output);
}
$output = "";
foreach($artikelarr as $k2 => $v2)
{
$output .= '"'.$v2.'"'.';';
}
$output .= "\r\n";
fputs($handle, $output);
fclose($handle);
return true;
}
}
return false;
}
// @todo
function Belegeexport($datei, $doctype, $doctypeid, $append = false, $optionen = null)
{
if($doctype == '' || (int)$doctypeid <= 0 || $datei == '') {
return false;
}
$arr = [
'adresse','artikel','art','status','beleg_status','beleg_datum','beleg_lieferdatum','beleg_tatsaechlicheslieferdatum','beleg_versandart','beleg_zahlungsweise','beleg_belegnr','beleg_hauptbelegnr','beleg_kundennummer','beleg_name','beleg_abteilung',
'beleg_unterabteilung','beleg_adresszusatz','beleg_ansprechpartner','beleg_telefon','beleg_email','beleg_land','beleg_strasse','beleg_plz','beleg_ort','beleg_projekt','beleg_aktion',
'beleg_internebemerkung','beleg_internebezeichnung','beleg_freitext','beleg_ihrebestellnummer','beleg_lieferbedingung','beleg_art','artikel_nummer','artikel_bezeichnung','artikel_beschreibung',
'artikel_menge','artikel_preis','artikel_rabatt','artikel_waehrung','artikel_lieferdatum','artikel_sort','artikel_umsatzsteuer','artikel_einheit','artikel_zolltarifnummer',
'artikel_herkunftsland','artikel_artikelnummerkunde',
'artikel_freifeld1','artikel_freifeld2','artikel_freifeld3','artikel_freifeld4','artikel_freifeld5','artikel_freifeld6','artikel_freifeld7','artikel_freifeld8','artikel_freifeld9','artikel_freifeld10',
'artikel_freifeld11','artikel_freifeld12','artikel_freifeld13','artikel_freifeld14','artikel_freifeld15','artikel_freifeld16','artikel_freifeld17','artikel_freifeld18','artikel_freifeld19','artikel_freifeld20','artikel_freifeld21','artikel_freifeld22','artikel_freifeld23','artikel_freifeld24','artikel_freifeld25','artikel_freifeld26','artikel_freifeld27','artikel_freifeld28','artikel_freifeld29','artikel_freifeld30','artikel_freifeld31','artikel_freifeld32','artikel_freifeld33','artikel_freifeld34','artikel_freifeld35','artikel_freifeld36','artikel_freifeld37','artikel_freifeld38','artikel_freifeld39','artikel_freifeld40',
'beleg_unterlistenexplodieren'
];
if($doctype === 'bestellung') {
$arr[] = 'beleg_lieferantennummer';
}
$colsa[] = 't.adresse';
if($doctype !== 'verbindlichkeit'){
$colsa[] = 'p.artikel';
}
$colsa[] = 'pr.abkuerzung as beleg_projekt';
if(isset($optionen['art']) && $optionen['art'] != '') {
$colsa[] = "'".$optionen['art']."' as art";
}
else{
$colsa[] = "'$doctype' as art";
}
$checkfields = $this->app->DB->SelectRow("SELECT * FROM $doctype LIMIT 1");
$checkfieldsposition = $doctype === 'verbindlichkeit'
?null: $this->app->DB->SelectRow("SELECT * FROM ".$doctype."_position LIMIT 1");
foreach($arr as $v) {
if(strpos($v,'beleg_') === 0) {
$k = substr($v, 6);
if($k !== 'projekt' && $k !== 'hauptbelegnr') {
if(($k !== 'tatsaechlicheslieferdatum' && $k !== 'aktion' && $k !== 'art' && $k !== 'ihrebestellnummer') || $doctype === 'auftrag') {
if(($doctype !== 'auftrag' && $doctype !== 'lieferschein') || $k !== 'lieferdatum') {
if(array_key_exists($k,$checkfields)) {
$colsa[] = 't.'.$k.' as '.$v;
}
}
}
}
}
elseif(strpos($v,'artikel_') === 0) {
$k = substr($v, 8);
if($k !== 'preisfuermenge' || $doctype === 'auftrag') {
if(($k !== 'rabatt'
|| ($doctype !== 'bestellung' && $doctype !== 'lieferschein' && $doctype !== 'retoure' && $doctype!=='produktion'))
&& (($k !== 'preis' && $k !== 'waehrung' && $k !== 'umsatzsteuer') ||
($doctype !== 'lieferschein' && $doctype!=='produktion' && $doctype !== 'retoure'))) {
if($doctype === 'bestellung' && $k === 'nummer') {
$k = 'bestellnummer';
}
if($doctype === 'bestellung' && $k === 'bezeichnung') {
$k = 'bezeichnunglieferant';
}
if($doctype === 'verbindlichkeit') {
$colsa[] = " '' as " . $v;
continue;
}
if(array_key_exists($k,$checkfieldsposition) && $k !== 'projekt') {
if($k=='preis')
{
$colsa[] = $this->app->erp->FormatPreis('p.'.$k).' as '.$v;
}
else if($k=='menge')
{
$colsa[] = $this->app->erp->FormatMenge('p.'.$k).' as '.$v;
}
else {
$colsa[] = 'p.' . $k . ' as ' . $v;
}
}
}
}
}
}
if($doctype === 'auftrag') {
$colsa[] = 't2.belegnr as beleg_hauptbelegnr';
}
if($doctype !== 'verbindlichkeit') {
$colsa[] = " art.ean as artikel_ean ";
}
$colsa[] = "'1' as artikel_preisfuermenge ";
$cols = implode(',', $colsa);
switch($doctype) {
case 'verbindlichkeit':
$arr = $this->app->DB->SelectArr(
sprintf(
"SELECT %s
FROM `verbindlichkeit` AS `t`
LEFT JOIN `projekt` AS `pr` ON t.projekt = pr.id
WHERE t.id = %d",
$cols, $doctypeid
)
);
break;
case 'auftrag':
$arr = $this->app->DB->SelectArr(
sprintf(
"SELECT %s
FROM `auftrag` AS `t`
INNER JOIN `auftrag_position` AS `p` ON t.id = p.auftrag
INNER JOIN `artikel` AS `art` ON p.artikel = art.id
LEFT JOIN `projekt` AS `pr` ON t.projekt = pr.id
LEFT JOIN `auftrag` AS `t2` ON t.teillieferungvon = t2.id
WHERE t.id = %d",
$cols, $doctypeid
)
);
break;
default:
$arr = $this->app->DB->SelectArr(
sprintf(
"SELECT %s
FROM `%s` AS `t`
INNER JOIN `%s` AS `p` ON t.id = p.%s
INNER JOIN `artikel` AS `art` ON p.artikel = art.id
LEFT JOIN `projekt` AS `pr` ON t.projekt = pr.id
WHERE t.id = %d",
$cols, $doctype, $doctype.'_position',$doctype, $doctypeid
)
);
break;
}
if($arr) {
$file_ex = @is_file($datei);
$handle = @fopen($datei, $append?'a':'w');
if($handle) {
if(!$append || !$file_ex) {
$output = '';
foreach($arr[0] as $k => $v) {
$output .= $k.';';
}
$output .= "\r\n";
fwrite($handle, $output);
}
$output = '';
foreach($arr as $k => $v) {
foreach($v as $k2 => $v2) {
if(($k2 === 'belegnr' || $k2 === 'beleg_belegnr')) {
if($k > 0) {
if((isset($optionen['new']) && $optionen['new'] ) || $v2 == '' || !(isset($optionen['noparent']) && $optionen['noparent'])){
$v2 = 'PARENT';
}
}
else {
if(isset($optionen['new']) && $optionen['new']) {
$v2 = 'NEW';
}
}
}
$v3 = str_replace(array('ü','ö','ä','Ü','Ö','Ä','ß','"'),array('ü','ö','ä','Ü','Ö','Ä','ß','"'.'"'),$v2);
if(isset($optionen['nowrap'])) {
$v3 = str_replace(array("\r","\n"),'', $v3);
}
$output .= '"'.$v3.'"'.';';
}
$output .= "\r\n";
}
fwrite($handle, $output);
fclose($handle);
return true;
}
}
return false;
}
// $app->Module()->Warehouse()->Gateway()->isConsumptionWarehouseAvailable()
// $app->Warehouse()->
function Verbrauchslagervorhanden()
{
if(is_null($this->verbrauchslagervorhanden))
{
$this->verbrauchslagervorhanden = $this->app->DB->Select("SELECT id FROM lager_platz WHERE verbrauchslager = 1 LIMIT 1")?true:false;
}
return $this->verbrauchslagervorhanden;
}
public function ExitWawi($status = 0)
{
if(method_exists($this->app, 'ExitXentral')) {
$this->app->ExitXentral($status);
}
exit($status);
}
// @refactor Module OrderPicking
public function GetNextKommissionierung($bezeichnung = '')
{
$this->app->DB->Insert("INSERT INTO kommissionierung (bearbeiter, bezeichnung) values ('".$this->app->DB->real_escape_string($this->app->User->GetName())."','".$bezeichnung."')");
return $this->app->DB->GetInsertID();
}
// @refactor in DevTools
function LogWithTime($message, $json = false)
{
if(defined('SCRIPT_START_TIME'))
{
$akttime = microtime(true);
$aktmemory = number_format(memory_get_usage()/1024.0/1024.0,2);
$peakmemory = number_format(memory_get_peak_usage()/1024.0/1024.0,2);
$runtime = number_format($akttime - $this->logtime,3);
$runtimeall = number_format($akttime - $this->firstlogtime,3);
$this->LogFile('Time all '.$runtimeall."s last: ".$runtime."s Memakt:".$aktmemory."MB peak:".$peakmemory."MB ".$this->app->DB->real_escape_string( $json?json_encode($message):$message));
$this->logtime = $akttime;
}
}
/**
* @deprecated Secure-Klasse verwenden
*
* @param $data
*
* @return mixed|null|string|string[]
*/
function xss_clean($data)
{
// Fix &entity\n;
$data = str_replace(array('&','<','>'), array('&','<','>'), $data);
$data = preg_replace('/(*\w+)[\x00-\x20]+;/u', '$1;', $data);
$data = preg_replace('/(*[0-9A-F]+);*/iu', '$1;', $data);
$data = html_entity_decode($data, ENT_COMPAT, 'UTF-8');
// Remove any attribute starting with "on" or xmlns
$data = preg_replace('#(<[^>]+?[\x00-\x20"\'])(?:on|xmlns)[^>]*+>#iu', '$1>', $data);
// Remove javascript: and vbscript: protocols
$data = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([`\'"]*)[\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2nojavascript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iu', '$1=$2novbscript...', $data);
$data = preg_replace('#([a-z]*)[\x00-\x20]*=([\'"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#u', '$1=$2nomozbinding...', $data);
// Only works in IE:
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?expression[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?behaviour[\x00-\x20]*\([^>]*+>#i', '$1>', $data);
$data = preg_replace('#(<[^>]+?)style[\x00-\x20]*=[\x00-\x20]*[`\'"]*.*?s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*+>#iu', '$1>', $data);
// Remove namespaced elements (we do not need them)
$data = preg_replace('#*\w+:\w[^>]*+>#i', '', $data);
do
{
// Remove really unwanted tags
$old_data = $data;
$data = preg_replace('#*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|i(?:frame|layer)|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|title|xml)[^>]*+>#i', '', $data);
}
while ($old_data !== $data);
return $data;
}
// @refactor in Benutzer Modul
/**
* @return array
*/
public function getEncModullist()
{
if(file_exists(__DIR__.'/modulliste.php')) {
$erg = [];
include __DIR__.'/modulliste.php';
return $erg;
}
return [];
}
/**
* @deprecated
*
* @return bool
*/
function checkLicense()
{
return true;
}
// @refactor LicenceManager Komponente
final public function isIoncube()
{
if(empty(erpAPI::$license))
{
erpAPI::Ioncube_Property('');
}
return !empty(erpAPI::$license);
}
// @refactor LicenceManager Komponente
static function Ioncube_Property($key = '')
{
if(!class_exists('License'))
{
if(is_file(dirname(dirname(__DIR__)).'/phpwf/plugins/class.license.php'))
{
include(dirname(dirname(__DIR__)).'/phpwf/plugins/class.license.php');
}
}
if(class_exists('License'))
{
if(!erpAPI::$license) {
erpAPI::$license = new License();
}
}
if(erpAPI::$license) {
return erpAPI::$license->getProperty($key);
}
if(function_exists('ioncube_license_properties'))
{
if(!self::$ioncubeproperties) {
self::$ioncubeproperties = ioncube_license_properties();
}
$data = self::$ioncubeproperties;
if($data && is_array($data) && isset($data[$key]) && is_array($data[$key]) && isset($data[$key]['value'])) {
$value = $data[$key]['value'];
return $value;
}
}
return false;
}
// @refactor LicenceManager Komponente
static function Ioncube_getMaxUser()
{
return erpAPI::Ioncube_Property('maxuser');
}
// @refactor LicenceManager Komponente
static function Ioncube_getMaxLightusers()
{
return erpAPI::Ioncube_Property('maxlightuser');
}
// @refactor LicenceManager Komponente
static function Ioncube_getMaxLightusersRights()
{
$rechte = (int)erpAPI::Ioncube_Property('maxlightuserrights');
if($rechte < 5) {
$rechte = 30;
}
return $rechte;
}
// @refactor LicenceManager Komponente
static function Ioncube_BenutzervorlageAnzahlLightuser(&$app, $vorlage)
{
if(!isset($app->DB)) {
return;
}
return $app->DB->Select("SELECT count(id) FROM `user` WHERE activ = 1 AND type = 'lightuser' AND vorlage = '$vorlage'");
}
// @refactor LicenceManager Komponente
static function Ioncube_LightuserRechteanzahl($app, $id, $type = 'user')
{
if(!isset($app->DB)) {
return false;
}
if($type === 'vorlage') {
$id = $app->DB->Select("SELECT id FROM `uservorlage` WHERE bezeichnung <> '' AND bezeichnung = '".$app->DB->real_escape_string($id)."' LIMIT 1");
}
$id = (int)$id;
if($id <= 0) {
return false;
}
if($type === 'vorlage')
{
if(!$app->DB->Select("SELECT id FROM `uservorlage` WHERE id = '$id' LIMIT 1")) {
return false;
}
return $app->DB->Select("SELECT count(DISTINCT module, action) FROM `uservorlagerights` WHERE vorlage = '$id' AND permission = 1");
}
if(!$app->DB->Select("SELECT id FROM `user` WHERE id = '$id' LIMIT 1")) {
return false;
}
return $app->DB->Select("SELECT count(DISTINCT module, action) FROM `userrights` WHERE `user` = '$id' AND permission = 1");
}
// @refactor LicenceManager Komponente
static function Ioncube_HasExpired()
{
return erpAPI::Ioncube_Property('expdate') && (int)erpAPI::Ioncube_Property('expdate') < time();
}
// @refactor LicenceManager Komponente
static function Ioncube_ExpireInDays()
{
if(function_exists('ioncube_file_info'))
{
if(erpAPI::Ioncube_Property('expdate')) {
return round(((int)erpAPI::Ioncube_Property('expdate')-time())/86400);
}
}
return false;
}
// @refactor LicenceManager Komponente
static function Ioncube_BeforeExpire()
{
if(false === erpAPI::Ioncube_ExpireInDays()) {
return false;
}
return erpAPI::Ioncube_ExpireInDays() < 42;
}
// @refactor LicenceManager Komponente
static function Ioncube_ExpireDate($format = 'd.m.Y')
{
if(function_exists('ioncube_file_info'))
{
$dat = erpAPI::Ioncube_Property('expdate');
if(!$dat) {
return false;
}
return date($format,(int)$dat);
}
return false;
}
// @refactor LicenceManager Komponente
final function GetIoncubeServerList()
{
$ret = null;
$i = 1;
while($check = $this->IoncubeProperty('servername'.$i))
{
$ret[] = $check;
$i++;
}
return $ret;
}
// @refactor LicenceManager Komponente
/**
* @return bool
*/
final function ServerOK()
{
$servername = (isset($_SERVER['SERVER_NAME']) && $_SERVER['SERVER_NAME'] != '')?$_SERVER['SERVER_NAME']:(isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:'');
$serverlist = $this->GetIoncubeServerList();
if(!$serverlist) {
return true;
}
foreach($serverlist as $check) {
if($servername == $check) {
return true;
}
}
return false;
}
// @refactor LicenceManager Komponente
final function IoncubeProperty($key)
{
if(!class_exists('License'))
{
if(is_file(dirname(dirname(__DIR__)).'/phpwf/plugins/class.license.php'))
{
include(dirname(dirname(__DIR__)).'/phpwf/plugins/class.license.php');
}
}
if(class_exists('License'))
{
if(!erpAPI::$license)erpAPI::$license = new License();
}
if(erpAPI::$license)return erpAPI::$license->getProperty($key);
if(method_exists('erpAPI','Ioncube_Property'))return erpAPI::Ioncube_Property($key);
if(function_exists('ioncube_license_properties'))
{
$data = ioncube_license_properties();
if($data && isset($data[$key]) && isset($data[$key]['value']))return $data[$key]['value'];
}
return false;
}
// @refactor LicenceManager Komponente
final function IoncubegetMaxUser()
{
return $this->IoncubeProperty('maxuser');
}
// @refactor LicenceManager Komponente
final function IoncubeHasExpired()
{
if($this->IoncubeProperty('expdate'))
{
if((int)$this->IoncubeProperty('expdate') < time())return true;
}
return false;
if(function_exists('ioncube_license_has_expired'))return ioncube_license_has_expired();
return false;
}
// @refactor LicenceManager Komponente
final function IoncubeServerOK()
{
if(function_exists('ioncube_license_matches_server'))return ioncube_license_matches_server();
return true;
}
// @refactor LicenceManager Komponente
final function IoncubeExpireInDays()
{
if(function_exists('ioncube_file_info'))
{
if($this->IoncubeProperty('expdate'))return round(((int)$this->IoncubeProperty('expdate')-time())/86400);
}
return false;
}
// @refactor LicenceManager Komponente
final function IoncubeBeforeExpire()
{
if(false === $this->IoncubeExpireInDays())return false;
return $this->IoncubeExpireInDays() < 42;
}
// @refactor LicenceManager Komponente
final function IoncubeExpireDate($format = 'd.m.Y')
{
if(function_exists('ioncube_file_info'))
{
$dat = $this->IoncubeProperty('expdate');
if(!$dat) {
return false;
}
return date($format,(int)$dat);
}
return false;
}
/**
* @return array|null
*/
public function getAppList()
{
if(!isset($this->appList[$this->app->Conf->WFdbname])) {
$this->appList[$this->app->Conf->WFdbname] = $this->app->getAppList();
}
return $this->appList[$this->app->Conf->WFdbname];
}
// @refactor LicenceManager Komponente
function ModuleBenutzeranzahlLizenzFehler($add = '', $typ = 'module', $vorlage = 0)
{
if(!method_exists($this->app->erp, 'IoncubeProperty')) {
return null;
}
if($typ === 'module')
{
if(strpos($add, 'shopimporter_') === 0) {
return null;
}
if($add === 'welcome' || $add === 'api' || $add === 'ajax') {
return null;
}
$anz = (int)$this->IoncubeProperty('moduleanzX'.str_replace('_','X',$add));
if($anz > 1) {
$anzadmin = (int)$this->app->DB->Select("SELECT count(id) FROM `user` WHERE activ = 1 AND type = 'admin'");
$rechte = (int)$this->app->DB->Select("SELECT count(u.i) FROM `user` u
INNER JOIN (SELECT DISTINCT `user` FROM `userrights` WHERE module = '$add' AND permission = 1) ur ON u.id = ur.`user`
WHERE activ = 1 AND type <> 'admin'
");
if($anzadmin + $rechte + 1 > $anz) {
return array('Error'=> 'Es '.($anz > 1?'sind':'ist').' nur '.$anz.' User für das Modul '.ucfirst($add).' lizenziert, es werden aber '.($anzadmin + $rechte + 1).' benötigt');
}
}
return null;
}
if($typ === 'vorlage' && $vorlage)
{
if(strpos($add, 'shopimporter_') === 0) {
return null;
}
if($add === 'welcome' || $add === 'api' || $add === 'ajax') {
return null;
}
$anz = (int)$this->IoncubeProperty('moduleanzX'.str_replace('_','X',$add));
if($anz > 1)
{
$anzadmin = (int)$this->app->DB->Select("SELECT count(id) FROM `user` WHERE activ = 1 AND type = 'admin'");
$bezeichnung = $this->app->DB->Select("SELECT bezeichnung FROM uservorlage WHERE id = '$vorlage' LIMIT 1");
if($bezeichnung == '') {
return null;
}
$rechte = (int)$this->app->DB->Select("SELECT count(u.i) FROM `user` u
INNER JOIN (SELECT DISTINCT `user` FROM `userrights` WHERE module = '$add' AND permission = 1) ur ON u.id = ur.`user`
WHERE activ = 1 AND type <> 'admin' AND vorlage != '".$this->app->DB->real_escape_string($bezeichnung)."'
");
$neueuser = (int)$this->app->DB->Select("SELECT count(u.id) FROM `user` u
WHERE activ = 1 AND type <> 'admin' AND vorlage = '".$this->app->DB->real_escape_string($bezeichnung)."'
");
if($anzadmin + $rechte + $neueuser > $anz) {
return array('Error'=> 'Es '.($anz > 1?'sind':'ist').' nur '.$anz.' User für das Modul '.ucfirst($add).' lizenziert, es werden aber '.($anzadmin + $rechte + $neueuser).' benötigt');
}
}
}
return null;
}
// @refactor LicenceManager Komponente
function OnlineshopsLizenzFehler($add = '')
{
if(!method_exists($this->app->erp, 'IoncubeProperty')) {
return false;
}
$shops = $this->app->DB->SelectArr("SELECT shoptyp,modulename FROM shopexport WHERE aktiv = 1 AND (shoptyp = 'intern' OR shoptyp = 'custom') AND modulename <> '' ORDER BY modulename");
if(!$shops) {
return false;
}
$counts = null;
foreach($shops as $shop)
{
if($shop['shoptyp'] === 'intern')
{
$modulename = $shop['modulename'];
}else{
if(preg_match_all('/(.*)\_(\d+).php/i',$shop['modulename'],$erg))
{
$modulename = $erg[1][0];
}else $modulename = '';
}
if($modulename != '')
{
if(!isset($counts[$modulename]))$counts[$modulename] = 0;
$counts[$modulename]++;
}
}
if($add != '')
{
if(substr($add,-4) === '.php')
{
if(preg_match_all('/(.*)\_(\d+).php/i',$add,$erg))
{
$add = $erg[1][0];
}else {
$add = '';
}
}
}
if($add != '')
{
if(!isset($counts[$add])) {
$counts[$add] = 0;
}
$counts[$add]++;
}
if($counts) {
foreach($counts as $k => $v) {
if($v <= 1) {
continue;
}
$anz = (int)$this->IoncubeProperty('moduleanzX'.str_replace('_','X',$k));
if($anz > 0 && $anz < $v) {
return array('Error'=> 'Es '.($anz > 1?'sind':'ist').' nur '.$anz.' Importer des Typs '.ucfirst(str_replace('shopimporter_','',$k)).' lizenziert');
}
}
}
return false;
}
function getApps()
{
/** @var Appstore $obj */
$obj = $this->LoadModul('appstore');
if(!empty($obj) && method_exists($obj,'getAppsList'))
{
return $obj->getAppsList();
}
return null;
}
function StartseiteMenu()
{
/** @var Welcome $obj */
$obj = $this->LoadModul('welcome');
if(!empty($obj) && method_exists($obj,'StartseiteMenu'))
{
$obj->StartseiteMenu();
}
}
function EventAPIAdd($eventname,$parameter,$module,$action,$kommentar="", $api = 0)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'EventAPIAdd'))
{
return $obj->EventAPIAdd($eventname,$parameter,$module,$action,$kommentar, $api);
}
}
function EventCall($id)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'EventCall'))
{
return $obj->EventCall($id);
}
}
function EventSendRequest($methodname,$xml,$hash,$parameter="",&$result_body="", $api = 0)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'EventSendRequest'))
{
return $obj->EventSendRequest($methodname,$xml,$hash,$parameter,$result_body, $api);
}
}
// @refactor Hook Komponente
function RemoveNavigationHook($module, $action = null)
{
if(empty($module)) {
return;
}
if($action)
{
$this->app->DB->Delete("DELETE FROM `hook_navigation` WHERE `module` = '".$this->app->DB->real_escape_string($module)."' AND `action` = '".$this->app->DB->real_escape_string($action)."'");
}else{
$this->app->DB->Delete("DELETE FROM `hook_navigation` WHERE `module` = '".$this->app->DB->real_escape_string($module)."'");
}
}
/**
* @param string $table
* @param string $uniqeCol
*/
public function repairNullIds($table, $uniqeCol = 'name')
{
$doppelteids = $this->app->DB->SelectArr(
sprintf(
'SELECT `id`, count(*) as `co` FROM `%s` GROUP BY `id` HAVING COUNT(*) > 1',
$table
)
);
if(empty($doppelteids)) {
$this->CheckAlterTable(sprintf("ALTER TABLE `%s` ADD PRIMARY KEY(`id`);", $table));
$maxid = 1+(int)$this->app->DB->Select(sprintf("SELECT max(id) FROM `%s`", $table));
$this->CheckAlterTable(
sprintf(
"ALTER TABLE `%s` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=%d",
$table,
$maxid
)
);
return;
}
foreach($doppelteids as $val) {
$maxid = 1+(int)$this->app->DB->Select(
sprintf("SELECT max(id) FROM `%s`", $table)
);
if(empty($uniqeCol)) {
for($i = 1; $i <= $val['co']; $i++) {
$this->app->DB->Update(
sprintf(
'UPDATE `%s`
SET `id` = %d WHERE `id` = %d
LIMIT 1',
$table, $maxid, $val['id']
)
);
}
continue;
}
$doppelte = $this->app->DB->SelectArr(
sprintf('SELECT * FROM `%s` WHERE id = %d', $table, $val['id'])
);
foreach($doppelte as $row) {
$this->app->DB->Update(
sprintf(
"UPDATE `%s`
SET id = %d WHERE id = %d AND `%s` = '%s'
LIMIT 1",
$table, $maxid, $val['id'], $uniqeCol, $val[$uniqeCol]
)
);
$maxid++;
}
}
$this->CheckAlterTable(sprintf("ALTER TABLE `%s` ADD PRIMARY KEY(`id`);", $table));
$maxid = 1+(int)$this->app->DB->Select(sprintf("SELECT max(id) FROM `%s`", $table));
$this->CheckAlterTable(
sprintf(
"ALTER TABLE `%s` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=%d",
$table,
$maxid
)
);
}
// @refactor Hook Komponente
function RegisterNavigationHook($module, $action, $first, $sec, $aftersec = '', $position = 0)
{
if(empty($module) || empty($action) || (String)$first === '') {
return;
}
$check = $this->app->DB->SelectRow(
"SELECT hn.id
FROM `hook_navigation` AS `hn`
WHERE hn.module = '".$this->app->DB->real_escape_string($module)."' AND hn.action = '".$this->app->DB->real_escape_string($action)."'
ORDER by hn.aktiv DESC
LIMIT 1"
);
if(!empty($check) && $check['id'] == 0) {
$this->repairNullIds('hook_navigation');
$check = $this->app->DB->SelectRow(
"SELECT hn.id
FROM `hook_navigation` AS `hn`
WHERE hn.module = '".$this->app->DB->real_escape_string($module)."' AND hn.action = '".$this->app->DB->real_escape_string($action)."'
ORDER by hn.aktiv DESC
LIMIT 1"
);
}
if($check) {
$this->app->DB->Update("UPDATE `hook_navigation` SET `aktiv` = 1, `first` = '".$this->app->DB->real_escape_string($first)."', `sec` = '".$this->app->DB->real_escape_string($sec)."', `aftersec` = '".$this->app->DB->real_escape_string($aftersec)."', `position` = '".$this->app->DB->real_escape_string($position)."' WHERE `id` = ".(int)$check['id'].' LIMIT 1');
}
else {
$this->app->DB->Insert("INSERT INTO `hook_navigation` (`module`, `action`, `first`, `sec`, `aftersec`, `position`, `aktiv`)
VALUES ('".$this->app->DB->real_escape_string($module)."','".$this->app->DB->real_escape_string($action)."',
'".$this->app->DB->real_escape_string($first)."','".$this->app->DB->real_escape_string($sec)."','".$this->app->DB->real_escape_string($aftersec)."','".$this->app->DB->real_escape_string($position)."','1')
");
}
}
// @refactor Hook Komponente
/**
* @param array $menu
*/
public function NavigationHooks(&$menu)
{
$hook_navigation = $this->app->DB->SelectArr(
"SELECT hn.*
FROM `hook_navigation` AS `hn`
WHERE hn.aktiv = 1 AND hn.first != '' AND hn.module != '' AND hn.action != ''
ORDER BY hn.first, hn.aftersec DESC, hn.position, hn.sec"
);
if(!$hook_navigation) {
return;
}
if($hook_navigation[0]['id'] === 0) {
$this->repairNullIds('hook_navigation');
$hook_navigation = $this->app->DB->SelectArr(
"SELECT hn.*
FROM `hook_navigation` AS `hn`
WHERE hn.aktiv = 1 AND hn.first != '' AND hn.module != '' AND hn.action != ''
ORDER BY hn.first, hn.aftersec DESC, hn.position, hn.sec"
);
}
foreach($menu as $k => $v) {
if(isset($v['first'])) {
$first[$v['first'][0]] = $k;
}
}
foreach($hook_navigation as $k => $v) {
if($k > 0 && $v['id'] > 0 && !empty($hook_navigation[$k-1]) && $hook_navigation[$k-1]['id'] > 0) {
if(
$v['module'] === $hook_navigation[$k-1]['module']
&& $v['action'] === $hook_navigation[$k-1]['action']
&& $v['sec'] === $hook_navigation[$k-1]['sec']
&& $v['first'] === $hook_navigation[$k-1]['first']
&& $v['aftersec'] === $hook_navigation[$k-1]['aftersec']
) {
$this->app->DB->Delete(sprintf('DELETE FROM `hook_navigation` WHERE `id` = %d LIMIT 1', $v['id']));
unset($hook_navigation[$k]);
continue;
}
}
if(!$this->RechteVorhanden($v['module'], $v['action'])) {
continue;
}
if($v['sec'] !== '' || !isset($first[$v['first']])) {
if($v['sec'] == '') {
$menu[] = array('first'=>array($v['first'], $v['module'],$v['action']));
$first[$v['first']] = (!empty($menu)?count($menu):0)-1;
}
elseif($v['sec'] != '' && !isset($first[$v['first']])){
$menu[] = array('first'=>array($v['first'], '',''),'sec'=>array(array($v['sec'],$v['module'],$v['action'])));
$first[$v['first']] = (!empty($menu)?count($menu):0)-1;
}
else{
if(isset($menu[$first[$v['first']]])) {
if($v['aftersec']) {
if(empty($menu[$first[$v['first']]]['sec'])) {
$ind = 0;
$menu[$first[$v['first']]]['sec'][$ind] = array($v['sec'],$v['module'],$v['action']);
}
else{
$found = false;
foreach($menu[$first[$v['first']]]['sec'] as $k2 => $v2) {
if($v2[0] == $v['aftersec']) {
$c = count($menu[$first[$v['first']]]['sec']);
for($k3 = $c; $k3 > $k2; $k3--) {
$menu[$first[$v['first']]]['sec'][$k3] = $menu[$first[$v['first']]]['sec'][$k3-1];
}
$ind = $k2 + 1;
$menu[$first[$v['first']]]['sec'][$ind] = array($v['sec'],$v['module'],$v['action']);
$found = true;
break;
}
}
if(!$found) {
$ind = empty($menu[$first[$v['first']]]['sec'])?0:count($menu[$first[$v['first']]]['sec']);
$menu[$first[$v['first']]]['sec'][$ind] = array($v['sec'],$v['module'],$v['action']);
}
}
}
else{
$ind = empty($menu[$first[$v['first']]]['sec'])?0:count($menu[$first[$v['first']]]['sec']);
$menu[$first[$v['first']]]['sec'][$ind] = array($v['sec'],$v['module'],$v['action']);
}
}
}
}
}
}
// @refactor ModuleRenderer Komponente
/**
* @param string $headline
* @param string $headline1
* @param string|array $headline2
*/
public function Headlines($headline = '', $headline1 = '', $headline2 = '')
{
if($headline) {
$this->kurzueberschrift = $headline;
$this->app->Tpl->Set('KURZUEBERSCHRIFT', $headline);
}
if($headline1) {
$this->kurzueberschrift1 = htmlspecialchars($headline1);
$this->app->Tpl->Set('KURZUEBERSCHRIFT1', ' '.$headline1);
}
if($this->kurzueberschrift && $this->backlink && $this->kurzueberschrift1) {
$this->app->Tpl->Set('KURZUEBERSCHRIFT', ''.$this->kurzueberschrift.'');
}
if($headline2) {
if(is_string($headline2)) {
$this->kurzueberschrift2 = ' '.(stripos($headline2,'')?$headline2:htmlspecialchars($headline2)).'';
$this->app->Tpl->Set('KURZUEBERSCHRIFT2', $this->kurzueberschrift2);
}
elseif(is_array($headline2)) {
$this->kurzueberschrift2 = ' ';
$first = true;
foreach($headline2 as $k => $v) {
if((String)$v !== '') {
if(!$first) {
$this->kurzueberschrift2 .= ' ';
}
$first = false;
if(!is_numeric($k)) {
$this->kurzueberschrift2 .= $k.' ';
}
$this->kurzueberschrift2 .= ''.htmlspecialchars($v).'';
}
}
$this->app->Tpl->Add('KURZUEBERSCHRIFT2', $this->kurzueberschrift2);
}
}
if(empty($headline) && !empty($this->kurzueberschrift)) {
$headline = $this->kurzueberschrift;
}
if(empty($headline1) && !empty($this->kurzueberschrift1)) {
$headline1 = $this->kurzueberschrift1;
}
$this->RunHook('HeadLines', 3, $headline, $headline1, $headline2);
}
function generateHash($id = 0)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'generateHashFromApi'))
{
return $obj->generateHashFromApi($id);
}
return '';
}
function XMLGruppe($id, $cdata = false)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'XMLGruppe'))
{
return $obj->XMLGruppe($id, $cdata);
}
return '';
}
function XMLAdresseKontakt($id, $cdata = false)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'XMLAdresseKontakt'))
{
return $obj->XMLAdresseKontakt($id, $cdata);
}
return '';
}
function XMLAdresse($id, $cdata = false)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'XMLAdresse'))
{
return $obj->XMLAdresse($id, $cdata);
}
}
function XMLAuftrag($id, $doctype = 'auftrag', $cdata = false)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'XMLAuftrag'))
{
return $obj->XMLAuftrag($id,$doctype, $cdata);
}
return '';
}
function XMLBenutzer($id, $cdata = false)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'XMLBenutzer'))
{
return $obj->XMLBenutzer($id, $cdata);
}
}
function XMLAdresseAccounts($filter=array(), $cdata = false)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'XMLAdresseAccounts'))
{
return $obj->XMLAdresseAccounts($filter, $cdata);
}
}
function XMLBerichte($id, $cdata = false){
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'XMLBerichte'))
{
return $obj->XMLBerichte($id, $cdata);
}
}
function XMLArtikelkontingente($filter=array(), $cdata = false)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'XMLArtikelkontingente'))
{
return $obj->XMLArtikelkontingente($filter, $cdata);
}
}
// @refactor PhysicalDimension Komponente
function GetGewichtbezeichnung()
{
$gewichtbezeichnung = $this->Firmendaten('gewichtbezeichnung');
if((String)$gewichtbezeichnung !== '')return $gewichtbezeichnung;
return 'kg';
}
// @refactor PhysicalDimension Komponente
function GewichtzuKgFaktor()
{
$faktor = (float)str_replace(',',',',$this->Firmendaten('gewichtzukgfaktor'));
if($faktor > 0)return $faktor;
return 1;
}
// @refactor DbHelper Komponente
function FormatGewicht($spalte)
{
return 'concat('.$spalte.",' ".$this->GetGewichtbezeichnung()."')";
}
// @refactor DbHelper Komponente
function FormatPreis($spalte, $stellen = null, $punkt = false)
{
if(is_null($stellen))return "if(trim(round( $spalte *100))+0 <> trim($spalte*100)+0, format($spalte, length( trim($spalte)+0)-length(round($spalte))-1 ".($punkt?"":" ,'de_DE'")."),format($spalte,2".($punkt?"":" ,'de_DE'")."))";
return "format($spalte,$stellen".($punkt?"":" ,'de_DE'").")";
}
/**
* @deprecated
*
* @param $value
*
* @return mixed
*/
function FromFormatZahlToDB($value)
{
$poskomma = strrpos($value, ',');
$pospunkt = strrpos($value, '.');
if($poskomma === false) {
return $value;
}
if($pospunkt === false) {
return str_replace(',','.', $value);
}
if($poskomma > $pospunkt) {
return str_replace(['.', ','], ['', '.'], $value);
}
return str_replace(',','', $value);
}
// @refactor Formater Komponente
function number_format_variable($value, $stellen = null)
{
if(is_null($stellen)) {
$ret = rtrim(number_format($value,8,',','.'),'0');
if(substr($ret,-1) === ',') {
$ret .= '0';
}
return $ret;
}
return number_format($value, $stellen,',','.');
}
// @refactor DbHelper Komponente
function BelegnummerSortierung($prefix = '')
{
$belegnummersortierungint = $this->Firmendaten('belegnummersortierungint');
if($belegnummersortierungint) {
if($prefix == '') {
return 'cast(belegnr as UNSIGNED)';
}
return 'cast('.$prefix.'.belegnr as UNSIGNED)';
}
if($prefix == '') {
return 'belegnr';
}
return $prefix.'.'.'belegnr';
}
// @refactor DbHelper Komponente
function FormatMenge($spalte, $decimals = 0)
{
return ('FORMAT('.$spalte.','.$decimals.',\'de_DE\')');
// return "replace(trim($spalte)+0,'.',',')";
}
static function add_alias(string $text, $alias = false) {
if (empty($alias)) {
return($text);
}
else {
return ($text." as `$alias`");
}
}
// @refactor DbHelper Komponente
function FormatDate(string $spalte, string $alias = null)
{
return $this->add_alias("DATE_FORMAT($spalte,'%d.%m.%Y')", $alias);
}
// @refactor DbHelper Komponente
function FormatDateShort(string $spalte, string $alias = null)
{
return $this->add_alias("DATE_FORMAT($spalte,'%d.%m.%y')", $alias);
}
// @refactor DbHelper Komponente
function FormatDateTimeShort(string $spalte, string $alias = null)
{
return $this->add_alias("DATE_FORMAT($spalte,'%d.%m.%y %H:%i')", $alias);
}
// @refactor DbHelper Komponente
function FormatDateTime(string $spalte, string $alias = null)
{
return $this->add_alias("DATE_FORMAT($spalte,'%d.%m.%Y %H:%i:%s')", $alias);
}
public function XMLExportVorlage($id,$filter=array(), $cdata = false)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'XMLExportVorlage'))
{
return $obj->XMLExportVorlage($id, $filter, $cdata);
}
}
/**
* Es werden Werte nur hinzugefuegt falls der Wert noch nicht existiert bzw. leer ist
*
* @refactor in ShopImporter Module
*
* @param int $shop Shopid
* @param int $artikel Artikelid
* @param array $arr Array zum Einfuegen / Updaten
* @param bool $escape Werte werden fuer DB escaped
*
* @return bool wenn Daten OK true sonst falsch
*/
public function AddShopArtikelIfEmpty($shop, $artikel, $arr, $escape = true)
{
if(empty($artikel) || empty($shop) || empty($arr)){
return false;
}
$bearbeiter = $this->GetBearbeiter(true);
$oldarr = array();
$old = $this->app->DB->SelectArr("SELECT min(id) as id, name,wert FROM shopexport_artikel
WHERE shopid = '$shop' AND artikel = '$artikel' GROUP BY name,wert");
if(!empty($old))
{
foreach($old as $v)
{
$oldarr[$v['name']] = array('id'=>$v['id'],'wert'=>$v['wert']);
}
}
foreach($arr as $k => $v)
{
if($k)
{
$check = !empty($oldarr[$k])?$oldarr[$k]['id']:0;
if(!$check)
{
$this->app->DB->Insert("INSERT INTO shopexport_artikel (shopid, artikel, name) VALUES ('$shop','$artikel','".$this->app->DB->real_escape_string($k)."')");
$new = $this->app->DB->GetInsertID();
$check = $new;
}else{
$new = null;
}
if(!empty($new) || ($oldarr[$k]['wert'] != $v && empty($oldarr[$k]['wert']))){
if($escape){
$this->app->DB->Update("UPDATE shopexport_artikel SET bearbeiter = '$bearbeiter', wert = '" . $this->app->DB->real_escape_string($v) . "' WHERE id = '$check' LIMIT 1");
}else{
$this->app->DB->Update("UPDATE shopexport_artikel SET bearbeiter = '$bearbeiter', wert = '$v' WHERE id = '$check' LIMIT 1");
}
}
}
}
return true;
}
/**
* @deprecated
* @refactor in User Klasse
*
* @param bool $escaped wenn true real_escaped zurueck
*
* @return string gibt Username oder Cronjob zurueck
*/
public function GetBearbeiter($escaped = false)
{
$bearbeiter = 'Cronjob';
if(!empty($this->app->User) && method_exists($this->app->User,'GetName'))
{
$bearbeiter = $this->app->User->GetName();
if($escaped)
{
$bearbeiter = $this->app->DB->real_escape_string($bearbeiter);
}
}
return $bearbeiter;
}
/**
* @refactor in ShopImport Module
*
* @param int $shop Shopid
* @param int $artikel Artikelid
* @param array $arr Array das Geaendert / Eingefuegt werden soll
* @param bool $escape Escapen fuer DB
*
* @return bool
*/
public function SaveShopArtikel($shop, $artikel, $arr, $escape = true)
{
if(empty($artikel) || empty($shop) || empty($arr)){
return false;
}
$bearbeiter = $this->GetBearbeiter(true);
$oldarr = array();
$old = $this->app->DB->SelectArr(
sprintf(
"SELECT MIN(id) as id, MAX(id) AS `maxid`, `name`, `wert`
FROM `shopexport_artikel`
WHERE `shopid` = %d AND `artikel` = %d
GROUP BY `name`, `wert`",
$shop, $artikel
)
);
if(!empty($old)) {
foreach($old as $v) {
$oldarr[
$this->app->DB->real_escape_string($v['name'])
] = array('id'=>$v['id'],'wert'=>$v['wert'],'maxid' => $v['maxid']);
}
}
foreach($arr as $k => $v) {
if(empty($k)) {
continue;
}
$nameForDb = $k;
$valueForDb = $v;
if($escape){
$nameForDb = $this->app->DB->real_escape_string($k);
$valueForDb = $this->app->DB->real_escape_string($v);
}
$check = !empty($oldarr[$k])?$oldarr[$k]['id']:0;
$new = null;
if(!$check) {
$this->app->DB->Insert(
sprintf(
"INSERT INTO `shopexport_artikel` (shopid, artikel, `name`,wert)
VALUES (%d,%d,'%s','%s')",
$shop, $artikel, $nameForDb, $valueForDb
)
);
$new = $this->app->DB->GetInsertID();
}
if($check && (!empty($new) || $oldarr[$k]['wert'] != $v)) {
$this->app->DB->Delete(
sprintf(
"DELETE FROM `shopexport_artikel`
WHERE `artikel` = %d AND `shopid` = %d AND `name` = '%s' AND `id` <> %d",
$artikel, $shop, $nameForDb, $check
)
);
$this->app->DB->Update(
"UPDATE shopexport_artikel SET bearbeiter = '$bearbeiter', wert = '$valueForDb' WHERE id = '$check' LIMIT 1"
);
}
elseif($check && $oldarr[$k]['id'] != $oldarr[$k]['maxid']) {
$this->app->DB->Delete(
sprintf(
"DELETE FROM `shopexport_artikel`
WHERE `artikel` = %d AND `shopid` = %d AND `name` = '%s' AND `id` <> %d",
$artikel, $shop, $nameForDb, $check
)
);
}
}
return true;
}
// @refactor in Placetel Module
function GetPhoneLink($adresse=0,$ansprechpartner=0,$telefon="")
{
$username = $this->app->User->GetUsername();
$accounts = $this->app->erp->GetKonfiguration("placetel_list_accounts");
$tmp = explode(PHP_EOL,trim($accounts));
$sipuid = false;
if($this->app->erp->RechteVorhanden('placetel','call'))
{
$this->app->Tpl->Set('JSPLACETEL','
function call(id, dummy)
{
$.ajax({
url: \'index.php?module=placetel&action=call&id=\'+id,
type: \'POST\',
dataType: \'json\',
data: {},
success: function(data) {
if(data)
{
}
}
});
}
');
$ctmp = !empty($tmp)?count($tmp):0;
for($i=0;$i<$ctmp;$i++)
{
$subtmp = explode(':',trim($tmp[$i]));
if((!empty($subtmp)?count($subtmp):0)>0)
{
$subtmp[0] = trim($subtmp[0]);
$subtmp[1] = !empty($subtmp[1])?trim($subtmp[1]):'';
if($subtmp[0]==$username)
{
$sipuid = $subtmp[1];
break;
}
}
}
}
if($ansprechpartner <=0)
{
$typ = $this->app->DB->Select("SELECT if(telefon='$telefon' AND telefon!='','1',if(mobil='$telefon' AND mobil!='','2','')) FROM adresse WHERE id='$adresse' LIMIT 1");
if($typ==1 OR $typ==2){
$typid = $adresse;
}
} else {
$typ = $this->app->DB->Select("SELECT if(telefon='$telefon' AND telefon!='','3',if(mobil='$telefon' AND mobil!='','4','')) FROM ansprechpartner WHERE id='$ansprechpartner' LIMIT 1");
if($typ==3 OR $typ==4){
$typid = $ansprechpartner;
}
}
// 1 = telefon adresse, 2 = mobil adresse, 3 telefon ansprechpartner, 4 mobil ansprechpartner
if($telefon!='') {
$telefon = str_replace('/','',$telefon);
$telefon = str_replace(' ','',$telefon);
if($sipuid) {
return "app->Conf->WFconf['defaulttheme']."/images/phone.png\" class=\"iconininput\" alt=\"anrufen\" />";
}
return "app->Conf->WFconf['defaulttheme']."/images/phone.png\" class=\"iconininput\" alt=\"anrufen\" />";
}
}
public function GetArtikelunterbaumids($id, &$arr, $lvl = 0)
{
/** @var Artikelbaum $obj */
$obj = $this->LoadModul('artikelbaum');
if(!empty($obj) && method_exists($obj, 'getArticleSubtreeIds')) {
$obj->getArticleSubtreeIds($id, $arr, $lvl);
}
}
// @refactor in Shopimport Module
public function GetShopArtikel($shop, $artikel, $name = '')
{
$ret = null;
if((int)$artikel <= 0 || (int)$shop <= 0){
return $ret;
}
$arr = $this->app->DB->SelectArr('SELECT `name`, `wert` FROM shopexport_artikel WHERE shopid = '.(int)$shop.' AND artikel = '.(int)$artikel." AND name <> ''".(!empty($name)?" AND name = '".$this->app->DB->real_escape_string($name)."' ":''));
if(!empty($arr))
{
foreach($arr as $v){
$ret[$v['name']] = $v['wert'];
}
}
if(!empty($name))
{
return !empty($ret[$name])?$ret[$name]:'';
}
return $ret;
}
public function XMLArtikel($id, $api = 0)
{
/** @var Api $obj */
$obj = $this->LoadModul('api');
if(!empty($obj) && method_exists($obj,'XMLArtikel'))
{
return $obj->XMLArtikel($id, $api);
}
}
// @refactor in Uservorlage Modul
function AbgleichBenutzerVorlagen($userid=0, $vorlage = 0, $module = '', $action = '')
{
$bezeichnung = '';
if($vorlage != 0)
{
$bezeichnung = $this->app->DB->Select("SELECT bezeichnung FROM uservorlage WHERE id = '$vorlage' LIMIT 1");
}
if($userid == 0 && $vorlag > 0 && $module != '' && $action != '')
{
$permission = $this->app->DB->Select("SELECT permission FROM uservorlagerights WHERE vorlage = '".$id_vorlage."' AND module = '$module' AND action = '$action' LIMIT 1");
}
// alle vorlagen ind ei Leute kopieren
if($userid<=0){
$user = $this->app->DB->SelectArr("SELECT * FROM user" . ($bezeichnung != '' ? " WHERE vorlage like '$bezeichnung' " : ''));
}
else{
$user = $this->app->DB->SelectArr("SELECT * FROM user WHERE id='$userid'");
}
$startzeit = microtime(true);
$cuser = !empty($user)?count($user):0;
$grantingUserId = $this->app->User->GetID();
$grantingUserName = $this->app->DB->Select("SELECT username FROM user WHERE id=$grantingUserId");
$userPermission = $this->app->Container->get('UserPermissionService');
for($i=0;$i<$cuser;$i++)
{
$user[$i]['vorlage'] = strtolower($user[$i]['vorlage']);
if($vorlage)
{
$id_vorlage = $vorlage;
}else{
$id_vorlage = $this->app->DB->Select("SELECT id FROM uservorlage WHERE bezeichnung LIKE '".$user[$i]['vorlage']."' LIMIT 1");
}
if($id_vorlage == $vorlage || $vorlage == 0)
{
$receivingUserId = $user[$i]['id'];
$receivingUserName = $this->app->DB->Select("SELECT username FROM user WHERE id=$receivingUserId");
// neue eintraege
if($userid == 0 && $vorlag > 0 && $module != '' && $action != '')
{
$this->app->DB->Delete("DELETE FROM userrights WHERE user = '".$user[$i]['id']."' AND module='$module' AND action = '$action'");
try {
$userPermission->log($grantingUserId,$grantingUserName,$receivingUserId,$receivingUserName,$module,$action,false);
}catch (Exception $ex){
$this->app->erp->LogFile('Fehler bei Zuweisung Rechtehistore',$ex->getMessage());
}
$this->app->DB->Insert("INSERT INTO userrights (user, module, action, permission) VALUES ('".$user[$i]['id']."','$module','$action','$permission')");
try {
$userPermission->log($grantingUserId,$grantingUserName,$receivingUserId,$receivingUserName,$module,$action,true);
}catch (Exception $ex){
$this->app->erp->LogFile('Fehler bei Zuweisung Rechtehistore',$ex->getMessage());
}
}else{
$permissions = $this->app->DB->SelectArr("SELECT module, action,permission
FROM uservorlagerights WHERE vorlage = '".$id_vorlage."' ".($module != ''?" AND module = '$module' ":"").($action != ''?" AND action = '$action'":''));
foreach($permissions as $permission){
try {
$userPermission->log($grantingUserId,$grantingUserName,$receivingUserId,$receivingUserName,$permission['module'],$permission['action'],$permission['permission']);
}catch (Exception $ex){
$this->app->erp->LogFile('Fehler bei Zuweisung Rechtehistore',$ex->getMessage());
}
}
$this->app->DB->Update("REPLACE INTO userrights (user, module,action,permission) (SELECT '".$user[$i]['id']."',module, action,permission
FROM uservorlagerights WHERE vorlage = '".$id_vorlage."' ".($module != ''?" AND module = '$module' ":"").($action != ''?" AND action = '$action'":'').") ");
$neuesquery = $this->app->DB->Query("Select * from userrights where user = ".$user[$i]['id']." ".($module != ''?" AND module = '$module' ":"").($action != ''?" AND action = '$action'":'')." order by module, action, id desc");
if($neuesquery)
{
$aktmodule = false;
$aktaction = false;
while($v = $this->app->DB->Fetch_Array($neuesquery))
{
if($aktaction != $v['action'] || $aktmodule != $v['module'])
{
$aktaction = $v['action'];
$aktmodule = $v['module'];
} else {
$this->app->DB->Delete("DELETE FROM userrights where id = ".$v['id']);
}
}
$this->app->DB->free($neuesquery);
}
}
}
}
}
// @refactor in Poll Komponente (oder Welcome Modul)
// @refactor replace stringcleaner? also validate options_json
function UserEvent($invisible = false)
{
/** @var \Xentral\Modules\SystemNotification\Service\NotificationInterface $notifyService */
$notifyService= $this->app->Container->get('NotificationService');
/** @var \Xentral\Modules\SystemNotification\Gateway\NotificationGateway $notifyGateway */
$notifyGateway = $this->app->Container->get('NotificationGateway');
$messages = $notifyGateway->findByUserId($this->app->User->GetID(), 0, 5);
$result = array();
if((!empty($messages)?count($messages):0) > 0) {
$cleaner = new Stringcleaner($this->app);
foreach ($messages as $message) {
// xss prevention
$message['title'] = $cleaner->CleanString($message['title'], 'nojs');
$message['message'] = $cleaner->CleanString($message['message'], 'nojs');
$message['options'] = [];
$messageOptions = !empty($message['options_json']) ? json_decode($message['options_json'], true) : null;
if (!empty($messageOptions['id'])) {
$message['options']['id'] = strip_tags($messageOptions['id']);
}
if (!empty($messageOptions['buttons'])) {
$message['options']['buttons'] = [];
foreach ($messageOptions['buttons'] as $messageButton) {
$messageButtonAttrs = [];
foreach ($messageButton as $buttonAttrName => $buttonAttrValue) {
if ($buttonAttrName === 'link') {
$messageButtonAttrs[htmlspecialchars($buttonAttrName)] = $cleaner->CleanString($buttonAttrValue, 'nojs');
} else{
$messageButtonAttrs[htmlspecialchars($buttonAttrName)] = htmlspecialchars($buttonAttrValue);
}
}
$message['options']['buttons'][] = $messageButtonAttrs;
}
}
// END xss prevention
$result[] = [
'event' => 'notification',
'type' => $message['type'],
'title' => $message['title'],
'message' => $message['message'],
'options' => !empty($message['options']) ? $message['options'] : null,
'priority' => (int)$message['priority'] === 1,
];
// Delete processed messages
$notifyService->delete($message['id']);
}
}
if($this->app->erp->RechteVorhanden('chat','list')) {
$userId = $this->app->User->GetID();
$registrierDatum = $this->app->DB->Select("SELECT u.logdatei FROM `user` AS u WHERE u.id='".$userId."'");
$ungelesenOeffentlich = (int)$this->app->DB->Select(
"SELECT COUNT(c.id)
FROM chat AS c
LEFT JOIN chat_gelesen AS g ON c.id = g.message AND (g.user = '".$userId."' OR g.user = 0)
WHERE c.user_to='0' AND c.zeitstempel > '".$registrierDatum."'
AND g.id IS NULL"
);
$ungelesenPrivat = (int)$this->app->DB->Select(
"SELECT COUNT(c.id)
FROM chat AS c
INNER JOIN `user` AS u ON c.user_from = u.id
LEFT JOIN chat_gelesen AS g ON c.id = g.message
WHERE u.activ = 1 AND c.user_to='".$userId."'
AND g.id IS NULL"
);
$anzchat = $ungelesenOeffentlich + $ungelesenPrivat;
if($anzchat>0) {
$result[] = array('event'=>'chatbox','sound'=>0, 'message'=>$anzchat);
}
}
if((!empty($result)?count($result):0)>0){
return $result;
}
return false;
}
/**
* @deprecated
*
* @param bool $delete
*
* @return array|void
*/
function UserEventNachrichten($delete = false)
{
$user = (int)$this->app->User->GetID();
if(!$user)return;
$adresse = (int)$this->app->DB->Select("SELECT adresse FROM user WHERE id = '".$user."' LIMIT 1");
if($adresse)
{
$_gruppen = $this->app->DB->SelectArr("SELECT distinct parameter as gruppe FROM adresse_rolle WHERE adresse = '$adresse' AND subjekt = 'Mitglied' AND (bis = '0000-00-00' OR bis >= date(now())) AND parameter > 0");
if($_gruppen)
{
foreach($_gruppen as $gruppe)
{
$gruppen[] = " b.gruppe = '".(int)$gruppe['gruppe']."' ";
}
}
}
if(!empty($gruppen))
{
$subwhere = implode(' OR ',$gruppen);
$nachrichten = $this->app->DB->SelectArr("SELECT b.* FROM boxnachrichten b WHERE (b.user = '$user' OR ($subwhere)) AND (ablaufzeit = 0 OR
TIME_TO_SEC(
TIMEDIFF(
now(),
zeitstempel
) <= ablaufzeit
)
) ORDER BY ablaufzeit > 0 DESC, prio DESC, zeitstempel");
}else{
$nachrichten = $this->app->DB->SelectArr("SELECT b.* FROM boxnachrichten b WHERE user = '$user' AND (ablaufzeit = 0 OR
TIME_TO_SEC(
TIMEDIFF(
now(),
zeitstempel
) <= ablaufzeit
)
) ORDER BY ablaufzeit > 0 DESC, prio DESC, zeitstempel");
}
if($nachrichten)
{
if($delete)$this->app->DB->Delete("DELETE from boxnachrichten WHERE id = '".$nachrichten[0]['id']."' LIMIT 1");
return array('anzahl'=>(!empty($nachrichten)?count($nachrichten):0),'nachricht'=>reset($nachrichten));
}
return array('anzahl'=>0);
}
/**
* @deprecated
*
* @param $user
* @param $gruppe
* @param $bezeichnung
* @param string $nachricht
* @param int $prio
* @param int $ablaufzeit
* @param int $beep
* @param string $objekt
* @param int $parameter
* @param bool $delete
*
* @return void
*/
function AddUserGruppenNachricht($user, $gruppe, $bezeichnung, $nachricht = '', $prio = 0,$ablaufzeit = 0, $beep = 0, $objekt = '', $parameter = 0, $delete = false)
{
$parameter = (int)$parameter;
$beep = (int)$beep;
$objekt = $this->app->DB->real_escape_string($objekt);
if($delete == true)
{
if(!empty($objekt) && !empty($parameter))$this->app->DB->Delete("DELETE FROM boxnachrichten WHERE objekt like '".$objekt."' AND parameter = '$parameter' ");
return;
}
if($delete && is_numeric($delete))
{
$delete = (int)$delete;
$this->app->DB->Delete("DELETE FROM boxnachrichten WHERE id = '$delete' LIMIT 1");
return;
}
$user = (int)$user;
$gruppe = (int)$gruppe;
$prio = (int)$prio;
$ablaufzeit = (int)$ablaufzeit;
$bezeichnung = $this->app->DB->real_escape_string($bezeichnung);
$nachricht = $this->app->DB->real_escape_string($nachricht);
$this->app->DB->Insert("INSERT INTO boxnachrichten (user, gruppe, bezeichnung, nachricht, prio, ablaufzeit, objekt, parameter, beep) VALUES (
'$user','$gruppe','$bezeichnung','$nachricht','$prio','$ablaufzeit','$objekt','$parameter','$beep'
)");
return $this->app->DB->GetInsertID();
}
// @refactor FileLock Komponente
function ProzessLock($name)
{
$fp = @fopen($this->GetTMP()."lock_". $name . '.lock', 'w+');
if($fp)
{
if (flock($fp, LOCK_EX)) {
ftruncate($fp, 0);
fwrite($fp, "Write something here\n");
return $fp;
}
@fclose($fp);
}
return false;
}
// @refactor FileLock Komponente
function ProzessUnlock($fp)
{
if(gettype($fp) != 'resource') return;
fflush($fp); // leere Ausgabepuffer bevor die Sperre frei gegeben wird
flock($fp, LOCK_UN); // Gib Sperre frei
fclose($fp);
}
// @refactor Formater Komponente
function ConvertToBytes($tmp)
{
$tmp = trim($tmp);
$last = strtolower($tmp[strlen($tmp)-1]);
switch($last)
{
case 'g':
$tmp *= 1024;
case 'm':
$tmp *= 1024;
case 'k':
$tmp *= 1024;
}
return $tmp;
}
// @refactor SystemInformation Komponente
function MaxUploadFileSize()
{
//select maximum upload size
$max_upload = $this->ConvertToBytes(ini_get('upload_max_filesize'));
$max_post = $this->ConvertToBytes(ini_get('post_max_size'));
$memory_limit = $this->ConvertToBytes(ini_get('memory_limit'));
return min($max_upload, $max_post, $memory_limit);
}
// @refactor Document Komponente
public function GetSpracheBeleg($type, $id)
{
if(!empty($this->sprachen) && !empty($this->sprachen[$type]) && !empty($this->sprachen[$type][$id]))
{
return $this->sprachen[$type][$id];
}
$docArr = $this->app->DB->SelectRow(sprintf('SELECT sprache, adresse FROM `%s` WHERE id = %d', $type, $id));
$sprache = !empty($docArr)?$docArr['sprache']:$this->app->DB->Select("SELECT sprache FROM $type WHERE id='$id' LIMIT 1");
if($sprache=='') {
$adresse = !empty($docArr)?$docArr['adresse']:$this->app->DB->Select("SELECT adresse FROM $type WHERE id='$id' LIMIT 1");
$sprache = $this->app->DB->Select("SELECT sprache FROM adresse WHERE id='$adresse' AND geloescht=0 LIMIT 1");
}
if($sprache=='') {
$sprache="de";
}
$this->sprachen[$type][$id] = $sprache;
return $sprache;
}
public function GetSpracheBelegISO($type, $id)
{
$language = $this->GetSpracheBeleg($type, $id);
if(strlen($language) > 2)
{
$language = $this->app->DB->Select("SELECT iso FROM sprachen WHERE alias='$language' ORDER by aktiv=1 LIMIT 1");
}
return $language;
}
// @refactor Document Komponente
function BelegVersand($typ,$id,$versandart,$drucker="")
{
if($typ!="rechnung" && $typ!="angebot" && $typ!="auftrag" && $typ!="gutschrift" && $typ!="lieferschein" && $typ!="reisekosten")
return;
if($versandart!="email" && $versandart!="brief")
return;
$projekt = $this->app->DB->Select("SELECT projekt FROM $typ WHERE id='$id' LIMIT 1");
$name = $this->app->DB->Select("SELECT name FROM $typ WHERE id='$id' LIMIT 1");
$email = $this->app->DB->Select("SELECT email FROM $typ WHERE id='$id' LIMIT 1");
$adresse = $this->app->DB->Select("SELECT adresse FROM $typ WHERE id='$id' LIMIT 1");
// pruefe ob immer per per Papier oder immer per mail
$rechnung_papier = $this->app->DB->Select("SELECT rechnung_papier FROM adresse WHERE id='$adresse' LIMIT 1");
$rechnung_permail = $this->app->DB->Select("SELECT rechnung_permail FROM adresse WHERE id='$adresse' LIMIT 1");
$rechnung_anzahlpapier = $this->app->DB->Select("SELECT rechnung_anzahlpapier FROM adresse WHERE id='$adresse' LIMIT 1");
if($rechnung_papier=="1" && $typ=="rechnung") $versandart="brief";
if($rechnung_permail=="1" && $typ=="rechnung") $versandart="email";
$sprache = $this->app->DB->Select("SELECT sprache FROM $typ WHERE id='$id' LIMIT 1");
if($sprache=="")
$sprache = $this->app->DB->Select("SELECT sprache FROM adresse WHERE id='$adresse' AND geloescht=0 LIMIT 1");
if($sprache=='') {
$sprache='deutsch';
}
$emailtext = $this->Geschaeftsbriefvorlage($sprache,$typ,$projekt,$name,$id);
$idvorlage = $this->GetGeschaeftsBriefID($typ,$sprache,$projekt);
$footer = $this->Grussformel($projekt,$sprache);
if($footer!="") $emailtext['text'] = $emailtext['text']."\r\n".$footer;
$this->BriefpapierHintergrundDisable($drucker);
switch($typ)
{
case "rechnung":
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?true:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('RechnungPDFCustom'))
{
$Brief = new RechnungPDFCustom($this->app,$projekt);
}else{
$Brief = new RechnungPDF($this->app,$projekt);
}
$Brief->GetRechnung($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
unlink($tmpfile);
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?false:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('RechnungPDFCustom'))
{
$Brief = new RechnungPDFCustom($this->app,$projekt);
}else{
$Brief = new RechnungPDF($this->app,$projekt);
}
$Brief->GetRechnung($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
break;
case "angebot":
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?true:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('AngebotPDFCustom'))
{
$Brief = new AngebotPDFCustom($this->app,$projekt);
}else{
$Brief = new AngebotPDF($this->app,$projekt);
}
$Brief->GetAngebot($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
unlink($tmpfile);
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?false:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('AngebotPDFCustom'))
{
$Brief = new AngebotPDFCustom($this->app,$projekt);
}else{
$Brief = new AngebotPDF($this->app,$projekt);
}
$Brief->GetAngebot($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
break;
case "auftrag":
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?true:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('AuftragPDFCustom'))
{
$Brief = new AuftragPDFCustom($this->app,$projekt);
}else{
$Brief = new AuftragPDF($this->app,$projekt);
}
$Brief->GetAuftrag($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
unlink($tmpfile);
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?false:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('AuftragPDFCustom'))
{
$Brief = new AuftragPDFCustom($this->app,$projekt);
}else{
$Brief = new AuftragPDF($this->app,$projekt);
}
$Brief->GetAuftrag($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
break;
case "bestellung":
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?true:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('BestellungPDFCustom'))
{
$Brief = new BestellungPDFCustom($this->app,$projekt);
}else{
$Brief = new BestellungPDF($this->app,$projekt);
}
$Brief->GetBestellung($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
unlink($tmpfile);
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?false:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('BestellungPDFCustom'))
{
$Brief = new BestellungPDFCustom($this->app,$projekt);
}else{
$Brief = new BestellungPDF($this->app,$projekt);
}
$Brief->GetBestellung($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
break;
case "preisanfrage":
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?true:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('PreisanfragePDFCustom'))
{
$Brief = new PreisanfragePDFCustom($this->app,$projekt);
}else{
$Brief = new PreisanfragePDF($this->app,$projekt);
}
$Brief->GetPreisanfrage($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
unlink($tmpfile);
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?false:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('PreisanfragePDFCustom'))
{
$Brief = new PreisanfragePDFCustom($this->app,$projekt);
}else{
$Brief = new PreisanfragePDF($this->app,$projekt);
}
$Brief->GetPreisanfrage($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
break;
case "produktion":
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?true:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('ProduktionPDFCustom'))
{
$Brief = new ProduktionPDFCustom($this->app,$projekt);
}else{
$Brief = new ProduktionPDF($this->app,$projekt);
}
$Brief->GetProduktion($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
unlink($tmpfile);
$this->app->erp->BriefpapierHintergrunddisable = $versandart === 'email'?false:!$this->app->erp->BriefpapierHintergrunddisable;
if(class_exists('ProduktionPDFCustom'))
{
$Brief = new ProduktionPDFCustom($this->app,$projekt);
}else{
$Brief = new ProduktionPDF($this->app,$projekt);
}
$Brief->GetProduktion($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument(true);
break;
}
if($rechnung_anzahlpapier > 1 && $typ==='rechnung' && $versandart==='brief')
{
for($ra_i=0;$ra_i<$rechnung_anzahlpapier;$ra_i++)
{
$sendtmp[]=$tmpfile;
}
} else {
$sendtmp = array($tmpfile);
}
//$this->LogFile("BelegeVersand T $typ I $id V $versandart Email $email Name $name betreff ".$emailtext['betreff']);
if($drucker<0)
$drucker = $this->app->DB->Select("SELECT standarddrucker FROM user WHERE id='".$this->app->User->GetID()."' LIMIT 1");
else
$drucker = $this->app->DB->Select("SELECT id FROM drucker WHERE id='".$drucker."' LIMIT 1");
if($drucker <=0)
$drucker = $this->Firmendaten('standardversanddrucker');
if($versandart==='email') {
if(!$this->isHTML($emailtext['text'])){
$emailtext['text'] = nl2br($emailtext['text']);//str_replace("\r\n", "
", $emailtext['text']);
}
if(
in_array(
$typ,
['auftrag', 'rechnung','gutschrift','angebot','bestellung','retoure','proformarechnung','lieferschein']
)
) {
$dateien = [$tmpfile];
if($typ === 'auftrag'){
$stichwoerter = $this->app->DB->SelectArr("SELECT * FROM datei_stichwoerter WHERE objekt='geschaeftsbrief_vorlagen' AND parameter='$idvorlage' AND parameter > 0");
if($stichwoerter){
foreach ($stichwoerter as $v) {
$dateiname = str_replace(' ', '_', $this->app->erp->GetDateiName($v['datei']));
if($dateiname){
$dateiinhalt = $this->app->erp->GetDatei($v['datei']);
if($handle = fopen(rtrim($this->app->erp->GetTMP(), '/') . "/" . $dateiname, "wb")){
fwrite($handle, $dateiinhalt);
fclose($handle);
$dateien[] = rtrim($this->app->erp->GetTMP(), '/') . "/" . $dateiname;
$dateienIds[] = $v['datei'];
}
}
}
}
}
$stichwoerterAnhaenge = $this->app->DB->SelectArr("SELECT * FROM datei_stichwoerter WHERE subjekt = 'Anhang' AND objekt = '$typ' AND parameter = '$id' AND parameter > 0");
if($stichwoerterAnhaenge)
{
foreach($stichwoerterAnhaenge as $v)
{
$dateiname = str_replace(' ','_',$this->app->erp->GetDateiName($v['datei']));
if($dateiname && !in_array($v['datei'], $dateienIds))
{
$dateiinhalt = $this->app->erp->GetDatei($v['datei']);
if($handle = fopen (rtrim($this->app->erp->GetTMP(),'/')."/".$dateiname, "wb"))
{
fwrite($handle, $dateiinhalt);
fclose($handle);
$dateien[] = rtrim($this->app->erp->GetTMP(),'/')."/".$dateiname;
}
}
}
}
$this->DokumentSend($adresse,$typ, $id, $versandart,$emailtext['betreff'],$emailtext['text'],$dateien,"","",$projekt,$email, $name);
if($dateien && (!empty($dateien)?count($dateien):0) > 1)
{
for($i = 1; $i < (!empty($dateien)?count($dateien):0); $i++)
{
if(@is_file($dateien[$i])){
@unlink($dateien[$i]);
}
}
}
}else{
$this->DokumentSend($adresse,$typ, $id, $versandart,$emailtext['betreff'],$emailtext['text'],array($tmpfile),"","",$projekt,$email, $name);
}
}
else{
$this->DokumentSend($adresse, $typ, $id, $versandart, $emailtext['betreff'], $emailtext['text'], $sendtmp, $drucker, "", $projekt, $email, $name);
}
if($this->Firmendaten("belegeinanhang")=="1") {
$fileid = $this->CreateDateiWithStichwort($tmpfile, $module,'','',$tmpfile, $this->app->User->GetName() ,$typ,$typ, $id, "",false);
}
/*
$fileid = $this->CreateDatei($tmpfile,$module,"","",$tmpfile,$this->app->User->GetName());
$this->AddDateiStichwort($fileid,$typ,$typ,$id,false);
*/
$ansprechpartner = $name." <".$email.">";
$this->app->DB->Insert("INSERT INTO dokumente_send
(id,dokument,zeit,bearbeiter,adresse,parameter,art,betreff,text,projekt,ansprechpartner,versendet,dateiid)
VALUES ('','$typ',NOW(),'".$this->app->User->GetName()."',
'$adresse','$id','$versandart','".$emailtext['betreff']."','".$emailtext['text']."','$projekt','$ansprechpartner',1,'$fileid')");
unlink($tmpfile);
if($typ==='rechnung' || $typ==='angebot' || $typ==='gutschrift')
{
if($typ === 'rechnung')
{
$this->closeInvoice($id,'freigegeben');
}
$this->app->DB->Update("UPDATE $typ SET status='versendet' WHERE id='$id' AND status='freigegeben' LIMIT 1");
}
$this->app->DB->Update("UPDATE $typ SET versendet=1, versendet_am=NOW(),
versendet_per='$versandart',versendet_durch='".$this->app->User->GetName()."',schreibschutz='1' WHERE id='$id' LIMIT 1");
$this->BriefpapierHintergrundEnable();
switch($typ)
{
case "angebot": $this->AngebotProtokoll($id,"Angebot versendet"); break;
case "auftrag": $this->AuftragProtokoll($id,"Auftrag versendet"); break;
case "rechnung": $this->RechnungProtokoll($id,"Rechnung versendet"); break;
case "lieferschein": $this->LieferscheinProtokoll($id,"Lieferschein versendet"); break;
case "gutschrift": $this->GutschriftProtokoll($id,"Gutschrift versendet"); break;
case "reisekosten": $this->ReisekostenProtokoll($id,"Reisekosten versendet"); break;
case "proformarechnung": $this->ProformarechnungProtokoll($id,"Proformarechnung versendet"); break;
}
}
// @refactor DocumentPdf Komponente
public function PDFArchivieren($type,$id, $force = false)
{
$id = (int)$id;
if($id <= 0){
return false;
}
$types = array("auftrag","angebot","rechnung","lieferschein","gutschrift","bestellung","reisekosten","anfrage","preisanfrage","proformarechnung","arbeitsnachweis");
if(!in_array($type, $types)){
return false;
}
$class = ucfirst($type).'PDFCustom';
if(!class_exists($class)){
$class = ucfirst($type).'PDF';
}
if(class_exists($class)) {
$projekt = $this->app->DB->Select("SELECT projekt FROM $type WHERE id = '$id' LIMIT 1");
$Brief = new $class($this->app,$projekt);
$get = 'Get'.ucfirst($type);
if(method_exists($Brief, $get)) {
$tmpfile = '';
try {
$Brief->$get($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument($force, $force);
unlink($tmpfile);
$tmpfile = '';
}
catch(Exception $e) {
if($tmpfile !== '' && is_file($tmpfile)) {
unlink($tmpfile);
$tmpfile = '';
}
$this->LogFile($this->app->DB->real_escape_string($e->getMessage()));
return false;
}
$this->app->erp->BriefpapierHintergrunddisable = !$this->app->erp->BriefpapierHintergrunddisable;
try {
$Brief = new $class($this->app, $projekt);
$Brief->$get($id);
$tmpfile = $Brief->displayTMP();
$Brief->ArchiviereDocument($force, $force);
unlink($tmpfile);
$tmpfile = '';
}
catch(Exception $e) {
if($tmpfile !== '' && is_file($tmpfile)) {
unlink($tmpfile);
}
$this->LogFile($this->app->DB->real_escape_string($e->getMessage()));
$this->app->erp->BriefpapierHintergrunddisable = !$this->app->erp->BriefpapierHintergrunddisable;
return false;
}
$this->app->erp->BriefpapierHintergrunddisable = !$this->app->erp->BriefpapierHintergrunddisable;
if($force) {
$this->app->DB->Update("UPDATE `{$type}` SET `zuarchivieren` = 0 WHERE `id` = {$id}");
}
return true;
}
}
return false;
}
// @refactor in Location Klasse
function UrlOrigin($s, $use_forwarded_host=false)
{
$ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on') ? true:false;
$sp = strtolower($s['SERVER_PROTOCOL']);
$protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
$port = $s['SERVER_PORT'];
$port = ((!$ssl && $port=='80') || ($ssl && $port=='443')) ? '' : ':'.$port;
$host = ($use_forwarded_host && isset($s['HTTP_X_FORWARDED_HOST'])) ? $s['HTTP_X_FORWARDED_HOST'] : (isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : null);
$host = isset($host) ? $host : $s['SERVER_NAME'] . $port;
$path = str_replace('/index.php','',$s['SCRIPT_NAME']);
return $protocol . '://' . $host.$path;
}
// @refactor Formater Komponente
function ZeitInStundenMinuten($number, $format = "%h:%i") {
$number = str_replace(",",'.',$number);
$h = floor($number);
$i = round(($number - $h) * 60);
$h = str_pad($h, 2, "0", STR_PAD_LEFT);
$i = str_pad($i, 2, "0", STR_PAD_LEFT);
$format = preg_replace("/%h/", $h, $format);
$format = preg_replace("/%i/", $i, $format);
return $format;
}
// @refactor Formater Komponente
/**
* @param string $text
*
* @return string
*/
public function UmlauteEntfernen($text)
{
$text = $this->ReadyForPDF($text);
$text = str_replace ("ä", "ae", $text);
$text = str_replace ("Ä", "Ae", $text);
$text = str_replace ("ö", "oe", $text);
$text = str_replace ("Ö", "Oe", $text);
$text = str_replace ("ü", "ue", $text);
$text = str_replace ("Ü", "Ue", $text);
$text = str_replace ("ß", "ss", $text);
$text = str_replace(
array('ü','Ü','ä','Ä','ö','Ö','ß'),
array('ue','Ue','ae','Ae','oe','Oe','ss'),
$text
);
$text = str_replace ("&", "u", $text);
$text = str_replace ("`", "", $text);
$text = str_replace ("'", "", $text);
return $text;
}
// @refactor DbHelper Komponente
function Stroke($fieldstroke, $field) {
return "if(" . $fieldstroke . ",CONCAT(''," . $field . ",'')," . $field . ")";
}
// @refactor Formater Komponente
function Dateinamen($text) {
$text = $this->UmlauteEntfernen($text);
$text = str_replace(' ', '_', $text);
$text = preg_replace('#[^-_.A-Za-z0-9]#', '', $text);
return $text;
}
// @refactor in Dateien Modul
function AnzahlDateien($objekt,$id)
{
return $this->app->DB->Select("SELECT COUNT(id) FROM datei_stichwoerter WHERE objekt='$objekt' AND parameter='$id'");
}
// @refactor in Service Modul
function AnzahlOffeneSupport()
{
return 0;
}
// @refactor in Aufgaben Modul
function AnzahlOffeneAufgaben()
{
return (int)$this->app->DB->Select("SELECT COUNT(a.id) FROM aufgabe a WHERE (a.adresse='" . $this->app->User->GetAdresse() . "') AND a.startdatum='0000-00-00' AND a.status!='abgeschlossen' AND ( abgabe_bis='0000-00-00' OR abgabe_bis<=NOW())");
}
public function AnzahlOffeneTickets($eigene=true)
{
$sql = "SELECT COUNT(t.id) FROM ticket t WHERE t.status = 'neu' AND ((t.warteschlange = '') OR (t.warteschlange IN (SELECT w.label FROM warteschlangen w WHERE w.adresse = '".$this->app->User->GetAdresse()."')))";
return (int)$this->app->DB->Select($sql);
}
// @refactor UiHelper Komponente
function UserDevice()
{
return 'desktop';
}
// @refactor in Acl oder Login Modul
function Startseite($weiterleitung = "")
{
if($this->app->User->GetID()!="")
{
if($this->UserDevice()=="desktop")
{
$startseite = (string)$weiterleitung !== ''?'':$this->app->DB->Select("SELECT startseite FROM user WHERE id='".$this->app->User->GetID()."' LIMIT 1");
$startseite = $this->ReadyForPDF($startseite);
if(strpos($startseite,'action=logout') !== false && strpos($startseite,'module=welcome') !== false) {
$startseite= '';
}
// wenn die GPS Stechuhr da ist
if((string)$weiterleitung !== '')
{
header("Location: $weiterleitung");
}
elseif($startseite!=''){
$this->app->Location->execute((String)$startseite);
}
else{
header("Location: index.php?module=welcome&action=start");
}
exit;
} else
{
header("Location: index.php?module=welcome&action=start");
exit;
}
}
header("Location: index.php?module=welcome&action=login");
exit;
}
// @refactor in Kalender Modul @prüfen
function getFirstDayOfWeek($year, $weeknr)
{
$offset = date('w', mktime(0,0,0,1,1,$year));
$offset = ($offset < 5) ? 1-$offset : 8-$offset;
$monday = mktime(0,0,0,1,1+$offset,$year);
return date('Y-m-d',strtotime('+' . ($weeknr - 1) . ' weeks', $monday));
}
// @refactor in SystemInformation Modul
function IsWindows()
{
return strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
}
/**
* Returns the absolute path to installation directory; without trailing slash
*
* @return string
*/
public function GetRootPath()
{
return dirname(dirname(__DIR__));
}
// @refactor in SystemInformation Modul
function GetTMP()
{
$userdata = $this->app->Conf->WFuserdata;
$dbname = $this->app->Conf->WFdbname;
if ($this->IsWindows()) {
$tmp = $userdata."\\tmp\\".$dbname."\\";
} else {
$tmp = $userdata."/tmp/".$dbname."/";
}
$tmp = str_replace('//','/',$tmp);
if(!is_dir($tmp)){
mkdir($tmp, 0777, true);
}
return $tmp;
}
// @refactor in SystemInformation Modul
function GetUSERDATA()
{
return $this->app->Conf->WFuserdata;
}
/** @deprecated */
function RetoureSeriennummernberechnen($id)
{
}
function LieferscheinSeriennummernberechnen($id)
{
/** @var Seriennummern $obj */
$obj = $this->LoadModul('seriennummern');
if(!empty($obj) && method_exists($obj, 'LieferscheinSeriennummernberechnen')) {
$obj->LieferscheinSeriennummernberechnen($id);
}
}
// @refactor in Lager Modul
function ArtikelAnzahlLagerPlatzMitSperre($artikel,$lager_platz)
{
$result = $this->app->DB->Select("SELECT SUM(lpi.menge) FROM lager_platz_inhalt lpi
LEFT JOIN lager_platz lp ON lp.id=lpi.lager_platz
WHERE lpi.artikel='$artikel' AND lpi.lager_platz='$lager_platz'");
if($result <=0) $result=0;
return $result;
}
// @refactor LagerBeleg Modul
function LieferscheinEinlagern($id,$grund="Lieferschein Einlagern", $lpiids = null)
{
if(!$id)return;
$belegnr = $this->app->DB->Select("SELECT belegnr FROM lieferschein WHERE id = '$id' LIMIT 1");
$bearbeiter = '';
if(isset($this->app->User) && $this->app->User && method_exists($this->app->User,'GetName'))$bearbeiter = $this->app->User->GetName();
$objekt_lager_platz = $this->app->DB->SelectArr("SELECT olp.id, olp.menge, olp.lager_platz, olp.artikel, olp.parameter, lp.id as lpid FROM
lieferschein_position lp INNER JOIN objekt_lager_platz olp ON lp.id = olp.parameter AND olp.objekt = 'lieferschein' AND lp.lieferschein = '$id'");
if($objekt_lager_platz)
{
$projekt = $this->app->DB->Select("SELECT projekt FROM lieferschein WHERE id = '$id' LIMIT 1");
foreach($objekt_lager_platz as $olp)
{
$lpiid = null;
if(isset($lpiids[$olp['lpid']]))$lpiid = $lpiids[$olp['lpid']];
$this->app->erp->LagerEinlagern($olp['artikel'],$olp['menge'],$olp['lager_platz'],$projekt,
"Stornierung Lieferschein $belegnr",$bearbeiter,"",'lieferschein', $id, $lpiid);
$beleg_chargesnmhd = $this->app->DB->SelectArr("SELECT * FROM `beleg_chargesnmhd` WEHRE doctype = 'lieferschein' AND doctypeid = '$id' AND pos = '".$olp['parameter']."'");
$seriennummern = $this->app->DB->SelectArr("SELECT * FROM seriennummern WHERE lieferschein = '$id' AND lieferscheinpos = '".$olp['parameter']."'");
if($seriennummern)
{
foreach($seriennummern as $sn)
{
$belegesnarr['sn'][] = array('menge'=>1, 'value'=>$sn['seriennummer'],'table'=>'seriennummern','id'=>$sn['id']);
}
}
if($beleg_chargesnmhd)
{
$belegesnarr = null;
foreach($beleg_chargesnmhd as $bc)
{
$belegesnarr[$bc['typ']][] = array('menge'=>$bc['menge'], 'value'=>$bc['wert'],'table'=>'beleg_chargesnmhd','id'=>$bc['id']);
}
}
if(isset($belegesnarr['sn']))
{
foreach($belegesnarr['sn'] as $v)
{
if(isset($belegesnarr['charge']) && isset($belegesnarr['mhd']))
{
$charge = '';
$mhd = '';
foreach($belegesnarr['charge'] as $k2 => $v2)
{
if($v2['menge'] > 1)
{
$charge = $v2['value'];
$belegesnarr['charge'][$k2]['menge'] -= 1;
break;
}elseif($v2['menge'] == 1)
{
$charge = $v2['value'];
unset($belegesnarr['charge'][$k2]);
break;
}
}
foreach($belegesnarr['mhd'] as $k2 => $v2)
{
if($v2['menge'] > 1)
{
$mhd = $v2['value'];
$belegesnarr['mhd'][$k2]['menge'] -= 1;
break;
}elseif($v2['menge'] == 1)
{
$mhd = $v2['value'];
unset($belegesnarr['mhd'][$k2]);
break;
}
}
if(isset($v['table']) && $v['table'] == 'seriennummern' && !empty($v['id']))
{
$this->app->DB->Delete("DELETE FROM seriennummern WHERE id = '".$v['id']."' LIMIT 1");
}elseif(isset($v['table']) && $v['table'] == 'beleg_chargesnmhd' && !empty($v['id'])){
$this->app->DB->Delete("DELETE FROM beleg_chargesnmhd WHERE id = '".$v['id']."' LIMIT 1");
}
if(method_exists($this->app->erp,'AddSeriennummerLager'))$this->app->erp->AddSeriennummerLager($olp['artikel'], $olp['lager_platz'], $v['value'],"Stornierung Lieferschein $belegnr", "", $mhd, $charge,'lieferschein', $id);
if(method_exists($this->app->erp,'AddMindesthaltbarkeitsdatumLagerOhneBewegung'))$this->app->erp->AddMindesthaltbarkeitsdatumLagerOhneBewegung($olp['artikel'], 1,$olp['lager_platz'], $mhd, $charge);
if(method_exists($this->app->erp,'AddChargeLagerOhneBewegung'))$this->app->erp->AddChargeLagerOhneBewegung($olp['artikel'],1, $olp['lager_platz'],$mhd,$charge,$grund);
}elseif(isset($belegesnarr['charge']))
{
$charge = '';
$mhd = '';
foreach($belegesnarr['charge'] as $k2 => $v2)
{
if($v2['menge'] > 1)
{
$charge = $v2['value'];
$belegesnarr['charge'][$k2]['menge'] -= 1;
break;
}elseif($v2['menge'] == 1)
{
$charge = $v2['value'];
unset($belegesnarr['charge'][$k2]);
break;
}
}
if(isset($v['table']) && $v['table'] == 'seriennummern' && !empty($v['id']))
{
$this->app->DB->Delete("DELETE FROM seriennummern WHERE id = '".$v['id']."' LIMIT 1");
}elseif(isset($v['table']) && $v['table'] == 'beleg_chargesnmhd' && !empty($v['id'])){
$this->app->DB->Delete("DELETE FROM beleg_chargesnmhd WHERE id = '".$v['id']."' LIMIT 1");
}
if(method_exists($this->app->erp,'AddSeriennummerLager'))$this->app->erp->AddSeriennummerLager($olp['artikel'],1, $olp['lager_platz'], $v['value'],$grund, "", $mhd, $charge,'lieferschein', $id);
if(method_exists($this->app->erp,'AddChargeLagerOhneBewegung'))$this->app->erp->AddChargeLagerOhneBewegung($olp['artikel'], 1,$olp['lager_platz'],$mhd,$charge,"", 'lieferschein', $id,$grund);
}elseif(isset($belegesnarr['mhd']))
{
$charge = '';
$mhd = '';
foreach($belegesnarr['mhd'] as $k2 => $v2)
{
if($v2['menge'] > 1)
{
$mhd = $v2['value'];
$belegesnarr['mhd'][$k2]['menge'] -= 1;
break;
}elseif($v2['menge'] == 1)
{
$mhd = $v2['value'];
unset($belegesnarr['mhd'][$k2]);
break;
}
}
if(isset($v['table']) && $v['table'] == 'seriennummern' && !empty($v['id']))
{
$this->app->DB->Delete("DELETE FROM seriennummern WHERE id = '".$v['id']."' LIMIT 1");
}elseif(isset($v['table']) && $v['table'] == 'beleg_chargesnmhd' && !empty($v['id'])){
$this->app->DB->Delete("DELETE FROM beleg_chargesnmhd WHERE id = '".$v['id']."' LIMIT 1");
}
if(method_exists($this->app->erp,'AddSeriennummerLager'))$this->app->erp->AddSeriennummerLager($olp['artikel'], $olp['lager_platz'], $v['value'],$grund, "", $mhd, $charge);
if(method_exists($this->app->erp,'AddMindesthaltbarkeitsdatumLagerOhneBewegung'))$this->app->erp->AddMindesthaltbarkeitsdatumLagerOhneBewegung($olp['artikel'],1, $olp['lager_platz'], $mhd, $charge, "", "lieferschein", $id, $grund);
}else{
if(isset($v['table']) && $v['table'] == 'seriennummern' && !empty($v['id']))
{
$this->app->DB->Delete("DELETE FROM seriennummern WHERE id = '".$v['id']."' LIMIT 1");
}elseif(isset($v['table']) && $v['table'] == 'beleg_chargesnmhd' && !empty($v['id'])){
$this->app->DB->Delete("DELETE FROM beleg_chargesnmhd WHERE id = '".$v['id']."' LIMIT 1");
}
if(method_exists($this->app->erp,'AddSeriennummerLager'))$this->app->erp->AddSeriennummerLager($olp['artikel'], $olp['lager_platz'], $v['value'],$grund, "", $mhd, $charge);
}
}
}else{
if(isset($belegesnarr['charge']) && isset($belegesnarr['mhd']))
{
foreach($belegesnarr['charge'] as $v2)
{
$nochmenge = $v2['value'];
foreach($belegesnarr['mhd'] as $k3 => $v3)
{
if($nochmenge <= 0)break;
if($nochmenge == $v3['menge'])
{
$mhd = $v3['value'];
$charge = $v2['value'];
if(method_exists($this->app->erp,'AddMindesthaltbarkeitsdatumLagerOhneBewegung'))$this->app->erp->AddMindesthaltbarkeitsdatumLagerOhneBewegung($olp['artikel'], $nochmenge,$olp['lager_platz'], $mhd, $charge, "", "lieferschein", $id, $grund);
if(method_exists($this->app->erp,'AddChargeLagerOhneBewegung'))$this->app->erp->AddChargeLagerOhneBewegung($olp['artikel'],$nochmenge, $olp['lager_platz'],$mhd,$charge,"", 'lieferschein', $id,$grund);
unset($belegesnarr['mhd'][$k3]);
break;
}elseif($nochmenge > $v3['menge'])
{
$mhd = $v3['value'];
$charge = $v2['value'];
if(method_exists($this->app->erp,'AddMindesthaltbarkeitsdatumLagerOhneBewegung'))$this->app->erp->AddMindesthaltbarkeitsdatumLagerOhneBewegung($olp['artikel'], $v3['menge'],$olp['lager_platz'], $mhd, $charge, "", "lieferschein", $id, $grund);
if(method_exists($this->app->erp,'AddChargeLagerOhneBewegung'))$this->app->erp->AddChargeLagerOhneBewegung($olp['artikel'],$v3['menge'], $olp['lager_platz'],$mhd,$charge,"", 'lieferschein', $id,$grund);
unset($belegesnarr['mhd'][$k3]);
$nochmenge -= $v3['menge'];
}elseif($nochmenge < $v3['menge'])
{
$mhd = $v3['value'];
$charge = $v2['value'];
if(method_exists($this->app->erp,'AddMindesthaltbarkeitsdatumLagerOhneBewegung'))$this->app->erp->AddMindesthaltbarkeitsdatumLagerOhneBewegung($olp['artikel'], $nochmenge,$olp['lager_platz'], $mhd, $charge, "", "lieferschein", $id, $grund);
if(method_exists($this->app->erp,'AddChargeLagerOhneBewegung'))$this->app->erp->AddChargeLagerOhneBewegung($olp['artikel'],$nochmenge, $olp['lager_platz'],$mhd,$charge,"", 'lieferschein', $id,$grund);
$belegesnarr['mhd'][$k3]['menge'] -= $nochmenge;
break;
}
}
}
}elseif($belegesnarr['charge'])
{
foreach($belegesnarr['charge'] as $v2)
{
if(method_exists($this->app->erp,'AddChargeLagerOhneBewegung'))$this->app->erp->AddChargeLagerOhneBewegung($olp['artikel'],$v2['menge'], $olp['lager_platz'],'',$v2['value'],"", 'lieferschein', $id,$grund);
}
}elseif($belegesnarr['mhd'])
{
if(method_exists($this->app->erp,'AddMindesthaltbarkeitsdatumLagerOhneBewegung'))$this->app->erp->AddMindesthaltbarkeitsdatumLagerOhneBewegung($olp['artikel'],$v2['menge'], $olp['lager_platz'], $v2['value'], "", "lieferschein", $id, $grund);
}
}
$this->app->DB->Delete("DELETE FROM objekt_lager_platz WHERE id = '".$olp['id']."' LIMIT 1");
}
}
}
// @refactor LagerBeleg Modul
function LieferscheinAuslagern($lieferschein,$anzeige_lagerplaetze_in_lieferschein=false, $standardlager = 0, $belegtyp = 'lieferschein', $chargenmhdnachprojekt = 0, $forceseriennummerngeliefertsetzen = false,$nurrestmenge = false, $lager_platz_vpe = 0, $lpiid = 0)
{
if($lieferschein <= 0) {
return;
}
if(!$anzeige_lagerplaetze_in_lieferschein) {
$anzeige_lagerplaetze_in_lieferschein = true;
}
$artikelarr = $this->app->DB->SelectArr(
sprintf(
"SELECT * FROM `%s` WHERE `%s` = %d ORDER BY sort",
$belegtyp.'_position', $belegtyp, (int)$lieferschein
)
);
$belegarr = $this->app->DB->SelectRow(
sprintf(
'SELECT * FROM `%s` WHERE id=%d LIMIT 1',
$belegtyp, (int)$lieferschein
)
);
$kommissionskonsignationslager = 0;
if($belegtyp === 'lieferschein'){
$kommissionskonsignationslager = $belegarr['kommissionskonsignationslager'];
}
$chargenerfassen = 0;
$mhderfassen = 0;
$seriennummernerfassen = 0;
$kommissionierverfahren = '';
$projekt = 0;
$belegnr = '';
if(!empty($belegarr)) {
$projekt = (int)$belegarr['projekt'];
$projektarr = $this->app->DB->SelectRow(
sprintf(
'SELECT * FROM projekt WHERE id = %d LIMIT 1',
$projekt
)
);
if(!empty($projektarr)) {
$chargenerfassen = $projektarr['chargenerfassen'];
$mhderfassen = $projektarr['mhderfassen'];
$seriennummernerfassen = $projektarr['seriennummernerfassen'];
if(!empty($projektarr['multiorderpicking']) && $this->ModulVorhanden('multiorderpicking')) {
$chargenerfassen = 1;
$mhderfassen = 1;
$seriennummernerfassen = 1;
}
$kommissionierverfahren = $projektarr['kommissionierverfahren'];
}
$belegnr = $belegarr['belegnr'];
}
$chargenauslagern = 1;
$mhdauslagern = 1;
$seriennummernauslagern = 1;
if($chargenmhdnachprojekt && $chargenerfassen){
$chargenauslagern = 0;
}
if($chargenmhdnachprojekt && $mhderfassen){
$mhdauslagern = 0;
}
if($chargenmhdnachprojekt && $seriennummernerfassen && $kommissionierverfahren !== 'kommissionierverfahren'){
$seriennummernauslagern = 0;
}
$sortreihenfolge = 'ASC';
if($belegtyp === 'produktion') {
$sortreihenfolge = 'DESC';
}
if($belegtyp === 'produktion') {
if($standardlager > 0 && !$this->app->DB->Select(
sprintf(
"SELECT id FROM lager WHERE id = %d AND bezeichnung <> '' AND IFNULL(geloescht,0) = 0 LIMIT 1",
(int)$standardlager)
)
) {
$standardlager = (int)$this->app->DB->Select(
sprintf(
"SELECT l.id
FROM projekt AS p
INNER JOIN lager AS l ON p.standardlagerproduktion = l.id
WHERE p.id = %d AND l.bezeichnung <> '' AND IFNULL(l.geloescht,0) = 0
LIMIT 1",
(int)$projekt
)
);
}
}
else{
if($standardlager > 0 && !$this->app->DB->Select(
sprintf(
"SELECT id FROM lager WHERE id = %d AND bezeichnung <> '' AND IFNULL(geloescht,0) = 0 LIMIT 1",
(int)$standardlager)
)){
$standardlager = (int)$this->app->DB->Select(
sprintf(
"SELECT l.id
FROM projekt AS p
INNER JOIN lager AS l ON p.standardlager = l.id
WHERE p.id = %d AND l.bezeichnung <> '' AND IFNULL(l.geloescht,0) = 0
LIMIT 1",
$projekt
)
);
}
}
if($standardlager == 0) {
if($projekt > 0){
$projektlager = $this->app->DB->Select("SELECT projektlager FROM projekt WHERE id='$projekt'");
}
}
$storageLocations = [];
$cartikel = $artikelarr?count($artikelarr):0;
for($i= ($belegtyp==='produktion'?1:0) ;$i<$cartikel;$i++) {
$beschreibung = $artikelarr[$i]['beschreibung'];
$artikel = $artikelarr[$i]['artikel'];
$menge = $artikelarr[$i]['menge'];
if($nurrestmenge && $belegtyp=='produktion')
{
$menge = $artikelarr[$i]['menge'] - $artikelarr[$i]['geliefert_menge'];
}
$subid = $artikelarr[$i]['id'];
$lager_string = '';
$arcticleRow = $this->app->DB->SelectRow(
sprintf(
"SELECT lagerartikel, mindesthaltbarkeitsdatum, chargenverwaltung, seriennummern
FROM artikel WHERE id=%d LIMIT 1",
(int)$artikel
)
);
$lagerartikel = $arcticleRow['lagerartikel'];
$seriennummern = $arcticleRow['seriennummern'] === 'keine'?'':$arcticleRow['seriennummern'];
$regal = 0;
$sperrlagerWhere = ' lp.sperrlager <> 1 ';
if($belegtyp=='produktion') {
$sperrlagerWhere = ' (lp.sperrlager <> 1 OR lp.allowproduction = 1) ';
}
if($lagerartikel > 0)
{
$this->LagerArtikelZusammenfassen($artikel);
// lager platz suchen eins abziehen und namen in lieferschein
// kleinster lager leer machen
$regal = 0;
$timeout=0;
$restmenge = $menge;
$lager_string = '';
$mindesthaltbarkeitsdatum = $arcticleRow['mindesthaltbarkeitsdatum'];
$chargenverwaltung = $arcticleRow['chargenverwaltung'];
while($restmenge > 0)
{
$timeout++;
if($restmenge <= 0){
break;
}
//if($timeout > 1000) break;
$extraorder = '';
$maxAuslagern = $restmenge;
if(!empty($seriennummern) && $belegtyp !== 'produktion') {
$snDeliveryNoteStorage = $this->app->DB->SelectArr(
sprintf(
'SELECT bc.lagerplatz AS storage_location_id, COUNT(bc.id) - IFNULL(olp.menge, 0) AS amount
FROM `beleg_chargesnmhd` AS bc
LEFT JOIN (
SELECT SUM(menge) AS menge, lager_platz
FROM `objekt_lager_platz`
WHERE objekt = \'lieferschein\' AND parameter = %d
GROUP BY lager_platz
) AS olp ON bc.lagerplatz = olp.lager_platz
WHERE bc.type = \'sn\' AND bc.doctype = \'lieferschein\' AND bc.doctypeid = %d AND bc.pos = %d AND bc.wert <> \'\'
GROUP BY bc.lagerplatz
HAVING amount > 0
ORDER BY COUNT(bc.id) - IFNULL(olp.menge, 0) = %f DESC, COUNT(bc.id) - IFNULL(olp.menge, 0)
',
(int)$subid, (int)$lieferschein, (int)$subid, (float)$restmenge
)
);
if(!empty($snDeliveryNoteStorage)) {
$extraorder = sprintf(' lpi.lager_platz = %d DESC, ', $snDeliveryNoteStorage[0]['storage_location_id']);
if($snDeliveryNoteStorage[0]['amount'] < $restmenge && $snDeliveryNoteStorage[0]['amount'] > 0 && (!empty($snDeliveryNoteStorage)?count($snDeliveryNoteStorage):0) > 1) {
$maxAuslagern = $snDeliveryNoteStorage[0]['amount'];
}
}
}
$this->app->erp->RunHook('lieferscheinauslagern', 6, $belegtyp, $subid, $artikel, $mindesthaltbarkeitsdatum, $chargenverwaltung, $extraorder);
if($mindesthaltbarkeitsdatum) {
if($standardlager > 0) {
$lager_max = $this->app->DB->SelectArr(
sprintf(
"SELECT lpi.lager_platz, if(lpi.menge > lm.menge, lm.menge,lpi.menge) as menge, lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id AND lp.id <> %d
INNER JOIN lager AS `lag` ON `lag`.id=lp.lager
INNER JOIN (
SELECT lager_platz, sum(menge) as menge,min(mhddatum) as mhddatum
FROM lager_mindesthaltbarkeitsdatum
WHERE artikel = %d
GROUP BY lager_platz
) AS lm ON lp.id = lm.lager_platz
WHERE lpi.artikel=%d AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)." AND `lag`.id='$standardlager'
ORDER by ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." `lag`.id='$standardlager' DESC, $extraorder lm.mhddatum ASC, lpi.menge $sortreihenfolge
LIMIT 1",
(int)$kommissionskonsignationslager,(int)$artikel, (int)$artikel
)
);
if(!$lager_max) {
$lager_max = $this->app->DB->SelectArr(
sprintf(
"SELECT lpi.lager_platz, lpi.menge, lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id
INNER JOIN lager AS `lag` ON `lag`.id=lp.lager
LEFT JOIN lager_mindesthaltbarkeitsdatum lm ON lm.artikel=lpi.artikel AND lp.id = lm.lager_platz
WHERE lpi.artikel=%d AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)." AND `lag`.id='$standardlager'
ORDER by ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." lag.id='$standardlager' DESC, $extraorder lm.mhddatum ASC, lpi.menge $sortreihenfolge
LIMIT 1",
(int)$artikel
)
);
}
}
elseif($projektlager > 0) {
// Hole nach und nach bis alles da ist
$lager_max = $this->app->DB->SelectArr(
"SELECT lpi.lager_platz, if(lpi.menge > lm.menge, lm.menge,lpi.menge) as menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id AND lp.id <> '$kommissionskonsignationslager'
INNER JOIN lager AS `lag` ON `lag`.id=lp.lager
INNER JOIN (
SELECT lager_platz, sum(menge) as menge,min(mhddatum) as mhddatum
FROM lager_mindesthaltbarkeitsdatum
WHERE artikel = '$artikel' AND menge > 0
GROUP BY lager_platz
) AS lm ON lp.id = lm.lager_platz
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)." AND `lag`.projekt='$projekt'
ORDER BY ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." $extraorder lm.mhddatum ASC, lpi.menge $sortreihenfolge
LIMIT 1"
);
if(!$lager_max) {
$lager_max = $this->app->DB->SelectArr(
"SELECT lpi.lager_platz, lpi.menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id
INNER JOIN lager AS `lag` ON `lag`.id=lp.lager
LEFT JOIN lager_mindesthaltbarkeitsdatum AS lm ON lm.artikel=lpi.artikel AND lp.id = lm.lager_platz
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)." AND `lag`.projekt='$projekt'
ORDER BY ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." $extraorder lm.mhddatum ASC, lpi.menge $sortreihenfolge
LIMIT 1");
}
}
else {
// Hole nach und nach bis alles da ist
$lager_max = $this->app->DB->SelectArr(
sprintf(
"SELECT lpi.lager_platz, if(lpi.menge > lm.menge, lm.menge,lpi.menge) as menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz lp ON lpi.lager_platz=lp.id AND lp.id <> '$kommissionskonsignationslager'
INNER JOIN (
SELECT lager_platz, sum(menge) as menge,min(mhddatum) as mhddatum
FROM lager_mindesthaltbarkeitsdatum
WHERE artikel = %d AND menge > 0
GROUP BY lager_platz
) AS lm ON lp.id = lm.lager_platz
WHERE lpi.artikel=%d AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)."
ORDER by ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." $extraorder lm.mhddatum ASC, lpi.menge $sortreihenfolge
LIMIT 1",
(int)$artikel, (int)$artikel
)
);
if(!$lager_max) {
$lager_max = $this->app->DB->SelectArr("SELECT lpi.lager_platz, lpi.menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id
INNER JOIN lager_mindesthaltbarkeitsdatum AS lm ON lm.artikel=lpi.artikel AND lp.id = lm.lager_platz
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)."
ORDER by ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." $extraorder lm.mhddatum ASC, lpi.menge $sortreihenfolge
LIMIT 1"
);
}
}
}
else {
if($chargenverwaltung) {
if($standardlager > 0) {
$lager_max = $this->app->DB->SelectArr(
"SELECT lpi.lager_platz, if(lpi.menge > lm.menge, lm.menge,lpi.menge) as menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id
INNER JOIN lager AS `lag` ON `lag`.id=lp.lager
INNER JOIN (
SELECT lager_platz, sum(menge) as menge
FROM lager_charge
WHERE artikel = '$artikel' AND menge > 0
GROUP BY lager_platz
) AS lm ON lp.id = lm.lager_platz
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)." AND `lag`.id='$standardlager'
ORDER BY ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." `lag`.id='$standardlager' DESC, $extraorder lpi.menge $sortreihenfolge
LIMIT 1"
);
if(!$lager_max)
{
$lager_max = $this->app->DB->SelectArr(
"SELECT lpi.lager_platz, lpi.menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id
INNER JOIN lager AS `lag` ON `lag`.id=lp.lager
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)." AND `lag`.id='$standardlager'
ORDER BY ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." `lag`.id='$standardlager' DESC, $extraorder lpi.menge $sortreihenfolge
LIMIT 1"
);
}
}
elseif($projektlager > 0){
$lager_max = $this->app->DB->SelectArr(
"SELECT lpi.lager_platz, if(lpi.menge > lm.menge, lm.menge,lpi.menge) as menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id AND lp.id <> '$kommissionskonsignationslager'
INNER JOIN lager AS `lag` ON `lag`.id=lp.lager
INNER JOIN (
SELECT lager_platz, sum(menge) as menge
FROM lager_charge
WHERE artikel = '$artikel' AND menge > 0
GROUP BY lager_platz
) AS lm ON lp.id = lm.lager_platz
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)." AND `lag`.projekt='$projekt'
ORDER BY ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." $extraorder lpi.menge $sortreihenfolge
LIMIT 1"
);
if(!$lager_max) {
$lager_max = $this->app->DB->SelectArr(
"SELECT lpi.lager_platz, lpi.menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id AND lp.id <> '$kommissionskonsignationslager'
INNER JOIN lager AS `lag` ON `lag`.id=lp.lager
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)." AND `lag`.projekt='$projekt'
ORDER BY ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." $extraorder lpi.menge $sortreihenfolge
LIMIT 1"
);
}
}
else {
$lager_max = $this->app->DB->SelectArr(
"SELECT lpi.lager_platz, if(lpi.menge > lm.menge, lm.menge,lpi.menge) as menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id AND lp.id <> '$kommissionskonsignationslager'
INNER JOIN (
SELECT lager_platz, sum(menge) as menge
FROM lager_charge
WHERE artikel = '$artikel' AND menge > 0
GROUP BY lager_platz
) AS lm ON lp.id = lm.lager_platz
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)."
ORDER BY ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." $extraorder lpi.menge $sortreihenfolge
LIMIT 1"
);
if(!$lager_max) {
$lager_max = $this->app->DB->SelectArr(
"SELECT lpi.lager_platz, lpi.menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id AND lp.id <> '$kommissionskonsignationslager'
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)."
ORDER BY ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." $extraorder lpi.menge $sortreihenfolge
LIMIT 1"
);
}
}
}
else{
if($standardlager > 0) {
$lager_max = $this->app->DB->SelectArr(
"SELECT lpi.lager_platz, lpi.menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id AND lp.id <> '$kommissionskonsignationslager'
INNER JOIN lager AS `lag` ON `lag`.id=lp.lager
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)." AND `lag`.id='$standardlager'
ORDER BY ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." `lag`.id='$standardlager' DESC, $extraorder lpi.menge $sortreihenfolge
LIMIT 1"
);
}
elseif($projektlager > 0) {
$lager_max = $this->app->DB->SelectArr(
"SELECT lpi.lager_platz, lpi.menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id AND lp.id <> '$kommissionskonsignationslager'
INNER JOIN lager AS `lag` ON `lag`.id=lp.lager
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)." AND `lag`.projekt='$projekt'
ORDER BY ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." $extraorder lpi.menge $sortreihenfolge
LIMIT 1"
);
}
else {
$lager_max = $this->app->DB->SelectArr(
"SELECT lpi.lager_platz, lpi.menge,lpi.id
FROM lager_platz_inhalt AS lpi
INNER JOIN lager_platz AS lp ON lpi.lager_platz=lp.id AND lp.id <> '$kommissionskonsignationslager'
WHERE lpi.artikel='$artikel' AND lpi.menge > 0
".($lpiid?'':' AND lp.autolagersperre!=1 AND '.$sperrlagerWhere)."
ORDER BY ".($lpiid?" lpi.id = '$lpiid' DESC, ":'')." ".($lager_platz_vpe?" lpi.lager_platz_vpe = '$lager_platz_vpe' DESC, ":'')." $extraorder lpi.menge $sortreihenfolge
LIMIT 1"
);
}
}
}
if(!$lager_max){
break;
}
if((round($maxAuslagern,8) > round($lager_max[0]['menge'],8)) && ($lager_max[0]['menge'] > 0)) {
// es werden mehr gebraucht als im lager sind
$this->LagerAuslagernRegal($artikel,$lager_max[0]['lager_platz'],$lager_max[0]['menge'],$projekt,ucfirst($belegtyp)." $belegnr","",$belegtyp,$lieferschein, $lager_max[0]['lager_platz_vpe'], $lager_max[0]['id']);
if($anzeige_lagerplaetze_in_lieferschein){
$this->LagerAuslagernText($artikel, $subid, $lager_max[0]['lager_platz'], $lager_max[0]['menge'], $belegtyp);
}else{
$this->LagerAuslagernObjektLagerPlatz($artikel, $subid, $lager_max[0]['lager_platz'], $lager_max[0]['menge'], $belegtyp);
}
$storageLocations[] = $lager_max[0]['lager_platz'];
$regal_name = $this->app->DB->Select("SELECT kurzbezeichnung FROM lager_platz WHERE id='".$lager_max[0]['lager_platz']."' LIMIT 1");
$lager_string .= $regal_name."(".$lager_max[0]['menge'].") ";
$restmenge = round($restmenge - $lager_max[0]['menge'],8);
if(!$nurrestmenge){
$this->LagerAuslagernRegalMHDCHARGESRN($artikel,$lager_max[0]['lager_platz'],$lager_max[0]['menge'],$projekt,ucfirst($belegtyp)." $belegnr","",$belegtyp,$lieferschein,$subid, $chargenauslagern, $mhdauslagern, $seriennummernauslagern);
}
}
else if( ($lager_max[0]['menge'] >= $maxAuslagern) && ($maxAuslagern > 0) ) {
// es sind genuegend lager
$this->LagerAuslagernRegal($artikel,$lager_max[0]['lager_platz'],$maxAuslagern,$projekt,ucfirst($belegtyp)." $belegnr","",$belegtyp,$lieferschein, $lager_max[0]['lager_platz_vpe'], $lager_max[0]['id']);
$storageLocations[] = $lager_max[0]['lager_platz'];
if($anzeige_lagerplaetze_in_lieferschein){
$this->LagerAuslagernText($artikel, $subid, $lager_max[0]['lager_platz'], $maxAuslagern, $belegtyp);
}else{
$this->LagerAuslagernObjektLagerPlatz($artikel, $subid, $lager_max[0]['lager_platz'], $maxAuslagern, $belegtyp);
}
$regal_name = $this->app->DB->Select("SELECT kurzbezeichnung FROM lager_platz WHERE id='".$lager_max[0]['lager_platz']."' LIMIT 1");
$lager_string .= $regal_name."(".(float)$maxAuslagern.") ";
if(!$nurrestmenge){
$this->LagerAuslagernRegalMHDCHARGESRN($artikel,$lager_max[0]['lager_platz'],$maxAuslagern,$projekt,ucfirst($belegtyp)." $belegnr","",$belegtyp,$lieferschein,$subid, $chargenauslagern, $mhdauslagern, $seriennummernauslagern);
}
$restmenge = round($restmenge - $maxAuslagern, 8);
}
else {
break;
}
}
/*
// neue datenstruktue
if($lager_string=='') {
$beschreibung .="\r\nLager: manuell";
}
else {
$beschreibung .="\r\nLager: $lager_string";
}
*/
}
$geliefert = $menge;
if($nurrestmenge && $belegtyp=='produktion') {
$geliefert = $menge + $artikelarr[$i]['geliefert_menge'];
}
$artikelhatseriennummer = $this->app->DB->Select("SELECT seriennummern FROM artikel WHERE id='".$artikel."' LIMIT 1");
if($belegtyp == 'produktion')
{
$this->app->DB->Update("UPDATE ".$belegtyp."_position SET geliefert_menge='$geliefert', geliefert = 1 WHERE id='$subid' LIMIT 1");
}else{
if($belegtyp=="lieferschein")
{
$auftragposid=$this->app->DB->Select("SELECT auftrag_position_id FROM lieferschein_position WHERE id='$subid'");
if($auftragposid>0)
{
$this->app->DB->Update("UPDATE auftrag_position SET geliefert_menge='$geliefert' WHERE id='$auftragposid' LIMIT 1");
}
}
if($seriennummernerfassen=='1' && ($artikelhatseriennummer=='vomprodukteinlagern' || $artikelhatseriennummer=='vomprodukt' || $artikelhatseriennummer=='eigene'))
{
// wenn Seriennummer erfasst werden soll
//if($anzeige_lagerplaetze_in_lieferschein)
//{
//$this->app->DB->Update("UPDATE ".$belegtyp."_position SET beschreibung='$beschreibung' WHERE id='$subid' LIMIT 1");
//neue datenstruktur
//}
if($forceseriennummerngeliefertsetzen)$this->app->DB->Update("UPDATE ".$belegtyp."_position SET geliefert='$geliefert' WHERE id='$subid' LIMIT 1");
} else {
//wenn nicht
//if($anzeige_lagerplaetze_in_lieferschein)
// $this->app->DB->Update("UPDATE ".$belegtyp."_position SET geliefert='$geliefert',beschreibung='$beschreibung' WHERE id='$subid' LIMIT 1");
//else
$this->app->DB->Update("UPDATE ".$belegtyp."_position SET geliefert='$geliefert' WHERE id='$subid' LIMIT 1");
}
}
}
if(!empty($storageLocations)) {
$this->addStorageCountry($belegtyp, $lieferschein, $storageLocations);
}
$this->app->DB->Delete("DELETE FROM lager_reserviert WHERE objekt = '$belegtyp' AND parameter = '$lieferschein'");
$auftragid = $this->app->DB->Select("SELECT auftragid FROM $belegtyp WHERE id='$lieferschein'");
if($auftragid){
$this->app->DB->Delete("DELETE FROM lager_reserviert WHERE objekt = 'auftrag' AND parameter = '$auftragid'");
}
if($belegtyp == '' || $belegtyp === 'lieferschein')
{
$this->RunHook('erpapi_lieferschein_auslagern', 1, $lieferschein);
$this->LieferscheinProtokoll($lieferschein,"Lieferschein ausgelagert");
}
}
/**
* @param string $doctype
* @param int $doctypeId
* @param array $storageLocations
*/
public function addStorageCountry($doctype, $doctypeId, $storageLocations)
{
if($doctype === 'lieferschein') {
$order = $this->app->DB->SelectRow(
sprintf(
"SELECT o.id, o.schreibschutz
FROM lieferschein AS dn
INNER JOIN auftrag AS o ON dn.auftragid = o.id AND o.belegnr <> ''
WHERE dn.id = %d AND o.`storage_country` = '' AND o.shop = 0
ORDER BY o.status <> 'storniert' DESC",
$doctypeId
)
);
if(!empty($order)) {
$country = $this->app->DB->Select(
sprintf(
"SELECT adr.land
FROM lager_platz AS lp
INNER JOIN lager AS l ON lp.lager = l.id
INNER JOIN adresse adr ON IF(l.adresse > 0, l.adresse, lp.adresse) = adr.id
AND adr.land <> '' AND adr.land <> '%s'
WHERE lp.id IN (%s)
LIMIT 1",
$this->app->DB->real_escape_string($this->app->erp->Firmendaten('land')),
implode(',', array_unique($storageLocations))
)
);
if(!empty($country)) {
$this->app->DB->Update(
sprintf(
"UPDATE auftrag
SET storage_country = '%s', zuarchivieren = 0, schreibschutz = 0
WHERE id = %d AND storage_country = ''",
$this->app->DB->real_escape_string($country), $order['id']
)
);
if($this->app->DB->affected_rows() > 0) {
$this->app->erp->ANABREGSNeuberechnen($order['id'], 'auftrag');
if($order['schreibschutz']) {
$this->app->erp->PDFArchivieren('auftrag', $order['id'], true);
}
$invoice = $this->app->DB->SelectRow(
sprintf(
"SELECT id,storage_country, schreibschutz
FROM rechnung
WHERE auftragid = %d AND status <> 'storniert'
ORDER BY id DESC
LIMIT 1",
$order['id']
)
);
if(!empty($invoice) && empty($invoice['storage_country'])) {
$this->app->DB->Update(
sprintf(
"UPDATE rechnung
SET storage_country = '%s', zuarchivieren = 0, schreibschutz = 0
WHERE id = %d AND storage_country = ''",
$this->app->DB->real_escape_string($country), $invoice['id']
)
);
$this->app->erp->ANABREGSNeuberechnen($invoice['id'], 'rechnung');
if($invoice['schreibschutz']) {
$this->app->erp->PDFArchivieren('rechunng', $invoice['id'], true);
}
}
}
}
}
}
}
// @refactor in Artikel Modul
function artikelnummerscan($artikel)
{
$hauptprojekt = (int)$this->app->erp->Firmendaten('projekt');
$haupteanherstellerscanerlauben = $this->app->DB->Select("SELECT eanherstellerscanerlauben FROM projekt WHERE id = '$hauptprojekt' LIMIT 1");
$subwhere = "";
if($haupteanherstellerscanerlauben)$subwhere = 'or isnull(p.id)';
$artikelnummer = $this->app->erp->FirstTillSpace($artikel);
$artikelid = $this->app->DB->Select("SELECT id FROM artikel WHERE nummer='$artikelnummer' AND geloescht!=1 LIMIT 1");
if(!$artikelid)$artikelid = $this->app->DB->Select("SELECT art.id FROM artikel art
LEFT JOIN projekt p ON art.projekt = p.id
WHERE (p.eanherstellerscanerlauben = 1 $subwhere) AND art.ean='$artikelnummer' AND art.ean != '' AND art.geloescht!=1 LIMIT 1");
if(!$artikelid)$artikelid = $this->app->DB->Select("SELECT art.id FROM artikel art
LEFT JOIN projekt p ON art.projekt = p.id
WHERE (p.eanherstellerscanerlauben = 1 $subwhere) AND art.herstellernummer='$artikelnummer' AND art.herstellernummer != '' AND art.geloescht!=1 LIMIT 1");
$this->RunHook('artikelnummerscan',2, $artikel, $artikelid);
return $artikelid;
}
// @refactor in TemplateMessge Komponente
function AddTplMsg($message)
{
if(!isset($this->app->User))return;
if(!method_exists($this->app->User,'GetID'))return;
$user = (int)$this->app->User->GetID();
$this->app->DB->Insert("INSERT INTO `templatemessage` (`message`, `user`, `zeitstempel`) VALUES ('".$this->app->DB->real_escape_string($message)."','$user',now())");
return $this->app->DB->GetInsertID();
}
// @refactor in TemplateMessge Komponente
function GetTmpMessageOut()
{
if(isset($this->app->Secure) && $this->app->Secure && method_exists($this->app->Secure, 'GetGET'))
{
$msgid = (int)$this->app->Secure->GetGET('msgid');
if($msgid)return $this->base64_url_decode($this->GetTplMessage($msgid));
return $this->base64_url_decode($this->app->Secure->GetGET('msg'));
}
return '';
}
// @refactor in TemplateMessge Komponente
function GetTplMessage($id)
{
if(!isset($this->app->User))return;
if(!method_exists($this->app->User,'GetID'))return;
$user = (int)$this->app->User->GetID();
return $this->app->DB->Select("SELECT `message` FROM `templatemessage` WHERE `user` = '$user' AND id = '$id' LIMIT 1");
}
// @refactor in TemplateMessge Komponente
function base64_url_encode($input) {
return strtr(base64_encode($input), '+/=', '-_,');
}
// @refactor in TemplateMessge Komponente
function base64_url_decode($input) {
return base64_decode(strtr($input, '-_,', '+/='));
}
// @refactor in Session Klasse
function ClearCookies()
{
if((!empty($_COOKIE)?count($_COOKIE):0) > 0)
{
foreach($_COOKIE as $key=>$value)
{
if($key!=str_replace("SpryMedia","",$key))
setcookie ($key, time() - 3600);
}
}
}
/** @deprecated */
function ManuelEcho($text)
{
echo $this->ClearDataBeforeOutput($text);
exit;
}
// @refactor Formater Komponente
function ClearDataBeforeOutput($text, $replaceEmptyFormAction = true)
{
if ((bool)$replaceEmptyFormAction === true) {
$text = str_replace('form action=""','form action="#"',$text);
}
$text = str_replace('NONBLOCKINGZERO','',$text);
$text = str_replace("'","'",$text);
return $text;
}
function AdresseAnschriftString($id,$ansprechpartner=false)
{
/** @var Adresse $obj */
$obj = $this->LoadModul('adresse');
if(!empty($obj) && method_exists($obj, 'AdresseAnschriftString')) {
return $obj->AdresseAnschriftString($id,$ansprechpartner);
}
return '';
}
// @refactor BelegPositionen Widget
function EinkaufspreiseTabelle($artikel, $divid = '')
{
if($this->RechteVorhanden('artikel','einkauf'))
{
$table = new EasyTable($this->app);
$table->Query("SELECT if(CHAR_LENGTH(adr.name) > 20, CONCAT(SUBSTRING(adr.name,1,20),'...'), adr.name) as adrname, if(CHAR_LENGTH(e.bestellnummer) > 20, CONCAT(SUBSTRING(e.bestellnummer,1,20),'...'), e.bestellnummer) as bestellnummer, trim(e.ab_menge)+0 as ab, ". $this->FormatPreis("e.preis")." as preis, e.waehrung FROM einkaufspreise e LEFT JOIN adresse adr ON e.adresse = adr.id
WHERE e.artikel = '$artikel' AND (e.gueltig_bis = '0000-00-00' OR isnull(e.gueltig_bis) OR gueltig_bis >= now() ) ORDER BY adrname, ab_menge");
return '