66 public $element =
'emailcollector';
71 public $table_element =
'emailcollector_emailcollector';
76 public $picto =
'email';
81 public $fk_element =
'fk_emailcollector';
86 protected $childtables = array();
91 protected $childtablesoncascade = array(
'emailcollector_emailcollectorfilter',
'emailcollector_emailcollectoraction');
117 public $fields = array(
118 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'visible' => -2,
'enabled' => 1,
'position' => 1,
'notnull' => 1,
'index' => 1),
119 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'enabled' => 1,
'visible' => 0,
'default' =>
'1',
'notnull' => 1,
'index' => 1,
'position' => 20),
120 'ref' => array(
'type' =>
'varchar(128)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'showoncombobox' => 1,
'index' => 1,
'position' => 10,
'searchall' => 1,
'help' =>
'Example: MyCollector1',
'csslist' =>
'tdoverflowmax200'),
121 'label' => array(
'type' =>
'varchar(255)',
'label' =>
'Label',
'visible' => 1,
'enabled' => 1,
'position' => 30,
'notnull' => -1,
'searchall' => 1,
'help' =>
'Example: My Email collector',
'csslist' =>
'tdoverflowmax150 small',
'tdcss' =>
'titlefieldmiddle'),
122 'description' => array(
'type' =>
'text',
'label' =>
'Description',
'visible' => -1,
'enabled' => 1,
'position' => 60,
'notnull' => -1,
'cssview' =>
'small',
'csslist' =>
'small tdoverflowmax200'),
123 'host' => array(
'type' =>
'varchar(255)',
'label' =>
'EMailHost',
'visible' => 1,
'enabled' => 1,
'position' => 90,
'notnull' => 1,
'searchall' => 1,
'comment' =>
"IMAP server",
'help' =>
'Example: imap.gmail.com',
'csslist' =>
'tdoverflowmax125'),
124 'port' => array(
'type' =>
'varchar(10)',
'label' =>
'EMailHostPort',
'visible' => 1,
'enabled' => 1,
'position' => 91,
'notnull' => 1,
'searchall' => 0,
'comment' =>
"IMAP server port",
'help' =>
'Example: 993',
'csslist' =>
'tdoverflowmax50',
'default' =>
'993'),
125 'imap_encryption' => array(
'type' =>
'varchar(16)',
'label' =>
'ImapEncryption',
'visible' => -1,
'enabled' => 1,
'position' => 92,
'searchall' => 0,
'comment' =>
"IMAP encryption",
'help' =>
'ImapEncryptionHelp',
'arrayofkeyval' => array(
'ssl' =>
'SSL',
'tls' =>
'TLS',
'notls' =>
'NOTLS'),
'default' =>
'ssl'),
126 'hostcharset' => array(
'type' =>
'varchar(16)',
'label' =>
'HostCharset',
'visible' => -1,
'enabled' => 1,
'position' => 93,
'notnull' => 0,
'searchall' => 0,
'comment' =>
"IMAP server charset",
'help' =>
'Example: "UTF-8" (May be "US-ASCII" with some Office365)',
'default' =>
'UTF-8'),
127 'norsh' => array(
'type' =>
'integer',
'label' =>
'NoRSH',
'visible' => -1,
'enabled' =>
"!getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')",
'position' => 94,
'searchall' => 0,
'help' =>
'NoRSHHelp',
'arrayofkeyval' => array(0 =>
'No', 1 =>
'Yes'),
'default' =>
'0'),
128 'acces_type' => array(
'type' =>
'integer',
'label' =>
'AuthenticationMethod',
'visible' => -1,
'enabled' =>
"getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')",
'position' => 101,
'notnull' => 1,
'index' => 1,
'comment' =>
"IMAP login type",
'arrayofkeyval' => array(0 =>
'loginPassword', 1 =>
'oauthToken'),
'default' =>
'0',
'help' =>
''),
129 'login' => array(
'type' =>
'varchar(128)',
'label' =>
'Login',
'visible' => -1,
'enabled' => 1,
'position' => 102,
'notnull' => -1,
'index' => 1,
'comment' =>
"IMAP login",
'help' =>
'Example: myaccount@gmail.com'),
130 'password' => array(
'type' =>
'password',
'label' =>
'Password',
'visible' => -1,
'enabled' =>
"1",
'position' => 103,
'notnull' => -1,
'comment' =>
"IMAP password",
'help' =>
'WithGMailYouCanCreateADedicatedPassword'),
131 'oauth_service' => array(
'type' =>
'varchar(128)',
'label' =>
'oauthService',
'visible' => -1,
'enabled' =>
"getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')",
'position' => 104,
'notnull' => 0,
'index' => 1,
'comment' =>
"IMAP login oauthService",
'arrayofkeyval' => array(),
'help' =>
'TokenMustHaveBeenCreated'),
132 'source_directory' => array(
'type' =>
'varchar(255)',
'label' =>
'MailboxSourceDirectory',
'visible' => -1,
'enabled' => 1,
'position' => 109,
'notnull' => 1,
'default' =>
'Inbox',
'csslist' =>
'tdoverflowmax100',
'help' =>
'Example: INBOX, [Gmail]/Spam, [Gmail]/Draft, [Gmail]/Brouillons, [Gmail]/Sent Mail, [Gmail]/Messages envoyés, ...'),
133 'target_directory' => array(
'type' =>
'varchar(255)',
'label' =>
'MailboxTargetDirectory',
'visible' => 1,
'enabled' => 1,
'position' => 110,
'notnull' => 0,
'csslist' =>
'tdoverflowmax100',
'help' =>
"EmailCollectorTargetDir"),
134 'maxemailpercollect' => array(
'type' =>
'integer',
'label' =>
'MaxEmailCollectPerCollect',
'visible' => -1,
'enabled' => 1,
'position' => 111,
'default' =>
'50'),
135 'datelastresult' => array(
'type' =>
'datetime',
'label' =>
'DateLastCollectResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 121,
'notnull' => -1,
'csslist' =>
'nowraponall'),
136 'codelastresult' => array(
'type' =>
'varchar(16)',
'label' =>
'CodeLastResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 122,
'notnull' => -1,),
137 'lastresult' => array(
'type' =>
'varchar(255)',
'label' =>
'LastResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 123,
'notnull' => -1,
'cssview' =>
'small',
'csslist' =>
'maxwidth250imp'),
138 'datelastok' => array(
'type' =>
'datetime',
'label' =>
'DateLastcollectResultOk',
'visible' => 1,
'enabled' =>
'$action != "create"',
'position' => 125,
'notnull' => -1,
'csslist' =>
'nowraponall'),
139 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'visible' => 0,
'enabled' => 1,
'position' => 61,
'notnull' => -1,),
140 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'visible' => 0,
'enabled' => 1,
'position' => 62,
'notnull' => -1,),
141 'date_creation' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'visible' => -2,
'enabled' => 1,
'position' => 500,
'notnull' => 1,),
142 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModification',
'visible' => -2,
'enabled' => 1,
'position' => 501,
'notnull' => 1,),
144 'fk_user_creat' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'visible' => -2,
'enabled' => 1,
'position' => 510,
'notnull' => 1,),
145 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModif',
'visible' => -2,
'enabled' => 1,
'position' => 511,
'notnull' => -1,),
147 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'visible' => -2,
'enabled' => 1,
'position' => 1000,
'notnull' => -1,),
148 'status' => array(
'type' =>
'integer',
'label' =>
'Status',
'visible' => 1,
'enabled' => 1,
'position' => 1000,
'notnull' => 1,
'default' =>
'0',
'index' => 1,
'arrayofkeyval' => array(0 =>
'Inactive', 1 =>
'Active'))
180 public $fk_user_creat;
185 public $fk_user_modif;
219 public $oauth_service;
223 public $imap_encryption;
231 public $source_directory;
235 public $target_directory;
239 public $maxemailpercollect;
244 public $datelastresult;
249 public $codelastresult;
274 const STATUS_DISABLED = 0;
275 const STATUS_ENABLED = 1;
285 global
$conf, $langs;
289 $this->ismultientitymanaged = 1;
290 $this->isextrafieldmanaged = 0;
295 if (!
isModEnabled(
'multicompany') && isset($this->fields[
'entity'])) {
296 $this->fields[
'entity'][
'enabled'] = 0;
300 $oauthservices = array();
302 foreach (
$conf->global as $key => $val) {
303 if (!empty($val) && preg_match(
'/^OAUTH_.*_ID$/', $key)) {
304 $key = preg_replace(
'/^OAUTH_/',
'', $key);
305 $key = preg_replace(
'/_ID$/',
'', $key);
306 if (preg_match(
'/^.*-/', $key)) {
307 $name = preg_replace(
'/^.*-/',
'', $key);
309 $name = $langs->trans(
"NoName");
311 $provider = preg_replace(
'/-.*$/',
'', $key);
312 $provider = ucfirst(strtolower($provider));
314 $oauthservices[$key] = $name.
" (".$provider.
")";
318 $this->fields[
'oauth_service'][
'arrayofkeyval'] = $oauthservices;
321 foreach ($this->fields as $key => $val) {
322 if (isset($val[
'enabled']) && empty($val[
'enabled'])) {
323 unset($this->fields[$key]);
328 foreach ($this->fields as $key => $val) {
329 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
330 foreach ($val[
'arrayofkeyval'] as $key2 => $val2) {
331 $this->fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
349 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
350 $langs->load(
"errors");
351 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
355 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
356 $this->password =
dolEncrypt($this->password);
360 $this->password =
dolDecrypt($this->password);
362 if (is_array($this->filters) && count($this->filters)) {
365 foreach ($this->filters as $filter) {
366 $emailcollectorfilter->type = $filter[
'type'];
367 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
368 $emailcollectorfilter->fk_emailcollector = $this->id;
369 $emailcollectorfilter->status = $filter[
'status'];
371 $emailcollectorfilter->create($user);
375 if (is_array($this->actions) && count($this->actions)) {
378 foreach ($this->actions as $operation) {
379 $emailcollectoroperation->type = $operation[
'type'];
380 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
381 $emailcollectoroperation->fk_emailcollector = $this->id;
382 $emailcollectoroperation->status = $operation[
'status'];
383 $emailcollectoroperation->position = $operation[
'position'];
385 $emailcollectoroperation->create($user);
401 global $langs, $extrafields;
422 unset(
$object->codelastresult);
423 unset(
$object->datelastresult);
428 $object->ref =
"copy_of_".$object->ref;
431 $object->host =
'imap.example.com';
434 if (is_array(
$object->array_options) && count(
$object->array_options) > 0) {
435 $extrafields->fetch_name_optionals_label($this->table_element);
436 foreach (
$object->array_options as $key => $option) {
437 $shortkey = preg_replace(
'/options_/',
'', $key);
438 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
439 unset(
$object->array_options[$key]);
445 $object->context[
'createfromclone'] =
'createfromclone';
446 $result =
$object->create($user);
452 unset(
$object->context[
'createfromclone']);
459 $this->db->rollback();
471 public function fetch($id, $ref =
null)
475 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
476 $this->password =
dolDecrypt($this->password);
509 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
513 $sql =
"SELECT s.rowid";
514 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
515 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
517 $sql .=
" AND s.status = 1";
519 $sql .= $this->db->order($sortfield, $sortorder);
524 $offset = $limit * $page;
526 $sql .= $this->db->plimit($limit + 1, $offset);
529 $result = $this->db->query($sql);
531 $num = $this->db->num_rows($result);
534 $obj = $this->db->fetch_object($result);
536 if ($emailcollector_static->fetch($obj->rowid)) {
537 $obj_ret[] = $emailcollector_static;
542 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
543 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
545 if (!count($obj_ret)) {
546 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
564 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
565 $langs->load(
"errors");
566 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
570 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
571 $this->password =
dolEncrypt($this->password);
575 $this->password =
dolDecrypt($this->password);
587 public function delete(
User $user, $notrigger = 0)
602 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
604 global
$conf, $langs, $action, $hookmanager;
606 if (!empty(
$conf->dol_no_mouse_hover)) {
612 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
614 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
616 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
618 if ($option !=
'nolink') {
620 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
621 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
622 $add_save_lastsearch_values = 1;
624 if ($add_save_lastsearch_values) {
625 $url .=
'&save_lastsearch_values=1';
630 if (empty($notooltip)) {
632 $label = $langs->trans(
"ShowEmailCollector");
633 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
635 $linkclose .=
' title="'.dolPrintHTMLForAttribute($label).
'"';
636 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
638 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
641 $linkstart =
'<a href="'.$url.
'"';
642 $linkstart .= $linkclose.
'>';
645 $result .= $linkstart;
647 $result .= img_object(($notooltip ?
'' : $label), ($this->picto ? $this->picto :
'generic'), ($notooltip ? (($withpicto != 2) ?
'class="paddingright"' :
'') :
'class="'.(($withpicto != 2) ?
'paddingright ' :
'').
'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
649 if ($withpicto != 2) {
650 $result .= $this->ref;
655 $hookmanager->initHooks(array(
'emailcollectordao'));
656 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result);
657 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
659 $result = $hookmanager->resPrint;
661 $result .= $hookmanager->resPrint;
689 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
692 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
693 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
694 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
695 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
698 $statusType =
'status5';
699 if ($status == self::STATUS_ENABLED) {
700 $statusType =
'status4';
703 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
714 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
715 $sql .=
' fk_user_creat, fk_user_modif';
716 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
717 $sql .=
' WHERE t.rowid = '.((int) $id);
718 $result = $this->db->query($sql);
720 if ($this->db->num_rows($result)) {
721 $obj = $this->db->fetch_object($result);
723 $this->
id = $obj->rowid;
725 $this->user_creation_id = $obj->fk_user_creat;
726 $this->user_modification_id = $obj->fk_user_modif;
727 $this->date_creation = $this->db->jdate($obj->datec);
728 $this->date_modification = empty($obj->datem) ?
'' : $this->db->jdate($obj->datem);
731 $this->db->free($result);
733 dol_print_error($this->db);
745 $this->host =
'localhost';
746 $this->login =
'alogin';
759 $this->filters = array();
761 $sql =
'SELECT rowid, type, rulevalue, status';
762 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
763 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
766 $resql = $this->db->query($sql);
768 $num = $this->db->num_rows($resql);
771 $obj = $this->db->fetch_object($resql);
772 $this->filters[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'rulevalue' => $obj->rulevalue,
'status' => $obj->status);
775 $this->db->free($resql);
777 dol_print_error($this->db);
791 $this->actions = array();
793 $sql =
'SELECT rowid, type, actionparam, status';
794 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
795 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
796 $sql .=
' ORDER BY position';
798 $resql = $this->db->query($sql);
800 $num = $this->db->num_rows($resql);
803 $obj = $this->db->fetch_object($resql);
804 $this->actions[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'actionparam' => $obj->actionparam,
'status' => $obj->status);
807 $this->db->free($resql);
811 dol_print_error($this->db);
826 $flags =
'/service=imap';
829 } elseif (empty($this->imap_encryption) || ($this->imap_encryption ==
'ssl' &&
getDolGlobalString(
'IMAP_FORCE_NOSSL'))) {
832 $flags .=
'/' . $this->imap_encryption;
835 $flags .=
'/novalidate-cert';
842 if (!empty($this->login) && strpos($this->login,
'/') !=
false) {
843 $partofauth = explode(
'/', $this->login);
844 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
847 $connectstringserver =
'{'.$this->host.
':'.$this->port.$flags.
'}';
849 return $connectstringserver;
860 if (function_exists(
'mb_convert_encoding')) {
862 $str = preg_replace(
"/ /",
"xxxSPACExxx", $str);
863 $str = preg_replace(
"/_/",
"xxxUNDERSCORExxx", $str);
864 $str = preg_replace(
"/\[Gmail\]/",
"xxxGMAILxxx", $str);
866 if ($str = mb_convert_encoding($str,
"UTF-7")) {
868 $str = preg_replace(
"/\+A/",
"&A", $str);
869 $str = preg_replace(
"/xxxUNDERSCORExxx/",
"_", $str);
871 $str = preg_replace(
"/xxxSPACExxx/",
" ", $str);
873 $str = preg_replace(
"/xxxGMAILxxx/",
"[Gmail]", $str);
877 $this->error =
"error: is not possible to encode this string '".$str.
"'";
897 $arrayofcollectors = $this->
fetchAll($user, 1);
899 foreach ($arrayofcollectors as $emailcollector) {
900 $result = $emailcollector->doCollectOneCollector(0);
902 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
904 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
905 if (!empty($emailcollector->errors)) {
906 $this->error .= implode(
'<br>', $emailcollector->errors);
909 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
932 global
$conf, $langs;
934 $errorforthisaction = 0;
937 $outputlangs = $langs;
940 $newlang =
GETPOST(
'lang_id',
'aZ09');
943 $newlang = !empty(
$object->thirdparty->default_lang) ?
$object->thirdparty->default_lang : $newlang;
945 if (!empty($newlang)) {
947 $outputlangs->setDefaultLang($newlang);
957 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
960 $tmparray = explode(
'.', $propertytooverwrite);
961 if (count($tmparray) == 2) {
962 $tmpclass = $tmparray[0];
963 $tmpproperty = $tmparray[1];
965 $tmpproperty = $tmparray[0];
967 if ($tmpclass && ($tmpclass !=
$object->element)) {
977 $regforregex = array();
978 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
979 $sourcefield = $regforregex[1];
980 $regexstring = $regforregex[2];
982 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
983 $sourcefield = $regforregex[1];
984 $regexstring = $regforregex[2];
987 if (!empty($sourcefield) && !empty($regexstring)) {
988 if (strtolower($sourcefield) ==
'body') {
989 $sourcestring = $messagetext;
990 } elseif (strtolower($sourcefield) ==
'subject') {
991 $sourcestring = $subject;
992 } elseif (strtolower($sourcefield) ==
'header') {
993 $sourcestring = $header;
997 $regforval = array();
999 if (strtolower($sourcefield) ==
'body') {
1000 $regexoptions =
'ms';
1002 if (strtolower($sourcefield) ==
'header') {
1003 $regexoptions =
'm';
1006 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
1008 $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
'';
1009 $valuetoset = (strtolower($sourcefield) ==
'body') ? $valueextracted : $this->
decodeSMTPSubject($valueextracted);
1010 if (preg_match(
'/^options_/', $tmpproperty)) {
1011 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetoset;
1013 if (property_exists(
$object, $tmpproperty)) {
1014 $object->$tmpproperty = $valuetoset;
1016 $tmp[$tmpproperty] = $valuetoset;
1020 if (preg_match(
'/^options_/', $tmpproperty)) {
1023 if (property_exists(
$object, $tmpproperty)) {
1031 if (property_exists(
$object, $tmpproperty)) {
1033 $operationslog .=
'<br>Regex /'.dol_escape_htmltag($regexstring).
'/'.
dol_escape_htmltag($regexoptions).
' into '.strtolower($sourcefield).
' -> not found, so object property '.
dol_escape_htmltag($tmpproperty).
' is set to null.';
1035 $tmp[$tmpproperty] =
null;
1036 $operationslog .=
'<br>Regex /'.dol_escape_htmltag($regexstring).
'/'.
dol_escape_htmltag($regexoptions).
' into '.strtolower($sourcefield).
' -> not found, so var '.
dol_escape_htmltag($tmpproperty).
' is set to null.';
1041 $errorforthisaction++;
1042 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1043 $this->errors[] = $this->error;
1045 $operationslog .=
'<br>'.$this->error;
1047 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1049 if (preg_match(
'/^options_/', $tmpproperty)) {
1050 $valuecurrent =
$object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1052 if (property_exists(
$object, $tmpproperty)) {
1053 $valuecurrent =
$object->$tmpproperty;
1056 $valuecurrent = $tmp[$tmpproperty];
1060 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1061 $valuetouse = $regforregex[2];
1062 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null,
$object);
1064 $matcharray = array();
1065 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1066 if (is_array($matcharray[1])) {
1067 foreach ($matcharray[1] as $keytoreplace) {
1068 if ($keytoreplace) {
1069 if (preg_match(
'/^options_/', $keytoreplace)) {
1070 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1072 if (property_exists(
$object, $keytoreplace)) {
1073 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->$keytoreplace;
1076 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1085 if (preg_match(
'/^options_/', $tmpproperty)) {
1086 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1088 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1090 if (property_exists(
$object, $tmpproperty)) {
1091 $object->$tmpproperty = $valuetouse;
1093 $tmp[$tmpproperty] = $valuetouse;
1096 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1100 $errorforthisaction++;
1101 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1102 $this->errors[] = $this->error;
1107 return $errorforthisaction;
1116 public function doCollectOneCollector($mode = 0)
1118 global $db,
$conf, $langs, $user;
1119 global $hookmanager;
1123 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1125 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1128 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1130 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1135 $this->debuginfo =
'';
1139 $searchfilterdoltrackid = 0;
1140 $searchfilternodoltrackid = 0;
1141 $searchfilterisanswer = 0;
1142 $searchfilterisnotanswer = 0;
1143 $searchfilterreplyto = 0;
1144 $searchfilterexcludebodyarray = array();
1145 $searchfilterexcludesubjectarray = array();
1146 $searchfilterexcludeemailarray = array();
1147 $searchfilterexcludedomainarray = array();
1148 $searchfilterexcludeemailmap = array();
1149 $operationslog =
'';
1150 $rulesreplyto = array();
1151 $connectstringsource =
'';
1152 $connectstringtarget =
'';
1153 $connection =
false;
1154 $arrayofemail = array();
1159 if (empty($this->host)) {
1160 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1163 if (empty($this->login)) {
1164 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1167 if (empty($this->source_directory)) {
1168 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1174 $sourcedir = $this->source_directory;
1175 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1180 $sourcedir = $this->source_directory;
1181 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1184 $timeoutconnect = (int)
getDolGlobalInt(
'MAIN_USE_CONNECT_TIMEOUT', 5);
1185 if ($timeoutconnect <= 0) {
1186 $timeoutconnect = 5;
1188 $timeoutread = (int)
getDolGlobalInt(
'MAIN_USE_RESPONSE_TIMEOUT', 20);
1189 if ($timeoutread <= 0) {
1192 if (function_exists(
'imap_timeout')) {
1193 imap_timeout(IMAP_OPENTIMEOUT, $timeoutconnect);
1194 imap_timeout(IMAP_READTIMEOUT, $timeoutread);
1195 imap_timeout(IMAP_WRITETIMEOUT, 5);
1196 imap_timeout(IMAP_CLOSETIMEOUT, 5);
1197 $this->debuginfo .=
'IMAP timeouts: connect='.$timeoutconnect.
's, read='.$timeoutread.
's<br>';
1201 if ($this->acces_type == 1) {
1203 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>';
1205 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1209 $keyforsupportedoauth2array = $this->oauth_service;
1210 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1211 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1213 $keyforprovider =
'';
1215 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', strtoupper($keyforsupportedoauth2array));
1216 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1218 if (!empty($supportedoauth2array)) {
1219 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1220 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1221 $OAUTH_SERVICENAME = $nameofservice;
1223 $OAUTH_SERVICENAME =
'Unknown';
1226 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1228 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1237 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1240 if (is_object($tokenobj) && method_exists($tokenobj,
'getEndOfLife')) {
1241 $endOfLife = $tokenobj->getEndOfLife();
1243 if ($endOfLife !== -9002 && $endOfLife !== -9001 && time() > ($endOfLife - 30)) {
1249 if (is_object($tokenobj) && $expire) {
1250 $this->debuginfo .=
'Refresh token '.$OAUTH_SERVICENAME.
'<br>';
1251 $credentials =
new Credentials(
1256 $serviceFactory = new \OAuth\ServiceFactory();
1257 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1261 if (preg_match(
'/^Microsoft/', $OAUTH_SERVICENAME)) {
1263 $tmp = explode(
'-', $OAUTH_SERVICENAME);
1264 $scopes = explode(
',',
getDolGlobalString(
'OAUTH_'.strtoupper($tmp[0]).(empty($tmp[1]) ?
'' :
'-'.$tmp[1]).
'_SCOPE'));
1267 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $scopes);
1269 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
1271 $refreshtoken = $tokenobj->getRefreshToken();
1272 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1275 $tokenobj->setRefreshToken($refreshtoken);
1276 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1278 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1279 if (is_object($tokenobj)) {
1280 $token = $tokenobj->getAccessToken();
1282 $this->error =
"Token not found";
1287 $this->error = $e->getMessage();
1288 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1292 $cm =
new ClientManager();
1293 $client = $cm->make([
1294 'host' => $this->host,
1295 'port' => $this->port,
1296 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1297 'validate_cert' => true,
1298 'protocol' =>
'imap',
1299 'username' => $this->login,
1300 'password' => $token,
1301 'authentication' =>
"oauth",
1305 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1307 $cm =
new ClientManager();
1308 $client = $cm->make([
1309 'host' => $this->host,
1310 'port' => $this->port,
1311 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1312 'validate_cert' => true,
1313 'protocol' =>
'imap',
1314 'username' => $this->login,
1315 'password' => $this->password,
1316 'authentication' =>
"login",
1324 }
catch (ConnectionFailedException $e) {
1325 $this->error = $e->getMessage();
1326 $this->errors[] = $this->error;
1327 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1331 $host = dol_getprefix(
'email');
1334 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1336 if (!function_exists(
'imap_open')) {
1337 $this->error =
'IMAP function not enabled on your PHP';
1343 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1344 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1346 $connectstringsource = $connectstringserver.$sourcedir;
1347 $connectstringtarget = $connectstringserver.$targetdir;
1350 $this->debuginfo .=
'connectstringsource = '.$connectstringsource.
', $connectstringtarget='.$connectstringtarget.
'<br>';
1352 $connection = imap_open($connectstringsource, $this->login, $this->password);
1353 if ($connection ===
false) {
1354 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1357 '@phan-var-force resource|IMAP\Connection $connection';
1360 $host = dol_getprefix(
'email');
1369 $criteria = array();
1372 $criteria = array(array(
'UNDELETED'));
1373 foreach ($this->filters as $rule) {
1374 if (empty($rule[
'status'])) {
1379 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1383 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1386 if ($rule[
'type'] ==
'excludeemail') {
1387 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1388 if (is_array($tmpvalues)) {
1389 foreach ($tmpvalues as $tmpvalue) {
1390 $tmpvalue = trim((
string) $tmpvalue);
1391 if ($tmpvalue ===
'') {
1395 if (preg_match_all(
'/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpvalue, $tmpmatches)) {
1396 foreach ($tmpmatches[0] as $tmpemail) {
1397 $tmpemail = strtolower(trim($tmpemail));
1398 if ($tmpemail !==
'') {
1399 $searchfilterexcludeemailarray[] = $tmpemail;
1407 if ($rule[
'type'] ==
'excludedomain') {
1408 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1409 if (is_array($tmpvalues)) {
1410 foreach ($tmpvalues as $tmpvalue) {
1411 $tmpvalue = trim((
string) $tmpvalue);
1412 if ($tmpvalue ===
'') {
1416 if (preg_match_all(
'/[a-z0-9._%+\\-]+@([a-z0-9.\\-]+\\.[a-z]{2,})/i', $tmpvalue, $tmpmatches)) {
1417 foreach ($tmpmatches[1] as $tmpdomain) {
1418 $tmpdomain = strtolower(trim($tmpdomain));
1419 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1420 if ($tmpdomain !==
'') {
1421 $searchfilterexcludedomainarray[] = $tmpdomain;
1427 $tmpdomain = strtolower($tmpvalue);
1428 $tmpdomain = preg_replace(
'/^mailto:/i',
'', $tmpdomain);
1429 $tmpdomain = trim($tmpdomain);
1430 $tmpdomain = trim($tmpdomain,
"<> \t\n\r\0\x0B.,;");
1431 if (strpos($tmpdomain,
'@') === 0) {
1432 $tmpdomain = substr($tmpdomain, 1);
1434 $posat = strrpos($tmpdomain,
'@');
1435 if ($posat !==
false) {
1436 $tmpdomain = substr($tmpdomain, $posat + 1);
1438 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1439 if ($tmpdomain !==
'') {
1440 $searchfilterexcludedomainarray[] = $tmpdomain;
1447 if ($rule[
'type'] ==
'from') {
1448 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1449 if (count($tmprulevaluearray) >= 2) {
1450 foreach ($tmprulevaluearray as $tmprulevalue) {
1451 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1454 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1457 if ($rule[
'type'] ==
'to') {
1458 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1459 if (count($tmprulevaluearray) >= 2) {
1460 foreach ($tmprulevaluearray as $tmprulevalue) {
1461 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1464 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1467 if ($rule[
'type'] ==
'bcc') {
1468 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1470 if ($rule[
'type'] ==
'cc') {
1471 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1473 if ($rule[
'type'] ==
'subject') {
1476 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1478 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1481 if ($rule[
'type'] ==
'body') {
1484 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1486 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1489 if ($rule[
'type'] ==
'header') {
1490 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1502 if ($rule[
'type'] ==
'seen') {
1503 array_push($criteria, array($not.
"SEEN"));
1505 if ($rule[
'type'] ==
'unseen') {
1506 array_push($criteria, array($not.
"UNSEEN"));
1508 if ($rule[
'type'] ==
'unanswered') {
1509 array_push($criteria, array($not.
"UNANSWERED"));
1511 if ($rule[
'type'] ==
'answered') {
1512 array_push($criteria, array($not.
"ANSWERED"));
1514 if ($rule[
'type'] ==
'smaller') {
1515 array_push($criteria, array($not.
"SMALLER"));
1517 if ($rule[
'type'] ==
'larger') {
1518 array_push($criteria, array($not.
"LARGER"));
1522 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1523 $searchfilterdoltrackid++;
1524 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1526 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1527 $searchfilterdoltrackid++;
1528 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1530 if ($rule[
'type'] ==
'withtrackingid') {
1531 $searchfilterdoltrackid++;
1532 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1534 if ($rule[
'type'] ==
'withouttrackingid') {
1535 $searchfilternodoltrackid++;
1536 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1539 if ($rule[
'type'] ==
'isanswer') {
1540 $searchfilterisanswer++;
1541 $searchhead .=
'/References.*@.*/';
1543 if ($rule[
'type'] ==
'isnotanswer') {
1544 $searchfilterisnotanswer++;
1545 $searchhead .=
'! /References.*@.*/';
1548 if ($rule[
'type'] ==
'replyto') {
1549 $searchfilterreplyto++;
1550 $rulesreplyto[] = $rule[
'rulevalue'];
1551 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1555 if (empty($targetdir) || !
getDolGlobalString(
'EMAILCOLLECTOR_NO_FILTER_ON_DATE_IF_THERE_IS_A_TARGETDIR')) {
1557 if ($this->datelastok) {
1558 $fromdate = $this->datelastok;
1560 if ($fromdate > 0) {
1562 array_push($criteria, array(
"SINCE" =>
date(
'j-M-Y', $fromdate - 86400)));
1568 $search = var_export($criteria,
true);
1571 $search =
'UNDELETED';
1572 foreach ($this->filters as $rule) {
1573 if (empty($rule[
'status'])) {
1581 if (!empty($rule[
'rulevalue']) && strpos($rule[
'rulevalue'],
'!') === 0) {
1585 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1588 if ($rule[
'type'] ==
'excludeemail') {
1589 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1590 if (is_array($tmpvalues)) {
1591 foreach ($tmpvalues as $tmpvalue) {
1592 $tmpvalue = trim((
string) $tmpvalue);
1593 if ($tmpvalue ===
'') {
1597 if (preg_match_all(
'/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpvalue, $tmpmatches)) {
1598 foreach ($tmpmatches[0] as $tmpemail) {
1599 $tmpemail = strtolower(trim($tmpemail));
1600 if ($tmpemail !==
'') {
1601 $searchfilterexcludeemailarray[] = $tmpemail;
1609 if ($rule[
'type'] ==
'excludedomain') {
1610 $tmpvalues = preg_split(
'/[\\r\\n,;]+/', (
string) $rule[
'rulevalue']);
1611 if (is_array($tmpvalues)) {
1612 foreach ($tmpvalues as $tmpvalue) {
1613 $tmpvalue = trim((
string) $tmpvalue);
1614 if ($tmpvalue ===
'') {
1618 if (preg_match_all(
'/[a-z0-9._%+\\-]+@([a-z0-9.\\-]+\\.[a-z]{2,})/i', $tmpvalue, $tmpmatches)) {
1619 foreach ($tmpmatches[1] as $tmpdomain) {
1620 $tmpdomain = strtolower(trim($tmpdomain));
1621 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1622 if ($tmpdomain !==
'') {
1623 $searchfilterexcludedomainarray[] = $tmpdomain;
1629 $tmpdomain = strtolower($tmpvalue);
1630 $tmpdomain = preg_replace(
'/^mailto:/i',
'', $tmpdomain);
1631 $tmpdomain = trim($tmpdomain);
1632 $tmpdomain = trim($tmpdomain,
"<> \t\n\r\0\x0B.,;");
1633 if (strpos($tmpdomain,
'@') === 0) {
1634 $tmpdomain = substr($tmpdomain, 1);
1636 $posat = strrpos($tmpdomain,
'@');
1637 if ($posat !==
false) {
1638 $tmpdomain = substr($tmpdomain, $posat + 1);
1640 $tmpdomain = trim($tmpdomain,
". \t\n\r\0\x0B");
1641 if ($tmpdomain !==
'') {
1642 $searchfilterexcludedomainarray[] = $tmpdomain;
1649 if ($rule[
'type'] ==
'from') {
1650 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1651 if (count($tmprulevaluearray) >= 2) {
1652 foreach ($tmprulevaluearray as $tmprulevalue) {
1653 $search .=
' '.$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1656 $search .=
' '.$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1659 if ($rule[
'type'] ==
'to') {
1660 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1661 if (count($tmprulevaluearray) >= 2) {
1662 foreach ($tmprulevaluearray as $tmprulevalue) {
1663 $search .=
' '.$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1666 $search .=
' '.$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1669 if ($rule[
'type'] ==
'bcc') {
1670 $search .=
' '.$not.
'BCC';
1672 if ($rule[
'type'] ==
'cc') {
1673 $search .=
' '.$not.
'CC';
1675 if ($rule[
'type'] ==
'subject') {
1678 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1680 $search .=
' SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1683 if ($rule[
'type'] ==
'body') {
1686 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1689 $search .=
' BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1692 if ($rule[
'type'] ==
'header') {
1693 $search .=
' '.$not.
'HEADER '.$rule[
'rulevalue'];
1705 if ($rule[
'type'] ==
'seen') {
1706 $search .=
' '.$not.
'SEEN';
1708 if ($rule[
'type'] ==
'unseen') {
1709 $search .=
' '.$not.
'UNSEEN';
1711 if ($rule[
'type'] ==
'unanswered') {
1712 $search .=
' '.$not.
'UNANSWERED';
1714 if ($rule[
'type'] ==
'answered') {
1715 $search .=
' '.$not.
'ANSWERED';
1717 if ($rule[
'type'] ==
'smaller') {
1718 $search .=
' '.$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1720 if ($rule[
'type'] ==
'larger') {
1721 $search .=
' '.$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1725 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1726 $searchfilterdoltrackid++;
1727 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1729 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1730 $searchfilterdoltrackid++;
1731 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1733 if ($rule[
'type'] ==
'withtrackingid') {
1734 $searchfilterdoltrackid++;
1735 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1737 if ($rule[
'type'] ==
'withouttrackingid') {
1738 $searchfilternodoltrackid++;
1739 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1742 if ($rule[
'type'] ==
'isanswer') {
1743 $searchfilterisanswer++;
1744 $searchhead .=
'/References.*@.*/';
1746 if ($rule[
'type'] ==
'isnotanswer') {
1747 $searchfilterisnotanswer++;
1748 $searchhead .=
'! /References.*@.*/';
1751 if ($rule[
'type'] ==
'replyto') {
1752 $searchfilterreplyto++;
1753 $rulesreplyto[] = $rule[
'rulevalue'];
1754 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1758 if (empty($targetdir)) {
1760 if ($this->datelastok) {
1761 $fromdate = $this->datelastok;
1763 if ($fromdate > 0) {
1765 $search .=
' SINCE '.date(
'j-M-Y', $fromdate - 86400);
1773 if (!empty($searchfilterexcludeemailarray)) {
1774 $searchfilterexcludeemailarray = array_values(array_filter(array_unique($searchfilterexcludeemailarray)));
1775 $searchfilterexcludeemailmap = array_fill_keys($searchfilterexcludeemailarray,
true);
1777 if (!empty($searchfilterexcludedomainarray)) {
1778 $searchfilterexcludedomainarray = array_values(array_filter(array_unique($searchfilterexcludedomainarray)));
1781 $nbemailprocessed = 0;
1784 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1785 $arrayofemail = array();
1794 $tmpsourcedir = $sourcedir;
1799 $f = $client->getFolders(
false, $tmpsourcedir);
1806 foreach ($f as $candidate) {
1807 if ($candidate instanceof Webklex\PHPIMAP\Folder && $candidate->full_name === $tmpsourcedir) {
1808 $folder = $candidate;
1812 if ($folder instanceof Webklex\PHPIMAP\Folder) {
1813 $Query = $folder->messages()->where($criteria);
1817 $this->error =
"Failed to execute getfolders";
1818 $this->errors[] = $this->error;
1819 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1822 }
catch (InvalidWhereQueryCriteriaException $e) {
1823 $this->error = $e->getMessage();
1824 $this->errors[] = $this->error;
1825 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1828 $this->error = $e->getMessage();
1829 $this->errors[] = $this->error;
1830 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1835 if (empty($Query)) {
1837 $this->error =
"Source directory ".$sourcedir.
" not found";
1838 $this->errors[] = $this->error;
1839 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_WARNING);
1843 '@phan-var-force Webklex\PHPIMAP\Query\Query $Query';
1846 $Query->leaveUnread();
1848 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1849 dol_syslog(
"EmailCollector::doCollectOneCollector nb arrayofemail ".(is_array($arrayofemail) ? count($arrayofemail) :
'Not array'));
1851 $this->error = $e->getMessage();
1852 $this->errors[] = $this->error;
1853 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1856 } elseif ($connection !==
false) {
1858 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1860 if ($arrayofemail ===
false) {
1862 $mapoferrrors = imap_errors();
1863 if ($mapoferrrors !==
false) {
1865 $this->error =
"Search string not understood - ".implode(
',', $mapoferrrors);
1866 $this->errors[] = $this->error;
1871 $arrayofemailtodelete = array();
1874 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0 && $connection !==
false) {
1891 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1893 $richarrayofemail = array();
1895 foreach ($arrayofemail as $imapemail) {
1898 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1899 $header = $imapemail->getHeader()->raw;
1900 $overview = $imapemail->getAttributes();
1902 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1903 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1906 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1909 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)(\r\n|\s$)/m', $header, $matches);
1910 $headers = array_combine($matches[1], $matches[2]);
1913 $richarrayofemail[] = array(
'imapemail' => $imapemail,
'header' => $header,
'headers' => $headers,
'overview' => $overview,
'date' => empty($headers[
'Date']) ?
false : strtotime($headers[
'Date']));
1918 $richarrayofemail =
dol_sort_array($richarrayofemail,
'date',
'asc');
1922 foreach ($richarrayofemail as $tmpval) {
1923 if ($nbemailprocessed > 1000) {
1929 $imapemail = $tmpval[
'imapemail'];
1930 $header = $tmpval[
'header'];
1931 $overview = $tmpval[
'overview'];
1932 $headers = $tmpval[
'headers'];
1934 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1935 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1937 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1938 $headers[
'References'] = $headers[
'references'];
1940 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1941 $headers[
'Message-ID'] = $headers[
'message-id'];
1943 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1944 $headers[
'Subject'] = $headers[
'subject'];
1950 $emailto = (string) $overview[
'to'];
1955 $operationslog .=
'<br>** Process email #'.dol_escape_htmltag((
string) $iforemailloop);
1959 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1961 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1963 $operationslog .=
" - ".dol_escape_htmltag((
string) $imapemail);
1964 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1966 $operationslog .=
" - MsgId: ".$msgid;
1967 $operationslog .=
" - Date: ".($headers[
'Date'] ?? $langs->transnoentitiesnoconv(
"NotFound"));
1968 $operationslog .=
" - References: ".dol_escape_htmltag($headers[
'References'] ?? $langs->transnoentitiesnoconv(
"NotFound")).
" - Subject: ".
dol_escape_htmltag($headers[
'Subject']);
1970 dol_syslog(
"-- Process email #".$iforemailloop.
", MsgId: ".$msgid.
", Date: ".($headers[
'Date'] ??
'').
", References: ".($headers[
'References'] ??
'').
", Subject: ".$headers[
'Subject']);
1973 $trackidfoundintorecipienttype =
'';
1974 $trackidfoundintorecipientid = 0;
1979 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)) {
1980 $trackidfoundintorecipienttype = $reg[1];
1981 $trackidfoundintorecipientid = $reg[2];
1982 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1983 $trackidfoundintorecipienttype =
'emailing';
1984 $trackidfoundintorecipientid = $reg[1];
1987 $trackidfoundintomsgidtype =
'';
1988 $trackidfoundintomsgidid = 0;
1993 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)) {
1994 $trackidfoundintomsgidtype = $reg[1];
1995 $trackidfoundintomsgidid = $reg[2];
1996 } elseif (preg_match(
'/(?:[\+\-])emailing-(\w+)@/', $msgid, $reg)) {
1997 $trackidfoundintomsgidtype =
'emailing';
1998 $trackidfoundintomsgidid = $reg[1];
2004 if ($searchfilterdoltrackid > 0) {
2005 $referencesForFilter = $headers[
'References'] ??
'';
2006 if (!empty($headers[
'References']) && !empty($headers[
'In-Reply-To'])) {
2007 $referencesForFilter .=
' ';
2009 $referencesForFilter .= ($headers[
'In-Reply-To'] ??
'');
2011 if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) {
2012 if (empty($referencesForFilter) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $referencesForFilter)) {
2013 $nbemailprocessed++;
2014 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");
2020 if ($searchfilternodoltrackid > 0) {
2021 $referencesForFilter = $headers[
'References'] ??
'';
2022 if (!empty($headers[
'References']) && !empty($headers[
'In-Reply-To'])) {
2023 $referencesForFilter .=
' ';
2025 $referencesForFilter .= ($headers[
'In-Reply-To'] ??
'');
2027 if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($referencesForFilter) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $referencesForFilter))) {
2028 $nbemailprocessed++;
2029 dol_syslog(
" Discarded - Suffix found into email recipient, or Header 'References/In-Reply-To' found and matching signature of application so with a trackid");
2034 if ($searchfilterisanswer > 0) {
2035 $referencesforanswer =
'';
2036 if (!empty($headers[
'References'])) {
2037 $referencesforanswer .= $headers[
'References'].
' ';
2039 if (!empty($headers[
'In-Reply-To'])) {
2040 $referencesforanswer .= $headers[
'In-Reply-To'];
2043 $hasdolibarrreference = 0;
2044 if (!empty($referencesforanswer)) {
2045 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $referencesforanswer)) {
2046 $hasdolibarrreference = 1;
2048 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $referencesforanswer)) {
2049 $hasdolibarrreference = 1;
2055 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
2061 if (!empty($headers[
'In-Reply-To'])) {
2065 if ($hasdolibarrreference) {
2072 $nbemailprocessed++;
2073 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)");
2077 if ($searchfilterisnotanswer > 0) {
2081 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
2086 if (!$isanswer &&
getDolGlobalInt(
'EMAILCOLLECTOR_ISNOTANSWER_USE_REFERENCES') && !empty($headers[
'References'])) {
2089 if (!$isanswer &&
getDolGlobalString(
'EMAILCOLLECTOR_USE_IN_REPLY_TO_TO_DETECT_ANSWERS')) {
2090 if (!empty($headers[
'In-Reply-To'])) {
2097 $nbemailprocessed++;
2098 dol_syslog(
" Discarded - Email is an answer");
2102 if ($searchfilterreplyto > 0) {
2103 if (!empty($headers[
'Reply-To'])) {
2105 foreach ($rulesreplyto as $key => $rulereplyto) {
2106 if (preg_match(
'/'.preg_quote($rulereplyto,
'/').
'/', $headers[
'Reply-To'])) {
2111 if (!$isreplytook || $isreplytook != count($rulesreplyto)) {
2112 $nbemailprocessed++;
2113 dol_syslog(
" Discarded - Reply-to does not match");
2121 $thirdpartystatic =
new Societe($this->db);
2122 $contactstatic =
new Contact($this->db);
2123 $projectstatic =
new Project($this->db);
2125 $nbactiondoneforemail = 0;
2127 $errorforactions = 0;
2128 $thirdpartyfoundby =
'';
2129 $contactfoundby =
'';
2130 $projectfoundby =
'';
2131 $ticketfoundby =
'';
2132 $candidaturefoundby =
'';
2136 $dateformated =
dol_print_date($overview[
'date'],
'dayrfc',
'gmt');
2137 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".$dateformated.
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
2142 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);
2152 global $htmlmsg, $plainmsg, $charset, $attachments;
2156 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
2159 $htmlmsg = $plainmsg =
'';
2160 $attachments = array();
2162 if ($imapemail->hasHTMLBody()) {
2163 $htmlmsg = $imapemail->getHTMLBody();
2165 if ($imapemail->hasTextBody() && $imapemail->getTextBody() !=
"\n") {
2166 $plainmsg = $imapemail->getTextBody();
2168 if ($imapemail->hasAttachments()) {
2169 $attachments = $imapemail->getAttachments()->all();
2171 $attachments = array();
2174 $getMsg = $this->
getmsg($connection, $imapemail);
2176 $this->errors = array_merge($this->errors, [$this->error]);
2180 '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments';
2190 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
2191 dol_syslog(
" Discarded - Email body is not valid utf8");
2195 if (!empty($searchfilterexcludebodyarray)) {
2196 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
2197 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
2198 $nbemailprocessed++;
2199 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
2200 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
2242 $replytostring =
'';
2246 $replytostring = !empty($headers[
'Reply-To']) ? $this->
decodeSMTPSubject($headers[
'Reply-To']) :
'';
2253 $tmpdate = $overview[
'date']->toDate();
2254 $tmptimezone = $tmpdate->getTimezone()->getName();
2257 if (preg_match(
'/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) {
2258 if ($reg[1] ==
'+' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2259 $dateemail -= (3600 * (int) $reg[2]);
2260 $dateemail -= (60 * (int) $reg[3]);
2262 if ($reg[1] ==
'-' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2263 $dateemail += (3600 * (int) $reg[2]);
2264 $dateemail += (60 * (int) $reg[3]);
2269 $fromstring = (string) $overview[0]->from;
2270 $replytostring = (!empty($overview[
'in_reply-to']) ? $overview[
'in_reply-to'] : (!empty($headers[
'Reply-To']) ? $headers[
'Reply-To'] :
"")) ;
2272 $sender = !empty($overview[0]->sender) ? $overview[0]->sender :
'';
2273 $to = $overview[0]->to;
2274 $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc :
'';
2275 $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc :
'';
2277 $subject = (string) $overview[0]->subject;
2280 if (!empty($searchfilterexcludesubjectarray)) {
2281 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
2282 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
2283 $nbemailprocessed++;
2284 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
2285 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
2292 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
2293 $email_from = $reg[2];
2294 $fromtext = $reg[1];
2296 $email_from = $fromstring;
2299 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
2301 $replytotext = $reg[1];
2303 $replyto = $replytostring;
2307 if (!empty($searchfilterexcludeemailmap) || !empty($searchfilterexcludedomainarray)) {
2308 $emailsToCheck = array();
2309 $tmpaddressblob = trim($fromstring.
' '.$replytostring);
2310 if ($tmpaddressblob !==
'' && preg_match_all(
'/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpaddressblob, $tmpmatches)) {
2311 foreach ($tmpmatches[0] as $tmpEmail) {
2312 $tmpEmail = strtolower(trim($tmpEmail));
2313 if ($tmpEmail !==
'') {
2314 $emailsToCheck[$tmpEmail] =
true;
2319 if (empty($emailsToCheck)) {
2320 foreach (array($email_from, $replyto) as $tmpEmail) {
2321 $tmpEmail = strtolower(trim((
string) $tmpEmail));
2322 if ($tmpEmail !==
'' && strpos($tmpEmail,
'@') !==
false) {
2323 $emailsToCheck[$tmpEmail] =
true;
2329 $discardDomain =
'';
2330 $matchedDomainRule =
'';
2332 foreach (array_keys($emailsToCheck) as $tmpEmail) {
2333 if (!empty($searchfilterexcludeemailmap[$tmpEmail])) {
2334 $discardEmail = $tmpEmail;
2338 if (!empty($searchfilterexcludedomainarray)) {
2339 $posat = strrpos($tmpEmail,
'@');
2340 if ($posat ===
false) {
2343 $tmpDomain = strtolower(substr($tmpEmail, $posat + 1));
2344 foreach ($searchfilterexcludedomainarray as $excludedDomain) {
2345 if ($excludedDomain ===
'') {
2348 if ($tmpDomain === $excludedDomain || substr($tmpDomain, -strlen(
'.'.$excludedDomain)) ===
'.'.$excludedDomain) {
2349 $discardDomain = $tmpDomain;
2350 $matchedDomainRule = $excludedDomain;
2357 if ($discardEmail !==
'' || $discardDomain !==
'') {
2358 $nbemailprocessed++;
2359 if ($discardEmail !==
'') {
2360 $operationslog .=
'<br>Discarded - Sender email excluded: '.$discardEmail;
2361 dol_syslog(
" Discarded - Sender email excluded: ".$discardEmail);
2363 $operationslog .=
'<br>Discarded - Sender domain excluded: '.$discardDomain.($matchedDomainRule !==
'' && $matchedDomainRule !== $discardDomain ?
' (matched '.$matchedDomainRule.
')' :
'');
2364 dol_syslog(
" Discarded - Sender domain excluded: ".$discardDomain.($matchedDomainRule !==
'' && $matchedDomainRule !== $discardDomain ?
" (matched ".$matchedDomainRule.
")" :
""));
2371 $fk_element_type =
'';
2388 $objectemail =
null;
2391 $arrayofreferences = array();
2392 if (!empty($headers[
'References'])) {
2393 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
2395 if (!in_array(
'<'.$msgid.
'>', $arrayofreferences)) {
2396 $arrayofreferences = array_merge($arrayofreferences, array(
'<'.$msgid.
'>'));
2401 foreach ($arrayofreferences as $reference) {
2403 if (!empty($trackidfoundintorecipienttype)) {
2404 $resultsearchtrackid = -1;
2405 $reg[1] = $trackidfoundintorecipienttype;
2406 $reg[2] = $trackidfoundintorecipientid;
2407 } elseif (!empty($trackidfoundintomsgidtype)) {
2408 $resultsearchtrackid = -1;
2409 $reg[1] = $trackidfoundintomsgidtype;
2410 $reg[2] = $trackidfoundintomsgidid;
2412 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
2413 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2414 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
2418 if (!empty($resultsearchtrackid)) {
2420 $trackid = $reg[1].$reg[2];
2422 $objectid = $reg[2];
2424 if ($reg[1] ==
'thi') {
2425 $objectemail =
new Societe($this->db);
2427 if ($reg[1] ==
'ctc') {
2428 $objectemail =
new Contact($this->db);
2430 if ($reg[1] ==
'inv') {
2431 $objectemail =
new Facture($this->db);
2433 if ($reg[1] ==
'sinv') {
2436 if ($reg[1] ==
'pro') {
2437 $objectemail =
new Propal($this->db);
2439 if ($reg[1] ==
'ord') {
2440 $objectemail =
new Commande($this->db);
2442 if ($reg[1] ==
'shi') {
2445 if ($reg[1] ==
'spro') {
2448 if ($reg[1] ==
'sord') {
2451 if ($reg[1] ==
'rec') {
2452 $objectemail =
new Reception($this->db);
2454 if ($reg[1] ==
'proj') {
2455 $objectemail =
new Project($this->db);
2456 $projectfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2458 if ($reg[1] ==
'tas') {
2459 $objectemail =
new Task($this->db);
2461 if ($reg[1] ==
'con') {
2462 $objectemail =
new Contact($this->db);
2464 if ($reg[1] ==
'use') {
2465 $objectemail =
new User($this->db);
2467 if ($reg[1] ==
'tic') {
2468 $objectemail =
new Ticket($this->db);
2469 $ticketfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2471 if ($reg[1] ==
'recruitmentcandidature') {
2473 $candidaturefoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2475 if ($reg[1] ==
'mem') {
2476 $objectemail =
new Adherent($this->db);
2484 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
2487 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket";
2488 $sql .=
" WHERE email_msgid = '".$this->db->escape($reg[1]).
"' OR origin_references LIKE '%".$this->db->escape($this->db->escapeforlike($reg[1])).
"%'";
2489 $resql = $this->db->query($sql);
2491 $obj = $this->db->fetch_object($resql);
2493 $objectid = $obj->rowid;
2494 $objectemail =
new Ticket($this->db);
2495 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2502 if (!is_object($objectemail) &&
isModEnabled(
'project')) {
2503 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2504 $resql = $this->db->query($sql);
2506 $obj = $this->db->fetch_object($resql);
2508 $objectid = $obj->rowid;
2509 $objectemail =
new Project($this->db);
2510 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2517 if (!is_object($objectemail) &&
isModEnabled(
'recruitment')) {
2518 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2519 $resql = $this->db->query($sql);
2521 $obj = $this->db->fetch_object($resql);
2523 $objectid = $obj->rowid;
2525 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2534 if (is_object($objectemail)) {
2535 $result = $objectemail->fetch($objectid);
2537 $fk_element_id = $objectemail->id;
2538 $fk_element_type = $objectemail->element;
2540 if ($fk_element_type ==
'facture') {
2541 $fk_element_type =
'invoice';
2544 if (get_class($objectemail) !=
'Societe') {
2545 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2547 $thirdpartyid = $objectemail->id;
2550 if (get_class($objectemail) !=
'Contact') {
2551 $contactid = $objectemail->fk_socpeople;
2553 $contactid = $objectemail->id;
2556 if (get_class($objectemail) !=
'Project') {
2557 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2559 $projectid = $objectemail->id;
2562 if ($objectemail instanceof
Ticket) {
2563 $ticketid = $objectemail->id;
2565 $changeonticket_references =
false;
2566 if (empty($trackid)) {
2567 $trackid = $objectemail->track_id;
2569 if (empty($objectemail->origin_references)) {
2570 $objectemail->origin_references = !empty($headers[
'References']) ? $headers[
'References'] :
null;
2571 $changeonticket_references =
true;
2573 foreach ($arrayofreferences as $key => $referencetmp) {
2574 if (!str_contains($objectemail->origin_references, $referencetmp)) {
2575 $objectemail->origin_references .=
" ".$referencetmp;
2576 $changeonticket_references =
true;
2580 if ($changeonticket_references) {
2581 $operationslog .=
'<br>We complete ticket ID='.$ticketid.
' with property origin_references='.$objectemail->origin_references;
2582 $objectemail->update($user, 1);
2589 if ($projectid > 0) {
2590 $result = $projectstatic->fetch($projectid);
2592 $projectstatic->id = 0;
2594 $projectid = $projectstatic->id;
2596 $projectfoundby =
'trackid ('.$trackid.
')';
2601 if (empty($thirdpartyid)) {
2602 $thirdpartyid = $projectstatic->socid;
2607 if ($contactid > 0) {
2608 $result = $contactstatic->fetch($contactid);
2610 $contactstatic->id = 0;
2612 $contactid = $contactstatic->id;
2614 $contactfoundby =
'trackid ('.$trackid.
')';
2616 if (empty($thirdpartyid)) {
2617 $thirdpartyid = $contactstatic->fk_soc;
2622 if ($thirdpartyid > 0) {
2623 $result = $thirdpartystatic->fetch($thirdpartyid);
2625 $thirdpartystatic->id = 0;
2627 $thirdpartyid = $thirdpartystatic->id;
2629 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2634 if (is_object($objectemail)) {
2639 if (empty($contactid)) {
2640 $result = $contactstatic->fetch(0,
null,
'', $email_from);
2643 dol_syslog(
"We found a contact with the email ".$email_from);
2644 $contactid = $contactstatic->id;
2645 $contactfoundby =
'email of contact ('.$email_from.
')';
2646 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2647 $result = $thirdpartystatic->fetch($contactstatic->socid);
2649 $thirdpartyid = $thirdpartystatic->id;
2650 $thirdpartyfoundby =
'email of contact ('.$email_from.
')';
2656 if (empty($thirdpartyid)) {
2657 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $email_from);
2659 dol_syslog(
"We found a thirdparty with the email ".$email_from);
2660 $thirdpartyid = $thirdpartystatic->id;
2661 $thirdpartyfoundby =
'email ('.$email_from.
')';
2696 $savedattachments = array();
2697 $savedattachmentsdir =
'';
2698 $savedattachmentsnote =
'';
2699 if (empty($mode) && !empty($attachments) && $fk_element_id > 0 && $fk_element_type ===
'order_supplier' && $objectemail instanceof
CommandeFournisseur) {
2700 $orderref = isset($objectemail->ref) ? (string) $objectemail->ref :
'';
2701 if ($orderref !==
'' && !empty(
$conf->fournisseur->commande)) {
2702 $entityforobject = isset($objectemail->entity) ? (int) $objectemail->entity : (int)
$conf->entity;
2703 $basedir = (!empty(
$conf->fournisseur->commande->multidir_output[$entityforobject]) ?
$conf->fournisseur->commande->multidir_output[$entityforobject] :
$conf->fournisseur->commande->dir_output);
2705 $savedattachments = $this->saveEmailCollectorAttachmentsToDir($savedattachmentsdir, $attachments);
2706 if (!empty($savedattachments)) {
2707 $operationslog .=
'<br>Saved '.count($savedattachments).
' attachment(s) into '.
dol_escape_htmltag($savedattachmentsdir);
2711 if (!empty($savedattachments)) {
2713 foreach ($savedattachments as $attmeta) {
2714 if (!is_array($attmeta) || empty($attmeta[
'name'])) {
2717 $names[] = (string) $attmeta[
'name'];
2719 if (!empty($names)) {
2720 $savedattachmentsnote = $langs->trans(
"NbOfAttachedFiles").
' : '.count($names);
2721 $savedattachmentsnote .=
' ('.implode(
', ', array_slice($names, 0, 10)).(count($names) > 10 ?
'...' :
'').
')';
2728 foreach ($this->actions as $operation) {
2729 $errorforthisaction = 0;
2730 $ticketalreadyexists = 0;
2731 if ($errorforactions) {
2734 if (empty($operation[
'status'])) {
2738 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2741 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2742 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2745 $actioncode =
'EMAIL_IN';
2747 if (preg_match(
'/Sent$/', $sourcedir) || preg_match(
'/envoyés$/i', $sourcedir)) {
2748 $actioncode =
'EMAIL';
2751 $arrayofemailtoconsidersender = array_filter(array_map(
'trim', explode(
',',
getDolGlobalString(
'MAIL_FROM_EMAILS_TO_CONSIDER_SENDING'))));
2752 foreach ($arrayofemailtoconsidersender as $emailtoconsidersender) {
2753 if ($emailtoconsidersender ===
'') {
2756 if (preg_match(
'/'.preg_quote($emailtoconsidersender,
'/').
'/', $fromstring)) {
2757 $actioncode =
'EMAIL';
2760 $operationslog .=
'<br>Email will have actioncode='.$actioncode;
2762 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2764 $descriptiontitle = $langs->transnoentitiesnoconv(
"RecordCreatedByEmailCollector", $this->
ref);
2769 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2771 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2773 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2775 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailReply").($langs->trans(
"MailReply") !=
'Reply to' ?
' (Reply to)' :
'').
' : '.
dol_escape_htmltag($replyto));
2778 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2780 if ($savedattachmentsnote) {
2781 $descriptionmeta =
dol_concatdesc($descriptionmeta, $savedattachmentsnote);
2784 if ($operation[
'type'] ==
'ticket') {
2786 $tickettocreate =
new Ticket($this->db);
2787 $errorfetchticket = 0;
2788 $alreadycreated = 0;
2789 if (!empty($objectid) && $objectemail instanceof
Ticket) {
2790 $alreadycreated = $tickettocreate->fetch((
int) $objectid);
2792 if ($alreadycreated == 0 && $ticketid > 0) {
2793 $alreadycreated = $tickettocreate->fetch($ticketid);
2795 if ($alreadycreated == 0 && !empty($trackid)) {
2796 $alreadycreated = $tickettocreate->fetch(0,
'', $trackid);
2798 if ($alreadycreated == 0 && !empty($msgid)) {
2799 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2801 if ($alreadycreated < 0) {
2802 $errorfetchticket++;
2804 if (empty($errorfetchticket)) {
2805 if ($alreadycreated == 0) {
2806 $operationslog .=
'<br>Ticket not found using trackid='.$trackid.
' or msgid='.$msgid;
2807 $ticketalreadyexists = 0;
2809 $operationslog .=
'<br>Ticket already found using trackid='.$trackid.
' or msgid='.$msgid.
", we replace operation 'ticket' with 'recordevent' to add a new message";
2810 $ticketalreadyexists = 1;
2811 $operation[
'type'] =
'recordevent';
2814 $ticketalreadyexists = -1;
2821 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2822 if ($thirdpartyid > 0) {
2824 $idtouseforthirdparty = $thirdpartyid;
2825 $operationslog .=
'<br>We already have found a related thirdparty id, so we bypass the action loadthirdparty and use idtouseforthirdparty='.$idtouseforthirdparty;
2826 } elseif (empty($operation[
'actionparam'])) {
2828 $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;";
2829 $this->errors[] = $this->error;
2831 $actionparam = $operation[
'actionparam'];
2832 $idtouseforthirdparty =
'';
2833 $nametouseforthirdparty =
'';
2834 $emailtouseforthirdparty =
'';
2835 $namealiastouseforthirdparty =
'';
2837 $operationslog .=
'<br>Loop on each property to set into actionparam';
2841 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2845 $regforregex = array();
2847 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2848 $sourcefield = $regforregex[1];
2849 $regexstring = $regforregex[2];
2852 if (!empty($sourcefield) && !empty($regexstring)) {
2853 if (strtolower($sourcefield) ==
'body') {
2854 $sourcestring = $messagetext;
2855 } elseif (strtolower($sourcefield) ==
'subject') {
2856 $sourcestring = $subject;
2857 } elseif (strtolower($sourcefield) ==
'header') {
2858 $sourcestring = $header;
2861 if ($sourcestring) {
2862 $regforval = array();
2863 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2865 if ($propertytooverwrite ==
'id') {
2866 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2868 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2869 } elseif ($propertytooverwrite ==
'email') {
2870 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2872 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2873 } elseif ($propertytooverwrite ==
'name') {
2874 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2876 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2877 } elseif ($propertytooverwrite ==
'name_alias') {
2878 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2880 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2882 $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';
2886 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2887 $idtouseforthirdparty =
null;
2888 $nametouseforthirdparty =
null;
2889 $emailtouseforthirdparty =
null;
2890 $namealiastouseforthirdparty =
null;
2892 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2894 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2900 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2901 $this->errors[] = $this->error;
2903 $operationslog .=
'<br>'.$this->error;
2905 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2909 if ($propertytooverwrite ==
'id') {
2910 $idtouseforthirdparty = $reg[2];
2912 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2913 } elseif ($propertytooverwrite ==
'email') {
2914 $emailtouseforthirdparty = $reg[2];
2916 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2917 } elseif ($propertytooverwrite ==
'name') {
2918 $nametouseforthirdparty = $reg[2];
2920 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2921 } elseif ($propertytooverwrite ==
'name_alias') {
2922 $namealiastouseforthirdparty = $reg[2];
2924 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2928 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2929 $this->errors[] = $this->error;
2934 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2936 $operationslog .=
'<br>We have this initial main data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty.
'.';
2939 $tmpobject->element =
'generic';
2940 $tmpobject->id = $idtouseforthirdparty;
2941 $tmpobject->name = $nametouseforthirdparty;
2942 $tmpobject->name_alias = $namealiastouseforthirdparty;
2943 $tmpobject->email = $emailtouseforthirdparty;
2947 $idtouseforthirdparty = $tmpobject->id;
2948 $nametouseforthirdparty = $tmpobject->name;
2949 $namealiastouseforthirdparty = $tmpobject->name_alias;
2950 $emailtouseforthirdparty = $tmpobject->email;
2952 $operationslog .=
'<br>We try to search existing thirdparty with idtouseforthirdparty='.$idtouseforthirdparty.
' emailtouseforthirdparty='.$emailtouseforthirdparty.
' nametouseforthirdparty='.$nametouseforthirdparty.
' namealiastouseforthirdparty='.$namealiastouseforthirdparty;
2955 $result = $thirdpartystatic->findNearest((
int) $idtouseforthirdparty, (
string) $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', (
string) $emailtouseforthirdparty, (
string) $namealiastouseforthirdparty);
2958 if (
getDolGlobalInt(
'EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE') && $result == -2) {
2959 $idtouseforthirdparty =
getDolGlobalInt(
'EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE');
2961 $thirdpartystatic->fetch($idtouseforthirdparty);
2963 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));
2965 $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);
2968 $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 ?)';
2969 $this->errors[] = $this->error;
2974 if ($operation[
'type'] ==
'loadthirdparty') {
2975 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2978 $resultContact = $contactstatic->findNearest(0,
'',
'',
'', (
string) $emailtouseforthirdparty,
'', 0);
2979 if ($resultContact > 0) {
2980 $contactstatic->fetch($resultContact);
2981 $idtouseforthirdparty = $contactstatic->socid;
2982 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2984 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2987 $langs->load(
"errors");
2988 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', (
string) $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2989 $this->errors[] = $this->error;
2993 $langs->load(
"errors");
2994 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', (
string) $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2995 $this->errors[] = $this->error;
2997 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2998 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
3001 $thirdpartystatic =
new Societe($db);
3002 $thirdpartystatic->name = (string) $nametouseforthirdparty;
3003 if (!empty($namealiastouseforthirdparty)) {
3004 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
3005 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
3008 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'' : $fromtext) : $replytostring);
3010 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($email_from) ?
'' : $email_from) : $replyto) : $emailtouseforthirdparty);
3013 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3015 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
3016 $thirdpartystatic->code_client =
'auto';
3018 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
3019 $thirdpartystatic->code_fournisseur =
'auto';
3022 if ($errorforthisaction) {
3025 $result = $thirdpartystatic->create($user);
3028 $this->error = $thirdpartystatic->error;
3029 $this->errors = $thirdpartystatic->errors;
3031 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag((
string) $thirdpartystatic->id);
3035 } elseif ($result > 0) {
3036 dol_syslog(
"One and only one existing third party has been found");
3038 $thirdpartystatic->fetch($result);
3040 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag((
string) $thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name);
3044 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
3045 if (empty($operation[
'actionparam'])) {
3047 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
3048 $this->errors[] = $this->error;
3050 $contact_static =
new Contact($this->db);
3052 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3053 if ($errorforthisaction) {
3056 if (!empty($contact_static->email) && $contact_static->email != $email_from) {
3057 $email_from = $contact_static->email;
3059 $email_from = (string) $email_from;
3061 $email_from = (string) $email_from;
3063 $result = $contactstatic->fetch(0,
null,
'', $email_from);
3066 $this->error =
'Error when getting contact with email ' . $email_from;
3067 $this->errors[] = $this->error;
3069 } elseif ($result == 0) {
3070 dol_syslog(
"Contact with email " . $email_from .
" was not found. We try to create it.");
3071 $contactstatic =
new Contact($this->db);
3074 $contactstatic->email = $email_from;
3075 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($email_from);
3078 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3080 if ($errorforthisaction) {
3084 if (!empty($contactstatic->country)) {
3085 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
3086 $result =
getCountry(
'',
'3', $this->db,
null, 1, $contactstatic->country);
3087 if ($result ==
'NotDefined') {
3089 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
3090 } elseif (!($result > 0)) {
3092 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
3093 $this->errors[] = $this->db->lasterror();
3095 $contactstatic->country_id = $result;
3096 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
3098 } elseif (!empty($contactstatic->country_code)) {
3099 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
3100 $result =
getCountry($contactstatic->country_code,
'3', $this->db);
3101 if ($result ==
'NotDefined') {
3103 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
3104 } elseif (!($result > 0)) {
3106 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
3107 $this->errors[] = $this->db->lasterror();
3109 $contactstatic->country_id = $result;
3110 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
3114 if (!$errorforactions) {
3116 if (!empty($contactstatic->state)) {
3117 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
3118 if (empty($result)) {
3120 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
3121 } elseif (!($result > 0)) {
3123 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
3124 $this->errors[] = $this->db->lasterror();
3126 $contactstatic->state_id = $result;
3127 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
3129 } elseif (!empty($contactstatic->state_code)) {
3130 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
3131 if (empty($result)) {
3133 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
3134 } elseif (!($result > 0)) {
3136 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
3137 $this->errors[] = $this->db->lasterror();
3139 $contactstatic->state_id = $result;
3140 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
3145 if (!$errorforactions) {
3146 $result = $contactstatic->create($user);
3149 $this->error = $contactstatic->error;
3150 $this->errors = $contactstatic->errors;
3152 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag((
string) $contactstatic->id);
3159 } elseif ($operation[
'type'] ==
'recordevent') {
3163 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
3164 if ($alreadycreated == 0) {
3165 $operationslog .=
'<br>We did not find existing actioncomm with msgid='.$msgid;
3167 if ($projectstatic->id > 0) {
3168 if ($projectfoundby) {
3169 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
3172 if ($thirdpartystatic->id > 0) {
3173 if ($thirdpartyfoundby) {
3174 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3177 if ($contactstatic->id > 0) {
3178 if ($contactfoundby) {
3179 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3183 $description = $descriptiontitle;
3189 $descriptionfull = $description;
3191 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3196 $actioncomm->type_code =
'AC_OTH_AUTO';
3197 $actioncomm->code =
'AC_'.$actioncode;
3198 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$email_from;
3199 $actioncomm->note_private = $descriptionfull;
3200 $actioncomm->fk_project = $projectstatic->id;
3201 $actioncomm->datep = $dateemail;
3202 $actioncomm->datef = $dateemail;
3203 $actioncomm->percentage = -1;
3204 $actioncomm->socid = $thirdpartystatic->id;
3205 $actioncomm->contact_id = $contactstatic->id;
3206 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array());
3207 $actioncomm->authorid = $user->id;
3208 $actioncomm->userownerid = $user->id;
3210 $actioncomm->email_msgid = $msgid;
3211 $actioncomm->email_from = $fromstring;
3212 $actioncomm->email_sender = $sender;
3213 $actioncomm->email_to = $to;
3214 $actioncomm->email_tocc = $sendtocc;
3215 $actioncomm->email_tobcc = $sendtobcc;
3216 $actioncomm->email_subject = $subject;
3217 $actioncomm->errors_to =
'';
3219 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
3220 $actioncomm->fk_element = $fk_element_id;
3221 $actioncomm->elementid = $fk_element_id;
3222 $actioncomm->elementtype = $fk_element_type;
3223 if (is_object($objectemail) && $objectemail->module) {
3224 $actioncomm->elementtype .=
'@'.$objectemail->module;
3231 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3233 if ($errorforthisaction) {
3236 $result = $actioncomm->create($user);
3239 $this->errors = $actioncomm->errors;
3241 if ($fk_element_type ==
"ticket" && is_object($objectemail)) {
3242 if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED || $objectemail->status == Ticket::STATUS_NEED_MORE_INFO || $objectemail->status == Ticket::STATUS_WAITING) {
3243 if ($objectemail->fk_user_assign !=
null) {
3244 $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED);
3246 $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ);
3250 $operationslog .=
'<br>Ticket Re-Opened successfully -> ref='.$objectemail->ref;
3253 $this->error =
'Error while changing the ticket status -> ref='.$objectemail->ref;
3254 $this->errors[] = $this->error;
3257 if (!empty($attachments)) {
3259 $ticket =
new Ticket($this->db);
3260 $ticket->fetch($fk_element_id);
3261 $destdir =
$conf->ticket->dir_output.
'/'.$ticket->ref;
3266 foreach ($attachments as $attachment) {
3267 $attachment->save($destdir.
'/');
3270 $this->
getmsg($connection, $imapemail, $destdir);
3275 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag((
string) $actioncomm->id);
3279 $operationslog .=
'<br>An event in actioncomm table already exists for the msgid = '.$msgid.
' so we bypass this action.';
3281 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
3284 foreach ($attachments as $attachment) {
3285 if ($attachment->getName() ===
'undefined') {
3288 $data[$attachment->getName()] = $attachment->getContent();
3292 foreach ($pj as $key => $val) {
3293 $data[$val[
'filename']] =
getFileData($imapemail, (
string) $val[
'pos'], $val[
'type'], $connection);
3296 if (count($data) > 0) {
3297 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($email_from).
"%'";
3298 $resql = $this->db->query($sql);
3299 if ($this->db->num_rows($resql) == 0) {
3300 $this->errors[] =
"User Not allowed to add documents ({$email_from})";
3302 $arrayobject = array(
3303 'propale' => array(
'table' =>
'propal',
3304 'fields' => array(
'ref'),
3305 'class' =>
'comm/propal/class/propal.class.php',
3306 'object' =>
'Propal'),
3307 'holiday' => array(
'table' =>
'holiday',
3308 'fields' => array(
'ref'),
3309 'class' =>
'holiday/class/holiday.class.php',
3310 'object' =>
'Holiday'),
3311 'expensereport' => array(
'table' =>
'expensereport',
3312 'fields' => array(
'ref'),
3313 'class' =>
'expensereport/class/expensereport.class.php',
3314 'object' =>
'ExpenseReport'),
3315 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
3316 'fields' => array(
'ref'),
3317 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
3318 'object' =>
'RecruitmentJobPosition'),
3319 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
3320 'fields' => array(
'ref'),
3321 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
3322 'object' =>
'RecruitmentCandidature'),
3323 'societe' => array(
'table' =>
'societe',
3324 'fields' => array(
'code_client',
'code_fournisseur'),
3325 'class' =>
'societe/class/societe.class.php',
3326 'object' =>
'Societe'),
3327 'commande' => array(
'table' =>
'commande',
3328 'fields' => array(
'ref'),
3329 'class' =>
'commande/class/commande.class.php',
3330 'object' =>
'Commande'),
3331 'expedition' => array(
'table' =>
'expedition',
3332 'fields' => array(
'ref'),
3333 'class' =>
'expedition/class/expedition.class.php',
3334 'object' =>
'Expedition'),
3335 'contract' => array(
'table' =>
'contrat',
3336 'fields' => array(
'ref'),
3337 'class' =>
'contrat/class/contrat.class.php',
3338 'object' =>
'Contrat'),
3339 'fichinter' => array(
'table' =>
'fichinter',
3340 'fields' => array(
'ref'),
3341 'class' =>
'fichinter/class/fichinter.class.php',
3342 'object' =>
'Fichinter'),
3343 'ticket' => array(
'table' =>
'ticket',
3344 'fields' => array(
'ref'),
3345 'class' =>
'ticket/class/ticket.class.php',
3346 'object' =>
'Ticket'),
3347 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
3348 'fields' => array(
'ref'),
3349 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
3350 'object' =>
'KnowledgeRecord'),
3351 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
3352 'fields' => array(
'ref'),
3353 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
3354 'object' =>
'SupplierProposal'),
3355 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
3356 'fields' => array(
'ref',
'ref_supplier'),
3357 'class' =>
'fourn/class/fournisseur.commande.class.php',
3358 'object' =>
'SupplierProposal'),
3359 'facture' => array(
'table' =>
'facture',
3360 'fields' => array(
'ref'),
3361 'class' =>
'compta/facture/class/facture.class.php',
3362 'object' =>
'Facture'),
3363 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
3364 'fields' => array(
'ref',
'ref_client'),
3365 'class' =>
'fourn/class/fournisseur.facture.class.php',
3366 'object' =>
'FactureFournisseur'),
3367 'produit' => array(
'table' =>
'product',
3368 'fields' => array(
'ref'),
3369 'class' =>
'product/class/product.class.php',
3370 'object' =>
'Product'),
3371 'productlot' => array(
'table' =>
'product_lot',
3372 'fields' => array(
'batch'),
3373 'class' =>
'product/stock/class/productlot.class.php',
3374 'object' =>
'Productlot'),
3375 'projet' => array(
'table' =>
'projet',
3376 'fields' => array(
'ref'),
3377 'class' =>
'projet/class/projet.class.php',
3378 'object' =>
'Project'),
3379 'projet_task' => array(
'table' =>
'projet_task',
3380 'fields' => array(
'ref'),
3381 'class' =>
'projet/class/task.class.php',
3382 'object' =>
'Task'),
3383 'ressource' => array(
'table' =>
'resource',
3384 'fields' => array(
'ref'),
3385 'class' =>
'ressource/class/dolressource.class.php',
3386 'object' =>
'Dolresource'),
3387 'bom' => array(
'table' =>
'bom_bom',
3388 'fields' => array(
'ref'),
3389 'class' =>
'bom/class/bom.class.php',
3391 'mrp' => array(
'table' =>
'mrp_mo',
3392 'fields' => array(
'ref'),
3393 'class' =>
'mrp/class/mo.class.php',
3397 if (!is_object($hookmanager)) {
3398 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3401 $hookmanager->initHooks(array(
'emailcolector',
'emailcollector'));
3402 $parameters = array(
'arrayobject' => $arrayobject);
3403 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
3405 $arrayobject = $hookmanager->resArray;
3408 $resultobj = array();
3410 foreach ($arrayobject as $key => $objectdesc) {
3411 $sql =
'SELECT DISTINCT t.rowid ';
3412 $sql .=
' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc[
'table']) .
' AS t';
3414 foreach ($objectdesc[
'fields'] as $field) {
3415 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $this->db->sanitize($field) .
", '%') AND t." . $this->db->sanitize($field) .
" <> '') OR ";
3417 $sql = substr($sql, 0, -4);
3419 $ressqlobj = $this->db->query($sql);
3421 while ($obj = $this->db->fetch_object($ressqlobj)) {
3422 $resultobj[$key][] = $obj->rowid;
3427 foreach ($resultobj as $mod => $ids) {
3428 $moddesc = $arrayobject[$mod];
3429 $elementpath = $mod;
3431 $objectmanaged =
new $moddesc[
'object']($this->db);
3432 '@phan-var-force CommonObject $objectmanaged';
3433 foreach ($ids as $val) {
3434 $res = $objectmanaged->fetch($val);
3436 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
3437 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
3439 $this->errors[] =
'object not found';
3443 foreach ($dirs as $target) {
3444 $prefix = $this->actions[$this->id][
'actionparam'];
3445 foreach ($data as $filename => $content) {
3446 $resr = $this->
saveAttachment($target, $prefix .
'_' . $filename, $content);
3448 $this->errors[] =
'Doc not saved';
3453 $operationslog .=
'<br>Save attachment files on disk';
3455 $this->errors[] =
'no joined piece';
3457 $operationslog .=
'<br>No joinded files';
3459 } elseif ($operation[
'type'] ==
'project') {
3461 $projecttocreate =
new Project($this->db);
3462 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
3463 if ($alreadycreated == 0) {
3464 if ($thirdpartystatic->id > 0) {
3465 $projecttocreate->socid = $thirdpartystatic->id;
3466 if ($thirdpartyfoundby) {
3467 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3470 if ($contactstatic->id > 0) {
3471 $projecttocreate->contact_id = $contactstatic->id;
3472 if ($contactfoundby) {
3473 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3477 $description = $descriptiontitle;
3483 $descriptionfull = $description;
3485 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3489 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
3490 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
3492 $projecttocreate->title = $subject;
3493 $projecttocreate->date_start = $dateemail;
3494 $projecttocreate->date_end = 0;
3495 $projecttocreate->opp_status = $id_opp_status;
3496 $projecttocreate->opp_percent = $percent_opp_status;
3498 $projecttocreate->note_private = $descriptionfull;
3499 $projecttocreate->entity =
$conf->entity;
3501 $projecttocreate->email_date = $dateemail;
3502 $projecttocreate->email_msgid = $msgid;
3503 $projecttocreate->email_from = $fromstring;
3504 $projecttocreate->email_sender = $sender;
3505 $projecttocreate->email_to = $to;
3506 $projecttocreate->email_tocc = $sendtocc;
3507 $projecttocreate->email_tobcc = $sendtobcc;
3508 $projecttocreate->email_subject = $subject;
3509 $projecttocreate->errors_to =
'';
3511 $savesocid = $projecttocreate->socid;
3515 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3519 if (empty($projecttocreate->ref)) {
3528 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
3529 foreach ($dirmodels as $reldir) {
3530 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
3531 if (file_exists($file)) {
3532 $classname = $modele;
3537 if ($classname !==
'') {
3538 if ($savesocid > 0) {
3539 if ($savesocid != $projecttocreate->socid) {
3541 $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';
3542 $this->errors[] = $this->error;
3545 if ($projecttocreate->socid > 0) {
3546 $thirdpartystatic->fetch($projecttocreate->socid);
3550 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
3551 $modModuleToUseForNextValue =
new $classname();
3552 '@phan-var-force ModeleNumRefProjects $modModuleToUseForNextValue';
3553 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
3555 $projecttocreate->ref = $defaultref;
3559 if ($errorforthisaction) {
3562 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
3564 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3566 $operationslog .=
'<br>'.$this->error;
3569 $result = $projecttocreate->create($user);
3572 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
3573 $this->errors = $projecttocreate->errors;
3575 $operationslog .=
'<br>'.$this->error;
3578 $destdir =
$conf->project->dir_output.
'/'.$projecttocreate->ref;
3583 foreach ($attachments as $attachment) {
3585 $typeattachment = (string) $attachment->getDisposition();
3586 $filename = $attachment->getFilename();
3587 $content = $attachment->getContent();
3591 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3593 $this->errors = array_merge($this->errors, [$this->error]);
3598 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3600 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3608 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3610 } elseif ($operation[
'type'] ==
'ticket') {
3612 $tickettocreate =
new Ticket($this->db);
3613 if ($ticketalreadyexists == 0) {
3614 if ($thirdpartystatic->id > 0) {
3615 $tickettocreate->socid = $thirdpartystatic->id;
3616 $tickettocreate->fk_soc = $thirdpartystatic->id;
3617 if ($thirdpartyfoundby) {
3618 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3621 if ($contactstatic->id > 0) {
3622 $tickettocreate->contact_id = $contactstatic->id;
3623 if ($contactfoundby) {
3624 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3628 $description = $descriptiontitle;
3634 $descriptionfull = $description;
3636 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3640 $tickettocreate->subject = $subject;
3641 $tickettocreate->message = $description;
3643 $tickettocreate->category_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1)));
3644 $tickettocreate->severity_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1)));
3645 $tickettocreate->origin_email = $email_from;
3646 $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto :
null);
3647 $tickettocreate->origin_references = (!empty($headers[
'References']) ? $headers[
'References'] :
null);
3648 $tickettocreate->fk_user_create = $user->id;
3649 $tickettocreate->datec =
dol_now();
3650 $tickettocreate->fk_project = $projectstatic->id;
3651 $tickettocreate->notify_tiers_at_create =
getDolGlobalInt(
'TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3652 $tickettocreate->note_private = $descriptionfull;
3653 $tickettocreate->entity =
$conf->entity;
3655 $tickettocreate->email_date = $dateemail;
3656 $tickettocreate->email_msgid = $msgid;
3657 $tickettocreate->email_from = $fromstring;
3658 $tickettocreate->email_sender = $sender;
3659 $tickettocreate->email_to = $to;
3660 $tickettocreate->email_tocc = $sendtocc;
3661 $tickettocreate->email_tobcc = $sendtobcc;
3662 $tickettocreate->email_subject = $subject;
3663 $tickettocreate->errors_to =
'';
3667 $savesocid = $tickettocreate->socid;
3671 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3673 $modele =
'UNDEFINED';
3675 if (empty($tickettocreate->ref)) {
3684 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
3685 foreach ($dirmodels as $reldir) {
3686 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3687 if (file_exists($file)) {
3688 $classname = $modele;
3693 if ($classname !==
'') {
3694 if ($savesocid > 0) {
3695 if ($savesocid != $tickettocreate->socid) {
3697 $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';
3698 $this->errors[] = $this->error;
3701 if ($tickettocreate->socid > 0) {
3702 $thirdpartystatic->fetch($tickettocreate->socid);
3707 $modModuleToUseForNextValue =
new $classname();
3708 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3709 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3711 $tickettocreate->ref = $defaultref;
3714 if ($errorforthisaction) {
3717 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3719 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3722 $tickettocreate->context[
'actionmsg2'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3723 $tickettocreate->context[
'actionmsg'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3727 $sender_contact =
new Contact($this->db);
3728 $sender_contact->fetch(0,
null,
'', $email_from);
3729 if (!empty($sender_contact->id)) {
3730 $tickettocreate->context[
'contact_id'] = $sender_contact->id;
3733 $result = $tickettocreate->create($user);
3736 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3737 $this->errors = $tickettocreate->errors;
3740 $destdir =
$conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3745 foreach ($attachments as $attachment) {
3747 $typeattachment = (string) $attachment->getDisposition();
3748 $filename = $attachment->getName();
3749 $content = $attachment->getContent();
3753 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3755 $this->errors = array_merge($this->errors, [$this->error]);
3760 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3762 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3771 $operationslog .=
'<br>Ticket already exists, so we bypass action "ticket"';
3773 } elseif ($operation[
'type'] ==
'candidature') {
3777 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3778 if ($alreadycreated == 0) {
3779 $description = $descriptiontitle;
3785 $descriptionfull = $description;
3787 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3791 $candidaturetocreate->subject = $subject;
3792 $candidaturetocreate->message = $description;
3793 $candidaturetocreate->type_code = 0;
3794 $candidaturetocreate->category_code =
null;
3795 $candidaturetocreate->severity_code =
null;
3796 $candidaturetocreate->email = $email_from;
3798 $candidaturetocreate->fk_user_creat = $user->id;
3799 $candidaturetocreate->date_creation =
dol_now();
3800 $candidaturetocreate->fk_project = $projectstatic->id;
3801 $candidaturetocreate->description = $description;
3802 $candidaturetocreate->note_private = $descriptionfull;
3803 $candidaturetocreate->entity =
$conf->entity;
3804 $candidaturetocreate->email_msgid = $msgid;
3805 $candidaturetocreate->email_date = $dateemail;
3806 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3811 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3855 if ($errorforthisaction) {
3859 $result = $candidaturetocreate->create($user);
3862 $this->error =
'Failed to create candidature: '.implode(
', ', $candidaturetocreate->errors);
3863 $this->errors = $candidaturetocreate->errors;
3866 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag((
string) $candidaturetocreate->id);
3869 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3872 if (!is_object($hookmanager)) {
3873 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3876 $hookmanager->initHooks(array(
'emailcolector',
'emailcollector'));
3878 $parameters = array(
3879 'connection' => $connection,
3880 'imapemail' => $imapemail,
3881 'overview' => $overview,
3883 'from' => $email_from,
3884 'fromtext' => $fromtext,
3886 'actionparam' => $operation[
'actionparam'],
3888 'thirdpartyid' => ($thirdpartyid ? $thirdpartyid : $thirdpartystatic->id),
3889 'objectid' => $objectid,
3890 'objectemail' => $objectemail,
3892 'messagetext' => $messagetext,
3893 'subject' => $subject,
3894 'header' => $header,
3895 'attachments' => $attachments,
3896 'savedattachments' => $savedattachments,
3897 'savedattachmentsdir' => $savedattachmentsdir,
3899 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3902 $errorforthisaction++;
3903 $this->error = $hookmanager->resPrint;
3904 if (!empty($hookmanager->resPrint)) {
3905 $operationslog .=
'<br>Hook error: '.dol_escape_htmltag($hookmanager->resPrint);
3908 if ($errorforthisaction) {
3910 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3912 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3916 if (!$errorforactions) {
3917 $nbactiondoneforemail++;
3923 if (!$errorforactions) {
3924 if (!empty($targetdir)) {
3927 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3928 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid.
' - '.$imapemail->getHeader()->get(
'subject').
' to '.$targetdir;
3930 $arrayofemailtodelete[$this->
uidAsString($imapemail)] = $imapemail;
3933 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3934 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3936 $arrayofemailtodelete[$imapemail] = $msgid;
3941 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);
3943 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3951 unset($objectemail);
3952 unset($projectstatic);
3953 unset($thirdpartystatic);
3954 unset($contactstatic);
3956 $nbemailprocessed++;
3958 if (!$errorforemail) {
3959 $nbactiondone += $nbactiondoneforemail;
3963 $this->db->commit();
3965 $this->db->rollback();
3969 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3970 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3971 $datelastok = strtotime($headers[
'Date']);
3977 $this->db->rollback();
3981 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3983 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3985 $langs->load(
"admin");
3986 $output = $langs->trans(
'NoNewEmailToProcess');
3987 $output .=
' (defaultlang='.$langs->defaultlang.
')';
3993 krsort($arrayofemailtodelete, SORT_NUMERIC);
3995 foreach ($arrayofemailtodelete as $imapemailnum => $imapemail) {
3996 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemailnum);
3998 $operationslog .=
"<br> move email ".$imapemailnum.($mode > 0 ?
' (test)' :
'');
4000 if (empty($mode) && empty($error)) {
4001 $tmptargetdir = $targetdir;
4008 $result = $imapemail->move($tmptargetdir,
false);
4011 $operationslog .=
'<br>Exception !!!! '.$e->getMessage();
4013 if (empty($result)) {
4014 dol_syslog(
"Failed to move email into target directory ".$targetdir);
4015 $operationslog .=
'<br>Failed to move email into target directory '.$targetdir;
4021 if (empty($mode) && empty($error)) {
4023 $operationslog .=
"<br>Expunge";
4028 $client->disconnect();
4030 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
4031 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
4033 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid.($mode > 0 ?
' (test)' :
'');
4035 if (empty($mode) && empty($error)) {
4036 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
4039 $this->error = imap_last_error();
4040 $this->errors[] = $this->error;
4042 $operationslog .=
'<br>Error in move '.$this->error;
4049 if (empty($mode) && empty($error)) {
4051 $operationslog .=
"<br>Expunge";
4053 imap_expunge($connection);
4055 imap_close($connection);
4058 $this->datelastresult = $now;
4059 $this->lastresult = $output;
4061 $this->debuginfo .=
'IMAP search array used : '.$search;
4063 $this->debuginfo .=
'IMAP search string used : '.$search;
4066 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
4068 if ($operationslog) {
4069 $this->debuginfo .= $operationslog;
4072 if (empty($error) && empty($mode)) {
4073 $this->datelastok = $datelastok;
4076 if (!empty($this->errors)) {
4077 $this->lastresult .=
"<br>".implode(
"<br>", $this->errors);
4079 $this->codelastresult = ($error ?
'KO' :
'OK');
4085 dol_syslog(
"EmailCollector::doCollectOneCollector end error=".$error, LOG_INFO);
4087 return $error ? -1 : 1;
4102 private function getmsg($mbox, $mid, $destdir =
''): int
4106 global $charset, $htmlmsg, $plainmsg, $attachments;
4107 $htmlmsg = $plainmsg = $charset =
'';
4108 $attachments = array();
4115 $s = imap_fetchstructure($mbox, $mid, FT_UID);
4117 $this->errors = array_merge($this->errors, [imap_last_error()]);
4121 if (empty($s->parts)) {
4123 $this->
getpart($mbox, $mid, $s,
'0');
4126 foreach ($s->parts as $partno0 => $p) {
4127 $this->
getpart($mbox, $mid, $p, (
string) ($partno0 + 1), $destdir);
4160 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
4163 global $htmlmsg, $plainmsg, $charset, $attachments;
4167 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
4168 imap_body($mbox, $mid, FT_UID);
4170 if ($p->encoding == 4) {
4171 $data = quoted_printable_decode($data);
4172 } elseif ($p->encoding == 3) {
4173 $data = base64_decode($data);
4179 if ($p->parameters) {
4180 foreach ($p->parameters as $x) {
4181 $params[strtolower($x->attribute)] = $x->value;
4184 if (!empty($p->dparameters)) {
4185 foreach ($p->dparameters as $x) {
4186 $params[strtolower($x->attribute)] = $x->value;
4189 '@phan-var-force array{filename?:string,name?:string,charset?:string} $params';
4194 if (!empty($params[
'filename']) || !empty($params[
'name'])) {
4196 $filename = $params[
'filename'] ?? $params[
'name'];
4198 $attachments[$filename] = $data;
4200 if (strlen($destdir)) {
4201 if (substr($destdir, -1) !=
'/') {
4206 $file_name_complete = $filename;
4207 $destination = $destdir.$file_name_complete;
4210 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
4213 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
4216 $file_name_original = $file_name;
4225 while (file_exists($destdir.$file_name.
".".$extension)) {
4226 $file_name = $file_name_original .
' (' . $num .
')';
4227 $file_name_complete = $file_name .
"." . $extension;
4228 $destination = $destdir.$file_name_complete;
4234 file_put_contents($destination, $data);
4240 if ($p->type == 0 && $data) {
4241 if (!empty($params[
'charset'])) {
4246 if (strtolower($p->subtype) ==
'plain') {
4247 $plainmsg .= trim($data).
"\n\n";
4249 $htmlmsg .= $data.
"<br><br>";
4251 $charset = $params[
'charset'];
4252 } elseif ($p->type == 2 && $data) {
4258 if (!empty($params[
'charset'])) {
4261 $plainmsg .= $data.
"\n\n";
4265 if (!empty($p->parts)) {
4266 foreach ($p->parts as $partno0 => $p2) {
4267 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1), $destdir);
4283 if (!$string || $fromEncoding == $toEncoding) {
4286 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
4287 if (!$convertedString && extension_loaded(
'mbstring')) {
4288 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
4290 if (!$convertedString) {
4291 throw new Exception(
'Mime string encoding conversion failed');
4293 return $convertedString;
4312 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
4313 $elements = imap_mime_header_decode($subject);
4315 if (!empty($elements)) {
4316 $num = count($elements);
4317 for ($i = 0; $i < $num; $i++) {
4318 $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));
4319 $newstring .= $stringinutf8;
4321 $subject = $newstring;
4323 } elseif (!function_exists(
'mb_decode_mimeheader')) {
4324 $subject = mb_decode_mimeheader($subject);
4325 } elseif (function_exists(
'iconv_mime_decode')) {
4326 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
4329 return (
string) $subject;
4339 private function saveEmailCollectorAttachmentsToDir($destdir, $attachments)
4341 $destdir = rtrim((
string) $destdir,
'/');
4342 if ($destdir ===
'' || empty($attachments) || !is_array($attachments)) {
4353 $seenHashes = array();
4356 $filelist =
dol_dir_list($destdir,
'files', 0,
'',
'(\\.meta|_preview.*.*\\.png)$',
'date', SORT_DESC, 0, 1);
4357 foreach ($filelist as $fileinfo) {
4358 if (empty($fileinfo[
'fullname']) || !is_file($fileinfo[
'fullname']) || !is_readable($fileinfo[
'fullname'])) {
4361 $hash = hash_file(
'sha256', $fileinfo[
'fullname']);
4362 if ($hash !==
false && empty($seenHashes[$hash])) {
4363 $seenHashes[$hash] = $fileinfo[
'name'];
4369 if (defined(
'DOL_DATA_ROOT')) {
4370 $root = rtrim((
string) DOL_DATA_ROOT,
'/').
'/';
4371 $destdirwithslash = $destdir.
'/';
4372 if (strpos($destdirwithslash, $root) === 0) {
4373 $relativeDir = rtrim(substr($destdirwithslash, strlen($root)),
'/');
4378 foreach ($attachments as $key => $attachment) {
4385 if (is_object($attachment)) {
4386 '@phan-var-force Webklex\PHPIMAP\Attachment $attachment';
4389 $origName = (string) $attachment->getName();
4390 }
catch (Throwable $e) {
4394 $content = (string) $attachment->getContent();
4395 }
catch (Throwable $e) {
4399 $tmpmime = (string) $attachment->getContentType();
4400 $mime = ($tmpmime !==
'' ? $tmpmime :
null);
4401 }
catch (Throwable $e) {
4406 $origName = (string) $key;
4407 $content = (string) $attachment;
4410 if ($origName ===
'' || $origName ===
'undefined') {
4411 $origName =
'attachment-'.$index;
4413 if ($content ===
'') {
4418 if ($safeName ===
'') {
4419 $safeName =
'attachment-'.$index;
4422 $contentHash = hash(
'sha256', $content);
4423 $finalName = $safeName;
4424 $useExisting =
false;
4425 if (!empty($seenHashes[$contentHash])) {
4426 $finalName = $seenHashes[$contentHash];
4427 if (file_exists($destdir.
'/'.$finalName)) {
4428 $useExisting =
true;
4432 if (!$useExisting) {
4434 while (file_exists($destdir.
'/'.$finalName)) {
4435 $finalName = preg_replace(
'/(\\.[A-Za-z0-9]{1,10})$/',
'', $safeName).
'-'.$n;
4436 if (preg_match(
'/\\.[A-Za-z0-9]{1,10}$/', $safeName, $m)) {
4437 $finalName .= $m[0];
4443 $seenHashes[$contentHash] = $finalName;
4446 $fullPath = $destdir.
'/'.$finalName;
4447 $size = (file_exists($fullPath) ? filesize($fullPath) : null);
4448 $sizevalue = ($size ===
false ? null : $size);
4449 $sha256 = $contentHash;
4452 'name' => $finalName,
4453 'original_name' => $origName,
4454 'relative_path' => ($relativeDir !==
'' ? $relativeDir.
'/'.$finalName :
''),
4455 'content_type' => $mime,
4456 'size' => ($sizevalue !== null ? (int) $sizevalue : null),
4457 'sha256' => $sha256,
4474 require_once DOL_DOCUMENT_ROOT .
'/core/lib/images.lib.php';
4479 if (!file_exists($destdir)) {
4485 $tmp = explode(
'.', $filename);
4486 $ext = array_pop($tmp);
4487 $filename = implode(
'.', $tmp);
4490 $filepath = $destdir . (preg_match(
'/\/$/', $destdir) ?
'' :
'/') . $filename .
'.' . $ext;
4492 while (file_exists($filepath)) {
4493 $filepath = $destdir . (preg_match(
'/\/$/', $destdir) ?
'' :
'/') . $filename .
'(' . $i .
').' . $ext;
4497 file_put_contents($filepath, $content);
4502 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
4503 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
4504 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
4505 $maxheightmini = $tmparraysize[
'maxheightmini'];
4506 $quality = $tmparraysize[
'quality'];
4509 vignette($filepath, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
4511 vignette($filepath, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
4527 if (is_object($imapemail)) {
4528 return $imapemail->getAttributes()[
"uid"];
4530 return (
string) $imapemail;