<?php
/*=======================================================================
 *
 * check_jb_permanent.php
 *
 * Autor: Carsten Annacker
 *
 =======================================================================*/

/*
 *
 * Dieses Skript muss vom PDA-Server aufgerufen werden (per php Shell-Aufruf),
 * wenn er einen Job DAS ERSTE MAL "anfässt", damit Folgeaufträgen von
 * Daueraufträgen erzeugt werden
 *
 * Es wird geprüft, ob der Job ein Dauerauftrag ist:
 * - wenn ja, wird automatisch der Folgeauftrag generiert, WENN noch nicht
 * vorhanden
 * - wenn nein, dann passiert nix
 *
 * ACHTUNG: Die Storno-Problematik ist hier noch nicht berücksichtigt!
 *
 * Parameter:
 *   in:  jb_id (Klartext)
 *   out: nix; es wird nur der Folgeauftrag in die DB geschrieben,
 *        wenn job in kb_id Dauerauftrag ist
 *
 * Beispiel-Aufruf: php.exe -q -c c:\Programme\Server\php check_jb_permanent.php 4711
 *
 * TOBEDONE: Feiertagsproblematik nicht praxisnah gelöst -> Klärungsbedarf vorhanden
 * (Bsp.: Wöchentlicher Dauerauftrag wird auf übernächste Woche verschoben, wenn
 *  nächste Woche an dem normalen nächsten Termin ein Feiertag ist ...)
 * Es wird zur Zeit auch noch nicht geprüft, ob der nächste Termin nicht schon längst verstrichen ist!
 */

// Execution-Time for script
set_time_limit(0);
error_reporting(E_ALL ^ (E_DEPRECATED | E_NOTICE | E_STRICT));
$phpVersion = substr(phpversion(), 0, 3);

// diese Art der Bearbeitung schafft leider nur ca. einen Auftrag pro SEKUNDE,
// mit set_time_limit (300) können ca. 250 Aufträge bearbeitet werden
//set_time_limit (300);
include_once("../include/dbglobal.inc.php");
//$hq_id = $HTTP_GET_VARS["hq_id"];
//if ($hq_id == ""):
////  writeLog_("../log/check_jb_permanent_standing_", "Fehler: 'hq_id' fehlt!");
////  exit();
//  $hq_id = HQ_ID_DEFAULT;
//endif;
include_once("../include/inc_check_publicholiday.inc.php");
include_once("../include/caglobal.inc.php");
include_once("../include/global.inc.php");
include_once("../include/email/htmlMimeMail.php");
$ph = array();

//   $hq_id = 3;
//   $ph = getPublicHolidays(getDateTime("year"), "1", "0");
//print_r($ph);
//      $ph_new = array();
//      // Neuer Kalender ab heute bis zum Ende nächsten Jahres mit allen Werktagen
//      for ($i = 1; $tmp_timestamp < mktime(0, 0, 0, 12, 31, date("Y") + 1); $i++):
//        $tmp_timestamp = mktime(0, 0, 0, date("m"), date("d") + $i, date("Y"));
//        if (!isPublicHoliday(date("Y", $tmp_timestamp), date("m", $tmp_timestamp), date("d", $tmp_timestamp)) && date("w", $tmp_timestamp) != 6)
//          $ph_new[] = array(date("Y", $tmp_timestamp), date("m", $tmp_timestamp), date("d", $tmp_timestamp));
//      endfor;
//      $ph = $ph_new;
//print_r($ph); die();

$no_continuation_list = array("17519468");

// "get_saved_tour.php" holt die Daten eines gespeicherten Jobs $jb_id
// voher muss aber die jobList initialisiert werden (macht sonst javascript)
$jobList = array();

// Einzelmodus
$jb_id = "";
if (isset($argv[1]))
  $jb_id = $argv[1];

$recipients = array("ca@assecutor.de");

if ($jb_id == "")
{
  // Sicherstellen, dass auch wirklich nur ein Prozess läuft...
  if ($argc > 0):
    $cnt = 0;
    exec("ps -fA", $output);
    for ($i = 0; $i < count($output); $i++):
      $pos = strpos ($output[$i], $argv[0]);
      if (!($pos === false)) {
        $cnt++;
        $cur_pid = trim(substr($output[$i], 9, 5));
        if ($cur_pid != getmypid())
          $pid = $cur_pid;
      }
    endfor;
    if ($cnt > 1):
      $mysql_process_list = shell_exec('echo "SHOW PROCESSLIST;" | mysql -h172.16.0.123 -P3391 -u root -p%Fidewz37% | grep -v Sleep 2>&1') . "\n";
      $system_process_list = shell_exec('ps aux | sort -nrk 3,3 2>&1') . "\n";
      echo $mysql_process_list . "\n";
      echo $system_process_list . "\n";
      exec("kill $pid");
      echo "[" . date("Y-m-d H:i:s") . "] " . "$PHP_SELF: [" . $argv[0] . "] lief schon als \$pid = " . $pid . ". Dieser Prozess wurde nun gekillt ...!\n" .
        $mysql_process_list . "\n" .
        $system_process_list . "\n";
      $mailObj = new htmlMimeMail();
      $mailObj->setFrom("support@assecutor.de");
//      $mailObj->setBcc("ca@assecutor.de");
      $mailObj->setSubject("Doppelter check_jb_permanent.php");
      $mailObj->setText("$PHP_SELF: [" . $argv[0] . "] lief schon als \$pid = " . $pid . ". Dieser Prozess wurde nun gekillt ...!\n");
      $mailResult = $mailObj->send($recipients, 'smtp');
      exit();    
    endif;
  endif;
//  if (date("H") != "00"):
    $mailObj = new htmlMimeMail();
    $mailObj->setFrom("auto-mailer@assecutor.de");
//    $mailObj->setBcc("ca@assecutor.de");
    $mailObj->setSubject("check_jb_permanent.php wurde neu gestartet");
    $mailObj->setText("$PHP_SELF: [" . $argv[0] . "] wurde neu gestartet...\n");
    $mailResult = $mailObj->send($recipients, 'smtp');
//  endif;

//  $yesterday = getdate(mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));
  $yesterday = getdate(mktime(0, 0, 0, date("m"), date("d") - 2, date("Y")));
  $jb_finishtime_start = $yesterday['year'] . "-" . sprintf("%02d", $yesterday['mon']) . "-" . sprintf("%02d", $yesterday['mday']) . " 00:00:01";
//  $jb_finishtime_start = "2008-02-20 00:00:01";

  getDb2Connection();     // Try to connect request server because of performance
  $db_conn = getDbConnectionSpecial($dbhostStatistic, $dbname2, $dblogin2, $dbpassword2);

  $dirty_jobs_sql = "";
  $sqlquery = "SELECT gdc_obj_id FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_invtext_dirty' and gdc_content = '1'";
  writeLog_("../log/check_jb_permanent_invtext_", "Querying for forgotten finished jobs to rebuild `jb_invtext` [$sqlquery]");
  $res = $db->query($sqlquery);
  while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
    if ($dirty_jobs_sql != "")
      $dirty_jobs_sql .= ",";
    $dirty_jobs_sql .= $row["gdc_obj_id"];
  endwhile;
  $res->free();
  
  // Endless loop
  while (TRUE):
echo "[" . date("Y-m-d H:i:s") . "] updating keepalive (memory_get_usage() = " . memory_get_usage() . ")\n";
    updateStmt("keepalive", "ka_process", "standing_orders", array("ka_lastexecutiontime", getDateTime("0")),"");
    $today = getdate();
    $now = $today['year'] . "-" . sprintf("%02d", $today['mon']) . "-" . sprintf("%02d", $today['mday']) . " " .
      sprintf("%02d", $today['hours']) . ":" . sprintf("%02d", $today['minutes']) . ":" . sprintf("%02d", $today['seconds']);
    $jb_finishtime_today = $today['year'] . "-" . sprintf("%02d", $today['mon']) . "-" . sprintf("%02d", $today['mday']) . " 00:00:01";

    //********************************************************************************
    // Dinge, die zu einer bestimmten Uhrzeit passieren sollen
    // Diese sind in eine Schleife eingebaut, die für mindestens 5 Minuten Verzögerung sorgt

    for ($i = 0; $i < 5; $i++):

      //********************************************************************************
      // Neue Funktion 27.06.2013: Binary Logs auf test_sb aufräumen

//$mysql_db = mysql_connect("172.16.0.102:3391", $dblogin, $dbpassword) or die (mysql_error($mysql_db));
//$purge_query = "PURGE MASTER LOGS BEFORE '" . date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 14, date("Y"))) . " 00:00:00'";
//mysql_query($purge_query, $mysql_db) or die ('SET NAMES latin1' . ": " . mysql_error($mysql_db));
//mysql_close($mysql_db);  $yesterday = getdate(mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));
//      writeLog_("../log/check_jb_permanent_invtext_", "Deleting finished commands in messageforum [$sqlquery]");

      //********************************************************************************
      // Neue Funktion 13.08.2011: Lager-Mail an Knapp (Stuttgart, EINE PRO TAG)
    
////      $autoExportDKT = "acapella7890";
////      include("../tools/auto_export_stkat_DKT.php");
//      $last_execution = $db->getOne("SELECT ka_lastexecutiontime FROM keepalive WHERE ka_process = 'standing_orders'");
//      list($jt_y, $jt_m, $jt_d, $jt_h, $jt_i, $jt_s) = getValsFromDate($jb_finishtime_today);
//      list($le_y, $le_m, $le_d, $le_h, $le_i, $le_s) = getValsFromDate($last_execution);      
//      if (mktime($jt_h, $jt_i, $jt_s, $jt_m, $jt_d, $jt_y)
//        > mktime($le_h, $le_i, $le_s, $le_m, $le_d, $le_y)):      
//        $system_result = "";
//        $cmd = "php ../tools/auto_export_stkat_DKT.php acapella7890 >> ../log/auto_export_stkat_DKT.stdout+err 2>&1 &";
//        $ausgabe = system($cmd, $system_result);
//        writeLog_("../log/check_jb_permanent_invtext_", "Calling auto_export_stkat_DKT.php: ausgabe='$ausgabe'");
//      else:
//        writeLog_("../log/check_jb_permanent_invtext_", "auto_export_stkat_DKT.php not called: '$jb_finishtime_today' <= '$last_execution'");
//      endif;
//      updateStmt("keepalive", "ka_process", "standing_orders", array("ka_lastexecutiontime", getDateTime("0")),"");

      // Neue Funktion 21.08.2023: TSZ für Kundenpreis und Frachtvergütung müssen in allen Aufträgen des heutigen Tages überprüft werden
      if (date("H:i") == "00:15"):
        $csc_id_payer_cashArr = array();
        $sqlquery = "SELECT hq_id, par_value FROM parameter WHERE par_key = 'CSC_ID_PAYER_CASH' ORDER BY hq_id";
        $res = $db2->query($sqlquery);
        if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
        while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
          $csc_id_payer_cashArr[] = $row['par_value'];
        endwhile;
        $res->free();
        $sqlquery = "SELECT jb_id, csc_id_payer, csc_id_payer_cash, hq_id, jb_ordertime, vht_id, jb_markup FROM job
          WHERE jb_ordertime >= '" . date("Y-m-d 00:00:00") . "' AND jb_ordertime <= '" . date("Y-m-d H:i:s", mktime(0, 0, 0, date("m"), date("d") + 3, date("Y"))) . "' AND jb_status IN (1,8,9)";
        writeLog_("../log/check_markup_", $sqlquery);
        $result = $db2->query($sqlquery);
        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
        while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
          writeLog_("../log/check_markup_", "*** " . $row['jb_id'] . ", \$row[\"csc_id_payer\"] = " . $row["csc_id_payer"] . ", \$row[\"csc_id_payer_cash\"] = " . $row["csc_id_payer_cash"] .
            ", \$row[\"hq_id\"] = " . $row["hq_id"] . ", \$row[\"jb_ordertime\"] = " . $row["jb_ordertime"] . ", \$row[\"vht_id\"] = " . $row["vht_id"] . ", \$row[\"jb_markup\"] = " . $row["jb_markup"]);
          $csc_id_payer = $row['csc_id_payer'];
          if (in_array($csc_id_payer, $csc_id_payer_cashArr)):
            if ($row["csc_id_payer_cash"] != 0)
              $csc_id_payer = $row['csc_id_payer_cash'];
          endif;
          $cs_id = getFieldValueFromId("costcenter", "csc_id", $csc_id_payer, "cs_id");
          $srvt_name = $db->getOne("SELECT mt_value FROM metatype WHERE mt_sort = '" . $row['vht_id'] . "' AND mt_type = 'vehicletype'");

          $jb_markup_man = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $row['jb_id'] . " AND mt_sort = 8");
          if ($jb_markup_man == "") {
            $jb_markup = getFuelMarkup($srvt_name, $cs_id, $row['hq_id'], $row['jb_ordertime']);
            writeLog_("../log/check_markup_", $row['jb_id'] . ", \$row[\"jb_markup\"] = " . $row["jb_markup"] . ", \$jb_markup = " . $jb_markup);
            if ($jb_markup != $row["jb_markup"]) {
              writeLog_("../log/check_markup_", "UPDATE job SET jb_markup = " . $jb_markup . " WHERE jb_id = " . $row['jb_id']);
              $db->query("UPDATE job SET jb_markup = " . $jb_markup . " WHERE jb_id = " . $row['jb_id']);
              recalc_jb_price($row['jb_id'], $jb_markup);
			}
	      }
          $jb_cr_markup_man = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $row['jb_id'] . " AND mt_sort = 9");
          if ($jb_cr_markup_man == "") {
            $jb_cr_markup_cur = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $row['jb_id'] . " AND mt_sort = 1");
            $jb_cr_markup = getFuelMarkupCr($srvt_name, $cs_id, $row['hq_id'], $row['jb_ordertime']);
            writeLog_("../log/check_markup_", $row['jb_id'] . ", \$jb_cr_markup_cur = " . $jb_cr_markup_cur . ", \$jb_cr_markup = " . $jb_cr_markup);
            if ($jb_cr_markup != $jb_cr_markup_cur) {
              writeLog_("../log/check_markup_", "DELETE FROM jobprice WHERE jb_id = " . $row['jb_id'] . " AND mt_sort = 1");
              $db->query("DELETE FROM jobprice WHERE jb_id = " . $row['jb_id'] . " AND mt_sort = 1");
              writeLog_("../log/check_markup_", "INSERT INTO jobprice (jb_id, mt_sort, jbprc_price) VALUES (" . $row['jb_id'] . ", 1, " . $jb_cr_markup . ")");
              $db->query("INSERT INTO jobprice (jb_id, mt_sort, jbprc_price) VALUES (" . $row['jb_id'] . ", 1, " . $jb_cr_markup . ")");
              recalc_jb_cr_price($row['jb_id']);
			}
          }
        endwhile;
        $result->free();
      endif;
      if (date("H:i") == "01:00" || $dirty_jobs_sql != ""):

        //********************************************************************************
        // Weitere Funktion:
        // Wenn zwischenzeitlich Kommissionsnummern eingetragen wurden, dann werden diese
        // vom PDAServer nicht im Rechnungstext eingetragen. Es muss also (einmal am Tag)
        // der Rechnungstext aller eledigten Aufträge neu erzeugt werden!
        // Das wird der Einfachheit halber gleich hier erledigt.
      
echo "[" . date("Y-m-d H:i:s") . "] checking finished jobs (memory_get_usage() = " . memory_get_usage() . ")\n";
        // Alle Aufträge seit dem letzten Mal finden, die erledigt sind (aber keine Unteraufträge)

        $where_clause = 
          "((jb_storno != 3 AND jb_storno != 4) OR jb_storno IS NULL) " .
          " AND job.jb_status = 2 AND (jb_finishtime BETWEEN '$jb_finishtime_start' AND '$jb_finishtime_today')" .
//          " AND job.jb_status = 2 AND (jb_finishtime BETWEEN '2019-04-01 00:00:00' AND '$jb_finishtime_today')" .
          " AND jb_export_time IS NULL AND (job.jb_id_parent IS NULL OR job.jb_id_parent <= 0)";
        if ($dirty_jobs_sql != "")
          $where_clause = "job.jb_id IN (" . $dirty_jobs_sql . ")";

        $sqlquery = "SELECT DISTINCT job.jb_id, job.hq_id, job.jb_finishtime, job.jb_freetext_2, job.jb_cr_price FROM job, tour WHERE " .
          $where_clause .
          " AND job.jb_id = tour.jb_id AND tour.tr_commission_no != \"\"" .
          " ORDER BY job.jb_id";
  //      $sqlquery = "SELECT job.jb_id, job.hq_id, job.jb_finishtime, job.jb_freetext_2 FROM job WHERE ((jb_storno != 3 AND jb_storno != 4) OR jb_storno IS NULL) " .
  //        " AND job.jb_status = 2 AND (jb_finishtime BETWEEN '$jb_finishtime_start' AND '$jb_finishtime_today') ORDER BY job.jb_id";
        writeLog_("../log/check_jb_permanent_invtext_", "Querying for finished jobs to rebuild `jb_invtext` [$sqlquery]");
        $res = $db->query($sqlquery);
        if (DB::isError($res))
          reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());

        $rows = array();
        while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
          if ($row["jb_id"] != ""):
            $rows[] = $row;
            if ($dirty_jobs_sql == "")
              insertStmt("genericdatacontainer", array("gdc_obj_type", "jb", "gdc_obj_id", $row["jb_id"], "gdc_gen_fieldname", "jb_invtext_dirty", "gdc_content", "1", "gdc_context", date("Y-m-d H:i:s")));
          endif;
        endwhile;
        $res->free();

        foreach ($rows as $cur_row) {
          $hq_id = $cur_row["hq_id"];
          writeLog_("../log/check_jb_permanent_invtext_", "Writing new invoice text in job " . $cur_row["jb_id"] . " (jb_cr_price: '" . $cur_row["jb_cr_price"] . "', jb_finishtime: '". $cur_row["jb_finishtime"] . "', \$jb_finishtime_start: '$jb_finishtime_start', \$jb_finishtime_today = '$jb_finishtime_today', memory_get_usage() = " . memory_get_usage() . ")");
          $jb_cr_price_total = $cur_row["jb_cr_price"];
          $jb_hiddenFreetext_1 = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $cur_row["jb_id"] . " AND gdc_gen_fieldname = 'jb_hiddenFreetext_1'");
          $jb_cr_serviceprice = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $cur_row["jb_id"] . " AND gdc_gen_fieldname = 'jb_cr_serviceprice'");
          // Sondervereinbarungen holen!!!
          $tmp_freetext_2Arr = explode("²", $cur_row["jb_freetext_2"]);
          // Unteraufträge holen!
          list ($tmp_add_jb_ids, $tmp_add_sids, $tmp_add_prices) = getJobChildren($cur_row["jb_id"], "job", "false");
          $jb_toll = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $cur_row["jb_id"] . " AND gdc_gen_fieldname = 'jb_toll'");
          mk_jb_invtext($cur_row["jb_id"], true, $tmp_freetext_2Arr[0], $tmp_freetext_2Arr[1], $tmp_freetext_2Arr[2], $tmp_freetext_2Arr[3], $tmp_add_sids, $tmp_add_prices);
  //        $dummy = $db->query("UPDATE job SET jb_freetext_2 = '' WHERE jb_id = " . $cur_row["jb_id"]);
