64 public $element =
'emailcollector';
69 public $table_element =
'emailcollector_emailcollector';
74 public $picto =
'email';
79 public $fk_element =
'fk_emailcollector';
84 protected $childtables = array();
89 protected $childtablesoncascade = array(
'emailcollector_emailcollectorfilter',
'emailcollector_emailcollectoraction');
115 public $fields = array(
116 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'visible' => -2,
'enabled' => 1,
'position' => 1,
'notnull' => 1,
'index' => 1),
117 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'enabled' => 1,
'visible' => 0,
'default' =>
'1',
'notnull' => 1,
'index' => 1,
'position' => 20),
118 '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'),
119 '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'),
120 'description' => array(
'type' =>
'text',
'label' =>
'Description',
'visible' => -1,
'enabled' => 1,
'position' => 60,
'notnull' => -1,
'cssview' =>
'small',
'csslist' =>
'small tdoverflowmax200'),
121 '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'),
122 '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'),
123 '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'),
124 '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'),
125 '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'),
126 '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' =>
''),
127 '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'),
128 'password' => array(
'type' =>
'password',
'label' =>
'Password',
'visible' => -1,
'enabled' =>
"1",
'position' => 103,
'notnull' => -1,
'comment' =>
"IMAP password",
'help' =>
'WithGMailYouCanCreateADedicatedPassword'),
129 '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'),
130 '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, ...'),
131 'target_directory' => array(
'type' =>
'varchar(255)',
'label' =>
'MailboxTargetDirectory',
'visible' => 1,
'enabled' => 1,
'position' => 110,
'notnull' => 0,
'csslist' =>
'tdoverflowmax100',
'help' =>
"EmailCollectorTargetDir"),
132 'maxemailpercollect' => array(
'type' =>
'integer',
'label' =>
'MaxEmailCollectPerCollect',
'visible' => -1,
'enabled' => 1,
'position' => 111,
'default' =>
'50'),
133 'datelastresult' => array(
'type' =>
'datetime',
'label' =>
'DateLastCollectResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 121,
'notnull' => -1,
'csslist' =>
'nowraponall'),
134 'codelastresult' => array(
'type' =>
'varchar(16)',
'label' =>
'CodeLastResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 122,
'notnull' => -1,),
135 'lastresult' => array(
'type' =>
'varchar(255)',
'label' =>
'LastResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 123,
'notnull' => -1,
'cssview' =>
'small',
'csslist' =>
'maxwidth250imp'),
136 'datelastok' => array(
'type' =>
'datetime',
'label' =>
'DateLastcollectResultOk',
'visible' => 1,
'enabled' =>
'$action != "create"',
'position' => 125,
'notnull' => -1,
'csslist' =>
'nowraponall'),
137 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'visible' => 0,
'enabled' => 1,
'position' => 61,
'notnull' => -1,),
138 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'visible' => 0,
'enabled' => 1,
'position' => 62,
'notnull' => -1,),
139 'date_creation' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'visible' => -2,
'enabled' => 1,
'position' => 500,
'notnull' => 1,),
140 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModification',
'visible' => -2,
'enabled' => 1,
'position' => 501,
'notnull' => 1,),
142 'fk_user_creat' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'visible' => -2,
'enabled' => 1,
'position' => 510,
'notnull' => 1,),
143 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModif',
'visible' => -2,
'enabled' => 1,
'position' => 511,
'notnull' => -1,),
145 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'visible' => -2,
'enabled' => 1,
'position' => 1000,
'notnull' => -1,),
146 'status' => array(
'type' =>
'integer',
'label' =>
'Status',
'visible' => 1,
'enabled' => 1,
'position' => 1000,
'notnull' => 1,
'default' =>
'0',
'index' => 1,
'arrayofkeyval' => array(0 =>
'Inactive', 1 =>
'Active'))
178 public $fk_user_creat;
183 public $fk_user_modif;
217 public $oauth_service;
221 public $imap_encryption;
229 public $source_directory;
233 public $target_directory;
237 public $maxemailpercollect;
242 public $datelastresult;
247 public $codelastresult;
272 const STATUS_DISABLED = 0;
273 const STATUS_ENABLED = 1;
283 global $conf, $langs;
287 $this->ismultientitymanaged = 1;
288 $this->isextrafieldmanaged = 0;
293 if (!
isModEnabled(
'multicompany') && isset($this->fields[
'entity'])) {
294 $this->fields[
'entity'][
'enabled'] = 0;
298 $oauthservices = array();
300 foreach ($conf->global as $key => $val) {
301 if (!empty($val) && preg_match(
'/^OAUTH_.*_ID$/', $key)) {
302 $key = preg_replace(
'/^OAUTH_/',
'', $key);
303 $key = preg_replace(
'/_ID$/',
'', $key);
304 if (preg_match(
'/^.*-/', $key)) {
305 $name = preg_replace(
'/^.*-/',
'', $key);
307 $name = $langs->trans(
"NoName");
309 $provider = preg_replace(
'/-.*$/',
'', $key);
310 $provider = ucfirst(strtolower($provider));
312 $oauthservices[$key] = $name.
" (".$provider.
")";
316 $this->fields[
'oauth_service'][
'arrayofkeyval'] = $oauthservices;
319 foreach ($this->fields as $key => $val) {
320 if (isset($val[
'enabled']) && empty($val[
'enabled'])) {
321 unset($this->fields[$key]);
326 foreach ($this->fields as $key => $val) {
327 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
328 foreach ($val[
'arrayofkeyval'] as $key2 => $val2) {
329 $this->fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
347 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
348 $langs->load(
"errors");
349 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
353 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
354 $this->password =
dolEncrypt($this->password);
358 $this->password =
dolDecrypt($this->password);
360 if (is_array($this->filters) && count($this->filters)) {
363 foreach ($this->filters as $filter) {
364 $emailcollectorfilter->type = $filter[
'type'];
365 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
366 $emailcollectorfilter->fk_emailcollector = $this->id;
367 $emailcollectorfilter->status = $filter[
'status'];
369 $emailcollectorfilter->create($user);
373 if (is_array($this->actions) && count($this->actions)) {
376 foreach ($this->actions as $operation) {
377 $emailcollectoroperation->type = $operation[
'type'];
378 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
379 $emailcollectoroperation->fk_emailcollector = $this->id;
380 $emailcollectoroperation->status = $operation[
'status'];
381 $emailcollectoroperation->position = $operation[
'position'];
383 $emailcollectoroperation->create($user);
399 global $langs, $extrafields;
420 unset(
$object->codelastresult);
421 unset(
$object->datelastresult);
426 $object->ref =
"copy_of_".$object->ref;
429 $object->host =
'imap.example.com';
432 if (is_array(
$object->array_options) && count(
$object->array_options) > 0) {
433 $extrafields->fetch_name_optionals_label($this->table_element);
434 foreach (
$object->array_options as $key => $option) {
435 $shortkey = preg_replace(
'/options_/',
'', $key);
436 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
437 unset(
$object->array_options[$key]);
443 $object->context[
'createfromclone'] =
'createfromclone';
444 $result =
$object->create($user);
450 unset(
$object->context[
'createfromclone']);
457 $this->db->rollback();
469 public function fetch($id, $ref =
null)
473 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
474 $this->password =
dolDecrypt($this->password);
507 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
511 $sql =
"SELECT s.rowid";
512 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
513 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
515 $sql .=
" AND s.status = 1";
517 $sql .= $this->db->order($sortfield, $sortorder);
522 $offset = $limit * $page;
524 $sql .= $this->db->plimit($limit + 1, $offset);
527 $result = $this->db->query($sql);
529 $num = $this->db->num_rows($result);
532 $obj = $this->db->fetch_object($result);
534 if ($emailcollector_static->fetch($obj->rowid)) {
535 $obj_ret[] = $emailcollector_static;
540 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
541 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
543 if (!count($obj_ret)) {
544 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
562 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
563 $langs->load(
"errors");
564 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
568 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
569 $this->password =
dolEncrypt($this->password);
573 $this->password =
dolDecrypt($this->password);
585 public function delete(
User $user, $notrigger = 0)
600 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
602 global $conf, $langs, $action, $hookmanager;
604 if (!empty($conf->dol_no_mouse_hover)) {
610 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
612 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
614 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
616 if ($option !=
'nolink') {
618 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
619 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
620 $add_save_lastsearch_values = 1;
622 if ($add_save_lastsearch_values) {
623 $url .=
'&save_lastsearch_values=1';
628 if (empty($notooltip)) {
630 $label = $langs->trans(
"ShowEmailCollector");
631 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
633 $linkclose .=
' title="'.dolPrintHTMLForAttribute($label).
'"';
634 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
636 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
639 $linkstart =
'<a href="'.$url.
'"';
640 $linkstart .= $linkclose.
'>';
643 $result .= $linkstart;
645 $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);
647 if ($withpicto != 2) {
648 $result .= $this->ref;
653 $hookmanager->initHooks(array(
'emailcollectordao'));
654 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result);
655 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
657 $result = $hookmanager->resPrint;
659 $result .= $hookmanager->resPrint;
687 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
690 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
691 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
692 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
693 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
696 $statusType =
'status5';
697 if ($status == self::STATUS_ENABLED) {
698 $statusType =
'status4';
701 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
712 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
713 $sql .=
' fk_user_creat, fk_user_modif';
714 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
715 $sql .=
' WHERE t.rowid = '.((int) $id);
716 $result = $this->db->query($sql);
718 if ($this->db->num_rows($result)) {
719 $obj = $this->db->fetch_object($result);
721 $this->
id = $obj->rowid;
723 $this->user_creation_id = $obj->fk_user_creat;
724 $this->user_modification_id = $obj->fk_user_modif;
725 $this->date_creation = $this->db->jdate($obj->datec);
726 $this->date_modification = empty($obj->datem) ?
'' : $this->db->jdate($obj->datem);
729 $this->db->free($result);
743 $this->host =
'localhost';
744 $this->login =
'alogin';
757 $this->filters = array();
759 $sql =
'SELECT rowid, type, rulevalue, status';
760 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
761 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
764 $resql = $this->db->query($sql);
766 $num = $this->db->num_rows($resql);
769 $obj = $this->db->fetch_object($resql);
770 $this->filters[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'rulevalue' => $obj->rulevalue,
'status' => $obj->status);
773 $this->db->free($resql);
789 $this->actions = array();
791 $sql =
'SELECT rowid, type, actionparam, status';
792 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
793 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
794 $sql .=
' ORDER BY position';
796 $resql = $this->db->query($sql);
798 $num = $this->db->num_rows($resql);
801 $obj = $this->db->fetch_object($resql);
802 $this->actions[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'actionparam' => $obj->actionparam,
'status' => $obj->status);
805 $this->db->free($resql);
824 $flags =
'/service=imap';
827 } elseif (empty($this->imap_encryption) || ($this->imap_encryption ==
'ssl' &&
getDolGlobalString(
'IMAP_FORCE_NOSSL'))) {
830 $flags .=
'/' . $this->imap_encryption;
833 $flags .=
'/novalidate-cert';
840 if (!empty($this->login) && strpos($this->login,
'/') !=
false) {
841 $partofauth = explode(
'/', $this->login);
842 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
845 $connectstringserver =
'{'.$this->host.
':'.$this->port.$flags.
'}';
847 return $connectstringserver;
858 if (function_exists(
'mb_convert_encoding')) {
860 $str = preg_replace(
"/ /",
"xxxSPACExxx", $str);
861 $str = preg_replace(
"/_/",
"xxxUNDERSCORExxx", $str);
862 $str = preg_replace(
"/\[Gmail\]/",
"xxxGMAILxxx", $str);
864 if ($str = mb_convert_encoding($str,
"UTF-7")) {
866 $str = preg_replace(
"/\+A/",
"&A", $str);
867 $str = preg_replace(
"/xxxUNDERSCORExxx/",
"_", $str);
869 $str = preg_replace(
"/xxxSPACExxx/",
" ", $str);
871 $str = preg_replace(
"/xxxGMAILxxx/",
"[Gmail]", $str);
875 $this->error =
"error: is not possible to encode this string '".$str.
"'";
895 $arrayofcollectors = $this->
fetchAll($user, 1);
897 foreach ($arrayofcollectors as $emailcollector) {
898 $result = $emailcollector->doCollectOneCollector(0);
900 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
902 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
903 if (!empty($emailcollector->errors)) {
904 $this->error .= implode(
'<br>', $emailcollector->errors);
907 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
930 global $conf, $langs;
932 $errorforthisaction = 0;
935 $outputlangs = $langs;
938 $newlang =
GETPOST(
'lang_id',
'aZ09');
941 $newlang = !empty(
$object->thirdparty->default_lang) ?
$object->thirdparty->default_lang : $newlang;
943 if (!empty($newlang)) {
945 $outputlangs->setDefaultLang($newlang);
955 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
958 $tmparray = explode(
'.', $propertytooverwrite);
959 if (count($tmparray) == 2) {
960 $tmpclass = $tmparray[0];
961 $tmpproperty = $tmparray[1];
963 $tmpproperty = $tmparray[0];
965 if ($tmpclass && ($tmpclass !=
$object->element)) {
975 $regforregex = array();
976 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
977 $sourcefield = $regforregex[1];
978 $regexstring = $regforregex[2];
980 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
981 $sourcefield = $regforregex[1];
982 $regexstring = $regforregex[2];
985 if (!empty($sourcefield) && !empty($regexstring)) {
986 if (strtolower($sourcefield) ==
'body') {
987 $sourcestring = $messagetext;
988 } elseif (strtolower($sourcefield) ==
'subject') {
989 $sourcestring = $subject;
990 } elseif (strtolower($sourcefield) ==
'header') {
991 $sourcestring = $header;
995 $regforval = array();
997 if (strtolower($sourcefield) ==
'body') {
998 $regexoptions =
'ms';
1000 if (strtolower($sourcefield) ==
'header') {
1001 $regexoptions =
'm';
1004 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
1006 $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
1007 if (strtolower($sourcefield) ==
'header') {
1008 if (preg_match(
'/^options_/', $tmpproperty)) {
1011 if (property_exists(
$object, $tmpproperty)) {
1018 if (preg_match(
'/^options_/', $tmpproperty)) {
1021 if (property_exists(
$object, $tmpproperty)) {
1029 if (preg_match(
'/^options_/', $tmpproperty)) {
1032 if (property_exists(
$object, $tmpproperty)) {
1040 if (property_exists(
$object, $tmpproperty)) {
1042 $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.';
1044 $tmp[$tmpproperty] =
null;
1045 $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.';
1050 $errorforthisaction++;
1051 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1052 $this->errors[] = $this->error;
1054 $operationslog .=
'<br>'.$this->error;
1056 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1058 if (preg_match(
'/^options_/', $tmpproperty)) {
1059 $valuecurrent =
$object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1061 if (property_exists(
$object, $tmpproperty)) {
1062 $valuecurrent =
$object->$tmpproperty;
1065 $valuecurrent = $tmp[$tmpproperty];
1069 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1070 $valuetouse = $regforregex[2];
1071 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null,
$object);
1073 $matcharray = array();
1074 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1075 if (is_array($matcharray[1])) {
1076 foreach ($matcharray[1] as $keytoreplace) {
1077 if ($keytoreplace) {
1078 if (preg_match(
'/^options_/', $keytoreplace)) {
1079 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1081 if (property_exists(
$object, $keytoreplace)) {
1082 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->$keytoreplace;
1085 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1094 if (preg_match(
'/^options_/', $tmpproperty)) {
1095 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1097 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1099 if (property_exists(
$object, $tmpproperty)) {
1100 $object->$tmpproperty = $valuetouse;
1102 $tmp[$tmpproperty] = $valuetouse;
1105 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1109 $errorforthisaction++;
1110 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1111 $this->errors[] = $this->error;
1116 return $errorforthisaction;
1125 public function doCollectOneCollector($mode = 0)
1127 global $db, $conf, $langs, $user;
1128 global $hookmanager;
1132 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1134 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1137 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1139 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1144 $this->debuginfo =
'';
1148 $searchfilterdoltrackid = 0;
1149 $searchfilternodoltrackid = 0;
1150 $searchfilterisanswer = 0;
1151 $searchfilterisnotanswer = 0;
1152 $searchfilterreplyto = 0;
1153 $searchfilterexcludebodyarray = array();
1154 $searchfilterexcludesubjectarray = array();
1155 $operationslog =
'';
1156 $rulesreplyto = array();
1157 $connectstringsource =
'';
1158 $connectstringtarget =
'';
1159 $connection =
false;
1160 $arrayofemail = array();
1165 if (empty($this->host)) {
1166 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1169 if (empty($this->login)) {
1170 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1173 if (empty($this->source_directory)) {
1174 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1180 $sourcedir = $this->source_directory;
1181 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1186 $sourcedir = $this->source_directory;
1187 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1190 if ($this->acces_type == 1) {
1192 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>';
1194 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1198 $keyforsupportedoauth2array = $this->oauth_service;
1199 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1200 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1202 $keyforprovider =
'';
1204 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', strtoupper($keyforsupportedoauth2array));
1205 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1207 if (!empty($supportedoauth2array)) {
1208 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1209 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1210 $OAUTH_SERVICENAME = $nameofservice;
1212 $OAUTH_SERVICENAME =
'Unknown';
1215 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1217 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1223 $storage =
new DoliStorage($db, $conf, $keyforprovider,
getDolGlobalString($keyforparamtenant));
1226 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1229 if (is_object($tokenobj) && method_exists($tokenobj,
'getEndOfLife')) {
1230 $endOfLife = $tokenobj->getEndOfLife();
1231 if ($endOfLife !== -9002 && $endOfLife !== -9001 && time() > ($endOfLife - 30)) {
1237 if (is_object($tokenobj) && $expire) {
1238 $this->debuginfo .=
'Refresh token '.$OAUTH_SERVICENAME.
'<br>';
1239 $credentials =
new Credentials(
1244 $serviceFactory = new \OAuth\ServiceFactory();
1245 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1249 if (preg_match(
'/^Microsoft/', $OAUTH_SERVICENAME)) {
1251 $tmp = explode(
'-', $OAUTH_SERVICENAME);
1252 $scopes = explode(
',',
getDolGlobalString(
'OAUTH_'.strtoupper($tmp[0]).(empty($tmp[1]) ?
'' :
'-'.$tmp[1]).
'_SCOPE'));
1255 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $scopes);
1257 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
1259 $refreshtoken = $tokenobj->getRefreshToken();
1260 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1263 $tokenobj->setRefreshToken($refreshtoken);
1264 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1266 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1267 if (is_object($tokenobj)) {
1268 $token = $tokenobj->getAccessToken();
1270 $this->error =
"Token not found";
1275 $this->error = $e->getMessage();
1276 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1280 $cm =
new ClientManager();
1281 $client = $cm->make([
1282 'host' => $this->host,
1283 'port' => $this->port,
1284 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1285 'validate_cert' => true,
1286 'protocol' =>
'imap',
1287 'username' => $this->login,
1288 'password' => $token,
1289 'authentication' =>
"oauth",
1293 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1295 $cm =
new ClientManager();
1296 $client = $cm->make([
1297 'host' => $this->host,
1298 'port' => $this->port,
1299 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1300 'validate_cert' => true,
1301 'protocol' =>
'imap',
1302 'username' => $this->login,
1303 'password' => $this->password,
1304 'authentication' =>
"login",
1312 }
catch (ConnectionFailedException $e) {
1313 $this->error = $e->getMessage();
1314 $this->errors[] = $this->error;
1315 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1319 $host = dol_getprefix(
'email');
1322 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1324 if (!function_exists(
'imap_open')) {
1325 $this->error =
'IMAP function not enabled on your PHP';
1331 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1332 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1334 $connectstringsource = $connectstringserver.$sourcedir;
1335 $connectstringtarget = $connectstringserver.$targetdir;
1338 $this->debuginfo .=
'connectstringsource = '.$connectstringsource.
', $connectstringtarget='.$connectstringtarget.
'<br>';
1340 $connection = imap_open($connectstringsource, $this->login, $this->password);
1341 if ($connection ===
false) {
1342 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1345 '@phan-var-force resource|IMAP\Connection $connection';
1348 $host = dol_getprefix(
'email');
1357 $criteria = array();
1360 $criteria = array(array(
'UNDELETED'));
1361 foreach ($this->filters as $rule) {
1362 if (empty($rule[
'status'])) {
1367 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1371 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1374 if ($rule[
'type'] ==
'from') {
1375 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1376 if (count($tmprulevaluearray) >= 2) {
1377 foreach ($tmprulevaluearray as $tmprulevalue) {
1378 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1381 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1384 if ($rule[
'type'] ==
'to') {
1385 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1386 if (count($tmprulevaluearray) >= 2) {
1387 foreach ($tmprulevaluearray as $tmprulevalue) {
1388 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1391 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1394 if ($rule[
'type'] ==
'bcc') {
1395 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1397 if ($rule[
'type'] ==
'cc') {
1398 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1400 if ($rule[
'type'] ==
'subject') {
1403 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1405 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1408 if ($rule[
'type'] ==
'body') {
1411 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1413 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1416 if ($rule[
'type'] ==
'header') {
1417 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1429 if ($rule[
'type'] ==
'seen') {
1430 array_push($criteria, array($not.
"SEEN"));
1432 if ($rule[
'type'] ==
'unseen') {
1433 array_push($criteria, array($not.
"UNSEEN"));
1435 if ($rule[
'type'] ==
'unanswered') {
1436 array_push($criteria, array($not.
"UNANSWERED"));
1438 if ($rule[
'type'] ==
'answered') {
1439 array_push($criteria, array($not.
"ANSWERED"));
1441 if ($rule[
'type'] ==
'smaller') {
1442 array_push($criteria, array($not.
"SMALLER"));
1444 if ($rule[
'type'] ==
'larger') {
1445 array_push($criteria, array($not.
"LARGER"));
1449 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1450 $searchfilterdoltrackid++;
1451 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1453 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1454 $searchfilterdoltrackid++;
1455 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1457 if ($rule[
'type'] ==
'withtrackingid') {
1458 $searchfilterdoltrackid++;
1459 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1461 if ($rule[
'type'] ==
'withouttrackingid') {
1462 $searchfilternodoltrackid++;
1463 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1466 if ($rule[
'type'] ==
'isanswer') {
1467 $searchfilterisanswer++;
1468 $searchhead .=
'/References.*@.*/';
1470 if ($rule[
'type'] ==
'isnotanswer') {
1471 $searchfilterisnotanswer++;
1472 $searchhead .=
'! /References.*@.*/';
1475 if ($rule[
'type'] ==
'replyto') {
1476 $searchfilterreplyto++;
1477 $rulesreplyto[] = $rule[
'rulevalue'];
1478 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1482 if (empty($targetdir) || !
getDolGlobalString(
'EMAILCOLLECTOR_NO_FILTER_ON_DATE_IF_THERE_IS_A_TARGETDIR')) {
1484 if ($this->datelastok) {
1485 $fromdate = $this->datelastok;
1487 if ($fromdate > 0) {
1489 array_push($criteria, array(
"SINCE" =>
date(
'j-M-Y', $fromdate - 86400)));
1494 dol_syslog(
"IMAP search string = ".var_export($criteria,
true));
1495 $search = var_export($criteria,
true);
1498 $search =
'UNDELETED';
1499 foreach ($this->filters as $rule) {
1500 if (empty($rule[
'status'])) {
1508 if (!empty($rule[
'rulevalue']) && strpos($rule[
'rulevalue'],
'!') === 0) {
1512 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1515 if ($rule[
'type'] ==
'from') {
1516 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1517 if (count($tmprulevaluearray) >= 2) {
1518 foreach ($tmprulevaluearray as $tmprulevalue) {
1519 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1522 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1525 if ($rule[
'type'] ==
'to') {
1526 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1527 if (count($tmprulevaluearray) >= 2) {
1528 foreach ($tmprulevaluearray as $tmprulevalue) {
1529 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1532 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1535 if ($rule[
'type'] ==
'bcc') {
1536 $search .= ($search ?
' ' :
'').$not.
'BCC';
1538 if ($rule[
'type'] ==
'cc') {
1539 $search .= ($search ?
' ' :
'').$not.
'CC';
1541 if ($rule[
'type'] ==
'subject') {
1544 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1546 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1549 if ($rule[
'type'] ==
'body') {
1552 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1555 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1558 if ($rule[
'type'] ==
'header') {
1559 $search .= ($search ?
' ' :
'').$not.
'HEADER '.$rule[
'rulevalue'];
1571 if ($rule[
'type'] ==
'seen') {
1572 $search .= ($search ?
' ' :
'').$not.
'SEEN';
1574 if ($rule[
'type'] ==
'unseen') {
1575 $search .= ($search ?
' ' :
'').$not.
'UNSEEN';
1577 if ($rule[
'type'] ==
'unanswered') {
1578 $search .= ($search ?
' ' :
'').$not.
'UNANSWERED';
1580 if ($rule[
'type'] ==
'answered') {
1581 $search .= ($search ?
' ' :
'').$not.
'ANSWERED';
1583 if ($rule[
'type'] ==
'smaller') {
1584 $search .= ($search ?
' ' :
'').$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1586 if ($rule[
'type'] ==
'larger') {
1587 $search .= ($search ?
' ' :
'').$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1591 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1592 $searchfilterdoltrackid++;
1593 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1595 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1596 $searchfilterdoltrackid++;
1597 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1599 if ($rule[
'type'] ==
'withtrackingid') {
1600 $searchfilterdoltrackid++;
1601 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1603 if ($rule[
'type'] ==
'withouttrackingid') {
1604 $searchfilternodoltrackid++;
1605 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1608 if ($rule[
'type'] ==
'isanswer') {
1609 $searchfilterisanswer++;
1610 $searchhead .=
'/References.*@.*/';
1612 if ($rule[
'type'] ==
'isnotanswer') {
1613 $searchfilterisnotanswer++;
1614 $searchhead .=
'! /References.*@.*/';
1617 if ($rule[
'type'] ==
'replyto') {
1618 $searchfilterreplyto++;
1619 $rulesreplyto[] = $rule[
'rulevalue'];
1620 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1624 if (empty($targetdir)) {
1626 if ($this->datelastok) {
1627 $fromdate = $this->datelastok;
1629 if ($fromdate > 0) {
1631 $search .= ($search ?
' ' :
'').
'SINCE '.
date(
'j-M-Y', $fromdate - 86400);
1639 $nbemailprocessed = 0;
1642 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1643 $arrayofemail = array();
1650 $tmpsourcedir = $sourcedir;
1655 $f = $client->getFolders(
false, $tmpsourcedir);
1662 foreach ($f as $candidate) {
1663 if ($candidate instanceof Webklex\PHPIMAP\Folder && $candidate->full_name === $tmpsourcedir) {
1664 $folder = $candidate;
1668 if ($folder instanceof Webklex\PHPIMAP\Folder) {
1669 $Query = $folder->messages()->where($criteria);
1672 $this->error =
"Source directory ".$sourcedir.
" not found";
1673 $this->errors[] = $this->error;
1674 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_WARNING);
1679 $this->error =
"Failed to execute getfolders";
1680 $this->errors[] = $this->error;
1681 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1684 }
catch (InvalidWhereQueryCriteriaException $e) {
1685 $this->error = $e->getMessage();
1686 $this->errors[] = $this->error;
1687 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1690 $this->error = $e->getMessage();
1691 $this->errors[] = $this->error;
1692 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1696 '@phan-var-force Webklex\PHPIMAP\Query\Query $Query';
1699 $Query->leaveUnread();
1701 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1702 dol_syslog(
"EmailCollector::doCollectOneCollector nb arrayofemail ".(is_array($arrayofemail) ? count($arrayofemail) :
'Not array'));
1704 $this->error = $e->getMessage();
1705 $this->errors[] = $this->error;
1706 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1709 } elseif ($connection !==
false) {
1711 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1713 if ($arrayofemail ===
false) {
1715 $mapoferrrors = imap_errors();
1716 if ($mapoferrrors !==
false) {
1718 $this->error =
"Search string not understood - ".implode(
',', $mapoferrrors);
1719 $this->errors[] = $this->error;
1724 $arrayofemailtodelete = array();
1727 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0 && $connection !==
false) {
1744 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1746 $richarrayofemail = array();
1748 foreach ($arrayofemail as $imapemail) {
1749 if ($nbemailprocessed > 1000) {
1755 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1756 $header = $imapemail->getHeader()->raw;
1757 $overview = $imapemail->getAttributes();
1759 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1760 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1763 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1766 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)(\r\n|\s$)/m', $header, $matches);
1767 $headers = array_combine($matches[1], $matches[2]);
1770 $richarrayofemail[] = array(
'imapemail' => $imapemail,
'header' => $header,
'headers' => $headers,
'overview' => $overview,
'date' => strtotime($headers[
'Date']));
1775 $richarrayofemail =
dol_sort_array($richarrayofemail,
'date',
'asc');
1779 foreach ($richarrayofemail as $tmpval) {
1783 $imapemail = $tmpval[
'imapemail'];
1784 $header = $tmpval[
'header'];
1785 $overview = $tmpval[
'overview'];
1786 $headers = $tmpval[
'headers'];
1788 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1789 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1791 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1792 $headers[
'References'] = $headers[
'references'];
1794 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1795 $headers[
'Message-ID'] = $headers[
'message-id'];
1797 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1798 $headers[
'Subject'] = $headers[
'subject'];
1804 $emailto = (string) $overview[
'to'];
1809 $operationslog .=
'<br>** Process email #'.dol_escape_htmltag((
string) $iforemailloop);
1813 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1815 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1817 $operationslog .=
" - ".dol_escape_htmltag((
string) $imapemail);
1818 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1820 $operationslog .=
" - MsgId: ".$msgid;
1821 $operationslog .=
" - Date: ".($headers[
'Date'] ?? $langs->transnoentitiesnoconv(
"NotFound"));
1822 $operationslog .=
" - References: ".dol_escape_htmltag($headers[
'References'] ?? $langs->transnoentitiesnoconv(
"NotFound")).
" - Subject: ".
dol_escape_htmltag($headers[
'Subject']);
1824 dol_syslog(
"-- Process email #".$iforemailloop.
", MsgId: ".$msgid.
", Date: ".($headers[
'Date'] ??
'').
", References: ".($headers[
'References'] ??
'').
", Subject: ".$headers[
'Subject']);
1827 $trackidfoundintorecipienttype =
'';
1828 $trackidfoundintorecipientid = 0;
1833 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)) {
1834 $trackidfoundintorecipienttype = $reg[1];
1835 $trackidfoundintorecipientid = $reg[2];
1836 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1837 $trackidfoundintorecipienttype =
'emailing';
1838 $trackidfoundintorecipientid = $reg[1];
1841 $trackidfoundintomsgidtype =
'';
1842 $trackidfoundintomsgidid = 0;
1847 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)) {
1848 $trackidfoundintomsgidtype = $reg[1];
1849 $trackidfoundintomsgidid = $reg[2];
1850 } elseif (preg_match(
'/(?:[\+\-])emailing-(\w+)@/', $msgid, $reg)) {
1851 $trackidfoundintomsgidtype =
'emailing';
1852 $trackidfoundintomsgidid = $reg[1];
1858 if ($searchfilterdoltrackid > 0) {
1859 $referencesForFilter = $headers[
'References'] ??
'';
1860 if (!empty($headers[
'References']) && !empty($headers[
'In-Reply-To'])) {
1861 $referencesForFilter .=
' ';
1863 $referencesForFilter .= ($headers[
'In-Reply-To'] ??
'');
1865 if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) {
1866 if (empty($referencesForFilter) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $referencesForFilter)) {
1867 $nbemailprocessed++;
1868 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");
1874 if ($searchfilternodoltrackid > 0) {
1875 $referencesForFilter = $headers[
'References'] ??
'';
1876 if (!empty($headers[
'References']) && !empty($headers[
'In-Reply-To'])) {
1877 $referencesForFilter .=
' ';
1879 $referencesForFilter .= ($headers[
'In-Reply-To'] ??
'');
1881 if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($referencesForFilter) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $referencesForFilter))) {
1882 $nbemailprocessed++;
1883 dol_syslog(
" Discarded - Suffix found into email recipient, or Header 'References/In-Reply-To' found and matching signature of application so with a trackid");
1888 if ($searchfilterisanswer > 0) {
1889 $referencesforanswer =
'';
1890 if (!empty($headers[
'References'])) {
1891 $referencesforanswer .= $headers[
'References'].
' ';
1893 if (!empty($headers[
'In-Reply-To'])) {
1894 $referencesforanswer .= $headers[
'In-Reply-To'];
1897 $hasdolibarrreference = 0;
1898 if (!empty($referencesforanswer)) {
1899 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $referencesforanswer)) {
1900 $hasdolibarrreference = 1;
1902 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $referencesforanswer)) {
1903 $hasdolibarrreference = 1;
1909 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
1915 if (!empty($headers[
'In-Reply-To'])) {
1919 if ($hasdolibarrreference) {
1926 $nbemailprocessed++;
1927 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)");
1931 if ($searchfilterisnotanswer > 0) {
1932 if (!empty($headers[
'In-Reply-To'])) {
1936 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
1942 $nbemailprocessed++;
1943 dol_syslog(
" Discarded - Email is an answer");
1948 if ($searchfilterreplyto > 0) {
1949 if (!empty($headers[
'Reply-To'])) {
1951 foreach ($rulesreplyto as $key => $rulereplyto) {
1952 if (preg_match(
'/'.preg_quote($rulereplyto,
'/').
'/', $headers[
'Reply-To'])) {
1957 if (!$isreplytook || $isreplytook != count($rulesreplyto)) {
1958 $nbemailprocessed++;
1959 dol_syslog(
" Discarded - Reply-to does not match");
1967 $thirdpartystatic =
new Societe($this->db);
1968 $contactstatic =
new Contact($this->db);
1969 $projectstatic =
new Project($this->db);
1971 $nbactiondoneforemail = 0;
1973 $errorforactions = 0;
1974 $thirdpartyfoundby =
'';
1975 $contactfoundby =
'';
1976 $projectfoundby =
'';
1977 $ticketfoundby =
'';
1978 $candidaturefoundby =
'';
1982 $dateformated =
dol_print_date($overview[
'date'],
'dayrfc',
'gmt');
1983 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".$dateformated.
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
1988 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);
1998 global $htmlmsg, $plainmsg, $charset, $attachments;
2002 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
2005 $htmlmsg = $plainmsg =
'';
2006 $attachments = array();
2008 if ($imapemail->hasHTMLBody()) {
2009 $htmlmsg = $imapemail->getHTMLBody();
2011 if ($imapemail->hasTextBody() && $imapemail->getTextBody() !=
"\n") {
2012 $plainmsg = $imapemail->getTextBody();
2014 if ($imapemail->hasAttachments()) {
2015 $attachments = $imapemail->getAttachments()->all();
2017 $attachments = array();
2020 $getMsg = $this->
getmsg($connection, $imapemail);
2022 $this->errors = array_merge($this->errors, [$this->error]);
2026 '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments';
2036 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
2037 dol_syslog(
" Discarded - Email body is not valid utf8");
2041 if (!empty($searchfilterexcludebodyarray)) {
2042 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
2043 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
2044 $nbemailprocessed++;
2045 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
2046 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
2088 $replytostring =
'';
2092 $replytostring = !empty($headers[
'Reply-To']) ? $this->
decodeSMTPSubject($headers[
'Reply-To']) :
'';
2099 $tmpdate = $overview[
'date']->toDate();
2100 $tmptimezone = $tmpdate->getTimezone()->getName();
2103 if (preg_match(
'/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) {
2104 if ($reg[1] ==
'+' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2105 $dateemail -= (3600 * (int) $reg[2]);
2106 $dateemail -= (60 * (int) $reg[3]);
2108 if ($reg[1] ==
'-' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2109 $dateemail += (3600 * (int) $reg[2]);
2110 $dateemail += (60 * (int) $reg[3]);
2115 $fromstring = $overview[0]->from;
2116 $replytostring = (!empty($overview[
'in_reply-to']) ? $overview[
'in_reply-to'] : (!empty($headers[
'Reply-To']) ? $headers[
'Reply-To'] :
"")) ;
2118 $sender = !empty($overview[0]->sender) ? $overview[0]->sender :
'';
2119 $to = $overview[0]->to;
2120 $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc :
'';
2121 $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc :
'';
2123 $subject = $overview[0]->subject;
2126 if (!empty($searchfilterexcludesubjectarray)) {
2127 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
2128 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
2129 $nbemailprocessed++;
2130 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
2131 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
2138 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
2140 $fromtext = $reg[1];
2142 $from = $fromstring;
2145 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
2147 $replytotext = $reg[1];
2149 $replyto = $replytostring;
2153 $fk_element_type =
'';
2170 $objectemail =
null;
2173 $arrayofreferences = array();
2174 if (!empty($headers[
'References'])) {
2175 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
2177 if (!in_array(
'<'.$msgid.
'>', $arrayofreferences)) {
2178 $arrayofreferences = array_merge($arrayofreferences, array(
'<'.$msgid.
'>'));
2183 foreach ($arrayofreferences as $reference) {
2185 if (!empty($trackidfoundintorecipienttype)) {
2186 $resultsearchtrackid = -1;
2187 $reg[1] = $trackidfoundintorecipienttype;
2188 $reg[2] = $trackidfoundintorecipientid;
2189 } elseif (!empty($trackidfoundintomsgidtype)) {
2190 $resultsearchtrackid = -1;
2191 $reg[1] = $trackidfoundintomsgidtype;
2192 $reg[2] = $trackidfoundintomsgidid;
2194 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
2195 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2196 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
2200 if (!empty($resultsearchtrackid)) {
2202 $trackid = $reg[1].$reg[2];
2204 $objectid = $reg[2];
2206 if ($reg[1] ==
'thi') {
2207 $objectemail =
new Societe($this->db);
2209 if ($reg[1] ==
'ctc') {
2210 $objectemail =
new Contact($this->db);
2212 if ($reg[1] ==
'inv') {
2213 $objectemail =
new Facture($this->db);
2215 if ($reg[1] ==
'sinv') {
2218 if ($reg[1] ==
'pro') {
2219 $objectemail =
new Propal($this->db);
2221 if ($reg[1] ==
'ord') {
2222 $objectemail =
new Commande($this->db);
2224 if ($reg[1] ==
'shi') {
2227 if ($reg[1] ==
'spro') {
2230 if ($reg[1] ==
'sord') {
2233 if ($reg[1] ==
'rec') {
2234 $objectemail =
new Reception($this->db);
2236 if ($reg[1] ==
'proj') {
2237 $objectemail =
new Project($this->db);
2238 $projectfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2240 if ($reg[1] ==
'tas') {
2241 $objectemail =
new Task($this->db);
2243 if ($reg[1] ==
'con') {
2244 $objectemail =
new Contact($this->db);
2246 if ($reg[1] ==
'use') {
2247 $objectemail =
new User($this->db);
2249 if ($reg[1] ==
'tic') {
2250 $objectemail =
new Ticket($this->db);
2251 $ticketfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2253 if ($reg[1] ==
'recruitmentcandidature') {
2255 $candidaturefoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2257 if ($reg[1] ==
'mem') {
2258 $objectemail =
new Adherent($this->db);
2266 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
2269 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket";
2270 $sql .=
" WHERE email_msgid = '".$this->db->escape($reg[1]).
"' OR origin_references LIKE '%".$this->db->escape($this->db->escapeforlike($reg[1])).
"%'";
2271 $resql = $this->db->query($sql);
2273 $obj = $this->db->fetch_object($resql);
2275 $objectid = $obj->rowid;
2276 $objectemail =
new Ticket($this->db);
2277 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2284 if (!is_object($objectemail) &&
isModEnabled(
'project')) {
2285 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2286 $resql = $this->db->query($sql);
2288 $obj = $this->db->fetch_object($resql);
2290 $objectid = $obj->rowid;
2291 $objectemail =
new Project($this->db);
2292 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2299 if (!is_object($objectemail) &&
isModEnabled(
'recruitment')) {
2300 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2301 $resql = $this->db->query($sql);
2303 $obj = $this->db->fetch_object($resql);
2305 $objectid = $obj->rowid;
2307 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2316 if (is_object($objectemail)) {
2317 $result = $objectemail->fetch($objectid);
2319 $fk_element_id = $objectemail->id;
2320 $fk_element_type = $objectemail->element;
2322 if ($fk_element_type ==
'facture') {
2323 $fk_element_type =
'invoice';
2326 if (get_class($objectemail) !=
'Societe') {
2327 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2329 $thirdpartyid = $objectemail->id;
2332 if (get_class($objectemail) !=
'Contact') {
2333 $contactid = $objectemail->fk_socpeople;
2335 $contactid = $objectemail->id;
2338 if (get_class($objectemail) !=
'Project') {
2339 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2341 $projectid = $objectemail->id;
2344 if ($objectemail instanceof
Ticket) {
2345 $ticketid = $objectemail->id;
2347 $changeonticket_references =
false;
2348 if (empty($trackid)) {
2349 $trackid = $objectemail->track_id;
2351 if (empty($objectemail->origin_references)) {
2352 $objectemail->origin_references = !empty($headers[
'References']) ? $headers[
'References'] :
null;
2353 $changeonticket_references =
true;
2355 foreach ($arrayofreferences as $key => $referencetmp) {
2356 if (!str_contains($objectemail->origin_references, $referencetmp)) {
2357 $objectemail->origin_references .=
" ".$referencetmp;
2358 $changeonticket_references =
true;
2362 if ($changeonticket_references) {
2363 $operationslog .=
'<br>We complete ticket ID='.$ticketid.
' with property origin_references='.$objectemail->origin_references;
2364 $objectemail->update($user, 1);
2371 if ($projectid > 0) {
2372 $result = $projectstatic->fetch($projectid);
2374 $projectstatic->id = 0;
2376 $projectid = $projectstatic->id;
2378 $projectfoundby =
'trackid ('.$trackid.
')';
2380 if (empty($contactid)) {
2381 $contactid = $projectstatic->fk_contact;
2383 if (empty($thirdpartyid)) {
2384 $thirdpartyid = $projectstatic->fk_soc;
2389 if ($contactid > 0) {
2390 $result = $contactstatic->fetch($contactid);
2392 $contactstatic->id = 0;
2394 $contactid = $contactstatic->id;
2396 $contactfoundby =
'trackid ('.$trackid.
')';
2398 if (empty($thirdpartyid)) {
2399 $thirdpartyid = $contactstatic->fk_soc;
2404 if ($thirdpartyid > 0) {
2405 $result = $thirdpartystatic->fetch($thirdpartyid);
2407 $thirdpartystatic->id = 0;
2409 $thirdpartyid = $thirdpartystatic->id;
2411 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2416 if (is_object($objectemail)) {
2421 if (empty($contactid)) {
2422 $result = $contactstatic->fetch(0,
null,
'', $from);
2425 dol_syslog(
"We found a contact with the email ".$from);
2426 $contactid = $contactstatic->id;
2427 $contactfoundby =
'email of contact ('.$from.
')';
2428 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2429 $result = $thirdpartystatic->fetch($contactstatic->socid);
2431 $thirdpartyid = $thirdpartystatic->id;
2432 $thirdpartyfoundby =
'email of contact ('.$from.
')';
2438 if (empty($thirdpartyid)) {
2439 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
2441 dol_syslog(
"We found a thirdparty with the email ".$from);
2442 $thirdpartyid = $thirdpartystatic->id;
2443 $thirdpartyfoundby =
'email ('.$from.
')';
2480 foreach ($this->actions as $operation) {
2481 $errorforthisaction = 0;
2482 $ticketalreadyexists = 0;
2483 if ($errorforactions) {
2486 if (empty($operation[
'status'])) {
2490 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2493 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2494 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2497 $actioncode =
'EMAIL_IN';
2499 if (preg_match(
'/Sent$/', $sourcedir) || preg_match(
'/envoyés$/i', $sourcedir)) {
2500 $actioncode =
'EMAIL';
2503 $arrayofemailtoconsidersender = array_filter(array_map(
'trim', explode(
',',
getDolGlobalString(
'MAIL_FROM_EMAILS_TO_CONSIDER_SENDING'))));
2504 foreach ($arrayofemailtoconsidersender as $emailtoconsidersender) {
2505 if ($emailtoconsidersender ===
'') {
2508 if (preg_match(
'/'.preg_quote($emailtoconsidersender,
'/').
'/', $fromstring)) {
2509 $actioncode =
'EMAIL';
2512 $operationslog .=
'<br>Email will have actioncode='.$actioncode;
2514 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2516 $descriptiontitle = $langs->transnoentitiesnoconv(
"RecordCreatedByEmailCollector", $this->
ref);
2521 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2523 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2525 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2527 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailReply").($langs->trans(
"MailReply") !=
'Reply to' ?
' (Reply to)' :
'').
' : '.
dol_escape_htmltag($replyto));
2530 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2533 if ($operation[
'type'] ==
'ticket') {
2535 $tickettocreate =
new Ticket($this->db);
2536 $errorfetchticket = 0;
2537 $alreadycreated = 0;
2538 if (!empty($objectid) && $objectemail instanceof
Ticket) {
2539 $alreadycreated = $tickettocreate->fetch((
int) $objectid);
2541 if ($alreadycreated == 0 && $ticketid > 0) {
2542 $alreadycreated = $tickettocreate->fetch($ticketid);
2544 if ($alreadycreated == 0 && !empty($trackid)) {
2545 $alreadycreated = $tickettocreate->fetch(0,
'', $trackid);
2547 if ($alreadycreated == 0 && !empty($msgid)) {
2548 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2550 if ($alreadycreated < 0) {
2551 $errorfetchticket++;
2553 if (empty($errorfetchticket)) {
2554 if ($alreadycreated == 0) {
2555 $operationslog .=
'<br>Ticket not found using trackid='.$trackid.
' or msgid='.$msgid;
2556 $ticketalreadyexists = 0;
2558 $operationslog .=
'<br>Ticket already found using trackid='.$trackid.
' or msgid='.$msgid.
", we replace operation 'ticket' with 'recordevent' to add a new message";
2559 $ticketalreadyexists = 1;
2560 $operation[
'type'] =
'recordevent';
2563 $ticketalreadyexists = -1;
2570 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2571 if ($thirdpartyid > 0) {
2573 $idtouseforthirdparty = $thirdpartyid;
2574 $operationslog .=
'<br>We already have found a related thirdparty id, so we bypass the action loadthirdparty and use idtouseforthirdparty='.$idtouseforthirdparty;
2575 } elseif (empty($operation[
'actionparam'])) {
2577 $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;";
2578 $this->errors[] = $this->error;
2580 $actionparam = $operation[
'actionparam'];
2581 $idtouseforthirdparty =
'';
2582 $nametouseforthirdparty =
'';
2583 $emailtouseforthirdparty =
'';
2584 $namealiastouseforthirdparty =
'';
2586 $operationslog .=
'<br>Loop on each property to set into actionparam';
2590 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2594 $regforregex = array();
2596 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2597 $sourcefield = $regforregex[1];
2598 $regexstring = $regforregex[2];
2601 if (!empty($sourcefield) && !empty($regexstring)) {
2602 if (strtolower($sourcefield) ==
'body') {
2603 $sourcestring = $messagetext;
2604 } elseif (strtolower($sourcefield) ==
'subject') {
2605 $sourcestring = $subject;
2606 } elseif (strtolower($sourcefield) ==
'header') {
2607 $sourcestring = $header;
2610 if ($sourcestring) {
2611 $regforval = array();
2612 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2614 if ($propertytooverwrite ==
'id') {
2615 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2617 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2618 } elseif ($propertytooverwrite ==
'email') {
2619 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2621 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2622 } elseif ($propertytooverwrite ==
'name') {
2623 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2625 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2626 } elseif ($propertytooverwrite ==
'name_alias') {
2627 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2629 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2631 $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';
2635 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2636 $idtouseforthirdparty =
null;
2637 $nametouseforthirdparty =
null;
2638 $emailtouseforthirdparty =
null;
2639 $namealiastouseforthirdparty =
null;
2641 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2643 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2649 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2650 $this->errors[] = $this->error;
2652 $operationslog .=
'<br>'.$this->error;
2654 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2658 if ($propertytooverwrite ==
'id') {
2659 $idtouseforthirdparty = $reg[2];
2661 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2662 } elseif ($propertytooverwrite ==
'email') {
2663 $emailtouseforthirdparty = $reg[2];
2665 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2666 } elseif ($propertytooverwrite ==
'name') {
2667 $nametouseforthirdparty = $reg[2];
2669 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2670 } elseif ($propertytooverwrite ==
'name_alias') {
2671 $namealiastouseforthirdparty = $reg[2];
2673 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2677 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2678 $this->errors[] = $this->error;
2683 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2685 $operationslog .=
'<br>We have this initial main data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty.
'.';
2688 $tmpobject->element =
'generic';
2689 $tmpobject->id = $idtouseforthirdparty;
2690 $tmpobject->name = $nametouseforthirdparty;
2691 $tmpobject->name_alias = $namealiastouseforthirdparty;
2692 $tmpobject->email = $emailtouseforthirdparty;
2696 $idtouseforthirdparty = $tmpobject->id;
2697 $nametouseforthirdparty = $tmpobject->name;
2698 $namealiastouseforthirdparty = $tmpobject->name_alias;
2699 $emailtouseforthirdparty = $tmpobject->email;
2701 $operationslog .=
'<br>We try to search existing thirdparty with idtouseforthirdparty='.$idtouseforthirdparty.
' emailtouseforthirdparty='.$emailtouseforthirdparty.
' nametouseforthirdparty='.$nametouseforthirdparty.
' namealiastouseforthirdparty='.$namealiastouseforthirdparty;
2704 $result = $thirdpartystatic->findNearest((
int) $idtouseforthirdparty, (
string) $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', (
string) $emailtouseforthirdparty, (
string) $namealiastouseforthirdparty);
2707 if (
getDolGlobalInt(
'EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE') && $result == -2) {
2708 $idtouseforthirdparty =
getDolGlobalInt(
'EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE');
2710 $thirdpartystatic->fetch($idtouseforthirdparty);
2712 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));
2714 $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);
2717 $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 ?)';
2718 $this->errors[] = $this->error;
2723 if ($operation[
'type'] ==
'loadthirdparty') {
2724 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2727 $resultContact = $contactstatic->findNearest(0,
'',
'',
'', (
string) $emailtouseforthirdparty,
'', 0);
2728 if ($resultContact > 0) {
2729 $contactstatic->fetch($resultContact);
2730 $idtouseforthirdparty = $contactstatic->socid;
2731 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2733 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2736 $langs->load(
"errors");
2737 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', (
string) $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2738 $this->errors[] = $this->error;
2742 $langs->load(
"errors");
2743 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', (
string) $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2744 $this->errors[] = $this->error;
2746 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2747 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
2750 $thirdpartystatic =
new Societe($db);
2751 $thirdpartystatic->name = (string) $nametouseforthirdparty;
2752 if (!empty($namealiastouseforthirdparty)) {
2753 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
2754 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
2757 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'' : $fromtext) : $replytostring);
2759 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ?
'' : $from) : $replyto) : $emailtouseforthirdparty);
2762 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2764 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
2765 $thirdpartystatic->code_client =
'auto';
2767 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
2768 $thirdpartystatic->code_fournisseur =
'auto';
2771 if ($errorforthisaction) {
2774 $result = $thirdpartystatic->create($user);
2777 $this->error = $thirdpartystatic->error;
2778 $this->errors = $thirdpartystatic->errors;
2780 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag((
string) $thirdpartystatic->id);
2784 } elseif ($result > 0) {
2785 dol_syslog(
"One and only one existing third party has been found");
2787 $thirdpartystatic->fetch($result);
2789 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag((
string) $thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name);
2793 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
2794 if (empty($operation[
'actionparam'])) {
2796 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
2797 $this->errors[] = $this->error;
2799 $contact_static =
new Contact($this->db);
2801 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2802 if ($errorforthisaction) {
2805 if (!empty($contact_static->email) && $contact_static->email != $from) {
2806 $from = $contact_static->email;
2809 $from = (string) $from;
2811 $result = $contactstatic->fetch(0,
null,
'', $from);
2814 $this->error =
'Error when getting contact with email ' . $from;
2815 $this->errors[] = $this->error;
2817 } elseif ($result == 0) {
2818 dol_syslog(
"Contact with email " . $from .
" was not found. We try to create it.");
2819 $contactstatic =
new Contact($this->db);
2822 $contactstatic->email = $from;
2823 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($from);
2826 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2828 if ($errorforthisaction) {
2832 if (!empty($contactstatic->country)) {
2833 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2834 $result =
getCountry(
'',
'3', $this->db,
null, 1, $contactstatic->country);
2835 if ($result ==
'NotDefined') {
2837 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
2838 } elseif (!($result > 0)) {
2840 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
2841 $this->errors[] = $this->db->lasterror();
2843 $contactstatic->country_id = $result;
2844 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2846 } elseif (!empty($contactstatic->country_code)) {
2847 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2848 $result =
getCountry($contactstatic->country_code,
'3', $this->db);
2849 if ($result ==
'NotDefined') {
2851 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
2852 } elseif (!($result > 0)) {
2854 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
2855 $this->errors[] = $this->db->lasterror();
2857 $contactstatic->country_id = $result;
2858 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2862 if (!$errorforactions) {
2864 if (!empty($contactstatic->state)) {
2865 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2866 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
2867 if (empty($result)) {
2869 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
2870 } elseif (!($result > 0)) {
2872 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
2873 $this->errors[] = $this->db->lasterror();
2875 $contactstatic->state_id = $result;
2876 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2878 } elseif (!empty($contactstatic->state_code)) {
2879 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2880 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
2881 if (empty($result)) {
2883 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
2884 } elseif (!($result > 0)) {
2886 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
2887 $this->errors[] = $this->db->lasterror();
2889 $contactstatic->state_id = $result;
2890 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2895 if (!$errorforactions) {
2896 $result = $contactstatic->create($user);
2899 $this->error = $contactstatic->error;
2900 $this->errors = $contactstatic->errors;
2902 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag((
string) $contactstatic->id);
2909 } elseif ($operation[
'type'] ==
'recordevent') {
2913 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
2914 if ($alreadycreated == 0) {
2915 $operationslog .=
'<br>We did not find existing actioncomm with msgid='.$msgid;
2917 if ($projectstatic->id > 0) {
2918 if ($projectfoundby) {
2919 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
2922 if ($thirdpartystatic->id > 0) {
2923 if ($thirdpartyfoundby) {
2924 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2927 if ($contactstatic->id > 0) {
2928 if ($contactfoundby) {
2929 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2933 $description = $descriptiontitle;
2939 $descriptionfull = $description;
2941 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2946 $actioncomm->type_code =
'AC_OTH_AUTO';
2947 $actioncomm->code =
'AC_'.$actioncode;
2948 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
2949 $actioncomm->note_private = $descriptionfull;
2950 $actioncomm->fk_project = $projectstatic->id;
2951 $actioncomm->datep = $dateemail;
2952 $actioncomm->datef = $dateemail;
2953 $actioncomm->percentage = -1;
2954 $actioncomm->socid = $thirdpartystatic->id;
2955 $actioncomm->contact_id = $contactstatic->id;
2956 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array());
2957 $actioncomm->authorid = $user->id;
2958 $actioncomm->userownerid = $user->id;
2960 $actioncomm->email_msgid = $msgid;
2961 $actioncomm->email_from = $fromstring;
2962 $actioncomm->email_sender = $sender;
2963 $actioncomm->email_to = $to;
2964 $actioncomm->email_tocc = $sendtocc;
2965 $actioncomm->email_tobcc = $sendtobcc;
2966 $actioncomm->email_subject = $subject;
2967 $actioncomm->errors_to =
'';
2969 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
2970 $actioncomm->fk_element = $fk_element_id;
2971 $actioncomm->elementid = $fk_element_id;
2972 $actioncomm->elementtype = $fk_element_type;
2973 if (is_object($objectemail) && $objectemail->module) {
2974 $actioncomm->elementtype .=
'@'.$objectemail->module;
2981 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2983 if ($errorforthisaction) {
2986 $result = $actioncomm->create($user);
2989 $this->errors = $actioncomm->errors;
2991 if ($fk_element_type ==
"ticket" && is_object($objectemail)) {
2992 if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED || $objectemail->status == Ticket::STATUS_NEED_MORE_INFO || $objectemail->status == Ticket::STATUS_WAITING) {
2993 if ($objectemail->fk_user_assign !=
null) {
2994 $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED);
2996 $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ);
3000 $operationslog .=
'<br>Ticket Re-Opened successfully -> ref='.$objectemail->ref;
3003 $this->error =
'Error while changing the ticket status -> ref='.$objectemail->ref;
3004 $this->errors[] = $this->error;
3007 if (!empty($attachments)) {
3009 $ticket =
new Ticket($this->db);
3010 $ticket->fetch($fk_element_id);
3011 $destdir = $conf->ticket->dir_output.
'/'.$ticket->ref;
3016 foreach ($attachments as $attachment) {
3017 $attachment->save($destdir.
'/');
3020 $this->
getmsg($connection, $imapemail, $destdir);
3025 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag((
string) $actioncomm->id);
3029 $operationslog .=
'<br>An event in actioncomm table already exists for the msgid = '.$msgid.
' so we bypass this action.';
3031 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
3034 foreach ($attachments as $attachment) {
3035 if ($attachment->getName() ===
'undefined') {
3038 $data[$attachment->getName()] = $attachment->getContent();
3042 foreach ($pj as $key => $val) {
3043 $data[$val[
'filename']] =
getFileData($imapemail, (
string) $val[
'pos'], $val[
'type'], $connection);
3046 if (count($data) > 0) {
3047 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($from).
"%'";
3048 $resql = $this->db->query($sql);
3049 if ($this->db->num_rows($resql) == 0) {
3050 $this->errors[] =
"User Not allowed to add documents ({$from})";
3052 $arrayobject = array(
3053 'propale' => array(
'table' =>
'propal',
3054 'fields' => array(
'ref'),
3055 'class' =>
'comm/propal/class/propal.class.php',
3056 'object' =>
'Propal'),
3057 'holiday' => array(
'table' =>
'holiday',
3058 'fields' => array(
'ref'),
3059 'class' =>
'holiday/class/holiday.class.php',
3060 'object' =>
'Holiday'),
3061 'expensereport' => array(
'table' =>
'expensereport',
3062 'fields' => array(
'ref'),
3063 'class' =>
'expensereport/class/expensereport.class.php',
3064 'object' =>
'ExpenseReport'),
3065 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
3066 'fields' => array(
'ref'),
3067 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
3068 'object' =>
'RecruitmentJobPosition'),
3069 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
3070 'fields' => array(
'ref'),
3071 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
3072 'object' =>
'RecruitmentCandidature'),
3073 'societe' => array(
'table' =>
'societe',
3074 'fields' => array(
'code_client',
'code_fournisseur'),
3075 'class' =>
'societe/class/societe.class.php',
3076 'object' =>
'Societe'),
3077 'commande' => array(
'table' =>
'commande',
3078 'fields' => array(
'ref'),
3079 'class' =>
'commande/class/commande.class.php',
3080 'object' =>
'Commande'),
3081 'expedition' => array(
'table' =>
'expedition',
3082 'fields' => array(
'ref'),
3083 'class' =>
'expedition/class/expedition.class.php',
3084 'object' =>
'Expedition'),
3085 'contract' => array(
'table' =>
'contrat',
3086 'fields' => array(
'ref'),
3087 'class' =>
'contrat/class/contrat.class.php',
3088 'object' =>
'Contrat'),
3089 'fichinter' => array(
'table' =>
'fichinter',
3090 'fields' => array(
'ref'),
3091 'class' =>
'fichinter/class/fichinter.class.php',
3092 'object' =>
'Fichinter'),
3093 'ticket' => array(
'table' =>
'ticket',
3094 'fields' => array(
'ref'),
3095 'class' =>
'ticket/class/ticket.class.php',
3096 'object' =>
'Ticket'),
3097 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
3098 'fields' => array(
'ref'),
3099 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
3100 'object' =>
'KnowledgeRecord'),
3101 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
3102 'fields' => array(
'ref'),
3103 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
3104 'object' =>
'SupplierProposal'),
3105 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
3106 'fields' => array(
'ref',
'ref_supplier'),
3107 'class' =>
'fourn/class/fournisseur.commande.class.php',
3108 'object' =>
'SupplierProposal'),
3109 'facture' => array(
'table' =>
'facture',
3110 'fields' => array(
'ref'),
3111 'class' =>
'compta/facture/class/facture.class.php',
3112 'object' =>
'Facture'),
3113 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
3114 'fields' => array(
'ref',
'ref_client'),
3115 'class' =>
'fourn/class/fournisseur.facture.class.php',
3116 'object' =>
'FactureFournisseur'),
3117 'produit' => array(
'table' =>
'product',
3118 'fields' => array(
'ref'),
3119 'class' =>
'product/class/product.class.php',
3120 'object' =>
'Product'),
3121 'productlot' => array(
'table' =>
'product_lot',
3122 'fields' => array(
'batch'),
3123 'class' =>
'product/stock/class/productlot.class.php',
3124 'object' =>
'Productlot'),
3125 'projet' => array(
'table' =>
'projet',
3126 'fields' => array(
'ref'),
3127 'class' =>
'projet/class/projet.class.php',
3128 'object' =>
'Project'),
3129 'projet_task' => array(
'table' =>
'projet_task',
3130 'fields' => array(
'ref'),
3131 'class' =>
'projet/class/task.class.php',
3132 'object' =>
'Task'),
3133 'ressource' => array(
'table' =>
'resource',
3134 'fields' => array(
'ref'),
3135 'class' =>
'ressource/class/dolressource.class.php',
3136 'object' =>
'Dolresource'),
3137 'bom' => array(
'table' =>
'bom_bom',
3138 'fields' => array(
'ref'),
3139 'class' =>
'bom/class/bom.class.php',
3141 'mrp' => array(
'table' =>
'mrp_mo',
3142 'fields' => array(
'ref'),
3143 'class' =>
'mrp/class/mo.class.php',
3147 if (!is_object($hookmanager)) {
3148 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3151 $hookmanager->initHooks(array(
'emailcolector'));
3152 $parameters = array(
'arrayobject' => $arrayobject);
3153 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
3155 $arrayobject = $hookmanager->resArray;
3158 $resultobj = array();
3160 foreach ($arrayobject as $key => $objectdesc) {
3161 $sql =
'SELECT DISTINCT t.rowid ';
3162 $sql .=
' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc[
'table']) .
' AS t';
3164 foreach ($objectdesc[
'fields'] as $field) {
3165 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $this->db->sanitize($field) .
", '%') AND t." . $this->db->sanitize($field) .
" <> '') OR ";
3167 $sql = substr($sql, 0, -4);
3169 $ressqlobj = $this->db->query($sql);
3171 while ($obj = $this->db->fetch_object($ressqlobj)) {
3172 $resultobj[$key][] = $obj->rowid;
3177 foreach ($resultobj as $mod => $ids) {
3178 $moddesc = $arrayobject[$mod];
3179 $elementpath = $mod;
3181 $objectmanaged =
new $moddesc[
'object']($this->db);
3182 '@phan-var-force CommonObject $objectmanaged';
3183 foreach ($ids as $val) {
3184 $res = $objectmanaged->fetch($val);
3186 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
3187 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
3189 $this->errors[] =
'object not found';
3193 foreach ($dirs as $target) {
3194 $prefix = $this->actions[$this->id][
'actionparam'];
3195 foreach ($data as $filename => $content) {
3196 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
3198 $this->errors[] =
'Doc not saved';
3203 $operationslog .=
'<br>Save attachment files on disk';
3205 $this->errors[] =
'no joined piece';
3207 $operationslog .=
'<br>No joinded files';
3209 } elseif ($operation[
'type'] ==
'project') {
3211 $projecttocreate =
new Project($this->db);
3212 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
3213 if ($alreadycreated == 0) {
3214 if ($thirdpartystatic->id > 0) {
3215 $projecttocreate->socid = $thirdpartystatic->id;
3216 if ($thirdpartyfoundby) {
3217 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3220 if ($contactstatic->id > 0) {
3221 $projecttocreate->contact_id = $contactstatic->id;
3222 if ($contactfoundby) {
3223 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3227 $description = $descriptiontitle;
3233 $descriptionfull = $description;
3235 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3239 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
3240 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
3242 $projecttocreate->title = $subject;
3243 $projecttocreate->date_start = $dateemail;
3244 $projecttocreate->date_end = 0;
3245 $projecttocreate->opp_status = $id_opp_status;
3246 $projecttocreate->opp_percent = $percent_opp_status;
3248 $projecttocreate->note_private = $descriptionfull;
3249 $projecttocreate->entity = $conf->entity;
3251 $projecttocreate->email_date = $dateemail;
3252 $projecttocreate->email_msgid = $msgid;
3253 $projecttocreate->email_from = $fromstring;
3254 $projecttocreate->email_sender = $sender;
3255 $projecttocreate->email_to = $to;
3256 $projecttocreate->email_tocc = $sendtocc;
3257 $projecttocreate->email_tobcc = $sendtobcc;
3258 $projecttocreate->email_subject = $subject;
3259 $projecttocreate->errors_to =
'';
3261 $savesocid = $projecttocreate->socid;
3265 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3269 if (empty($projecttocreate->ref)) {
3278 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3279 foreach ($dirmodels as $reldir) {
3280 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
3281 if (file_exists($file)) {
3282 $classname = $modele;
3287 if ($classname !==
'') {
3288 if ($savesocid > 0) {
3289 if ($savesocid != $projecttocreate->socid) {
3291 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');
3294 if ($projecttocreate->socid > 0) {
3295 $thirdpartystatic->fetch($projecttocreate->socid);
3299 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
3300 $modModuleToUseForNextValue =
new $classname();
3301 '@phan-var-force ModeleNumRefProjects $modModuleToUseForNextValue';
3302 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
3304 $projecttocreate->ref = $defaultref;
3308 if ($errorforthisaction) {
3311 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
3313 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3315 $operationslog .=
'<br>'.$this->error;
3318 $result = $projecttocreate->create($user);
3321 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
3322 $this->errors = $projecttocreate->errors;
3324 $operationslog .=
'<br>'.$this->error;
3327 $destdir = $conf->project->dir_output.
'/'.$projecttocreate->ref;
3332 foreach ($attachments as $attachment) {
3334 $typeattachment = (string) $attachment->getDisposition();
3335 $filename = $attachment->getFilename();
3336 $content = $attachment->getContent();
3340 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3342 $this->errors = array_merge($this->errors, [$this->error]);
3347 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3349 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3357 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3359 } elseif ($operation[
'type'] ==
'ticket') {
3361 $tickettocreate =
new Ticket($this->db);
3362 if ($ticketalreadyexists == 0) {
3363 if ($thirdpartystatic->id > 0) {
3364 $tickettocreate->socid = $thirdpartystatic->id;
3365 $tickettocreate->fk_soc = $thirdpartystatic->id;
3366 if ($thirdpartyfoundby) {
3367 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3370 if ($contactstatic->id > 0) {
3371 $tickettocreate->contact_id = $contactstatic->id;
3372 if ($contactfoundby) {
3373 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3377 $description = $descriptiontitle;
3383 $descriptionfull = $description;
3385 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3389 $tickettocreate->subject = $subject;
3390 $tickettocreate->message = $description;
3392 $tickettocreate->category_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1)));
3393 $tickettocreate->severity_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1)));
3394 $tickettocreate->origin_email = $from;
3395 $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto :
null);
3396 $tickettocreate->origin_references = (!empty($headers[
'References']) ? $headers[
'References'] :
null);
3397 $tickettocreate->fk_user_create = $user->id;
3398 $tickettocreate->datec =
dol_now();
3399 $tickettocreate->fk_project = $projectstatic->id;
3400 $tickettocreate->notify_tiers_at_create =
getDolGlobalInt(
'TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3401 $tickettocreate->note_private = $descriptionfull;
3402 $tickettocreate->entity = $conf->entity;
3404 $tickettocreate->email_date = $dateemail;
3405 $tickettocreate->email_msgid = $msgid;
3406 $tickettocreate->email_from = $fromstring;
3407 $tickettocreate->email_sender = $sender;
3408 $tickettocreate->email_to = $to;
3409 $tickettocreate->email_tocc = $sendtocc;
3410 $tickettocreate->email_tobcc = $sendtobcc;
3411 $tickettocreate->email_subject = $subject;
3412 $tickettocreate->errors_to =
'';
3416 $savesocid = $tickettocreate->socid;
3420 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3422 $modele =
'UNDEFINED';
3424 if (empty($tickettocreate->ref)) {
3433 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3434 foreach ($dirmodels as $reldir) {
3435 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3436 if (file_exists($file)) {
3437 $classname = $modele;
3442 if ($classname !==
'') {
3443 if ($savesocid > 0) {
3444 if ($savesocid != $tickettocreate->socid) {
3446 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');
3449 if ($tickettocreate->socid > 0) {
3450 $thirdpartystatic->fetch($tickettocreate->socid);
3455 $modModuleToUseForNextValue =
new $classname();
3456 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3457 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3459 $tickettocreate->ref = $defaultref;
3462 if ($errorforthisaction) {
3465 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3467 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3470 $tickettocreate->context[
'actionmsg2'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3471 $tickettocreate->context[
'actionmsg'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3475 $sender_contact =
new Contact($this->db);
3476 $sender_contact->fetch(0,
null,
'', $from);
3477 if (!empty($sender_contact->id)) {
3478 $tickettocreate->context[
'contact_id'] = $sender_contact->id;
3481 $result = $tickettocreate->create($user);
3484 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3485 $this->errors = $tickettocreate->errors;
3488 $destdir = $conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3493 foreach ($attachments as $attachment) {
3495 $typeattachment = (string) $attachment->getDisposition();
3496 $filename = $attachment->getName();
3497 $content = $attachment->getContent();
3501 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3503 $this->errors = array_merge($this->errors, [$this->error]);
3508 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3510 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3519 $operationslog .=
'<br>Ticket already exists, so we bypass action "ticket"';
3521 } elseif ($operation[
'type'] ==
'candidature') {
3525 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3526 if ($alreadycreated == 0) {
3527 $description = $descriptiontitle;
3533 $descriptionfull = $description;
3534 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3537 $candidaturetocreate->subject = $subject;
3538 $candidaturetocreate->message = $description;
3539 $candidaturetocreate->type_code = 0;
3540 $candidaturetocreate->category_code =
null;
3541 $candidaturetocreate->severity_code =
null;
3542 $candidaturetocreate->email = $from;
3544 $candidaturetocreate->fk_user_creat = $user->id;
3545 $candidaturetocreate->date_creation =
dol_now();
3546 $candidaturetocreate->fk_project = $projectstatic->id;
3547 $candidaturetocreate->description = $description;
3548 $candidaturetocreate->note_private = $descriptionfull;
3549 $candidaturetocreate->entity = $conf->entity;
3550 $candidaturetocreate->email_msgid = $msgid;
3551 $candidaturetocreate->email_date = $dateemail;
3552 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3557 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3600 if ($errorforthisaction) {
3604 $result = $candidaturetocreate->create($user);
3607 $this->error =
'Failed to create candidature: '.implode(
', ', $candidaturetocreate->errors);
3608 $this->errors = $candidaturetocreate->errors;
3611 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag((
string) $candidaturetocreate->id);
3614 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3617 if (!is_object($hookmanager)) {
3618 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3621 $hookmanager->initHooks([
'emailcolector']);
3623 $parameters = array(
3624 'connection' => $connection,
3625 'imapemail' => $imapemail,
3626 'overview' => $overview,
3629 'fromtext' => $fromtext,
3631 'actionparam' => $operation[
'actionparam'],
3633 'thirdpartyid' => $thirdpartyid,
3634 'objectid' => $objectid,
3635 'objectemail' => $objectemail,
3637 'messagetext' => $messagetext,
3638 'subject' => $subject,
3639 'header' => $header,
3640 'attachments' => $attachments,
3642 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3645 $errorforthisaction++;
3646 $this->error = $hookmanager->resPrint;
3648 if ($errorforthisaction) {
3650 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3652 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3656 if (!$errorforactions) {
3657 $nbactiondoneforemail++;
3663 if (!$errorforactions) {
3664 if (!empty($targetdir)) {
3667 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3668 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid.
' - '.$imapemail->getHeader()->get(
'subject').
' to '.$targetdir;
3670 $arrayofemailtodelete[$this->
uidAsString($imapemail)] = $imapemail;
3673 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3674 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3676 $arrayofemailtodelete[$imapemail] = $msgid;
3681 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);
3683 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3691 unset($objectemail);
3692 unset($projectstatic);
3693 unset($thirdpartystatic);
3694 unset($contactstatic);
3696 $nbemailprocessed++;
3698 if (!$errorforemail) {
3699 $nbactiondone += $nbactiondoneforemail;
3703 $this->db->commit();
3705 $this->db->rollback();
3709 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3710 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3711 $datelastok = strtotime($headers[
'Date']);
3717 $this->db->rollback();
3719 }
catch (Throwable $e) {
3723 $this->db->rollback();
3724 }
catch (Throwable $eInner) {
3725 dol_syslog(
"EmailCollector loop catch rollback failed: ".$eInner->getMessage(), LOG_ERR);
3727 dol_syslog(
"EmailCollector loop caught exception on one email, skipping: ".$e->getMessage(), LOG_WARNING);
3728 $operationslog .=
'<br>** Exception while processing email #'.dol_escape_htmltag((
string) $iforemailloop).
' - '.
dol_escape_htmltag($e->getMessage()).
' (skipped)';
3732 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3734 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3736 $langs->load(
"admin");
3737 $output = $langs->trans(
'NoNewEmailToProcess');
3738 $output .=
' (defaultlang='.$langs->defaultlang.
')';
3744 krsort($arrayofemailtodelete, SORT_NUMERIC);
3746 foreach ($arrayofemailtodelete as $imapemailnum => $imapemail) {
3747 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemailnum);
3749 $operationslog .=
"<br> move email ".$imapemailnum.($mode > 0 ?
' (test)' :
'');
3751 if (empty($mode) && empty($error)) {
3752 $tmptargetdir = $targetdir;
3759 $result = $imapemail->move($tmptargetdir,
false);
3762 $operationslog .=
'<br>Exception !!!! '.$e->getMessage();
3764 if (empty($result)) {
3765 dol_syslog(
"Failed to move email into target directory ".$targetdir);
3766 $operationslog .=
'<br>Failed to move email into target directory '.$targetdir;
3772 if (empty($mode) && empty($error)) {
3774 $operationslog .=
"<br>Expunge";
3779 $client->disconnect();
3781 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
3782 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
3784 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid.($mode > 0 ?
' (test)' :
'');
3786 if (empty($mode) && empty($error)) {
3787 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
3790 $this->error = imap_last_error();
3791 $this->errors[] = $this->error;
3793 $operationslog .=
'<br>Error in move '.$this->error;
3800 if (empty($mode) && empty($error)) {
3802 $operationslog .=
"<br>Expunge";
3804 imap_expunge($connection);
3806 imap_close($connection);
3809 $this->datelastresult = $now;
3810 $this->lastresult = $output;
3812 $this->debuginfo .=
'IMAP search array used : '.$search;
3814 $this->debuginfo .=
'IMAP search string used : '.$search;
3817 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
3819 if ($operationslog) {
3820 $this->debuginfo .= $operationslog;
3823 if (empty($error) && empty($mode)) {
3824 $this->datelastok = $datelastok;
3827 if (!empty($this->errors)) {
3828 $this->lastresult .=
"<br>".implode(
"<br>", $this->errors);
3830 $this->codelastresult = ($error ?
'KO' :
'OK');
3836 dol_syslog(
"EmailCollector::doCollectOneCollector end error=".$error, LOG_INFO);
3838 return $error ? -1 : 1;
3853 private function getmsg($mbox, $mid, $destdir =
''): int
3857 global $charset, $htmlmsg, $plainmsg, $attachments;
3858 $htmlmsg = $plainmsg = $charset =
'';
3859 $attachments = array();
3866 $s = imap_fetchstructure($mbox, $mid, FT_UID);
3868 $this->errors = array_merge($this->errors, [imap_last_error()]);
3872 if (empty($s->parts)) {
3874 $this->
getpart($mbox, $mid, $s,
'0');
3877 foreach ($s->parts as $partno0 => $p) {
3878 $this->
getpart($mbox, $mid, $p, (
string) ($partno0 + 1), $destdir);
3911 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
3914 global $htmlmsg, $plainmsg, $charset, $attachments;
3918 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
3919 imap_body($mbox, $mid, FT_UID);
3921 if ($p->encoding == 4) {
3922 $data = quoted_printable_decode($data);
3923 } elseif ($p->encoding == 3) {
3924 $data = base64_decode($data);
3930 if ($p->parameters) {
3931 foreach ($p->parameters as $x) {
3932 $params[strtolower($x->attribute)] = $x->value;
3935 if (!empty($p->dparameters)) {
3936 foreach ($p->dparameters as $x) {
3937 $params[strtolower($x->attribute)] = $x->value;
3940 '@phan-var-force array{filename?:string,name?:string,charset?:string} $params';
3945 if (!empty($params[
'filename']) || !empty($params[
'name'])) {
3947 $filename = $params[
'filename'] ?? $params[
'name'];
3949 $attachments[$filename] = $data;
3951 if (strlen($destdir)) {
3952 if (substr($destdir, -1) !=
'/') {
3957 $file_name_complete = $filename;
3958 $destination = $destdir.$file_name_complete;
3961 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
3964 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
3967 $file_name_original = $file_name;
3976 while (file_exists($destdir.$file_name.
".".$extension)) {
3977 $file_name = $file_name_original .
' (' . $num .
')';
3978 $file_name_complete = $file_name .
"." . $extension;
3979 $destination = $destdir.$file_name_complete;
3985 file_put_contents($destination, $data);
3991 if ($p->type == 0 && $data) {
3992 if (!empty($params[
'charset'])) {
3997 if (strtolower($p->subtype) ==
'plain') {
3998 $plainmsg .= trim($data).
"\n\n";
4000 $htmlmsg .= $data.
"<br><br>";
4002 $charset = $params[
'charset'];
4003 } elseif ($p->type == 2 && $data) {
4009 if (!empty($params[
'charset'])) {
4012 $plainmsg .= $data.
"\n\n";
4016 if (!empty($p->parts)) {
4017 foreach ($p->parts as $partno0 => $p2) {
4018 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1), $destdir);
4034 if (!$string || $fromEncoding == $toEncoding) {
4037 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
4038 if (!$convertedString && extension_loaded(
'mbstring')) {
4039 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
4041 if (!$convertedString) {
4042 throw new Exception(
'Mime string encoding conversion failed');
4044 return $convertedString;
4063 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
4064 $elements = imap_mime_header_decode($subject);
4066 if (!empty($elements)) {
4067 $num = count($elements);
4068 for ($i = 0; $i < $num; $i++) {
4069 $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));
4070 $newstring .= $stringinutf8;
4072 $subject = $newstring;
4074 } elseif (!function_exists(
'mb_decode_mimeheader')) {
4075 $subject = mb_decode_mimeheader($subject);
4076 } elseif (function_exists(
'iconv_mime_decode')) {
4077 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
4093 require_once DOL_DOCUMENT_ROOT .
'/core/lib/images.lib.php';
4096 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
4097 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
4098 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
4099 $maxheightmini = $tmparraysize[
'maxheightmini'];
4100 $quality = $tmparraysize[
'quality'];
4102 file_put_contents($destdir.
'/'.$filename, $content);
4107 vignette($destdir.
'/'.$filename, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
4109 vignette($destdir.
'/'.$filename, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
4123 if (is_object($imapemail)) {
4124 return $imapemail->getAttributes()[
"uid"];
4126 return (
string) $imapemail;