63 public $element =
'emailcollector';
68 public $table_element =
'emailcollector_emailcollector';
73 public $ismultientitymanaged = 1;
78 public $isextrafieldmanaged = 0;
83 public $picto =
'email';
88 public $fk_element =
'fk_emailcollector';
93 protected $childtables = array();
98 protected $childtablesoncascade = array(
'emailcollector_emailcollectorfilter',
'emailcollector_emailcollectoraction');
124 public $fields = array(
125 'rowid' => array(
'type'=>
'integer',
'label'=>
'TechnicalID',
'visible'=>2,
'enabled'=>1,
'position'=>1,
'notnull'=>1,
'index'=>1),
126 'entity' => array(
'type'=>
'integer',
'label'=>
'Entity',
'enabled'=>1,
'visible'=>0,
'default'=>1,
'notnull'=>1,
'index'=>1,
'position'=>20),
127 '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'),
128 'label' => array(
'type'=>
'varchar(255)',
'label'=>
'Label',
'visible'=>1,
'enabled'=>1,
'position'=>30,
'notnull'=>-1,
'searchall'=>1,
'help'=>
'Example: My Email collector',
'csslist'=>
'tdoverflowmax150'),
129 'description' => array(
'type'=>
'text',
'label'=>
'Description',
'visible'=>-1,
'enabled'=>1,
'position'=>60,
'notnull'=>-1,
'cssview'=>
'small',
'csslist'=>
'small tdoverflowmax200'),
130 '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'),
131 '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'),
132 'hostcharset' => array(
'type'=>
'varchar(16)',
'label'=>
'HostCharset',
'visible'=>-1,
'enabled'=>1,
'position'=>92,
'notnull'=>0,
'searchall'=>0,
'comment'=>
"IMAP server charset",
'help'=>
'Example: "UTF-8" (May be "US-ASCII" with some Office365)',
'default'=>
'UTF-8'),
133 'imap_encryption' => array(
'type'=>
'varchar(16)',
'label'=>
'ImapEncryption',
'visible'=>-1,
'enabled'=>1,
'position'=>93,
'searchall'=>0,
'comment'=>
"IMAP encryption",
'help'=>
'ImapEncryptionHelp',
'arrayofkeyval'=> array(
'ssl'=>
'SSL',
'tls' =>
'TLS',
'notls' =>
'NOTLS'),
'default'=>
'ssl'),
134 '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),
135 'acces_type' => array(
'type'=>
'integer',
'label'=>
'accessType',
'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'=>
''),
136 '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'),
137 'password' => array(
'type'=>
'password',
'label'=>
'Password',
'visible'=>-1,
'enabled'=>
"1",
'position'=>103,
'notnull'=>-1,
'comment'=>
"IMAP password",
'help'=>
'WithGMailYouCanCreateADedicatedPassword'),
138 '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'),
139 'source_directory' => array(
'type'=>
'varchar(255)',
'label'=>
'MailboxSourceDirectory',
'visible'=>-1,
'enabled'=>1,
'position'=>109,
'notnull'=>1,
'default' =>
'Inbox',
'help'=>
'Example: INBOX, [Gmail]/Spam, [Gmail]/Draft, [Gmail]/Brouillons, [Gmail]/Sent Mail, [Gmail]/Messages envoyés, ...'),
140 'target_directory' => array(
'type'=>
'varchar(255)',
'label'=>
'MailboxTargetDirectory',
'visible'=>1,
'enabled'=>1,
'position'=>110,
'notnull'=>0,
'help'=>
"EmailCollectorTargetDir"),
141 'maxemailpercollect' => array(
'type'=>
'integer',
'label'=>
'MaxEmailCollectPerCollect',
'visible'=>-1,
'enabled'=>1,
'position'=>111,
'default'=>50),
142 'datelastresult' => array(
'type'=>
'datetime',
'label'=>
'DateLastCollectResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>121,
'notnull'=>-1,
'csslist'=>
'nowraponall'),
143 'codelastresult' => array(
'type'=>
'varchar(16)',
'label'=>
'CodeLastResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>122,
'notnull'=>-1,),
144 'lastresult' => array(
'type'=>
'varchar(255)',
'label'=>
'LastResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>123,
'notnull'=>-1,
'cssview'=>
'small',
'csslist'=>
'small tdoverflowmax200'),
145 'datelastok' => array(
'type'=>
'datetime',
'label'=>
'DateLastcollectResultOk',
'visible'=>1,
'enabled'=>
'$action != "create"',
'position'=>125,
'notnull'=>-1,
'csslist'=>
'nowraponall'),
146 'note_public' => array(
'type'=>
'html',
'label'=>
'NotePublic',
'visible'=>0,
'enabled'=>1,
'position'=>61,
'notnull'=>-1,),
147 'note_private' => array(
'type'=>
'html',
'label'=>
'NotePrivate',
'visible'=>0,
'enabled'=>1,
'position'=>62,
'notnull'=>-1,),
148 'date_creation' => array(
'type'=>
'datetime',
'label'=>
'DateCreation',
'visible'=>-2,
'enabled'=>1,
'position'=>500,
'notnull'=>1,),
149 'tms' => array(
'type'=>
'timestamp',
'label'=>
'DateModification',
'visible'=>-2,
'enabled'=>1,
'position'=>501,
'notnull'=>1,),
151 'fk_user_creat' => array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserAuthor',
'visible'=>-2,
'enabled'=>1,
'position'=>510,
'notnull'=>1,),
152 'fk_user_modif' => array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserModif',
'visible'=>-2,
'enabled'=>1,
'position'=>511,
'notnull'=>-1,),
154 'import_key' => array(
'type'=>
'varchar(14)',
'label'=>
'ImportId',
'visible'=>-2,
'enabled'=>1,
'position'=>1000,
'notnull'=>-1,),
155 'status' => array(
'type'=>
'integer',
'label'=>
'Status',
'visible'=>1,
'enabled'=>1,
'position'=>1000,
'notnull'=>1,
'default'=>
'0',
'index'=>1,
'arrayofkeyval'=>array(
'0'=>
'Inactive',
'1'=>
'Active'))
188 public $date_creation;
198 public $fk_user_creat;
203 public $fk_user_modif;
216 public $oauth_service;
217 public $imap_encryption;
219 public $source_directory;
220 public $target_directory;
221 public $maxemailpercollect;
226 public $datelastresult;
228 public $codelastresult;
238 const STATUS_DISABLED = 0;
239 const STATUS_ENABLED = 1;
249 global $conf, $langs;
254 $this->fields[
'rowid'][
'visible'] = 0;
256 if (!isModEnabled(
'multicompany') && isset($this->fields[
'entity'])) {
257 $this->fields[
'entity'][
'enabled'] = 0;
261 $oauthservices = array();
263 foreach ($conf->global as $key => $val) {
264 if (!empty($val) && preg_match(
'/^OAUTH_.*_ID$/', $key)) {
265 $key = preg_replace(
'/^OAUTH_/',
'', $key);
266 $key = preg_replace(
'/_ID$/',
'', $key);
267 if (preg_match(
'/^.*-/', $key)) {
268 $name = preg_replace(
'/^.*-/',
'', $key);
270 $name = $langs->trans(
"NoName");
272 $provider = preg_replace(
'/-.*$/',
'', $key);
273 $provider = ucfirst(strtolower($provider));
275 $oauthservices[$key] = $name.
" (".$provider.
")";
279 $this->fields[
'oauth_service'][
'arrayofkeyval'] = $oauthservices;
282 foreach ($this->fields as $key => $val) {
283 if (isset($val[
'enabled']) && empty($val[
'enabled'])) {
284 unset($this->fields[$key]);
289 foreach ($this->fields as $key => $val) {
290 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
291 foreach ($val[
'arrayofkeyval'] as $key2 => $val2) {
292 $this->fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
310 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
311 $langs->load(
"errors");
312 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
316 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
317 $this->password =
dolEncrypt($this->password);
321 $this->password =
dolDecrypt($this->password);
323 if (is_array($this->filters) && count($this->filters)) {
326 foreach ($this->filters as $filter) {
327 $emailcollectorfilter->type = $filter[
'type'];
328 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
329 $emailcollectorfilter->fk_emailcollector = $this->id;
330 $emailcollectorfilter->status = $filter[
'status'];
332 $emailcollectorfilter->create($user);
336 if (is_array($this->actions) && count($this->actions)) {
339 foreach ($this->actions as $operation) {
340 $emailcollectoroperation->type = $operation[
'type'];
341 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
342 $emailcollectoroperation->fk_emailcollector = $this->id;
343 $emailcollectoroperation->status = $operation[
'status'];
344 $emailcollectoroperation->position = $operation[
'position'];
346 $emailcollectoroperation->create($user);
362 global $langs, $extrafields;
367 $object =
new self($this->db);
372 $object->fetchCommon($fromid);
374 $object->fetchFilters();
375 $object->fetchActions();
379 unset($object->fk_user_creat);
380 unset($object->import_key);
381 unset($object->password);
382 unset($object->lastresult);
383 unset($object->codelastresult);
384 unset($object->datelastresult);
385 unset($object->datelastok);
386 unset($object->debuginfo);
389 $object->ref =
"copy_of_".$object->ref;
390 $object->label = $langs->trans(
"CopyOf").
" ".$object->label;
391 if (empty($object->host)) {
392 $object->host =
'imap.example.com';
395 if (is_array($object->array_options) && count($object->array_options) > 0) {
396 $extrafields->fetch_name_optionals_label($this->table_element);
397 foreach ($object->array_options as $key => $option) {
398 $shortkey = preg_replace(
'/options_/',
'', $key);
399 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
401 unset($object->array_options[$key]);
407 $object->context[
'createfromclone'] =
'createfromclone';
408 $result = $object->create($user);
411 $this->error = $object->error;
412 $this->errors = $object->errors;
415 unset($object->context[
'createfromclone']);
422 $this->db->rollback();
434 public function fetch($id, $ref =
null)
438 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
439 $this->password =
dolDecrypt($this->password);
472 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
478 $sql =
"SELECT s.rowid";
479 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
480 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
482 $sql .=
" AND s.status = 1";
484 $sql .= $this->db->order($sortfield, $sortorder);
489 $offset = $limit * $page;
491 $sql .= $this->db->plimit($limit + 1, $offset);
494 $result = $this->db->query($sql);
496 $num = $this->db->num_rows($result);
499 $obj = $this->db->fetch_object($result);
501 if ($emailcollector_static->fetch($obj->rowid)) {
502 $obj_ret[] = $emailcollector_static;
507 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
508 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
511 if (!count($obj_ret)) {
512 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
530 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
531 $langs->load(
"errors");
532 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
536 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
537 $this->password =
dolEncrypt($this->password);
541 $this->password =
dolDecrypt($this->password);
553 public function delete(
User $user, $notrigger =
false)
568 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
570 global $conf, $langs, $action, $hookmanager;
572 if (!empty($conf->dol_no_mouse_hover)) {
578 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
580 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
582 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
584 if ($option !=
'nolink') {
586 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
587 if ($save_lastsearch_value == -1 && isset($_SERVER[
"PHP_SELF"]) && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
588 $add_save_lastsearch_values = 1;
590 if ($add_save_lastsearch_values) {
591 $url .=
'&save_lastsearch_values=1';
596 if (empty($notooltip)) {
598 $label = $langs->trans(
"ShowEmailCollector");
599 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
601 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
602 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
604 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
607 $linkstart =
'<a href="'.$url.
'"';
608 $linkstart .= $linkclose.
'>';
611 $result .= $linkstart;
613 $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);
615 if ($withpicto != 2) {
616 $result .= $this->ref;
621 $hookmanager->initHooks(array(
'emailcollectordao'));
622 $parameters = array(
'id'=>$this->
id,
'getnomurl' => &$result);
623 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
625 $result = $hookmanager->resPrint;
627 $result .= $hookmanager->resPrint;
655 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
658 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
659 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
660 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
661 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
664 $statusType =
'status5';
665 if ($status == self::STATUS_ENABLED) {
666 $statusType =
'status4';
669 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
680 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
681 $sql .=
' fk_user_creat, fk_user_modif';
682 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
683 $sql .=
' WHERE t.rowid = '.((int) $id);
684 $result = $this->db->query($sql);
686 if ($this->db->num_rows($result)) {
687 $obj = $this->db->fetch_object($result);
689 $this->
id = $obj->rowid;
691 $this->user_creation_id = $obj->fk_user_creat;
692 $this->user_modification_id = $obj->fk_user_modif;
693 $this->date_creation = $this->db->jdate($obj->datec);
694 $this->date_modification = empty($obj->datem) ?
'' : $this->db->jdate($obj->datem);
697 $this->db->free($result);
711 $this->host =
'localhost';
712 $this->login =
'alogin';
725 $this->filters = array();
727 $sql =
'SELECT rowid, type, rulevalue, status';
728 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
729 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
732 $resql = $this->db->query($sql);
734 $num = $this->db->num_rows($resql);
737 $obj = $this->db->fetch_object($resql);
738 $this->filters[$obj->rowid] = array(
'id'=>$obj->rowid,
'type'=>$obj->type,
'rulevalue'=>$obj->rulevalue,
'status'=>$obj->status);
741 $this->db->free($resql);
757 $this->actions = array();
759 $sql =
'SELECT rowid, type, actionparam, status';
760 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
761 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
762 $sql .=
' ORDER BY position';
764 $resql = $this->db->query($sql);
766 $num = $this->db->num_rows($resql);
769 $obj = $this->db->fetch_object($resql);
770 $this->actions[$obj->rowid] = array(
'id'=>$obj->rowid,
'type'=>$obj->type,
'actionparam'=>$obj->actionparam,
'status'=>$obj->status);
773 $this->db->free($resql);
794 $flags =
'/service=imap';
797 } elseif (empty($this->imap_encryption) || ($this->imap_encryption ==
'ssl' &&
getDolGlobalString(
'IMAP_FORCE_NOSSL'))) {
800 $flags .=
'/' . $this->imap_encryption;
803 $flags .=
'/novalidate-cert';
810 if (strpos($this->login,
'/') !=
false) {
811 $partofauth = explode(
'/', $this->login);
812 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
815 $connectstringserver =
'{'.$this->host.
':'.$this->port.$flags.
'}';
817 return $connectstringserver;
828 if (function_exists(
'mb_convert_encoding')) {
830 $str = preg_replace(
"/ /",
"xxxSPACExxx", $str);
831 $str = preg_replace(
"/\[Gmail\]/",
"xxxGMAILxxx", $str);
833 if ($str = mb_convert_encoding($str,
"UTF-7")) {
835 $str = preg_replace(
"/\+A/",
"&A", $str);
837 $str = preg_replace(
"/xxxSPACExxx/",
" ", $str);
839 $str = preg_replace(
"/xxxGMAILxxx/",
"[Gmail]", $str);
843 $this->error =
"error: is not possible to encode this string '".$str.
"'";
863 $arrayofcollectors = $this->
fetchAll($user, 1);
866 foreach ($arrayofcollectors as $emailcollector) {
867 $result = $emailcollector->doCollectOneCollector(0);
868 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
870 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
871 if (!empty($emailcollector->errors)) {
872 $this->error .= join(
'<br>', $emailcollector->errors);
874 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
893 global $conf, $langs;
895 $errorforthisaction = 0;
898 $outputlangs = $langs;
901 $newlang =
GETPOST(
'lang_id',
'aZ09');
904 $newlang = $object->thirdparty->default_lang;
906 if (!empty($newlang)) {
908 $outputlangs->setDefaultLang($newlang);
918 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
921 $tmparray = explode(
'.', $propertytooverwrite);
922 if (count($tmparray) == 2) {
923 $tmpclass = $tmparray[0];
924 $tmpproperty = $tmparray[1];
926 $tmpproperty = $tmparray[0];
928 if ($tmpclass && ($tmpclass != $object->element)) {
938 $regforregex = array();
939 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
940 $sourcefield = $regforregex[1];
941 $regexstring = $regforregex[2];
943 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
944 $sourcefield = $regforregex[1];
945 $regexstring = $regforregex[2];
948 if (!empty($sourcefield) && !empty($regexstring)) {
949 if (strtolower($sourcefield) ==
'body') {
950 $sourcestring = $messagetext;
951 } elseif (strtolower($sourcefield) ==
'subject') {
952 $sourcestring = $subject;
953 } elseif (strtolower($sourcefield) ==
'header') {
954 $sourcestring = $header;
958 $regforval = array();
960 if (strtolower($sourcefield) ==
'body') {
961 $regexoptions =
'ms';
963 if (strtolower($sourcefield) ==
'header') {
968 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
970 $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
971 if (strtolower($sourcefield) ==
'header') {
972 if (preg_match(
'/^options_/', $tmpproperty)) {
973 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $this->
decodeSMTPSubject($valueextracted);
975 if (property_exists($object, $tmpproperty)) {
982 if (preg_match(
'/^options_/', $tmpproperty)) {
983 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $this->
decodeSMTPSubject($valueextracted);
985 if (property_exists($object, $tmpproperty)) {
992 if (preg_match(
'/^options_/', $tmpproperty)) {
993 $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));
995 if (property_exists($object, $tmpproperty)) {
1003 if (property_exists($object, $tmpproperty)) {
1004 $object->$tmpproperty =
null;
1006 $tmp[$tmpproperty] =
null;
1009 $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.';
1013 $errorforthisaction++;
1014 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1015 $this->errors[] = $this->error;
1017 $operationslog .=
'<br>'.$this->error;
1019 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1021 if (preg_match(
'/^options_/', $tmpproperty)) {
1022 $valuecurrent = $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1024 if (property_exists($object, $tmpproperty)) {
1025 $valuecurrent = $object->$tmpproperty;
1027 $valuecurrent = $tmp[$tmpproperty];
1031 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1032 $valuetouse = $regforregex[2];
1035 $matcharray = array();
1036 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1038 if (is_array($matcharray[1])) {
1039 foreach ($matcharray[1] as $keytoreplace) {
1040 if ($keytoreplace) {
1041 if (preg_match(
'/^options_/', $keytoreplace)) {
1042 $substitutionarray[
'__'.$keytoreplace.
'__'] = $object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1044 if (property_exists($object, $keytoreplace)) {
1045 $substitutionarray[
'__'.$keytoreplace.
'__'] = $object->$keytoreplace;
1047 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1057 if (preg_match(
'/^options_/', $tmpproperty)) {
1058 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1060 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1062 if (property_exists($object, $tmpproperty)) {
1063 $object->$tmpproperty = $valuetouse;
1065 $tmp[$tmpproperty] = $valuetouse;
1068 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1072 $errorforthisaction++;
1073 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1074 $this->errors[] = $this->error;
1079 return $errorforthisaction;
1088 public function doCollectOneCollector($mode = 0)
1090 global $db, $conf, $langs, $user;
1091 global $hookmanager;
1095 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1097 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1100 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1102 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1107 $this->debuginfo =
'';
1111 $searchfilterdoltrackid = 0;
1112 $searchfilternodoltrackid = 0;
1113 $searchfilterisanswer = 0;
1114 $searchfilterisnotanswer = 0;
1115 $searchfilterreplyto = 0;
1116 $searchfilterexcludebodyarray = array();
1117 $searchfilterexcludesubjectarray = array();
1118 $operationslog =
'';
1122 if (empty($this->host)) {
1123 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1126 if (empty($this->login)) {
1127 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1130 if (empty($this->source_directory)) {
1131 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1135 $sourcedir = $this->source_directory;
1136 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1141 $sourcedir = $this->source_directory;
1142 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1145 if ($this->acces_type == 1) {
1147 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>';
1149 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1153 $keyforsupportedoauth2array = $this->oauth_service;
1154 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1155 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1157 $keyforprovider =
'';
1159 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1160 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1162 $OAUTH_SERVICENAME =
'Unknown';
1163 if (array_key_exists($keyforsupportedoauth2array, $supportedoauth2array)
1164 && array_key_exists(
'name', $supportedoauth2array[$keyforsupportedoauth2array])
1165 && !empty($supportedoauth2array[$keyforsupportedoauth2array][
'name'])) {
1166 $OAUTH_SERVICENAME = $supportedoauth2array[$keyforsupportedoauth2array][
'name'].(!empty($keyforprovider) ?
'-'.$keyforprovider :
'');
1169 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1175 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1178 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1186 if (is_object($tokenobj) && $expire) {
1187 $credentials =
new Credentials(
1192 $serviceFactory = new \OAuth\ServiceFactory();
1193 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1195 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1197 $refreshtoken = $tokenobj->getRefreshToken();
1198 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1199 $tokenobj->setRefreshToken($refreshtoken);
1200 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1202 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1203 if (is_object($tokenobj)) {
1204 $token = $tokenobj->getAccessToken();
1206 $this->error =
"Token not found";
1211 $this->error = $e->getMessage();
1212 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1216 $cm =
new ClientManager();
1217 $client = $cm->make([
1218 'host' => $this->host,
1219 'port' => $this->port,
1220 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1221 'validate_cert' => true,
1222 'protocol' =>
'imap',
1223 'username' => $this->login,
1224 'password' => $token,
1225 'authentication' =>
"oauth",
1229 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1231 $cm =
new ClientManager();
1232 $client = $cm->make([
1233 'host' => $this->host,
1234 'port' => $this->port,
1235 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1236 'validate_cert' => true,
1237 'protocol' =>
'imap',
1238 'username' => $this->login,
1239 'password' => $this->password,
1240 'authentication' =>
"login",
1246 }
catch (ConnectionFailedException $e) {
1247 $this->error = $e->getMessage();
1248 $this->errors[] = $this->error;
1249 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1253 $host = dol_getprefix(
'email');
1256 $this->debuginfo .=
'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1258 if (!function_exists(
'imap_open')) {
1259 $this->error =
'IMAP function not enabled on your PHP';
1264 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1265 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1267 $this->debuginfo .=
'connectstringsource = '.$connectstringsource.
', $connectstringtarget='.$connectstringtarget.
'<br>';
1269 $connection = imap_open($connectstringsource, $this->login, $this->password);
1271 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1276 $host = dol_getprefix(
'email');
1287 $criteria = array(array(
'UNDELETED'));
1288 foreach ($this->filters as $rule) {
1289 if (empty($rule[
'status'])) {
1294 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1298 $rule[
'rulevalue'] = substr($rule[
'rulevalue'], 1);
1301 if ($rule[
'type'] ==
'from') {
1302 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1303 if (count($tmprulevaluearray) >= 2) {
1304 foreach ($tmprulevaluearray as $tmprulevalue) {
1305 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1308 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1311 if ($rule[
'type'] ==
'to') {
1312 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1313 if (count($tmprulevaluearray) >= 2) {
1314 foreach ($tmprulevaluearray as $tmprulevalue) {
1315 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1318 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1321 if ($rule[
'type'] ==
'bcc') {
1322 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1324 if ($rule[
'type'] ==
'cc') {
1325 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1327 if ($rule[
'type'] ==
'subject') {
1328 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1330 $searchfilterexcludesubjectarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1332 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1335 if ($rule[
'type'] ==
'body') {
1336 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1338 $searchfilterexcludebodyarray[] = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1340 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1343 if ($rule[
'type'] ==
'header') {
1344 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1356 if ($rule[
'type'] ==
'seen') {
1357 array_push($criteria, array($not.
"SEEN"));
1359 if ($rule[
'type'] ==
'unseen') {
1360 array_push($criteria, array($not.
"UNSEEN"));
1362 if ($rule[
'type'] ==
'unanswered') {
1363 array_push($criteria, array($not.
"UNANSWERED"));
1365 if ($rule[
'type'] ==
'answered') {
1366 array_push($criteria, array($not.
"ANSWERED"));
1368 if ($rule[
'type'] ==
'smaller') {
1369 array_push($criteria, array($not.
"SMALLER"));
1371 if ($rule[
'type'] ==
'larger') {
1372 array_push($criteria, array($not.
"LARGER"));
1376 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1377 $searchfilterdoltrackid++;
1378 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1380 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1381 $searchfilterdoltrackid++;
1382 $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1384 if ($rule[
'type'] ==
'withtrackingid') {
1385 $searchfilterdoltrackid++;
1386 $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1388 if ($rule[
'type'] ==
'withouttrackingid') {
1389 $searchfilternodoltrackid++;
1390 $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1393 if ($rule[
'type'] ==
'isanswer') {
1394 $searchfilterisanswer++;
1395 $searchhead .=
'/References.*@.*/';
1397 if ($rule[
'type'] ==
'isnotanswer') {
1398 $searchfilterisnotanswer++;
1399 $searchhead .=
'! /References.*@.*/';
1402 if ($rule[
'type'] ==
'replyto') {
1403 $searchfilterreplyto++;
1404 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1408 if (empty($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 (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 $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1549 if (empty($targetdir)) {
1551 if ($this->datelastok) {
1552 $fromdate = $this->datelastok;
1554 if ($fromdate > 0) {
1555 $search .= ($search ?
' ' :
'').
'SINCE '.date(
'j-M-Y', $fromdate - 1);
1564 $nbemailprocessed = 0;
1567 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1573 $f = $client->getFolders(
false, $sourcedir);
1574 $Query = $f[0]->messages()->where($criteria);
1575 }
catch (InvalidWhereQueryCriteriaException $e) {
1576 $this->error = $e->getMessage();
1577 $this->errors[] = $this->error;
1578 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1581 $this->error = $e->getMessage();
1582 $this->errors[] = $this->error;
1583 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1590 $Query->leaveUnread();
1592 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1595 $this->error = $e->getMessage();
1596 $this->errors[] = $this->error;
1597 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1602 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1604 if ($arrayofemail ===
false) {
1606 $mapoferrrors = imap_errors();
1607 if ($mapoferrrors !==
false) {
1609 $this->error =
"Search string not understood - ".join(
',', $mapoferrrors);
1610 $this->errors[] = $this->error;
1615 $arrayofemailtodelete = array();
1618 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
1635 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1638 foreach ($arrayofemail as $imapemail) {
1639 if ($nbemailprocessed > 1000) {
1647 $header = $imapemail->getHeader()->raw;
1648 $overview = $imapemail->getAttributes();
1650 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1651 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1654 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1657 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches);
1658 $headers = array_combine($matches[1], $matches[2]);
1661 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1662 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1664 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1665 $headers[
'References'] = $headers[
'references'];
1667 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1668 $headers[
'Message-ID'] = $headers[
'message-id'];
1670 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1671 $headers[
'Subject'] = $headers[
'subject'];
1678 $operationslog .=
'<br>** Process email #'.dol_escape_htmltag($iforemailloop);
1683 $operationslog .=
" - ".dol_escape_htmltag((
string) $imapemail);
1685 $operationslog .=
" - References: ".dol_escape_htmltag($headers[
'References']??
'').
" - Subject: ".
dol_escape_htmltag($headers[
'Subject']);
1687 dol_syslog(
"** Process email ".$iforemailloop.
" References: ".($headers[
'References']??
'').
" Subject: ".$headers[
'Subject']);
1690 $trackidfoundintorecipienttype =
'';
1691 $trackidfoundintorecipientid = 0;
1694 if (preg_match(
'/\+(thi|ctc|use|mem|sub|proj|tas|con|tic|pro|ord|inv|spro|sor|sin|leav|stockinv|job|surv|salary)([0-9]+)@/', $emailto, $reg)) {
1695 $trackidfoundintorecipienttype = $reg[1];
1696 $trackidfoundintorecipientid = $reg[2];
1697 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1698 $trackidfoundintorecipienttype =
'emailing';
1699 $trackidfoundintorecipientid = $reg[1];
1703 if ($searchfilterdoltrackid > 0) {
1704 if (empty($trackidfoundintorecipienttype)) {
1705 if (empty($headers[
'References']) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References'])) {
1706 $nbemailprocessed++;
1707 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");
1712 if ($searchfilternodoltrackid > 0) {
1713 if (!empty($trackidfoundintorecipienttype) || (!empty($headers[
'References']) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))) {
1714 $nbemailprocessed++;
1715 dol_syslog(
" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
1720 if ($searchfilterisanswer > 0) {
1721 if (empty($headers[
'In-Reply-To'])) {
1722 $nbemailprocessed++;
1723 dol_syslog(
" Discarded - Email is not an answer (no In-Reply-To header)");
1727 if (preg_match(
'/^(Re|AW)\s*:\s+/i', $headers[
'Subject'])) {
1730 if (getDolglobalString(
'EMAILCOLLECTOR_USE_IN_REPLY_TO_TO_DETECT_ANSWERS')) {
1733 if (!empty($headers[
'In-Reply-To'])) {
1741 $nbemailprocessed++;
1742 dol_syslog(
" Discarded - Email is not an answer (no RE prefix in subject)");
1746 if ($searchfilterisnotanswer > 0) {
1747 if (!empty($headers[
'In-Reply-To'])) {
1751 if (preg_match(
'/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers[
'Subject'])) {
1757 $nbemailprocessed++;
1758 dol_syslog(
" Discarded - Email is an answer");
1766 $thirdpartystatic =
new Societe($this->db);
1767 $contactstatic =
new Contact($this->db);
1768 $projectstatic =
new Project($this->db);
1770 $nbactiondoneforemail = 0;
1772 $errorforactions = 0;
1773 $thirdpartyfoundby =
'';
1774 $contactfoundby =
'';
1775 $projectfoundby =
'';
1776 $ticketfoundby =
'';
1777 $candidaturefoundby =
'';
1781 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".
dol_print_date($overview[
'date'],
'dayrfc',
'gmt').
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
1784 $overview[
'subject'] = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $overview[
'subject']);
1786 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);
1793 $overview[0]->subject = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $overview[0]->subject);
1796 global $htmlmsg, $plainmsg, $charset, $attachments;
1800 if ($imapemail->hasHTMLBody()) {
1801 $htmlmsg = $imapemail->getHTMLBody();
1803 if ($imapemail->hasTextBody() && $imapemail->getTextBody() !=
"\n") {
1804 $plainmsg = $imapemail->getTextBody();
1806 if ($imapemail->hasAttachments()) {
1807 $attachments = $imapemail->getAttachments()->all();
1812 $this->
getmsg($connection, $imapemail);
1825 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
1826 dol_syslog(
" Discarded - Email body is not valid utf8");
1830 if (!empty($searchfilterexcludebodyarray)) {
1831 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
1832 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
1833 $nbemailprocessed++;
1834 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
1835 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
1897 $replytostring =
'';
1900 $fromstring = $overview[
'from'];
1903 $sender = $overview[
'sender'];
1904 $to = $overview[
'to'];
1905 $sendtocc = empty($overview[
'cc']) ?
'' : $overview[
'cc'];
1906 $sendtobcc = empty($overview[
'bcc']) ?
'' : $overview[
'bcc'];
1907 $date = $overview[
'date'];
1908 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1909 $subject = $overview[
'subject'];
1911 $fromstring = $overview[0]->from;
1914 $sender = $overview[0]->sender;
1915 $to = $overview[0]->to;
1916 $sendtocc = $overview[0]->cc;
1917 $sendtobcc = $overview[0]->bcc;
1918 $date = $overview[0]->udate;
1919 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1920 $subject = $overview[0]->subject;
1924 if (!empty($searchfilterexcludesubjectarray)) {
1925 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
1926 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
1927 $nbemailprocessed++;
1928 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
1929 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
1936 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
1938 $fromtext = $reg[1];
1940 $from = $fromstring;
1943 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
1945 $replytotext = $reg[1];
1947 $replyto = $replytostring;
1951 $fk_element_type =
'';
1966 $objectemail =
null;
1969 if (!empty($headers[
'References'])) {
1970 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
1974 foreach ($arrayofreferences as $reference) {
1976 if (!empty($trackidfoundintorecipienttype)) {
1977 $resultsearchtrackid = -1;
1978 $reg[1] = $trackidfoundintorecipienttype;
1979 $reg[2] = $trackidfoundintorecipientid;
1981 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
1982 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
1983 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
1987 if (!empty($resultsearchtrackid)) {
1989 $trackid = $reg[1].$reg[2];
1991 $objectid = $reg[2];
1993 if ($reg[1] ==
'thi') {
1994 $objectemail =
new Societe($this->db);
1996 if ($reg[1] ==
'ctc') {
1997 $objectemail =
new Contact($this->db);
1999 if ($reg[1] ==
'inv') {
2000 $objectemail =
new Facture($this->db);
2002 if ($reg[1] ==
'sinv') {
2005 if ($reg[1] ==
'pro') {
2006 $objectemail =
new Propal($this->db);
2008 if ($reg[1] ==
'ord') {
2009 $objectemail =
new Commande($this->db);
2011 if ($reg[1] ==
'shi') {
2014 if ($reg[1] ==
'spro') {
2017 if ($reg[1] ==
'sord') {
2020 if ($reg[1] ==
'rec') {
2021 $objectemail =
new Reception($this->db);
2023 if ($reg[1] ==
'proj') {
2024 $objectemail =
new Project($this->db);
2026 if ($reg[1] ==
'tas') {
2027 $objectemail =
new Task($this->db);
2029 if ($reg[1] ==
'con') {
2030 $objectemail =
new Contact($this->db);
2032 if ($reg[1] ==
'use') {
2033 $objectemail =
new User($this->db);
2035 if ($reg[1] ==
'tic') {
2036 $objectemail =
new Ticket($this->db);
2038 if ($reg[1] ==
'recruitmentcandidature') {
2041 if ($reg[1] ==
'mem') {
2042 $objectemail =
new Adherent($this->db);
2050 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
2052 if (!is_object($objectemail) && isModEnabled(
'ticket')) {
2053 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket where email_msgid = '".$this->db->escape($reg[1]).
"'";
2054 $resql = $this->db->query($sql);
2056 $obj = $this->db->fetch_object($resql);
2058 $objectid = $obj->rowid;
2059 $objectemail =
new Ticket($this->db);
2060 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2067 if (!is_object($objectemail) && isModEnabled(
'project')) {
2068 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2069 $resql = $this->db->query($sql);
2071 $obj = $this->db->fetch_object($resql);
2073 $objectid = $obj->rowid;
2074 $objectemail =
new Project($this->db);
2075 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2082 if (!is_object($objectemail) && isModEnabled(
'recruitment')) {
2083 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2084 $resql = $this->db->query($sql);
2086 $obj = $this->db->fetch_object($resql);
2088 $objectid = $obj->rowid;
2090 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2099 if (is_object($objectemail)) {
2100 $result = $objectemail->fetch($objectid);
2102 $fk_element_id = $objectemail->id;
2103 $fk_element_type = $objectemail->element;
2105 if ($fk_element_type ==
'facture') {
2106 $fk_element_type =
'invoice';
2109 if (get_class($objectemail) !=
'Societe') {
2110 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2112 $thirdpartyid = $objectemail->id;
2115 if (get_class($objectemail) !=
'Contact') {
2116 $contactid = $objectemail->fk_socpeople;
2118 $contactid = $objectemail->id;
2121 if (get_class($objectemail) !=
'Project') {
2122 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2124 $projectid = $objectemail->id;
2130 if ($projectid > 0) {
2131 $result = $projectstatic->fetch($projectid);
2133 $projectstatic->id = 0;
2135 $projectid = $projectstatic->id;
2137 $projectfoundby =
'trackid ('.$trackid.
')';
2139 if (empty($contactid)) {
2140 $contactid = $projectstatic->fk_contact;
2142 if (empty($thirdpartyid)) {
2143 $thirdpartyid = $projectstatic->fk_soc;
2148 if ($contactid > 0) {
2149 $result = $contactstatic->fetch($contactid);
2151 $contactstatic->id = 0;
2153 $contactid = $contactstatic->id;
2155 $contactfoundby =
'trackid ('.$trackid.
')';
2157 if (empty($thirdpartyid)) {
2158 $thirdpartyid = $contactstatic->fk_soc;
2163 if ($thirdpartyid > 0) {
2164 $result = $thirdpartystatic->fetch($thirdpartyid);
2166 $thirdpartystatic->id = 0;
2168 $thirdpartyid = $thirdpartystatic->id;
2170 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2175 if (is_object($objectemail)) {
2181 if (empty($contactid)) {
2182 $result = $contactstatic->fetch(0,
null,
'', $from);
2185 dol_syslog(
"We found a contact with the email ".$from);
2186 $contactid = $contactstatic->id;
2187 $contactfoundby =
'email of contact ('.$from.
')';
2188 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2189 $result = $thirdpartystatic->fetch($contactstatic->socid);
2191 $thirdpartyid = $thirdpartystatic->id;
2192 $thirdpartyfoundby =
'email of contact ('.$from.
')';
2198 if (empty($thirdpartyid)) {
2199 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
2201 dol_syslog(
"We found a thirdparty with the email ".$from);
2202 $thirdpartyid = $thirdpartystatic->id;
2203 $thirdpartyfoundby =
'email ('.$from.
')';
2239 foreach ($this->actions as $operation) {
2240 $errorforthisaction = 0;
2242 if ($errorforactions) {
2245 if (empty($operation[
'status'])) {
2249 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2252 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2253 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2255 $actioncode =
'EMAIL_IN';
2257 if (preg_match(
'/Sent$/', $sourcedir)) {
2258 $actioncode =
'EMAIL_OUT';
2261 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2263 $descriptiontitle = $langs->trans(
"RecordCreatedByEmailCollector", $this->
ref, $msgid);
2266 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2268 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2270 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2272 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2276 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2277 if (empty($operation[
'actionparam'])) {
2279 $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;";
2280 $this->errors[] = $this->error;
2282 $actionparam = $operation[
'actionparam'];
2283 $idtouseforthirdparty =
'';
2284 $nametouseforthirdparty =
'';
2285 $emailtouseforthirdparty =
'';
2286 $namealiastouseforthirdparty =
'';
2288 $operationslog .=
'<br>Loop on each property to set into actionparam';
2292 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2296 $regforregex = array();
2298 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2299 $sourcefield = $regforregex[1];
2300 $regexstring = $regforregex[2];
2303 if (!empty($sourcefield) && !empty($regexstring)) {
2304 if (strtolower($sourcefield) ==
'body') {
2305 $sourcestring = $messagetext;
2306 } elseif (strtolower($sourcefield) ==
'subject') {
2307 $sourcestring = $subject;
2308 } elseif (strtolower($sourcefield) ==
'header') {
2309 $sourcestring = $header;
2312 if ($sourcestring) {
2313 $regforval = array();
2315 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2318 if ($propertytooverwrite ==
'id') {
2319 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2321 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2322 } elseif ($propertytooverwrite ==
'email') {
2323 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2325 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2326 } elseif ($propertytooverwrite ==
'name') {
2327 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2329 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2330 } elseif ($propertytooverwrite ==
'name_alias') {
2331 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2333 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2335 $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';
2339 if (in_array($propertytooverwrite, array(
'id',
'email',
'name',
'name_alias'))) {
2340 $idtouseforthirdparty =
null;
2341 $nametouseforthirdparty =
null;
2342 $emailtouseforthirdparty =
null;
2343 $namealiastouseforthirdparty =
null;
2345 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found. Property searched is critical so we cancel the search.';
2347 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2354 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2355 $this->errors[] = $this->error;
2357 $operationslog .=
'<br>'.$this->error;
2359 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2363 if ($propertytooverwrite ==
'id') {
2364 $idtouseforthirdparty = $reg[2];
2366 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2367 } elseif ($propertytooverwrite ==
'email') {
2368 $emailtouseforthirdparty = $reg[2];
2370 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2371 } elseif ($propertytooverwrite ==
'name') {
2372 $nametouseforthirdparty = $reg[2];
2374 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2375 } elseif ($propertytooverwrite ==
'name_alias') {
2376 $namealiastouseforthirdparty = $reg[2];
2378 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2382 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2383 $this->errors[] = $this->error;
2388 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2390 $operationslog .=
'<br>We have this data to search thirdparty: id='.$idtouseforthirdparty.
', email='.$emailtouseforthirdparty.
', name='.$nametouseforthirdparty.
', name_alias='.$namealiastouseforthirdparty;
2393 $tmpobject->element ==
'generic';
2394 $tmpobject->id = $idtouseforthirdparty;
2395 $tmpobject->name = $nametouseforthirdparty;
2396 $tmpobject->name_alias = $namealiastouseforthirdparty;
2397 $tmpobject->email = $emailtouseforthirdparty;
2401 $idtouseforthirdparty = $tmpobject->id;
2402 $nametouseforthirdparty = $tmpobject->name;
2403 $namealiastouseforthirdparty = $tmpobject->name_alias;
2404 $emailtouseforthirdparty = $tmpobject->email;
2406 $operationslog .=
'<br>We try to search existing thirdparty with '.$idtouseforthirdparty.
' '.$emailtouseforthirdparty.
' '.$nametouseforthirdparty.
' '.$namealiastouseforthirdparty;
2408 $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', $emailtouseforthirdparty, $namealiastouseforthirdparty);
2411 $this->error =
'Error when getting thirdparty with name '.$nametouseforthirdparty.
' (may be 2 record exists with same name ?)';
2412 $this->errors[] = $this->error;
2414 } elseif ($result == 0) {
2415 if ($operation[
'type'] ==
'loadthirdparty') {
2416 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2419 $resultContact = $contactstatic->fetch(
'',
'',
'', $emailtouseforthirdparty);
2420 if ($resultContact > 0) {
2421 $idtouseforthirdparty = $contactstatic->socid;
2422 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2424 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was found thanks to linked contact search");
2427 $langs->load(
"errors");
2428 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2429 $this->errors[] = $this->error;
2433 $langs->load(
"errors");
2434 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2435 $this->errors[] = $this->error;
2437 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2438 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
2441 $thirdpartystatic =
new Societe($db);
2442 $thirdpartystatic->name = $nametouseforthirdparty;
2443 if (!empty($namealiastouseforthirdparty)) {
2444 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
2445 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
2448 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'' : $fromtext) : $replytostring);
2450 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ?
'' : $from) : $replyto) : $emailtouseforthirdparty);
2453 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2455 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
2456 $thirdpartystatic->code_client =
'auto';
2458 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
2459 $thirdpartystatic->code_fournisseur =
'auto';
2462 if ($errorforthisaction) {
2465 $result = $thirdpartystatic->create($user);
2468 $this->error = $thirdpartystatic->error;
2469 $this->errors = $thirdpartystatic->errors;
2471 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag($thirdpartystatic->id);
2476 dol_syslog(
"One and only one existing third party has been found");
2478 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag($thirdpartystatic->id);
2482 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
2483 if (empty($operation[
'actionparam'])) {
2485 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
2486 $this->errors[] = $this->error;
2488 $contact_static =
new Contact($this->db);
2490 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2491 if ($errorforthisaction) {
2494 if (!empty($contact_static->email) && $contact_static->email != $from) {
2495 $from = $contact_static->email;
2498 $result = $contactstatic->fetch(0,
null,
'', $from);
2501 $this->error =
'Error when getting contact with email ' . $from;
2502 $this->errors[] = $this->error;
2504 } elseif ($result == 0) {
2505 dol_syslog(
"Contact with email " . $from .
" was not found. We try to create it.");
2506 $contactstatic =
new Contact($this->db);
2509 $contactstatic->email = $from;
2510 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($from);
2513 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2515 if ($errorforthisaction) {
2519 if (!empty($contactstatic->country)) {
2520 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2521 $result =
getCountry(
'', 3, $this->db,
'', 1, $contactstatic->country);
2522 if ($result ==
'NotDefined') {
2524 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
2525 } elseif (!($result > 0)) {
2527 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
2528 $this->errors[] = $this->db->lasterror();
2530 $contactstatic->country_id = $result;
2531 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2533 } elseif (!empty($contactstatic->country_code)) {
2534 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2535 $result =
getCountry($contactstatic->country_code, 3, $this->db);
2536 if ($result ==
'NotDefined') {
2538 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
2539 } elseif (!($result > 0)) {
2541 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
2542 $this->errors[] = $this->db->lasterror();
2544 $contactstatic->country_id = $result;
2545 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2549 if (!$errorforactions) {
2551 if (!empty($contactstatic->state)) {
2552 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2553 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
2554 if (empty($result)) {
2556 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
2557 } elseif (!($result > 0)) {
2559 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
2560 $this->errors[] = $this->db->lasterror();
2562 $contactstatic->state_id = $result;
2563 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2565 } elseif (!empty($contactstatic->state_code)) {
2566 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2567 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
2568 if (empty($result)) {
2570 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
2571 } elseif (!($result > 0)) {
2573 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
2574 $this->errors[] = $this->db->lasterror();
2576 $contactstatic->state_id = $result;
2577 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2582 if (!$errorforactions) {
2583 $result = $contactstatic->create($user);
2586 $this->error = $contactstatic->error;
2587 $this->errors = $contactstatic->errors;
2589 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag($contactstatic->id);
2596 } elseif ($operation[
'type'] ==
'recordevent') {
2600 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
2601 if ($alreadycreated == 0) {
2602 if ($projectstatic->id > 0) {
2603 if ($projectfoundby) {
2604 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
2607 if ($thirdpartystatic->id > 0) {
2608 if ($thirdpartyfoundby) {
2609 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2612 if ($contactstatic->id > 0) {
2613 if ($contactfoundby) {
2614 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2618 $description = $descriptiontitle;
2624 $descriptionfull = $description;
2626 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2631 $actioncomm->type_code =
'AC_OTH_AUTO';
2632 $actioncomm->code =
'AC_'.$actioncode;
2633 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
2634 $actioncomm->note_private = $descriptionfull;
2635 $actioncomm->fk_project = $projectstatic->id;
2636 $actioncomm->datep = $date;
2637 $actioncomm->datef = $date;
2638 $actioncomm->percentage = -1;
2639 $actioncomm->socid = $thirdpartystatic->id;
2640 $actioncomm->contact_id = $contactstatic->id;
2641 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id =>
'') : array());
2642 $actioncomm->authorid = $user->id;
2643 $actioncomm->userownerid = $user->id;
2645 $actioncomm->email_msgid = $msgid;
2646 $actioncomm->email_from = $fromstring;
2647 $actioncomm->email_sender = $sender;
2648 $actioncomm->email_to = $to;
2649 $actioncomm->email_tocc = $sendtocc;
2650 $actioncomm->email_tobcc = $sendtobcc;
2651 $actioncomm->email_subject = $subject;
2652 $actioncomm->errors_to =
'';
2654 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
2655 $actioncomm->fk_element = $fk_element_id;
2656 $actioncomm->elementid = $fk_element_id;
2657 $actioncomm->elementtype = $fk_element_type;
2658 if (is_object($objectemail) && $objectemail->module) {
2659 $actioncomm->elementtype .=
'@'.$objectemail->module;
2666 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2675 if ($errorforthisaction) {
2678 $result = $actioncomm->create($user);
2681 $this->errors = $actioncomm->errors;
2683 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag($actioncomm->id);
2687 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
2690 foreach ($attachments as $attachment) {
2691 if ($attachment->getName() ===
'undefined') {
2694 $data[$attachment->getName()] = $attachment->getContent();
2698 foreach ($pj as $key => $val) {
2699 $data[$val[
'filename']] =
getFileData($imapemail, $val[
'pos'], $val[
'type'], $connection);
2702 if (count($data) > 0) {
2703 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($from).
"%'";
2704 $resql = $this->db->query($sql);
2705 if ($this->db->num_rows($resql) == 0) {
2706 $this->errors[] =
"User Not allowed to add documents ({$from})";
2708 $arrayobject = array(
2709 'propale' => array(
'table' =>
'propal',
2710 'fields' => array(
'ref'),
2711 'class' =>
'comm/propal/class/propal.class.php',
2712 'object' =>
'Propal'),
2713 'holiday' => array(
'table' =>
'holiday',
2714 'fields' => array(
'ref'),
2715 'class' =>
'holiday/class/holiday.class.php',
2716 'object' =>
'Holiday'),
2717 'expensereport' => array(
'table' =>
'expensereport',
2718 'fields' => array(
'ref'),
2719 'class' =>
'expensereport/class/expensereport.class.php',
2720 'object' =>
'ExpenseReport'),
2721 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
2722 'fields' => array(
'ref'),
2723 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
2724 'object' =>
'RecruitmentJobPosition'),
2725 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
2726 'fields' => array(
'ref'),
2727 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
2728 'object' =>
' RecruitmentCandidature'),
2729 'societe' => array(
'table' =>
'societe',
2730 'fields' => array(
'code_client',
'code_fournisseur'),
2731 'class' =>
'societe/class/societe.class.php',
2732 'object' =>
'Societe'),
2733 'commande' => array(
'table' =>
'commande',
2734 'fields' => array(
'ref'),
2735 'class' =>
'commande/class/commande.class.php',
2736 'object' =>
'Commande'),
2737 'expedition' => array(
'table' =>
'expedition',
2738 'fields' => array(
'ref'),
2739 'class' =>
'expedition/class/expedition.class.php',
2740 'object' =>
'Expedition'),
2741 'contract' => array(
'table' =>
'contrat',
2742 'fields' => array(
'ref'),
2743 'class' =>
'contrat/class/contrat.class.php',
2744 'object' =>
'Contrat'),
2745 'fichinter' => array(
'table' =>
'fichinter',
2746 'fields' => array(
'ref'),
2747 'class' =>
'fichinter/class/fichinter.class.php',
2748 'object' =>
'Fichinter'),
2749 'ticket' => array(
'table' =>
'ticket',
2750 'fields' => array(
'ref'),
2751 'class' =>
'ticket/class/ticket.class.php',
2752 'object' =>
'Ticket'),
2753 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
2754 'fields' => array(
'ref'),
2755 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
2756 'object' =>
'KnowledgeRecord'),
2757 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
2758 'fields' => array(
'ref'),
2759 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
2760 'object' =>
'SupplierProposal'),
2761 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
2762 'fields' => array(
'ref',
'ref_supplier'),
2763 'class' =>
'fourn/class/fournisseur.commande.class.php',
2764 'object' =>
'SupplierProposal'),
2765 'facture' => array(
'table' =>
'facture',
2766 'fields' => array(
'ref'),
2767 'class' =>
'compta/facture/class/facture.class.php',
2768 'object' =>
'Facture'),
2769 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
2770 'fields' => array(
'ref',
'ref_client'),
2771 'class' =>
'fourn/class/fournisseur.facture.class.php',
2772 'object' =>
'FactureFournisseur'),
2773 'produit' => array(
'table' =>
'product',
2774 'fields' => array(
'ref'),
2775 'class' =>
'product/class/product.class.php',
2776 'object' =>
'Product'),
2777 'productlot' => array(
'table' =>
'product_lot',
2778 'fields' => array(
'batch'),
2779 'class' =>
'product/stock/class/productlot.class.php',
2780 'object' =>
'Productlot'),
2781 'projet' => array(
'table' =>
'projet',
2782 'fields' => array(
'ref'),
2783 'class' =>
'projet/class/projet.class.php',
2784 'object' =>
'Project'),
2785 'projet_task' => array(
'table' =>
'projet_task',
2786 'fields' => array(
'ref'),
2787 'class' =>
'projet/class/task.class.php',
2788 'object' =>
'Task'),
2789 'ressource' => array(
'table' =>
'resource',
2790 'fields' => array(
'ref'),
2791 'class' =>
'ressource/class/dolressource.class.php',
2792 'object' =>
'Dolresource'),
2793 'bom' => array(
'table' =>
'bom_bom',
2794 'fields' => array(
'ref'),
2795 'class' =>
'bom/class/bom.class.php',
2797 'mrp' => array(
'table' =>
'mrp_mo',
2798 'fields' => array(
'ref'),
2799 'class' =>
'mrp/class/mo.class.php',
2803 if (!is_object($hookmanager)) {
2804 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
2807 $hookmanager->initHooks(array(
'emailcolector'));
2808 $parameters = array(
'arrayobject' => $arrayobject);
2809 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
2811 $arrayobject = $hookmanager->resArray;
2814 $resultobj = array();
2816 foreach ($arrayobject as $key => $objectdesc) {
2817 $sql =
'SELECT DISTINCT t.rowid ';
2818 $sql .=
' FROM ' . MAIN_DB_PREFIX . $objectdesc[
'table'] .
' AS t';
2820 foreach ($objectdesc[
'fields'] as $field) {
2821 $sql .=
"('" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $field .
", '%') AND t." . $field .
"<>'') OR ";
2823 $sql = substr($sql, 0, -4);
2825 $ressqlobj = $this->db->query($sql);
2827 while ($obj = $this->db->fetch_object($ressqlobj)) {
2828 $resultobj[$key][] = $obj->rowid;
2833 foreach ($resultobj as $mod => $ids) {
2834 $moddesc = $arrayobject[$mod];
2835 $elementpath = $mod;
2837 $objectmanaged =
new $moddesc[
'object']($this->db);
2838 foreach ($ids as $val) {
2839 $res = $objectmanaged->fetch($val);
2841 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
2842 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
2844 $this->errors[] =
'object not found';
2848 foreach ($dirs as $target) {
2849 $prefix = $this->actions[$this->id][
'actionparam'];
2850 foreach ($data as $filename => $content) {
2851 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
2853 $this->errors[] =
'Doc not saved';
2858 $operationslog .=
'<br>Save attachment files on disk';
2860 $this->errors[] =
'no joined piece';
2862 $operationslog .=
'<br>No joinded files';
2864 } elseif ($operation[
'type'] ==
'project') {
2866 $projecttocreate =
new Project($this->db);
2867 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
2868 if ($alreadycreated == 0) {
2869 if ($thirdpartystatic->id > 0) {
2870 $projecttocreate->socid = $thirdpartystatic->id;
2871 if ($thirdpartyfoundby) {
2872 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2875 if ($contactstatic->id > 0) {
2876 $projecttocreate->contact_id = $contactstatic->id;
2877 if ($contactfoundby) {
2878 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2882 $description = $descriptiontitle;
2888 $descriptionfull = $description;
2890 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2894 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
2895 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
2897 $projecttocreate->title = $subject;
2898 $projecttocreate->date_start = $date;
2899 $projecttocreate->date_end =
'';
2900 $projecttocreate->opp_status = $id_opp_status;
2901 $projecttocreate->opp_percent = $percent_opp_status;
2903 $projecttocreate->note_private = $descriptionfull;
2904 $projecttocreate->entity = $conf->entity;
2905 $projecttocreate->email_msgid = $msgid;
2907 $savesocid = $projecttocreate->socid;
2911 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2914 if (empty($projecttocreate->ref)) {
2917 $modele = !
getDolGlobalString(
'PROJECT_ADDON') ?
'mod_project_simple' : $conf->global->PROJECT_ADDON;
2924 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
2925 foreach ($dirmodels as $reldir) {
2926 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
2927 if (file_exists($file)) {
2929 $classname = $modele;
2935 if ($savesocid > 0) {
2936 if ($savesocid != $projecttocreate->socid) {
2938 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');
2941 if ($projecttocreate->socid > 0) {
2942 $thirdpartystatic->fetch($projecttocreate->socid);
2946 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
2947 $modModuleToUseForNextValue =
new $classname();
2948 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
2950 $projecttocreate->ref = $defaultref;
2954 if ($errorforthisaction) {
2957 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
2959 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
2961 $operationslog .=
'<br>'.$this->error;
2964 $result = $projecttocreate->create($user);
2967 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
2968 $this->errors = $projecttocreate->errors;
2970 $operationslog .=
'<br>'.$this->error;
2973 $destdir = $conf->project->dir_output.
'/'.$projecttocreate->ref;
2978 foreach ($attachments as $attachment) {
2980 $typeattachment = (string) $attachment->getDisposition();
2981 $filename = $attachment->getFilename();
2982 $content = $attachment->getContent();
2986 $this->
getmsg($connection, $imapemail, $destdir);
2989 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag($projecttocreate->id);
2991 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag($projecttocreate->id);
2999 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3001 } elseif ($operation[
'type'] ==
'ticket') {
3003 $tickettocreate =
new Ticket($this->db);
3005 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
3006 if ($alreadycreated == 0) {
3007 if ($thirdpartystatic->id > 0) {
3008 $tickettocreate->socid = $thirdpartystatic->id;
3009 $tickettocreate->fk_soc = $thirdpartystatic->id;
3010 if ($thirdpartyfoundby) {
3011 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
3014 if ($contactstatic->id > 0) {
3015 $tickettocreate->contact_id = $contactstatic->id;
3016 if ($contactfoundby) {
3017 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
3021 $description = $descriptiontitle;
3027 $descriptionfull = $description;
3029 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3033 $tickettocreate->subject = $subject;
3034 $tickettocreate->message = $description;
3035 $tickettocreate->type_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE') ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE :
dol_getIdFromCode($this->db, 1,
'c_ticket_type',
'use_default',
'code', 1));
3036 $tickettocreate->category_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE') ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE :
dol_getIdFromCode($this->db, 1,
'c_ticket_category',
'use_default',
'code', 1));
3037 $tickettocreate->severity_code = (
getDolGlobalString(
'MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE') ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE :
dol_getIdFromCode($this->db, 1,
'c_ticket_severity',
'use_default',
'code', 1));
3038 $tickettocreate->origin_email = $from;
3039 $tickettocreate->fk_user_create = $user->id;
3040 $tickettocreate->datec =
dol_now();
3041 $tickettocreate->fk_project = $projectstatic->id;
3042 $tickettocreate->notify_tiers_at_create =
getDolGlobalInt(
'TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3043 $tickettocreate->note_private = $descriptionfull;
3044 $tickettocreate->entity = $conf->entity;
3045 $tickettocreate->email_msgid = $msgid;
3046 $tickettocreate->email_date = $date;
3049 $savesocid = $tickettocreate->socid;
3053 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3056 if (empty($tickettocreate->ref)) {
3059 $modele = !
getDolGlobalString(
'TICKET_ADDON') ?
'mod_ticket_simple' : $conf->global->TICKET_ADDON;
3066 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
3067 foreach ($dirmodels as $reldir) {
3068 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
3069 if (file_exists($file)) {
3071 $classname = $modele;
3077 if ($savesocid > 0) {
3078 if ($savesocid != $tickettocreate->socid) {
3080 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');
3083 if ($tickettocreate->socid > 0) {
3084 $thirdpartystatic->fetch($tickettocreate->socid);
3089 $modModuleToUseForNextValue =
new $classname();
3090 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3092 $tickettocreate->ref = $defaultref;
3095 if ($errorforthisaction) {
3098 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3100 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
3103 $result = $tickettocreate->create($user);
3106 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3107 $this->errors = $tickettocreate->errors;
3110 $destdir = $conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3115 foreach ($attachments as $attachment) {
3117 $typeattachment = (string) $attachment->getDisposition();
3118 $filename = $attachment->getFilename();
3119 $content = $attachment->getContent();
3123 $this->
getmsg($connection, $imapemail, $destdir);
3126 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3128 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3134 } elseif ($operation[
'type'] ==
'candidature') {
3138 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3139 if ($alreadycreated == 0) {
3140 $description = $descriptiontitle;
3146 $descriptionfull = $description;
3147 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3150 $candidaturetocreate->subject = $subject;
3151 $candidaturetocreate->message = $description;
3152 $candidaturetocreate->type_code = 0;
3153 $candidaturetocreate->category_code =
null;
3154 $candidaturetocreate->severity_code =
null;
3155 $candidaturetocreate->email = $from;
3157 $candidaturetocreate->fk_user_creat = $user->id;
3158 $candidaturetocreate->date_creation =
dol_now();
3159 $candidaturetocreate->fk_project = $projectstatic->id;
3160 $candidaturetocreate->description = $description;
3161 $candidaturetocreate->note_private = $descriptionfull;
3162 $candidaturetocreate->entity = $conf->entity;
3163 $candidaturetocreate->email_msgid = $msgid;
3164 $candidaturetocreate->email_date = $date;
3165 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3170 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3212 if ($errorforthisaction) {
3216 $result = $candidaturetocreate->create($user);
3219 $this->error =
'Failed to create candidature: '.join(
', ', $candidaturetocreate->errors);
3220 $this->errors = $candidaturetocreate->errors;
3223 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag($candidaturetocreate->id);
3226 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3229 if (!is_object($hookmanager)) {
3230 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3232 $hookmanager->initHooks([
'emailcolector']);
3235 $parameters = array(
3236 'connection'=> $connection,
3237 'imapemail'=>$imapemail,
3238 'overview'=>$overview,
3241 'fromtext' => $fromtext,
3243 'actionparam'=> $operation[
'actionparam'],
3245 'thirdpartyid' => $thirdpartyid,
3246 'objectid'=> $objectid,
3247 'objectemail'=> $objectemail,
3249 'messagetext'=>$messagetext,
3250 'subject'=>$subject,
3252 'attachments'=>$attachments,
3254 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3257 $errorforthisaction++;
3258 $this->error = $hookmanager->resPrint;
3260 if ($errorforthisaction) {
3262 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3264 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3268 if (!$errorforactions) {
3269 $nbactiondoneforemail++;
3275 if (!$errorforactions) {
3276 if (!empty($targetdir)) {
3279 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3281 $imapemail->move($targetdir);
3284 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget, LOG_DEBUG);
3285 $operationslog .=
'<br>Move mail '.($this->uidAsString($imapemail)).
' - '.$msgid;
3287 $arrayofemailtodelete[$imapemail] = $msgid;
3292 dol_syslog(
"EmailCollector::doCollectOneCollector message '".($imapemail->getHeader()->get(
'subject')).
"' using this->host=".$this->host.
", this->access_type=".$this->acces_type.
" was set to read", LOG_DEBUG);
3294 dol_syslog(
"EmailCollector::doCollectOneCollector message ".($this->
uidAsString($imapemail)).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3302 unset($objectemail);
3303 unset($projectstatic);
3304 unset($thirdpartystatic);
3305 unset($contactstatic);
3307 $nbemailprocessed++;
3309 if (!$errorforemail) {
3310 $nbactiondone += $nbactiondoneforemail;
3314 $this->db->commit();
3316 $this->db->rollback();
3320 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3321 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3327 $this->db->rollback();
3331 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3333 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3335 $langs->load(
"admin");
3336 $output = $langs->trans(
'NoNewEmailToProcess');
3337 $output .=
' (defaultlang='.$langs->defaultlang.
')';
3342 $client->disconnect();
3344 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
3345 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
3347 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid;
3349 if (empty($mode) && empty($error)) {
3350 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
3351 if ($res ==
false) {
3353 $this->error = imap_last_error();
3354 $this->errors[] = $this->error;
3356 $operationslog .=
'<br>Error in move '.$this->error;
3363 if (empty($mode) && empty($error)) {
3365 $operationslog .=
"<br>Expunge";
3367 imap_expunge($connection);
3369 imap_close($connection);
3372 $this->datelastresult = $now;
3373 $this->lastresult = $output;
3374 $this->debuginfo .=
'IMAP search string used : '.$search;
3376 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
3378 if ($operationslog) {
3379 $this->debuginfo .= $operationslog;
3382 if (empty($error) && empty($mode)) {
3383 $this->datelastok = $now;
3386 if (!empty($this->errors)) {
3387 $this->lastresult .=
"<br>".join(
"<br>", $this->errors);
3389 $this->codelastresult = ($error ?
'KO' :
'OK');
3395 dol_syslog(
"EmailCollector::doCollectOneCollector end", LOG_INFO);
3397 return $error ? -1 : 1;
3412 private function getmsg($mbox, $mid, $destdir =
'')
3416 global $charset, $htmlmsg, $plainmsg, $attachments;
3417 $htmlmsg = $plainmsg = $charset =
'';
3418 $attachments = array();
3425 $s = imap_fetchstructure($mbox, $mid, FT_UID);
3430 $this->
getpart($mbox, $mid, $s, 0);
3433 foreach ($s->parts as $partno0 => $p) {
3434 $this->
getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
3465 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
3468 global $htmlmsg, $plainmsg, $charset, $attachments;
3472 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
3473 imap_body($mbox, $mid, FT_UID);
3475 if ($p->encoding == 4) {
3476 $data = quoted_printable_decode($data);
3477 } elseif ($p->encoding == 3) {
3478 $data = base64_decode($data);
3484 if ($p->parameters) {
3485 foreach ($p->parameters as $x) {
3486 $params[strtolower($x->attribute)] = $x->value;
3489 if (!empty($p->dparameters)) {
3490 foreach ($p->dparameters as $x) {
3491 $params[strtolower($x->attribute)] = $x->value;
3498 if (!empty($params[
'filename']) || !empty($params[
'name'])) {
3500 $filename = $params[
'filename'] ?? $params[
'name'];
3502 $attachments[$filename] = $data;
3504 if (strlen($destdir)) {
3505 if (substr($destdir, -1) !=
'/') {
3510 $file_name_complete = $params[
'filename'];
3511 $destination = $destdir.$file_name_complete;
3514 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
3517 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
3520 $file_name_original = $file_name;
3529 while (file_exists($destdir.$file_name.
".".$extension)) {
3530 $file_name = $file_name_original .
' (' . $num .
')';
3531 $file_name_complete = $file_name .
"." . $extension;
3532 $destination = $destdir.$file_name_complete;
3538 file_put_contents($destination, $data);
3543 if ($p->type == 0 && $data) {
3544 if (!empty($params[
'charset'])) {
3549 if (strtolower($p->subtype) ==
'plain') {
3550 $plainmsg .= trim($data).
"\n\n";
3552 $htmlmsg .= $data.
"<br><br>";
3554 $charset = $params[
'charset'];
3555 } elseif ($p->type == 2 && $data) {
3561 if (!empty($params[
'charset'])) {
3564 $plainmsg .= $data.
"\n\n";
3568 if (!empty($p->parts)) {
3569 foreach ($p->parts as $partno0 => $p2) {
3570 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1), $destdir);
3586 if (!$string || $fromEncoding == $toEncoding) {
3589 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
3590 if (!$convertedString && extension_loaded(
'mbstring')) {
3591 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
3593 if (!$convertedString) {
3594 throw new Exception(
'Mime string encoding conversion failed');
3596 return $convertedString;
3615 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
3616 $elements = imap_mime_header_decode($subject);
3618 if (!empty($elements)) {
3619 $num = count($elements);
3620 for ($i = 0; $i < $num; $i++) {
3621 $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));
3622 $newstring .= $stringinutf8;
3624 $subject = $newstring;
3626 } elseif (!function_exists(
'mb_decode_mimeheader')) {
3627 $subject = mb_decode_mimeheader($subject);
3628 } elseif (function_exists(
'iconv_mime_decode')) {
3629 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
3644 $text = preg_replace(
'/[\x{1F600}-\x{1F64F}]/u',
'', $text);
3645 $text = preg_replace(
'/[\x{1F300}-\x{1F5FF}]/u',
'', $text);
3646 $text = preg_replace(
'/[\x{1F680}-\x{1F6FF}]/u',
'', $text);
3647 $text = preg_replace(
'/[\x{2600}-\x{26FF}]/u',
'', $text);
3648 $text = preg_replace(
'/[\x{2700}-\x{27BF}]/u',
'', $text);
3649 $text = preg_replace(
'/[\x{1F900}-\x{1F9FF}]/u',
'', $text);
3650 $text = preg_replace(
'/[\x{1F1E0}-\x{1F1FF}]/u',
'', $text);
3665 require_once DOL_DOCUMENT_ROOT .
'/core/lib/images.lib.php';
3668 $maxwidthsmall = $tmparraysize[
'maxwidthsmall'];
3669 $maxheightsmall = $tmparraysize[
'maxheightsmall'];
3670 $maxwidthmini = $tmparraysize[
'maxwidthmini'];
3671 $maxheightmini = $tmparraysize[
'maxheightmini'];
3672 $quality = $tmparraysize[
'quality'];
3674 file_put_contents($destdir.
'/'.$filename, $content);
3677 vignette($destdir.
'/'.$filename, $maxwidthsmall, $maxheightsmall,
'_small', $quality,
"thumbs");
3679 vignette($destdir.
'/'.$filename, $maxwidthmini, $maxheightmini,
'_mini', $quality,
"thumbs");
3692 if (is_object($imapemail)) {
3693 return $imapemail->getAttributes()[
"uid"];
3695 return (
string) $imapemail;