//          deleteStmt("genericdatacontainer", "gdc_obj_type = 'jb' AND gdc_obj_id = " . $cur_row["jb_id"] . " AND gdc_gen_fieldname = 'jb_invtext_dirty'");
          updateStmt("genericdatacontainer", "", "", array("gdc_content", "0", "gdc_context", date("Y-m-d H:i:s")), "gdc_obj_id = " . $cur_row["jb_id"] . " AND gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_invtext_dirty'");
        // Set execution time for keepalive (in order to avoid being called anew while still running (making invoice text can take long time!)
  //      updateStmt("keepalive", "ka_process", "standing_orders", array("ka_lastexecutiontime", getDateTime("0")),"");
	    }
        $dirty_jobs_sql = "";

        //********************************************************************************
        // Neue Funktion 21.12.2010: Tabellen 'commandexec' und 'messageforum' aufräumen
        
echo "[" . date("Y-m-d H:i:s") . "] cleaning up commandexechistory (memory_get_usage() = " . memory_get_usage() . ")\n";
        // Vorher commandexechistory aufräumen (sollte eigentlich nicht nötig sein)
        $sqlquery =
          "DELETE phoenix_pda.commandexechistory.* FROM phoenix_pda.commandexec, phoenix_pda.commandexechistory WHERE phoenix_pda.commandexec.cmde_id = phoenix_pda.commandexechistory.cmde_id";
        writeLog_("../log/check_jb_permanent_invtext_", "[$sqlquery]");
        $res = $db->query($sqlquery);
        if (DB::isError($res))
          reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
          
echo "[" . date("Y-m-d H:i:s") . "] moving finished commands to commandexechistory (memory_get_usage() = " . memory_get_usage() . ")\n";
        // jetzt die eigentliche Prozedur
        $createtime_limit = date("Y-m-d H:i:s", mktime(date("H"), date("i"), date("s"), date("m") - 6, date("d"), date("Y")));
        $where_clause = "WHERE cmde_mode = '0' OR cmde_exec_timelimit < '" . $jb_finishtime_today . "' OR cmde_exec_time < '" . $createtime_limit . "'";
        $sqlquery =
          "INSERT INTO phoenix_pda.commandexechistory (cmde_id, cr_id, hq_id, cmd_command, cmde_exec_time, cmde_exec_timelimit, cmde_mode, cmde_param) " .
            "SELECT cmde_id, cr_id, hq_id, cmd_command, cmde_exec_time, cmde_exec_timelimit, cmde_mode, cmde_param FROM phoenix_pda.commandexec $where_clause";
        writeLog_("../log/check_jb_permanent_invtext_", "Moving finished commands to commandexechistory [$sqlquery]");
        $res = $db->query($sqlquery);
        if (DB::isError($res))
          reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
        $sqlquery =
          "DELETE FROM phoenix_pda.commandexec $where_clause";
        writeLog_("../log/check_jb_permanent_invtext_", "Deleting finished commands in commandexec [$sqlquery]");
        $res = $db->query($sqlquery);
        if (DB::isError($res))
          reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
  
echo "[" . date("Y-m-d H:i:s") . "] moving finished commands to messageforumhistory (memory_get_usage() = " . memory_get_usage() . ")\n";
        $createtime_limit = date("Y-m-d H:i:s", mktime(date("H"), date("i"), date("s"), date("m"), date("d") - 14, date("Y")));
        $where_clause = "WHERE mf_state = 2 OR mf_createtime < '" . $createtime_limit . "' OR mf_expiration < NOW()";
        $sqlquery =
          "INSERT INTO phoenix_log.messageforumhistory (mf_id, hq_id, mf_type, mf_createtime, mf_expiration, mf_delivery, mf_acknowledge, usr_id_sender, usr_id_receiver, mf_usr_type, mf_state, mf_prio, mf_subject, mf_body, mf_pre_id) " .
            "SELECT mf_id, hq_id, mf_type, mf_createtime, mf_expiration, mf_delivery, mf_acknowledge, usr_id_sender, usr_id_receiver, mf_usr_type, mf_state, mf_prio, mf_subject, mf_body, mf_pre_id FROM phoenix_log.messageforum $where_clause";
        writeLog_("../log/check_jb_permanent_invtext_", "Moving finished commands to messageforumhistory [$sqlquery]");
        $res = $db->query($sqlquery);
        if (DB::isError($res))
          reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
        $sqlquery =
          "DELETE FROM phoenix_log.messageforum $where_clause";
        writeLog_("../log/check_jb_permanent_invtext_", "Deleting finished commands in messageforum [$sqlquery]");
        $res = $db->query($sqlquery);
        if (DB::isError($res))
          reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());

echo "[" . date("Y-m-d H:i:s") . "] cleaning up locating and log (memory_get_usage() = " . memory_get_usage() . ")\n";
        //********************************************************************************
        // Neue Funktion 09.10.2015: Tabellen 'locating' und 'log' aufräumen        
        $sqlquery =
          "DELETE FROM phoenix_log.locating WHERE loc_created < '" . date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 60, date("Y"))) . "'";
        $res = $db->query($sqlquery);
        writeLog_("../log/check_jb_permanent_invtext_", "Deleting entries in locating older than 3 months [$sqlquery]");
        if (DB::isError($res))
          reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
        for ($hour = 0; $hour < 24; $hour++):
          $sqlquery =
            "DELETE FROM phoenix_log.log WHERE logo_id IN (33, 113, 101, 103, 29, 30, 31, 160, 156) AND log_createtime < '" . date("Y-m-d H:i:s", mktime($hour, 59, 59, date("m"), date("d") - 61, date("Y"))) . "'" .
            " AND log_createtime > '" . date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 63, date("Y"))) . "'";
          $res = $db->query($sqlquery);
          writeLog_("../log/check_jb_permanent_invtext_", "Deleting entries in log (logo_ids 33, 113, 101, 103, 29, 30, 31) older than 3 months [$sqlquery]");
          if (DB::isError($res))
            reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
        endfor;
//echo "[" . date("Y-m-d H:i:s") . "] calling ../tools/deleteDuplicateCr_sids.php (memory_get_usage() = " . memory_get_usage() . ")\n";
//        //********************************************************************************
//        // Neue Funktion 12.04.2016: Dubletten-Aufräumung
//        writeLog_("../log/check_jb_permanent_invtext_", "calling ../tools/deleteDuplicateCr_sids.php");
//        $system_result = "";
//        $cmd = "php ../tools/deleteDuplicateCr_sids.php >> ../log/check_jb_permanent_invtext_" . date("Ym") . ".log 2>&1";
//        $ausgabe = system($cmd, $system_result);

        //********************************************************************************
        // Neue Funktion 30.06.2021: Spezial-Behandlung für STB979666 "Dachdecker Einkauf"
//SELECT job.jb_id AS Auftragsr, job.csc_id, jb_ordertime AS Auftragszeit, job.csc_id_payer, costcenter.csc_name AS Kostenstelle_Zahler,
// tour.csc_id, csc1.csc_name AS Kostenstelle_Abholer, usr_account AS Erfasser
//FROM job, costcenter, customer, tour, costcenter AS csc1, customer AS cs1, user
//WHERE jb_storno IS NULL AND jb_ordertime > "2021-06-01 00:00:00" AND job.csc_id_payer = costcenter.csc_id AND costcenter.cs_id = customer.cs_id AND customer.cs_eid = "STB979666"
// AND job.jb_id = tour.jb_id AND tour.csc_id = csc1.csc_id AND cs1.cs_id = csc1.cs_id AND cs1.cs_eid = "STB979666" AND tour.tr_sort = 1 AND emp_id = user.usr_id AND usr_type = 2
// AND job.csc_id_payer != tour.csc_id
        $sqlquery = "SELECT DISTINCT job.jb_id, tour.csc_id
          FROM job, costcenter, customer, tour, costcenter AS csc1, customer AS cs1, user, tourservice
          WHERE jb_storno IS NULL AND jb_ordertime > '2021-07-01 00:00:00' AND job.csc_id_payer = costcenter.csc_id AND costcenter.cs_id = customer.cs_id AND customer.cs_eid = 'STB979666'
          AND job.jb_id = tour.jb_id AND tour.csc_id = csc1.csc_id AND cs1.cs_id = csc1.cs_id AND cs1.cs_eid = 'STB979666' AND tour.tr_sort = 1 AND emp_id = user.usr_id AND usr_type = 2
          AND (job.csc_id_payer = 865206 OR tourservice.csc_id = 865206) AND tourservice.jb_id = job.jb_id";
        writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
        $result = $db2->query($sqlquery);
        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
        while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
          $sqlquery = "UPDATE job SET csc_id_payer = " . $row["csc_id"] . " WHERE jb_id = " . $row["jb_id"] . " AND csc_id_payer = 865206";
          writeLog_("../log/check_jb_permanent_invtext_", "[$sqlquery]");
          $res = $db->query($sqlquery);
          if (DB::isError($res))
            reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
          $sqlquery = "UPDATE tourservice SET csc_id = " . $row["csc_id"] . " WHERE jb_id = " . $row["jb_id"] . " AND csc_id = 865206";
          writeLog_("../log/check_jb_permanent_invtext_", "[$sqlquery]");
          $res = $db->query($sqlquery);
          if (DB::isError($res))
            reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
        endwhile;
        $result->free();

        //********************************************************************************
        // Neue Funktion 29.11.2023: Filter aus Aufträgen löschen, wenn sie zuvor aus der Filterliste gelöscht worden sind

        $sql_query = "SELECT par_value FROM parameter WHERE par_key = 'FILTER_TO_BE_DELETED'";
        writeLog_("../log/check_jb_permanent_invtext_", $sql_query);
        $filter_to_be_deleted = $db->getOne($sql_query);
        if (trim($filter_to_be_deleted) != "") {
          $filters = array_filter(explode(",", $filter_to_be_deleted));
          if (count($filters) > 0) {
            $sqlQueries = array(
              "SELECT jb_id, jb_cr_filter FROM job WHERE LENGTH(jb_tourname) > 0 AND ",
              "SELECT jb_id, jb_cr_filter FROM job WHERE (jb_ordertime >= NOW()) AND ((jb_storno != 3 AND jb_storno != 4) OR jb_storno IS NULL) AND jb_status != 2 AND (jb_permanent IN (4, 5, 6, 7, 8, 9, 10, 11) OR (jb_permanent IN (1, 2, 3)" .
              " AND jb_permanent2 != '0000000')) AND (jb_id_copy_permanent IS NULL OR jb_id_copy_permanent = 0) AND (jp_permenddat >= NOW() OR jp_permenddat IS NULL OR jp_permenddat = '0000-00-00 00:00:00') AND "
            );
            
            foreach ($filters as $filter) {
              if (trim($filter) != "") {
				$fLen = strlen($filter) + 1;
                $filter_clauses = array(
                 array(
                   "jb_cr_filter = '" . $filter . "'",
                   "UPDATE job SET jb_cr_filter = '', jb_modify = jb_modify WHERE jb_id = "),
                 array(
                   "jb_cr_filter LIKE '%," . $filter . ",%'",
                   "UPDATE job SET jb_cr_filter = REPLACE(jb_cr_filter, '," . $filter . ",', ','), jb_modify = jb_modify WHERE jb_id = "),
                 array(
                   "LEFT(jb_cr_filter, " . $fLen . ") = '" . $filter . ",'",
                   "UPDATE job SET jb_cr_filter = REPLACE(jb_cr_filter, '" . $filter . ",', ''), jb_modify = jb_modify WHERE jb_id = "),
                 array(
                   "RIGHT(jb_cr_filter, " . $fLen . ") = '," . $filter . "'",
                   "UPDATE job SET jb_cr_filter = REPLACE(jb_cr_filter, '," . $filter . "', ''), jb_modify = jb_modify WHERE jb_id = ")
                );
          	  
                foreach ($sqlQueries as $sqlQuery) {
                  foreach ($filter_clauses as $filter_clause) {
                    $sql_query = $sqlQuery . $filter_clause[0];
                    writeLog_("../log/check_jb_permanent_invtext_", $sql_query);
                    $res = $db2->query($sql_query);
                    if (DB::isError($res)) die ("$PHP_SELF: '$sqlQuery'" . $res->getMessage());
                    while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
                      $sql_query = $filter_clause[1] . $row["jb_id"] . " AND jb_cr_filter = '" . $row["jb_cr_filter"] . "'";
                      writeLog_("../log/check_jb_permanent_invtext_", $sql_query);
                      $db->query($sql_query);
                    endwhile;
                    $res->free();
                  }
                }
              }
            }
            $sql_query = "UPDATE parameter SET par_value = '' WHERE par_key = 'FILTER_TO_BE_DELETED'";
            writeLog_("../log/check_jb_permanent_invtext_", $sql_query);
            $db->query($sql_query);
          }
        }

        $jb_finishtime_start = $jb_finishtime_today;
      //********************************************************************************
      // Neue Funktion 03.01.2015:
      // Anfang des Jahres job2 umbennen und neu erzeugen; erst um 01:30 Uhr, um sicherzugehen, dass dieses Skript auch wirklich läuft    
      elseif (date("d") == "02" && date("m") == "01" && date("H:i") == "01:30"):
        $sqlquery1 = "DROP TABLE IF EXISTS job2_" . (date("Y") - 1);
//        $result = $db2->query($sqlquery1);
//        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
        $sqlquery2 = "ALTER TABLE job2 RENAME job2_" . (date("Y") - 1);
//        $result = $db2->query($sqlquery2);
//        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
        $sqlquery3 =
          "CREATE TABLE job2 (\n" .
          "  jb_id int(10) NOT NULL default '0',\n" .
          "  jb2_history_rawdata blob NOT NULL,\n" .
          "  jb2_history_hq blob NOT NULL,\n" .
          "  jb2_history_cs blob NOT NULL,\n" .
          "  jb2_history_mail blob NOT NULL,\n" .
          "  UNIQUE KEY jb_id (jb_id)\n" .
          ") ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_german1_ci\n";
//        $result = $db2->query($sqlquery3);
//        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
        $mailObj = new htmlMimeMail();
        $mailObj->setFrom("support@assecutor.de");
        $mailObj->setSubject("Tabelle job2 wurde neu angelegt");
        $mailObj->setText("Und die alte Tabelle job2 wurde umbenannt in job2_" . (date("Y") - 1) . ".\n\n SQL-Statements:\n\n$sqlquery1\n\n$sqlquery2\n\n$sqlquery3\n\nAnpassung der Replikation nicht vergessen!");
//        $mailResult = $mailObj->send(array("admin@assecutor.de"), 'smtp');
        $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
        writeLog_("../log/check_jb_permanent_invtext_", "Tabelle job2 wurde neu angelegt");
      //********************************************************************************
      // Neue Funktion 22.06.2018:
      // Jeden Montag eine Hennig-Statistik-Mail
//      elseif (date("w") == 1 && date("H:i") == "04:59"):
//        $date_from = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 7, date("Y"))) . " 00:00:00";
//        $date_mail_from = substr($date_from, 8, 2) . "." . substr($date_from, 5, 2) . "." . substr($date_from, 0, 4);
//        $date_to = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y"))) . " 23:59:59";
//        $date_mail_to = substr($date_to, 8, 2) . "." . substr($date_to, 5, 2) . "." . substr($date_to, 0, 4);
//        $sqlquery =
//          "SELECT job.cr_sid AS Fahrzeugnr, tour.jb_id AS Auftragsnr, tourarticle.tr_sort AS Stationsnr, CONCAT('=\"', tourarticle.trat_serialno, '\"') AS Scancode,
//             IFNULL(LEFT(tourarticleprocess.tratp_createtime, 10), '') AS Datum
//           FROM customer, costcenter, job, tour, tourarticle
//             LEFT JOIN tourarticleprocess ON tourarticle.trat_id = tourarticleprocess.trat_id
//           WHERE customer.cs_eid = 'STE900684' AND customer.cs_id = costcenter.cs_id AND costcenter.csc_id = job.csc_id_payer AND job.jb_id = tour.jb_id AND tour.tr_id = tourarticle.tr_id
//           AND trat_serialno != '' AND jb_status = 2 AND jb_storno IS NULL AND jb_ordertime >= '" . $date_from . "' AND jb_ordertime <= '" . $date_to . "'";
//        writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
//        $result = $db2->query($sqlquery);
//        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
//        $csv_txt = "Fahrzeugnr;Auftragsnr;Stationsnr;Scancode;Datum\n";
//        while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
//          $csv_txt .= $row["Fahrzeugnr"] . ";" . $row ["Auftragsnr"] . ";" . $row ["Stationsnr"] . ";" . $row ["Scancode"] . ";" . $row ["Datum"] . "\n";
//        endwhile;
//        $result->free();
//
//        $tmp_filename = "STE900684_" . substr($date_to, 0, 10) . ".csv";
//        $tmp_fullfilename = "../temp/" . $tmp_filename;
//        file_put_contents($tmp_fullfilename, $csv_txt);
//        $mailObj = new htmlMimeMail();
//        $mailObj->setFrom("auto-mailer@assecutor.de");
//        $mailObj->setBcc("support@assecutor.de");
//        $mailObj->setSubject("Scancodes für STE900684 von " . $date_mail_from . " bis " . $date_mail_to);
//        $mailObj->setText("Im Anhang die Liste der Scancodes aller erledigten Aufträge von STE900684 in der letzten Woche.\n\n");
//        $mailObj->addAttachment($mailObj->getFile($tmp_fullfilename), $tmp_filename);
////        $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
//        $mailResult = $mailObj->send(array("essen@stadtbote.de"), 'smtp');
//        unlink($tmp_fullfilename);
//        writeLog_("../log/check_jb_permanent_invtext_", "Hennig-Mail versandt: \$mailResult='$mailResult'");

      //********************************************************************************
      // Neue Funktion 06.08.2018:
      // Jeden Ersten im Monat eine STH913068-Statistik-Mail
      elseif (date("d") == 1 && date("H:i") == "05:15"):
