65 public $element =
'emailcollector';
70 public $table_element =
'emailcollector_emailcollector';
75 public $picto =
'email';
80 public $fk_element =
'fk_emailcollector';
85 protected $childtables = array();
90 protected $childtablesoncascade = array(
'emailcollector_emailcollectorfilter',
'emailcollector_emailcollectoraction');
116 public $fields = array(
117 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'visible' => -2,
'enabled' => 1,
'position' => 1,
'notnull' => 1,
'index' => 1),
118 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'enabled' => 1,
'visible' => 0,
'default' =>
'1',
'notnull' => 1,
'index' => 1,
'position' => 20),
119 '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'),
120 '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'),
121 'description' => array(
'type' =>
'text',
'label' =>
'Description',
'visible' => -1,
'enabled' => 1,
'position' => 60,
'notnull' => -1,
'cssview' =>
'small',
'csslist' =>
'small tdoverflowmax200'),
122 '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'),
123 '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'),
124 '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'),
125 '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'),
126 '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'),
127 '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' =>
''),
128 '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'),
129 'password' => array(
'type' =>
'password',
'label' =>
'Password',
'visible' => -1,
'enabled' =>
"1",
'position' => 103,
'notnull' => -1,
'comment' =>
"IMAP password",
'help' =>
'WithGMailYouCanCreateADedicatedPassword'),
130 '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'),
131 '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, ...'),
132 'target_directory' => array(
'type' =>
'varchar(255)',
'label' =>
'MailboxTargetDirectory',
'visible' => 1,
'enabled' => 1,
'position' => 110,
'notnull' => 0,
'csslist' =>
'tdoverflowmax100',
'help' =>
"EmailCollectorTargetDir"),
133 'maxemailpercollect' => array(
'type' =>
'integer',
'label' =>
'MaxEmailCollectPerCollect',
'visible' => -1,
'enabled' => 1,
'position' => 111,
'default' =>
'50'),
134 'datelastresult' => array(
'type' =>
'datetime',
'label' =>
'DateLastCollectResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 121,
'notnull' => -1,
'csslist' =>
'nowraponall'),
135 'codelastresult' => array(
'type' =>
'varchar(16)',
'label' =>
'CodeLastResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 122,
'notnull' => -1,),
136 'lastresult' => array(
'type' =>
'varchar(255)',
'label' =>
'LastResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 123,
'notnull' => -1,
'cssview' =>
'small',
'csslist' =>
'maxwidth250imp'),
137 'datelastok' => array(
'type' =>
'datetime',
'label' =>
'DateLastcollectResultOk',
'visible' => 1,
'enabled' =>
'$action != "create"',
'position' => 125,
'notnull' => -1,
'csslist' =>
'nowraponall'),
138 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'visible' => 0,
'enabled' => 1,
'position' => 61,
'notnull' => -1,),
139 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'visible' => 0,
'enabled' => 1,
'position' => 62,
'notnull' => -1,),
140 'date_creation' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'visible' => -2,
'enabled' => 1,
'position' => 500,
'notnull' => 1,),
141 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModification',
'visible' => -2,
'enabled' => 1,
'position' => 501,
'notnull' => 1,),
143 'fk_user_creat' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'visible' => -2,
'enabled' => 1,
'position' => 510,
'notnull' => 1,),
144 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModif',
'visible' => -2,
'enabled' => 1,
'position' => 511,
'notnull' => -1,),
146 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'visible' => -2,
'enabled' => 1,
'position' => 1000,
'notnull' => -1,),
147 'status' => array(
'type' =>
'integer',
'label' =>
'Status',
'visible' => 1,
'enabled' => 1,
'position' => 1000,
'notnull' => 1,
'default' =>
'0',
'index' => 1,
'arrayofkeyval' => array(0 =>
'Inactive', 1 =>
'Active'))
179 public $fk_user_creat;
184 public $fk_user_modif;
218 public $oauth_service;
222 public $imap_encryption;
230 public $source_directory;
234 public $target_directory;
238 public $maxemailpercollect;
243 public $datelastresult;
248 public $codelastresult;
273 const STATUS_DISABLED = 0;
274 const STATUS_ENABLED = 1;
284 global $conf, $langs;
288 $this->ismultientitymanaged = 1;
289 $this->isextrafieldmanaged = 0;
294 if (!
isModEnabled(
'multicompany') && isset($this->fields[
'entity'])) {
295 $this->fields[
'entity'][
'enabled'] = 0;
299 $oauthservices = array();
301 foreach ($conf->global as $key => $val) {
302 if (!empty($val) && preg_match(
'/^OAUTH_.*_ID$/', $key)) {
303 $key = preg_replace(
'/^OAUTH_/',
'', $key);
304 $key = preg_replace(
'/_ID$/',
'', $key);
305 if (preg_match(
'/^.*-/', $key)) {
306 $name = preg_replace(
'/^.*-/',
'', $key);
308 $name = $langs->trans(
"NoName");
310 $provider = preg_replace(
'/-.*$/',
'', $key);
311 $provider = ucfirst(strtolower($provider));
313 $oauthservices[$key] = $name.
" (".$provider.
")";
317 $this->fields[
'oauth_service'][
'arrayofkeyval'] = $oauthservices;
320 foreach ($this->fields as $key => $val) {
321 if (isset($val[
'enabled']) && empty($val[
'enabled'])) {
322 unset($this->fields[$key]);
327 foreach ($this->fields as $key => $val) {
328 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
329 foreach ($val[
'arrayofkeyval'] as $key2 => $val2) {
330 $this->fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
348 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
349 $langs->load(
"errors");
350 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
354 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
355 $this->password =
dolEncrypt($this->password);
359 $this->password =
dolDecrypt($this->password);
361 if (is_array($this->filters) && count($this->filters)) {
364 foreach ($this->filters as $filter) {
365 $emailcollectorfilter->type = $filter[
'type'];
366 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
367 $emailcollectorfilter->fk_emailcollector = $this->id;
368 $emailcollectorfilter->status = $filter[
'status'];
370 $emailcollectorfilter->create($user);
374 if (is_array($this->actions) && count($this->actions)) {
377 foreach ($this->actions as $operation) {
378 $emailcollectoroperation->type = $operation[
'type'];
379 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
380 $emailcollectoroperation->fk_emailcollector = $this->id;
381 $emailcollectoroperation->status = $operation[
'status'];
382 $emailcollectoroperation->position = $operation[
'position'];
384 $emailcollectoroperation->create($user);
400 global $langs, $extrafields;
421 unset(
$object->codelastresult);
422 unset(
$object->datelastresult);
427 $object->ref =
"copy_of_".$object->ref;
430 $object->host =
'imap.example.com';
433 if (is_array(
$object->array_options) && count(
$object->array_options) > 0) {
434 $extrafields->fetch_name_optionals_label($this->table_element);
435 foreach (
$object->array_options as $key => $option) {
436 $shortkey = preg_replace(
'/options_/',
'', $key);
437 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
438 unset(
$object->array_options[$key]);
444 $object->context[
'createfromclone'] =
'createfromclone';
445 $result =
$object->create($user);
451 unset(
$object->context[
'createfromclone']);
458 $this->db->rollback();
470 public function fetch($id, $ref =
null)
474 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
475 $this->password =
dolDecrypt($this->password);
508 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
512 $sql =
"SELECT s.rowid";
513 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
514 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
516 $sql .=
" AND s.status = 1";
518 $sql .= $this->db->order($sortfield, $sortorder);
523 $offset = $limit * $page;
525 $sql .= $this->db->plimit($limit + 1, $offset);
528 $result = $this->db->query($sql);
530 $num = $this->db->num_rows($result);
533 $obj = $this->db->fetch_object($result);
535 if ($emailcollector_static->fetch($obj->rowid)) {
536 $obj_ret[] = $emailcollector_static;
541 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
542 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
544 if (!count($obj_ret)) {
545 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
563 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
564 $langs->load(
"errors");
565 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
569 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
570 $this->password =
dolEncrypt($this->password);
574 $this->password =
dolDecrypt($this->password);
586 public function delete(
User $user, $notrigger = 0)
601 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
603 global $conf, $langs, $action, $hookmanager;
605 if (!empty($conf->dol_no_mouse_hover)) {
611 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
613 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
615 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
617 if ($option !=
'nolink') {
619 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
620 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
621 $add_save_lastsearch_values = 1;
623 if ($add_save_lastsearch_values) {
624 $url .=
'&save_lastsearch_values=1';
629 if (empty($notooltip)) {
631 $label = $langs->trans(
"ShowEmailCollector");
632 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
634 $linkclose .=
' title="'.dolPrintHTMLForAttribute($label).
'"';
635 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
637 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
640 $linkstart =
'<a href="'.$url.
'"';
641 $linkstart .= $linkclose.
'>';
644 $result .= $linkstart;
646 $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);
648 if ($withpicto != 2) {
649 $result .= $this->ref;
654 $hookmanager->initHooks(array(
'emailcollectordao'));
655 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result);
656 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
658 $result = $hookmanager->resPrint;
660 $result .= $hookmanager->resPrint;
688 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
691 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
692 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
693 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
694 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
697 $statusType =
'status5';
698 if ($status == self::STATUS_ENABLED) {
699 $statusType =
'status4';
702 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
713 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
714 $sql .=
' fk_user_creat, fk_user_modif';
715 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
716 $sql .=
' WHERE t.rowid = '.((int) $id);
717 $result = $this->db->query($sql);
719 if ($this->db->num_rows($result)) {
720 $obj = $this->db->fetch_object($result);
722 $this->
id = $obj->rowid;
724 $this->user_creation_id = $obj->fk_user_creat;
725 $this->user_modification_id = $obj->fk_user_modif;
726 $this->date_creation = $this->db->jdate($obj->datec);
727 $this->date_modification = empty($obj->datem) ?
'' : $this->db->jdate($obj->datem);
730 $this->db->free($result);
744 $this->host =
'localhost';
745 $this->login =
'alogin';
758 $this->filters = array();
760 $sql =
'SELECT rowid, type, rulevalue, status';
761 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
762 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
765 $resql = $this->db->query($sql);
767 $num = $this->db->num_rows($resql);
770 $obj = $this->db->fetch_object($resql);
771 $this->filters[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'rulevalue' => $obj->rulevalue,
'status' => $obj->status);
774 $this->db->free($resql);
790 $this->actions = array();
792 $sql =
'SELECT rowid, type, actionparam, status';
793 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
794 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
795 $sql .=
' ORDER BY position';
797 $resql = $this->db->query($sql);
799 $num = $this->db->num_rows($resql);
802 $obj = $this->db->fetch_object($resql);
803 $this->actions[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'actionparam' => $obj->actionparam,
'status' => $obj->status);
806 $this->db->free($resql);
825 $flags =
'/service=imap';
828 } elseif (empty($this->imap_encryption) || ($this->imap_encryption ==
'ssl' &&
getDolGlobalString(
'IMAP_FORCE_NOSSL'))) {
831 $flags .=
'/' . $this->imap_encryption;
834 $flags .=
'/novalidate-cert';
841 if (!empty($this->login) && strpos($this->login,
'/') !=
false) {
842 $partofauth = explode(
'/', $this->login);
843 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
846 $connectstringserver =
'{'.$this->host.
':'.$this->port.$flags.
'}';
848 return $connectstringserver;
859 if (function_exists(
'mb_convert_encoding')) {
861 $str = preg_replace(
"/ /",
"xxxSPACExxx", $str);
862 $str = preg_replace(
"/_/",
"xxxUNDERSCORExxx", $str);
863 $str = preg_replace(
"/\[Gmail\]/",
"xxxGMAILxxx", $str);
865 if ($str = mb_convert_encoding($str,
"UTF-7")) {
867 $str = preg_replace(
"/\+A/",
"&A", $str);
868 $str = preg_replace(
"/xxxUNDERSCORExxx/",
"_", $str);
870 $str = preg_replace(
"/xxxSPACExxx/",
" ", $str);
872 $str = preg_replace(
"/xxxGMAILxxx/",
"[Gmail]", $str);
876 $this->error =
"error: is not possible to encode this string '".$str.
"'";
896 $arrayofcollectors = $this->
fetchAll($user, 1);
898 foreach ($arrayofcollectors as $emailcollector) {
899 $result = $emailcollector->doCollectOneCollector(0);
901 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
903 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
904 if (!empty($emailcollector->errors)) {
905 $this->error .= implode(
'<br>', $emailcollector->errors);
908 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
931 global $conf, $langs;
933 $errorforthisaction = 0;
936 $outputlangs = $langs;
939 $newlang =
GETPOST(
'lang_id',
'aZ09');
942 $newlang = !empty(
$object->thirdparty->default_lang) ?
$object->thirdparty->default_lang : $newlang;
944 if (!empty($newlang)) {
946 $outputlangs->setDefaultLang($newlang);
956 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
959 $tmparray = explode(
'.', $propertytooverwrite);
960 if (count($tmparray) == 2) {
961 $tmpclass = $tmparray[0];
962 $tmpproperty = $tmparray[1];
964 $tmpproperty = $tmparray[0];
966 if ($tmpclass && ($tmpclass !=
$object->element)) {
976 $regforregex = array();
977 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
978 $sourcefield = $regforregex[1];
979 $regexstring = $regforregex[2];
981 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
982 $sourcefield = $regforregex[1];
983 $regexstring = $regforregex[2];
986 if (!empty($sourcefield) && !empty($regexstring)) {
987 if (strtolower($sourcefield) ==
'body') {
988 $sourcestring = $messagetext;
989 } elseif (strtolower($sourcefield) ==
'subject') {
990 $sourcestring = $subject;
991 } elseif (strtolower($sourcefield) ==
'header') {
992 $sourcestring = $header;
996 $regforval = array();
998 if (strtolower($sourcefield) ==
'body') {
999 $regexoptions =
'ms';
1001 if (strtolower($sourcefield) ==
'header') {
1002 $regexoptions =
'm';
1005 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
1007 $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
1008 if (strtolower($sourcefield) ==
'header') {
1009 if (preg_match(
'/^options_/', $tmpproperty)) {
1012 if (property_exists(
$object, $tmpproperty)) {
1019 if (preg_match(
'/^options_/', $tmpproperty)) {
1022 if (property_exists(
$object, $tmpproperty)) {
1030 if (preg_match(
'/^options_/', $tmpproperty)) {
1033 if (property_exists(
$object, $tmpproperty)) {
1041 if (property_exists(
$object, $tmpproperty)) {
1043 $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.';
1045 $tmp[$tmpproperty] =
null;
1046 $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.';
1051 $errorforthisaction++;
1052 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1053 $this->errors[] = $this->error;
1055 $operationslog .=
'<br>'.$this->error;
1057 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1059 if (preg_match(
'/^options_/', $tmpproperty)) {
1060 $valuecurrent =
$object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1062 if (property_exists(
$object, $tmpproperty)) {
1063 $valuecurrent =
$object->$tmpproperty;
1066 $valuecurrent = $tmp[$tmpproperty];
1070 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1071 $valuetouse = $regforregex[2];
1072 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null,
$object);
1074 $matcharray = array();
1075 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1076 if (is_array($matcharray[1])) {
1077 foreach ($matcharray[1] as $keytoreplace) {
1078 if ($keytoreplace) {
1079 if (preg_match(
'/^options_/', $keytoreplace)) {
1080 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1082 if (property_exists(
$object, $keytoreplace)) {
1083 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->$keytoreplace;
1086 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1095 if (preg_match(
'/^options_/', $tmpproperty)) {
1096 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1098 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1100 if (property_exists(
$object, $tmpproperty)) {
1101 $object->$tmpproperty = $valuetouse;
1103 $tmp[$tmpproperty] = $valuetouse;
1106 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1110 $errorforthisaction++;
1111 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1112 $this->errors[] = $this->error;
1117 return $errorforthisaction;
1126 public function doCollectOneCollector($mode = 0)
1128 global $db, $conf, $langs, $user;
1129 global $hookmanager;
1133 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1135 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1138 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1140 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1145 $this->debuginfo =
'';
1149 $searchfilterdoltrackid = 0;
1150 $searchfilternodoltrackid = 0;
1151 $searchfilterisanswer = 0;
1152 $searchfilterisnotanswer = 0;
1153 $searchfilterreplyto = 0;
1154 $searchfilterexcludebodyarray = array();
1155 $searchfilterexcludesubjectarray = array();
1156 $operationslog =
'';
1157 $rulesreplyto = array();
1158 $connectstringsource =
'';
1159 $connectstringtarget =
'';
1160 $connection =
false;
1161 $arrayofemail = array();
1166 if (empty($this->host)) {
1167 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1170 if (empty($this->login)) {
1171 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1174 if (empty($this->source_directory)) {
1175 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1181 $sourcedir = $this->source_directory;
1182 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1187 $sourcedir = $this->source_directory;
1188 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1191 if ($this->acces_type == 1) {
1193 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>';
1195 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1199 $keyforsupportedoauth2array = $this->oauth_service;
1200 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1201 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1203 $keyforprovider =
'';
1205 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', strtoupper($keyforsupportedoauth2array));
1206 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1208 if (!empty($supportedoauth2array)) {
1209 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1210 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1211 $OAUTH_SERVICENAME = $nameofservice;
1213 $OAUTH_SERVICENAME =
'Unknown';
1216 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1218 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1224 $storage =
new DoliStorage($db, $conf, $keyforprovider,
getDolGlobalString($keyforparamtenant));
1227 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1230 if (is_object($tokenobj) && method_exists($tokenobj,
'getEndOfLife')) {
1231 $endOfLife = $tokenobj->getEndOfLife();
1232 if ($endOfLife !== -9002 && $endOfLife !== -9001 && time() > ($endOfLife - 30)) {
1238 if (is_object($tokenobj) && $expire) {
1239 $this->debuginfo .=
'Refresh token '.$OAUTH_SERVICENAME.
'<br>';
1240 $credentials =
new Credentials(
1245 $serviceFactory = new \OAuth\ServiceFactory();
1246 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1250 if (preg_match(
'/^Microsoft/', $OAUTH_SERVICENAME)) {
1252 $tmp = explode(
'-', $OAUTH_SERVICENAME);
1253 $scopes = explode(
',',
getDolGlobalString(
'OAUTH_'.strtoupper($tmp[0]).(empty($tmp[1]) ?
'' :
'-'.$tmp[1]).
'_SCOPE'));
1256 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $scopes);
1258 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
1260 $refreshtoken = $tokenobj->getRefreshToken();
1261 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1264 $tokenobj->setRefreshToken($refreshtoken);
1265 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1267 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1268 if (is_object($tokenobj)) {
1269 $token = $tokenobj->getAccessToken();
1271 $this->error =
"Token not found";
1276 $this->error = $e->getMessage();
1277 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1281 $cm =
new ClientManager();
1282 $client = $cm->make([
1283 'host' => $this->host,
1284 'port' => $this->port,
1285 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1286 'validate_cert' => true,
1287 'protocol' =>
'imap',
1288 'username' => $this->login,
1289 'password' => $token,
1290 'authentication' =>
"oauth",
1294 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1296 $cm =
new ClientManager();
1297 $client = $cm->make([
1298 'host' => $this->host,
1299 'port' => $this->port,
1300 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1301 'validate_cert' => true,
1302 'protocol' =>
'imap',
1303 'username' => $this->login,
1304 'password' => $this->password,
1305 'authentication' =>
"login",
1313 }
catch (ConnectionFailedException $e) {
1314 $this->error = $e->getMessage();
1315 $this->errors[] = $this->error;
1316 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1320 $host = dol_getprefix(
'email');
1323 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1325 if (!function_exists(
'imap_open')) {
1326 $this->error =
'IMAP function not enabled on your PHP';
1332 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1333 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1335 $connectstringsource = $connectstringserver.$sourcedir;
1336 $connectstringtarget = $connectstringserver.$targetdir;
1339 $this->debuginfo .=
'connectstringsource = '.$connectstringsource.
', $connectstringtarget='.$connectstringtarget.
'<br>';
1341 $connection = imap_open($connectstringsource, $this->login, $this->password);
1342 if ($connection ===
false) {
1343 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1346 '@phan-var-force resource|IMAP\Connection $connection';
1349 $host = dol_getprefix(
'email');
1358 $criteria = array();
1361 $criteria = array(array(
'UNDELETED'));
1362 foreach ($this->filters as $rule) {
1363 if (empty($rule[
'status'])) {
1368 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1372 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1375 if ($rule[
'type'] ==
'from') {
1376 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1377 if (count($tmprulevaluearray) >= 2) {
1378 foreach ($tmprulevaluearray as $tmprulevalue) {
1379 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1382 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1385 if ($rule[
'type'] ==
'to') {
1386 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1387 if (count($tmprulevaluearray) >= 2) {
1388 foreach ($tmprulevaluearray as $tmprulevalue) {
1389 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1392 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1395 if ($rule[
'type'] ==
'bcc') {
1396 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1398 if ($rule[
'type'] ==
'cc') {
1399 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1401 if ($rule[
'type'] ==
'subject') {
1404 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1406 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1409 if ($rule[
'type'] ==
'body') {
1412 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1414 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1417 if ($rule[
'type'] ==
'header') {
1418 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1430 if ($rule[
'type'] ==
'seen') {
1431 array_push($criteria, array($not.
"SEEN"));
1433 if ($rule[
'type'] ==
'unseen') {
1434 array_push($criteria, array($not.
"UNSEEN"));
1436 if ($rule[
'type'] ==
'unanswered') {
1437 array_push($criteria, array($not.
"UNANSWERED"));
1439 if ($rule[
'type'] ==
'answered') {
1440 array_push($criteria, array($not.
"ANSWERED"));
1442 if ($rule[
'type'] ==
'smaller') {
1443 array_push($criteria, array($not.
"SMALLER"));
1445 if ($rule[
'type'] ==
'larger') {
1446 array_push($criteria, array($not.
"LARGER"));
1450 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1451 $searchfilterdoltrackid++;
1452 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1454 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1455 $searchfilterdoltrackid++;
1456 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1458 if ($rule[
'type'] ==
'withtrackingid') {
1459 $searchfilterdoltrackid++;
1460 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1462 if ($rule[
'type'] ==
'withouttrackingid') {
1463 $searchfilternodoltrackid++;
1464 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1467 if ($rule[
'type'] ==
'isanswer') {
1468 $searchfilterisanswer++;
1469 $searchhead .=
'/References.*@.*/';
1471 if ($rule[
'type'] ==
'isnotanswer') {
1472 $searchfilterisnotanswer++;
1473 $searchhead .=
'! /References.*@.*/';
1476 if ($rule[
'type'] ==
'replyto') {
1477 $searchfilterreplyto++;
1478 $rulesreplyto[] = $rule[
'rulevalue'];
1479 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1483 if (empty($targetdir) || !
getDolGlobalString(
'EMAILCOLLECTOR_NO_FILTER_ON_DATE_IF_THERE_IS_A_TARGETDIR')) {
1485 if ($this->datelastok) {
1486 $fromdate = $this->datelastok;
1488 if ($fromdate > 0) {
1490 array_push($criteria, array(
"SINCE" =>
date(
'j-M-Y', $fromdate - 86400)));
1495 dol_syslog(
"IMAP search string = ".var_export($criteria,
true));
1496 $search = var_export($criteria,
true);
1499 $search =
'UNDELETED';
1500 foreach ($this->filters as $rule) {
1501 if (empty($rule[
'status'])) {
1509 if (!empty($rule[
'rulevalue']) && strpos($rule[
'rulevalue'],
'!') === 0) {
1513 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1516 if ($rule[
'type'] ==
'from') {
1517 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1518 if (count($tmprulevaluearray) >= 2) {
1519 foreach ($tmprulevaluearray as $tmprulevalue) {
1520 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1523 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1526 if ($rule[
'type'] ==
'to') {
1527 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1528 if (count($tmprulevaluearray) >= 2) {
1529 foreach ($tmprulevaluearray as $tmprulevalue) {
1530 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1533 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1536 if ($rule[
'type'] ==
'bcc') {
1537 $search .= ($search ?
' ' :
'').$not.
'BCC';
1539 if ($rule[
'type'] ==
'cc') {
1540 $search .= ($search ?
' ' :
'').$not.
'CC';
1542 if ($rule[
'type'] ==
'subject') {
1545 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1547 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1550 if ($rule[
'type'] ==
'body') {
1553 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1556 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1559 if ($rule[
'type'] ==
'header') {
1560 $search .= ($search ?
' ' :
'').$not.
'HEADER '.$rule[
'rulevalue'];
1572 if ($rule[
'type'] ==
'seen') {
1573 $search .= ($search ?
' ' :
'').$not.
'SEEN';
1575 if ($rule[
'type'] ==
'unseen') {
1576 $search .= ($search ?
' ' :
'').$not.
'UNSEEN';
1578 if ($rule[
'type'] ==
'unanswered') {
1579 $search .= ($search ?
' ' :
'').$not.
'UNANSWERED';
1581 if ($rule[
'type'] ==
'answered') {
1582 $search .= ($search ?
' ' :
'').$not.
'ANSWERED';
1584 if ($rule[
'type'] ==
'smaller') {
1585 $search .= ($search ?
' ' :
'').$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1587 if ($rule[
'type'] ==
'larger') {
1588 $search .= ($search ?
' ' :
'').$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1592 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1593 $searchfilterdoltrackid++;
1594 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1596 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1597 $searchfilterdoltrackid++;
1598 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1600 if ($rule[
'type'] ==
'withtrackingid') {
1601 $searchfilterdoltrackid++;
1602 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1604 if ($rule[
'type'] ==
'withouttrackingid') {
1605 $searchfilternodoltrackid++;
1606 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1609 if ($rule[
'type'] ==
'isanswer') {
1610 $searchfilterisanswer++;
1611 $searchhead .=
'/References.*@.*/';
1613 if ($rule[
'type'] ==
'isnotanswer') {
1614 $searchfilterisnotanswer++;
1615 $searchhead .=
'! /References.*@.*/';
1618 if ($rule[
'type'] ==
'replyto') {
1619 $searchfilterreplyto++;
1620 $rulesreplyto[] = $rule[
'rulevalue'];
1621 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1625 if (empty($targetdir)) {
1627 if ($this->datelastok) {
1628 $fromdate = $this->datelastok;
1630 if ($fromdate > 0) {
1632 $search .= ($search ?
' ' :
'').
'SINCE '.
date(
'j-M-Y', $fromdate - 86400);
1640 $nbemailprocessed = 0;
1643 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1644 $arrayofemail = array();
1651 $tmpsourcedir = $sourcedir;
1656 $f = $client->getFolders(
false, $tmpsourcedir);
1663 foreach ($f as $candidate) {
1664 if ($candidate instanceof Webklex\PHPIMAP\Folder && $candidate->full_name === $tmpsourcedir) {
1665 $folder = $candidate;
1669 if ($folder instanceof Webklex\PHPIMAP\Folder) {
1670 $Query = $folder->messages()->where($criteria);
1673 $this->error =
"Source directory ".$sourcedir.
" not found";
1674 $this->errors[] = $this->error;
1675 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_WARNING);
1680 $this->error =
"Failed to execute getfolders";
1681 $this->errors[] = $this->error;
1682 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1685 }
catch (InvalidWhereQueryCriteriaException $e) {
1686 $this->error = $e->getMessage();
1687 $this->errors[] = $this->error;
1688 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1691 $this->error = $e->getMessage();
1692 $this->errors[] = $this->error;
1693 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1697 '@phan-var-force Webklex\PHPIMAP\Query\Query $Query';
1700 $Query->leaveUnread();
1702 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1703 dol_syslog(
"EmailCollector::doCollectOneCollector nb arrayofemail ".(is_array($arrayofemail) ? count($arrayofemail) :
'Not array'));
1705 $this->error = $e->getMessage();
1706 $this->errors[] = $this->error;
1707 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1710 } elseif ($connection !==
false) {
1712 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1714 if ($arrayofemail ===
false) {
1716 $mapoferrrors = imap_errors();
1717 if ($mapoferrrors !==
false) {
1719 $this->error =
"Search string not understood - ".implode(
',', $mapoferrrors);
1720 $this->errors[] = $this->error;
1725 $arrayofemailtodelete = array();
1728 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0 && $connection !==
false) {
1745 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1747 $richarrayofemail = array();
1749 foreach ($arrayofemail as $imapemail) {
1752 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1753 $header = $imapemail->getHeader()->raw;
1754 $overview = $imapemail->getAttributes();
1756 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1757 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1760 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1763 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)(\r\n|\s$)/m', $header, $matches);
1764 $headers = array_combine($matches[1], $matches[2]);
1767 $richarrayofemail[] = array(
'imapemail' => $imapemail,
'header' => $header,
'headers' => $headers,
'overview' => $overview,
'date' => empty($headers[
'Date']) ?
false : strtotime($headers[
'Date']));
1772 $richarrayofemail =
dol_sort_array($richarrayofemail,
'date',
'asc');
1776 foreach ($richarrayofemail as $tmpval) {
1777 if ($nbemailprocessed > 1000) {
1784 $imapemail = $tmpval[
'imapemail'];
1785 $header = $tmpval[
'header'];
1786 $overview = $tmpval[
'overview'];
1787 $headers = $tmpval[
'headers'];
1789 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1790 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1792 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1793 $headers[
'References'] = $headers[
'references'];
1795 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1796 $headers[
'Message-ID'] = $headers[
'message-id'];
1798 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1799 $headers[
'Subject'] = $headers[
'subject'];
1805 $emailto = (string) $overview[
'to'];
1810 $operationslog .=
'<br>** Process email #'.dol_escape_htmltag((
string) $iforemailloop);
1814 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1816 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1818 $operationslog .=
" - ".dol_escape_htmltag((
string) $imapemail);
1819 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id ??
'');
1821 $operationslog .=
" - MsgId: ".$msgid;
1822 $operationslog .=
" - Date: ".($headers[
'Date'] ?? $langs->transnoentitiesnoconv(
"NotFound"));
1823 $operationslog .=
" - References: ".dol_escape_htmltag($headers[
'References'] ?? $langs->transnoentitiesnoconv(
"NotFound")).
" - Subject: ".
dol_escape_htmltag($headers[
'Subject']);
1825 dol_syslog(
"-- Process email #".$iforemailloop.
", MsgId: ".$msgid.
", Date: ".($headers[
'Date'] ??
'').
", References: ".($headers[
'References'] ??
'').
", Subject: ".$headers[
'Subject']);
1828 $trackidfoundintorecipienttype =
'';
1829 $trackidfoundintorecipientid = 0;
1834 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)) {
1835 $trackidfoundintorecipienttype = $reg[1];
1836 $trackidfoundintorecipientid = $reg[2];
1837 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1838 $trackidfoundintorecipienttype =
'emailing';
1839 $trackidfoundintorecipientid = $reg[1];
1842 $trackidfoundintomsgidtype =
'';
1843 $trackidfoundintomsgidid = 0;
1848 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)) {
1849 $trackidfoundintomsgidtype = $reg[1];
1850 $trackidfoundintomsgidid = $reg[2];
1851 } elseif (preg_match(
'/(?:[\+\-])emailing-(\w+)@/', $msgid, $reg)) {
1852 $trackidfoundintomsgidtype =
'emailing';
1853 $trackidfoundintomsgidid = $reg[1];
1859 if ($searchfilterdoltrackid > 0) {
1860 $referencesForFilter = $headers[
'References'] ??
'';
1861 if (!empty($headers[
'References']) && !empty($headers[
'In-Reply-To'])) {
1862 $referencesForFilter .=
' ';
1864 $referencesForFilter .= ($headers[
'In-Reply-To'] ??
'');
1866 if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) {
1867 if (empty($referencesForFilter) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $referencesForFilter)) {
1868 $nbemailprocessed++;
1869 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");
1875 if ($searchfilternodoltrackid > 0) {
1876 $referencesForFilter = $headers[
'References'] ??
'';
1877 if (!empty($headers[
'References']) && !empty($headers[
'In-Reply-To'])) {
1878 $referencesForFilter .=
' ';
1880 $referencesForFilter .= ($headers[
'In-Reply-To'] ??
'');
1882 if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($referencesForFilter) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $referencesForFilter))) {
1883 $nbemailprocessed++;
1884 dol_syslog(
" Discarded - Suffix found into email recipient, or Header 'References/In-Reply-To' found and matching signature of application so with a trackid");
1889 if ($searchfilterisanswer > 0) {
1890 $referencesforanswer =
'';
1891 if (!empty($headers[
'References'])) {
1892 $referencesforanswer .= $headers[
'References'].
' ';
1894 if (!empty($headers[
'In-Reply-To'])) {
1895 $referencesforanswer .= $headers[
'In-Reply-To'];
1898 $hasdolibarrreference = 0;
1899 if (!empty($referencesforanswer)) {
1900 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $referencesforanswer)) {
1901 $hasdolibarrreference = 1;
1903 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $referencesforanswer)) {
1904 $hasdolibarrreference = 1;
1910 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
1916 if (!empty($headers[
'In-Reply-To'])) {
1920 if ($hasdolibarrreference) {
1927 $nbemailprocessed++;
1928 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)");
1932 if ($searchfilterisnotanswer > 0) {
1933 if (!empty($headers[
'In-Reply-To'])) {
1937 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
1943 $nbemailprocessed++;
1944 dol_syslog(
" Discarded - Email is an answer");
1949 if ($searchfilterreplyto > 0) {
1950 if (!empty($headers[
'Reply-To'])) {
1952 foreach ($rulesreplyto as $key => $rulereplyto) {
1953 if (preg_match(
'/'.preg_quote($rulereplyto,
'/').
'/', $headers[
'Reply-To'])) {
1958 if (!$isreplytook || $isreplytook != count($rulesreplyto)) {
1959 $nbemailprocessed++;
1960 dol_syslog(
" Discarded - Reply-to does not match");
1968 $thirdpartystatic =
new Societe($this->db);
1969 $contactstatic =
new Contact($this->db);
1970 $projectstatic =
new Project($this->db);
1972 $nbactiondoneforemail = 0;
1974 $errorforactions = 0;
1975 $thirdpartyfoundby =
'';
1976 $contactfoundby =
'';
1977 $projectfoundby =
'';
1978 $ticketfoundby =
'';
1979 $candidaturefoundby =
'';
1983 $overviewdate = ($overview[
'date'] instanceof DateTimeInterface) ? $overview[
'date']->getTimestamp() : $overview[
'date'];
1985 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".$dateformated.
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
1990 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);
2000 global $htmlmsg, $plainmsg, $charset, $attachments;
2004 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
2007 $htmlmsg = $plainmsg =
'';
2008 $attachments = array();
2010 if ($imapemail->hasHTMLBody()) {
2011 $htmlmsg = $imapemail->getHTMLBody();
2013 if ($imapemail->hasTextBody() && $imapemail->getTextBody() !=
"\n") {
2014 $plainmsg = $imapemail->getTextBody();
2016 if ($imapemail->hasAttachments()) {
2017 $attachments = $imapemail->getAttachments()->all();
2019 $attachments = array();
2022 $getMsg = $this->
getmsg($connection, $imapemail);
2024 $this->errors = array_merge($this->errors, [$this->error]);
2028 '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments';
2038 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
2039 dol_syslog(
" Discarded - Email body is not valid utf8");
2043 if (!empty($searchfilterexcludebodyarray)) {
2044 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
2045 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
2046 $nbemailprocessed++;
2047 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
2048 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
2090 $replytostring =
'';
2094 $replytostring = !empty($headers[
'Reply-To']) ? $this->
decodeSMTPSubject($headers[
'Reply-To']) :
'';
2101 $tmpdate = $overview[
'date']->toDate();
2102 $tmptimezone = $tmpdate->getTimezone()->getName();
2105 if (preg_match(
'/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) {
2106 if ($reg[1] ==
'+' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2107 $dateemail -= (3600 * (int) $reg[2]);
2108 $dateemail -= (60 * (int) $reg[3]);
2110 if ($reg[1] ==
'-' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2111 $dateemail += (3600 * (int) $reg[2]);
2112 $dateemail += (60 * (int) $reg[3]);
2117 $fromstring = $overview[0]->from;
2118 $replytostring = (!empty($overview[
'in_reply-to']) ? $overview[
'in_reply-to'] : (!empty($headers[
'Reply-To']) ? $headers[
'Reply-To'] :
"")) ;
2120 $sender = !empty($overview[0]->sender) ? $overview[0]->sender :
'';
2121 $to = $overview[0]->to;
2122 $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc :
'';
2123 $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc :
'';
2125 $subject = $overview[0]->subject;
2128 if (!empty($searchfilterexcludesubjectarray)) {
2129 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
2130 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
2131 $nbemailprocessed++;
2132 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
2133 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
2140 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
2142 $fromtext = $reg[1];
2144 $from = $fromstring;
2147 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
2149 $replytotext = $reg[1];
2151 $replyto = $replytostring;
2155 $fk_element_type =
'';
2172 $objectemail =
null;
2175 $arrayofreferences = array();
2176 if (!empty($headers[
'References'])) {
2177 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
2179 if (!in_array(
'<'.$msgid.
'>', $arrayofreferences)) {
2180 $arrayofreferences = array_merge($arrayofreferences, array(
'<'.$msgid.
'>'));
2185 foreach ($arrayofreferences as $reference) {
2187 if (!empty($trackidfoundintorecipienttype)) {
2188 $resultsearchtrackid = -1;
2189 $reg[1] = $trackidfoundintorecipienttype;
2190 $reg[2] = $trackidfoundintorecipientid;
2191 } elseif (!empty($trackidfoundintomsgidtype)) {
2192 $resultsearchtrackid = -1;
2193 $reg[1] = $trackidfoundintomsgidtype;
2194 $reg[2] = $trackidfoundintomsgidid;
2196 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
2197 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2198 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
2202 if (!empty($resultsearchtrackid)) {
2204 $trackid = $reg[1].$reg[2];
2206 $objectid = $reg[2];
2208 if ($reg[1] ==
'thi') {
2209 $objectemail =
new Societe($this->db);
2211 if ($reg[1] ==
'ctc') {
2212 $objectemail =
new Contact($this->db);
2214 if ($reg[1] ==
'inv') {
2215 $objectemail =
new Facture($this->db);
2217 if ($reg[1] ==
'sinv') {
2220 if ($reg[1] ==
'pro') {
2221 $objectemail =
new Propal($this->db);
2223 if ($reg[1] ==
'ord') {
2224 $objectemail =
new Commande($this->db);
2226 if ($reg[1] ==
'shi') {
2229 if ($reg[1] ==
'spro') {
2232 if ($reg[1] ==
'sord') {
2235 if ($reg[1] ==
'rec') {
2236 $objectemail =
new Reception($this->db);
2238 if ($reg[1] ==
'proj') {
2239 $objectemail =
new Project($this->db);
2240 $projectfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2242 if ($reg[1] ==
'tas') {
2243 $objectemail =
new Task($this->db);
2245 if ($reg[1] ==
'con') {
2246 $objectemail =
new Contact($this->db);
2248 if ($reg[1] ==
'use') {
2249 $objectemail =
new User($this->db);
2251 if ($reg[1] ==
'tic') {
2252 $objectemail =
new Ticket($this->db);
2253 $ticketfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2255 if ($reg[1] ==
'recruitmentcandidature') {
2257 $candidaturefoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2259 if ($reg[1] ==
'mem') {
2260 $objectemail =
new Adherent($this->db);
2268 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
2271 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket";
2272 $sql .=
" WHERE email_msgid = '".$this->db->escape($reg[1]).
"' OR origin_references LIKE '%".$this->db->escape($this->db->escapeforlike($reg[1])).
"%'";
2273 $resql = $this->db->query($sql);
2275 $obj = $this->db->fetch_object($resql);
2277 $objectid = $obj->rowid;
2278 $objectemail =
new Ticket($this->db);
2279 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2286 if (!is_object($objectemail) &&
isModEnabled(
'project')) {
2287 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2288 $resql = $this->db->query($sql);
2290 $obj = $this->db->fetch_object($resql);
2292 $objectid = $obj->rowid;
2293 $objectemail =
new Project($this->db);
2294 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2301 if (!is_object($objectemail) &&
isModEnabled(
'recruitment')) {
2302 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2303 $resql = $this->db->query($sql);
2305 $obj = $this->db->fetch_object($resql);
2307 $objectid = $obj->rowid;
2309 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2318 if (is_object($objectemail)) {
2319 $result = $objectemail->fetch($objectid);
2321 $fk_element_id = $objectemail->id;
2322 $fk_element_type = $objectemail->element;
2324 if ($fk_element_type ==
'facture') {
2325 $fk_element_type =
'invoice';
2328 if (get_class($objectemail) !=
'Societe') {
2329 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2331 $thirdpartyid = $objectemail->id;
2334 if (get_class($objectemail) !=
'Contact') {
2335 $contactid = $objectemail->fk_socpeople;
2337 $contactid = $objectemail->id;
2340 if (get_class($objectemail) !=
'Project') {
2341 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2343 $projectid = $objectemail->id;
2346 if ($objectemail instanceof
Ticket) {
2347 $ticketid = $objectemail->id;
2349 $changeonticket_references =
false;
2350 if (empty($trackid)) {
2351 $trackid = $objectemail->track_id;
2353 if (empty($objectemail->origin_references)) {
2354 $objectemail->origin_references = !empty($headers[
'References']) ? $headers[
'References'] :
null;
2355 $changeonticket_references =
true;
2357 foreach ($arrayofreferences as $key => $referencetmp) {
2358 if (!str_contains($objectemail->origin_references, $referencetmp)) {
2359 $objectemail->origin_references .=
" ".$referencetmp;
2360 $changeonticket_references =
true;
2364 if ($changeonticket_references) {
2365 $operationslog .=
'<br>We complete ticket ID='.$ticketid.
' with property origin_references='.$objectemail->origin_references;
2366 $objectemail->update($user, 1);
2373 if ($projectid > 0) {
2374 $result = $projectstatic->fetch($projectid);
2376 $projectstatic->id = 0;
2378 $projectid = $projectstatic->id;
2380 $projectfoundby =
'trackid ('.$trackid.
')';
2385 if (empty($thirdpartyid)) {
2386 $thirdpartyid = $projectstatic->socid;
2391 if ($contactid > 0) {
2392 $result = $contactstatic->fetch($contactid);
2394 $contactstatic->id = 0;
2396 $contactid = $contactstatic->id;
2398 $contactfoundby =
'trackid ('.$trackid.
')';
2400 if (empty($thirdpartyid)) {
2401 $thirdpartyid = $contactstatic->fk_soc;
2406 if ($thirdpartyid > 0) {
2407 $result = $thirdpartystatic->fetch($thirdpartyid);
2409 $thirdpartystatic->id = 0;
2411 $thirdpartyid = $thirdpartystatic->id;
2413 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2418 if (is_object($objectemail)) {
2423 if (empty($contactid)) {
2424 $result = $contactstatic->fetch(0,
null,
'', $from);
2427 dol_syslog(
"We found a contact with the email ".$from);
2428 $contactid = $contactstatic->id;
2429 $contactfoundby =
'email of contact ('.$from.
')';
2430 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2431 $result = $thirdpartystatic->fetch($contactstatic->socid);
2433 $thirdpartyid = $thirdpartystatic->id;
2434 $thirdpartyfoundby =
'email of contact ('.$from.
')';
2440 if (empty($thirdpartyid)) {
2441 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
2443 dol_syslog(
"We found a thirdparty with the email ".$from);
2444 $thirdpartyid = $thirdpartystatic->id;
2445 $thirdpartyfoundby =
'email ('.$from.
')';
2482 foreach ($this->actions as $operation) {
2483 $errorforthisaction = 0;
2484 $ticketalreadyexists = 0;
2485 if ($errorforactions) {
2488 if (empty($operation[
'status'])) {
2492 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2495 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2496 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2499 $actioncode =
'EMAIL_IN';
2501 if (preg_match(
'/Sent$/', $sourcedir) || preg_match(
'/envoyés$/i', $sourcedir)) {
2502 $actioncode =
'EMAIL';
2505 $arrayofemailtoconsidersender = array_filter(array_map(
'trim', explode(
',',
getDolGlobalString(
'MAIL_FROM_EMAILS_TO_CONSIDER_SENDING'))));
2506 foreach ($arrayofemailtoconsidersender as $emailtoconsidersender) {
2507 if ($emailtoconsidersender ===
'') {
2510 if (preg_match(
'/'.preg_quote($emailtoconsidersender,
'/').
'/', $fromstring)) {
2511 $actioncode =
'EMAIL';
2514 $operationslog .=
'<br>Email will have actioncode='.$actioncode;
2516 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2518 $descriptiontitle = $langs->transnoentitiesnoconv(
"RecordCreatedByEmailCollector", $this->
ref);
2523 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2525 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2527 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2529 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailReply").($langs->trans(
"MailReply") !=
'Reply to' ?
' (Reply to)' :
'').
' : '.
dol_escape_htmltag($replyto));
2532 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2535 if ($operation[
'type'] ==
'ticket') {
2537 $tickettocreate =
new Ticket($this->db);
2538 $errorfetchticket = 0;
2539 $alreadycreated = 0;
2540 if (!empty($objectid) && $objectemail instanceof
Ticket) {
2541 $alreadycreated = $tickettocreate->fetch((
int) $objectid);
2543 if ($alreadycreated == 0 && $ticketid > 0) {
2544 $alreadycreated = $tickettocreate->fetch($ticketid);
2546 if ($alreadycreated == 0 && !empty($trackid)) {
2547 $alreadycreated = $tickettocreate->fetch(0,
'', $trackid);
2549 if ($alreadycreated == 0 && !empty($msgid)) {
2550 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2552 if ($alreadycreated < 0) {
2553 $errorfetchticket++;
2555 if (empty($errorfetchticket)) {
2556 if ($alreadycreated == 0) {
2557 $operationslog .=
'<br>Ticket not found using trackid='.$trackid.
' or msgid='.$msgid;
2558 $ticketalreadyexists = 0;
2560 $operationslog .=
'<br>Ticket already found using trackid='.$trackid.
' or msgid='.$msgid.
", we replace operation 'ticket' with 'recordevent' to add a new message";
2561 $ticketalreadyexists = 1;
2562 $operation[
'type'] =
'recordevent';
2565 $ticketalreadyexists = -1;
2572 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2573 if ($thirdpartyid > 0) {
2575 $idtouseforthirdparty = $thirdpartyid;
2576 $operationslog .=
'<br>We already have found a related thirdparty id, so we bypass the action loadthirdparty and use idtouseforthirdparty='.$idtouseforthirdparty;
2577 } elseif (empty($operation[
'actionparam'])) {
2579 $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;";
2580 $this->errors[] = $this->error;
2582 $actionparam = $operation[
'actionparam'];
2583 $idtouseforthirdparty =
'';
2584 $nametouseforthirdparty =
'';
2585 $emailtouseforthirdparty =
'';
2586 $namealiastouseforthirdparty =
'';
2588 $operationslog .=
'<br>Loop on each property to set into actionparam';
2592 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2596 $regforregex = array();
2598 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2599 $sourcefield = $regforregex[1];
2600 $regexstring = $regforregex[2];
2603 if (!empty($sourcefield) && !empty($regexstring)) {
2604 if (strtolower($sourcefield) ==
'body') {
2605 $sourcestring = $messagetext;
2606 } elseif (strtolower($sourcefield) ==
'subject') {
2607 $sourcestring = $subject;
2608 } elseif (strtolower($sourcefield) ==
'header') {
2609 $sourcestring = $header;
2612 if ($sourcestring) {
2613 $regforval = array();
2614 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2616 if ($propertytooverwrite ==
'id') {
2617 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2619 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2620 } elseif ($propertytooverwrite ==
'email') {
2621 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2623 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2624 } elseif ($propertytooverwrite ==
'name') {
2625 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2627 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2628 } elseif ($propertytooverwrite ==
'name_alias') {
2629 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2631 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2633 $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';
2637 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2638 $idtouseforthirdparty =
null;
2639 $nametouseforthirdparty =
null;
2640 $emailtouseforthirdparty =
null;
2641 $namealiastouseforthirdparty =
null;
2643 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2645 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2651 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2652 $this->errors[] = $this->error;
2654 $operationslog .=
'<br>'.$this->error;
2656 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2660 if ($propertytooverwrite ==
'id') {
2661 $idtouseforthirdparty = $reg[2];
2663 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2664 } elseif ($propertytooverwrite ==
'email') {
2665 $emailtouseforthirdparty = $reg[2];
2667 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2668 } elseif ($propertytooverwrite ==
'name') {
2669 $nametouseforthirdparty = $reg[2];
2671 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2672 } elseif ($propertytooverwrite ==
'name_alias') {
2673 $namealiastouseforthirdparty = $reg[2];
2675 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2679 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2680 $this->errors[] = $this->error;
2685 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2687 $operationslog .=
'<br>We have this initial main data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty.
'.';
2690 $tmpobject->element =
'generic';
2691 $tmpobject->id = $idtouseforthirdparty;
2692 $tmpobject->name = $nametouseforthirdparty;
2693 $tmpobject->name_alias = $namealiastouseforthirdparty;
2694 $tmpobject->email = $emailtouseforthirdparty;
2698 $idtouseforthirdparty = $tmpobject->id;
2699 $nametouseforthirdparty = $tmpobject->name;
2700 $namealiastouseforthirdparty = $tmpobject->name_alias;
2701 $emailtouseforthirdparty = $tmpobject->email;
2703 $operationslog .=
'<br>We try to search existing thirdparty with idtouseforthirdparty='.$idtouseforthirdparty.
' emailtouseforthirdparty='.$emailtouseforthirdparty.
' nametouseforthirdparty='.$nametouseforthirdparty.
' namealiastouseforthirdparty='.$namealiastouseforthirdparty;
2706 $result = $thirdpartystatic->findNearest((
int) $idtouseforthirdparty, (
string) $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', (
string) $emailtouseforthirdparty, (
string) $namealiastouseforthirdparty);
2709 if (
getDolGlobalInt(
'EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE') && $result == -2) {
2710 $idtouseforthirdparty =
getDolGlobalInt(
'EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE');
2712 $thirdpartystatic->fetch($idtouseforthirdparty);
2714 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));
2716 $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);
2719 $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 ?)';
2720 $this->errors[] = $this->error;
2725 if ($operation[
'type'] ==
'loadthirdparty') {
2726 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2729 $resultContact = $contactstatic->findNearest(0,
'',
'',
'', (
string) $emailtouseforthirdparty,
'', 0);
2730 if ($resultContact > 0) {
2731 $contactstatic->fetch($resultContact);
2732 $idtouseforthirdparty = $contactstatic->socid;
2733 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2735 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2738 $langs->load(
"errors");
2739 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', (
string) $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2740 $this->errors[] = $this->error;
2744 $langs->load(
"errors");
2745 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', (
string) $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2746 $this->errors[] = $this->error;
2748 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2749 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
2752 $thirdpartystatic =
new Societe($db);
2753 $thirdpartystatic->name = (string) $nametouseforthirdparty;
2754 if (!empty($namealiastouseforthirdparty)) {
2755 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
2756 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
2759 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'' : $fromtext) : $replytostring);
2761 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ?
'' : $from) : $replyto) : $emailtouseforthirdparty);
2764 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2766 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
2767 $thirdpartystatic->code_client =
'auto';
2769 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
2770 $thirdpartystatic->code_fournisseur =
'auto';
2773 if ($errorforthisaction) {
2776 $result = $thirdpartystatic->create($user);
2779 $this->error = $thirdpartystatic->error;
2780 $this->errors = $thirdpartystatic->errors;
2782 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag((
string) $thirdpartystatic->id);
2786 } elseif ($result > 0) {
2787 dol_syslog(
"One and only one existing third party has been found");
2789 $thirdpartystatic->fetch($result);
2791 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag((
string) $thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name);
2795 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
2796 if (empty($operation[
'actionparam'])) {
2798 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
2799 $this->errors[] = $this->error;
2801 $contact_static =
new Contact($this->db);
2803 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2804 if ($errorforthisaction) {
2807 if (!empty($contact_static->email) && $contact_static->email != $from) {
2808 $from = $contact_static->email;
2811 $from = (string) $from;
2813 $result = $contactstatic->fetch(0,
null,
'', $from);
2816 $this->error =
'Error when getting contact with email ' . $from;
2817 $this->errors[] = $this->error;
2819 } elseif ($result == 0) {
2820 dol_syslog(
"Contact with email " . $from .
" was not found. We try to create it.");
2821 $contactstatic =
new Contact($this->db);
2824 $contactstatic->email = $from;
2825 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($from);
2828 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2830 if ($errorforthisaction) {
2834 if (!empty($contactstatic->country)) {
2835 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2836 $result =
getCountry(
'',
'3', $this->db,
null, 1, $contactstatic->country);
2837 if ($result ==
'NotDefined') {
2839 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
2840 } elseif (!($result > 0)) {
2842 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
2843 $this->errors[] = $this->db->lasterror();
2845 $contactstatic->country_id = $result;
2846 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2848 } elseif (!empty($contactstatic->country_code)) {
2849 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2850 $result =
getCountry($contactstatic->country_code,
'3', $this->db);
2851 if ($result ==
'NotDefined') {
2853 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
2854 } elseif (!($result > 0)) {
2856 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
2857 $this->errors[] = $this->db->lasterror();
2859 $contactstatic->country_id = $result;
2860 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2864 if (!$errorforactions) {
2866 if (!empty($contactstatic->state)) {
2867 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2868 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
2869 if (empty($result)) {
2871 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
2872 } elseif (!($result > 0)) {
2874 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
2875 $this->errors[] = $this->db->lasterror();
2877 $contactstatic->state_id = $result;
2878 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2880 } elseif (!empty($contactstatic->state_code)) {
2881 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2882 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
2883 if (empty($result)) {
2885 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
2886 } elseif (!($result > 0)) {
2888 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
2889 $this->errors[] = $this->db->lasterror();
2891 $contactstatic->state_id = $result;
2892 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2897 if (!$errorforactions) {
2898 $result = $contactstatic->create($user);
2901 $this->error = $contactstatic->error;
2902 $this->errors = $contactstatic->errors;
2904 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag((
string) $contactstatic->id);
2911 } elseif ($operation[
'type'] ==
'recordevent') {
2915 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
2916 if ($alreadycreated == 0) {
2917 $operationslog .=
'<br>We did not find existing actioncomm with msgid='.$msgid;
2919 if ($projectstatic->id > 0) {
2920 if ($projectfoundby) {
2921 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
2924 if ($thirdpartystatic->id > 0) {
2925 if ($thirdpartyfoundby) {
2926 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2929 if ($contactstatic->id > 0) {
2930 if ($contactfoundby) {
2931 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2935 $description = $descriptiontitle;
2941 $descriptionfull = $description;
2943 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2948 $actioncomm->type_code =
'AC_OTH_AUTO';
2949 $actioncomm->code =
'AC_'.$actioncode;
2950 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
2951 $actioncomm->note_private = $descriptionfull;
2952 $actioncomm->fk_project = $projectstatic->id;
2953 $actioncomm->datep = $dateemail;
2954 $actioncomm->datef = $dateemail;
2955 $actioncomm->percentage = -1;
2956 $actioncomm->socid = $thirdpartystatic->id;
2957 $actioncomm->contact_id = $contactstatic->id;
2958 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array());
2959 $actioncomm->authorid = $user->id;
2960 $actioncomm->userownerid = $user->id;
2962 $actioncomm->email_msgid = $msgid;
2963 $actioncomm->email_from = $fromstring;
2964 $actioncomm->email_sender = $sender;
2965 $actioncomm->email_to = $to;
2966 $actioncomm->email_tocc = $sendtocc;
2967 $actioncomm->email_tobcc = $sendtobcc;
2968 $actioncomm->email_subject = $subject;
2969 $actioncomm->errors_to =
'';
2971 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
2972 $actioncomm->fk_element = $fk_element_id;
2973 $actioncomm->elementid = $fk_element_id;
2974 $actioncomm->elementtype = $fk_element_type;
2975 if (is_object($objectemail) && $objectemail->module) {
2976 $actioncomm->elementtype .=
'@'.$objectemail->module;
2983 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2985 if ($errorforthisaction) {
2988 $result = $actioncomm->create($user);
2991 $this->errors = $actioncomm->errors;
2993 if ($fk_element_type ==
"ticket" && is_object($objectemail)) {
2994 if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED || $objectemail->status == Ticket::STATUS_NEED_MORE_INFO || $objectemail->status == Ticket::STATUS_WAITING) {
2995 if ($objectemail->fk_user_assign !=
null) {
2996 $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED);
2998 $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ);
3002 $operationslog .=
'<br>Ticket Re-Opened successfully -> ref='.$objectemail->ref;
3005 $this->error =
'Error while changing the ticket status -> ref='.$objectemail->ref;
3006 $this->errors[] = $this->error;
3009 if (!empty($attachments)) {
3011 $ticket =
new Ticket($this->db);
3012 $ticket->fetch($fk_element_id);
3013 $destdir = $conf->ticket->dir_output.
'/'.$ticket->ref;
3018 foreach ($attachments as $attachment) {
3019 $attachment->save($destdir.
'/');
3022 $this->
getmsg($connection, $imapemail, $destdir);
3027 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag((
string) $actioncomm->id);
3031 $operationslog .=
'<br>An event in actioncomm table already exists for the msgid = '.$msgid.
' so we bypass this action.';
3033 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
3036 foreach ($attachments as $attachment) {
3037 if ($attachment->getName() ===
'undefined') {
3040 $data[$attachment->getName()] = $attachment->getContent();
3044 foreach ($pj as $key => $val) {
3045 $data[$val[
'filename']] =
getFileData($imapemail, (
string) $val[
'pos'], $val[
'type'], $connection);
3048 if (count($data) > 0) {
3049 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($from).
"%'";
3050 $resql = $this->db->query($sql);
3051 if ($this->db->num_rows($resql) == 0) {
3052 $this->errors[] =
"User Not allowed to add documents ({$from})";
3054 $arrayobject = array(
3055 'propale' => array(
'table' =>
'propal',
3056 'fields' => array(
'ref'),
3057 'class' =>
'comm/propal/class/propal.class.php',
3058 'object' =>
'Propal'),
3059 'holiday' => array(
'table' =>
'holiday',
3060 'fields' => array(
'ref'),
3061 'class' =>
'holiday/class/holiday.class.php',
3062 'object' =>
'Holiday'),
3063 'expensereport' => array(
'table' =>
'expensereport',
3064 'fields' => array(
'ref'),
3065 'class' =>
'expensereport/class/expensereport.class.php',
3066 'object' =>
'ExpenseReport'),
3067 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
3068 'fields' => array(
'ref'),
3069 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
3070 'object' =>
'RecruitmentJobPosition'),
3071 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
3072 'fields' => array(
'ref'),
3073 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
3074 'object' =>
'RecruitmentCandidature'),
3075 'societe' => array(
'table' =>
'societe',
3076 'fields' => array(
'code_client',
'code_fournisseur'),
3077 'class' =>
'societe/class/societe.class.php',
3078 'object' =>
'Societe'),
3079 'commande' => array(
'table' =>
'commande',
3080 'fields' => array(
'ref'),
3081 'class' =>
'commande/class/commande.class.php',
3082 'object' =>
'Commande'),
3083 'expedition' => array(
'table' =>
'expedition',
3084 'fields' => array(
'ref'),
3085 'class' =>
'expedition/class/expedition.class.php',
3086 'object' =>
'Expedition'),
3087 'contract' => array(
'table' =>
'contrat',
3088 'fields' => array(
'ref'),
3089 'class' =>
'contrat/class/contrat.class.php',
3090 'object' =>
'Contrat'),
3091 'fichinter' => array(
'table' =>
'fichinter',
3092 'fields' => array(
'ref'),
3093 'class' =>
'fichinter/class/fichinter.class.php',
3094 'object' =>
'Fichinter'),
3095 'ticket' => array(
'table' =>
'ticket',
3096 'fields' => array(
'ref'),
3097 'class' =>
'ticket/class/ticket.class.php',
3098 'object' =>
'Ticket'),
3099 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
3100 'fields' => array(
'ref'),
3101 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
3102 'object' =>
'KnowledgeRecord'),
3103 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
3104 'fields' => array(
'ref'),
3105 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
3106 'object' =>
'SupplierProposal'),
3107 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
3108 'fields' => array(
'ref',
'ref_supplier'),
3109 'class' =>
'fourn/class/fournisseur.commande.class.php',
3110 'object' =>
'SupplierProposal'),
3111 'facture' => array(
'table' =>
'facture',
3112 'fields' => array(
'ref'),
3113 'class' =>
'compta/facture/class/facture.class.php',
3114 'object' =>
'Facture'),
3115 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
3116 'fields' => array(
'ref',
'ref_client'),
3117 'class' =>
'fourn/class/fournisseur.facture.class.php',
3118 'object' =>
'FactureFournisseur'),
3119 'produit' => array(
'table' =>
'product',
3120 'fields' => array(
'ref'),
3121 'class' =>
'product/class/product.class.php',
3122 'object' =>
'Product'),
3123 'productlot' => array(
'table' =>
'product_lot',
3124 'fields' => array(
'batch'),
3125 'class' =>
'product/stock/class/productlot.class.php',
3126 'object' =>
'Productlot'),
3127 'projet' => array(
'table' =>
'projet',
3128 'fields' => array(
'ref'),
3129 'class' =>
'projet/class/projet.class.php',
3130 'object' =>
'Project'),
3131 'projet_task' => array(
'table' =>
'projet_task',
3132 'fields' => array(
'ref'),
3133 'class' =>
'projet/class/task.class.php',
3134 'object' =>
'Task'),
3135 'ressource' => array(
'table' =>
'resource',
3136 'fields' => array(
'ref'),
3137 'class' =>
'ressource/class/dolressource.class.php',
3138 'object' =>
'Dolresource'),
3139 'bom' => array(
'table' =>
'bom_bom',
3140 'fields' => array(
'ref'),
3141 'class' =>
'bom/class/bom.class.php',
3143 'mrp' => array(
'table' =>
'mrp_mo',
3144 'fields' => array(
'ref'),
3145 'class' =>
'mrp/class/mo.class.php',
3149 if (!is_object($hookmanager)) {
3150 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3153 $hookmanager->initHooks(array(
'emailcolector',
'emailcollector'));
3154 $parameters = array(
'arrayobject' => $arrayobject);
3155 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
3157 $arrayobject = $hookmanager->resArray;
3160 $resultobj = array();
3162 foreach ($arrayobject as $key => $objectdesc) {
3163 $sql =
'SELECT DISTINCT t.rowid ';
3164 $sql .=
' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc[
'table']) .
' AS t';
3166 foreach ($objectdesc[
'fields'] as $field) {
3167 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $this->db->sanitize($field) .
", '%') AND t." . $this->db->sanitize($field) .
" <> '') OR ";
3169 $sql = substr($sql, 0, -4);
3171 $ressqlobj = $this->db->query($sql);
3173 while ($obj = $this->db->fetch_object($ressqlobj)) {
3174 $resultobj[$key][] = $obj->rowid;
3179 foreach ($resultobj as $mod => $ids) {
3180 $moddesc = $arrayobject[$mod];
3181 $elementpath = $mod;
3183 $objectmanaged =
new $moddesc[
'object']($this->db);
3184 '@phan-var-force CommonObject $objectmanaged';
3185 foreach ($ids as $val) {
3186 $res = $objectmanaged->fetch($val);
3188 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
3189 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
3191 $this->errors[] =
'object not found';
3195 foreach ($dirs as $target) {
3196 $prefix = $this->actions[$this->id][
'actionparam'];
3197 foreach ($data as $filename => $content) {
3198 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
3200 $this->errors[] =
'Doc not saved';
3205 $operationslog .=
'<br>Save attachment files on disk';
3207 $this->errors[] =
'no joined piece';
3209 $operationslog .=
'<br>No joinded files';
3211 } elseif ($operation[
'type'] ==
'project') {
3213 $projecttocreate =
new Project($this->db);
3214 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
3215 if ($alreadycreated == 0) {
3216 if ($thirdpartystatic->id > 0) {
3217 $projecttocreate->socid = $thirdpartystatic->id;
3218 if ($thirdpartyfoundby) {
3219 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3222 if ($contactstatic->id > 0) {
3223 $projecttocreate->contact_id = $contactstatic->id;
3224 if ($contactfoundby) {
3225 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3229 $description = $descriptiontitle;
3235 $descriptionfull = $description;
3237 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3241 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
3242 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
3244 $projecttocreate->title = $subject;
3245 $projecttocreate->date_start = $dateemail;
3246 $projecttocreate->date_end = 0;
3247 $projecttocreate->opp_status = $id_opp_status;
3248 $projecttocreate->opp_percent = $percent_opp_status;
3250 $projecttocreate->note_private = $descriptionfull;
3251 $projecttocreate->entity = $conf->entity;
3253 $projecttocreate->email_date = $dateemail;
3254 $projecttocreate->email_msgid = $msgid;
3255 $projecttocreate->email_from = $fromstring;
3256 $projecttocreate->email_sender = $sender;
3257 $projecttocreate->email_to = $to;
3258 $projecttocreate->email_tocc = $sendtocc;
3259 $projecttocreate->email_tobcc = $sendtobcc;
3260 $projecttocreate->email_subject = $subject;
3261 $projecttocreate->errors_to =
'';
3263 $savesocid = $projecttocreate->socid;
3267 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3271 if (empty($projecttocreate->ref)) {
3280 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3281 foreach ($dirmodels as $reldir) {
3282 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
3283 if (file_exists($file)) {
3284 $classname = $modele;
3289 if ($classname !==
'') {
3290 if ($savesocid > 0) {
3291 if ($savesocid != $projecttocreate->socid) {
3293 setEventMessages(
'You loaded a thirdparty (id='.$savesocid.
') and you force another thirdparty id (id='.$projecttocreate->socid.
') by setting socid in operation with a different value',
null,
'errors');
3296 if ($projecttocreate->socid > 0) {
3297 $thirdpartystatic->fetch($projecttocreate->socid);
3301 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
3302 $modModuleToUseForNextValue =
new $classname();
3303 '@phan-var-force ModeleNumRefProjects $modModuleToUseForNextValue';
3304 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
3306 $projecttocreate->ref = $defaultref;
3310 if ($errorforthisaction) {
3313 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
3315 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3317 $operationslog .=
'<br>'.$this->error;
3320 $result = $projecttocreate->create($user);
3323 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
3324 $this->errors = $projecttocreate->errors;
3326 $operationslog .=
'<br>'.$this->error;
3329 $destdir = $conf->project->dir_output.
'/'.$projecttocreate->ref;
3334 foreach ($attachments as $attachment) {
3336 $typeattachment = (string) $attachment->getDisposition();
3337 $filename = $attachment->getFilename();
3338 $content = $attachment->getContent();
3342 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3344 $this->errors = array_merge($this->errors, [$this->error]);
3349 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3351 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3359 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3361 } elseif ($operation[
'type'] ==
'ticket') {
3363 $tickettocreate =
new Ticket($this->db);
3364 if ($ticketalreadyexists == 0) {
3365 if ($thirdpartystatic->id > 0) {
3366 $tickettocreate->socid = $thirdpartystatic->id;
3367 $tickettocreate->fk_soc = $thirdpartystatic->id;
3368 if ($thirdpartyfoundby) {
3369 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3372 if ($contactstatic->id > 0) {
3373 $tickettocreate->contact_id = $contactstatic->id;
3374 if ($contactfoundby) {
3375 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3379 $description = $descriptiontitle;
3385 $descriptionfull = $description;
3387 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3391 $tickettocreate->subject = $subject;
3392 $tickettocreate->message = $description;
3394 $tickettocreate->category_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1)));
3395 $tickettocreate->severity_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1)));
3396 $tickettocreate->origin_email = $from;
3397 $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto :
null);
3398 $tickettocreate->origin_references = (!empty($headers[
'References']) ? $headers[
'References'] :
null);
3399 $tickettocreate->fk_user_create = $user->id;
3400 $tickettocreate->datec =
dol_now();
3401 $tickettocreate->fk_project = $projectstatic->id;
3402 $tickettocreate->notify_tiers_at_create =
getDolGlobalInt(
'TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3403 $tickettocreate->note_private = $descriptionfull;
3404 $tickettocreate->entity = $conf->entity;
3406 $tickettocreate->email_date = $dateemail;
3407 $tickettocreate->email_msgid = $msgid;
3408 $tickettocreate->email_from = $fromstring;
3409 $tickettocreate->email_sender = $sender;
3410 $tickettocreate->email_to = $to;
3411 $tickettocreate->email_tocc = $sendtocc;
3412 $tickettocreate->email_tobcc = $sendtobcc;
3413 $tickettocreate->email_subject = $subject;
3414 $tickettocreate->errors_to =
'';
3418 $savesocid = $tickettocreate->socid;
3422 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3424 $modele =
'UNDEFINED';
3426 if (empty($tickettocreate->ref)) {
3435 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3436 foreach ($dirmodels as $reldir) {
3437 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3438 if (file_exists($file)) {
3439 $classname = $modele;
3444 if ($classname !==
'') {
3445 if ($savesocid > 0) {
3446 if ($savesocid != $tickettocreate->socid) {
3448 setEventMessages(
'You loaded a thirdparty (id='.$savesocid.
') and you force another thirdparty id (id='.$tickettocreate->socid.
') by setting socid in operation with a different value',
null,
'errors');
3451 if ($tickettocreate->socid > 0) {
3452 $thirdpartystatic->fetch($tickettocreate->socid);
3457 $modModuleToUseForNextValue =
new $classname();
3458 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3459 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3461 $tickettocreate->ref = $defaultref;
3464 if ($errorforthisaction) {
3467 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3469 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3472 $tickettocreate->context[
'actionmsg2'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3473 $tickettocreate->context[
'actionmsg'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3477 $sender_contact =
new Contact($this->db);
3478 $sender_contact->fetch(0,
null,
'', $from);
3479 if (!empty($sender_contact->id)) {
3480 $tickettocreate->context[
'contact_id'] = $sender_contact->id;
3483 $result = $tickettocreate->create($user);
3486 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3487 $this->errors = $tickettocreate->errors;
3490 $destdir = $conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3495 foreach ($attachments as $attachment) {
3497 $typeattachment = (string) $attachment->getDisposition();
3498 $filename = $attachment->getName();
3499 $content = $attachment->getContent();
3503 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3505 $this->errors = array_merge($this->errors, [$this->error]);
3510 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3512 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3521 $operationslog .=
'<br>Ticket already exists, so we bypass action "ticket"';
3523 } elseif ($operation[
'type'] ==
'candidature') {
3527 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3528 if ($alreadycreated == 0) {
3529 $description = $descriptiontitle;
3535 $descriptionfull = $description;
3536 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3539 $candidaturetocreate->subject = $subject;
3540 $candidaturetocreate->message = $description;
3541 $candidaturetocreate->type_code = 0;
3542 $candidaturetocreate->category_code =
null;
3543 $candidaturetocreate->severity_code =
null;
3544 $candidaturetocreate->email = $from;
3546 $candidaturetocreate->fk_user_creat = $user->id;
3547 $candidaturetocreate->date_creation =
dol_now();
3548 $candidaturetocreate->fk_project = $projectstatic->id;
3549 $candidaturetocreate->description = $description;
3550 $candidaturetocreate->note_private = $descriptionfull;
3551 $candidaturetocreate->entity = $conf->entity;
3552 $candidaturetocreate->email_msgid = $msgid;
3553 $candidaturetocreate->email_date = $dateemail;
3554 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3559 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3602 if ($errorforthisaction) {
3606 $result = $candidaturetocreate->create($user);
3609 $this->error =
'Failed to create candidature: '.implode(
', ', $candidaturetocreate->errors);
3610 $this->errors = $candidaturetocreate->errors;
3613 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag((
string) $candidaturetocreate->id);
3616 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3619 if (!is_object($hookmanager)) {
3620 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3623 $hookmanager->initHooks(array(
'emailcolector',
'emailcollector'));
3625 $parameters = array(
3626 'connection' => $connection,
3627 'imapemail' => $imapemail,
3628 'overview' => $overview,
3631 'fromtext' => $fromtext,
3633 'actionparam' => $operation[
'actionparam'],
3635 'thirdpartyid' => $thirdpartyid,
3636 'objectid' => $objectid,
3637 'objectemail' => $objectemail,
3639 'messagetext' => $messagetext,
3640 'subject' => $subject,
3641 'header' => $header,
3642 'attachments' => $attachments,
3644 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3647 $errorforthisaction++;
3648 $this->error = $hookmanager->resPrint;
3650 if ($errorforthisaction) {
3652 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3654 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3658 if (!$errorforactions) {
3659 $nbactiondoneforemail++;
3665 if (!$errorforactions) {
3666 if (!empty($targetdir)) {
3669 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3670 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid.
' - '.$imapemail->getHeader()->get(
'subject').
' to '.$targetdir;
3672 $arrayofemailtodelete[$this->
uidAsString($imapemail)] = $imapemail;
3675 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3676 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3678 $arrayofemailtodelete[$imapemail] = $msgid;
3683 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);
3685 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3693 unset($objectemail);
3694 unset($projectstatic);
3695 unset($thirdpartystatic);
3696 unset($contactstatic);
3698 $nbemailprocessed++;
3700 if (!$errorforemail) {
3701 $nbactiondone += $nbactiondoneforemail;
3705 $this->db->commit();
3707 $this->db->rollback();
3711 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3712 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3713 $datelastok = empty($headers[
'Date']) ? false : strtotime($headers[
'Date']);
3719 $this->db->rollback();
3721 }
catch (Throwable $e) {
3725 $this->db->rollback();
3726 }
catch (Throwable $eInner) {
3727 dol_syslog(
"EmailCollector loop catch rollback failed: ".$eInner->getMessage(), LOG_ERR);
3729 dol_syslog(
"EmailCollector loop caught exception on one email, skipping: ".$e->getMessage(), LOG_WARNING);
3730 $operationslog .=
'<br>** Exception while processing email #'.dol_escape_htmltag((
string) $iforemailloop).
' - '.
dol_escape_htmltag($e->getMessage()).
' (skipped)';
3734 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3736 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3738 $langs->load(
"admin");
3739 $output = $langs->trans(
'NoNewEmailToProcess');
3740 $output .=
' (defaultlang='.$langs->defaultlang.
')';
3746 krsort($arrayofemailtodelete, SORT_NUMERIC);
3748 foreach ($arrayofemailtodelete as $imapemailnum => $imapemail) {
3749 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemailnum);
3751 $operationslog .=
"<br> move email ".$imapemailnum.($mode > 0 ?
' (test)' :
'');
3753 if (empty($mode) && empty($error)) {
3754 $tmptargetdir = $targetdir;
3761 $result = $imapemail->move($tmptargetdir,
false);
3764 $operationslog .=
'<br>Exception !!!! '.$e->getMessage();
3766 if (empty($result)) {
3767 dol_syslog(
"Failed to move email into target directory ".$targetdir);
3768 $operationslog .=
'<br>Failed to move email into target directory '.$targetdir;
3774 if (empty($mode) && empty($error)) {
3776 $operationslog .=
"<br>Expunge";
3781 $client->disconnect();
3783 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
3784 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
3786 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid.($mode > 0 ?
' (test)' :
'');
3788 if (empty($mode) && empty($error)) {
3789 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
3792 $this->error = imap_last_error();
3793 $this->errors[] = $this->error;
3795 $operationslog .=
'<br>Error in move '.$this->error;
3802 if (empty($mode) && empty($error)) {
3804 $operationslog .=
"<br>Expunge";
3806 imap_expunge($connection);
3808 imap_close($connection);
3811 $this->datelastresult = $now;
3812 $this->lastresult = $output;
3814 $this->debuginfo .=
'IMAP search array used : '.$search;
3816 $this->debuginfo .=
'IMAP search string used : '.$search;
3819 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
3821 if ($operationslog) {
3822 $this->debuginfo .= $operationslog;
3825 if (empty($error) && empty($mode)) {
3826 $this->datelastok = $datelastok;
3829 if (!empty($this->errors)) {
3830 $this->lastresult .=
"<br>".implode(
"<br>", $this->errors);
3832 $this->codelastresult = ($error ?
'KO' :
'OK');
3838 dol_syslog(
"EmailCollector::doCollectOneCollector end error=".$error, LOG_INFO);
3840 return $error ? -1 : 1;
3855 private function getmsg($mbox, $mid, $destdir =
''): int
3859 global $charset, $htmlmsg, $plainmsg, $attachments;
3860 $htmlmsg = $plainmsg = $charset =
'';
3861 $attachments = array();
3868 $s = imap_fetchstructure($mbox, $mid, FT_UID);
3870 $this->errors = array_merge($this->errors, [imap_last_error()]);
3874 if (empty($s->parts)) {
3876 $this->
getpart($mbox, $mid, $s,
'0');
3879 foreach ($s->parts as $partno0 => $p) {
3880 $this->
getpart($mbox, $mid, $p, (
string) ($partno0 + 1), $destdir);
3913 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
3916 global $htmlmsg, $plainmsg, $charset, $attachments;
3920 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
3921 imap_body($mbox, $mid, FT_UID);
3923 if ($p->encoding == 4) {
3924 $data = quoted_printable_decode($data);
3925 } elseif ($p->encoding == 3) {
3926 $data = base64_decode($data);
3932 if ($p->parameters) {
3933 foreach ($p->parameters as $x) {
3934 $params[strtolower($x->attribute)] = $x->value;
3937 if (!empty($p->dparameters)) {
3938 foreach ($p->dparameters as $x) {
3939 $params[strtolower($x->attribute)] = $x->value;
3942 '@phan-var-force array{filename?:string,name?:string,charset?:string} $params';
3947 if (!empty($params[
'filename']) || !empty($params[
'name'])) {
3949 $filename = $params[
'filename'] ?? $params[
'name'];
3951 $attachments[$filename] = $data;
3953 if (strlen($destdir)) {
3954 if (substr($destdir, -1) !=
'/') {
3959 $file_name_complete = $filename;
3960 $destination = $destdir.$file_name_complete;
3963 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
3966 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
3969 $file_name_original = $file_name;
3978 while (file_exists($destdir.$file_name.
".".$extension)) {
3979 $file_name = $file_name_original .
' (' . $num .
')';
3980 $file_name_complete = $file_name .
"." . $extension;
3981 $destination = $destdir.$file_name_complete;
3987 file_put_contents($destination, $data);
3993 if ($p->type == 0 && $data) {
3994 if (!empty($params[
'charset'])) {
3999 if (strtolower($p->subtype) ==
'plain') {
4000 $plainmsg .= trim($data).
"\n\n";
4002 $htmlmsg .= $data.
"<br><br>";
4004 $charset = $params[
'charset'];
4005 } elseif ($p->type == 2 && $data) {
4011 if (!empty($params[
'charset'])) {
4014 $plainmsg .= $data.
"\n\n";
4018 if (!empty($p->parts)) {
4019 foreach ($p->parts as $partno0 => $p2) {
4020 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1), $destdir);
4036 if (!$string || $fromEncoding == $toEncoding) {
4039 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
4040 if (!$convertedString && extension_loaded(
'mbstring')) {
4041 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
4043 if (!$convertedString) {
4044 throw new Exception(
'Mime string encoding conversion failed');
4046 return $convertedString;
4065 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
4066 $elements = imap_mime_header_decode($subject);
4068 if (!empty($elements)) {
4069 $num = count($elements);
4070 for ($i = 0; $i < $num; $i++) {
4071 $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));
4072 $newstring .= $stringinutf8;
4074 $subject = $newstring;
4076 } elseif (!function_exists(
'mb_decode_mimeheader')) {
4077 $subject = mb_decode_mimeheader($subject);
4078 } elseif (function_exists(
'iconv_mime_decode')) {
4079 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
4095 require_once DOL_DOCUMENT_ROOT .
'/core/lib/images.lib.php';
4098 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
4099 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
4100 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
4101 $maxheightmini = $tmparraysize[
'maxheightmini'];
4102 $quality = $tmparraysize[
'quality'];
4104 file_put_contents($destdir.
'/'.$filename, $content);
4109 vignette($destdir.
'/'.$filename, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
4111 vignette($destdir.
'/'.$filename, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
4125 if (is_object($imapemail)) {
4126 return $imapemail->getAttributes()[
"uid"];
4128 return (
string) $imapemail;