65 public $element =
'emailcollector';
70 public $table_element =
'emailcollector_emailcollector';
75 public $picto =
'email';
80 public $fk_element =
'fk_emailcollector';
85 protected $childtables = array();
90 protected $childtablesoncascade = array(
'emailcollector_emailcollectorfilter',
'emailcollector_emailcollectoraction');
116 public $fields = array(
117 'rowid' => array(
'type' =>
'integer',
'label' =>
'TechnicalID',
'visible' => 2,
'enabled' => 1,
'position' => 1,
'notnull' => 1,
'index' => 1),
118 'entity' => array(
'type' =>
'integer',
'label' =>
'Entity',
'enabled' => 1,
'visible' => 0,
'default' => 1,
'notnull' => 1,
'index' => 1,
'position' => 20),
119 'ref' => array(
'type' =>
'varchar(128)',
'label' =>
'Ref',
'enabled' => 1,
'visible' => 1,
'notnull' => 1,
'showoncombobox' => 1,
'index' => 1,
'position' => 10,
'searchall' => 1,
'help' =>
'Example: MyCollector1',
'csslist' =>
'tdoverflowmax200'),
120 'label' => array(
'type' =>
'varchar(255)',
'label' =>
'Label',
'visible' => 1,
'enabled' => 1,
'position' => 30,
'notnull' => -1,
'searchall' => 1,
'help' =>
'Example: My Email collector',
'csslist' =>
'tdoverflowmax150',
'tdcss' =>
'titlefieldmiddle'),
121 'description' => array(
'type' =>
'text',
'label' =>
'Description',
'visible' => -1,
'enabled' => 1,
'position' => 60,
'notnull' => -1,
'cssview' =>
'small',
'csslist' =>
'small tdoverflowmax200'),
122 'host' => array(
'type' =>
'varchar(255)',
'label' =>
'EMailHost',
'visible' => 1,
'enabled' => 1,
'position' => 90,
'notnull' => 1,
'searchall' => 1,
'comment' =>
"IMAP server",
'help' =>
'Example: imap.gmail.com',
'csslist' =>
'tdoverflowmax125'),
123 'port' => array(
'type' =>
'varchar(10)',
'label' =>
'EMailHostPort',
'visible' => 1,
'enabled' => 1,
'position' => 91,
'notnull' => 1,
'searchall' => 0,
'comment' =>
"IMAP server port",
'help' =>
'Example: 993',
'csslist' =>
'tdoverflowmax50',
'default' =>
'993'),
124 'imap_encryption' => array(
'type' =>
'varchar(16)',
'label' =>
'ImapEncryption',
'visible' => -1,
'enabled' => 1,
'position' => 92,
'searchall' => 0,
'comment' =>
"IMAP encryption",
'help' =>
'ImapEncryptionHelp',
'arrayofkeyval' => array(
'ssl' =>
'SSL',
'tls' =>
'TLS',
'notls' =>
'NOTLS'),
'default' =>
'ssl'),
125 'hostcharset' => array(
'type' =>
'varchar(16)',
'label' =>
'HostCharset',
'visible' => -1,
'enabled' => 1,
'position' => 93,
'notnull' => 0,
'searchall' => 0,
'comment' =>
"IMAP server charset",
'help' =>
'Example: "UTF-8" (May be "US-ASCII" with some Office365)',
'default' =>
'UTF-8'),
126 'norsh' => array(
'type' =>
'integer',
'label' =>
'NoRSH',
'visible' => -1,
'enabled' =>
"!getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')",
'position' => 94,
'searchall' => 0,
'help' =>
'NoRSHHelp',
'arrayofkeyval' => array(0 =>
'No', 1 =>
'Yes'),
'default' => 0),
127 'acces_type' => array(
'type' =>
'integer',
'label' =>
'AuthenticationMethod',
'visible' => -1,
'enabled' =>
"getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')",
'position' => 101,
'notnull' => 1,
'index' => 1,
'comment' =>
"IMAP login type",
'arrayofkeyval' => array(
'0' =>
'loginPassword',
'1' =>
'oauthToken'),
'default' =>
'0',
'help' =>
''),
128 'login' => array(
'type' =>
'varchar(128)',
'label' =>
'Login',
'visible' => -1,
'enabled' => 1,
'position' => 102,
'notnull' => -1,
'index' => 1,
'comment' =>
"IMAP login",
'help' =>
'Example: myaccount@gmail.com'),
129 'password' => array(
'type' =>
'password',
'label' =>
'Password',
'visible' => -1,
'enabled' =>
"1",
'position' => 103,
'notnull' => -1,
'comment' =>
"IMAP password",
'help' =>
'WithGMailYouCanCreateADedicatedPassword'),
130 'oauth_service' => array(
'type' =>
'varchar(128)',
'label' =>
'oauthService',
'visible' => -1,
'enabled' =>
"getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')",
'position' => 104,
'notnull' => 0,
'index' => 1,
'comment' =>
"IMAP login oauthService",
'arrayofkeyval' => array(),
'help' =>
'TokenMustHaveBeenCreated'),
131 'source_directory' => array(
'type' =>
'varchar(255)',
'label' =>
'MailboxSourceDirectory',
'visible' => -1,
'enabled' => 1,
'position' => 109,
'notnull' => 1,
'default' =>
'Inbox',
'csslist' =>
'tdoverflowmax100',
'help' =>
'Example: INBOX, [Gmail]/Spam, [Gmail]/Draft, [Gmail]/Brouillons, [Gmail]/Sent Mail, [Gmail]/Messages envoyés, ...'),
132 'target_directory' => array(
'type' =>
'varchar(255)',
'label' =>
'MailboxTargetDirectory',
'visible' => 1,
'enabled' => 1,
'position' => 110,
'notnull' => 0,
'csslist' =>
'tdoverflowmax100',
'help' =>
"EmailCollectorTargetDir"),
133 'maxemailpercollect' => array(
'type' =>
'integer',
'label' =>
'MaxEmailCollectPerCollect',
'visible' => -1,
'enabled' => 1,
'position' => 111,
'default' => 50),
134 'datelastresult' => array(
'type' =>
'datetime',
'label' =>
'DateLastCollectResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 121,
'notnull' => -1,
'csslist' =>
'nowraponall'),
135 'codelastresult' => array(
'type' =>
'varchar(16)',
'label' =>
'CodeLastResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 122,
'notnull' => -1,),
136 'lastresult' => array(
'type' =>
'varchar(255)',
'label' =>
'LastResult',
'visible' => 1,
'enabled' =>
'$action != "create" && $action != "edit"',
'position' => 123,
'notnull' => -1,
'cssview' =>
'small',
'csslist' =>
'small tdoverflowmax200'),
137 'datelastok' => array(
'type' =>
'datetime',
'label' =>
'DateLastcollectResultOk',
'visible' => 1,
'enabled' =>
'$action != "create"',
'position' => 125,
'notnull' => -1,
'csslist' =>
'nowraponall'),
138 'note_public' => array(
'type' =>
'html',
'label' =>
'NotePublic',
'visible' => 0,
'enabled' => 1,
'position' => 61,
'notnull' => -1,),
139 'note_private' => array(
'type' =>
'html',
'label' =>
'NotePrivate',
'visible' => 0,
'enabled' => 1,
'position' => 62,
'notnull' => -1,),
140 'date_creation' => array(
'type' =>
'datetime',
'label' =>
'DateCreation',
'visible' => -2,
'enabled' => 1,
'position' => 500,
'notnull' => 1,),
141 'tms' => array(
'type' =>
'timestamp',
'label' =>
'DateModification',
'visible' => -2,
'enabled' => 1,
'position' => 501,
'notnull' => 1,),
143 'fk_user_creat' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserAuthor',
'visible' => -2,
'enabled' => 1,
'position' => 510,
'notnull' => 1,),
144 'fk_user_modif' => array(
'type' =>
'integer:User:user/class/user.class.php',
'label' =>
'UserModif',
'visible' => -2,
'enabled' => 1,
'position' => 511,
'notnull' => -1,),
146 'import_key' => array(
'type' =>
'varchar(14)',
'label' =>
'ImportId',
'visible' => -2,
'enabled' => 1,
'position' => 1000,
'notnull' => -1,),
147 'status' => array(
'type' =>
'integer',
'label' =>
'Status',
'visible' => 1,
'enabled' => 1,
'position' => 1000,
'notnull' => 1,
'default' =>
'0',
'index' => 1,
'arrayofkeyval' => array(
'0' =>
'Inactive',
'1' =>
'Active'))
184 public $fk_user_creat;
189 public $fk_user_modif;
202 public $oauth_service;
203 public $imap_encryption;
205 public $source_directory;
206 public $target_directory;
207 public $maxemailpercollect;
212 public $datelastresult;
214 public $codelastresult;
224 const STATUS_DISABLED = 0;
225 const STATUS_ENABLED = 1;
235 global $conf, $langs;
239 $this->ismultientitymanaged = 1;
240 $this->isextrafieldmanaged = 0;
243 $this->fields[
'rowid'][
'visible'] = 0;
245 if (!isModEnabled(
'multicompany') && isset($this->fields[
'entity'])) {
246 $this->fields[
'entity'][
'enabled'] = 0;
250 $oauthservices = array();
252 foreach ($conf->global as $key => $val) {
253 if (!empty($val) && preg_match(
'/^OAUTH_.*_ID$/', $key)) {
254 $key = preg_replace(
'/^OAUTH_/',
'', $key);
255 $key = preg_replace(
'/_ID$/',
'', $key);
256 if (preg_match(
'/^.*-/', $key)) {
257 $name = preg_replace(
'/^.*-/',
'', $key);
259 $name = $langs->trans(
"NoName");
261 $provider = preg_replace(
'/-.*$/',
'', $key);
262 $provider = ucfirst(strtolower($provider));
264 $oauthservices[$key] = $name.
" (".$provider.
")";
268 $this->fields[
'oauth_service'][
'arrayofkeyval'] = $oauthservices;
271 foreach ($this->fields as $key => $val) {
272 if (isset($val[
'enabled']) && empty($val[
'enabled'])) {
273 unset($this->fields[$key]);
278 foreach ($this->fields as $key => $val) {
279 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
280 foreach ($val[
'arrayofkeyval'] as $key2 => $val2) {
281 $this->fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
299 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
300 $langs->load(
"errors");
301 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
305 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
306 $this->password =
dolEncrypt($this->password);
310 $this->password =
dolDecrypt($this->password);
312 if (is_array($this->filters) && count($this->filters)) {
315 foreach ($this->filters as $filter) {
316 $emailcollectorfilter->type = $filter[
'type'];
317 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
318 $emailcollectorfilter->fk_emailcollector = $this->id;
319 $emailcollectorfilter->status = $filter[
'status'];
321 $emailcollectorfilter->create($user);
325 if (is_array($this->actions) && count($this->actions)) {
328 foreach ($this->actions as $operation) {
329 $emailcollectoroperation->type = $operation[
'type'];
330 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
331 $emailcollectoroperation->fk_emailcollector = $this->id;
332 $emailcollectoroperation->status = $operation[
'status'];
333 $emailcollectoroperation->position = $operation[
'position'];
335 $emailcollectoroperation->create($user);
351 global $langs, $extrafields;
372 unset(
$object->codelastresult);
373 unset(
$object->datelastresult);
378 $object->ref =
"copy_of_".$object->ref;
381 $object->host =
'imap.example.com';
384 if (is_array(
$object->array_options) && count(
$object->array_options) > 0) {
385 $extrafields->fetch_name_optionals_label($this->table_element);
386 foreach (
$object->array_options as $key => $option) {
387 $shortkey = preg_replace(
'/options_/',
'', $key);
388 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
390 unset(
$object->array_options[$key]);
396 $object->context[
'createfromclone'] =
'createfromclone';
397 $result =
$object->create($user);
401 $this->errors =
$object->errors;
404 unset(
$object->context[
'createfromclone']);
411 $this->db->rollback();
423 public function fetch($id, $ref =
null)
427 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
428 $this->password =
dolDecrypt($this->password);
461 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
467 $sql =
"SELECT s.rowid";
468 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
469 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
471 $sql .=
" AND s.status = 1";
473 $sql .= $this->db->order($sortfield, $sortorder);
478 $offset = $limit * $page;
480 $sql .= $this->db->plimit($limit + 1, $offset);
483 $result = $this->db->query($sql);
485 $num = $this->db->num_rows($result);
488 $obj = $this->db->fetch_object($result);
490 if ($emailcollector_static->fetch($obj->rowid)) {
491 $obj_ret[] = $emailcollector_static;
496 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
497 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
500 if (!count($obj_ret)) {
501 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
519 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
520 $langs->load(
"errors");
521 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
525 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
526 $this->password =
dolEncrypt($this->password);
530 $this->password =
dolDecrypt($this->password);
542 public function delete(
User $user, $notrigger = 0)
557 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
559 global $conf, $langs, $action, $hookmanager;
561 if (!empty($conf->dol_no_mouse_hover)) {
567 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
569 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
571 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
573 if ($option !=
'nolink') {
575 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
576 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
577 $add_save_lastsearch_values = 1;
579 if ($add_save_lastsearch_values) {
580 $url .=
'&save_lastsearch_values=1';
585 if (empty($notooltip)) {
587 $label = $langs->trans(
"ShowEmailCollector");
588 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
590 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
591 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
593 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
596 $linkstart =
'<a href="'.$url.
'"';
597 $linkstart .= $linkclose.
'>';
600 $result .= $linkstart;
602 $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);
604 if ($withpicto != 2) {
605 $result .= $this->ref;
610 $hookmanager->initHooks(array(
'emailcollectordao'));
611 $parameters = array(
'id' => $this->
id,
'getnomurl' => &$result);
612 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
614 $result = $hookmanager->resPrint;
616 $result .= $hookmanager->resPrint;
644 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
647 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
648 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
649 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
650 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
653 $statusType =
'status5';
654 if ($status == self::STATUS_ENABLED) {
655 $statusType =
'status4';
658 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
669 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
670 $sql .=
' fk_user_creat, fk_user_modif';
671 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
672 $sql .=
' WHERE t.rowid = '.((int) $id);
673 $result = $this->db->query($sql);
675 if ($this->db->num_rows($result)) {
676 $obj = $this->db->fetch_object($result);
678 $this->
id = $obj->rowid;
680 $this->user_creation_id = $obj->fk_user_creat;
681 $this->user_modification_id = $obj->fk_user_modif;
682 $this->date_creation = $this->db->jdate($obj->datec);
683 $this->date_modification = empty($obj->datem) ?
'' : $this->db->jdate($obj->datem);
686 $this->db->free($result);
700 $this->host =
'localhost';
701 $this->login =
'alogin';
714 $this->filters = array();
716 $sql =
'SELECT rowid, type, rulevalue, status';
717 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
718 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
721 $resql = $this->db->query($sql);
723 $num = $this->db->num_rows($resql);
726 $obj = $this->db->fetch_object($resql);
727 $this->filters[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'rulevalue' => $obj->rulevalue,
'status' => $obj->status);
730 $this->db->free($resql);
746 $this->actions = array();
748 $sql =
'SELECT rowid, type, actionparam, status';
749 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
750 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
751 $sql .=
' ORDER BY position';
753 $resql = $this->db->query($sql);
755 $num = $this->db->num_rows($resql);
758 $obj = $this->db->fetch_object($resql);
759 $this->actions[$obj->rowid] = array(
'id' => $obj->rowid,
'type' => $obj->type,
'actionparam' => $obj->actionparam,
'status' => $obj->status);
762 $this->db->free($resql);
781 $flags =
'/service=imap';
784 } elseif (empty($this->imap_encryption) || ($this->imap_encryption ==
'ssl' &&
getDolGlobalString(
'IMAP_FORCE_NOSSL'))) {
787 $flags .=
'/' . $this->imap_encryption;
790 $flags .=
'/novalidate-cert';
797 if (!empty($this->login) && strpos($this->login,
'/') !=
false) {
798 $partofauth = explode(
'/', $this->login);
799 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
802 $connectstringserver =
'{'.$this->host.
':'.$this->port.$flags.
'}';
804 return $connectstringserver;
815 if (function_exists(
'mb_convert_encoding')) {
817 $str = preg_replace(
"/ /",
"xxxSPACExxx", $str);
818 $str = preg_replace(
"/\[Gmail\]/",
"xxxGMAILxxx", $str);
820 if ($str = mb_convert_encoding($str,
"UTF-7")) {
822 $str = preg_replace(
"/\+A/",
"&A", $str);
824 $str = preg_replace(
"/xxxSPACExxx/",
" ", $str);
826 $str = preg_replace(
"/xxxGMAILxxx/",
"[Gmail]", $str);
830 $this->error =
"error: is not possible to encode this string '".$str.
"'";
850 $arrayofcollectors = $this->
fetchAll($user, 1);
852 foreach ($arrayofcollectors as $emailcollector) {
853 $result = $emailcollector->doCollectOneCollector(0);
854 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
856 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
857 if (!empty($emailcollector->errors)) {
858 $this->error .= implode(
'<br>', $emailcollector->errors);
861 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
880 global $conf, $langs;
882 $errorforthisaction = 0;
885 $outputlangs = $langs;
888 $newlang =
GETPOST(
'lang_id',
'aZ09');
891 $newlang = !empty(
$object->thirdparty->default_lang) ?
$object->thirdparty->default_lang : $newlang;
893 if (!empty($newlang)) {
895 $outputlangs->setDefaultLang($newlang);
905 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
908 $tmparray = explode(
'.', $propertytooverwrite);
909 if (count($tmparray) == 2) {
910 $tmpclass = $tmparray[0];
911 $tmpproperty = $tmparray[1];
913 $tmpproperty = $tmparray[0];
915 if ($tmpclass && ($tmpclass !=
$object->element)) {
925 $regforregex = array();
926 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
927 $sourcefield = $regforregex[1];
928 $regexstring = $regforregex[2];
930 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
931 $sourcefield = $regforregex[1];
932 $regexstring = $regforregex[2];
935 if (!empty($sourcefield) && !empty($regexstring)) {
936 if (strtolower($sourcefield) ==
'body') {
937 $sourcestring = $messagetext;
938 } elseif (strtolower($sourcefield) ==
'subject') {
939 $sourcestring = $subject;
940 } elseif (strtolower($sourcefield) ==
'header') {
941 $sourcestring = $header;
945 $regforval = array();
947 if (strtolower($sourcefield) ==
'body') {
948 $regexoptions =
'ms';
950 if (strtolower($sourcefield) ==
'header') {
955 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
957 $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
958 if (strtolower($sourcefield) ==
'header') {
959 if (preg_match(
'/^options_/', $tmpproperty)) {
962 if (property_exists(
$object, $tmpproperty)) {
969 if (preg_match(
'/^options_/', $tmpproperty)) {
972 if (property_exists(
$object, $tmpproperty)) {
979 if (preg_match(
'/^options_/', $tmpproperty)) {
980 $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));
982 if (property_exists(
$object, $tmpproperty)) {
990 if (property_exists(
$object, $tmpproperty)) {
993 $tmp[$tmpproperty] =
null;
996 $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.';
1000 $errorforthisaction++;
1001 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1002 $this->errors[] = $this->error;
1004 $operationslog .=
'<br>'.$this->error;
1006 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1008 if (preg_match(
'/^options_/', $tmpproperty)) {
1009 $valuecurrent =
$object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1011 if (property_exists(
$object, $tmpproperty)) {
1012 $valuecurrent =
$object->$tmpproperty;
1014 $valuecurrent = $tmp[$tmpproperty];
1018 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1019 $valuetouse = $regforregex[2];
1022 $matcharray = array();
1023 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1025 if (is_array($matcharray[1])) {
1026 foreach ($matcharray[1] as $keytoreplace) {
1027 if ($keytoreplace) {
1028 if (preg_match(
'/^options_/', $keytoreplace)) {
1029 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1031 if (property_exists(
$object, $keytoreplace)) {
1032 $substitutionarray[
'__'.$keytoreplace.
'__'] =
$object->$keytoreplace;
1034 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1044 if (preg_match(
'/^options_/', $tmpproperty)) {
1045 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1047 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1049 if (property_exists(
$object, $tmpproperty)) {
1050 $object->$tmpproperty = $valuetouse;
1052 $tmp[$tmpproperty] = $valuetouse;
1055 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1059 $errorforthisaction++;
1060 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1061 $this->errors[] = $this->error;
1066 return $errorforthisaction;
1075 public function doCollectOneCollector($mode = 0)
1077 global $db, $conf, $langs, $user;
1078 global $hookmanager;
1082 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1084 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1087 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1089 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1094 $this->debuginfo =
'';
1098 $searchfilterdoltrackid = 0;
1099 $searchfilternodoltrackid = 0;
1100 $searchfilterisanswer = 0;
1101 $searchfilterisnotanswer = 0;
1102 $searchfilterreplyto = 0;
1103 $searchfilterexcludebodyarray = array();
1104 $searchfilterexcludesubjectarray = array();
1105 $operationslog =
'';
1106 $rulesreplyto = array();
1110 if (empty($this->host)) {
1111 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1114 if (empty($this->login)) {
1115 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1118 if (empty($this->source_directory)) {
1119 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1123 $sourcedir = $this->source_directory;
1124 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1129 $sourcedir = $this->source_directory;
1130 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1133 if ($this->acces_type == 1) {
1135 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>';
1137 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1141 $keyforsupportedoauth2array = $this->oauth_service;
1142 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1143 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1145 $keyforprovider =
'';
1147 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', strtoupper($keyforsupportedoauth2array));
1148 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1150 if (!empty($supportedoauth2array)) {
1151 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']));
1152 $nameofservice .= ($keyforprovider ?
'-'.$keyforprovider :
'');
1153 $OAUTH_SERVICENAME = $nameofservice;
1155 $OAUTH_SERVICENAME =
'Unknown';
1158 $keyforparamtenant =
'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'callbackfile']).($keyforprovider ?
'-'.$keyforprovider :
'').
'_TENANT';
1160 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1166 $storage =
new DoliStorage($db, $conf, $keyforprovider,
getDolGlobalString($keyforparamtenant));
1169 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1178 if (is_object($tokenobj) && $expire) {
1179 $this->debuginfo .=
'Refresh token '.$OAUTH_SERVICENAME.
'<br>';
1180 $credentials =
new Credentials(
1185 $serviceFactory = new \OAuth\ServiceFactory();
1186 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1190 if (preg_match(
'/^Microsoft/', $OAUTH_SERVICENAME)) {
1192 $tmp = explode(
'-', $OAUTH_SERVICENAME);
1193 $scopes = explode(
',',
getDolGlobalString(
'OAUTH_'.strtoupper($tmp[0]).(empty($tmp[1]) ?
'' :
'-'.$tmp[1]).
'_SCOPE'));
1196 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $scopes);
1198 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
1200 $refreshtoken = $tokenobj->getRefreshToken();
1201 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1204 $tokenobj->setRefreshToken($refreshtoken);
1205 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1207 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1208 if (is_object($tokenobj)) {
1209 $token = $tokenobj->getAccessToken();
1211 $this->error =
"Token not found";
1216 $this->error = $e->getMessage();
1217 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1221 $cm =
new ClientManager();
1222 $client = $cm->make([
1223 'host' => $this->host,
1224 'port' => $this->port,
1225 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1226 'validate_cert' => true,
1227 'protocol' =>
'imap',
1228 'username' => $this->login,
1229 'password' => $token,
1230 'authentication' =>
"oauth",
1234 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1236 $cm =
new ClientManager();
1237 $client = $cm->make([
1238 'host' => $this->host,
1239 'port' => $this->port,
1240 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1241 'validate_cert' => true,
1242 'protocol' =>
'imap',
1243 'username' => $this->login,
1244 'password' => $this->password,
1245 'authentication' =>
"login",
1251 }
catch (ConnectionFailedException $e) {
1252 $this->error = $e->getMessage();
1253 $this->errors[] = $this->error;
1254 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1258 $host = dol_getprefix(
'email');
1261 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1263 if (!function_exists(
'imap_open')) {
1264 $this->error =
'IMAP function not enabled on your PHP';
1270 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1271 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1273 $connectstringsource = $connectstringserver.$sourcedir;
1274 $connectstringtarget = $connectstringserver.$targetdir;
1277 $this->debuginfo .=
'connectstringsource = '.$connectstringsource.
', $connectstringtarget='.$connectstringtarget.
'<br>';
1279 $connection = imap_open($connectstringsource, $this->login, $this->password);
1281 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1286 $host = dol_getprefix(
'email');
1297 $criteria = array(array(
'UNDELETED'));
1298 foreach ($this->filters as $rule) {
1299 if (empty($rule[
'status'])) {
1304 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1308 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1311 if ($rule[
'type'] ==
'from') {
1312 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1313 if (count($tmprulevaluearray) >= 2) {
1314 foreach ($tmprulevaluearray as $tmprulevalue) {
1315 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1318 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1321 if ($rule[
'type'] ==
'to') {
1322 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1323 if (count($tmprulevaluearray) >= 2) {
1324 foreach ($tmprulevaluearray as $tmprulevalue) {
1325 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1328 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1331 if ($rule[
'type'] ==
'bcc') {
1332 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1334 if ($rule[
'type'] ==
'cc') {
1335 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1337 if ($rule[
'type'] ==
'subject') {
1338 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1340 $searchfilterexcludesubjectarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1342 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1345 if ($rule[
'type'] ==
'body') {
1346 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1348 $searchfilterexcludebodyarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1350 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1353 if ($rule[
'type'] ==
'header') {
1354 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1366 if ($rule[
'type'] ==
'seen') {
1367 array_push($criteria, array($not.
"SEEN"));
1369 if ($rule[
'type'] ==
'unseen') {
1370 array_push($criteria, array($not.
"UNSEEN"));
1372 if ($rule[
'type'] ==
'unanswered') {
1373 array_push($criteria, array($not.
"UNANSWERED"));
1375 if ($rule[
'type'] ==
'answered') {
1376 array_push($criteria, array($not.
"ANSWERED"));
1378 if ($rule[
'type'] ==
'smaller') {
1379 array_push($criteria, array($not.
"SMALLER"));
1381 if ($rule[
'type'] ==
'larger') {
1382 array_push($criteria, array($not.
"LARGER"));
1386 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1387 $searchfilterdoltrackid++;
1388 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1390 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1391 $searchfilterdoltrackid++;
1392 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1394 if ($rule[
'type'] ==
'withtrackingid') {
1395 $searchfilterdoltrackid++;
1396 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1398 if ($rule[
'type'] ==
'withouttrackingid') {
1399 $searchfilternodoltrackid++;
1400 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1403 if ($rule[
'type'] ==
'isanswer') {
1404 $searchfilterisanswer++;
1405 $searchhead .=
'/References.*@.*/';
1407 if ($rule[
'type'] ==
'isnotanswer') {
1408 $searchfilterisnotanswer++;
1409 $searchhead .=
'! /References.*@.*/';
1412 if ($rule[
'type'] ==
'replyto') {
1413 $searchfilterreplyto++;
1414 $rulesreplyto[] = $rule[
'rulevalue'];
1415 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1419 if (empty($targetdir) || !
getDolGlobalString(
'EMAILCOLLECTOR_NO_FILTER_ON_DATE_IF_THERE_IS_A_TARGETDIR')) {
1421 if ($this->datelastok) {
1422 $fromdate = $this->datelastok;
1424 if ($fromdate > 0) {
1426 array_push($criteria, array(
"SINCE" => date(
'j-M-Y', $fromdate - 1)));
1431 dol_syslog(
"IMAP search string = ".var_export($criteria,
true));
1432 $search = var_export($criteria,
true);
1435 $search =
'UNDELETED';
1436 foreach ($this->filters as $rule) {
1437 if (empty($rule[
'status'])) {
1445 if (!empty($rule[
'rulevalue']) && strpos($rule[
'rulevalue'],
'!') === 0) {
1449 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1452 if ($rule[
'type'] ==
'from') {
1453 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1454 if (count($tmprulevaluearray) >= 2) {
1455 foreach ($tmprulevaluearray as $tmprulevalue) {
1456 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1459 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1462 if ($rule[
'type'] ==
'to') {
1463 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1464 if (count($tmprulevaluearray) >= 2) {
1465 foreach ($tmprulevaluearray as $tmprulevalue) {
1466 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1469 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1472 if ($rule[
'type'] ==
'bcc') {
1473 $search .= ($search ?
' ' :
'').$not.
'BCC';
1475 if ($rule[
'type'] ==
'cc') {
1476 $search .= ($search ?
' ' :
'').$not.
'CC';
1478 if ($rule[
'type'] ==
'subject') {
1481 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1483 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1486 if ($rule[
'type'] ==
'body') {
1489 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1492 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1495 if ($rule[
'type'] ==
'header') {
1496 $search .= ($search ?
' ' :
'').$not.
'HEADER '.$rule[
'rulevalue'];
1508 if ($rule[
'type'] ==
'seen') {
1509 $search .= ($search ?
' ' :
'').$not.
'SEEN';
1511 if ($rule[
'type'] ==
'unseen') {
1512 $search .= ($search ?
' ' :
'').$not.
'UNSEEN';
1514 if ($rule[
'type'] ==
'unanswered') {
1515 $search .= ($search ?
' ' :
'').$not.
'UNANSWERED';
1517 if ($rule[
'type'] ==
'answered') {
1518 $search .= ($search ?
' ' :
'').$not.
'ANSWERED';
1520 if ($rule[
'type'] ==
'smaller') {
1521 $search .= ($search ?
' ' :
'').$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1523 if ($rule[
'type'] ==
'larger') {
1524 $search .= ($search ?
' ' :
'').$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1528 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1529 $searchfilterdoltrackid++;
1530 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1532 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1533 $searchfilterdoltrackid++;
1534 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1536 if ($rule[
'type'] ==
'withtrackingid') {
1537 $searchfilterdoltrackid++;
1538 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1540 if ($rule[
'type'] ==
'withouttrackingid') {
1541 $searchfilternodoltrackid++;
1542 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1545 if ($rule[
'type'] ==
'isanswer') {
1546 $searchfilterisanswer++;
1547 $searchhead .=
'/References.*@.*/';
1549 if ($rule[
'type'] ==
'isnotanswer') {
1550 $searchfilterisnotanswer++;
1551 $searchhead .=
'! /References.*@.*/';
1554 if ($rule[
'type'] ==
'replyto') {
1555 $searchfilterreplyto++;
1556 $rulesreplyto[] = $rule[
'rulevalue'];
1557 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1561 if (empty($targetdir)) {
1563 if ($this->datelastok) {
1564 $fromdate = $this->datelastok;
1566 if ($fromdate > 0) {
1567 $search .= ($search ?
' ' :
'').
'SINCE '.date(
'j-M-Y', $fromdate - 1);
1576 $nbemailprocessed = 0;
1579 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1586 $tmpsourcedir = $sourcedir;
1591 $f = $client->getFolders(
false, $tmpsourcedir);
1594 if ($folder instanceof Webklex\PHPIMAP\Folder) {
1595 $Query = $folder->messages()->where($criteria);
1598 $this->error =
"Source directory ".$sourcedir.
" not found";
1599 $this->errors[] = $this->error;
1600 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_WARNING);
1605 $this->error =
"Failed to execute getfolders";
1606 $this->errors[] = $this->error;
1607 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1610 }
catch (InvalidWhereQueryCriteriaException $e) {
1611 $this->error = $e->getMessage();
1612 $this->errors[] = $this->error;
1613 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1616 $this->error = $e->getMessage();
1617 $this->errors[] = $this->error;
1618 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1622 '@phan-var-force Webklex\PHPIMAP\Query\Query $Query';
1626 $Query->leaveUnread();
1628 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1631 $this->error = $e->getMessage();
1632 $this->errors[] = $this->error;
1633 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1638 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1640 if ($arrayofemail ===
false) {
1642 $mapoferrrors = imap_errors();
1643 if ($mapoferrrors !==
false) {
1645 $this->error =
"Search string not understood - ".implode(
',', $mapoferrrors);
1646 $this->errors[] = $this->error;
1651 $arrayofemailtodelete = array();
1654 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
1671 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1673 $richarrayofemail = array();
1675 foreach ($arrayofemail as $imapemail) {
1676 if ($nbemailprocessed > 1000) {
1682 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1683 $header = $imapemail->getHeader()->raw;
1684 $overview = $imapemail->getAttributes();
1686 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1687 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1690 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1693 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)(\r\n|\s$)/m', $header, $matches);
1694 $headers = array_combine($matches[1], $matches[2]);
1697 $richarrayofemail[] = array(
'imapemail' => $imapemail,
'header' => $header,
'headers' => $headers,
'overview' => $overview,
'date' => strtotime($headers[
'Date']));
1702 $richarrayofemail =
dol_sort_array($richarrayofemail,
'date',
'asc');
1706 foreach ($richarrayofemail as $tmpval) {
1709 $imapemail = $tmpval[
'imapemail'];
1710 $header = $tmpval[
'header'];
1711 $overview = $tmpval[
'overview'];
1712 $headers = $tmpval[
'headers'];
1714 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1715 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1717 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1718 $headers[
'References'] = $headers[
'references'];
1720 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1721 $headers[
'Message-ID'] = $headers[
'message-id'];
1723 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1724 $headers[
'Subject'] = $headers[
'subject'];
1730 $emailto = (string) $overview[
'to'];
1737 $operationslog .=
'<br>** Process email #'.dol_escape_htmltag($iforemailloop);
1741 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1743 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1745 $operationslog .=
" - ".dol_escape_htmltag((
string) $imapemail);
1746 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1748 $operationslog .=
" - MsgId: ".$msgid;
1749 $operationslog .=
" - Date: ".($headers[
'Date'] ?? $langs->transnoentitiesnoconv(
"NotFound"));
1750 $operationslog .=
" - References: ".dol_escape_htmltag($headers[
'References'] ?? $langs->transnoentitiesnoconv(
"NotFound")).
" - Subject: ".
dol_escape_htmltag($headers[
'Subject']);
1752 dol_syslog(
"-- Process email #".$iforemailloop.
", MsgId: ".$msgid.
", Date: ".($headers[
'Date'] ??
'').
", References: ".($headers[
'References'] ??
'').
", Subject: ".$headers[
'Subject']);
1755 $trackidfoundintorecipienttype =
'';
1756 $trackidfoundintorecipientid = 0;
1761 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)) {
1762 $trackidfoundintorecipienttype = $reg[1];
1763 $trackidfoundintorecipientid = $reg[2];
1764 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1765 $trackidfoundintorecipienttype =
'emailing';
1766 $trackidfoundintorecipientid = $reg[1];
1769 $trackidfoundintomsgidtype =
'';
1770 $trackidfoundintomsgidid = 0;
1775 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)) {
1776 $trackidfoundintomsgidtype = $reg[1];
1777 $trackidfoundintomsgidid = $reg[2];
1778 } elseif (preg_match(
'/(?:[\+\-])emailing-(\w+)@/', $msgid, $reg)) {
1779 $trackidfoundintomsgidtype =
'emailing';
1780 $trackidfoundintomsgidid = $reg[1];
1784 if ($searchfilterdoltrackid > 0) {
1785 if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) {
1786 if (empty($headers[
'References']) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References'])) {
1787 $nbemailprocessed++;
1788 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");
1793 if ($searchfilternodoltrackid > 0) {
1794 if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($headers[
'References']) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))) {
1795 $nbemailprocessed++;
1796 dol_syslog(
" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
1801 if ($searchfilterisanswer > 0) {
1802 if (empty($headers[
'In-Reply-To'])) {
1803 $nbemailprocessed++;
1804 dol_syslog(
" Discarded - Email is not an answer (no In-Reply-To header)");
1808 if (preg_match(
'/^(Re|AW)\s*:\s+/i', $headers[
'Subject'])) {
1814 if (!empty($headers[
'In-Reply-To'])) {
1822 $nbemailprocessed++;
1823 dol_syslog(
" Discarded - Email is not an answer (no RE prefix in subject)");
1827 if ($searchfilterisnotanswer > 0) {
1828 if (!empty($headers[
'In-Reply-To'])) {
1832 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
1838 $nbemailprocessed++;
1839 dol_syslog(
" Discarded - Email is an answer");
1844 if ($searchfilterreplyto > 0) {
1845 if (!empty($headers[
'Reply-To'])) {
1847 foreach ($rulesreplyto as $key => $rulereplyto) {
1848 if (preg_match(
'/'.preg_quote($rulereplyto,
'/').
'/', $headers[
'Reply-To'])) {
1853 if (!$isreplytook || $isreplytook != count($rulesreplyto)) {
1854 $nbemailprocessed++;
1855 dol_syslog(
" Discarded - Reply-to does not match");
1863 $thirdpartystatic =
new Societe($this->db);
1864 $contactstatic =
new Contact($this->db);
1865 $projectstatic =
new Project($this->db);
1867 $nbactiondoneforemail = 0;
1869 $errorforactions = 0;
1870 $thirdpartyfoundby =
'';
1871 $contactfoundby =
'';
1872 $projectfoundby =
'';
1873 $ticketfoundby =
'';
1874 $candidaturefoundby =
'';
1878 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".
dol_print_date($overview[
'date'],
'dayrfc',
'gmt').
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
1883 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);
1893 global $htmlmsg, $plainmsg, $charset, $attachments;
1897 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1898 if ($imapemail->hasHTMLBody()) {
1899 $htmlmsg = $imapemail->getHTMLBody();
1901 if ($imapemail->hasTextBody() && $imapemail->getTextBody() !=
"\n") {
1902 $plainmsg = $imapemail->getTextBody();
1904 if ($imapemail->hasAttachments()) {
1905 $attachments = $imapemail->getAttachments()->all();
1910 $getMsg = $this->
getmsg($connection, $imapemail);
1912 $this->errors = array_merge($this->errors, [$this->error]);
1916 '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments';
1928 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
1929 dol_syslog(
" Discarded - Email body is not valid utf8");
1933 if (!empty($searchfilterexcludebodyarray)) {
1934 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
1935 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
1936 $nbemailprocessed++;
1937 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
1938 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
2000 $replytostring =
'';
2003 $fromstring = $overview[
'from'];
2004 $replytostring = empty($overview[
'in_reply-to']) ? $headers[
'Reply-To'] : $overview[
'in_reply-to'];
2006 $sender = $overview[
'sender'];
2007 $to = $overview[
'to'];
2008 $sendtocc = empty($overview[
'cc']) ?
'' : $overview[
'cc'];
2009 $sendtobcc = empty($overview[
'bcc']) ?
'' : $overview[
'bcc'];
2011 $tmpdate = $overview[
'date']->toDate();
2012 $tmptimezone = $tmpdate->getTimezone()->getName();
2015 if (preg_match(
'/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) {
2016 if ($reg[1] ==
'+' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2017 $dateemail -= (3600 * (int) $reg[2]);
2018 $dateemail -= (60 * (int) $reg[3]);
2020 if ($reg[1] ==
'-' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2021 $dateemail += (3600 * (int) $reg[2]);
2022 $dateemail += (60 * (int) $reg[3]);
2025 $subject = $overview[
'subject'];
2027 $fromstring = $overview[0]->from;
2028 $replytostring = (!empty($overview[
'in_reply-to']) ? $overview[
'in_reply-to'] : (!empty($headers[
'Reply-To']) ? $headers[
'Reply-To'] :
"")) ;
2030 $sender = !empty($overview[0]->sender) ? $overview[0]->sender :
'';
2031 $to = $overview[0]->to;
2032 $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc :
'';
2033 $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc :
'';
2035 $subject = $overview[0]->subject;
2039 if (!empty($searchfilterexcludesubjectarray)) {
2040 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
2041 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
2042 $nbemailprocessed++;
2043 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
2044 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
2051 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
2053 $fromtext = $reg[1];
2055 $from = $fromstring;
2058 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
2060 $replytotext = $reg[1];
2062 $replyto = $replytostring;
2066 $fk_element_type =
'';
2083 $objectemail =
null;
2086 $arrayofreferences = array();
2087 if (!empty($headers[
'References'])) {
2088 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
2090 if (!in_array(
'<'.$msgid.
'>', $arrayofreferences)) {
2091 $arrayofreferences = array_merge($arrayofreferences, array(
'<'.$msgid.
'>'));
2096 foreach ($arrayofreferences as $reference) {
2098 if (!empty($trackidfoundintorecipienttype)) {
2099 $resultsearchtrackid = -1;
2100 $reg[1] = $trackidfoundintorecipienttype;
2101 $reg[2] = $trackidfoundintorecipientid;
2102 } elseif (!empty($trackidfoundintomsgidtype)) {
2103 $resultsearchtrackid = -1;
2104 $reg[1] = $trackidfoundintomsgidtype;
2105 $reg[2] = $trackidfoundintomsgidid;
2107 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
2108 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2109 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
2113 if (!empty($resultsearchtrackid)) {
2115 $trackid = $reg[1].$reg[2];
2117 $objectid = $reg[2];
2119 if ($reg[1] ==
'thi') {
2120 $objectemail =
new Societe($this->db);
2122 if ($reg[1] ==
'ctc') {
2123 $objectemail =
new Contact($this->db);
2125 if ($reg[1] ==
'inv') {
2126 $objectemail =
new Facture($this->db);
2128 if ($reg[1] ==
'sinv') {
2131 if ($reg[1] ==
'pro') {
2132 $objectemail =
new Propal($this->db);
2134 if ($reg[1] ==
'ord') {
2135 $objectemail =
new Commande($this->db);
2137 if ($reg[1] ==
'shi') {
2140 if ($reg[1] ==
'spro') {
2143 if ($reg[1] ==
'sord') {
2146 if ($reg[1] ==
'rec') {
2147 $objectemail =
new Reception($this->db);
2149 if ($reg[1] ==
'proj') {
2150 $objectemail =
new Project($this->db);
2151 $projectfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2153 if ($reg[1] ==
'tas') {
2154 $objectemail =
new Task($this->db);
2156 if ($reg[1] ==
'con') {
2157 $objectemail =
new Contact($this->db);
2159 if ($reg[1] ==
'use') {
2160 $objectemail =
new User($this->db);
2162 if ($reg[1] ==
'tic') {
2163 $objectemail =
new Ticket($this->db);
2164 $ticketfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2166 if ($reg[1] ==
'recruitmentcandidature') {
2168 $candidaturefoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2170 if ($reg[1] ==
'mem') {
2171 $objectemail =
new Adherent($this->db);
2179 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
2181 if (is_null($objectemail) && isModEnabled(
'ticket')) {
2182 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket";
2183 $sql .=
" WHERE email_msgid = '".$this->db->escape($reg[1]).
"' OR origin_references like '%".$this->db->escape($this->db->escapeforlike($reg[1])).
"%'";
2184 $resql = $this->db->query($sql);
2186 $obj = $this->db->fetch_object($resql);
2188 $objectid = $obj->rowid;
2189 $objectemail =
new Ticket($this->db);
2190 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2197 if (!is_object($objectemail) && isModEnabled(
'project')) {
2198 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2199 $resql = $this->db->query($sql);
2201 $obj = $this->db->fetch_object($resql);
2203 $objectid = $obj->rowid;
2204 $objectemail =
new Project($this->db);
2205 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2212 if (!is_object($objectemail) && isModEnabled(
'recruitment')) {
2213 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2214 $resql = $this->db->query($sql);
2216 $obj = $this->db->fetch_object($resql);
2218 $objectid = $obj->rowid;
2220 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2229 if (is_object($objectemail)) {
2230 $result = $objectemail->fetch($objectid);
2232 $fk_element_id = $objectemail->id;
2233 $fk_element_type = $objectemail->element;
2235 if ($fk_element_type ==
'facture') {
2236 $fk_element_type =
'invoice';
2239 if (get_class($objectemail) !=
'Societe') {
2240 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2242 $thirdpartyid = $objectemail->id;
2245 if (get_class($objectemail) !=
'Contact') {
2246 $contactid = $objectemail->fk_socpeople;
2248 $contactid = $objectemail->id;
2251 if (get_class($objectemail) !=
'Project') {
2252 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2254 $projectid = $objectemail->id;
2257 if ($objectemail instanceof
Ticket) {
2258 $ticketid = $objectemail->id;
2260 $changeonticket_references =
false;
2261 if (empty($trackid)) {
2262 $trackid = $objectemail->track_id;
2264 if (empty($objectemail->origin_references)) {
2265 $objectemail->origin_references = !empty($headers[
'References']) ? $headers[
'References'] :
null;
2266 $changeonticket_references =
true;
2268 foreach ($arrayofreferences as $key => $referencetmp) {
2269 if (!str_contains($objectemail->origin_references, $referencetmp)) {
2270 $objectemail->origin_references .=
" ".$referencetmp;
2271 $changeonticket_references =
true;
2275 if ($changeonticket_references) {
2276 $objectemail->update($user, 1);
2283 if ($projectid > 0) {
2284 $result = $projectstatic->fetch($projectid);
2286 $projectstatic->id = 0;
2288 $projectid = $projectstatic->id;
2290 $projectfoundby =
'trackid ('.$trackid.
')';
2292 if (empty($contactid)) {
2293 $contactid = $projectstatic->fk_contact;
2295 if (empty($thirdpartyid)) {
2296 $thirdpartyid = $projectstatic->fk_soc;
2301 if ($contactid > 0) {
2302 $result = $contactstatic->fetch($contactid);
2304 $contactstatic->id = 0;
2306 $contactid = $contactstatic->id;
2308 $contactfoundby =
'trackid ('.$trackid.
')';
2310 if (empty($thirdpartyid)) {
2311 $thirdpartyid = $contactstatic->fk_soc;
2316 if ($thirdpartyid > 0) {
2317 $result = $thirdpartystatic->fetch($thirdpartyid);
2319 $thirdpartystatic->id = 0;
2321 $thirdpartyid = $thirdpartystatic->id;
2323 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2328 if (is_object($objectemail)) {
2333 if (empty($contactid)) {
2334 $result = $contactstatic->fetch(0,
null,
'', $from);
2337 dol_syslog(
"We found a contact with the email ".$from);
2338 $contactid = $contactstatic->id;
2339 $contactfoundby =
'email of contact ('.$from.
')';
2340 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2341 $result = $thirdpartystatic->fetch($contactstatic->socid);
2343 $thirdpartyid = $thirdpartystatic->id;
2344 $thirdpartyfoundby =
'email of contact ('.$from.
')';
2350 if (empty($thirdpartyid)) {
2351 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
2353 dol_syslog(
"We found a thirdparty with the email ".$from);
2354 $thirdpartyid = $thirdpartystatic->id;
2355 $thirdpartyfoundby =
'email ('.$from.
')';
2391 foreach ($this->actions as $operation) {
2392 $errorforthisaction = 0;
2393 $ticketalreadyexists = 0;
2394 if ($errorforactions) {
2397 if (empty($operation[
'status'])) {
2401 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2404 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2405 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2408 $actioncode =
'EMAIL_IN';
2410 if (preg_match(
'/Sent$/', $sourcedir) || preg_match(
'/envoyés$/i', $sourcedir)) {
2411 $actioncode =
'EMAIL';
2414 $arrayofemailtoconsideresender = explode(
',',
getDolGlobalString(
'MAIL_FROM_EMAILS_TO_CONSIDER_SENDING'));
2415 foreach ($arrayofemailtoconsideresender as $emailtoconsidersender) {
2416 if (preg_match(
'/'.preg_quote($emailtoconsidersender,
'/').
'/', $fromstring)) {
2417 $actioncode =
'EMAIL';
2420 $operationslog .=
'<br>Email will have actioncode='.$actioncode;
2422 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2424 $descriptiontitle = $langs->transnoentitiesnoconv(
"RecordCreatedByEmailCollector", $this->
ref);
2429 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2431 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2433 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2435 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailReply").($langs->trans(
"MailReply") !=
'Reply to' ?
' (Reply to)' :
'').
' : '.
dol_escape_htmltag($replyto));
2438 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2441 if ($operation[
'type'] ==
'ticket') {
2443 $tickettocreate =
new Ticket($this->db);
2444 $errorfetchticket = 0;
2445 $alreadycreated = 0;
2446 if (!empty($trackid)) {
2447 $alreadycreated = $tickettocreate->fetch(0,
'', $trackid);
2449 if ($alreadycreated == 0 && !empty($msgid)) {
2450 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2452 if ($alreadycreated < 0) {
2453 $errorfetchticket++;
2455 if (empty($errorfetchticket)) {
2456 if ($alreadycreated == 0) {
2457 $operationslog .=
'<br>Ticket not found using trackid='.$trackid.
' or msgid='.$msgid;
2458 $ticketalreadyexists = 0;
2460 $operationslog .=
'<br>Ticket already found using trackid='.$trackid.
' or msgid='.$msgid;
2461 $ticketalreadyexists = 1;
2462 $operation[
'type'] =
'recordevent';
2465 $ticketalreadyexists = -1;
2472 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2473 if (empty($operation[
'actionparam'])) {
2475 $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;";
2476 $this->errors[] = $this->error;
2478 $actionparam = $operation[
'actionparam'];
2479 $idtouseforthirdparty =
'';
2480 $nametouseforthirdparty =
'';
2481 $emailtouseforthirdparty =
'';
2482 $namealiastouseforthirdparty =
'';
2484 $operationslog .=
'<br>Loop on each property to set into actionparam';
2488 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2492 $regforregex = array();
2494 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2495 $sourcefield = $regforregex[1];
2496 $regexstring = $regforregex[2];
2499 if (!empty($sourcefield) && !empty($regexstring)) {
2500 if (strtolower($sourcefield) ==
'body') {
2501 $sourcestring = $messagetext;
2502 } elseif (strtolower($sourcefield) ==
'subject') {
2503 $sourcestring = $subject;
2504 } elseif (strtolower($sourcefield) ==
'header') {
2505 $sourcestring = $header;
2508 if ($sourcestring) {
2509 $regforval = array();
2511 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2514 if ($propertytooverwrite ==
'id') {
2515 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2517 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2518 } elseif ($propertytooverwrite ==
'email') {
2519 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2521 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2522 } elseif ($propertytooverwrite ==
'name') {
2523 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2525 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2526 } elseif ($propertytooverwrite ==
'name_alias') {
2527 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2529 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2531 $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';
2535 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2536 $idtouseforthirdparty =
null;
2537 $nametouseforthirdparty =
null;
2538 $emailtouseforthirdparty =
null;
2539 $namealiastouseforthirdparty =
null;
2541 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2543 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2550 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2551 $this->errors[] = $this->error;
2553 $operationslog .=
'<br>'.$this->error;
2555 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2559 if ($propertytooverwrite ==
'id') {
2560 $idtouseforthirdparty = $reg[2];
2562 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2563 } elseif ($propertytooverwrite ==
'email') {
2564 $emailtouseforthirdparty = $reg[2];
2566 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2567 } elseif ($propertytooverwrite ==
'name') {
2568 $nametouseforthirdparty = $reg[2];
2570 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2571 } elseif ($propertytooverwrite ==
'name_alias') {
2572 $namealiastouseforthirdparty = $reg[2];
2574 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2578 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2579 $this->errors[] = $this->error;
2584 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2586 $operationslog .=
'<br>We have this initial main data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty.
'.';
2589 $tmpobject->element =
'generic';
2590 $tmpobject->id = $idtouseforthirdparty;
2591 $tmpobject->name = $nametouseforthirdparty;
2592 $tmpobject->name_alias = $namealiastouseforthirdparty;
2593 $tmpobject->email = $emailtouseforthirdparty;
2597 $idtouseforthirdparty = $tmpobject->id;
2598 $nametouseforthirdparty = $tmpobject->name;
2599 $namealiastouseforthirdparty = $tmpobject->name_alias;
2600 $emailtouseforthirdparty = $tmpobject->email;
2602 $operationslog .=
'<br>We try to search existing thirdparty with idtouseforthirdparty='.$idtouseforthirdparty.
' emailtouseforthirdparty='.$emailtouseforthirdparty.
' nametouseforthirdparty='.$nametouseforthirdparty.
' namealiastouseforthirdparty='.$namealiastouseforthirdparty;
2605 $result = $thirdpartystatic->findNearest($idtouseforthirdparty, $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', $emailtouseforthirdparty, $namealiastouseforthirdparty);
2609 $this->error =
'Error when getting thirdparty with name '.$nametouseforthirdparty.
' (may be 2 record exists with same name ?)';
2610 $this->errors[] = $this->error;
2612 } elseif ($result == 0) {
2613 if ($operation[
'type'] ==
'loadthirdparty') {
2614 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2617 $resultContact = $contactstatic->findNearest(0,
'',
'',
'', $emailtouseforthirdparty,
'', 0);
2618 if ($resultContact > 0) {
2619 $contactstatic->fetch($resultContact);
2620 $idtouseforthirdparty = $contactstatic->socid;
2621 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2623 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2626 $langs->load(
"errors");
2627 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2628 $this->errors[] = $this->error;
2632 $langs->load(
"errors");
2633 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2634 $this->errors[] = $this->error;
2636 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2637 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
2640 $thirdpartystatic =
new Societe($db);
2641 $thirdpartystatic->name = $nametouseforthirdparty;
2642 if (!empty($namealiastouseforthirdparty)) {
2643 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
2644 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
2647 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'' : $fromtext) : $replytostring);
2649 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ?
'' : $from) : $replyto) : $emailtouseforthirdparty);
2652 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2654 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
2655 $thirdpartystatic->code_client =
'auto';
2657 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
2658 $thirdpartystatic->code_fournisseur =
'auto';
2661 if ($errorforthisaction) {
2664 $result = $thirdpartystatic->create($user);
2667 $this->error = $thirdpartystatic->error;
2668 $this->errors = $thirdpartystatic->errors;
2670 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag($thirdpartystatic->id);
2675 dol_syslog(
"One and only one existing third party has been found");
2677 $thirdpartystatic->fetch($result);
2679 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag($thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name);
2683 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
2684 if (empty($operation[
'actionparam'])) {
2686 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
2687 $this->errors[] = $this->error;
2689 $contact_static =
new Contact($this->db);
2691 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2692 if ($errorforthisaction) {
2695 if (!empty($contact_static->email) && $contact_static->email != $from) {
2696 $from = $contact_static->email;
2699 $result = $contactstatic->fetch(0,
null,
'', $from);
2702 $this->error =
'Error when getting contact with email ' . $from;
2703 $this->errors[] = $this->error;
2705 } elseif ($result == 0) {
2706 dol_syslog(
"Contact with email " . $from .
" was not found. We try to create it.");
2707 $contactstatic =
new Contact($this->db);
2710 $contactstatic->email = $from;
2711 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($from);
2714 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2716 if ($errorforthisaction) {
2720 if (!empty($contactstatic->country)) {
2721 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2722 $result =
getCountry(
'', 3, $this->db,
null, 1, $contactstatic->country);
2723 if ($result ==
'NotDefined') {
2725 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
2726 } elseif (!($result > 0)) {
2728 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
2729 $this->errors[] = $this->db->lasterror();
2731 $contactstatic->country_id = $result;
2732 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2734 } elseif (!empty($contactstatic->country_code)) {
2735 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2736 $result =
getCountry($contactstatic->country_code, 3, $this->db);
2737 if ($result ==
'NotDefined') {
2739 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
2740 } elseif (!($result > 0)) {
2742 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
2743 $this->errors[] = $this->db->lasterror();
2745 $contactstatic->country_id = $result;
2746 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2750 if (!$errorforactions) {
2752 if (!empty($contactstatic->state)) {
2753 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2754 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
2755 if (empty($result)) {
2757 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
2758 } elseif (!($result > 0)) {
2760 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
2761 $this->errors[] = $this->db->lasterror();
2763 $contactstatic->state_id = $result;
2764 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2766 } elseif (!empty($contactstatic->state_code)) {
2767 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2768 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
2769 if (empty($result)) {
2771 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
2772 } elseif (!($result > 0)) {
2774 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
2775 $this->errors[] = $this->db->lasterror();
2777 $contactstatic->state_id = $result;
2778 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2783 if (!$errorforactions) {
2784 $result = $contactstatic->create($user);
2787 $this->error = $contactstatic->error;
2788 $this->errors = $contactstatic->errors;
2790 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag($contactstatic->id);
2797 } elseif ($operation[
'type'] ==
'recordevent') {
2801 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
2802 if ($alreadycreated == 0) {
2803 $operationslog .=
'<br>We did not find existing actionmail with msgid='.$msgid;
2805 if ($projectstatic->id > 0) {
2806 if ($projectfoundby) {
2807 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
2810 if ($thirdpartystatic->id > 0) {
2811 if ($thirdpartyfoundby) {
2812 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2815 if ($contactstatic->id > 0) {
2816 if ($contactfoundby) {
2817 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2821 $description = $descriptiontitle;
2827 $descriptionfull = $description;
2829 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2834 $actioncomm->type_code =
'AC_OTH_AUTO';
2835 $actioncomm->code =
'AC_'.$actioncode;
2836 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
2837 $actioncomm->note_private = $descriptionfull;
2838 $actioncomm->fk_project = $projectstatic->id;
2839 $actioncomm->datep = $dateemail;
2840 $actioncomm->datef = $dateemail;
2841 $actioncomm->percentage = -1;
2842 $actioncomm->socid = $thirdpartystatic->id;
2843 $actioncomm->contact_id = $contactstatic->id;
2844 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array());
2845 $actioncomm->authorid = $user->id;
2846 $actioncomm->userownerid = $user->id;
2848 $actioncomm->email_msgid = $msgid;
2849 $actioncomm->email_from = $fromstring;
2850 $actioncomm->email_sender = $sender;
2851 $actioncomm->email_to = $to;
2852 $actioncomm->email_tocc = $sendtocc;
2853 $actioncomm->email_tobcc = $sendtobcc;
2854 $actioncomm->email_subject = $subject;
2855 $actioncomm->errors_to =
'';
2857 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
2858 $actioncomm->fk_element = $fk_element_id;
2859 $actioncomm->elementid = $fk_element_id;
2860 $actioncomm->elementtype = $fk_element_type;
2861 if (is_object($objectemail) && $objectemail->module) {
2862 $actioncomm->elementtype .=
'@'.$objectemail->module;
2869 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2871 if ($errorforthisaction) {
2874 $result = $actioncomm->create($user);
2877 $this->errors = $actioncomm->errors;
2879 if ($fk_element_type ==
"ticket" && is_object($objectemail)) {
2880 if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED || $objectemail->status == Ticket::STATUS_NEED_MORE_INFO || $objectemail->status == Ticket::STATUS_WAITING) {
2881 if ($objectemail->fk_user_assign !=
null) {
2882 $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED);
2884 $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ);
2888 $operationslog .=
'<br>Ticket Re-Opened successfully -> ref='.$objectemail->ref;
2891 $this->error =
'Error while changing the ticket status -> ref='.$objectemail->ref;
2892 $this->errors[] = $this->error;
2895 if (!empty($attachments)) {
2897 $ticket =
new Ticket($this->db);
2898 $ticket->fetch($fk_element_id);
2899 $destdir = $conf->ticket->dir_output.
'/'.$ticket->ref;
2904 foreach ($attachments as $attachment) {
2905 $attachment->save($destdir.
'/');
2908 $this->
getmsg($connection, $imapemail, $destdir);
2913 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag($actioncomm->id);
2917 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
2920 foreach ($attachments as $attachment) {
2921 if ($attachment->getName() ===
'undefined') {
2924 $data[$attachment->getName()] = $attachment->getContent();
2928 foreach ($pj as $key => $val) {
2929 $data[$val[
'filename']] =
getFileData($imapemail, $val[
'pos'], $val[
'type'], $connection);
2932 if (count($data) > 0) {
2933 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($from).
"%'";
2934 $resql = $this->db->query($sql);
2935 if ($this->db->num_rows($resql) == 0) {
2936 $this->errors[] =
"User Not allowed to add documents ({$from})";
2938 $arrayobject = array(
2939 'propale' => array(
'table' =>
'propal',
2940 'fields' => array(
'ref'),
2941 'class' =>
'comm/propal/class/propal.class.php',
2942 'object' =>
'Propal'),
2943 'holiday' => array(
'table' =>
'holiday',
2944 'fields' => array(
'ref'),
2945 'class' =>
'holiday/class/holiday.class.php',
2946 'object' =>
'Holiday'),
2947 'expensereport' => array(
'table' =>
'expensereport',
2948 'fields' => array(
'ref'),
2949 'class' =>
'expensereport/class/expensereport.class.php',
2950 'object' =>
'ExpenseReport'),
2951 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
2952 'fields' => array(
'ref'),
2953 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
2954 'object' =>
'RecruitmentJobPosition'),
2955 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
2956 'fields' => array(
'ref'),
2957 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
2958 'object' =>
' RecruitmentCandidature'),
2959 'societe' => array(
'table' =>
'societe',
2960 'fields' => array(
'code_client',
'code_fournisseur'),
2961 'class' =>
'societe/class/societe.class.php',
2962 'object' =>
'Societe'),
2963 'commande' => array(
'table' =>
'commande',
2964 'fields' => array(
'ref'),
2965 'class' =>
'commande/class/commande.class.php',
2966 'object' =>
'Commande'),
2967 'expedition' => array(
'table' =>
'expedition',
2968 'fields' => array(
'ref'),
2969 'class' =>
'expedition/class/expedition.class.php',
2970 'object' =>
'Expedition'),
2971 'contract' => array(
'table' =>
'contrat',
2972 'fields' => array(
'ref'),
2973 'class' =>
'contrat/class/contrat.class.php',
2974 'object' =>
'Contrat'),
2975 'fichinter' => array(
'table' =>
'fichinter',
2976 'fields' => array(
'ref'),
2977 'class' =>
'fichinter/class/fichinter.class.php',
2978 'object' =>
'Fichinter'),
2979 'ticket' => array(
'table' =>
'ticket',
2980 'fields' => array(
'ref'),
2981 'class' =>
'ticket/class/ticket.class.php',
2982 'object' =>
'Ticket'),
2983 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
2984 'fields' => array(
'ref'),
2985 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
2986 'object' =>
'KnowledgeRecord'),
2987 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
2988 'fields' => array(
'ref'),
2989 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
2990 'object' =>
'SupplierProposal'),
2991 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
2992 'fields' => array(
'ref',
'ref_supplier'),
2993 'class' =>
'fourn/class/fournisseur.commande.class.php',
2994 'object' =>
'SupplierProposal'),
2995 'facture' => array(
'table' =>
'facture',
2996 'fields' => array(
'ref'),
2997 'class' =>
'compta/facture/class/facture.class.php',
2998 'object' =>
'Facture'),
2999 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
3000 'fields' => array(
'ref',
'ref_client'),
3001 'class' =>
'fourn/class/fournisseur.facture.class.php',
3002 'object' =>
'FactureFournisseur'),
3003 'produit' => array(
'table' =>
'product',
3004 'fields' => array(
'ref'),
3005 'class' =>
'product/class/product.class.php',
3006 'object' =>
'Product'),
3007 'productlot' => array(
'table' =>
'product_lot',
3008 'fields' => array(
'batch'),
3009 'class' =>
'product/stock/class/productlot.class.php',
3010 'object' =>
'Productlot'),
3011 'projet' => array(
'table' =>
'projet',
3012 'fields' => array(
'ref'),
3013 'class' =>
'projet/class/projet.class.php',
3014 'object' =>
'Project'),
3015 'projet_task' => array(
'table' =>
'projet_task',
3016 'fields' => array(
'ref'),
3017 'class' =>
'projet/class/task.class.php',
3018 'object' =>
'Task'),
3019 'ressource' => array(
'table' =>
'resource',
3020 'fields' => array(
'ref'),
3021 'class' =>
'ressource/class/dolressource.class.php',
3022 'object' =>
'Dolresource'),
3023 'bom' => array(
'table' =>
'bom_bom',
3024 'fields' => array(
'ref'),
3025 'class' =>
'bom/class/bom.class.php',
3027 'mrp' => array(
'table' =>
'mrp_mo',
3028 'fields' => array(
'ref'),
3029 'class' =>
'mrp/class/mo.class.php',
3033 if (!is_object($hookmanager)) {
3034 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3037 $hookmanager->initHooks(array(
'emailcolector'));
3038 $parameters = array(
'arrayobject' => $arrayobject);
3039 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
3041 $arrayobject = $hookmanager->resArray;
3044 $resultobj = array();
3046 foreach ($arrayobject as $key => $objectdesc) {
3047 $sql =
'SELECT DISTINCT t.rowid ';
3048 $sql .=
' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc[
'table']) .
' AS t';
3050 foreach ($objectdesc[
'fields'] as $field) {
3051 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $this->db->sanitize($field) .
", '%') AND t." . $this->db->sanitize($field) .
" <> '') OR ";
3053 $sql = substr($sql, 0, -4);
3055 $ressqlobj = $this->db->query($sql);
3057 while ($obj = $this->db->fetch_object($ressqlobj)) {
3058 $resultobj[$key][] = $obj->rowid;
3063 foreach ($resultobj as $mod => $ids) {
3064 $moddesc = $arrayobject[$mod];
3065 $elementpath = $mod;
3067 $objectmanaged =
new $moddesc[
'object']($this->db);
3068 foreach ($ids as $val) {
3069 $res = $objectmanaged->fetch($val);
3071 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
3072 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
3074 $this->errors[] =
'object not found';
3078 foreach ($dirs as $target) {
3079 $prefix = $this->actions[$this->id][
'actionparam'];
3080 foreach ($data as $filename => $content) {
3081 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
3083 $this->errors[] =
'Doc not saved';
3088 $operationslog .=
'<br>Save attachment files on disk';
3090 $this->errors[] =
'no joined piece';
3092 $operationslog .=
'<br>No joinded files';
3094 } elseif ($operation[
'type'] ==
'project') {
3096 $projecttocreate =
new Project($this->db);
3097 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
3098 if ($alreadycreated == 0) {
3099 if ($thirdpartystatic->id > 0) {
3100 $projecttocreate->socid = $thirdpartystatic->id;
3101 if ($thirdpartyfoundby) {
3102 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3105 if ($contactstatic->id > 0) {
3106 $projecttocreate->contact_id = $contactstatic->id;
3107 if ($contactfoundby) {
3108 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3112 $description = $descriptiontitle;
3118 $descriptionfull = $description;
3120 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3124 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
3125 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
3127 $projecttocreate->title = $subject;
3128 $projecttocreate->date_start = $dateemail;
3129 $projecttocreate->date_end = 0;
3130 $projecttocreate->opp_status = $id_opp_status;
3131 $projecttocreate->opp_percent = $percent_opp_status;
3133 $projecttocreate->note_private = $descriptionfull;
3134 $projecttocreate->entity = $conf->entity;
3136 $projecttocreate->email_date = $dateemail;
3137 $projecttocreate->email_msgid = $msgid;
3138 $projecttocreate->email_from = $fromstring;
3139 $projecttocreate->email_sender = $sender;
3140 $projecttocreate->email_to = $to;
3141 $projecttocreate->email_tocc = $sendtocc;
3142 $projecttocreate->email_tobcc = $sendtobcc;
3143 $projecttocreate->email_subject = $subject;
3144 $projecttocreate->errors_to =
'';
3146 $savesocid = $projecttocreate->socid;
3150 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3153 if (empty($projecttocreate->ref)) {
3162 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3163 foreach ($dirmodels as $reldir) {
3164 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
3165 if (file_exists($file)) {
3166 $classname = $modele;
3171 if ($classname !==
'') {
3172 if ($savesocid > 0) {
3173 if ($savesocid != $projecttocreate->socid) {
3175 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');
3178 if ($projecttocreate->socid > 0) {
3179 $thirdpartystatic->fetch($projecttocreate->socid);
3183 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
3184 $modModuleToUseForNextValue =
new $classname();
3185 '@phan-var-force ModeleNumRefProjects $modModuleToUseForNextValue';
3186 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
3188 $projecttocreate->ref = $defaultref;
3192 if ($errorforthisaction) {
3195 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
3197 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3199 $operationslog .=
'<br>'.$this->error;
3202 $result = $projecttocreate->create($user);
3205 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
3206 $this->errors = $projecttocreate->errors;
3208 $operationslog .=
'<br>'.$this->error;
3211 $destdir = $conf->project->dir_output.
'/'.$projecttocreate->ref;
3216 foreach ($attachments as $attachment) {
3218 $typeattachment = (string) $attachment->getDisposition();
3219 $filename = $attachment->getFilename();
3220 $content = $attachment->getContent();
3224 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3226 $this->errors = array_merge($this->errors, [$this->error]);
3231 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag($projecttocreate->id);
3233 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag($projecttocreate->id);
3241 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3243 } elseif ($operation[
'type'] ==
'ticket') {
3245 $tickettocreate =
new Ticket($this->db);
3246 if ($ticketalreadyexists == 0) {
3247 if ($thirdpartystatic->id > 0) {
3248 $tickettocreate->socid = $thirdpartystatic->id;
3249 $tickettocreate->fk_soc = $thirdpartystatic->id;
3250 if ($thirdpartyfoundby) {
3251 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3254 if ($contactstatic->id > 0) {
3255 $tickettocreate->contact_id = $contactstatic->id;
3256 if ($contactfoundby) {
3257 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3261 $description = $descriptiontitle;
3267 $descriptionfull = $description;
3269 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3273 $tickettocreate->subject = $subject;
3274 $tickettocreate->message = $description;
3276 $tickettocreate->category_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1)));
3277 $tickettocreate->severity_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1)));
3278 $tickettocreate->origin_email = $from;
3279 $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto :
null);
3280 $tickettocreate->origin_references = (!empty($headers[
'References']) ? $headers[
'References'] :
null);
3281 $tickettocreate->fk_user_create = $user->id;
3282 $tickettocreate->datec =
dol_now();
3283 $tickettocreate->fk_project = $projectstatic->id;
3284 $tickettocreate->notify_tiers_at_create =
getDolGlobalInt(
'TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3285 $tickettocreate->note_private = $descriptionfull;
3286 $tickettocreate->entity = $conf->entity;
3288 $tickettocreate->email_date = $dateemail;
3289 $tickettocreate->email_msgid = $msgid;
3290 $tickettocreate->email_from = $fromstring;
3291 $tickettocreate->email_sender = $sender;
3292 $tickettocreate->email_to = $to;
3293 $tickettocreate->email_tocc = $sendtocc;
3294 $tickettocreate->email_tobcc = $sendtobcc;
3295 $tickettocreate->email_subject = $subject;
3296 $tickettocreate->errors_to =
'';
3300 $savesocid = $tickettocreate->socid;
3304 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3307 if (empty($tickettocreate->ref)) {
3316 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3317 foreach ($dirmodels as $reldir) {
3318 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3319 if (file_exists($file)) {
3320 $classname = $modele;
3325 if ($classname !==
'') {
3326 if ($savesocid > 0) {
3327 if ($savesocid != $tickettocreate->socid) {
3329 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');
3332 if ($tickettocreate->socid > 0) {
3333 $thirdpartystatic->fetch($tickettocreate->socid);
3338 $modModuleToUseForNextValue =
new $classname();
3339 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3340 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3342 $tickettocreate->ref = $defaultref;
3345 if ($errorforthisaction) {
3348 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3350 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3353 $tickettocreate->context[
'actionmsg2'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3354 $tickettocreate->context[
'actionmsg'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3358 $sender_contact =
new Contact($this->db);
3359 $sender_contact->fetch(0,
null,
'', $from);
3360 if (!empty($sender_contact->id)) {
3361 $tickettocreate->context[
'contactid'] = $sender_contact->id;
3364 $result = $tickettocreate->create($user);
3367 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3368 $this->errors = $tickettocreate->errors;
3371 $destdir = $conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3376 foreach ($attachments as $attachment) {
3378 $typeattachment = (string) $attachment->getDisposition();
3379 $filename = $attachment->getName();
3380 $content = $attachment->getContent();
3384 $getMsg = $this->
getmsg($connection, $imapemail, $destdir);
3386 $this->errors = array_merge($this->errors, [$this->error]);
3391 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3393 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3399 } elseif ($operation[
'type'] ==
'candidature') {
3403 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3404 if ($alreadycreated == 0) {
3405 $description = $descriptiontitle;
3411 $descriptionfull = $description;
3412 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3415 $candidaturetocreate->subject = $subject;
3416 $candidaturetocreate->message = $description;
3417 $candidaturetocreate->type_code = 0;
3418 $candidaturetocreate->category_code =
null;
3419 $candidaturetocreate->severity_code =
null;
3420 $candidaturetocreate->email = $from;
3422 $candidaturetocreate->fk_user_creat = $user->id;
3423 $candidaturetocreate->date_creation =
dol_now();
3424 $candidaturetocreate->fk_project = $projectstatic->id;
3425 $candidaturetocreate->description = $description;
3426 $candidaturetocreate->note_private = $descriptionfull;
3427 $candidaturetocreate->entity = $conf->entity;
3428 $candidaturetocreate->email_msgid = $msgid;
3429 $candidaturetocreate->email_date = $dateemail;
3430 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3435 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3477 if ($errorforthisaction) {
3481 $result = $candidaturetocreate->create($user);
3484 $this->error =
'Failed to create candidature: '.implode(
', ', $candidaturetocreate->errors);
3485 $this->errors = $candidaturetocreate->errors;
3488 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag($candidaturetocreate->id);
3491 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3494 if (!is_object($hookmanager)) {
3495 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3497 $hookmanager->initHooks([
'emailcolector']);
3500 $parameters = array(
3501 'connection' => $connection,
3502 'imapemail' => $imapemail,
3503 'overview' => $overview,
3506 'fromtext' => $fromtext,
3508 'actionparam' => $operation[
'actionparam'],
3510 'thirdpartyid' => $thirdpartyid,
3511 'objectid' => $objectid,
3512 'objectemail' => $objectemail,
3514 'messagetext' => $messagetext,
3515 'subject' => $subject,
3516 'header' => $header,
3517 'attachments' => $attachments,
3519 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3522 $errorforthisaction++;
3523 $this->error = $hookmanager->resPrint;
3525 if ($errorforthisaction) {
3527 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3529 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3533 if (!$errorforactions) {
3534 $nbactiondoneforemail++;
3540 if (!$errorforactions) {
3541 if (!empty($targetdir)) {
3544 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3545 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid.
' - '.$imapemail->getHeader()->get(
'subject').
' to '.$targetdir;
3547 $arrayofemailtodelete[$this->
uidAsString($imapemail)] = $imapemail;
3550 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3551 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3553 $arrayofemailtodelete[$imapemail] = $msgid;
3558 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);
3560 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3568 unset($objectemail);
3569 unset($projectstatic);
3570 unset($thirdpartystatic);
3571 unset($contactstatic);
3573 $nbemailprocessed++;
3575 if (!$errorforemail) {
3576 $nbactiondone += $nbactiondoneforemail;
3580 $this->db->commit();
3582 $this->db->rollback();
3586 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3587 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3593 $this->db->rollback();
3597 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3599 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3601 $langs->load(
"admin");
3602 $output = $langs->trans(
'NoNewEmailToProcess');
3603 $output .=
' (defaultlang='.$langs->defaultlang.
')';
3609 krsort($arrayofemailtodelete, SORT_NUMERIC);
3611 foreach ($arrayofemailtodelete as $imapemailnum => $imapemail) {
3612 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemailnum);
3614 $operationslog .=
"<br> move email ".$imapemailnum.($mode> 0 ?
' (test)' :
'');
3616 if (empty($mode) && empty($error)) {
3617 $tmptargetdir = $targetdir;
3624 $result = $imapemail->move($tmptargetdir,
false);
3627 $operationslog .=
'<br>Exception !!!! '.$e->getMessage();
3629 if (empty($result)) {
3630 dol_syslog(
"Failed to move email into target directory ".$targetdir);
3631 $operationslog .=
'<br>Failed to move email into target directory '.$targetdir;
3637 if (empty($mode) && empty($error)) {
3639 $operationslog .=
"<br>Expunge";
3644 $client->disconnect();
3646 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
3647 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
3649 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid.($mode> 0 ?
' (test)' :
'');
3651 if (empty($mode) && empty($error)) {
3652 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
3655 $this->error = imap_last_error();
3656 $this->errors[] = $this->error;
3658 $operationslog .=
'<br>Error in move '.$this->error;
3665 if (empty($mode) && empty($error)) {
3667 $operationslog .=
"<br>Expunge";
3669 imap_expunge($connection);
3671 imap_close($connection);
3674 $this->datelastresult = $now;
3675 $this->lastresult = $output;
3677 $this->debuginfo .=
'IMAP search array used : '.$search;
3679 $this->debuginfo .=
'IMAP search string used : '.$search;
3682 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
3684 if ($operationslog) {
3685 $this->debuginfo .= $operationslog;
3688 if (empty($error) && empty($mode)) {
3689 $this->datelastok = $now;
3692 if (!empty($this->errors)) {
3693 $this->lastresult .=
"<br>".implode(
"<br>", $this->errors);
3695 $this->codelastresult = ($error ?
'KO' :
'OK');
3701 dol_syslog(
"EmailCollector::doCollectOneCollector end", LOG_INFO);
3703 return $error ? -1 : 1;
3718 private function getmsg($mbox, $mid, $destdir =
''): int
3722 global $charset, $htmlmsg, $plainmsg, $attachments;
3723 $htmlmsg = $plainmsg = $charset =
'';
3724 $attachments = array();
3731 $s = imap_fetchstructure($mbox, $mid, FT_UID);
3733 $this->errors = array_merge($this->errors, [imap_last_error()]);
3737 if (empty($s->parts)) {
3739 $this->
getpart($mbox, $mid, $s, 0);
3742 foreach ($s->parts as $partno0 => $p) {
3743 $this->
getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
3776 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
3779 global $htmlmsg, $plainmsg, $charset, $attachments;
3783 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
3784 imap_body($mbox, $mid, FT_UID);
3786 if ($p->encoding == 4) {
3787 $data = quoted_printable_decode($data);
3788 } elseif ($p->encoding == 3) {
3789 $data = base64_decode($data);
3795 if ($p->parameters) {
3796 foreach ($p->parameters as $x) {
3797 $params[strtolower($x->attribute)] = $x->value;
3800 if (!empty($p->dparameters)) {
3801 foreach ($p->dparameters as $x) {
3802 $params[strtolower($x->attribute)] = $x->value;
3805 '@phan-var-force array{filename?:string,name?:string,charset?:string} $params';
3810 if (!empty($params[
'filename']) || !empty($params[
'name'])) {
3812 $filename = $params[
'filename'] ?? $params[
'name'];
3814 $attachments[$filename] = $data;
3816 if (strlen($destdir)) {
3817 if (substr($destdir, -1) !=
'/') {
3822 $file_name_complete = $filename;
3823 $destination = $destdir.$file_name_complete;
3826 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
3829 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
3832 $file_name_original = $file_name;
3841 while (file_exists($destdir.$file_name.
".".$extension)) {
3842 $file_name = $file_name_original .
' (' . $num .
')';
3843 $file_name_complete = $file_name .
"." . $extension;
3844 $destination = $destdir.$file_name_complete;
3850 file_put_contents($destination, $data);
3855 if ($p->type == 0 && $data) {
3856 if (!empty($params[
'charset'])) {
3861 if (strtolower($p->subtype) ==
'plain') {
3862 $plainmsg .= trim($data).
"\n\n";
3864 $htmlmsg .= $data.
"<br><br>";
3866 $charset = $params[
'charset'];
3867 } elseif ($p->type == 2 && $data) {
3873 if (!empty($params[
'charset'])) {
3876 $plainmsg .= $data.
"\n\n";
3880 if (!empty($p->parts)) {
3881 foreach ($p->parts as $partno0 => $p2) {
3882 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1), $destdir);
3898 if (!$string || $fromEncoding == $toEncoding) {
3901 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
3902 if (!$convertedString && extension_loaded(
'mbstring')) {
3903 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
3905 if (!$convertedString) {
3906 throw new Exception(
'Mime string encoding conversion failed');
3908 return $convertedString;
3927 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
3928 $elements = imap_mime_header_decode($subject);
3930 if (!empty($elements)) {
3931 $num = count($elements);
3932 for ($i = 0; $i < $num; $i++) {
3933 $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));
3934 $newstring .= $stringinutf8;
3936 $subject = $newstring;
3938 } elseif (!function_exists(
'mb_decode_mimeheader')) {
3939 $subject = mb_decode_mimeheader($subject);
3940 } elseif (function_exists(
'iconv_mime_decode')) {
3941 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
3957 require_once DOL_DOCUMENT_ROOT .
'/core/lib/images.lib.php';
3960 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
3961 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
3962 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
3963 $maxheightmini = $tmparraysize[
'maxheightmini'];
3964 $quality = $tmparraysize[
'quality'];
3966 file_put_contents($destdir.
'/'.$filename, $content);
3969 vignette($destdir.
'/'.$filename, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
3971 vignette($destdir.
'/'.$filename, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
3984 if (is_object($imapemail)) {
3985 return $imapemail->getAttributes()[
"uid"];
3987 return (
string) $imapemail;