//      elseif (date("d") == 9 && date("H:i") == "20:08"): (nur zum Testen)
        $date_from = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 1, date("Y"))) . " 00:00:00";
        $date_mail_from = substr($date_from, 8, 2) . "." . substr($date_from, 5, 2) . "." . substr($date_from, 0, 4);
        $date_to = date("Y-m-d", mktime(0, 0, 0, date("m"), 0, date("Y"))) . " 23:59:59";
        $date_mail_to = substr($date_to, 8, 2) . "." . substr($date_to, 5, 2) . "." . substr($date_to, 0, 4);
//        $sqlquery =
//         "SELECT jb_ordertime AS Auftragsdatum, tour.jb_id AS Auftragsnr, CONCAT(REPLACE(ROUND(jb_totalprice, 2), '.', ','), ' €') AS Preis,
//          csc_name AS Kostenstellen_Nr, ad_street AS Straße, tr_hsno AS Hausnr, ad_zipcode AS PLZ, cr_sid AS Kurier, tr_commission_no AS Kommissionsnr,
//          CASE jb_serviceprice WHEN 0 THEN '' ELSE CONCAT(REPLACE(ROUND(jb_serviceprice, 2), '.', ','), ' €') END AS Servicezeit
//          FROM customer, costcenter, job, tour, address
//          WHERE customer.cs_eid = 'STH913068' AND customer.cs_id = costcenter.cs_id AND costcenter.csc_id = job.csc_id_payer AND tour.ad_id = address.ad_id
//          AND job.jb_id = tour.jb_id AND jb_status = 2 AND jb_storno IS NULL AND jb_ordertime >= '" . $date_from . "' AND jb_ordertime <= '" . $date_to . "' AND tr_sort = 1";
//        writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
//        $result = $db2->query($sqlquery);
//        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
//        $csv_txt = "Auftragsdatum;Auftragsnr;Preis;Kostenstellen_Nr;Straße;Hausnr;PLZ;Kurier;Kommissionsnr;Servicezeit\n";
//        while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
//          $csv_txt .= $row["Auftragsdatum"] . ";" . $row ["Auftragsnr"] . ";" . $row ["Preis"] . ";" . $row ["Kostenstellen_Nr"]
//            . ";" . $row ["Straße"] . ";" . $row ["Hausnr"] . ";" . $row ["PLZ"] . ";" . $row ["Kurier"] . ";" . $row ["Kommissionsnr"] . ";" . $row ["Servicezeit"] . "\n";
//        endwhile;
//        $result->free();
//
//        $tmp_filename = "STH913068_" . substr($date_to, 0, 10) . ".csv";
//        $tmp_fullfilename = "../temp/" . $tmp_filename;
//        file_put_contents($tmp_fullfilename, $csv_txt);
//        $mailObj = new htmlMimeMail();
//        $mailObj->setFrom("auto-mailer@assecutor.de");
//        $mailObj->setBcc("support@assecutor.de");
//        $mailObj->setSubject("Monatsmail für STH913068 von " . $date_mail_from . " bis " . $date_mail_to);
//        $mailObj->setText("Im Anhang die Liste aller erledigten Aufträge von STH913068 im letzten Monat.\n\n");
//        $mailObj->addAttachment($mailObj->getFile($tmp_fullfilename), $tmp_filename);
////        $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
//        $mailResult = $mailObj->send(array("hannover@stadtbote.de"), 'smtp');
//        unlink($tmp_fullfilename);
//        writeLog_("../log/check_jb_permanent_invtext_", "FedEx-Mail versandt: \$mailResult='$mailResult'");

//      //********************************************************************************
//      // Neue Funktion 12.04.2019: (nicht mehr ab 01.12.2022)
//      // Jeden Ersten im Monat eine STB979550-Statistik-Mail
//        $sqlquery = 
//          "SELECT cs.cs_eid, ad.ad_zipcode, ad.ad_city, (CASE tr_commission_no WHEN '' THEN '(fehlt)' ELSE tr_commission_no END) AS tr_commission_no
//          FROM job AS jb, costcenter AS csc, customer AS cs, company AS cmp, tour AS tr, address AS ad
//          WHERE jb.jb_status = '2' AND (isnull( jb.jb_storno ) OR jb.jb_storno = '0' OR jb.jb_storno = '1' OR jb.jb_storno = '3')
//          AND jb.jb_ordertime >= '" . $date_from . "' AND jb.jb_ordertime <= '" . $date_to . "'
//          AND jb.csc_id_payer = csc.csc_id AND csc.cs_id = cs.cs_id AND cs.cmp_id = cmp.cmp_id AND cs.cs_eid = 'STB979550'
//          AND tr.jb_id = jb.jb_id AND tr.ad_id = ad.ad_id AND tr_sort > 1
//          ORDER BY cs.cs_eid, ad.ad_zipcode, ad.ad_city";
//        writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
//
//        $prev_cs_eid = "";
//        $prev_ad_zipcode = "";
//        $prev_ad_city = "";
//        $prev_cnt = 0;
//        $prev_tr_commission_nos = "";
//        $result = $db2->query($sqlquery);
//        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
//        $csv_txt = "Zahler;PLZ;Ort;Anzahl_Stopps;Kommissionsnummern\n";
//        while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
//          if ($prev_ad_zipcode != $row["ad_zipcode"] || $prev_ad_city != $row["ad_city"]) {
//            if ($prev_cs_eid != "")
//              $csv_txt .= $prev_cs_eid . ";" . $prev_ad_zipcode . ";" . $prev_ad_city . ";" . $prev_cnt . ";" . $prev_tr_commission_nos . "\n";
//            $prev_cs_eid = $row["cs_eid"];
//            $prev_ad_zipcode = $row["ad_zipcode"];
//            $prev_ad_city = $row["ad_city"];
//            $prev_cnt = 1;
//            $prev_tr_commission_nos = chr(160) . $row["tr_commission_no"];
//          } else {
//            $prev_tr_commission_nos .= " | " . $row["tr_commission_no"];
//            $prev_cnt++;
//          }
//        }
//        $csv_txt .= $prev_cs_eid . ";" . $prev_ad_zipcode . ";" . $prev_ad_city . ";" . $prev_cnt . ";" . $prev_tr_commission_nos . "\n";
//        $result->free();
//
//        $tmp_filename = "STB979550_" . substr($date_to, 0, 10) . ".csv";
//        $tmp_fullfilename = "../temp/" . $tmp_filename;
//        file_put_contents($tmp_fullfilename, $csv_txt);
//        $mailObj = new htmlMimeMail();
//        $mailObj->setFrom("auto-mailer@assecutor.de");
//        $mailObj->setBcc("support@assecutor.de");
//        $mailObj->setSubject("Monatsmail für STB979550 von " . $date_mail_from . " bis " . $date_mail_to);
//        $mailObj->setText("Im Anhang die Auswertungstabelle für alle erledigten Aufträge von STB979550 im letzten Monat.\n\n");
//        $mailObj->addAttachment($mailObj->getFile($tmp_fullfilename), $tmp_filename);
////        $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
//        $mailResult = $mailObj->send(array("verkauf-berlin@stadtbote.de"), 'smtp');
//        unlink($tmp_fullfilename);
//        writeLog_("../log/check_jb_permanent_invtext_", "BMW-Mail versandt: \$mailResult='$mailResult'");

//      //********************************************************************************
//      // Neue Funktion 24.01.2022:
//      // Jeden Ersten im Monat eine Statistik-Mail über erstmalige Kundenlogins
//        $date_from = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 1, date("Y"))) . " 00:00:00";
//        $date_mail_from = substr($date_from, 8, 2) . "." . substr($date_from, 5, 2) . "." . substr($date_from, 0, 4);
//        $date_from_before = date("Y-m-d", mktime(0, 0, 0, date("m") - 1, 1, date("Y") - 1)) . " 00:00:00";
//
//        $sqlquery = "
//          SELECT DISTINCT phoenix_log.log.usr_id FROM phoenix_log.log
//          WHERE log_createtime > '" . $date_from_before . "' AND log_createtime < '" . $date_from . "' AND logo_id IN (1, 25)";
//
//        writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
//        trace_execution_time_start();
//        $res = $db_conn->query($sqlquery);
//        writeLog_("../log/check_jb_permanent_invtext_", trace_execution_time_stop() . " (query time)");
//        if (DB::isError($res))
//          reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
//        $excluded_userids = "";
//        while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
//          $excluded_userids .= $row["usr_id"] . ",";
//        endwhile;
//        $res->free();
//
//        $sqlquery = "
//          SELECT *, COUNT(*) AS cnt FROM 
//          (
//            SELECT phoenix_log.log.usr_id, usr_account, usr_firstname, usr_name, usr_modify, cs_eid, cmp_comp, cmp_comp2, jb_id, log_createtime
//            FROM phoenix_log.log, phoenix.user, phoenix.employee, phoenix.costcenter, phoenix.customer, phoenix.company
//            WHERE logo_id IN (1, 25) AND usr_type = 2 AND customer.hq_id = 3 AND phoenix_log.log.usr_id = phoenix.user.usr_id AND log_createtime > '" . $date_from . "'
//            AND phoenix.employee.usr_id = phoenix.user.usr_id AND phoenix.employee.csc_id = phoenix.costcenter.csc_id AND phoenix.costcenter.cs_id = phoenix.customer.cs_id AND phoenix.customer.cmp_id = phoenix.company.cmp_id
//            AND NOT (phoenix.user.usr_id IN
//            (" .
////              SELECT DISTINCT phoenix_log.log.usr_id FROM phoenix_log.log
////              WHERE log_createtime > '" . $date_from_before . "' AND log_createtime < '" . $date_from . "' AND logo_id IN (1, 25)
//            substr($excluded_userids, 0, strlen($excluded_userids) - 1)
//            . "))
//            ORDER BY usr_id, log_createtime DESC
//          ) AS honk
//          GROUP BY usr_id
//          ORDER BY usr_id";
//
//        writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
//        trace_execution_time_start();
//        $res = $db_conn->query($sqlquery);
//        writeLog_("../log/check_jb_permanent_invtext_", trace_execution_time_stop() . " (query time)");
//
//        if (DB::isError($res))
//          reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
//        $csv_txt = "Nutzer-ID;Login;Vorname;Name;Letzte Änderung;Kundennummer;Firma;Firma2;Letzte Auftragsnummer;Letztes Erfassungsdatum;Anzahl Aufträge\n";
//        while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
//          $csv_txt .= $row["usr_id"] . ";" . $row["usr_account"] . ";" . $row["usr_firstname"] . ";" . $row["usr_name"] . ";" . $row["usr_modify"] . ";" . $row["cs_eid"] . ";" . $row["cmp_comp"] . ";" . $row["cmp_comp2"] . ";" . $row["jb_id"] . ";" . $row["log_createtime"] . ";" . $row["cnt"] . "\n";
//        endwhile;
//        $res->free();
//        $tmp_filename = "Neue_Nutzer_" . substr($date_from, 0, 10) . ".csv";
//        $tmp_fullfilename = "../temp/" . $tmp_filename;
//        file_put_contents($tmp_fullfilename, $csv_txt);
//        $mailObj = new htmlMimeMail();
//        $mailObj->setFrom("auto-mailer@assecutor.de");
//        $mailObj->setBcc("support@assecutor.de");
//        $mailObj->setSubject("Neue Nutzer seit dem " . $date_mail_from);
//        $mailObj->setText("Im Anhang die Auswertungstabelle für neue Nutzer im letzten Monat.\n\n");
//        $mailObj->addAttachment($mailObj->getFile($tmp_fullfilename), $tmp_filename);
////        $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
//        $mailResult = $mailObj->send(array("Jana.Langlotz@stadtbote.de"), 'smtp');
//        unlink($tmp_fullfilename);
//        writeLog_("../log/check_jb_permanent_invtext_", "Mail über neue Nutzer versandt: \$mailResult='$mailResult'");
      //********************************************************************************
      // Neue Funktion 13.09.2022:
      // Täglich eine Kontroll-Mail über geänderte Konserven/Daueraufträge
      elseif (date("H:i") == "03:00"):
        $sql_date = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));
//        $ctl_lists['1']['short'] = "HB";
//        $ctl_lists['1']['send'] = array("Rajko.Hill@stadtbote.de");
////        $ctl_lists['1']['send'] = array("ca@assecutor.de");
//        $ctl_lists['1']['cc'] = "Nadine.Nehm@stadtbote.de";
////        $ctl_lists['1']['cc'] = "annacker@gmx.net";
//        $ctl_lists['1']['categories'] = array('named_tours');
        $ctl_lists['2']['short'] = "HH";
        $ctl_lists['2']['send'] = array("hamburg@stadtbote.de");
//        $ctl_lists['2']['send'] = array("ca@assecutor.de");
        $ctl_lists['2']['cc'] = array();
        $ctl_lists['2']['categories'] = array('named_tours', 'permanent');
        $ctl_lists['3']['short'] = "B";
        $ctl_lists['3']['send'] = array("verkauf-berlin@stadtbote.de");
//        $ctl_lists['3']['send'] = array("ca@assecutor.de");
        $ctl_lists['3']['cc'] = array();
        $ctl_lists['3']['categories'] = array('named_tours');
        $ctl_lists['4']['short'] = "H";
        $ctl_lists['4']['send'] = array("alexandra.cordes@stadtbote.de");
//        $ctl_lists['4']['send'] = array("ca@assecutor.de");
        $ctl_lists['4']['cc'] = array();
//        $ctl_lists['4']['cc'] = "alexandra.hoefers@stadtbote.de";
        $ctl_lists['4']['categories'] = array('named_tours');
//        $ctl_lists['6']['short'] = "DD";
//        $ctl_lists['6']['send'] = array("steffen.schicht@stadtbote.de");
////        $ctl_lists['6']['send'] = array("ca@assecutor.de");
//        $ctl_lists['6']['cc'] = array();
//        $ctl_lists['6']['categories'] = array('named_tours');
//        $ctl_lists['9']['short'] = "M";
//        $ctl_lists['9']['send'] = array("marco.scherer@stadtbote.de");
////        $ctl_lists['9']['send'] = array("ca@assecutor.de");
//        $ctl_lists['9']['cc'] = "anja.dormann@stadtbote.de";
//        $ctl_lists['9']['categories'] = array('named_tours');
        $categories['named_tours']['clause'] = "NOT (jb_tourname IS NULL) AND jb_tourname != ''";
        $categories['named_tours']['name'] = "Konserven";
        $categories['permanent']['clause'] = "(jb_permanent IN (4, 5, 6, 7, 8, 9, 10, 11) OR (jb_permanent IN (1, 2, 3) AND jb_permanent2 != '0000000'))";
        $categories['permanent']['name'] = "Dauertouren";

        foreach ($ctl_lists as $ctl_hq_id => $ctl_details) {
          foreach($ctl_details['categories'] as $category) {
            $sqlquery = 
              "SELECT cs_eid AS Zahler, CONCAT(CHAR(160), cmp_comp) AS Name, CONCAT(CHAR(160), cmp_comp2) AS Name2, CONCAT(CHAR(160), csc_name) AS Kostenstelle, job.jb_id AS Auftragsnr," .
              " CONCAT(CHAR(160), jb_tourname) AS Tourenname, log_createtime, CONCAT(CHAR(160), usr_firstname, ' ', usr_name) AS Nutzer, logo_description" .
              " FROM costcenter, job, customer, company, phoenix_log.log, user" .
              " WHERE job.csc_id_payer = costcenter.csc_id AND costcenter.cs_id = customer.cs_id AND customer.cmp_id = company.cmp_id AND " . $categories[$category]['clause'] .
              " AND job.hq_id = " . $ctl_hq_id . " AND LEFT(jb_modify, 10) = '" . $sql_date . "' AND phoenix_log.log.jb_id = job.jb_id AND logo_id = 2 AND LEFT(log_createtime, 10) = '" . $sql_date . "'" .
              " AND phoenix_log.log.usr_id = user.usr_id" .
              " ORDER BY cs_eid, csc_name, jb_tourname, job.jb_id, log_createtime";
            writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
            $result = $db2->query($sqlquery);
            if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
            $csv_txt = "Zahler;Name;Name2;Kostenstelle;Auftragsnr;Tourenname;Änderungsdatum;Nutzer;Änderungstext\n";
            while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())) {
              $csv_txt .= '"' . $row["Zahler"] . '";"' . $row["Name"] . '";"' . $row["Name2"] . '";"' . $row["Kostenstelle"] . '";"' . $row["Auftragsnr"] . '";"' . $row["Tourenname"] . '";"' .
                $row["log_createtime"] . '";"' . $row["Nutzer"] . '";"' . $row["logo_description"] . '"' . "\n";
            }
            $result->free();
		    
            $tmp_filename = $categories[$category]['name'] . "-Updates_" . $ctl_details['short'] . "_" . $sql_date . ".csv";
            $tmp_fullfilename = "../temp/" . $tmp_filename;
            file_put_contents($tmp_fullfilename, $csv_txt);
            $mailObj = new htmlMimeMail();
            $mailObj->setFrom("auto-mailer@assecutor.de");
            if (count($ctl_details['cc']) > 0)
              $mailObj->setCc($ctl_details['cc']);
            $mailObj->setBcc("support@assecutor.de");
            $mailObj->setSubject("Geänderte " . $categories[$category]['name'] . "  vom " . date("d.m.Y", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y"))));
            $mailObj->setText("Im Anhang eine Liste der geänderten " . $categories[$category]['name'] . " vom gestrigen Tage.\n\n");
            $mailObj->addAttachment($mailObj->getFile($tmp_fullfilename), $tmp_filename);
//            $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
            $mailResult = $mailObj->send($ctl_details['send'], 'smtp');
            unlink($tmp_fullfilename);
            writeLog_("../log/check_jb_permanent_invtext_", $categories[$category]['name'] . "-Mail versandt: \$mailResult='$mailResult'");
          }
        }
      //********************************************************************************
      // Neue Funktion 04.11.2011: Überwachungs-Mail (Gütertaxi, EINE PRO TAG)    
      elseif (date("H:i") == "04:00"):
