<?php
/*=======================================================================
 *
 * metafield_special_cron.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/


include_once ("../include/mcglobal.inc.php");

$autoMode = false;
if (!isset($argv[1]) || $argv[1] == "") :
   include_once ("../include/auth.inc.php");

   $httpVars = array("category", "objId", "cascadingObjType", "specialPageTitle", "sendToClientInlineDisplay", "sendToClientFileDownload", "fileTargetType", 
                     "auth", "mailToAdresses", "mailCcAdresses", "mailBccAdresses", "pdfPageSize", 
                     "ftp_db_parameter", "ftp_server", "ftp_user_name", "ftp_user_pass", "ftp_ssl", "ftp_remotepath",
                     "customerId", "cscIdRoot", "cscIdActual");
   getSecHttpVars("1", $httpVars);

   $autoMode = false;
   $isCron = false;
else :
   $category = ""; $objId = ""; $cascadingObjType = ""; $specialPageTitle = ""; $mailToAdresses = ""; $mailCcAdresses = ""; $mailBccAdresses = ""; $pdfPageSize = "";

   $isCron = true;
   if ($argv[1] == "acapella7890") :
       $autoMode = true;
       $category = $argv[2];
       $objId = $argv[3];
       $cascadingObjType = $argv[4];
       $specialPageTitle = $argv[5];
       $mailToAdresses = $argv[6];
       $mailCcAdresses = $argv[7];
       $mailBccAdresses = $argv[8];
       $pdfPageSize = $argv[9];
       $ftp_db_parameter = $argv[10];
       $ftp_server = $argv[11];
       $ftp_user_name = $argv[12];
       $ftp_user_pass = $argv[13];
       $ftp_ssl = $argv[14];
       $ftp_remotepath = $argv[15];
   endif;
endif;

require_once ("../include/WkHtmlToPdf.php");


// Execution-Time for script
set_time_limit(120);

getLanguage(__FILE__);

// if ($specialPageTitle == "") : $specialPageTitle = $objId; endif;
mcIsSet($debug, false);

$pageTitel = getLngt($specialPageTitle);
include_once ("../include/html.inc.php");
include_once ("../include/ftp.inc.php");
include_once ("../include/email/htmlMimeMail.php");

// "$objId" and "$category" (and additional "$cascadingObjType") have to be defined HERE !!!
include_once ("../include/inc_metafield.inc.php");

getCurrentScript(__FILE__);
if (!$autoMode) :
   // Check for authentication access and granted rights
   $usrAccessArray["hq"] = "1"; $usrAccessArray["cs"] = "1";
   authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);
   if ($userTypeName == "hq") :
      if (!(authCheckEmployeeRights($emp_id, "0") || authCheckEmployeeRights($emp_id, "1") || authCheckEmployeeRights($emp_id, "7") || authCheckEmployeeRights($emp_id, "14"))) :
         gotoReferer("1");
      endif;
   elseif ($userTypeName == "cs") :
      if (!(authCheckEmployeeRights($emp_id, "4"))) :
         gotoReferer("1");
      endif;
   endif;
   $hqId = $hq_id;
endif;


function generateOutputHTML ($htmlSnip, $pageTitel = "") {
	$htmlOut = "";
  $htmlOut .= "<html>\n";
  $htmlOut .= "  <head>\n";
  $htmlOut .= "    <title>" . $pageTitel . "</title>\n";
  $htmlOut .= "  </head>\n";
  $htmlOut .= "  <body>\n";
  $htmlOut .=      $htmlSnip;
  $htmlOut .= "  </body>\n";
  $htmlOut .= "</html>\n";
  return $htmlOut;
}

// Try to get headquartes. It is important send mails !!!!
if ($hqId == "" && $objId != "" && is_numeric($objId)) :
   if ($cascadingObjType = "jb") :
      $hqId = getFieldValueFromId("job","jb_id",$objId,"hq_id");
   endif;
endif;

// Check for sending mail if requested
$sendMail = false;
$mailToAdressesArray = array();
if ($mailToAdresses != "" && $hqId != "") :
   $sendMail = true;
   $mailToAdressesArray = spliti(",",$mailToAdresses);

   // Proprietary check regarding to the categories !!!!
   if ($category = "300") :
      $gdcContext = getFieldValueFromClause("genericdatacontainer", "gdc_context", "gdc_obj_type = '" . $cascadingObjType . "' AND gdc_obj_id = '" . $objId . "' AND gdc_gen_fieldname = 'mobile_photos'");
      if (!strpos($gdcContext, "MAIL_SENT=OK") === FALSE) :
         $sendMail = false;  // Mail had been sent in the past. Do not send again!
      endif;
   endif;
endif;

// Check for sending per (S)FTP if requested
$sendFTP = false;
if ($ftp_server != "" && $ftp_user_name != "" && $ftp_user_pass != "") :
   $sendFTP = true;
   if ($ftp_ssl == "") : $ftp_ssl = "0"; endif;
   if ($ftp_remotepath == "") : $ftp_remotepath = ""; endif;
else :
   if ($ftp_db_parameter != "") :
      $ftp_server = getParameterValue("0", "FTP_SERVER_" . $ftp_db_parameter, "0");
      $ftp_user_name = getParameterValue("0", "FTP_USER_" . $ftp_db_parameter, "0");
      $ftp_user_pass = getParameterValue("0", "FTP_PASSWORD_" . $ftp_db_parameter, "0");
      $ftp_ssl = getParameterValue("0", "FTP_SSL_" . $ftp_db_parameter, "0");
      $ftp_remotepath = getParameterValue("0", "FTP_REMOTEPATH_" . $ftp_db_parameter, "0");
      if ($ftp_server != "" && $ftp_user_name != "" && $ftp_user_pass != "") :
         $sendFTP = true;
         if ($ftp_ssl == "") : $ftp_ssl = "0"; endif;
      endif;
   endif;
endif;

if ($debug) :
   echo "\n category         :" . $category;
   echo "\n objId            :" . $objId;
   echo "\n cascadingObjType :" . $cascadingObjType;
   echo "\n specialPageTitle :" . $specialPageTitle;
   echo "\n mailToAdresses   :" . $mailToAdresses;
   echo "\n mailCcAdresses   :" . $mailCcAdresses;
   echo "\n mailBccAdresses  :" . $mailBccAdresses;
   echo "\n pdfPageSize      :" . $pdfPageSize;
   echo "\n ftp_db_parameter :" . $ftp_db_parameter;
   echo "\n ftp_server       :" . $ftp_server;
   echo "\n ftp_user_name    :" . $ftp_user_name;
   echo "\n ftp_user_pass    :" . $ftp_user_pass;
   echo "\n ftp_ssl          :" . $ftp_ssl;
   echo "\n ftp_remotepath   :" . $ftp_remotepath . "\n\n";
endif;

// Get current template stored in metafieldcategory for output
$currTemplateId = getFieldValueFromId("metafieldcategory","mtfc_id",$category,"mtft_id");
$atLeastOneImageDoesExistInForm = false;   // Init according to image file upload

// Generate output
$absoluteSystemPath = getAbsoluteSystemPath();  // Definition of absolute path, filename and extension. Has to be called here BEFORE calling function "outputMetaFieldSpecial()" !!!!
getDBData("job", $objId);                       // Get associative array for JOB data. Has to be called here BEFORE calling function "outputMetaFieldSpecial()" !!!!
getDBData("tour", $objId);                      // Get associative array for TOUR data of ALL stations. Has to be called here BEFORE calling function "outputMetaFieldSpecial()" !!!!
getDBData("tourservice", $objId);
getDBData("tourarticle", $objId);
// print_r($jobData); die();
$editMode = 3;  // Prepare for HTML email to convert e.g. to PDF
$outputMetaFieldsHtml = outputMetaFieldSpecial($currTemplateId, $editMode, $absoluteSystemPath);
$outputMetaFieldsHtmlPHP = $outputMetaFieldsHtml[0];
$outputMetaFieldsHtmlJS = $outputMetaFieldsHtml[1];

// Parse template
$jsFormularFinishPageFunc = "finishPage();";
if ($currTemplateId != "" && $currTemplateId != "0") :
   $contentOfCurrTemplate = getFieldValueFromId("metafieldtemplate","mtft_id",$currTemplateId,"mtft_content");
   if (!(strpos($contentOfCurrTemplate, "formularFinishPage") === FALSE)) :
      $jsFormularFinishPageFunc = "formularFinishPage();";
   endif;
endif;

// Check configuration for output
if (isset($sendToClientInlineDisplay) && $sendToClientInlineDisplay == "1") : $sendToClientInlineDisplay = true; else : $sendToClientInlineDisplay = false; endif;
if (isset($sendToClientFileDownload) && $sendToClientFileDownload == "1") : $sendToClientFileDownload = true; else : $sendToClientFileDownload = false; endif;
if (!isset($fileTargetType) || $fileTargetType == "") : $fileTargetType = "pdf"; endif;


// ******************************************************************************************************************   


// Generate filename
// $f_secretFileName = "news_" . md5($objId);
$f_secretFileName = md5($category) . "_" . $objId;

// Source filename
$fileExtensionSource = "html";
$fileName = "../temp/download/" . $f_secretFileName . "." . $fileExtensionSource;
$fileNameConversion = "/temp/download/" . $f_secretFileName;

// Target filename
$fileExtensionTarget = $fileTargetType;
$fileNameTarget = "../temp/download/" . $f_secretFileName . "." . $fileExtensionTarget;

// Generate HTML WITH ABSOLUTE path for creating PDF, etc.
$htmlOut = generateOutputHTML($outputMetaFieldsHtmlPHP);
// $htmlOut = urlencode(my_str_check_http($htmlOut));

// $htmlOut = str_replace("/var/www/html/images/", "../images/", $htmlOut);
// $htmlOut = str_replace("../", "EMC2/", $htmlOut);
// echo $htmlOut; die();

// Remove old file(s)
foreach (glob($fileName) as $fileNameToBoRemoved) {
  if (file_exists($fileNameToBoRemoved)) :
     unlink($fileNameToBoRemoved);
  endif;
}

// Write new file according to the current employee
// writeToFile($fileName, $htmlOut);   // Write attachement data into file

// **** Convert HTML file ****
// Call script e.g.: https://212.79.60.73/htm/admin/metafield_special_cron.php?category=302&objId=150017&cascadingObjType=jb&sendToClientFileDownload=1&pdfPageSize=label60x40
$pdfGlobalOptions = array();
$pdfPageOptions = array();
if ($pdfPageSize != "") :
   if ($pdfPageSize == "label60x40") :
      $pdfGlobalOptions = array('page-height' => '40mm', 'page-width' => '60mm', 'margin-bottom' => '1mm', 'margin-left' => '3mm', 'margin-right' => '1mm', 'margin-top' => '1mm');
      $pdfPageOptions = array('disable-smart-shrinking');
   else :
      $pdfGlobalOptions = array('page-size' => $pdfPageSize);
   endif;
endif;
if ($pdfGlobalOptions == "" || !is_array($pdfGlobalOptions)) :
   $pdf = new WkHtmlToPdf;
else :
   // $pdfGlobalOptions['enable-local-file-access'] = true;
   $pdf = new WkHtmlToPdf($pdfGlobalOptions);
endif;

$pdf->addPage($htmlOut, $pdfPageOptions);  // Add a HTML file, a HTML string or a page from a URL ["$pdf->addPage($fileName);" OR "$pdf->addPage('http://assecutor.de');" possible]
// $pdf->addCover('mycover.html');  // Add a cover (same sources as above are possible)
// $pdf->addToc();  // Add a Table of contents
// Save the PDF
if (!$pdf->saveAs($fileNameTarget)) :
    throw new Exception('Could not create PDF: '.$pdf->getError());
endif;
// Send to client for inline display
if ($sendToClientInlineDisplay == "1") :
   $pdf->send();
endif;
// Send to client for file download
if ($sendToClientFileDownload == "1") :
// echo "fileNameTarget = " . $fileNameTarget . "<br>";
   $pdf->send($fileNameTarget);
endif;



// Send mail if requested per setting at least one "mail to" address
if ($sendMail) :

   // Generate HTML WITH RELATIVE path for creating mail
   $outputMetaFieldsHtml = outputMetaFieldSpecial($currTemplateId, $editMode);
   $outputMetaFieldsHtmlPHP = $outputMetaFieldsHtml[0];
   $htmlOut = generateOutputHTML($outputMetaFieldsHtmlPHP);

   // Get current timestamp
   $currentTime = getDateTime("0");

   // Define constants   
   $constMailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $hqId);
   if ($category == "300") :
      $logFile = getParameterValue("0", "AUTOMAILER_ACCEPTANCE_PROTOCOL_LOGFILE", $hqId);
      if ($logFile == "") : $logFile = getParameterValue("0", "AUTOMAILER_ACCEPTANCE_PROTOCOL_LOGFILE", "0"); endif;
   endif;
   // Take default log for mails triggered by CRON independent from the type
   if ($logFile == "") : $logFile = getParameterValue("0", "AUTOMAILER_CRON_LOGFILE", $hqId); endif;
   if ($logFile == "") : $logFile = getParameterValue("0", "AUTOMAILER_CRON_LOGFILE", "0"); endif;
   if ($logFile == "") : $logFile = "../log/automailer_cron.log"; endif;

   // Send mail to admin@assecutor.de
   $mailObj = new htmlMimeMail();
   $mailObj->setFrom($constMailSenderAddress);
   if ($mailCcAdresses != "") :
      $mailObj->setCc($mailCcAdresses);
   endif;
   if ($mailBccAdresses != "") :
      $mailObj->setBcc($mailBccAdresses);
   endif;
   $mailObj->setSubject($pageTitel . " (" . $objId . ")");

   // HTML
   $mailObj->setHtml($htmlOut, null, "./");

   // Attachment
   if ($fileTargetType == "pdf" && file_exists($fileNameTarget)) :
      $attachment = $mailObj->getFile($fileNameTarget);
      $mailObj->addAttachment($attachment, $pageTitel . "_" . $objId . "." . $fileExtensionTarget, 'application/pdf');
   endif;

   $writeToLogfile = true;
   $mailResult = $mailObj->send($mailToAdressesArray, 'smtp');
   if ($mailResult) :
      if ($category == "300") :
         // Special case for service acceptance protocol
         $res = updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_SENT=OK"),"gdc_obj_id = '" . $objId . "' AND gdc_gen_fieldname = 'mail_srv_acc_prot' AND gdc_context LIKE '%SEND_IN_PROGRESS%'");
         
         // Write logdata into log file
         writeToFile($logFile, "[" . $pageTitel . "] [Status: OK] [Time: " . $currentTime . "] [Job: " . $objId . "] [From: " . $constMailSenderAddress . "] [To: " . $mailToAdresses . "] [Cc: " . $mailCcAdresses . "] [Bcc: " . $mailBccAdresses . "]");
         $writeToLogfile = false;

      elseif ($category == "9999") :
         // ....
      endif;

      // Write logdata into log file if not have been done before
      if ($writeToLogfile) :
         writeToFile($logFile, "[" . $pageTitel . "] [Status: OK] [Time: " . $currentTime . "] [Object: " . $objId . "] [Type: " . $cascadingObjType . "] [To: " . $mailToAdresses . "] [Cc: " . $mailCcAdresses . "] [Bcc: " . $mailBccAdresses . "]");
      endif;

   else :
      if ($category == "300") :
         // Special case for service acceptance protocol
         // IN CASE OF SENDING MAIL FAILED, DO NOT UPDATE ANYTHING, BECAUSE THE NEXT CRON WILL CATCH IT AGAIN!!!!
         // updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "MAIL_SENT=NOT_OK"),"gdc_obj_id = '" . $objId . "' AND gdc_gen_fieldname = 'mobile_photos'");         
      
         // Unlock semaphore if necessary (e.g. mail has not been sent)
         $res = updateStmt("genericdatacontainer", "gdc_obj_id", $objId, array("gdc_context", "MAIL_SENT=NOT_OK"), "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'mail_srv_acc_prot' AND gdc_context LIKE '%SEND_IN_PROGRESS%'");

      elseif ($category == "9999") :
         // ....
      endif;
   endif;
   $mailObj = NULL;


   // Remove stored temporary sign images on the filesystem
   /*
   $tmpSignPath = "../temp/signs/";
   $imgFilenamesLen = count($imgFilenames);
   if (SIGNS_PATH != "") : $tmpSignPath = SIGNS_PATH; endif;
   for ($im = 0; $im < $imgFilenamesLen; $im++) :
       if (file_exists($tmpSignPath . $imgFilenames[$im])) :
          unlink($tmpSignPath . $imgFilenames[$im]);
       endif;
   endfor;
   */
