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="'.dolPrintHTMLForAttribute($label).
'"';
643 $linkclose .=
' title="'.dolPrintHTMLForAttribute($label).
'"';
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(
"/_/",
"xxxUNDERSCORExxx", $str);
872 $str = preg_replace(
"/\[Gmail\]/",
"xxxGMAILxxx", $str);
874 if ($str = mb_convert_encoding($str,
"UTF-7")) {
876 $str = preg_replace(
"/\+A/",
"&A", $str);
877 $str = preg_replace(
"/xxxUNDERSCORExxx/",
"_", $str);
879 $str = preg_replace(
"/xxxSPACExxx/",
" ", $str);
881 $str = preg_replace(
"/xxxGMAILxxx/",
"[Gmail]", $str);
885 $this->error =
"error: is not possible to encode this string '".$str.
"'";
905 $arrayofcollectors = $this->
fetchAll($user, 1);
908 foreach ($arrayofcollectors as $emailcollector) {
909 $result = $emailcollector->doCollectOneCollector(0);
910 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
912 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
913 if (!empty($emailcollector->errors)) {
914 $this->error .= implode(
'<br>', $emailcollector->errors);
916 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
935 global
$conf, $langs;
937 $errorforthisaction = 0;
940 $outputlangs = $langs;
943 $newlang =
GETPOST(
'lang_id',
'aZ09');
946 $newlang = !empty(
$object->thirdparty->default_lang) ?
$object->thirdparty->default_lang : $newlang;
948 if (!empty($newlang)) {
950 $outputlangs->setDefaultLang($newlang);
960 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
963 $tmparray = explode(
'.', $propertytooverwrite);
964 if (count($tmparray) == 2) {
965 $tmpclass = $tmparray[0];
966 $tmpproperty = $tmparray[1];
968 $tmpproperty = $tmparray[0];
970 if ($tmpclass && ($tmpclass !=
$object->element)) {
980 $regforregex = array();
981 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
982 $sourcefield = $regforregex[1];
983 $regexstring = $regforregex[2];
985 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
986 $sourcefield = $regforregex[1];
987 $regexstring = $regforregex[2];
990 if (!empty($sourcefield) && !empty($regexstring)) {
991 if (strtolower($sourcefield) ==
'body') {
992 $sourcestring = $messagetext;
993 } elseif (strtolower($sourcefield) ==
'subject') {
994 $sourcestring = $subject;
995 } elseif (strtolower($sourcefield) ==
'header') {
996 $sourcestring = $header;
1000 $regforval = array();
1002 if (strtolower($sourcefield) ==
'body') {
1003 $regexoptions =
'ms';
1005 if (strtolower($sourcefield) ==
'header') {
1006 $regexoptions =
'm';
1010 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
1012 $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
1013 if (strtolower($sourcefield) ==
'header') {
1014 if (preg_match(
'/^options_/', $tmpproperty)) {
1017 if (property_exists(
$object, $tmpproperty)) {
1024 if (preg_match(
'/^options_/', $tmpproperty)) {
1027 if (property_exists(
$object, $tmpproperty)) {
1034 if (preg_match(
'/^options_/', $tmpproperty)) {
1035 $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));
1037 if (property_exists(
$object, $tmpproperty)) {
1045 if (property_exists(
$object, $tmpproperty)) {
1048 $tmp[$tmpproperty] =
null;
1051 $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.';
1055 $errorforthisaction++;
1056 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1057 $this->errors[] = $this->error;
1059 $operationslog .=
'<br>'.$this->error;
1061 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1063 if (preg_match(
'/^options_/', $tmpproperty)) {
1064 $valuecurrent =
$object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1066 if (property_exists(
$object, $tmpproperty)) {
1067 $valuecurrent =
$object->$tmpproperty;
1070 $valuecurrent = $tmp[$tmpproperty];
1074 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1075 $valuetouse = $regforregex[2];
1078 $matcharray = array();
1079 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1081 if (is_array($matcharray[1])) {
1082 foreach ($matcharray[1] as $keytoreplace) {
1083 if ($keytoreplace) {
1084 if (preg_match(
'/^options_/', $keytoreplace)) {
1085 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1087 if (property_exists(
$object, $keytoreplace)) {
1088 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->$keytoreplace;
1091 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1101 if (preg_match(
'/^options_/', $tmpproperty)) {
1102 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1104 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1106 if (property_exists(
$object, $tmpproperty)) {
1107 $object->$tmpproperty = $valuetouse;
1109 $tmp[$tmpproperty] = $valuetouse;
1112 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1116 $errorforthisaction++;
1117 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1118 $this->errors[] = $this->error;
1123 return $errorforthisaction;
1132 public function doCollectOneCollector($mode = 0)
1134 global $db,
$conf, $langs, $user;
1135 global $hookmanager;
1139 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1141 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1144 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1146 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1151 $this->debuginfo =
'';
1155 $searchfilterdoltrackid = 0;
1156 $searchfilternodoltrackid = 0;
1157 $searchfilterisanswer = 0;
1158 $searchfilterisnotanswer = 0;
1159 $searchfilterreplyto = 0;
1160 $searchfilterexcludebodyarray = array();
1161 $searchfilterexcludesubjectarray = array();
1162 $operationslog =
'';
1163 $rulesreplyto = array();
1164 $connectstringsource =
'';
1165 $connectstringtarget =
'';
1166 $connection =
false;
1167 $arrayofemail = array();
1172 if (empty($this->host)) {
1173 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1176 if (empty($this->login)) {
1177 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1180 if (empty($this->source_directory)) {
1181 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1187 $sourcedir = $this->source_directory;
1188 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1193 $sourcedir = $this->source_directory;
1194 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1197 if ($this->acces_type == 1) {
1199 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>';
1201 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1205 $keyforsupportedoauth2array = $this->oauth_service;
1206 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1207 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1209 $keyforprovider =
'';
1211 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', strtoupper($keyforsupportedoauth2array));
1212 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1214 if (!empty($supportedoauth2array)) {
1215 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1216 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1217 $OAUTH_SERVICENAME = $nameofservice;
1219 $OAUTH_SERVICENAME =
'Unknown';
1222 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1224 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1233 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1242 if (is_object($tokenobj) && $expire) {
1243 $this->debuginfo .=
'Refresh token '.$OAUTH_SERVICENAME.
'<br>';
1244 $credentials =
new Credentials(
1249 $serviceFactory = new \OAuth\ServiceFactory();
1250 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1254 if (preg_match(
'/^Microsoft/', $OAUTH_SERVICENAME)) {
1256 $tmp = explode(
'-', $OAUTH_SERVICENAME);
1257 $scopes = explode(
',',
getDolGlobalString(
'OAUTH_'.strtoupper($tmp[0]).(empty($tmp[1]) ?
'' :
'-'.$tmp[1]).
'_SCOPE'));
1260 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $scopes);
1262 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
1264 $refreshtoken = $tokenobj->getRefreshToken();
1265 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1268 $tokenobj->setRefreshToken($refreshtoken);
1269 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1271 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1272 if (is_object($tokenobj)) {
1273 $token = $tokenobj->getAccessToken();
1275 $this->error =
"Token not found";
1280 $this->error = $e->getMessage();
1281 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1285 $cm =
new ClientManager();
1286 $client = $cm->make([
1287 'host' => $this->host,
1288 'port' => $this->port,
1289 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1290 'validate_cert' => true,
1291 'protocol' =>
'imap',
1292 'username' => $this->login,
1293 'password' => $token,
1294 'authentication' =>
"oauth",
1298 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1300 $cm =
new ClientManager();
1301 $client = $cm->make([
1302 'host' => $this->host,
1303 'port' => $this->port,
1304 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1305 'validate_cert' => true,
1306 'protocol' =>
'imap',
1307 'username' => $this->login,
1308 'password' => $this->password,
1309 'authentication' =>
"login",
1317 }
catch (ConnectionFailedException $e) {
1318 $this->error = $e->getMessage();
1319 $this->errors[] = $this->error;
1320 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1324 $host = dol_getprefix(
'email');
1327 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1329 if (!function_exists(
'imap_open')) {
1330 $this->error =
'IMAP function not enabled on your PHP';
1336 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1337 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1339 $connectstringsource = $connectstringserver.$sourcedir;
1340 $connectstringtarget = $connectstringserver.$targetdir;
1343 $this->debuginfo .=
'connectstringsource = '.$connectstringsource.
', $connectstringtarget='.$connectstringtarget.
'<br>';
1345 $connection = imap_open($connectstringsource, $this->login, $this->password);
1346 if ($connection ===
false) {
1347 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1352 $host = dol_getprefix(
'email');
1361 $criteria = array();
1364 $criteria = array(array(
'UNDELETED'));
1365 foreach ($this->filters as $rule) {
1366 if (empty($rule[
'status'])) {
1371 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1375 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1378 if ($rule[
'type'] ==
'from') {
1379 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1380 if (count($tmprulevaluearray) >= 2) {
1381 foreach ($tmprulevaluearray as $tmprulevalue) {
1382 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1385 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1388 if ($rule[
'type'] ==
'to') {
1389 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1390 if (count($tmprulevaluearray) >= 2) {
1391 foreach ($tmprulevaluearray as $tmprulevalue) {
1392 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1395 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1398 if ($rule[
'type'] ==
'bcc') {
1399 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1401 if ($rule[
'type'] ==
'cc') {
1402 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1404 if ($rule[
'type'] ==
'subject') {
1405 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1407 $searchfilterexcludesubjectarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1409 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1412 if ($rule[
'type'] ==
'body') {
1413 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1415 $searchfilterexcludebodyarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1417 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1420 if ($rule[
'type'] ==
'header') {
1421 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1433 if ($rule[
'type'] ==
'seen') {
1434 array_push($criteria, array($not.
"SEEN"));
1436 if ($rule[
'type'] ==
'unseen') {
1437 array_push($criteria, array($not.
"UNSEEN"));
1439 if ($rule[
'type'] ==
'unanswered') {
1440 array_push($criteria, array($not.
"UNANSWERED"));
1442 if ($rule[
'type'] ==
'answered') {
1443 array_push($criteria, array($not.
"ANSWERED"));
1445 if ($rule[
'type'] ==
'smaller') {
1446 array_push($criteria, array($not.
"SMALLER"));
1448 if ($rule[
'type'] ==
'larger') {
1449 array_push($criteria, array($not.
"LARGER"));
1453 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1454 $searchfilterdoltrackid++;
1455 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1457 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1458 $searchfilterdoltrackid++;
1459 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1461 if ($rule[
'type'] ==
'withtrackingid') {
1462 $searchfilterdoltrackid++;
1463 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1465 if ($rule[
'type'] ==
'withouttrackingid') {
1466 $searchfilternodoltrackid++;
1467 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1470 if ($rule[
'type'] ==
'isanswer') {
1471 $searchfilterisanswer++;
1472 $searchhead .=
'/References.*@.*/';
1474 if ($rule[
'type'] ==
'isnotanswer') {
1475 $searchfilterisnotanswer++;
1476 $searchhead .=
'! /References.*@.*/';
1479 if ($rule[
'type'] ==
'replyto') {
1480 $searchfilterreplyto++;
1481 $rulesreplyto[] = $rule[
'rulevalue'];
1482 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1486 if (empty($targetdir) || !
getDolGlobalString(
'EMAILCOLLECTOR_NO_FILTER_ON_DATE_IF_THERE_IS_A_TARGETDIR')) {
1488 if ($this->datelastok) {
1489 $fromdate = $this->datelastok;
1491 if ($fromdate > 0) {
1493 array_push($criteria, array(
"SINCE" => date(
'j-M-Y', $fromdate - 1)));
1498 dol_syslog(
"IMAP search string = ".var_export($criteria,
true));
1499 $search = var_export($criteria,
true);
1502 $search =
'UNDELETED';
1503 foreach ($this->filters as $rule) {
1504 if (empty($rule[
'status'])) {
1512 if (!empty($rule[
'rulevalue']) && strpos($rule[
'rulevalue'],
'!') === 0) {
1516 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1519 if ($rule[
'type'] ==
'from') {
1520 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1521 if (count($tmprulevaluearray) >= 2) {
1522 foreach ($tmprulevaluearray as $tmprulevalue) {
1523 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1526 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1529 if ($rule[
'type'] ==
'to') {
1530 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1531 if (count($tmprulevaluearray) >= 2) {
1532 foreach ($tmprulevaluearray as $tmprulevalue) {
1533 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1536 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1539 if ($rule[
'type'] ==
'bcc') {
1540 $search .= ($search ?
' ' :
'').$not.
'BCC';
1542 if ($rule[
'type'] ==
'cc') {
1543 $search .= ($search ?
' ' :
'').$not.
'CC';
1545 if ($rule[
'type'] ==
'subject') {
1548 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1550 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1553 if ($rule[
'type'] ==
'body') {
1556 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1559 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1562 if ($rule[
'type'] ==
'header') {
1563 $search .= ($search ?
' ' :
'').$not.
'HEADER '.$rule[
'rulevalue'];
1575 if ($rule[
'type'] ==
'seen') {
1576 $search .= ($search ?
' ' :
'').$not.
'SEEN';
1578 if ($rule[
'type'] ==
'unseen') {
1579 $search .= ($search ?
' ' :
'').$not.
'UNSEEN';
1581 if ($rule[
'type'] ==
'unanswered') {
1582 $search .= ($search ?
' ' :
'').$not.
'UNANSWERED';
1584 if ($rule[
'type'] ==
'answered') {
1585 $search .= ($search ?
' ' :
'').$not.
'ANSWERED';
1587 if ($rule[
'type'] ==
'smaller') {
1588 $search .= ($search ?
' ' :
'').$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1590 if ($rule[
'type'] ==
'larger') {
1591 $search .= ($search ?
' ' :
'').$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1595 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1596 $searchfilterdoltrackid++;
1597 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1599 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1600 $searchfilterdoltrackid++;
1601 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1603 if ($rule[
'type'] ==
'withtrackingid') {
1604 $searchfilterdoltrackid++;
1605 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1607 if ($rule[
'type'] ==
'withouttrackingid') {
1608 $searchfilternodoltrackid++;
1609 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1612 if ($rule[
'type'] ==
'isanswer') {
1613 $searchfilterisanswer++;
1614 $searchhead .=
'/References.*@.*/';
1616 if ($rule[
'type'] ==
'isnotanswer') {
1617 $searchfilterisnotanswer++;
1618 $searchhead .=
'! /References.*@.*/';
1621 if ($rule[
'type'] ==
'replyto') {
1622 $searchfilterreplyto++;
1623 $rulesreplyto[] = $rule[
'rulevalue'];
1624 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1628 if (empty($targetdir)) {
1630 if ($this->datelastok) {
1631 $fromdate = $this->datelastok;
1633 if ($fromdate > 0) {
1634 $search .= ($search ?
' ' :
'').
'SINCE '.date(
'j-M-Y', $fromdate - 1);
1643 $nbemailprocessed = 0;
1646 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1647 $arrayofemail = array();
1654 $tmpsourcedir = $sourcedir;
1659 $f = $client->getFolders(
false, $tmpsourcedir);
1662 if ($folder instanceof Webklex\PHPIMAP\Folder) {
1663 $Query = $folder->messages()->where($criteria);
1666 $this->error =
"Source directory ".$sourcedir.
" not found";
1667 $this->errors[] = $this->error;
1668 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_WARNING);
1673 $this->error =
"Failed to execute getfolders";
1674 $this->errors[] = $this->error;
1675 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1678 }
catch (InvalidWhereQueryCriteriaException $e) {
1679 $this->error = $e->getMessage();
1680 $this->errors[] = $this->error;
1681 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1684 $this->error = $e->getMessage();
1685 $this->errors[] = $this->error;
1686 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1690 '@phan-var-force Webklex\PHPIMAP\Query\Query $Query';
1694 $Query->leaveUnread();
1696 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1697 dol_syslog(
"EmailCollector::doCollectOneCollector nb arrayofemail ".(is_array($arrayofemail) ? count($arrayofemail) :
'Not array'));
1700 $this->error = $e->getMessage();
1701 $this->errors[] = $this->error;
1702 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1705 } elseif ($connection !==
false) {
1707 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1709 if ($arrayofemail ===
false) {
1711 $mapoferrrors = imap_errors();
1712 if ($mapoferrrors !==
false) {
1714 $this->error =
"Search string not understood - ".implode(
',', $mapoferrrors);
1715 $this->errors[] = $this->error;
1720 $arrayofemailtodelete = array();
1723 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0 && $connection !==
false) {
1740 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1742 $richarrayofemail = array();
1744 foreach ($arrayofemail as $imapemail) {
1745 if ($nbemailprocessed > 1000) {
1751 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1752 $header = $imapemail->getHeader()->raw;
1753 $overview = $imapemail->getAttributes();
1755 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1756 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1759 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1762 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)(\r\n|\s$)/m', $header, $matches);
1763 $headers = array_combine($matches[1], $matches[2]);
1766 $richarrayofemail[] = array(
'imapemail' => $imapemail,
'header' => $header,
'headers' => $headers,
'overview' => $overview,
'date' => strtotime($headers[
'Date']));
1771 $richarrayofemail =
dol_sort_array($richarrayofemail,
'date',
'asc');
1775 foreach ($richarrayofemail as $tmpval) {
1778 $imapemail = $tmpval[
'imapemail'];
1779 $header = $tmpval[
'header'];
1780 $overview = $tmpval[
'overview'];
1781 $headers = $tmpval[
'headers'];
1783 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1784 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1786 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1787 $headers[
'References'] = $headers[
'references'];
1789 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1790 $headers[
'Message-ID'] = $headers[
'message-id'];
1792 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1793 $headers[
'Subject'] = $headers[
'subject'];
1799 $emailto = (string) $overview[
'to'];
1806 $operationslog .=
'<br>** Process email #'.dol_escape_htmltag((
string) $iforemailloop);
1810 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1812 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1814 $operationslog .=
" - ".dol_escape_htmltag((
string) $imapemail);
1815 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1817 $operationslog .=
" - MsgId: ".$msgid;
1818 $operationslog .=
" - Date: ".($headers[
'Date'] ?? $langs->transnoentitiesnoconv(
"NotFound"));
1819 $operationslog .=
" - References: ".dol_escape_htmltag($headers[
'References'] ?? $langs->transnoentitiesnoconv(
"NotFound")).
" - Subject: ".
dol_escape_htmltag($headers[
'Subject']);
1821 dol_syslog(
"-- Process email #".$iforemailloop.
", MsgId: ".$msgid.
", Date: ".($headers[
'Date'] ??
'').
", References: ".($headers[
'References'] ??
'').
", Subject: ".$headers[
'Subject']);
1824 $trackidfoundintorecipienttype =
'';
1825 $trackidfoundintorecipientid = 0;
1830 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)) {
1831 $trackidfoundintorecipienttype = $reg[1];
1832 $trackidfoundintorecipientid = $reg[2];
1833 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1834 $trackidfoundintorecipienttype =
'emailing';
1835 $trackidfoundintorecipientid = $reg[1];
1838 $trackidfoundintomsgidtype =
'';
1839 $trackidfoundintomsgidid = 0;
1844 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)) {
1845 $trackidfoundintomsgidtype = $reg[1];
1846 $trackidfoundintomsgidid = $reg[2];
1847 } elseif (preg_match(
'/(?:[\+\-])emailing-(\w+)@/', $msgid, $reg)) {
1848 $trackidfoundintomsgidtype =
'emailing';
1849 $trackidfoundintomsgidid = $reg[1];
1853 if ($searchfilterdoltrackid > 0) {
1854 if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) {
1855 if (empty($headers[
'References']) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References'])) {
1856 $nbemailprocessed++;
1857 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");
1862 if ($searchfilternodoltrackid > 0) {
1863 if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($headers[
'References']) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))) {
1864 $nbemailprocessed++;
1865 dol_syslog(
" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
1870 if ($searchfilterisanswer > 0) {
1871 if (empty($headers[
'In-Reply-To'])) {
1872 $nbemailprocessed++;
1873 dol_syslog(
" Discarded - Email is not an answer (no In-Reply-To header)");
1877 if (preg_match(
'/^(Re|AW)\s*:\s+/i', $headers[
'Subject'])) {
1883 if (!empty($headers[
'In-Reply-To'])) {
1891 $nbemailprocessed++;
1892 dol_syslog(
" Discarded - Email is not an answer (no RE prefix in subject)");
1896 if ($searchfilterisnotanswer > 0) {
1897 if (!empty($headers[
'In-Reply-To'])) {
1901 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
1907 $nbemailprocessed++;
1908 dol_syslog(
" Discarded - Email is an answer");
1913 if ($searchfilterreplyto > 0) {
1914 if (!empty($headers[
'Reply-To'])) {
1916 foreach ($rulesreplyto as $key => $rulereplyto) {
1917 if (preg_match(
'/'.preg_quote($rulereplyto,
'/').
'/', $headers[
'Reply-To'])) {
1922 if (!$isreplytook || $isreplytook != count($rulesreplyto)) {
1923 $nbemailprocessed++;
1924 dol_syslog(
" Discarded - Reply-to does not match");
1932 $thirdpartystatic =
new Societe($this->db);
1933 $contactstatic =
new Contact($this->db);
1934 $projectstatic =
new Project($this->db);
1936 $nbactiondoneforemail = 0;
1938 $errorforactions = 0;
1939 $thirdpartyfoundby =
'';
1940 $contactfoundby =
'';
1941 $projectfoundby =
'';
1942 $ticketfoundby =
'';
1943 $candidaturefoundby =
'';
1947 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".
dol_print_date($overview[
'date'],
'dayrfc',
'gmt').
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
1952 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);
1962 global $htmlmsg, $plainmsg, $charset, $attachments;
1966 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1967 if ($imapemail->hasHTMLBody()) {
1968 $htmlmsg = $imapemail->getHTMLBody();
1970 if ($imapemail->hasTextBody() && $imapemail->getTextBody() !=
"\n") {
1971 $plainmsg = $imapemail->getTextBody();
1973 if ($imapemail->hasAttachments()) {
1974 $attachments = $imapemail->getAttachments()->all();
1979 $this->
getmsg($connection, $imapemail);
1981 '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments';
1993 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
1994 dol_syslog(
" Discarded - Email body is not valid utf8");
1998 if (!empty($searchfilterexcludebodyarray)) {
1999 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
2000 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
2001 $nbemailprocessed++;
2002 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
2003 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
2065 $replytostring =
'';
2068 $fromstring = $overview[
'from'];
2069 $replytostring = empty($overview[
'in_reply-to']) ? $headers[
'Reply-To'] : $overview[
'in_reply-to'];
2071 $sender = $overview[
'sender'];
2072 $to = $overview[
'to'];
2073 $sendtocc = empty($overview[
'cc']) ?
'' : $overview[
'cc'];
2074 $sendtobcc = empty($overview[
'bcc']) ?
'' : $overview[
'bcc'];
2076 $tmpdate = $overview[
'date']->toDate();
2077 $tmptimezone = $tmpdate->getTimezone()->getName();
2080 if (preg_match(
'/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) {
2081 if ($reg[1] ==
'+' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2082 $dateemail -= (3600 * (int) $reg[2]);
2083 $dateemail -= (60 * (int) $reg[3]);
2085 if ($reg[1] ==
'-' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2086 $dateemail += (3600 * (int) $reg[2]);
2087 $dateemail += (60 * (int) $reg[3]);
2090 $subject = $overview[
'subject'];
2092 $fromstring = $overview[0]->from;
2093 $replytostring = (!empty($overview[
'in_reply-to']) ? $overview[
'in_reply-to'] : (!empty($headers[
'Reply-To']) ? $headers[
'Reply-To'] :
"")) ;
2095 $sender = !empty($overview[0]->sender) ? $overview[0]->sender :
'';
2096 $to = $overview[0]->to;
2097 $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc :
'';
2098 $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc :
'';
2100 $subject = $overview[0]->subject;
2104 if (!empty($searchfilterexcludesubjectarray)) {
2105 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
2106 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
2107 $nbemailprocessed++;
2108 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
2109 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
2116 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
2118 $fromtext = $reg[1];
2120 $from = $fromstring;
2123 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
2125 $replytotext = $reg[1];
2127 $replyto = $replytostring;
2131 $fk_element_type =
'';
2148 $objectemail =
null;
2151 $arrayofreferences = array();
2152 if (!empty($headers[
'References'])) {
2153 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
2155 if (!in_array(
'<'.$msgid.
'>', $arrayofreferences)) {
2156 $arrayofreferences = array_merge($arrayofreferences, array(
'<'.$msgid.
'>'));
2161 foreach ($arrayofreferences as $reference) {
2163 if (!empty($trackidfoundintorecipienttype)) {
2164 $resultsearchtrackid = -1;
2165 $reg[1] = $trackidfoundintorecipienttype;
2166 $reg[2] = $trackidfoundintorecipientid;
2167 } elseif (!empty($trackidfoundintomsgidtype)) {
2168 $resultsearchtrackid = -1;
2169 $reg[1] = $trackidfoundintomsgidtype;
2170 $reg[2] = $trackidfoundintomsgidid;
2172 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
2173 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2174 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
2178 if (!empty($resultsearchtrackid)) {
2180 $trackid = $reg[1].$reg[2];
2182 $objectid = $reg[2];
2184 if ($reg[1] ==
'thi') {
2185 $objectemail =
new Societe($this->db);
2187 if ($reg[1] ==
'ctc') {
2188 $objectemail =
new Contact($this->db);
2190 if ($reg[1] ==
'inv') {
2191 $objectemail =
new Facture($this->db);
2193 if ($reg[1] ==
'sinv') {
2196 if ($reg[1] ==
'pro') {
2197 $objectemail =
new Propal($this->db);
2199 if ($reg[1] ==
'ord') {
2200 $objectemail =
new Commande($this->db);
2202 if ($reg[1] ==
'shi') {
2205 if ($reg[1] ==
'spro') {
2208 if ($reg[1] ==
'sord') {
2211 if ($reg[1] ==
'rec') {
2212 $objectemail =
new Reception($this->db);
2214 if ($reg[1] ==
'proj') {
2215 $objectemail =
new Project($this->db);
2216 $projectfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2218 if ($reg[1] ==
'tas') {
2219 $objectemail =
new Task($this->db);
2221 if ($reg[1] ==
'con') {
2222 $objectemail =
new Contact($this->db);
2224 if ($reg[1] ==
'use') {
2225 $objectemail =
new User($this->db);
2227 if ($reg[1] ==
'tic') {
2228 $objectemail =
new Ticket($this->db);
2229 $ticketfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2231 if ($reg[1] ==
'recruitmentcandidature') {
2233 $candidaturefoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2235 if ($reg[1] ==
'mem') {
2236 $objectemail =
new Adherent($this->db);
2244 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
2246 if (is_null($objectemail) && isModEnabled(
'ticket')) {
2247 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket";
2248 $sql .=
" WHERE email_msgid = '".$this->db->escape($reg[1]).
"' OR origin_references like '%".$this->db->escape($this->db->escapeforlike($reg[1])).
"%'";
2249 $resql = $this->db->query($sql);
2251 $obj = $this->db->fetch_object($resql);
2253 $objectid = $obj->rowid;
2254 $objectemail =
new Ticket($this->db);
2255 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2262 if (!is_object($objectemail) && isModEnabled(
'project')) {
2263 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2264 $resql = $this->db->query($sql);
2266 $obj = $this->db->fetch_object($resql);
2268 $objectid = $obj->rowid;
2269 $objectemail =
new Project($this->db);
2270 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2277 if (!is_object($objectemail) && isModEnabled(
'recruitment')) {
2278 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2279 $resql = $this->db->query($sql);
2281 $obj = $this->db->fetch_object($resql);
2283 $objectid = $obj->rowid;
2285 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2294 if (is_object($objectemail)) {
2295 $result = $objectemail->fetch($objectid);
2297 $fk_element_id = $objectemail->id;
2298 $fk_element_type = $objectemail->element;
2300 if ($fk_element_type ==
'facture') {
2301 $fk_element_type =
'invoice';
2304 if (get_class($objectemail) !=
'Societe') {
2305 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2307 $thirdpartyid = $objectemail->id;
2310 if (get_class($objectemail) !=
'Contact') {
2311 $contactid = $objectemail->fk_socpeople;
2313 $contactid = $objectemail->id;
2316 if (get_class($objectemail) !=
'Project') {
2317 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2319 $projectid = $objectemail->id;
2322 if ($objectemail instanceof
Ticket) {
2323 $ticketid = $objectemail->id;
2325 $changeonticket_references =
false;
2326 if (empty($trackid)) {
2327 $trackid = $objectemail->track_id;
2329 if (empty($objectemail->origin_references)) {
2330 $objectemail->origin_references = !empty($headers[
'References']) ? $headers[
'References'] :
null;
2331 $changeonticket_references =
true;
2333 foreach ($arrayofreferences as $key => $referencetmp) {
2334 if (!str_contains($objectemail->origin_references, $referencetmp)) {
2335 $objectemail->origin_references .=
" ".$referencetmp;
2336 $changeonticket_references =
true;
2340 if ($changeonticket_references) {
2341 $objectemail->update($user, 1);
2348 if ($projectid > 0) {
2349 $result = $projectstatic->fetch($projectid);
2351 $projectstatic->id = 0;
2353 $projectid = $projectstatic->id;
2355 $projectfoundby =
'trackid ('.$trackid.
')';
2357 if (empty($contactid)) {
2358 $contactid = $projectstatic->fk_contact;
2360 if (empty($thirdpartyid)) {
2361 $thirdpartyid = $projectstatic->fk_soc;
2366 if ($contactid > 0) {
2367 $result = $contactstatic->fetch($contactid);
2369 $contactstatic->id = 0;
2371 $contactid = $contactstatic->id;
2373 $contactfoundby =
'trackid ('.$trackid.
')';
2375 if (empty($thirdpartyid)) {
2376 $thirdpartyid = $contactstatic->fk_soc;
2381 if ($thirdpartyid > 0) {
2382 $result = $thirdpartystatic->fetch($thirdpartyid);
2384 $thirdpartystatic->id = 0;
2386 $thirdpartyid = $thirdpartystatic->id;
2388 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2393 if (is_object($objectemail)) {
2398 if (empty($contactid)) {
2399 $result = $contactstatic->fetch(0,
null,
'', $from);
2402 dol_syslog(
"We found a contact with the email ".$from);
2403 $contactid = $contactstatic->id;
2404 $contactfoundby =
'email of contact ('.$from.
')';
2405 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2406 $result = $thirdpartystatic->fetch($contactstatic->socid);
2408 $thirdpartyid = $thirdpartystatic->id;
2409 $thirdpartyfoundby =
'email of contact ('.$from.
')';
2415 if (empty($thirdpartyid)) {
2416 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
2418 dol_syslog(
"We found a thirdparty with the email ".$from);
2419 $thirdpartyid = $thirdpartystatic->id;
2420 $thirdpartyfoundby =
'email ('.$from.
')';
2456 foreach ($this->actions as $operation) {
2457 $errorforthisaction = 0;
2458 $ticketalreadyexists = 0;
2459 if ($errorforactions) {
2462 if (empty($operation[
'status'])) {
2466 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2469 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2470 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2473 $actioncode =
'EMAIL_IN';
2475 if (preg_match(
'/Sent$/', $sourcedir) || preg_match(
'/envoyés$/i', $sourcedir)) {
2476 $actioncode =
'EMAIL';
2479 $arrayofemailtoconsideresender = explode(
',',
getDolGlobalString(
'MAIL_FROM_EMAILS_TO_CONSIDER_SENDING'));
2480 foreach ($arrayofemailtoconsideresender as $emailtoconsidersender) {
2481 if (preg_match(
'/'.preg_quote($emailtoconsidersender,
'/').
'/', $fromstring)) {
2482 $actioncode =
'EMAIL';
2485 $operationslog .=
'<br>Email will have actioncode='.$actioncode;
2487 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2489 $descriptiontitle = $langs->transnoentitiesnoconv(
"RecordCreatedByEmailCollector", $this->
ref);
2494 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2496 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2498 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2500 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailReply").($langs->trans(
"MailReply") !=
'Reply to' ?
' (Reply to)' :
'').
' : '.
dol_escape_htmltag($replyto));
2503 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2506 if ($operation[
'type'] ==
'ticket') {
2508 $tickettocreate =
new Ticket($this->db);
2509 $errorfetchticket = 0;
2510 $alreadycreated = 0;
2511 if (!empty($trackid)) {
2512 $alreadycreated = $tickettocreate->fetch(0,
'', $trackid);
2514 if ($alreadycreated == 0 && !empty($msgid)) {
2515 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2517 if ($alreadycreated < 0) {
2518 $errorfetchticket++;
2520 if (empty($errorfetchticket)) {
2521 if ($alreadycreated == 0) {
2522 $operationslog .=
'<br>Ticket not found using trackid='.$trackid.
' or msgid='.$msgid;
2523 $ticketalreadyexists = 0;
2525 $operationslog .=
'<br>Ticket already found using trackid='.$trackid.
' or msgid='.$msgid;
2526 $ticketalreadyexists = 1;
2527 $operation[
'type'] =
'recordevent';
2530 $ticketalreadyexists = -1;
2537 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2538 if (empty($operation[
'actionparam'])) {
2540 $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;";
2541 $this->errors[] = $this->error;
2543 $actionparam = $operation[
'actionparam'];
2544 $idtouseforthirdparty =
'';
2545 $nametouseforthirdparty =
'';
2546 $emailtouseforthirdparty =
'';
2547 $namealiastouseforthirdparty =
'';
2549 $operationslog .=
'<br>Loop on each property to set into actionparam';
2553 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2557 $regforregex = array();
2559 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2560 $sourcefield = $regforregex[1];
2561 $regexstring = $regforregex[2];
2564 if (!empty($sourcefield) && !empty($regexstring)) {
2565 if (strtolower($sourcefield) ==
'body') {
2566 $sourcestring = $messagetext;
2567 } elseif (strtolower($sourcefield) ==
'subject') {
2568 $sourcestring = $subject;
2569 } elseif (strtolower($sourcefield) ==
'header') {
2570 $sourcestring = $header;
2573 if ($sourcestring) {
2574 $regforval = array();
2576 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2579 if ($propertytooverwrite ==
'id') {
2580 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2582 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2583 } elseif ($propertytooverwrite ==
'email') {
2584 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2586 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2587 } elseif ($propertytooverwrite ==
'name') {
2588 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2590 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2591 } elseif ($propertytooverwrite ==
'name_alias') {
2592 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2594 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2596 $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';
2600 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2601 $idtouseforthirdparty =
null;
2602 $nametouseforthirdparty =
null;
2603 $emailtouseforthirdparty =
null;
2604 $namealiastouseforthirdparty =
null;
2606 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2608 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2615 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2616 $this->errors[] = $this->error;
2618 $operationslog .=
'<br>'.$this->error;
2620 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2624 if ($propertytooverwrite ==
'id') {
2625 $idtouseforthirdparty = $reg[2];
2627 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2628 } elseif ($propertytooverwrite ==
'email') {
2629 $emailtouseforthirdparty = $reg[2];
2631 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2632 } elseif ($propertytooverwrite ==
'name') {
2633 $nametouseforthirdparty = $reg[2];
2635 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2636 } elseif ($propertytooverwrite ==
'name_alias') {
2637 $namealiastouseforthirdparty = $reg[2];
2639 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2643 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2644 $this->errors[] = $this->error;
2649 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2651 $operationslog .=
'<br>We have this initial main data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty.
'.';
2654 $tmpobject->element =
'generic';
2655 $tmpobject->id = $idtouseforthirdparty;
2656 $tmpobject->name = $nametouseforthirdparty;
2657 $tmpobject->name_alias = $namealiastouseforthirdparty;
2658 $tmpobject->email = $emailtouseforthirdparty;
2662 $idtouseforthirdparty = $tmpobject->id;
2663 $nametouseforthirdparty = $tmpobject->name;
2664 $namealiastouseforthirdparty = $tmpobject->name_alias;
2665 $emailtouseforthirdparty = $tmpobject->email;
2667 $operationslog .=
'<br>We try to search existing thirdparty with idtouseforthirdparty='.$idtouseforthirdparty.
' emailtouseforthirdparty='.$emailtouseforthirdparty.
' nametouseforthirdparty='.$nametouseforthirdparty.
' namealiastouseforthirdparty='.$namealiastouseforthirdparty;
2670 $result = $thirdpartystatic->findNearest($idtouseforthirdparty, $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', $emailtouseforthirdparty, $namealiastouseforthirdparty);
2674 $this->error =
'Error when getting thirdparty with name '.$nametouseforthirdparty.
' (may be 2 record exists with same name ?)';
2675 $this->errors[] = $this->error;
2677 } elseif ($result == 0) {
2678 if ($operation[
'type'] ==
'loadthirdparty') {
2679 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2682 $resultContact = $contactstatic->findNearest(0,
'',
'',
'', $emailtouseforthirdparty,
'', 0);
2683 if ($resultContact > 0) {
2684 $contactstatic->fetch($resultContact);
2685 $idtouseforthirdparty = $contactstatic->socid;
2686 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2688 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2691 $langs->load(
"errors");
2692 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2693 $this->errors[] = $this->error;
2697 $langs->load(
"errors");
2698 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2699 $this->errors[] = $this->error;
2701 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2702 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
2705 $thirdpartystatic =
new Societe($db);
2706 $thirdpartystatic->name = (string) $nametouseforthirdparty;
2707 if (!empty($namealiastouseforthirdparty)) {
2708 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
2709 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
2712 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'' : $fromtext) : $replytostring);
2714 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ?
'' : $from) : $replyto) : $emailtouseforthirdparty);
2717 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2719 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
2720 $thirdpartystatic->code_client =
'auto';
2722 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
2723 $thirdpartystatic->code_fournisseur =
'auto';
2726 if ($errorforthisaction) {
2729 $result = $thirdpartystatic->create($user);
2732 $this->error = $thirdpartystatic->error;
2733 $this->errors = $thirdpartystatic->errors;
2735 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag($thirdpartystatic->id);
2740 dol_syslog(
"One and only one existing third party has been found");
2742 $thirdpartystatic->fetch($result);
2744 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag($thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name);
2748 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
2749 if (empty($operation[
'actionparam'])) {
2751 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
2752 $this->errors[] = $this->error;
2754 $contact_static =
new Contact($this->db);
2756 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2757 if ($errorforthisaction) {
2760 if (!empty($contact_static->email) && $contact_static->email != $from) {
2761 $from = $contact_static->email;
2764 $result = $contactstatic->fetch(0,
null,
'', $from);
2767 $this->error =
'Error when getting contact with email ' . $from;
2768 $this->errors[] = $this->error;
2770 } elseif ($result == 0) {
2771 dol_syslog(
"Contact with email " . $from .
" was not found. We try to create it.");
2772 $contactstatic =
new Contact($this->db);
2775 $contactstatic->email = $from;
2776 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($from);
2779 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2781 if ($errorforthisaction) {
2785 if (!empty($contactstatic->country)) {
2786 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2787 $result =
getCountry(
'',
'3', $this->db,
null, 1, $contactstatic->country);
2788 if ($result ==
'NotDefined') {
2790 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
2791 } elseif (!($result > 0)) {
2793 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
2794 $this->errors[] = $this->db->lasterror();
2796 $contactstatic->country_id = $result;
2797 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2799 } elseif (!empty($contactstatic->country_code)) {
2800 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2801 $result =
getCountry($contactstatic->country_code,
'3', $this->db);
2802 if ($result ==
'NotDefined') {
2804 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
2805 } elseif (!($result > 0)) {
2807 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
2808 $this->errors[] = $this->db->lasterror();
2810 $contactstatic->country_id = $result;
2811 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2815 if (!$errorforactions) {
2817 if (!empty($contactstatic->state)) {
2818 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2819 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
2820 if (empty($result)) {
2822 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
2823 } elseif (!($result > 0)) {
2825 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
2826 $this->errors[] = $this->db->lasterror();
2828 $contactstatic->state_id = $result;
2829 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2831 } elseif (!empty($contactstatic->state_code)) {
2832 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2833 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
2834 if (empty($result)) {
2836 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
2837 } elseif (!($result > 0)) {
2839 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
2840 $this->errors[] = $this->db->lasterror();
2842 $contactstatic->state_id = $result;
2843 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2848 if (!$errorforactions) {
2849 $result = $contactstatic->create($user);
2852 $this->error = $contactstatic->error;
2853 $this->errors = $contactstatic->errors;
2855 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag($contactstatic->id);
2862 } elseif ($operation[
'type'] ==
'recordevent') {
2866 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
2867 if ($alreadycreated == 0) {
2868 $operationslog .=
'<br>We did not find existing actionmail with msgid='.$msgid;
2870 if ($projectstatic->id > 0) {
2871 if ($projectfoundby) {
2872 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
2875 if ($thirdpartystatic->id > 0) {
2876 if ($thirdpartyfoundby) {
2877 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2880 if ($contactstatic->id > 0) {
2881 if ($contactfoundby) {
2882 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2886 $description = $descriptiontitle;
2892 $descriptionfull = $description;
2894 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2899 $actioncomm->type_code =
'AC_OTH_AUTO';
2900 $actioncomm->code =
'AC_'.$actioncode;
2901 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
2902 $actioncomm->note_private = $descriptionfull;
2903 $actioncomm->fk_project = $projectstatic->id;
2904 $actioncomm->datep = $dateemail;
2905 $actioncomm->datef = $dateemail;
2906 $actioncomm->percentage = -1;
2907 $actioncomm->socid = $thirdpartystatic->id;
2908 $actioncomm->contact_id = $contactstatic->id;
2909 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array());
2910 $actioncomm->authorid = $user->id;
2911 $actioncomm->userownerid = $user->id;
2913 $actioncomm->email_msgid = $msgid;
2914 $actioncomm->email_from = $fromstring;
2915 $actioncomm->email_sender = $sender;
2916 $actioncomm->email_to = $to;
2917 $actioncomm->email_tocc = $sendtocc;
2918 $actioncomm->email_tobcc = $sendtobcc;
2919 $actioncomm->email_subject = $subject;
2920 $actioncomm->errors_to =
'';
2922 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
2923 $actioncomm->fk_element = $fk_element_id;
2924 $actioncomm->elementid = $fk_element_id;
2925 $actioncomm->elementtype = $fk_element_type;
2926 if (is_object($objectemail) && $objectemail->module) {
2927 $actioncomm->elementtype .=
'@'.$objectemail->module;
2934 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2936 if ($errorforthisaction) {
2939 $result = $actioncomm->create($user);
2942 $this->errors = $actioncomm->errors;
2944 if ($fk_element_type ==
"ticket" && is_object($objectemail)) {
2945 if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED || $objectemail->status == Ticket::STATUS_NEED_MORE_INFO || $objectemail->status == Ticket::STATUS_WAITING) {
2946 if ($objectemail->fk_user_assign !=
null) {
2947 $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED);
2949 $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ);
2953 $operationslog .=
'<br>Ticket Re-Opened successfully -> ref='.$objectemail->ref;
2956 $this->error =
'Error while changing the ticket status -> ref='.$objectemail->ref;
2957 $this->errors[] = $this->error;
2960 if (!empty($attachments)) {
2962 $ticket =
new Ticket($this->db);
2963 $ticket->fetch($fk_element_id);
2964 $destdir =
$conf->ticket->dir_output.
'/'.$ticket->ref;
2969 foreach ($attachments as $attachment) {
2970 $attachment->save($destdir.
'/');
2973 $this->
getmsg($connection, $imapemail, $destdir);
2978 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag($actioncomm->id);
2982 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
2985 foreach ($attachments as $attachment) {
2986 if ($attachment->getName() ===
'undefined') {
2989 $data[$attachment->getName()] = $attachment->getContent();
2993 foreach ($pj as $key => $val) {
2994 $data[$val[
'filename']] =
getFileData($imapemail, (
string) $val[
'pos'], $val[
'type'], $connection);
2997 if (count($data) > 0) {
2998 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($from).
"%'";
2999 $resql = $this->db->query($sql);
3000 if ($this->db->num_rows($resql) == 0) {
3001 $this->errors[] =
"User Not allowed to add documents ({$from})";
3003 $arrayobject = array(
3004 'propale' => array(
'table' =>
'propal',
3005 'fields' => array(
'ref'),
3006 'class' =>
'comm/propal/class/propal.class.php',
3007 'object' =>
'Propal'),
3008 'holiday' => array(
'table' =>
'holiday',
3009 'fields' => array(
'ref'),
3010 'class' =>
'holiday/class/holiday.class.php',
3011 'object' =>
'Holiday'),
3012 'expensereport' => array(
'table' =>
'expensereport',
3013 'fields' => array(
'ref'),
3014 'class' =>
'expensereport/class/expensereport.class.php',
3015 'object' =>
'ExpenseReport'),
3016 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
3017 'fields' => array(
'ref'),
3018 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
3019 'object' =>
'RecruitmentJobPosition'),
3020 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
3021 'fields' => array(
'ref'),
3022 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
3023 'object' =>
'RecruitmentCandidature'),
3024 'societe' => array(
'table' =>
'societe',
3025 'fields' => array(
'code_client',
'code_fournisseur'),
3026 'class' =>
'societe/class/societe.class.php',
3027 'object' =>
'Societe'),
3028 'commande' => array(
'table' =>
'commande',
3029 'fields' => array(
'ref'),
3030 'class' =>
'commande/class/commande.class.php',
3031 'object' =>
'Commande'),
3032 'expedition' => array(
'table' =>
'expedition',
3033 'fields' => array(
'ref'),
3034 'class' =>
'expedition/class/expedition.class.php',
3035 'object' =>
'Expedition'),
3036 'contract' => array(
'table' =>
'contrat',
3037 'fields' => array(
'ref'),
3038 'class' =>
'contrat/class/contrat.class.php',
3039 'object' =>
'Contrat'),
3040 'fichinter' => array(
'table' =>
'fichinter',
3041 'fields' => array(
'ref'),
3042 'class' =>
'fichinter/class/fichinter.class.php',
3043 'object' =>
'Fichinter'),
3044 'ticket' => array(
'table' =>
'ticket',
3045 'fields' => array(
'ref'),
3046 'class' =>
'ticket/class/ticket.class.php',
3047 'object' =>
'Ticket'),
3048 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
3049 'fields' => array(
'ref'),
3050 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
3051 'object' =>
'KnowledgeRecord'),
3052 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
3053 'fields' => array(
'ref'),
3054 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
3055 'object' =>
'SupplierProposal'),
3056 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
3057 'fields' => array(
'ref',
'ref_supplier'),
3058 'class' =>
'fourn/class/fournisseur.commande.class.php',
3059 'object' =>
'SupplierProposal'),
3060 'facture' => array(
'table' =>
'facture',
3061 'fields' => array(
'ref'),
3062 'class' =>
'compta/facture/class/facture.class.php',
3063 'object' =>
'Facture'),
3064 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
3065 'fields' => array(
'ref',
'ref_client'),
3066 'class' =>
'fourn/class/fournisseur.facture.class.php',
3067 'object' =>
'FactureFournisseur'),
3068 'produit' => array(
'table' =>
'product',
3069 'fields' => array(
'ref'),
3070 'class' =>
'product/class/product.class.php',
3071 'object' =>
'Product'),
3072 'productlot' => array(
'table' =>
'product_lot',
3073 'fields' => array(
'batch'),
3074 'class' =>
'product/stock/class/productlot.class.php',
3075 'object' =>
'Productlot'),
3076 'projet' => array(
'table' =>
'projet',
3077 'fields' => array(
'ref'),
3078 'class' =>
'projet/class/projet.class.php',
3079 'object' =>
'Project'),
3080 'projet_task' => array(
'table' =>
'projet_task',
3081 'fields' => array(
'ref'),
3082 'class' =>
'projet/class/task.class.php',
3083 'object' =>
'Task'),
3084 'ressource' => array(
'table' =>
'resource',
3085 'fields' => array(
'ref'),
3086 'class' =>
'ressource/class/dolressource.class.php',
3087 'object' =>
'Dolresource'),
3088 'bom' => array(
'table' =>
'bom_bom',
3089 'fields' => array(
'ref'),
3090 'class' =>
'bom/class/bom.class.php',
3092 'mrp' => array(
'table' =>
'mrp_mo',
3093 'fields' => array(
'ref'),
3094 'class' =>
'mrp/class/mo.class.php',
3098 if (!is_object($hookmanager)) {
3099 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3102 $hookmanager->initHooks(array(
'emailcolector'));
3103 $parameters = array(
'arrayobject' => $arrayobject);
3104 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
3106 $arrayobject = $hookmanager->resArray;
3109 $resultobj = array();
3111 foreach ($arrayobject as $key => $objectdesc) {
3112 $sql =
'SELECT DISTINCT t.rowid ';
3113 $sql .=
' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc[
'table']) .
' AS t';
3115 foreach ($objectdesc[
'fields'] as $field) {
3116 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $this->db->sanitize($field) .
", '%') AND t." . $this->db->sanitize($field) .
" <> '') OR ";
3118 $sql = substr($sql, 0, -4);
3120 $ressqlobj = $this->db->query($sql);
3122 while ($obj = $this->db->fetch_object($ressqlobj)) {
3123 $resultobj[$key][] = $obj->rowid;
3128 foreach ($resultobj as $mod => $ids) {
3129 $moddesc = $arrayobject[$mod];
3130 $elementpath = $mod;
3132 $objectmanaged =
new $moddesc[
'object']($this->db);
3133 '@phan-var-force CommonObject $objectmanaged';
3134 foreach ($ids as $val) {
3135 $res = $objectmanaged->fetch($val);
3137 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
3138 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
3140 $this->errors[] =
'object not found';
3144 foreach ($dirs as $target) {
3145 $prefix = $this->actions[$this->id][
'actionparam'];
3146 foreach ($data as $filename => $content) {
3147 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
3149 $this->errors[] =
'Doc not saved';
3154 $operationslog .=
'<br>Save attachment files on disk';
3156 $this->errors[] =
'no joined piece';
3158 $operationslog .=
'<br>No joinded files';
3160 } elseif ($operation[
'type'] ==
'project') {
3162 $projecttocreate =
new Project($this->db);
3163 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
3164 if ($alreadycreated == 0) {
3165 if ($thirdpartystatic->id > 0) {
3166 $projecttocreate->socid = $thirdpartystatic->id;
3167 if ($thirdpartyfoundby) {
3168 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3171 if ($contactstatic->id > 0) {
3172 $projecttocreate->contact_id = $contactstatic->id;
3173 if ($contactfoundby) {
3174 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3178 $description = $descriptiontitle;
3184 $descriptionfull = $description;
3186 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3190 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
3191 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
3193 $projecttocreate->title = $subject;
3194 $projecttocreate->date_start = $dateemail;
3195 $projecttocreate->date_end = 0;
3196 $projecttocreate->opp_status = $id_opp_status;
3197 $projecttocreate->opp_percent = $percent_opp_status;
3199 $projecttocreate->note_private = $descriptionfull;
3200 $projecttocreate->entity =
$conf->entity;
3202 $projecttocreate->email_date = $dateemail;
3203 $projecttocreate->email_msgid = $msgid;
3204 $projecttocreate->email_from = $fromstring;
3205 $projecttocreate->email_sender = $sender;
3206 $projecttocreate->email_to = $to;
3207 $projecttocreate->email_tocc = $sendtocc;
3208 $projecttocreate->email_tobcc = $sendtobcc;
3209 $projecttocreate->email_subject = $subject;
3210 $projecttocreate->errors_to =
'';
3212 $savesocid = $projecttocreate->socid;
3216 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3220 if (empty($projecttocreate->ref)) {
3229 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
3230 foreach ($dirmodels as $reldir) {
3231 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
3232 if (file_exists($file)) {
3233 $classname = $modele;
3238 if ($classname !==
'') {
3239 if ($savesocid > 0) {
3240 if ($savesocid != $projecttocreate->socid) {
3242 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');
3245 if ($projecttocreate->socid > 0) {
3246 $thirdpartystatic->fetch($projecttocreate->socid);
3250 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
3251 $modModuleToUseForNextValue =
new $classname();
3252 '@phan-var-force ModeleNumRefProjects $modModuleToUseForNextValue';
3253 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
3255 $projecttocreate->ref = $defaultref;
3259 if ($errorforthisaction) {
3262 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
3264 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3266 $operationslog .=
'<br>'.$this->error;
3269 $result = $projecttocreate->create($user);
3272 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
3273 $this->errors = $projecttocreate->errors;
3275 $operationslog .=
'<br>'.$this->error;
3278 $destdir =
$conf->project->dir_output.
'/'.$projecttocreate->ref;
3283 foreach ($attachments as $attachment) {
3285 $typeattachment = (string) $attachment->getDisposition();
3286 $filename = $attachment->getFilename();
3287 $content = $attachment->getContent();
3291 $this->
getmsg($connection, $imapemail, $destdir);
3294 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag($projecttocreate->id);
3296 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag($projecttocreate->id);
3304 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3306 } elseif ($operation[
'type'] ==
'ticket') {
3308 $tickettocreate =
new Ticket($this->db);
3309 if ($ticketalreadyexists == 0) {
3310 if ($thirdpartystatic->id > 0) {
3311 $tickettocreate->socid = $thirdpartystatic->id;
3312 $tickettocreate->fk_soc = $thirdpartystatic->id;
3313 if ($thirdpartyfoundby) {
3314 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3317 if ($contactstatic->id > 0) {
3318 $tickettocreate->contact_id = $contactstatic->id;
3319 if ($contactfoundby) {
3320 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3324 $description = $descriptiontitle;
3330 $descriptionfull = $description;
3332 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3336 $tickettocreate->subject = $subject;
3337 $tickettocreate->message = $description;
3339 $tickettocreate->category_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1)));
3340 $tickettocreate->severity_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1)));
3341 $tickettocreate->origin_email = $from;
3342 $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto :
null);
3343 $tickettocreate->origin_references = (!empty($headers[
'References']) ? $headers[
'References'] :
null);
3344 $tickettocreate->fk_user_create = $user->id;
3345 $tickettocreate->datec =
dol_now();
3346 $tickettocreate->fk_project = $projectstatic->id;
3347 $tickettocreate->notify_tiers_at_create =
getDolGlobalInt(
'TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3348 $tickettocreate->note_private = $descriptionfull;
3349 $tickettocreate->entity =
$conf->entity;
3351 $tickettocreate->email_date = $dateemail;
3352 $tickettocreate->email_msgid = $msgid;
3353 $tickettocreate->email_from = $fromstring;
3354 $tickettocreate->email_sender = $sender;
3355 $tickettocreate->email_to = $to;
3356 $tickettocreate->email_tocc = $sendtocc;
3357 $tickettocreate->email_tobcc = $sendtobcc;
3358 $tickettocreate->email_subject = $subject;
3359 $tickettocreate->errors_to =
'';
3363 $savesocid = $tickettocreate->socid;
3367 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3369 $modele =
'UNDEFINED';
3371 if (empty($tickettocreate->ref)) {
3380 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
3381 foreach ($dirmodels as $reldir) {
3382 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3383 if (file_exists($file)) {
3384 $classname = $modele;
3389 if ($classname !==
'') {
3390 if ($savesocid > 0) {
3391 if ($savesocid != $tickettocreate->socid) {
3393 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');
3396 if ($tickettocreate->socid > 0) {
3397 $thirdpartystatic->fetch($tickettocreate->socid);
3402 $modModuleToUseForNextValue =
new $classname();
3403 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3404 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3406 $tickettocreate->ref = $defaultref;
3409 if ($errorforthisaction) {
3412 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3414 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3417 $tickettocreate->context[
'actionmsg2'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3418 $tickettocreate->context[
'actionmsg'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3422 $sender_contact =
new Contact($this->db);
3423 $sender_contact->fetch(0,
null,
'', $from);
3424 if (!empty($sender_contact->id)) {
3425 $tickettocreate->context[
'contactid'] = $sender_contact->id;
3428 $result = $tickettocreate->create($user);
3431 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3432 $this->errors = $tickettocreate->errors;
3435 $destdir =
$conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3440 foreach ($attachments as $attachment) {
3442 $typeattachment = (string) $attachment->getDisposition();
3443 $filename = $attachment->getName();
3444 $content = $attachment->getContent();
3448 $this->
getmsg($connection, $imapemail, $destdir);
3451 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3453 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3459 } elseif ($operation[
'type'] ==
'candidature') {
3463 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3464 if ($alreadycreated == 0) {
3465 $description = $descriptiontitle;
3471 $descriptionfull = $description;
3472 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3475 $candidaturetocreate->subject = $subject;
3476 $candidaturetocreate->message = $description;
3477 $candidaturetocreate->type_code = 0;
3478 $candidaturetocreate->category_code =
null;
3479 $candidaturetocreate->severity_code =
null;
3480 $candidaturetocreate->email = $from;
3482 $candidaturetocreate->fk_user_creat = $user->id;
3483 $candidaturetocreate->date_creation =
dol_now();
3484 $candidaturetocreate->fk_project = $projectstatic->id;
3485 $candidaturetocreate->description = $description;
3486 $candidaturetocreate->note_private = $descriptionfull;
3487 $candidaturetocreate->entity =
$conf->entity;
3488 $candidaturetocreate->email_msgid = $msgid;
3489 $candidaturetocreate->email_date = $dateemail;
3490 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3495 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3538 if ($errorforthisaction) {
3542 $result = $candidaturetocreate->create($user);
3545 $this->error =
'Failed to create candidature: '.implode(
', ', $candidaturetocreate->errors);
3546 $this->errors = $candidaturetocreate->errors;
3549 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag($candidaturetocreate->id);
3552 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3555 if (!is_object($hookmanager)) {
3556 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3559 $hookmanager->initHooks([
'emailcolector']);
3561 $parameters = array(
3562 'connection' => $connection,
3563 'imapemail' => $imapemail,
3564 'overview' => $overview,
3567 'fromtext' => $fromtext,
3569 'actionparam' => $operation[
'actionparam'],
3571 'thirdpartyid' => $thirdpartyid,
3572 'objectid' => $objectid,
3573 'objectemail' => $objectemail,
3575 'messagetext' => $messagetext,
3576 'subject' => $subject,
3577 'header' => $header,
3578 'attachments' => $attachments,
3580 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3583 $errorforthisaction++;
3584 $this->error = $hookmanager->resPrint;
3586 if ($errorforthisaction) {
3588 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3590 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3594 if (!$errorforactions) {
3595 $nbactiondoneforemail++;
3601 if (!$errorforactions) {
3602 if (!empty($targetdir)) {
3605 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3606 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid.
' - '.$imapemail->getHeader()->get(
'subject').
' to '.$targetdir;
3608 $arrayofemailtodelete[$this->
uidAsString($imapemail)] = $imapemail;
3611 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3612 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3614 $arrayofemailtodelete[$imapemail] = $msgid;
3619 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);
3621 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3629 unset($objectemail);
3630 unset($projectstatic);
3631 unset($thirdpartystatic);
3632 unset($contactstatic);
3634 $nbemailprocessed++;
3636 if (!$errorforemail) {
3637 $nbactiondone += $nbactiondoneforemail;
3641 $this->db->commit();
3643 $this->db->rollback();
3647 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3648 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3649 $datelastok = strtotime($headers[
'Date']);
3655 $this->db->rollback();
3659 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3661 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3663 $langs->load(
"admin");
3664 $output = $langs->trans(
'NoNewEmailToProcess');
3665 $output .=
' (defaultlang='.$langs->defaultlang.
')';
3671 krsort($arrayofemailtodelete, SORT_NUMERIC);
3673 foreach ($arrayofemailtodelete as $imapemailnum => $imapemail) {
3674 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemailnum);
3676 $operationslog .=
"<br> move email ".$imapemailnum.($mode > 0 ?
' (test)' :
'');
3678 if (empty($mode) && empty($error)) {
3679 $tmptargetdir = $targetdir;
3686 $result = $imapemail->move($tmptargetdir,
false);
3689 $operationslog .=
'<br>Exception !!!! '.$e->getMessage();
3691 if (empty($result)) {
3692 dol_syslog(
"Failed to move email into target directory ".$targetdir);
3693 $operationslog .=
'<br>Failed to move email into target directory '.$targetdir;
3699 if (empty($mode) && empty($error)) {
3701 $operationslog .=
"<br>Expunge";
3706 $client->disconnect();
3708 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
3709 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
3711 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid.($mode > 0 ?
' (test)' :
'');
3713 if (empty($mode) && empty($error)) {
3714 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
3717 $this->error = imap_last_error();
3718 $this->errors[] = $this->error;
3720 $operationslog .=
'<br>Error in move '.$this->error;
3727 if (empty($mode) && empty($error)) {
3729 $operationslog .=
"<br>Expunge";
3731 imap_expunge($connection);
3733 imap_close($connection);
3736 $this->datelastresult = $now;
3737 $this->lastresult = $output;
3739 $this->debuginfo .=
'IMAP search array used : '.$search;
3741 $this->debuginfo .=
'IMAP search string used : '.$search;
3744 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
3746 if ($operationslog) {
3747 $this->debuginfo .= $operationslog;
3750 if (empty($error) && empty($mode)) {
3751 $this->datelastok = $datelastok;
3754 if (!empty($this->errors)) {
3755 $this->lastresult .=
"<br>".implode(
"<br>", $this->errors);
3757 $this->codelastresult = ($error ?
'KO' :
'OK');
3763 dol_syslog(
"EmailCollector::doCollectOneCollector end", LOG_INFO);
3765 return $error ? -1 : 1;
3780 private function getmsg($mbox, $mid, $destdir =
'')
3784 global $charset, $htmlmsg, $plainmsg, $attachments;
3785 $htmlmsg = $plainmsg = $charset =
'';
3786 $attachments = array();
3793 $s = imap_fetchstructure($mbox, $mid, FT_UID);
3798 $this->
getpart($mbox, $mid, $s,
'0');
3801 foreach ($s->parts as $partno0 => $p) {
3802 $this->
getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
3833 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
3836 global $htmlmsg, $plainmsg, $charset, $attachments;
3840 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
3841 imap_body($mbox, $mid, FT_UID);
3843 if ($p->encoding == 4) {
3844 $data = quoted_printable_decode($data);
3845 } elseif ($p->encoding == 3) {
3846 $data = base64_decode($data);
3852 if ($p->parameters) {
3853 foreach ($p->parameters as $x) {
3854 $params[strtolower($x->attribute)] = $x->value;
3857 if (!empty($p->dparameters)) {
3858 foreach ($p->dparameters as $x) {
3859 $params[strtolower($x->attribute)] = $x->value;
3862 '@phan-var-force array{filename?:string,name?:string,charset?:string} $params';
3867 if (!empty($params[
'filename']) || !empty($params[
'name'])) {
3869 $filename = $params[
'filename'] ?? $params[
'name'];
3871 $attachments[$filename] = $data;
3873 if (strlen($destdir)) {
3874 if (substr($destdir, -1) !=
'/') {
3879 $file_name_complete = $filename;
3880 $destination = $destdir.$file_name_complete;
3883 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
3886 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
3889 $file_name_original = $file_name;
3898 while (file_exists($destdir.$file_name.
".".$extension)) {
3899 $file_name = $file_name_original .
' (' . $num .
')';
3900 $file_name_complete = $file_name .
"." . $extension;
3901 $destination = $destdir.$file_name_complete;
3907 file_put_contents($destination, $data);
3912 if ($p->type == 0 && $data) {
3913 if (!empty($params[
'charset'])) {
3918 if (strtolower($p->subtype) ==
'plain') {
3919 $plainmsg .= trim($data).
"\n\n";
3921 $htmlmsg .= $data.
"<br><br>";
3923 $charset = $params[
'charset'];
3924 } elseif ($p->type == 2 && $data) {
3930 if (!empty($params[
'charset'])) {
3933 $plainmsg .= $data.
"\n\n";
3937 if (!empty($p->parts)) {
3938 foreach ($p->parts as $partno0 => $p2) {
3939 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1), $destdir);
3955 if (!$string || $fromEncoding == $toEncoding) {
3958 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
3959 if (!$convertedString && extension_loaded(
'mbstring')) {
3960 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
3962 if (!$convertedString) {
3963 throw new Exception(
'Mime string encoding conversion failed');
3965 return $convertedString;
3984 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
3985 $elements = imap_mime_header_decode($subject);
3987 if (!empty($elements)) {
3988 $num = count($elements);
3989 for ($i = 0; $i < $num; $i++) {
3990 $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));
3991 $newstring .= $stringinutf8;
3993 $subject = $newstring;
3995 } elseif (!function_exists(
'mb_decode_mimeheader')) {
3996 $subject = mb_decode_mimeheader($subject);
3997 } elseif (function_exists(
'iconv_mime_decode')) {
3998 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
4014 require_once DOL_DOCUMENT_ROOT .
'/core/lib/images.lib.php';
4017 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
4018 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
4019 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
4020 $maxheightmini = $tmparraysize[
'maxheightmini'];
4021 $quality = $tmparraysize[
'quality'];
4023 file_put_contents($destdir.
'/'.$filename, $content);
4026 vignette($destdir.
'/'.$filename, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
4028 vignette($destdir.
'/'.$filename, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
4041 if (is_object($imapemail)) {
4042 return $imapemail->getAttributes()[
"uid"];
4044 return (
string) $imapemail;