//        $last_execution = $db->getOne("SELECT ka_lastexecutiontime FROM keepalive WHERE ka_process = 'standing_orders'");
//        list($jt_y, $jt_m, $jt_d, $jt_h, $jt_i, $jt_s) = getValsFromDate($jb_finishtime_today);
//        list($le_y, $le_m, $le_d, $le_h, $le_i, $le_s) = getValsFromDate($last_execution);      
//        if (mktime($jt_h, $jt_i, $jt_s, $jt_m, $jt_d, $jt_y)
//          > mktime($le_h, $le_i, $le_s, $le_m, $le_d, $le_y)):        
          $sqlquery = "SELECT hq_id FROM headquarters WHERE hq_id IN (101,102,103,104,105,106,107,108,109,110,111,112)";
          $result = $db2->query($sqlquery);
          if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
          while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
            $hq_id = $row["hq_id"];
            $system_result = "";
            $cmd = "php ../tools/auto_trigger_check_metafield_hq.php acapella7890 $hq_id >> ../log/auto_trigger_check_metafield_hq.stdout+err 2>&1 &";
            $ausgabe = system($cmd, $system_result);
            writeLog_("../log/check_jb_permanent_invtext_", "Calling auto_trigger_check_metafield_hq.php $hq_id: ausgabe='$ausgabe'");
          endwhile;
          $result->free();
//        else:
//          writeLog_("../log/check_jb_permanent_invtext_", "auto_trigger_check_metafield_hq.php not called: '$jb_finishtime_today' <= '$last_execution'");
//        endif;
//    updateStmt("keepalive", "ka_process", "standing_orders", array("ka_lastexecutiontime", getDateTime("0")),"");

        // Neue Funktion 14.02.2022: Angaben in der Ko.-Nr. der Aufträge von STB981135 (vormals STB975894) (Tims Kanadische Backwaren) werden in Calculatorposten umgedingst
        // Ab dem 22.11.2023 kommt STB931592 (Zeit für Brot) hinzu

        foreach(array("STB981135", "STB931592") AS $cs_eid) {
          $sqlquery = "SELECT tour.jb_id, tr_id, tr_sort, tr_commission_no, tr_remark FROM job, tour, customer AS cs, costcenter AS csc WHERE LEFT (jb_ordertime, 10) = '" . date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y"))) . "'" .
            " AND cs_eid = '" . $cs_eid . "' AND cs.cs_id = csc.cs_id AND csc.csc_id = job.csc_id_payer AND job.jb_id = tour.jb_id ORDER BY tour.jb_id, tr_sort";
  //echo $sqlquery . "\n";
          writeLog_("../log/check_jb_permanent_invtext_", "[$sqlquery]");
          $result = $db->query($sqlquery);
          if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
          $error_text = "";
          $prev_jb_id = "";
          $post_jb_ids = array();
          $post_sqlqueries = array();
          while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
  //print_r($row);
            if ($prev_jb_id != $row["jb_id"]):
              $sqlquery = "DELETE FROM jobcalculator WHERE jb_id = " . $row["jb_id"];
  //echo $sqlquery . "\n";
              writeLog_("../log/check_jb_permanent_invtext_", "[$sqlquery]");
              $theResult = $db->query($sqlquery);
              if (DB::isError($theResult)): reportDie ("$PHP_SELF: '$sqlquery': " . $theResult->getMessage()); endif;
              $post_jb_ids[] = $row["jb_id"];
              $prev_jb_id = $row["jb_id"];
            endif;
            $tr_commission_no = trim($row["tr_commission_no"]);
            if ($tr_commission_no != "" && $row["tr_sort"] > 1):
              $tr_commission_no_corr = str_replace(".", " ", $tr_commission_no);
              $tr_commission_no_corr = str_replace("/", " ", $tr_commission_no_corr);
              while (!(strpos($tr_commission_no_corr, "  ") === false)):
                $tr_commission_no_corr = str_replace("  ", " ", $tr_commission_no_corr);
              endwhile;
              $tr_commission_no_arr = explode(" ", $tr_commission_no_corr);
  //print_r($tr_commission_no_arr);
              if (($cs_eid == "STB981135" && count($tr_commission_no_arr) == 2 && strval($tr_commission_no_arr[0]) === strval(intval($tr_commission_no_arr[0])) && strval($tr_commission_no_arr[1]) === strval(intval($tr_commission_no_arr[1])))
                || ($cs_eid == "STB931592" && count($tr_commission_no_arr) == 1 && strval($tr_commission_no_arr[0]) === strval(intval($tr_commission_no_arr[0])))):
                $srv_name = "Stopps";
                $srvt_name = "";
                if ($cs_eid == "STB981135") {
                  $srv_name = "Körbe";
                  $srvt_name = "geliefert";
                }
                $post_sqlqueries[] = "INSERT INTO jobcalculator (jb_id, tr_sort, jbc_amount, srv_name, srvt_name, jbc_price, jbc_totalprice) VALUES (" . $row["jb_id"] . ", " . $row["tr_sort"] . ", " . $tr_commission_no_arr[0] . ", '$srv_name', '$srvt_name', 0.0, 0.0)";
                if ($cs_eid == "STB981135") {
                  $srvt_name = "abgeholt";
                  $post_sqlqueries[] = "INSERT INTO jobcalculator (jb_id, tr_sort, jbc_amount, srv_name, srvt_name, jbc_price, jbc_totalprice) VALUES (" . $row["jb_id"] . ", " . $row["tr_sort"] . ", " . $tr_commission_no_arr[1] . ", '$srv_name', '$srvt_name', 0.0, 0.0)";
                }
                $second_val = "";
                if ($cs_eid == "STB981135") {
                  $second_val = $tr_commission_no_arr[1];
                }
                $sqlquery = "INSERT INTO jobcalculator (jb_id, tr_sort, jbc_amount, srv_name, srvt_name, jbc_price, jbc_totalprice) VALUES (" . $row["jb_id"] . ", " . $row["tr_sort"] . ", 0, $tr_commission_no_arr[0], '$second_val', 0.0, 0.0)";
  //echo $sqlquery . "\n";
                writeLog_("../log/check_jb_permanent_invtext_", "[$sqlquery]");
                $theResult = $db->query($sqlquery);
                if (DB::isError($theResult)): reportDie ("$PHP_SELF: '$sqlquery': " . $theResult->getMessage()); endif;
              else:
                $error_text .= $row["jb_id"] . "/" . $row["tr_sort"] . ": Ungültiger Wert \"" . $tr_commission_no . "\" im Kommissionsnummernfeld.\n";
              endif;
            elseif ($row["tr_sort"] > 1):
              $error_text .= $row["jb_id"] . "/" . $row["tr_sort"] . ": Kommissionsnummernfeld leer.\n";
            elseif ($tr_commission_no != ""):
              $error_text .= $row["jb_id"] . "/" . $row["tr_sort"] . ": Kommissionsnummernfeld in 1. Station muss leer sein.\n";
            endif;
            $tr_remark = trim($row["tr_remark"]);
            if (!(strpos($tr_remark, "[*") === false)):
              $tr_commission_no_ori = substr($tr_remark, strpos($tr_remark, "[*") + 2, strpos($tr_remark, "*]") - strpos($tr_remark, "[*") - 2);
              $tr_remark = str_replace($tr_commission_no_ori, trim($tr_commission_no_ori . " " . $tr_commission_no), $tr_remark);
              $sqlquery = "UPDATE tour SET tr_commission_no = '" . $tr_commission_no_ori . "', tr_remark = '" . $tr_remark . "' WHERE tr_id = " . $row["tr_id"];
  //echo $sqlquery . "\n";
              writeLog_("../log/check_jb_permanent_invtext_", "[$sqlquery]");
              $theResult = $db->query($sqlquery);
            endif;    
          endwhile;
  
          if ($error_text != ""):
            $mailObj = new htmlMimeMail();
            $mailObj->setFrom("auto-mailer@assecutor.de");
  //          $mailObj->setBcc("support@assecutor.de");
            $mailObj->setSubject("Fehler in den Aufträgen von " . $cs_eid);
            $mailObj->setText($error_text);
            $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
          endif;
  
          if ($prev_jb_id != ""):
            $system_result = "";
            $cmd = "php ../tools/cron_export_zfbg.php acapella7890 " . date("Y m d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y"))) . " >> ../log/check_jb_permanent_invtext_" . date("Ym") . ".log 2>&1";
            if ($cs_eid == "STB981135") {
              $cmd = "php ../tools/cron_export_tkbg.php acapella7890 " . date("Y m d", mktime(0, 0, 0, date("m"), date("d") - 1, date("Y"))) . " >> ../log/check_jb_permanent_invtext_" . date("Ym") . ".log 2>&1";
            }
            writeLog_("../log/check_jb_permanent_invtext_", $cmd);
//  echo $cmd . "\n";
            $ausgabe = system($cmd, $system_result);
            foreach ($post_jb_ids as $jb_id) {
              $sqlquery = "DELETE FROM jobcalculator WHERE jb_id = " . $jb_id;
  //echo $sqlquery . "\n";
              writeLog_("../log/check_jb_permanent_invtext_", "[$sqlquery]");
              $theResult = $db->query($sqlquery);
              if (DB::isError($theResult)): reportDie ("$PHP_SELF: '$sqlquery': " . $theResult->getMessage()); endif;
            }
            foreach ($post_sqlqueries as $sqlquery) {
  //echo $sqlquery . "\n";
              writeLog_("../log/check_jb_permanent_invtext_", "[$sqlquery]");
              $theResult = $db->query($sqlquery);
              if (DB::isError($theResult)): reportDie ("$PHP_SELF: '$sqlquery': " . $theResult->getMessage()); endif;
            }
          else:
            writeLog_("../log/check_jb_permanent_invtext_", "no jobs were processed, no need to call cron for \$cs_eid = " . $cs_eid);
          endif;
        }
        // Am dritten Werktag
        if (is3rdOr4thWorkDay(3)):
          $system_result = "";
          $cmd = "php ../tools/cron_sustainability_customer_report.php acapella7890 >> ../log/cron_sustainability_customer_report.stdout+err 2>&1 &";
          $ausgabe = system($cmd, $system_result);
          writeLog_("../log/check_jb_permanent_invtext_", "cron_sustainability_customer_report.php: ausgabe='$ausgabe'");
        endif;
//      elseif (date("H:i") == "16:45" || date("H:i") == "16:46" || date("H:i") == "16:47" || date("H:i") == "16:48" || date("H:i") == "16:49"):
        // Einmal bitte wöchentlich die Exportierten, die im Zeitraum von Dienstag bis Montag erledigt wurden. Der Bericht erstellt in der Nacht auf Dienstag
        if (date("w") == "2"): // Dienstag
          $system_result = "";
          $cmd = "php ../tools/statistic_special_cartage.php acapella7890 \"\" \""
            . date("Y-m-d H:i:s", mktime(0, 0, 0, date("n"), date("j") - 7, date("Y"))) . "\" \"" . date("Y-m-d H:i:s", mktime(23, 59, 59, date("n"), date("j") - 1, date("Y"))) . "\""
            . " >> ../log/statistic_special_cartage.stdout+err 2>&1 &";
          $ausgabe = system($cmd, $system_result);
          writeLog_("../log/check_jb_permanent_invtext_", $cmd);
        endif;
        // Einmal Exportierte, die erledigt worden vom 01.-15., erstellt in einem Bericht in der Nacht vom 20. auf den 21., sowie vom 16. - Ultimo, erstellt in einem Bericht in der Nacht vom 06. auf den 07. des Folgemonats.
        if (date("j") == 21): // Am 21. des Monats
          $system_result = "";
          $cmd = "php ../tools/statistic_special_cartage.php acapella7890 \"\" \""
            . date("Y-m-d H:i:s", mktime(0, 0, 0, date("n"), 1, date("Y"))) . "\" \"" . date("Y-m-d H:i:s", mktime(23, 59, 59, date("n"), 15, date("Y"))) . "\""
            . " >> ../log/statistic_special_cartage.stdout+err 2>&1 &";
          $ausgabe = system($cmd, $system_result);
          writeLog_("../log/check_jb_permanent_invtext_", $cmd);
	    endif;
        if (date("j") == 7): // Am 7. des Monats
          $system_result = "";
          $cmd = "php ../tools/statistic_special_cartage.php acapella7890 \"\" \""
            . date("Y-m-d H:i:s", mktime(0, 0, 0, date("n") - 1, 16, date("Y"))) . "\" \"" . date("Y-m-d H:i:s", mktime(23, 59, 59, date("n"), 0, date("Y"))). "\""
            . " >> ../log/statistic_special_cartage.stdout+err 2>&1 &";
          $ausgabe = system($cmd, $system_result);
          writeLog_("../log/check_jb_permanent_invtext_", $cmd);
        endif;
        // ab 05.12.2024: Neue Mails am 4. Werktag des Monats
        if (is3rdOr4thWorkDay(4)): // Am 4. Werktag des Monats
          foreach (array("1","2","3","4","5","6","7","8","11") as $hq_id) {
            $system_result = "";
            $cmd = "cd /srv/htdocs/stadtbote/tools/; php auto_trigger_sales_customer_report.php acapella7890 hq " . $hq_id . " >> ../log/auto_trigger_sales_customer_report.stdout+err 2>&1 &";
            $ausgabe = system($cmd, $system_result);
            writeLog_("../log/check_jb_permanent_invtext_", $cmd);
          }
	endif;
      elseif (date("H:i") == "07:02" /* && $last_exec_loc != date("Y-m-d") */ ):
        $sqlquery = "SELECT hq_id FROM headquarters WHERE hq_id IN (5)";
        $result = $db2->query($sqlquery);
        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
        while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
          $hq_id = $row["hq_id"];
          $system_result = "";
          $cmd = "php ../tools/auto_trigger_locating_STF.php acapella7890 5 65824 >> ../log/auto_trigger_locating_STF.stdout+err 2>&1 &";
          $ausgabe = system($cmd, $system_result);
//          $last_exec_loc = date("Y-m-d");
          writeLog_("../log/check_jb_permanent_invtext_", "auto_trigger_locating_STF.php: ausgabe='$ausgabe', hq_id = $hq_id");
        endwhile;
        $result->free();

//        $sqlquery = "SELECT jb_id, jb_markup FROM job, costcenter WHERE job.csc_id_payer = costcenter.csc_id AND cs_id = 306066 AND jb_export_time IS NULL and (jb_storno IS NULL OR (jb_storno != 2 and jb_storno != 4)) AND jb_markup > 0";
//        $result = $db2->query($sqlquery);
//        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
//         while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
//          $jb_id_tmp = $row["jb_id"];
//          $mailObj = new htmlMimeMail();
//          $mailObj->setFrom("support@assecutor.de");
////          $mailObj->setBcc("ca@assecutor.de");
//          $mailObj->setSubject("Auftrag Nr. " . $row["jb_id"] . " hat einen TZ von " . $row["jb_markup"] . "%");
//          $mailObj->setText("Kunde STB918648 hat eigentlich einen TZ von 0%");
//          $mailResult = $mailObj->send($recipients, 'smtp');
//          writeLog_("../log/check_jb_permanent_invtext_", "Mail zu Auftrag Nr. " . $row["jb_id"] . " wurde versandt, result = " . $mailResult);
//        endwhile;
//        $result->free();
      elseif (date("H:i") == "17:00"):
        if (mktime(0, 0, 0, date("m"), date("d"), date("Y")) < mktime(0, 0, 0, 9, 11, 2025)
          && floor(date("U") / 3600 / 24) % 2 == 1):
          $system_result = "";
          $cmd = "php ../sysadmin/mf_msg2all.php >> ../log/mf_msg2all.stdout+err 2>&1 &";
          $ausgabe = system($cmd, $system_result);
          writeLog_("../log/check_jb_permanent_invtext_", "mf_msg2all: ausgabe='$ausgabe'");
        endif;
      elseif (date("H:i") == "19:30"):
        $system_result = "";
        $cmd = "cd /srv/www/sb/tools; php auto_export_PDF_STB_H_SINGLE.php acapella7890 824381 >> ../log/auto_export_PDF_STB_H_SINGLE.stdout+err 2>&1 &";
        $ausgabe = system($cmd, $system_result);
        writeLog_("../log/check_jb_permanent_invtext_", "auto_export_PDF_STB_H_SINGLE.php: ausgabe='$ausgabe', hq_id = $hq_id");
      elseif (
        date("H:i") == "05:00" ||
        date("H:i") == "05:30" ||
        date("H:i") == "06:00" ||
        date("H:i") == "06:30" ||
        date("H:i") == "07:00" ||
        date("H:i") == "07:30" ||
        date("H:i") == "08:00" ||
        date("H:i") == "08:30" ||
        date("H:i") == "09:00" ||
        date("H:i") == "09:30" ||
        date("H:i") == "10:00" ||
        date("H:i") == "10:30" ||
        date("H:i") == "11:00" ||
        date("H:i") == "11:30" ||
        date("H:i") == "12:00" ||
        date("H:i") == "12:30" ||
        date("H:i") == "13:00" ||
        date("H:i") == "13:30" ||
        date("H:i") == "14:00" ||
        date("H:i") == "14:30" ||
        date("H:i") == "15:00" ||
        date("H:i") == "15:30" ||
        date("H:i") == "16:00" ||
        date("H:i") == "16:30" ||
        date("H:i") == "17:01" ||
        date("H:i") == "17:30" ||
        date("H:i") == "18:00" ||
        date("H:i") == "18:30" ||
        date("H:i") == "19:00" ||
        date("H:i") == "19:31" ||
        date("H:i") == "20:00" ||
        date("H:i") == "20:30" ||
        date("H:i") == "21:00" ||
        date("H:i") == "21:30"):

