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)
520 $sql =
"SELECT s.rowid";
521 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
522 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
524 $sql .=
" AND s.status = 1";
526 $sql .= $this->db->order($sortfield, $sortorder);
531 $offset = $limit * $page;
533 $sql .= $this->db->plimit($limit + 1, $offset);
536 $result = $this->db->query($sql);
538 $num = $this->db->num_rows($result);
541 $obj = $this->db->fetch_object($result);
543 if ($emailcollector_static->fetch($obj->rowid)) {
544 $obj_ret[] = $emailcollector_static;
549 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
550 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
553 if (!count($obj_ret)) {
554 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
572 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
573 $langs->load(
"errors");
574 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
578 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
579 $this->password =
dolEncrypt($this->password);
583 $this->password =
dolDecrypt($this->password);
595 public function delete(
User $user, $notrigger = 0)
610 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
612 global $conf, $langs, $action, $hookmanager;
614 if (!empty($conf->dol_no_mouse_hover)) {
620 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
622 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
624 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
626 if ($option !=
'nolink') {
628 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
629 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
630 $add_save_lastsearch_values = 1;
632 if ($add_save_lastsearch_values) {
633 $url .=
'&save_lastsearch_values=1';
638 if (empty($notooltip)) {
640 $label = $langs->trans(
"ShowEmailCollector");
641 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
643 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
644 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
646 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
649 $linkstart =
'<a href="'.$url.
'"';
650 $linkstart .= $linkclose.
'>';
653 $result .= $linkstart;
655 $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);
657 if ($withpicto != 2) {
658 $result .= $this->ref;
663 $hookmanager->initHooks(array(
'emailcollectordao'));
664 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result);
665 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
667 $result = $hookmanager->resPrint;
669 $result .= $hookmanager->resPrint;
697 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
700 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
701 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
702 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
703 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
706 $statusType =
'status5';
707 if ($status == self::STATUS_ENABLED) {
708 $statusType =
'status4';
711 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
722 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
723 $sql .=
' fk_user_creat, fk_user_modif';
724 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
725 $sql .=
' WHERE t.rowid = '.((int) $id);
726 $result = $this->db->query($sql);
728 if ($this->db->num_rows($result)) {
729 $obj = $this->db->fetch_object($result);
731 $this->
id = $obj->rowid;
733 $this->user_creation_id = $obj->fk_user_creat;
734 $this->user_modification_id = $obj->fk_user_modif;
735 $this->date_creation = $this->db->jdate($obj->datec);
736 $this->date_modification = empty($obj->datem) ?
'' : $this->db->jdate($obj->datem);
739 $this->db->free($result);
753 $this->host =
'localhost';
754 $this->login =
'alogin';
767 $this->filters = array();
769 $sql =
'SELECT rowid, type, rulevalue, status';
770 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
771 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
774 $resql = $this->db->query($sql);
776 $num = $this->db->num_rows($resql);
779 $obj = $this->db->fetch_object($resql);
780 $this->filters[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'rulevalue' => $obj->rulevalue,
'status' => $obj->status);
783 $this->db->free($resql);
799 $this->actions = array();
801 $sql =
'SELECT rowid, type, actionparam, status';
802 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
803 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
804 $sql .=
' ORDER BY position';
806 $resql = $this->db->query($sql);
808 $num = $this->db->num_rows($resql);
811 $obj = $this->db->fetch_object($resql);
812 $this->actions[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'actionparam' => $obj->actionparam,
'status' => $obj->status);
815 $this->db->free($resql);
834 $flags =
'/service=imap';
837 } elseif (empty($this->imap_encryption) || ($this->imap_encryption ==
'ssl' &&
getDolGlobalString(
'IMAP_FORCE_NOSSL'))) {
840 $flags .=
'/' . $this->imap_encryption;
843 $flags .=
'/novalidate-cert';
850 if (!empty($this->login) && strpos($this->login,
'/') !=
false) {
851 $partofauth = explode(
'/', $this->login);
852 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
855 $connectstringserver =
'{'.$this->host.
':'.$this->port.$flags.
'}';
857 return $connectstringserver;
868 if (function_exists(
'mb_convert_encoding')) {
870 $str = preg_replace(
"/ /",
"xxxSPACExxx", $str);
871 $str = preg_replace(
"/\[Gmail\]/",
"xxxGMAILxxx", $str);
873 if ($str = mb_convert_encoding($str,
"UTF-7")) {
875 $str = preg_replace(
"/\+A/",
"&A", $str);
877 $str = preg_replace(
"/xxxSPACExxx/",
" ", $str);
879 $str = preg_replace(
"/xxxGMAILxxx/",
"[Gmail]", $str);
883 $this->error =
"error: is not possible to encode this string '".$str.
"'";
903 $arrayofcollectors = $this->
fetchAll($user, 1);
906 foreach ($arrayofcollectors as $emailcollector) {
907 $result = $emailcollector->doCollectOneCollector(0);
908 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
910 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
911 if (!empty($emailcollector->errors)) {
912 $this->error .= implode(
'<br>', $emailcollector->errors);
914 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
933 global $conf, $langs;
935 $errorforthisaction = 0;
938 $outputlangs = $langs;
941 $newlang =
GETPOST(
'lang_id',
'aZ09');
944 $newlang = !empty(
$object->thirdparty->default_lang) ?
$object->thirdparty->default_lang : $newlang;
946 if (!empty($newlang)) {
948 $outputlangs->setDefaultLang($newlang);
958 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
961 $tmparray = explode(
'.', $propertytooverwrite);
962 if (count($tmparray) == 2) {
963 $tmpclass = $tmparray[0];
964 $tmpproperty = $tmparray[1];
966 $tmpproperty = $tmparray[0];
968 if ($tmpclass && ($tmpclass !=
$object->element)) {
978 $regforregex = array();
979 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
980 $sourcefield = $regforregex[1];
981 $regexstring = $regforregex[2];
983 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
984 $sourcefield = $regforregex[1];
985 $regexstring = $regforregex[2];
988 if (!empty($sourcefield) && !empty($regexstring)) {
989 if (strtolower($sourcefield) ==
'body') {
990 $sourcestring = $messagetext;
991 } elseif (strtolower($sourcefield) ==
'subject') {
992 $sourcestring = $subject;
993 } elseif (strtolower($sourcefield) ==
'header') {
994 $sourcestring = $header;
998 $regforval = array();
1000 if (strtolower($sourcefield) ==
'body') {
1001 $regexoptions =
'ms';
1003 if (strtolower($sourcefield) ==
'header') {
1004 $regexoptions =
'm';
1008 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
1010 $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
1011 if (strtolower($sourcefield) ==
'header') {
1012 if (preg_match(
'/^options_/', $tmpproperty)) {
1015 if (property_exists(
$object, $tmpproperty)) {
1022 if (preg_match(
'/^options_/', $tmpproperty)) {
1025 if (property_exists(
$object, $tmpproperty)) {
1032 if (preg_match(
'/^options_/', $tmpproperty)) {
1033 $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));
1035 if (property_exists(
$object, $tmpproperty)) {
1043 if (property_exists(
$object, $tmpproperty)) {
1046 $tmp[$tmpproperty] =
null;
1049 $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.';
1053 $errorforthisaction++;
1054 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1055 $this->errors[] = $this->error;
1057 $operationslog .=
'<br>'.$this->error;
1059 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1061 if (preg_match(
'/^options_/', $tmpproperty)) {
1062 $valuecurrent =
$object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1064 if (property_exists(
$object, $tmpproperty)) {
1065 $valuecurrent =
$object->$tmpproperty;
1068 $valuecurrent = $tmp[$tmpproperty];
1072 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1073 $valuetouse = $regforregex[2];
1076 $matcharray = array();
1077 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1079 if (is_array($matcharray[1])) {
1080 foreach ($matcharray[1] as $keytoreplace) {
1081 if ($keytoreplace) {
1082 if (preg_match(
'/^options_/', $keytoreplace)) {
1083 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1085 if (property_exists(
$object, $keytoreplace)) {
1086 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->$keytoreplace;
1089 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1099 if (preg_match(
'/^options_/', $tmpproperty)) {
1100 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1102 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1104 if (property_exists(
$object, $tmpproperty)) {
1105 $object->$tmpproperty = $valuetouse;
1107 $tmp[$tmpproperty] = $valuetouse;
1110 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1114 $errorforthisaction++;
1115 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1116 $this->errors[] = $this->error;
1121 return $errorforthisaction;
1130 public function doCollectOneCollector($mode = 0)
1132 global $db, $conf, $langs, $user;
1133 global $hookmanager;
1137 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1139 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1142 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1144 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1149 $this->debuginfo =
'';
1153 $searchfilterdoltrackid = 0;
1154 $searchfilternodoltrackid = 0;
1155 $searchfilterisanswer = 0;
1156 $searchfilterisnotanswer = 0;
1157 $searchfilterreplyto = 0;
1158 $searchfilterexcludebodyarray = array();
1159 $searchfilterexcludesubjectarray = array();
1160 $operationslog =
'';
1161 $rulesreplyto = array();
1162 $connectstringsource =
'';
1163 $connectstringtarget =
'';
1164 $connection =
false;
1165 $arrayofemail = array();
1169 if (empty($this->host)) {
1170 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1173 if (empty($this->login)) {
1174 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1177 if (empty($this->source_directory)) {
1178 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1182 $sourcedir = $this->source_directory;
1183 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1188 $sourcedir = $this->source_directory;
1189 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1192 if ($this->acces_type == 1) {
1194 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>';
1196 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1200 $keyforsupportedoauth2array = $this->oauth_service;
1201 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1202 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1204 $keyforprovider =
'';
1206 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', strtoupper($keyforsupportedoauth2array));
1207 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1209 if (!empty($supportedoauth2array)) {
1210 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1211 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1212 $OAUTH_SERVICENAME = $nameofservice;
1214 $OAUTH_SERVICENAME =
'Unknown';
1217 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1219 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1225 $storage =
new DoliStorage($db, $conf, $keyforprovider,
getDolGlobalString($keyforparamtenant));
1228 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1237 if (is_object($tokenobj) && $expire) {
1238 $this->debuginfo .=
'Refresh token '.$OAUTH_SERVICENAME.
'<br>';
1239 $credentials =
new Credentials(
1244 $serviceFactory = new \OAuth\ServiceFactory();
1245 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1249 if (preg_match(
'/^Microsoft/', $OAUTH_SERVICENAME)) {
1251 $tmp = explode(
'-', $OAUTH_SERVICENAME);
1252 $scopes = explode(
',',
getDolGlobalString(
'OAUTH_'.strtoupper($tmp[0]).(empty($tmp[1]) ?
'' :
'-'.$tmp[1]).
'_SCOPE'));
1255 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $scopes);
1257 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
1259 $refreshtoken = $tokenobj->getRefreshToken();
1260 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1263 $tokenobj->setRefreshToken($refreshtoken);
1264 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1266 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1267 if (is_object($tokenobj)) {
1268 $token = $tokenobj->getAccessToken();
1270 $this->error =
"Token not found";
1275 $this->error = $e->getMessage();
1276 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1280 $cm =
new ClientManager();
1281 $client = $cm->make([
1282 'host' => $this->host,
1283 'port' => $this->port,
1284 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1285 'validate_cert' => true,
1286 'protocol' =>
'imap',
1287 'username' => $this->login,
1288 'password' => $token,
1289 'authentication' =>
"oauth",
1293 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1295 $cm =
new ClientManager();
1296 $client = $cm->make([
1297 'host' => $this->host,
1298 'port' => $this->port,
1299 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1300 'validate_cert' => true,
1301 'protocol' =>
'imap',
1302 'username' => $this->login,
1303 'password' => $this->password,
1304 'authentication' =>
"login",
1312 }
catch (ConnectionFailedException $e) {
1313 $this->error = $e->getMessage();
1314 $this->errors[] = $this->error;
1315 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1319 $host = dol_getprefix(
'email');
1322 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1324 if (!function_exists(
'imap_open')) {
1325 $this->error =
'IMAP function not enabled on your PHP';
1331 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1332 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1334 $connectstringsource = $connectstringserver.$sourcedir;
1335 $connectstringtarget = $connectstringserver.$targetdir;
1338 $this->debuginfo .=
'connectstringsource = '.$connectstringsource.
', $connectstringtarget='.$connectstringtarget.
'<br>';
1340 $connection = imap_open($connectstringsource, $this->login, $this->password);
1341 if ($connection ===
false) {
1342 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1347 $host = dol_getprefix(
'email');
1356 $criteria = array();
1359 $criteria = array(array(
'UNDELETED'));
1360 foreach ($this->filters as $rule) {
1361 if (empty($rule[
'status'])) {
1366 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1370 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1373 if ($rule[
'type'] ==
'from') {
1374 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1375 if (count($tmprulevaluearray) >= 2) {
1376 foreach ($tmprulevaluearray as $tmprulevalue) {
1377 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1380 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1383 if ($rule[
'type'] ==
'to') {
1384 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1385 if (count($tmprulevaluearray) >= 2) {
1386 foreach ($tmprulevaluearray as $tmprulevalue) {
1387 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1390 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1393 if ($rule[
'type'] ==
'bcc') {
1394 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1396 if ($rule[
'type'] ==
'cc') {
1397 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1399 if ($rule[
'type'] ==
'subject') {
1400 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1402 $searchfilterexcludesubjectarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1404 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1407 if ($rule[
'type'] ==
'body') {
1408 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1410 $searchfilterexcludebodyarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1412 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1415 if ($rule[
'type'] ==
'header') {
1416 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1428 if ($rule[
'type'] ==
'seen') {
1429 array_push($criteria, array($not.
"SEEN"));
1431 if ($rule[
'type'] ==
'unseen') {
1432 array_push($criteria, array($not.
"UNSEEN"));
1434 if ($rule[
'type'] ==
'unanswered') {
1435 array_push($criteria, array($not.
"UNANSWERED"));
1437 if ($rule[
'type'] ==
'answered') {
1438 array_push($criteria, array($not.
"ANSWERED"));
1440 if ($rule[
'type'] ==
'smaller') {
1441 array_push($criteria, array($not.
"SMALLER"));
1443 if ($rule[
'type'] ==
'larger') {
1444 array_push($criteria, array($not.
"LARGER"));
1448 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1449 $searchfilterdoltrackid++;
1450 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1452 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1453 $searchfilterdoltrackid++;
1454 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1456 if ($rule[
'type'] ==
'withtrackingid') {
1457 $searchfilterdoltrackid++;
1458 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1460 if ($rule[
'type'] ==
'withouttrackingid') {
1461 $searchfilternodoltrackid++;
1462 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1465 if ($rule[
'type'] ==
'isanswer') {
1466 $searchfilterisanswer++;
1467 $searchhead .=
'/References.*@.*/';
1469 if ($rule[
'type'] ==
'isnotanswer') {
1470 $searchfilterisnotanswer++;
1471 $searchhead .=
'! /References.*@.*/';
1474 if ($rule[
'type'] ==
'replyto') {
1475 $searchfilterreplyto++;
1476 $rulesreplyto[] = $rule[
'rulevalue'];
1477 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1481 if (empty($targetdir) || !
getDolGlobalString(
'EMAILCOLLECTOR_NO_FILTER_ON_DATE_IF_THERE_IS_A_TARGETDIR')) {
1483 if ($this->datelastok) {
1484 $fromdate = $this->datelastok;
1486 if ($fromdate > 0) {
1488 array_push($criteria, array(
"SINCE" => date(
'j-M-Y', $fromdate - 1)));
1493 dol_syslog(
"IMAP search string = ".var_export($criteria,
true));
1494 $search = var_export($criteria,
true);
1497 $search =
'UNDELETED';
1498 foreach ($this->filters as $rule) {
1499 if (empty($rule[
'status'])) {
1507 if (!empty($rule[
'rulevalue']) && strpos($rule[
'rulevalue'],
'!') === 0) {
1511 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1514 if ($rule[
'type'] ==
'from') {
1515 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1516 if (count($tmprulevaluearray) >= 2) {
1517 foreach ($tmprulevaluearray as $tmprulevalue) {
1518 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1521 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1524 if ($rule[
'type'] ==
'to') {
1525 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1526 if (count($tmprulevaluearray) >= 2) {
1527 foreach ($tmprulevaluearray as $tmprulevalue) {
1528 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1531 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1534 if ($rule[
'type'] ==
'bcc') {
1535 $search .= ($search ?
' ' :
'').$not.
'BCC';
1537 if ($rule[
'type'] ==
'cc') {
1538 $search .= ($search ?
' ' :
'').$not.
'CC';
1540 if ($rule[
'type'] ==
'subject') {
1543 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1545 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1548 if ($rule[
'type'] ==
'body') {
1551 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1554 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1557 if ($rule[
'type'] ==
'header') {
1558 $search .= ($search ?
' ' :
'').$not.
'HEADER '.$rule[
'rulevalue'];
1570 if ($rule[
'type'] ==
'seen') {
1571 $search .= ($search ?
' ' :
'').$not.
'SEEN';
1573 if ($rule[
'type'] ==
'unseen') {
1574 $search .= ($search ?
' ' :
'').$not.
'UNSEEN';
1576 if ($rule[
'type'] ==
'unanswered') {
1577 $search .= ($search ?
' ' :
'').$not.
'UNANSWERED';
1579 if ($rule[
'type'] ==
'answered') {
1580 $search .= ($search ?
' ' :
'').$not.
'ANSWERED';
1582 if ($rule[
'type'] ==
'smaller') {
1583 $search .= ($search ?
' ' :
'').$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1585 if ($rule[
'type'] ==
'larger') {
1586 $search .= ($search ?
' ' :
'').$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1590 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1591 $searchfilterdoltrackid++;
1592 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1594 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1595 $searchfilterdoltrackid++;
1596 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1598 if ($rule[
'type'] ==
'withtrackingid') {
1599 $searchfilterdoltrackid++;
1600 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1602 if ($rule[
'type'] ==
'withouttrackingid') {
1603 $searchfilternodoltrackid++;
1604 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1607 if ($rule[
'type'] ==
'isanswer') {
1608 $searchfilterisanswer++;
1609 $searchhead .=
'/References.*@.*/';
1611 if ($rule[
'type'] ==
'isnotanswer') {
1612 $searchfilterisnotanswer++;
1613 $searchhead .=
'! /References.*@.*/';
1616 if ($rule[
'type'] ==
'replyto') {
1617 $searchfilterreplyto++;
1618 $rulesreplyto[] = $rule[
'rulevalue'];
1619 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1623 if (empty($targetdir)) {
1625 if ($this->datelastok) {
1626 $fromdate = $this->datelastok;
1628 if ($fromdate > 0) {
1629 $search .= ($search ?
' ' :
'').
'SINCE '.date(
'j-M-Y', $fromdate - 1);
1638 $nbemailprocessed = 0;
1641 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1642 $arrayofemail = array();
1649 $tmpsourcedir = $sourcedir;
1654 $f = $client->getFolders(
false, $tmpsourcedir);
1657 if ($folder instanceof Webklex\PHPIMAP\Folder) {
1658 $Query = $folder->messages()->where($criteria);
1661 $this->error =
"Source directory ".$sourcedir.
" not found";
1662 $this->errors[] = $this->error;
1663 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_WARNING);
1668 $this->error =
"Failed to execute getfolders";
1669 $this->errors[] = $this->error;
1670 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1673 }
catch (InvalidWhereQueryCriteriaException $e) {
1674 $this->error = $e->getMessage();
1675 $this->errors[] = $this->error;
1676 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1679 $this->error = $e->getMessage();
1680 $this->errors[] = $this->error;
1681 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1685 '@phan-var-force Webklex\PHPIMAP\Query\Query $Query';
1689 $Query->leaveUnread();
1691 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1692 dol_syslog(
"EmailCollector::doCollectOneCollector nb arrayofemail ".(is_array($arrayofemail) ? count($arrayofemail) :
'Not array'));
1695 $this->error = $e->getMessage();
1696 $this->errors[] = $this->error;
1697 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1700 } elseif ($connection !==
false) {
1702 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1704 if ($arrayofemail ===
false) {
1706 $mapoferrrors = imap_errors();
1707 if ($mapoferrrors !==
false) {
1709 $this->error =
"Search string not understood - ".implode(
',', $mapoferrrors);
1710 $this->errors[] = $this->error;
1715 $arrayofemailtodelete = array();
1718 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0 && $connection !==
false) {
1735 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1737 $richarrayofemail = array();
1739 foreach ($arrayofemail as $imapemail) {
1740 if ($nbemailprocessed > 1000) {
1746 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1747 $header = $imapemail->getHeader()->raw;
1748 $overview = $imapemail->getAttributes();
1750 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1751 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1754 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1757 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)(\r\n|\s$)/m', $header, $matches);
1758 $headers = array_combine($matches[1], $matches[2]);
1761 $richarrayofemail[] = array(
'imapemail' => $imapemail,
'header' => $header,
'headers' => $headers,
'overview' => $overview,
'date' => strtotime($headers[
'Date']));
1766 $richarrayofemail =
dol_sort_array($richarrayofemail,
'date',
'asc');
1770 foreach ($richarrayofemail as $tmpval) {
1773 $imapemail = $tmpval[
'imapemail'];
1774 $header = $tmpval[
'header'];
1775 $overview = $tmpval[
'overview'];
1776 $headers = $tmpval[
'headers'];
1778 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1779 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1781 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1782 $headers[
'References'] = $headers[
'references'];
1784 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1785 $headers[
'Message-ID'] = $headers[
'message-id'];
1787 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1788 $headers[
'Subject'] = $headers[
'subject'];
1794 $emailto = (string) $overview[
'to'];
1801 $operationslog .=
'<br>** Process email #'.dol_escape_htmltag((
string) $iforemailloop);
1805 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1807 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1809 $operationslog .=
" - ".dol_escape_htmltag((
string) $imapemail);
1810 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1812 $operationslog .=
" - MsgId: ".$msgid;
1813 $operationslog .=
" - Date: ".($headers[
'Date'] ?? $langs->transnoentitiesnoconv(
"NotFound"));
1814 $operationslog .=
" - References: ".dol_escape_htmltag($headers[
'References'] ?? $langs->transnoentitiesnoconv(
"NotFound")).
" - Subject: ".
dol_escape_htmltag($headers[
'Subject']);
1816 dol_syslog(
"-- Process email #".$iforemailloop.
", MsgId: ".$msgid.
", Date: ".($headers[
'Date'] ??
'').
", References: ".($headers[
'References'] ??
'').
", Subject: ".$headers[
'Subject']);
1819 $trackidfoundintorecipienttype =
'';
1820 $trackidfoundintorecipientid = 0;
1825 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)) {
1826 $trackidfoundintorecipienttype = $reg[1];
1827 $trackidfoundintorecipientid = $reg[2];
1828 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1829 $trackidfoundintorecipienttype =
'emailing';
1830 $trackidfoundintorecipientid = $reg[1];
1833 $trackidfoundintomsgidtype =
'';
1834 $trackidfoundintomsgidid = 0;
1839 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)) {
1840 $trackidfoundintomsgidtype = $reg[1];
1841 $trackidfoundintomsgidid = $reg[2];
1842 } elseif (preg_match(
'/(?:[\+\-])emailing-(\w+)@/', $msgid, $reg)) {
1843 $trackidfoundintomsgidtype =
'emailing';
1844 $trackidfoundintomsgidid = $reg[1];
1848 if ($searchfilterdoltrackid > 0) {
1849 if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) {
1850 if (empty($headers[
'References']) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References'])) {
1851 $nbemailprocessed++;
1852 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");
1857 if ($searchfilternodoltrackid > 0) {
1858 if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($headers[
'References']) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))) {
1859 $nbemailprocessed++;
1860 dol_syslog(
" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
1865 if ($searchfilterisanswer > 0) {
1866 if (empty($headers[
'In-Reply-To'])) {
1867 $nbemailprocessed++;
1868 dol_syslog(
" Discarded - Email is not an answer (no In-Reply-To header)");
1872 if (preg_match(
'/^(Re|AW)\s*:\s+/i', $headers[
'Subject'])) {
1878 if (!empty($headers[
'In-Reply-To'])) {
1886 $nbemailprocessed++;
1887 dol_syslog(
" Discarded - Email is not an answer (no RE prefix in subject)");
1891 if ($searchfilterisnotanswer > 0) {
1892 if (!empty($headers[
'In-Reply-To'])) {
1896 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) {
1902 $nbemailprocessed++;
1903 dol_syslog(
" Discarded - Email is an answer");
1908 if ($searchfilterreplyto > 0) {
1909 if (!empty($headers[
'Reply-To'])) {
1911 foreach ($rulesreplyto as $key => $rulereplyto) {
1912 if (preg_match(
'/'.preg_quote($rulereplyto,
'/').
'/', $headers[
'Reply-To'])) {
1917 if (!$isreplytook || $isreplytook != count($rulesreplyto)) {
1918 $nbemailprocessed++;
1919 dol_syslog(
" Discarded - Reply-to does not match");
1927 $thirdpartystatic =
new Societe($this->db);
1928 $contactstatic =
new Contact($this->db);
1929 $projectstatic =
new Project($this->db);
1931 $nbactiondoneforemail = 0;
1933 $errorforactions = 0;
1934 $thirdpartyfoundby =
'';
1935 $contactfoundby =
'';
1936 $projectfoundby =
'';
1937 $ticketfoundby =
'';
1938 $candidaturefoundby =
'';
1942 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".
dol_print_date($overview[
'date'],
'dayrfc',
'gmt').
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
1947 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);
1957 global $htmlmsg, $plainmsg, $charset, $attachments;
1961 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1962 if ($imapemail->hasHTMLBody()) {
1963 $htmlmsg = $imapemail->getHTMLBody();
1965 if ($imapemail->hasTextBody()) {
1966 $plainmsg = $imapemail->getTextBody();
1968 if ($imapemail->hasAttachments()) {
1969 $attachments = $imapemail->getAttachments()->all();
1974 $this->
getmsg($connection, $imapemail);
1976 '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments';
1988 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
1989 dol_syslog(
" Discarded - Email body is not valid utf8");
1993 if (!empty($searchfilterexcludebodyarray)) {
1994 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
1995 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
1996 $nbemailprocessed++;
1997 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
1998 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
2060 $replytostring =
'';
2063 $fromstring = $overview[
'from'];
2064 $replytostring = empty($overview[
'in_reply-to']) ? $headers[
'Reply-To'] : $overview[
'in_reply-to'];
2066 $sender = $overview[
'sender'];
2067 $to = $overview[
'to'];
2068 $sendtocc = empty($overview[
'cc']) ?
'' : $overview[
'cc'];
2069 $sendtobcc = empty($overview[
'bcc']) ?
'' : $overview[
'bcc'];
2071 $tmpdate = $overview[
'date']->toDate();
2072 $tmptimezone = $tmpdate->getTimezone()->getName();
2075 if (preg_match(
'/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) {
2076 if ($reg[1] ==
'+' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2077 $dateemail -= (3600 * (int) $reg[2]);
2078 $dateemail -= (60 * (int) $reg[3]);
2080 if ($reg[1] ==
'-' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2081 $dateemail += (3600 * (int) $reg[2]);
2082 $dateemail += (60 * (int) $reg[3]);
2085 $subject = $overview[
'subject'];
2087 $fromstring = $overview[0]->from;
2088 $replytostring = (!empty($overview[
'in_reply-to']) ? $overview[
'in_reply-to'] : (!empty($headers[
'Reply-To']) ? $headers[
'Reply-To'] :
"")) ;
2090 $sender = !empty($overview[0]->sender) ? $overview[0]->sender :
'';
2091 $to = $overview[0]->to;
2092 $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc :
'';
2093 $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc :
'';
2095 $subject = $overview[0]->subject;
2099 if (!empty($searchfilterexcludesubjectarray)) {
2100 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
2101 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
2102 $nbemailprocessed++;
2103 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
2104 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
2111 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
2113 $fromtext = $reg[1];
2115 $from = $fromstring;
2118 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
2120 $replytotext = $reg[1];
2122 $replyto = $replytostring;
2126 $fk_element_type =
'';
2143 $objectemail =
null;
2146 $arrayofreferences = array();
2147 if (!empty($headers[
'References'])) {
2148 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
2150 if (!in_array(
'<'.$msgid.
'>', $arrayofreferences)) {
2151 $arrayofreferences = array_merge($arrayofreferences, array(
'<'.$msgid.
'>'));
2156 foreach ($arrayofreferences as $reference) {
2158 if (!empty($trackidfoundintorecipienttype)) {
2159 $resultsearchtrackid = -1;
2160 $reg[1] = $trackidfoundintorecipienttype;
2161 $reg[2] = $trackidfoundintorecipientid;
2162 } elseif (!empty($trackidfoundintomsgidtype)) {
2163 $resultsearchtrackid = -1;
2164 $reg[1] = $trackidfoundintomsgidtype;
2165 $reg[2] = $trackidfoundintomsgidid;
2167 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
2168 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2169 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
2173 if (!empty($resultsearchtrackid)) {
2175 $trackid = $reg[1].$reg[2];
2177 $objectid = $reg[2];
2179 if ($reg[1] ==
'thi') {
2180 $objectemail =
new Societe($this->db);
2182 if ($reg[1] ==
'ctc') {
2183 $objectemail =
new Contact($this->db);
2185 if ($reg[1] ==
'inv') {
2186 $objectemail =
new Facture($this->db);
2188 if ($reg[1] ==
'sinv') {
2191 if ($reg[1] ==
'pro') {
2192 $objectemail =
new Propal($this->db);
2194 if ($reg[1] ==
'ord') {
2195 $objectemail =
new Commande($this->db);
2197 if ($reg[1] ==
'shi') {
2200 if ($reg[1] ==
'spro') {
2203 if ($reg[1] ==
'sord') {
2206 if ($reg[1] ==
'rec') {
2207 $objectemail =
new Reception($this->db);
2209 if ($reg[1] ==
'proj') {
2210 $objectemail =
new Project($this->db);
2211 $projectfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2213 if ($reg[1] ==
'tas') {
2214 $objectemail =
new Task($this->db);
2216 if ($reg[1] ==
'con') {
2217 $objectemail =
new Contact($this->db);
2219 if ($reg[1] ==
'use') {
2220 $objectemail =
new User($this->db);
2222 if ($reg[1] ==
'tic') {
2223 $objectemail =
new Ticket($this->db);
2224 $ticketfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2226 if ($reg[1] ==
'recruitmentcandidature') {
2228 $candidaturefoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2230 if ($reg[1] ==
'mem') {
2231 $objectemail =
new Adherent($this->db);
2239 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
2241 if (is_null($objectemail) && isModEnabled(
'ticket')) {
2242 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket";
2243 $sql .=
" WHERE email_msgid = '".$this->db->escape($reg[1]).
"' OR origin_references like '%".$this->db->escape($this->db->escapeforlike($reg[1])).
"%'";
2244 $resql = $this->db->query($sql);
2246 $obj = $this->db->fetch_object($resql);
2248 $objectid = $obj->rowid;
2249 $objectemail =
new Ticket($this->db);
2250 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2257 if (!is_object($objectemail) && isModEnabled(
'project')) {
2258 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2259 $resql = $this->db->query($sql);
2261 $obj = $this->db->fetch_object($resql);
2263 $objectid = $obj->rowid;
2264 $objectemail =
new Project($this->db);
2265 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2272 if (!is_object($objectemail) && isModEnabled(
'recruitment')) {
2273 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2274 $resql = $this->db->query($sql);
2276 $obj = $this->db->fetch_object($resql);
2278 $objectid = $obj->rowid;
2280 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2289 if (is_object($objectemail)) {
2290 $result = $objectemail->fetch($objectid);
2292 $fk_element_id = $objectemail->id;
2293 $fk_element_type = $objectemail->element;
2295 if ($fk_element_type ==
'facture') {
2296 $fk_element_type =
'invoice';
2299 if (get_class($objectemail) !=
'Societe') {
2300 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2302 $thirdpartyid = $objectemail->id;
2305 if (get_class($objectemail) !=
'Contact') {
2306 $contactid = $objectemail->fk_socpeople;
2308 $contactid = $objectemail->id;
2311 if (get_class($objectemail) !=
'Project') {
2312 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2314 $projectid = $objectemail->id;
2317 if ($objectemail instanceof
Ticket) {
2318 $ticketid = $objectemail->id;
2320 $changeonticket_references =
false;
2321 if (empty($trackid)) {
2322 $trackid = $objectemail->track_id;
2324 if (empty($objectemail->origin_references)) {
2325 $objectemail->origin_references = $headers[
'References'];
2326 $changeonticket_references =
true;
2328 foreach ($arrayofreferences as $key => $referencetmp) {
2329 if (!str_contains($objectemail->origin_references, $referencetmp)) {
2330 $objectemail->origin_references .=
" ".$referencetmp;
2331 $changeonticket_references =
true;
2335 if ($changeonticket_references) {
2336 $objectemail->update($user, 1);
2343 if ($projectid > 0) {
2344 $result = $projectstatic->fetch($projectid);
2346 $projectstatic->id = 0;
2348 $projectid = $projectstatic->id;
2350 $projectfoundby =
'trackid ('.$trackid.
')';
2352 if (empty($contactid)) {
2353 $contactid = $projectstatic->fk_contact;
2355 if (empty($thirdpartyid)) {
2356 $thirdpartyid = $projectstatic->fk_soc;
2361 if ($contactid > 0) {
2362 $result = $contactstatic->fetch($contactid);
2364 $contactstatic->id = 0;
2366 $contactid = $contactstatic->id;
2368 $contactfoundby =
'trackid ('.$trackid.
')';
2370 if (empty($thirdpartyid)) {
2371 $thirdpartyid = $contactstatic->fk_soc;
2376 if ($thirdpartyid > 0) {
2377 $result = $thirdpartystatic->fetch($thirdpartyid);
2379 $thirdpartystatic->id = 0;
2381 $thirdpartyid = $thirdpartystatic->id;
2383 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2388 if (is_object($objectemail)) {
2393 if (empty($contactid)) {
2394 $result = $contactstatic->fetch(0,
null,
'', $from);
2397 dol_syslog(
"We found a contact with the email ".$from);
2398 $contactid = $contactstatic->id;
2399 $contactfoundby =
'email of contact ('.$from.
')';
2400 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2401 $result = $thirdpartystatic->fetch($contactstatic->socid);
2403 $thirdpartyid = $thirdpartystatic->id;
2404 $thirdpartyfoundby =
'email of contact ('.$from.
')';
2410 if (empty($thirdpartyid)) {
2411 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
2413 dol_syslog(
"We found a thirdparty with the email ".$from);
2414 $thirdpartyid = $thirdpartystatic->id;
2415 $thirdpartyfoundby =
'email ('.$from.
')';
2451 foreach ($this->actions as $operation) {
2452 $errorforthisaction = 0;
2453 $ticketalreadyexists = 0;
2454 if ($errorforactions) {
2457 if (empty($operation[
'status'])) {
2461 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2464 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2465 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2468 $actioncode =
'EMAIL_IN';
2470 if (preg_match(
'/Sent$/', $sourcedir) || preg_match(
'/envoyés$/i', $sourcedir)) {
2471 $actioncode =
'EMAIL';
2474 $arrayofemailtoconsideresender = explode(
',',
getDolGlobalString(
'MAIL_FROM_EMAILS_TO_CONSIDER_SENDING'));
2475 foreach ($arrayofemailtoconsideresender as $emailtoconsidersender) {
2476 if (preg_match(
'/'.preg_quote($emailtoconsidersender,
'/').
'/', $fromstring)) {
2477 $actioncode =
'EMAIL';
2480 $operationslog .=
'<br>Email will have actioncode='.$actioncode;
2482 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2484 $descriptiontitle = $langs->transnoentitiesnoconv(
"RecordCreatedByEmailCollector", $this->
ref);
2489 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2491 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2493 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2495 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailReply").($langs->trans(
"MailReply") !=
'Reply to' ?
' (Reply to)' :
'').
' : '.
dol_escape_htmltag($replyto));
2498 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2501 if ($operation[
'type'] ==
'ticket') {
2503 $tickettocreate =
new Ticket($this->db);
2504 $errorfetchticket = 0;
2505 $alreadycreated = 0;
2506 if (!empty($trackid)) {
2507 $alreadycreated = $tickettocreate->fetch(0,
'', $trackid);
2509 if ($alreadycreated == 0 && !empty($msgid)) {
2510 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2512 if ($alreadycreated < 0) {
2513 $errorfetchticket++;
2515 if (empty($errorfetchticket)) {
2516 if ($alreadycreated == 0) {
2517 $operationslog .=
'<br>Ticket not found using trackid='.$trackid.
' or msgid='.$msgid;
2518 $ticketalreadyexists = 0;
2520 $operationslog .=
'<br>Ticket already found using trackid='.$trackid.
' or msgid='.$msgid;
2521 $ticketalreadyexists = 1;
2522 $operation[
'type'] =
'recordevent';
2525 $ticketalreadyexists = -1;
2532 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2533 if (empty($operation[
'actionparam'])) {
2535 $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;";
2536 $this->errors[] = $this->error;
2538 $actionparam = $operation[
'actionparam'];
2539 $idtouseforthirdparty =
'';
2540 $nametouseforthirdparty =
'';
2541 $emailtouseforthirdparty =
'';
2542 $namealiastouseforthirdparty =
'';
2544 $operationslog .=
'<br>Loop on each property to set into actionparam';
2548 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2552 $regforregex = array();
2554 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2555 $sourcefield = $regforregex[1];
2556 $regexstring = $regforregex[2];
2559 if (!empty($sourcefield) && !empty($regexstring)) {
2560 if (strtolower($sourcefield) ==
'body') {
2561 $sourcestring = $messagetext;
2562 } elseif (strtolower($sourcefield) ==
'subject') {
2563 $sourcestring = $subject;
2564 } elseif (strtolower($sourcefield) ==
'header') {
2565 $sourcestring = $header;
2568 if ($sourcestring) {
2569 $regforval = array();
2571 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2574 if ($propertytooverwrite ==
'id') {
2575 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2577 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2578 } elseif ($propertytooverwrite ==
'email') {
2579 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2581 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2582 } elseif ($propertytooverwrite ==
'name') {
2583 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2585 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2586 } elseif ($propertytooverwrite ==
'name_alias') {
2587 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2589 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2591 $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';
2595 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2596 $idtouseforthirdparty =
null;
2597 $nametouseforthirdparty =
null;
2598 $emailtouseforthirdparty =
null;
2599 $namealiastouseforthirdparty =
null;
2601 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2603 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2610 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2611 $this->errors[] = $this->error;
2613 $operationslog .=
'<br>'.$this->error;
2615 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2619 if ($propertytooverwrite ==
'id') {
2620 $idtouseforthirdparty = $reg[2];
2622 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2623 } elseif ($propertytooverwrite ==
'email') {
2624 $emailtouseforthirdparty = $reg[2];
2626 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2627 } elseif ($propertytooverwrite ==
'name') {
2628 $nametouseforthirdparty = $reg[2];
2630 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2631 } elseif ($propertytooverwrite ==
'name_alias') {
2632 $namealiastouseforthirdparty = $reg[2];
2634 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2638 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2639 $this->errors[] = $this->error;
2644 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2646 $operationslog .=
'<br>We have this initial main data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty.
'.';
2649 $tmpobject->element =
'generic';
2650 $tmpobject->id = $idtouseforthirdparty;
2651 $tmpobject->name = $nametouseforthirdparty;
2652 $tmpobject->name_alias = $namealiastouseforthirdparty;
2653 $tmpobject->email = $emailtouseforthirdparty;
2657 $idtouseforthirdparty = $tmpobject->id;
2658 $nametouseforthirdparty = $tmpobject->name;
2659 $namealiastouseforthirdparty = $tmpobject->name_alias;
2660 $emailtouseforthirdparty = $tmpobject->email;
2662 $operationslog .=
'<br>We try to search existing thirdparty with idtouseforthirdparty='.$idtouseforthirdparty.
' emailtouseforthirdparty='.$emailtouseforthirdparty.
' nametouseforthirdparty='.$nametouseforthirdparty.
' namealiastouseforthirdparty='.$namealiastouseforthirdparty;
2665 $result = $thirdpartystatic->findNearest($idtouseforthirdparty, $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', $emailtouseforthirdparty, $namealiastouseforthirdparty);
2669 $this->error =
'Error when getting thirdparty with name '.$nametouseforthirdparty.
' (may be 2 record exists with same name ?)';
2670 $this->errors[] = $this->error;
2672 } elseif ($result == 0) {
2673 if ($operation[
'type'] ==
'loadthirdparty') {
2674 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2677 $resultContact = $contactstatic->findNearest(0,
'',
'',
'', $emailtouseforthirdparty,
'', 0);
2678 if ($resultContact > 0) {
2679 $idtouseforthirdparty = $contactstatic->socid;
2680 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2682 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2685 $langs->load(
"errors");
2686 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2687 $this->errors[] = $this->error;
2691 $langs->load(
"errors");
2692 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2693 $this->errors[] = $this->error;
2695 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2696 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
2699 $thirdpartystatic =
new Societe($db);
2700 $thirdpartystatic->name = (string) $nametouseforthirdparty;
2701 if (!empty($namealiastouseforthirdparty)) {
2702 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
2703 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
2706 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'' : $fromtext) : $replytostring);
2708 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ?
'' : $from) : $replyto) : $emailtouseforthirdparty);
2711 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2713 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
2714 $thirdpartystatic->code_client =
'auto';
2716 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
2717 $thirdpartystatic->code_fournisseur =
'auto';
2720 if ($errorforthisaction) {
2723 $result = $thirdpartystatic->create($user);
2726 $this->error = $thirdpartystatic->error;
2727 $this->errors = $thirdpartystatic->errors;
2729 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag($thirdpartystatic->id);
2734 dol_syslog(
"One and only one existing third party has been found");
2736 $thirdpartystatic->fetch($result);
2738 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag($thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name);
2742 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
2743 if (empty($operation[
'actionparam'])) {
2745 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
2746 $this->errors[] = $this->error;
2748 $contact_static =
new Contact($this->db);
2750 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2751 if ($errorforthisaction) {
2754 if (!empty($contact_static->email) && $contact_static->email != $from) {
2755 $from = $contact_static->email;
2758 $result = $contactstatic->fetch(0,
null,
'', $from);
2761 $this->error =
'Error when getting contact with email ' . $from;
2762 $this->errors[] = $this->error;
2764 } elseif ($result == 0) {
2765 dol_syslog(
"Contact with email " . $from .
" was not found. We try to create it.");
2766 $contactstatic =
new Contact($this->db);
2769 $contactstatic->email = $from;
2770 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($from);
2773 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2775 if ($errorforthisaction) {
2779 if (!empty($contactstatic->country)) {
2780 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2781 $result =
getCountry(
'',
'3', $this->db,
null, 1, $contactstatic->country);
2782 if ($result ==
'NotDefined') {
2784 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
2785 } elseif (!($result > 0)) {
2787 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
2788 $this->errors[] = $this->db->lasterror();
2790 $contactstatic->country_id = $result;
2791 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2793 } elseif (!empty($contactstatic->country_code)) {
2794 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2795 $result =
getCountry($contactstatic->country_code,
'3', $this->db);
2796 if ($result ==
'NotDefined') {
2798 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
2799 } elseif (!($result > 0)) {
2801 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
2802 $this->errors[] = $this->db->lasterror();
2804 $contactstatic->country_id = $result;
2805 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2809 if (!$errorforactions) {
2811 if (!empty($contactstatic->state)) {
2812 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2813 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
2814 if (empty($result)) {
2816 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
2817 } elseif (!($result > 0)) {
2819 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
2820 $this->errors[] = $this->db->lasterror();
2822 $contactstatic->state_id = $result;
2823 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2825 } elseif (!empty($contactstatic->state_code)) {
2826 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2827 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
2828 if (empty($result)) {
2830 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
2831 } elseif (!($result > 0)) {
2833 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
2834 $this->errors[] = $this->db->lasterror();
2836 $contactstatic->state_id = $result;
2837 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2842 if (!$errorforactions) {
2843 $result = $contactstatic->create($user);
2846 $this->error = $contactstatic->error;
2847 $this->errors = $contactstatic->errors;
2849 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag($contactstatic->id);
2856 } elseif ($operation[
'type'] ==
'recordevent') {
2860 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
2861 if ($alreadycreated == 0) {
2862 $operationslog .=
'<br>We did not find existing actionmail with msgid='.$msgid;
2864 if ($projectstatic->id > 0) {
2865 if ($projectfoundby) {
2866 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
2869 if ($thirdpartystatic->id > 0) {
2870 if ($thirdpartyfoundby) {
2871 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2874 if ($contactstatic->id > 0) {
2875 if ($contactfoundby) {
2876 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2880 $description = $descriptiontitle;
2886 $descriptionfull = $description;
2888 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2893 $actioncomm->type_code =
'AC_OTH_AUTO';
2894 $actioncomm->code =
'AC_'.$actioncode;
2895 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
2896 $actioncomm->note_private = $descriptionfull;
2897 $actioncomm->fk_project = $projectstatic->id;
2898 $actioncomm->datep = $dateemail;
2899 $actioncomm->datef = $dateemail;
2900 $actioncomm->percentage = -1;
2901 $actioncomm->socid = $thirdpartystatic->id;
2902 $actioncomm->contact_id = $contactstatic->id;
2903 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array());
2904 $actioncomm->authorid = $user->id;
2905 $actioncomm->userownerid = $user->id;
2907 $actioncomm->email_msgid = $msgid;
2908 $actioncomm->email_from = $fromstring;
2909 $actioncomm->email_sender = $sender;
2910 $actioncomm->email_to = $to;
2911 $actioncomm->email_tocc = $sendtocc;
2912 $actioncomm->email_tobcc = $sendtobcc;
2913 $actioncomm->email_subject = $subject;
2914 $actioncomm->errors_to =
'';
2916 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
2917 $actioncomm->fk_element = $fk_element_id;
2918 $actioncomm->elementid = $fk_element_id;
2919 $actioncomm->elementtype = $fk_element_type;
2920 if (is_object($objectemail) && $objectemail->module) {
2921 $actioncomm->elementtype .=
'@'.$objectemail->module;
2928 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2930 if ($errorforthisaction) {
2933 $result = $actioncomm->create($user);
2936 $this->errors = $actioncomm->errors;
2938 if ($fk_element_type ==
"ticket" && is_object($objectemail)) {
2939 if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED) {
2940 if ($objectemail->fk_user_assign !=
null) {
2941 $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED);
2943 $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ);
2947 $operationslog .=
'<br>Ticket Re-Opened successfully -> ref='.$objectemail->ref;
2950 $this->error =
'Error while changing the ticket status -> ref='.$objectemail->ref;
2951 $this->errors[] = $this->error;
2954 if (!empty($attachments)) {
2956 $ticket =
new Ticket($this->db);
2957 $ticket->fetch($fk_element_id);
2958 $destdir = $conf->ticket->dir_output.
'/'.$ticket->ref;
2963 foreach ($attachments as $attachment) {
2964 $attachment->save($destdir.
'/');
2967 $this->
getmsg($connection, $imapemail, $destdir);
2972 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag($actioncomm->id);
2976 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
2979 foreach ($attachments as $attachment) {
2980 if ($attachment->getName() ===
'undefined') {
2983 $data[$attachment->getName()] = $attachment->getContent();
2987 foreach ($pj as $key => $val) {
2988 $data[$val[
'filename']] =
getFileData($imapemail, (
string) $val[
'pos'], $val[
'type'], $connection);
2991 if (count($data) > 0) {
2992 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($from).
"%'";
2993 $resql = $this->db->query($sql);
2994 if ($this->db->num_rows($resql) == 0) {
2995 $this->errors[] =
"User Not allowed to add documents ({$from})";
2997 $arrayobject = array(
2998 'propale' => array(
'table' =>
'propal',
2999 'fields' => array(
'ref'),
3000 'class' =>
'comm/propal/class/propal.class.php',
3001 'object' =>
'Propal'),
3002 'holiday' => array(
'table' =>
'holiday',
3003 'fields' => array(
'ref'),
3004 'class' =>
'holiday/class/holiday.class.php',
3005 'object' =>
'Holiday'),
3006 'expensereport' => array(
'table' =>
'expensereport',
3007 'fields' => array(
'ref'),
3008 'class' =>
'expensereport/class/expensereport.class.php',
3009 'object' =>
'ExpenseReport'),
3010 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
3011 'fields' => array(
'ref'),
3012 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
3013 'object' =>
'RecruitmentJobPosition'),
3014 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
3015 'fields' => array(
'ref'),
3016 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
3017 'object' =>
'RecruitmentCandidature'),
3018 'societe' => array(
'table' =>
'societe',
3019 'fields' => array(
'code_client',
'code_fournisseur'),
3020 'class' =>
'societe/class/societe.class.php',
3021 'object' =>
'Societe'),
3022 'commande' => array(
'table' =>
'commande',
3023 'fields' => array(
'ref'),
3024 'class' =>
'commande/class/commande.class.php',
3025 'object' =>
'Commande'),
3026 'expedition' => array(
'table' =>
'expedition',
3027 'fields' => array(
'ref'),
3028 'class' =>
'expedition/class/expedition.class.php',
3029 'object' =>
'Expedition'),
3030 'contract' => array(
'table' =>
'contrat',
3031 'fields' => array(
'ref'),
3032 'class' =>
'contrat/class/contrat.class.php',
3033 'object' =>
'Contrat'),
3034 'fichinter' => array(
'table' =>
'fichinter',
3035 'fields' => array(
'ref'),
3036 'class' =>
'fichinter/class/fichinter.class.php',
3037 'object' =>
'Fichinter'),
3038 'ticket' => array(
'table' =>
'ticket',
3039 'fields' => array(
'ref'),
3040 'class' =>
'ticket/class/ticket.class.php',
3041 'object' =>
'Ticket'),
3042 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
3043 'fields' => array(
'ref'),
3044 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
3045 'object' =>
'KnowledgeRecord'),
3046 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
3047 'fields' => array(
'ref'),
3048 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
3049 'object' =>
'SupplierProposal'),
3050 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
3051 'fields' => array(
'ref',
'ref_supplier'),
3052 'class' =>
'fourn/class/fournisseur.commande.class.php',
3053 'object' =>
'SupplierProposal'),
3054 'facture' => array(
'table' =>
'facture',
3055 'fields' => array(
'ref'),
3056 'class' =>
'compta/facture/class/facture.class.php',
3057 'object' =>
'Facture'),
3058 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
3059 'fields' => array(
'ref',
'ref_client'),
3060 'class' =>
'fourn/class/fournisseur.facture.class.php',
3061 'object' =>
'FactureFournisseur'),
3062 'produit' => array(
'table' =>
'product',
3063 'fields' => array(
'ref'),
3064 'class' =>
'product/class/product.class.php',
3065 'object' =>
'Product'),
3066 'productlot' => array(
'table' =>
'product_lot',
3067 'fields' => array(
'batch'),
3068 'class' =>
'product/stock/class/productlot.class.php',
3069 'object' =>
'Productlot'),
3070 'projet' => array(
'table' =>
'projet',
3071 'fields' => array(
'ref'),
3072 'class' =>
'projet/class/projet.class.php',
3073 'object' =>
'Project'),
3074 'projet_task' => array(
'table' =>
'projet_task',
3075 'fields' => array(
'ref'),
3076 'class' =>
'projet/class/task.class.php',
3077 'object' =>
'Task'),
3078 'ressource' => array(
'table' =>
'resource',
3079 'fields' => array(
'ref'),
3080 'class' =>
'ressource/class/dolressource.class.php',
3081 'object' =>
'Dolresource'),
3082 'bom' => array(
'table' =>
'bom_bom',
3083 'fields' => array(
'ref'),
3084 'class' =>
'bom/class/bom.class.php',
3086 'mrp' => array(
'table' =>
'mrp_mo',
3087 'fields' => array(
'ref'),
3088 'class' =>
'mrp/class/mo.class.php',
3092 if (!is_object($hookmanager)) {
3093 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3096 $hookmanager->initHooks(array(
'emailcolector'));
3097 $parameters = array(
'arrayobject' => $arrayobject);
3098 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
3100 $arrayobject = $hookmanager->resArray;
3103 $resultobj = array();
3105 foreach ($arrayobject as $key => $objectdesc) {
3106 $sql =
'SELECT DISTINCT t.rowid ';
3107 $sql .=
' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc[
'table']) .
' AS t';
3109 foreach ($objectdesc[
'fields'] as $field) {
3110 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $this->db->sanitize($field) .
", '%') AND t." . $this->db->sanitize($field) .
" <> '') OR ";
3112 $sql = substr($sql, 0, -4);
3114 $ressqlobj = $this->db->query($sql);
3116 while ($obj = $this->db->fetch_object($ressqlobj)) {
3117 $resultobj[$key][] = $obj->rowid;
3122 foreach ($resultobj as $mod => $ids) {
3123 $moddesc = $arrayobject[$mod];
3124 $elementpath = $mod;
3126 $objectmanaged =
new $moddesc[
'object']($this->db);
3127 '@phan-var-force CommonObject $objectmanaged';
3128 foreach ($ids as $val) {
3129 $res = $objectmanaged->fetch($val);
3131 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
3132 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
3134 $this->errors[] =
'object not found';
3138 foreach ($dirs as $target) {
3139 $prefix = $this->actions[$this->id][
'actionparam'];
3140 foreach ($data as $filename => $content) {
3141 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
3143 $this->errors[] =
'Doc not saved';
3148 $operationslog .=
'<br>Save attachment files on disk';
3150 $this->errors[] =
'no joined piece';
3152 $operationslog .=
'<br>No joinded files';
3154 } elseif ($operation[
'type'] ==
'project') {
3156 $projecttocreate =
new Project($this->db);
3157 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
3158 if ($alreadycreated == 0) {
3159 if ($thirdpartystatic->id > 0) {
3160 $projecttocreate->socid = $thirdpartystatic->id;
3161 if ($thirdpartyfoundby) {
3162 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3165 if ($contactstatic->id > 0) {
3166 $projecttocreate->contact_id = $contactstatic->id;
3167 if ($contactfoundby) {
3168 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3172 $description = $descriptiontitle;
3178 $descriptionfull = $description;
3180 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3184 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
3185 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
3187 $projecttocreate->title = $subject;
3188 $projecttocreate->date_start = $dateemail;
3189 $projecttocreate->date_end = 0;
3190 $projecttocreate->opp_status = $id_opp_status;
3191 $projecttocreate->opp_percent = $percent_opp_status;
3193 $projecttocreate->note_private = $descriptionfull;
3194 $projecttocreate->entity = $conf->entity;
3196 $projecttocreate->email_date = $dateemail;
3197 $projecttocreate->email_msgid = $msgid;
3198 $projecttocreate->email_from = $fromstring;
3199 $projecttocreate->email_sender = $sender;
3200 $projecttocreate->email_to = $to;
3201 $projecttocreate->email_tocc = $sendtocc;
3202 $projecttocreate->email_tobcc = $sendtobcc;
3203 $projecttocreate->email_subject = $subject;
3204 $projecttocreate->errors_to =
'';
3206 $savesocid = $projecttocreate->socid;
3210 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3214 if (empty($projecttocreate->ref)) {
3223 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3224 foreach ($dirmodels as $reldir) {
3225 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
3226 if (file_exists($file)) {
3227 $classname = $modele;
3232 if ($classname !==
'') {
3233 if ($savesocid > 0) {
3234 if ($savesocid != $projecttocreate->socid) {
3236 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');
3239 if ($projecttocreate->socid > 0) {
3240 $thirdpartystatic->fetch($projecttocreate->socid);
3244 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
3245 $modModuleToUseForNextValue =
new $classname();
3246 '@phan-var-force ModeleNumRefProjects $modModuleToUseForNextValue';
3247 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
3249 $projecttocreate->ref = $defaultref;
3253 if ($errorforthisaction) {
3256 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
3258 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3260 $operationslog .=
'<br>'.$this->error;
3263 $result = $projecttocreate->create($user);
3266 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
3267 $this->errors = $projecttocreate->errors;
3269 $operationslog .=
'<br>'.$this->error;
3272 $destdir = $conf->project->dir_output.
'/'.$projecttocreate->ref;
3277 foreach ($attachments as $attachment) {
3279 $typeattachment = (string) $attachment->getDisposition();
3280 $filename = $attachment->getFilename();
3281 $content = $attachment->getContent();
3285 $this->
getmsg($connection, $imapemail, $destdir);
3288 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag($projecttocreate->id);
3290 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag($projecttocreate->id);
3298 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3300 } elseif ($operation[
'type'] ==
'ticket') {
3302 $tickettocreate =
new Ticket($this->db);
3303 if ($ticketalreadyexists == 0) {
3304 if ($thirdpartystatic->id > 0) {
3305 $tickettocreate->socid = $thirdpartystatic->id;
3306 $tickettocreate->fk_soc = $thirdpartystatic->id;
3307 if ($thirdpartyfoundby) {
3308 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3311 if ($contactstatic->id > 0) {
3312 $tickettocreate->contact_id = $contactstatic->id;
3313 if ($contactfoundby) {
3314 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3318 $description = $descriptiontitle;
3324 $descriptionfull = $description;
3326 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3330 $tickettocreate->subject = $subject;
3331 $tickettocreate->message = $description;
3333 $tickettocreate->category_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1)));
3334 $tickettocreate->severity_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1)));
3335 $tickettocreate->origin_email = $from;
3336 $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto :
null);
3337 $tickettocreate->origin_references = (!empty($headers[
'References']) ? $headers[
'References'] :
null);
3338 $tickettocreate->fk_user_create = $user->id;
3339 $tickettocreate->datec =
dol_now();
3340 $tickettocreate->fk_project = $projectstatic->id;
3341 $tickettocreate->notify_tiers_at_create =
getDolGlobalInt(
'TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3342 $tickettocreate->note_private = $descriptionfull;
3343 $tickettocreate->entity = $conf->entity;
3345 $tickettocreate->email_date = $dateemail;
3346 $tickettocreate->email_msgid = $msgid;
3347 $tickettocreate->email_from = $fromstring;
3348 $tickettocreate->email_sender = $sender;
3349 $tickettocreate->email_to = $to;
3350 $tickettocreate->email_tocc = $sendtocc;
3351 $tickettocreate->email_tobcc = $sendtobcc;
3352 $tickettocreate->email_subject = $subject;
3353 $tickettocreate->errors_to =
'';
3357 $savesocid = $tickettocreate->socid;
3361 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3363 $modele =
'UNDEFINED';
3365 if (empty($tickettocreate->ref)) {
3374 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3375 foreach ($dirmodels as $reldir) {
3376 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3377 if (file_exists($file)) {
3378 $classname = $modele;
3383 if ($classname !==
'') {
3384 if ($savesocid > 0) {
3385 if ($savesocid != $tickettocreate->socid) {
3387 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');
3390 if ($tickettocreate->socid > 0) {
3391 $thirdpartystatic->fetch($tickettocreate->socid);
3396 $modModuleToUseForNextValue =
new $classname();
3397 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3398 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3400 $tickettocreate->ref = $defaultref;
3403 if ($errorforthisaction) {
3406 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3408 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3411 $tickettocreate->context[
'actionmsg2'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3412 $tickettocreate->context[
'actionmsg'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3415 $result = $tickettocreate->create($user);
3418 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3419 $this->errors = $tickettocreate->errors;
3422 $destdir = $conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3427 foreach ($attachments as $attachment) {
3429 $typeattachment = (string) $attachment->getDisposition();
3430 $filename = $attachment->getFilename();
3431 $content = $attachment->getContent();
3435 $this->
getmsg($connection, $imapemail, $destdir);
3438 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3440 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3446 } elseif ($operation[
'type'] ==
'candidature') {
3450 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3451 if ($alreadycreated == 0) {
3452 $description = $descriptiontitle;
3458 $descriptionfull = $description;
3459 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3462 $candidaturetocreate->subject = $subject;
3463 $candidaturetocreate->message = $description;
3464 $candidaturetocreate->type_code = 0;
3465 $candidaturetocreate->category_code =
null;
3466 $candidaturetocreate->severity_code =
null;
3467 $candidaturetocreate->email = $from;
3469 $candidaturetocreate->fk_user_creat = $user->id;
3470 $candidaturetocreate->date_creation =
dol_now();
3471 $candidaturetocreate->fk_project = $projectstatic->id;
3472 $candidaturetocreate->description = $description;
3473 $candidaturetocreate->note_private = $descriptionfull;
3474 $candidaturetocreate->entity = $conf->entity;
3475 $candidaturetocreate->email_msgid = $msgid;
3476 $candidaturetocreate->email_date = $dateemail;
3477 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3482 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3525 if ($errorforthisaction) {
3529 $result = $candidaturetocreate->create($user);
3532 $this->error =
'Failed to create candidature: '.implode(
', ', $candidaturetocreate->errors);
3533 $this->errors = $candidaturetocreate->errors;
3536 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag($candidaturetocreate->id);
3539 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3542 if (!is_object($hookmanager)) {
3543 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3546 $hookmanager->initHooks([
'emailcolector']);
3548 $parameters = array(
3549 'connection' => $connection,
3550 'imapemail' => $imapemail,
3551 'overview' => $overview,
3554 'fromtext' => $fromtext,
3556 'actionparam' => $operation[
'actionparam'],
3558 'thirdpartyid' => $thirdpartyid,
3559 'objectid' => $objectid,
3560 'objectemail' => $objectemail,
3562 'messagetext' => $messagetext,
3563 'subject' => $subject,
3564 'header' => $header,
3565 'attachments' => $attachments,
3567 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3570 $errorforthisaction++;
3571 $this->error = $hookmanager->resPrint;
3573 if ($errorforthisaction) {
3575 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3577 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3581 if (!$errorforactions) {
3582 $nbactiondoneforemail++;
3588 if (!$errorforactions) {
3589 if (!empty($targetdir)) {
3592 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3593 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid.
' - '.$imapemail->getHeader()->get(
'subject').
' to '.$targetdir;
3595 $arrayofemailtodelete[$this->
uidAsString($imapemail)] = $imapemail;
3598 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3599 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3601 $arrayofemailtodelete[$imapemail] = $msgid;
3606 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);
3608 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3616 unset($objectemail);
3617 unset($projectstatic);
3618 unset($thirdpartystatic);
3619 unset($contactstatic);
3621 $nbemailprocessed++;
3623 if (!$errorforemail) {
3624 $nbactiondone += $nbactiondoneforemail;
3628 $this->db->commit();
3630 $this->db->rollback();
3634 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3635 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3641 $this->db->rollback();
3645 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3647 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3649 $langs->load(
"admin");
3650 $output = $langs->trans(
'NoNewEmailToProcess');
3651 $output .=
' (defaultlang='.$langs->defaultlang.
')';
3657 krsort($arrayofemailtodelete, SORT_NUMERIC);
3659 foreach ($arrayofemailtodelete as $imapemailnum => $imapemail) {
3660 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemailnum);
3662 $operationslog .=
"<br> move email ".$imapemailnum.($mode > 0 ?
' (test)' :
'');
3664 if (empty($mode) && empty($error)) {
3665 $tmptargetdir = $targetdir;
3672 $result = $imapemail->move($tmptargetdir,
false);
3675 $operationslog .=
'<br>Exception !!!! '.$e->getMessage();
3677 if (empty($result)) {
3678 dol_syslog(
"Failed to move email into target directory ".$targetdir);
3679 $operationslog .=
'<br>Failed to move email into target directory '.$targetdir;
3685 if (empty($mode) && empty($error)) {
3687 $operationslog .=
"<br>Expunge";
3692 $client->disconnect();
3694 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
3695 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
3697 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid.($mode > 0 ?
' (test)' :
'');
3699 if (empty($mode) && empty($error)) {
3700 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
3703 $this->error = imap_last_error();
3704 $this->errors[] = $this->error;
3706 $operationslog .=
'<br>Error in move '.$this->error;
3713 if (empty($mode) && empty($error)) {
3715 $operationslog .=
"<br>Expunge";
3717 imap_expunge($connection);
3719 imap_close($connection);
3722 $this->datelastresult = $now;
3723 $this->lastresult = $output;
3725 $this->debuginfo .=
'IMAP search array used : '.$search;
3727 $this->debuginfo .=
'IMAP search string used : '.$search;
3730 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
3732 if ($operationslog) {
3733 $this->debuginfo .= $operationslog;
3736 if (empty($error) && empty($mode)) {
3737 $this->datelastok = $now;
3740 if (!empty($this->errors)) {
3741 $this->lastresult .=
"<br>".implode(
"<br>", $this->errors);
3743 $this->codelastresult = ($error ?
'KO' :
'OK');
3749 dol_syslog(
"EmailCollector::doCollectOneCollector end", LOG_INFO);
3751 return $error ? -1 : 1;
3766 private function getmsg($mbox, $mid, $destdir =
'')
3770 global $charset, $htmlmsg, $plainmsg, $attachments;
3771 $htmlmsg = $plainmsg = $charset =
'';
3772 $attachments = array();
3779 $s = imap_fetchstructure($mbox, $mid, FT_UID);
3784 $this->
getpart($mbox, $mid, $s,
'0');
3787 foreach ($s->parts as $partno0 => $p) {
3788 $this->
getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
3819 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
3822 global $htmlmsg, $plainmsg, $charset, $attachments;
3826 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
3827 imap_body($mbox, $mid, FT_UID);
3829 if ($p->encoding == 4) {
3830 $data = quoted_printable_decode($data);
3831 } elseif ($p->encoding == 3) {
3832 $data = base64_decode($data);
3838 if ($p->parameters) {
3839 foreach ($p->parameters as $x) {
3840 $params[strtolower($x->attribute)] = $x->value;
3843 if (!empty($p->dparameters)) {
3844 foreach ($p->dparameters as $x) {
3845 $params[strtolower($x->attribute)] = $x->value;
3848 '@phan-var-force array{filename?:string,name?:string,charset?:string} $params';
3853 if (!empty($params[
'filename']) || !empty($params[
'name'])) {
3855 $filename = $params[
'filename'] ?? $params[
'name'];
3857 $attachments[$filename] = $data;
3859 if (strlen($destdir)) {
3860 if (substr($destdir, -1) !=
'/') {
3865 $file_name_complete = $filename;
3866 $destination = $destdir.$file_name_complete;
3869 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
3872 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
3875 $file_name_original = $file_name;
3884 while (file_exists($destdir.$file_name.
".".$extension)) {
3885 $file_name = $file_name_original .
' (' . $num .
')';
3886 $file_name_complete = $file_name .
"." . $extension;
3887 $destination = $destdir.$file_name_complete;
3893 file_put_contents($destination, $data);
3898 if ($p->type == 0 && $data) {
3899 if (!empty($params[
'charset'])) {
3904 if (strtolower($p->subtype) ==
'plain') {
3905 $plainmsg .= trim($data).
"\n\n";
3907 $htmlmsg .= $data.
"<br><br>";
3909 $charset = $params[
'charset'];
3910 } elseif ($p->type == 2 && $data) {
3916 if (!empty($params[
'charset'])) {
3919 $plainmsg .= $data.
"\n\n";
3923 if (!empty($p->parts)) {
3924 foreach ($p->parts as $partno0 => $p2) {
3925 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1), $destdir);
3941 if (!$string || $fromEncoding == $toEncoding) {
3944 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
3945 if (!$convertedString && extension_loaded(
'mbstring')) {
3946 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
3948 if (!$convertedString) {
3949 throw new Exception(
'Mime string encoding conversion failed');
3951 return $convertedString;
3970 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
3971 $elements = imap_mime_header_decode($subject);
3973 if (!empty($elements)) {
3974 $num = count($elements);
3975 for ($i = 0; $i < $num; $i++) {
3976 $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));
3977 $newstring .= $stringinutf8;
3979 $subject = $newstring;
3981 } elseif (!function_exists(
'mb_decode_mimeheader')) {
3982 $subject = mb_decode_mimeheader($subject);
3983 } elseif (function_exists(
'iconv_mime_decode')) {
3984 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
4000 require_once DOL_DOCUMENT_ROOT .
'/core/lib/images.lib.php';
4003 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
4004 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
4005 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
4006 $maxheightmini = $tmparraysize[
'maxheightmini'];
4007 $quality = $tmparraysize[
'quality'];
4009 file_put_contents($destdir.
'/'.$filename, $content);
4012 vignette($destdir.
'/'.$filename, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
4014 vignette($destdir.
'/'.$filename, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
4027 if (is_object($imapemail)) {
4028 return $imapemail->getAttributes()[
"uid"];
4030 return (
string) $imapemail;