66 public $element =
'emailcollector';
71 public $table_element =
'emailcollector_emailcollector';
76 public $picto =
'email';
81 public $fk_element =
'fk_emailcollector';
86 protected $childtables = array();
91 protected $childtablesoncascade = array(
'emailcollector_emailcollectorfilter',
'emailcollector_emailcollectoraction');
117 public $fields = array(
118 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'visible' => -2,
'enabled' => 1,
'position' => 1,
'notnull' => 1,
'index' => 1),
119 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'enabled' => 1,
'visible' => 0,
'default' =>
'1',
'notnull' => 1,
'index' => 1,
'position' => 20),
120 'ref' => array(
'type' =>
'varchar(128)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'showoncombobox' => 1,
'index' => 1,
'position' => 10,
'searchall' => 1,
'help' =>
'Example: MyCollector1',
'csslist' =>
'tdoverflowmax200'),
121 'label' => array(
'type' =>
'varchar(255)',
'label' =>
'Label',
'visible' => 1,
'enabled' => 1,
'position' => 30,
'notnull' => -1,
'searchall' => 1,
'help' =>
'Example: My Email collector',
'csslist' =>
'tdoverflowmax150 small',
'tdcss' =>
'titlefieldmiddle'),
122 'description' => array(
'type' =>
'text',
'label' =>
'Description',
'visible' => -1,
'enabled' => 1,
'position' => 60,
'notnull' => -1,
'cssview' =>
'small',
'csslist' =>
'small tdoverflowmax200'),
123 'host' => array(
'type' =>
'varchar(255)',
'label' =>
'EMailHost',
'visible' => 1,
'enabled' => 1,
'position' => 90,
'notnull' => 1,
'searchall' => 1,
'comment' =>
"IMAP server",
'help' =>
'Example: imap.gmail.com',
'csslist' =>
'tdoverflowmax125'),
124 'port' => array(
'type' =>
'varchar(10)',
'label' =>
'EMailHostPort',
'visible' => 1,
'enabled' => 1,
'position' => 91,
'notnull' => 1,
'searchall' => 0,
'comment' =>
"IMAP server port",
'help' =>
'Example: 993',
'csslist' =>
'tdoverflowmax50',
'default' =>
'993'),
125 'imap_encryption' => array(
'type' =>
'varchar(16)',
'label' =>
'ImapEncryption',
'visible' => -1,
'enabled' => 1,
'position' => 92,
'searchall' => 0,
'comment' =>
"IMAP encryption",
'help' =>
'ImapEncryptionHelp',
'arrayofkeyval' => array(
'ssl' =>
'SSL',
'tls' =>
'TLS',
'notls' =>
'NOTLS'),
'default' =>
'ssl'),
126 'hostcharset' => array(
'type' =>
'varchar(16)',
'label' =>
'HostCharset',
'visible' => -1,
'enabled' => 1,
'position' => 93,
'notnull' => 0,
'searchall' => 0,
'comment' =>
"IMAP server charset",
'help' =>
'Example: "UTF-8" (May be "US-ASCII" with some Office365)',
'default' =>
'UTF-8'),
127 'norsh' => array(
'type' =>
'integer',
'label' =>
'NoRSH',
'visible' => -1,
'enabled' =>
"!getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')",
'position' => 94,
'searchall' => 0,
'help' =>
'NoRSHHelp',
'arrayofkeyval' => array(0 =>
'No', 1 =>
'Yes'),
'default' =>
'0'),
128 'acces_type' => array(
'type' =>
'integer',
'label' =>
'AuthenticationMethod',
'visible' => -1,
'enabled' =>
"getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')",
'position' => 101,
'notnull' => 1,
'index' => 1,
'comment' =>
"IMAP login type",
'arrayofkeyval' => array(0 =>
'loginPassword', 1 =>
'oauthToken'),
'default' =>
'0',
'help' =>
''),
129 'login' => array(
'type' =>
'varchar(128)',
'label' =>
'Login',
'visible' => -1,
'enabled' => 1,
'position' => 102,
'notnull' => -1,
'index' => 1,
'comment' =>
"IMAP login",
'help' =>
'Example: myaccount@gmail.com'),
130 'password' => array(
'type' =>
'password',
'label' =>
'Password',
'visible' => -1,
'enabled' =>
"1",
'position' => 103,
'notnull' => -1,
'comment' =>
"IMAP password",
'help' =>
'WithGMailYouCanCreateADedicatedPassword'),
131 'oauth_service' => array(
'type' =>
'varchar(128)',
'label' =>
'oauthService',
'visible' => -1,
'enabled' =>
"getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')",
'position' => 104,
'notnull' => 0,
'index' => 1,
'comment' =>
"IMAP login oauthService",
'arrayofkeyval' => array(),
'help' =>
'TokenMustHaveBeenCreated'),
132 'source_directory' => array(
'type' =>
'varchar(255)',
'label' =>
'MailboxSourceDirectory',
'visible' => -1,
'enabled' => 1,
'position' => 109,
'notnull' => 1,
'default' =>
'Inbox',
'csslist' =>
'tdoverflowmax100',
'help' =>
'Example: INBOX, [Gmail]/Spam, [Gmail]/Draft, [Gmail]/Brouillons, [Gmail]/Sent Mail, [Gmail]/Messages envoyés, ...'),
133 'target_directory' => array(
'type' =>
'varchar(255)',
'label' =>
'MailboxTargetDirectory',
'visible' => 1,
'enabled' => 1,
'position' => 110,
'notnull' => 0,
'csslist' =>
'tdoverflowmax100',
'help' =>
"EmailCollectorTargetDir"),
134 'maxemailpercollect' => array(
'type' =>
'integer',
'label' =>
'MaxEmailCollectPerCollect',
'visible' => -1,
'enabled' => 1,
'position' => 111,
'default' =>
'50'),
135 'datelastresult' => array(
'type' =>
'datetime',
'label' =>
'DateLastCollectResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 121,
'notnull' => -1,
'csslist' =>
'nowraponall'),
136 'codelastresult' => array(
'type' =>
'varchar(16)',
'label' =>
'CodeLastResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 122,
'notnull' => -1,),
137 'lastresult' => array(
'type' =>
'varchar(255)',
'label' =>
'LastResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 123,
'notnull' => -1,
'cssview' =>
'small',
'csslist' =>
'maxwidth250imp'),
138 'datelastok' => array(
'type' =>
'datetime',
'label' =>
'DateLastcollectResultOk',
'visible' => 1,
'enabled' =>
'$action != "create"',
'position' => 125,
'notnull' => -1,
'csslist' =>
'nowraponall'),
139 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'visible' => 0,
'enabled' => 1,
'position' => 61,
'notnull' => -1,),
140 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'visible' => 0,
'enabled' => 1,
'position' => 62,
'notnull' => -1,),
141 'date_creation' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'visible' => -2,
'enabled' => 1,
'position' => 500,
'notnull' => 1,),
142 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModification',
'visible' => -2,
'enabled' => 1,
'position' => 501,
'notnull' => 1,),
144 'fk_user_creat' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'visible' => -2,
'enabled' => 1,
'position' => 510,
'notnull' => 1,),
145 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModif',
'visible' => -2,
'enabled' => 1,
'position' => 511,
'notnull' => -1,),
147 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'visible' => -2,
'enabled' => 1,
'position' => 1000,
'notnull' => -1,),
148 'status' => array(
'type' =>
'integer',
'label' =>
'Status',
'visible' => 1,
'enabled' => 1,
'position' => 1000,
'notnull' => 1,
'default' =>
'0',
'index' => 1,
'arrayofkeyval' => array(0 =>
'Inactive', 1 =>
'Active'))
180 public $fk_user_creat;
185 public $fk_user_modif;
219 public $oauth_service;
223 public $imap_encryption;
231 public $source_directory;
235 public $target_directory;
239 public $maxemailpercollect;
244 public $datelastresult;
249 public $codelastresult;
274 const STATUS_DISABLED = 0;
275 const STATUS_ENABLED = 1;
285 global
$conf, $langs;
289 $this->ismultientitymanaged = 1;
290 $this->isextrafieldmanaged = 0;
295 if (!
isModEnabled(
'multicompany') && isset($this->fields[
'entity'])) {
296 $this->fields[
'entity'][
'enabled'] = 0;
300 $oauthservices = array();
302 foreach (
$conf->global as $key => $val) {
303 if (!empty($val) && preg_match(
'/^OAUTH_.*_ID$/', $key)) {
304 $key = preg_replace(
'/^OAUTH_/',
'', $key);
305 $key = preg_replace(
'/_ID$/',
'', $key);
306 if (preg_match(
'/^.*-/', $key)) {
307 $name = preg_replace(
'/^.*-/',
'', $key);
309 $name = $langs->trans(
"NoName");
311 $provider = preg_replace(
'/-.*$/',
'', $key);
312 $provider = ucfirst(strtolower($provider));
314 $oauthservices[$key] = $name.
" (".$provider.
")";
318 $this->fields[
'oauth_service'][
'arrayofkeyval'] = $oauthservices;
321 foreach ($this->fields as $key => $val) {
322 if (isset($val[
'enabled']) && empty($val[
'enabled'])) {
323 unset($this->fields[$key]);
328 foreach ($this->fields as $key => $val) {
329 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
330 foreach ($val[
'arrayofkeyval'] as $key2 => $val2) {
331 $this->fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
349 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
350 $langs->load(
"errors");
351 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
355 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
356 $this->password =
dolEncrypt($this->password);
360 $this->password =
dolDecrypt($this->password);
362 if (is_array($this->filters) && count($this->filters)) {
365 foreach ($this->filters as $filter) {
366 $emailcollectorfilter->type = $filter[
'type'];
367 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
368 $emailcollectorfilter->fk_emailcollector = $this->id;
369 $emailcollectorfilter->status = $filter[
'status'];
371 $emailcollectorfilter->create($user);
375 if (is_array($this->actions) && count($this->actions)) {
378 foreach ($this->actions as $operation) {
379 $emailcollectoroperation->type = $operation[
'type'];
380 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
381 $emailcollectoroperation->fk_emailcollector = $this->id;
382 $emailcollectoroperation->status = $operation[
'status'];
383 $emailcollectoroperation->position = $operation[
'position'];
385 $emailcollectoroperation->create($user);
401 global $langs, $extrafields;
422 unset(
$object->codelastresult);
423 unset(
$object->datelastresult);
428 $object->ref =
"copy_of_".$object->ref;
431 $object->host =
'imap.example.com';
434 if (is_array(
$object->array_options) && count(
$object->array_options) > 0) {
435 $extrafields->fetch_name_optionals_label($this->table_element);
436 foreach (
$object->array_options as $key => $option) {
437 $shortkey = preg_replace(
'/options_/',
'', $key);
438 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
439 unset(
$object->array_options[$key]);
445 $object->context[
'createfromclone'] =
'createfromclone';
446 $result =
$object->create($user);
452 unset(
$object->context[
'createfromclone']);
459 $this->db->rollback();
471 public function fetch($id, $ref =
null)
475 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
476 $this->password =
dolDecrypt($this->password);
509 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
513 $sql =
"SELECT s.rowid";
514 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
515 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
517 $sql .=
" AND s.status = 1";
519 $sql .= $this->db->order($sortfield, $sortorder);
524 $offset = $limit * $page;
526 $sql .= $this->db->plimit($limit + 1, $offset);
529 $result = $this->db->query($sql);
531 $num = $this->db->num_rows($result);
534 $obj = $this->db->fetch_object($result);
536 if ($emailcollector_static->fetch($obj->rowid)) {
537 $obj_ret[] = $emailcollector_static;
542 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
543 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
545 if (!count($obj_ret)) {
546 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
564 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
565 $langs->load(
"errors");
566 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
570 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
571 $this->password =
dolEncrypt($this->password);
575 $this->password =
dolDecrypt($this->password);
587 public function delete(
User $user, $notrigger = 0)
602 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
604 global
$conf, $langs, $action, $hookmanager;
606 if (!empty(
$conf->dol_no_mouse_hover)) {
612 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
614 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
616 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
618 if ($option !=
'nolink') {
620 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
621 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
622 $add_save_lastsearch_values = 1;
624 if ($add_save_lastsearch_values) {
625 $url .=
'&save_lastsearch_values=1';
630 if (empty($notooltip)) {
632 $label = $langs->trans(
"ShowEmailCollector");
633 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
635 $linkclose .=
' title="'.dolPrintHTMLForAttribute($label).
'"';
636 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
638 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
641 $linkstart =
'<a href="'.$url.
'"';
642 $linkstart .= $linkclose.
'>';
645 $result .= $linkstart;
647 $result .=
img_object(($notooltip ?
'' : $label), ($this->picto ? $this->picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
649 if ($withpicto != 2) {
650 $result .= $this->ref;
655 $hookmanager->initHooks(array(
'emailcollectordao'));
656 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result);
657 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
659 $result = $hookmanager->resPrint;
661 $result .= $hookmanager->resPrint;
689 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
692 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
693 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
694 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
695 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
698 $statusType =
'status5';
699 if ($status == self::STATUS_ENABLED) {
700 $statusType =
'status4';
703 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
714 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
715 $sql .=
' fk_user_creat, fk_user_modif';
716 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
717 $sql .=
' WHERE t.rowid = '.((int) $id);
718 $result = $this->db->query($sql);
720 if ($this->db->num_rows($result)) {
721 $obj = $this->db->fetch_object($result);
723 $this->
id = $obj->rowid;
725 $this->user_creation_id = $obj->fk_user_creat;
726 $this->user_modification_id = $obj->fk_user_modif;
727 $this->date_creation = $this->db->jdate($obj->datec);
728 $this->date_modification = empty($obj->datem) ?
'' : $this->db->jdate($obj->datem);
731 $this->db->free($result);
745 $this->host =
'localhost';
746 $this->login =
'alogin';
759 $this->filters = array();
761 $sql =
'SELECT rowid, type, rulevalue, status';
762 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
763 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
766 $resql = $this->db->query($sql);
768 $num = $this->db->num_rows($resql);
771 $obj = $this->db->fetch_object($resql);
772 $this->filters[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'rulevalue' => $obj->rulevalue,
'status' => $obj->status);
775 $this->db->free($resql);
791 $this->actions = array();
793 $sql =
'SELECT rowid, type, actionparam, status, position';
794 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
795 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
796 $sql .=
' ORDER BY position';
798 $resql = $this->db->query($sql);
800 $num = $this->db->num_rows($resql);
803 $obj = $this->db->fetch_object($resql);
804 $this->actions[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'actionparam' => $obj->actionparam,
'status' => $obj->status,
'position' => $obj->position);
807 $this->db->free($resql);
826 $flags =
'/service=imap';
829 } elseif (empty($this->imap_encryption) || ($this->imap_encryption ==
'ssl' &&
getDolGlobalString(
'IMAP_FORCE_NOSSL'))) {
832 $flags .=
'/' . $this->imap_encryption;
835 $flags .=
'/novalidate-cert';
842 if (!empty($this->login) && strpos($this->login,
'/') !=
false) {
843 $partofauth = explode(
'/', $this->login);
844 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
847 $connectstringserver =
'{'.$this->host.
':'.$this->port.$flags.
'}';
849 return $connectstringserver;
860 if (function_exists(
'mb_convert_encoding')) {
862 $str = preg_replace(
"/ /",
"xxxSPACExxx", $str);
863 $str = preg_replace(
"/_/",
"xxxUNDERSCORExxx", $str);
864 $str = preg_replace(
"/\[Gmail\]/",
"xxxGMAILxxx", $str);
866 if ($str = mb_convert_encoding($str,
"UTF-7")) {
868 $str = preg_replace(
"/\+A/",
"&A", $str);
869 $str = preg_replace(
"/xxxUNDERSCORExxx/",
"_", $str);
871 $str = preg_replace(
"/xxxSPACExxx/",
" ", $str);
873 $str = preg_replace(
"/xxxGMAILxxx/",
"[Gmail]", $str);
877 $this->error =
"error: is not possible to encode this string '".$str.
"'";
897 $arrayofcollectors = $this->
fetchAll($user, 1);
899 foreach ($arrayofcollectors as $emailcollector) {
900 $result = $emailcollector->doCollectOneCollector(0);
902 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
904 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
905 if (!empty($emailcollector->errors)) {
906 $this->error .= implode(
'<br>', $emailcollector->errors);
909 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
932 global
$conf, $langs;
934 $errorforthisaction = 0;
937 $outputlangs = $langs;
940 $newlang =
GETPOST(
'lang_id',
'aZ09');
943 $newlang = !empty(
$object->thirdparty->default_lang) ?
$object->thirdparty->default_lang : $newlang;
945 if (!empty($newlang)) {
947 $outputlangs->setDefaultLang($newlang);
957 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
960 $tmparray = explode(
'.', $propertytooverwrite);
961 if (count($tmparray) == 2) {
962 $tmpclass = $tmparray[0];
963 $tmpproperty = $tmparray[1];
965 $tmpproperty = $tmparray[0];
967 if ($tmpclass && ($tmpclass !=
$object->element)) {
977 $regforregex = array();
978 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
979 $sourcefield = $regforregex[1];
980 $regexstring = $regforregex[2];
982 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
983 $sourcefield = $regforregex[1];
984 $regexstring = $regforregex[2];
987 if (!empty($sourcefield) && !empty($regexstring)) {
988 if (strtolower($sourcefield) ==
'body') {
989 $sourcestring = $messagetext;
990 } elseif (strtolower($sourcefield) ==
'subject') {
991 $sourcestring = $subject;
992 } elseif (strtolower($sourcefield) ==
'header') {
993 $sourcestring = $header;
997 $regforval = array();
999 if (strtolower($sourcefield) ==
'body') {
1000 $regexoptions =
'ms';
1002 if (strtolower($sourcefield) ==
'header') {
1003 $regexoptions =
'm';
1006 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
1008 $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
'';
1009 $valuetoset = (strtolower($sourcefield) ==
'body') ? $valueextracted : $this->
decodeSMTPSubject($valueextracted);
1010 if (preg_match(
'/^options_/', $tmpproperty)) {
1011 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetoset;
1013 if (property_exists(
$object, $tmpproperty)) {
1014 $object->$tmpproperty = $valuetoset;
1016 $tmp[$tmpproperty] = $valuetoset;
1020 if (preg_match(
'/^options_/', $tmpproperty)) {
1023 if (property_exists(
$object, $tmpproperty)) {
1031 if (property_exists(
$object, $tmpproperty)) {
1033 $operationslog .=
'<br>Regex /'.dol_escape_htmltag($regexstring).
'/'.
dol_escape_htmltag($regexoptions).
' into '.strtolower($sourcefield).
' -> not found, so object property '.
dol_escape_htmltag($tmpproperty).
' is set to null.';
1035 $tmp[$tmpproperty] =
null;
1036 $operationslog .=
'<br>Regex /'.dol_escape_htmltag($regexstring).
'/'.
dol_escape_htmltag($regexoptions).
' into '.strtolower($sourcefield).
' -> not found, so var '.
dol_escape_htmltag($tmpproperty).
' is set to null.';
1041 $errorforthisaction++;
1042 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1043 $this->errors[] = $this->error;
1045 $operationslog .=
'<br>'.$this->error;
1047 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1049 if (preg_match(
'/^options_/', $tmpproperty)) {
1050 $valuecurrent =
$object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1052 if (property_exists(
$object, $tmpproperty)) {
1053 $valuecurrent =
$object->$tmpproperty;
1056 $valuecurrent = $tmp[$tmpproperty];
1060 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1061 $valuetouse = $regforregex[2];
1062 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null,
$object);
1064 $matcharray = array();
1065 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1066 if (is_array($matcharray[1])) {
1067 foreach ($matcharray[1] as $keytoreplace) {
1068 if ($keytoreplace) {
1069 if (preg_match(
'/^options_/', $keytoreplace)) {
1070 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1072 if (property_exists(
$object, $keytoreplace)) {
1073 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->$keytoreplace;
1076 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1085 if (preg_match(
'/^options_/', $tmpproperty)) {
1086 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1088 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1090 if (property_exists(
$object, $tmpproperty)) {
1091 $object->$tmpproperty = $valuetouse;
1093 $tmp[$tmpproperty] = $valuetouse;
1096 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1100 $errorforthisaction++;
1101 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1102 $this->errors[] = $this->error;
1107 return $errorforthisaction;
1116 public function doCollectOneCollector($mode = 0)
1118 global $db,
$conf, $langs, $user;
1119 global $hookmanager;
1123 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1125 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1128 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1130 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1135 $this->debuginfo =
'';
1139 $searchfilterdoltrackid = 0;
1140 $searchfilternodoltrackid = 0;
1141 $searchfilterisanswer = 0;
1142 $searchfilterisnotanswer = 0;
1143 $searchfilterreplyto = 0;
1144 $searchfilterexcludebodyarray = array();
1145 $searchfilterexcludesubjectarray = array();
1146 $searchfilterexcludeemailarray = array();
1147 $searchfilterexcludedomainarray = array();
1148 $searchfilterexcludeemailmap = array();
1149 $operationslog =
'';
1150 $rulesreplyto = array();
1151 $connectstringsource =
'';
1152 $connectstringtarget =
'';
1153 $connection =
false;
1154 $arrayofemail = array();
1159 if (empty($this->host)) {
1160 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1163 if (empty($this->login)) {
1164 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1167 if (empty($this->source_directory)) {
1168 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1174 $sourcedir = $this->source_directory;
1175 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1180 $sourcedir = $this->source_directory;
1181 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1184 $timeoutconnect = (int)
getDolGlobalInt(
'MAIN_USE_CONNECT_TIMEOUT', 5);
1185 if ($timeoutconnect <= 0) {
1186 $timeoutconnect = 5;
1188 $timeoutread = (int)
getDolGlobalInt(
'MAIN_USE_RESPONSE_TIMEOUT', 20);
1189 if ($timeoutread <= 0) {
1192 if (function_exists(
'imap_timeout')) {
1193 imap_timeout(IMAP_OPENTIMEOUT, $timeoutconnect);
1194 imap_timeout(IMAP_READTIMEOUT, $timeoutread);
1195 imap_timeout(IMAP_WRITETIMEOUT, 5);
1196 imap_timeout(IMAP_CLOSETIMEOUT, 5);
1197 $this->debuginfo .=
'IMAP timeouts: connect='.$timeoutconnect.
's, read='.$timeoutread.
's<br>';
1201 if ($this->acces_type == 1) {
1203 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>';
1205 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1209 $keyforsupportedoauth2array = $this->oauth_service;
1210 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1211 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1213 $keyforprovider =
'';
1215 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', strtoupper($keyforsupportedoauth2array));
1216 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1218 if (!empty($supportedoauth2array)) {
1219 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1220 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1221 $OAUTH_SERVICENAME = $nameofservice;
1223 $OAUTH_SERVICENAME =
'Unknown';
1226 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1228 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1237 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1240 if (is_object($tokenobj) && method_exists($tokenobj,
'getEndOfLife')) {
1241 $endOfLife = $tokenobj->getEndOfLife();
1242 if ($endOfLife !== -9002 && $endOfLife !== -9001 && time() > ($endOfLife - 30)) {
1248 if (is_object($tokenobj) && $expire) {
1249 $this->debuginfo .=
'Refresh token '.$OAUTH_SERVICENAME.
'<br>';
1250 $credentials =
new Credentials(
1255 $serviceFactory = new \OAuth\ServiceFactory();
1256 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1260 if (preg_match(
'/^Microsoft/', $OAUTH_SERVICENAME)) {
1262 $tmp = explode(
'-', $OAUTH_SERVICENAME);
1263 $scopes = explode(
',',
getDolGlobalString(
'OAUTH_'.strtoupper($tmp[0]).(empty($tmp[1]) ?
'' :
'-'.$tmp[1]).
'_SCOPE'));
1266 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $scopes);
1268 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
1270 $refreshtoken = $tokenobj->getRefreshToken();
1271 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1274 if (empty($tokenobj->getRefreshToken())) {
1275 $tokenobj->setRefreshToken($refreshtoken);
1277 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1279 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1280 if (is_object($tokenobj)) {
1281 $token = $tokenobj->getAccessToken();
1283 $this->error =
"Token not found";
1288 $this->error = $e->getMessage();
1289 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1293 $cm =
new ClientManager();
1294 $client = $cm->make([
1295 'host' => $this->host,
1296 'port' => $this->port,
1297 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1298 'validate_cert' => true,
1299 'protocol' =>
'imap',
1300 'username' => $this->login,
1301 'password' => $token,
1302 'authentication' =>
"oauth",
1306 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1308 $cm =
new ClientManager();
1309 $client = $cm->make([
1310 'host' => $this->host,
1311 'port' => $this->port,
1312 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1313 'validate_cert' => true,
1314 'protocol' =>
'imap',
1315 'username' => $this->login,
1316 'password' => $this->password,
1317 'authentication' =>
"login",
1325 }
catch (ConnectionFailedException $e) {
1326 $this->error = $e->getMessage();
1327 $this->errors[] = $this->error;
1328 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1332 $host = dol_getprefix(
'email');
1335 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1337 if (!function_exists(
'imap_open')) {
1338 $this->error =
'IMAP function not enabled on your PHP';
1344 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1345 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1347 $connectstringsource = $connectstringserver.$sourcedir;
1348 $connectstringtarget = $connectstringserver.$targetdir;
1351 $this->debuginfo .=
'connectstringsource = '.$connectstringsource.
', $connectstringtarget='.$connectstringtarget.
'<br>';
1353 $connection = imap_open($connectstringsource, $this->login, $this->password);
1354 if ($connection ===
false) {
1355 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1358 '@phan-var-force resource|IMAP\Connection $connection';
1361 $host = dol_getprefix(
'email');
1370 $criteria = array();
1373 $criteria = array(array(
'UNDELETED'));
1374 foreach ($this->filters as $rule) {
1375 if (empty($rule[
'status'])) {
1380 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1384 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1387 if ($rule[
'type'] ==
'excludeemail') {
1388 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1389 if (is_array($tmpvalues)) {
1390 foreach ($tmpvalues as $tmpvalue) {
1391 $tmpvalue = trim((
string) $tmpvalue);
1392 if ($tmpvalue ===
'') {
1396 if (preg_match_all(
'/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpvalue, $tmpmatches)) {
1397 foreach ($tmpmatches[0] as $tmpemail) {
1398 $tmpemail = strtolower(trim($tmpemail));
1399 if ($tmpemail !==
'') {
1400 $searchfilterexcludeemailarray[] = $tmpemail;
1408 if ($rule[
'type'] ==
'excludedomain') {
1409 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1410 if (is_array($tmpvalues)) {
1411 foreach ($tmpvalues as $tmpvalue) {
1412 $tmpvalue = trim((
string) $tmpvalue);
1413 if ($tmpvalue ===
'') {
1417 if (preg_match_all(
'/[a-z0-9._%+\\-]+@([a-z0-9.\\-]+\\.[a-z]{2,})/i', $tmpvalue, $tmpmatches)) {
1418 foreach ($tmpmatches[1] as $tmpdomain) {
1419 $tmpdomain = strtolower(trim($tmpdomain));
1420 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1421 if ($tmpdomain !==
'') {
1422 $searchfilterexcludedomainarray[] = $tmpdomain;
1428 $tmpdomain = strtolower($tmpvalue);
1429 $tmpdomain = preg_replace(
'/^mailto:/i',
'', $tmpdomain);
1430 $tmpdomain = trim($tmpdomain);
1431 $tmpdomain = trim($tmpdomain,
"<> \t\n\r\0\x0B.,;");
1432 if (strpos($tmpdomain,
'@') === 0) {
1433 $tmpdomain = substr($tmpdomain, 1);
1435 $posat = strrpos($tmpdomain,
'@');
1436 if ($posat !==
false) {
1437 $tmpdomain = substr($tmpdomain, $posat + 1);
1439 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1440 if ($tmpdomain !==
'') {
1441 $searchfilterexcludedomainarray[] = $tmpdomain;
1448 if ($rule[
'type'] ==
'from') {
1449 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1450 if (count($tmprulevaluearray) >= 2) {
1451 foreach ($tmprulevaluearray as $tmprulevalue) {
1452 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1455 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1458 if ($rule[
'type'] ==
'to') {
1459 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1460 if (count($tmprulevaluearray) >= 2) {
1461 foreach ($tmprulevaluearray as $tmprulevalue) {
1462 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1465 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1468 if ($rule[
'type'] ==
'bcc') {
1469 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1471 if ($rule[
'type'] ==
'cc') {
1472 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1474 if ($rule[
'type'] ==
'subject') {
1477 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1479 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1482 if ($rule[
'type'] ==
'body') {
1485 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1487 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1490 if ($rule[
'type'] ==
'header') {
1491 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1503 if ($rule[
'type'] ==
'seen') {
1504 array_push($criteria, array($not.
"SEEN"));
1506 if ($rule[
'type'] ==
'unseen') {
1507 array_push($criteria, array($not.
"UNSEEN"));
1509 if ($rule[
'type'] ==
'unanswered') {
1510 array_push($criteria, array($not.
"UNANSWERED"));
1512 if ($rule[
'type'] ==
'answered') {
1513 array_push($criteria, array($not.
"ANSWERED"));
1515 if ($rule[
'type'] ==
'smaller') {
1516 array_push($criteria, array($not.
"SMALLER"));
1518 if ($rule[
'type'] ==
'larger') {
1519 array_push($criteria, array($not.
"LARGER"));
1523 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1524 $searchfilterdoltrackid++;
1525 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1527 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1528 $searchfilterdoltrackid++;
1529 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1531 if ($rule[
'type'] ==
'withtrackingid') {
1532 $searchfilterdoltrackid++;
1533 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1535 if ($rule[
'type'] ==
'withouttrackingid') {
1536 $searchfilternodoltrackid++;
1537 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1540 if ($rule[
'type'] ==
'isanswer') {
1541 $searchfilterisanswer++;
1542 $searchhead .=
'/References.*@.*/';
1544 if ($rule[
'type'] ==
'isnotanswer') {
1545 $searchfilterisnotanswer++;
1546 $searchhead .=
'! /References.*@.*/';
1549 if ($rule[
'type'] ==
'replyto') {
1550 $searchfilterreplyto++;
1551 $rulesreplyto[] = $rule[
'rulevalue'];
1552 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1556 if (empty($targetdir) || !
getDolGlobalString(
'EMAILCOLLECTOR_NO_FILTER_ON_DATE_IF_THERE_IS_A_TARGETDIR')) {
1558 if ($this->datelastok) {
1559 $fromdate = $this->datelastok;
1561 if ($fromdate > 0) {
1563 array_push($criteria, array(
"SINCE" =>
date(
'j-M-Y', $fromdate - 86400)));
1569 $search = var_export($criteria,
true);
1572 $search =
'UNDELETED';
1573 foreach ($this->filters as $rule) {
1574 if (empty($rule[
'status'])) {
1582 if (!empty($rule[
'rulevalue']) && strpos($rule[
'rulevalue'],
'!') === 0) {
1586 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1589 if ($rule[
'type'] ==
'excludeemail') {
1590 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1591 if (is_array($tmpvalues)) {
1592 foreach ($tmpvalues as $tmpvalue) {
1593 $tmpvalue = trim((
string) $tmpvalue);
1594 if ($tmpvalue ===
'') {
1598 if (preg_match_all(
'/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpvalue, $tmpmatches)) {
1599 foreach ($tmpmatches[0] as $tmpemail) {
1600 $tmpemail = strtolower(trim($tmpemail));
1601 if ($tmpemail !==
'') {
1602 $searchfilterexcludeemailarray[] = $tmpemail;
1610 if ($rule[
'type'] ==
'excludedomain') {
1611 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1612 if (is_array($tmpvalues)) {
1613 foreach ($tmpvalues as $tmpvalue) {
1614 $tmpvalue = trim((
string) $tmpvalue);
1615 if ($tmpvalue ===
'') {
1619 if (preg_match_all(
'/[a-z0-9._%+\\-]+@([a-z0-9.\\-]+\\.[a-z]{2,})/i', $tmpvalue, $tmpmatches)) {
1620 foreach ($tmpmatches[1] as $tmpdomain) {
1621 $tmpdomain = strtolower(trim($tmpdomain));
1622 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1623 if ($tmpdomain !==
'') {
1624 $searchfilterexcludedomainarray[] = $tmpdomain;
1630 $tmpdomain = strtolower($tmpvalue);
1631 $tmpdomain = preg_replace(
'/^mailto:/i',
'', $tmpdomain);
1632 $tmpdomain = trim($tmpdomain);
1633 $tmpdomain = trim($tmpdomain,
"<> \t\n\r\0\x0B.,;");
1634 if (strpos($tmpdomain,
'@') === 0) {
1635 $tmpdomain = substr($tmpdomain, 1);
1637 $posat = strrpos($tmpdomain,
'@');
1638 if ($posat !==
false) {
1639 $tmpdomain = substr($tmpdomain, $posat + 1);
1641 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1642 if ($tmpdomain !==
'') {
1643 $searchfilterexcludedomainarray[] = $tmpdomain;
1650 if ($rule[
'type'] ==
'from') {
1651 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1652 if (count($tmprulevaluearray) >= 2) {
1653 foreach ($tmprulevaluearray as $tmprulevalue) {
1654 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1657 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1660 if ($rule[
'type'] ==
'to') {
1661 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1662 if (count($tmprulevaluearray) >= 2) {
1663 foreach ($tmprulevaluearray as $tmprulevalue) {
1664 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1667 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1670 if ($rule[
'type'] ==
'bcc') {
1671 $search .= ($search ?
' ' :
'').$not.
'BCC';
1673 if ($rule[
'type'] ==
'cc') {
1674 $search .= ($search ?
' ' :
'').$not.
'CC';
1676 if ($rule[
'type'] ==
'subject') {
1679 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1681 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1684 if ($rule[
'type'] ==
'body') {
1687 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1690 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1693 if ($rule[
'type'] ==
'header') {
1694 $search .= ($search ?
' ' :
'').$not.
'HEADER '.$rule[
'rulevalue'];
1706 if ($rule[
'type'] ==
'seen') {
1707 $search .= ($search ?
' ' :
'').$not.
'SEEN';
1709 if ($rule[
'type'] ==
'unseen') {
1710 $search .= ($search ?
' ' :
'').$not.
'UNSEEN';
1712 if ($rule[
'type'] ==
'unanswered') {
1713 $search .= ($search ?
' ' :
'').$not.
'UNANSWERED';
1715 if ($rule[
'type'] ==
'answered') {
1716 $search .= ($search ?
' ' :
'').$not.
'ANSWERED';
1718 if ($rule[
'type'] ==
'smaller') {
1719 $search .= ($search ?
' ' :
'').$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1721 if ($rule[
'type'] ==
'larger') {
1722 $search .= ($search ?
' ' :
'').$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1726 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1727 $searchfilterdoltrackid++;
1728 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1730 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1731 $searchfilterdoltrackid++;
1732 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1734 if ($rule[
'type'] ==
'withtrackingid') {
1735 $searchfilterdoltrackid++;
1736 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1738 if ($rule[
'type'] ==
'withouttrackingid') {
1739 $searchfilternodoltrackid++;
1740 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1743 if ($rule[
'type'] ==
'isanswer') {
1744 $searchfilterisanswer++;
1745 $searchhead .=
'/References.*@.*/';
1747 if ($rule[
'type'] ==
'isnotanswer') {
1748 $searchfilterisnotanswer++;
1749 $searchhead .=
'! /References.*@.*/';
1752 if ($rule[
'type'] ==
'replyto') {
1753 $searchfilterreplyto++;
1754 $rulesreplyto[] = $rule[
'rulevalue'];
1755 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1759 if (empty($targetdir)) {
1761 if ($this->datelastok) {
1762 $fromdate = $this->datelastok;
1764 if ($fromdate > 0) {
1766 $search .= ($search ?
' ' :
'').
'SINCE '.
date(
'j-M-Y', $fromdate - 86400);
1774 if (!empty($searchfilterexcludeemailarray)) {
1775 $searchfilterexcludeemailarray = array_values(array_filter(array_unique($searchfilterexcludeemailarray)));
1776 $searchfilterexcludeemailmap = array_fill_keys($searchfilterexcludeemailarray,
true);
1778 if (!empty($searchfilterexcludedomainarray)) {
1779 $searchfilterexcludedomainarray = array_values(array_filter(array_unique($searchfilterexcludedomainarray)));
1782 $nbemailprocessed = 0;
1785 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1786 $arrayofemail = array();
1795 $tmpsourcedir = $sourcedir;
1800 $f = $client->getFolders(
false, $tmpsourcedir);
1807 foreach ($f as $candidate) {
1808 if ($candidate instanceof Webklex\PHPIMAP\Folder && $candidate->full_name === $tmpsourcedir) {
1809 $folder = $candidate;
1813 if ($folder instanceof Webklex\PHPIMAP\Folder) {
1814 $Query = $folder->messages()->where($criteria);
1818 $this->error =
"Failed to execute getfolders";
1819 $this->errors[] = $this->error;
1820 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1823 }
catch (InvalidWhereQueryCriteriaException $e) {
1824 $this->error = $e->getMessage();
1825 $this->errors[] = $this->error;
1826 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1829 $this->error = $e->getMessage();
1830 $this->errors[] = $this->error;
1831 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1836 if (empty($Query)) {
1838 $this->error =
"Source directory ".$sourcedir.
" not found";
1839 $this->errors[] = $this->error;
1840 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_WARNING);
1844 '@phan-var-force Webklex\PHPIMAP\Query\Query $Query';
1847 $Query->leaveUnread();
1849 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1850 dol_syslog(
"EmailCollector::doCollectOneCollector nb arrayofemail ".(is_array($arrayofemail) ? count($arrayofemail) :
'Not array'));
1852 $this->error = $e->getMessage();
1853 $this->errors[] = $this->error;
1854 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1857 } elseif ($connection !==
false) {
1859 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1861 if ($arrayofemail ===
false) {
1863 $mapoferrrors = imap_errors();
1864 if ($mapoferrrors !==
false) {
1866 $this->error =
"Search string not understood - ".implode(
',', $mapoferrrors);
1867 $this->errors[] = $this->error;
1872 $arrayofemailtodelete = array();
1875 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0 && $connection !==
false) {
1892 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1894 $richarrayofemail = array();
1896 foreach ($arrayofemail as $imapemail) {
1899 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1900 $header = $imapemail->getHeader()->raw;
1901 $overview = $imapemail->getAttributes();
1903 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1904 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1907 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1910 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)(\r\n|\s$)/m', $header, $matches);
1911 $headers = array_combine($matches[1], $matches[2]);
1914 $richarrayofemail[] = array(
'imapemail' => $imapemail,
'header' => $header,
'headers' => $headers,
'overview' => $overview,
'date' => empty($headers[
'Date']) ?
false : strtotime($headers[
'Date']));
1919 $richarrayofemail =
dol_sort_array($richarrayofemail,
'date',
'asc');
1923 foreach ($richarrayofemail as $tmpval) {
1924 if ($nbemailprocessed > 1000) {
1930 $imapemail = $tmpval[
'imapemail'];
1931 $header = $tmpval[
'header'];
1932 $overview = $tmpval[
'overview'];
1933 $headers = $tmpval[
'headers'];
1935 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1936 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1938 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1939 $headers[
'References'] = $headers[
'references'];
1941 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1942 $headers[
'Message-ID'] = $headers[
'message-id'];
1944 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1945 $headers[
'Subject'] = $headers[
'subject'];
1951 $emailto = (
string) $overview[
'to'];
1956 $operationslog .=
'<br>** Process email #'.dol_escape_htmltag((
string) $iforemailloop);
1960 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1962 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1964 $operationslog .=
" - ".dol_escape_htmltag((
string) $imapemail);
1965 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1967 $operationslog .=
" - MsgId: ".$msgid;
1968 $operationslog .=
" - Date: ".($headers[
'Date'] ?? $langs->transnoentitiesnoconv(
"NotFound"));
1969 $operationslog .=
" - References: ".dol_escape_htmltag($headers[
'References'] ?? $langs->transnoentitiesnoconv(
"NotFound")).
" - Subject: ".
dol_escape_htmltag($headers[
'Subject']);
1971 dol_syslog(
"-- Process email #".$iforemailloop.
", MsgId: ".$msgid.
", Date: ".($headers[
'Date'] ??
'').
", References: ".($headers[
'References'] ??
'').
", Subject: ".$headers[
'Subject']);
1974 $trackidfoundintorecipienttype =
'';
1975 $trackidfoundintorecipientid = 0;
1980 if (preg_match(
'/\+(th[i]|ctc|use|mem|sub|proj|tas|con|tic|pro|ord|inv|spro|sor|sin|leav|stockinv|job|surv|salary)([0-9]+)@/', $emailto, $reg)) {
1981 $trackidfoundintorecipienttype = $reg[1];
1982 $trackidfoundintorecipientid = $reg[2];
1983 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1984 $trackidfoundintorecipienttype =
'emailing';
1985 $trackidfoundintorecipientid = $reg[1];
1988 $trackidfoundintomsgidtype =
'';
1989 $trackidfoundintomsgidid = 0;
1994 if (preg_match(
'/(?:[\+\-])(th[i]|ctc|use|mem|sub|proj|tas|con|tic|pro|ord|inv|spro|sor|sin|leav|stockinv|job|surv|salary)([0-9]+)@/', $msgid, $reg)) {
1995 $trackidfoundintomsgidtype = $reg[1];
1996 $trackidfoundintomsgidid = $reg[2];
1997 } elseif (preg_match(
'/(?:[\+\-])emailing-(\w+)@/', $msgid, $reg)) {
1998 $trackidfoundintomsgidtype =
'emailing';
1999 $trackidfoundintomsgidid = $reg[1];
2005 if ($searchfilterdoltrackid > 0) {
2006 $referencesForFilter = $headers[
'References'] ??
'';
2007 if (!empty($headers[
'References']) && !empty($headers[
'In-Reply-To'])) {
2008 $referencesForFilter .=
' ';
2010 $referencesForFilter .= ($headers[
'In-Reply-To'] ??
'');
2012 if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) {
2013 if (empty($referencesForFilter) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $referencesForFilter)) {
2014 $nbemailprocessed++;
2015 dol_syslog(
" Discarded - No suffix in email recipient, and no Header 'References/In-Reply-To' found matching the signature of the application, so with a trackid coming from the application");
2021 if ($searchfilternodoltrackid > 0) {
2022 $referencesForFilter = $headers[
'References'] ??
'';
2023 if (!empty($headers[
'References']) && !empty($headers[
'In-Reply-To'])) {
2024 $referencesForFilter .=
' ';
2026 $referencesForFilter .= ($headers[
'In-Reply-To'] ??
'');
2028 if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($referencesForFilter) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $referencesForFilter))) {
2029 $nbemailprocessed++;
2030 dol_syslog(
" Discarded - Suffix found into email recipient, or Header 'References/In-Reply-To' found and matching signature of application so with a trackid");
2035 if ($searchfilterisanswer > 0) {
2036 $referencesforanswer =
'';
2037 if (!empty($headers[
'References'])) {
2038 $referencesforanswer .= $headers[
'References'].
' ';
2040 if (!empty($headers[
'In-Reply-To'])) {
2041 $referencesforanswer .= $headers[
'In-Reply-To'];
2044 $hasdolibarrreference = 0;
2045 if (!empty($referencesforanswer)) {
2046 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $referencesforanswer)) {
2047 $hasdolibarrreference = 1;
2049 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $referencesforanswer)) {
2050 $hasdolibarrreference = 1;
2056 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
2062 if (!empty($headers[
'In-Reply-To'])) {
2066 if ($hasdolibarrreference) {
2073 $nbemailprocessed++;
2074 dol_syslog(
" Discarded - Email is not an answer (no reply marker detected, and test on In-Reply-To not requested because not reliable, or test on In-Reply-To requested but not found)");
2078 if ($searchfilterisnotanswer > 0) {
2082 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
2087 if (!$isanswer &&
getDolGlobalInt(
'EMAILCOLLECTOR_ISNOTANSWER_USE_REFERENCES') && !empty($headers[
'References'])) {
2090 if (!$isanswer &&
getDolGlobalString(
'EMAILCOLLECTOR_USE_IN_REPLY_TO_TO_DETECT_ANSWERS')) {
2091 if (!empty($headers[
'In-Reply-To'])) {
2098 $nbemailprocessed++;
2099 dol_syslog(
" Discarded - Email is an answer");
2103 if ($searchfilterreplyto > 0) {
2104 if (!empty($headers[
'Reply-To'])) {
2106 foreach ($rulesreplyto as $key => $rulereplyto) {
2107 if (preg_match(
'/'.preg_quote($rulereplyto,
'/').
'/', $headers[
'Reply-To'])) {
2112 if (!$isreplytook || $isreplytook != count($rulesreplyto)) {
2113 $nbemailprocessed++;
2114 dol_syslog(
" Discarded - Reply-to does not match");
2122 $thirdpartystatic =
new Societe($this->db);
2123 $contactstatic =
new Contact($this->db);
2124 $projectstatic =
new Project($this->db);
2126 $nbactiondoneforemail = 0;
2128 $errorforactions = 0;
2129 $thirdpartyfoundby =
'';
2130 $contactfoundby =
'';
2131 $projectfoundby =
'';
2132 $ticketfoundby =
'';
2133 $candidaturefoundby =
'';
2137 $dateformated =
dol_print_date($overview[
'date'],
'dayrfc',
'gmt');
2138 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".$dateformated.
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
2143 dol_syslog(
"msgid=".$overview[0]->message_id.
" date=".
dol_print_date($overview[0]->udate,
'dayrfc',
'gmt').
" from=".$overview[0]->from.
" to=".$overview[0]->to.
" subject=".$overview[0]->subject);
2153 global $htmlmsg, $plainmsg, $charset, $attachments;
2157 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
2160 $htmlmsg = $plainmsg =
'';
2161 $attachments = array();
2163 if ($imapemail->hasHTMLBody()) {
2164 $htmlmsg = $imapemail->getHTMLBody();
2166 if ($imapemail->hasTextBody() && $imapemail->getTextBody() !=
"\n") {
2167 $plainmsg = $imapemail->getTextBody();
2169 if ($imapemail->hasAttachments()) {
2170 $attachments = $imapemail->getAttachments()->all();
2172 $attachments = array();
2175 $getMsg = $this->
getmsg($connection, $imapemail);
2177 $this->errors = array_merge($this->errors, [$this->error]);
2181 '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments';
2191 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
2192 dol_syslog(
" Discarded - Email body is not valid utf8");
2196 if (!empty($searchfilterexcludebodyarray)) {
2197 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
2198 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
2199 $nbemailprocessed++;
2200 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
2201 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
2243 $replytostring =
'';
2247 $replytostring = !empty($headers[
'Reply-To']) ? $this->
decodeSMTPSubject($headers[
'Reply-To']) :
'';
2254 $tmpdate = $overview[
'date']->toDate();
2255 $tmptimezone = $tmpdate->getTimezone()->getName();
2258 if (preg_match(
'/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) {
2259 if ($reg[1] ==
'+' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2260 $dateemail -= (3600 * (int) $reg[2]);
2261 $dateemail -= (60 * (int) $reg[3]);
2263 if ($reg[1] ==
'-' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2264 $dateemail += (3600 * (int) $reg[2]);
2265 $dateemail += (60 * (int) $reg[3]);
2270 $fromstring = (
string) $overview[0]->from;
2271 $replytostring = (!empty($overview[
'in_reply-to']) ? $overview[
'in_reply-to'] : (!empty($headers[
'Reply-To']) ? $headers[
'Reply-To'] :
"")) ;
2273 $sender = !empty($overview[0]->sender) ? $overview[0]->sender :
'';
2274 $to = $overview[0]->to;
2275 $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc :
'';
2276 $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc :
'';
2278 $subject = (
string) $overview[0]->subject;
2281 if (!empty($searchfilterexcludesubjectarray)) {
2282 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
2283 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
2284 $nbemailprocessed++;
2285 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
2286 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
2293 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
2294 $email_from = $reg[2];
2295 $fromtext = $reg[1];
2297 $email_from = $fromstring;
2300 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
2302 $replytotext = $reg[1];
2304 $replyto = $replytostring;
2308 if (!empty($searchfilterexcludeemailmap) || !empty($searchfilterexcludedomainarray)) {
2309 $emailsToCheck = array();
2310 $tmpaddressblob = trim($fromstring.
' '.$replytostring);
2311 if ($tmpaddressblob !==
'' && preg_match_all(
'/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpaddressblob, $tmpmatches)) {
2312 foreach ($tmpmatches[0] as $tmpEmail) {
2313 $tmpEmail = strtolower(trim($tmpEmail));
2314 if ($tmpEmail !==
'') {
2315 $emailsToCheck[$tmpEmail] =
true;
2320 if (empty($emailsToCheck)) {
2321 foreach (array($email_from, $replyto) as $tmpEmail) {
2322 $tmpEmail = strtolower(trim((
string) $tmpEmail));
2323 if ($tmpEmail !==
'' && strpos($tmpEmail,
'@') !==
false) {
2324 $emailsToCheck[$tmpEmail] =
true;
2330 $discardDomain =
'';
2331 $matchedDomainRule =
'';
2333 foreach (array_keys($emailsToCheck) as $tmpEmail) {
2334 if (!empty($searchfilterexcludeemailmap[$tmpEmail])) {
2335 $discardEmail = $tmpEmail;
2339 if (!empty($searchfilterexcludedomainarray)) {
2340 $posat = strrpos($tmpEmail,
'@');
2341 if ($posat ===
false) {
2344 $tmpDomain = strtolower(substr($tmpEmail, $posat + 1));
2345 foreach ($searchfilterexcludedomainarray as $excludedDomain) {
2346 if ($excludedDomain ===
'') {
2349 if ($tmpDomain === $excludedDomain || substr($tmpDomain, -strlen(
'.'.$excludedDomain)) ===
'.'.$excludedDomain) {
2350 $discardDomain = $tmpDomain;
2351 $matchedDomainRule = $excludedDomain;
2358 if ($discardEmail !==
'' || $discardDomain !==
'') {
2359 $nbemailprocessed++;
2360 if ($discardEmail !==
'') {
2361 $operationslog .=
'<br>Discarded - Sender email excluded: '.$discardEmail;
2362 dol_syslog(
" Discarded - Sender email excluded: ".$discardEmail);
2364 $operationslog .=
'<br>Discarded - Sender domain excluded: '.$discardDomain.($matchedDomainRule !==
'' && $matchedDomainRule !== $discardDomain ?
' (matched '.$matchedDomainRule.
')' :
'');
2365 dol_syslog(
" Discarded - Sender domain excluded: ".$discardDomain.($matchedDomainRule !==
'' && $matchedDomainRule !== $discardDomain ?
" (matched ".$matchedDomainRule.
")" :
""));
2372 $fk_element_type =
'';
2389 $objectemail =
null;
2392 $arrayofreferences = array();
2393 if (!empty($headers[
'References'])) {
2394 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
2396 if (!in_array(
'<'.$msgid.
'>', $arrayofreferences)) {
2397 $arrayofreferences = array_merge($arrayofreferences, array(
'<'.$msgid.
'>'));
2402 foreach ($arrayofreferences as $reference) {
2404 if (!empty($trackidfoundintorecipienttype)) {
2405 $resultsearchtrackid = -1;
2406 $reg[1] = $trackidfoundintorecipienttype;
2407 $reg[2] = $trackidfoundintorecipientid;
2408 } elseif (!empty($trackidfoundintomsgidtype)) {
2409 $resultsearchtrackid = -1;
2410 $reg[1] = $trackidfoundintomsgidtype;
2411 $reg[2] = $trackidfoundintomsgidid;
2413 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
2414 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2415 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
2419 if (!empty($resultsearchtrackid)) {
2421 $trackid = $reg[1].$reg[2];
2423 $objectid = $reg[2];
2425 if ($reg[1] ==
'thi') {
2426 $objectemail =
new Societe($this->db);
2428 if ($reg[1] ==
'ctc') {
2429 $objectemail =
new Contact($this->db);
2431 if ($reg[1] ==
'inv') {
2432 $objectemail =
new Facture($this->db);
2434 if ($reg[1] ==
'sinv') {
2437 if ($reg[1] ==
'pro') {
2438 $objectemail =
new Propal($this->db);
2440 if ($reg[1] ==
'ord') {
2441 $objectemail =
new Commande($this->db);
2443 if ($reg[1] ==
'shi') {
2446 if ($reg[1] ==
'spro') {
2449 if ($reg[1] ==
'sord') {
2452 if ($reg[1] ==
'rec') {
2453 $objectemail =
new Reception($this->db);
2455 if ($reg[1] ==
'proj') {
2456 $objectemail =
new Project($this->db);
2457 $projectfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2459 if ($reg[1] ==
'tas') {
2460 $objectemail =
new Task($this->db);
2462 if ($reg[1] ==
'con') {
2463 $objectemail =
new Contact($this->db);
2465 if ($reg[1] ==
'use') {
2466 $objectemail =
new User($this->db);
2468 if ($reg[1] ==
'tic') {
2469 $objectemail =
new Ticket($this->db);
2470 $ticketfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2472 if ($reg[1] ==
'recruitmentcandidature') {
2474 $candidaturefoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2476 if ($reg[1] ==
'mem') {
2477 $objectemail =
new Adherent($this->db);
2485 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
2488 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket";
2489 $sql .=
" WHERE email_msgid = '".$this->db->escape($reg[1]).
"' OR origin_references LIKE '%".$this->db->escape($this->db->escapeforlike($reg[1])).
"%'";
2490 $resql = $this->db->query($sql);
2492 $obj = $this->db->fetch_object($resql);
2494 $objectid = $obj->rowid;
2495 $objectemail =
new Ticket($this->db);
2496 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2503 if (!is_object($objectemail) &&
isModEnabled(
'project')) {
2504 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2505 $resql = $this->db->query($sql);
2507 $obj = $this->db->fetch_object($resql);
2509 $objectid = $obj->rowid;
2510 $objectemail =
new Project($this->db);
2511 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2518 if (!is_object($objectemail) &&
isModEnabled(
'recruitment')) {
2519 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2520 $resql = $this->db->query($sql);
2522 $obj = $this->db->fetch_object($resql);
2524 $objectid = $obj->rowid;
2526 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2535 if (is_object($objectemail)) {
2536 $result = $objectemail->fetch($objectid);
2538 $fk_element_id = $objectemail->id;
2539 $fk_element_type = $objectemail->element;
2541 if ($fk_element_type ==
'facture') {
2542 $fk_element_type =
'invoice';
2545 if (get_class($objectemail) !=
'Societe') {
2546 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2548 $thirdpartyid = $objectemail->id;
2551 if (get_class($objectemail) !=
'Contact') {
2552 $contactid = $objectemail->fk_socpeople;
2554 $contactid = $objectemail->id;
2557 if (get_class($objectemail) !=
'Project') {
2558 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2560 $projectid = $objectemail->id;
2563 if ($objectemail instanceof
Ticket) {
2564 $ticketid = $objectemail->id;
2566 $changeonticket_references =
false;
2567 if (empty($trackid)) {
2568 $trackid = $objectemail->track_id;
2570 if (empty($objectemail->origin_references)) {
2571 $objectemail->origin_references = !empty($headers[
'References']) ? $headers[
'References'] :
null;
2572 $changeonticket_references =
true;
2574 foreach ($arrayofreferences as $key => $referencetmp) {
2575 if (!str_contains($objectemail->origin_references, $referencetmp)) {
2576 $objectemail->origin_references .=
" ".$referencetmp;
2577 $changeonticket_references =
true;
2581 if ($changeonticket_references) {
2582 $operationslog .=
'<br>We complete ticket ID='.$ticketid.
' with property origin_references='.$objectemail->origin_references;
2583 $objectemail->update($user, 1);
2590 if ($projectid > 0) {
2591 $result = $projectstatic->fetch($projectid);
2593 $projectstatic->id = 0;
2595 $projectid = $projectstatic->id;
2597 $projectfoundby =
'trackid ('.$trackid.
')';
2602 if (empty($thirdpartyid)) {
2603 $thirdpartyid = $projectstatic->socid;
2608 if ($contactid > 0) {
2609 $result = $contactstatic->fetch($contactid);
2611 $contactstatic->id = 0;
2613 $contactid = $contactstatic->id;
2615 $contactfoundby =
'trackid ('.$trackid.
')';
2617 if (empty($thirdpartyid)) {
2618 $thirdpartyid = $contactstatic->fk_soc;
2623 if ($thirdpartyid > 0) {
2624 $result = $thirdpartystatic->fetch($thirdpartyid);
2626 $thirdpartystatic->id = 0;
2628 $thirdpartyid = $thirdpartystatic->id;
2630 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2635 if (is_object($objectemail)) {
2640 if (empty($contactid)) {
2641 $result = $contactstatic->fetch(0,
null,
'', $email_from);
2644 dol_syslog(
"We found a contact with the email ".$email_from);
2645 $contactid = $contactstatic->id;
2646 $contactfoundby =
'email of contact ('.$email_from.
')';
2647 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2648 $result = $thirdpartystatic->fetch($contactstatic->socid);
2650 $thirdpartyid = $thirdpartystatic->id;
2651 $thirdpartyfoundby =
'email of contact ('.$email_from.
')';
2657 if (empty($thirdpartyid)) {
2658 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $email_from);
2660 dol_syslog(
"We found a thirdparty with the email ".$email_from);
2661 $thirdpartyid = $thirdpartystatic->id;
2662 $thirdpartyfoundby =
'email ('.$email_from.
')';
2697 $savedattachments = array();
2698 $savedattachmentsdir =
'';
2699 $savedattachmentsnote =
'';
2700 if (empty($mode) && !empty($attachments) && $fk_element_id > 0 && $fk_element_type ===
'order_supplier' && $objectemail instanceof
CommandeFournisseur) {
2701 $orderref = isset($objectemail->ref) ? (
string) $objectemail->ref :
'';
2702 if ($orderref !==
'' && !empty(
$conf->fournisseur->commande)) {
2703 $entityforobject = isset($objectemail->entity) ? (int) $objectemail->entity : (int)
$conf->entity;
2704 $basedir = (!empty(
$conf->fournisseur->commande->multidir_output[$entityforobject]) ?
$conf->fournisseur->commande->multidir_output[$entityforobject] :
$conf->fournisseur->commande->dir_output);
2706 $savedattachments = $this->saveEmailCollectorAttachmentsToDir($savedattachmentsdir, $attachments);
2707 if (!empty($savedattachments)) {
2708 $operationslog .=
'<br>Saved '.count($savedattachments).
' attachment(s) into '.
dol_escape_htmltag($savedattachmentsdir);
2712 if (!empty($savedattachments)) {
2714 foreach ($savedattachments as $attmeta) {
2715 if (!is_array($attmeta) || empty($attmeta[
'name'])) {
2718 $names[] = (
string) $attmeta[
'name'];
2720 if (!empty($names)) {
2721 $savedattachmentsnote = $langs->trans(
"NbOfAttachedFiles").
' : '.count($names);
2722 $savedattachmentsnote .=
' ('.implode(
', ', array_slice($names, 0, 10)).(count($names) > 10 ?
'...' :
'').
')';
2729 foreach ($this->actions as $operation) {
2730 $errorforthisaction = 0;
2731 $ticketalreadyexists = 0;
2732 if ($errorforactions) {
2735 if (empty($operation[
'status'])) {
2739 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2742 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2743 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2746 $actioncode =
'EMAIL_IN';
2748 if (preg_match(
'/Sent$/', $sourcedir) || preg_match(
'/envoyés$/i', $sourcedir)) {
2749 $actioncode =
'EMAIL';
2752 $arrayofemailtoconsidersender = array_filter(array_map(
'trim', explode(
',',
getDolGlobalString(
'MAIL_FROM_EMAILS_TO_CONSIDER_SENDING'))));
2753 foreach ($arrayofemailtoconsidersender as $emailtoconsidersender) {
2754 if ($emailtoconsidersender ===
'') {
2757 if (preg_match(
'/'.preg_quote($emailtoconsidersender,
'/').
'/', $fromstring)) {
2758 $actioncode =
'EMAIL';
2761 $operationslog .=
'<br>Email will have actioncode='.$actioncode;
2763 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2765 $descriptiontitle = $langs->transnoentitiesnoconv(
"RecordCreatedByEmailCollector", $this->
ref);
2770 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2772 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2774 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2776 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailReply").($langs->trans(
"MailReply") !=
'Reply to' ?
' (Reply to)' :
'').
' : '.
dol_escape_htmltag($replyto));
2779 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2781 if ($savedattachmentsnote) {
2782 $descriptionmeta =
dol_concatdesc($descriptionmeta, $savedattachmentsnote);
2785 if ($operation[
'type'] ==
'ticket') {
2787 $tickettocreate =
new Ticket($this->db);
2788 $errorfetchticket = 0;
2789 $alreadycreated = 0;
2790 if (!empty($objectid) && $objectemail instanceof
Ticket) {
2791 $alreadycreated = $tickettocreate->fetch((
int) $objectid);
2793 if ($alreadycreated == 0 && $ticketid > 0) {
2794 $alreadycreated = $tickettocreate->fetch($ticketid);
2796 if ($alreadycreated == 0 && !empty($trackid)) {
2797 $alreadycreated = $tickettocreate->fetch(0,
'', $trackid);
2799 if ($alreadycreated == 0 && !empty($msgid)) {
2800 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2802 if ($alreadycreated < 0) {
2803 $errorfetchticket++;
2805 if (empty($errorfetchticket)) {
2806 if ($alreadycreated == 0) {
2807 $operationslog .=
'<br>Ticket not found using trackid='.$trackid.
' or msgid='.$msgid;
2808 $ticketalreadyexists = 0;
2810 $operationslog .=
'<br>Ticket already found using trackid='.$trackid.
' or msgid='.$msgid.
", we replace operation 'ticket' with 'recordevent' to add a new message";
2811 $ticketalreadyexists = 1;
2812 $operation[
'type'] =
'recordevent';
2815 $ticketalreadyexists = -1;
2822 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2823 if ($thirdpartyid > 0) {
2825 $idtouseforthirdparty = $thirdpartyid;
2826 $operationslog .=
'<br>We already have found a related thirdparty id, so we bypass the action loadthirdparty and use idtouseforthirdparty='.$idtouseforthirdparty;
2827 } elseif (empty($operation[
'actionparam'])) {
2829 $this->error =
"Action loadthirdparty or loadandcreatethirdparty has empty parameter. Must be a rule like 'name=HEADER:^From:(.*);' or 'name=SET:xxx' or 'name=EXTRACT:(body|subject):regex where 'name' can be replaced with 'id' or 'email' to define how to set or extract data. More properties can also be set, for example client=SET:2;";
2830 $this->errors[] = $this->error;
2832 $actionparam = $operation[
'actionparam'];
2833 $idtouseforthirdparty =
'';
2834 $nametouseforthirdparty =
'';
2835 $emailtouseforthirdparty =
'';
2836 $namealiastouseforthirdparty =
'';
2838 $operationslog .=
'<br>Loop on each property to set into actionparam';
2842 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2846 $regforregex = array();
2848 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2849 $sourcefield = $regforregex[1];
2850 $regexstring = $regforregex[2];
2853 if (!empty($sourcefield) && !empty($regexstring)) {
2854 if (strtolower($sourcefield) ==
'body') {
2855 $sourcestring = $messagetext;
2856 } elseif (strtolower($sourcefield) ==
'subject') {
2857 $sourcestring = $subject;
2858 } elseif (strtolower($sourcefield) ==
'header') {
2859 $sourcestring = $header;
2862 if ($sourcestring) {
2863 $regforval = array();
2864 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2866 if ($propertytooverwrite ==
'id') {
2867 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2869 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2870 } elseif ($propertytooverwrite ==
'email') {
2871 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2873 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2874 } elseif ($propertytooverwrite ==
'name') {
2875 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2877 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2878 } elseif ($propertytooverwrite ==
'name_alias') {
2879 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2881 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2883 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> We discard this, not a field used to search an existing thirdparty';
2887 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2888 $idtouseforthirdparty =
null;
2889 $nametouseforthirdparty =
null;
2890 $emailtouseforthirdparty =
null;
2891 $namealiastouseforthirdparty =
null;
2893 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2895 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2901 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2902 $this->errors[] = $this->error;
2904 $operationslog .=
'<br>'.$this->error;
2906 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2910 if ($propertytooverwrite ==
'id') {
2911 $idtouseforthirdparty = $reg[2];
2913 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2914 } elseif ($propertytooverwrite ==
'email') {
2915 $emailtouseforthirdparty = $reg[2];
2917 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2918 } elseif ($propertytooverwrite ==
'name') {
2919 $nametouseforthirdparty = $reg[2];
2921 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2922 } elseif ($propertytooverwrite ==
'name_alias') {
2923 $namealiastouseforthirdparty = $reg[2];
2925 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2929 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2930 $this->errors[] = $this->error;
2935 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2937 $operationslog .=
'<br>We have this initial main data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty.
'.';
2940 $tmpobject->element =
'generic';
2941 $tmpobject->id = $idtouseforthirdparty;
2942 $tmpobject->name = $nametouseforthirdparty;
2943 $tmpobject->name_alias = $namealiastouseforthirdparty;
2944 $tmpobject->email = $emailtouseforthirdparty;
2948 $idtouseforthirdparty = $tmpobject->id;
2949 $nametouseforthirdparty = $tmpobject->name;
2950 $namealiastouseforthirdparty = $tmpobject->name_alias;
2951 $emailtouseforthirdparty = $tmpobject->email;
2953 $operationslog .=
'<br>We try to search existing thirdparty with idtouseforthirdparty='.$idtouseforthirdparty.
' emailtouseforthirdparty='.$emailtouseforthirdparty.
' nametouseforthirdparty='.$nametouseforthirdparty.
' namealiastouseforthirdparty='.$namealiastouseforthirdparty;
2956 $result = $thirdpartystatic->findNearest((
int) $idtouseforthirdparty, (
string) $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', (
string) $emailtouseforthirdparty, (
string) $namealiastouseforthirdparty);
2959 if (
getDolGlobalInt(
'EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE') && $result == -2) {
2960 $idtouseforthirdparty =
getDolGlobalInt(
'EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE');
2962 $thirdpartystatic->fetch($idtouseforthirdparty);
2964 dol_syslog(
'Thirdparty found twice (or more) so, according to option EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE, we will use the generic one with id = '.
dol_escape_htmltag((
string) $thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name));
2966 $operationslog .=
'<br>Thirdparty found twice (or more) so, according to option EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE, we will use the generic one with id = '.dol_escape_htmltag((
string) $thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name);
2969 $this->error =
'Error when getting thirdparty with name '.((string) $nametouseforthirdparty).
', alternative name '.((
string) $namealiastouseforthirdparty).
' and email '.$emailtouseforthirdparty.
' (may be 2 record exists with same name ?)';
2970 $this->errors[] = $this->error;
2975 if ($operation[
'type'] ==
'loadthirdparty') {
2976 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2979 $resultContact = $contactstatic->findNearest(0,
'',
'',
'', (
string) $emailtouseforthirdparty,
'', 0);
2980 if ($resultContact > 0) {
2981 $contactstatic->fetch($resultContact);
2982 $idtouseforthirdparty = $contactstatic->socid;
2983 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2985 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2988 $langs->load(
"errors");
2989 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', (
string) $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2990 $this->errors[] = $this->error;
2994 $langs->load(
"errors");
2995 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', (
string) $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2996 $this->errors[] = $this->error;
2998 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2999 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
3002 $thirdpartystatic =
new Societe($db);
3003 $thirdpartystatic->name = (
string) $nametouseforthirdparty;
3004 if (!empty($namealiastouseforthirdparty)) {
3005 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
3006 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
3009 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'' : $fromtext) : $replytostring);
3011 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($email_from) ?
'' : $email_from) : $replyto) : $emailtouseforthirdparty);
3014 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3016 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
3017 $thirdpartystatic->code_client =
'auto';
3019 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
3020 $thirdpartystatic->code_fournisseur =
'auto';
3023 if ($errorforthisaction) {
3026 $result = $thirdpartystatic->create($user);
3029 $this->error = $thirdpartystatic->error;
3030 $this->errors = $thirdpartystatic->errors;
3032 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag((
string) $thirdpartystatic->id);
3036 } elseif ($result > 0) {
3037 dol_syslog(
"One and only one existing third party has been found");
3039 $thirdpartystatic->fetch($result);
3041 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag((
string) $thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name);
3045 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
3046 if (empty($operation[
'actionparam'])) {
3048 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
3049 $this->errors[] = $this->error;
3051 $contact_static =
new Contact($this->db);
3053 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3054 if ($errorforthisaction) {
3057 if (!empty($contact_static->email) && $contact_static->email != $email_from) {
3058 $email_from = $contact_static->email;
3060 $email_from = (
string) $email_from;
3062 $email_from = (
string) $email_from;
3064 $result = $contactstatic->fetch(0,
null,
'', $email_from);
3067 $this->error =
'Error when getting contact with email ' . $email_from;
3068 $this->errors[] = $this->error;
3070 } elseif ($result == 0) {
3071 dol_syslog(
"Contact with email " . $email_from .
" was not found. We try to create it.");
3072 $contactstatic =
new Contact($this->db);
3075 $contactstatic->email = $email_from;
3076 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($email_from);
3079 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3081 if ($errorforthisaction) {
3085 if (!empty($contactstatic->country)) {
3086 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
3087 $result =
getCountry(
'',
'3', $this->db,
null, 1, $contactstatic->country);
3088 if ($result ==
'NotDefined') {
3090 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
3091 } elseif (!($result > 0)) {
3093 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
3094 $this->errors[] = $this->db->lasterror();
3096 $contactstatic->country_id = $result;
3097 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
3099 } elseif (!empty($contactstatic->country_code)) {
3100 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
3101 $result =
getCountry($contactstatic->country_code,
'3', $this->db);
3102 if ($result ==
'NotDefined') {
3104 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
3105 } elseif (!($result > 0)) {
3107 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
3108 $this->errors[] = $this->db->lasterror();
3110 $contactstatic->country_id = $result;
3111 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
3115 if (!$errorforactions) {
3117 if (!empty($contactstatic->state)) {
3118 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
3119 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
3120 if (empty($result)) {
3122 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
3123 } elseif (!($result > 0)) {
3125 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
3126 $this->errors[] = $this->db->lasterror();
3128 $contactstatic->state_id = $result;
3129 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
3131 } elseif (!empty($contactstatic->state_code)) {
3132 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
3133 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
3134 if (empty($result)) {
3136 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
3137 } elseif (!($result > 0)) {
3139 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
3140 $this->errors[] = $this->db->lasterror();
3142 $contactstatic->state_id = $result;
3143 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
3148 if (!$errorforactions) {
3149 $result = $contactstatic->create($user);
3152 $this->error = $contactstatic->error;
3153 $this->errors = $contactstatic->errors;
3155 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag((
string) $contactstatic->id);
3162 } elseif ($operation[
'type'] ==
'recordevent') {
3166 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
3167 if ($alreadycreated == 0) {
3168 $operationslog .=
'<br>We did not find existing actioncomm with msgid='.$msgid;
3170 if ($projectstatic->id > 0) {
3171 if ($projectfoundby) {
3172 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
3175 if ($thirdpartystatic->id > 0) {
3176 if ($thirdpartyfoundby) {
3177 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3180 if ($contactstatic->id > 0) {
3181 if ($contactfoundby) {
3182 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3186 $description = $descriptiontitle;
3192 $descriptionfull = $description;
3194 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3199 $actioncomm->type_code =
'AC_OTH_AUTO';
3200 $actioncomm->code =
'AC_'.$actioncode;
3201 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$email_from;
3202 $actioncomm->note_private = $descriptionfull;
3203 $actioncomm->fk_project = $projectstatic->id;
3204 $actioncomm->datep = $dateemail;
3205 $actioncomm->datef = $dateemail;
3206 $actioncomm->percentage = -1;
3207 $actioncomm->socid = $thirdpartystatic->id;
3208 $actioncomm->contact_id = $contactstatic->id;
3209 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array());
3210 $actioncomm->authorid = $user->id;
3211 $actioncomm->userownerid = $user->id;
3213 $actioncomm->email_msgid = $msgid;
3214 $actioncomm->email_from = $fromstring;
3215 $actioncomm->email_sender = $sender;
3216 $actioncomm->email_to = $to;
3217 $actioncomm->email_tocc = $sendtocc;
3218 $actioncomm->email_tobcc = $sendtobcc;
3219 $actioncomm->email_subject = $subject;
3220 $actioncomm->errors_to =
'';
3222 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
3223 $actioncomm->fk_element = $fk_element_id;
3224 $actioncomm->elementid = $fk_element_id;
3225 $actioncomm->elementtype = $fk_element_type;
3226 if (is_object($objectemail) && $objectemail->module) {
3227 $actioncomm->elementtype .=
'@'.$objectemail->module;
3234 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3236 if ($errorforthisaction) {
3239 $result = $actioncomm->create($user);
3242 $this->errors = $actioncomm->errors;
3244 if ($fk_element_type ==
"ticket" && is_object($objectemail)) {
3245 if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED || $objectemail->status == Ticket::STATUS_NEED_MORE_INFO || $objectemail->status == Ticket::STATUS_WAITING) {
3246 if ($objectemail->fk_user_assign !=
null) {
3247 $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED);
3249 $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ);
3253 $operationslog .=
'<br>Ticket Re-Opened successfully -> ref='.$objectemail->ref;
3256 $this->error =
'Error while changing the ticket status -> ref='.$objectemail->ref;
3257 $this->errors[] = $this->error;
3260 if (!empty($attachments)) {
3262 $ticket =
new Ticket($this->db);
3263 $ticket->fetch($fk_element_id);
3264 $destdir =
$conf->ticket->dir_output.
'/'.$ticket->ref;
3269 foreach ($attachments as $attachment) {
3271 $filename = (
string) $attachment->getName();
3272 }
catch (Throwable $e) {
3275 $this->
saveAttachment($destdir, $filename, (
string) $attachment->getContent());
3278 $this->
getmsg($connection, $imapemail, $destdir);
3283 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag((
string) $actioncomm->id);
3287 $operationslog .=
'<br>An event in actioncomm table already exists for the msgid = '.$msgid.
' so we bypass this action.';
3289 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
3292 foreach ($attachments as $attachment) {
3293 if ($attachment->getName() ===
'undefined') {
3296 $data[$attachment->getName()] = $attachment->getContent();
3300 foreach ($pj as $key => $val) {
3301 $data[$val[
'filename']] =
getFileData($imapemail, (
string) $val[
'pos'], $val[
'type'], $connection);
3304 if (count($data) > 0) {
3305 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($email_from).
"%'";
3306 $resql = $this->db->query($sql);
3307 if ($this->db->num_rows($resql) == 0) {
3308 $this->errors[] =
"User Not allowed to add documents ({$email_from})";
3310 $arrayobject = array(
3311 'propale' => array(
'table' =>
'propal',
3312 'fields' => array(
'ref'),
3313 'class' =>
'comm/propal/class/propal.class.php',
3314 'object' =>
'Propal'),
3315 'holiday' => array(
'table' =>
'holiday',
3316 'fields' => array(
'ref'),
3317 'class' =>
'holiday/class/holiday.class.php',
3318 'object' =>
'Holiday'),
3319 'expensereport' => array(
'table' =>
'expensereport',
3320 'fields' => array(
'ref'),
3321 'class' =>
'expensereport/class/expensereport.class.php',
3322 'object' =>
'ExpenseReport'),
3323 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
3324 'fields' => array(
'ref'),
3325 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
3326 'object' =>
'RecruitmentJobPosition'),
3327 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
3328 'fields' => array(
'ref'),
3329 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
3330 'object' =>
'RecruitmentCandidature'),
3331 'societe' => array(
'table' =>
'societe',
3332 'fields' => array(
'code_client',
'code_fournisseur'),
3333 'class' =>
'societe/class/societe.class.php',
3334 'object' =>
'Societe'),
3335 'commande' => array(
'table' =>
'commande',
3336 'fields' => array(
'ref'),
3337 'class' =>
'commande/class/commande.class.php',
3338 'object' =>
'Commande'),
3339 'expedition' => array(
'table' =>
'expedition',
3340 'fields' => array(
'ref'),
3341 'class' =>
'expedition/class/expedition.class.php',
3342 'object' =>
'Expedition'),
3343 'contract' => array(
'table' =>
'contrat',
3344 'fields' => array(
'ref'),
3345 'class' =>
'contrat/class/contrat.class.php',
3346 'object' =>
'Contrat'),
3347 'fichinter' => array(
'table' =>
'fichinter',
3348 'fields' => array(
'ref'),
3349 'class' =>
'fichinter/class/fichinter.class.php',
3350 'object' =>
'Fichinter'),
3351 'ticket' => array(
'table' =>
'ticket',
3352 'fields' => array(
'ref'),
3353 'class' =>
'ticket/class/ticket.class.php',
3354 'object' =>
'Ticket'),
3355 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
3356 'fields' => array(
'ref'),
3357 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
3358 'object' =>
'KnowledgeRecord'),
3359 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
3360 'fields' => array(
'ref'),
3361 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
3362 'object' =>
'SupplierProposal'),
3363 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
3364 'fields' => array(
'ref',
'ref_supplier'),
3365 'class' =>
'fourn/class/fournisseur.commande.class.php',
3366 'object' =>
'SupplierProposal'),
3367 'facture' => array(
'table' =>
'facture',
3368 'fields' => array(
'ref'),
3369 'class' =>
'compta/facture/class/facture.class.php',
3370 'object' =>
'Facture'),
3371 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
3372 'fields' => array(
'ref',
'ref_client'),
3373 'class' =>
'fourn/class/fournisseur.facture.class.php',
3374 'object' =>
'FactureFournisseur'),
3375 'produit' => array(
'table' =>
'product',
3376 'fields' => array(
'ref'),
3377 'class' =>
'product/class/product.class.php',
3378 'object' =>
'Product'),
3379 'productlot' => array(
'table' =>
'product_lot',
3380 'fields' => array(
'batch'),
3381 'class' =>
'product/stock/class/productlot.class.php',
3382 'object' =>
'Productlot'),
3383 'projet' => array(
'table' =>
'projet',
3384 'fields' => array(
'ref'),
3385 'class' =>
'projet/class/projet.class.php',
3386 'object' =>
'Project'),
3387 'projet_task' => array(
'table' =>
'projet_task',
3388 'fields' => array(
'ref'),
3389 'class' =>
'projet/class/task.class.php',
3390 'object' =>
'Task'),
3391 'ressource' => array(
'table' =>
'resource',
3392 'fields' => array(
'ref'),
3393 'class' =>
'ressource/class/dolressource.class.php',
3394 'object' =>
'Dolresource'),
3395 'bom' => array(
'table' =>
'bom_bom',
3396 'fields' => array(
'ref'),
3397 'class' =>
'bom/class/bom.class.php',
3399 'mrp' => array(
'table' =>
'mrp_mo',
3400 'fields' => array(
'ref'),
3401 'class' =>
'mrp/class/mo.class.php',
3405 if (!is_object($hookmanager)) {
3406 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3409 $hookmanager->initHooks(array(
'emailcolector',
'emailcollector'));
3410 $parameters = array(
'arrayobject' => $arrayobject);
3411 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
3413 $arrayobject = $hookmanager->resArray;
3416 $resultobj = array();
3418 foreach ($arrayobject as $key => $objectdesc) {
3419 $sql =
'SELECT DISTINCT t.rowid ';
3420 $sql .=
' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc[
'table']) .
' AS t';
3422 foreach ($objectdesc[
'fields'] as $field) {
3423 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $this->db->sanitize($field) .
", '%') AND t." . $this->db->sanitize($field) .
" <> '') OR ";
3425 $sql = substr($sql, 0, -4);
3427 $ressqlobj = $this->db->query($sql);
3429 while ($obj = $this->db->fetch_object($ressqlobj)) {
3430 $resultobj[$key][] = $obj->rowid;
3435 foreach ($resultobj as $mod => $ids) {
3436 $moddesc = $arrayobject[$mod];
3437 $elementpath = $mod;
3439 $objectmanaged =
new $moddesc[
'object']($this->db);
3440 '@phan-var-force CommonObject $objectmanaged';
3441 foreach ($ids as $val) {
3442 $res = $objectmanaged->fetch($val);
3444 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
3445 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
3447 $this->errors[] =
'object not found';
3451 foreach ($dirs as $target) {
3452 $prefix = $this->actions[$this->id][
'actionparam'];
3453 foreach ($data as $filename => $content) {
3454 $resr = $this->
saveAttachment($target, $prefix .
'_' . $filename, $content);
3456 $this->errors[] =
'Doc not saved';
3461 $operationslog .=
'<br>Save attachment files on disk';
3463 $this->errors[] =
'no joined piece';
3465 $operationslog .=
'<br>No joinded files';
3467 } elseif ($operation[
'type'] ==
'project') {
3469 $projecttocreate =
new Project($this->db);
3470 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
3471 if ($alreadycreated == 0) {
3472 if ($thirdpartystatic->id > 0) {
3473 $projecttocreate->socid = $thirdpartystatic->id;
3474 if ($thirdpartyfoundby) {
3475 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3478 if ($contactstatic->id > 0) {
3479 $projecttocreate->contact_id = $contactstatic->id;
3480 if ($contactfoundby) {
3481 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3485 $description = $descriptiontitle;
3491 $descriptionfull = $description;
3493 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3497 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
3498 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
3500 $projecttocreate->title = $subject;
3501 $projecttocreate->date_start = $dateemail;
3502 $projecttocreate->date_end = 0;
3503 $projecttocreate->opp_status = $id_opp_status;
3504 $projecttocreate->opp_percent = $percent_opp_status;
3506 $projecttocreate->note_private = $descriptionfull;
3507 $projecttocreate->entity =
$conf->entity;
3509 $projecttocreate->email_date = $dateemail;
3510 $projecttocreate->email_msgid = $msgid;
3511 $projecttocreate->email_from = $fromstring;
3512 $projecttocreate->email_sender = $sender;
3513 $projecttocreate->email_to = $to;
3514 $projecttocreate->email_tocc = $sendtocc;
3515 $projecttocreate->email_tobcc = $sendtobcc;
3516 $projecttocreate->email_subject = $subject;
3517 $projecttocreate->errors_to =
'';
3519 $savesocid = $projecttocreate->socid;
3523 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3527 if (empty($projecttocreate->ref)) {
3536 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
3537 foreach ($dirmodels as $reldir) {
3538 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
3539 if (file_exists($file)) {
3540 $classname = $modele;
3545 if ($classname !==
'') {
3546 if ($savesocid > 0) {
3547 if ($savesocid != $projecttocreate->socid) {
3549 setEventMessages(
'You loaded a thirdparty (id='.$savesocid.
') and you force another thirdparty id (id='.$projecttocreate->socid.
') by setting socid in operation with a different value',
null,
'errors');
3552 if ($projecttocreate->socid > 0) {
3553 $thirdpartystatic->fetch($projecttocreate->socid);
3557 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
3558 $modModuleToUseForNextValue =
new $classname();
3559 '@phan-var-force ModeleNumRefProjects $modModuleToUseForNextValue';
3560 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
3562 $projecttocreate->ref = $defaultref;
3566 if ($errorforthisaction) {
3569 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
3571 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3573 $operationslog .=
'<br>'.$this->error;
3576 $result = $projecttocreate->create($user);
3579 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
3580 $this->errors = $projecttocreate->errors;
3582 $operationslog .=
'<br>'.$this->error;
3585 $destdir =
$conf->project->dir_output.
'/'.$projecttocreate->ref;
3590 foreach ($attachments as $attachment) {
3592 $typeattachment = (
string) $attachment->getDisposition();
3593 $filename = $attachment->getName();
3594 $content = $attachment->getContent();
3598 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3600 $this->errors = array_merge($this->errors, [$this->error]);
3605 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3607 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3615 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3617 } elseif ($operation[
'type'] ==
'ticket') {
3619 $tickettocreate =
new Ticket($this->db);
3620 if ($ticketalreadyexists == 0) {
3621 if ($thirdpartystatic->id > 0) {
3622 $tickettocreate->socid = $thirdpartystatic->id;
3623 $tickettocreate->fk_soc = $thirdpartystatic->id;
3624 if ($thirdpartyfoundby) {
3625 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3628 if ($contactstatic->id > 0) {
3629 $tickettocreate->contact_id = $contactstatic->id;
3630 if ($contactfoundby) {
3631 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3635 $description = $descriptiontitle;
3641 $descriptionfull = $description;
3643 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3647 $tickettocreate->subject = $subject;
3648 $tickettocreate->message = $description;
3650 $tickettocreate->category_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1)));
3651 $tickettocreate->severity_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1)));
3652 $tickettocreate->origin_email = $email_from;
3653 $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto :
null);
3654 $tickettocreate->origin_references = (!empty($headers[
'References']) ? $headers[
'References'] :
null);
3655 $tickettocreate->fk_user_create = $user->id;
3656 $tickettocreate->datec =
dol_now();
3657 $tickettocreate->fk_project = $projectstatic->id;
3658 $tickettocreate->notify_tiers_at_create =
getDolGlobalInt(
'TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3659 $tickettocreate->note_private = $descriptionfull;
3660 $tickettocreate->entity =
$conf->entity;
3662 $tickettocreate->email_date = $dateemail;
3663 $tickettocreate->email_msgid = $msgid;
3664 $tickettocreate->email_from = $fromstring;
3665 $tickettocreate->email_sender = $sender;
3666 $tickettocreate->email_to = $to;
3667 $tickettocreate->email_tocc = $sendtocc;
3668 $tickettocreate->email_tobcc = $sendtobcc;
3669 $tickettocreate->email_subject = $subject;
3670 $tickettocreate->errors_to =
'';
3674 $savesocid = $tickettocreate->socid;
3678 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3680 $modele =
'UNDEFINED';
3682 if (empty($tickettocreate->ref)) {
3691 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
3692 foreach ($dirmodels as $reldir) {
3693 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3694 if (file_exists($file)) {
3695 $classname = $modele;
3700 if ($classname !==
'') {
3701 if ($savesocid > 0) {
3702 if ($savesocid != $tickettocreate->socid) {
3704 setEventMessages(
'You loaded a thirdparty (id='.$savesocid.
') and you force another thirdparty id (id='.$tickettocreate->socid.
') by setting socid in operation with a different value',
null,
'errors');
3707 if ($tickettocreate->socid > 0) {
3708 $thirdpartystatic->fetch($tickettocreate->socid);
3713 $modModuleToUseForNextValue =
new $classname();
3714 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3715 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3717 $tickettocreate->ref = $defaultref;
3720 if ($errorforthisaction) {
3723 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3725 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3728 $tickettocreate->context[
'actionmsg2'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3729 $tickettocreate->context[
'actionmsg'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3733 $sender_contact =
new Contact($this->db);
3734 $sender_contact->fetch(0,
null,
'', $email_from);
3735 if (!empty($sender_contact->id)) {
3736 $tickettocreate->context[
'contact_id'] = $sender_contact->id;
3739 $result = $tickettocreate->create($user);
3742 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3743 $this->errors = $tickettocreate->errors;
3746 $destdir =
$conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3751 foreach ($attachments as $attachment) {
3753 $typeattachment = (
string) $attachment->getDisposition();
3754 $filename = $attachment->getName();
3755 $content = $attachment->getContent();
3759 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3761 $this->errors = array_merge($this->errors, [$this->error]);
3766 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3768 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3777 $operationslog .=
'<br>Ticket already exists, so we bypass action "ticket"';
3779 } elseif ($operation[
'type'] ==
'candidature') {
3783 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3784 if ($alreadycreated == 0) {
3785 $description = $descriptiontitle;
3791 $descriptionfull = $description;
3793 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3797 $candidaturetocreate->subject = $subject;
3798 $candidaturetocreate->message = $description;
3799 $candidaturetocreate->type_code = 0;
3800 $candidaturetocreate->category_code =
null;
3801 $candidaturetocreate->severity_code =
null;
3802 $candidaturetocreate->email = $email_from;
3804 $candidaturetocreate->fk_user_creat = $user->id;
3805 $candidaturetocreate->date_creation =
dol_now();
3806 $candidaturetocreate->fk_project = $projectstatic->id;
3807 $candidaturetocreate->description = $description;
3808 $candidaturetocreate->note_private = $descriptionfull;
3809 $candidaturetocreate->entity =
$conf->entity;
3810 $candidaturetocreate->email_msgid = $msgid;
3811 $candidaturetocreate->email_date = $dateemail;
3812 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3817 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3860 if ($errorforthisaction) {
3864 $result = $candidaturetocreate->create($user);
3867 $this->error =
'Failed to create candidature: '.implode(
', ', $candidaturetocreate->errors);
3868 $this->errors = $candidaturetocreate->errors;
3871 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag((
string) $candidaturetocreate->id);
3874 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3877 if (!is_object($hookmanager)) {
3878 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3881 $hookmanager->initHooks(array(
'emailcolector',
'emailcollector'));
3883 $parameters = array(
3884 'connection' => $connection,
3885 'imapemail' => $imapemail,
3886 'overview' => $overview,
3888 'from' => $email_from,
3889 'fromtext' => $fromtext,
3891 'actionparam' => $operation[
'actionparam'],
3893 'thirdpartyid' => ($thirdpartyid ? $thirdpartyid : $thirdpartystatic->id),
3894 'objectid' => $objectid,
3895 'objectemail' => $objectemail,
3897 'messagetext' => $messagetext,
3898 'subject' => $subject,
3899 'header' => $header,
3900 'attachments' => $attachments,
3901 'savedattachments' => $savedattachments,
3902 'savedattachmentsdir' => $savedattachmentsdir,
3904 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3907 $errorforthisaction++;
3908 $this->error = $hookmanager->resPrint;
3909 if (!empty($hookmanager->resPrint)) {
3910 $operationslog .=
'<br>Hook error: '.dol_escape_htmltag($hookmanager->resPrint);
3913 if ($errorforthisaction) {
3915 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3917 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3921 if (!$errorforactions) {
3922 $nbactiondoneforemail++;
3928 if (!$errorforactions) {
3929 if (!empty($targetdir)) {
3932 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3933 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid.
' - '.$imapemail->getHeader()->get(
'subject').
' to '.$targetdir;
3935 $arrayofemailtodelete[$this->
uidAsString($imapemail)] = $imapemail;
3938 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3939 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3941 $arrayofemailtodelete[$imapemail] = $msgid;
3946 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" '".($imapemail->getHeader()->get(
'subject')).
"' using this->host=".$this->host.
", this->access_type=".$this->acces_type.
" was set to read", LOG_DEBUG);
3948 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3956 unset($objectemail);
3957 unset($projectstatic);
3958 unset($thirdpartystatic);
3959 unset($contactstatic);
3961 $nbemailprocessed++;
3963 if (!$errorforemail) {
3964 $nbactiondone += $nbactiondoneforemail;
3968 $this->db->commit();
3970 $this->db->rollback();
3974 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3975 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3976 $datelastok = strtotime($headers[
'Date']);
3982 $this->db->rollback();
3986 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3988 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3990 $langs->load(
"admin");
3991 $output = $langs->trans(
'NoNewEmailToProcess');
3992 $output .=
' (defaultlang='.$langs->defaultlang.
')';
3998 krsort($arrayofemailtodelete, SORT_NUMERIC);
4000 foreach ($arrayofemailtodelete as $imapemailnum => $imapemail) {
4001 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemailnum);
4003 $operationslog .=
"<br> move email ".$imapemailnum.($mode > 0 ?
' (test)' :
'');
4005 if (empty($mode) && empty($error)) {
4006 $tmptargetdir = $targetdir;
4013 $result = $imapemail->move($tmptargetdir,
false);
4016 $operationslog .=
'<br>Exception !!!! '.$e->getMessage();
4018 if (empty($result)) {
4019 dol_syslog(
"Failed to move email into target directory ".$targetdir);
4020 $operationslog .=
'<br>Failed to move email into target directory '.$targetdir;
4026 if (empty($mode) && empty($error)) {
4028 $operationslog .=
"<br>Expunge";
4033 $client->disconnect();
4035 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
4036 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
4038 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid.($mode > 0 ?
' (test)' :
'');
4040 if (empty($mode) && empty($error)) {
4041 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
4044 $this->error = imap_last_error();
4045 $this->errors[] = $this->error;
4047 $operationslog .=
'<br>Error in move '.$this->error;
4054 if (empty($mode) && empty($error)) {
4056 $operationslog .=
"<br>Expunge";
4058 imap_expunge($connection);
4060 imap_close($connection);
4063 $this->datelastresult = $now;
4064 $this->lastresult = $output;
4066 $this->debuginfo .=
'IMAP search array used : '.$search;
4068 $this->debuginfo .=
'IMAP search string used : '.$search;
4071 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
4073 if ($operationslog) {
4074 $this->debuginfo .= $operationslog;
4077 if (empty($error) && empty($mode)) {
4078 $this->datelastok = $datelastok;
4081 if (!empty($this->errors)) {
4082 $this->lastresult .=
"<br>".implode(
"<br>", $this->errors);
4084 $this->codelastresult = ($error ?
'KO' :
'OK');
4090 dol_syslog(
"EmailCollector::doCollectOneCollector end error=".$error, LOG_INFO);
4092 return $error ? -1 : 1;
4107 private function getmsg($mbox, $mid, $destdir =
''): int
4111 global $charset, $htmlmsg, $plainmsg, $attachments;
4112 $htmlmsg = $plainmsg = $charset =
'';
4113 $attachments = array();
4120 $s = imap_fetchstructure($mbox, $mid, FT_UID);
4122 $this->errors = array_merge($this->errors, [imap_last_error()]);
4126 if (empty($s->parts)) {
4128 $this->
getpart($mbox, $mid, $s,
'0');
4131 foreach ($s->parts as $partno0 => $p) {
4132 $this->
getpart($mbox, $mid, $p, (
string) ($partno0 + 1), $destdir);
4165 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
4168 global $htmlmsg, $plainmsg, $charset, $attachments;
4172 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
4173 imap_body($mbox, $mid, FT_UID);
4175 if ($p->encoding == 4) {
4176 $data = quoted_printable_decode($data);
4177 } elseif ($p->encoding == 3) {
4178 $data = base64_decode($data);
4184 if ($p->parameters) {
4185 foreach ($p->parameters as $x) {
4186 $params[strtolower($x->attribute)] = $x->value;
4189 if (!empty($p->dparameters)) {
4190 foreach ($p->dparameters as $x) {
4191 $params[strtolower($x->attribute)] = $x->value;
4194 '@phan-var-force array{filename?:string,name?:string,charset?:string} $params';
4199 if (!empty($params[
'filename']) || !empty($params[
'name'])) {
4201 $filename = $params[
'filename'] ?? $params[
'name'];
4203 $attachments[$filename] = $data;
4205 if (strlen($destdir)) {
4212 if ($p->type == 0 && $data) {
4213 if (!empty($params[
'charset'])) {
4218 if (strtolower($p->subtype) ==
'plain') {
4219 $plainmsg .= trim($data).
"\n\n";
4221 $htmlmsg .= $data.
"<br><br>";
4223 $charset = $params[
'charset'];
4224 } elseif ($p->type == 2 && $data) {
4230 if (!empty($params[
'charset'])) {
4233 $plainmsg .= $data.
"\n\n";
4237 if (!empty($p->parts)) {
4238 foreach ($p->parts as $partno0 => $p2) {
4239 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1), $destdir);
4255 if (!$string || $fromEncoding == $toEncoding) {
4258 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
4259 if (!$convertedString && extension_loaded(
'mbstring')) {
4260 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
4262 if (!$convertedString) {
4263 throw new Exception(
'Mime string encoding conversion failed');
4265 return $convertedString;
4284 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
4285 $elements = imap_mime_header_decode($subject);
4287 if (!empty($elements)) {
4288 $num = count($elements);
4289 for ($i = 0; $i < $num; $i++) {
4290 $stringinutf8 = (in_array(strtoupper($elements[$i]->charset), array(
'DEFAULT',
'UTF-8')) ? $elements[$i]->text : iconv_mime_decode($elements[$i]->text, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, $elements[$i]->charset));
4291 $newstring .= $stringinutf8;
4293 $subject = $newstring;
4295 } elseif (!function_exists(
'mb_decode_mimeheader')) {
4296 $subject = mb_decode_mimeheader($subject);
4297 } elseif (function_exists(
'iconv_mime_decode')) {
4298 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
4301 return (
string) $subject;
4311 private function saveEmailCollectorAttachmentsToDir($destdir, $attachments)
4313 $destdir = rtrim((
string) $destdir,
'/');
4314 if ($destdir ===
'' || empty($attachments) || !is_array($attachments)) {
4325 $seenHashes = array();
4328 $filelist =
dol_dir_list($destdir,
'files', 0,
'',
'(\\.meta|_preview.*.*\\.png)$',
'date', SORT_DESC, 0, 1);
4329 foreach ($filelist as $fileinfo) {
4330 if (empty($fileinfo[
'fullname']) || !is_file($fileinfo[
'fullname']) || !is_readable($fileinfo[
'fullname'])) {
4333 $hash = hash_file(
'sha256', $fileinfo[
'fullname']);
4334 if ($hash !==
false && empty($seenHashes[$hash])) {
4335 $seenHashes[$hash] = $fileinfo[
'name'];
4341 if (defined(
'DOL_DATA_ROOT')) {
4342 $root = rtrim((
string) DOL_DATA_ROOT,
'/').
'/';
4343 $destdirwithslash = $destdir.
'/';
4344 if (strpos($destdirwithslash, $root) === 0) {
4345 $relativeDir = rtrim(substr($destdirwithslash, strlen($root)),
'/');
4350 foreach ($attachments as $key => $attachment) {
4357 if (is_object($attachment)) {
4358 '@phan-var-force Webklex\PHPIMAP\Attachment $attachment';
4361 $origName = (
string) $attachment->getName();
4362 }
catch (Throwable $e) {
4366 $content = (
string) $attachment->getContent();
4367 }
catch (Throwable $e) {
4371 $tmpmime = (
string) $attachment->getContentType();
4372 $mime = ($tmpmime !==
'' ? $tmpmime :
null);
4373 }
catch (Throwable $e) {
4378 $origName = (
string) $key;
4379 $content = (
string) $attachment;
4382 if ($origName ===
'' || $origName ===
'undefined') {
4383 $origName =
'attachment-'.$index;
4385 if ($content ===
'') {
4390 if ($safeName ===
'') {
4391 $safeName =
'attachment-'.$index;
4394 $contentHash = hash(
'sha256', $content);
4395 $finalName = $safeName;
4396 $useExisting =
false;
4397 if (!empty($seenHashes[$contentHash])) {
4398 $finalName = $seenHashes[$contentHash];
4399 if (file_exists($destdir.
'/'.$finalName)) {
4400 $useExisting =
true;
4404 if (!$useExisting) {
4406 while (file_exists($destdir.
'/'.$finalName)) {
4407 $finalName = preg_replace(
'/(\\.[A-Za-z0-9]{1,10})$/',
'', $safeName).
'-'.$n;
4408 if (preg_match(
'/\\.[A-Za-z0-9]{1,10}$/', $safeName, $m)) {
4409 $finalName .= $m[0];
4414 $resultsave = $this->
saveAttachment($destdir, $finalName, $content);
4415 if (!is_string($resultsave)) {
4418 $finalName = basename($resultsave);
4419 $seenHashes[$contentHash] = $finalName;
4422 $fullPath = $destdir.
'/'.$finalName;
4423 $size = (file_exists($fullPath) ? filesize($fullPath) : null);
4424 $sizevalue = ($size ===
false ? null : $size);
4425 $sha256 = $contentHash;
4428 'name' => $finalName,
4429 'original_name' => $origName,
4430 'relative_path' => ($relativeDir !==
'' ? $relativeDir.
'/'.$finalName :
''),
4431 'content_type' => $mime,
4432 'size' => ($sizevalue !== null ? (int) $sizevalue : null),
4433 'sha256' => $sha256,
4452 require_once DOL_DOCUMENT_ROOT .
'/core/lib/images.lib.php';
4458 $filename = preg_replace(
'/[\x00-\x1F\x7F]/',
'', $filename);
4459 $filename = preg_replace(
'/^\.+/',
'', rtrim($filename,
'. '));
4460 if ($filename ===
'') {
4461 $filename =
'attachment';
4464 if (!file_exists($destdir)) {
4470 $tmp = explode(
'.', $filename);
4471 $ext = (count($tmp) > 1 ?
'.' . array_pop($tmp) :
'');
4472 $filename = implode(
'.', $tmp);
4481 $filepath = $destdir . (preg_match(
'/\/$/', $destdir) ?
'' :
'/') . $filename . $ext;
4483 while (file_exists($filepath)) {
4484 $filepath = $destdir . (preg_match(
'/\/$/', $destdir) ?
'' :
'/') . $filename .
'(' . $i .
')' . $ext;
4490 $tmpdir =
$conf->admin->dir_temp;
4494 $tmpfile = $tmpdir.
'/emailcollector_attachment_'.
dol_hash(uniqid((
string) mt_rand(),
true),
'md5');
4495 if (file_put_contents($tmpfile, $content) ===
false) {
4499 if (count($checkvirusarray)) {
4500 dol_syslog(
'EmailCollector::saveAttachment File "'.$filepath.
'" KO with antivirus: errors='.implode(
',', $checkvirusarray), LOG_WARNING);
4504 if (!
dol_move($tmpfile, $filepath,
'0', 0, 0, 0)) {
4512 $filename = basename($filepath);
4516 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
4517 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
4518 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
4519 $maxheightmini = $tmparraysize[
'maxheightmini'];
4520 $quality = $tmparraysize[
'quality'];
4523 vignette($filepath, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
4525 vignette($filepath, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
4541 if (is_object($imapemail)) {
4542 return $imapemail->getAttributes()[
"uid"];
4544 return (
string) $imapemail;