echo "[" . date("Y-m-d H:i:s") . "] checking for jobs to correct jb_finishtime (memory_get_usage() = " . memory_get_usage() . ")\n";
        //********************************************************************************
        // Neue Funktion 03.01.2017: Aufträge mit "0000-00-00 00:00:00"-Zeiten reparieren
//        $sqlquery =
//          "SELECT" .
//          "  max_tr_modify AS Erledigung_korrekt, jb_id AS Auftragsnr, jb_finishtime AS Erledigung_kaputt" .
//          " FROM (" .
//          "  SELECT job.jb_id, cr_sid, jb_totalprice, cs_eid, cmp_comp, jb_ordertime, jb_finishtime, MAX(tr_modify) AS max_tr_modify, jb_modify" .
//          "  FROM tour, job, costcenter, customer, company" .
//          "  WHERE (jb_export_time IS NULL AND jb_status = 2 AND jb_storno IS NULL AND jb_incomplete = 0 AND jb_totalprice > 0)" .
//          "    AND tour.jb_id = job.jb_id AND costcenter.csc_id = job.csc_id_payer AND costcenter.cs_id = customer.cs_id AND customer.cmp_id = company.cmp_id" .
//          "    AND jb_modify > '2016-12-01'" .
//          "  GROUP BY jb_id ORDER BY max_tr_modify" .
//          ") AS honk" .
//         " WHERE" .
//         "  TIMESTAMPDIFF(WEEK, jb_ordertime,jb_finishtime) > 50" .
//          "  OR TIMESTAMPDIFF(WEEK, jb_finishtime,jb_ordertime) > 50" .
//          "  OR TIMESTAMPDIFF(WEEK, jb_finishtime, jb_ordertime) IS NULL";
        $sqlquery =
          "SELECT job.jb_id, jb_finishtime, tr_finishtime, jb_id_parent FROM tour, job WHERE" .
          " (jb_export_time IS NULL AND jb_status = 2 AND jb_storno IS NULL " /* AND jb_incomplete = 0 */ . " AND (jb_totalprice > 0 OR" .
          " LEFT (jb_ordertime, 10) = '" . date("Y-m-d") . "')) AND" . // because of automatic finish-mails also change jobs with totalprice = 0 if they are from today
          " tour.jb_id = job.jb_id AND jb_finishtime = '0000-00-00 00:00:00'" .
          " AND jb_modify > '2016-12-01'" .
          " ORDER BY jb_id, tr_finishtime DESC";
        writeLog_("../log/check_jb_permanent_invtext_", "Checking for jobs to correct jb_finishtime [$sqlquery]");
        $res = $db_conn->query($sqlquery);
        if (DB::isError($res))
          reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
        $jb_id_prev = 0;
        while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
          if ($jb_id_prev != $row["jb_id"]):
            $jb_id_sql = $row["jb_id"];
            $correct_finishtime = $row["tr_finishtime"];
            if ($row["jb_id_parent"] == -1):
              $jb_id_child = "";
              $jb_id_child = $db->getOne("SELECT jb_id FROM job WHERE jb_id_parent = " . $row["jb_id"] . " AND jb_finishtime = '0000-00-00 00:00:00'");
              $jb_id_child2 = "";
              if ($jb_id_child != ""):
                $jb_id_sql .= " OR jb_id = " . $jb_id_child;
                $jb_id_child2 = $db->getOne("SELECT jb_id FROM job WHERE jb_id_parent = " . $jb_id_child . " AND jb_finishtime = '0000-00-00 00:00:00'");
                if ($jb_id_child2 != ""):
                  $jb_id_sql .= " OR jb_id = " . $jb_id_child2;
                endif;
              endif;
            elseif ($row["jb_id_parent"] > 0):
              $correct_finishtime = $db->getOne("SELECT jb_finishtime FROM job WHERE jb_id = " . $row["jb_id_parent"]);
            endif;
            writeLog_("../log/check_jb_permanent_invtext_", "Correcting jb_finishtime = '" . $row["jb_finishtime"] . "': " .
              "[UPDATE job SET jb_finishtime = '" . $correct_finishtime . "', jb_modify = jb_modify WHERE jb_id = " . $jb_id_sql . "]"
            );
            $db->query("UPDATE job SET jb_finishtime = '" . $correct_finishtime . "', jb_modify = jb_modify WHERE jb_id = " . $jb_id_sql);
            $jb_id_prev = $row["jb_id"];
          endif;
        endwhile;
        $res->free();

//echo "[" . date("Y-m-d H:i:s") . "] checking for rogue cr_sids (memory_get_usage() = " . memory_get_usage() . ")\n";
//        // Neue Funktion 02.09.2024: Dubletten-Aufräumung (../tools/deleteDuplicateCr_sids.php) ersetzt durch Versand einer Mail
//        // 26.08.2025: Das Übel wird jetzt an der Wurzel beseitigt, so dass es jetzt gar nicht erst entstehen kann
////        $sqlquery = "SELECT cr_sid FROM courier WHERE cr_sid != '' GROUP BY cr_sid HAVING COUNT(*) > 1";
//        $sqlquery = "SELECT courier.cr_id, cr_sid FROM courier LEFT JOIN couriervehicle ON courier.cr_id = couriervehicle.cr_id WHERE cr_sid != '' AND couriervehicle.cr_id IS NULL";
//        writeLog_("../log/check_jb_permanent_invtext_", "checking for rogue cr_sids: \$sqlquery = [" . $sqlquery . "]");
//        $result = $db2->query($sqlquery);
//        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
//        $cr_sids = "";
//        $cr_ids = "";
//        while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
//          $cr_sids .= "'" . trim($row['cr_sid']) . "' (cr_id=" . $row['cr_id'] . "),";
//          $cr_ids .= $row['cr_id'] . ",";
////          $cr_ids .= $db->getOne("SELECT courier.cr_id FROM courier LEFT JOIN couriervehicle ON courier.cr_id = couriervehicle.cr_id WHERE cr_sid = '" . $row['cr_sid'] ."' AND  couriervehicle.cr_id IS NULL") . "',";
//        endwhile;
//        $res->free();
//        if ($cr_ids != ""):
//          $cr_sids = substr($cr_sids, 0, -1);
//          $cr_ids = substr($cr_ids, 0, -1);
////          echo "duplicate cr_sids: " . $cr_sids . "\n";
//          writeLog_("../log/check_jb_permanent_invtext_", "cr_sids from courier with no entry in couriervehicle: " . $cr_sids);
//          writeLog_("../log/check_jb_permanent_invtext_", "cr_ids where the cr_sid is to be deleted: " . $cr_ids);
//          $sqlquery = "UPDATE courier SET cr_sid = '' WHERE cr_id IN (" . $cr_ids . ")";
//          writeLog_("../log/check_jb_permanent_invtext_", "Deleting rogue cr_sids: [" . $sqlquery . "]");
//          $db->query($sqlquery);
//        //  $sqlquery = "UPDATE courier SET cr_sid = '' WHERE cr_mobile_pda = '' AND cr_sid IN (" . $cr_sids . ")";
//        //  mysql_query($sqlquery) or die ($sqlquery);
//        //  echo mysql_affected_rows() . " duplicate cr_sids deleted\n";
//          $mailObj = new htmlMimeMail();
//          $mailObj->setFrom("support@assecutor.de");
//          $mailObj->setSubject("Potentielle Kurier-Dubletten entdeckt");
//          $mailObj->setText("Folgende SIDs sind in courier, aber nicht in courier_vehicle: " . $cr_sids . ", das Feld cr_sid wurde in folgenden cr_ids gelöscht: " . $cr_ids . ".\n" . "UPDATE courier SET cr_sid = '' WHERE cr_id IN (" . $cr_ids . ")" . "\n");
//          $mailResult = $mailObj->send(array("admin@assecutor.de"), 'smtp');
////          $mailResult = $mailObj->send(array("ca@assecutor.de"), 'smtp');
//        endif;
      elseif (date("H:i") == "22:00"):
        // Und noch einer...
//        // alle Vorgänger-Daueraufträge von HTM18156 bis zum 01.06.2013 zurück holen
//        $sqlquery = "SELECT jb_id, jb_id_copy_permanent FROM job, customer AS cs, costcenter AS csc WHERE jb_ordertime > " .
//          "'2013-05-16 00:00:00' AND NOT (jb_id_copy_permanent IS NULL) AND cs_eid = 'HTM18156' AND cs.cs_id = csc.cs_id AND csc.csc_id = job.csc_id_payer";
//        $res = $db->query($sqlquery);
//        if (DB::isError($res)) reportDie ("$PHP_SELF: '$sqlquery': " . $res->getMessage());   
//        $permanent_jobs = array();
//        while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
//          $permanent_jobs[$row['jb_id_copy_permanent']] = array($row['jb_id']);
//        endwhile;
//        $res->free();
        // Alle unerledigten Aufträge von HTM18156 des heutigen Tages ab 22:00 Uhr auf erledigt setzen ("Schablonen-Daueraufträge")
        $sqlquery = "SELECT jb_id, cr_id, job.hq_id, jb_ordertime, jb_tourname FROM job, customer AS cs, costcenter AS csc WHERE LEFT (jb_ordertime, 10) = '" . date("Y-m-d") . "' AND cs_eid = 'HTM18156' AND cs.cs_id = csc.cs_id AND csc.csc_id = job.csc_id_payer AND jb_status != 2";
        writeLog_("../log/check_jb_permanent_standing_", "[$sqlquery]");
        $result = $db2->query($sqlquery);
        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
        $cmd_exec_limit = date("Y-m-d H:i:s", mktime(date("H"), date("i"), date("s"), date("m"), date("d"), date("Y") + 1));
        while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
//print_r($row);
          $jb_finishtime_man = date("Y-m-d H:i:s");
          $sqlquery = "UPDATE job SET jb_status = 2, jb_finishtime = '$jb_finishtime_man' WHERE jb_id = '" . $row["jb_id"] . "'";
          writeLog_("../log/check_jb_permanent_standing_", "[$sqlquery]");
          $theResult = $db->query($sqlquery);
          if (DB::isError($theResult)) reportDie ("$PHP_SELF: '$sqlquery': " . $theResult->getMessage());
          $sqlquery = "INSERT INTO phoenix_pda.commandexec (cr_id, hq_id, cmd_command, cmde_exec_time, cmde_exec_timelimit, cmde_mode, cmde_param) VALUES ('" . $row["cr_id"] . "', '" . $row["hq_id"] . "', '3', '$now', '$cmd_exec_limit', '1', '" . $row["jb_id"] . "')";
          writeLog_("../log/check_jb_permanent_standing_", "[$sqlquery]");
          $theResult = $db->query($sqlquery);
          if (DB::isError($theResult)) reportDie ("$PHP_SELF: '$sqlquery': " . $theResult->getMessage());
//          // finde den ältesten Vorgänger
//          $jb_id_prev = $row["jb_id"];
//          while(array_key_exists($jb_id_prev, $permanent_jobs)):           // solange bis der Vorgänger selbst keinen weiteren Vorgänger hat
//          	$jb_id_follow = $jb_id_prev;
//            $jb_id_prev = $permanent_jobs[$jb_id_prev][0];                   // jb_id des Vorgängers
//          endwhile;
//          // den ältesten Vorgänger fortsetzen
////echo "copy_job($jb_id_prev, " . $jb_finishtime_man . ", " . $row["hq_id"] . ", " . $row ["jb_ordertime"] . ")\n";
//          copy_job($jb_id_prev, $jb_finishtime_man, $row["hq_id"], $row ["jb_ordertime"]);
//          // Kette wieder reparieren
//          $jb_id_new = getFieldValueFromId("job", "jb_id", $jb_id_prev, "jb_id_copy_permanent");
//          updateStmt("job", "jb_id", $row["jb_id"], array("jb_id_copy_permanent", $jb_id_new, "jb_tourname", NULL));
//          writeLog_("../log/check_jb_permanent_standing_", $row["jb_id"] . ": " . "jb_id_copy_permanent=$jb_id_new, jb_tourname=NULL");
//          updateStmt("job", "jb_id", $jb_id_new, array("jb_tourname", $row["jb_tourname"]));
//          writeLog_("../log/check_jb_permanent_standing_", $jb_id_new . ": " . "jb_tourname='" . $row["jb_tourname"] . "'");
//          updateStmt("job", "jb_id", $jb_id_prev, array("jb_id_copy_permanent", $jb_id_follow));
//          writeLog_("../log/check_jb_permanent_standing_", $jb_id_prev . ": " . "jb_id_copy_permanent=$jb_id_follow");
        endwhile;
        $result->free();
      elseif (date("H:i") == "23:45"):
        //********************************************************************************
        // 02.08.2020: Kurierer in Quarantäne müssen nach 14 Tagen rehabilitiert werden

        $cr_quarantinePar = getParameterValue("0", "CR_QUARANTINE", "0");
        $cr_quarantineArrArr = array_filter(explode(";", $cr_quarantinePar));
        $cr_quarantines = array();
        foreach($cr_quarantineArrArr AS $cr_quarantineArr) {
          $cr_quarantines[] = array_filter(explode(",", $cr_quarantineArr));
          $cr_quarantines[count($cr_quarantines) - 1][2] = 0;
        }
        writeLog_("../log/check_jb_permanent_invtext_", "Quarantine control: \$cr_quarantinePar = '" . $cr_quarantinePar . "'");
      
        $cr_group_clause = "";
        $sqlquery = "SELECT grp_id FROM groups WHERE grp_name = 'Quarantäne'";
        $result = $db2->query($sqlquery);
        if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
        while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
          $sqlquery = "SELECT cr_id, cr_group FROM courier WHERE cr_group LIKE '%," . $row["grp_id"] . ",%'";
          $theResult = $db2->query($sqlquery);
          if (DB::isError($theResult)) reportDie ("$PHP_SELF: '$sqlquery': " . $theResult->getMessage());
          while ($theRow = ($phpVersion >= "8.0" ? $theResult->fetch_assoc() : $theResult->fetchRow())):
            $found = false;
            for ($i = 0; $i < count($cr_quarantines); $i++) {
              if ($theRow["cr_id"] == $cr_quarantines[$i][0]) {
                $found = true;
                if (strtotime($cr_quarantines[$i][1]) + (14 * 24 * 60 * 60) < time()) {
                  $theRow["cr_group"] = str_replace($row["grp_id"] . ',' , '', $theRow["cr_group"]);
                  if ($theRow["cr_group"] == ',')
                    $theRow["cr_group"] = '';
                  $db->query("UPDATE courier SET cr_group = '" . $theRow["cr_group"] . "' WHERE cr_id = " . $theRow["cr_id"]);
                  array_splice($cr_quarantines, $i, 1);
                  writeLog_("../log/check_jb_permanent_invtext_", "Quarantine ended: \$cr_id = " . $theRow["cr_id"] . " (" . $cr_quarantines[$i][1] . ")");
                } else {
                  $cr_quarantines[$i][2] = 1;
                }
              }
            }
            if (!$found) {
              $cr_quarantines[] = array($theRow["cr_id"], date("Y-m-d"), 1);
              writeLog_("../log/check_jb_permanent_invtext_", "Quarantine started: \$cr_id = " . $theRow["cr_id"] . " (" . date("Y-m-d") . ")");
            }
          endwhile;
          $theResult->free();
        endwhile;
        $result->free();
        
        $cr_quarantinePar = "";
        foreach($cr_quarantines AS $cr_quarantine) {
          if ($cr_quarantine[2] == 1) {
            if ($cr_quarantinePar != "")
              $cr_quarantinePar .= ";";
            $cr_quarantinePar .= $cr_quarantine[0] . "," . $cr_quarantine[1];
          } else {
            writeLog_("../log/check_jb_permanent_invtext_", "Quarantine vanished: \$cr_id = " . $cr_quarantine[0] . " (" . $cr_quarantine[1] . ")");
          }
        }
        $db->query("UPDATE parameter SET par_value = '" . $cr_quarantinePar . "' WHERE par_key = 'CR_QUARANTINE'");
        //********************************************************************************

        writeLog_("../log/check_jb_permanent_invtext_", "exiting...");
        exit();
      endif;

echo "[" . date("Y-m-d H:i:s") . "] sleeping (memory_get_usage() = " . memory_get_usage() . ")\n";
      $sleep_time = 59 - date("s") - 1;
writeLog_("../log/check_jb_permanent_invtext_", "sleeping " . ($i + 1) . "/5");
      sleep($sleep_time);
writeLog_("../log/check_jb_permanent_invtext_", "waking up");
      while (date("s") != "00") {
writeLog_("../log/check_jb_permanent_invtext_", "date(\"s\") = " . date("s"));
        // Warte 0.25 Sekunden
        usleep(250000);
      }
writeLog_("../log/check_jb_permanent_invtext_", "continuing");
    endfor;

    //********************************************************************************
    // Dauerauftragsfortsetzung (ALLE 500 SEC)
echo "[" . date("Y-m-d H:i:s") . "] querying for finished jobs to be continued (memory_get_usage() = " . memory_get_usage() . ")\n";
    $today_date = $today['year'] . "-" . sprintf("%02d", $today['mon']) . "-" . sprintf("%02d", $today['mday']);

    // JB_ID nicht angegeben -> kein expliziter Aufruf
    // Alle Daueraufträge finden, die erledigt sind
