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);
853 foreach ($arrayofcollectors as $emailcollector) {
854 $result = $emailcollector->doCollectOneCollector(0);
855 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
857 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
858 if (!empty($emailcollector->errors)) {
859 $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(
'/-.*$/',
'', $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);
1188 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1189 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService';
1191 $refreshtoken = $tokenobj->getRefreshToken();
1192 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1193 $tokenobj->setRefreshToken($refreshtoken);
1194 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1196 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1197 if (is_object($tokenobj)) {
1198 $token = $tokenobj->getAccessToken();
1200 $this->error =
"Token not found";
1205 $this->error = $e->getMessage();
1206 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1210 $cm =
new ClientManager();
1211 $client = $cm->make([
1212 'host' => $this->host,
1213 'port' => $this->port,
1214 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1215 'validate_cert' => true,
1216 'protocol' =>
'imap',
1217 'username' => $this->login,
1218 'password' => $token,
1219 'authentication' =>
"oauth",
1223 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1225 $cm =
new ClientManager();
1226 $client = $cm->make([
1227 'host' => $this->host,
1228 'port' => $this->port,
1229 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1230 'validate_cert' => true,
1231 'protocol' =>
'imap',
1232 'username' => $this->login,
1233 'password' => $this->password,
1234 'authentication' =>
"login",
1240 }
catch (ConnectionFailedException $e) {
1241 $this->error = $e->getMessage();
1242 $this->errors[] = $this->error;
1243 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1247 $host = dol_getprefix(
'email');
1250 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1252 if (!function_exists(
'imap_open')) {
1253 $this->error =
'IMAP function not enabled on your PHP';
1259 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1260 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1262 $connectstringsource = $connectstringserver.$sourcedir;
1263 $connectstringtarget = $connectstringserver.$targetdir;
1266 $this->debuginfo .=
'connectstringsource = '.$connectstringsource.
', $connectstringtarget='.$connectstringtarget.
'<br>';
1268 $connection = imap_open($connectstringsource, $this->login, $this->password);
1270 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1275 $host = dol_getprefix(
'email');
1286 $criteria = array(array(
'UNDELETED'));
1287 foreach ($this->filters as $rule) {
1288 if (empty($rule[
'status'])) {
1293 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1297 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1300 if ($rule[
'type'] ==
'from') {
1301 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1302 if (count($tmprulevaluearray) >= 2) {
1303 foreach ($tmprulevaluearray as $tmprulevalue) {
1304 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1307 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1310 if ($rule[
'type'] ==
'to') {
1311 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1312 if (count($tmprulevaluearray) >= 2) {
1313 foreach ($tmprulevaluearray as $tmprulevalue) {
1314 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1317 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1320 if ($rule[
'type'] ==
'bcc') {
1321 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1323 if ($rule[
'type'] ==
'cc') {
1324 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1326 if ($rule[
'type'] ==
'subject') {
1327 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1329 $searchfilterexcludesubjectarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1331 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1334 if ($rule[
'type'] ==
'body') {
1335 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1337 $searchfilterexcludebodyarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1339 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1342 if ($rule[
'type'] ==
'header') {
1343 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1355 if ($rule[
'type'] ==
'seen') {
1356 array_push($criteria, array($not.
"SEEN"));
1358 if ($rule[
'type'] ==
'unseen') {
1359 array_push($criteria, array($not.
"UNSEEN"));
1361 if ($rule[
'type'] ==
'unanswered') {
1362 array_push($criteria, array($not.
"UNANSWERED"));
1364 if ($rule[
'type'] ==
'answered') {
1365 array_push($criteria, array($not.
"ANSWERED"));
1367 if ($rule[
'type'] ==
'smaller') {
1368 array_push($criteria, array($not.
"SMALLER"));
1370 if ($rule[
'type'] ==
'larger') {
1371 array_push($criteria, array($not.
"LARGER"));
1375 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1376 $searchfilterdoltrackid++;
1377 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1379 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1380 $searchfilterdoltrackid++;
1381 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1383 if ($rule[
'type'] ==
'withtrackingid') {
1384 $searchfilterdoltrackid++;
1385 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1387 if ($rule[
'type'] ==
'withouttrackingid') {
1388 $searchfilternodoltrackid++;
1389 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1392 if ($rule[
'type'] ==
'isanswer') {
1393 $searchfilterisanswer++;
1394 $searchhead .=
'/References.*@.*/';
1396 if ($rule[
'type'] ==
'isnotanswer') {
1397 $searchfilterisnotanswer++;
1398 $searchhead .=
'! /References.*@.*/';
1401 if ($rule[
'type'] ==
'replyto') {
1402 $searchfilterreplyto++;
1403 $rulesreplyto[] = $rule[
'rulevalue'];
1404 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1408 if (empty($targetdir) || !
getDolGlobalString(
'EMAILCOLLECTOR_NO_FILTER_ON_DATE_IF_THERE_IS_A_TARGETDIR')) {
1410 if ($this->datelastok) {
1411 $fromdate = $this->datelastok;
1413 if ($fromdate > 0) {
1415 array_push($criteria, array(
"SINCE" => date(
'j-M-Y', $fromdate - 1)));
1420 dol_syslog(
"IMAP search string = ".var_export($criteria,
true));
1421 $search = var_export($criteria,
true);
1424 $search =
'UNDELETED';
1425 foreach ($this->filters as $rule) {
1426 if (empty($rule[
'status'])) {
1434 if (!empty($rule[
'rulevalue']) && strpos($rule[
'rulevalue'],
'!') === 0) {
1438 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1441 if ($rule[
'type'] ==
'from') {
1442 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1443 if (count($tmprulevaluearray) >= 2) {
1444 foreach ($tmprulevaluearray as $tmprulevalue) {
1445 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1448 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1451 if ($rule[
'type'] ==
'to') {
1452 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1453 if (count($tmprulevaluearray) >= 2) {
1454 foreach ($tmprulevaluearray as $tmprulevalue) {
1455 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1458 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1461 if ($rule[
'type'] ==
'bcc') {
1462 $search .= ($search ?
' ' :
'').$not.
'BCC';
1464 if ($rule[
'type'] ==
'cc') {
1465 $search .= ($search ?
' ' :
'').$not.
'CC';
1467 if ($rule[
'type'] ==
'subject') {
1470 $searchfilterexcludesubjectarray[] = $rule[
'rulevalue'];
1472 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1475 if ($rule[
'type'] ==
'body') {
1478 $searchfilterexcludebodyarray[] = $rule[
'rulevalue'];
1481 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1484 if ($rule[
'type'] ==
'header') {
1485 $search .= ($search ?
' ' :
'').$not.
'HEADER '.$rule[
'rulevalue'];
1497 if ($rule[
'type'] ==
'seen') {
1498 $search .= ($search ?
' ' :
'').$not.
'SEEN';
1500 if ($rule[
'type'] ==
'unseen') {
1501 $search .= ($search ?
' ' :
'').$not.
'UNSEEN';
1503 if ($rule[
'type'] ==
'unanswered') {
1504 $search .= ($search ?
' ' :
'').$not.
'UNANSWERED';
1506 if ($rule[
'type'] ==
'answered') {
1507 $search .= ($search ?
' ' :
'').$not.
'ANSWERED';
1509 if ($rule[
'type'] ==
'smaller') {
1510 $search .= ($search ?
' ' :
'').$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1512 if ($rule[
'type'] ==
'larger') {
1513 $search .= ($search ?
' ' :
'').$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1517 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1518 $searchfilterdoltrackid++;
1519 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1521 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1522 $searchfilterdoltrackid++;
1523 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1525 if ($rule[
'type'] ==
'withtrackingid') {
1526 $searchfilterdoltrackid++;
1527 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1529 if ($rule[
'type'] ==
'withouttrackingid') {
1530 $searchfilternodoltrackid++;
1531 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1534 if ($rule[
'type'] ==
'isanswer') {
1535 $searchfilterisanswer++;
1536 $searchhead .=
'/References.*@.*/';
1538 if ($rule[
'type'] ==
'isnotanswer') {
1539 $searchfilterisnotanswer++;
1540 $searchhead .=
'! /References.*@.*/';
1543 if ($rule[
'type'] ==
'replyto') {
1544 $searchfilterreplyto++;
1545 $rulesreplyto[] = $rule[
'rulevalue'];
1546 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1550 if (empty($targetdir)) {
1552 if ($this->datelastok) {
1553 $fromdate = $this->datelastok;
1555 if ($fromdate > 0) {
1556 $search .= ($search ?
' ' :
'').
'SINCE '.date(
'j-M-Y', $fromdate - 1);
1565 $nbemailprocessed = 0;
1568 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1575 $tmpsourcedir = $sourcedir;
1580 $f = $client->getFolders(
false, $tmpsourcedir);
1583 if ($folder instanceof Webklex\PHPIMAP\Folder) {
1584 $Query = $folder->messages()->where($criteria);
1587 $this->error =
"Source directory ".$sourcedir.
" not found";
1588 $this->errors[] = $this->error;
1589 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_WARNING);
1594 $this->error =
"Failed to execute getfolders";
1595 $this->errors[] = $this->error;
1596 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1599 }
catch (InvalidWhereQueryCriteriaException $e) {
1600 $this->error = $e->getMessage();
1601 $this->errors[] = $this->error;
1602 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1605 $this->error = $e->getMessage();
1606 $this->errors[] = $this->error;
1607 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1611 '@phan-var-force Webklex\PHPIMAP\Query\Query $Query';
1615 $Query->leaveUnread();
1617 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1620 $this->error = $e->getMessage();
1621 $this->errors[] = $this->error;
1622 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1627 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1629 if ($arrayofemail ===
false) {
1631 $mapoferrrors = imap_errors();
1632 if ($mapoferrrors !==
false) {
1634 $this->error =
"Search string not understood - ".implode(
',', $mapoferrrors);
1635 $this->errors[] = $this->error;
1640 $arrayofemailtodelete = array();
1643 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
1660 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1662 $richarrayofemail = array();
1664 foreach ($arrayofemail as $imapemail) {
1665 if ($nbemailprocessed > 1000) {
1671 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1672 $header = $imapemail->getHeader()->raw;
1673 $overview = $imapemail->getAttributes();
1675 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1676 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1679 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1682 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)(\r\n|\s$)/m', $header, $matches);
1683 $headers = array_combine($matches[1], $matches[2]);
1686 $richarrayofemail[] = array(
'imapemail' => $imapemail,
'header' => $header,
'headers' => $headers,
'overview' => $overview,
'date' => strtotime($headers[
'Date']));
1691 $richarrayofemail =
dol_sort_array($richarrayofemail,
'date',
'asc');
1695 foreach ($richarrayofemail as $tmpval) {
1698 $imapemail = $tmpval[
'imapemail'];
1699 $header = $tmpval[
'header'];
1700 $overview = $tmpval[
'overview'];
1701 $headers = $tmpval[
'headers'];
1703 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1704 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1706 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1707 $headers[
'References'] = $headers[
'references'];
1709 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1710 $headers[
'Message-ID'] = $headers[
'message-id'];
1712 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1713 $headers[
'Subject'] = $headers[
'subject'];
1719 $emailto = (string) $overview[
'to'];
1726 $operationslog .=
'<br>** Process email #'.dol_escape_htmltag($iforemailloop);
1730 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1732 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1734 $operationslog .=
" - ".dol_escape_htmltag((
string) $imapemail);
1735 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1737 $operationslog .=
" - MsgId: ".$msgid;
1738 $operationslog .=
" - Date: ".($headers[
'Date'] ?? $langs->transnoentitiesnoconv(
"NotFound"));
1739 $operationslog .=
" - References: ".dol_escape_htmltag($headers[
'References'] ?? $langs->transnoentitiesnoconv(
"NotFound")).
" - Subject: ".
dol_escape_htmltag($headers[
'Subject']);
1741 dol_syslog(
"-- Process email #".$iforemailloop.
", MsgId: ".$msgid.
", Date: ".($headers[
'Date'] ??
'').
", References: ".($headers[
'References'] ??
'').
", Subject: ".$headers[
'Subject']);
1744 $trackidfoundintorecipienttype =
'';
1745 $trackidfoundintorecipientid = 0;
1750 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)) {
1751 $trackidfoundintorecipienttype = $reg[1];
1752 $trackidfoundintorecipientid = $reg[2];
1753 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1754 $trackidfoundintorecipienttype =
'emailing';
1755 $trackidfoundintorecipientid = $reg[1];
1758 $trackidfoundintomsgidtype =
'';
1759 $trackidfoundintomsgidid = 0;
1764 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)) {
1765 $trackidfoundintomsgidtype = $reg[1];
1766 $trackidfoundintomsgidid = $reg[2];
1767 } elseif (preg_match(
'/(?:[\+\-])emailing-(\w+)@/', $msgid, $reg)) {
1768 $trackidfoundintomsgidtype =
'emailing';
1769 $trackidfoundintomsgidid = $reg[1];
1773 if ($searchfilterdoltrackid > 0) {
1774 if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) {
1775 if (empty($headers[
'References']) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References'])) {
1776 $nbemailprocessed++;
1777 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");
1782 if ($searchfilternodoltrackid > 0) {
1783 if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($headers[
'References']) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))) {
1784 $nbemailprocessed++;
1785 dol_syslog(
" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
1790 if ($searchfilterisanswer > 0) {
1791 if (empty($headers[
'In-Reply-To'])) {
1792 $nbemailprocessed++;
1793 dol_syslog(
" Discarded - Email is not an answer (no In-Reply-To header)");
1797 if (preg_match(
'/^(Re|AW)\s*:\s+/i', $headers[
'Subject'])) {
1803 if (!empty($headers[
'In-Reply-To'])) {
1811 $nbemailprocessed++;
1812 dol_syslog(
" Discarded - Email is not an answer (no RE prefix in subject)");
1816 if ($searchfilterisnotanswer > 0) {
1817 if (!empty($headers[
'In-Reply-To'])) {
1821 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) {
1827 $nbemailprocessed++;
1828 dol_syslog(
" Discarded - Email is an answer");
1833 if ($searchfilterreplyto > 0) {
1834 if (!empty($headers[
'Reply-To'])) {
1836 foreach ($rulesreplyto as $key => $rulereplyto) {
1837 if (preg_match(
'/'.preg_quote($rulereplyto,
'/').
'/', $headers[
'Reply-To'])) {
1842 if (!$isreplytook || $isreplytook != count($rulesreplyto)) {
1843 $nbemailprocessed++;
1844 dol_syslog(
" Discarded - Reply-to does not match");
1852 $thirdpartystatic =
new Societe($this->db);
1853 $contactstatic =
new Contact($this->db);
1854 $projectstatic =
new Project($this->db);
1856 $nbactiondoneforemail = 0;
1858 $errorforactions = 0;
1859 $thirdpartyfoundby =
'';
1860 $contactfoundby =
'';
1861 $projectfoundby =
'';
1862 $ticketfoundby =
'';
1863 $candidaturefoundby =
'';
1867 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".
dol_print_date($overview[
'date'],
'dayrfc',
'gmt').
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
1872 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);
1882 global $htmlmsg, $plainmsg, $charset, $attachments;
1886 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1887 if ($imapemail->hasHTMLBody()) {
1888 $htmlmsg = $imapemail->getHTMLBody();
1890 if ($imapemail->hasTextBody()) {
1891 $plainmsg = $imapemail->getTextBody();
1893 if ($imapemail->hasAttachments()) {
1894 $attachments = $imapemail->getAttachments()->all();
1899 $this->
getmsg($connection, $imapemail);
1901 '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments';
1913 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
1914 dol_syslog(
" Discarded - Email body is not valid utf8");
1918 if (!empty($searchfilterexcludebodyarray)) {
1919 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
1920 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
1921 $nbemailprocessed++;
1922 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
1923 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
1985 $replytostring =
'';
1988 $fromstring = $overview[
'from'];
1989 $replytostring = empty($overview[
'in_reply-to']) ? $headers[
'Reply-To'] : $overview[
'in_reply-to'];
1991 $sender = $overview[
'sender'];
1992 $to = $overview[
'to'];
1993 $sendtocc = empty($overview[
'cc']) ?
'' : $overview[
'cc'];
1994 $sendtobcc = empty($overview[
'bcc']) ?
'' : $overview[
'bcc'];
1996 $tmpdate = $overview[
'date']->toDate();
1997 $tmptimezone = $tmpdate->getTimezone()->getName();
2000 if (preg_match(
'/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) {
2001 if ($reg[1] ==
'+' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2002 $dateemail -= (3600 * (int) $reg[2]);
2003 $dateemail -= (60 * (int) $reg[3]);
2005 if ($reg[1] ==
'-' && ($reg[2] !=
'00' || $reg[3] !=
'00')) {
2006 $dateemail += (3600 * (int) $reg[2]);
2007 $dateemail += (60 * (int) $reg[3]);
2010 $subject = $overview[
'subject'];
2012 $fromstring = $overview[0]->from;
2013 $replytostring = (!empty($overview[
'in_reply-to']) ? $overview[
'in_reply-to'] : (!empty($headers[
'Reply-To']) ? $headers[
'Reply-To'] :
"")) ;
2015 $sender = !empty($overview[0]->sender) ? $overview[0]->sender :
'';
2016 $to = $overview[0]->to;
2017 $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc :
'';
2018 $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc :
'';
2020 $subject = $overview[0]->subject;
2024 if (!empty($searchfilterexcludesubjectarray)) {
2025 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
2026 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
2027 $nbemailprocessed++;
2028 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
2029 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
2036 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
2038 $fromtext = $reg[1];
2040 $from = $fromstring;
2043 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
2045 $replytotext = $reg[1];
2047 $replyto = $replytostring;
2051 $fk_element_type =
'';
2068 $objectemail =
null;
2071 $arrayofreferences = array();
2072 if (!empty($headers[
'References'])) {
2073 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
2075 if (!in_array(
'<'.$msgid.
'>', $arrayofreferences)) {
2076 $arrayofreferences = array_merge($arrayofreferences, array(
'<'.$msgid.
'>'));
2081 foreach ($arrayofreferences as $reference) {
2083 if (!empty($trackidfoundintorecipienttype)) {
2084 $resultsearchtrackid = -1;
2085 $reg[1] = $trackidfoundintorecipienttype;
2086 $reg[2] = $trackidfoundintorecipientid;
2087 } elseif (!empty($trackidfoundintomsgidtype)) {
2088 $resultsearchtrackid = -1;
2089 $reg[1] = $trackidfoundintomsgidtype;
2090 $reg[2] = $trackidfoundintomsgidid;
2092 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
2093 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2094 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
2098 if (!empty($resultsearchtrackid)) {
2100 $trackid = $reg[1].$reg[2];
2102 $objectid = $reg[2];
2104 if ($reg[1] ==
'thi') {
2105 $objectemail =
new Societe($this->db);
2107 if ($reg[1] ==
'ctc') {
2108 $objectemail =
new Contact($this->db);
2110 if ($reg[1] ==
'inv') {
2111 $objectemail =
new Facture($this->db);
2113 if ($reg[1] ==
'sinv') {
2116 if ($reg[1] ==
'pro') {
2117 $objectemail =
new Propal($this->db);
2119 if ($reg[1] ==
'ord') {
2120 $objectemail =
new Commande($this->db);
2122 if ($reg[1] ==
'shi') {
2125 if ($reg[1] ==
'spro') {
2128 if ($reg[1] ==
'sord') {
2131 if ($reg[1] ==
'rec') {
2132 $objectemail =
new Reception($this->db);
2134 if ($reg[1] ==
'proj') {
2135 $objectemail =
new Project($this->db);
2136 $projectfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2138 if ($reg[1] ==
'tas') {
2139 $objectemail =
new Task($this->db);
2141 if ($reg[1] ==
'con') {
2142 $objectemail =
new Contact($this->db);
2144 if ($reg[1] ==
'use') {
2145 $objectemail =
new User($this->db);
2147 if ($reg[1] ==
'tic') {
2148 $objectemail =
new Ticket($this->db);
2149 $ticketfoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2151 if ($reg[1] ==
'recruitmentcandidature') {
2153 $candidaturefoundby =
'TrackID dolibarr-'.$trackid.
'@...';
2155 if ($reg[1] ==
'mem') {
2156 $objectemail =
new Adherent($this->db);
2164 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
2166 if (is_null($objectemail) && isModEnabled(
'ticket')) {
2167 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket";
2168 $sql .=
" WHERE email_msgid = '".$this->db->escape($reg[1]).
"' OR origin_references like '%".$this->db->escape($this->db->escapeforlike($reg[1])).
"%'";
2169 $resql = $this->db->query($sql);
2171 $obj = $this->db->fetch_object($resql);
2173 $objectid = $obj->rowid;
2174 $objectemail =
new Ticket($this->db);
2175 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2182 if (!is_object($objectemail) && isModEnabled(
'project')) {
2183 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2184 $resql = $this->db->query($sql);
2186 $obj = $this->db->fetch_object($resql);
2188 $objectid = $obj->rowid;
2189 $objectemail =
new Project($this->db);
2190 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2197 if (!is_object($objectemail) && isModEnabled(
'recruitment')) {
2198 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature 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;
2205 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2214 if (is_object($objectemail)) {
2215 $result = $objectemail->fetch($objectid);
2217 $fk_element_id = $objectemail->id;
2218 $fk_element_type = $objectemail->element;
2220 if ($fk_element_type ==
'facture') {
2221 $fk_element_type =
'invoice';
2224 if (get_class($objectemail) !=
'Societe') {
2225 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2227 $thirdpartyid = $objectemail->id;
2230 if (get_class($objectemail) !=
'Contact') {
2231 $contactid = $objectemail->fk_socpeople;
2233 $contactid = $objectemail->id;
2236 if (get_class($objectemail) !=
'Project') {
2237 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2239 $projectid = $objectemail->id;
2242 if ($objectemail instanceof
Ticket) {
2243 $ticketid = $objectemail->id;
2245 $changeonticket_references =
false;
2246 if (empty($trackid)) {
2247 $trackid = $objectemail->track_id;
2249 if (empty($objectemail->origin_references)) {
2250 $objectemail->origin_references = $headers[
'References'];
2251 $changeonticket_references =
true;
2253 foreach ($arrayofreferences as $key => $referencetmp) {
2254 if (!str_contains($objectemail->origin_references, $referencetmp)) {
2255 $objectemail->origin_references .=
" ".$referencetmp;
2256 $changeonticket_references =
true;
2260 if ($changeonticket_references) {
2261 $objectemail->update($user, 1);
2268 if ($projectid > 0) {
2269 $result = $projectstatic->fetch($projectid);
2271 $projectstatic->id = 0;
2273 $projectid = $projectstatic->id;
2275 $projectfoundby =
'trackid ('.$trackid.
')';
2277 if (empty($contactid)) {
2278 $contactid = $projectstatic->fk_contact;
2280 if (empty($thirdpartyid)) {
2281 $thirdpartyid = $projectstatic->fk_soc;
2286 if ($contactid > 0) {
2287 $result = $contactstatic->fetch($contactid);
2289 $contactstatic->id = 0;
2291 $contactid = $contactstatic->id;
2293 $contactfoundby =
'trackid ('.$trackid.
')';
2295 if (empty($thirdpartyid)) {
2296 $thirdpartyid = $contactstatic->fk_soc;
2301 if ($thirdpartyid > 0) {
2302 $result = $thirdpartystatic->fetch($thirdpartyid);
2304 $thirdpartystatic->id = 0;
2306 $thirdpartyid = $thirdpartystatic->id;
2308 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2313 if (is_object($objectemail)) {
2318 if (empty($contactid)) {
2319 $result = $contactstatic->fetch(0,
null,
'', $from);
2322 dol_syslog(
"We found a contact with the email ".$from);
2323 $contactid = $contactstatic->id;
2324 $contactfoundby =
'email of contact ('.$from.
')';
2325 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2326 $result = $thirdpartystatic->fetch($contactstatic->socid);
2328 $thirdpartyid = $thirdpartystatic->id;
2329 $thirdpartyfoundby =
'email of contact ('.$from.
')';
2335 if (empty($thirdpartyid)) {
2336 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
2338 dol_syslog(
"We found a thirdparty with the email ".$from);
2339 $thirdpartyid = $thirdpartystatic->id;
2340 $thirdpartyfoundby =
'email ('.$from.
')';
2376 foreach ($this->actions as $operation) {
2377 $errorforthisaction = 0;
2378 $ticketalreadyexists = 0;
2379 if ($errorforactions) {
2382 if (empty($operation[
'status'])) {
2386 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2389 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2390 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2393 $actioncode =
'EMAIL_IN';
2395 if (preg_match(
'/Sent$/', $sourcedir) || preg_match(
'/envoyés$/i', $sourcedir)) {
2396 $actioncode =
'EMAIL';
2399 $arrayofemailtoconsideresender = explode(
',',
getDolGlobalString(
'MAIL_FROM_EMAILS_TO_CONSIDER_SENDING'));
2400 foreach ($arrayofemailtoconsideresender as $emailtoconsidersender) {
2401 if (preg_match(
'/'.preg_quote($emailtoconsidersender,
'/').
'/', $fromstring)) {
2402 $actioncode =
'EMAIL';
2405 $operationslog .=
'<br>Email will have actioncode='.$actioncode;
2407 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2409 $descriptiontitle = $langs->transnoentitiesnoconv(
"RecordCreatedByEmailCollector", $this->
ref);
2414 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2416 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2418 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2420 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailReply").($langs->trans(
"MailReply") !=
'Reply to' ?
' (Reply to)' :
'').
' : '.
dol_escape_htmltag($replyto));
2423 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2426 if ($operation[
'type'] ==
'ticket') {
2428 $tickettocreate =
new Ticket($this->db);
2429 $errorfetchticket = 0;
2430 $alreadycreated = 0;
2431 if (!empty($trackid)) {
2432 $alreadycreated = $tickettocreate->fetch(0,
'', $trackid);
2434 if ($alreadycreated == 0 && !empty($msgid)) {
2435 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2437 if ($alreadycreated < 0) {
2438 $errorfetchticket++;
2440 if (empty($errorfetchticket)) {
2441 if ($alreadycreated == 0) {
2442 $operationslog .=
'<br>Ticket not found using trackid='.$trackid.
' or msgid='.$msgid;
2443 $ticketalreadyexists = 0;
2445 $operationslog .=
'<br>Ticket already found using trackid='.$trackid.
' or msgid='.$msgid;
2446 $ticketalreadyexists = 1;
2447 $operation[
'type'] =
'recordevent';
2450 $ticketalreadyexists = -1;
2457 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2458 if (empty($operation[
'actionparam'])) {
2460 $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;";
2461 $this->errors[] = $this->error;
2463 $actionparam = $operation[
'actionparam'];
2464 $idtouseforthirdparty =
'';
2465 $nametouseforthirdparty =
'';
2466 $emailtouseforthirdparty =
'';
2467 $namealiastouseforthirdparty =
'';
2469 $operationslog .=
'<br>Loop on each property to set into actionparam';
2473 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2477 $regforregex = array();
2479 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2480 $sourcefield = $regforregex[1];
2481 $regexstring = $regforregex[2];
2484 if (!empty($sourcefield) && !empty($regexstring)) {
2485 if (strtolower($sourcefield) ==
'body') {
2486 $sourcestring = $messagetext;
2487 } elseif (strtolower($sourcefield) ==
'subject') {
2488 $sourcestring = $subject;
2489 } elseif (strtolower($sourcefield) ==
'header') {
2490 $sourcestring = $header;
2493 if ($sourcestring) {
2494 $regforval = array();
2496 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2499 if ($propertytooverwrite ==
'id') {
2500 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2502 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2503 } elseif ($propertytooverwrite ==
'email') {
2504 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2506 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2507 } elseif ($propertytooverwrite ==
'name') {
2508 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2510 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2511 } elseif ($propertytooverwrite ==
'name_alias') {
2512 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2514 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2516 $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';
2520 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2521 $idtouseforthirdparty =
null;
2522 $nametouseforthirdparty =
null;
2523 $emailtouseforthirdparty =
null;
2524 $namealiastouseforthirdparty =
null;
2526 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2528 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2535 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2536 $this->errors[] = $this->error;
2538 $operationslog .=
'<br>'.$this->error;
2540 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2544 if ($propertytooverwrite ==
'id') {
2545 $idtouseforthirdparty = $reg[2];
2547 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2548 } elseif ($propertytooverwrite ==
'email') {
2549 $emailtouseforthirdparty = $reg[2];
2551 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2552 } elseif ($propertytooverwrite ==
'name') {
2553 $nametouseforthirdparty = $reg[2];
2555 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2556 } elseif ($propertytooverwrite ==
'name_alias') {
2557 $namealiastouseforthirdparty = $reg[2];
2559 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2563 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2564 $this->errors[] = $this->error;
2569 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2571 $operationslog .=
'<br>We have this initial main data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty.
'.';
2574 $tmpobject->element =
'generic';
2575 $tmpobject->id = $idtouseforthirdparty;
2576 $tmpobject->name = $nametouseforthirdparty;
2577 $tmpobject->name_alias = $namealiastouseforthirdparty;
2578 $tmpobject->email = $emailtouseforthirdparty;
2582 $idtouseforthirdparty = $tmpobject->id;
2583 $nametouseforthirdparty = $tmpobject->name;
2584 $namealiastouseforthirdparty = $tmpobject->name_alias;
2585 $emailtouseforthirdparty = $tmpobject->email;
2587 $operationslog .=
'<br>We try to search existing thirdparty with idtouseforthirdparty='.$idtouseforthirdparty.
' emailtouseforthirdparty='.$emailtouseforthirdparty.
' nametouseforthirdparty='.$nametouseforthirdparty.
' namealiastouseforthirdparty='.$namealiastouseforthirdparty;
2590 $result = $thirdpartystatic->findNearest($idtouseforthirdparty, $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', $emailtouseforthirdparty, $namealiastouseforthirdparty);
2594 $this->error =
'Error when getting thirdparty with name '.$nametouseforthirdparty.
' (may be 2 record exists with same name ?)';
2595 $this->errors[] = $this->error;
2597 } elseif ($result == 0) {
2598 if ($operation[
'type'] ==
'loadthirdparty') {
2599 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2602 $resultContact = $contactstatic->findNearest(0,
'',
'',
'', $emailtouseforthirdparty,
'', 0);
2603 if ($resultContact > 0) {
2604 $idtouseforthirdparty = $contactstatic->socid;
2605 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2607 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2610 $langs->load(
"errors");
2611 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2612 $this->errors[] = $this->error;
2616 $langs->load(
"errors");
2617 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2618 $this->errors[] = $this->error;
2620 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2621 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
2624 $thirdpartystatic =
new Societe($db);
2625 $thirdpartystatic->name = $nametouseforthirdparty;
2626 if (!empty($namealiastouseforthirdparty)) {
2627 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
2628 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
2631 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'' : $fromtext) : $replytostring);
2633 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ?
'' : $from) : $replyto) : $emailtouseforthirdparty);
2636 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2638 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
2639 $thirdpartystatic->code_client =
'auto';
2641 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
2642 $thirdpartystatic->code_fournisseur =
'auto';
2645 if ($errorforthisaction) {
2648 $result = $thirdpartystatic->create($user);
2651 $this->error = $thirdpartystatic->error;
2652 $this->errors = $thirdpartystatic->errors;
2654 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag($thirdpartystatic->id);
2659 dol_syslog(
"One and only one existing third party has been found");
2661 $thirdpartystatic->fetch($result);
2663 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag($thirdpartystatic->id).
" and name ".
dol_escape_htmltag($thirdpartystatic->name);
2667 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
2668 if (empty($operation[
'actionparam'])) {
2670 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
2671 $this->errors[] = $this->error;
2673 $contact_static =
new Contact($this->db);
2675 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2676 if ($errorforthisaction) {
2679 if (!empty($contact_static->email) && $contact_static->email != $from) {
2680 $from = $contact_static->email;
2683 $result = $contactstatic->fetch(0,
null,
'', $from);
2686 $this->error =
'Error when getting contact with email ' . $from;
2687 $this->errors[] = $this->error;
2689 } elseif ($result == 0) {
2690 dol_syslog(
"Contact with email " . $from .
" was not found. We try to create it.");
2691 $contactstatic =
new Contact($this->db);
2694 $contactstatic->email = $from;
2695 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($from);
2698 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2700 if ($errorforthisaction) {
2704 if (!empty($contactstatic->country)) {
2705 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2706 $result =
getCountry(
'', 3, $this->db,
null, 1, $contactstatic->country);
2707 if ($result ==
'NotDefined') {
2709 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
2710 } elseif (!($result > 0)) {
2712 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
2713 $this->errors[] = $this->db->lasterror();
2715 $contactstatic->country_id = $result;
2716 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2718 } elseif (!empty($contactstatic->country_code)) {
2719 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2720 $result =
getCountry($contactstatic->country_code, 3, $this->db);
2721 if ($result ==
'NotDefined') {
2723 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
2724 } elseif (!($result > 0)) {
2726 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
2727 $this->errors[] = $this->db->lasterror();
2729 $contactstatic->country_id = $result;
2730 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2734 if (!$errorforactions) {
2736 if (!empty($contactstatic->state)) {
2737 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2738 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
2739 if (empty($result)) {
2741 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
2742 } elseif (!($result > 0)) {
2744 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
2745 $this->errors[] = $this->db->lasterror();
2747 $contactstatic->state_id = $result;
2748 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2750 } elseif (!empty($contactstatic->state_code)) {
2751 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2752 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
2753 if (empty($result)) {
2755 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
2756 } elseif (!($result > 0)) {
2758 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
2759 $this->errors[] = $this->db->lasterror();
2761 $contactstatic->state_id = $result;
2762 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2767 if (!$errorforactions) {
2768 $result = $contactstatic->create($user);
2771 $this->error = $contactstatic->error;
2772 $this->errors = $contactstatic->errors;
2774 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag($contactstatic->id);
2781 } elseif ($operation[
'type'] ==
'recordevent') {
2785 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
2786 if ($alreadycreated == 0) {
2787 $operationslog .=
'<br>We did not find existing actionmail with msgid='.$msgid;
2789 if ($projectstatic->id > 0) {
2790 if ($projectfoundby) {
2791 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
2794 if ($thirdpartystatic->id > 0) {
2795 if ($thirdpartyfoundby) {
2796 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2799 if ($contactstatic->id > 0) {
2800 if ($contactfoundby) {
2801 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2805 $description = $descriptiontitle;
2811 $descriptionfull = $description;
2813 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2818 $actioncomm->type_code =
'AC_OTH_AUTO';
2819 $actioncomm->code =
'AC_'.$actioncode;
2820 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
2821 $actioncomm->note_private = $descriptionfull;
2822 $actioncomm->fk_project = $projectstatic->id;
2823 $actioncomm->datep = $dateemail;
2824 $actioncomm->datef = $dateemail;
2825 $actioncomm->percentage = -1;
2826 $actioncomm->socid = $thirdpartystatic->id;
2827 $actioncomm->contact_id = $contactstatic->id;
2828 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array());
2829 $actioncomm->authorid = $user->id;
2830 $actioncomm->userownerid = $user->id;
2832 $actioncomm->email_msgid = $msgid;
2833 $actioncomm->email_from = $fromstring;
2834 $actioncomm->email_sender = $sender;
2835 $actioncomm->email_to = $to;
2836 $actioncomm->email_tocc = $sendtocc;
2837 $actioncomm->email_tobcc = $sendtobcc;
2838 $actioncomm->email_subject = $subject;
2839 $actioncomm->errors_to =
'';
2841 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
2842 $actioncomm->fk_element = $fk_element_id;
2843 $actioncomm->elementid = $fk_element_id;
2844 $actioncomm->elementtype = $fk_element_type;
2845 if (is_object($objectemail) && $objectemail->module) {
2846 $actioncomm->elementtype .=
'@'.$objectemail->module;
2853 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2855 if ($errorforthisaction) {
2858 $result = $actioncomm->create($user);
2861 $this->errors = $actioncomm->errors;
2863 if ($fk_element_type ==
"ticket" && is_object($objectemail)) {
2864 if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED) {
2865 if ($objectemail->fk_user_assign !=
null) {
2866 $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED);
2868 $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ);
2872 $operationslog .=
'<br>Ticket Re-Opened successfully -> ref='.$objectemail->ref;
2875 $this->error =
'Error while changing the ticket status -> ref='.$objectemail->ref;
2876 $this->errors[] = $this->error;
2879 if (!empty($attachments)) {
2881 $ticket =
new Ticket($this->db);
2882 $ticket->fetch($fk_element_id);
2883 $destdir = $conf->ticket->dir_output.
'/'.$ticket->ref;
2888 foreach ($attachments as $attachment) {
2889 $attachment->save($destdir.
'/');
2892 $this->
getmsg($connection, $imapemail, $destdir);
2897 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag($actioncomm->id);
2901 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
2904 foreach ($attachments as $attachment) {
2905 if ($attachment->getName() ===
'undefined') {
2908 $data[$attachment->getName()] = $attachment->getContent();
2912 foreach ($pj as $key => $val) {
2913 $data[$val[
'filename']] =
getFileData($imapemail, $val[
'pos'], $val[
'type'], $connection);
2916 if (count($data) > 0) {
2917 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($from).
"%'";
2918 $resql = $this->db->query($sql);
2919 if ($this->db->num_rows($resql) == 0) {
2920 $this->errors[] =
"User Not allowed to add documents ({$from})";
2922 $arrayobject = array(
2923 'propale' => array(
'table' =>
'propal',
2924 'fields' => array(
'ref'),
2925 'class' =>
'comm/propal/class/propal.class.php',
2926 'object' =>
'Propal'),
2927 'holiday' => array(
'table' =>
'holiday',
2928 'fields' => array(
'ref'),
2929 'class' =>
'holiday/class/holiday.class.php',
2930 'object' =>
'Holiday'),
2931 'expensereport' => array(
'table' =>
'expensereport',
2932 'fields' => array(
'ref'),
2933 'class' =>
'expensereport/class/expensereport.class.php',
2934 'object' =>
'ExpenseReport'),
2935 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
2936 'fields' => array(
'ref'),
2937 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
2938 'object' =>
'RecruitmentJobPosition'),
2939 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
2940 'fields' => array(
'ref'),
2941 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
2942 'object' =>
' RecruitmentCandidature'),
2943 'societe' => array(
'table' =>
'societe',
2944 'fields' => array(
'code_client',
'code_fournisseur'),
2945 'class' =>
'societe/class/societe.class.php',
2946 'object' =>
'Societe'),
2947 'commande' => array(
'table' =>
'commande',
2948 'fields' => array(
'ref'),
2949 'class' =>
'commande/class/commande.class.php',
2950 'object' =>
'Commande'),
2951 'expedition' => array(
'table' =>
'expedition',
2952 'fields' => array(
'ref'),
2953 'class' =>
'expedition/class/expedition.class.php',
2954 'object' =>
'Expedition'),
2955 'contract' => array(
'table' =>
'contrat',
2956 'fields' => array(
'ref'),
2957 'class' =>
'contrat/class/contrat.class.php',
2958 'object' =>
'Contrat'),
2959 'fichinter' => array(
'table' =>
'fichinter',
2960 'fields' => array(
'ref'),
2961 'class' =>
'fichinter/class/fichinter.class.php',
2962 'object' =>
'Fichinter'),
2963 'ticket' => array(
'table' =>
'ticket',
2964 'fields' => array(
'ref'),
2965 'class' =>
'ticket/class/ticket.class.php',
2966 'object' =>
'Ticket'),
2967 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
2968 'fields' => array(
'ref'),
2969 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
2970 'object' =>
'KnowledgeRecord'),
2971 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
2972 'fields' => array(
'ref'),
2973 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
2974 'object' =>
'SupplierProposal'),
2975 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
2976 'fields' => array(
'ref',
'ref_supplier'),
2977 'class' =>
'fourn/class/fournisseur.commande.class.php',
2978 'object' =>
'SupplierProposal'),
2979 'facture' => array(
'table' =>
'facture',
2980 'fields' => array(
'ref'),
2981 'class' =>
'compta/facture/class/facture.class.php',
2982 'object' =>
'Facture'),
2983 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
2984 'fields' => array(
'ref',
'ref_client'),
2985 'class' =>
'fourn/class/fournisseur.facture.class.php',
2986 'object' =>
'FactureFournisseur'),
2987 'produit' => array(
'table' =>
'product',
2988 'fields' => array(
'ref'),
2989 'class' =>
'product/class/product.class.php',
2990 'object' =>
'Product'),
2991 'productlot' => array(
'table' =>
'product_lot',
2992 'fields' => array(
'batch'),
2993 'class' =>
'product/stock/class/productlot.class.php',
2994 'object' =>
'Productlot'),
2995 'projet' => array(
'table' =>
'projet',
2996 'fields' => array(
'ref'),
2997 'class' =>
'projet/class/projet.class.php',
2998 'object' =>
'Project'),
2999 'projet_task' => array(
'table' =>
'projet_task',
3000 'fields' => array(
'ref'),
3001 'class' =>
'projet/class/task.class.php',
3002 'object' =>
'Task'),
3003 'ressource' => array(
'table' =>
'resource',
3004 'fields' => array(
'ref'),
3005 'class' =>
'ressource/class/dolressource.class.php',
3006 'object' =>
'Dolresource'),
3007 'bom' => array(
'table' =>
'bom_bom',
3008 'fields' => array(
'ref'),
3009 'class' =>
'bom/class/bom.class.php',
3011 'mrp' => array(
'table' =>
'mrp_mo',
3012 'fields' => array(
'ref'),
3013 'class' =>
'mrp/class/mo.class.php',
3017 if (!is_object($hookmanager)) {
3018 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3021 $hookmanager->initHooks(array(
'emailcolector'));
3022 $parameters = array(
'arrayobject' => $arrayobject);
3023 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
3025 $arrayobject = $hookmanager->resArray;
3028 $resultobj = array();
3030 foreach ($arrayobject as $key => $objectdesc) {
3031 $sql =
'SELECT DISTINCT t.rowid ';
3032 $sql .=
' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc[
'table']) .
' AS t';
3034 foreach ($objectdesc[
'fields'] as $field) {
3035 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $this->db->sanitize($field) .
", '%') AND t." . $this->db->sanitize($field) .
" <> '') OR ";
3037 $sql = substr($sql, 0, -4);
3039 $ressqlobj = $this->db->query($sql);
3041 while ($obj = $this->db->fetch_object($ressqlobj)) {
3042 $resultobj[$key][] = $obj->rowid;
3047 foreach ($resultobj as $mod => $ids) {
3048 $moddesc = $arrayobject[$mod];
3049 $elementpath = $mod;
3051 $objectmanaged =
new $moddesc[
'object']($this->db);
3052 foreach ($ids as $val) {
3053 $res = $objectmanaged->fetch($val);
3055 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
3056 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
3058 $this->errors[] =
'object not found';
3062 foreach ($dirs as $target) {
3063 $prefix = $this->actions[$this->id][
'actionparam'];
3064 foreach ($data as $filename => $content) {
3065 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
3067 $this->errors[] =
'Doc not saved';
3072 $operationslog .=
'<br>Save attachment files on disk';
3074 $this->errors[] =
'no joined piece';
3076 $operationslog .=
'<br>No joinded files';
3078 } elseif ($operation[
'type'] ==
'project') {
3080 $projecttocreate =
new Project($this->db);
3081 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
3082 if ($alreadycreated == 0) {
3083 if ($thirdpartystatic->id > 0) {
3084 $projecttocreate->socid = $thirdpartystatic->id;
3085 if ($thirdpartyfoundby) {
3086 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3089 if ($contactstatic->id > 0) {
3090 $projecttocreate->contact_id = $contactstatic->id;
3091 if ($contactfoundby) {
3092 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3096 $description = $descriptiontitle;
3102 $descriptionfull = $description;
3104 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3108 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
3109 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
3111 $projecttocreate->title = $subject;
3112 $projecttocreate->date_start = $dateemail;
3113 $projecttocreate->date_end = 0;
3114 $projecttocreate->opp_status = $id_opp_status;
3115 $projecttocreate->opp_percent = $percent_opp_status;
3117 $projecttocreate->note_private = $descriptionfull;
3118 $projecttocreate->entity = $conf->entity;
3120 $projecttocreate->email_date = $dateemail;
3121 $projecttocreate->email_msgid = $msgid;
3122 $projecttocreate->email_from = $fromstring;
3123 $projecttocreate->email_sender = $sender;
3124 $projecttocreate->email_to = $to;
3125 $projecttocreate->email_tocc = $sendtocc;
3126 $projecttocreate->email_tobcc = $sendtobcc;
3127 $projecttocreate->email_subject = $subject;
3128 $projecttocreate->errors_to =
'';
3130 $savesocid = $projecttocreate->socid;
3134 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3137 if (empty($projecttocreate->ref)) {
3146 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3147 foreach ($dirmodels as $reldir) {
3148 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
3149 if (file_exists($file)) {
3150 $classname = $modele;
3155 if ($classname !==
'') {
3156 if ($savesocid > 0) {
3157 if ($savesocid != $projecttocreate->socid) {
3159 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');
3162 if ($projecttocreate->socid > 0) {
3163 $thirdpartystatic->fetch($projecttocreate->socid);
3167 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
3168 $modModuleToUseForNextValue =
new $classname();
3169 '@phan-var-force ModeleNumRefProjects $modModuleToUseForNextValue';
3170 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
3172 $projecttocreate->ref = $defaultref;
3176 if ($errorforthisaction) {
3179 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
3181 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3183 $operationslog .=
'<br>'.$this->error;
3186 $result = $projecttocreate->create($user);
3189 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
3190 $this->errors = $projecttocreate->errors;
3192 $operationslog .=
'<br>'.$this->error;
3195 $destdir = $conf->project->dir_output.
'/'.$projecttocreate->ref;
3200 foreach ($attachments as $attachment) {
3202 $typeattachment = (string) $attachment->getDisposition();
3203 $filename = $attachment->getFilename();
3204 $content = $attachment->getContent();
3208 $this->
getmsg($connection, $imapemail, $destdir);
3211 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag($projecttocreate->id);
3213 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag($projecttocreate->id);
3221 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3223 } elseif ($operation[
'type'] ==
'ticket') {
3225 $tickettocreate =
new Ticket($this->db);
3226 if ($ticketalreadyexists == 0) {
3227 if ($thirdpartystatic->id > 0) {
3228 $tickettocreate->socid = $thirdpartystatic->id;
3229 $tickettocreate->fk_soc = $thirdpartystatic->id;
3230 if ($thirdpartyfoundby) {
3231 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3234 if ($contactstatic->id > 0) {
3235 $tickettocreate->contact_id = $contactstatic->id;
3236 if ($contactfoundby) {
3237 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3241 $description = $descriptiontitle;
3247 $descriptionfull = $description;
3249 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3253 $tickettocreate->subject = $subject;
3254 $tickettocreate->message = $description;
3256 $tickettocreate->category_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1)));
3257 $tickettocreate->severity_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE',
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1)));
3258 $tickettocreate->origin_email = $from;
3259 $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto :
null);
3260 $tickettocreate->origin_references = (!empty($headers[
'References']) ? $headers[
'References'] :
null);
3261 $tickettocreate->fk_user_create = $user->id;
3262 $tickettocreate->datec =
dol_now();
3263 $tickettocreate->fk_project = $projectstatic->id;
3264 $tickettocreate->notify_tiers_at_create =
getDolGlobalInt(
'TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3265 $tickettocreate->note_private = $descriptionfull;
3266 $tickettocreate->entity = $conf->entity;
3268 $tickettocreate->email_date = $dateemail;
3269 $tickettocreate->email_msgid = $msgid;
3270 $tickettocreate->email_from = $fromstring;
3271 $tickettocreate->email_sender = $sender;
3272 $tickettocreate->email_to = $to;
3273 $tickettocreate->email_tocc = $sendtocc;
3274 $tickettocreate->email_tobcc = $sendtobcc;
3275 $tickettocreate->email_subject = $subject;
3276 $tickettocreate->errors_to =
'';
3280 $savesocid = $tickettocreate->socid;
3284 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3287 if (empty($tickettocreate->ref)) {
3296 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3297 foreach ($dirmodels as $reldir) {
3298 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3299 if (file_exists($file)) {
3300 $classname = $modele;
3305 if ($classname !==
'') {
3306 if ($savesocid > 0) {
3307 if ($savesocid != $tickettocreate->socid) {
3309 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');
3312 if ($tickettocreate->socid > 0) {
3313 $thirdpartystatic->fetch($tickettocreate->socid);
3318 $modModuleToUseForNextValue =
new $classname();
3319 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3320 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3322 $tickettocreate->ref = $defaultref;
3325 if ($errorforthisaction) {
3328 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3330 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3333 $tickettocreate->context[
'actionmsg2'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3334 $tickettocreate->context[
'actionmsg'] = $langs->trans(
"ActionAC_EMAIL_IN").
' - '.$langs->trans(
"TICKET_CREATEInDolibarr");
3337 $result = $tickettocreate->create($user);
3340 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3341 $this->errors = $tickettocreate->errors;
3344 $destdir = $conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3349 foreach ($attachments as $attachment) {
3351 $typeattachment = (string) $attachment->getDisposition();
3352 $filename = $attachment->getFilename();
3353 $content = $attachment->getContent();
3357 $this->
getmsg($connection, $imapemail, $destdir);
3360 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3362 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3368 } elseif ($operation[
'type'] ==
'candidature') {
3372 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3373 if ($alreadycreated == 0) {
3374 $description = $descriptiontitle;
3380 $descriptionfull = $description;
3381 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3384 $candidaturetocreate->subject = $subject;
3385 $candidaturetocreate->message = $description;
3386 $candidaturetocreate->type_code = 0;
3387 $candidaturetocreate->category_code =
null;
3388 $candidaturetocreate->severity_code =
null;
3389 $candidaturetocreate->email = $from;
3391 $candidaturetocreate->fk_user_creat = $user->id;
3392 $candidaturetocreate->date_creation =
dol_now();
3393 $candidaturetocreate->fk_project = $projectstatic->id;
3394 $candidaturetocreate->description = $description;
3395 $candidaturetocreate->note_private = $descriptionfull;
3396 $candidaturetocreate->entity = $conf->entity;
3397 $candidaturetocreate->email_msgid = $msgid;
3398 $candidaturetocreate->email_date = $dateemail;
3399 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3404 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3446 if ($errorforthisaction) {
3450 $result = $candidaturetocreate->create($user);
3453 $this->error =
'Failed to create candidature: '.implode(
', ', $candidaturetocreate->errors);
3454 $this->errors = $candidaturetocreate->errors;
3457 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag($candidaturetocreate->id);
3460 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3463 if (!is_object($hookmanager)) {
3464 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3466 $hookmanager->initHooks([
'emailcolector']);
3469 $parameters = array(
3470 'connection' => $connection,
3471 'imapemail' => $imapemail,
3472 'overview' => $overview,
3475 'fromtext' => $fromtext,
3477 'actionparam' => $operation[
'actionparam'],
3479 'thirdpartyid' => $thirdpartyid,
3480 'objectid' => $objectid,
3481 'objectemail' => $objectemail,
3483 'messagetext' => $messagetext,
3484 'subject' => $subject,
3485 'header' => $header,
3486 'attachments' => $attachments,
3488 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3491 $errorforthisaction++;
3492 $this->error = $hookmanager->resPrint;
3494 if ($errorforthisaction) {
3496 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3498 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3502 if (!$errorforactions) {
3503 $nbactiondoneforemail++;
3509 if (!$errorforactions) {
3510 if (!empty($targetdir)) {
3513 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3514 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid.
' - '.$imapemail->getHeader()->get(
'subject').
' to '.$targetdir;
3516 $arrayofemailtodelete[$this->
uidAsString($imapemail)] = $imapemail;
3519 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3520 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3522 $arrayofemailtodelete[$imapemail] = $msgid;
3527 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);
3529 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3537 unset($objectemail);
3538 unset($projectstatic);
3539 unset($thirdpartystatic);
3540 unset($contactstatic);
3542 $nbemailprocessed++;
3544 if (!$errorforemail) {
3545 $nbactiondone += $nbactiondoneforemail;
3549 $this->db->commit();
3551 $this->db->rollback();
3555 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3556 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3562 $this->db->rollback();
3566 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3568 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3570 $langs->load(
"admin");
3571 $output = $langs->trans(
'NoNewEmailToProcess');
3572 $output .=
' (defaultlang='.$langs->defaultlang.
')';
3578 krsort($arrayofemailtodelete, SORT_NUMERIC);
3580 foreach ($arrayofemailtodelete as $imapemailnum => $imapemail) {
3581 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemailnum);
3583 $operationslog .=
"<br> move email ".$imapemailnum.($mode> 0 ?
' (test)' :
'');
3585 if (empty($mode) && empty($error)) {
3586 $tmptargetdir = $targetdir;
3593 $result = $imapemail->move($tmptargetdir,
false);
3596 $operationslog .=
'<br>Exception !!!! '.$e->getMessage();
3598 if (empty($result)) {
3599 dol_syslog(
"Failed to move email into target directory ".$targetdir);
3600 $operationslog .=
'<br>Failed to move email into target directory '.$targetdir;
3606 if (empty($mode) && empty($error)) {
3608 $operationslog .=
"<br>Expunge";
3613 $client->disconnect();
3615 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
3616 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
3618 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid.($mode> 0 ?
' (test)' :
'');
3620 if (empty($mode) && empty($error)) {
3621 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
3624 $this->error = imap_last_error();
3625 $this->errors[] = $this->error;
3627 $operationslog .=
'<br>Error in move '.$this->error;
3634 if (empty($mode) && empty($error)) {
3636 $operationslog .=
"<br>Expunge";
3638 imap_expunge($connection);
3640 imap_close($connection);
3643 $this->datelastresult = $now;
3644 $this->lastresult = $output;
3646 $this->debuginfo .=
'IMAP search array used : '.$search;
3648 $this->debuginfo .=
'IMAP search string used : '.$search;
3651 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
3653 if ($operationslog) {
3654 $this->debuginfo .= $operationslog;
3657 if (empty($error) && empty($mode)) {
3658 $this->datelastok = $now;
3661 if (!empty($this->errors)) {
3662 $this->lastresult .=
"<br>".implode(
"<br>", $this->errors);
3664 $this->codelastresult = ($error ?
'KO' :
'OK');
3670 dol_syslog(
"EmailCollector::doCollectOneCollector end", LOG_INFO);
3672 return $error ? -1 : 1;
3687 private function getmsg($mbox, $mid, $destdir =
'')
3691 global $charset, $htmlmsg, $plainmsg, $attachments;
3692 $htmlmsg = $plainmsg = $charset =
'';
3693 $attachments = array();
3700 $s = imap_fetchstructure($mbox, $mid, FT_UID);
3705 $this->
getpart($mbox, $mid, $s, 0);
3708 foreach ($s->parts as $partno0 => $p) {
3709 $this->
getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
3740 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
3743 global $htmlmsg, $plainmsg, $charset, $attachments;
3747 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
3748 imap_body($mbox, $mid, FT_UID);
3750 if ($p->encoding == 4) {
3751 $data = quoted_printable_decode($data);
3752 } elseif ($p->encoding == 3) {
3753 $data = base64_decode($data);
3759 if ($p->parameters) {
3760 foreach ($p->parameters as $x) {
3761 $params[strtolower($x->attribute)] = $x->value;
3764 if (!empty($p->dparameters)) {
3765 foreach ($p->dparameters as $x) {
3766 $params[strtolower($x->attribute)] = $x->value;
3769 '@phan-var-force array{filename?:string,name?:string,charset?:string} $params';
3774 if (!empty($params[
'filename']) || !empty($params[
'name'])) {
3776 $filename = $params[
'filename'] ?? $params[
'name'];
3778 $attachments[$filename] = $data;
3780 if (strlen($destdir)) {
3781 if (substr($destdir, -1) !=
'/') {
3786 $file_name_complete = $filename;
3787 $destination = $destdir.$file_name_complete;
3790 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
3793 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
3796 $file_name_original = $file_name;
3805 while (file_exists($destdir.$file_name.
".".$extension)) {
3806 $file_name = $file_name_original .
' (' . $num .
')';
3807 $file_name_complete = $file_name .
"." . $extension;
3808 $destination = $destdir.$file_name_complete;
3814 file_put_contents($destination, $data);
3819 if ($p->type == 0 && $data) {
3820 if (!empty($params[
'charset'])) {
3825 if (strtolower($p->subtype) ==
'plain') {
3826 $plainmsg .= trim($data).
"\n\n";
3828 $htmlmsg .= $data.
"<br><br>";
3830 $charset = $params[
'charset'];
3831 } elseif ($p->type == 2 && $data) {
3837 if (!empty($params[
'charset'])) {
3840 $plainmsg .= $data.
"\n\n";
3844 if (!empty($p->parts)) {
3845 foreach ($p->parts as $partno0 => $p2) {
3846 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1), $destdir);
3862 if (!$string || $fromEncoding == $toEncoding) {
3865 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
3866 if (!$convertedString && extension_loaded(
'mbstring')) {
3867 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
3869 if (!$convertedString) {
3870 throw new Exception(
'Mime string encoding conversion failed');
3872 return $convertedString;
3891 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
3892 $elements = imap_mime_header_decode($subject);
3894 if (!empty($elements)) {
3895 $num = count($elements);
3896 for ($i = 0; $i < $num; $i++) {
3897 $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));
3898 $newstring .= $stringinutf8;
3900 $subject = $newstring;
3902 } elseif (!function_exists(
'mb_decode_mimeheader')) {
3903 $subject = mb_decode_mimeheader($subject);
3904 } elseif (function_exists(
'iconv_mime_decode')) {
3905 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
3921 require_once DOL_DOCUMENT_ROOT .
'/core/lib/images.lib.php';
3924 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
3925 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
3926 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
3927 $maxheightmini = $tmparraysize[
'maxheightmini'];
3928 $quality = $tmparraysize[
'quality'];
3930 file_put_contents($destdir.
'/'.$filename, $content);
3933 vignette($destdir.
'/'.$filename, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
3935 vignette($destdir.
'/'.$filename, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
3948 if (is_object($imapemail)) {
3949 return $imapemail->getAttributes()[
"uid"];
3951 return (
string) $imapemail;