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',
'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' =>
'small tdoverflowmax200'),
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'))
183 public $fk_user_creat;
188 public $fk_user_modif;
222 public $oauth_service;
226 public $imap_encryption;
234 public $source_directory;
238 public $target_directory;
242 public $maxemailpercollect;
247 public $datelastresult;
252 public $codelastresult;
277 const STATUS_DISABLED = 0;
278 const STATUS_ENABLED = 1;
288 global
$conf, $langs;
292 $this->ismultientitymanaged = 1;
293 $this->isextrafieldmanaged = 0;
296 $this->fields[
'rowid'][
'visible'] = 0;
298 if (!isModEnabled(
'multicompany') && isset($this->fields[
'entity'])) {
299 $this->fields[
'entity'][
'enabled'] = 0;
303 $oauthservices = array();
305 foreach (
$conf->global as $key => $val) {
306 if (!empty($val) && preg_match(
'/^OAUTH_.*_ID$/', $key)) {
307 $key = preg_replace(
'/^OAUTH_/',
'', $key);
308 $key = preg_replace(
'/_ID$/',
'', $key);
309 if (preg_match(
'/^.*-/', $key)) {
310 $name = preg_replace(
'/^.*-/',
'', $key);
312 $name = $langs->trans(
"NoName");
314 $provider = preg_replace(
'/-.*$/',
'', $key);
315 $provider = ucfirst(strtolower($provider));
317 $oauthservices[$key] = $name.
" (".$provider.
")";
321 $this->fields[
'oauth_service'][
'arrayofkeyval'] = $oauthservices;
324 foreach ($this->fields as $key => $val) {
325 if (isset($val[
'enabled']) && empty($val[
'enabled'])) {
326 unset($this->fields[$key]);
331 foreach ($this->fields as $key => $val) {
332 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
333 foreach ($val[
'arrayofkeyval'] as $key2 => $val2) {
334 $this->fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
352 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
353 $langs->load(
"errors");
354 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
358 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
359 $this->password =
dolEncrypt($this->password);
363 $this->password =
dolDecrypt($this->password);
365 if (is_array($this->filters) && count($this->filters)) {
368 foreach ($this->filters as $filter) {
369 $emailcollectorfilter->type = $filter[
'type'];
370 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
371 $emailcollectorfilter->fk_emailcollector = $this->id;
372 $emailcollectorfilter->status = $filter[
'status'];
374 $emailcollectorfilter->create($user);
378 if (is_array($this->actions) && count($this->actions)) {
381 foreach ($this->actions as $operation) {
382 $emailcollectoroperation->type = $operation[
'type'];
383 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
384 $emailcollectoroperation->fk_emailcollector = $this->id;
385 $emailcollectoroperation->status = $operation[
'status'];
386 $emailcollectoroperation->position = $operation[
'position'];
388 $emailcollectoroperation->create($user);
404 global $langs, $extrafields;
425 unset(
$object->codelastresult);
426 unset(
$object->datelastresult);
431 $object->ref =
"copy_of_".$object->ref;
434 $object->host =
'imap.example.com';
437 if (is_array(
$object->array_options) && count(
$object->array_options) > 0) {
438 $extrafields->fetch_name_optionals_label($this->table_element);
439 foreach (
$object->array_options as $key => $option) {
440 $shortkey = preg_replace(
'/options_/',
'', $key);
441 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
443 unset(
$object->array_options[$key]);
449 $object->context[
'createfromclone'] =
'createfromclone';
450 $result =
$object->create($user);
454 $this->errors =
$object->errors;
457 unset(
$object->context[
'createfromclone']);
464 $this->db->rollback();
476 public function fetch($id, $ref =
null)
480 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
481 $this->password =
dolDecrypt($this->password);
514 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
518 $sql =
"SELECT s.rowid";
519 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
520 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
522 $sql .=
" AND s.status = 1";
524 $sql .= $this->db->order($sortfield, $sortorder);
529 $offset = $limit * $page;
531 $sql .= $this->db->plimit($limit + 1, $offset);
534 $result = $this->db->query($sql);
536 $num = $this->db->num_rows($result);
539 $obj = $this->db->fetch_object($result);
541 if ($emailcollector_static->fetch($obj->rowid)) {
542 $obj_ret[] = $emailcollector_static;
547 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
548 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
550 if (!count($obj_ret)) {
551 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
569 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
570 $langs->load(
"errors");
571 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
575 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
576 $this->password =
dolEncrypt($this->password);
580 $this->password =
dolDecrypt($this->password);
592 public function delete(
User $user, $notrigger = 0)
607 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
609 global
$conf, $langs, $action, $hookmanager;
611 if (!empty(
$conf->dol_no_mouse_hover)) {
617 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
619 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
621 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
623 if ($option !=
'nolink') {
625 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
626 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
627 $add_save_lastsearch_values = 1;
629 if ($add_save_lastsearch_values) {
630 $url .=
'&save_lastsearch_values=1';
635 if (empty($notooltip)) {
637 $label = $langs->trans(
"ShowEmailCollector");
638 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
640 $linkclose .=
' title="'.dolPrintHTMLForAttribute($label).
'"';
641 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
643 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
646 $linkstart =
'<a href="'.$url.
'"';
647 $linkstart .= $linkclose.
'>';
650 $result .= $linkstart;
652 $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);
654 if ($withpicto != 2) {
655 $result .= $this->ref;
660 $hookmanager->initHooks(array(
'emailcollectordao'));
661 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result);
662 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
664 $result = $hookmanager->resPrint;
666 $result .= $hookmanager->resPrint;
694 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
697 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
698 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
699 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
700 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
703 $statusType =
'status5';
704 if ($status == self::STATUS_ENABLED) {
705 $statusType =
'status4';
708 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
719 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
720 $sql .=
' fk_user_creat, fk_user_modif';
721 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
722 $sql .=
' WHERE t.rowid = '.((int) $id);
723 $result = $this->db->query($sql);
725 if ($this->db->num_rows($result)) {
726 $obj = $this->db->fetch_object($result);
728 $this->
id = $obj->rowid;
730 $this->user_creation_id = $obj->fk_user_creat;
731 $this->user_modification_id = $obj->fk_user_modif;
732 $this->date_creation = $this->db->jdate($obj->datec);
733 $this->date_modification = empty($obj->datem) ?
'' : $this->db->jdate($obj->datem);
736 $this->db->free($result);
750 $this->host =
'localhost';
751 $this->login =
'alogin';
764 $this->filters = array();
766 $sql =
'SELECT rowid, type, rulevalue, status';
767 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
768 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
771 $resql = $this->db->query($sql);
773 $num = $this->db->num_rows($resql);
776 $obj = $this->db->fetch_object($resql);
777 $this->filters[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'rulevalue' => $obj->rulevalue,
'status' => $obj->status);
780 $this->db->free($resql);
796 $this->actions = array();
798 $sql =
'SELECT rowid, type, actionparam, status';
799 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
800 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
801 $sql .=
' ORDER BY position';
803 $resql = $this->db->query($sql);
805 $num = $this->db->num_rows($resql);
808 $obj = $this->db->fetch_object($resql);
809 $this->actions[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'actionparam' => $obj->actionparam,
'status' => $obj->status);
812 $this->db->free($resql);
831 $flags =
'/service=imap';
834 } elseif (empty($this->imap_encryption) || ($this->imap_encryption ==
'ssl' &&
getDolGlobalString(
'IMAP_FORCE_NOSSL'))) {
837 $flags .=
'/' . $this->imap_encryption;
840 $flags .=
'/novalidate-cert';
847 if (!empty($this->login) && strpos($this->login,
'/') !=
false) {
848 $partofauth = explode(
'/', $this->login);
849 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
852 $connectstringserver =
'{'.$this->host.
':'.$this->port.$flags.
'}';
854 return $connectstringserver;
865 if (function_exists(
'mb_convert_encoding')) {
867 $str = preg_replace(
"/ /",
"xxxSPACExxx", $str);
868 $str = preg_replace(
"/_/",
"xxxUNDERSCORExxx", $str);
869 $str = preg_replace(
"/\[Gmail\]/",
"xxxGMAILxxx", $str);
871 if ($str = mb_convert_encoding($str,
"UTF-7")) {
873 $str = preg_replace(
"/\+A/",
"&A", $str);
874 $str = preg_replace(
"/xxxUNDERSCORExxx/",
"_", $str);
876 $str = preg_replace(
"/xxxSPACExxx/",
" ", $str);
878 $str = preg_replace(
"/xxxGMAILxxx/",
"[Gmail]", $str);
882 $this->error =
"error: is not possible to encode this string '".$str.
"'";
902 $arrayofcollectors = $this->
fetchAll($user, 1);
904 foreach ($arrayofcollectors as $emailcollector) {
905 $result = $emailcollector->doCollectOneCollector(0);
907 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
909 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
910 if (!empty($emailcollector->errors)) {
911 $this->error .= implode(
'<br>', $emailcollector->errors);
914 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
937 global
$conf, $langs;
939 $errorforthisaction = 0;
942 $outputlangs = $langs;
945 $newlang =
GETPOST(
'lang_id',
'aZ09');
948 $newlang = !empty(
$object->thirdparty->default_lang) ?
$object->thirdparty->default_lang : $newlang;
950 if (!empty($newlang)) {
952 $outputlangs->setDefaultLang($newlang);
962 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
965 $tmparray = explode(
'.', $propertytooverwrite);
966 if (count($tmparray) == 2) {
967 $tmpclass = $tmparray[0];
968 $tmpproperty = $tmparray[1];
970 $tmpproperty = $tmparray[0];
972 if ($tmpclass && ($tmpclass !=
$object->element)) {
982 $regforregex = array();
983 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
984 $sourcefield = $regforregex[1];
985 $regexstring = $regforregex[2];
987 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
988 $sourcefield = $regforregex[1];
989 $regexstring = $regforregex[2];
992 if (!empty($sourcefield) && !empty($regexstring)) {
993 if (strtolower($sourcefield) ==
'body') {
994 $sourcestring = $messagetext;
995 } elseif (strtolower($sourcefield) ==
'subject') {
996 $sourcestring = $subject;
997 } elseif (strtolower($sourcefield) ==
'header') {
998 $sourcestring = $header;
1001 if ($sourcestring) {
1002 $regforval = array();
1004 if (strtolower($sourcefield) ==
'body') {
1005 $regexoptions =
'ms';
1007 if (strtolower($sourcefield) ==
'header') {
1008 $regexoptions =
'm';
1012 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
1014 $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
1015 if (strtolower($sourcefield) ==
'header') {
1016 if (preg_match(
'/^options_/', $tmpproperty)) {
1019 if (property_exists(
$object, $tmpproperty)) {
1026 if (preg_match(
'/^options_/', $tmpproperty)) {
1029 if (property_exists(
$object, $tmpproperty)) {
1036 if (preg_match(
'/^options_/', $tmpproperty)) {
1037 $operationslog .=
'<br>Regex /'.dol_escape_htmltag($regexstring).
'/'.
dol_escape_htmltag($regexoptions).
' into '.strtolower($sourcefield).
' -> found '.
dol_escape_htmltag(
dol_trunc(
$object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)], 128));
1039 if (property_exists(
$object, $tmpproperty)) {
1047 if (property_exists(
$object, $tmpproperty)) {
1050 $tmp[$tmpproperty] =
null;
1053 $operationslog .=
'<br>Regex /'.dol_escape_htmltag($regexstring).
'/'.
dol_escape_htmltag($regexoptions).
' into '.strtolower($sourcefield).
' -> not found, so property '.
dol_escape_htmltag($tmpproperty).
' is set to null.';
1057 $errorforthisaction++;
1058 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1059 $this->errors[] = $this->error;
1061 $operationslog .=
'<br>'.$this->error;
1063 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1065 if (preg_match(
'/^options_/', $tmpproperty)) {
1066 $valuecurrent =
$object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1068 if (property_exists(
$object, $tmpproperty)) {
1069 $valuecurrent =
$object->$tmpproperty;
1072 $valuecurrent = $tmp[$tmpproperty];
1076 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1077 $valuetouse = $regforregex[2];
1078 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0,
null,
$object);
1080 $matcharray = array();
1081 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1083 if (is_array($matcharray[1])) {
1084 foreach ($matcharray[1] as $keytoreplace) {
1085 if ($keytoreplace) {
1086 if (preg_match(
'/^options_/', $keytoreplace)) {
1087 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1089 if (property_exists(
$object, $keytoreplace)) {
1090 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->$keytoreplace;
1093 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1103 if (preg_match(
'/^options_/', $tmpproperty)) {
1104 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1106 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1108 if (property_exists(
$object, $tmpproperty)) {
1109 $object->$tmpproperty = $valuetouse;
1111 $tmp[$tmpproperty] = $valuetouse;
1114 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1118 $errorforthisaction++;
1119 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1120 $this->errors[] = $this->error;
1125 return $errorforthisaction;
1134 public function doCollectOneCollector($mode = 0)
1136 global $db,
$conf, $langs, $user;
1137 global $hookmanager;
1141 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1143 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1146 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1148 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1153 $this->debuginfo =
'';
1157 $searchfilterdoltrackid = 0;
1158 $searchfilternodoltrackid = 0;
1159 $searchfilterisanswer = 0;
1160 $searchfilterisnotanswer = 0;
1161 $searchfilterreplyto = 0;
1162 $searchfilterexcludebodyarray = array();
1163 $searchfilterexcludesubjectarray = array();
1164 $operationslog =
'';
1165 $rulesreplyto = array();
1166 $connectstringsource =
'';
1167 $connectstringtarget =
'';
1168 $connection =
false;
1169 $arrayofemail = array();
1174 if (empty($this->host)) {
1175 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1178 if (empty($this->login)) {
1179 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1182 if (empty($this->source_directory)) {
1183 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1189 $sourcedir = $this->source_directory;
1190 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1195 $sourcedir = $this->source_directory;
1196 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1199 if ($this->acces_type == 1) {
1201 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>';
1203 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1207 $keyforsupportedoauth2array = $this->oauth_service;
1208 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1209 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1211 $keyforprovider =
'';
1213 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', strtoupper($keyforsupportedoauth2array));
1214 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1216 if (!empty($supportedoauth2array)) {
1217 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1218 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1219 $OAUTH_SERVICENAME = $nameofservice;
1221 $OAUTH_SERVICENAME =
'Unknown';
1224 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1226 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1235 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1244 if (is_object($tokenobj) && $expire) {
1245 $this->debuginfo .=
'Refresh token '.$OAUTH_SERVICENAME.
'<br>';
1246 $credentials =
new Credentials(
1251 $serviceFactory = new \OAuth\ServiceFactory();
1252 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1256 if (preg_match(
'/^Microsoft/', $OAUTH_SERVICENAME)) {
1258 $tmp = explode(
'-', $OAUTH_SERVICENAME);
1259 $scopes = explode(
',',
getDolGlobalString(
'OAUTH_'.strtoupper($tmp[0]).(empty($tmp[1]) ?
'' :
'-'.$tmp[1]).
'_SCOPE'));
1262 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $scopes);
1264 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
1266 $refreshtoken = $tokenobj->getRefreshToken();
1267 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1270 $tokenobj->setRefreshToken($refreshtoken);
1271 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1273 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1274 if (is_object($tokenobj)) {
1275 $token = $tokenobj->getAccessToken();
1277 $this->error =
"Token not found";
1282 $this->error = $e->getMessage();
1283 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1287 $cm =
new ClientManager();
1288 $client = $cm->make([
1289 'host' => $this->host,
1290 'port' => $this->port,
1291 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1292 'validate_cert' => true,
1293 'protocol' =>
'imap',
1294 'username' => $this->login,
1295 'password' => $token,
1296 'authentication' =>
"oauth",
1300 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1302 $cm =
new ClientManager();
1303 $client = $cm->make([
1304 'host' => $this->host,
1305 'port' => $this->port,
1306 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1307 'validate_cert' => true,
1308 'protocol' =>
'imap',
1309 'username' => $this->login,
1310 'password' => $this->password,
1311 'authentication' =>
"login",
1319 }
catch (ConnectionFailedException $e) {
1320 $this->error = $e->getMessage();
1321 $this->errors[] = $this->error;
1322 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1326 $host = dol_getprefix(
'email');
1329 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1331 if (!function_exists(
'imap_open')) {
1332 $this->error =
'IMAP function not enabled on your PHP';
1338 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1339 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1341 $connectstringsource = $connectstringserver.$sourcedir;
1342 $connectstringtarget = $connectstringserver.$targetdir;
1345 $this->debuginfo .=
'connectstringsource = '.$connectstringsource.
', $connectstringtarget='.$connectstringtarget.
'<br>';
1347 $connection = imap_open($connectstringsource, $this->login, $this->password);
1348 if ($connection ===
false) {
1349 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1352 '@phan-var-force resource|IMAP\Connection $connection';
1355 $host = dol_getprefix(
'email');
1364 $criteria = array();
1367 $criteria = array(array(
'UNDELETED'));
1368 foreach ($this->filters as $rule) {
1369 if (empty($rule[
'status'])) {
1374 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1378 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1381 if ($rule[
'type'] ==
'from') {
1382 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1383 if (count($tmprulevaluearray) >= 2) {
1384 foreach ($tmprulevaluearray as $tmprulevalue) {
1385 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1388 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1391 if ($rule[
'type'] ==
'to') {
1392 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1393 if (count($tmprulevaluearray) >= 2) {
1394 foreach ($tmprulevaluearray as $tmprulevalue) {
1395 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1398 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1401 if ($rule[
'type'] ==
'bcc') {
1402 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1404 if ($rule[
'type'] ==
'cc') {
1405 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1407 if ($rule[
'type'] ==
'subject') {
1408 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1410 $searchfilterexcludesubjectarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1412 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1415 if ($rule[
'type'] ==
'body') {
1416 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1418 $searchfilterexcludebodyarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1420 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1423 if ($rule[
'type'] ==
'header') {
1424 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1436 if ($rule[
'type'] ==
'seen') {
1437 array_push($criteria, array($not.
"SEEN"));
1439 if ($rule[
'type'] ==
'unseen') {
1440 array_push($criteria, array($not.
"UNSEEN"));
1442 if ($rule[
'type'] ==
'unanswered') {
1443 array_push($criteria, array($not.
"UNANSWERED"));
1445 if ($rule[
'type'] ==
'answered') {
1446 array_push($criteria, array($not.
"ANSWERED"));
1448 if ($rule[
'type'] ==
'smaller') {
1449 array_push($criteria, array($not.
"SMALLER"));
1451 if ($rule[
'type'] ==
'larger') {
1452 array_push($criteria, array($not.
"LARGER"));
1456 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1457 $searchfilterdoltrackid++;
1458 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1460 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1461 $searchfilterdoltrackid++;
1462 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1464 if ($rule[
'type'] ==
'withtrackingid') {
1465 $searchfilterdoltrackid++;
1466 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1468 if ($rule[
'type'] ==
'withouttrackingid') {
1469 $searchfilternodoltrackid++;
1470 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1473 if ($rule[
'type'] ==
'isanswer') {
1474 $searchfilterisanswer++;
1475 $searchhead .=
'/References.*@.*/';
1477 if ($rule[
'type'] ==
'isnotanswer') {
1478 $searchfilterisnotanswer++;
1479 $searchhead .=
'! /References.*@.*/';
1482 if ($rule[
'type'] ==
'replyto') {
1483 $searchfilterreplyto++;
1484 $rulesreplyto[] = $rule[
'rulevalue'];
1485 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1489 if (empty($targetdir) || !
getDolGlobalString(
'EMAILCOLLECTOR_NO_FILTER_ON_DATE_IF_THERE_IS_A_TARGETDIR')) {
1491 if ($this->datelastok) {
1492 $fromdate = $this->datelastok;
1494 if ($fromdate > 0) {
1496 array_push($criteria, array(
"SINCE" => date(
'j-M-Y', $fromdate - 1)));
1501 dol_syslog(
"IMAP search string = ".var_export($criteria,
true));
1502 $search = var_export($criteria,
true);
1505 $search =
'UNDELETED';
1506 foreach ($this->filters as $rule) {
1507 if (empty($rule[
'status'])) {
1515 if (!empty($rule[
'rulevalue']) && strpos($rule[
'rulevalue'],
'!') === 0) {
1519 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1522 if ($rule[
'type'] ==
'from') {
1523 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1524 if (count($tmprulevaluearray) >= 2) {
1525 foreach ($tmprulevaluearray as $tmprulevalue) {
1526 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1529 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1532 if ($rule[
'type'] ==
'to') {
1533 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1534 if (count($tmprulevaluearray) >= 2) {
1535 foreach ($tmprulevaluearray as $tmprulevalue) {
1536 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1539 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1542 if ($rule[
'type'] ==
'bcc') {
1543 $search .= ($search ?
' ' :
'').$not.
'BCC';
1545 if ($rule[
'type'] ==
'cc') {
1546 $search .= ($search ?
' ' :
'').$not.
'CC';
1548 if ($rule[
'type'] ==
'subject') {
1551 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1553 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1556 if ($rule[
'type'] ==
'body') {
1559 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1562 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1565 if ($rule[
'type'] ==
'header') {
1566 $search .= ($search ?
' ' :
'').$not.
'HEADER '.$rule[
'rulevalue'];
1578 if ($rule[
'type'] ==
'seen') {
1579 $search .= ($search ?
' ' :
'').$not.
'SEEN';
1581 if ($rule[
'type'] ==
'unseen') {
1582 $search .= ($search ?
' ' :
'').$not.
'UNSEEN';
1584 if ($rule[
'type'] ==
'unanswered') {
1585 $search .= ($search ?
' ' :
'').$not.
'UNANSWERED';
1587 if ($rule[
'type'] ==
'answered') {
1588 $search .= ($search ?
' ' :
'').$not.
'ANSWERED';
1590 if ($rule[
'type'] ==
'smaller') {
1591 $search .= ($search ?
' ' :
'').$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1593 if ($rule[
'type'] ==
'larger') {
1594 $search .= ($search ?
' ' :
'').$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1598 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1599 $searchfilterdoltrackid++;
1600 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1602 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1603 $searchfilterdoltrackid++;
1604 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1606 if ($rule[
'type'] ==
'withtrackingid') {
1607 $searchfilterdoltrackid++;
1608 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1610 if ($rule[
'type'] ==
'withouttrackingid') {
1611 $searchfilternodoltrackid++;
1612 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1615 if ($rule[
'type'] ==
'isanswer') {
1616 $searchfilterisanswer++;
1617 $searchhead .=
'/References.*@.*/';
1619 if ($rule[
'type'] ==
'isnotanswer') {
1620 $searchfilterisnotanswer++;
1621 $searchhead .=
'! /References.*@.*/';
1624 if ($rule[
'type'] ==
'replyto') {
1625 $searchfilterreplyto++;
1626 $rulesreplyto[] = $rule[
'rulevalue'];
1627 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1631 if (empty($targetdir)) {
1633 if ($this->datelastok) {
1634 $fromdate = $this->datelastok;
1636 if ($fromdate > 0) {
1637 $search .= ($search ?
' ' :
'').
'SINCE '.date(
'j-M-Y', $fromdate - 1);
1646 $nbemailprocessed = 0;
1649 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1650 $arrayofemail = array();
1657 $tmpsourcedir = $sourcedir;
1662 $f = $client->getFolders(
false, $tmpsourcedir);
1665 if ($folder instanceof Webklex\PHPIMAP\Folder) {
1666 $Query = $folder->messages()->where($criteria);
1669 $this->error =
"Source directory ".$sourcedir.
" not found";
1670 $this->errors[] = $this->error;
1671 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_WARNING);
1676 $this->error =
"Failed to execute getfolders";
1677 $this->errors[] = $this->error;
1678 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1681 }
catch (InvalidWhereQueryCriteriaException $e) {
1682 $this->error = $e->getMessage();
1683 $this->errors[] = $this->error;
1684 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1687 $this->error = $e->getMessage();
1688 $this->errors[] = $this->error;
1689 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1693 '@phan-var-force Webklex\PHPIMAP\Query\Query $Query';
1697 $Query->leaveUnread();
1699 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1700 dol_syslog(
"EmailCollector::doCollectOneCollector nb arrayofemail ".(is_array($arrayofemail) ? count($arrayofemail) :
'Not array'));
1703 $this->error = $e->getMessage();
1704 $this->errors[] = $this->error;
1705 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1708 } elseif ($connection !==
false) {
1710 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1712 if ($arrayofemail ===
false) {
1714 $mapoferrrors = imap_errors();
1715 if ($mapoferrrors !==
false) {
1717 $this->error =
"Search string not understood - ".implode(
',', $mapoferrrors);
1718 $this->errors[] = $this->error;
1723 $arrayofemailtodelete = array();
1726 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0 && $connection !==
false) {
1743 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1745 $richarrayofemail = array();
1747 foreach ($arrayofemail as $imapemail) {
1748 if ($nbemailprocessed > 1000) {
1754 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1755 $header = $imapemail->getHeader()->raw;
1756 $overview = $imapemail->getAttributes();
1758 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1759 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1762 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1765 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)(\r\n|\s$)/m', $header, $matches);
1766 $headers = array_combine($matches[1], $matches[2]);
1769 $richarrayofemail[] = array(
'imapemail' => $imapemail,
'header' => $header,
'headers' => $headers,
'overview' => $overview,
'date' => strtotime($headers[
'Date']));
1774 $richarrayofemail =
dol_sort_array($richarrayofemail,
'date',
'asc');
1778 foreach ($richarrayofemail as $tmpval) {
1781 $imapemail = $tmpval[
'imapemail'];
1782 $header = $tmpval[
'header'];
1783 $overview = $tmpval[
'overview'];
1784 $headers = $tmpval[
'headers'];
1786 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1787 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1789 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1790 $headers[
'References'] = $headers[
'references'];
1792 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1793 $headers[
'Message-ID'] = $headers[
'message-id'];
1795 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1796 $headers[
'Subject'] = $headers[
'subject'];
1802 $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 if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) {
1860 if (empty($headers[
'References']) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References'])) {
1861 $nbemailprocessed++;
1862 dol_syslog(
" Discarded - No suffix in email recipient and no Header References found matching the signature of the application, so with a trackid coming from the application");
1867 if ($searchfilternodoltrackid > 0) {
1868 if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($headers[
'References']) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))) {
1869 $nbemailprocessed++;
1870 dol_syslog(
" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
1875 if ($searchfilterisanswer > 0) {
1876 $referencesforanswer =
'';
1877 if (!empty($headers[
'References'])) {
1878 $referencesforanswer .= $headers[
'References'].
' ';
1880 if (!empty($headers[
'In-Reply-To'])) {
1881 $referencesforanswer .= $headers[
'In-Reply-To'];
1884 $hasdolibarrreference = 0;
1885 if (!empty($referencesforanswer)) {
1886 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $referencesforanswer)) {
1887 $hasdolibarrreference = 1;
1889 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $referencesforanswer)) {
1890 $hasdolibarrreference = 1;
1895 if (empty($headers[
'In-Reply-To']) && empty($hasdolibarrreference)) {
1896 $nbemailprocessed++;
1897 dol_syslog(
" Discarded - Email is not an answer (no In-Reply-To header and no Dolibarr reference)");
1901 if (preg_match(
'/^(Re|AW)\s*:\s+/i', $headers[
'Subject'])) {
1907 if (!empty($headers[
'In-Reply-To'])) {
1911 if ($hasdolibarrreference) {
1918 $nbemailprocessed++;
1919 dol_syslog(
" Discarded - Email is not an answer (no RE prefix in subject)");
1923 if ($searchfilterisnotanswer > 0) {
1924 if (!empty($headers[
'In-Reply-To'])) {
1928 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
1934 $nbemailprocessed++;
1935 dol_syslog(
" Discarded - Email is an answer");
1940 if ($searchfilterreplyto > 0) {
1941 if (!empty($headers[
'Reply-To'])) {
1943 foreach ($rulesreplyto as $key => $rulereplyto) {
1944 if (preg_match(
'/'.preg_quote($rulereplyto,
'/').
'/', $headers[
'Reply-To'])) {
1949 if (!$isreplytook || $isreplytook != count($rulesreplyto)) {
1950 $nbemailprocessed++;
1951 dol_syslog(
" Discarded - Reply-to does not match");
1959 $thirdpartystatic =
new Societe($this->db);
1960 $contactstatic =
new Contact($this->db);
1961 $projectstatic =
new Project($this->db);
1963 $nbactiondoneforemail = 0;
1965 $errorforactions = 0;
1966 $thirdpartyfoundby =
'';
1967 $contactfoundby =
'';
1968 $projectfoundby =
'';
1969 $ticketfoundby =
'';
1970 $candidaturefoundby =
'';
1974 $dateformated =
dol_print_date($overview[
'date'],
'dayrfc',
'gmt');
1975 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".$dateformated.
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
1980 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);
1990 global $htmlmsg, $plainmsg, $charset, $attachments;
1994 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1995 if ($imapemail->hasHTMLBody()) {
1996 $htmlmsg = $imapemail->getHTMLBody();
1998 if ($imapemail->hasTextBody() && $imapemail->getTextBody() !=
"\n") {
1999 $plainmsg = $imapemail->getTextBody();
2001 if ($imapemail->hasAttachments()) {
2002 $attachments = $imapemail->getAttachments()->all();
2007 $getMsg = $this->
getmsg($connection, $imapemail);
2009 $this->errors = array_merge($this->errors, [$this->error]);
2013 '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments';
2025 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
2026 dol_syslog(
" Discarded - Email body is not valid utf8");
2030 if (!empty($searchfilterexcludebodyarray)) {
2031 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
2032 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
2033 $nbemailprocessed++;
2034 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
2035 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
2097 $replytostring =
'';
2100 $fromstring = $overview[
'from'];
2101 $replytostring = empty($overview[
'in_reply-to']) ? $headers[
'Reply-To'] : $overview[
'in_reply-to'];
2103 $sender = $overview[
'sender'];
2104 $to = $overview[
'to'];
2105 $sendtocc = empty($overview[
'cc']) ?
'' : $overview[
'cc'];
2106 $sendtobcc = empty($overview[
'bcc']) ?
'' : $overview[
'bcc'];
2108 $tmpdate = $overview[
'date']->toDate();
2109 $tmptimezone = $tmpdate->getTimezone()->getName();
2112 if (preg_match(
'/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) {
2113 if ($reg[1] ==
'+' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2114 $dateemail -= (3600 * (int) $reg[2]);
2115 $dateemail -= (60 * (int) $reg[3]);
2117 if ($reg[1] ==
'-' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2118 $dateemail += (3600 * (int) $reg[2]);
2119 $dateemail += (60 * (int) $reg[3]);
2122 $subject = $overview[
'subject'];
2124 $fromstring = $overview[0]->from;
2125 $replytostring = (!empty($overview[
'in_reply-to']) ? $overview[
'in_reply-to'] : (!empty($headers[
'Reply-To']) ? $headers[
'Reply-To'] :
"")) ;
2127 $sender = !empty($overview[0]->sender) ? $overview[0]->sender :
'';
2128 $to = $overview[0]->to;
2129 $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc :
'';
2130 $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc :
'';
2132 $subject = $overview[0]->subject;
2136 if (!empty($searchfilterexcludesubjectarray)) {
2137 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
2138 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
2139 $nbemailprocessed++;
2140 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
2141 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
2148 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
2150 $fromtext = $reg[1];
2152 $from = $fromstring;
2155 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
2157 $replytotext = $reg[1];
2159 $replyto = $replytostring;
2163 $fk_element_type =
'';
2180 $objectemail =
null;
2183 $arrayofreferences = array();
2184 if (!empty($headers[
'References'])) {
2185 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
2187 if (!in_array(
'<'.$msgid.
'>', $arrayofreferences)) {
2188 $arrayofreferences = array_merge($arrayofreferences, array(
'<'.$msgid.
'>'));
2195 foreach ($arrayofreferences as $reference) {
2197 if (!empty($trackidfoundintorecipienttype)) {
2198 $resultsearchtrackid = -1;
2199 $reg[1] = $trackidfoundintorecipienttype;
2200 $reg[2] = $trackidfoundintorecipientid;
2201 } elseif (!empty($trackidfoundintomsgidtype)) {
2202 $resultsearchtrackid = -1;
2203 $reg[1] = $trackidfoundintomsgidtype;
2204 $reg[2] = $trackidfoundintomsgidid;
2206 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
2207 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2208 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
2212 if (!empty($resultsearchtrackid)) {
2214 $trackid = $reg[1].$reg[2];
2216 $objectid = $reg[2];
2218 if ($reg[1] ==
'thi') {
2219 $objectemail =
new Societe($this->db);
2221 if ($reg[1] ==
'ctc') {
2222 $objectemail =
new Contact($this->db);
2224 if ($reg[1] ==
'inv') {
2225 $objectemail =
new Facture($this->db);
2227 if ($reg[1] ==
'sinv') {
2230 if ($reg[1] ==
'pro') {
2231 $objectemail =
new Propal($this->db);
2233 if ($reg[1] ==
'ord') {
2234 $objectemail =
new Commande($this->db);
2236 if ($reg[1] ==
'shi') {
2239 if ($reg[1] ==
'spro') {
2242 if ($reg[1] ==
'sord') {
2245 if ($reg[1] ==
'rec') {
2246 $objectemail =
new Reception($this->db);
2248 if ($reg[1] ==
'proj') {
2249 $objectemail =
new Project($this->db);
2250 $projectfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2252 if ($reg[1] ==
'tas') {
2253 $objectemail =
new Task($this->db);
2255 if ($reg[1] ==
'con') {
2256 $objectemail =
new Contact($this->db);
2258 if ($reg[1] ==
'use') {
2259 $objectemail =
new User($this->db);
2261 if ($reg[1] ==
'tic') {
2262 $objectemail =
new Ticket($this->db);
2263 $ticketfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2265 if ($reg[1] ==
'recruitmentcandidature') {
2267 $candidaturefoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2269 if ($reg[1] ==
'mem') {
2270 $objectemail =
new Adherent($this->db);
2278 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
2280 if (is_null($objectemail) && isModEnabled(
'ticket')) {
2281 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket";
2282 $sql .=
" WHERE email_msgid = '".$this->db->escape($reg[1]).
"' OR origin_references LIKE '%".$this->db->escape($this->db->escapeforlike($reg[1])).
"%'";
2283 $resql = $this->db->query($sql);
2285 $obj = $this->db->fetch_object($resql);
2287 $objectid = $obj->rowid;
2288 $objectemail =
new Ticket($this->db);
2289 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2296 if (!is_object($objectemail) && isModEnabled(
'project')) {
2297 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2298 $resql = $this->db->query($sql);
2300 $obj = $this->db->fetch_object($resql);
2302 $objectid = $obj->rowid;
2303 $objectemail =
new Project($this->db);
2304 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2311 if (!is_object($objectemail) && isModEnabled(
'recruitment')) {
2312 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2313 $resql = $this->db->query($sql);
2315 $obj = $this->db->fetch_object($resql);
2317 $objectid = $obj->rowid;
2319 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2328 if (is_object($objectemail)) {
2329 $result = $objectemail->fetch($objectid);
2331 $fk_element_id = $objectemail->id;
2332 $fk_element_type = $objectemail->element;
2334 if ($fk_element_type ==
'facture') {
2335 $fk_element_type =
'invoice';
2338 if (get_class($objectemail) !=
'Societe') {
2339 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2341 $thirdpartyid = $objectemail->id;
2344 if (get_class($objectemail) !=
'Contact') {
2345 $contactid = $objectemail->fk_socpeople;
2347 $contactid = $objectemail->id;
2350 if (get_class($objectemail) !=
'Project') {
2351 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2353 $projectid = $objectemail->id;
2356 if ($objectemail instanceof
Ticket) {
2357 $ticketid = $objectemail->id;
2359 $changeonticket_references =
false;
2360 if (empty($trackid)) {
2361 $trackid = $objectemail->track_id;
2363 if (empty($objectemail->origin_references)) {
2364 $objectemail->origin_references = !empty($headers[
'References']) ? $headers[
'References'] :
null;
2365 $changeonticket_references =
true;
2367 foreach ($arrayofreferences as $key => $referencetmp) {
2368 if (!str_contains($objectemail->origin_references, $referencetmp)) {
2369 $objectemail->origin_references .=
" ".$referencetmp;
2370 $changeonticket_references =
true;
2374 if ($changeonticket_references) {
2375 $operationslog .=
'<br>We complete ticket ID='.$ticketid.
' with property origin_references='.$objectemail->origin_references;
2376 $objectemail->update($user, 1);
2383 if ($projectid > 0) {
2384 $result = $projectstatic->fetch($projectid);
2386 $projectstatic->id = 0;
2388 $projectid = $projectstatic->id;
2390 $projectfoundby =
'trackid ('.$trackid.
')';
2392 if (empty($contactid)) {
2393 $contactid = $projectstatic->fk_contact;
2395 if (empty($thirdpartyid)) {
2396 $thirdpartyid = $projectstatic->fk_soc;
2401 if ($contactid > 0) {
2402 $result = $contactstatic->fetch($contactid);
2404 $contactstatic->id = 0;
2406 $contactid = $contactstatic->id;
2408 $contactfoundby =
'trackid ('.$trackid.
')';
2410 if (empty($thirdpartyid)) {
2411 $thirdpartyid = $contactstatic->fk_soc;
2416 if ($thirdpartyid > 0) {
2417 $result = $thirdpartystatic->fetch($thirdpartyid);
2419 $thirdpartystatic->id = 0;
2421 $thirdpartyid = $thirdpartystatic->id;
2423 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2428 if (is_object($objectemail)) {
2433 if (empty($contactid)) {
2434 $result = $contactstatic->fetch(0,
null,
'', $from);
2437 dol_syslog(
"We found a contact with the email ".$from);
2438 $contactid = $contactstatic->id;
2439 $contactfoundby =
'email of contact ('.$from.
')';
2440 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2441 $result = $thirdpartystatic->fetch($contactstatic->socid);
2443 $thirdpartyid = $thirdpartystatic->id;
2444 $thirdpartyfoundby =
'email of contact ('.$from.
')';
2450 if (empty($thirdpartyid)) {
2451 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
2453 dol_syslog(
"We found a thirdparty with the email ".$from);
2454 $thirdpartyid = $thirdpartystatic->id;
2455 $thirdpartyfoundby =
'email ('.$from.
')';
2492 foreach ($this->actions as $operation) {
2493 $errorforthisaction = 0;
2494 $ticketalreadyexists = 0;
2495 if ($errorforactions) {
2498 if (empty($operation[
'status'])) {
2502 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2505 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2506 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2509 $actioncode =
'EMAIL_IN';
2511 if (preg_match(
'/Sent$/', $sourcedir) || preg_match(
'/envoyés$/i', $sourcedir)) {
2512 $actioncode =
'EMAIL';
2515 $arrayofemailtoconsideresender = explode(
',',
getDolGlobalString(
'MAIL_FROM_EMAILS_TO_CONSIDER_SENDING'));
2516 foreach ($arrayofemailtoconsideresender as $emailtoconsidersender) {
2517 if (preg_match(
'/'.preg_quote($emailtoconsidersender,
'/').
'/', $fromstring)) {
2518 $actioncode =
'EMAIL';
2521 $operationslog .=
'<br>Email will have actioncode='.$actioncode;
2523 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2525 $descriptiontitle = $langs->transnoentitiesnoconv(
"RecordCreatedByEmailCollector", $this->
ref);
2530 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2532 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2534 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2536 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailReply").($langs->trans(
"MailReply") !=
'Reply to' ?
' (Reply to)' :
'').
' : '.
dol_escape_htmltag($replyto));
2539 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2542 if ($operation[
'type'] ==
'ticket') {
2544 $tickettocreate =
new Ticket($this->db);
2545 $errorfetchticket = 0;
2546 $alreadycreated = 0;
2547 if ($ticketid > 0) {
2548 $alreadycreated = $tickettocreate->fetch($ticketid);
2550 if ($alreadycreated == 0 && !empty($trackid)) {
2551 $alreadycreated = $tickettocreate->fetch(0,
'', $trackid);
2553 if ($alreadycreated == 0 && !empty($msgid)) {
2554 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2556 if ($alreadycreated < 0) {
2557 $errorfetchticket++;
2559 if (empty($errorfetchticket)) {
2560 if ($alreadycreated == 0) {
2561 $operationslog .=
'<br>Ticket not found using trackid='.$trackid.
' or msgid='.$msgid;
2562 $ticketalreadyexists = 0;
2564 $operationslog .=
'<br>Ticket already found using trackid='.$trackid.
' or msgid='.$msgid.
", we replace operation 'ticket' with 'recordevent' to add a new message";
2565 $ticketalreadyexists = 1;
2566 $operation[
'type'] =
'recordevent';
2569 $ticketalreadyexists = -1;
2576 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2577 if ($thirdpartyid > 0) {
2579 $idtouseforthirdparty = $thirdpartyid;
2580 $operationslog .=
'<br>We already have found a related thirdparty id, so we bypass the action loadthirdparty and use idtouseforthirdparty='.$idtouseforthirdparty;
2581 } elseif (empty($operation[
'actionparam'])) {
2583 $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;";
2584 $this->errors[] = $this->error;
2586 $actionparam = $operation[
'actionparam'];
2587 $idtouseforthirdparty =
'';
2588 $nametouseforthirdparty =
'';
2589 $emailtouseforthirdparty =
'';
2590 $namealiastouseforthirdparty =
'';
2592 $operationslog .=
'<br>Loop on each property to set into actionparam';
2596 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2600 $regforregex = array();
2602 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2603 $sourcefield = $regforregex[1];
2604 $regexstring = $regforregex[2];
2607 if (!empty($sourcefield) && !empty($regexstring)) {
2608 if (strtolower($sourcefield) ==
'body') {
2609 $sourcestring = $messagetext;
2610 } elseif (strtolower($sourcefield) ==
'subject') {
2611 $sourcestring = $subject;
2612 } elseif (strtolower($sourcefield) ==
'header') {
2613 $sourcestring = $header;
2616 if ($sourcestring) {
2617 $regforval = array();
2619 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2622 if ($propertytooverwrite ==
'id') {
2623 $idtouseforthirdparty = 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 idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2626 } elseif ($propertytooverwrite ==
'email') {
2627 $emailtouseforthirdparty = 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 emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2630 } elseif ($propertytooverwrite ==
'name') {
2631 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2633 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2634 } elseif ($propertytooverwrite ==
'name_alias') {
2635 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2637 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2639 $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';
2643 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2644 $idtouseforthirdparty =
null;
2645 $nametouseforthirdparty =
null;
2646 $emailtouseforthirdparty =
null;
2647 $namealiastouseforthirdparty =
null;
2649 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2651 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2658 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2659 $this->errors[] = $this->error;
2661 $operationslog .=
'<br>'.$this->error;
2663 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2667 if ($propertytooverwrite ==
'id') {
2668 $idtouseforthirdparty = $reg[2];
2670 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2671 } elseif ($propertytooverwrite ==
'email') {
2672 $emailtouseforthirdparty = $reg[2];
2674 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2675 } elseif ($propertytooverwrite ==
'name') {
2676 $nametouseforthirdparty = $reg[2];
2678 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2679 } elseif ($propertytooverwrite ==
'name_alias') {
2680 $namealiastouseforthirdparty = $reg[2];
2682 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2686 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2687 $this->errors[] = $this->error;
2692 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2694 $operationslog .=
'<br>We have this initial main data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty.
'.';
2697 $tmpobject->element =
'generic';
2698 $tmpobject->id = $idtouseforthirdparty;
2699 $tmpobject->name = $nametouseforthirdparty;
2700 $tmpobject->name_alias = $namealiastouseforthirdparty;
2701 $tmpobject->email = $emailtouseforthirdparty;
2705 $idtouseforthirdparty = $tmpobject->id;
2706 $nametouseforthirdparty = $tmpobject->name;
2707 $namealiastouseforthirdparty = $tmpobject->name_alias;
2708 $emailtouseforthirdparty = $tmpobject->email;
2710 $operationslog .=
'<br>We try to search existing thirdparty with idtouseforthirdparty='.$idtouseforthirdparty.
' emailtouseforthirdparty='.$emailtouseforthirdparty.
' nametouseforthirdparty='.$nametouseforthirdparty.
' namealiastouseforthirdparty='.$namealiastouseforthirdparty;
2713 $result = $thirdpartystatic->findNearest((
int) $idtouseforthirdparty, (
string) $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', (
string) $emailtouseforthirdparty, (
string) $namealiastouseforthirdparty);
2717 $this->error =
'Error when getting thirdparty with name '.$nametouseforthirdparty.
' (may be 2 record exists with same name ?)';
2718 $this->errors[] = $this->error;
2720 } elseif ($result == 0) {
2721 if ($operation[
'type'] ==
'loadthirdparty') {
2722 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2725 $resultContact = $contactstatic->findNearest(0,
'',
'',
'', (
string) $emailtouseforthirdparty,
'', 0);
2726 if ($resultContact > 0) {
2727 $contactstatic->fetch($resultContact);
2728 $idtouseforthirdparty = $contactstatic->socid;
2729 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2731 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2734 $langs->load(
"errors");
2735 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2736 $this->errors[] = $this->error;
2740 $langs->load(
"errors");
2741 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, (
string) $emailtouseforthirdparty, (
string) $nametouseforthirdparty, (
string) $namealiastouseforthirdparty);
2742 $this->errors[] = $this->error;
2744 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2745 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
2748 $thirdpartystatic =
new Societe($db);
2749 $thirdpartystatic->name = (string) $nametouseforthirdparty;
2750 if (!empty($namealiastouseforthirdparty)) {
2751 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
2752 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
2755 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'' : $fromtext) : $replytostring);
2757 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ?
'' : $from) : $replyto) : $emailtouseforthirdparty);
2760 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2762 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
2763 $thirdpartystatic->code_client =
'auto';
2765 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
2766 $thirdpartystatic->code_fournisseur =
'auto';
2769 if ($errorforthisaction) {
2772 $result = $thirdpartystatic->create($user);
2775 $this->error = $thirdpartystatic->error;
2776 $this->errors = $thirdpartystatic->errors;
2778 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag((
string) $thirdpartystatic->id);
2783 dol_syslog(
"One and only one existing third party has been found");
2785 $thirdpartystatic->fetch($result);
2787 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag((
string) $thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name);
2791 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
2792 if (empty($operation[
'actionparam'])) {
2794 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
2795 $this->errors[] = $this->error;
2797 $contact_static =
new Contact($this->db);
2799 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2800 if ($errorforthisaction) {
2803 if (!empty($contact_static->email) && $contact_static->email != $from) {
2804 $from = $contact_static->email;
2807 $result = $contactstatic->fetch(0,
null,
'', $from);
2810 $this->error =
'Error when getting contact with email ' . $from;
2811 $this->errors[] = $this->error;
2813 } elseif ($result == 0) {
2814 dol_syslog(
"Contact with email " . $from .
" was not found. We try to create it.");
2815 $contactstatic =
new Contact($this->db);
2818 $contactstatic->email = $from;
2819 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($from);
2822 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2824 if ($errorforthisaction) {
2828 if (!empty($contactstatic->country)) {
2829 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2830 $result =
getCountry(
'',
'3', $this->db,
null, 1, $contactstatic->country);
2831 if ($result ==
'NotDefined') {
2833 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
2834 } elseif (!($result > 0)) {
2836 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
2837 $this->errors[] = $this->db->lasterror();
2839 $contactstatic->country_id = $result;
2840 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2842 } elseif (!empty($contactstatic->country_code)) {
2843 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2844 $result =
getCountry($contactstatic->country_code,
'3', $this->db);
2845 if ($result ==
'NotDefined') {
2847 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
2848 } elseif (!($result > 0)) {
2850 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
2851 $this->errors[] = $this->db->lasterror();
2853 $contactstatic->country_id = $result;
2854 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2858 if (!$errorforactions) {
2860 if (!empty($contactstatic->state)) {
2861 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2862 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
2863 if (empty($result)) {
2865 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
2866 } elseif (!($result > 0)) {
2868 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
2869 $this->errors[] = $this->db->lasterror();
2871 $contactstatic->state_id = $result;
2872 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2874 } elseif (!empty($contactstatic->state_code)) {
2875 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2876 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
2877 if (empty($result)) {
2879 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
2880 } elseif (!($result > 0)) {
2882 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
2883 $this->errors[] = $this->db->lasterror();
2885 $contactstatic->state_id = $result;
2886 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2891 if (!$errorforactions) {
2892 $result = $contactstatic->create($user);
2895 $this->error = $contactstatic->error;
2896 $this->errors = $contactstatic->errors;
2898 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag((
string) $contactstatic->id);
2905 } elseif ($operation[
'type'] ==
'recordevent') {
2909 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
2910 if ($alreadycreated == 0) {
2911 $operationslog .=
'<br>We did not find existing actioncomm with msgid='.$msgid;
2913 if ($projectstatic->id > 0) {
2914 if ($projectfoundby) {
2915 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
2918 if ($thirdpartystatic->id > 0) {
2919 if ($thirdpartyfoundby) {
2920 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2923 if ($contactstatic->id > 0) {
2924 if ($contactfoundby) {
2925 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2929 $description = $descriptiontitle;
2935 $descriptionfull = $description;
2937 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2942 $actioncomm->type_code =
'AC_OTH_AUTO';
2943 $actioncomm->code =
'AC_'.$actioncode;
2944 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
2945 $actioncomm->note_private = $descriptionfull;
2946 $actioncomm->fk_project = $projectstatic->id;
2947 $actioncomm->datep = $dateemail;
2948 $actioncomm->datef = $dateemail;
2949 $actioncomm->percentage = -1;
2950 $actioncomm->socid = $thirdpartystatic->id;
2951 $actioncomm->contact_id = $contactstatic->id;
2952 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array());
2953 $actioncomm->authorid = $user->id;
2954 $actioncomm->userownerid = $user->id;
2956 $actioncomm->email_msgid = $msgid;
2957 $actioncomm->email_from = $fromstring;
2958 $actioncomm->email_sender = $sender;
2959 $actioncomm->email_to = $to;
2960 $actioncomm->email_tocc = $sendtocc;
2961 $actioncomm->email_tobcc = $sendtobcc;
2962 $actioncomm->email_subject = $subject;
2963 $actioncomm->errors_to =
'';
2965 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
2966 $actioncomm->fk_element = $fk_element_id;
2967 $actioncomm->elementid = $fk_element_id;
2968 $actioncomm->elementtype = $fk_element_type;
2969 if (is_object($objectemail) && $objectemail->module) {
2970 $actioncomm->elementtype .=
'@'.$objectemail->module;
2977 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2979 if ($errorforthisaction) {
2982 $result = $actioncomm->create($user);
2985 $this->errors = $actioncomm->errors;
2987 if ($fk_element_type ==
"ticket" && is_object($objectemail)) {
2988 if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED || $objectemail->status == Ticket::STATUS_NEED_MORE_INFO || $objectemail->status == Ticket::STATUS_WAITING) {
2989 if ($objectemail->fk_user_assign !=
null) {
2990 $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED);
2992 $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ);
2996 $operationslog .=
'<br>Ticket Re-Opened successfully -> ref='.$objectemail->ref;
2999 $this->error =
'Error while changing the ticket status -> ref='.$objectemail->ref;
3000 $this->errors[] = $this->error;
3003 if (!empty($attachments)) {
3005 $ticket =
new Ticket($this->db);
3006 $ticket->fetch($fk_element_id);
3007 $destdir =
$conf->ticket->dir_output.
'/'.$ticket->ref;
3012 foreach ($attachments as $attachment) {
3013 $attachment->save($destdir.
'/');
3016 $this->
getmsg($connection, $imapemail, $destdir);
3021 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag((
string) $actioncomm->id);
3025 $operationslog .=
'<br>An event in actioncomm table already exists for the msgid = '.$msgid.
' so we bypass this action.';
3027 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
3030 foreach ($attachments as $attachment) {
3031 if ($attachment->getName() ===
'undefined') {
3034 $data[$attachment->getName()] = $attachment->getContent();
3038 foreach ($pj as $key => $val) {
3039 $data[$val[
'filename']] =
getFileData($imapemail, (
string) $val[
'pos'], $val[
'type'], $connection);
3042 if (count($data) > 0) {
3043 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($from).
"%'";
3044 $resql = $this->db->query($sql);
3045 if ($this->db->num_rows($resql) == 0) {
3046 $this->errors[] =
"User Not allowed to add documents ({$from})";
3048 $arrayobject = array(
3049 'propale' => array(
'table' =>
'propal',
3050 'fields' => array(
'ref'),
3051 'class' =>
'comm/propal/class/propal.class.php',
3052 'object' =>
'Propal'),
3053 'holiday' => array(
'table' =>
'holiday',
3054 'fields' => array(
'ref'),
3055 'class' =>
'holiday/class/holiday.class.php',
3056 'object' =>
'Holiday'),
3057 'expensereport' => array(
'table' =>
'expensereport',
3058 'fields' => array(
'ref'),
3059 'class' =>
'expensereport/class/expensereport.class.php',
3060 'object' =>
'ExpenseReport'),
3061 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
3062 'fields' => array(
'ref'),
3063 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
3064 'object' =>
'RecruitmentJobPosition'),
3065 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
3066 'fields' => array(
'ref'),
3067 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
3068 'object' =>
'RecruitmentCandidature'),
3069 'societe' => array(
'table' =>
'societe',
3070 'fields' => array(
'code_client',
'code_fournisseur'),
3071 'class' =>
'societe/class/societe.class.php',
3072 'object' =>
'Societe'),
3073 'commande' => array(
'table' =>
'commande',
3074 'fields' => array(
'ref'),
3075 'class' =>
'commande/class/commande.class.php',
3076 'object' =>
'Commande'),
3077 'expedition' => array(
'table' =>
'expedition',
3078 'fields' => array(
'ref'),
3079 'class' =>
'expedition/class/expedition.class.php',
3080 'object' =>
'Expedition'),
3081 'contract' => array(
'table' =>
'contrat',
3082 'fields' => array(
'ref'),
3083 'class' =>
'contrat/class/contrat.class.php',
3084 'object' =>
'Contrat'),
3085 'fichinter' => array(
'table' =>
'fichinter',
3086 'fields' => array(
'ref'),
3087 'class' =>
'fichinter/class/fichinter.class.php',
3088 'object' =>
'Fichinter'),
3089 'ticket' => array(
'table' =>
'ticket',
3090 'fields' => array(
'ref'),
3091 'class' =>
'ticket/class/ticket.class.php',
3092 'object' =>
'Ticket'),
3093 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
3094 'fields' => array(
'ref'),
3095 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
3096 'object' =>
'KnowledgeRecord'),
3097 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
3098 'fields' => array(
'ref'),
3099 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
3100 'object' =>
'SupplierProposal'),
3101 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
3102 'fields' => array(
'ref',
'ref_supplier'),
3103 'class' =>
'fourn/class/fournisseur.commande.class.php',
3104 'object' =>
'SupplierProposal'),
3105 'facture' => array(
'table' =>
'facture',
3106 'fields' => array(
'ref'),
3107 'class' =>
'compta/facture/class/facture.class.php',
3108 'object' =>
'Facture'),
3109 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
3110 'fields' => array(
'ref',
'ref_client'),
3111 'class' =>
'fourn/class/fournisseur.facture.class.php',
3112 'object' =>
'FactureFournisseur'),
3113 'produit' => array(
'table' =>
'product',
3114 'fields' => array(
'ref'),
3115 'class' =>
'product/class/product.class.php',
3116 'object' =>
'Product'),
3117 'productlot' => array(
'table' =>
'product_lot',
3118 'fields' => array(
'batch'),
3119 'class' =>
'product/stock/class/productlot.class.php',
3120 'object' =>
'Productlot'),
3121 'projet' => array(
'table' =>
'projet',
3122 'fields' => array(
'ref'),
3123 'class' =>
'projet/class/projet.class.php',
3124 'object' =>
'Project'),
3125 'projet_task' => array(
'table' =>
'projet_task',
3126 'fields' => array(
'ref'),
3127 'class' =>
'projet/class/task.class.php',
3128 'object' =>
'Task'),
3129 'ressource' => array(
'table' =>
'resource',
3130 'fields' => array(
'ref'),
3131 'class' =>
'ressource/class/dolressource.class.php',
3132 'object' =>
'Dolresource'),
3133 'bom' => array(
'table' =>
'bom_bom',
3134 'fields' => array(
'ref'),
3135 'class' =>
'bom/class/bom.class.php',
3137 'mrp' => array(
'table' =>
'mrp_mo',
3138 'fields' => array(
'ref'),
3139 'class' =>
'mrp/class/mo.class.php',
3143 if (!is_object($hookmanager)) {
3144 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3147 $hookmanager->initHooks(array(
'emailcolector'));
3148 $parameters = array(
'arrayobject' => $arrayobject);
3149 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
3151 $arrayobject = $hookmanager->resArray;
3154 $resultobj = array();
3156 foreach ($arrayobject as $key => $objectdesc) {
3157 $sql =
'SELECT DISTINCT t.rowid ';
3158 $sql .=
' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc[
'table']) .
' AS t';
3160 foreach ($objectdesc[
'fields'] as $field) {
3161 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $this->db->sanitize($field) .
", '%') AND t." . $this->db->sanitize($field) .
" <> '') OR ";
3163 $sql = substr($sql, 0, -4);
3165 $ressqlobj = $this->db->query($sql);
3167 while ($obj = $this->db->fetch_object($ressqlobj)) {
3168 $resultobj[$key][] = $obj->rowid;
3173 foreach ($resultobj as $mod => $ids) {
3174 $moddesc = $arrayobject[$mod];
3175 $elementpath = $mod;
3177 $objectmanaged =
new $moddesc[
'object']($this->db);
3178 '@phan-var-force CommonObject $objectmanaged';
3179 foreach ($ids as $val) {
3180 $res = $objectmanaged->fetch($val);
3182 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
3183 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
3185 $this->errors[] =
'object not found';
3189 foreach ($dirs as $target) {
3190 $prefix = $this->actions[$this->id][
'actionparam'];
3191 foreach ($data as $filename => $content) {
3192 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
3194 $this->errors[] =
'Doc not saved';
3199 $operationslog .=
'<br>Save attachment files on disk';
3201 $this->errors[] =
'no joined piece';
3203 $operationslog .=
'<br>No joinded files';
3205 } elseif ($operation[
'type'] ==
'project') {
3207 $projecttocreate =
new Project($this->db);
3208 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
3209 if ($alreadycreated == 0) {
3210 if ($thirdpartystatic->id > 0) {
3211 $projecttocreate->socid = $thirdpartystatic->id;
3212 if ($thirdpartyfoundby) {
3213 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3216 if ($contactstatic->id > 0) {
3217 $projecttocreate->contact_id = $contactstatic->id;
3218 if ($contactfoundby) {
3219 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3223 $description = $descriptiontitle;
3229 $descriptionfull = $description;
3231 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3235 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
3236 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
3238 $projecttocreate->title = $subject;
3239 $projecttocreate->date_start = $dateemail;
3240 $projecttocreate->date_end = 0;
3241 $projecttocreate->opp_status = $id_opp_status;
3242 $projecttocreate->opp_percent = $percent_opp_status;
3244 $projecttocreate->note_private = $descriptionfull;
3245 $projecttocreate->entity =
$conf->entity;
3247 $projecttocreate->email_date = $dateemail;
3248 $projecttocreate->email_msgid = $msgid;
3249 $projecttocreate->email_from = $fromstring;
3250 $projecttocreate->email_sender = $sender;
3251 $projecttocreate->email_to = $to;
3252 $projecttocreate->email_tocc = $sendtocc;
3253 $projecttocreate->email_tobcc = $sendtobcc;
3254 $projecttocreate->email_subject = $subject;
3255 $projecttocreate->errors_to =
'';
3257 $savesocid = $projecttocreate->socid;
3261 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3265 if (empty($projecttocreate->ref)) {
3274 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
3275 foreach ($dirmodels as $reldir) {
3276 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
3277 if (file_exists($file)) {
3278 $classname = $modele;
3283 if ($classname !==
'') {
3284 if ($savesocid > 0) {
3285 if ($savesocid != $projecttocreate->socid) {
3287 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');
3290 if ($projecttocreate->socid > 0) {
3291 $thirdpartystatic->fetch($projecttocreate->socid);
3295 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
3296 $modModuleToUseForNextValue =
new $classname();
3297 '@phan-var-force ModeleNumRefProjects $modModuleToUseForNextValue';
3298 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
3300 $projecttocreate->ref = $defaultref;
3304 if ($errorforthisaction) {
3307 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
3309 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3311 $operationslog .=
'<br>'.$this->error;
3314 $result = $projecttocreate->create($user);
3317 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
3318 $this->errors = $projecttocreate->errors;
3320 $operationslog .=
'<br>'.$this->error;
3323 $destdir =
$conf->project->dir_output.
'/'.$projecttocreate->ref;
3328 foreach ($attachments as $attachment) {
3330 $typeattachment = (string) $attachment->getDisposition();
3331 $filename = $attachment->getFilename();
3332 $content = $attachment->getContent();
3336 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3338 $this->errors = array_merge($this->errors, [$this->error]);
3343 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3345 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag((
string) $projecttocreate->id);
3353 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3355 } elseif ($operation[
'type'] ==
'ticket') {
3357 $tickettocreate =
new Ticket($this->db);
3358 if ($ticketalreadyexists == 0) {
3359 if ($thirdpartystatic->id > 0) {
3360 $tickettocreate->socid = $thirdpartystatic->id;
3361 $tickettocreate->fk_soc = $thirdpartystatic->id;
3362 if ($thirdpartyfoundby) {
3363 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3366 if ($contactstatic->id > 0) {
3367 $tickettocreate->contact_id = $contactstatic->id;
3368 if ($contactfoundby) {
3369 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3373 $description = $descriptiontitle;
3379 $descriptionfull = $description;
3381 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3385 $tickettocreate->subject = $subject;
3386 $tickettocreate->message = $description;
3388 $tickettocreate->category_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1)));
3389 $tickettocreate->severity_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1)));
3390 $tickettocreate->origin_email = $from;
3391 $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto :
null);
3392 $tickettocreate->origin_references = (!empty($headers[
'References']) ? $headers[
'References'] :
null);
3393 $tickettocreate->fk_user_create = $user->id;
3394 $tickettocreate->datec =
dol_now();
3395 $tickettocreate->fk_project = $projectstatic->id;
3396 $tickettocreate->notify_tiers_at_create =
getDolGlobalInt(
'TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3397 $tickettocreate->note_private = $descriptionfull;
3398 $tickettocreate->entity =
$conf->entity;
3400 $tickettocreate->email_date = $dateemail;
3401 $tickettocreate->email_msgid = $msgid;
3402 $tickettocreate->email_from = $fromstring;
3403 $tickettocreate->email_sender = $sender;
3404 $tickettocreate->email_to = $to;
3405 $tickettocreate->email_tocc = $sendtocc;
3406 $tickettocreate->email_tobcc = $sendtobcc;
3407 $tickettocreate->email_subject = $subject;
3408 $tickettocreate->errors_to =
'';
3412 $savesocid = $tickettocreate->socid;
3416 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3418 $modele =
'UNDEFINED';
3420 if (empty($tickettocreate->ref)) {
3429 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
3430 foreach ($dirmodels as $reldir) {
3431 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3432 if (file_exists($file)) {
3433 $classname = $modele;
3438 if ($classname !==
'') {
3439 if ($savesocid > 0) {
3440 if ($savesocid != $tickettocreate->socid) {
3442 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');
3445 if ($tickettocreate->socid > 0) {
3446 $thirdpartystatic->fetch($tickettocreate->socid);
3451 $modModuleToUseForNextValue =
new $classname();
3452 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3453 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3455 $tickettocreate->ref = $defaultref;
3458 if ($errorforthisaction) {
3461 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3463 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3466 $tickettocreate->context[
'actionmsg2'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3467 $tickettocreate->context[
'actionmsg'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3471 $sender_contact =
new Contact($this->db);
3472 $sender_contact->fetch(0,
null,
'', $from);
3473 if (!empty($sender_contact->id)) {
3474 $tickettocreate->context[
'contact_id'] = $sender_contact->id;
3477 $result = $tickettocreate->create($user);
3480 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3481 $this->errors = $tickettocreate->errors;
3484 $destdir =
$conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3489 foreach ($attachments as $attachment) {
3491 $typeattachment = (string) $attachment->getDisposition();
3492 $filename = $attachment->getName();
3493 $content = $attachment->getContent();
3497 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3499 $this->errors = array_merge($this->errors, [$this->error]);
3504 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3506 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag((
string) $tickettocreate->id);
3515 $operationslog .=
'<br>Ticket already exists, so we bypass action "ticket"';
3517 } elseif ($operation[
'type'] ==
'candidature') {
3521 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3522 if ($alreadycreated == 0) {
3523 $description = $descriptiontitle;
3529 $descriptionfull = $description;
3530 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3533 $candidaturetocreate->subject = $subject;
3534 $candidaturetocreate->message = $description;
3535 $candidaturetocreate->type_code = 0;
3536 $candidaturetocreate->category_code =
null;
3537 $candidaturetocreate->severity_code =
null;
3538 $candidaturetocreate->email = $from;
3540 $candidaturetocreate->fk_user_creat = $user->id;
3541 $candidaturetocreate->date_creation =
dol_now();
3542 $candidaturetocreate->fk_project = $projectstatic->id;
3543 $candidaturetocreate->description = $description;
3544 $candidaturetocreate->note_private = $descriptionfull;
3545 $candidaturetocreate->entity =
$conf->entity;
3546 $candidaturetocreate->email_msgid = $msgid;
3547 $candidaturetocreate->email_date = $dateemail;
3548 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3553 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3596 if ($errorforthisaction) {
3600 $result = $candidaturetocreate->create($user);
3603 $this->error =
'Failed to create candidature: '.implode(
', ', $candidaturetocreate->errors);
3604 $this->errors = $candidaturetocreate->errors;
3607 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag((
string) $candidaturetocreate->id);
3610 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3613 if (!is_object($hookmanager)) {
3614 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3617 $hookmanager->initHooks([
'emailcolector']);
3619 $parameters = array(
3620 'connection' => $connection,
3621 'imapemail' => $imapemail,
3622 'overview' => $overview,
3625 'fromtext' => $fromtext,
3627 'actionparam' => $operation[
'actionparam'],
3629 'thirdpartyid' => $thirdpartyid,
3630 'objectid' => $objectid,
3631 'objectemail' => $objectemail,
3633 'messagetext' => $messagetext,
3634 'subject' => $subject,
3635 'header' => $header,
3636 'attachments' => $attachments,
3638 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3641 $errorforthisaction++;
3642 $this->error = $hookmanager->resPrint;
3644 if ($errorforthisaction) {
3646 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3648 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3652 if (!$errorforactions) {
3653 $nbactiondoneforemail++;
3659 if (!$errorforactions) {
3660 if (!empty($targetdir)) {
3663 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3664 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid.
' - '.$imapemail->getHeader()->get(
'subject').
' to '.$targetdir;
3666 $arrayofemailtodelete[$this->
uidAsString($imapemail)] = $imapemail;
3669 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3670 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3672 $arrayofemailtodelete[$imapemail] = $msgid;
3677 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);
3679 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3687 unset($objectemail);
3688 unset($projectstatic);
3689 unset($thirdpartystatic);
3690 unset($contactstatic);
3692 $nbemailprocessed++;
3694 if (!$errorforemail) {
3695 $nbactiondone += $nbactiondoneforemail;
3699 $this->db->commit();
3701 $this->db->rollback();
3705 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3706 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3707 $datelastok = strtotime($headers[
'Date']);
3713 $this->db->rollback();
3717 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3719 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3721 $langs->load(
"admin");
3722 $output = $langs->trans(
'NoNewEmailToProcess');
3723 $output .=
' (defaultlang='.$langs->defaultlang.
')';
3729 krsort($arrayofemailtodelete, SORT_NUMERIC);
3731 foreach ($arrayofemailtodelete as $imapemailnum => $imapemail) {
3732 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemailnum);
3734 $operationslog .=
"<br> move email ".$imapemailnum.($mode > 0 ?
' (test)' :
'');
3736 if (empty($mode) && empty($error)) {
3737 $tmptargetdir = $targetdir;
3744 $result = $imapemail->move($tmptargetdir,
false);
3747 $operationslog .=
'<br>Exception !!!! '.$e->getMessage();
3749 if (empty($result)) {
3750 dol_syslog(
"Failed to move email into target directory ".$targetdir);
3751 $operationslog .=
'<br>Failed to move email into target directory '.$targetdir;
3757 if (empty($mode) && empty($error)) {
3759 $operationslog .=
"<br>Expunge";
3764 $client->disconnect();
3766 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
3767 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
3769 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid.($mode > 0 ?
' (test)' :
'');
3771 if (empty($mode) && empty($error)) {
3772 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
3775 $this->error = imap_last_error();
3776 $this->errors[] = $this->error;
3778 $operationslog .=
'<br>Error in move '.$this->error;
3785 if (empty($mode) && empty($error)) {
3787 $operationslog .=
"<br>Expunge";
3789 imap_expunge($connection);
3791 imap_close($connection);
3794 $this->datelastresult = $now;
3795 $this->lastresult = $output;
3797 $this->debuginfo .=
'IMAP search array used : '.$search;
3799 $this->debuginfo .=
'IMAP search string used : '.$search;
3802 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
3804 if ($operationslog) {
3805 $this->debuginfo .= $operationslog;
3808 if (empty($error) && empty($mode)) {
3809 $this->datelastok = $datelastok;
3812 if (!empty($this->errors)) {
3813 $this->lastresult .=
"<br>".implode(
"<br>", $this->errors);
3815 $this->codelastresult = ($error ?
'KO' :
'OK');
3821 dol_syslog(
"EmailCollector::doCollectOneCollector end error=".$error, LOG_INFO);
3823 return $error ? -1 : 1;
3838 private function getmsg($mbox, $mid, $destdir =
''): int
3842 global $charset, $htmlmsg, $plainmsg, $attachments;
3843 $htmlmsg = $plainmsg = $charset =
'';
3844 $attachments = array();
3851 $s = imap_fetchstructure($mbox, $mid, FT_UID);
3853 $this->errors = array_merge($this->errors, [imap_last_error()]);
3857 if (empty($s->parts)) {
3859 $this->
getpart($mbox, $mid, $s,
'0');
3862 foreach ($s->parts as $partno0 => $p) {
3863 $this->
getpart($mbox, $mid, $p, (
string) ($partno0 + 1), $destdir);
3896 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
3899 global $htmlmsg, $plainmsg, $charset, $attachments;
3903 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
3904 imap_body($mbox, $mid, FT_UID);
3906 if ($p->encoding == 4) {
3907 $data = quoted_printable_decode($data);
3908 } elseif ($p->encoding == 3) {
3909 $data = base64_decode($data);
3915 if ($p->parameters) {
3916 foreach ($p->parameters as $x) {
3917 $params[strtolower($x->attribute)] = $x->value;
3920 if (!empty($p->dparameters)) {
3921 foreach ($p->dparameters as $x) {
3922 $params[strtolower($x->attribute)] = $x->value;
3925 '@phan-var-force array{filename?:string,name?:string,charset?:string} $params';
3930 if (!empty($params[
'filename']) || !empty($params[
'name'])) {
3932 $filename = $params[
'filename'] ?? $params[
'name'];
3934 $attachments[$filename] = $data;
3936 if (strlen($destdir)) {
3937 if (substr($destdir, -1) !=
'/') {
3942 $file_name_complete = $filename;
3943 $destination = $destdir.$file_name_complete;
3946 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
3949 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
3952 $file_name_original = $file_name;
3961 while (file_exists($destdir.$file_name.
".".$extension)) {
3962 $file_name = $file_name_original .
' (' . $num .
')';
3963 $file_name_complete = $file_name .
"." . $extension;
3964 $destination = $destdir.$file_name_complete;
3970 file_put_contents($destination, $data);
3975 if ($p->type == 0 && $data) {
3976 if (!empty($params[
'charset'])) {
3981 if (strtolower($p->subtype) ==
'plain') {
3982 $plainmsg .= trim($data).
"\n\n";
3984 $htmlmsg .= $data.
"<br><br>";
3986 $charset = $params[
'charset'];
3987 } elseif ($p->type == 2 && $data) {
3993 if (!empty($params[
'charset'])) {
3996 $plainmsg .= $data.
"\n\n";
4000 if (!empty($p->parts)) {
4001 foreach ($p->parts as $partno0 => $p2) {
4002 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1), $destdir);
4018 if (!$string || $fromEncoding == $toEncoding) {
4021 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
4022 if (!$convertedString && extension_loaded(
'mbstring')) {
4023 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
4025 if (!$convertedString) {
4026 throw new Exception(
'Mime string encoding conversion failed');
4028 return $convertedString;
4047 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
4048 $elements = imap_mime_header_decode($subject);
4050 if (!empty($elements)) {
4051 $num = count($elements);
4052 for ($i = 0; $i < $num; $i++) {
4053 $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));
4054 $newstring .= $stringinutf8;
4056 $subject = $newstring;
4058 } elseif (!function_exists(
'mb_decode_mimeheader')) {
4059 $subject = mb_decode_mimeheader($subject);
4060 } elseif (function_exists(
'iconv_mime_decode')) {
4061 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
4077 require_once DOL_DOCUMENT_ROOT .
'/core/lib/images.lib.php';
4080 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
4081 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
4082 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
4083 $maxheightmini = $tmparraysize[
'maxheightmini'];
4084 $quality = $tmparraysize[
'quality'];
4086 file_put_contents($destdir.
'/'.$filename, $content);
4089 vignette($destdir.
'/'.$filename, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
4091 vignette($destdir.
'/'.$filename, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
4104 if (is_object($imapemail)) {
4105 return $imapemail->getAttributes()[
"uid"];
4107 return (
string) $imapemail;