//    $sqlquery = "SELECT job.jb_id, job.jb_finishtime, job.hq_id FROM job FORCE INDEX (jb_storno_2) WHERE ((jb_storno != 3 AND jb_storno != 4) OR jb_storno IS NULL) " .
//      " AND job.jb_status = 2 AND jb_permanent IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) AND (jb_id_copy_permanent IS NULL OR jb_id_copy_permanent = 0) " .
//      " AND (job.jp_permenddat >= '$today_date" . " 00:00:00' OR job.jp_permenddat IS NULL OR job.jp_permenddat = '0000-00-00 00:00:00')" .
//      " ORDER BY job.jb_id";

    $no_continuation_list_sql = implode(",", $no_continuation_list);
    if ($no_continuation_list_sql != "")
      $no_continuation_list_sql = " AND jb_id NOT IN (" . $no_continuation_list_sql . ")";
    $sqlquery = "(SELECT job.jb_id, job.jb_finishtime, job.hq_id FROM job WHERE (jb_storno != 3 AND jb_storno != 4)" .
      " AND job.jb_status = 2 AND jb_permanent IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) AND (jb_id_copy_permanent IS NULL OR jb_id_copy_permanent = 0)" .
      " AND (job.jp_permenddat >= '$today_date" . " 00:00:00' OR job.jp_permenddat IS NULL)$no_continuation_list_sql" .
      " AND jb_finishtime > '" . date("Y-m-d H:i:s", mktime(0, 0, 0, date("m") - 2, date("d"), date("Y"))) . "')" .
      " UNION " .
      "(SELECT job.jb_id, job.jb_finishtime, job.hq_id FROM job WHERE jb_storno IS NULL" .
      " AND job.jb_status = 2 AND jb_permanent IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) AND (jb_id_copy_permanent IS NULL OR jb_id_copy_permanent = 0)" .
      " AND (job.jp_permenddat >= '$today_date" . " 00:00:00' OR job.jp_permenddat IS NULL)$no_continuation_list_sql" .
      " AND jb_finishtime > '" . date("Y-m-d H:i:s", mktime(0, 0, 0, date("m") - 2, date("d"), date("Y"))) . "')" .
      " ORDER BY jb_id";
    writeLog_("../log/check_jb_permanent_standing_", "Querying for finished jobs to be continued [$sqlquery]");
    trace_execution_time_start();
    $res = $db_conn->query($sqlquery);
    writeLog_("../log/check_jb_permanent_standing_", trace_execution_time_stop() . " (query time)");

    if (DB::isError($res))
      reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
    while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
      writeLog_("../log/check_jb_permanent_standing_", $row["jb_id"] . " is to be continued");
      if ($row["jb_id"] != ""):
//      writeCmd($row["jb_id"]);
//      $jobList = array();
        $hq_id = $row["hq_id"];
        copy_job($row["jb_id"], $row["jb_finishtime"], $row["hq_id"]);
    // Aufruf des Batch
//      $ausgabe = system("..\jobs\check_jb_permanent.cmd " . $row["jb_id"] . " " . $row["jb_finishtime"]  . " >>..\log\check_jb_permanent.stdout", $result);
//      echo "Result:", $result;
//      echo "Ausgabe:", $ausgabe;
      endif;
      // Set execution time for keepalive (in order to avoid being called anew while still running (making invoice text can take long time!)
//      updateStmt("keepalive", "ka_process", "standing_orders", array("ka_lastexecutiontime", getDateTime("0")),"");
    endwhile;
    $res->free();
    writeLog_("../log/check_jb_permanent_standing_", "no more jobs to be continued");

    //********************************************************************************
    // Nachfolgendes NUR EINMAL AM TAG    
    
//    if ($jb_finishtime_today > $jb_finishtime_start && $jb_finishtime_today < $now):
    
//    endif;

//    updateStmt("keepalive", "ka_process", "standing_orders", array("ka_lastexecutiontime", getDateTime("0")),"");
    
    //********************************************************************************
    // NACHFOLGENDES WIEDER ALLE 5 MIN.
    
    // Noch eine weitere Funktion:
    // Javascript-Arrays mit selten veränderlichen Variablen werden in eine extra .js-Datei geschrieben, die
    // mind. einmal am Tag upgedatet werden sollte

//    $sqlquery = "SELECT hq_id FROM headquarters";
//writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
//    $result = $db2->query($sqlquery);
//    if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
//    while ($row = ($phpVersion >= "8.0" ? $result->fetch_assoc() : $result->fetchRow())):
//      $hq_id = $row["hq_id"];
//echo "[" . date("Y-m-d H:i:s") . "] updating job_options_" . $hq_id . ".js\n";
//writeLog_("../log/check_jb_permanent_invtext_", "include(\"../jobs/job_options.js.inc.php\"), \$hq_id = " . $hq_id);
//      include("../jobs/job_options.js.inc.php");
//    endwhile;
//    $result->free();

    $system_result = "";
    $cmd = "php ../tools/mk_job_options.js.inc.php >> ../log/mk_job_options.js.inc.stdout+err 2>&1 &";
    writeLog_("../log/check_jb_permanent_invtext_", "Calling mk_job_options.js.inc.php");
    $ausgabe = system($cmd, $system_result);

echo "[" . date("Y-m-d H:i:s") . "] checking jb_sales_tax_rate (memory_get_usage() = " . memory_get_usage() . ")\n";
    // Und noch einer: Wenn aus einer alten Konserve Auftrag erzeugt wird, dann manchmal noch mit 16%
    // Deshalb hier checken und auf 16% setzen
    $sqlquery = "SELECT jb_id FROM job WHERE jb_sales_tax_rate = 16 AND jb_finishtime > '2007-01-01 00:00:00' AND jb_export_time IS NULL";
writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
    $theResult = $db2->query($sqlquery);
    if (DB::isError($theResult)) reportDie ("$PHP_SELF: '$sqlquery': " . $theResult->getMessage());
    while ($row = ($phpVersion >= "8.0" ? $theResult->fetch_assoc() : $theResult->fetchRow())):
      $sqlquery = "UPDATE job SET jb_sales_tax_rate = 19 WHERE jb_id = '" . $row["jb_id"] . "'";
      $result = $db->query($sqlquery);
      if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
    endwhile;
    $theResult->free();

echo "[" . date("Y-m-d H:i:s") . "] updating cr_sid (memory_get_usage() = " . memory_get_usage() . ")\n";
    // Und noch einer...
    // ... muss eigentlich im Code gecheckt werden, aber erst einmal so ... *urgh*
    $sqlquery = "UPDATE job SET cr_sid = '' WHERE cr_sid = '0'";
writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
    $result = $db->query($sqlquery);
    if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());

    // Und noch einer... (nur HT)
    if (getParameterValue("0", "CLEANUP_TABLE_COURIER", "0") == "1"):
      $availabletime_limit = date("Y-m-d H:i:s", mktime(date("H"), date("i"), date("s"), date("m"), date("d") - 1, date("Y")));
      $sqlquery = "UPDATE courier SET cr_sid = '' WHERE cr_sid <> '0' AND cr_sid <> '' AND cr_available = 0 AND cr_availabletime < '$availabletime_limit'";
      $result1 = $db->query($sqlquery);
      if (DB::isError($result1)) myDie ("$PHP_SELF: '$sqlquery': " . $result1->getMessage());
      writeLog_("../log/check_jb_permanent_invtext_", "Deleting cr_sids with availability until yesterday [$sqlquery]");
    endif;
    
echo "[" . date("Y-m-d H:i:s") . "] checking global jobs (memory_get_usage() = " . memory_get_usage() . ")\n";
    // Und noch einer...
    // Unvermittelte globale Aufträge in Zuzuweisende zurückschicken
    // 18.08.2025: Die Ablaufzeit für jb_globaljob wurde von 60 auf 15 Minuten reduziert
    $sqlquery = "SELECT jb_id FROM job WHERE jb_globaljob = 1 AND jb_status = 0 AND (DATE_SUB(NOW(), INTERVAL 15 MINUTE) >= jb_modify)";
writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
    $theTheResult = $db2->query($sqlquery);
    if (DB::isError($theTheResult)) reportDie ("$PHP_SELF: '$sqlquery': " . $theTheResult->getMessage());
    while ($row = ($phpVersion >= "8.0" ? $theTheResult->fetch_assoc() : $theTheResult->fetchRow())):
      $sqlquery = "UPDATE job SET jb_globaljob = 0, jb_status = 9 WHERE jb_id = '" . $row["jb_id"] . "'";
      $result = $db->query($sqlquery);
      if (DB::isError($result)) reportDie ("$PHP_SELF: '$sqlquery': " . $result->getMessage());
    endwhile;
    $theTheResult->free();

// MEGA abgeschaltet am 17.06.
//    // Und noch einer...
//    // Ab dem 01.08. erhalten Aufträge eines bestimmten Kunden (MEGA) einen Mindestfuhrlohn über den Calculator
//    // Die Fahrzeugzuschläge und der Servicepreis müssen dabei berücksichtigt werden, da der Mindestfuhrlohn sich nur auf den Entfernungspreis bezieht
//    $jb_cr_price_minimum = 18; // Erhöhung von 13 auf 18 am 19.08.2023
//    $sqlquery = "SELECT job.jb_id, cr_sid, job.hq_id, vht_id, jb_payment, jb_type, emp_id, jb_invmode, jb_sales_tax_rate, jb_sales_tax_rate_sign, jb_markup, trs_price, trs_discount, jb_serviceprice" .
//    " FROM costcenter, customer, job LEFT JOIN tourservice ON job.jb_id = tourservice.jb_id AND trs_srv_name = 'Grundpreis'" .
//    " WHERE job.csc_id_payer = costcenter.csc_id AND costcenter.cs_id = customer.cs_id AND cs_eid IN (" . getParameterValue("0", "JB_CR_PRICE_MINIMUM", "0") . ")" .
//    " AND csc_name = '- Ad hoc Pkw bis XL-Bus'" .
//    " AND jb_finishtime > '2020-08-10' AND jb_status = 2" .
//    " AND jb_storno IS NULL" .
//    " AND jb_export_time IS NULL" .
//    " AND ((trs_price IS NULL AND jb_fixprice = 0.0) OR jb_totalprice < (" . $jb_cr_price_minimum . " + trs_price * ((100 - trs_discount) / 100) + jb_serviceprice)) AND (jb_id_parent IS NULL OR jb_id_parent != - 1)";
//writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
//    $theTheResult = $db2->query($sqlquery);
//    if (DB::isError($theTheResult)) reportDie ("$PHP_SELF: '$sqlquery': " . $theTheResult->getMessage());
//    while ($row = ($phpVersion >= "8.0" ? $theTheResult->fetch_assoc() : $theTheResult->fetchRow())):
//writeLog_("../log/check_jb_permanent_invtext_", $row["jb_id"] . " erhält automatischen Unterauftrag");
//      $tmp_add_jb_ids = "";
//      $tmp_add_sids = $row["cr_sid"];
//      $tmp_add_prices = sprintf("%01.2f", $jb_cr_price_minimum + $row["trs_price"] * ((100 - $row["trs_discount"]) / 100) + $row["jb_serviceprice"]);
//      saveJobChildren($row["jb_id"],
//         array("hq_id", $row["hq_id"], "vht_id", $row["vht_id"], "jb_payment", $row["jb_payment"],
//              "jb_status", "2", "jb_autoranking", "0", "jb_type", $row["jb_type"], "emp_id", $row["emp_id"], 
//              "jb_postage", 0, "jb_invmode", $row["jb_invmode"], "jb_freetext_1", "",
//              "jb_sales_tax_rate", $row["jb_sales_tax_rate"], "jb_sales_tax_rate_sign", $row["jb_sales_tax_rate_sign"]),
//        $tmp_add_jb_ids, $tmp_add_sids, $tmp_add_prices, $row["jb_markup"], 0, 0);
//      $db->query("UPDATE job SET cr_sid = 'B1555', cr_id = 10857, cr_id_order = 10857 WHERE jb_id = " . $row["jb_id"]);
//    endwhile;
//    $theTheResult->free();

    $sqlquery = "SELECT tr_id, tr_commission_no FROM job AS jb, tour AS tr WHERE jb.jb_id = tr.jb_id AND jb_status IN (8, 9) AND tr_commission_no LIKE '%\t%'";
writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
    $theTheResult = $db2->query($sqlquery);
    if (DB::isError($theTheResult)) reportDie ("$PHP_SELF: '$sqlquery': " . $theTheResult->getMessage());
    while ($row = ($phpVersion >= "8.0" ? $theTheResult->fetch_assoc() : $theTheResult->fetchRow())):
writeLog_("../log/check_jb_permanent_invtext_", "\$row['tr_id'] = " . $row["tr_id"] . ", \$tr_commission_no = '" . $row["tr_commission_no"] . "'");
    $sqlquery = "UPDATE tour SET tr_commission_no = '" . str_replace("\t", "  ", $row["tr_commission_no"]) . "', tr_modify = tr_modify WHERE tr_id = " . $row["tr_id"];
writeLog_("../log/check_jb_permanent_invtext_", "[" . $sqlquery . "]");
      $db->query($sqlquery);
    endwhile;
    $theTheResult->free();

    // BWV nachträgliche Preiskorrektur
    $currentTime = getDateTime("0");
    $sqlquery = "SELECT jb_id, jb_finishtime, hq_id, cr_id, cr_sid, jb_cr_price, gdc_content AS jb_cr_price_retour FROM job AS jb, genericdatacontainer AS gdc" .
      " WHERE jb_id = gdc_obj_id AND gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_cr_price_retour' AND gdc_context = '' AND DATE_ADD(jb_finishtime, INTERVAL 60 MINUTE) <= '" . $currentTime . "'";
writeLog_("../log/check_jb_permanent_invtext_", $sqlquery);
    $theTheResult = $db2->query($sqlquery);
    if (DB::isError($theTheResult)) reportDie ("$PHP_SELF: '$sqlquery': " . $theTheResult->getMessage());
    while ($row = $theTheResult->fetch_assoc()):
writeLog_("../log/check_jb_permanent_invtext_", "\$row['jb_id'] = " . $row["jb_id"] . ", \$jb_finishtime = '" . $row["jb_finishtime"] . ", \$cr_id = '" . $row["cr_id"] . ", \$jb_cr_price_retour = '" . $row["jb_cr_price_retour"] . "'");
      $jb_id_follow = $db->getOne("SELECT jb_id FROM job WHERE cr_id = " . $row["cr_id"] . " AND jb_longhaul = 1 AND jb_status = 1 AND jb_id != " . $row["jb_id"]);
      if ($jb_id_follow == "") {
        $jb_cr_price_retourArr = explode("|", $row["jb_cr_price_retour"]);
        $sqlquery = "UPDATE job SET jb_cr_price = " . $jb_cr_price_retourArr[0] . " WHERE jb_id = " . $row["jb_id"];
writeLog_("../log/check_jb_permanent_invtext_", "[" . $sqlquery . "]");
        $db->query($sqlquery);
        $sqlquery = "UPDATE jobprice SET jbprc_price = " . $jb_cr_price_retourArr[1] . " WHERE jb_id = " . $row["jb_id"] . " AND mt_sort = 10";
writeLog_("../log/check_jb_permanent_invtext_", "[" . $sqlquery . "]");
        $db->query($sqlquery);
        $gdc_context = "No follow-up";
        $pda_changes_text .= "#" . $row["jb_id"] . ", Frachtvergütung alt " . str_replace(".", ",", sprintf("%01.2f", $row["jb_cr_price"])) . " EUR, neu " . str_replace(".", ",", sprintf("%01.2f", $jb_cr_price_retourArr[0])) . " EUR\n";
        writeToLogDB("192",$row["hq_id"],$row["jb_id"],0,$row["cr_id"],$row["cr_sid"],"","\$jb_cr_price_old=" . $row["jb_cr_price"]);
        $pdaCommandExecTime = getdate(mktime(date("H"), date("i"), date("s") + 20, date("m"), date("d"), date("Y")));
        $pdaCommandExecTimeMySQL = $pdaCommandExecTime['year'] . "-" . sprintf("%02d", $pdaCommandExecTime['mon']) . "-" . sprintf("%02d", $pdaCommandExecTime['mday']) .
          " " . sprintf("%02d", $pdaCommandExecTime['hours']) . ":" . sprintf("%02d", $pdaCommandExecTime['minutes']) . ":" . sprintf("%02d", $pdaCommandExecTime['seconds']);
        $pdaCommandExpireTimeFromNow = getdate(mktime(date("H") + 36, date("i"), date("s"), date("m"), date("d"), date("Y")));
        $jb_ordertime_vals = getValsFromDate(getFieldValueFromId("job", "jb_id", $row["jb_id"], "jb_ordertime"));
        $pdaCommandExpireTimeFromOrdertime = getdate(mktime($jb_ordertime_vals[3] + 36, $jb_ordertime_vals[4], $jb_ordertime_vals[5],
          $jb_ordertime_vals[1], $jb_ordertime_vals[2], $jb_ordertime_vals[0]));
        if ($pdaCommandExpireTimeFromNow > $pdaCommandExpireTimeFromOrdertime):              
          $pdaCommandExpireTime = $pdaCommandExpireTimeFromNow;
        else:
          $pdaCommandExpireTime = $pdaCommandExpireTimeFromOrdertime;
        endif;
        $pdaCommandExpireTimeMySQL = $pdaCommandExpireTime['year'] . "-" . sprintf("%02d", $pdaCommandExpireTime['mon']) . "-" . sprintf("%02d", $pdaCommandExpireTime['mday']) .
          " " . sprintf("%02d", $pdaCommandExpireTime['hours']) . ":" . sprintf("%02d", $pdaCommandExpireTime['minutes']) . ":" . sprintf("%02d", $pdaCommandExpireTime['seconds']);
writeLog_("../log/check_jb_permanent_invtext_", $row["hq_id"] . ", " . $row["cr_id"] . ", " . "7" . ", " . "1" . ", " . $pda_changes_text . ", " . $pdaCommandExecTimeMySQL . ", " . $pdaCommandExpireTimeMySQL);
        insertPDACommand($row["hq_id"], $row["cr_id"], "7", "1", $pda_changes_text, $pdaCommandExecTimeMySQL, $pdaCommandExpireTimeMySQL);
	  } else {
        $gdc_context = "Follow-up: " . $jb_id_follow;
	  }
      $sqlquery = "UPDATE genericdatacontainer SET gdc_context = '" . $gdc_context . "|" . $currentTime  . "' WHERE gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'jb_cr_price_retour' AND gdc_obj_id = " . $row["jb_id"];
