25 include_once DOL_DOCUMENT_ROOT .
'/emailcollector/lib/emailcollector.lib.php';
27 require_once DOL_DOCUMENT_ROOT .
'/core/class/commonobject.class.php';
28 require_once DOL_DOCUMENT_ROOT .
'/core/lib/files.lib.php';
30 require_once DOL_DOCUMENT_ROOT .
'/comm/propal/class/propal.class.php';
31 require_once DOL_DOCUMENT_ROOT .
'/commande/class/commande.class.php';
32 require_once DOL_DOCUMENT_ROOT .
'/compta/facture/class/facture.class.php';
33 require_once DOL_DOCUMENT_ROOT .
'/contact/class/contact.class.php';
34 require_once DOL_DOCUMENT_ROOT .
'/expedition/class/expedition.class.php';
35 require_once DOL_DOCUMENT_ROOT .
'/fourn/class/fournisseur.commande.class.php';
36 require_once DOL_DOCUMENT_ROOT .
'/fourn/class/fournisseur.facture.class.php';
37 require_once DOL_DOCUMENT_ROOT .
'/projet/class/project.class.php';
38 require_once DOL_DOCUMENT_ROOT .
'/reception/class/reception.class.php';
39 require_once DOL_DOCUMENT_ROOT .
'/recruitment/class/recruitmentcandidature.class.php';
40 require_once DOL_DOCUMENT_ROOT .
'/societe/class/societe.class.php';
41 require_once DOL_DOCUMENT_ROOT .
'/supplier_proposal/class/supplier_proposal.class.php';
42 require_once DOL_DOCUMENT_ROOT .
'/ticket/class/ticket.class.php';
47 use Webklex\PHPIMAP\ClientManager;
48 use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
49 use Webklex\PHPIMAP\Exceptions\InvalidWhereQueryCriteriaException;
50 use Webklex\PHPIMAP\Exceptions\GetMessagesFailedException;
52 use OAuth\Common\Storage\DoliStorage;
53 use OAuth\Common\Consumer\Credentials;
64 public $element =
'emailcollector';
69 public $table_element =
'emailcollector_emailcollector';
74 public $ismultientitymanaged = 1;
79 public $isextrafieldmanaged = 0;
84 public $picto =
'email';
89 public $fk_element =
'fk_emailcollector';
94 protected $childtables = array();
99 protected $childtablesoncascade = array(
'emailcollector_emailcollectorfilter',
'emailcollector_emailcollectoraction');
125 public $fields = array(
126 'rowid' => array(
'type'=>
'integer',
'label'=>
'TechnicalID',
'visible'=>2,
'enabled'=>1,
'position'=>1,
'notnull'=>1,
'index'=>1),
127 'entity' => array(
'type'=>
'integer',
'label'=>
'Entity',
'enabled'=>1,
'visible'=>0,
'default'=>1,
'notnull'=>1,
'index'=>1,
'position'=>20),
128 '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'),
129 'label' => array(
'type'=>
'varchar(255)',
'label'=>
'Label',
'visible'=>1,
'enabled'=>1,
'position'=>30,
'notnull'=>-1,
'searchall'=>1,
'help'=>
'Example: My Email collector',
'csslist'=>
'tdoverflowmax150'),
130 'description' => array(
'type'=>
'text',
'label'=>
'Description',
'visible'=>-1,
'enabled'=>1,
'position'=>60,
'notnull'=>-1,
'cssview'=>
'small',
'csslist'=>
'small tdoverflowmax200'),
131 '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'),
132 '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'),
133 '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'),
134 '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'=>
''),
135 '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'),
136 'password' => array(
'type'=>
'password',
'label'=>
'Password',
'visible'=>-1,
'enabled'=>
"1",
'position'=>103,
'notnull'=>-1,
'comment'=>
"IMAP password",
'help'=>
'WithGMailYouCanCreateADedicatedPassword'),
137 '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'),
138 'source_directory' => array(
'type'=>
'varchar(255)',
'label'=>
'MailboxSourceDirectory',
'visible'=>-1,
'enabled'=>1,
'position'=>104,
'notnull'=>1,
'default' =>
'Inbox',
'help'=>
'Example: INBOX'),
139 'target_directory' => array(
'type'=>
'varchar(255)',
'label'=>
'MailboxTargetDirectory',
'visible'=>1,
'enabled'=>1,
'position'=>110,
'notnull'=>0,
'help'=>
"EmailCollectorTargetDir"),
140 'maxemailpercollect' => array(
'type'=>
'integer',
'label'=>
'MaxEmailCollectPerCollect',
'visible'=>-1,
'enabled'=>1,
'position'=>111,
'default'=>100),
141 'datelastresult' => array(
'type'=>
'datetime',
'label'=>
'DateLastCollectResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>121,
'notnull'=>-1,
'csslist'=>
'nowraponall'),
142 'codelastresult' => array(
'type'=>
'varchar(16)',
'label'=>
'CodeLastResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>122,
'notnull'=>-1,),
143 'lastresult' => array(
'type'=>
'varchar(255)',
'label'=>
'LastResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>123,
'notnull'=>-1,
'cssview'=>
'small',
'csslist'=>
'small tdoverflowmax200'),
144 'datelastok' => array(
'type'=>
'datetime',
'label'=>
'DateLastcollectResultOk',
'visible'=>1,
'enabled'=>
'$action != "create"',
'position'=>125,
'notnull'=>-1,
'csslist'=>
'nowraponall'),
145 'note_public' => array(
'type'=>
'html',
'label'=>
'NotePublic',
'visible'=>0,
'enabled'=>1,
'position'=>61,
'notnull'=>-1,),
146 'note_private' => array(
'type'=>
'html',
'label'=>
'NotePrivate',
'visible'=>0,
'enabled'=>1,
'position'=>62,
'notnull'=>-1,),
147 'date_creation' => array(
'type'=>
'datetime',
'label'=>
'DateCreation',
'visible'=>-2,
'enabled'=>1,
'position'=>500,
'notnull'=>1,),
148 'tms' => array(
'type'=>
'timestamp',
'label'=>
'DateModification',
'visible'=>-2,
'enabled'=>1,
'position'=>501,
'notnull'=>1,),
150 'fk_user_creat' => array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserAuthor',
'visible'=>-2,
'enabled'=>1,
'position'=>510,
'notnull'=>1,),
151 'fk_user_modif' => array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserModif',
'visible'=>-2,
'enabled'=>1,
'position'=>511,
'notnull'=>-1,),
153 'import_key' => array(
'type'=>
'varchar(14)',
'label'=>
'ImportId',
'visible'=>-2,
'enabled'=>1,
'position'=>1000,
'notnull'=>-1,),
154 'status' => array(
'type'=>
'integer',
'label'=>
'Status',
'visible'=>1,
'enabled'=>1,
'position'=>1000,
'notnull'=>1,
'index'=>1,
'arrayofkeyval'=>array(
'0'=>
'Inactive',
'1'=>
'Active'))
187 public $date_creation;
197 public $fk_user_creat;
202 public $fk_user_modif;
215 public $oauth_service;
216 public $source_directory;
217 public $target_directory;
218 public $maxemailpercollect;
223 public $datelastresult;
225 public $codelastresult;
235 const STATUS_DISABLED = 0;
236 const STATUS_ENABLED = 1;
246 global $conf, $langs;
250 if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields[
'rowid'])) {
251 $this->fields[
'rowid'][
'visible'] = 0;
253 if (!
isModEnabled(
'multicompany') && isset($this->fields[
'entity'])) {
254 $this->fields[
'entity'][
'enabled'] = 0;
258 $oauthservices = array();
260 foreach ($conf->global as $key => $val) {
261 if (!empty($val) && preg_match(
'/^OAUTH_.*_ID$/', $key)) {
262 $key = preg_replace(
'/^OAUTH_/',
'', $key);
263 $key = preg_replace(
'/_ID$/',
'', $key);
264 if (preg_match(
'/^.*-/', $key)) {
265 $name = preg_replace(
'/^.*-/',
'', $key);
267 $name = $langs->trans(
"NoName");
269 $provider = preg_replace(
'/-.*$/',
'', $key);
270 $provider = ucfirst(strtolower($provider));
272 $oauthservices[$key] = $name.
" (".$provider.
")";
276 $this->fields[
'oauth_service'][
'arrayofkeyval'] = $oauthservices;
279 foreach ($this->fields as $key => $val) {
280 if (isset($val[
'enabled']) && empty($val[
'enabled'])) {
281 unset($this->fields[$key]);
286 foreach ($this->fields as $key => $val) {
287 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
288 foreach ($val[
'arrayofkeyval'] as $key2 => $val2) {
289 $this->fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
307 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
308 $langs->load(
"errors");
309 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
313 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
314 $this->password =
dolEncrypt($this->password);
318 $this->password =
dolDecrypt($this->password);
320 if (is_array($this->filters) && count($this->filters)) {
323 foreach ($this->filters as $filter) {
324 $emailcollectorfilter->type = $filter[
'type'];
325 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
326 $emailcollectorfilter->fk_emailcollector = $this->id;
327 $emailcollectorfilter->status = $filter[
'status'];
329 $emailcollectorfilter->create($user);
333 if (is_array($this->actions) && count($this->actions)) {
336 foreach ($this->actions as $operation) {
337 $emailcollectoroperation->type = $operation[
'type'];
338 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
339 $emailcollectoroperation->fk_emailcollector = $this->id;
340 $emailcollectoroperation->status = $operation[
'status'];
341 $emailcollectoroperation->position = $operation[
'position'];
343 $emailcollectoroperation->create($user);
359 global $langs, $extrafields;
364 $object =
new self($this->db);
369 $object->fetchCommon($fromid);
371 $object->fetchFilters();
372 $object->fetchActions();
376 unset($object->fk_user_creat);
377 unset($object->import_key);
378 unset($object->password);
381 $object->ref =
"copy_of_".$object->ref;
382 $object->label = $langs->trans(
"CopyOf").
" ".$object->label;
383 if (empty($object->host)) {
384 $object->host =
'imap.example.com';
387 if (is_array($object->array_options) && count($object->array_options) > 0) {
388 $extrafields->fetch_name_optionals_label($this->table_element);
389 foreach ($object->array_options as $key => $option) {
390 $shortkey = preg_replace(
'/options_/',
'', $key);
391 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
393 unset($object->array_options[$key]);
399 $object->context[
'createfromclone'] =
'createfromclone';
400 $result = $object->create($user);
403 $this->error = $object->error;
404 $this->errors = $object->errors;
407 unset($object->context[
'createfromclone']);
414 $this->
db->rollback();
426 public function fetch($id, $ref =
null)
430 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
431 $this->password =
dolDecrypt($this->password);
464 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
470 $sql =
"SELECT s.rowid";
471 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
472 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
474 $sql .=
" AND s.status = 1";
476 $sql .= $this->
db->order($sortfield, $sortorder);
481 $offset = $limit * $page;
483 $sql .= $this->
db->plimit($limit + 1, $offset);
486 $result = $this->
db->query($sql);
488 $num = $this->
db->num_rows($result);
491 $obj = $this->
db->fetch_object($result);
493 if ($emailcollector_static->fetch($obj->rowid)) {
494 $obj_ret[] = $emailcollector_static;
499 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
500 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
503 if (!count($obj_ret)) {
504 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
522 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
523 $langs->load(
"errors");
524 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
528 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
529 $this->password =
dolEncrypt($this->password);
533 $this->password =
dolDecrypt($this->password);
545 public function delete(
User $user, $notrigger =
false)
560 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
562 global $conf, $langs, $action, $hookmanager;
564 if (!empty($conf->dol_no_mouse_hover)) {
570 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
572 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
574 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
576 if ($option !=
'nolink') {
578 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
579 if ($save_lastsearch_value == -1 && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
580 $add_save_lastsearch_values = 1;
582 if ($add_save_lastsearch_values) {
583 $url .=
'&save_lastsearch_values=1';
588 if (empty($notooltip)) {
589 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
590 $label = $langs->trans(
"ShowEmailCollector");
591 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
593 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
594 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
596 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
599 $linkstart =
'<a href="'.$url.
'"';
600 $linkstart .= $linkclose.
'>';
603 $result .= $linkstart;
605 $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);
607 if ($withpicto != 2) {
608 $result .= $this->ref;
613 $hookmanager->initHooks(array(
'emailcollectordao'));
614 $parameters = array(
'id'=>$this->
id,
'getnomurl' => &$result);
615 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
617 $result = $hookmanager->resPrint;
619 $result .= $hookmanager->resPrint;
633 return $this->
LibStatut($this->status, $mode);
647 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
650 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
651 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
652 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
653 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
656 $statusType =
'status5';
657 if ($status == self::STATUS_ENABLED) {
658 $statusType =
'status4';
661 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
672 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
673 $sql .=
' fk_user_creat, fk_user_modif';
674 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
675 $sql .=
' WHERE t.rowid = '.((int) $id);
676 $result = $this->
db->query($sql);
678 if ($this->
db->num_rows($result)) {
679 $obj = $this->
db->fetch_object($result);
680 $this->
id = $obj->rowid;
682 $this->user_creation_id = $obj->fk_user_creat;
683 $this->user_modification_id = $obj->fk_user_modif;
684 $this->date_creation = $this->
db->jdate($obj->datec);
685 $this->date_modification = empty($obj->datem) ?
'' : $this->
db->jdate($obj->datem);
688 $this->
db->free($result);
702 $this->host =
'localhost';
703 $this->login =
'alogin';
716 $this->filters = array();
718 $sql =
'SELECT rowid, type, rulevalue, status';
719 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
720 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
728 $obj = $this->
db->fetch_object(
$resql);
729 $this->filters[$obj->rowid] = array(
'id'=>$obj->rowid,
'type'=>$obj->type,
'rulevalue'=>$obj->rulevalue,
'status'=>$obj->status);
748 $this->actions = array();
750 $sql =
'SELECT rowid, type, actionparam, status';
751 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
752 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
753 $sql .=
' ORDER BY position';
760 $obj = $this->
db->fetch_object(
$resql);
761 $this->actions[$obj->rowid] = array(
'id'=>$obj->rowid,
'type'=>$obj->type,
'actionparam'=>$obj->actionparam,
'status'=>$obj->status);
783 $flags =
'/service=imap';
784 if (!empty($conf->global->IMAP_FORCE_TLS)) {
786 } elseif (empty($conf->global->IMAP_FORCE_NOSSL)) {
791 $flags .=
'/novalidate-cert';
794 if ($norsh || !empty($conf->global->IMAP_FORCE_NORSH)) {
798 if (strpos($this->login,
'/') !=
false) {
799 $partofauth = explode(
'/', $this->login);
800 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
803 $connectstringserver =
'{'.$this->host.
':'.$this->port.$flags.
'}';
805 return $connectstringserver;
816 if (function_exists(
'mb_convert_encoding')) {
818 $str = preg_replace(
"/ /",
"xyxy", $str);
820 if ($str = mb_convert_encoding($str,
"UTF-7")) {
822 $str = preg_replace(
"/\+A/",
"&A", $str);
824 $str = preg_replace(
"/xyxy/",
" ", $str);
828 $this->error =
"error: is not possible to encode this string '".$str.
"'";
848 $arrayofcollectors = $this->
fetchAll($user, 1);
851 foreach ($arrayofcollectors as $emailcollector) {
852 $result = $emailcollector->doCollectOneCollector(0);
853 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
855 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
856 if (!empty($emailcollector->errors)) {
857 $this->error .= join(
'<br>', $emailcollector->errors);
859 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
878 global $conf, $langs;
880 $errorforthisaction = 0;
883 $outputlangs = $langs;
886 $newlang =
GETPOST(
'lang_id',
'aZ09');
889 $newlang = $object->thirdparty->default_lang;
891 if (!empty($newlang)) {
893 $outputlangs->setDefaultLang($newlang);
903 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
906 $tmparray = explode(
'.', $propertytooverwrite);
907 if (count($tmparray) == 2) {
908 $tmpclass = $tmparray[0];
909 $tmpproperty = $tmparray[1];
911 $tmpproperty = $tmparray[0];
913 if ($tmpclass && ($tmpclass != $object->element)) {
923 $regforregex = array();
924 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
925 $sourcefield = $regforregex[1];
926 $regexstring = $regforregex[2];
928 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
929 $sourcefield = $regforregex[1];
930 $regexstring = $regforregex[2];
933 if (!empty($sourcefield) && !empty($regexstring)) {
934 if (strtolower($sourcefield) ==
'body') {
935 $sourcestring = $messagetext;
936 } elseif (strtolower($sourcefield) ==
'subject') {
937 $sourcestring = $subject;
938 } elseif (strtolower($sourcefield) ==
'header') {
939 $sourcestring = $header;
943 $regforval = array();
945 if (strtolower($sourcefield) ==
'body') {
946 $regexoptions =
'ms';
948 if (strtolower($sourcefield) ==
'header') {
953 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
955 $valueextracted = isset($regforval[count($regforval) - 1]) ?trim($regforval[count($regforval) - 1]) :
null;
956 if (strtolower($sourcefield) ==
'header') {
957 if (preg_match(
'/^options_/', $tmpproperty)) {
958 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $this->
decodeSMTPSubject($valueextracted);
960 if (property_exists($object, $tmpproperty)) {
967 if (preg_match(
'/^options_/', $tmpproperty)) {
968 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $this->
decodeSMTPSubject($valueextracted);
970 if (property_exists($object, $tmpproperty)) {
977 if (preg_match(
'/^options_/', $tmpproperty)) {
978 $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));
980 if (property_exists($object, $tmpproperty)) {
988 if (property_exists($object, $tmpproperty)) {
989 $object->$tmpproperty =
null;
991 $tmp[$tmpproperty] =
null;
994 $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.';
998 $errorforthisaction++;
999 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1000 $this->errors[] = $this->error;
1002 $operationslog .=
'<br>'.$this->error;
1004 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1006 if (preg_match(
'/^options_/', $tmpproperty)) {
1007 $valuecurrent = $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1009 if (property_exists($object, $tmpproperty)) {
1010 $valuecurrent = $object->$tmpproperty;
1012 $valuecurrent = $tmp[$tmpproperty];
1016 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1017 $valuetouse = $regforregex[2];
1020 $matcharray = array();
1021 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1023 if (is_array($matcharray[1])) {
1024 foreach ($matcharray[1] as $keytoreplace) {
1025 if ($keytoreplace) {
1026 if (preg_match(
'/^options_/', $keytoreplace)) {
1027 $substitutionarray[
'__'.$keytoreplace.
'__'] = $object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1029 if (property_exists($object, $keytoreplace)) {
1030 $substitutionarray[
'__'.$keytoreplace.
'__'] = $object->$keytoreplace;
1032 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1042 if (preg_match(
'/^options_/', $tmpproperty)) {
1043 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1045 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1047 if (property_exists($object, $tmpproperty)) {
1048 $object->$tmpproperty = $valuetouse;
1050 $tmp[$tmpproperty] = $valuetouse;
1053 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1057 $errorforthisaction++;
1058 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1059 $this->errors[] = $this->error;
1064 return $errorforthisaction;
1075 global $db, $conf, $langs, $user;
1076 global $hookmanager;
1080 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1081 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1082 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1085 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1087 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1092 $this->debuginfo =
'';
1096 $searchfilterdoltrackid = 0;
1097 $searchfilternodoltrackid = 0;
1098 $searchfilterisanswer = 0;
1099 $searchfilterisnotanswer = 0;
1100 $searchfilterreplyto = 0;
1101 $searchfilterexcludebody =
'';
1102 $searchfilterexcludesubject =
'';
1103 $operationslog =
'';
1108 if (empty($this->host)) {
1109 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1112 if (empty($this->login)) {
1113 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1116 if (empty($this->source_directory)) {
1117 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1124 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1125 if ($this->acces_type == 1) {
1127 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1128 $keyforsupportedoauth2array = $this->oauth_service;
1129 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1130 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1132 $keyforprovider =
'';
1134 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1135 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1137 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
1139 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1145 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1148 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1156 if (is_object($tokenobj) && $expire) {
1157 $credentials =
new Credentials(
1162 $serviceFactory = new \OAuth\ServiceFactory();
1163 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1165 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1167 $refreshtoken = $tokenobj->getRefreshToken();
1168 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1169 $tokenobj->setRefreshToken($refreshtoken);
1170 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1172 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1173 if (is_object($tokenobj)) {
1174 $token = $tokenobj->getAccessToken();
1176 $this->error =
"Token not found";
1181 $this->error = $e->getMessage();
1182 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1186 $cm =
new ClientManager();
1187 $client = $cm->make([
1188 'host' => $this->host,
1189 'port' => $this->port,
1190 'encryption' =>
'ssl',
1191 'validate_cert' =>
true,
1192 'protocol' =>
'imap',
1193 'username' => $this->login,
1194 'password' => $token,
1195 'authentication' =>
"oauth",
1199 $cm =
new ClientManager();
1200 $client = $cm->make([
1201 'host' => $this->host,
1202 'port' => $this->port,
1203 'encryption' =>
'ssl',
1204 'validate_cert' =>
true,
1205 'protocol' =>
'imap',
1206 'username' => $this->login,
1207 'password' => $this->password,
1208 'authentication' =>
"login",
1214 }
catch (ConnectionFailedException $e) {
1215 $this->error = $e->getMessage();
1216 $this->errors[] = $this->error;
1217 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1221 $host = dol_getprefix(
'email');
1224 if (!function_exists(
'imap_open')) {
1225 $this->error =
'IMAP function not enabled on your PHP';
1228 $sourcedir = $this->source_directory;
1229 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1232 $connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
1233 $connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
1235 $connection = imap_open($connectstringsource, $this->login, $this->password);
1237 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1242 $host = dol_getprefix(
'email');
1251 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1253 $criteria = array(array(
'UNDELETED'));
1254 foreach ($this->filters as $rule) {
1255 if (empty($rule[
'status'])) {
1260 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1265 if ($rule[
'type'] ==
'from') {
1266 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1267 if (count($tmprulevaluearray) >= 2) {
1268 foreach ($tmprulevaluearray as $tmprulevalue) {
1269 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1272 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1275 if ($rule[
'type'] ==
'to') {
1276 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1277 if (count($tmprulevaluearray) >= 2) {
1278 foreach ($tmprulevaluearray as $tmprulevalue) {
1279 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1282 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1285 if ($rule[
'type'] ==
'bcc') {
1286 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1288 if ($rule[
'type'] ==
'cc') {
1289 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1291 if ($rule[
'type'] ==
'subject') {
1292 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1294 $searchfilterexcludesubject = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1296 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1299 if ($rule[
'type'] ==
'body') {
1300 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1302 $searchfilterexcludebody = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1304 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1307 if ($rule[
'type'] ==
'header') {
1308 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1320 if ($rule[
'type'] ==
'seen') {
1321 array_push($criteria, array($not.
"SEEN"));
1323 if ($rule[
'type'] ==
'unseen') {
1324 array_push($criteria, array($not.
"UNSEEN"));
1326 if ($rule[
'type'] ==
'unanswered') {
1327 array_push($criteria, array($not.
"UNANSWERED"));
1329 if ($rule[
'type'] ==
'answered') {
1330 array_push($criteria, array($not.
"ANSWERED"));
1332 if ($rule[
'type'] ==
'smaller') {
1333 array_push($criteria, array($not.
"SMALLER"));
1335 if ($rule[
'type'] ==
'larger') {
1336 array_push($criteria, array($not.
"LARGER"));
1340 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1341 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1343 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1344 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1346 if ($rule[
'type'] ==
'withtrackingid') {
1347 $searchfilterdoltrackid++; $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1349 if ($rule[
'type'] ==
'withouttrackingid') {
1350 $searchfilternodoltrackid++; $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1353 if ($rule[
'type'] ==
'isanswer') {
1354 $searchfilterisanswer++; $searchhead .=
'/References.*@.*/';
1356 if ($rule[
'type'] ==
'isnotanswer') {
1357 $searchfilterisnotanswer++; $searchhead .=
'! /References.*@.*/';
1360 if ($rule[
'type'] ==
'replyto') {
1361 $searchfilterreplyto++; $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1365 if (empty($targetdir)) {
1367 if ($this->datelastok) {
1368 $fromdate = $this->datelastok;
1370 if ($fromdate > 0) {
1372 array_push($criteria, array(
"SINCE" => date(
'j-M-Y', $fromdate - 1)));
1377 dol_syslog(
"IMAP search string = ".var_export($criteria,
true));
1378 $search = var_export($criteria,
true);
1381 $search =
'UNDELETED';
1382 foreach ($this->filters as $rule) {
1383 if (empty($rule[
'status'])) {
1391 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1396 if ($rule[
'type'] ==
'from') {
1397 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1398 if (count($tmprulevaluearray) >= 2) {
1399 foreach ($tmprulevaluearray as $tmprulevalue) {
1400 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1403 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1406 if ($rule[
'type'] ==
'to') {
1407 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1408 if (count($tmprulevaluearray) >= 2) {
1409 foreach ($tmprulevaluearray as $tmprulevalue) {
1410 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1413 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1416 if ($rule[
'type'] ==
'bcc') {
1417 $search .= ($search ?
' ' :
'').$not.
'BCC';
1419 if ($rule[
'type'] ==
'cc') {
1420 $search .= ($search ?
' ' :
'').$not.
'CC';
1422 if ($rule[
'type'] ==
'subject') {
1423 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1425 $searchfilterexcludesubject = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1427 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1430 if ($rule[
'type'] ==
'body') {
1431 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1433 $searchfilterexcludebody = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1436 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1439 if ($rule[
'type'] ==
'header') {
1440 $search .= ($search ?
' ' :
'').$not.
'HEADER '.$rule[
'rulevalue'];
1452 if ($rule[
'type'] ==
'seen') {
1453 $search .= ($search ?
' ' :
'').$not.
'SEEN';
1455 if ($rule[
'type'] ==
'unseen') {
1456 $search .= ($search ?
' ' :
'').$not.
'UNSEEN';
1458 if ($rule[
'type'] ==
'unanswered') {
1459 $search .= ($search ?
' ' :
'').$not.
'UNANSWERED';
1461 if ($rule[
'type'] ==
'answered') {
1462 $search .= ($search ?
' ' :
'').$not.
'ANSWERED';
1464 if ($rule[
'type'] ==
'smaller') {
1465 $search .= ($search ?
' ' :
'').$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1467 if ($rule[
'type'] ==
'larger') {
1468 $search .= ($search ?
' ' :
'').$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1472 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1473 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1475 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1476 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1478 if ($rule[
'type'] ==
'withtrackingid') {
1479 $searchfilterdoltrackid++; $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1481 if ($rule[
'type'] ==
'withouttrackingid') {
1482 $searchfilternodoltrackid++; $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1485 if ($rule[
'type'] ==
'isanswer') {
1486 $searchfilterisanswer++; $searchhead .=
'/References.*@.*/';
1488 if ($rule[
'type'] ==
'isnotanswer') {
1489 $searchfilterisnotanswer++; $searchhead .=
'! /References.*@.*/';
1492 if ($rule[
'type'] ==
'replyto') {
1493 $searchfilterreplyto++; $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1497 if (empty($targetdir)) {
1499 if ($this->datelastok) {
1500 $fromdate = $this->datelastok;
1502 if ($fromdate > 0) {
1503 $search .= ($search ?
' ' :
'').
'SINCE '.date(
'j-M-Y', $fromdate - 1);
1512 $nbemailprocessed = 0;
1515 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1517 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1521 $f = $client->getFolders(
false, $this->source_directory);
1522 $Query = $f[0]->messages()->where($criteria);
1523 }
catch (InvalidWhereQueryCriteriaException $e) {
1524 $this->error = $e->getMessage();
1525 $this->errors[] = $this->error;
1526 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1529 $this->error = $e->getMessage();
1530 $this->errors[] = $this->error;
1531 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1538 $Query->leaveUnread();
1540 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1543 $this->error = $e->getMessage();
1544 $this->errors[] = $this->error;
1545 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1550 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1552 if ($arrayofemail ===
false) {
1554 $mapoferrrors = imap_errors();
1555 if ($mapoferrrors !==
false) {
1557 $this->error =
"Search string not understood - ".join(
',', $mapoferrrors);
1558 $this->errors[] = $this->error;
1563 $arrayofemailtodelete = array();
1566 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
1583 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1586 foreach ($arrayofemail as $imapemail) {
1587 if ($nbemailprocessed > 1000) {
1594 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1595 $header = $imapemail->getHeader()->raw;
1596 $overview = $imapemail->getAttributes();
1598 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1599 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1602 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1605 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches);
1606 $headers = array_combine($matches[1], $matches[2]);
1609 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1610 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1612 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1613 $headers[
'References'] = $headers[
'references'];
1615 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1616 $headers[
'Message-ID'] = $headers[
'message-id'];
1618 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1619 $headers[
'Subject'] = $headers[
'subject'];
1627 dol_syslog(
"** Process email ".$iforemailloop.
" References: ".$headers[
'References'].
" Subject: ".$headers[
'Subject']);
1630 $trackidfoundintorecipienttype =
'';
1631 $trackidfoundintorecipientid = 0;
1634 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)) {
1635 $trackidfoundintorecipienttype = $reg[1];
1636 $trackidfoundintorecipientid = $reg[2];
1637 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1638 $trackidfoundintorecipienttype =
'emailing';
1639 $trackidfoundintorecipientid = $reg[1];
1643 if ($searchfilterdoltrackid > 0) {
1644 if (empty($trackidfoundintorecipienttype)) {
1645 if (empty($headers[
'References']) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References'])) {
1646 $nbemailprocessed++;
1647 dol_syslog(
" Discarded - No suffix in email recipient and no Header References found matching signature of application so with a trackid");
1652 if ($searchfilternodoltrackid > 0) {
1653 if (!empty($trackidfoundintorecipienttype) || (!empty($headers[
'References']) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))) {
1654 $nbemailprocessed++;
1655 dol_syslog(
" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
1660 if ($searchfilterisanswer > 0) {
1661 if (empty($headers[
'In-Reply-To'])) {
1662 $nbemailprocessed++;
1663 dol_syslog(
" Discarded - Email is not an answer (no In-Reply-To header)");
1669 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) {
1676 $nbemailprocessed++;
1677 dol_syslog(
" Discarded - Email is not an answer (no RE prefix in subject)");
1681 if ($searchfilterisnotanswer > 0) {
1682 if (!empty($headers[
'In-Reply-To'])) {
1686 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) {
1692 $nbemailprocessed++;
1693 dol_syslog(
" Discarded - Email is an answer");
1701 $thirdpartystatic =
new Societe($this->
db);
1702 $contactstatic =
new Contact($this->
db);
1703 $projectstatic =
new Project($this->
db);
1705 $nbactiondoneforemail = 0;
1707 $errorforactions = 0;
1708 $thirdpartyfoundby =
'';
1709 $contactfoundby =
'';
1710 $projectfoundby =
'';
1711 $ticketfoundby =
'';
1712 $candidaturefoundby =
'';
1715 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1716 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".
dol_print_date($overview[
'date'],
'dayrfc',
'gmt').
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
1719 $overview[
'subject'] = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $overview[
'subject']);
1721 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);
1728 $overview[0]->subject = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $overview[0]->subject);
1732 global $htmlmsg, $plainmsg, $charset, $attachments;
1734 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1735 if ($imapemail->hasHTMLBody()) {
1736 $htmlmsg = $imapemail->getHTMLBody();
1738 if ($imapemail->hasTextBody()) {
1739 $plainmsg = $imapemail->getTextBody();
1741 if ($imapemail->hasAttachments()) {
1742 $attachments = $imapemail->getAttachments()->all();
1747 $this->
getmsg($connection, $imapemail);
1760 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
1761 dol_syslog(
" Discarded - Email body is not valid utf8");
1765 if ($searchfilterexcludebody) {
1766 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
1767 $nbemailprocessed++;
1768 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
1769 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
1830 $replytostring =
'';
1832 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1833 $fromstring = $overview[
'from'];
1836 $sender = $overview[
'sender'];
1837 $to = $overview[
'to'];
1838 $sendtocc = empty($overview[
'cc']) ?
'' : $overview[
'cc'];
1839 $sendtobcc = empty($overview[
'bcc']) ?
'' : $overview[
'bcc'];
1840 $date = $overview[
'date'];
1841 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1842 $subject = $overview[
'subject'];
1844 $fromstring = $overview[0]->from;
1847 $sender = $overview[0]->sender;
1848 $to = $overview[0]->to;
1849 $sendtocc = $overview[0]->cc;
1850 $sendtobcc = $overview[0]->bcc;
1851 $date = $overview[0]->udate;
1852 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1853 $subject = $overview[0]->subject;
1857 if ($searchfilterexcludesubject) {
1858 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
1859 $nbemailprocessed++;
1860 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
1861 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
1867 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
1869 $fromtext = $reg[1];
1871 $from = $fromstring;
1874 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
1876 $replytotext = $reg[1];
1878 $replyto = $replytostring;
1881 $fk_element_id = 0; $fk_element_type =
'';
1885 $contactid = 0; $thirdpartyid = 0; $projectid = 0; $ticketid = 0;
1893 $objectemail =
null;
1896 if (!empty($headers[
'References'])) {
1897 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
1901 foreach ($arrayofreferences as $reference) {
1903 if (!empty($trackidfoundintorecipienttype)) {
1904 $resultsearchtrackid = -1;
1905 $reg[1] = $trackidfoundintorecipienttype;
1906 $reg[2] = $trackidfoundintorecipientid;
1908 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
1909 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
1910 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
1914 if (!empty($resultsearchtrackid)) {
1916 $trackid = $reg[1].$reg[2];
1918 $objectid = $reg[2];
1920 if ($reg[1] ==
'thi') {
1923 if ($reg[1] ==
'ctc') {
1926 if ($reg[1] ==
'inv') {
1929 if ($reg[1] ==
'sinv') {
1932 if ($reg[1] ==
'pro') {
1933 $objectemail =
new Propal($this->
db);
1935 if ($reg[1] ==
'ord') {
1938 if ($reg[1] ==
'shi') {
1941 if ($reg[1] ==
'spro') {
1944 if ($reg[1] ==
'sord') {
1947 if ($reg[1] ==
'rec') {
1950 if ($reg[1] ==
'proj') {
1953 if ($reg[1] ==
'tas') {
1954 $objectemail =
new Task($this->
db);
1956 if ($reg[1] ==
'con') {
1959 if ($reg[1] ==
'use') {
1960 $objectemail =
new User($this->
db);
1962 if ($reg[1] ==
'tic') {
1963 $objectemail =
new Ticket($this->
db);
1965 if ($reg[1] ==
'recruitmentcandidature') {
1968 if ($reg[1] ==
'mem') {
1977 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
1979 if (!is_object($objectemail)) {
1980 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket where email_msgid = '".$this->
db->escape($reg[1]).
"'";
1983 $obj = $this->
db->fetch_object(
$resql);
1985 $objectid = $obj->rowid;
1986 $objectemail =
new Ticket($this->
db);
1987 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
1994 if (!is_object($objectemail)) {
1995 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->
db->escape($reg[1]).
"'";
1998 $obj = $this->
db->fetch_object(
$resql);
2000 $objectid = $obj->rowid;
2002 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2009 if (!is_object($objectemail)) {
2010 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->
db->escape($reg[1]).
"'";
2013 $obj = $this->
db->fetch_object(
$resql);
2015 $objectid = $obj->rowid;
2017 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2026 if (is_object($objectemail)) {
2027 $result = $objectemail->fetch($objectid);
2029 $fk_element_id = $objectemail->id;
2030 $fk_element_type = $objectemail->element;
2032 if ($fk_element_type ==
'facture') {
2033 $fk_element_type =
'invoice';
2036 if (get_class($objectemail) !=
'Societe') {
2037 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2039 $thirdpartyid = $objectemail->id;
2042 if (get_class($objectemail) !=
'Contact') {
2043 $contactid = $objectemail->fk_socpeople;
2045 $contactid = $objectemail->id;
2048 if (get_class($objectemail) !=
'Project') {
2049 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2051 $projectid = $objectemail->id;
2057 if ($projectid > 0) {
2058 $result = $projectstatic->fetch($projectid);
2060 $projectstatic->id = 0;
2062 $projectid = $projectstatic->id;
2064 $projectfoundby =
'trackid ('.$trackid.
')';
2066 if (empty($contactid)) {
2067 $contactid = $projectstatic->fk_contact;
2069 if (empty($thirdpartyid)) {
2070 $thirdpartyid = $projectstatic->fk_soc;
2075 if ($contactid > 0) {
2076 $result = $contactstatic->fetch($contactid);
2078 $contactstatic->id = 0;
2080 $contactid = $contactstatic->id;
2082 $contactfoundby =
'trackid ('.$trackid.
')';
2084 if (empty($thirdpartyid)) {
2085 $thirdpartyid = $contactstatic->fk_soc;
2090 if ($thirdpartyid > 0) {
2091 $result = $thirdpartystatic->fetch($thirdpartyid);
2093 $thirdpartystatic->id = 0;
2095 $thirdpartyid = $thirdpartystatic->id;
2097 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2102 if (is_object($objectemail)) {
2108 if (empty($contactid)) {
2109 $result = $contactstatic->fetch(0,
null,
'', $from);
2112 dol_syslog(
"We found a contact with the email ".$from);
2113 $contactid = $contactstatic->id;
2114 $contactfoundby =
'email of contact ('.$from.
')';
2115 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2116 $result = $thirdpartystatic->fetch($contactstatic->socid);
2118 $thirdpartyid = $thirdpartystatic->id;
2119 $thirdpartyfoundby =
'email of contact ('.$from.
')';
2125 if (empty($thirdpartyid)) {
2126 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
2128 dol_syslog(
"We found a thirdparty with the email ".$from);
2129 $thirdpartyid = $thirdpartystatic->id;;
2130 $thirdpartyfoundby =
'email ('.$from.
')';
2166 foreach ($this->actions as $operation) {
2167 $errorforthisaction = 0;
2169 if ($errorforactions) {
2172 if (empty($operation[
'status'])) {
2176 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2179 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2180 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2182 $actioncode =
'EMAIL_IN';
2184 if ($this->source_directory ==
'Sent') {
2185 $actioncode =
'EMAIL_OUT';
2188 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2190 $descriptiontitle = $langs->trans(
"RecordCreatedByEmailCollector", $this->ref, $msgid);
2193 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2195 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2197 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2199 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2203 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2204 if (empty($operation[
'actionparam'])) {
2206 $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;";
2207 $this->errors[] = $this->error;
2209 $actionparam = $operation[
'actionparam'];
2210 $idtouseforthirdparty =
'';
2211 $nametouseforthirdparty =
'';
2212 $emailtouseforthirdparty =
'';
2213 $namealiastouseforthirdparty =
'';
2215 $operationslog .=
'<br>Loop on each property to set into actionparam';
2219 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2223 $regforregex = array();
2225 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2226 $sourcefield = $regforregex[1];
2227 $regexstring = $regforregex[2];
2230 if (!empty($sourcefield) && !empty($regexstring)) {
2231 if (strtolower($sourcefield) ==
'body') {
2232 $sourcestring = $messagetext;
2233 } elseif (strtolower($sourcefield) ==
'subject') {
2234 $sourcestring = $subject;
2235 } elseif (strtolower($sourcefield) ==
'header') {
2236 $sourcestring = $header;
2239 if ($sourcestring) {
2240 $regforval = array();
2242 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2245 if ($propertytooverwrite ==
'id') {
2246 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2248 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2249 } elseif ($propertytooverwrite ==
'email') {
2250 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2252 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2253 } elseif ($propertytooverwrite ==
'name') {
2254 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2256 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2257 } elseif ($propertytooverwrite ==
'name_alias') {
2258 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2260 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2262 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> We discard this, not used to search existing thirdparty';
2266 $idtouseforthirdparty =
null;
2267 $nametouseforthirdparty =
null;
2268 $emailtouseforthirdparty =
null;
2269 $namealiastouseforthirdparty =
null;
2271 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2277 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2278 $this->errors[] = $this->error;
2280 $operationslog .=
'<br>'.$this->error;
2282 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2286 if ($propertytooverwrite ==
'id') {
2287 $idtouseforthirdparty = $reg[2];
2289 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
'We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2290 } elseif ($propertytooverwrite ==
'email') {
2291 $emailtouseforthirdparty = $reg[2];
2293 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
'We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2294 } elseif ($propertytooverwrite ==
'name') {
2295 $nametouseforthirdparty = $reg[2];
2297 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
'We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2298 } elseif ($propertytooverwrite ==
'name_alias') {
2299 $namealiastouseforthirdparty = $reg[2];
2301 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
'We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2305 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2306 $this->errors[] = $this->error;
2311 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2313 $operationslog .=
'<br>We have this data to search thirdparty: '.$idtouseforthirdparty.
' '.$emailtouseforthirdparty.
' '.$nametouseforthirdparty.
' '.$namealiastouseforthirdparty;
2315 $tmpobject =
new stdClass();
2316 $tmpobject->element ==
'generic';
2317 $tmpobject->id = $idtouseforthirdparty;
2318 $tmpobject->name = $nametouseforthirdparty;
2319 $tmpobject->name_alias = $namealiastouseforthirdparty;
2320 $tmpobject->email = $emailtouseforthirdparty;
2324 $idtouseforthirdparty = $tmpobject->id;
2325 $nametouseforthirdparty = $tmpobject->name;
2326 $namealiastouseforthirdparty = $tmpobject->name_alias;
2327 $emailtouseforthirdparty = $tmpobject->email;
2329 $operationslog .=
'<br>We try to search existing thirdparty with '.$idtouseforthirdparty.
' '.$emailtouseforthirdparty.
' '.$nametouseforthirdparty.
' '.$namealiastouseforthirdparty;
2331 $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', $emailtouseforthirdparty, $namealiastouseforthirdparty);
2334 $this->error =
'Error when getting thirdparty with name '.$nametouseforthirdparty.
' (may be 2 record exists with same name ?)';
2335 $this->errors[] = $this->error;
2337 } elseif ($result == 0) {
2338 if ($operation[
'type'] ==
'loadthirdparty') {
2339 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2342 $langs->load(
"errors");
2343 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2344 $this->errors[] = $this->error;
2345 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2346 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
2349 $thirdpartystatic =
new Societe($db);
2350 $thirdpartystatic->name = $nametouseforthirdparty;
2351 if (!empty($namealiastouseforthirdparty)) {
2352 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
2353 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
2356 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'': $fromtext) : $replytostring);
2358 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ?
'' : $from) : $replyto) : $emailtouseforthirdparty);
2361 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2363 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
2364 $thirdpartystatic->code_client =
'auto';
2366 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
2367 $thirdpartystatic->code_fournisseur =
'auto';
2370 if ($errorforthisaction) {
2373 $result = $thirdpartystatic->create($user);
2376 $this->error = $thirdpartystatic->error;
2377 $this->errors = $thirdpartystatic->errors;
2379 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag($thirdpartystatic->id);
2384 dol_syslog(
"One and only one existing third party has been found");
2386 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag($thirdpartystatic->id);
2390 } elseif ($operation[
'type'] ==
'recordevent') {
2394 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
2395 if ($alreadycreated == 0) {
2396 if ($projectstatic->id > 0) {
2397 if ($projectfoundby) {
2398 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
2401 if ($thirdpartystatic->id > 0) {
2402 if ($thirdpartyfoundby) {
2403 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2406 if ($contactstatic->id > 0) {
2407 if ($contactfoundby) {
2408 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2412 $description = $descriptiontitle;
2418 $descriptionfull = $description;
2419 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2420 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2425 $actioncomm->type_code =
'AC_OTH_AUTO';
2426 $actioncomm->code =
'AC_'.$actioncode;
2427 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
2428 $actioncomm->note_private = $descriptionfull;
2429 $actioncomm->fk_project = $projectstatic->id;
2430 $actioncomm->datep = $date;
2431 $actioncomm->datef = $date;
2432 $actioncomm->percentage = -1;
2433 $actioncomm->socid = $thirdpartystatic->id;
2434 $actioncomm->contact_id = $contactstatic->id;
2435 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id =>
'') : array());
2436 $actioncomm->authorid = $user->id;
2437 $actioncomm->userownerid = $user->id;
2439 $actioncomm->email_msgid = $msgid;
2440 $actioncomm->email_from = $fromstring;
2441 $actioncomm->email_sender = $sender;
2442 $actioncomm->email_to = $to;
2443 $actioncomm->email_tocc = $sendtocc;
2444 $actioncomm->email_tobcc = $sendtobcc;
2445 $actioncomm->email_subject = $subject;
2446 $actioncomm->errors_to =
'';
2448 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
2449 $actioncomm->fk_element = $fk_element_id;
2450 $actioncomm->elementid = $fk_element_id;
2451 $actioncomm->elementtype = $fk_element_type;
2452 if (is_object($objectemail) && $objectemail->module) {
2453 $actioncomm->elementtype .=
'@'.$objectemail->module;
2460 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2469 if ($errorforthisaction) {
2472 $result = $actioncomm->create($user);
2475 $this->errors = $actioncomm->errors;
2477 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag($actioncomm->id);
2481 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
2483 foreach ($pj as $key => $val) {
2484 $data[$val[
'filename']] =
getFileData($imapemail, $val[
'pos'], $val[
'type'], $connection);
2486 if (count($pj) > 0) {
2487 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->
db->escape($from).
"%'";
2489 if ($this->
db->num_rows(
$resql) == 0) {
2490 $this->errors[] =
'User Not allowed to add documents';
2492 $arrayobject = array(
2493 'propale' => array(
'table' =>
'propal',
2494 'fields' => array(
'ref'),
2495 'class' =>
'comm/propal/class/propal.class.php',
2496 'object' =>
'Propal'),
2497 'holiday' => array(
'table' =>
'holiday',
2498 'fields' => array(
'ref'),
2499 'class' =>
'holiday/class/holiday.class.php',
2500 'object' =>
'Holiday'),
2501 'expensereport' => array(
'table' =>
'expensereport',
2502 'fields' => array(
'ref'),
2503 'class' =>
'expensereport/class/expensereport.class.php',
2504 'object' =>
'ExpenseReport'),
2505 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
2506 'fields' => array(
'ref'),
2507 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
2508 'object' =>
'RecruitmentJobPosition'),
2509 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
2510 'fields' => array(
'ref'),
2511 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
2512 'object' =>
' RecruitmentCandidature'),
2513 'societe' => array(
'table' =>
'societe',
2514 'fields' => array(
'code_client',
'code_fournisseur'),
2515 'class' =>
'societe/class/societe.class.php',
2516 'object' =>
'Societe'),
2517 'commande' => array(
'table' =>
'commande',
2518 'fields' => array(
'ref'),
2519 'class' =>
'commande/class/commande.class.php',
2520 'object' =>
'Commande'),
2521 'expedition' => array(
'table' =>
'expedition',
2522 'fields' => array(
'ref'),
2523 'class' =>
'expedition/class/expedition.class.php',
2524 'object' =>
'Expedition'),
2525 'contract' => array(
'table' =>
'contrat',
2526 'fields' => array(
'ref'),
2527 'class' =>
'contrat/class/contrat.class.php',
2528 'object' =>
'Contrat'),
2529 'fichinter' => array(
'table' =>
'fichinter',
2530 'fields' => array(
'ref'),
2531 'class' =>
'fichinter/class/fichinter.class.php',
2532 'object' =>
'Fichinter'),
2533 'ticket' => array(
'table' =>
'ticket',
2534 'fields' => array(
'ref'),
2535 'class' =>
'ticket/class/ticket.class.php',
2536 'object' =>
'Ticket'),
2537 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
2538 'fields' => array(
'ref'),
2539 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
2540 'object' =>
'KnowledgeRecord'),
2541 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
2542 'fields' => array(
'ref'),
2543 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
2544 'object' =>
'SupplierProposal'),
2545 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
2546 'fields' => array(
'ref',
'ref_supplier'),
2547 'class' =>
'fourn/class/fournisseur.commande.class.php',
2548 'object' =>
'SupplierProposal'),
2549 'facture' => array(
'table' =>
'facture',
2550 'fields' => array(
'ref'),
2551 'class' =>
'compta/facture/class/facture.class.php',
2552 'object' =>
'Facture'),
2553 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
2554 'fields' => array(
'ref',
'ref_client'),
2555 'class' =>
'fourn/class/fournisseur.facture.class.php',
2556 'object' =>
'FactureFournisseur'),
2557 'produit' => array(
'table' =>
'product',
2558 'fields' => array(
'ref'),
2559 'class' =>
'product/class/product.class.php',
2560 'object' =>
'Product'),
2561 'productlot' => array(
'table' =>
'product_lot',
2562 'fields' => array(
'batch'),
2563 'class' =>
'product/stock/class/productlot.class.php',
2564 'object' =>
'Productlot'),
2565 'projet' => array(
'table' =>
'projet',
2566 'fields' => array(
'ref'),
2567 'class' =>
'projet/class/projet.class.php',
2568 'object' =>
'Project'),
2569 'projet_task' => array(
'table' =>
'projet_task',
2570 'fields' => array(
'ref'),
2571 'class' =>
'projet/class/task.class.php',
2572 'object' =>
'Task'),
2573 'ressource' => array(
'table' =>
'resource',
2574 'fields' => array(
'ref'),
2575 'class' =>
'ressource/class/dolressource.class.php',
2576 'object' =>
'Dolresource'),
2577 'bom' => array(
'table' =>
'bom_bom',
2578 'fields' => array(
'ref'),
2579 'class' =>
'bom/class/bom.class.php',
2581 'mrp' => array(
'table' =>
'mrp_mo',
2582 'fields' => array(
'ref'),
2583 'class' =>
'mrp/class/mo.class.php',
2587 if (!is_object($hookmanager)) {
2588 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
2591 $hookmanager->initHooks(array(
'emailcolector'));
2592 $parameters = array(
'arrayobject' => $arrayobject);
2593 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
2595 $arrayobject = $hookmanager->resArray;
2598 $resultobj = array();
2600 foreach ($arrayobject as $key => $objectdesc) {
2601 $sql =
'SELECT DISTINCT t.rowid ';
2602 $sql .=
' FROM ' . MAIN_DB_PREFIX . $objectdesc[
'table'] .
' AS t';
2604 foreach ($objectdesc[
'fields'] as $field) {
2605 $sql .=
"'" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $field .
", '%') OR ";
2607 $sql = substr($sql, 0, -4);
2609 $ressqlobj = $this->
db->query($sql);
2611 while ($obj = $this->
db->fetch_object($ressqlobj)) {
2612 $resultobj[$key][] = $obj->rowid;
2617 foreach ($resultobj as $mod => $ids) {
2618 $moddesc = $arrayobject[$mod];
2619 $elementpath = $mod;
2621 $objectmanaged =
new $moddesc[
'object']($this->db);
2622 foreach ($ids as $val) {
2623 $res = $objectmanaged->fetch($val);
2625 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
2626 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
2628 $this->errors[] =
'object not found';
2632 foreach ($dirs as $target) {
2633 foreach ($data as $filename => $content) {
2634 $prefix = $this->actions[$this->id][
'actionparam'];
2636 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
2638 $this->errors[] =
'Doc not saved';
2643 $operationslog .=
'<br>Save attachment files on disk';
2645 $this->errors[] =
'no joined piece';
2647 $operationslog .=
'<br>No joinded files';
2649 } elseif ($operation[
'type'] ==
'project') {
2651 $projecttocreate =
new Project($this->
db);
2652 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
2653 if ($alreadycreated == 0) {
2654 if ($thirdpartystatic->id > 0) {
2655 $projecttocreate->socid = $thirdpartystatic->id;
2656 if ($thirdpartyfoundby) {
2657 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2660 if ($contactstatic->id > 0) {
2661 $projecttocreate->contact_id = $contactstatic->id;
2662 if ($contactfoundby) {
2663 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2667 $description = $descriptiontitle;
2673 $descriptionfull = $description;
2674 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2675 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2680 $percent_opp_status =
dol_getIdFromCode($this->
db,
'PROSP',
'c_lead_status',
'code',
'percent');
2682 $projecttocreate->title = $subject;
2683 $projecttocreate->date_start = $date;
2684 $projecttocreate->date_end =
'';
2685 $projecttocreate->opp_status = $id_opp_status;
2686 $projecttocreate->opp_percent = $percent_opp_status;
2688 $projecttocreate->note_private = $descriptionfull;
2689 $projecttocreate->entity = $conf->entity;
2690 $projecttocreate->email_msgid = $msgid;
2692 $savesocid = $projecttocreate->socid;
2696 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2699 if (empty($projecttocreate->ref)) {
2702 $modele = empty($conf->global->PROJECT_ADDON) ?
'mod_project_simple' : $conf->global->PROJECT_ADDON;
2705 $file =
''; $classname =
''; $filefound = 0; $reldir =
'';
2706 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
2707 foreach ($dirmodels as $reldir) {
2708 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
2709 if (file_exists($file)) {
2711 $classname = $modele;
2717 if ($savesocid > 0) {
2718 if ($savesocid != $projecttocreate->socid) {
2720 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');
2723 if ($projecttocreate->socid > 0) {
2724 $thirdpartystatic->fetch($projecttocreate->socid);
2728 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
2729 $modModuleToUseForNextValue =
new $classname;
2730 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic :
null), $projecttocreate);
2732 $projecttocreate->ref = $defaultref;
2736 if ($errorforthisaction) {
2739 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
2741 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
2744 $result = $projecttocreate->create($user);
2747 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
2748 $this->errors = $projecttocreate->errors;
2751 $destdir = $conf->project->dir_output.
'/'.$projecttocreate->ref;
2755 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
2756 foreach ($attachments as $attachment) {
2757 $attachment->save($destdir.
'/');
2760 $this->
getmsg($connection, $imapemail, $destdir);
2763 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag($projecttocreate->id);
2765 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag($projecttocreate->id);
2773 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
2775 } elseif ($operation[
'type'] ==
'ticket') {
2777 $tickettocreate =
new Ticket($this->
db);
2779 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2780 if ($alreadycreated == 0) {
2781 if ($thirdpartystatic->id > 0) {
2782 $tickettocreate->socid = $thirdpartystatic->id;
2783 $tickettocreate->fk_soc = $thirdpartystatic->id;
2784 if ($thirdpartyfoundby) {
2785 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2788 if ($contactstatic->id > 0) {
2789 $tickettocreate->contact_id = $contactstatic->id;
2790 if ($contactfoundby) {
2791 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2795 $description = $descriptiontitle;
2801 $descriptionfull = $description;
2802 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2803 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2807 $tickettocreate->subject = $subject;
2808 $tickettocreate->message = $description;
2809 $tickettocreate->type_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE :
dol_getIdFromCode($this->
db, 1,
'c_ticket_type',
'use_default',
'code', 1));
2810 $tickettocreate->category_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE :
dol_getIdFromCode($this->
db, 1,
'c_ticket_category',
'use_default',
'code', 1));
2811 $tickettocreate->severity_code = (!empty($conf->global->MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE) ? $conf->global->MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE :
dol_getIdFromCode($this->
db, 1,
'c_ticket_severity',
'use_default',
'code', 1));
2812 $tickettocreate->origin_email = $from;
2813 $tickettocreate->fk_user_create = $user->id;
2814 $tickettocreate->datec =
dol_now();
2815 $tickettocreate->fk_project = $projectstatic->id;
2816 $tickettocreate->notify_tiers_at_create = 0;
2817 $tickettocreate->note_private = $descriptionfull;
2818 $tickettocreate->entity = $conf->entity;
2819 $tickettocreate->email_msgid = $msgid;
2820 $tickettocreate->email_date = $date;
2823 $savesocid = $tickettocreate->socid;
2827 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2830 if (empty($tickettocreate->ref)) {
2833 $modele = empty($conf->global->TICKET_ADDON) ?
'mod_ticket_simple' : $conf->global->TICKET_ADDON;
2836 $file =
''; $classname =
''; $filefound = 0; $reldir =
'';
2837 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
2838 foreach ($dirmodels as $reldir) {
2839 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
2840 if (file_exists($file)) {
2842 $classname = $modele;
2848 if ($savesocid > 0) {
2849 if ($savesocid != $tickettocreate->socid) {
2851 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');
2854 if ($tickettocreate->socid > 0) {
2855 $thirdpartystatic->fetch($tickettocreate->socid);
2860 $modModuleToUseForNextValue =
new $classname;
2861 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic :
null), $tickettocreate);
2863 $tickettocreate->ref = $defaultref;
2866 if ($errorforthisaction) {
2869 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
2871 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
2874 $result = $tickettocreate->create($user);
2877 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
2878 $this->errors = $tickettocreate->errors;
2881 $destdir = $conf->ticket->dir_output.
'/'.$tickettocreate->ref;
2885 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
2886 foreach ($attachments as $attachment) {
2887 $attachment->save($destdir.
'/');
2890 $this->
getmsg($connection, $imapemail, $destdir);
2893 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag($tickettocreate->id);
2895 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag($tickettocreate->id);
2901 } elseif ($operation[
'type'] ==
'candidature') {
2905 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
2906 if ($alreadycreated == 0) {
2907 $description = $descriptiontitle;
2913 $descriptionfull = $description;
2914 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2917 $candidaturetocreate->subject = $subject;
2918 $candidaturetocreate->message = $description;
2919 $candidaturetocreate->type_code = 0;
2920 $candidaturetocreate->category_code =
null;
2921 $candidaturetocreate->severity_code =
null;
2922 $candidaturetocreate->email = $from;
2924 $candidaturetocreate->fk_user_creat = $user->id;
2925 $candidaturetocreate->date_creation =
dol_now();
2926 $candidaturetocreate->fk_project = $projectstatic->id;
2927 $candidaturetocreate->description = $description;
2928 $candidaturetocreate->note_private = $descriptionfull;
2929 $candidaturetocreate->entity = $conf->entity;
2930 $candidaturetocreate->email_msgid = $msgid;
2931 $candidaturetocreate->email_date = $date;
2932 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
2937 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2979 if ($errorforthisaction) {
2983 $result = $candidaturetocreate->create($user);
2986 $this->error =
'Failed to create candidature: '.join(
', ', $candidaturetocreate->errors);
2987 $this->errors = $candidaturetocreate->errors;
2990 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag($candidaturetocreate->id);
2993 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
2996 if (!is_object($hookmanager)) {
2997 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3001 $parameters = array(
3002 'connection'=> $connection,
3003 'imapemail'=>$imapemail,
3004 'overview'=>$overview,
3007 'fromtext' => $fromtext,
3009 'actionparam'=> $operation[
'actionparam'],
3011 'thirdpartyid' => $thirdpartyid,
3012 'objectid'=> $objectid,
3013 'objectemail'=> $objectemail,
3015 'messagetext'=>$messagetext,
3016 'subject'=>$subject,
3018 'attachments'=>$attachments,
3020 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3023 $errorforthisaction++;
3024 $this->error = $hookmanager->resPrint;
3026 if ($errorforthisaction) {
3028 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3030 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3034 if (!$errorforactions) {
3035 $nbactiondoneforemail++;
3041 if (!$errorforactions) {
3042 if (!empty($targetdir)) {
3043 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
3045 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3047 $imapemail->move($targetdir);
3050 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".((
string) $imapemail).
" to ".$connectstringtarget, LOG_DEBUG);
3051 $operationslog .=
'<br>Move mail '.((string) $imapemail).
' - '.$msgid;
3053 $arrayofemailtodelete[$imapemail] = $msgid;
3056 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
3057 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);
3059 dol_syslog(
"EmailCollector::doCollectOneCollector message ".((
string) $imapemail).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3067 unset($objectemail);
3068 unset($projectstatic);
3069 unset($thirdpartystatic);
3070 unset($contactstatic);
3072 $nbemailprocessed++;
3074 if (!$errorforemail) {
3075 $nbactiondone += $nbactiondoneforemail;
3079 $this->
db->commit();
3081 $this->
db->rollback();
3085 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3086 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3092 $this->
db->rollback();
3096 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3098 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3100 $output = $langs->trans(
'NoNewEmailToProcess');
3104 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
3105 $client->disconnect();
3107 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
3108 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
3110 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid;
3112 if (empty($mode) && empty($error)) {
3113 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
3114 if ($res ==
false) {
3116 $this->error = imap_last_error();
3117 $this->errors[] = $this->error;
3119 $operationslog .=
'<br>Error in move '.$this->error;
3126 if (empty($mode) && empty($error)) {
3128 $operationslog .=
"<br>Expunge";
3130 imap_expunge($connection);
3132 imap_close($connection);
3135 $this->datelastresult = $now;
3136 $this->lastresult = $output;
3137 $this->debuginfo .=
'IMAP search string used : '.$search;
3139 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
3141 if ($operationslog) {
3142 $this->debuginfo .= $operationslog;
3145 if (empty($error) && empty($mode)) {
3146 $this->datelastok = $now;
3149 if (!empty($this->errors)) {
3150 $this->lastresult .=
"<br>".join(
"<br>", $this->errors);
3152 $this->codelastresult = ($error ?
'KO' :
'OK');
3158 dol_syslog(
"EmailCollector::doCollectOneCollector end", LOG_INFO);
3160 return $error ? -1 : 1;
3175 private function getmsg($mbox, $mid, $destdir =
'')
3179 global $charset, $htmlmsg, $plainmsg, $attachments;
3180 $htmlmsg = $plainmsg = $charset =
'';
3181 $attachments = array();
3188 $s = imap_fetchstructure($mbox, $mid, FT_UID);
3193 $this->
getpart($mbox, $mid, $s, 0);
3196 foreach ($s->parts as $partno0 => $p) {
3197 $this->
getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
3228 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
3231 global $htmlmsg, $plainmsg, $charset, $attachments;
3235 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
3236 imap_body($mbox, $mid, FT_UID);
3238 if ($p->encoding == 4) {
3239 $data = quoted_printable_decode($data);
3240 } elseif ($p->encoding == 3) {
3241 $data = base64_decode($data);
3247 if ($p->parameters) {
3248 foreach ($p->parameters as $x) {
3249 $params[strtolower($x->attribute)] = $x->value;
3252 if ($p->dparameters) {
3253 foreach ($p->dparameters as $x) {
3254 $params[strtolower($x->attribute)] = $x->value;
3261 if ($params[
'filename'] || $params[
'name']) {
3263 $filename = ($params[
'filename']) ? $params[
'filename'] : $params[
'name'];
3265 $attachments[$filename] = $data;
3268 $file_name_complete = $params[
'filename'];
3271 $destination = $destdir.
'/'.$file_name_complete;
3274 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
3277 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
3280 $file_name_original = $file_name;
3289 while (file_exists($destdir.
"/".$file_name.
".".$extension)) {
3290 $file_name = $file_name_original .
' (' . $num .
')';
3291 $file_name_complete = $file_name .
"." . $extension;
3292 $destination = $destdir.
'/'.$file_name_complete;
3298 file_put_contents($destination, $data);
3302 if ($p->type == 0 && $data) {
3303 if (!empty($params[
'charset'])) {
3308 if (strtolower($p->subtype) ==
'plain') {
3309 $plainmsg .= trim($data).
"\n\n";
3311 $htmlmsg .= $data.
"<br><br>";
3313 $charset = $params[
'charset'];
3314 } elseif ($p->type == 2 && $data) {
3320 if (!empty($params[
'charset'])) {
3323 $plainmsg .= $data.
"\n\n";
3328 foreach ($p->parts as $partno0 => $p2) {
3329 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1));
3345 if (!$string || $fromEncoding == $toEncoding) {
3348 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
3349 if (!$convertedString && extension_loaded(
'mbstring')) {
3350 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
3352 if (!$convertedString) {
3353 throw new Exception(
'Mime string encoding conversion failed');
3355 return $convertedString;
3374 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
3375 $elements = imap_mime_header_decode($subject);
3377 if (!empty($elements)) {
3378 $num = count($elements);
3379 for ($i = 0; $i < $num; $i++) {
3380 $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));
3381 $newstring .= $stringinutf8;
3383 $subject = $newstring;
3385 } elseif (!function_exists(
'mb_decode_mimeheader')) {
3386 $subject = mb_decode_mimeheader($subject);
3387 } elseif (function_exists(
'iconv_mime_decode')) {
3388 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
3403 $text = preg_replace(
'/[\x{1F600}-\x{1F64F}]/u',
'', $text);
3404 $text = preg_replace(
'/[\x{1F300}-\x{1F5FF}]/u',
'', $text);
3405 $text = preg_replace(
'/[\x{1F680}-\x{1F6FF}]/u',
'', $text);
3406 $text = preg_replace(
'/[\x{2600}-\x{26FF}]/u',
'', $text);
3407 $text = preg_replace(
'/[\x{2700}-\x{27BF}]/u',
'', $text);
3408 $text = preg_replace(
'/[\x{1F900}-\x{1F9FF}]/u',
'', $text);
3409 $text = preg_replace(
'/[\x{1F1E0}-\x{1F1FF}]/u',
'', $text);
Class to manage agenda events (actions)
Class to manage members of a foundation.
Class to manage predefined suppliers products.
Class to manage customers orders.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetchCommon($id, $ref=null, $morewhere='')
Load object in memory from the database.
createCommon(User $user, $notrigger=false)
Create object into database.
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
updateCommon(User $user, $notrigger=false)
Update object into database.
Class to manage Dolibarr database access.
Class for EmailCollectorAction.
Class for EmailCollectorFilter.
Class for EmailCollector.
fetch($id, $ref=null)
Load object in memory from the database.
createFromClone(User $user, $fromid)
Clone and object into another one.
create(User $user, $notrigger=false)
Create object into database.
update(User $user, $notrigger=false)
Update object into database.
convertStringEncoding($string, $fromEncoding, $toEncoding='UTF-8')
Converts a string from one encoding to another.
overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject, $header, &$operationslog)
overwitePropertiesOfObject
__construct(DoliDB $db)
Constructor.
getpart($mbox, $mid, $p, $partno, $destdir='')
Sub function for getpart().
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
removeEmoji($text)
Remove EMoji from email content.
getEncodedUtf7($str)
Convert str to UTF-7 imap default mailbox names.
decodeSMTPSubject($subject)
Decode a subject string according to RFC2047 Example: '=?Windows-1252?Q?RE=A0:_ABC?...
fetchFilters()
Fetch filters.
LibStatut($status, $mode=0)
Return the status.
fetchActions()
Fetch actions.
fetchAll(User $user, $activeOnly=0, $sortfield='s.rowid', $sortorder='ASC', $limit=100, $page=0)
Load object lines in memory from the database.
getConnectStringIMAP($ssl=1, $norsh=0)
Return the connectstring to use with IMAP connection function.
info($id)
Charge les informations d'ordre info dans l'objet commande.
getmsg($mbox, $mid, $destdir='')
getmsg
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionaly the picto)
doCollectOneCollector($mode=0)
Execute collect for current collector loaded previously with fetch.
doCollect()
Action executed by scheduler CAN BE A CRON TASK.
getLibStatut($mode=0)
Return label of the status.
Class to manage shipments.
Class to manage suppliers invoices.
Class to manage invoices.
Class to manage projects.
Class to manage proposals.
Class to manage receptions.
Class for RecruitmentCandidature.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage price ask supplier.
Class to manage translations.
Class to manage Dolibarr users.
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
saveAttachment($path, $filename, $data)
Save joined file into a directory with a given name.
getFileData($jk, $fpos, $type, $mbox)
Get content of a joined file from its position into a given email.
getAttachments($jk, $mbox)
Get attachments of a given mail.
dol_is_dir($folder)
Test if filename is a directory.
dolExplodeIntoArray($string, $delimiter=';', $kv='=')
Split a string with 2 keys into key array.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
utf8_valid($str)
Check if a string is in UTF8.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '…' if string larger than length.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_sanitizePathName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a path name.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Class to generate the form for creating a new ticket.
dolEncrypt($chain, $key='', $ciphering='AES-256-CTR', $forceseed='')
Encode a string with a symetric encryption.
dolDecrypt($chain, $key='')
Decode a string with a symetric encryption.
$conf db
API class for accounts.