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 if (is_object($langs)) {
329 foreach ($this->fields as $key => $val) {
330 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
331 foreach ($val[
'arrayofkeyval'] as $key2 => $val2) {
332 $this->fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
351 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
352 $langs->load(
"errors");
353 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
357 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
358 $this->password =
dolEncrypt($this->password);
362 $this->password =
dolDecrypt($this->password);
364 if (is_array($this->filters) && count($this->filters)) {
367 foreach ($this->filters as $filter) {
368 $emailcollectorfilter->type = $filter[
'type'];
369 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
370 $emailcollectorfilter->fk_emailcollector = $this->id;
371 $emailcollectorfilter->status = $filter[
'status'];
373 $emailcollectorfilter->create($user);
377 if (is_array($this->actions) && count($this->actions)) {
380 foreach ($this->actions as $operation) {
381 $emailcollectoroperation->type = $operation[
'type'];
382 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
383 $emailcollectoroperation->fk_emailcollector = $this->id;
384 $emailcollectoroperation->status = $operation[
'status'];
385 $emailcollectoroperation->position = $operation[
'position'];
387 $emailcollectoroperation->create($user);
403 global $langs, $extrafields;
424 unset(
$object->codelastresult);
425 unset(
$object->datelastresult);
430 $object->ref =
"copy_of_".$object->ref;
433 $object->host =
'imap.example.com';
436 if (is_array(
$object->array_options) && count(
$object->array_options) > 0) {
437 $extrafields->fetch_name_optionals_label($this->table_element);
438 foreach (
$object->array_options as $key => $option) {
439 $shortkey = preg_replace(
'/options_/',
'', $key);
440 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
441 unset(
$object->array_options[$key]);
447 $object->context[
'createfromclone'] =
'createfromclone';
448 $result =
$object->create($user);
454 unset(
$object->context[
'createfromclone']);
461 $this->db->rollback();
473 public function fetch($id, $ref =
null)
477 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
478 $this->password =
dolDecrypt($this->password);
511 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
515 $sql =
"SELECT s.rowid";
516 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
517 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
519 $sql .=
" AND s.status = 1";
521 $sql .= $this->db->order($sortfield, $sortorder);
526 $offset = $limit * $page;
528 $sql .= $this->db->plimit($limit + 1, $offset);
531 $result = $this->db->query($sql);
533 $num = $this->db->num_rows($result);
536 $obj = $this->db->fetch_object($result);
538 if ($emailcollector_static->fetch($obj->rowid)) {
539 $obj_ret[] = $emailcollector_static;
544 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
545 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
547 if (!count($obj_ret)) {
548 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
566 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
567 $langs->load(
"errors");
568 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
572 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
573 $this->password =
dolEncrypt($this->password);
577 $this->password =
dolDecrypt($this->password);
589 public function delete(
User $user, $notrigger = 0)
604 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
606 global
$conf, $langs, $action, $hookmanager;
608 if (!empty(
$conf->dol_no_mouse_hover)) {
614 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
616 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
618 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
620 if ($option !=
'nolink') {
622 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
623 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
624 $add_save_lastsearch_values = 1;
626 if ($add_save_lastsearch_values) {
627 $url .=
'&save_lastsearch_values=1';
632 if (empty($notooltip)) {
634 $label = $langs->trans(
"ShowEmailCollector");
635 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
637 $linkclose .=
' title="'.dolPrintHTMLForAttribute($label).
'"';
638 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
640 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
643 $linkstart =
'<a href="'.$url.
'"';
644 $linkstart .= $linkclose.
'>';
647 $result .= $linkstart;
649 $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);
651 if ($withpicto != 2) {
652 $result .= $this->ref;
657 $hookmanager->initHooks(array(
'emailcollectordao'));
658 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result);
659 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
661 $result = $hookmanager->resPrint;
663 $result .= $hookmanager->resPrint;
691 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
694 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
695 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
696 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
697 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
700 $statusType =
'status5';
701 if ($status == self::STATUS_ENABLED) {
702 $statusType =
'status4';
705 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
716 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
717 $sql .=
' fk_user_creat, fk_user_modif';
718 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
719 $sql .=
' WHERE t.rowid = '.((int) $id);
720 $result = $this->db->query($sql);
722 if ($this->db->num_rows($result)) {
723 $obj = $this->db->fetch_object($result);
725 $this->
id = $obj->rowid;
727 $this->user_creation_id = $obj->fk_user_creat;
728 $this->user_modification_id = $obj->fk_user_modif;
729 $this->date_creation = $this->db->jdate($obj->datec);
730 $this->date_modification = empty($obj->datem) ?
'' : $this->db->jdate($obj->datem);
733 $this->db->free($result);
735 dol_print_error($this->db);
747 $this->host =
'localhost';
748 $this->login =
'alogin';
761 $this->filters = array();
763 $sql =
'SELECT rowid, type, rulevalue, status';
764 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
765 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
768 $resql = $this->db->query($sql);
770 $num = $this->db->num_rows($resql);
773 $obj = $this->db->fetch_object($resql);
774 $this->filters[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'rulevalue' => $obj->rulevalue,
'status' => $obj->status);
777 $this->db->free($resql);
779 dol_print_error($this->db);
793 $this->actions = array();
795 $sql =
'SELECT rowid, type, actionparam, status';
796 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
797 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
798 $sql .=
' ORDER BY position';
800 $resql = $this->db->query($sql);
802 $num = $this->db->num_rows($resql);
805 $obj = $this->db->fetch_object($resql);
806 $this->actions[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'actionparam' => $obj->actionparam,
'status' => $obj->status);
809 $this->db->free($resql);
813 dol_print_error($this->db);
828 $flags =
'/service=imap';
831 } elseif (empty($this->imap_encryption) || ($this->imap_encryption ==
'ssl' &&
getDolGlobalString(
'IMAP_FORCE_NOSSL'))) {
834 $flags .=
'/' . $this->imap_encryption;
837 $flags .=
'/novalidate-cert';
844 if (!empty($this->login) && strpos($this->login,
'/') !=
false) {
845 $partofauth = explode(
'/', $this->login);
846 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
849 $connectstringserver =
'{'.$this->host.
':'.$this->port.$flags.
'}';
851 return $connectstringserver;
862 if (function_exists(
'mb_convert_encoding')) {
864 $str = preg_replace(
"/ /",
"xxxSPACExxx", $str);
865 $str = preg_replace(
"/_/",
"xxxUNDERSCORExxx", $str);
866 $str = preg_replace(
"/\[Gmail\]/",
"xxxGMAILxxx", $str);
868 if ($str = mb_convert_encoding($str,
"UTF-7")) {
870 $str = preg_replace(
"/\+A/",
"&A", $str);
871 $str = preg_replace(
"/xxxUNDERSCORExxx/",
"_", $str);
873 $str = preg_replace(
"/xxxSPACExxx/",
" ", $str);
875 $str = preg_replace(
"/xxxGMAILxxx/",
"[Gmail]", $str);
879 $this->error =
"error: is not possible to encode this string '".$str.
"'";
899 $arrayofcollectors = $this->
fetchAll($user, 1);
901 foreach ($arrayofcollectors as $emailcollector) {
902 $result = $emailcollector->doCollectOneCollector(0);
904 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
906 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
907 if (!empty($emailcollector->errors)) {
908 $this->error .= implode(
'<br>', $emailcollector->errors);
911 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
934 global
$conf, $langs;
936 $errorforthisaction = 0;
939 $outputlangs = $langs;
942 $newlang =
GETPOST(
'lang_id',
'aZ09');
945 $newlang = !empty(
$object->thirdparty->default_lang) ?
$object->thirdparty->default_lang : $newlang;
947 if (!empty($newlang)) {
949 $outputlangs->setDefaultLang($newlang);
959 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
962 $tmparray = explode(
'.', $propertytooverwrite);
963 if (count($tmparray) == 2) {
964 $tmpclass = $tmparray[0];
965 $tmpproperty = $tmparray[1];
967 $tmpproperty = $tmparray[0];
969 if ($tmpclass && ($tmpclass !=
$object->element)) {
979 $regforregex = array();
980 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
981 $sourcefield = $regforregex[1];
982 $regexstring = $regforregex[2];
984 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
985 $sourcefield = $regforregex[1];
986 $regexstring = $regforregex[2];
989 if (!empty($sourcefield) && !empty($regexstring)) {
990 if (strtolower($sourcefield) ==
'body') {
991 $sourcestring = $messagetext;
992 } elseif (strtolower($sourcefield) ==
'subject') {
993 $sourcestring = $subject;
994 } elseif (strtolower($sourcefield) ==
'header') {
995 $sourcestring = $header;
999 $regforval = array();
1001 if (strtolower($sourcefield) ==
'body') {
1002 $regexoptions =
'ms';
1004 if (strtolower($sourcefield) ==
'header') {
1005 $regexoptions =
'm';
1008 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
1010 $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
'';
1011 $valuetoset = (strtolower($sourcefield) ==
'body') ? $valueextracted : $this->
decodeSMTPSubject($valueextracted);
1012 if (preg_match(
'/^options_/', $tmpproperty)) {
1013 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetoset;
1015 if (property_exists(
$object, $tmpproperty)) {
1016 $object->$tmpproperty = $valuetoset;
1018 $tmp[$tmpproperty] = $valuetoset;
1022 if (preg_match(
'/^options_/', $tmpproperty)) {
1025 if (property_exists(
$object, $tmpproperty)) {
1033 if (property_exists(
$object, $tmpproperty)) {
1035 $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.';
1037 $tmp[$tmpproperty] =
null;
1038 $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.';
1043 $errorforthisaction++;
1044 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1045 $this->errors[] = $this->error;
1047 $operationslog .=
'<br>'.$this->error;
1049 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1051 if (preg_match(
'/^options_/', $tmpproperty)) {
1052 $valuecurrent =
$object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1054 if (property_exists(
$object, $tmpproperty)) {
1055 $valuecurrent =
$object->$tmpproperty;
1058 $valuecurrent = $tmp[$tmpproperty];
1062 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1063 $valuetouse = $regforregex[2];
1064 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null,
$object);
1066 $matcharray = array();
1067 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1068 if (is_array($matcharray[1])) {
1069 foreach ($matcharray[1] as $keytoreplace) {
1070 if ($keytoreplace) {
1071 if (preg_match(
'/^options_/', $keytoreplace)) {
1072 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1074 if (property_exists(
$object, $keytoreplace)) {
1075 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->$keytoreplace;
1078 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1087 if (preg_match(
'/^options_/', $tmpproperty)) {
1088 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1090 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1092 if (property_exists(
$object, $tmpproperty)) {
1093 $object->$tmpproperty = $valuetouse;
1095 $tmp[$tmpproperty] = $valuetouse;
1098 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1102 $errorforthisaction++;
1103 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1104 $this->errors[] = $this->error;
1109 return $errorforthisaction;
1118 public function doCollectOneCollector($mode = 0)
1120 global $db,
$conf, $langs, $user;
1121 global $hookmanager;
1125 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1127 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1130 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1132 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1137 $this->debuginfo =
'';
1141 $searchfilterdoltrackid = 0;
1142 $searchfilternodoltrackid = 0;
1143 $searchfilterisanswer = 0;
1144 $searchfilterisnotanswer = 0;
1145 $searchfilterreplyto = 0;
1146 $searchfilterexcludebodyarray = array();
1147 $searchfilterexcludesubjectarray = array();
1148 $searchfilterexcludeemailarray = array();
1149 $searchfilterexcludedomainarray = array();
1150 $searchfilterexcludeemailmap = array();
1151 $operationslog =
'';
1152 $rulesreplyto = array();
1153 $connectstringsource =
'';
1154 $connectstringtarget =
'';
1155 $connection =
false;
1156 $arrayofemail = array();
1161 if (empty($this->host)) {
1162 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1165 if (empty($this->login)) {
1166 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1169 if (empty($this->source_directory)) {
1170 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1176 $sourcedir = $this->source_directory;
1177 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1182 $sourcedir = $this->source_directory;
1183 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1186 $timeoutconnect = (int)
getDolGlobalInt(
'MAIN_USE_CONNECT_TIMEOUT', 5);
1187 if ($timeoutconnect <= 0) {
1188 $timeoutconnect = 5;
1190 $timeoutread = (int)
getDolGlobalInt(
'MAIN_USE_RESPONSE_TIMEOUT', 20);
1191 if ($timeoutread <= 0) {
1194 if (function_exists(
'imap_timeout')) {
1195 imap_timeout(IMAP_OPENTIMEOUT, $timeoutconnect);
1196 imap_timeout(IMAP_READTIMEOUT, $timeoutread);
1197 imap_timeout(IMAP_WRITETIMEOUT, 5);
1198 imap_timeout(IMAP_CLOSETIMEOUT, 5);
1199 $this->debuginfo .=
'IMAP timeouts: connect='.$timeoutconnect.
's, read='.$timeoutread.
's<br>';
1203 if ($this->acces_type == 1) {
1205 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>';
1207 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1211 $keyforsupportedoauth2array = $this->oauth_service;
1212 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1213 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1215 $keyforprovider =
'';
1217 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', strtoupper($keyforsupportedoauth2array));
1218 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1220 if (!empty($supportedoauth2array)) {
1221 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1222 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1223 $OAUTH_SERVICENAME = $nameofservice;
1225 $OAUTH_SERVICENAME =
'Unknown';
1228 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1230 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1239 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1242 if (is_object($tokenobj) && method_exists($tokenobj,
'getEndOfLife')) {
1243 $endOfLife = $tokenobj->getEndOfLife();
1245 if ($endOfLife !== -9002 && $endOfLife !== -9001 && time() > ($endOfLife - 30)) {
1251 if (is_object($tokenobj) && $expire) {
1252 $this->debuginfo .=
'Refresh token '.$OAUTH_SERVICENAME.
'<br>';
1253 $credentials =
new Credentials(
1258 $serviceFactory = new \OAuth\ServiceFactory();
1259 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1263 if (preg_match(
'/^Microsoft/', $OAUTH_SERVICENAME)) {
1265 $tmp = explode(
'-', $OAUTH_SERVICENAME);
1266 $scopes = explode(
',',
getDolGlobalString(
'OAUTH_'.strtoupper($tmp[0]).(empty($tmp[1]) ?
'' :
'-'.$tmp[1]).
'_SCOPE'));
1269 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $scopes);
1271 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
1273 $refreshtoken = $tokenobj->getRefreshToken();
1274 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1277 $tokenobj->setRefreshToken($refreshtoken);
1278 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1280 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1281 if (is_object($tokenobj)) {
1282 $token = $tokenobj->getAccessToken();
1284 $this->error =
"Token not found";
1289 $this->error = $e->getMessage();
1290 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1294 $cm =
new ClientManager();
1295 $client = $cm->make([
1296 'host' => $this->host,
1297 'port' => $this->port,
1298 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1299 'validate_cert' => true,
1300 'protocol' =>
'imap',
1301 'username' => $this->login,
1302 'password' => $token,
1303 'authentication' =>
"oauth",
1307 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1309 $cm =
new ClientManager();
1310 $client = $cm->make([
1311 'host' => $this->host,
1312 'port' => $this->port,
1313 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1314 'validate_cert' => true,
1315 'protocol' =>
'imap',
1316 'username' => $this->login,
1317 'password' => $this->password,
1318 'authentication' =>
"login",
1326 }
catch (ConnectionFailedException $e) {
1327 $this->error = $e->getMessage();
1328 $this->errors[] = $this->error;
1329 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1333 $host = dol_getprefix(
'email');
1336 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1338 if (!function_exists(
'imap_open')) {
1339 $this->error =
'IMAP function not enabled on your PHP';
1345 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1346 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1348 $connectstringsource = $connectstringserver.$sourcedir;
1349 $connectstringtarget = $connectstringserver.$targetdir;
1352 $this->debuginfo .=
'connectstringsource = '.$connectstringsource.
', $connectstringtarget='.$connectstringtarget.
'<br>';
1354 $connection = imap_open($connectstringsource, $this->login, $this->password);
1355 if ($connection ===
false) {
1356 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1359 '@phan-var-force resource|IMAP\Connection $connection';
1362 $host = dol_getprefix(
'email');
1371 $criteria = array();
1374 $criteria = array(array(
'UNDELETED'));
1375 foreach ($this->filters as $rule) {
1376 if (empty($rule[
'status'])) {
1381 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1385 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1388 if ($rule[
'type'] ==
'excludeemail') {
1389 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1390 if (is_array($tmpvalues)) {
1391 foreach ($tmpvalues as $tmpvalue) {
1392 $tmpvalue = trim((
string) $tmpvalue);
1393 if ($tmpvalue ===
'') {
1397 if (preg_match_all(
'/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpvalue, $tmpmatches)) {
1398 foreach ($tmpmatches[0] as $tmpemail) {
1399 $tmpemail = strtolower(trim($tmpemail));
1400 if ($tmpemail !==
'') {
1401 $searchfilterexcludeemailarray[] = $tmpemail;
1409 if ($rule[
'type'] ==
'excludedomain') {
1410 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1411 if (is_array($tmpvalues)) {
1412 foreach ($tmpvalues as $tmpvalue) {
1413 $tmpvalue = trim((
string) $tmpvalue);
1414 if ($tmpvalue ===
'') {
1418 if (preg_match_all(
'/[a-z0-9._%+\\-]+@([a-z0-9.\\-]+\\.[a-z]{2,})/i', $tmpvalue, $tmpmatches)) {
1419 foreach ($tmpmatches[1] as $tmpdomain) {
1420 $tmpdomain = strtolower(trim($tmpdomain));
1421 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1422 if ($tmpdomain !==
'') {
1423 $searchfilterexcludedomainarray[] = $tmpdomain;
1429 $tmpdomain = strtolower($tmpvalue);
1430 $tmpdomain = preg_replace(
'/^mailto:/i',
'', $tmpdomain);
1431 $tmpdomain = trim($tmpdomain);
1432 $tmpdomain = trim($tmpdomain,
"<> \t\n\r\0\x0B.,;");
1433 if (strpos($tmpdomain,
'@') === 0) {
1434 $tmpdomain = substr($tmpdomain, 1);
1436 $posat = strrpos($tmpdomain,
'@');
1437 if ($posat !==
false) {
1438 $tmpdomain = substr($tmpdomain, $posat + 1);
1440 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1441 if ($tmpdomain !==
'') {
1442 $searchfilterexcludedomainarray[] = $tmpdomain;
1449 if ($rule[
'type'] ==
'from') {
1450 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1451 if (count($tmprulevaluearray) >= 2) {
1452 foreach ($tmprulevaluearray as $tmprulevalue) {
1453 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1456 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1459 if ($rule[
'type'] ==
'to') {
1460 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1461 if (count($tmprulevaluearray) >= 2) {
1462 foreach ($tmprulevaluearray as $tmprulevalue) {
1463 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1466 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1469 if ($rule[
'type'] ==
'bcc') {
1470 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1472 if ($rule[
'type'] ==
'cc') {
1473 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1475 if ($rule[
'type'] ==
'subject') {
1478 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1480 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1483 if ($rule[
'type'] ==
'body') {
1486 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1488 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1491 if ($rule[
'type'] ==
'header') {
1492 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1504 if ($rule[
'type'] ==
'seen') {
1505 array_push($criteria, array($not.
"SEEN"));
1507 if ($rule[
'type'] ==
'unseen') {
1508 array_push($criteria, array($not.
"UNSEEN"));
1510 if ($rule[
'type'] ==
'unanswered') {
1511 array_push($criteria, array($not.
"UNANSWERED"));
1513 if ($rule[
'type'] ==
'answered') {
1514 array_push($criteria, array($not.
"ANSWERED"));
1516 if ($rule[
'type'] ==
'smaller') {
1517 array_push($criteria, array($not.
"SMALLER"));
1519 if ($rule[
'type'] ==
'larger') {
1520 array_push($criteria, array($not.
"LARGER"));
1524 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1525 $searchfilterdoltrackid++;
1526 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1528 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1529 $searchfilterdoltrackid++;
1530 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1532 if ($rule[
'type'] ==
'withtrackingid') {
1533 $searchfilterdoltrackid++;
1534 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1536 if ($rule[
'type'] ==
'withouttrackingid') {
1537 $searchfilternodoltrackid++;
1538 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1541 if ($rule[
'type'] ==
'isanswer') {
1542 $searchfilterisanswer++;
1543 $searchhead .=
'/References.*@.*/';
1545 if ($rule[
'type'] ==
'isnotanswer') {
1546 $searchfilterisnotanswer++;
1547 $searchhead .=
'! /References.*@.*/';
1550 if ($rule[
'type'] ==
'replyto') {
1551 $searchfilterreplyto++;
1552 $rulesreplyto[] = $rule[
'rulevalue'];
1553 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1557 if (empty($targetdir) || !
getDolGlobalString(
'EMAILCOLLECTOR_NO_FILTER_ON_DATE_IF_THERE_IS_A_TARGETDIR')) {
1559 if ($this->datelastok) {
1560 $fromdate = $this->datelastok;
1562 if ($fromdate > 0) {
1564 array_push($criteria, array(
"SINCE" =>
date(
'j-M-Y', $fromdate - 86400)));
1570 $search = var_export($criteria,
true);
1573 $search =
'UNDELETED';
1574 foreach ($this->filters as $rule) {
1575 if (empty($rule[
'status'])) {
1583 if (!empty($rule[
'rulevalue']) && strpos($rule[
'rulevalue'],
'!') === 0) {
1587 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1590 if ($rule[
'type'] ==
'excludeemail') {
1591 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1592 if (is_array($tmpvalues)) {
1593 foreach ($tmpvalues as $tmpvalue) {
1594 $tmpvalue = trim((
string) $tmpvalue);
1595 if ($tmpvalue ===
'') {
1599 if (preg_match_all(
'/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpvalue, $tmpmatches)) {
1600 foreach ($tmpmatches[0] as $tmpemail) {
1601 $tmpemail = strtolower(trim($tmpemail));
1602 if ($tmpemail !==
'') {
1603 $searchfilterexcludeemailarray[] = $tmpemail;
1611 if ($rule[
'type'] ==
'excludedomain') {
1612 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1613 if (is_array($tmpvalues)) {
1614 foreach ($tmpvalues as $tmpvalue) {
1615 $tmpvalue = trim((
string) $tmpvalue);
1616 if ($tmpvalue ===
'') {
1620 if (preg_match_all(
'/[a-z0-9._%+\\-]+@([a-z0-9.\\-]+\\.[a-z]{2,})/i', $tmpvalue, $tmpmatches)) {
1621 foreach ($tmpmatches[1] as $tmpdomain) {
1622 $tmpdomain = strtolower(trim($tmpdomain));
1623 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1624 if ($tmpdomain !==
'') {
1625 $searchfilterexcludedomainarray[] = $tmpdomain;
1631 $tmpdomain = strtolower($tmpvalue);
1632 $tmpdomain = preg_replace(
'/^mailto:/i',
'', $tmpdomain);
1633 $tmpdomain = trim($tmpdomain);
1634 $tmpdomain = trim($tmpdomain,
"<> \t\n\r\0\x0B.,;");
1635 if (strpos($tmpdomain,
'@') === 0) {
1636 $tmpdomain = substr($tmpdomain, 1);
1638 $posat = strrpos($tmpdomain,
'@');
1639 if ($posat !==
false) {
1640 $tmpdomain = substr($tmpdomain, $posat + 1);
1642 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1643 if ($tmpdomain !==
'') {
1644 $searchfilterexcludedomainarray[] = $tmpdomain;
1651 if ($rule[
'type'] ==
'from') {
1652 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1653 if (count($tmprulevaluearray) >= 2) {
1654 foreach ($tmprulevaluearray as $tmprulevalue) {
1655 $search .=
' '.$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1658 $search .=
' '.$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1661 if ($rule[
'type'] ==
'to') {
1662 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1663 if (count($tmprulevaluearray) >= 2) {
1664 foreach ($tmprulevaluearray as $tmprulevalue) {
1665 $search .=
' '.$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1668 $search .=
' '.$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1671 if ($rule[
'type'] ==
'bcc') {
1672 $search .=
' '.$not.
'BCC';
1674 if ($rule[
'type'] ==
'cc') {
1675 $search .=
' '.$not.
'CC';
1677 if ($rule[
'type'] ==
'subject') {
1680 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1682 $search .=
' SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1685 if ($rule[
'type'] ==
'body') {
1688 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1691 $search .=
' BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1694 if ($rule[
'type'] ==
'header') {
1695 $search .=
' '.$not.
'HEADER '.$rule[
'rulevalue'];
1707 if ($rule[
'type'] ==
'seen') {
1708 $search .=
' '.$not.
'SEEN';
1710 if ($rule[
'type'] ==
'unseen') {
1711 $search .=
' '.$not.
'UNSEEN';
1713 if ($rule[
'type'] ==
'unanswered') {
1714 $search .=
' '.$not.
'UNANSWERED';
1716 if ($rule[
'type'] ==
'answered') {
1717 $search .=
' '.$not.
'ANSWERED';
1719 if ($rule[
'type'] ==
'smaller') {
1720 $search .=
' '.$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1722 if ($rule[
'type'] ==
'larger') {
1723 $search .=
' '.$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1727 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1728 $searchfilterdoltrackid++;
1729 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1731 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1732 $searchfilterdoltrackid++;
1733 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1735 if ($rule[
'type'] ==
'withtrackingid') {
1736 $searchfilterdoltrackid++;
1737 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1739 if ($rule[
'type'] ==
'withouttrackingid') {
1740 $searchfilternodoltrackid++;
1741 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1744 if ($rule[
'type'] ==
'isanswer') {
1745 $searchfilterisanswer++;
1746 $searchhead .=
'/References.*@.*/';
1748 if ($rule[
'type'] ==
'isnotanswer') {
1749 $searchfilterisnotanswer++;
1750 $searchhead .=
'! /References.*@.*/';
1753 if ($rule[
'type'] ==
'replyto') {
1754 $searchfilterreplyto++;
1755 $rulesreplyto[] = $rule[
'rulevalue'];
1756 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1760 if (empty($targetdir)) {
1762 if ($this->datelastok) {
1763 $fromdate = $this->datelastok;
1765 if ($fromdate > 0) {
1767 $search .=
' SINCE '.date(
'j-M-Y', $fromdate - 86400);
1775 if (!empty($searchfilterexcludeemailarray)) {
1776 $searchfilterexcludeemailarray = array_values(array_filter(array_unique($searchfilterexcludeemailarray)));
1777 $searchfilterexcludeemailmap = array_fill_keys($searchfilterexcludeemailarray,
true);
1779 if (!empty($searchfilterexcludedomainarray)) {
1780 $searchfilterexcludedomainarray = array_values(array_filter(array_unique($searchfilterexcludedomainarray)));
1783 $nbemailprocessed = 0;
1786 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1787 $arrayofemail = array();
1796 $tmpsourcedir = $sourcedir;
1801 $f = $client->getFolders(
false, $tmpsourcedir);
1808 foreach ($f as $candidate) {
1809 if ($candidate instanceof Webklex\PHPIMAP\Folder && $candidate->full_name === $tmpsourcedir) {
1810 $folder = $candidate;
1814 if ($folder instanceof Webklex\PHPIMAP\Folder) {
1815 $Query = $folder->messages()->where($criteria);
1819 $this->error =
"Failed to execute getfolders";
1820 $this->errors[] = $this->error;
1821 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1824 }
catch (InvalidWhereQueryCriteriaException $e) {
1825 $this->error = $e->getMessage();
1826 $this->errors[] = $this->error;
1827 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1830 $this->error = $e->getMessage();
1831 $this->errors[] = $this->error;
1832 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1837 if (empty($Query)) {
1839 $this->error =
"Source directory ".$sourcedir.
" not found";
1840 $this->errors[] = $this->error;
1841 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_WARNING);
1845 '@phan-var-force Webklex\PHPIMAP\Query\Query $Query';
1848 $Query->leaveUnread();
1850 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1851 dol_syslog(
"EmailCollector::doCollectOneCollector nb arrayofemail ".(is_array($arrayofemail) ? count($arrayofemail) :
'Not array'));
1853 $this->error = $e->getMessage();
1854 $this->errors[] = $this->error;
1855 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1858 } elseif ($connection !==
false) {
1860 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1862 if ($arrayofemail ===
false) {
1864 $mapoferrrors = imap_errors();
1865 if ($mapoferrrors !==
false) {
1867 $this->error =
"Search string not understood - ".implode(
',', $mapoferrrors);
1868 $this->errors[] = $this->error;
1873 $arrayofemailtodelete = array();
1876 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
1893 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1895 $richarrayofemail = array();
1897 foreach ($arrayofemail as $imapemail) {
1900 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1901 $header = $imapemail->getHeader()->raw;
1902 $overview = $imapemail->getAttributes();
1904 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1905 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1908 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1911 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)(\r\n|\s$)/m', $header, $matches);
1912 $headers = array_combine($matches[1], $matches[2]);
1915 $richarrayofemail[] = array(
'imapemail' => $imapemail,
'header' => $header,
'headers' => $headers,
'overview' => $overview,
'date' => empty($headers[
'Date']) ?
false : strtotime($headers[
'Date']));
1920 $richarrayofemail =
dol_sort_array($richarrayofemail,
'date',
'asc');
1924 foreach ($richarrayofemail as $tmpval) {
1925 if ($nbemailprocessed > 1000) {
1931 $imapemail = $tmpval[
'imapemail'];
1932 $header = $tmpval[
'header'];
1933 $overview = $tmpval[
'overview'];
1934 $headers = $tmpval[
'headers'];
1936 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1937 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1939 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1940 $headers[
'References'] = $headers[
'references'];
1942 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1943 $headers[
'Message-ID'] = $headers[
'message-id'];
1945 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1946 $headers[
'Subject'] = $headers[
'subject'];
1952 $emailto = (string) $overview[
'to'];
1957 $operationslog .=
'<br>** Process email #'.dol_escape_htmltag((
string) $iforemailloop);
1961 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1963 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1965 $operationslog .=
" - ".dol_escape_htmltag((
string) $imapemail);
1966 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1968 $operationslog .=
" - MsgId: ".$msgid;
1969 $operationslog .=
" - Date: ".($headers[
'Date'] ?? $langs->transnoentitiesnoconv(
"NotFound"));
1970 $operationslog .=
" - References: ".dol_escape_htmltag($headers[
'References'] ?? $langs->transnoentitiesnoconv(
"NotFound")).
" - Subject: ".
dol_escape_htmltag($headers[
'Subject']);
1972 dol_syslog(
"-- Process email #".$iforemailloop.
", MsgId: ".$msgid.
", Date: ".($headers[
'Date'] ??
'').
", References: ".($headers[
'References'] ??
'').
", Subject: ".$headers[
'Subject']);
1975 $trackidfoundintorecipienttype =
'';
1976 $trackidfoundintorecipientid = 0;
1981 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)) {
1982 $trackidfoundintorecipienttype = $reg[1];
1983 $trackidfoundintorecipientid = $reg[2];
1984 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1985 $trackidfoundintorecipienttype =
'emailing';
1986 $trackidfoundintorecipientid = $reg[1];
1989 $trackidfoundintomsgidtype =
'';
1990 $trackidfoundintomsgidid = 0;
1995 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)) {
1996 $trackidfoundintomsgidtype = $reg[1];
1997 $trackidfoundintomsgidid = $reg[2];
1998 } elseif (preg_match(
'/(?:[\+\-])emailing-(\w+)@/', $msgid, $reg)) {
1999 $trackidfoundintomsgidtype =
'emailing';
2000 $trackidfoundintomsgidid = $reg[1];
2006 if ($searchfilterdoltrackid > 0) {
2007 $referencesForFilter = $headers[
'References'] ??
'';
2008 if (!empty($headers[
'References']) && !empty($headers[
'In-Reply-To'])) {
2009 $referencesForFilter .=
' ';
2011 $referencesForFilter .= ($headers[
'In-Reply-To'] ??
'');
2013 if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) {
2014 if (empty($referencesForFilter) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $referencesForFilter)) {
2015 $nbemailprocessed++;
2016 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");
2022 if ($searchfilternodoltrackid > 0) {
2023 $referencesForFilter = $headers[
'References'] ??
'';
2024 if (!empty($headers[
'References']) && !empty($headers[
'In-Reply-To'])) {
2025 $referencesForFilter .=
' ';
2027 $referencesForFilter .= ($headers[
'In-Reply-To'] ??
'');
2029 if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($referencesForFilter) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $referencesForFilter))) {
2030 $nbemailprocessed++;
2031 dol_syslog(
" Discarded - Suffix found into email recipient, or Header 'References/In-Reply-To' found and matching signature of application so with a trackid");
2036 if ($searchfilterisanswer > 0) {
2037 $referencesforanswer =
'';
2038 if (!empty($headers[
'References'])) {
2039 $referencesforanswer .= $headers[
'References'].
' ';
2041 if (!empty($headers[
'In-Reply-To'])) {
2042 $referencesforanswer .= $headers[
'In-Reply-To'];
2045 $hasdolibarrreference = 0;
2046 if (!empty($referencesforanswer)) {
2047 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $referencesforanswer)) {
2048 $hasdolibarrreference = 1;
2050 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $referencesforanswer)) {
2051 $hasdolibarrreference = 1;
2057 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
2063 if (!empty($headers[
'In-Reply-To'])) {
2067 if ($hasdolibarrreference) {
2074 $nbemailprocessed++;
2075 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)");
2079 if ($searchfilterisnotanswer > 0) {
2083 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
2088 if (!$isanswer &&
getDolGlobalInt(
'EMAILCOLLECTOR_ISNOTANSWER_USE_REFERENCES') && !empty($headers[
'References'])) {
2091 if (!$isanswer &&
getDolGlobalString(
'EMAILCOLLECTOR_USE_IN_REPLY_TO_TO_DETECT_ANSWERS')) {
2092 if (!empty($headers[
'In-Reply-To'])) {
2099 $nbemailprocessed++;
2100 dol_syslog(
" Discarded - Email is an answer");
2104 if ($searchfilterreplyto > 0) {
2105 if (!empty($headers[
'Reply-To'])) {
2107 foreach ($rulesreplyto as $key => $rulereplyto) {
2108 if (preg_match(
'/'.preg_quote($rulereplyto,
'/').
'/', $headers[
'Reply-To'])) {
2113 if (!$isreplytook || $isreplytook != count($rulesreplyto)) {
2114 $nbemailprocessed++;
2115 dol_syslog(
" Discarded - Reply-to does not match");
2123 $thirdpartystatic =
new Societe($this->db);
2124 $contactstatic =
new Contact($this->db);
2125 $projectstatic =
new Project($this->db);
2127 $nbactiondoneforemail = 0;
2129 $errorforactions = 0;
2130 $thirdpartyfoundby =
'';
2131 $contactfoundby =
'';
2132 $projectfoundby =
'';
2133 $ticketfoundby =
'';
2134 $candidaturefoundby =
'';
2138 $dateformated =
dol_print_date($overview[
'date'],
'dayrfc',
'gmt');
2139 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".$dateformated.
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
2144 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);
2154 global $htmlmsg, $plainmsg, $charset, $attachments;
2158 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
2161 $htmlmsg = $plainmsg =
'';
2162 $attachments = array();
2164 if ($imapemail->hasHTMLBody()) {
2165 $htmlmsg = $imapemail->getHTMLBody();
2167 if ($imapemail->hasTextBody() && $imapemail->getTextBody() !=
"\n") {
2168 $plainmsg = $imapemail->getTextBody();
2170 if ($imapemail->hasAttachments()) {
2171 $attachments = $imapemail->getAttachments()->all();
2173 $attachments = array();
2176 $getMsg = $this->
getmsg($connection, $imapemail);
2178 $this->errors = array_merge($this->errors, [$this->error]);
2182 '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments';
2192 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
2193 dol_syslog(
" Discarded - Email body is not valid utf8");
2197 if (!empty($searchfilterexcludebodyarray)) {
2198 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
2199 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
2200 $nbemailprocessed++;
2201 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
2202 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
2244 $replytostring =
'';
2248 $replytostring = !empty($headers[
'Reply-To']) ? $this->
decodeSMTPSubject($headers[
'Reply-To']) :
'';
2255 $tmpdate = $overview[
'date']->toDate();
2256 $tmptimezone = $tmpdate->getTimezone()->getName();
2259 if (preg_match(
'/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) {
2260 if ($reg[1] ==
'+' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2261 $dateemail -= (3600 * (int) $reg[2]);
2262 $dateemail -= (60 * (int) $reg[3]);
2264 if ($reg[1] ==
'-' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2265 $dateemail += (3600 * (int) $reg[2]);
2266 $dateemail += (60 * (int) $reg[3]);
2271 $fromstring = (string) $overview[0]->from;
2272 $replytostring = (!empty($overview[
'in_reply-to']) ? $overview[
'in_reply-to'] : (!empty($headers[
'Reply-To']) ? $headers[
'Reply-To'] :
"")) ;
2274 $sender = !empty($overview[0]->sender) ? $overview[0]->sender :
'';
2275 $to = $overview[0]->to;
2276 $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc :
'';
2277 $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc :
'';
2279 $subject = (string) $overview[0]->subject;
2282 if (!empty($searchfilterexcludesubjectarray)) {
2283 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
2284 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
2285 $nbemailprocessed++;
2286 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
2287 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
2294 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
2295 $email_from = $reg[2];
2296 $fromtext = $reg[1];
2298 $email_from = $fromstring;
2301 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
2303 $replytotext = $reg[1];
2305 $replyto = $replytostring;
2309 if (!empty($searchfilterexcludeemailmap) || !empty($searchfilterexcludedomainarray)) {
2310 $emailsToCheck = array();
2311 $tmpaddressblob = trim($fromstring.
' '.$replytostring);
2312 if ($tmpaddressblob !==
'' && preg_match_all(
'/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpaddressblob, $tmpmatches)) {
2313 foreach ($tmpmatches[0] as $tmpEmail) {
2314 $tmpEmail = strtolower(trim($tmpEmail));
2315 if ($tmpEmail !==
'') {
2316 $emailsToCheck[$tmpEmail] =
true;
2321 if (empty($emailsToCheck)) {
2322 foreach (array($email_from, $replyto) as $tmpEmail) {
2323 $tmpEmail = strtolower(trim((
string) $tmpEmail));
2324 if ($tmpEmail !==
'' && strpos($tmpEmail,
'@') !==
false) {
2325 $emailsToCheck[$tmpEmail] =
true;
2331 $discardDomain =
'';
2332 $matchedDomainRule =
'';
2334 foreach (array_keys($emailsToCheck) as $tmpEmail) {
2335 if (!empty($searchfilterexcludeemailmap[$tmpEmail])) {
2336 $discardEmail = $tmpEmail;
2340 if (!empty($searchfilterexcludedomainarray)) {
2341 $posat = strrpos($tmpEmail,
'@');
2342 if ($posat ===
false) {
2345 $tmpDomain = strtolower(substr($tmpEmail, $posat + 1));
2346 foreach ($searchfilterexcludedomainarray as $excludedDomain) {
2347 if ($excludedDomain ===
'') {
2350 if ($tmpDomain === $excludedDomain || substr($tmpDomain, -strlen(
'.'.$excludedDomain)) ===
'.'.$excludedDomain) {
2351 $discardDomain = $tmpDomain;
2352 $matchedDomainRule = $excludedDomain;
2359 if ($discardEmail !==
'' || $discardDomain !==
'') {
2360 $nbemailprocessed++;
2361 if ($discardEmail !==
'') {
2362 $operationslog .=
'<br>Discarded - Sender email excluded: '.$discardEmail;
2363 dol_syslog(
" Discarded - Sender email excluded: ".$discardEmail);
2365 $operationslog .=
'<br>Discarded - Sender domain excluded: '.$discardDomain.($matchedDomainRule !==
'' && $matchedDomainRule !== $discardDomain ?
' (matched '.$matchedDomainRule.
')' :
'');
2366 dol_syslog(
" Discarded - Sender domain excluded: ".$discardDomain.($matchedDomainRule !==
'' && $matchedDomainRule !== $discardDomain ?
" (matched ".$matchedDomainRule.
")" :
""));
2373 $fk_element_type =
'';
2390 $objectemail =
null;
2393 $arrayofreferences = array();
2394 if (!empty($headers[
'References'])) {
2395 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
2397 if (!in_array(
'<'.$msgid.
'>', $arrayofreferences)) {
2398 $arrayofreferences = array_merge($arrayofreferences, array(
'<'.$msgid.
'>'));
2403 foreach ($arrayofreferences as $reference) {
2405 if (!empty($trackidfoundintorecipienttype)) {
2406 $resultsearchtrackid = -1;
2407 $reg[1] = $trackidfoundintorecipienttype;
2408 $reg[2] = $trackidfoundintorecipientid;
2409 } elseif (!empty($trackidfoundintomsgidtype)) {
2410 $resultsearchtrackid = -1;
2411 $reg[1] = $trackidfoundintomsgidtype;
2412 $reg[2] = $trackidfoundintomsgidid;
2414 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
2415 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2416 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
2420 if (!empty($resultsearchtrackid)) {
2422 $trackid = $reg[1].$reg[2];
2424 $objectid = $reg[2];
2426 if ($reg[1] ==
'thi') {
2427 $objectemail =
new Societe($this->db);
2429 if ($reg[1] ==
'ctc') {
2430 $objectemail =
new Contact($this->db);
2432 if ($reg[1] ==
'inv') {
2433 $objectemail =
new Facture($this->db);
2435 if ($reg[1] ==
'sinv') {
2438 if ($reg[1] ==
'pro') {
2439 $objectemail =
new Propal($this->db);
2441 if ($reg[1] ==
'ord') {
2442 $objectemail =
new Commande($this->db);
2444 if ($reg[1] ==
'shi') {
2447 if ($reg[1] ==
'spro') {
2450 if ($reg[1] ==
'sord') {
2453 if ($reg[1] ==
'rec') {
2454 $objectemail =
new Reception($this->db);
2456 if ($reg[1] ==
'proj') {
2457 $objectemail =
new Project($this->db);
2458 $projectfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2460 if ($reg[1] ==
'tas') {
2461 $objectemail =
new Task($this->db);
2463 if ($reg[1] ==
'con') {
2464 $objectemail =
new Contact($this->db);
2466 if ($reg[1] ==
'use') {
2467 $objectemail =
new User($this->db);
2469 if ($reg[1] ==
'tic') {
2470 $objectemail =
new Ticket($this->db);
2471 $ticketfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2473 if ($reg[1] ==
'recruitmentcandidature') {
2475 $candidaturefoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2477 if ($reg[1] ==
'mem') {
2478 $objectemail =
new Adherent($this->db);
2486 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
2489 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket";
2490 $sql .=
" WHERE email_msgid = '".$this->db->escape($reg[1]).
"' OR origin_references LIKE '%".$this->db->escape($this->db->escapeforlike($reg[1])).
"%'";
2491 $resql = $this->db->query($sql);
2493 $obj = $this->db->fetch_object($resql);
2495 $objectid = $obj->rowid;
2496 $objectemail =
new Ticket($this->db);
2497 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2504 if (!is_object($objectemail) &&
isModEnabled(
'project')) {
2505 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2506 $resql = $this->db->query($sql);
2508 $obj = $this->db->fetch_object($resql);
2510 $objectid = $obj->rowid;
2511 $objectemail =
new Project($this->db);
2512 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2519 if (!is_object($objectemail) &&
isModEnabled(
'recruitment')) {
2520 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2521 $resql = $this->db->query($sql);
2523 $obj = $this->db->fetch_object($resql);
2525 $objectid = $obj->rowid;
2527 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2536 if (is_object($objectemail)) {
2537 $result = $objectemail->fetch($objectid);
2539 $fk_element_id = $objectemail->id;
2540 $fk_element_type = $objectemail->element;
2542 if ($fk_element_type ==
'facture') {
2543 $fk_element_type =
'invoice';
2546 if (get_class($objectemail) !=
'Societe') {
2547 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2549 $thirdpartyid = $objectemail->id;
2552 if (get_class($objectemail) !=
'Contact') {
2553 $contactid = $objectemail->fk_socpeople;
2555 $contactid = $objectemail->id;
2558 if (get_class($objectemail) !=
'Project') {
2559 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2561 $projectid = $objectemail->id;
2564 if ($objectemail instanceof
Ticket) {
2565 $ticketid = $objectemail->id;
2567 $changeonticket_references =
false;
2568 if (empty($trackid)) {
2569 $trackid = $objectemail->track_id;
2571 if (empty($objectemail->origin_references)) {
2572 $objectemail->origin_references = !empty($headers[
'References']) ? $headers[
'References'] :
null;
2573 $changeonticket_references =
true;
2575 foreach ($arrayofreferences as $key => $referencetmp) {
2576 if (!str_contains($objectemail->origin_references, $referencetmp)) {
2577 $objectemail->origin_references .=
" ".$referencetmp;
2578 $changeonticket_references =
true;
2582 if ($changeonticket_references) {
2583 $operationslog .=
'<br>We complete ticket ID='.$ticketid.
' with property origin_references='.$objectemail->origin_references;
2584 $objectemail->update($user, 1);
2591 if ($projectid > 0) {
2592 $result = $projectstatic->fetch($projectid);
2594 $projectstatic->id = 0;
2596 $projectid = $projectstatic->id;
2598 $projectfoundby =
'trackid ('.$trackid.
')';
2603 if (empty($thirdpartyid)) {
2604 $thirdpartyid = $projectstatic->socid;
2609 if ($contactid > 0) {
2610 $result = $contactstatic->fetch($contactid);
2612 $contactstatic->id = 0;
2614 $contactid = $contactstatic->id;
2616 $contactfoundby =
'trackid ('.$trackid.
')';
2618 if (empty($thirdpartyid)) {
2619 $thirdpartyid = $contactstatic->fk_soc;
2624 if ($thirdpartyid > 0) {
2625 $result = $thirdpartystatic->fetch($thirdpartyid);
2627 $thirdpartystatic->id = 0;
2629 $thirdpartyid = $thirdpartystatic->id;
2631 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2636 if (is_object($objectemail)) {
2641 if (empty($contactid)) {
2642 $result = $contactstatic->fetch(0,
null,
'', $email_from);
2645 dol_syslog(
"We found a contact with the email ".$email_from);
2646 $contactid = $contactstatic->id;
2647 $contactfoundby =
'email of contact ('.$email_from.
')';
2648 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2649 $result = $thirdpartystatic->fetch($contactstatic->socid);
2651 $thirdpartyid = $thirdpartystatic->id;
2652 $thirdpartyfoundby =
'email of contact ('.$email_from.
')';
2658 if (empty($thirdpartyid)) {
2659 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $email_from);
2661 dol_syslog(
"We found a thirdparty with the email ".$email_from);
2662 $thirdpartyid = $thirdpartystatic->id;
2663 $thirdpartyfoundby =
'email ('.$email_from.
')';
2698 $savedattachments = array();
2699 $savedattachmentsdir =
'';
2700 $savedattachmentsnote =
'';
2701 if (empty($mode) && !empty($attachments) && $fk_element_id > 0 && $fk_element_type ===
'order_supplier' && $objectemail instanceof
CommandeFournisseur) {
2702 $orderref = isset($objectemail->ref) ? (string) $objectemail->ref :
'';
2703 if ($orderref !==
'' && !empty(
$conf->fournisseur->commande)) {
2704 $entityforobject = isset($objectemail->entity) ? (int) $objectemail->entity : (int)
$conf->entity;
2705 $basedir = (!empty(
$conf->fournisseur->commande->multidir_output[$entityforobject]) ?
$conf->fournisseur->commande->multidir_output[$entityforobject] :
$conf->fournisseur->commande->dir_output);
2707 $savedattachments = $this->saveEmailCollectorAttachmentsToDir($savedattachmentsdir, $attachments);
2708 if (!empty($savedattachments)) {
2709 $operationslog .=
'<br>Saved '.count($savedattachments).
' attachment(s) into '.
dol_escape_htmltag($savedattachmentsdir);
2713 if (!empty($savedattachments)) {
2715 foreach ($savedattachments as $attmeta) {
2716 if (!is_array($attmeta) || empty($attmeta[
'name'])) {
2719 $names[] = (string) $attmeta[
'name'];
2721 if (!empty($names)) {
2722 $savedattachmentsnote = $langs->trans(
"NbOfAttachedFiles").
' : '.count($names);
2723 $savedattachmentsnote .=
' ('.implode(
', ', array_slice($names, 0, 10)).(count($names) > 10 ?
'...' :
'').
')';
2730 foreach ($this->actions as $operation) {
2731 $errorforthisaction = 0;
2732 $ticketalreadyexists = 0;
2733 if ($errorforactions) {
2736 if (empty($operation[
'status'])) {
2740 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2743 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2744 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2747 $actioncode =
'EMAIL_IN';
2749 if (preg_match(
'/Sent$/', $sourcedir) || preg_match(
'/envoyés$/i', $sourcedir)) {
2750 $actioncode =
'EMAIL';
2753 $arrayofemailtoconsidersender = array_filter(array_map(
'trim', explode(
',',
getDolGlobalString(
'MAIL_FROM_EMAILS_TO_CONSIDER_SENDING'))));
2754 foreach ($arrayofemailtoconsidersender as $emailtoconsidersender) {
2755 if ($emailtoconsidersender ===
'') {
2758 if (preg_match(
'/'.preg_quote($emailtoconsidersender,
'/').
'/', $fromstring)) {
2759 $actioncode =
'EMAIL';
2762 $operationslog .=
'<br>Email will have actioncode='.$actioncode;
2764 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2766 $descriptiontitle = $langs->transnoentitiesnoconv(
"RecordCreatedByEmailCollector", $this->
ref);
2771 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2773 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2775 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2777 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailReply").($langs->trans(
"MailReply") !=
'Reply to' ?
' (Reply to)' :
'').
' : '.
dol_escape_htmltag($replyto));
2780 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2782 if ($savedattachmentsnote) {
2783 $descriptionmeta =
dol_concatdesc($descriptionmeta, $savedattachmentsnote);
2786 if ($operation[
'type'] ==
'ticket') {
2788 $tickettocreate =
new Ticket($this->db);
2789 $errorfetchticket = 0;
2790 $alreadycreated = 0;
2791 if (!empty($objectid) && $objectemail instanceof
Ticket) {
2792 $alreadycreated = $tickettocreate->fetch((
int) $objectid);
2794 if ($alreadycreated == 0 && $ticketid > 0) {
2795 $alreadycreated = $tickettocreate->fetch($ticketid);
2797 if ($alreadycreated == 0 && !empty($trackid)) {
2798 $alreadycreated = $tickettocreate->fetch(0,
'', $trackid);
2800 if ($alreadycreated == 0 && !empty($msgid)) {
2801 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2803 if ($alreadycreated < 0) {
2804 $errorfetchticket++;
2806 if (empty($errorfetchticket)) {
2807 if ($alreadycreated == 0) {
2808 $operationslog .=
'<br>Ticket not found using trackid='.$trackid.
' or msgid='.$msgid;
2809 $ticketalreadyexists = 0;
2811 $operationslog .=
'<br>Ticket already found using trackid='.$trackid.
' or msgid='.$msgid.
", we replace operation 'ticket' with 'recordevent' to add a new message";
2812 $ticketalreadyexists = 1;
2813 $operation[
'type'] =
'recordevent';
2816 $ticketalreadyexists = -1;
2823 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2824 if ($thirdpartyid > 0) {
2826 $idtouseforthirdparty = $thirdpartyid;
2827 $operationslog .=
'<br>We already have found a related thirdparty id, so we bypass the action loadthirdparty and use idtouseforthirdparty='.$idtouseforthirdparty;
2828 } elseif (empty($operation[
'actionparam'])) {
2830 $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;";
2831 $this->errors[] = $this->error;
2833 $actionparam = $operation[
'actionparam'];
2834 $idtouseforthirdparty =
'';
2835 $nametouseforthirdparty =
'';
2836 $emailtouseforthirdparty =
'';
2837 $namealiastouseforthirdparty =
'';
2839 $operationslog .=
'<br>Loop on each property to set into actionparam';
2843 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2847 $regforregex = array();
2849 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2850 $sourcefield = $regforregex[1];
2851 $regexstring = $regforregex[2];
2854 if (!empty($sourcefield) && !empty($regexstring)) {
2855 if (strtolower($sourcefield) ==
'body') {
2856 $sourcestring = $messagetext;
2857 } elseif (strtolower($sourcefield) ==
'subject') {
2858 $sourcestring = $subject;
2859 } elseif (strtolower($sourcefield) ==
'header') {
2860 $sourcestring = $header;
2863 if ($sourcestring) {
2864 $regforval = array();
2865 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2867 if ($propertytooverwrite ==
'id') {
2868 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2870 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2871 } elseif ($propertytooverwrite ==
'email') {
2872 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2874 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2875 } elseif ($propertytooverwrite ==
'name') {
2876 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2878 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2879 } elseif ($propertytooverwrite ==
'name_alias') {
2880 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2882 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2884 $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';
2888 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2889 $idtouseforthirdparty =
null;
2890 $nametouseforthirdparty =
null;
2891 $emailtouseforthirdparty =
null;
2892 $namealiastouseforthirdparty =
null;
2894 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2896 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2902 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2903 $this->errors[] = $this->error;
2905 $operationslog .=
'<br>'.$this->error;
2907 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2911 if ($propertytooverwrite ==
'id') {
2912 $idtouseforthirdparty = $reg[2];
2914 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2915 } elseif ($propertytooverwrite ==
'email') {
2916 $emailtouseforthirdparty = $reg[2];
2918 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2919 } elseif ($propertytooverwrite ==
'name') {
2920 $nametouseforthirdparty = $reg[2];
2922 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2923 } elseif ($propertytooverwrite ==
'name_alias') {
2924 $namealiastouseforthirdparty = $reg[2];
2926 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2930 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2931 $this->errors[] = $this->error;
2936 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2938 $operationslog .=
'<br>We have this initial main data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty.
'.';
2941 $tmpobject->element =
'generic';
2942 $tmpobject->id = $idtouseforthirdparty;
2943 $tmpobject->name = $nametouseforthirdparty;
2944 $tmpobject->name_alias = $namealiastouseforthirdparty;
2945 $tmpobject->email = $emailtouseforthirdparty;
2949 $idtouseforthirdparty = $tmpobject->id;
2950 $nametouseforthirdparty = $tmpobject->name;
2951 $namealiastouseforthirdparty = $tmpobject->name_alias;
2952 $emailtouseforthirdparty = $tmpobject->email;
2954 $operationslog .=
'<br>We try to search existing thirdparty with idtouseforthirdparty='.$idtouseforthirdparty.
' emailtouseforthirdparty='.$emailtouseforthirdparty.
' nametouseforthirdparty='.$nametouseforthirdparty.
' namealiastouseforthirdparty='.$namealiastouseforthirdparty;
2957 $result = $thirdpartystatic->findNearest((
int) $idtouseforthirdparty, (
string) $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', (
string) $emailtouseforthirdparty, (
string) $namealiastouseforthirdparty);
2960 if (
getDolGlobalInt(
'EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE') && $result == -2) {
2961 $idtouseforthirdparty =
getDolGlobalInt(
'EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE');
2963 $thirdpartystatic->fetch($idtouseforthirdparty);
2965 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));
2967 $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);
2970 $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 ?)';
2971 $this->errors[] = $this->error;
2976 if ($operation[
'type'] ==
'loadthirdparty') {
2977 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2980 $resultContact = $contactstatic->findNearest(0,
'',
'',
'', (
string) $emailtouseforthirdparty,
'', 0);
2981 if ($resultContact > 0) {
2982 $contactstatic->fetch($resultContact);
2983 $idtouseforthirdparty = $contactstatic->socid;
2984 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2986 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2989 $langs->load(
"errors");
2990 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', (
string) $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2991 $this->errors[] = $this->error;
2995 $langs->load(
"errors");
2996 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', (
string) $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2997 $this->errors[] = $this->error;
2999 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
3000 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
3003 $thirdpartystatic =
new Societe($db);
3004 $thirdpartystatic->name = (string) $nametouseforthirdparty;
3005 if (!empty($namealiastouseforthirdparty)) {
3006 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
3007 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
3010 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'' : $fromtext) : $replytostring);
3012 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($email_from) ?
'' : $email_from) : $replyto) : $emailtouseforthirdparty);
3015 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3017 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
3018 $thirdpartystatic->code_client =
'auto';
3020 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
3021 $thirdpartystatic->code_fournisseur =
'auto';
3024 if ($errorforthisaction) {
3027 $result = $thirdpartystatic->create($user);
3030 $this->error = $thirdpartystatic->error;
3031 $this->errors = $thirdpartystatic->errors;
3033 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag((
string) $thirdpartystatic->id);
3037 } elseif ($result > 0) {
3038 dol_syslog(
"One and only one existing third party has been found");
3040 $thirdpartystatic->fetch($result);
3042 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag((
string) $thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name);
3046 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
3047 if (empty($operation[
'actionparam'])) {
3049 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
3050 $this->errors[] = $this->error;
3052 $contact_static =
new Contact($this->db);
3054 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3055 if ($errorforthisaction) {
3058 if (!empty($contact_static->email) && $contact_static->email != $email_from) {
3059 $email_from = $contact_static->email;
3061 $email_from = (string) $email_from;
3063 $email_from = (string) $email_from;
3065 $result = $contactstatic->fetch(0,
null,
'', $email_from);
3068 $this->error =
'Error when getting contact with email ' . $email_from;
3069 $this->errors[] = $this->error;
3071 } elseif ($result == 0) {
3072 dol_syslog(
"Contact with email " . $email_from .
" was not found. We try to create it.");
3073 $contactstatic =
new Contact($this->db);
3076 $contactstatic->email = $email_from;
3077 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($email_from);
3080 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3082 if ($errorforthisaction) {
3086 if (!empty($contactstatic->country)) {
3087 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
3088 $result =
getCountry(
'',
'3', $this->db,
null, 1, $contactstatic->country);
3089 if ($result ==
'NotDefined') {
3091 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
3092 } elseif (!($result > 0)) {
3094 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
3095 $this->errors[] = $this->db->lasterror();
3097 $contactstatic->country_id = $result;
3098 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
3100 } elseif (!empty($contactstatic->country_code)) {
3101 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
3102 $result =
getCountry($contactstatic->country_code,
'3', $this->db);
3103 if ($result ==
'NotDefined') {
3105 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
3106 } elseif (!($result > 0)) {
3108 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
3109 $this->errors[] = $this->db->lasterror();
3111 $contactstatic->country_id = $result;
3112 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
3116 if (!$errorforactions) {
3118 if (!empty($contactstatic->state)) {
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 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
3133 if (empty($result)) {
3135 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
3136 } elseif (!($result > 0)) {
3138 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
3139 $this->errors[] = $this->db->lasterror();
3141 $contactstatic->state_id = $result;
3142 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
3147 if (!$errorforactions) {
3148 $result = $contactstatic->create($user);
3151 $this->error = $contactstatic->error;
3152 $this->errors = $contactstatic->errors;
3154 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag((
string) $contactstatic->id);
3161 } elseif ($operation[
'type'] ==
'recordevent') {
3165 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
3166 if ($alreadycreated == 0) {
3167 $operationslog .=
'<br>We did not find existing actioncomm with msgid='.$msgid;
3169 if ($projectstatic->id > 0) {
3170 if ($projectfoundby) {
3171 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
3174 if ($thirdpartystatic->id > 0) {
3175 if ($thirdpartyfoundby) {
3176 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3179 if ($contactstatic->id > 0) {
3180 if ($contactfoundby) {
3181 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3185 $description = $descriptiontitle;
3191 $descriptionfull = $description;
3193 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3198 $actioncomm->type_code =
'AC_OTH_AUTO';
3199 $actioncomm->code =
'AC_'.$actioncode;
3200 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$email_from;
3201 $actioncomm->note_private = $descriptionfull;
3202 $actioncomm->fk_project = $projectstatic->id;
3203 $actioncomm->datep = $dateemail;
3204 $actioncomm->datef = $dateemail;
3205 $actioncomm->percentage = -1;
3206 $actioncomm->socid = $thirdpartystatic->id;
3207 $actioncomm->contact_id = $contactstatic->id;
3208 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array());
3209 $actioncomm->authorid = $user->id;
3210 $actioncomm->userownerid = $user->id;
3212 $actioncomm->email_msgid = $msgid;
3213 $actioncomm->email_from = $fromstring;
3214 $actioncomm->email_sender = $sender;
3215 $actioncomm->email_to = $to;
3216 $actioncomm->email_tocc = $sendtocc;
3217 $actioncomm->email_tobcc = $sendtobcc;
3218 $actioncomm->email_subject = $subject;
3219 $actioncomm->errors_to =
'';
3221 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
3222 $actioncomm->fk_element = $fk_element_id;
3223 $actioncomm->elementid = $fk_element_id;
3224 $actioncomm->elementtype = $fk_element_type;
3225 if (is_object($objectemail) && $objectemail->module) {
3226 $actioncomm->elementtype .=
'@'.$objectemail->module;
3233 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3235 if ($errorforthisaction) {
3238 $result = $actioncomm->create($user);
3241 $this->errors = $actioncomm->errors;
3243 if ($fk_element_type ==
"ticket" && is_object($objectemail)) {
3244 if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED || $objectemail->status == Ticket::STATUS_NEED_MORE_INFO || $objectemail->status == Ticket::STATUS_WAITING) {
3245 if ($objectemail->fk_user_assign !=
null) {
3246 $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED);
3248 $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ);
3252 $operationslog .=
'<br>Ticket Re-Opened successfully -> ref='.$objectemail->ref;
3255 $this->error =
'Error while changing the ticket status -> ref='.$objectemail->ref;
3256 $this->errors[] = $this->error;
3259 if (!empty($attachments)) {
3261 $ticket =
new Ticket($this->db);
3262 $ticket->fetch($fk_element_id);
3263 $destdir =
$conf->ticket->dir_output.
'/'.$ticket->ref;
3269 foreach ($attachments as $attachment) {
3271 $filename = (string) $attachment->getName();
3272 }
catch (Throwable $e) {
3279 $this->
saveAttachment($destdir, $filename, (
string) $attachment->getContent());
3281 if ($skippedatt > 0) {
3282 $operationslog .=
'<br>Skipped '.$skippedatt.
' attachment(s) due to allowed extensions filter';
3285 $this->
getmsg($connection, $imapemail, $destdir);
3290 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag((
string) $actioncomm->id);
3294 $operationslog .=
'<br>An event in actioncomm table already exists for the msgid = '.$msgid.
' so we bypass this action.';
3296 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
3300 foreach ($attachments as $attachment) {
3302 $filename = (string) $attachment->getName();
3303 }
catch (Throwable $e) {
3310 $data[$filename] = $attachment->getContent();
3314 foreach ($pj as $key => $val) {
3319 $data[$val[
'filename']] =
getFileData($imapemail, (
string) $val[
'pos'], $val[
'type'], $connection);
3322 if ($skippedatt > 0) {
3323 $operationslog .=
'<br>Skipped '.$skippedatt.
' attachment(s) due to allowed extensions filter';
3325 if (count($data) > 0) {
3326 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($email_from).
"%'";
3327 $resql = $this->db->query($sql);
3328 if ($this->db->num_rows($resql) == 0) {
3329 $this->errors[] =
"User Not allowed to add documents ({$email_from})";
3331 $arrayobject = array(
3332 'propale' => array(
'table' =>
'propal',
3333 'fields' => array(
'ref'),
3334 'class' =>
'comm/propal/class/propal.class.php',
3335 'object' =>
'Propal'),
3336 'holiday' => array(
'table' =>
'holiday',
3337 'fields' => array(
'ref'),
3338 'class' =>
'holiday/class/holiday.class.php',
3339 'object' =>
'Holiday'),
3340 'expensereport' => array(
'table' =>
'expensereport',
3341 'fields' => array(
'ref'),
3342 'class' =>
'expensereport/class/expensereport.class.php',
3343 'object' =>
'ExpenseReport'),
3344 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
3345 'fields' => array(
'ref'),
3346 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
3347 'object' =>
'RecruitmentJobPosition'),
3348 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
3349 'fields' => array(
'ref'),
3350 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
3351 'object' =>
'RecruitmentCandidature'),
3352 'societe' => array(
'table' =>
'societe',
3353 'fields' => array(
'code_client',
'code_fournisseur'),
3354 'class' =>
'societe/class/societe.class.php',
3355 'object' =>
'Societe'),
3356 'commande' => array(
'table' =>
'commande',
3357 'fields' => array(
'ref'),
3358 'class' =>
'commande/class/commande.class.php',
3359 'object' =>
'Commande'),
3360 'expedition' => array(
'table' =>
'expedition',
3361 'fields' => array(
'ref'),
3362 'class' =>
'expedition/class/expedition.class.php',
3363 'object' =>
'Expedition'),
3364 'contract' => array(
'table' =>
'contrat',
3365 'fields' => array(
'ref'),
3366 'class' =>
'contrat/class/contrat.class.php',
3367 'object' =>
'Contrat'),
3368 'fichinter' => array(
'table' =>
'fichinter',
3369 'fields' => array(
'ref'),
3370 'class' =>
'fichinter/class/fichinter.class.php',
3371 'object' =>
'Fichinter'),
3372 'ticket' => array(
'table' =>
'ticket',
3373 'fields' => array(
'ref'),
3374 'class' =>
'ticket/class/ticket.class.php',
3375 'object' =>
'Ticket'),
3376 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
3377 'fields' => array(
'ref'),
3378 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
3379 'object' =>
'KnowledgeRecord'),
3380 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
3381 'fields' => array(
'ref'),
3382 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
3383 'object' =>
'SupplierProposal'),
3384 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
3385 'fields' => array(
'ref',
'ref_supplier'),
3386 'class' =>
'fourn/class/fournisseur.commande.class.php',
3387 'object' =>
'SupplierProposal'),
3388 'facture' => array(
'table' =>
'facture',
3389 'fields' => array(
'ref'),
3390 'class' =>
'compta/facture/class/facture.class.php',
3391 'object' =>
'Facture'),
3392 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
3393 'fields' => array(
'ref',
'ref_client'),
3394 'class' =>
'fourn/class/fournisseur.facture.class.php',
3395 'object' =>
'FactureFournisseur'),
3396 'produit' => array(
'table' =>
'product',
3397 'fields' => array(
'ref'),
3398 'class' =>
'product/class/product.class.php',
3399 'object' =>
'Product'),
3400 'productlot' => array(
'table' =>
'product_lot',
3401 'fields' => array(
'batch'),
3402 'class' =>
'product/stock/class/productlot.class.php',
3403 'object' =>
'Productlot'),
3404 'projet' => array(
'table' =>
'projet',
3405 'fields' => array(
'ref'),
3406 'class' =>
'projet/class/projet.class.php',
3407 'object' =>
'Project'),
3408 'projet_task' => array(
'table' =>
'projet_task',
3409 'fields' => array(
'ref'),
3410 'class' =>
'projet/class/task.class.php',
3411 'object' =>
'Task'),
3412 'ressource' => array(
'table' =>
'resource',
3413 'fields' => array(
'ref'),
3414 'class' =>
'ressource/class/dolressource.class.php',
3415 'object' =>
'Dolresource'),
3416 'bom' => array(
'table' =>
'bom_bom',
3417 'fields' => array(
'ref'),
3418 'class' =>
'bom/class/bom.class.php',
3420 'mrp' => array(
'table' =>
'mrp_mo',
3421 'fields' => array(
'ref'),
3422 'class' =>
'mrp/class/mo.class.php',
3426 if (!is_object($hookmanager)) {
3427 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3430 $hookmanager->initHooks(array(
'emailcolector',
'emailcollector'));
3431 $parameters = array(
'arrayobject' => $arrayobject);
3432 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
3434 $arrayobject = $hookmanager->resArray;
3437 $resultobj = array();
3439 foreach ($arrayobject as $key => $objectdesc) {
3440 $sql =
'SELECT DISTINCT t.rowid ';
3441 $sql .=
' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc[
'table']) .
' AS t';
3443 foreach ($objectdesc[
'fields'] as $field) {
3444 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $this->db->sanitize($field) .
", '%') AND t." . $this->db->sanitize($field) .
" <> '') OR ";
3446 $sql = substr($sql, 0, -4);
3448 $ressqlobj = $this->db->query($sql);
3450 while ($obj = $this->db->fetch_object($ressqlobj)) {
3451 $resultobj[$key][] = $obj->rowid;
3456 foreach ($resultobj as $mod => $ids) {
3457 $moddesc = $arrayobject[$mod];
3458 $elementpath = $mod;
3460 $objectmanaged =
new $moddesc[
'object']($this->db);
3461 '@phan-var-force CommonObject $objectmanaged';
3462 foreach ($ids as $val) {
3463 $res = $objectmanaged->fetch($val);
3465 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
3466 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
3468 $this->errors[] =
'object not found';
3472 foreach ($dirs as $target) {
3473 $prefix = $this->actions[$this->id][
'actionparam'];
3474 foreach ($data as $filename => $content) {
3475 $resr = $this->
saveAttachment($target, $prefix .
'_' . $filename, $content);
3477 $this->errors[] =
'Doc not saved';
3482 $operationslog .=
'<br>Save attachment files on disk';
3484 $this->errors[] =
'no joined piece';
3486 $operationslog .=
'<br>No joinded files';
3488 } elseif ($operation[
'type'] ==
'project') {
3490 $projecttocreate =
new Project($this->db);
3491 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
3492 if ($alreadycreated == 0) {
3493 if ($thirdpartystatic->id > 0) {
3494 $projecttocreate->socid = $thirdpartystatic->id;
3495 if ($thirdpartyfoundby) {
3496 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3499 if ($contactstatic->id > 0) {
3500 $projecttocreate->contact_id = $contactstatic->id;
3501 if ($contactfoundby) {
3502 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3506 $description = $descriptiontitle;
3512 $descriptionfull = $description;
3514 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3518 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
3519 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
3521 $projecttocreate->title = $subject;
3522 $projecttocreate->date_start = $dateemail;
3523 $projecttocreate->date_end = 0;
3524 $projecttocreate->opp_status = $id_opp_status;
3525 $projecttocreate->opp_percent = $percent_opp_status;
3527 $projecttocreate->note_private = $descriptionfull;
3528 $projecttocreate->entity =
$conf->entity;
3530 $projecttocreate->email_date = $dateemail;
3531 $projecttocreate->email_msgid = $msgid;
3532 $projecttocreate->email_from = $fromstring;
3533 $projecttocreate->email_sender = $sender;
3534 $projecttocreate->email_to = $to;
3535 $projecttocreate->email_tocc = $sendtocc;
3536 $projecttocreate->email_tobcc = $sendtobcc;
3537 $projecttocreate->email_subject = $subject;
3538 $projecttocreate->errors_to =
'';
3540 $savesocid = $projecttocreate->socid;
3544 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3548 if (empty($projecttocreate->ref)) {
3557 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
3558 foreach ($dirmodels as $reldir) {
3559 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
3560 if (file_exists($file)) {
3561 $classname = $modele;
3566 if ($classname !==
'') {
3567 if ($savesocid > 0) {
3568 if ($savesocid != $projecttocreate->socid) {
3570 $this->error =
'You loaded a thirdparty (id='.$savesocid.
') and you force another thirdparty id (id='.$projecttocreate->socid.
') by setting socid in operation with a different value';
3571 $this->errors[] = $this->error;
3574 if ($projecttocreate->socid > 0) {
3575 $thirdpartystatic->fetch($projecttocreate->socid);
3579 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
3580 $modModuleToUseForNextValue =
new $classname();
3581 '@phan-var-force ModeleNumRefProjects $modModuleToUseForNextValue';
3582 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
3584 $projecttocreate->ref = $defaultref;
3588 if ($errorforthisaction) {
3591 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
3593 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3595 $operationslog .=
'<br>'.$this->error;
3598 $result = $projecttocreate->create($user);
3601 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
3602 $this->errors = $projecttocreate->errors;
3604 $operationslog .=
'<br>'.$this->error;
3607 $destdir =
$conf->project->dir_output.
'/'.$projecttocreate->ref;
3613 foreach ($attachments as $attachment) {
3615 $filename = $attachment->getFilename();
3620 $content = $attachment->getContent();
3623 if ($skippedatt > 0) {
3624 $operationslog .=
'<br>Skipped '.$skippedatt.
' attachment(s) due to allowed extensions filter';
3627 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3629 $this->errors = array_merge($this->errors, [$this->error]);
3634 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3636 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3644 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3646 } elseif ($operation[
'type'] ==
'ticket') {
3648 $tickettocreate =
new Ticket($this->db);
3649 if ($ticketalreadyexists == 0) {
3650 if ($thirdpartystatic->id > 0) {
3651 $tickettocreate->socid = $thirdpartystatic->id;
3652 $tickettocreate->fk_soc = $thirdpartystatic->id;
3653 if ($thirdpartyfoundby) {
3654 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3657 if ($contactstatic->id > 0) {
3658 $tickettocreate->contact_id = $contactstatic->id;
3659 if ($contactfoundby) {
3660 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3664 $description = $descriptiontitle;
3670 $descriptionfull = $description;
3672 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3676 $tickettocreate->subject = $subject;
3677 $tickettocreate->message = $description;
3679 $tickettocreate->category_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1)));
3680 $tickettocreate->severity_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1)));
3681 $tickettocreate->origin_email = $email_from;
3682 $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto :
null);
3683 $tickettocreate->origin_references = (!empty($headers[
'References']) ? $headers[
'References'] :
null);
3684 $tickettocreate->fk_user_create = $user->id;
3685 $tickettocreate->datec =
dol_now();
3686 $tickettocreate->fk_project = $projectstatic->id;
3687 $tickettocreate->notify_tiers_at_create =
getDolGlobalInt(
'TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3688 $tickettocreate->note_private = $descriptionfull;
3689 $tickettocreate->entity =
$conf->entity;
3691 $tickettocreate->email_date = $dateemail;
3692 $tickettocreate->email_msgid = $msgid;
3693 $tickettocreate->email_from = $fromstring;
3694 $tickettocreate->email_sender = $sender;
3695 $tickettocreate->email_to = $to;
3696 $tickettocreate->email_tocc = $sendtocc;
3697 $tickettocreate->email_tobcc = $sendtobcc;
3698 $tickettocreate->email_subject = $subject;
3699 $tickettocreate->errors_to =
'';
3703 $savesocid = $tickettocreate->socid;
3707 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3709 $modele =
'UNDEFINED';
3711 if (empty($tickettocreate->ref)) {
3720 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
3721 foreach ($dirmodels as $reldir) {
3722 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3723 if (file_exists($file)) {
3724 $classname = $modele;
3729 if ($classname !==
'') {
3730 if ($savesocid > 0) {
3731 if ($savesocid != $tickettocreate->socid) {
3733 $this->error =
'You loaded a thirdparty (id='.$savesocid.
') and you force another thirdparty id (id='.$tickettocreate->socid.
') by setting socid in operation with a different value';
3734 $this->errors[] = $this->error;
3737 if ($tickettocreate->socid > 0) {
3738 $thirdpartystatic->fetch($tickettocreate->socid);
3743 $modModuleToUseForNextValue =
new $classname();
3744 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3745 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3747 $tickettocreate->ref = $defaultref;
3750 if ($errorforthisaction) {
3753 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3755 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3758 $tickettocreate->context[
'actionmsg2'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3759 $tickettocreate->context[
'actionmsg'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3763 $sender_contact =
new Contact($this->db);
3764 $sender_contact->fetch(0,
null,
'', $email_from);
3765 if (!empty($sender_contact->id)) {
3766 $tickettocreate->context[
'contact_id'] = $sender_contact->id;
3769 $result = $tickettocreate->create($user);
3772 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3773 $this->errors = $tickettocreate->errors;
3776 $destdir =
$conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3782 foreach ($attachments as $attachment) {
3784 $filename = $attachment->getName();
3789 $content = $attachment->getContent();
3792 if ($skippedatt > 0) {
3793 $operationslog .=
'<br>Skipped '.$skippedatt.
' attachment(s) due to allowed extensions filter';
3796 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3798 $this->errors = array_merge($this->errors, [$this->error]);
3803 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3805 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3814 $operationslog .=
'<br>Ticket already exists, so we bypass action "ticket"';
3816 } elseif ($operation[
'type'] ==
'candidature') {
3820 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3821 if ($alreadycreated == 0) {
3822 $description = $descriptiontitle;
3828 $descriptionfull = $description;
3830 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3834 $candidaturetocreate->subject = $subject;
3835 $candidaturetocreate->message = $description;
3836 $candidaturetocreate->type_code = 0;
3837 $candidaturetocreate->category_code =
null;
3838 $candidaturetocreate->severity_code =
null;
3839 $candidaturetocreate->email = $email_from;
3841 $candidaturetocreate->fk_user_creat = $user->id;
3842 $candidaturetocreate->date_creation =
dol_now();
3843 $candidaturetocreate->fk_project = $projectstatic->id;
3844 $candidaturetocreate->description = $description;
3845 $candidaturetocreate->note_private = $descriptionfull;
3846 $candidaturetocreate->entity =
$conf->entity;
3847 $candidaturetocreate->email_msgid = $msgid;
3848 $candidaturetocreate->email_date = $dateemail;
3849 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3854 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3898 if ($errorforthisaction) {
3902 $result = $candidaturetocreate->create($user);
3905 $this->error =
'Failed to create candidature: '.implode(
', ', $candidaturetocreate->errors);
3906 $this->errors = $candidaturetocreate->errors;
3909 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag((
string) $candidaturetocreate->id);
3912 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3915 if (!is_object($hookmanager)) {
3916 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3919 $hookmanager->initHooks(array(
'emailcolector',
'emailcollector'));
3921 $parameters = array(
3922 'connection' => $connection,
3923 'imapemail' => $imapemail,
3924 'overview' => $overview,
3926 'from' => $email_from,
3927 'fromtext' => $fromtext,
3929 'actionparam' => $operation[
'actionparam'],
3931 'thirdpartyid' => ($thirdpartyid ? $thirdpartyid : $thirdpartystatic->id),
3932 'objectid' => $objectid,
3933 'objectemail' => $objectemail,
3935 'messagetext' => $messagetext,
3936 'subject' => $subject,
3937 'header' => $header,
3938 'attachments' => $attachments,
3939 'savedattachments' => $savedattachments,
3940 'savedattachmentsdir' => $savedattachmentsdir,
3942 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3945 $errorforthisaction++;
3946 $this->error = $hookmanager->resPrint;
3947 if (!empty($hookmanager->resPrint)) {
3948 $operationslog .=
'<br>Hook error: '.dol_escape_htmltag($hookmanager->resPrint);
3951 if ($errorforthisaction) {
3953 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3955 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3959 if (!$errorforactions) {
3960 $nbactiondoneforemail++;
3966 if (!$errorforactions) {
3967 if (!empty($targetdir)) {
3970 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3971 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid.
' - '.$imapemail->getHeader()->get(
'subject').
' to '.$targetdir;
3973 $arrayofemailtodelete[$this->
uidAsString($imapemail)] = $imapemail;
3976 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3977 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3979 $arrayofemailtodelete[$imapemail] = $msgid;
3984 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);
3986 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3994 unset($objectemail);
3995 unset($projectstatic);
3996 unset($thirdpartystatic);
3997 unset($contactstatic);
3999 $nbemailprocessed++;
4001 if (!$errorforemail) {
4002 $nbactiondone += $nbactiondoneforemail;
4006 $this->db->commit();
4008 $this->db->rollback();
4012 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
4013 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
4014 $datelastok = strtotime($headers[
'Date']);
4020 $this->db->rollback();
4024 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
4026 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
4028 $langs->load(
"admin");
4029 $output = $langs->trans(
'NoNewEmailToProcess');
4030 $output .=
' (defaultlang='.$langs->defaultlang.
')';
4036 krsort($arrayofemailtodelete, SORT_NUMERIC);
4038 foreach ($arrayofemailtodelete as $imapemailnum => $imapemail) {
4039 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemailnum);
4041 $operationslog .=
"<br> move email ".$imapemailnum.($mode > 0 ?
' (test)' :
'');
4043 if (empty($mode) && empty($error)) {
4044 $tmptargetdir = $targetdir;
4051 $result = $imapemail->move($tmptargetdir,
false);
4054 $operationslog .=
'<br>Exception !!!! '.$e->getMessage();
4056 if (empty($result)) {
4057 dol_syslog(
"Failed to move email into target directory ".$targetdir);
4058 $operationslog .=
'<br>Failed to move email into target directory '.$targetdir;
4064 if (empty($mode) && empty($error)) {
4066 $operationslog .=
"<br>Expunge";
4071 $client->disconnect();
4073 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
4074 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
4076 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid.($mode > 0 ?
' (test)' :
'');
4078 if (empty($mode) && empty($error)) {
4079 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
4082 $this->error = imap_last_error();
4083 $this->errors[] = $this->error;
4085 $operationslog .=
'<br>Error in move '.$this->error;
4092 if (empty($mode) && empty($error)) {
4094 $operationslog .=
"<br>Expunge";
4096 imap_expunge($connection);
4098 imap_close($connection);
4101 $this->datelastresult = $now;
4102 $this->lastresult = $output;
4104 $this->debuginfo .=
'IMAP search array used : '.$search;
4106 $this->debuginfo .=
'IMAP search string used : '.$search;
4109 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
4111 if ($operationslog) {
4112 $this->debuginfo .= $operationslog;
4115 if (empty($error) && empty($mode)) {
4116 $this->datelastok = $datelastok;
4119 if (!empty($this->errors)) {
4120 $this->lastresult .=
"<br>".implode(
"<br>", $this->errors);
4122 $this->codelastresult = ($error ?
'KO' :
'OK');
4128 dol_syslog(
"EmailCollector::doCollectOneCollector end error=".$error, LOG_INFO);
4130 return $error ? -1 : 1;
4145 private function getmsg($mbox, $mid, $destdir =
''): int
4149 global $charset, $htmlmsg, $plainmsg, $attachments;
4150 $htmlmsg = $plainmsg = $charset =
'';
4151 $attachments = array();
4158 $s = imap_fetchstructure($mbox, $mid, FT_UID);
4160 $this->errors = array_merge($this->errors, [imap_last_error()]);
4164 if (empty($s->parts)) {
4166 $this->
getpart($mbox, $mid, $s,
'0');
4169 foreach ($s->parts as $partno0 => $p) {
4170 $this->
getpart($mbox, $mid, $p, (
string) ($partno0 + 1), $destdir);
4203 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
4206 global $htmlmsg, $plainmsg, $charset, $attachments;
4210 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
4211 imap_body($mbox, $mid, FT_UID);
4213 if ($p->encoding == 4) {
4214 $data = quoted_printable_decode($data);
4215 } elseif ($p->encoding == 3) {
4216 $data = base64_decode($data);
4222 if ($p->parameters) {
4223 foreach ($p->parameters as $x) {
4224 $params[strtolower($x->attribute)] = $x->value;
4227 if (!empty($p->dparameters)) {
4228 foreach ($p->dparameters as $x) {
4229 $params[strtolower($x->attribute)] = $x->value;
4232 '@phan-var-force array{filename?:string,name?:string,charset?:string} $params';
4237 if ((!empty($params[
'filename']) || !empty($params[
'name'])) && $this->
isAllowedAttachmentFilename((
string) ($params[
'filename'] ?? $params[
'name']))) {
4239 $filename = $params[
'filename'] ?? $params[
'name'];
4241 $attachments[$filename] = $data;
4243 if (strlen($destdir)) {
4250 if ($p->type == 0 && $data) {
4251 if (!empty($params[
'charset'])) {
4256 if (strtolower($p->subtype) ==
'plain') {
4257 $plainmsg .= trim($data).
"\n\n";
4259 $htmlmsg .= $data.
"<br><br>";
4261 $charset = $params[
'charset'];
4262 } elseif ($p->type == 2 && $data) {
4268 if (!empty($params[
'charset'])) {
4271 $plainmsg .= $data.
"\n\n";
4275 if (!empty($p->parts)) {
4276 foreach ($p->parts as $partno0 => $p2) {
4277 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1), $destdir);
4293 if (!$string || $fromEncoding == $toEncoding) {
4296 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
4297 if (!$convertedString && extension_loaded(
'mbstring')) {
4298 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
4300 if (!$convertedString) {
4301 throw new Exception(
'Mime string encoding conversion failed');
4303 return $convertedString;
4322 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
4323 $elements = imap_mime_header_decode($subject);
4325 if (!empty($elements)) {
4326 $num = count($elements);
4327 for ($i = 0; $i < $num; $i++) {
4328 $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));
4329 $newstring .= $stringinutf8;
4331 $subject = $newstring;
4333 } elseif (!function_exists(
'mb_decode_mimeheader')) {
4334 $subject = mb_decode_mimeheader($subject);
4335 } elseif (function_exists(
'iconv_mime_decode')) {
4336 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
4339 return (
string) $subject;
4349 private function saveEmailCollectorAttachmentsToDir($destdir, $attachments)
4351 $destdir = rtrim((
string) $destdir,
'/');
4352 if ($destdir ===
'' || empty($attachments) || !is_array($attachments)) {
4363 $seenHashes = array();
4366 $filelist =
dol_dir_list($destdir,
'files', 0,
'',
'(\\.meta|_preview.*.*\\.png)$',
'date', SORT_DESC, 0, 1);
4367 foreach ($filelist as $fileinfo) {
4368 if (empty($fileinfo[
'fullname']) || !is_file($fileinfo[
'fullname']) || !is_readable($fileinfo[
'fullname'])) {
4371 $hash = hash_file(
'sha256', $fileinfo[
'fullname']);
4372 if ($hash !==
false && empty($seenHashes[$hash])) {
4373 $seenHashes[$hash] = $fileinfo[
'name'];
4379 if (defined(
'DOL_DATA_ROOT')) {
4380 $root = rtrim((
string) DOL_DATA_ROOT,
'/').
'/';
4381 $destdirwithslash = $destdir.
'/';
4382 if (strpos($destdirwithslash, $root) === 0) {
4383 $relativeDir = rtrim(substr($destdirwithslash, strlen($root)),
'/');
4388 foreach ($attachments as $key => $attachment) {
4395 if (is_object($attachment)) {
4396 '@phan-var-force Webklex\PHPIMAP\Attachment $attachment';
4399 $origName = (string) $attachment->getName();
4400 }
catch (Throwable $e) {
4404 $content = (string) $attachment->getContent();
4405 }
catch (Throwable $e) {
4409 $tmpmime = (string) $attachment->getContentType();
4410 $mime = ($tmpmime !==
'' ? $tmpmime :
null);
4411 }
catch (Throwable $e) {
4416 $origName = (string) $key;
4417 $content = (string) $attachment;
4420 if ($origName ===
'' || $origName ===
'undefined') {
4421 $origName =
'attachment-'.$index;
4426 if ($content ===
'') {
4431 if ($safeName ===
'') {
4432 $safeName =
'attachment-'.$index;
4435 $contentHash = hash(
'sha256', $content);
4436 $finalName = $safeName;
4437 $useExisting =
false;
4438 if (!empty($seenHashes[$contentHash])) {
4439 $finalName = $seenHashes[$contentHash];
4440 if (file_exists($destdir.
'/'.$finalName)) {
4441 $useExisting =
true;
4445 if (!$useExisting) {
4447 while (file_exists($destdir.
'/'.$finalName)) {
4448 $finalName = preg_replace(
'/(\\.[A-Za-z0-9]{1,10})$/',
'', $safeName).
'-'.$n;
4449 if (preg_match(
'/\\.[A-Za-z0-9]{1,10}$/', $safeName, $m)) {
4450 $finalName .= $m[0];
4455 $resultsave = $this->
saveAttachment($destdir, $finalName, $content);
4456 if (!is_string($resultsave)) {
4459 $finalName = basename($resultsave);
4460 $seenHashes[$contentHash] = $finalName;
4463 $fullPath = $destdir.
'/'.$finalName;
4464 $size = (file_exists($fullPath) ? filesize($fullPath) : null);
4465 $sizevalue = ($size ===
false ? null : $size);
4466 $sha256 = $contentHash;
4469 'name' => $finalName,
4470 'original_name' => $origName,
4471 'relative_path' => ($relativeDir !==
'' ? $relativeDir.
'/'.$finalName :
''),
4472 'content_type' => $mime,
4473 'size' => ($sizevalue !== null ? (int) $sizevalue : null),
4474 'sha256' => $sha256,
4492 static $allowedExtRaw =
null;
4493 static $allowedExtMap =
null;
4500 if ($allowedExtRaw !== $raw) {
4501 $allowedExtRaw = $raw;
4502 $allowedExtMap = array();
4503 $tokens = preg_split(
'/[\s,;]+/', strtolower($raw));
4504 if (is_array($tokens)) {
4505 foreach ($tokens as $token) {
4506 $token = (string) preg_replace(
'/[^a-z0-9]+/',
'', ltrim(trim($token),
'.'));
4507 if ($token !==
'') {
4508 $allowedExtMap[$token] =
true;
4515 if (empty($allowedExtMap)) {
4519 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
4520 return $extension !==
'' && !empty($allowedExtMap[$extension]);
4535 require_once DOL_DOCUMENT_ROOT .
'/core/lib/images.lib.php';
4541 $filename = preg_replace(
'/[\x00-\x1F\x7F]/',
'', $filename);
4542 $filename = preg_replace(
'/^\.+/',
'', rtrim($filename,
'. '));
4543 if ($filename ===
'') {
4544 $filename =
'attachment';
4547 if (!file_exists($destdir)) {
4553 $tmp = explode(
'.', $filename);
4554 $ext = (count($tmp) > 1 ?
'.' . array_pop($tmp) :
'');
4555 $filename = implode(
'.', $tmp);
4564 $filepath = $destdir . (preg_match(
'/\/$/', $destdir) ?
'' :
'/') . $filename . $ext;
4566 while (file_exists($filepath)) {
4567 $filepath = $destdir . (preg_match(
'/\/$/', $destdir) ?
'' :
'/') . $filename .
'(' . $i .
')' . $ext;
4573 $tmpdir =
$conf->admin->dir_temp;
4577 $tmpfile = $tmpdir.
'/emailcollector_attachment_'.
dol_hash(uniqid((
string) mt_rand(),
true),
'md5');
4578 if (file_put_contents($tmpfile, $content) ===
false) {
4582 if (count($checkvirusarray)) {
4583 dol_syslog(
'EmailCollector::saveAttachment File "'.$filepath.
'" KO with antivirus: errors='.implode(
',', $checkvirusarray), LOG_WARNING);
4587 if (!
dol_move($tmpfile, $filepath,
'0', 0, 0, 0)) {
4595 $filename = basename($filepath);
4599 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
4600 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
4601 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
4602 $maxheightmini = $tmparraysize[
'maxheightmini'];
4603 $quality = $tmparraysize[
'quality'];
4606 vignette($filepath, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
4608 vignette($filepath, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
4624 if (is_object($imapemail)) {
4625 return $imapemail->getAttributes()[
"uid"];
4627 return (
string) $imapemail;