writeLog_("../log/check_jb_permanent_invtext_", "[" . $sqlquery . "]");
      $db->query($sqlquery);
    endwhile;
    $theTheResult->free();

//    /*
//    835489 //STE900608
//    //203463 //STHH927621
//    //823978 //STF909226
//    //819825 //STDD908923
//    //833194 //STB975597
//    835016 //STS910215
//    832514 //STHB922142
//    819783 //STH910930
//    823862 //STE900608 
//    */
//    foreach (array(835489, 835016, 832514, 819783, 823862) as $cs_id_tmp) {
//      $system_result = "";
//      $cmd = "php ../tools/auto_response.php acapella7890 $cs_id_tmp >> ../log/auto_response.stdout+err 2>&1 &";
//      $ausgabe = system($cmd, $system_result);
//      writeLog_("../log/check_jb_permanent_invtext_", "Calling auto_response.php $cs_id_tmp: ausgabe='$ausgabe'");
//    }

/*******************************************************************************
abgeschaltet am 16.06.2010
    // Und noch einer...
    // Alle erledigten und fertigen Aufträge von HTN40261 und HTN40260 in den benannten Zeiträumen automatisch auf unfertig setzen
    // Ab 21.10.2009 lauten die Kundennummern HTN40335 und HTN40336
    $sqlquery = "SELECT jb_id FROM job WHERE hq_id = 110 AND jb_status = 2 AND jb_incomplete != 1 AND " .
//      "(csc_id_payer = 49135 OR csc_id_payer = 49136) AND (" .
      "(csc_id_payer = 50330 OR csc_id_payer = 50331) AND (" .
//      "(jb_finishtime > '2009-03-13 00:00:00' AND jb_finishtime < '2009-03-18 23:59:59' AND '$now' > '2009-03-13 00:00:00' AND '$now' < '2009-03-18 23:59:59') OR" .
//      "(jb_finishtime > '2009-04-15 00:00:00' AND jb_finishtime < '2009-04-20 23:59:59' AND '$now' > '2009-04-15 00:00:00' AND '$now' < '2009-04-20 23:59:59') OR" .
//      "(jb_finishtime > '2009-05-15 00:00:00' AND jb_finishtime < '2009-05-20 23:59:59' AND '$now' > '2009-05-15 00:00:00' AND '$now' < '2009-05-20 23:59:59') OR" .
//      "(jb_finishtime > '2009-06-15 00:00:00' AND jb_finishtime < '2009-06-18 23:59:59' AND '$now' > '2009-06-15 00:00:00' AND '$now' < '2009-06-18 23:59:59') OR" .
//      "(jb_finishtime > '2009-07-15 00:00:00' AND jb_finishtime < '2009-07-20 23:59:59' AND '$now' > '2009-07-15 00:00:00' AND '$now' < '2009-07-20 23:59:59') OR" .
//      "(jb_finishtime > '2009-08-13 00:00:00' AND jb_finishtime < '2009-08-19 23:59:59' AND '$now' > '2009-08-13 00:00:00' AND '$now' < '2009-08-19 23:59:59') OR" .
//      "(jb_finishtime > '2009-09-14 00:00:00' AND jb_finishtime < '2009-09-18 23:59:59' AND '$now' > '2009-09-14 00:00:00' AND '$now' < '2009-09-18 23:59:59') OR" .
//      "(jb_finishtime > '2009-10-14 00:00:00' AND jb_finishtime < '2009-10-20 23:59:59' AND '$now' > '2009-10-14 00:00:00' AND '$now' < '2009-10-20 23:59:59') OR" .
//      "(jb_finishtime > '2009-11-13 00:00:00' AND jb_finishtime < '2009-11-18 23:59:59' AND '$now' > '2009-11-13 00:00:00' AND '$now' < '2009-11-18 23:59:59') OR" .
//      "(jb_finishtime > '2009-12-14 00:00:00' AND jb_finishtime < '2009-12-18 23:59:59' AND '$now' > '2009-12-14 00:00:00' AND '$now' < '2009-12-18 23:59:59') OR" .
//      "(jb_finishtime > '2010-01-15 00:00:00' AND jb_finishtime < '2010-01-18 23:59:59' AND '$now' > '2010-01-15 00:00:00' AND '$now' < '2010-01-18 23:59:59') OR" .
//      "(jb_finishtime > '2010-02-15 00:00:00' AND jb_finishtime < '2010-02-18 23:59:59' AND '$now' > '2010-02-15 00:00:00' AND '$now' < '2010-02-18 23:59:59') OR" .
//      "(jb_finishtime > '2010-03-15 00:00:00' AND jb_finishtime < '2010-03-18 23:59:59' AND '$now' > '2010-03-15 00:00:00' AND '$now' < '2010-03-18 23:59:59') OR" .
//      "(jb_finishtime > '2010-04-15 00:00:00' AND jb_finishtime < '2010-04-19 23:59:59' AND '$now' > '2010-04-15 00:00:00' AND '$now' < '2010-04-19 23:59:59') OR" .
//      "(jb_finishtime > '2010-05-14 00:00:00' AND jb_finishtime < '2010-05-18 23:59:59' AND '$now' > '2010-05-14 00:00:00' AND '$now' < '2010-05-18 23:59:59') OR" .
//      "(jb_finishtime > '2010-06-15 00:00:00' AND jb_finishtime < '2010-06-18 23:59:59' AND '$now' > '2010-06-15 00:00:00' AND '$now' < '2010-06-18 23:59:59') OR" .
      "(jb_finishtime > '2010-07-15 00:00:00' AND jb_finishtime < '2010-07-19 23:59:59' AND '$now' > '2010-07-15 00:00:00' AND '$now' < '2010-07-19 23:59:59') OR" .
      "(jb_finishtime > '2010-08-13 00:00:00' AND jb_finishtime < '2010-08-18 23:59:59' AND '$now' > '2010-08-13 00:00:00' AND '$now' < '2010-08-18 23:59:59') OR" .
      "(jb_finishtime > '2010-09-15 00:00:00' AND jb_finishtime < '2010-09-19 23:59:59' AND '$now' > '2010-09-15 00:00:00' AND '$now' < '2010-09-19 23:59:59') OR" .
      "(jb_finishtime > '2010-10-15 00:00:00' AND jb_finishtime < '2010-10-19 23:59:59' AND '$now' > '2010-10-15 00:00:00' AND '$now' < '2010-10-19 23:59:59') OR" .
      "(jb_finishtime > '2010-11-15 00:00:00' AND jb_finishtime < '2010-11-18 23:59:59' AND '$now' > '2010-11-15 00:00:00' AND '$now' < '2010-11-18 23:59:59') OR" .
      "(jb_finishtime > '2010-12-15 00:00:00' AND jb_finishtime < '2010-12-19 23:59:59' AND '$now' > '2010-12-15 00:00:00' AND '$now' < '2010-12-19 23:59:59'))";
    $theTheTheResult = $db2->query($sqlquery);
    if (DB::isError($theTheTheResult)) reportDie ("$PHP_SELF: '$sqlquery': " . $theTheTheResult->getMessage());
    while ($row = ($phpVersion >= "8.0" ? $theTheTheResult->fetch_assoc() : $theTheTheResult->fetchRow())):
      $sqlquery = "UPDATE job SET jb_incomplete = 1 WHERE jb_id = '" . $row["jb_id"] . "'";
      $theTheTheresult = $db->query($sqlquery);
      if (DB::isError($theTheTheresult)) reportDie ("$PHP_SELF: '$sqlquery': " . $theTheTheresult->getMessage());
    endwhile;
    $theTheTheResult->free();
*******************************************************************************/

    // Set execution time for keepalive
//    updateStmt("keepalive", "ka_process", "standing_orders", array("ka_lastexecutiontime", getDateTime("0")),"");
    // 500 Sekunden warten...
//    sleep(500);
  endwhile;  // Endless loop
} else {
/* Abfrage nach dauerhafter Änderung nicht, wenn keine echte Änderung */
/* Bei Storno ib_id_copy_permanent berücksichtigen wg. Löschen der Dauerauftragsregel */
/* Manuelle / automatische Vermittlung berücksichtigen*/
  // $jb_id angegeben -> expliziter Aufruf
  $jb_ids = array($jb_id);
  $jb_multi = "0";
  if (isset($argv[2]))
    $jb_multi = $argv[2];
  $jb_multi_factor = 1;
  if (isset($argv[3]))
    $jb_multi_factor = $argv[3];
//echo $jb_id . ", " . $jb_multi . ", " . $jb_multi_factor . "\n";
  if ($jb_multi_factor > 0) {
    if (isset($argv[4])) {
      $cr_id_orders = array_filter(explode(",", $argv[4]));
    }
    if (isset($cr_id_orders[0]) && $cr_id_orders[0] != "") {
      $cr_id_check_jb_permanent = getFieldValueFromId("couriervehicle", "crvh_sid", $cr_id_orders[0], "cr_id");
      updateStmt("job", "jb_id", $jb_id, array("cr_id_permanent", $cr_id_orders[0], "cr_sid", $cr_id_orders[0], "cr_id_order", $cr_id_check_jb_permanent, "cr_id", $cr_id_check_jb_permanent));
    }
    for ($i_multi = 2; $i_multi <= $jb_multi_factor; $i_multi++) {
//echo "\$jb_multi_factor=" . $jb_multi_factor . ", " . "\$i_multi=" . $i_multi . "\n";
      $hq_id = $db->getOne("SELECT hq_id FROM job WHERE jb_id = " . $jb_id);
      initJobList();
      $check_jb_permanent_flag = true;
      $_get_tr_commission_no = true;
      if (getParameterValue("0", "MASK_STANDING_KEEP_COMMISSION", $hq_id) != "1")
        $_get_tr_commission_no = false;
//echo "vor get_saved_tour.php\n";
      include("../jobs/get_saved_tour.php");
//echo "nach get_saved_tour.php\n";
      $jobListOri = $jobList;
      // jetzt wird das Senden eines jobs "simuliert",
      // woraufhin der Auftrag neu gespeichert wird
      $toursubmit = "Senden";  // Senden simulieren
      $csc_id_orderer = '0';   // Zentralenmodus
      $getPriceOnly = 0;       // Keine Nur-Preisabfrage
      $jb_id_ori_copy = $jb_id;    // jetzt neuer Auftrag
      $jb_id = "";             // jetzt neuer Auftrag
                               // Als emp_id (eingebender Mitarbeiter) wird 0 eingetragen,
                               // da niemand angemeldet ist
      // Natürlich kein neuer Multi-Auftrag
      $jb_multi_ori = $jb_multi;
      $jb_multi = "0";
      $jb_multi_factor_ori = $jb_multi_factor;
      $jb_multi_factor = "1";
//echo "vor job_options.php\n";
      $cr_id_order = ""; // Müll entfernen
      include("../jobs/job_options.php");
//echo "nach job_options.php\n";
      $jb_multi = $jb_multi_ori;
      $jb_multi_factor = $jb_multi_factor_ori;
      updateStmt("job", "jb_id", $jb_id, array("jb_status", $db->getOne("SELECT jb_status FROM job WHERE jb_id = " . $jb_id_ori_copy)));
      if (isset($cr_id_orders[$i_multi - 1]) && $cr_id_orders[$i_multi - 1] != "") {
      	$cr_sid_check_jb_permanent = $cr_id_orders[$i_multi - 1];
        $cr_id_check_jb_permanent = getFieldValueFromId("couriervehicle", "crvh_sid", $cr_sid_check_jb_permanent, "cr_id");
      	updateStmt("job", "jb_id", $jb_id, array("cr_id_permanent", $cr_sid_check_jb_permanent, "cr_sid", $cr_sid_check_jb_permanent, "cr_id_order", $cr_id_check_jb_permanent, "cr_id", $cr_id_check_jb_permanent));
      }
      if ($jb_multi == "1")
        updateStmt("job", "jb_id", $jb_id, array("jb_id_copy_permanent", $jb_id_ori_copy));
      $jb_ids[] = $jb_id;    // jetzt neuer Auftrag
      $jb_id = $jb_id_ori_copy;    // jetzt neuer Auftrag
    }
  }
//print_r($jb_ids);
//echo "\$jb_multi = " . $jb_multi . "\n";
  if ($jb_multi == "1") {
    // Nur den angegebenen Auftrag verarzten
    if (($jb_id_new = copy_job($jb_ids[0], $db->getOne("SELECT jb_finishtime FROM job WHERE jb_id = " . $jb_ids[0]), $db->getOne("SELECT hq_id FROM job WHERE jb_id = " . $jb_ids[0]))) != 0) {
      $cmd = "php ../jobs/check_jb_permanent.php " . $jb_id_new . " " . $jb_multi . " " . $jb_multi_factor . " " . $argv[4] . " >> " . "../log/check_jb_permanent_multi_" . date("Ym") . ".log" . " 2>&1 &";
echo $cmd . "\n";
      exec($cmd);
    }
  }
}