endif;


// Take PDF and put to the remote FTP environment
if ($sendFTP) :

   $opArray = ftpUpload($f_secretFileName . "." . $fileExtensionTarget, $f_secretFileName . "." . $fileExtensionTarget, $ftp_server, $ftp_user_name, $ftp_user_pass, "../temp/download/", $ftp_remotepath, $ftp_ssl);

   if ($opArray[0] == "0") :
      if ($category == "300") :
         // Special case for service acceptance protocol
         $res = updateStmt("genericdatacontainer","gdc_obj_type","jb",array("gdc_context", "LETTER_SENT=OK"),"gdc_obj_id = '" . $objId . "' AND gdc_gen_fieldname = 'letter_srv_acc_prot' AND gdc_context LIKE '%SEND_IN_PROGRESS%'");
         
         // Write logdata into log file
         writeToFile($logFile, "[" . $pageTitel . "] [Status: OK] [Time: " . $currentTime . "] [Job: " . $objId . "]");
         $writeToLogfile = false;

      elseif ($category == "9999") :
         // ....
      endif;

      // Write logdata into log file if not have been done before
      if ($writeToLogfile) :
         writeToFile($logFile, "[" . $pageTitel . "] [Status: OK] [Time: " . $currentTime . "] [Object: " . $objId . "] [Type: " . $cascadingObjType . "]");
      endif;

   else :
      if ($category == "300") :
         // Unlock semaphore if necessary (e.g. mail has not been sent)
         $res = updateStmt("genericdatacontainer", "gdc_obj_id", $objId, array("gdc_context", "LETTER_SENT=NOT_OK"), "gdc_obj_type = 'jb' AND gdc_gen_fieldname = 'letter_srv_acc_prot' AND gdc_context LIKE '%SEND_IN_PROGRESS%'");

      elseif ($category == "9999") :
         // ....
      endif;
   endif;                

   if ($ftp_ssl == "2") :
      sftpQuitConnection($connId);
   else :
      ftpQuitConnection($connId);
   endif;
endif;


echo $htmlOut;
?>
