25 require_once DOL_DOCUMENT_ROOT.
'/core/class/commonobject.class.php';
26 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
27 require_once DOL_DOCUMENT_ROOT.
'/contact/class/contact.class.php';
28 require_once DOL_DOCUMENT_ROOT.
'/societe/class/societe.class.php';
29 require_once DOL_DOCUMENT_ROOT.
'/projet/class/project.class.php';
30 require_once DOL_DOCUMENT_ROOT.
'/compta/facture/class/facture.class.php';
31 require_once DOL_DOCUMENT_ROOT.
'/ticket/class/ticket.class.php';
32 require_once DOL_DOCUMENT_ROOT.
'/recruitment/class/recruitmentcandidature.class.php';
34 require_once DOL_DOCUMENT_ROOT.
'/comm/propal/class/propal.class.php';
35 require_once DOL_DOCUMENT_ROOT.
'/commande/class/commande.class.php';
36 require_once DOL_DOCUMENT_ROOT.
'/expedition/class/expedition.class.php';
37 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.facture.class.php';
38 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.commande.class.php';
39 require_once DOL_DOCUMENT_ROOT.
'/supplier_proposal/class/supplier_proposal.class.php';
40 require_once DOL_DOCUMENT_ROOT.
'/reception/class/reception.class.php';
41 include_once DOL_DOCUMENT_ROOT.
'/emailcollector/lib/emailcollector.lib.php';
54 public $element =
'emailcollector';
58 public $table_element =
'emailcollector_emailcollector';
62 public $ismultientitymanaged = 1;
66 public $isextrafieldmanaged = 0;
71 public $picto =
'email';
76 public $fk_element =
'fk_emailcollector';
81 protected $childtables = array();
85 protected $childtablesoncascade = array(
'emailcollector_emailcollectorfilter',
'emailcollector_emailcollectoraction');
111 public $fields = array(
112 'rowid' => array(
'type'=>
'integer',
'label'=>
'TechnicalID',
'visible'=>2,
'enabled'=>1,
'position'=>1,
'notnull'=>1,
'index'=>1),
113 'entity' => array(
'type'=>
'integer',
'label'=>
'Entity',
'enabled'=>1,
'visible'=>0,
'default'=>1,
'notnull'=>1,
'index'=>1,
'position'=>20),
114 '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'=>
'tdoverflowmax150'),
115 'label' => array(
'type'=>
'varchar(255)',
'label'=>
'Label',
'visible'=>1,
'enabled'=>1,
'position'=>30,
'notnull'=>-1,
'searchall'=>1,
'help'=>
'Example: My Email collector',
'csslist'=>
'tdoverflowmax150'),
116 'description' => array(
'type'=>
'text',
'label'=>
'Description',
'visible'=>-1,
'enabled'=>1,
'position'=>60,
'notnull'=>-1,
'csslist'=>
'small'),
117 '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'=>
'tdoverflow125'),
118 '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)'),
119 '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'),
120 'password' => array(
'type'=>
'password',
'label'=>
'Password',
'visible'=>-1,
'enabled'=>1,
'position'=>102,
'notnull'=>-1,
'comment'=>
"IMAP password",
'help'=>
'WithGMailYouCanCreateADedicatedPassword'),
121 'source_directory' => array(
'type'=>
'varchar(255)',
'label'=>
'MailboxSourceDirectory',
'visible'=>-1,
'enabled'=>1,
'position'=>103,
'notnull'=>1,
'default' =>
'Inbox',
'help'=>
'Example: INBOX'),
124 'target_directory' => array(
'type'=>
'varchar(255)',
'label'=>
'MailboxTargetDirectory',
'visible'=>1,
'enabled'=>1,
'position'=>110,
'notnull'=>0,
'help'=>
"EmailCollectorTargetDir"),
125 'maxemailpercollect' => array(
'type'=>
'integer',
'label'=>
'MaxEmailCollectPerCollect',
'visible'=>-1,
'enabled'=>1,
'position'=>111,
'default'=>100),
126 'datelastresult' => array(
'type'=>
'datetime',
'label'=>
'DateLastCollectResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>121,
'notnull'=>-1,
'csslist'=>
'nowraponall'),
127 'codelastresult' => array(
'type'=>
'varchar(16)',
'label'=>
'CodeLastResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>122,
'notnull'=>-1,),
128 'lastresult' => array(
'type'=>
'varchar(255)',
'label'=>
'LastResult',
'visible'=>1,
'enabled'=>
'$action != "create" && $action != "edit"',
'position'=>123,
'notnull'=>-1,
'csslist'=>
'small'),
129 'datelastok' => array(
'type'=>
'datetime',
'label'=>
'DateLastcollectResultOk',
'visible'=>1,
'enabled'=>
'$action != "create"',
'position'=>125,
'notnull'=>-1,
'csslist'=>
'nowraponall'),
130 'note_public' => array(
'type'=>
'html',
'label'=>
'NotePublic',
'visible'=>0,
'enabled'=>1,
'position'=>61,
'notnull'=>-1,),
131 'note_private' => array(
'type'=>
'html',
'label'=>
'NotePrivate',
'visible'=>0,
'enabled'=>1,
'position'=>62,
'notnull'=>-1,),
132 'date_creation' => array(
'type'=>
'datetime',
'label'=>
'DateCreation',
'visible'=>-2,
'enabled'=>1,
'position'=>500,
'notnull'=>1,),
133 'tms' => array(
'type'=>
'timestamp',
'label'=>
'DateModification',
'visible'=>-2,
'enabled'=>1,
'position'=>501,
'notnull'=>1,),
135 'fk_user_creat' => array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserAuthor',
'visible'=>-2,
'enabled'=>1,
'position'=>510,
'notnull'=>1,),
136 'fk_user_modif' => array(
'type'=>
'integer:User:user/class/user.class.php',
'label'=>
'UserModif',
'visible'=>-2,
'enabled'=>1,
'position'=>511,
'notnull'=>-1,),
138 'import_key' => array(
'type'=>
'varchar(14)',
'label'=>
'ImportId',
'visible'=>-2,
'enabled'=>1,
'position'=>1000,
'notnull'=>-1,),
139 'status' => array(
'type'=>
'integer',
'label'=>
'Status',
'visible'=>1,
'enabled'=>1,
'position'=>1000,
'notnull'=>1,
'index'=>1,
'arrayofkeyval'=>array(
'0'=>
'Inactive',
'1'=>
'Active'))
172 public $date_creation;
182 public $fk_user_creat;
187 public $fk_user_modif;
199 public $source_directory;
200 public $target_directory;
201 public $maxemailpercollect;
206 public $datelastresult;
208 public $codelastresult;
218 const STATUS_DISABLED = 0;
219 const STATUS_ENABLED = 1;
229 global $conf, $langs;
233 if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields[
'rowid'])) {
234 $this->fields[
'rowid'][
'visible'] = 0;
236 if (empty($conf->multicompany->enabled) && isset($this->fields[
'entity'])) {
237 $this->fields[
'entity'][
'enabled'] = 0;
241 foreach ($this->fields as $key => $val) {
242 if (isset($val[
'enabled']) && empty($val[
'enabled'])) {
243 unset($this->fields[$key]);
248 foreach ($this->fields as $key => $val) {
249 if (!empty($val[
'arrayofkeyval']) && is_array($val[
'arrayofkeyval'])) {
250 foreach ($val[
'arrayofkeyval'] as $key2 => $val2) {
251 $this->fields[$key][
'arrayofkeyval'][$key2] = $langs->trans($val2);
269 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
270 $langs->load(
"errors");
271 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
277 if (is_array($this->filters) && count($this->filters)) {
280 foreach ($this->filters as $filter) {
281 $emailcollectorfilter->type = $filter[
'type'];
282 $emailcollectorfilter->rulevalue = $filter[
'rulevalue'];
283 $emailcollectorfilter->fk_emailcollector = $this->id;
284 $emailcollectorfilter->status = $filter[
'status'];
286 $emailcollectorfilter->create($user);
290 if (is_array($this->actions) && count($this->actions)) {
293 foreach ($this->actions as $operation) {
294 $emailcollectoroperation->type = $operation[
'type'];
295 $emailcollectoroperation->actionparam = $operation[
'actionparam'];
296 $emailcollectoroperation->fk_emailcollector = $this->id;
297 $emailcollectoroperation->status = $operation[
'status'];
298 $emailcollectoroperation->position = $operation[
'position'];
300 $emailcollectoroperation->create($user);
316 global $langs, $extrafields;
321 $object =
new self($this->db);
326 $object->fetchCommon($fromid);
328 $object->fetchFilters();
329 $object->fetchActions();
333 unset($object->fk_user_creat);
334 unset($object->import_key);
337 $object->ref =
"copy_of_".$object->ref;
338 $object->title = $langs->trans(
"CopyOf").
" ".$object->title;
339 if (empty($object->host)) {
340 $object->host =
'imap.example.com';
344 if (is_array($object->array_options) && count($object->array_options) > 0) {
345 $extrafields->fetch_name_optionals_label($this->table_element);
346 foreach ($object->array_options as $key => $option) {
347 $shortkey = preg_replace(
'/options_/',
'', $key);
348 if (!empty($extrafields->attributes[$this->element][
'unique'][$shortkey])) {
350 unset($object->array_options[$key]);
356 $object->context[
'createfromclone'] =
'createfromclone';
357 $result = $object->create($user);
360 $this->error = $object->error;
361 $this->errors = $object->errors;
364 unset($object->context[
'createfromclone']);
371 $this->
db->rollback();
383 public function fetch($id, $ref =
null)
417 public function fetchAll(
User $user, $activeOnly = 0, $sortfield =
's.rowid', $sortorder =
'ASC', $limit = 100, $page = 0)
423 $sql =
"SELECT s.rowid";
424 $sql .=
" FROM ".MAIN_DB_PREFIX.
"emailcollector_emailcollector as s";
425 $sql .=
' WHERE s.entity IN ('.getEntity(
'emailcollector').
')';
427 $sql .=
" AND s.status = 1";
429 $sql .= $this->
db->order($sortfield, $sortorder);
434 $offset = $limit * $page;
436 $sql .= $this->
db->plimit($limit + 1, $offset);
439 $result = $this->
db->query($sql);
441 $num = $this->
db->num_rows($result);
444 $obj = $this->
db->fetch_object($result);
446 if ($emailcollector_static->fetch($obj->rowid)) {
447 $obj_ret[] = $emailcollector_static;
452 $this->errors[] =
'EmailCollector::fetchAll Error when retrieve emailcollector list';
453 dol_syslog(
'EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
456 if (!count($obj_ret)) {
457 dol_syslog(
'EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
475 if ($this->host && preg_match(
'/^http:/i', trim($this->host))) {
476 $langs->load(
"errors");
477 $this->error = $langs->trans(
"ErrorHostMustNotStartWithHttp", $this->host);
491 public function delete(
User $user, $notrigger =
false)
506 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
508 global $conf, $langs, $action, $hookmanager;
510 if (!empty($conf->dol_no_mouse_hover)) {
516 $label =
'<u>'.$langs->trans(
"EmailCollector").
'</u>';
518 $label .=
'<b>'.$langs->trans(
'Ref').
':</b> '.$this->ref;
520 $url = DOL_URL_ROOT.
'/admin/emailcollector_card.php?id='.$this->id;
522 if ($option !=
'nolink') {
524 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
525 if ($save_lastsearch_value == -1 && preg_match(
'/list\.php/', $_SERVER[
"PHP_SELF"])) {
526 $add_save_lastsearch_values = 1;
528 if ($add_save_lastsearch_values) {
529 $url .=
'&save_lastsearch_values=1';
534 if (empty($notooltip)) {
535 if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
536 $label = $langs->trans(
"ShowEmailCollector");
537 $linkclose .=
' alt="'.dol_escape_htmltag($label, 1).
'"';
539 $linkclose .=
' title="'.dol_escape_htmltag($label, 1).
'"';
540 $linkclose .=
' class="classfortooltip'.($morecss ?
' '.$morecss :
'').
'"';
542 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
545 $linkstart =
'<a href="'.$url.
'"';
546 $linkstart .= $linkclose.
'>';
549 $result .= $linkstart;
551 $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);
553 if ($withpicto != 2) {
554 $result .= $this->ref;
559 $hookmanager->initHooks(array(
'emailcollectordao'));
560 $parameters = array(
'id'=>$this->
id,
'getnomurl' => &$result);
561 $reshook = $hookmanager->executeHooks(
'getNomUrl', $parameters, $this, $action);
563 $result = $hookmanager->resPrint;
565 $result .= $hookmanager->resPrint;
579 return $this->
LibStatut($this->status, $mode);
593 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
596 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
597 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
598 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv(
'Enabled');
599 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv(
'Disabled');
602 $statusType =
'status5';
603 if ($status == self::STATUS_ENABLED) {
604 $statusType =
'status4';
607 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status],
'', $statusType, $mode);
618 $sql =
'SELECT rowid, date_creation as datec, tms as datem,';
619 $sql .=
' fk_user_creat, fk_user_modif';
620 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
621 $sql .=
' WHERE t.rowid = '.((int) $id);
622 $result = $this->
db->query($sql);
624 if ($this->
db->num_rows($result)) {
625 $obj = $this->
db->fetch_object($result);
626 $this->
id = $obj->rowid;
628 $this->user_creation_id = $obj->fk_user_creat;
629 $this->user_modification_id = $obj->fk_user_modif;
630 $this->date_creation = $this->
db->jdate($obj->datec);
631 $this->date_modification = empty($obj->datem) ?
'' : $this->
db->jdate($obj->datem);
634 $this->
db->free($result);
648 $this->host =
'localhost';
649 $this->login =
'alogin';
662 $this->filters = array();
664 $sql =
'SELECT rowid, type, rulevalue, status';
665 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectorfilter';
666 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
674 $obj = $this->
db->fetch_object(
$resql);
675 $this->filters[$obj->rowid] = array(
'id'=>$obj->rowid,
'type'=>$obj->type,
'rulevalue'=>$obj->rulevalue,
'status'=>$obj->status);
694 $this->actions = array();
696 $sql =
'SELECT rowid, type, actionparam, status';
697 $sql .=
' FROM '.MAIN_DB_PREFIX.
'emailcollector_emailcollectoraction';
698 $sql .=
' WHERE fk_emailcollector = '.((int) $this->
id);
699 $sql .=
' ORDER BY position';
706 $obj = $this->
db->fetch_object(
$resql);
707 $this->actions[$obj->rowid] = array(
'id'=>$obj->rowid,
'type'=>$obj->type,
'actionparam'=>$obj->actionparam,
'status'=>$obj->status);
729 $flags =
'/service=imap';
730 if (!empty($conf->global->IMAP_FORCE_TLS)) {
732 } elseif (empty($conf->global->IMAP_FORCE_NOSSL)) {
737 $flags .=
'/novalidate-cert';
740 if ($norsh || !empty($conf->global->IMAP_FORCE_NORSH)) {
744 if (strpos($this->login,
'/') !=
false) {
745 $partofauth = explode(
'/', $this->login);
746 $flags .=
'/authuser='.$partofauth[0].
'/user='.$partofauth[1];
749 $connectstringserver =
'{'.$this->host.
':993'.$flags.
'}';
751 return $connectstringserver;
762 if (function_exists(
'mb_convert_encoding')) {
764 $str = preg_replace(
"/ /",
"xyxy", $str);
766 if ($str = mb_convert_encoding($str,
"UTF-7")) {
768 $str = preg_replace(
"/\+A/",
"&A", $str);
770 $str = preg_replace(
"/xyxy/",
" ", $str);
774 $this->error =
"error: is not possible to encode this string '".$str.
"'";
794 $arrayofcollectors = $this->
fetchAll($user, 1);
797 foreach ($arrayofcollectors as $emailcollector) {
798 $result = $emailcollector->doCollectOneCollector();
799 dol_syslog(
"doCollect result = ".$result.
" for emailcollector->id = ".$emailcollector->id);
801 $this->error .=
'EmailCollector ID '.$emailcollector->id.
':'.$emailcollector->error.
'<br>';
802 if (!empty($emailcollector->errors)) {
803 $this->error .= join(
'<br>', $emailcollector->errors);
805 $this->output .=
'EmailCollector ID '.$emailcollector->id.
': '.$emailcollector->lastresult.
'<br>';
823 $errorforthisaction = 0;
828 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
829 $tmpclass =
''; $tmpproperty =
'';
830 $tmparray = explode(
'.', $propertytooverwrite);
831 if (count($tmparray) == 2) {
832 $tmpclass = $tmparray[0];
833 $tmpproperty = $tmparray[1];
835 $tmpproperty = $tmparray[0];
837 if ($tmpclass && ($tmpclass != $object->element)) {
847 $regforregex = array();
848 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
849 $sourcefield = $regforregex[1];
850 $regexstring = $regforregex[2];
852 } elseif (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
853 $sourcefield = $regforregex[1];
854 $regexstring = $regforregex[2];
856 if (!empty($sourcefield) && !empty($regexstring)) {
857 if (strtolower($sourcefield) ==
'body') {
858 $sourcestring = $messagetext;
859 } elseif (strtolower($sourcefield) ==
'subject') {
860 $sourcestring = $subject;
861 } elseif (strtolower($sourcefield) ==
'header') {
862 $sourcestring = $header;
866 $regforval = array();
868 if (strtolower($sourcefield) ==
'body') {
869 $regexoptions =
'ms';
871 if (strtolower($sourcefield) ==
'header') {
876 if (preg_match(
'/'.$regexstring.
'/'.$regexoptions, $sourcestring, $regforval)) {
879 $valueextracted = isset($regforval[count($regforval) - 1]) ?trim($regforval[count($regforval) - 1]) :
null;
880 if (strtolower($sourcefield) ==
'header') {
881 if (preg_match(
'/^options_/', $tmpproperty)) {
882 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $this->
decodeSMTPSubject($valueextracted);
887 if (preg_match(
'/^options_/', $tmpproperty)) {
888 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $this->
decodeSMTPSubject($valueextracted);
895 $object->$tmpproperty =
null;
899 $errorforthisaction++;
900 $this->error =
'The extract rule to use has on an unknown source (must be HEADER, SUBJECT or BODY)';
901 $this->errors[] = $this->error;
903 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
905 if (preg_match(
'/^options_/', $tmpproperty)) {
906 $valuecurrent = $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)];
908 $valuecurrent = $object->$tmpproperty;
911 if ($regforregex[1] ==
'SET' || empty($valuecurrent)) {
912 $valuetouse = $regforregex[2];
913 $substitutionarray = array();
914 $matcharray = array();
915 preg_match_all(
'/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
917 if (is_array($matcharray[1])) {
918 foreach ($matcharray[1] as $keytoreplace) {
919 if ($keytoreplace && isset($object->$keytoreplace)) {
920 $substitutionarray[
'__'.$keytoreplace.
'__'] = $object->$keytoreplace;
925 dol_syslog(var_export($substitutionarray,
true));
928 if (preg_match(
'/^options_/', $tmpproperty)) {
929 $object->array_options[preg_replace(
'/^options_/',
'', $tmpproperty)] = $valuetouse;
931 $object->$tmpproperty = $valuetouse;
935 $errorforthisaction++;
936 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
937 $this->errors[] = $this->error;
942 return $errorforthisaction;
952 global $conf, $langs, $user;
957 require_once DOL_DOCUMENT_ROOT.
'/comm/action/class/actioncomm.class.php';
959 dol_syslog(
"EmailCollector::doCollectOneCollector start for id=".$this->
id.
" - ".$this->
ref, LOG_DEBUG);
961 $langs->loadLangs(array(
"project",
"companies",
"mails",
"errors",
"ticket",
"agenda",
"commercial"));
969 if (empty($this->host)) {
970 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'EMailHost'));
973 if (empty($this->login)) {
974 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'Login'));
977 if (empty($this->source_directory)) {
978 $this->error = $langs->trans(
'ErrorFieldRequired', $langs->transnoentitiesnoconv(
'MailboxSourceDirectory'));
981 if (!function_exists(
'imap_open')) {
982 $this->error =
'IMAP function not enabled on your PHP';
989 $sourcedir = $this->source_directory;
990 $targetdir = ($this->target_directory ? $this->target_directory :
'');
993 $connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
994 $connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
996 $connection = imap_open($connectstringsource, $this->login, $this->password);
998 $this->error =
'Failed to open IMAP connection '.$connectstringsource;
1003 $host = dol_getprefix(
'email');
1010 $search =
'UNDELETED';
1012 $searchfilterdoltrackid = 0;
1013 $searchfilternodoltrackid = 0;
1014 $searchfilterisanswer = 0;
1015 $searchfilterisnotanswer = 0;
1016 foreach ($this->filters as $rule) {
1017 if (empty($rule[
'status'])) {
1021 if ($rule[
'type'] ==
'to') {
1022 $tmprulevaluearray = explode(
'*', $rule[
'rulevalue']);
1023 if (count($tmprulevaluearray) >= 2) {
1024 foreach ($tmprulevaluearray as $tmprulevalue) {
1025 $search .= ($search ?
' ' :
'').
'TO "'.str_replace(
'"',
'', $tmprulevalue).
'"';
1028 $search .= ($search ?
' ' :
'').
'TO "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1031 if ($rule[
'type'] ==
'bcc') {
1032 $search .= ($search ?
' ' :
'').
'BCC';
1034 if ($rule[
'type'] ==
'cc') {
1035 $search .= ($search ?
' ' :
'').
'CC';
1037 if ($rule[
'type'] ==
'from') {
1038 $search .= ($search ?
' ' :
'').
'FROM "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1040 if ($rule[
'type'] ==
'subject') {
1041 $search .= ($search ?
' ' :
'').
'SUBJECT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1043 if ($rule[
'type'] ==
'body') {
1044 $search .= ($search ?
' ' :
'').
'BODY "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1046 if ($rule[
'type'] ==
'header') {
1047 $search .= ($search ?
' ' :
'').
'HEADER '.$rule[
'rulevalue'];
1050 if ($rule[
'type'] ==
'notinsubject') {
1051 $search .= ($search ?
' ' :
'').
'SUBJECT NOT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1053 if ($rule[
'type'] ==
'notinbody') {
1054 $search .= ($search ?
' ' :
'').
'BODY NOT "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1057 if ($rule[
'type'] ==
'seen') {
1058 $search .= ($search ?
' ' :
'').
'SEEN';
1060 if ($rule[
'type'] ==
'unseen') {
1061 $search .= ($search ?
' ' :
'').
'UNSEEN';
1063 if ($rule[
'type'] ==
'unanswered') {
1064 $search .= ($search ?
' ' :
'').
'UNANSWERED';
1066 if ($rule[
'type'] ==
'answered') {
1067 $search .= ($search ?
' ' :
'').
'ANSWERED';
1069 if ($rule[
'type'] ==
'smaller') {
1070 $search .= ($search ?
' ' :
'').
'SMALLER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1072 if ($rule[
'type'] ==
'larger') {
1073 $search .= ($search ?
' ' :
'').
'LARGER "'.str_replace(
'"',
'', $rule[
'rulevalue']).
'"';
1076 if ($rule[
'type'] ==
'withtrackingidinmsgid') {
1077 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1079 if ($rule[
'type'] ==
'withouttrackingidinmsgid') {
1080 $searchfilterdoltrackid++; $searchhead .=
'/Message-ID.*@'.preg_quote($host,
'/').
'/';
1082 if ($rule[
'type'] ==
'withtrackingid') {
1083 $searchfilterdoltrackid++; $searchhead .=
'/References.*@'.preg_quote($host,
'/').
'/';
1085 if ($rule[
'type'] ==
'withouttrackingid') {
1086 $searchfilternodoltrackid++; $searchhead .=
'! /References.*@'.preg_quote($host,
'/').
'/';
1089 if ($rule[
'type'] ==
'isanswer') {
1090 $searchfilterisanswer++; $searchhead .=
'/References.*@.*/';
1092 if ($rule[
'type'] ==
'isnotanswer') {
1093 $searchfilterisnotanswer++; $searchhead .=
'! /References.*@.*/';
1097 if (empty($targetdir)) {
1099 if ($this->datelastok) {
1100 $fromdate = $this->datelastok;
1102 if ($fromdate > 0) {
1103 $search .= ($search ?
' ' :
'').
'SINCE '.date(
'j-M-Y', $fromdate - 1);
1110 $nbemailprocessed = 0;
1113 $charset = ($this->hostcharset ? $this->hostcharset :
"UTF-8");
1116 $arrayofemail = imap_search($connection, $search,
null, $charset);
1117 if ($arrayofemail ===
false) {
1119 $mapoferrrors = imap_errors();
1120 if ($mapoferrrors !==
false) {
1122 $this->error =
"Search string not understood - ".join(
',', $mapoferrrors);
1123 $this->errors[] = $this->error;
1128 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
1202 dol_syslog(
"Start of loop on email", LOG_INFO, 1);
1205 foreach ($arrayofemail as $imapemail) {
1206 if ($nbemailprocessed > 1000) {
1214 $header = imap_fetchheader($connection, $imapemail, 0);
1215 $overview = imap_fetch_overview($connection, $imapemail, 0);
1221 $header = preg_replace(
'/\r\n\s+/m',
' ', $header);
1224 preg_match_all(
'/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches);
1225 $headers = array_combine($matches[1], $matches[2]);
1227 if (!empty($headers[
'in-reply-to']) && empty($headers[
'In-Reply-To'])) {
1228 $headers[
'In-Reply-To'] = $headers[
'in-reply-to'];
1230 if (!empty($headers[
'references']) && empty($headers[
'References'])) {
1231 $headers[
'References'] = $headers[
'references'];
1233 if (!empty($headers[
'message-id']) && empty($headers[
'Message-ID'])) {
1234 $headers[
'Message-ID'] = $headers[
'message-id'];
1242 dol_syslog(
"** Process email ".$iforemailloop.
" References: ".$headers[
'References'].
" Subject: ".$headers[
'Subject']);
1245 $trackidfoundintorecipienttype =
'';
1246 $trackidfoundintorecipientid = 0;
1249 if (preg_match(
'/\+(thi|ctc|use|mem|sub|proj|tas|con|tic|job|pro|ord|inv|spro|sor|sin|leav|stockinv|job|surv|salary)([0-9]+)@/', $emailto, $reg)) {
1250 $trackidfoundintorecipienttype = $reg[1];
1251 $trackidfoundintorecipientid = $reg[2];
1252 } elseif (preg_match(
'/\+emailing-(\w+)@/', $emailto, $reg)) {
1253 $trackidfoundintorecipienttype =
'emailing';
1254 $trackidfoundintorecipientid = $reg[1];
1258 if ($searchfilterdoltrackid > 0) {
1259 if (empty($trackidfoundintorecipienttype)) {
1260 if (empty($headers[
'References']) || !preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References'])) {
1261 $nbemailprocessed++;
1262 dol_syslog(
" Discarded - No suffix in email recipient and no Header References found matching signature of application so with a trackid");
1267 if ($searchfilternodoltrackid > 0) {
1268 if (!empty($trackidfoundintorecipienttype) || (!empty($headers[
'References']) && preg_match(
'/@'.preg_quote($host,
'/').
'/', $headers[
'References']))) {
1269 $nbemailprocessed++;
1270 dol_syslog(
" Discarded - Suffix found into email or Header References found and matching signature of application so with a trackid");
1275 if ($searchfilterisanswer > 0) {
1276 if (empty($headers[
'In-Reply-To'])) {
1277 $nbemailprocessed++;
1278 dol_syslog(
" Discarded - Email is not an answer (no In-Reply-To header)");
1284 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) {
1291 $nbemailprocessed++;
1292 dol_syslog(
" Discarded - Email is not an answer (no RE prefix in subject)");
1296 if ($searchfilterisnotanswer > 0) {
1297 if (!empty($headers[
'In-Reply-To'])) {
1301 if (preg_match(
'/Re\s*:\s+/i', $headers[
'Subject'])) {
1307 $nbemailprocessed++;
1308 dol_syslog(
" Discarded - Email is an answer");
1316 $thirdpartystatic =
new Societe($this->
db);
1317 $contactstatic =
new Contact($this->
db);
1318 $projectstatic =
new Project($this->
db);
1320 $nbactiondoneforemail = 0;
1322 $errorforactions = 0;
1323 $thirdpartyfoundby =
'';
1324 $contactfoundby =
'';
1325 $projectfoundby =
'';
1326 $ticketfoundby =
'';
1327 $candidaturefoundby =
'';
1332 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);
1339 $overview[0]->subject = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $overview[0]->subject);
1343 global $htmlmsg, $plainmsg, $charset, $attachments;
1345 $this->
getmsg($connection, $imapemail);
1353 $messagetext = preg_replace(
'/[\x{10000}-\x{10FFFF}]/u',
"\xEF\xBF\xBD", $messagetext);
1410 $fromstring = $overview[0]->from;
1412 $sender = $overview[0]->sender;
1413 $to = $overview[0]->to;
1414 $sendtocc = $overview[0]->cc;
1415 $sendtobcc = $overview[0]->bcc;
1416 $date = $overview[0]->udate;
1417 $msgid = str_replace(array(
'<',
'>'),
'', $overview[0]->message_id);
1418 $subject = $overview[0]->subject;
1422 if (preg_match(
'/^(.*)<(.*)>$/', $fromstring, $reg)) {
1424 $fromtext = $reg[1];
1426 $from = $fromstring;
1429 $fk_element_id = 0; $fk_element_type =
'';
1432 $contactid = 0; $thirdpartyid = 0; $projectid = 0; $ticketid = 0;
1440 $objectemail =
null;
1443 if (!empty($headers[
'References'])) {
1444 $arrayofreferences = preg_split(
'/(,|\s+)/', $headers[
'References']);
1448 foreach ($arrayofreferences as $reference) {
1450 if (!empty($trackidfoundintorecipienttype)) {
1451 $resultsearchtrackid = -1;
1452 $reg[1] = $trackidfoundintorecipienttype;
1453 $reg[2] = $trackidfoundintorecipientid;
1455 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host,
'/').
'/', $reference, $reg);
1456 if (empty($resultsearchtrackid) &&
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
1457 $resultsearchtrackid = preg_match(
'/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(
getDolGlobalString(
'EMAIL_ALTERNATIVE_HOST_SIGNATURE'),
'/').
'/', $reference, $reg);
1461 if (!empty($resultsearchtrackid)) {
1463 $trackid = $reg[1].$reg[2];
1465 $objectid = $reg[2];
1467 if ($reg[1] ==
'thi') {
1470 if ($reg[1] ==
'ctc') {
1473 if ($reg[1] ==
'inv') {
1476 if ($reg[1] ==
'sinv') {
1479 if ($reg[1] ==
'pro') {
1480 $objectemail =
new Propal($this->
db);
1482 if ($reg[1] ==
'ord') {
1485 if ($reg[1] ==
'shi') {
1488 if ($reg[1] ==
'spro') {
1491 if ($reg[1] ==
'sord') {
1494 if ($reg[1] ==
'rec') {
1497 if ($reg[1] ==
'proj') {
1500 if ($reg[1] ==
'tas') {
1501 $objectemail =
new Task($this->
db);
1503 if ($reg[1] ==
'con') {
1506 if ($reg[1] ==
'use') {
1507 $objectemail =
new User($this->
db);
1509 if ($reg[1] ==
'tic') {
1510 $objectemail =
new Ticket($this->
db);
1512 if ($reg[1] ==
'recruitmentcandidature') {
1515 if ($reg[1] ==
'mem') {
1524 } elseif (preg_match(
'/<(.*@.*)>/', $reference, $reg)) {
1526 if (!is_object($objectemail)) {
1527 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"ticket where email_msgid = '".$this->
db->escape($reg[1]).
"'";
1530 $obj = $this->
db->fetch_object(
$resql);
1532 $objectid = $obj->rowid;
1533 $objectemail =
new Ticket($this->
db);
1534 $ticketfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
1541 if (!is_object($objectemail)) {
1542 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"projet where email_msgid = '".$this->
db->escape($reg[1]).
"'";
1545 $obj = $this->
db->fetch_object(
$resql);
1547 $objectid = $obj->rowid;
1549 $projectfoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
1556 if (!is_object($objectemail)) {
1557 $sql =
"SELECT rowid FROM ".MAIN_DB_PREFIX.
"recruitment_recruitmentcandidature where email_msgid = '".$this->
db->escape($reg[1]).
"'";
1560 $obj = $this->
db->fetch_object(
$resql);
1562 $objectid = $obj->rowid;
1564 $candidaturefoundby = $langs->transnoentitiesnoconv(
"EmailMsgID").
' ('.$reg[1].
')';
1573 if (is_object($objectemail)) {
1574 $result = $objectemail->fetch($objectid);
1576 $fk_element_id = $objectemail->id;
1577 $fk_element_type = $objectemail->element;
1579 if ($fk_element_type ==
'facture') {
1580 $fk_element_type =
'invoice';
1583 if (get_class($objectemail) !=
'Societe') {
1584 $thirdpartyid = $objectemail->fk_soc;
1586 $thirdpartyid = $objectemail->id;
1589 if (get_class($objectemail) !=
'Contact') {
1590 $contactid = $objectemail->fk_socpeople;
1592 $contactid = $objectemail->id;
1595 if (get_class($objectemail) !=
'Project') {
1596 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
1598 $projectid = $objectemail->id;
1604 if ($projectid > 0) {
1605 $result = $projectstatic->fetch($projectid);
1607 $projectstatic->id = 0;
1609 $projectid = $projectstatic->id;
1611 $projectfoundby =
'trackid ('.$trackid.
')';
1613 if (empty($contactid)) {
1614 $contactid = $projectstatic->fk_contact;
1616 if (empty($thirdpartyid)) {
1617 $thirdpartyid = $projectstatic->fk_soc;
1622 if ($contactid > 0) {
1623 $result = $contactstatic->fetch($contactid);
1625 $contactstatic->id = 0;
1627 $contactid = $contactstatic->id;
1629 $contactfoundby =
'trackid ('.$trackid.
')';
1631 if (empty($thirdpartyid)) {
1632 $thirdpartyid = $contactstatic->fk_soc;
1637 if ($thirdpartyid > 0) {
1638 $result = $thirdpartystatic->fetch($thirdpartyid);
1640 $thirdpartystatic->id = 0;
1642 $thirdpartyid = $thirdpartystatic->id;
1644 $thirdpartyfoundby =
'trackid ('.$trackid.
')';
1649 if (is_object($objectemail)) {
1655 if (empty($contactid)) {
1656 $result = $contactstatic->fetch(0,
null,
'', $from);
1659 $contactid = $contactstatic->id;
1660 $contactfoundby =
'email of contact ('.$from.
')';
1661 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
1662 $result = $thirdpartystatic->fetch($contactstatic->socid);
1664 $thirdpartyid = $thirdpartystatic->id;
1665 $thirdpartyfoundby =
'email of contact ('.$from.
')';
1671 if (empty($thirdpartyid)) {
1672 $result = $thirdpartystatic->fetch(0,
'',
'',
'',
'',
'',
'',
'',
'',
'', $from);
1674 $thirdpartyfoundby =
'email ('.$from.
')';
1679 foreach ($this->actions as $operation) {
1680 $errorforthisaction = 0;
1682 if ($errorforactions) {
1685 if (empty($operation[
'status'])) {
1690 dol_syslog(
"Execute action ".$operation[
'type'].
" actionparam=".$operation[
'actionparam'].
' thirdpartystatic->id='.$thirdpartystatic->id.
' contactstatic->id='.$contactstatic->id.
' projectstatic->id='.$projectstatic->id);
1691 dol_syslog(
"Execute action fk_element_id=".$fk_element_id.
" fk_element_type=".$fk_element_type);
1693 $actioncode =
'EMAIL_IN';
1695 if ($this->source_directory ==
'Sent') {
1696 $actioncode =
'EMAIL_OUT';
1699 $description = $descriptiontitle = $descriptionmeta = $descriptionfull =
'';
1701 $descriptiontitle = $langs->trans(
"RecordCreatedByEmailCollector", $this->ref, $msgid);
1704 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailFrom").($langs->trans(
"MailFrom") !=
'From' ?
' (From)' :
'').
' : '.
dol_escape_htmltag($fromstring));
1706 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"Sender").($langs->trans(
"Sender") !=
'Sender' ?
' (Sender)' :
'').
' : '.
dol_escape_htmltag($sender));
1708 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailTo").($langs->trans(
"MailTo") !=
'To' ?
' (To)' :
'').
' : '.
dol_escape_htmltag($to));
1710 $descriptionmeta =
dol_concatdesc($descriptionmeta, $langs->trans(
"MailCC").($langs->trans(
"MailCC") !=
'CC' ?
' (CC)' :
'').
' : '.
dol_escape_htmltag($sendtocc));
1714 if ($operation[
'type'] ==
'loadthirdparty' || $operation[
'type'] ==
'loadandcreatethirdparty') {
1715 if (empty($operation[
'actionparam'])) {
1717 $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;";
1718 $this->errors[] = $this->error;
1720 $actionparam = $operation[
'actionparam'];
1721 $idtouseforthirdparty =
'';
1722 $nametouseforthirdparty =
'';
1723 $emailtouseforthirdparty =
'';
1727 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
1731 $regforregex = array();
1733 if (preg_match(
'/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
1734 $sourcefield = $regforregex[1];
1735 $regexstring = $regforregex[2];
1738 if (!empty($sourcefield) && !empty($regexstring)) {
1739 if (strtolower($sourcefield) ==
'body') {
1740 $sourcestring = $messagetext;
1741 } elseif (strtolower($sourcefield) ==
'subject') {
1742 $sourcestring = $subject;
1743 } elseif (strtolower($sourcefield) ==
'header') {
1744 $sourcestring = $header;
1747 if ($sourcestring) {
1748 $regforval = array();
1750 if (preg_match(
'/'.$regexstring.
'/ms', $sourcestring, $regforval)) {
1753 if ($propertytooverwrite ==
'id') {
1754 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
1755 } elseif ($propertytooverwrite ==
'email') {
1756 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
1758 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) :
null;
1762 $idtouseforthirdparty =
null;
1763 $nametouseforthirdparty =
null;
1764 $emailtouseforthirdparty =
null;
1770 $this->error =
'The extract rule to use to load thirdparty has on an unknown source (must be HEADER, SUBJECT or BODY)';
1771 $this->errors[] = $this->error;
1773 } elseif (preg_match(
'/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
1776 if ($propertytooverwrite ==
'id') {
1777 $idtouseforthirdparty = $reg[2];
1778 } elseif ($propertytooverwrite ==
'email') {
1779 $emailtouseforthirdparty = $reg[2];
1781 $nametouseforthirdparty = $reg[2];
1785 $this->error =
'Bad syntax for description of action parameters: '.$actionparam;
1786 $this->errors[] = $this->error;
1791 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty)) {
1792 $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty,
'',
'',
'',
'',
'',
'',
'',
'', $emailtouseforthirdparty);
1795 $this->error =
'Error when getting thirdparty with name '.$nametouseforthirdparty.
' (may be 2 record exists with same name ?)';
1796 $this->errors[] = $this->error;
1798 } elseif ($result == 0) {
1799 if ($operation[
'type'] ==
'loadthirdparty') {
1800 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" was not found");
1803 $this->error =
'ErrorFailedToLoadThirdParty';
1804 $this->errors[] =
'ErrorFailedToLoadThirdParty';
1805 } elseif ($operation[
'type'] ==
'loadandcreatethirdparty') {
1806 dol_syslog(
"Third party with id=".$idtouseforthirdparty.
" email=".$emailtouseforthirdparty.
" name=".$nametouseforthirdparty.
" was not found. We try to create it.");
1809 $thirdpartystatic->name = $nametouseforthirdparty;
1810 if ($fromtext != $nametouseforthirdparty) {
1811 $thirdpartystatic->name_alias = $fromtext;
1813 $thirdpartystatic->email = ($emailtouseforthirdparty ? $emailtouseforthirdparty : $from);
1816 $errorforthisaction = $this->
overwritePropertiesOfObject($thirdpartystatic, $operation[
'actionparam'], $messagetext, $subject, $header);
1818 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
1819 $thirdpartystatic->code_client =
'auto';
1821 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
1822 $thirdpartystatic->code_fournisseur =
'auto';
1825 if ($errorforthisaction) {
1828 $result = $thirdpartystatic->create($user);
1831 $this->error = $thirdpartystatic->error;
1832 $this->errors = $thirdpartystatic->errors;
1839 } elseif ($operation[
'type'] ==
'recordevent') {
1843 $alreadycreated = $actioncomm->fetch(0,
'',
'', $msgid);
1844 if ($alreadycreated == 0) {
1845 if ($projectstatic->id > 0) {
1846 if ($projectfoundby) {
1847 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Project found from '.$projectfoundby);
1850 if ($thirdpartystatic->id > 0) {
1851 if ($thirdpartyfoundby) {
1852 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
1855 if ($contactstatic->id > 0) {
1856 if ($contactfoundby) {
1857 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
1861 $description = $descriptiontitle;
1867 $descriptionfull = $description;
1868 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
1869 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
1874 $actioncomm->type_code =
'AC_OTH_AUTO';
1875 $actioncomm->code =
'AC_'.$actioncode;
1876 $actioncomm->label = $langs->trans(
"ActionAC_".$actioncode).
' - '.$langs->trans(
"MailFrom").
' '.$from;
1877 $actioncomm->note_private = $descriptionfull;
1878 $actioncomm->fk_project = $projectstatic->id;
1879 $actioncomm->datep = $date;
1880 $actioncomm->datef = $date;
1881 $actioncomm->percentage = -1;
1882 $actioncomm->socid = $thirdpartystatic->id;
1883 $actioncomm->contact_id = $contactstatic->id;
1884 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id =>
'') : array());
1885 $actioncomm->authorid = $user->id;
1886 $actioncomm->userownerid = $user->id;
1888 $actioncomm->email_msgid = $msgid;
1889 $actioncomm->email_from = $fromstring;
1890 $actioncomm->email_sender = $sender;
1891 $actioncomm->email_to = $to;
1892 $actioncomm->email_tocc = $sendtocc;
1893 $actioncomm->email_tobcc = $sendtobcc;
1894 $actioncomm->email_subject = $subject;
1895 $actioncomm->errors_to =
'';
1897 if (!in_array($fk_element_type, array(
'societe',
'contact',
'project',
'user'))) {
1898 $actioncomm->fk_element = $fk_element_id;
1899 $actioncomm->elementid = $fk_element_id;
1900 $actioncomm->elementtype = $fk_element_type;
1901 if (is_object($objectemail) && $objectemail->module) {
1902 $actioncomm->elementtype .=
'@'.$objectemail->module;
1909 $errorforthisaction = $this->
overwritePropertiesOfObject($actioncomm, $operation[
'actionparam'], $messagetext, $subject, $header);
1918 if ($errorforthisaction) {
1921 $result = $actioncomm->create($user);
1924 $this->errors = $actioncomm->errors;
1928 } elseif ($operation[
'type'] ==
'recordjoinpiece') {
1930 foreach ($pj as $key => $val) {
1931 $data[$val[
'filename']] =
getFileData($imapemail, $val[
'pos'], $val[
'type'], $connection);
1933 if (count($pj) > 0) {
1934 $sql =
"SELECT rowid as id FROM " . MAIN_DB_PREFIX .
"user WHERE email LIKE '%" . $from .
"%'";
1936 if ($this->
db->num_rows(
$resql) == 0) {
1937 $this->errors[] =
'User Not allowed to add documents';
1939 $arrayobject = array(
1940 'propale' => array(
'table' =>
'propal',
1941 'fields' => array(
'ref'),
1942 'class' =>
'comm/propal/class/propal.class.php',
1943 'object' =>
'Propal'),
1944 'holiday' => array(
'table' =>
'holiday',
1945 'fields' => array(
'ref'),
1946 'class' =>
'holiday/class/holiday.class.php',
1947 'object' =>
'Holiday'),
1948 'expensereport' => array(
'table' =>
'expensereport',
1949 'fields' => array(
'ref'),
1950 'class' =>
'expensereport/class/expensereport.class.php',
1951 'object' =>
'ExpenseReport'),
1952 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentjobposition',
1953 'fields' => array(
'ref'),
1954 'class' =>
'recruitment/class/recruitmentjobposition.class.php',
1955 'object' =>
'RecruitmentJobPosition'),
1956 'recruitment/recruitmentjobposition' => array(
'table' =>
'recruitment_recruitmentcandidature',
1957 'fields' => array(
'ref'),
1958 'class' =>
'recruitment/class/recruitmentcandidature.class.php',
1959 'object' =>
' RecruitmentCandidature'),
1960 'societe' => array(
'table' =>
'societe',
1961 'fields' => array(
'code_client',
'code_fournisseur'),
1962 'class' =>
'societe/class/societe.class.php',
1963 'object' =>
'Societe'),
1964 'commande' => array(
'table' =>
'commande',
1965 'fields' => array(
'ref'),
1966 'class' =>
'commande/class/commande.class.php',
1967 'object' =>
'Commande'),
1968 'expedition' => array(
'table' =>
'expedition',
1969 'fields' => array(
'ref'),
1970 'class' =>
'expedition/class/expedition.class.php',
1971 'object' =>
'Expedition'),
1972 'contract' => array(
'table' =>
'contrat',
1973 'fields' => array(
'ref'),
1974 'class' =>
'contrat/class/contrat.class.php',
1975 'object' =>
'Contrat'),
1976 'fichinter' => array(
'table' =>
'fichinter',
1977 'fields' => array(
'ref'),
1978 'class' =>
'fichinter/class/fichinter.class.php',
1979 'object' =>
'Fichinter'),
1980 'ticket' => array(
'table' =>
'ticket',
1981 'fields' => array(
'ref'),
1982 'class' =>
'ticket/class/ticket.class.php',
1983 'object' =>
'Ticket'),
1984 'knowledgemanagement' => array(
'table' =>
'knowledgemanagement_knowledgerecord',
1985 'fields' => array(
'ref'),
1986 'class' =>
'knowledgemanagement/class/knowledgemanagement.class.php',
1987 'object' =>
'KnowledgeRecord'),
1988 'supplier_proposal' => array(
'table' =>
'supplier_proposal',
1989 'fields' => array(
'ref'),
1990 'class' =>
'supplier_proposal/class/supplier_proposal.class.php',
1991 'object' =>
'SupplierProposal'),
1992 'fournisseur/commande' => array(
'table' =>
'commande_fournisseur',
1993 'fields' => array(
'ref',
'ref_supplier'),
1994 'class' =>
'fourn/class/fournisseur.commande.class.php',
1995 'object' =>
'SupplierProposal'),
1996 'facture' => array(
'table' =>
'facture',
1997 'fields' => array(
'ref'),
1998 'class' =>
'compta/facture/class/facture.class.php',
1999 'object' =>
'Facture'),
2000 'fournisseur/facture' => array(
'table' =>
'facture_fourn',
2001 'fields' => array(
'ref',
'ref_client'),
2002 'class' =>
'fourn/class/fournisseur.facture.class.php',
2003 'object' =>
'FactureFournisseur'),
2004 'produit' => array(
'table' =>
'product',
2005 'fields' => array(
'ref'),
2006 'class' =>
'product/class/product.class.php',
2007 'object' =>
'Product'),
2008 'productlot' => array(
'table' =>
'product_lot',
2009 'fields' => array(
'batch'),
2010 'class' =>
'product/stock/class/productlot.class.php',
2011 'object' =>
'Productlot'),
2012 'projet' => array(
'table' =>
'projet',
2013 'fields' => array(
'ref'),
2014 'class' =>
'projet/class/projet.class.php',
2015 'object' =>
'Project'),
2016 'projet_task' => array(
'table' =>
'projet_task',
2017 'fields' => array(
'ref'),
2018 'class' =>
'projet/class/task.class.php',
2019 'object' =>
'Task'),
2020 'ressource' => array(
'table' =>
'resource',
2021 'fields' => array(
'ref'),
2022 'class' =>
'ressource/class/dolressource.class.php',
2023 'object' =>
'Dolresource'),
2024 'bom' => array(
'table' =>
'bom_bom',
2025 'fields' => array(
'ref'),
2026 'class' =>
'bom/class/bom.class.php',
2028 'mrp' => array(
'table' =>
'mrp_mo',
2029 'fields' => array(
'ref'),
2030 'class' =>
'mrp/class/mo.class.php',
2034 if (!is_object($hookmanager)) {
2035 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
2038 $hookmanager->initHooks(array(
'emailcolector'));
2039 $parameters = array(
'arrayobject' => $arrayobject);
2040 $reshook = $hookmanager->executeHooks(
'addmoduletoeamailcollectorjoinpiece', $parameters);
2042 $arrayobject = $hookmanager->resArray;
2045 $resultobj = array();
2047 foreach ($arrayobject as $key => $objectdesc) {
2048 $sql =
'SELECT DISTINCT t.rowid ';
2049 $sql .=
' FROM ' . MAIN_DB_PREFIX . $objectdesc[
'table'] .
' AS t';
2051 foreach ($objectdesc[
'fields'] as $field) {
2052 $sql .=
"'" .$this->db->escape($subject) .
"' LIKE CONCAT('%', t." . $field .
", '%') OR ";
2054 $sql = substr($sql, 0, -4);
2056 $ressqlobj = $this->
db->query($sql);
2058 while ($obj = $this->
db->fetch_object($ressqlobj)) {
2059 $resultobj[$key][] = $obj->rowid;
2064 foreach ($resultobj as $mod => $ids) {
2065 $moddesc = $arrayobject[$mod];
2066 $elementpath = $mod;
2068 $objectmanaged =
new $moddesc[
'object']($this->db);
2069 foreach ($ids as $val) {
2070 $res = $objectmanaged->fetch($val);
2072 $path = ($objectmanaged->entity > 1 ?
"/" . $objectmanaged->entity :
'');
2073 $dirs[] = DOL_DATA_ROOT . $path .
"/" . $elementpath .
'/' .
dol_sanitizeFileName($objectmanaged->ref) .
'/';
2075 $this->errors[] =
'object not found';
2079 foreach ($dirs as $target) {
2080 foreach ($data as $filename => $content) {
2081 $prefix = $this->actions[$this->id][
'actionparam'];
2083 $resr =
saveAttachment($target, $prefix .
'_' . $filename, $content);
2085 $this->errors[] =
'Doc not saved';
2090 $this->errors[] =
'no joined piece';
2092 } elseif ($operation[
'type'] ==
'project') {
2094 $projecttocreate =
new Project($this->
db);
2096 $alreadycreated = $projecttocreate->fetch(0,
'',
'', $msgid);
2097 if ($alreadycreated == 0) {
2098 if ($thirdpartystatic->id > 0) {
2099 $projecttocreate->socid = $thirdpartystatic->id;
2100 if ($thirdpartyfoundby) {
2101 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2104 if ($contactstatic->id > 0) {
2105 $projecttocreate->contact_id = $contactstatic->id;
2106 if ($contactfoundby) {
2107 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2111 $description = $descriptiontitle;
2117 $descriptionfull = $description;
2118 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2119 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2124 $percent_opp_status =
dol_getIdFromCode($this->
db,
'PROSP',
'c_lead_status',
'code',
'percent');
2126 $projecttocreate->title = $subject;
2127 $projecttocreate->date_start = $date;
2128 $projecttocreate->date_end =
'';
2129 $projecttocreate->opp_status = $id_opp_status;
2130 $projecttocreate->opp_percent = $percent_opp_status;
2132 $projecttocreate->note_private = $descriptionfull;
2133 $projecttocreate->entity = $conf->entity;
2134 $projecttocreate->email_msgid = $msgid;
2136 $savesocid = $projecttocreate->socid;
2140 $errorforthisaction = $this->
overwritePropertiesOfObject($projecttocreate, $operation[
'actionparam'], $messagetext, $subject, $header);
2143 if (empty($projecttocreate->ref)) {
2146 $modele = empty($conf->global->PROJECT_ADDON) ?
'mod_project_simple' : $conf->global->PROJECT_ADDON;
2149 $file =
''; $classname =
''; $filefound = 0; $reldir =
'';
2150 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
2151 foreach ($dirmodels as $reldir) {
2152 $file =
dol_buildpath($reldir.
"core/modules/project/".$modele.
'.php', 0);
2153 if (file_exists($file)) {
2155 $classname = $modele;
2161 if ($savesocid > 0) {
2162 if ($savesocid != $projecttocreate->socid) {
2164 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');
2167 if ($projecttocreate->socid > 0) {
2168 $thirdpartystatic->fetch($projecttocreate->socid);
2172 $result =
dol_include_once($reldir.
"core/modules/project/".$modele.
'.php');
2173 $modModuleToUseForNextValue =
new $classname;
2174 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic :
null), $projecttocreate);
2176 $projecttocreate->ref = $defaultref;
2179 if ($errorforthisaction) {
2182 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
2184 $this->error =
'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
2187 $result = $projecttocreate->create($user);
2190 $this->error =
'Failed to create project: '.$langs->trans($projecttocreate->error);
2191 $this->errors = $projecttocreate->errors;
2196 } elseif ($operation[
'type'] ==
'ticket') {
2198 $tickettocreate =
new Ticket($this->
db);
2200 $alreadycreated = $tickettocreate->fetch(0,
'',
'', $msgid);
2201 if ($alreadycreated == 0) {
2202 if ($thirdpartystatic->id > 0) {
2203 $tickettocreate->socid = $thirdpartystatic->id;
2204 $tickettocreate->fk_soc = $thirdpartystatic->id;
2205 if ($thirdpartyfoundby) {
2206 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Third party found from '.$thirdpartyfoundby);
2209 if ($contactstatic->id > 0) {
2210 $tickettocreate->contact_id = $contactstatic->id;
2211 if ($contactfoundby) {
2212 $descriptionmeta =
dol_concatdesc($descriptionmeta,
'Contact/address found from '.$contactfoundby);
2216 $description = $descriptiontitle;
2222 $descriptionfull = $description;
2223 if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2224 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2228 $tickettocreate->subject = $subject;
2229 $tickettocreate->message = $description;
2230 $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));
2231 $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));
2232 $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));
2233 $tickettocreate->origin_email = $from;
2234 $tickettocreate->fk_user_create = $user->id;
2235 $tickettocreate->datec = $date;
2236 $tickettocreate->fk_project = $projectstatic->id;
2237 $tickettocreate->notify_tiers_at_create = 0;
2238 $tickettocreate->note_private = $descriptionfull;
2239 $tickettocreate->entity = $conf->entity;
2240 $tickettocreate->email_msgid = $msgid;
2243 $savesocid = $tickettocreate->socid;
2247 $errorforthisaction = $this->
overwritePropertiesOfObject($tickettocreate, $operation[
'actionparam'], $messagetext, $subject, $header);
2250 if (empty($tickettocreate->ref)) {
2253 $modele = empty($conf->global->TICKET_ADDON) ?
'mod_ticket_simple' : $conf->global->TICKET_ADDON;
2256 $file =
''; $classname =
''; $filefound = 0; $reldir =
'';
2257 $dirmodels = array_merge(array(
'/'), (array) $conf->modules_parts[
'models']);
2258 foreach ($dirmodels as $reldir) {
2259 $file =
dol_buildpath($reldir.
"core/modules/ticket/".$modele.
'.php', 0);
2260 if (file_exists($file)) {
2262 $classname = $modele;
2268 if ($savesocid > 0) {
2269 if ($savesocid != $tickettocreate->socid) {
2271 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');
2274 if ($tickettocreate->socid > 0) {
2275 $thirdpartystatic->fetch($tickettocreate->socid);
2280 $modModuleToUseForNextValue =
new $classname;
2281 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic :
null), $tickettocreate);
2283 $tickettocreate->ref = $defaultref;
2286 if ($errorforthisaction) {
2289 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
2291 $this->error =
'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.
', thirdparty id = '.$thirdpartystatic->id;
2294 $result = $tickettocreate->create($user);
2297 $this->error =
'Failed to create ticket: '.$langs->trans($tickettocreate->error);
2298 $this->errors = $tickettocreate->errors;
2301 $destdir = $conf->ticket->dir_output.
'/'.$tickettocreate->ref;
2304 $this->
getmsg($connection, $imapemail, $destdir);
2311 } elseif ($operation[
'type'] ==
'candidature') {
2315 $alreadycreated = $candidaturetocreate->fetch(0,
'', $msgid);
2316 if ($alreadycreated == 0) {
2317 $description = $descriptiontitle;
2323 $descriptionfull = $description;
2324 $descriptionfull =
dol_concatdesc($descriptionfull,
"----- Header");
2327 $candidaturetocreate->subject = $subject;
2328 $candidaturetocreate->message = $description;
2329 $candidaturetocreate->type_code = 0;
2330 $candidaturetocreate->category_code =
null;
2331 $candidaturetocreate->severity_code =
null;
2332 $candidaturetocreate->email = $from;
2334 $candidaturetocreate->fk_user_creat = $user->id;
2335 $candidaturetocreate->date_creation = $date;
2336 $candidaturetocreate->fk_project = $projectstatic->id;
2337 $candidaturetocreate->description = $description;
2338 $candidaturetocreate->note_private = $descriptionfull;
2339 $candidaturetocreate->entity = $conf->entity;
2340 $candidaturetocreate->email_msgid = $msgid;
2341 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
2346 $errorforthisaction = $this->
overwritePropertiesOfObject($candidaturetocreate, $operation[
'actionparam'], $messagetext, $subject, $header);
2388 if ($errorforthisaction) {
2392 $result = $candidaturetocreate->create($user);
2395 $this->error =
'Failed to create ticket: '.join(
', ', $candidaturetocreate->errors);
2396 $this->errors = $candidaturetocreate->errors;
2400 } elseif (substr($operation[
'type'], 0, 4) ==
'hook') {
2403 if (!is_object($hookmanager)) {
2404 include_once DOL_DOCUMENT_ROOT.
'/core/class/hookmanager.class.php';
2408 $parameters = array(
2409 'connection'=> $connection,
2410 'imapemail'=>$imapemail,
2411 'overview'=>$overview,
2414 'fromtext' => $fromtext,
2416 'actionparam'=> $operation[
'actionparam'],
2418 'thirdpartyid' => $thirdpartyid,
2419 'objectid'=> $objectid,
2420 'objectemail'=> $objectemail,
2422 'messagetext'=>$messagetext,
2423 'subject'=>$subject,
2425 'attachments'=>$attachments,
2427 $reshook = $hookmanager->executeHooks(
'doCollectOneCollector', $parameters, $this, $operation[
'type']);
2430 $errorforthisaction++;
2431 $this->error = $hookmanager->resPrint;
2433 if ($errorforthisaction) {
2438 if (!$errorforactions) {
2439 $nbactiondoneforemail++;
2444 if (!$errorforactions) {
2446 dol_syslog(
"EmailCollector::doCollectOneCollector move message ".$imapemail.
" to ".$connectstringtarget, LOG_DEBUG);
2447 $res = imap_mail_move($connection, $imapemail, $targetdir, 0);
2448 if ($res ==
false) {
2450 $this->error = imap_last_error();
2451 $this->errors[] = $this->error;
2455 dol_syslog(
"EmailCollector::doCollectOneCollector message ".$imapemail.
" to ".$connectstringtarget.
" was set to read", LOG_DEBUG);
2461 unset($objectemail);
2462 unset($projectstatic);
2463 unset($thirdpartystatic);
2464 unset($contactstatic);
2466 $nbemailprocessed++;
2468 if (!$errorforemail) {
2469 $nbactiondone += $nbactiondoneforemail;
2472 $this->
db->commit();
2475 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
2476 dol_syslog(
"EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok.
" collected with success, so we stop this collector now.");
2482 $this->
db->rollback();
2486 $output = $langs->trans(
'XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
2488 dol_syslog(
"End of loop on emails", LOG_INFO, -1);
2490 $output = $langs->trans(
'NoNewEmailToProcess');
2493 imap_expunge($connection);
2495 imap_close($connection);
2497 $this->datelastresult = $now;
2498 $this->lastresult = $output;
2499 $this->debuginfo =
'IMAP search string used : '.$search;
2501 $this->debuginfo .=
'<br>Then search string into email header : '.$searchhead;
2505 $this->datelastok = $now;
2508 if (!empty($this->errors)) {
2509 $this->lastresult .=
" - ".join(
" - ", $this->errors);
2511 $this->codelastresult = ($error ?
'KO' :
'OK');
2514 dol_syslog(
"EmailCollector::doCollectOneCollector end", LOG_DEBUG);
2516 return $error ?-1 : 1;
2531 private function getmsg($mbox, $mid, $destdir =
'')
2535 global $charset, $htmlmsg, $plainmsg, $attachments;
2536 $htmlmsg = $plainmsg = $charset =
'';
2537 $attachments = array();
2544 $s = imap_fetchstructure($mbox, $mid);
2548 $this->
getpart($mbox, $mid, $s, 0);
2551 foreach ($s->parts as $partno0 => $p) {
2552 $this->
getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
2582 private function getpart($mbox, $mid, $p, $partno, $destdir =
'')
2585 global $htmlmsg, $plainmsg, $charset, $attachments;
2589 imap_fetchbody($mbox, $mid, $partno) :
2590 imap_body($mbox, $mid);
2592 if ($p->encoding == 4) {
2593 $data = quoted_printable_decode($data);
2594 } elseif ($p->encoding == 3) {
2595 $data = base64_decode($data);
2601 if ($p->parameters) {
2602 foreach ($p->parameters as $x) {
2603 $params[strtolower($x->attribute)] = $x->value;
2606 if ($p->dparameters) {
2607 foreach ($p->dparameters as $x) {
2608 $params[strtolower($x->attribute)] = $x->value;
2615 if ($params[
'filename'] || $params[
'name']) {
2617 $filename = ($params[
'filename']) ? $params[
'filename'] : $params[
'name'];
2619 $attachments[$filename] = $data;
2622 $file_name_complete = $params[
'filename'];
2625 $destination = $destdir.
'/'.$file_name_complete;
2628 $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
2631 $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
2634 $file_name_original = $file_name;
2643 while (file_exists($destdir.
"/" . $file_name .
"." . $extension)) {
2644 $file_name = (string) $file_name_original .
' (' . $num .
')';
2645 $file_name_complete = $file_name .
"." . $extension;
2646 $destination = $destdir.
'/'.$file_name_complete;
2651 file_put_contents($destination, $data);
2655 if ($p->type == 0 && $data) {
2656 if (!empty($params[
'charset'])) {
2661 if (strtolower($p->subtype) ==
'plain') {
2662 $plainmsg .= trim($data).
"\n\n";
2664 $htmlmsg .= $data.
"<br><br>";
2666 $charset = $params[
'charset'];
2667 } elseif ($p->type == 2 && $data) {
2673 if (!empty($params[
'charset'])) {
2676 $plainmsg .= $data.
"\n\n";
2681 foreach ($p->parts as $partno0 => $p2) {
2682 $this->
getpart($mbox, $mid, $p2, $partno.
'.'.($partno0 + 1));
2698 if (!$string || $fromEncoding == $toEncoding) {
2701 $convertedString = function_exists(
'iconv') ? @iconv($fromEncoding, $toEncoding.
'//IGNORE', $string) :
null;
2702 if (!$convertedString && extension_loaded(
'mbstring')) {
2703 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
2705 if (!$convertedString) {
2706 throw new Exception(
'Mime string encoding conversion failed');
2708 return $convertedString;
2727 if (function_exists(
'imap_mime_header_decode') && function_exists(
'iconv_mime_decode')) {
2728 $elements = imap_mime_header_decode($subject);
2730 if (!empty($elements)) {
2731 $num = count($elements);
2732 for ($i = 0; $i < $num; $i++) {
2733 $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));
2734 $newstring .= $stringinutf8;
2736 $subject = $newstring;
2738 } elseif (!function_exists(
'mb_decode_mimeheader')) {
2739 $subject = mb_decode_mimeheader($subject);
2740 } elseif (function_exists(
'iconv_mime_decode')) {
2741 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR,
'UTF-8');