Advertisement
Guest User

checkMailTicket

a guest
Jan 31st, 2020
2,152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 10.51 KB | None | 0 0
  1. private static $checkMailTicket;
  2.  
  3. ________________________________________________________
  4.  
  5. public static function getCheckMailTicket()
  6. {
  7. self::init();
  8. if (self::$checkMailTicket) {
  9.     return self::$checkMailTicket;
  10. }
  11. $checkMailTicket = 90; // Parameter::getGlobalParameter('cronCheckMailTicket');
  12. if (!$checkMailTicket) {
  13.     $checkMailTicket = 5 * 60;
  14. } // Default=every 5 mn
  15. self::$checkMailTicket = $checkMailTicket;
  16. return self::$checkMailTicket;
  17. }
  18.  
  19. ________________________________________________________
  20.  
  21.  
  22. $cronCheckMailTicket = self::getCheckMailTicket(); // PARAMETRE TICKET
  23.  
  24. ________________________________________________________
  25.  
  26. // CheckEmailsTicket : automatically import new tickets from mails
  27. if ($cronCheckMailTicket > 0) {
  28.         $cronCheckMailTicket -= $cronSleepTime;
  29.         if ($cronCheckMailTicket <= 0) {
  30.             try {
  31.             self::checkMailTicket();
  32.             } catch (Exception $e) {
  33.             traceLog("Cron::run() - Error on checkNewMailTicket()");
  34.             }
  35.             $cronCheckMailTicket = Cron::getCheckMailTicket();
  36.         }
  37.     }
  38.  
  39.  
  40. ________________________________________________________
  41.  
  42.  
  43. /* ==============================================================================
  44.   ==================== CRÉATION DE TICKET PAR LES MAILS =========================
  45.   =============================================================================== */
  46.   public static function checkMailTicket()
  47.   {
  48.     self::init();
  49.     global $globalCronMode, $globalCatchErrors;
  50.     $globalCronMode = true;
  51.     $globalCatchErrors = true;
  52.     require_once("../model/ImapMailbox.php"); // Imap management Class
  53.  
  54.     if (!ImapMailbox::checkImapEnabled()) {
  55.       traceLog("ERROR - Cron::checkMailTicket() - IMAP extension not enabled in your PHP config. Cannot connect to IMAP Mailbox.");
  56.       return;
  57.     }
  58.     $checkMailTicket = 90; // Parameter::getGlobalParameter('cronCheckMailTicket');
  59.     if (!$checkMailTicket or intval($checkMailTicket) <= 0) {
  60.       return; // disabled
  61.     }
  62.     // IMAP must be enabled in Google Mail Settings
  63.     $emailEmail = Parameter::getGlobalParameter('cronCheckEmailsUser');
  64.     $emailPassword = Parameter::getGlobalParameter('cronCheckEmailsPassword');
  65.     //$emailAttachmentsDir=dirname(__FILE__) . '/../files/attach';
  66.     $paramAttachDir = Parameter::getGlobalParameter('paramAttachmentDirectory');
  67.     $pathSeparator = Parameter::getGlobalParameter('paramPathSeparator');
  68.     if (substr($paramAttachDir, 0, 2) == '..') {
  69.       $curdir = dirname(__FILE__);
  70.       $paramAttachDir = str_replace(array('/model', '\model'), array('', ''), $curdir) . substr($paramAttachDir, 2);
  71.     }
  72.     $emailAttachmentsDir = ((substr($paramAttachDir, -1) == '\\' or substr($paramAttachDir, -1) == "/") ? $paramAttachDir : $paramAttachDir . $pathSeparator) . 'emails';
  73.     if (!file_exists($emailAttachmentsDir)) {
  74.       mkdir($emailAttachmentsDir, 0777, true);
  75.     }
  76.     $emailHost = Parameter::getGlobalParameter('cronCheckEmailsHost'); // {imap.gmail.com:993/imap/ssl}INBOX';
  77.     if (!$emailHost) {
  78.       traceLog("IMAP connection string not defined");
  79.       return;
  80.     }
  81.     $imapServerEncoding = Parameter::getGlobalParameter('imapFilterCriteria');
  82.     if (!$imapServerEncoding) {
  83.       $imapServerEncoding = 'utf-8';
  84.     }
  85.     $mailbox = new ImapMailbox($emailHost, $emailEmail, $emailPassword, $emailAttachmentsDir, $imapServerEncoding);
  86.     $mails = array();
  87.  
  88.     // Get some mail
  89.     //$mailsIds = $mailbox->searchMailBox('UNSEEN UNDELETED');
  90.     $imapFilterCriteria = Parameter::getGlobalParameter('imapFilterCriteria');
  91.     if (!$imapFilterCriteria) {
  92.       $imapFilterCriteria = 'UNSEEN UNDELETED';
  93.     }
  94.     $mailsIds = $mailbox->searchMailBox($imapFilterCriteria);
  95.     if (!$mailsIds) {
  96.       debugTraceLog("Mailbox is empty (filter='$imapFilterCriteria')"); // Will be a debug level trace
  97.       return;
  98.     }
  99.  
  100.     foreach ($mailsIds as $mailId) {
  101.       $mail = $mailbox->getMail($mailId);
  102.       $mailbox->markMailAsUnread($mailId);
  103.       debugTraceLog('===============================');
  104.       debugTraceLog("Message read (id $mailId), from $mail->fromAddress");
  105.       $body = $mail->textPlain;
  106.       $bodyHtml = $mail->textHtml;
  107.       if (!$body and $bodyHtml) {
  108.         $toText = new Html2Text($bodyHtml);
  109.         $body = $toText->getText();
  110.       }
  111.       $class = "ticket"; // INITIALISÉ A TICKET CAR UN VEUT CRÉER UN NV TICKET
  112.       $msg = null;
  113.       $senderId = null;
  114.  
  115.       // Search end of Message (this is valid for text only, treatment of html messages would require other code)      
  116.       $posEndMsg = strpos($body, "\r\n>"); // Search for Thunderbird and Gmail
  117.       if ($posEndMsg) {
  118.         $posEndMsg = strrpos(substr($body, 0, $posEndMsg - 20), "\r\n");
  119.       } else {
  120.         $posEndMsg = strpos($body, "\n>");
  121.       }
  122.  
  123.       if (!$posEndMsg) { // Search for outlook
  124.         preg_match('/<.*?@.*?> [\r\n]/', $body, $matches);
  125.         if (count($matches) > 0) {
  126.           $posEndMsg = strpos($body, $matches[0]);
  127.           $posEndMsg = strrpos(substr($body, 0, $posEndMsg - 2), "\r\n");
  128.         }
  129.       }
  130.  
  131.       if (!$posEndMsg) {
  132.         $posEndMsg = strpos($body, "\r\n\r\n\r\n");
  133.         if (!$posEndMsg) {
  134.           $posEndMsg = strpos($body, "\n\n\n");
  135.         }
  136.       }
  137.  
  138.       if ($posEndMsg) {
  139.         $msg = substr($body, 0, $posEndMsg);
  140.       }
  141.  
  142.       if (!trim($msg)) { // Message not received with previous methods, try another one
  143.         $posEndMsg = strrpos(substr($body, 0), "\n");
  144.         $posDe = strrpos(substr($body, 0, $posEndMsg), "De : ");
  145.         if ($posDe > 2) {
  146.           $posEndMsg = $posDe - 1;
  147.         } else {
  148.           $posDe = strrpos(substr($body, 0, $posEndMsg), "From : ");
  149.           if ($posDe > 2) {
  150.             $posEndMsg = $posDe - 1;
  151.           }
  152.         }
  153.         $msg = substr($body, 0, $posEndMsg);
  154.       }
  155.  
  156.       // Remove unexpected "tags" // Valid as long as we treat emails as text
  157.       $msg = preg_replace('/<mailto.*?\>/', '', $msg);
  158.       $msg = preg_replace('/<http.*?\>/', '', $msg);
  159.       $msg = preg_replace('/<#[A-F0-9\-]*?\>/', '', $msg);
  160.       $msg = str_replace(" \r\n", "\r\n", $msg);
  161.       $msg = str_replace(" \r\n", "\r\n", $msg);
  162.       $msg = str_replace("\r\n\r\n\r\n", "\r\n\r\n", $msg);
  163.       $msg = str_replace("\r\n\r\n\r\n", "\r\n\r\n", $msg);
  164.       $msg = str_replace(" \n", "\n", $msg);
  165.       $msg = str_replace(" \n", "\n", $msg);
  166.       $msg = str_replace("\n\n\n", "\n\n", $msg);
  167.       $msg = str_replace("\n\n\n", "\n\n", $msg);
  168.  
  169.       // Sender
  170.       $sender = $mail->fromAddress;
  171.       $crit = array('email' => $sender);
  172.       $usr = new Affectable();
  173.       $usrList = $usr->getSqlElementsFromCriteria($crit, false, null, 'idle asc, isUser desc, isResource desc');
  174.  
  175.       if (count($usrList)) {
  176.         $senderId = $usrList[0]->id;
  177.         $senderObj = $usrList[0];
  178.       }
  179.       debugTraceLog("User corresponding to email address is #$senderId");
  180.       if (!$senderId) {
  181.         traceLog("Email message received from '$sender', not recognized as resource or user or contact : message not stored as ticket to avoid spamming");
  182.         $mailbox->markMailAsUnread($mailId);
  183.         continue;
  184.       }
  185.       $arrayFrom = array("\n", "\r", " ");
  186.       $arrayTo = array("", "", "");
  187.       $class = str_replace($arrayFrom, $arrayTo, $class);
  188.       $obj = null;
  189.       if (SqlElement::class_exists($class)) {
  190.         $obj = new $class();
  191.         debugTraceLog("Message identified as a message for a new $class");
  192.       }
  193.       if (!trim($msg)) {
  194.         traceLog("Could not retreive body of the mail (empty response) from '$sender' mail concerning a new $class");
  195.         debugTraceLog($body);
  196.         $mailbox->markMailAsRead($mailId);
  197.         continue;
  198.       }
  199.       if ($obj and $senderId) {
  200.  
  201.         $pjc = 592; // ID of the project "TO DEFINE"
  202.  
  203.         // Getting sender affectations
  204.         if($senderObj->isUser == 1){ // isUser
  205.             $critere = array('idUser' => $senderId);
  206.             debugTraceLog("Sender $sender identified as a User");
  207.           }
  208.         else{ // isContact
  209.           $critere = array('idContact' => $senderId);
  210.           debugTraceLog("Sender $sender identified as a Contact");
  211.         }
  212.         if($critere){
  213.           $affectation = new Affectation();
  214.           $affectationList = $affectation->getSqlElementsFromCriteria($critere, false, null);
  215.           if (count($affectationList) == 1) {
  216.             $pjc = $affectationList[0]->idProject;
  217.             debugTraceLog("Project identified : $pjc");
  218.           }
  219.           else{
  220.             debugTraceLog("Project could not be identified  ...");
  221.           }
  222.         }
  223.  
  224.         // NEW TICKET CREATION
  225.         $ticket = new Ticket();
  226.         $ticket->name = $mail->subject; // TICKET NAME : SUBJECT
  227.         $ticket->idTicketType = 152; // TICKET TYPE : TO DEFINE
  228.         $ticket->idUser = 943; // EMITTER : MAIL
  229.         $ticket->idContact = intval($senderId); // REQUESTER : SENDER
  230.         $ticket->idProject = $pjc; // PROJECT: ONLY 1 AFFECTATION || TO DEFINE
  231.         $ticket->description = nl2brForPlainText($msg); // DESCRIPTION : PARSED MAIL BODY
  232.         $ticket->creationDateTime = date('Y-m-d H:i:s'); // CREATION DATE : CURRENT
  233.         $ticket->idStatus = 1; // STATUS : REGISTERED
  234.         $ticket->idPriority = 4; // PRIORITY : P3
  235.         $ticket->idCriticality = 1; // CRITICITY : LOW
  236.         $ticket->idProductVersion = 29; // PRODUCT VERSION : TO DEFINE
  237.  
  238.         $resSaveTicket = $ticket->save(); // Saving the ticket
  239.         $mailbox->markMailAsRead($mailId); // Mark the ticket as read
  240.  
  241.         // Log the saving operation
  242.         $status = getLastOperationStatus($resSaveTicket);
  243.         if ($status == 'OK') {
  244.           debugTraceLog("Ticket from '$sender' added");
  245.         } else {
  246.           debugTraceLog($status);
  247.           traceLog("ERROR saving ticket from '$sender' ");
  248.         }
  249.       } else {
  250.         $mailbox->markMailAsUnread($mailId); // Repassage en "non-lu"
  251.       }
  252.  
  253.       // DEBUG IN THE LOG FILE
  254.         ob_start();
  255.         //var_dump($affectationList);
  256.         //var_dump($ticket);
  257.         $result = ob_get_clean();
  258.         debugTraceLog($result);
  259.  
  260.     }
  261.     // Clean $emailAttachmentsDir for php files
  262.     foreach (glob($emailAttachmentsDir . '/*') as $v) {
  263.       if (!is_file($v)) continue;
  264.       if (substr(strtolower($v), -4) == '.php' or substr(strtolower($v), -5, 4) == '.php') unlink($v); // Default, but not enough
  265.       if (is_file($v)) unlink($v); // delete all files (as of today, we don't retreive attachments)
  266.     }
  267.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement