25 require_once DOL_DOCUMENT_ROOT.
'/core/class/commonobject.class.php';
26 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
27 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
28 require_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
29 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
30 require_once DOL_DOCUMENT_ROOT.
'/ticket/class/ticket.class.php';
31 require_once DOL_DOCUMENT_ROOT.
'/recruitment/class/recruitmentcandidature.class.php';
42 public $element =
'emailcollector';
46 public $table_element =
'emailcollector_emailcollector';
50 public $ismultientitymanaged = 1;
54 public $isextrafieldmanaged = 0;
59 public $picto =
'email';
64 public $fk_element =
'fk_emailcollector';
69 protected $childtables = array();
73 protected $childtablesoncascade = array(
'emailcollector_emailcollectorfilter',
'emailcollector_emailcollectoraction');
99 public $fields = array(
100 'rowid' => array(
'type'=>
'integer',
'label'=>
'TechnicalID',
'visible'=>2,
'enabled'=>1,
'position'=>1,
'notnull'=>1,
'index'=>1),
101 'entity' => array(
'type'=>
'integer',
'label'=>
'Entity',
'enabled'=>1,
'visible'=>0,
'default'=>1,
'notnull'=>1,
'index'=>1,
'position'=>20),
102 'ref' => array(
'type'=>
'varchar(128)',
'label'=>
'Ref',
'enabled'=>1,
'visible'=>1,
'notnull'=>1,
'showoncombobox'=>1,
'index'=>1,
'position'=>10,
'searchall'=>1,
'help'=>
'Example: MyCollector1'),
103 'label' => array(
'type'=>
'varchar(255)',
'label'=>
'Label',
'visible'=>1,
'enabled'=>1,
'position'=>30,
'notnull'=>-1,
'searchall'=>1,
'help'=>
'Example: My Email collector'),
104 'description' => array(
'type'=>
'text',
'label'=>
'Description',
'visible'=>-1,
'enabled'=>1,
'position'=>60,
'notnull'=>-1),
105 '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'),
106 'hostcharset' => array(
'type'=>
'varchar(16)',
'label'=>
'HostCharset',
'visible'=>-1,
'enabled'=>1,
'position'=>91,
'notnull'=>0,
'searchall'=>0,
'comment'=>
"IMAP server charset",
'help'=>
'Example: "UTF-8" (May be "US-ASCII" with some Office365)'),
107 'login' => array(
'type'=>
'varchar(128)',
'label'=>
'Login',
'visible'=>1,
'enabled'=>1,
'position'=>101,
'notnull'=>-1,
'index'=>1,
'comment'=>
"IMAP login",
'help'=>
'Example: myaccount@gmail.com'),
108 'password' => array(
'type'=>
'password',
'label'=>
'Password',
'visible'=>-1,
'enabled'=>1,
'position'=>102,
'notnull'=>-1,
'comment'=>
"IMAP password",
'help'=>
'WithGMailYouCanCreateADedicatedPassword'),
109 'source_directory' => array(
'type'=>
'varchar(255)',
'label'=>
'MailboxSourceDirectory',
'visible'=>-1,
'enabled'=>1,
'position'=>103,
'notnull'=>1,
'default' =>
'Inbox',
'help'=>
'Example: INBOX'),
112 'target_directory' => array(
'type'=>
'varchar(255)',
'label'=>
'MailboxTargetDirectory',
'visible'=>1,
'enabled'=>1,
'position'=>110,
'notnull'=>0,
'help'=>
"EmailCollectorTargetDir"),
113 'maxemailpercollect' => array(
'type'=>
'integer',
'label'=>
'MaxEmailCollectPerCollect',
'visible'=>-1,
'enabled'=>1,
'position'=>111,
'default'=>100),
114 'datelastresult' => array(
'type'=>
'datetime',
'label'=>
'DateLastCollectResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>121,
'notnull'=>-1,),
115 'codelastresult' => array(
'type'=>
'varchar(16)',
'label'=>
'CodeLastResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>122,
'notnull'=>-1,),
116 'lastresult' => array(
'type'=>
'varchar(255)',
'label'=>
'LastResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>123,
'notnull'=>-1,),
117 'datelastok' => array(
'type'=>
'datetime',
'label'=>
'DateLastcollectResultOk',
'visible'=>1,
'enabled'=>
'$action != "create"',
'position'=>125,
'notnull'=>-1,),
118 'note_public' => array(
'type'=>
'html',
'label'=>
'NotePublic',
'visible'=>0,
'enabled'=>1,
'position'=>61,
'notnull'=>-1,),
119 'note_private' => array(
'type'=>
'html',
'label'=>
'NotePrivate',
'visible'=>0,
'enabled'=>1,
'position'=>62,
'notnull'=>-1,),
120 'date_creation' => array(
'type'=>
'datetime',
'label'=>
'DateCreation',
'visible'=>-2,
'enabled'=>1,
'position'=>500,
'notnull'=>1,),
121 'tms' => array(
'type'=>
'timestamp',
'label'=>
'DateModification',
'visible'=>-2,
'enabled'=>1,
'position'=>501,
'notnull'=>1,),
123 'fk_user_creat' => array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserAuthor',
'visible'=>-2,
'enabled'=>1,
'position'=>510,
'notnull'=>1,),
124 'fk_user_modif' => array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserModif',
'visible'=>-2,
'enabled'=>1,
'position'=>511,
'notnull'=>-1,),
126 'import_key' => array(
'type'=>
'varchar(14)',
'label'=>
'ImportId',
'visible'=>-2,
'enabled'=>1,
'position'=>1000,
'notnull'=>-1,),
127 'status' => array(
'type'=>
'integer',
'label'=>
'Status',
'visible'=>1,
'enabled'=>1,
'position'=>1000,
'notnull'=>1,
'index'=>1,
'arrayofkeyval'=>array(
'0'=>
'Inactive',
'1'=>
'Active'))
160 public $date_creation;
170 public $fk_user_creat;
175 public $fk_user_modif;
187 public $source_directory;
188 public $target_directory;
189 public $maxemailpercollect;
194 public $datelastresult;
205 const STATUS_DISABLED = 0;
206 const STATUS_ENABLED = 1;
216 global $conf, $langs;
220 if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->
fields[
'rowid'])) $this->
fields[
'rowid'][
'visible'] = 0;
221 if (empty($conf->multicompany->enabled) && isset($this->
fields[
'entity'])) $this->
fields[
'entity'][
'enabled'] = 0;
224 foreach ($this->
fields as $key => $val)
226 if (isset($val[
'enabled']) && empty($val[
'enabled']))
228 unset($this->
fields[$key]);
233 foreach ($this->
fields as $key => $val)
235 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval']))
237 foreach ($val[
'arrayofkeyval'] as $key2 => $val2)
239 $this->
fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
256 if (is_array($this->filters) && count($this->filters)) {
259 foreach ($this->filters as $filter) {
260 $emailcollectorfilter->type = $filter[
'type'];
261 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
262 $emailcollectorfilter->fk_emailcollector = $this->id;
263 $emailcollectorfilter->status = $filter[
'status'];
265 $emailcollectorfilter->create($user);
269 if (is_array($this->filters) && count($this->filters)) {
272 foreach ($this->actions as $operation) {
273 $emailcollectoroperation->type = $operation[
'type'];
274 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
275 $emailcollectoroperation->fk_emailcollector = $this->id;
276 $emailcollectoroperation->status = $operation[
'status'];
277 $emailcollectoroperation->position = $operation[
'position'];
279 $emailcollectoroperation->create($user);
295 global $langs, $extrafields;
300 $object =
new self($this->db);
305 $object->fetchCommon($fromid);
307 $object->fetchFilters();
308 $object->fetchActions();
312 unset($object->fk_user_creat);
313 unset($object->import_key);
316 $object->ref =
"copy_of_".$object->ref;
317 $object->title = $langs->trans(
"CopyOf").
" ".$object->title;
320 if (is_array($object->array_options) && count($object->array_options) > 0)
322 $extrafields->fetch_name_optionals_label($this->table_element);
323 foreach ($object->array_options as $key => $option)
325 $shortkey = preg_replace(
'/options_/',
'', $key);
326 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey]))
329 unset($object->array_options[$key]);
335 $object->context[
'createfromclone'] =
'createfromclone';
336 $result = $object->create($user);
339 $this->error = $object->error;
340 $this->errors = $object->errors;
343 unset($object->context[
'createfromclone']);
350 $this->
db->rollback();
362 public function fetch($id, $ref = null)
396 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
402 $sql =
"SELECT s.rowid";
403 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
404 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
406 $sql .=
" AND s.status = 1";
408 $sql .= $this->
db->order($sortfield, $sortorder);
413 $offset = $limit * $page;
415 $sql .= $this->
db->plimit($limit + 1, $offset);
418 $result = $this->
db->query($sql);
420 $num = $this->
db->num_rows($result);
424 $obj = $this->
db->fetch_object($result);
426 if ($emailcollector_static->fetch($obj->rowid)) {
427 $obj_ret[] = $emailcollector_static;
432 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
433 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
436 if (!count($obj_ret)) {
437 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
462 public function delete(
User $user, $notrigger =
false)
477 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
479 global $conf, $langs, $hookmanager;
481 if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1;
485 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
487 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
489 $url =
dol_buildpath(
'/admin/emailcollector_card.php', 1).
'?id='.$this->id;
491 if ($option !=
'nolink')
494 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
495 if ($save_lastsearch_value == -1 && preg_match(
'/list\.php/',
$_SERVER[
"PHP_SELF"])) {
496 $add_save_lastsearch_values = 1;
498 if ($add_save_lastsearch_values) {
499 $url .=
'&save_lastsearch_values=1';
504 if (empty($notooltip))
506 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
508 $label = $langs->trans(
"ShowEmailCollector");
509 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
511 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
512 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
520 }
else $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
522 $linkstart =
'<a href="'.$url.
'"';
523 $linkstart .= $linkclose.
'>';
526 $result .= $linkstart;
527 if ($withpicto) $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);
528 if ($withpicto != 2) $result .= $this->ref;
532 global $action, $hookmanager;
533 $hookmanager->initHooks(array(
'emailcollectordao'));
534 $parameters = array(
'id'=>$this->
id,
'getnomurl'=>$result);
535 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
536 if ($reshook > 0) $result = $hookmanager->resPrint;
537 else $result .= $hookmanager->resPrint;
550 return $this->
LibStatut($this->status, $mode);
564 if (empty($this->labelStatus) || empty($this->labelStatusShort))
568 $this->labelStatus[self::STATUS_ENABLED] = $langs->trans(
'Enabled');
569 $this->labelStatus[self::STATUS_DISABLED] = $langs->trans(
'Disabled');
570 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->trans(
'Enabled');
571 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->trans(
'Disabled');
574 $statusType =
'status5';
575 if ($status == self::STATUS_ENABLED) $statusType =
'status4';
577 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
588 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
589 $sql .=
' fk_user_creat, fk_user_modif';
590 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
591 $sql .=
' WHERE t.rowid = '.$id;
592 $result = $this->
db->query($sql);
595 if ($this->
db->num_rows($result))
597 $obj = $this->
db->fetch_object($result);
598 $this->
id = $obj->rowid;
599 if ($obj->fk_user_author)
601 $cuser =
new User($this->
db);
602 $cuser->fetch($obj->fk_user_author);
603 $this->user_creation = $cuser;
606 if ($obj->fk_user_valid)
608 $vuser =
new User($this->
db);
609 $vuser->fetch($obj->fk_user_valid);
610 $this->user_validation = $vuser;
613 if ($obj->fk_user_cloture)
615 $cluser =
new User($this->
db);
616 $cluser->fetch($obj->fk_user_cloture);
617 $this->user_cloture = $cluser;
620 $this->date_creation = $this->
db->jdate($obj->datec);
621 $this->date_modification = $this->
db->jdate($obj->datem);
622 $this->date_validation = $this->
db->jdate($obj->datev);
625 $this->
db->free($result);
650 $this->filters = array();
652 $sql =
'SELECT rowid, type, rulevalue, status';
653 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
654 $sql .=
' WHERE fk_emailcollector = '.$this->id;
664 $obj = $this->
db->fetch_object(
$resql);
665 $this->filters[$obj->rowid] = array(
'id'=>$obj->rowid,
'type'=>$obj->type,
'rulevalue'=>$obj->rulevalue,
'status'=>$obj->status);
682 $this->actions = array();
684 $sql =
'SELECT rowid, type, actionparam, status';
685 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
686 $sql .=
' WHERE fk_emailcollector = '.$this->id;
687 $sql .=
' ORDER BY position';
696 $obj = $this->
db->fetch_object(
$resql);
697 $this->actions[$obj->rowid] = array(
'id'=>$obj->rowid,
'type'=>$obj->type,
'actionparam'=>$obj->actionparam,
'status'=>$obj->status);
717 $flags =
'/service=imap';
718 if (!empty($conf->global->IMAP_FORCE_TLS)) {
720 } elseif (empty($conf->global->IMAP_FORCE_NOSSL)) {
721 if ($ssl) $flags .=
'/ssl';
723 $flags .=
'/novalidate-cert';
726 if ($norsh || !empty($conf->global->IMAP_FORCE_NORSH)) $flags .=
'/norsh';
728 $connectstringserver =
'{'.$this->host.
':993'.$flags.
'}';
730 return $connectstringserver;
741 if (function_exists(
'mb_convert_encoding')) {
743 $str = preg_replace(
"/ /",
"xyxy", $str);
745 if ($str = mb_convert_encoding($str,
"UTF-7")) {
747 $str = preg_replace(
"/\+A/",
"&A", $str);
749 $str = preg_replace(
"/xyxy/",
" ", $str);
753 $this->error =
"error: is not possible to encode this string '".$str.
"'";
773 $arrayofcollectors = $this->
fetchAll($user, 1);
776 foreach ($arrayofcollectors as $emailcollector)
778 $result = $emailcollector->doCollectOneCollector();
779 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
781 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
782 if (!empty($emailcollector->errors)) $this->error .= join(
'<br>', $emailcollector->errors);
783 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
801 $errorforthisaction = 0;
806 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty)
808 $tmpclass =
''; $tmpproperty =
'';
809 $tmparray = explode(
'.', $propertytooverwrite);
810 if (count($tmparray) == 2)
812 $tmpclass = $tmparray[0];
813 $tmpproperty = $tmparray[1];
815 $tmpproperty = $tmparray[0];
817 if ($tmpclass && ($tmpclass != $object->element))
continue;
826 $regforregex = array();
827 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9]+):(.*):([^:])$/', $valueforproperty, $regforregex))
829 $sourcefield = $regforregex[1];
830 $regexstring = $regforregex[2];
832 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9]+):(.*)$/', $valueforproperty, $regforregex))
834 $sourcefield = $regforregex[1];
835 $regexstring = $regforregex[2];
837 if (!empty($sourcefield) && !empty($regexstring))
839 if (strtolower($sourcefield) ==
'body') $sourcestring = $messagetext;
840 elseif (strtolower($sourcefield) ==
'subject') $sourcestring = $subject;
841 elseif (strtolower($sourcefield) ==
'header') $sourcestring = $header;
845 $regforval = array();
847 if (strtolower($sourcefield) ==
'body') $regexoptions =
'ms';
848 if (strtolower($sourcefield) ==
'header') $regexoptions =
'm';
851 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval))
855 $valueextracted = isset($regforval[count($regforval) - 1]) ?trim($regforval[count($regforval) - 1]) : null;
856 if (strtolower($sourcefield) ==
'header') {
859 $object->$tmpproperty = $valueextracted;
863 $object->$tmpproperty = null;
867 $errorforthisaction++;
868 $this->error =
'The extract rule to use has on an unknown source (must be HEADER, SUBJECT or BODY)';
869 $this->errors[] = $this->error;
871 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex))
874 if (preg_match(
'/^options_/', $tmpproperty)) $valuecurrent = $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
875 else $valuecurrent = $object->$tmpproperty;
877 if ($regforregex[1] ==
'SET' || empty($valuecurrent))
879 $valuetouse = $regforregex[2];
880 $substitutionarray = array();
881 $matcharray = array();
882 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
884 if (is_array($matcharray[1]))
886 foreach ($matcharray[1] as $keytoreplace)
888 if ($keytoreplace && isset($object->$keytoreplace))
890 $substitutionarray[
'__'.$keytoreplace.
'__'] = $object->$keytoreplace;
895 dol_syslog(var_export($substitutionarray,
true));
898 if (preg_match(
'/^options_/', $tmpproperty)) $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
899 else $object->$tmpproperty = $valuetouse;
902 $errorforthisaction++;
903 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
904 $this->errors[] = $this->error;
909 return $errorforthisaction;
919 global $conf, $langs, $user;
923 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
925 dol_syslog(
"EmailCollector::doCollectOneCollector start", LOG_DEBUG);
927 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda"));
935 if (empty($this->host))
937 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
940 if (empty($this->login))
942 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
945 if (empty($this->source_directory))
947 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
950 if (!function_exists(
'imap_open'))
952 $this->error =
'IMAP function not enabled on your PHP';
959 $sourcedir = $this->source_directory;
960 $targetdir = ($this->target_directory ? $this->target_directory :
'');
963 $connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
964 $connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
966 $connection = imap_open($connectstringsource, $this->login, $this->password);
969 $this->error =
'Failed to open IMAP connection '.$connectstringsource;
974 $host = dol_getprefix(
'email');
981 $search =
'UNDELETED';
983 $searchfilterdoltrackid = 0;
984 $searchfilternodoltrackid = 0;
985 $searchfilterisanswer = 0;
986 $searchfilterisnotanswer = 0;
987 foreach ($this->filters as $rule)
989 if (empty($rule[
'status']))
continue;
991 if ($rule[
'type'] ==
'to') {
992 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
993 if (count($tmprulevaluearray) >= 2) {
994 foreach ($tmprulevaluearray as $tmprulevalue) {
995 $search .= ($search ?
' ' :
'').
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
998 $search .= ($search ?
' ' :
'').
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1001 if ($rule[
'type'] ==
'bcc') $search .= ($search ?
' ' :
'').
'BCC';
1002 if ($rule[
'type'] ==
'cc') $search .= ($search ?
' ' :
'').
'CC';
1003 if ($rule[
'type'] ==
'from') $search .= ($search ?
' ' :
'').
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1004 if ($rule[
'type'] ==
'subject') $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1005 if ($rule[
'type'] ==
'body') $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1006 if ($rule[
'type'] ==
'header') $search .= ($search ?
' ' :
'').
'HEADER '.$rule[
'rulevalue'];
1008 if ($rule[
'type'] ==
'notinsubject') $search .= ($search ?
' ' :
'').
'SUBJECT NOT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1009 if ($rule[
'type'] ==
'notinbody') $search .= ($search ?
' ' :
'').
'BODY NOT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1011 if ($rule[
'type'] ==
'seen') $search .= ($search ?
' ' :
'').
'SEEN';
1012 if ($rule[
'type'] ==
'unseen') $search .= ($search ?
' ' :
'').
'UNSEEN';
1013 if ($rule[
'type'] ==
'unanswered') $search .= ($search ?
' ' :
'').
'UNANSWERED';
1014 if ($rule[
'type'] ==
'answered') $search .= ($search ?
' ' :
'').
'ANSWERED';
1015 if ($rule[
'type'] ==
'smaller') $search .= ($search ?
' ' :
'').
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1016 if ($rule[
'type'] ==
'larger') $search .= ($search ?
' ' :
'').
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1018 if ($rule[
'type'] ==
'withtrackingidinmsgid') { $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/'; }
1019 if ($rule[
'type'] ==
'withouttrackingidinmsgid') { $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/'; }
1020 if ($rule[
'type'] ==
'withtrackingid') { $searchfilterdoltrackid++; $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/'; }
1021 if ($rule[
'type'] ==
'withouttrackingid') { $searchfilternodoltrackid++; $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/'; }
1023 if ($rule[
'type'] ==
'isanswer') { $searchfilterisanswer++; $searchhead .=
'/References.*@.*/'; }
1024 if ($rule[
'type'] ==
'isnotanswer') { $searchfilterisnotanswer++; $searchhead .=
'! /References.*@.*/'; }
1027 if (empty($targetdir))
1030 if ($this->datelastok) $fromdate = $this->datelastok;
1031 if ($fromdate > 0) $search .= ($search ?
' ' :
'').
'SINCE '.date(
'j-M-Y', $fromdate - 1);
1037 $nbemailprocessed = 0;
1040 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1043 $arrayofemail = imap_search($connection, $search, null, $charset);
1044 if ($arrayofemail ===
false)
1047 $mapoferrrors = imap_errors();
1048 if ($mapoferrrors !==
false)
1051 $this->error =
"Search string not understood - ".join(
',', $mapoferrrors);
1052 $this->errors[] = $this->error;
1057 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0)
1132 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1135 foreach ($arrayofemail as $imapemail)
1137 if ($nbemailprocessed > 1000)
1144 $header = imap_fetchheader($connection, $imapemail, 0);
1145 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1150 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches);
1151 $headers = array_combine($matches[1], $matches[2]);
1153 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) { $headers[
'In-Reply-To'] = $headers[
'in-reply-to']; }
1154 if (!empty($headers[
'references']) && empty($headers[
'References'])) { $headers[
'References'] = $headers[
'references']; }
1155 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) { $headers[
'Message-ID'] = $headers[
'message-id']; }
1160 dol_syslog(
"** Process email ".$iforemailloop.
" References: ".$headers[
'References']);
1164 if ($searchfilterdoltrackid > 0)
1166 if (empty($headers[
'References']) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))
1168 $nbemailprocessed++;
1172 if ($searchfilternodoltrackid > 0)
1174 if (!empty($headers[
'References']) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))
1176 $nbemailprocessed++;
1181 if ($searchfilterisanswer > 0) {
1182 if (empty($headers[
'In-Reply-To']))
1184 $nbemailprocessed++;
1190 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) $isanswer = 1;
1195 $nbemailprocessed++;
1199 if ($searchfilterisnotanswer > 0) {
1200 if (!empty($headers[
'In-Reply-To']))
1205 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) $isanswer = 1;
1209 $nbemailprocessed++;
1217 $thirdpartystatic =
new Societe($this->
db);
1218 $contactstatic =
new Contact($this->
db);
1219 $projectstatic =
new Project($this->
db);
1221 $nbactiondoneforemail = 0;
1223 $errorforactions = 0;
1224 $thirdpartyfoundby =
'';
1225 $contactfoundby =
'';
1226 $projectfoundby =
'';
1227 $ticketfoundby =
'';
1228 $candidaturefoundby =
'';
1234 $overview = imap_fetch_overview($connection, $imapemail, 0);
1236 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);
1243 $overview[0]->subject = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $overview[0]->subject);
1246 global $htmlmsg, $plainmsg, $charset, $attachments;
1247 $this->
getmsg($connection, $imapemail);
1252 $messagetext = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $messagetext);
1307 $fromstring = $overview[0]->from;
1309 $sender = $overview[0]->sender;
1310 $to = $overview[0]->to;
1311 $sendtocc = $overview[0]->cc;
1312 $sendtobcc = $overview[0]->bcc;
1313 $date = $overview[0]->udate;
1314 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1315 $subject = $overview[0]->subject;
1319 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg))
1322 $fromtext = $reg[1];
1324 $from = $fromstring;
1327 $fk_element_id = 0; $fk_element_type =
'';
1330 $contactid = 0; $thirdpartyid = 0; $projectid = 0; $ticketid = 0;
1338 $objectemail = null;
1341 if (!empty($headers[
'References']))
1343 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
1347 foreach ($arrayofreferences as $reference) {
1349 if (preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg)) {
1351 $trackid = $reg[1].$reg[2];
1353 $objectid = $reg[2];
1355 if ($reg[1] ==
'thi')
1359 if ($reg[1] ==
'ctc')
1363 if ($reg[1] ==
'inv')
1367 if ($reg[1] ==
'proj')
1371 if ($reg[1] ==
'tas')
1373 $objectemail =
new Task($this->
db);
1375 if ($reg[1] ==
'con')
1379 if ($reg[1] ==
'use')
1381 $objectemail =
new User($this->
db);
1383 if ($reg[1] ==
'tic')
1385 $objectemail =
new Ticket($this->
db);
1387 if ($reg[1] ==
'recruitmentcandidature')
1391 if ($reg[1] ==
'mem')
1395 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
1397 if (!is_object($objectemail)) {
1398 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket where email_msgid = '".$this->
db->escape($reg[1]).
"'";
1401 $obj = $this->
db->fetch_object(
$resql);
1403 $objectid = $obj->rowid;
1404 $objectemail =
new Ticket($this->
db);
1405 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
1412 if (!is_object($objectemail)) {
1413 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->
db->escape($reg[1]).
"'";
1416 $obj = $this->
db->fetch_object(
$resql);
1418 $objectid = $obj->rowid;
1420 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
1427 if (!is_object($objectemail)) {
1428 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->
db->escape($reg[1]).
"'";
1431 $obj = $this->
db->fetch_object(
$resql);
1433 $objectid = $obj->rowid;
1435 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
1444 if (is_object($objectemail))
1446 $result = $objectemail->fetch($objectid);
1449 $fk_element_id = $objectemail->id;
1450 $fk_element_type = $objectemail->element;
1452 if ($fk_element_type ==
'facture') $fk_element_type =
'invoice';
1454 if (get_class($objectemail) !=
'Societe') $thirdpartyid = $objectemail->fk_soc;
1455 else $thirdpartyid = $objectemail->id;
1457 if (get_class($objectemail) !=
'Contact') $contactid = $objectemail->fk_socpeople;
1458 else $contactid = $objectemail->id;
1460 if (get_class($objectemail) !=
'Project') $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
1461 else $projectid = $objectemail->id;
1468 $result = $projectstatic->fetch($projectid);
1469 if ($result <= 0) $projectstatic->id = 0;
1471 $projectid = $projectstatic->id;
1472 if ($trackid) $projectfoundby =
'trackid ('.$trackid.
')';
1473 if (empty($contactid)) $contactid = $projectstatic->fk_contact;
1474 if (empty($thirdpartyid)) $thirdpartyid = $projectstatic->fk_soc;
1480 $result = $contactstatic->fetch($contactid);
1481 if ($result <= 0) $contactstatic->id = 0;
1483 $contactid = $contactstatic->id;
1484 if ($trackid) $contactfoundby =
'trackid ('.$trackid.
')';
1485 if (empty($thirdpartyid)) $thirdpartyid = $contactstatic->fk_soc;
1489 if ($thirdpartyid > 0)
1491 $result = $thirdpartystatic->fetch($thirdpartyid);
1492 if ($result <= 0) $thirdpartystatic->id = 0;
1494 $thirdpartyid = $thirdpartystatic->id;
1495 if ($trackid) $thirdpartyfoundby =
'trackid ('.$trackid.
')';
1499 if (is_object($objectemail))
1506 if (empty($contactid))
1508 $result = $contactstatic->fetch(0, null,
'', $from);
1512 $contactid = $contactstatic->id;
1513 $contactfoundby =
'email of contact ('.$from.
')';
1514 if (empty($thirdpartyid) && $contactstatic->socid > 0)
1516 $result = $thirdpartystatic->fetch($contactstatic->socid);
1519 $thirdpartyid = $thirdpartystatic->id;
1520 $thirdpartyfoundby =
'email of contact ('.$from.
')';
1526 if (empty($thirdpartyid))
1528 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
1529 if ($result > 0) $thirdpartyfoundby =
'email ('.$from.
')';
1533 foreach ($this->actions as $operation)
1535 $errorforthisaction = 0;
1537 if ($errorforactions)
break;
1538 if (empty($operation[
'status']))
continue;
1541 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
1542 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
1544 $actioncode =
'EMAIL_IN';
1546 if ($this->source_directory ==
'Sent') $actioncode =
'EMAIL_OUT';
1548 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
1550 $descriptiontitle = $langs->trans(
"RecordCreatedByEmailCollector", $this->ref, $msgid);
1553 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
1554 if ($sender) $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
1555 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
1556 if ($sendtocc) $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
1559 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty')
1561 if (empty($operation[
'actionparam'])) {
1563 $this->error =
"Action loadthirdparty or loadandcreatethirdparty has empty parameter. Must be a rule like 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to set or extract data";
1564 $this->errors[] = $this->error;
1566 $actionparam = $operation[
'actionparam'];
1567 $nametouseforthirdparty =
'';
1571 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty)
1576 $regforregex = array();
1578 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9]+):(.*)$/', $valueforproperty, $regforregex))
1580 $sourcefield = $regforregex[1];
1581 $regexstring = $regforregex[2];
1584 if (!empty($sourcefield) && !empty($regexstring))
1586 if (strtolower($sourcefield) ==
'body') $sourcestring = $messagetext;
1587 elseif (strtolower($sourcefield) ==
'subject') $sourcestring = $subject;
1588 elseif (strtolower($sourcefield) ==
'header') $sourcestring = $header;
1592 $regforval = array();
1594 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval))
1598 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
1601 $nametouseforthirdparty = null;
1607 $this->error =
'The extract rule to use to load thirdparty has on an unknown source (must be HEADER, SUBJECT or BODY)';
1608 $this->errors[] = $this->error;
1610 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg))
1614 $nametouseforthirdparty = $reg[2];
1617 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1618 $this->errors[] = $this->error;
1623 if (!$errorforactions && $nametouseforthirdparty)
1625 $result = $thirdpartystatic->fetch(0, $nametouseforthirdparty);
1629 $this->error =
'Error when getting thirdparty with name '.$nametouseforthirdparty.
' (may be 2 record exists with same name ?)';
1630 $this->errors[] = $this->error;
1632 } elseif ($result == 0)
1634 if ($operation[
'type'] ==
'loadthirdparty')
1636 dol_syslog(
"Third party with name ".$nametouseforthirdparty.
" was not found");
1639 $this->error =
'ErrorFailedToLoadThirdParty';
1640 $this->errors[] =
'ErrorFailedToLoadThirdParty';
1641 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty')
1643 dol_syslog(
"Third party with name ".$nametouseforthirdparty.
" was not found. We try to create it.");
1646 $thirdpartystatic->name = $nametouseforthirdparty;
1647 if ($fromtext != $nametouseforthirdparty) $thirdpartystatic->name_alias = $fromtext;
1648 $thirdpartystatic->email = $from;
1651 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header);
1653 if ($errorforthisaction)
1657 $result = $thirdpartystatic->create($user);
1661 $this->error = $thirdpartystatic->error;
1662 $this->errors = $thirdpartystatic->errors;
1671 elseif ($operation[
'type'] ==
'recordevent')
1675 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
1676 if ($alreadycreated == 0)
1678 if ($projectstatic->id > 0)
1680 if ($projectfoundby) $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
1682 if ($thirdpartystatic->id > 0)
1684 if ($thirdpartyfoundby) $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
1686 if ($contactstatic->id > 0)
1688 if ($contactfoundby) $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
1691 $description = $descriptiontitle;
1697 $descriptionfull = $description;
1698 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
1699 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
1704 $actioncomm->type_code =
'AC_OTH_AUTO';
1705 $actioncomm->code =
'AC_'.$actioncode;
1706 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
1707 $actioncomm->note_private = $descriptionfull;
1708 $actioncomm->fk_project = $projectstatic->id;
1709 $actioncomm->datep = $date;
1710 $actioncomm->datef = $date;
1711 $actioncomm->percentage = -1;
1712 $actioncomm->socid = $thirdpartystatic->id;
1713 $actioncomm->contact_id = $contactstatic->id;
1714 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id =>
'') : array());
1715 $actioncomm->authorid = $user->id;
1716 $actioncomm->userownerid = $user->id;
1718 $actioncomm->email_msgid = $msgid;
1719 $actioncomm->email_from = $fromstring;
1720 $actioncomm->email_sender = $sender;
1721 $actioncomm->email_to = $to;
1722 $actioncomm->email_tocc = $sendtocc;
1723 $actioncomm->email_tobcc = $sendtobcc;
1724 $actioncomm->email_subject = $subject;
1725 $actioncomm->errors_to =
'';
1727 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user')))
1729 $actioncomm->fk_element = $fk_element_id;
1730 $actioncomm->elementid = $fk_element_id;
1731 $actioncomm->elementtype = $fk_element_type;
1732 if (is_object($objectemail) && $objectemail->module) {
1733 $actioncomm->elementtype .=
'@'.$objectemail->module;
1740 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header);
1749 if ($errorforthisaction)
1753 $result = $actioncomm->create($user);
1757 $this->errors = $actioncomm->errors;
1763 elseif ($operation[
'type'] ==
'project')
1765 $projecttocreate =
new Project($this->
db);
1767 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
1768 if ($alreadycreated == 0)
1770 if ($thirdpartystatic->id > 0)
1772 $projecttocreate->socid = $thirdpartystatic->id;
1773 if ($thirdpartyfoundby) $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
1775 if ($contactstatic->id > 0)
1777 $projecttocreate->contact_id = $contactstatic->id;
1778 if ($contactfoundby) $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
1781 $description = $descriptiontitle;
1787 $descriptionfull = $description;
1788 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
1789 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
1794 $percent_opp_status =
dol_getIdFromCode($this->
db,
'PROSP',
'c_lead_status',
'code',
'percent');
1796 $projecttocreate->title = $subject;
1797 $projecttocreate->date_start = $date;
1798 $projecttocreate->date_end =
'';
1799 $projecttocreate->opp_status = $id_opp_status;
1800 $projecttocreate->opp_percent = $percent_opp_status;
1802 $projecttocreate->note_private = $descriptionfull;
1803 $projecttocreate->entity = $conf->entity;
1804 $projecttocreate->email_msgid = $msgid;
1806 $savesocid = $projecttocreate->socid;
1810 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header);
1813 if (empty($projecttocreate->ref))
1817 $modele = empty($conf->global->PROJECT_ADDON) ?
'mod_project_simple' : $conf->global->PROJECT_ADDON;
1820 $file =
''; $classname =
''; $filefound = 0; $reldir =
'';
1821 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
1822 foreach ($dirmodels as $reldir)
1824 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
1825 if (file_exists($file))
1828 $classname = $modele;
1837 if ($savesocid != $projecttocreate->socid)
1840 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');
1843 if ($projecttocreate->socid > 0)
1845 $thirdpartystatic->fetch($projecttocreate->socid);
1849 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
1850 $modModuleToUseForNextValue =
new $classname;
1851 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
1853 $projecttocreate->ref = $defaultref;
1856 if ($errorforthisaction)
1860 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0))
1863 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
1866 $result = $projecttocreate->create($user);
1870 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
1871 $this->errors = $projecttocreate->errors;
1878 elseif ($operation[
'type'] ==
'ticket')
1880 $tickettocreate =
new Ticket($this->
db);
1882 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
1883 if ($alreadycreated == 0)
1885 if ($thirdpartystatic->id > 0)
1887 $tickettocreate->socid = $thirdpartystatic->id;
1888 $tickettocreate->fk_soc = $thirdpartystatic->id;
1889 if ($thirdpartyfoundby) $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
1891 if ($contactstatic->id > 0)
1893 $tickettocreate->contact_id = $contactstatic->id;
1894 if ($contactfoundby) $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
1897 $description = $descriptiontitle;
1903 $descriptionfull = $description;
1904 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
1905 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
1909 $tickettocreate->subject = $subject;
1910 $tickettocreate->message = $description;
1911 $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));
1912 $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));
1913 $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));
1914 $tickettocreate->origin_email = $from;
1915 $tickettocreate->fk_user_create = $user->id;
1916 $tickettocreate->datec = $date;
1917 $tickettocreate->fk_project = $projectstatic->id;
1918 $tickettocreate->notify_tiers_at_create = 0;
1919 $tickettocreate->note_private = $descriptionfull;
1920 $tickettocreate->entity = $conf->entity;
1921 $tickettocreate->email_msgid = $msgid;
1924 $savesocid = $tickettocreate->socid;
1928 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header);
1931 if (empty($tickettocreate->ref))
1935 $modele = empty($conf->global->TICKET_ADDON) ?
'mod_ticket_simple' : $conf->global->TICKET_ADDON;
1938 $file =
''; $classname =
''; $filefound = 0; $reldir =
'';
1939 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
1940 foreach ($dirmodels as $reldir)
1942 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
1943 if (file_exists($file))
1946 $classname = $modele;
1955 if ($savesocid != $tickettocreate->socid)
1958 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');
1961 if ($tickettocreate->socid > 0)
1963 $thirdpartystatic->fetch($tickettocreate->socid);
1968 $modModuleToUseForNextValue =
new $classname;
1969 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
1971 $tickettocreate->ref = $defaultref;
1974 if ($errorforthisaction)
1978 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0)
1981 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
1984 $result = $tickettocreate->create($user);
1988 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
1989 $this->errors = $tickettocreate->errors;
1996 elseif ($operation[
'type'] ==
'candidature')
2000 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
2001 if ($alreadycreated == 0)
2003 $description = $descriptiontitle;
2009 $descriptionfull = $description;
2010 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2013 $candidaturetocreate->subject = $subject;
2014 $candidaturetocreate->message = $description;
2015 $candidaturetocreate->type_code = 0;
2016 $candidaturetocreate->category_code = null;
2017 $candidaturetocreate->severity_code = null;
2018 $candidaturetocreate->email = $from;
2020 $candidaturetocreate->fk_user_creat = $user->id;
2021 $candidaturetocreate->date_creation = $date;
2022 $candidaturetocreate->fk_project = $projectstatic->id;
2023 $candidaturetocreate->description = $description;
2024 $candidaturetocreate->note_private = $descriptionfull;
2025 $candidaturetocreate->entity = $conf->entity;
2026 $candidaturetocreate->email_msgid = $msgid;
2027 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
2032 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header);
2078 if ($errorforthisaction)
2083 $result = $candidaturetocreate->create($user);
2087 $this->error =
'Failed to create ticket: '.join(
', ', $candidaturetocreate->errors);
2088 $this->errors = $candidaturetocreate->errors;
2095 elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
2096 global $hookmanager;
2098 if (!is_object($hookmanager)) {
2099 $hookmanager->initHooks(array(
'emailcollectorcard'));
2102 $parameters = array(
2103 'connection'=> $connection,
2104 'imapemail'=>$imapemail,
2105 'overview'=>$overview,
2108 'fromtext' => $fromtext,
2110 'actionparam'=> $operation[
'actionparam'],
2112 'thirdpartyid' => $thirdpartyid,
2113 'objectid'=> $objectid,
2114 'objectemail'=> $objectemail,
2116 'messagetext'=>$messagetext,
2117 'subject'=>$subject,
2120 $res = $hookmanager->executeHooks(
'doCollectOneCollector', $parameters, $this, $operation[
'type']);
2123 $errorforthisaction++;
2124 $this->error = $hookmanager->resPrint;
2126 if ($errorforthisaction)
2132 if (!$errorforactions)
2134 $nbactiondoneforemail++;
2139 if (!$errorforactions)
2143 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".$imapemail.
" to ".$connectstringtarget, LOG_DEBUG);
2144 $res = imap_mail_move($connection, $imapemail, $targetdir, 0);
2145 if ($res ==
false) {
2147 $this->error = imap_last_error();
2148 $this->errors[] = $this->error;
2152 dol_syslog(
"EmailCollector::doCollectOneCollector message ".$imapemail.
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
2158 unset($objectemail);
2159 unset($projectstatic);
2160 unset($thirdpartystatic);
2161 unset($contactstatic);
2163 $nbemailprocessed++;
2165 if (!$errorforemail)
2167 $nbactiondone += $nbactiondoneforemail;
2170 $this->
db->commit();
2173 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect)
2175 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
2181 $this->
db->rollback();
2185 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
2187 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
2189 $output = $langs->trans(
'NoNewEmailToProcess');
2192 imap_expunge($connection);
2194 imap_close($connection);
2196 $this->datelastresult = $now;
2197 $this->lastresult = $output;
2198 $this->debuginfo =
'IMAP search string used : '.$search;
2199 if ($searchhead) $this->debuginfo .=
'<br>Then search string into email header : '.$searchhead;
2201 if (!$error) $this->datelastok = $now;
2203 if (!empty($this->errors)) $this->lastresult .=
" - ".join(
" - ", $this->errors);
2204 $this->codelastresult = ($error ?
'KO' :
'OK');
2207 dol_syslog(
"EmailCollector::doCollectOneCollector end", LOG_DEBUG);
2209 return $error ?-1 : 1;
2227 global $charset, $htmlmsg, $plainmsg, $attachments;
2228 $htmlmsg = $plainmsg = $charset =
'';
2229 $attachments = array();
2236 $s = imap_fetchstructure($mbox, $mid);
2240 $this->
getpart($mbox, $mid, $s, 0);
2243 foreach ($s->parts as $partno0 => $p) {
2244 $this->
getpart($mbox, $mid, $p, $partno0 + 1);
2273 private function getpart($mbox, $mid, $p, $partno)
2276 global $htmlmsg, $plainmsg, $charset, $attachments;
2280 imap_fetchbody($mbox, $mid, $partno) :
2281 imap_body($mbox, $mid);
2283 if ($p->encoding == 4)
2284 $data = quoted_printable_decode($data);
2285 elseif ($p->encoding == 3)
2286 $data = base64_decode($data);
2293 foreach ($p->parameters as $x)
2295 $params[strtolower($x->attribute)] = $x->value;
2298 if ($p->dparameters)
2300 foreach ($p->dparameters as $x)
2302 $params[strtolower($x->attribute)] = $x->value;
2309 if ($params[
'filename'] || $params[
'name']) {
2311 $filename = ($params[
'filename']) ? $params[
'filename'] : $params[
'name'];
2313 $attachments[$filename] = $data;
2317 if ($p->type == 0 && $data) {
2318 if (!empty($params[
'charset'])) {
2323 if (strtolower($p->subtype) ==
'plain')
2324 $plainmsg .= trim($data).
"\n\n";
2325 else $htmlmsg .= $data.
"<br><br>";
2326 $charset = $params[
'charset'];
2334 elseif ($p->type == 2 && $data) {
2335 if (!empty($params[
'charset'])) {
2338 $plainmsg .= $data.
"\n\n";
2343 foreach ($p->parts as $partno0=>$p2)
2345 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1));
2361 if (!$string || $fromEncoding == $toEncoding) {
2364 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) : null;
2365 if (!$convertedString && extension_loaded(
'mbstring')) {
2366 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
2368 if (!$convertedString) {
2369 throw new Exception(
'Mime string encoding conversion failed');
2371 return $convertedString;
2390 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
2391 $elements = imap_mime_header_decode($subject);
2393 if (!empty($elements)) {
2394 $num = count($elements);
2395 for ($i = 0; $i < $num; $i++) {
2396 $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));
2397 $newstring .= $stringinutf8;
2399 $subject = $newstring;
2401 } elseif (!function_exists(
'mb_decode_mimeheader')) {
2402 $subject = mb_decode_mimeheader($subject);
2403 } elseif (function_exists(
'iconv_mime_decode')) {
2404 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname= '')
Make an include_once using default root and alternate root if it fails.
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto= 'UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
fetchFilters()
Fetch filters.
fetch($id, $ref=null)
Load object in memory from the database.
Class to manage agenda events (actions)
doCollectOneCollector()
Execute collect for current collector loaded previously with fetch.
foreach($object->fields as $key=> $val) if(is_array($extrafields->attributes[$object->table_element]['label'])&&count($extrafields->attributes[$object->table_element]['label']) > 0) $object fields
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
dol_now($mode= 'auto')
Return date for now.
convertStringEncoding($string, $fromEncoding, $toEncoding= 'UTF-8')
Converts a string from one encoding to another.
Class to manage Dolibarr users.
Class to manage Dolibarr database access.
fetchAll(User $user, $activeOnly=0, $sortfield= 's.rowid', $sortorder= 'ASC', $limit=100, $page=0)
Load object lines in memory from the database.
Class for EmailCollectorAction.
getmsg($mbox, $mid)
getmsg
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
createCommon(User $user, $notrigger=false)
Create object into database.
getConnectStringIMAP($ssl=1, $norsh=0)
Return the connectstring to use with IMAP connection function.
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...
getpart($mbox, $mid, $p, $partno)
Sub function for getpart().
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
$conf db
API class for accounts.
doCollect()
Action executed by scheduler CAN BE A CRON TASK.
__construct(DoliDB $db)
Constructor.
info($id)
Charge les informations d'ordre info dans l'objet commande.
createFromClone(User $user, $fromid)
Clone and object into another one.
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject, $header)
overwitePropertiesOfObject
getLibStatut($mode=0)
Return label of the status.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage projects.
Class for EmailCollector.
getNomUrl($withpicto=0, $option= '', $notooltip=0, $morecss= '', $save_lastsearch_value=-1)
Return a link to the object card (with optionaly the picto)
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
update(User $user, $notrigger=false)
Update object into database.
Class to manage members of a foundation.
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
updateCommon(User $user, $notrigger=false)
Update object into database.
create(User $user, $notrigger=false)
Create object into database.
print $_SERVER["PHP_SELF"]
Edit parameters.
dolExplodeIntoArray($string, $delimiter= ';', $kv= '=')
Split a string with 2 keys into key array.
Class for EmailCollectorFilter.
Class for RecruitmentCandidature.
dolGetFirstLineOfText($text, $nboflines=1, $charset= 'UTF-8')
Return first line of text.
dol_getIdFromCode($db, $key, $tablename, $fieldkey= 'code', $fieldid= 'id', $entityfilter=0)
Return an id or code from a code or id.
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(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getEncodedUtf7($str)
Convert str to UTF-7 imap default mailbox names.
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
make_substitutions($text, $substitutionarray, $outputlangs=null)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
Class to manage invoices.
fetchActions()
Fetch actions.
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
LibStatut($status, $mode=0)
Return the status.
fetchCommon($id, $ref=null, $morewhere= '')
Load object in memory from the database.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $keepmoretags= '', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...
decodeSMTPSubject($subject)
Decode a subject string according to RFC2047 Example: '=?Windows-1252?Q?RE=A0:_ABC?=' => 'RE : ABC...' Example: '=?UTF-8?Q?A=C3=A9B?=' => 'AéB' Example: '=?UTF-8?B?2KLYstmF2KfbjNi0?=' => Example: '=?utf-8?B?UkU6IG1vZHVsZSBkb2xpYmFyciBnZXN0aW9ubmFpcmUgZGUgZmljaGllcnMg?= =?utf-8?B?UsOpZsOpcmVuY2UgZGUgbGEgY29tbWFuZGUgVFVHRURJSklSIOKAkyBwYXNz?= =?utf-8?B?w6llIGxlIDIyLzA0LzIwMjA=?='.