function copy_job($jb_id, $jb_finishtime, $hq_id_job = 0 /*, $jb_ordertime_override = "0000-00-00 00:00:00" */) 
{
  global $db, $jobList, $ph, $hq_id, $no_continuation_list, $ph, $jb_multi, $jb_multi_factor, $jb_hiddenFreetext_1, $phpVersion, $db_geo;

  if ($hq_id_job != 0)
    $hq_id = $hq_id_job;
  $ph = getPublicHolidays(getDateTime("year"), "1", "0");

//  writeLog_("../log/check_jb_permanent_standing_", "Duplicating job " . $jb_id . ", finishtime " . $jb_finishtime);
//  echo $jb_id . "<br>\n";

  initJobList();

  $check_jb_permanent_flag = true;
  $_get_tr_commission_no = true;
  if (getParameterValue("0", "MASK_STANDING_KEEP_COMMISSION", $hq_id) != "1")
    $_get_tr_commission_no = false;
  // Wenn dieser Dauerauftrag temporär geändert worden war, dann gibt es einen Vorgänger, der den ungeänderten Dauerauftrag enthält und
  // statt des geänderten als Vorlage genommen werden soll
  $jb_id_permanent_pre1 = $db->getOne("SELECT gdc_content FROM genericdatacontainer WHERE gdc_obj_type = 'jb' AND gdc_obj_id = " . $jb_id . " AND gdc_gen_fieldname = 'jb_id_permanent_pre'");
  $jb_id_copy_real = $jb_id;
  if ($jb_id_permanent_pre1 != ""):
    writeLog_("../log/check_jb_permanent_standing_", "temporary change was made in " . $jb_id . ", so instead predecessor " . $jb_id_permanent_pre1 . " is taken as source for continuation");
    $jb_id = $jb_id_permanent_pre1;
  endif;
//writeLog_("../log/check_jb_permanent_standing_", "vor get_saved_tour");
  include("../jobs/get_saved_tour.php");
//writeLog_("../log/check_jb_permanent_standing_", "nach get_saved_tour");
  $jb_id = $jb_id_copy_real;
  if ($jb_id_permanent_pre1 != ""):
    list($jahr, $monat, $tag, $stunde, $minute) = getValsFromDate($db->getOne("SELECT jb_ordertime FROM job WHERE jb_id = " . $jb_id));
//writeLog_("../log/check_jb_permanent_standing_", "$jahr, $monat, $tag, $stunde, $minute " . $db->getOne("SELECT jb_ordertime FROM job WHERE jb_id = " . $jb_id));
  endif;
  // Auftragsnummern der Unteraufträge entfernen: Kinderaufträge werden neu angelegt (d.h. kopiert)
  $tmp_add_jb_ids = "";
  // Daten der Unteraufträge entfernen: Unteraufträge verschwinden in der Kopie
  $tmp_add_sids = "";
  $tmp_add_prices = "";

//echo "$jb_id, $csc_id, $vht_id, $jb_weight, $jb_ordertime, $jb_reserv, 3, $vht_id, " .
//  "$cr_id_order, $jb_waitstorno, $jb_waittime, $jb_fixprice, $csc_id_payer </ br>\n";
//echo "'$jobList'\n";
//echo "'$jb_discount'" . " " . "'$jb_discount_rate'";

  // 14.10.2015 Aufgrund von unaufgeklärten Doppelverlängerungen wird hier noch einmal extra auf jb_id_copy_permanent abgefragt
  $jb_id_copy_permanent = $db->getOne("SELECT jb_id_copy_permanent FROM job WHERE jb_id = '$jb_id'");
  if ($jb_id_copy_permanent != "")
    writeLog_("../log/check_jb_permanent_standing_", "jb_id = $jb_id is not continued because a successor already exists: jb_id_copy_permanent = $jb_id_copy_permanent");

  // Ist aktueller Job ein Dauerauftrag?
  if ((in_array($jb_permanent, array(4, 5, 6, 7, 8, 9, 10, 11))
    || (in_array($jb_permanent, array(1, 2, 3)) && $jb_permanent2 != "0000000")) && $jb_id_copy_permanent == "")
  {
//echo "$jb_id '$jb_permanent'</ br>\n";
    // gültiger Dauerauftragsparameter vorhanden

    writeLog_("../log/check_jb_permanent_standing_", "* Continuing: jb_id = $jb_id, jb_permanent = $jb_permanent,  jb_finishtime = $jb_finishtime, jb_ordertime = $jahr-$monat-$tag $stunde:$minute:00, jb_permanent2 = $jb_permanent2, jp_permenddat = $jp_permenddat, CSC_ID_PAYER_CASH = " . CSC_ID_PAYER_CASH . ", \$CSC_ID_PAYER_CASH_VAR = " . $CSC_ID_PAYER_CASH_VAR);

    // Auswertung des Dauerauftrags-Parameters:
    // Neuberechnung des Reservierungsdatums (benötigen Kalenderfunktionen)
//    if ($jb_ordertime_override != "0000-00-00 00:00:00")
//      list($jahr, $monat, $tag, $stunde, $minute) = getValsFromDate($jb_ordertime_override);
//// STB975496 Lichtenberger Fleisch- und Wurstproduktion auch an Feiertagen!
//    if ($cs_id == 834928)
//      $ph = array();
// Ab 21.10.2019: Seit jb_permanent = 9 (feiertags) darf $ph natürlich nicht mehr zurückgesetzt werden!
//    if ($cs_id == 305826): // STB916864 St. Hedwig Kliniken Berlin GmbH _nur_ an Feiertagen, Samstagen und Sonntagen
//      $ph_new = array();
// Ab 19.12.2018: Keine Feiertage mehr für STB916864
//      // Neuer Kalender ab heute bis zum Ende nächsten Jahres mit allen Werktagen
//      for ($i = 1; $tmp_timestamp < mktime(0, 0, 0, 12, 31, date("Y") + 1); $i++):
//        $tmp_timestamp = mktime(0, 0, 0, date("m"), date("d") + $i, date("Y"));
//        if (!isPublicHoliday(date("Y", $tmp_timestamp), date("m", $tmp_timestamp), date("d", $tmp_timestamp)) && date("w", $tmp_timestamp) != 6 && date("w", $tmp_timestamp) != 0)
//          $ph_new[] = array(date("Y", $tmp_timestamp), date("m", $tmp_timestamp), date("d", $tmp_timestamp));
//      endfor;
//      $ph = $ph_new;
//    endif;

    $tempDate = getNextOrderDate($jahr, $monat, $tag, $jb_permanent, $jb_permanent2, true);
    
    $jb_ordertime_old = "";
                             // Alten Tag, Monat, Jahr für log_file speichern
    // Überprüfen, ob der Dauerauftrag nicht schon an seinem Enddatum angekomen ist!
    list($endejahr, $endemonat, $endetag, $dummy1, $dummy2, $dummy3) = getValsFromDate($jp_permenddat);
    if (mktime(0, 0, 0, $tempDate[1], $tempDate[2], $tempDate[0])
      < mktime($dummy1, $dummy2, $dummy3, $endemonat, $endetag, $endejahr) || trim($jp_permenddat) == "") {
      $jobListOri = $jobList;
      $jahr = $tempDate[0];    // ermittelten Tag, Monat, Jahr setzen
      $monat = sprintf("%02d", $tempDate[1]);
      $tag = sprintf("%02d", $tempDate[2]);
      $cr_id_order = $cr_id_permanent; // Kurier löschen bzw. usrsprünglichen Wunschkurier wieder einstellen
                               // jb_status wird daher = 9 gesetzt (kein Kurier eingetragen)
      //echo "$jahr.$monat.$tag<br>";
      // Treibstoffzuschlag updaten
      // Neu ab 23.01.2024: Manuelle TSZs entfernen wird jetzt in get_saved_tour gemacht und nicht mehr hier

      $jb_markup_man = $db->getOne("SELECT jbprc_price FROM jobprice WHERE jb_id = " . $jb_id . " AND mt_sort = 8");
      $cs_id = $db->getOne("SELECT cs_id FROM costcenter WHERE csc_id = " . $csc_id_payer);
      if ($jb_markup_man == "")
        writeLog_("../log/check_jb_permanent_standing_", "Manual markup will be updated: " . "\$jb_id (old) = " . $jb_id . ", \$jb_markup_man = " . $jb_markup_man . ", \$job_csc_id_payer = " . $job_csc_id_payer .
          ", (\$csc_id_payer = " . $csc_id_payer . "), \$cs_id_payer = " . $cs_id_payer . ", (\$cs_id = " . $cs_id . "), \$vht_id = " . $vht_id . ", \$srvt_name = " . $srvt_name . ", \$jb_markup = " . $jb_markup);
//      if (getParameterValue("0", "MASK_CHECK_MARKUP_PERMANENT", $hq_id) == "1"):
//        $jb_markup_old = getFieldValueFromId("job", "jb_id", $jb_id, "jb_markup");
////        if ($jb_markup_old == 0):
//          $job_csc_id_payer = getFieldValueFromId("job", "jb_id", $jb_id, "csc_id_payer");
//          $cs_id_payer = getFieldValueFromId("costcenter", "csc_id", $job_csc_id_payer, "cs_id");
//          $vht_id = getFieldValueFromId("job", "jb_id", $jb_id, "vht_id");
//          $srvt_name = $db->getOne("SELECT mt_value FROM metatype WHERE mt_sort = '" . $vht_id . "' AND mt_type = 'vehicletype'");
//          $jb_markup = getFuelMarkup($srvt_name, $cs_id_payer, $hq_id, "$jahr-$monat-$tag $stunde:$minute:00");
//          writeLog_("../log/check_jb_permanent_standing_", "Markup updated: " . "\$jb_id (old) = " . $jb_id . ", \$jb_markup_old = " . $jb_markup_old . ", \$job_csc_id_payer = " . $job_csc_id_payer .
//            ", (\$csc_id_payer = " . $csc_id_payer . "), \$cs_id_payer = " . $cs_id_payer . ", (\$cs_id = " . $cs_id . "), \$vht_id = " . $vht_id . ", \$srvt_name = " . $srvt_name . ", \$jb_markup = " . $jb_markup);
////        endif;
//      endif;

      // 31.05.2025 PZM-Preis?
      if ($jb_fixprice == 0 && $db->getOne("SELECT cs_invmode FROM customer WHERE cs_id = " . $cs_id) == 0) {
        $addr_params = "";
        $sqlquery = "SELECT tr_hsno, ad_zipcode, ad_city, ad_street, ad_country FROM tour AS tr, address AS ad WHERE jb_id = " . $jb_id . " AND tr.ad_id = ad.ad_id ORDER BY tr_sort";
        $res = $db->query($sqlquery);
        if (DB::isError($res)) die ("$PHP_SELF: '$sqlquery': " . $res->getMessage());
        while ($row = ($phpVersion >= "8.0" ? $res->fetch_assoc() : $res->fetchRow())):
          if ($row['ad_country'] == "" || $row['ad_country'] == "D")
            $row['ad_country'] = "DE";
          $addr_params .= ($addr_params != "" ? "|" : "") . urlencode($row['ad_street']) . ";" . urlencode($row['tr_hsno']) . ";" . urlencode($row['ad_zipcode']) . ";" . urlencode($row['ad_city']) . ";" . urlencode($row['ad_country']);
        endwhile;
        $res->free();

        $params = "hq_id=" . $hq_id . "&cs_id=" . $cs_id . "&vht_id=" . $vht_id . "&jb_markup=&jb_ordertime=" . urlencode("$jahr-$monat-$tag $stunde:$minute:00") ."&mode=zone&a=" . $addr_params;
//echo "https://bwv-test.assecutor.de/include/ajaxReqKmPrice.php?" . $params;die();
        $result = file_get_contents("https://bwv-test.assecutor.de/include/ajaxReqKmPrice.php?" . $params);
        writeLog_("../log/check_jb_permanent_standing_", "PZM-Preis will be updated: \$params = " . $params);
        writeLog_("../log/check_jb_permanent_standing_", "PZM-Preis will be updated: \$result = " . $result);
        eval("$" . $result);
        if ($retValue[0] != "ERROR") {
          $jb_fixprice = $retValue[5];
          $jb_cr_price = $retValue[6];
          $km_price_params = $retValue[2] . "|" . $retValue[3] . "|" . $retValue[4] . "|" . $retValue[7] . "|" . $retValue[8];
        }
      }

      // jetzt wird das Senden eines jobs mit dem neuen Datum "simuliert",
      // woraufhin der Auftrag neu gespeichert wird
      $toursubmit = "Senden";  // Senden simulieren
      $csc_id_orderer = '0';   // Zentralenmodus
      $getPriceOnly = 0;       // Keine Nur-Preisabfrage
      $jb_id_ori = $jb_id;
      $jb_id = "";             // jetzt neuer Auftrag
                               // Als emp_id (eingebender Mitarbeiter) wird 0 eingetragen,
                               // da niemand angemeldet ist
      if ($hq_id == 1 || $hq_id == 9) // nur Stadtbote Bremen und ab 26.06.2018 auch München
        $jb_globaljob = 0;        // darf natürlich niemals an alle Kuriere gehen!!!
      $jb_status_manual = 0;
      // manuelle Vermittlung ja/nein abhängig von hq_id!
      if (getParameterValue("0", "MASK_MANUAL_DISPOSITION", $db->getOne("SELECT hq_id FROM job WHERE jb_id = '$jb_id_ori'")) == "1"):
        $jb_status_manual = 1;
      endif;
      // 28.11.2022: Wenn `Manuelle Disposition´ geklickt, dann soll das übernommen werden
      if ($db->getOne("SELECT jb_id FROM phoenix_log.log WHERE jb_id = " . $jb_id_ori . " AND logo_id IN (1, 25) AND logo_description LIKE '%Manuelle Disposition%'") == $jb_id_ori)
        $jb_status_manual = 1;
      // Natürlich kein neuer Multi-Auftrag
      $jb_multi_ori = $jb_multi;
      $jb_multi = "0";
      $jb_multi_factor_ori = $jb_multi_factor;
      $jb_multi_factor = 1;
// Auftragsherkunft ist natürlich "Dauerauftrag"
      $jb_origin = 5;
      include("../jobs/job_options.php");
      $jb_multi_factor = $jb_multi_factor_ori;
      $jb_multi = $jb_multi_ori;
      if ($jb_multi == "1"):
        updateStmt("job", "jb_id", $jb_id, array("jb_status", $db->getOne("SELECT jb_status FROM job WHERE jb_id = " . $jb_id_ori)));
      endif;
      $jb_tourname = getFieldValueFromId("job", "jb_id", $jb_id_ori, "jb_tourname");
      updateStmt("job", "jb_id", $jb_id_ori, array("jb_id_copy", $jb_id, "jb_id_copy_permanent", $jb_id, "jb_tourname", NULL));
      updateStmt("job", "jb_id", $jb_id, array("cr_id_permanent", $cr_id_permanent, "jb_tourname", $jb_tourname));
      if (trim("$cr_id_permanent") != "" && trim("$cr_id_permanent") != "0")
        updateStmt("job", "jb_id", $jb_id, array("cr_sid", $cr_id_permanent));
      // überprüfen, ob sich die tx_id nicht zwischenzeitlich geändert hat...
      $cmp_tx_id = $db->getOne("SELECT cmp.tx_id FROM company AS cmp, customer AS cs WHERE cs.hq_id = '$hq_id' AND cmp.cmp_id = cs.cmp_id AND cs.cs_id = $csc_id_payer");
      if ($cmp_tx_id > 0):
//echo "SELECT cmp.tx_id FROM company AS cmp, customer AS cs WHERE cs.hq_id = '$hq_id' AND cmp.cmp_id = cs.cmp_id AND cs.cs_id = $csc_id_payer";
//echo "csc_id_payer: '$csc_id_payer'";
//echo "cmp_tx_id: '$cmp_tx_id'";
//echo "jb_sales_tax_rate: " . $db->getOne("SELECT tx_value FROM tax WHERE tx_id = '$cmp_tx_id'");
//echo "jb_sales_tax_rate_sign: " . $db->getOne("SELECT tx_sign FROM tax WHERE tx_id = '$cmp_tx_id'");
        updateStmt("job", "jb_id", $jb_id,
          array("jb_sales_tax_rate", $db->getOne("SELECT tx_value FROM tax WHERE tx_id = '$cmp_tx_id'"),
          "jb_sales_tax_rate_sign", $db->getOne("SELECT tx_sign FROM tax WHERE tx_id = '$cmp_tx_id'")));
      endif;
//      // evtl. vorhandene Kommissionsnummern entfernen!!!
//      // (nat. nur wenn so gewünscht...)
//      if (getParameterValue("0", "MASK_STANDING_KEEP_COMMISSION", $hq_id) != "1"):
//        $sqlquery = "UPDATE tour SET tr_commission_no = '' WHERE jb_id = " . $jb_id;
//        $res = $db->query($sqlquery);
//        if (DB::isError($res))
//          reportDie ("$PHP_SELF: '$sqlquery' : " . $res->getMessage());
//      endif;
      if ($cs_id == 18260 && $hq_id == 109): // HTM18156
        $max_tour = $db->getOne("SELECT MAX(tr_sort) FROM tour WHERE jb_id = '$jb_id'");
        if ($max_tour >= 16):
          for ($i = 2; $i <= $max_tour; $i++):
            updateStmt("tour", "jb_id", $jb_id, array("ad_id", 3209, "csc_id", 44549, "tr_comp", ($i - 1), 
              "tr_comp2", NULL, "tr_hsno", ".", "tr_remark", "", "tr_person", "", "tr_phone", ""), "tr_sort=" . $i);
          endfor;
        endif;
      endif;
      writeLog_("../log/check_jb_permanent_standing_", "Continuation: jb_id = $jb_id, jb_permanent = $jb_permanent, jb_ordertime = $jb_ordertime, jb_permanent2 = $jb_permanent2, jp_permenddat = $jp_permenddat, cr_id_permanent = [$cr_id_permanent], hq_id = [$hq_id],MASK_STANDING_KEEP_COMMISSION = [" . getParameterValue("0", "MASK_STANDING_KEEP_COMMISSION", $hq_id) . "], " . ", MASK_COURIER_IMMEDIATE = [" . getParameterValue("0", "MASK_COURIER_IMMEDIATE", $hq_id) . "]: $statusMessageTxt");
      return $jb_id;
    } else {
      $no_continuation_list[] = $jb_id;
      writeLog_("../log/check_jb_permanent_standing_", "NO CONTINUATION (finishdate reached): jb_id = $jb_id, jb_permanent = $jb_permanent, jb_permanent2 = $jb_permanent2, jp_permenddat = $jp_permenddat, jb_ordertime = $jb_ordertime: $statusMessageTxt");
    }
  } else {
    $no_continuation_list[] = $jb_id;
  }
  return 0;
}

//function delCmd() {
//  $fileHandle = @fopen("../log/call_check_jb_permanent.cmd", 'w');
//  @fclose($fileHandle);
//  return;
//}

//function writeCmd($jb_id) {
//  $fileHandle = @fopen("../log/call_check_jb_permanent.cmd", 'a');
//  @fwrite($fileHandle, "call check_jb_permanent.cmd " . $jb_id .  "\n");
//  @fclose($fileHandle);
//  return;
//}

function initJobList() {
  global $jobList;

  $tmpJobList = array();
  $tmpJobListJoin = array();
  for ($i = 0; $i < 6; $i++):
    $tmpJobList[$i] = array();
    for ($j = 0; $j < 9; $j++)
      $tmpJobList[$i][$j] = "";
    $tmpJobListJoin[$i] = implode("²", $tmpJobList[$i]);
  endfor;
  $jobList = implode("¹", $tmpJobListJoin);
}

// Funktion wird in get_saved_tour.php benötigt
function setJobList($tourNo, $fldNo, $newVal)
{
  global $jobList;
//echo  "$tourNo, $fldNo, $newVal <br>\n";
  $tmpJobListJoin = explode("¹", $jobList);
  $tmpJobList = explode("²", $tmpJobListJoin[$tourNo - 1]);
  $tmpJobList[$fldNo] = $newVal;
  $tmpJobListJoin[$tourNo - 1] = implode("²", $tmpJobList);
  $jobList = implode("¹", $tmpJobListJoin);
}

function is3rdOr4thWorkDay($whichone) {  
  global $ph;

  $jb_permanent = 1;
  $jb_permanent2 = "1111100";
  $ph = array(); // muss leer sein für getNextOrderDate()
  
  $tempDate = array(date("Y"), date("n"), date("j"));
  writeLog_("../log/check_jb_permanent_invtext_", "\$today = " . weekDayNameMapping(date("l")) . ", " . $tempDate[2] . "." . $tempDate[1] . "." . $tempDate[0]);
  
  $tempDate[1] -= 1;
  do {
    $lastUltimo = mktime(0, 0, 0, $tempDate[1] + 1, 0, $tempDate[0]);
    $tempDate = array(date("Y", $lastUltimo), date("n", $lastUltimo), date("j", $lastUltimo));
    writeLog_("../log/check_jb_permanent_invtext_", "\$lastUltimo = " . weekDayNameMapping(date("l", mktime(0, 0, 0, $tempDate[1], $tempDate[2], $tempDate[0]))) . ", " . $tempDate[2] . "." . $tempDate[1] . "." . $tempDate[0]);
  
    for($i = 0; $i <= $whichone - 1; $i++) {
      $tempDate = getNextOrderDate($tempDate[0], $tempDate[1], $tempDate[2], $jb_permanent, $jb_permanent2);
      while (feiertag($tempDate[0], $tempDate[1], $tempDate[2]))
        $tempDate = getNextOrderDate($tempDate[0], $tempDate[1], $tempDate[2], $jb_permanent, $jb_permanent2);
    }
  } while (mktime(23, 59, 59, $tempDate[1], $tempDate[2], $tempDate[0]) < time());
  
  writeLog_("../log/check_jb_permanent_invtext_", "\$is3rdOr4thWorkDay(". $whichone .") = " . weekDayNameMapping(date("l", mktime(0, 0, 0, $tempDate[1], $tempDate[2], $tempDate[0]))) . ", " . $tempDate[2] . "." . $tempDate[1] . "." . $tempDate[0]);
  if ($tempDate[0] == date("Y") && $tempDate[1] == date("n") && $tempDate[2] == date("j"))
    writeLog_("../log/check_jb_permanent_invtext_", "Heute ist der " . $whichone . ". Werktag des Monats!");
  return ($tempDate[0] == date("Y") && $tempDate[1] == date("n") && $tempDate[2] == date("j"));
}
?>
