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 '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'),
135 '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),
136 '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'=>
''),
137 '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'),
138 'password' => array(
'type'=>
'password',
'label'=>
'Password',
'visible'=>-1,
'enabled'=>
"1",
'position'=>103,
'notnull'=>-1,
'comment'=>
"IMAP password",
'help'=>
'WithGMailYouCanCreateADedicatedPassword'),
139 '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'),
140 'source_directory' => array(
'type'=>
'varchar(255)',
'label'=>
'MailboxSourceDirectory',
'visible'=>-1,
'enabled'=>1,
'position'=>104,
'notnull'=>1,
'default' =>
'Inbox',
'help'=>
'Example: INBOX'),
141 'target_directory' => array(
'type'=>
'varchar(255)',
'label'=>
'MailboxTargetDirectory',
'visible'=>1,
'enabled'=>1,
'position'=>110,
'notnull'=>0,
'help'=>
"EmailCollectorTargetDir"),
142 'maxemailpercollect' => array(
'type'=>
'integer',
'label'=>
'MaxEmailCollectPerCollect',
'visible'=>-1,
'enabled'=>1,
'position'=>111,
'default'=>100),
143 'datelastresult' => array(
'type'=>
'datetime',
'label'=>
'DateLastCollectResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>121,
'notnull'=>-1,
'csslist'=>
'nowraponall'),
144 'codelastresult' => array(
'type'=>
'varchar(16)',
'label'=>
'CodeLastResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>122,
'notnull'=>-1,),
145 'lastresult' => array(
'type'=>
'varchar(255)',
'label'=>
'LastResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>123,
'notnull'=>-1,
'cssview'=>
'small',
'csslist'=>
'small tdoverflowmax200'),
146 'datelastok' => array(
'type'=>
'datetime',
'label'=>
'DateLastcollectResultOk',
'visible'=>1,
'enabled'=>
'$action != "create"',
'position'=>125,
'notnull'=>-1,
'csslist'=>
'nowraponall'),
147 'note_public' => array(
'type'=>
'html',
'label'=>
'NotePublic',
'visible'=>0,
'enabled'=>1,
'position'=>61,
'notnull'=>-1,),
148 'note_private' => array(
'type'=>
'html',
'label'=>
'NotePrivate',
'visible'=>0,
'enabled'=>1,
'position'=>62,
'notnull'=>-1,),
149 'date_creation' => array(
'type'=>
'datetime',
'label'=>
'DateCreation',
'visible'=>-2,
'enabled'=>1,
'position'=>500,
'notnull'=>1,),
150 'tms' => array(
'type'=>
'timestamp',
'label'=>
'DateModification',
'visible'=>-2,
'enabled'=>1,
'position'=>501,
'notnull'=>1,),
152 'fk_user_creat' => array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserAuthor',
'visible'=>-2,
'enabled'=>1,
'position'=>510,
'notnull'=>1,),
153 'fk_user_modif' => array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserModif',
'visible'=>-2,
'enabled'=>1,
'position'=>511,
'notnull'=>-1,),
155 'import_key' => array(
'type'=>
'varchar(14)',
'label'=>
'ImportId',
'visible'=>-2,
'enabled'=>1,
'position'=>1000,
'notnull'=>-1,),
156 'status' => array(
'type'=>
'integer',
'label'=>
'Status',
'visible'=>1,
'enabled'=>1,
'position'=>1000,
'notnull'=>1,
'index'=>1,
'arrayofkeyval'=>array(
'0'=>
'Inactive',
'1'=>
'Active'))
189 public $date_creation;
199 public $fk_user_creat;
204 public $fk_user_modif;
217 public $oauth_service;
218 public $imap_encryption;
220 public $source_directory;
221 public $target_directory;
222 public $maxemailpercollect;
227 public $datelastresult;
229 public $codelastresult;
239 const STATUS_DISABLED = 0;
240 const STATUS_ENABLED = 1;
250 global $conf, $langs;
254 if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields[
'rowid'])) {
255 $this->fields[
'rowid'][
'visible'] = 0;
257 if (!
isModEnabled(
'multicompany') && isset($this->fields[
'entity'])) {
258 $this->fields[
'entity'][
'enabled'] = 0;
262 $oauthservices = array();
264 foreach ($conf->global as $key => $val) {
265 if (!empty($val) && preg_match(
'/^OAUTH_.*_ID$/', $key)) {
266 $key = preg_replace(
'/^OAUTH_/',
'', $key);
267 $key = preg_replace(
'/_ID$/',
'', $key);
268 if (preg_match(
'/^.*-/', $key)) {
269 $name = preg_replace(
'/^.*-/',
'', $key);
271 $name = $langs->trans(
"NoName");
273 $provider = preg_replace(
'/-.*$/',
'', $key);
274 $provider = ucfirst(strtolower($provider));
276 $oauthservices[$key] = $name.
" (".$provider.
")";
280 $this->fields[
'oauth_service'][
'arrayofkeyval'] = $oauthservices;
283 foreach ($this->fields as $key => $val) {
284 if (isset($val[
'enabled']) && empty($val[
'enabled'])) {
285 unset($this->fields[$key]);
290 foreach ($this->fields as $key => $val) {
291 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
292 foreach ($val[
'arrayofkeyval'] as $key2 => $val2) {
293 $this->fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
311 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
312 $langs->load(
"errors");
313 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
317 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
318 $this->password =
dolEncrypt($this->password);
322 $this->password =
dolDecrypt($this->password);
324 if (is_array($this->filters) && count($this->filters)) {
327 foreach ($this->filters as $filter) {
328 $emailcollectorfilter->type = $filter[
'type'];
329 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
330 $emailcollectorfilter->fk_emailcollector = $this->id;
331 $emailcollectorfilter->status = $filter[
'status'];
333 $emailcollectorfilter->create($user);
337 if (is_array($this->actions) && count($this->actions)) {
340 foreach ($this->actions as $operation) {
341 $emailcollectoroperation->type = $operation[
'type'];
342 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
343 $emailcollectoroperation->fk_emailcollector = $this->id;
344 $emailcollectoroperation->status = $operation[
'status'];
345 $emailcollectoroperation->position = $operation[
'position'];
347 $emailcollectoroperation->create($user);
363 global $langs, $extrafields;
368 $object =
new self($this->db);
373 $object->fetchCommon($fromid);
375 $object->fetchFilters();
376 $object->fetchActions();
380 unset($object->fk_user_creat);
381 unset($object->import_key);
382 unset($object->password);
385 $object->ref =
"copy_of_".$object->ref;
386 $object->label = $langs->trans(
"CopyOf").
" ".$object->label;
387 if (empty($object->host)) {
388 $object->host =
'imap.example.com';
391 if (is_array($object->array_options) && count($object->array_options) > 0) {
392 $extrafields->fetch_name_optionals_label($this->table_element);
393 foreach ($object->array_options as $key => $option) {
394 $shortkey = preg_replace(
'/options_/',
'', $key);
395 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
397 unset($object->array_options[$key]);
403 $object->context[
'createfromclone'] =
'createfromclone';
404 $result = $object->create($user);
407 $this->error = $object->error;
408 $this->errors = $object->errors;
411 unset($object->context[
'createfromclone']);
418 $this->db->rollback();
430 public function fetch($id, $ref =
null)
434 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
435 $this->password =
dolDecrypt($this->password);
468 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
474 $sql =
"SELECT s.rowid";
475 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
476 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
478 $sql .=
" AND s.status = 1";
480 $sql .= $this->db->order($sortfield, $sortorder);
485 $offset = $limit * $page;
487 $sql .= $this->db->plimit($limit + 1, $offset);
490 $result = $this->db->query(
$sql);
492 $num = $this->db->num_rows($result);
495 $obj = $this->db->fetch_object($result);
497 if ($emailcollector_static->fetch($obj->rowid)) {
498 $obj_ret[] = $emailcollector_static;
503 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
504 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
507 if (!count($obj_ret)) {
508 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
526 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
527 $langs->load(
"errors");
528 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
532 include_once DOL_DOCUMENT_ROOT.
'/core/lib/security.lib.php';
533 $this->password =
dolEncrypt($this->password);
537 $this->password =
dolDecrypt($this->password);
549 public function delete(
User $user, $notrigger =
false)
564 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
566 global $conf, $langs, $action, $hookmanager;
568 if (!empty($conf->dol_no_mouse_hover)) {
574 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
576 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
578 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
580 if ($option !=
'nolink') {
582 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
583 if ($save_lastsearch_value == -1 && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
584 $add_save_lastsearch_values = 1;
586 if ($add_save_lastsearch_values) {
587 $url .=
'&save_lastsearch_values=1';
592 if (empty($notooltip)) {
593 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
594 $label = $langs->trans(
"ShowEmailCollector");
595 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
597 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
598 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
600 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
603 $linkstart =
'<a href="'.$url.
'"';
604 $linkstart .= $linkclose.
'>';
607 $result .= $linkstart;
609 $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);
611 if ($withpicto != 2) {
612 $result .= $this->ref;
617 $hookmanager->initHooks(array(
'emailcollectordao'));
618 $parameters = array(
'id'=>$this->
id,
'getnomurl' => &$result);
619 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
621 $result = $hookmanager->resPrint;
623 $result .= $hookmanager->resPrint;
637 return $this->
LibStatut($this->status, $mode);
651 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
654 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
655 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
656 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
657 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
660 $statusType =
'status5';
661 if ($status == self::STATUS_ENABLED) {
662 $statusType =
'status4';
665 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
676 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
677 $sql .=
' fk_user_creat, fk_user_modif';
678 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
679 $sql .=
' WHERE t.rowid = '.((int) $id);
680 $result = $this->db->query(
$sql);
682 if ($this->db->num_rows($result)) {
683 $obj = $this->db->fetch_object($result);
684 $this->
id = $obj->rowid;
686 $this->user_creation_id = $obj->fk_user_creat;
687 $this->user_modification_id = $obj->fk_user_modif;
688 $this->date_creation = $this->db->jdate($obj->datec);
689 $this->date_modification = empty($obj->datem) ?
'' : $this->db->jdate($obj->datem);
692 $this->db->free($result);
706 $this->host =
'localhost';
707 $this->login =
'alogin';
720 $this->filters = array();
722 $sql =
'SELECT rowid, type, rulevalue, status';
723 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
724 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
727 $resql = $this->db->query(
$sql);
729 $num = $this->db->num_rows($resql);
732 $obj = $this->db->fetch_object($resql);
733 $this->filters[$obj->rowid] = array(
'id'=>$obj->rowid,
'type'=>$obj->type,
'rulevalue'=>$obj->rulevalue,
'status'=>$obj->status);
736 $this->db->free($resql);
752 $this->actions = array();
754 $sql =
'SELECT rowid, type, actionparam, status';
755 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
756 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
757 $sql .=
' ORDER BY position';
759 $resql = $this->db->query(
$sql);
761 $num = $this->db->num_rows($resql);
764 $obj = $this->db->fetch_object($resql);
765 $this->actions[$obj->rowid] = array(
'id'=>$obj->rowid,
'type'=>$obj->type,
'actionparam'=>$obj->actionparam,
'status'=>$obj->status);
768 $this->db->free($resql);
789 $flags =
'/service=imap';
790 if (!empty($conf->global->IMAP_FORCE_TLS)) {
792 } elseif (empty($this->imap_encryption) || ($this->imap_encryption ==
'ssl' && !empty($conf->global->IMAP_FORCE_NOSSL))) {
795 $flags .=
'/' . $this->imap_encryption;
798 $flags .=
'/novalidate-cert';
801 if (!empty($this->norsh) || !empty($conf->global->IMAP_FORCE_NORSH)) {
805 if (strpos($this->login,
'/') !=
false) {
806 $partofauth = explode(
'/', $this->login);
807 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
810 $connectstringserver =
'{'.$this->host.
':'.$this->port.$flags.
'}';
812 return $connectstringserver;
823 if (function_exists(
'mb_convert_encoding')) {
825 $str = preg_replace(
"/ /",
"xyxy", $str);
827 if ($str = mb_convert_encoding($str,
"UTF-7")) {
829 $str = preg_replace(
"/\+A/",
"&A", $str);
831 $str = preg_replace(
"/xyxy/",
" ", $str);
835 $this->error =
"error: is not possible to encode this string '".$str.
"'";
855 $arrayofcollectors = $this->
fetchAll($user, 1);
858 foreach ($arrayofcollectors as $emailcollector) {
859 $result = $emailcollector->doCollectOneCollector(0);
860 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
862 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
863 if (!empty($emailcollector->errors)) {
864 $this->error .= join(
'<br>', $emailcollector->errors);
866 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
885 global $conf, $langs;
887 $errorforthisaction = 0;
890 $outputlangs = $langs;
893 $newlang =
GETPOST(
'lang_id',
'aZ09');
896 $newlang = $object->thirdparty->default_lang;
898 if (!empty($newlang)) {
900 $outputlangs->setDefaultLang($newlang);
910 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
913 $tmparray = explode(
'.', $propertytooverwrite);
914 if (count($tmparray) == 2) {
915 $tmpclass = $tmparray[0];
916 $tmpproperty = $tmparray[1];
918 $tmpproperty = $tmparray[0];
920 if ($tmpclass && ($tmpclass != $object->element)) {
930 $regforregex = array();
931 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
932 $sourcefield = $regforregex[1];
933 $regexstring = $regforregex[2];
935 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
936 $sourcefield = $regforregex[1];
937 $regexstring = $regforregex[2];
940 if (!empty($sourcefield) && !empty($regexstring)) {
941 if (strtolower($sourcefield) ==
'body') {
942 $sourcestring = $messagetext;
943 } elseif (strtolower($sourcefield) ==
'subject') {
944 $sourcestring = $subject;
945 } elseif (strtolower($sourcefield) ==
'header') {
946 $sourcestring = $header;
950 $regforval = array();
952 if (strtolower($sourcefield) ==
'body') {
953 $regexoptions =
'ms';
955 if (strtolower($sourcefield) ==
'header') {
960 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
962 $valueextracted = isset($regforval[count($regforval) - 1]) ?trim($regforval[count($regforval) - 1]) :
null;
963 if (strtolower($sourcefield) ==
'header') {
964 if (preg_match(
'/^options_/', $tmpproperty)) {
965 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $this->
decodeSMTPSubject($valueextracted);
967 if (property_exists($object, $tmpproperty)) {
974 if (preg_match(
'/^options_/', $tmpproperty)) {
975 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $this->
decodeSMTPSubject($valueextracted);
977 if (property_exists($object, $tmpproperty)) {
984 if (preg_match(
'/^options_/', $tmpproperty)) {
985 $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));
987 if (property_exists($object, $tmpproperty)) {
995 if (property_exists($object, $tmpproperty)) {
996 $object->$tmpproperty =
null;
998 $tmp[$tmpproperty] =
null;
1001 $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.';
1005 $errorforthisaction++;
1006 $this->error =
'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1007 $this->errors[] = $this->error;
1009 $operationslog .=
'<br>'.$this->error;
1011 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1013 if (preg_match(
'/^options_/', $tmpproperty)) {
1014 $valuecurrent = $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
1016 if (property_exists($object, $tmpproperty)) {
1017 $valuecurrent = $object->$tmpproperty;
1019 $valuecurrent = $tmp[$tmpproperty];
1023 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
1024 $valuetouse = $regforregex[2];
1027 $matcharray = array();
1028 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1030 if (is_array($matcharray[1])) {
1031 foreach ($matcharray[1] as $keytoreplace) {
1032 if ($keytoreplace) {
1033 if (preg_match(
'/^options_/', $keytoreplace)) {
1034 $substitutionarray[
'__'.$keytoreplace.
'__'] = $object->array_options[preg_replace(
'/^options_/',
'', $keytoreplace)];
1036 if (property_exists($object, $keytoreplace)) {
1037 $substitutionarray[
'__'.$keytoreplace.
'__'] = $object->$keytoreplace;
1039 $substitutionarray[
'__'.$keytoreplace.
'__'] = $tmp[$keytoreplace];
1049 if (preg_match(
'/^options_/', $tmpproperty)) {
1050 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
1052 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->array_options['.
dol_escape_htmltag(preg_replace(
'/^options_/',
'', $tmpproperty)).
']';
1054 if (property_exists($object, $tmpproperty)) {
1055 $object->$tmpproperty = $valuetouse;
1057 $tmp[$tmpproperty] = $valuetouse;
1060 $operationslog .=
'<br>Set value '.dol_escape_htmltag($valuetouse).
' into object->'.
dol_escape_htmltag($tmpproperty);
1064 $errorforthisaction++;
1065 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1066 $this->errors[] = $this->error;
1071 return $errorforthisaction;
1082 global $db, $conf, $langs, $user;
1083 global $hookmanager;
1087 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
1088 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1089 require_once DOL_DOCUMENT_ROOT.
'/includes/webklex/php-imap/vendor/autoload.php';
1092 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_INFO);
1094 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
1099 $this->debuginfo =
'';
1103 $searchfilterdoltrackid = 0;
1104 $searchfilternodoltrackid = 0;
1105 $searchfilterisanswer = 0;
1106 $searchfilterisnotanswer = 0;
1107 $searchfilterreplyto = 0;
1108 $searchfilterexcludebody =
'';
1109 $searchfilterexcludesubject =
'';
1110 $operationslog =
'';
1115 if (empty($this->host)) {
1116 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
1119 if (empty($this->login)) {
1120 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
1123 if (empty($this->source_directory)) {
1124 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
1131 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1132 if ($this->acces_type == 1) {
1134 require_once DOL_DOCUMENT_ROOT.
'/core/lib/oauth.lib.php';
1135 $keyforsupportedoauth2array = $this->oauth_service;
1136 if (preg_match(
'/^.*-/', $keyforsupportedoauth2array)) {
1137 $keyforprovider = preg_replace(
'/^.*-/',
'', $keyforsupportedoauth2array);
1139 $keyforprovider =
'';
1141 $keyforsupportedoauth2array = preg_replace(
'/-.*$/',
'', $keyforsupportedoauth2array);
1142 $keyforsupportedoauth2array =
'OAUTH_'.$keyforsupportedoauth2array.
'_NAME';
1144 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array][
'name']) ?
'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array][
'name'].($keyforprovider ?
'-'.$keyforprovider :
''));
1146 require_once DOL_DOCUMENT_ROOT.
'/includes/OAuth/bootstrap.php';
1152 $storage =
new DoliStorage($db, $conf, $keyforprovider);
1155 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1163 if (is_object($tokenobj) && $expire) {
1164 $credentials =
new Credentials(
1169 $serviceFactory = new \OAuth\ServiceFactory();
1170 $oauthname = explode(
'-', $OAUTH_SERVICENAME);
1172 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1174 $refreshtoken = $tokenobj->getRefreshToken();
1175 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1176 $tokenobj->setRefreshToken($refreshtoken);
1177 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1179 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1180 if (is_object($tokenobj)) {
1181 $token = $tokenobj->getAccessToken();
1183 $this->error =
"Token not found";
1188 $this->error = $e->getMessage();
1189 dol_syslog(
"CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1193 $cm =
new ClientManager();
1194 $client = $cm->make([
1195 'host' => $this->host,
1196 'port' => $this->port,
1197 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption :
false,
1198 'validate_cert' =>
true,
1199 'protocol' =>
'imap',
1200 'username' => $this->login,
1201 'password' => $token,
1202 'authentication' =>
"oauth",
1206 $cm =
new ClientManager();
1207 $client = $cm->make([
1208 'host' => $this->host,
1209 'port' => $this->port,
1210 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption :
false,
1211 'validate_cert' =>
true,
1212 'protocol' =>
'imap',
1213 'username' => $this->login,
1214 'password' => $this->password,
1215 'authentication' =>
"login",
1221 }
catch (ConnectionFailedException $e) {
1222 $this->error = $e->getMessage();
1223 $this->errors[] = $this->error;
1224 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1228 $host = dol_getprefix(
'email');
1231 if (!function_exists(
'imap_open')) {
1232 $this->error =
'IMAP function not enabled on your PHP';
1235 $sourcedir = $this->source_directory;
1236 $targetdir = ($this->target_directory ? $this->target_directory :
'');
1239 $connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
1240 $connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
1242 $connection = imap_open($connectstringsource, $this->login, $this->password);
1244 $this->error =
'Failed to open IMAP connection '.$connectstringsource.
' '.imap_last_error();
1249 $host = dol_getprefix(
'email');
1258 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1260 $criteria = array(array(
'UNDELETED'));
1261 foreach ($this->filters as $rule) {
1262 if (empty($rule[
'status'])) {
1267 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1272 if ($rule[
'type'] ==
'from') {
1273 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1274 if (count($tmprulevaluearray) >= 2) {
1275 foreach ($tmprulevaluearray as $tmprulevalue) {
1276 array_push($criteria, array($not.
"FROM" => $tmprulevalue));
1279 array_push($criteria, array($not.
"FROM" => $rule[
'rulevalue']));
1282 if ($rule[
'type'] ==
'to') {
1283 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1284 if (count($tmprulevaluearray) >= 2) {
1285 foreach ($tmprulevaluearray as $tmprulevalue) {
1286 array_push($criteria, array($not.
"TO" => $tmprulevalue));
1289 array_push($criteria, array($not.
"TO" => $rule[
'rulevalue']));
1292 if ($rule[
'type'] ==
'bcc') {
1293 array_push($criteria, array($not.
"BCC" => $rule[
'rulevalue']));
1295 if ($rule[
'type'] ==
'cc') {
1296 array_push($criteria, array($not.
"CC" => $rule[
'rulevalue']));
1298 if ($rule[
'type'] ==
'subject') {
1299 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1301 $searchfilterexcludesubject = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1303 array_push($criteria, array(
"SUBJECT" => $rule[
'rulevalue']));
1306 if ($rule[
'type'] ==
'body') {
1307 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1309 $searchfilterexcludebody = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1311 array_push($criteria, array(
"BODY" => $rule[
'rulevalue']));
1314 if ($rule[
'type'] ==
'header') {
1315 array_push($criteria, array($not.
"HEADER" => $rule[
'rulevalue']));
1327 if ($rule[
'type'] ==
'seen') {
1328 array_push($criteria, array($not.
"SEEN"));
1330 if ($rule[
'type'] ==
'unseen') {
1331 array_push($criteria, array($not.
"UNSEEN"));
1333 if ($rule[
'type'] ==
'unanswered') {
1334 array_push($criteria, array($not.
"UNANSWERED"));
1336 if ($rule[
'type'] ==
'answered') {
1337 array_push($criteria, array($not.
"ANSWERED"));
1339 if ($rule[
'type'] ==
'smaller') {
1340 array_push($criteria, array($not.
"SMALLER"));
1342 if ($rule[
'type'] ==
'larger') {
1343 array_push($criteria, array($not.
"LARGER"));
1347 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1348 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1350 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1351 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1353 if ($rule[
'type'] ==
'withtrackingid') {
1354 $searchfilterdoltrackid++; $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1356 if ($rule[
'type'] ==
'withouttrackingid') {
1357 $searchfilternodoltrackid++; $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1360 if ($rule[
'type'] ==
'isanswer') {
1361 $searchfilterisanswer++; $searchhead .=
'/References.*@.*/';
1363 if ($rule[
'type'] ==
'isnotanswer') {
1364 $searchfilterisnotanswer++; $searchhead .=
'! /References.*@.*/';
1367 if ($rule[
'type'] ==
'replyto') {
1368 $searchfilterreplyto++; $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1372 if (empty($targetdir)) {
1374 if ($this->datelastok) {
1375 $fromdate = $this->datelastok;
1377 if ($fromdate > 0) {
1379 array_push($criteria, array(
"SINCE" => date(
'j-M-Y', $fromdate - 1)));
1384 dol_syslog(
"IMAP search string = ".var_export($criteria,
true));
1385 $search = var_export($criteria,
true);
1388 $search =
'UNDELETED';
1389 foreach ($this->filters as $rule) {
1390 if (empty($rule[
'status'])) {
1398 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1403 if ($rule[
'type'] ==
'from') {
1404 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1405 if (count($tmprulevaluearray) >= 2) {
1406 foreach ($tmprulevaluearray as $tmprulevalue) {
1407 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1410 $search .= ($search ?
' ' :
'').$not.
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1413 if ($rule[
'type'] ==
'to') {
1414 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1415 if (count($tmprulevaluearray) >= 2) {
1416 foreach ($tmprulevaluearray as $tmprulevalue) {
1417 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1420 $search .= ($search ?
' ' :
'').$not.
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1423 if ($rule[
'type'] ==
'bcc') {
1424 $search .= ($search ?
' ' :
'').$not.
'BCC';
1426 if ($rule[
'type'] ==
'cc') {
1427 $search .= ($search ?
' ' :
'').$not.
'CC';
1429 if ($rule[
'type'] ==
'subject') {
1430 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1432 $searchfilterexcludesubject = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1434 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1437 if ($rule[
'type'] ==
'body') {
1438 if (strpos($rule[
'rulevalue'],
'!') === 0) {
1440 $searchfilterexcludebody = preg_replace(
'/^!/',
'', $rule[
'rulevalue']);
1443 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1446 if ($rule[
'type'] ==
'header') {
1447 $search .= ($search ?
' ' :
'').$not.
'HEADER '.$rule[
'rulevalue'];
1459 if ($rule[
'type'] ==
'seen') {
1460 $search .= ($search ?
' ' :
'').$not.
'SEEN';
1462 if ($rule[
'type'] ==
'unseen') {
1463 $search .= ($search ?
' ' :
'').$not.
'UNSEEN';
1465 if ($rule[
'type'] ==
'unanswered') {
1466 $search .= ($search ?
' ' :
'').$not.
'UNANSWERED';
1468 if ($rule[
'type'] ==
'answered') {
1469 $search .= ($search ?
' ' :
'').$not.
'ANSWERED';
1471 if ($rule[
'type'] ==
'smaller') {
1472 $search .= ($search ?
' ' :
'').$not.
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1474 if ($rule[
'type'] ==
'larger') {
1475 $search .= ($search ?
' ' :
'').$not.
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1479 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1480 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1482 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1483 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1485 if ($rule[
'type'] ==
'withtrackingid') {
1486 $searchfilterdoltrackid++; $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1488 if ($rule[
'type'] ==
'withouttrackingid') {
1489 $searchfilternodoltrackid++; $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1492 if ($rule[
'type'] ==
'isanswer') {
1493 $searchfilterisanswer++; $searchhead .=
'/References.*@.*/';
1495 if ($rule[
'type'] ==
'isnotanswer') {
1496 $searchfilterisnotanswer++; $searchhead .=
'! /References.*@.*/';
1499 if ($rule[
'type'] ==
'replyto') {
1500 $searchfilterreplyto++; $searchhead .=
'/Reply-To.*'.preg_quote($rule[
'rulevalue'],
'/').
'/';
1504 if (empty($targetdir)) {
1506 if ($this->datelastok) {
1507 $fromdate = $this->datelastok;
1509 if ($fromdate > 0) {
1510 $search .= ($search ?
' ' :
'').
'SINCE '.date(
'j-M-Y', $fromdate - 1);
1519 $nbemailprocessed = 0;
1522 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1524 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1528 $f = $client->getFolders(
false, $this->source_directory);
1529 $Query = $f[0]->messages()->where($criteria);
1530 }
catch (InvalidWhereQueryCriteriaException $e) {
1531 $this->error = $e->getMessage();
1532 $this->errors[] = $this->error;
1533 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1536 $this->error = $e->getMessage();
1537 $this->errors[] = $this->error;
1538 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1545 $Query->leaveUnread();
1547 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder(
"asc")->get();
1550 $this->error = $e->getMessage();
1551 $this->errors[] = $this->error;
1552 dol_syslog(
"EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1557 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1559 if ($arrayofemail ===
false) {
1561 $mapoferrrors = imap_errors();
1562 if ($mapoferrrors !==
false) {
1564 $this->error =
"Search string not understood - ".join(
',', $mapoferrrors);
1565 $this->errors[] = $this->error;
1570 $arrayofemailtodelete = array();
1573 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
1590 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1593 foreach ($arrayofemail as $imapemail) {
1594 if ($nbemailprocessed > 1000) {
1601 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1602 $header = $imapemail->getHeader()->raw;
1603 $overview = $imapemail->getAttributes();
1605 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1606 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1609 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1612 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches);
1613 $headers = array_combine($matches[1], $matches[2]);
1616 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1617 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1619 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1620 $headers[
'References'] = $headers[
'references'];
1622 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1623 $headers[
'Message-ID'] = $headers[
'message-id'];
1625 if (!empty($headers[
'subject']) && empty($headers[
'Subject'])) {
1626 $headers[
'Subject'] = $headers[
'subject'];
1634 dol_syslog(
"** Process email ".$iforemailloop.
" References: ".$headers[
'References'].
" Subject: ".$headers[
'Subject']);
1637 $trackidfoundintorecipienttype =
'';
1638 $trackidfoundintorecipientid = 0;
1641 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)) {
1642 $trackidfoundintorecipienttype = $reg[1];
1643 $trackidfoundintorecipientid = $reg[2];
1644 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1645 $trackidfoundintorecipienttype =
'emailing';
1646 $trackidfoundintorecipientid = $reg[1];
1650 if ($searchfilterdoltrackid > 0) {
1651 if (empty($trackidfoundintorecipienttype)) {
1652 if (empty($headers[
'References']) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References'])) {
1653 $nbemailprocessed++;
1654 dol_syslog(
" Discarded - No suffix in email recipient and no Header References found matching signature of application so with a trackid");
1659 if ($searchfilternodoltrackid > 0) {
1660 if (!empty($trackidfoundintorecipienttype) || (!empty($headers[
'References']) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))) {
1661 $nbemailprocessed++;
1662 dol_syslog(
" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
1667 if ($searchfilterisanswer > 0) {
1668 if (empty($headers[
'In-Reply-To'])) {
1669 $nbemailprocessed++;
1670 dol_syslog(
" Discarded - Email is not an answer (no In-Reply-To header)");
1676 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) {
1683 $nbemailprocessed++;
1684 dol_syslog(
" Discarded - Email is not an answer (no RE prefix in subject)");
1688 if ($searchfilterisnotanswer > 0) {
1689 if (!empty($headers[
'In-Reply-To'])) {
1693 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) {
1699 $nbemailprocessed++;
1700 dol_syslog(
" Discarded - Email is an answer");
1708 $thirdpartystatic =
new Societe($this->db);
1709 $contactstatic =
new Contact($this->db);
1710 $projectstatic =
new Project($this->db);
1712 $nbactiondoneforemail = 0;
1714 $errorforactions = 0;
1715 $thirdpartyfoundby =
'';
1716 $contactfoundby =
'';
1717 $projectfoundby =
'';
1718 $ticketfoundby =
'';
1719 $candidaturefoundby =
'';
1722 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1723 dol_syslog(
"msgid=".$overview[
'message_id'].
" date=".
dol_print_date($overview[
'date'],
'dayrfc',
'gmt').
" from=".$overview[
'from'].
" to=".$overview[
'to'].
" subject=".$overview[
'subject']);
1726 $overview[
'subject'] = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $overview[
'subject']);
1728 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);
1735 $overview[0]->subject = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $overview[0]->subject);
1739 global $htmlmsg, $plainmsg, $charset, $attachments;
1741 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1742 if ($imapemail->hasHTMLBody()) {
1743 $htmlmsg = $imapemail->getHTMLBody();
1745 if ($imapemail->hasTextBody()) {
1746 $plainmsg = $imapemail->getTextBody();
1748 if ($imapemail->hasAttachments()) {
1749 $attachments = $imapemail->getAttachments()->all();
1754 $this->
getmsg($connection, $imapemail);
1767 $operationslog .=
'<br>Discarded - Email body is not valid utf8';
1768 dol_syslog(
" Discarded - Email body is not valid utf8");
1772 if ($searchfilterexcludebody) {
1773 if (preg_match(
'/'.preg_quote($searchfilterexcludebody,
'/').
'/ms', $messagetext)) {
1774 $nbemailprocessed++;
1775 $operationslog .=
'<br>Discarded - Email body contains string '.$searchfilterexcludebody;
1776 dol_syslog(
" Discarded - Email body contains string ".$searchfilterexcludebody);
1837 $replytostring =
'';
1839 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
1840 $fromstring = $overview[
'from'];
1843 $sender = $overview[
'sender'];
1844 $to = $overview[
'to'];
1845 $sendtocc = empty($overview[
'cc']) ?
'' : $overview[
'cc'];
1846 $sendtobcc = empty($overview[
'bcc']) ?
'' : $overview[
'bcc'];
1847 $date = $overview[
'date'];
1848 $msgid = str_replace(array(
'<',
'>'),
'', $overview[
'message_id']);
1849 $subject = $overview[
'subject'];
1851 $fromstring = $overview[0]->from;
1854 $sender = $overview[0]->sender;
1855 $to = $overview[0]->to;
1856 $sendtocc = $overview[0]->cc;
1857 $sendtobcc = $overview[0]->bcc;
1858 $date = $overview[0]->udate;
1859 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1860 $subject = $overview[0]->subject;
1864 if ($searchfilterexcludesubject) {
1865 if (preg_match(
'/'.preg_quote($searchfilterexcludesubject,
'/').
'/ms', $subject)) {
1866 $nbemailprocessed++;
1867 $operationslog .=
'<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
1868 dol_syslog(
" Discarded - Email subject contains string ".$searchfilterexcludesubject);
1874 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
1876 $fromtext = $reg[1];
1878 $from = $fromstring;
1881 if (preg_match(
'/^(.*)<(.*)>$/', $replytostring, $reg)) {
1883 $replytotext = $reg[1];
1885 $replyto = $replytostring;
1888 $fk_element_id = 0; $fk_element_type =
'';
1892 $contactid = 0; $thirdpartyid = 0; $projectid = 0; $ticketid = 0;
1900 $objectemail =
null;
1903 if (!empty($headers[
'References'])) {
1904 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
1908 foreach ($arrayofreferences as $reference) {
1910 if (!empty($trackidfoundintorecipienttype)) {
1911 $resultsearchtrackid = -1;
1912 $reg[1] = $trackidfoundintorecipienttype;
1913 $reg[2] = $trackidfoundintorecipientid;
1915 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
1916 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
1917 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
1921 if (!empty($resultsearchtrackid)) {
1923 $trackid = $reg[1].$reg[2];
1925 $objectid = $reg[2];
1927 if ($reg[1] ==
'thi') {
1928 $objectemail =
new Societe($this->db);
1930 if ($reg[1] ==
'ctc') {
1931 $objectemail =
new Contact($this->db);
1933 if ($reg[1] ==
'inv') {
1934 $objectemail =
new Facture($this->db);
1936 if ($reg[1] ==
'sinv') {
1939 if ($reg[1] ==
'pro') {
1940 $objectemail =
new Propal($this->db);
1942 if ($reg[1] ==
'ord') {
1943 $objectemail =
new Commande($this->db);
1945 if ($reg[1] ==
'shi') {
1948 if ($reg[1] ==
'spro') {
1951 if ($reg[1] ==
'sord') {
1954 if ($reg[1] ==
'rec') {
1955 $objectemail =
new Reception($this->db);
1957 if ($reg[1] ==
'proj') {
1958 $objectemail =
new Project($this->db);
1960 if ($reg[1] ==
'tas') {
1961 $objectemail =
new Task($this->db);
1963 if ($reg[1] ==
'con') {
1964 $objectemail =
new Contact($this->db);
1966 if ($reg[1] ==
'use') {
1967 $objectemail =
new User($this->db);
1969 if ($reg[1] ==
'tic') {
1970 $objectemail =
new Ticket($this->db);
1972 if ($reg[1] ==
'recruitmentcandidature') {
1975 if ($reg[1] ==
'mem') {
1976 $objectemail =
new Adherent($this->db);
1984 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
1986 if (!is_object($objectemail)) {
1987 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket where email_msgid = '".$this->db->escape($reg[1]).
"'";
1988 $resql = $this->db->query(
$sql);
1990 $obj = $this->db->fetch_object($resql);
1992 $objectid = $obj->rowid;
1993 $objectemail =
new Ticket($this->db);
1994 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2001 if (!is_object($objectemail)) {
2002 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->db->escape($reg[1]).
"'";
2003 $resql = $this->db->query(
$sql);
2005 $obj = $this->db->fetch_object($resql);
2007 $objectid = $obj->rowid;
2008 $objectemail =
new Project($this->db);
2009 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2016 if (!is_object($objectemail)) {
2017 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1]).
"'";
2018 $resql = $this->db->query(
$sql);
2020 $obj = $this->db->fetch_object($resql);
2022 $objectid = $obj->rowid;
2024 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
2033 if (is_object($objectemail)) {
2034 $result = $objectemail->fetch($objectid);
2036 $fk_element_id = $objectemail->id;
2037 $fk_element_type = $objectemail->element;
2039 if ($fk_element_type ==
'facture') {
2040 $fk_element_type =
'invoice';
2043 if (get_class($objectemail) !=
'Societe') {
2044 $thirdpartyid = $objectemail->fk_soc;
2046 $thirdpartyid = $objectemail->id;
2049 if (get_class($objectemail) !=
'Contact') {
2050 $contactid = $objectemail->fk_socpeople;
2052 $contactid = $objectemail->id;
2055 if (get_class($objectemail) !=
'Project') {
2056 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2058 $projectid = $objectemail->id;
2064 if ($projectid > 0) {
2065 $result = $projectstatic->fetch($projectid);
2067 $projectstatic->id = 0;
2069 $projectid = $projectstatic->id;
2071 $projectfoundby =
'trackid ('.$trackid.
')';
2073 if (empty($contactid)) {
2074 $contactid = $projectstatic->fk_contact;
2076 if (empty($thirdpartyid)) {
2077 $thirdpartyid = $projectstatic->fk_soc;
2082 if ($contactid > 0) {
2083 $result = $contactstatic->fetch($contactid);
2085 $contactstatic->id = 0;
2087 $contactid = $contactstatic->id;
2089 $contactfoundby =
'trackid ('.$trackid.
')';
2091 if (empty($thirdpartyid)) {
2092 $thirdpartyid = $contactstatic->fk_soc;
2097 if ($thirdpartyid > 0) {
2098 $result = $thirdpartystatic->fetch($thirdpartyid);
2100 $thirdpartystatic->id = 0;
2102 $thirdpartyid = $thirdpartystatic->id;
2104 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
2109 if (is_object($objectemail)) {
2115 if (empty($contactid)) {
2116 $result = $contactstatic->fetch(0,
null,
'', $from);
2119 dol_syslog(
"We found a contact with the email ".$from);
2120 $contactid = $contactstatic->id;
2121 $contactfoundby =
'email of contact ('.$from.
')';
2122 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2123 $result = $thirdpartystatic->fetch($contactstatic->socid);
2125 $thirdpartyid = $thirdpartystatic->id;
2126 $thirdpartyfoundby =
'email of contact ('.$from.
')';
2132 if (empty($thirdpartyid)) {
2133 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
2135 dol_syslog(
"We found a thirdparty with the email ".$from);
2136 $thirdpartyid = $thirdpartystatic->id;
2137 $thirdpartyfoundby =
'email ('.$from.
')';
2173 foreach ($this->actions as $operation) {
2174 $errorforthisaction = 0;
2176 if ($errorforactions) {
2179 if (empty($operation[
'status'])) {
2183 $operationslog .=
'<br>* Process operation '.$operation[
'type'];
2186 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
2187 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
2189 $actioncode =
'EMAIL_IN';
2191 if ($this->source_directory ==
'Sent') {
2192 $actioncode =
'EMAIL_OUT';
2195 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
2197 $descriptiontitle = $langs->trans(
"RecordCreatedByEmailCollector", $this->ref, $msgid);
2200 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
2202 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
2204 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
2206 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
2210 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
2211 if (empty($operation[
'actionparam'])) {
2213 $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;";
2214 $this->errors[] = $this->error;
2216 $actionparam = $operation[
'actionparam'];
2217 $idtouseforthirdparty =
'';
2218 $nametouseforthirdparty =
'';
2219 $emailtouseforthirdparty =
'';
2220 $namealiastouseforthirdparty =
'';
2222 $operationslog .=
'<br>Loop on each property to set into actionparam';
2226 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2230 $regforregex = array();
2232 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2233 $sourcefield = $regforregex[1];
2234 $regexstring = $regforregex[2];
2237 if (!empty($sourcefield) && !empty($regexstring)) {
2238 if (strtolower($sourcefield) ==
'body') {
2239 $sourcestring = $messagetext;
2240 } elseif (strtolower($sourcefield) ==
'subject') {
2241 $sourcestring = $subject;
2242 } elseif (strtolower($sourcefield) ==
'header') {
2243 $sourcestring = $header;
2246 if ($sourcestring) {
2247 $regforval = array();
2249 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
2252 if ($propertytooverwrite ==
'id') {
2253 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2255 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found idtouseforthirdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2256 } elseif ($propertytooverwrite ==
'email') {
2257 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2259 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found emailtouseforthirdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2260 } elseif ($propertytooverwrite ==
'name') {
2261 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2263 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2264 } elseif ($propertytooverwrite ==
'name_alias') {
2265 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
2267 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Found namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2269 $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';
2273 $idtouseforthirdparty =
null;
2274 $nametouseforthirdparty =
null;
2275 $emailtouseforthirdparty =
null;
2276 $namealiastouseforthirdparty =
null;
2278 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' Regex /'.
dol_escape_htmltag($regexstring).
'/ms into '.strtoupper($sourcefield).
' -> Not found';
2284 $this->error =
'The extract rule to use to load thirdparty for email '.$msgid.
' has an unknown source (must be HEADER, SUBJECT or BODY)';
2285 $this->errors[] = $this->error;
2287 $operationslog .=
'<br>'.$this->error;
2289 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2293 if ($propertytooverwrite ==
'id') {
2294 $idtouseforthirdparty = $reg[2];
2296 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property idtouseforthrdparty='.
dol_escape_htmltag($idtouseforthirdparty);
2297 } elseif ($propertytooverwrite ==
'email') {
2298 $emailtouseforthirdparty = $reg[2];
2300 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property emailtouseforthrdparty='.
dol_escape_htmltag($emailtouseforthirdparty);
2301 } elseif ($propertytooverwrite ==
'name') {
2302 $nametouseforthirdparty = $reg[2];
2304 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property nametouseforthirdparty='.
dol_escape_htmltag($nametouseforthirdparty);
2305 } elseif ($propertytooverwrite ==
'name_alias') {
2306 $namealiastouseforthirdparty = $reg[2];
2308 $operationslog .=
'<br>propertytooverwrite='.$propertytooverwrite.
' We set property namealiastouseforthirdparty='.
dol_escape_htmltag($namealiastouseforthirdparty);
2312 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
2313 $this->errors[] = $this->error;
2318 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2320 $operationslog .=
'<br>We have this data to search thirdparty: '.$idtouseforthirdparty.
' '.$emailtouseforthirdparty.
' '.$nametouseforthirdparty.
' '.$namealiastouseforthirdparty;
2322 $tmpobject =
new stdClass();
2323 $tmpobject->element ==
'generic';
2324 $tmpobject->id = $idtouseforthirdparty;
2325 $tmpobject->name = $nametouseforthirdparty;
2326 $tmpobject->name_alias = $namealiastouseforthirdparty;
2327 $tmpobject->email = $emailtouseforthirdparty;
2331 $idtouseforthirdparty = $tmpobject->id;
2332 $nametouseforthirdparty = $tmpobject->name;
2333 $namealiastouseforthirdparty = $tmpobject->name_alias;
2334 $emailtouseforthirdparty = $tmpobject->email;
2336 $operationslog .=
'<br>We try to search existing thirdparty with '.$idtouseforthirdparty.
' '.$emailtouseforthirdparty.
' '.$nametouseforthirdparty.
' '.$namealiastouseforthirdparty;
2338 $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', $emailtouseforthirdparty, $namealiastouseforthirdparty);
2341 $this->error =
'Error when getting thirdparty with name '.$nametouseforthirdparty.
' (may be 2 record exists with same name ?)';
2342 $this->errors[] = $this->error;
2344 } elseif ($result == 0) {
2345 if ($operation[
'type'] ==
'loadthirdparty') {
2346 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found");
2349 $langs->load(
"errors");
2350 $this->error = $langs->trans(
'ErrorFailedToLoadThirdParty', $idtouseforthirdparty, $emailtouseforthirdparty, $nametouseforthirdparty, $namealiastouseforthirdparty);
2351 $this->errors[] = $this->error;
2352 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
2353 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" name_alias=".$namealiastouseforthirdparty.
" was not found. We try to create it.");
2356 $thirdpartystatic =
new Societe($db);
2357 $thirdpartystatic->name = $nametouseforthirdparty;
2358 if (!empty($namealiastouseforthirdparty)) {
2359 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
2360 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
2363 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ?
'': $fromtext) : $replytostring);
2365 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($from) ?
'' : $from) : $replyto) : $emailtouseforthirdparty);
2368 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2370 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
2371 $thirdpartystatic->code_client =
'auto';
2373 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
2374 $thirdpartystatic->code_fournisseur =
'auto';
2377 if ($errorforthisaction) {
2380 $result = $thirdpartystatic->create($user);
2383 $this->error = $thirdpartystatic->error;
2384 $this->errors = $thirdpartystatic->errors;
2386 $operationslog .=
'<br>Thirdparty created -> id = '.dol_escape_htmltag($thirdpartystatic->id);
2391 dol_syslog(
"One and only one existing third party has been found");
2393 $operationslog .=
'<br>Thirdparty already exists with id = '.dol_escape_htmltag($thirdpartystatic->id);
2397 } elseif ($operation[
'type'] ==
'loadandcreatecontact') {
2398 if (empty($operation[
'actionparam'])) {
2400 $this->error =
"Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
2401 $this->errors[] = $this->error;
2403 $contact_static =
new Contact($this->db);
2405 $errorforthisaction = $this->
overwritePropertiesOfObject($contact_static, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2406 if ($errorforthisaction) {
2409 if (!empty($contact_static->email) && $contact_static->email != $from) $from = $contact_static->email;
2411 $result = $contactstatic->fetch(0,
null,
'', $from);
2414 $this->error =
'Error when getting contact with email ' . $from;
2415 $this->errors[] = $this->error;
2417 } elseif ($result == 0) {
2418 dol_syslog(
"Contact with email " . $from .
" was not found. We try to create it.");
2419 $contactstatic =
new Contact($this->db);
2422 $contactstatic->email = $from;
2423 $operationslog .=
'<br>We set property email='.dol_escape_htmltag($from);
2426 $errorforthisaction = $this->
overwritePropertiesOfObject($contactstatic, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2428 if ($errorforthisaction) {
2432 if (!empty($contactstatic->country)) {
2433 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2434 $result =
getCountry(
'', 3, $this->db,
'', 1, $contactstatic->country);
2435 if ($result ==
'NotDefined') {
2437 $this->error =
"Error country not found by this name '" . $contactstatic->country .
"'";
2438 } elseif (!($result > 0)) {
2440 $this->error =
"Error when search country by this name '" . $contactstatic->country .
"'";
2441 $this->errors[] = $this->db->lasterror();
2443 $contactstatic->country_id = $result;
2444 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2446 } elseif (!empty($contactstatic->country_code)) {
2447 require_once DOL_DOCUMENT_ROOT .
'/core/lib/company.lib.php';
2448 $result =
getCountry($contactstatic->country_code, 3, $this->db);
2449 if ($result ==
'NotDefined') {
2451 $this->error =
"Error country not found by this code '" . $contactstatic->country_code .
"'";
2452 } elseif (!($result > 0)) {
2454 $this->error =
"Error when search country by this code '" . $contactstatic->country_code .
"'";
2455 $this->errors[] = $this->db->lasterror();
2457 $contactstatic->country_id = $result;
2458 $operationslog .=
'<br>We set property country_id='.dol_escape_htmltag($result);
2462 if (!$errorforactions) {
2464 if (!empty($contactstatic->state)) {
2465 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2466 $result =
dol_getIdFromCode($this->db, $contactstatic->state,
'c_departements',
'nom',
'rowid');
2467 if (empty($result)) {
2469 $this->error =
"Error state not found by this name '" . $contactstatic->state .
"'";
2470 } elseif (!($result > 0)) {
2472 $this->error =
"Error when search state by this name '" . $contactstatic->state .
"'";
2473 $this->errors[] = $this->db->lasterror();
2475 $contactstatic->state_id = $result;
2476 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2478 } elseif (!empty($contactstatic->state_code)) {
2479 require_once DOL_DOCUMENT_ROOT .
'/core/lib/functions.lib.php';
2480 $result =
dol_getIdFromCode($this->db, $contactstatic->state_code,
'c_departements',
'code_departement',
'rowid');
2481 if (empty($result)) {
2483 $this->error =
"Error state not found by this code '" . $contactstatic->state_code .
"'";
2484 } elseif (!($result > 0)) {
2486 $this->error =
"Error when search state by this code '" . $contactstatic->state_code .
"'";
2487 $this->errors[] = $this->db->lasterror();
2489 $contactstatic->state_id = $result;
2490 $operationslog .=
'<br>We set property state_id='.dol_escape_htmltag($result);
2495 if (!$errorforactions) {
2496 $result = $contactstatic->create($user);
2499 $this->error = $contactstatic->error;
2500 $this->errors = $contactstatic->errors;
2502 $operationslog .=
'<br>Contact created -> id = '.dol_escape_htmltag($contactstatic->id);
2509 } elseif ($operation[
'type'] ==
'recordevent') {
2513 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
2514 if ($alreadycreated == 0) {
2515 if ($projectstatic->id > 0) {
2516 if ($projectfoundby) {
2517 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
2520 if ($thirdpartystatic->id > 0) {
2521 if ($thirdpartyfoundby) {
2522 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2525 if ($contactstatic->id > 0) {
2526 if ($contactfoundby) {
2527 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2531 $description = $descriptiontitle;
2537 $descriptionfull = $description;
2538 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2539 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2544 $actioncomm->type_code =
'AC_OTH_AUTO';
2545 $actioncomm->code =
'AC_'.$actioncode;
2546 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
2547 $actioncomm->note_private = $descriptionfull;
2548 $actioncomm->fk_project = $projectstatic->id;
2549 $actioncomm->datep = $date;
2550 $actioncomm->datef = $date;
2551 $actioncomm->percentage = -1;
2552 $actioncomm->socid = $thirdpartystatic->id;
2553 $actioncomm->contact_id = $contactstatic->id;
2554 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id =>
'') : array());
2555 $actioncomm->authorid = $user->id;
2556 $actioncomm->userownerid = $user->id;
2558 $actioncomm->email_msgid = $msgid;
2559 $actioncomm->email_from = $fromstring;
2560 $actioncomm->email_sender = $sender;
2561 $actioncomm->email_to = $to;
2562 $actioncomm->email_tocc = $sendtocc;
2563 $actioncomm->email_tobcc = $sendtobcc;
2564 $actioncomm->email_subject = $subject;
2565 $actioncomm->errors_to =
'';
2567 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
2568 $actioncomm->fk_element = $fk_element_id;
2569 $actioncomm->elementid = $fk_element_id;
2570 $actioncomm->elementtype = $fk_element_type;
2571 if (is_object($objectemail) && $objectemail->module) {
2572 $actioncomm->elementtype .=
'@'.$objectemail->module;
2579 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2588 if ($errorforthisaction) {
2591 $result = $actioncomm->create($user);
2594 $this->errors = $actioncomm->errors;
2596 $operationslog .=
'<br>Event created -> id='.dol_escape_htmltag($actioncomm->id);
2600 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
2602 foreach ($pj as $key => $val) {
2603 $data[$val[
'filename']] =
getFileData($imapemail, $val[
'pos'], $val[
'type'], $connection);
2605 if (count($pj) > 0) {
2606 $sql =
"SELECT rowid as id FROM ".MAIN_DB_PREFIX.
"user WHERE email LIKE '%".$this->db->escape($from).
"%'";
2607 $resql = $this->db->query(
$sql);
2608 if ($this->db->num_rows($resql) == 0) {
2609 $this->errors[] =
'User Not allowed to add documents';
2611 $arrayobject = array(
2612 'propale' => array(
'table' =>
'propal',
2613 'fields' => array(
'ref'),
2614 'class' =>
'comm/propal/class/propal.class.php',
2615 'object' =>
'Propal'),
2616 'holiday' => array(
'table' =>
'holiday',
2617 'fields' => array(
'ref'),
2618 'class' =>
'holiday/class/holiday.class.php',
2619 'object' =>
'Holiday'),
2620 'expensereport' => array(
'table' =>
'expensereport',
2621 'fields' => array(
'ref'),
2622 'class' =>
'expensereport/class/expensereport.class.php',
2623 'object' =>
'ExpenseReport'),
2624 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
2625 'fields' => array(
'ref'),
2626 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
2627 'object' =>
'RecruitmentJobPosition'),
2628 'recruitment/recruitmentcandidature' => array(
'table' =>
'recruitment_recruitmentcandidature',
2629 'fields' => array(
'ref'),
2630 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
2631 'object' =>
' RecruitmentCandidature'),
2632 'societe' => array(
'table' =>
'societe',
2633 'fields' => array(
'code_client',
'code_fournisseur'),
2634 'class' =>
'societe/class/societe.class.php',
2635 'object' =>
'Societe'),
2636 'commande' => array(
'table' =>
'commande',
2637 'fields' => array(
'ref'),
2638 'class' =>
'commande/class/commande.class.php',
2639 'object' =>
'Commande'),
2640 'expedition' => array(
'table' =>
'expedition',
2641 'fields' => array(
'ref'),
2642 'class' =>
'expedition/class/expedition.class.php',
2643 'object' =>
'Expedition'),
2644 'contract' => array(
'table' =>
'contrat',
2645 'fields' => array(
'ref'),
2646 'class' =>
'contrat/class/contrat.class.php',
2647 'object' =>
'Contrat'),
2648 'fichinter' => array(
'table' =>
'fichinter',
2649 'fields' => array(
'ref'),
2650 'class' =>
'fichinter/class/fichinter.class.php',
2651 'object' =>
'Fichinter'),
2652 'ticket' => array(
'table' =>
'ticket',
2653 'fields' => array(
'ref'),
2654 'class' =>
'ticket/class/ticket.class.php',
2655 'object' =>
'Ticket'),
2656 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
2657 'fields' => array(
'ref'),
2658 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
2659 'object' =>
'KnowledgeRecord'),
2660 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
2661 'fields' => array(
'ref'),
2662 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
2663 'object' =>
'SupplierProposal'),
2664 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
2665 'fields' => array(
'ref',
'ref_supplier'),
2666 'class' =>
'fourn/class/fournisseur.commande.class.php',
2667 'object' =>
'SupplierProposal'),
2668 'facture' => array(
'table' =>
'facture',
2669 'fields' => array(
'ref'),
2670 'class' =>
'compta/facture/class/facture.class.php',
2671 'object' =>
'Facture'),
2672 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
2673 'fields' => array(
'ref',
'ref_client'),
2674 'class' =>
'fourn/class/fournisseur.facture.class.php',
2675 'object' =>
'FactureFournisseur'),
2676 'produit' => array(
'table' =>
'product',
2677 'fields' => array(
'ref'),
2678 'class' =>
'product/class/product.class.php',
2679 'object' =>
'Product'),
2680 'productlot' => array(
'table' =>
'product_lot',
2681 'fields' => array(
'batch'),
2682 'class' =>
'product/stock/class/productlot.class.php',
2683 'object' =>
'Productlot'),
2684 'projet' => array(
'table' =>
'projet',
2685 'fields' => array(
'ref'),
2686 'class' =>
'projet/class/projet.class.php',
2687 'object' =>
'Project'),
2688 'projet_task' => array(
'table' =>
'projet_task',
2689 'fields' => array(
'ref'),
2690 'class' =>
'projet/class/task.class.php',
2691 'object' =>
'Task'),
2692 'ressource' => array(
'table' =>
'resource',
2693 'fields' => array(
'ref'),
2694 'class' =>
'ressource/class/dolressource.class.php',
2695 'object' =>
'Dolresource'),
2696 'bom' => array(
'table' =>
'bom_bom',
2697 'fields' => array(
'ref'),
2698 'class' =>
'bom/class/bom.class.php',
2700 'mrp' => array(
'table' =>
'mrp_mo',
2701 'fields' => array(
'ref'),
2702 'class' =>
'mrp/class/mo.class.php',
2706 if (!is_object($hookmanager)) {
2707 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
2710 $hookmanager->initHooks(array(
'emailcolector'));
2711 $parameters = array(
'arrayobject' => $arrayobject);
2712 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
2714 $arrayobject = $hookmanager->resArray;
2717 $resultobj = array();
2719 foreach ($arrayobject as $key => $objectdesc) {
2720 $sql =
'SELECT DISTINCT t.rowid ';
2721 $sql .=
' FROM ' . MAIN_DB_PREFIX . $objectdesc[
'table'] .
' AS t';
2723 foreach ($objectdesc[
'fields'] as $field) {
2724 $sql .=
"'" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $field .
", '%') OR ";
2728 $ressqlobj = $this->db->query(
$sql);
2730 while ($obj = $this->db->fetch_object($ressqlobj)) {
2731 $resultobj[$key][] = $obj->rowid;
2736 foreach ($resultobj as $mod => $ids) {
2737 $moddesc = $arrayobject[$mod];
2738 $elementpath = $mod;
2740 $objectmanaged =
new $moddesc[
'object']($this->db);
2741 foreach ($ids as $val) {
2742 $res = $objectmanaged->fetch($val);
2744 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
2745 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
2747 $this->errors[] =
'object not found';
2751 foreach ($dirs as $target) {
2752 foreach ($data as $filename => $content) {
2753 $prefix = $this->actions[$this->id][
'actionparam'];
2755 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
2757 $this->errors[] =
'Doc not saved';
2762 $operationslog .=
'<br>Save attachment files on disk';
2764 $this->errors[] =
'no joined piece';
2766 $operationslog .=
'<br>No joinded files';
2768 } elseif ($operation[
'type'] ==
'project') {
2770 $projecttocreate =
new Project($this->db);
2771 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
2772 if ($alreadycreated == 0) {
2773 if ($thirdpartystatic->id > 0) {
2774 $projecttocreate->socid = $thirdpartystatic->id;
2775 if ($thirdpartyfoundby) {
2776 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2779 if ($contactstatic->id > 0) {
2780 $projecttocreate->contact_id = $contactstatic->id;
2781 if ($contactfoundby) {
2782 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2786 $description = $descriptiontitle;
2792 $descriptionfull = $description;
2793 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2794 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2798 $id_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'rowid');
2799 $percent_opp_status =
dol_getIdFromCode($this->db,
'PROSP',
'c_lead_status',
'code',
'percent');
2801 $projecttocreate->title = $subject;
2802 $projecttocreate->date_start = $date;
2803 $projecttocreate->date_end =
'';
2804 $projecttocreate->opp_status = $id_opp_status;
2805 $projecttocreate->opp_percent = $percent_opp_status;
2807 $projecttocreate->note_private = $descriptionfull;
2808 $projecttocreate->entity = $conf->entity;
2809 $projecttocreate->email_msgid = $msgid;
2811 $savesocid = $projecttocreate->socid;
2815 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2818 if (empty($projecttocreate->ref)) {
2821 $modele = empty($conf->global->PROJECT_ADDON) ?
'mod_project_simple' : $conf->global->PROJECT_ADDON;
2824 $file =
''; $classname =
''; $filefound = 0; $reldir =
'';
2825 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
2826 foreach ($dirmodels as $reldir) {
2827 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
2828 if (file_exists($file)) {
2830 $classname = $modele;
2836 if ($savesocid > 0) {
2837 if ($savesocid != $projecttocreate->socid) {
2839 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');
2842 if ($projecttocreate->socid > 0) {
2843 $thirdpartystatic->fetch($projecttocreate->socid);
2847 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
2848 $modModuleToUseForNextValue =
new $classname;
2849 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic :
null), $projecttocreate);
2851 $projecttocreate->ref = $defaultref;
2855 if ($errorforthisaction) {
2858 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
2860 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
2862 $operationslog .=
'<br>'.$this->error;
2865 $result = $projecttocreate->create($user);
2868 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
2869 $this->errors = $projecttocreate->errors;
2871 $operationslog .=
'<br>'.$this->error;
2874 $destdir = $conf->project->dir_output.
'/'.$projecttocreate->ref;
2878 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
2879 foreach ($attachments as $attachment) {
2880 $attachment->save($destdir.
'/');
2883 $this->
getmsg($connection, $imapemail, $destdir);
2886 $operationslog .=
'<br>Project created with attachments -> id='.dol_escape_htmltag($projecttocreate->id);
2888 $operationslog .=
'<br>Project created without attachments -> id='.dol_escape_htmltag($projecttocreate->id);
2896 $operationslog .=
'<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
2898 } elseif ($operation[
'type'] ==
'ticket') {
2900 $tickettocreate =
new Ticket($this->db);
2902 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2903 if ($alreadycreated == 0) {
2904 if ($thirdpartystatic->id > 0) {
2905 $tickettocreate->socid = $thirdpartystatic->id;
2906 $tickettocreate->fk_soc = $thirdpartystatic->id;
2907 if ($thirdpartyfoundby) {
2908 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2911 if ($contactstatic->id > 0) {
2912 $tickettocreate->contact_id = $contactstatic->id;
2913 if ($contactfoundby) {
2914 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2918 $description = $descriptiontitle;
2924 $descriptionfull = $description;
2925 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2926 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2930 $tickettocreate->subject = $subject;
2931 $tickettocreate->message = $description;
2932 $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));
2933 $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));
2934 $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));
2935 $tickettocreate->origin_email = $from;
2936 $tickettocreate->fk_user_create = $user->id;
2937 $tickettocreate->datec =
dol_now();
2938 $tickettocreate->fk_project = $projectstatic->id;
2939 $tickettocreate->notify_tiers_at_create = 0;
2940 $tickettocreate->note_private = $descriptionfull;
2941 $tickettocreate->entity = $conf->entity;
2942 $tickettocreate->email_msgid = $msgid;
2943 $tickettocreate->email_date = $date;
2946 $savesocid = $tickettocreate->socid;
2950 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
2953 if (empty($tickettocreate->ref)) {
2956 $modele = empty($conf->global->TICKET_ADDON) ?
'mod_ticket_simple' : $conf->global->TICKET_ADDON;
2959 $file =
''; $classname =
''; $filefound = 0; $reldir =
'';
2960 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
2961 foreach ($dirmodels as $reldir) {
2962 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
2963 if (file_exists($file)) {
2965 $classname = $modele;
2971 if ($savesocid > 0) {
2972 if ($savesocid != $tickettocreate->socid) {
2974 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');
2977 if ($tickettocreate->socid > 0) {
2978 $thirdpartystatic->fetch($tickettocreate->socid);
2983 $modModuleToUseForNextValue =
new $classname;
2984 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic :
null), $tickettocreate);
2986 $tickettocreate->ref = $defaultref;
2989 if ($errorforthisaction) {
2992 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
2994 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
2997 $result = $tickettocreate->create($user);
3000 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3001 $this->errors = $tickettocreate->errors;
3004 $destdir = $conf->ticket->dir_output.
'/'.$tickettocreate->ref;
3008 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
3009 foreach ($attachments as $attachment) {
3010 $attachment->save($destdir.
'/');
3013 $this->
getmsg($connection, $imapemail, $destdir);
3016 $operationslog .=
'<br>Ticket created with attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3018 $operationslog .=
'<br>Ticket created without attachments -> id='.dol_escape_htmltag($tickettocreate->id);
3024 } elseif ($operation[
'type'] ==
'candidature') {
3028 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
3029 if ($alreadycreated == 0) {
3030 $description = $descriptiontitle;
3036 $descriptionfull = $description;
3037 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
3040 $candidaturetocreate->subject = $subject;
3041 $candidaturetocreate->message = $description;
3042 $candidaturetocreate->type_code = 0;
3043 $candidaturetocreate->category_code =
null;
3044 $candidaturetocreate->severity_code =
null;
3045 $candidaturetocreate->email = $from;
3047 $candidaturetocreate->fk_user_creat = $user->id;
3048 $candidaturetocreate->date_creation =
dol_now();
3049 $candidaturetocreate->fk_project = $projectstatic->id;
3050 $candidaturetocreate->description = $description;
3051 $candidaturetocreate->note_private = $descriptionfull;
3052 $candidaturetocreate->entity = $conf->entity;
3053 $candidaturetocreate->email_msgid = $msgid;
3054 $candidaturetocreate->email_date = $date;
3055 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3060 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header, $operationslog);
3102 if ($errorforthisaction) {
3106 $result = $candidaturetocreate->create($user);
3109 $this->error =
'Failed to create candidature: '.join(
', ', $candidaturetocreate->errors);
3110 $this->errors = $candidaturetocreate->errors;
3113 $operationslog .=
'<br>Candidature created without attachments -> id='.dol_escape_htmltag($candidaturetocreate->id);
3116 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
3119 if (!is_object($hookmanager)) {
3120 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
3124 $parameters = array(
3125 'connection'=> $connection,
3126 'imapemail'=>$imapemail,
3127 'overview'=>$overview,
3130 'fromtext' => $fromtext,
3132 'actionparam'=> $operation[
'actionparam'],
3134 'thirdpartyid' => $thirdpartyid,
3135 'objectid'=> $objectid,
3136 'objectemail'=> $objectemail,
3138 'messagetext'=>$messagetext,
3139 'subject'=>$subject,
3141 'attachments'=>$attachments,
3143 $reshook = $hookmanager->executeHooks(
'doCollectImapOneCollector', $parameters, $this, $operation[
'type']);
3146 $errorforthisaction++;
3147 $this->error = $hookmanager->resPrint;
3149 if ($errorforthisaction) {
3151 $operationslog .=
'<br>Hook doCollectImapOneCollector executed with error';
3153 $operationslog .=
'<br>Hook doCollectImapOneCollector executed without error';
3157 if (!$errorforactions) {
3158 $nbactiondoneforemail++;
3164 if (!$errorforactions) {
3165 if (!empty($targetdir)) {
3166 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
3168 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get(
'subject')).
" to ".$targetdir, LOG_DEBUG);
3170 $imapemail->move($targetdir);
3173 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".((
string) $imapemail).
" to ".$connectstringtarget, LOG_DEBUG);
3174 $operationslog .=
'<br>Move mail '.((string) $imapemail).
' - '.$msgid;
3176 $arrayofemailtodelete[$imapemail] = $msgid;
3179 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
3180 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);
3182 dol_syslog(
"EmailCollector::doCollectOneCollector message ".((
string) $imapemail).
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
3190 unset($objectemail);
3191 unset($projectstatic);
3192 unset($thirdpartystatic);
3193 unset($contactstatic);
3195 $nbemailprocessed++;
3197 if (!$errorforemail) {
3198 $nbactiondone += $nbactiondoneforemail;
3202 $this->db->commit();
3204 $this->db->rollback();
3208 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
3209 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
3215 $this->db->rollback();
3219 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
3221 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
3223 $langs->load(
"admin");
3224 $output = $langs->trans(
'NoNewEmailToProcess');
3228 if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
3229 $client->disconnect();
3231 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
3232 dol_syslog(
"EmailCollect::doCollectOneCollector delete email ".$imapemail.
" ".$msgid);
3234 $operationslog .=
"<br> delete email ".$imapemail.
" ".$msgid;
3236 if (empty($mode) && empty($error)) {
3237 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
3238 if ($res ==
false) {
3240 $this->error = imap_last_error();
3241 $this->errors[] = $this->error;
3243 $operationslog .=
'<br>Error in move '.$this->error;
3250 if (empty($mode) && empty($error)) {
3252 $operationslog .=
"<br>Expunge";
3254 imap_expunge($connection);
3256 imap_close($connection);
3259 $this->datelastresult = $now;
3260 $this->lastresult = $output;
3261 $this->debuginfo .=
'IMAP search string used : '.$search;
3263 $this->debuginfo .=
'<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
3265 if ($operationslog) {
3266 $this->debuginfo .= $operationslog;
3269 if (empty($error) && empty($mode)) {
3270 $this->datelastok = $now;
3273 if (!empty($this->errors)) {
3274 $this->lastresult .=
"<br>".join(
"<br>", $this->errors);
3276 $this->codelastresult = ($error ?
'KO' :
'OK');
3282 dol_syslog(
"EmailCollector::doCollectOneCollector end", LOG_INFO);
3284 return $error ? -1 : 1;
3299 private function getmsg($mbox, $mid, $destdir =
'')
3303 global $charset, $htmlmsg, $plainmsg, $attachments;
3304 $htmlmsg = $plainmsg = $charset =
'';
3305 $attachments = array();
3312 $s = imap_fetchstructure($mbox, $mid, FT_UID);
3317 $this->
getpart($mbox, $mid, $s, 0);
3320 foreach ($s->parts as $partno0 => $p) {
3321 $this->
getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
3352 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
3355 global $htmlmsg, $plainmsg, $charset, $attachments;
3359 imap_fetchbody($mbox, $mid, $partno, FT_UID) :
3360 imap_body($mbox, $mid, FT_UID);
3362 if ($p->encoding == 4) {
3363 $data = quoted_printable_decode($data);
3364 } elseif ($p->encoding == 3) {
3365 $data = base64_decode($data);
3371 if ($p->parameters) {
3372 foreach ($p->parameters as $x) {
3373 $params[strtolower($x->attribute)] = $x->value;
3376 if ($p->dparameters) {
3377 foreach ($p->dparameters as $x) {
3378 $params[strtolower($x->attribute)] = $x->value;
3385 if ($params[
'filename'] || $params[
'name']) {
3387 $filename = ($params[
'filename']) ? $params[
'filename'] : $params[
'name'];
3389 $attachments[$filename] = $data;
3392 $file_name_complete = $params[
'filename'];
3395 $destination = $destdir.
'/'.$file_name_complete;
3398 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
3401 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
3404 $file_name_original = $file_name;
3413 while (file_exists($destdir.
"/".$file_name.
".".$extension)) {
3414 $file_name = $file_name_original .
' (' . $num .
')';
3415 $file_name_complete = $file_name .
"." . $extension;
3416 $destination = $destdir.
'/'.$file_name_complete;
3422 file_put_contents($destination, $data);
3426 if ($p->type == 0 && $data) {
3427 if (!empty($params[
'charset'])) {
3432 if (strtolower($p->subtype) ==
'plain') {
3433 $plainmsg .= trim($data).
"\n\n";
3435 $htmlmsg .= $data.
"<br><br>";
3437 $charset = $params[
'charset'];
3438 } elseif ($p->type == 2 && $data) {
3444 if (!empty($params[
'charset'])) {
3447 $plainmsg .= $data.
"\n\n";
3452 foreach ($p->parts as $partno0 => $p2) {
3453 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1));
3469 if (!$string || $fromEncoding == $toEncoding) {
3472 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
3473 if (!$convertedString && extension_loaded(
'mbstring')) {
3474 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
3476 if (!$convertedString) {
3477 throw new Exception(
'Mime string encoding conversion failed');
3479 return $convertedString;
3498 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
3499 $elements = imap_mime_header_decode($subject);
3501 if (!empty($elements)) {
3502 $num = count($elements);
3503 for ($i = 0; $i < $num; $i++) {
3504 $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));
3505 $newstring .= $stringinutf8;
3507 $subject = $newstring;
3509 } elseif (!function_exists(
'mb_decode_mimeheader')) {
3510 $subject = mb_decode_mimeheader($subject);
3511 } elseif (function_exists(
'iconv_mime_decode')) {
3512 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
3527 $text = preg_replace(
'/[\x{1F600}-\x{1F64F}]/u',
'', $text);
3528 $text = preg_replace(
'/[\x{1F300}-\x{1F5FF}]/u',
'', $text);
3529 $text = preg_replace(
'/[\x{1F680}-\x{1F6FF}]/u',
'', $text);
3530 $text = preg_replace(
'/[\x{2600}-\x{26FF}]/u',
'', $text);
3531 $text = preg_replace(
'/[\x{2700}-\x{27BF}]/u',
'', $text);
3532 $text = preg_replace(
'/[\x{1F900}-\x{1F9FF}]/u',
'', $text);
3533 $text = preg_replace(
'/[\x{1F1E0}-\x{1F1FF}]/u',
'', $text);