dolibarr  16.0.5
emailcollector.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program. If not, see <https://www.gnu.org/licenses/>.
16  */
17 
24 // Put here all includes required by your class file
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';
33 
34 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; // customer proposal
35 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; // customer order
36 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; // Shipment
37 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; // supplier invoice
38 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; // supplier order
39 require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; // supplier proposal
40 require_once DOL_DOCUMENT_ROOT.'/reception/class/reception.class.php'; // reception
41 include_once DOL_DOCUMENT_ROOT.'/emailcollector/lib/emailcollector.lib.php';
42 //require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; // Holidays (leave request)
43 //require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; // expernse report
44 
45 
50 {
54  public $element = 'emailcollector';
58  public $table_element = 'emailcollector_emailcollector';
62  public $ismultientitymanaged = 1;
66  public $isextrafieldmanaged = 0;
67 
71  public $picto = 'email';
72 
76  public $fk_element = 'fk_emailcollector';
77 
81  protected $childtables = array();
85  protected $childtablesoncascade = array('emailcollector_emailcollectorfilter', 'emailcollector_emailcollectoraction');
86 
87 
107  // BEGIN MODULEBUILDER PROPERTIES
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'),
122  //'filter' => array('type'=>'text', 'label'=>'Filter', 'visible'=>1, 'enabled'=>1, 'position'=>105),
123  //'actiontodo' => array('type'=>'varchar(255)', 'label'=>'ActionToDo', 'visible'=>1, 'enabled'=>1, 'position'=>106),
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,),
134  //'date_validation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
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,),
137  //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
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'))
140  );
141 
142 
146  public $rowid;
147 
151  public $ref;
152 
156  public $entity;
157 
161  public $label;
162 
163 
167  public $status;
168 
172  public $date_creation;
173 
177  public $tms;
178 
182  public $fk_user_creat;
183 
187  public $fk_user_modif;
188 
192  public $import_key;
193 
194 
195  public $host;
196  public $hostcharset;
197  public $login;
198  public $password;
199  public $source_directory;
200  public $target_directory;
201  public $maxemailpercollect;
202 
206  public $datelastresult;
207 
208  public $codelastresult;
209  public $lastresult;
210  public $datelastok;
211  // END MODULEBUILDER PROPERTIES
212 
213  public $filters;
214  public $actions;
215 
216  public $debuginfo;
217 
218  const STATUS_DISABLED = 0;
219  const STATUS_ENABLED = 1;
220 
221 
227  public function __construct(DoliDB $db)
228  {
229  global $conf, $langs;
230 
231  $this->db = $db;
232 
233  if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
234  $this->fields['rowid']['visible'] = 0;
235  }
236  if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
237  $this->fields['entity']['enabled'] = 0;
238  }
239 
240  // Unset fields that are disabled
241  foreach ($this->fields as $key => $val) {
242  if (isset($val['enabled']) && empty($val['enabled'])) {
243  unset($this->fields[$key]);
244  }
245  }
246 
247  // Translate some data of arrayofkeyval
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);
252  }
253  }
254  }
255  }
256 
264  public function create(User $user, $notrigger = false)
265  {
266  global $langs;
267 
268  // Check parameters
269  if ($this->host && preg_match('/^http:/i', trim($this->host))) {
270  $langs->load("errors");
271  $this->error = $langs->trans("ErrorHostMustNotStartWithHttp", $this->host);
272  return -1;
273  }
274 
275  $id = $this->createCommon($user, $notrigger);
276 
277  if (is_array($this->filters) && count($this->filters)) {
278  $emailcollectorfilter = new EmailCollectorFilter($this->db);
279 
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'];
285 
286  $emailcollectorfilter->create($user);
287  }
288  }
289 
290  if (is_array($this->actions) && count($this->actions)) {
291  $emailcollectoroperation = new EmailCollectorAction($this->db);
292 
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'];
299 
300  $emailcollectoroperation->create($user);
301  }
302  }
303 
304  return $id;
305  }
306 
314  public function createFromClone(User $user, $fromid)
315  {
316  global $langs, $extrafields;
317  $error = 0;
318 
319  dol_syslog(__METHOD__, LOG_DEBUG);
320 
321  $object = new self($this->db);
322 
323  $this->db->begin();
324 
325  // Load source object
326  $object->fetchCommon($fromid);
327 
328  $object->fetchFilters(); // Rules
329  $object->fetchActions(); // Operations
330 
331  // Reset some properties
332  unset($object->id);
333  unset($object->fk_user_creat);
334  unset($object->import_key);
335 
336  // Clear fields
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';
341  }
342  // ...
343  // Clear extrafields that are unique
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])) {
349  //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
350  unset($object->array_options[$key]);
351  }
352  }
353  }
354 
355  // Create clone
356  $object->context['createfromclone'] = 'createfromclone';
357  $result = $object->create($user);
358  if ($result < 0) {
359  $error++;
360  $this->error = $object->error;
361  $this->errors = $object->errors;
362  }
363 
364  unset($object->context['createfromclone']);
365 
366  // End
367  if (!$error) {
368  $this->db->commit();
369  return $object;
370  } else {
371  $this->db->rollback();
372  return -1;
373  }
374  }
375 
383  public function fetch($id, $ref = null)
384  {
385  $result = $this->fetchCommon($id, $ref);
386  //if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines();
387  return $result;
388  }
389 
395  /*
396  public function fetchLines()
397  {
398  $this->lines=array();
399 
400  // Load lines with object EmailCollectorLine
401 
402  return count($this->lines)?1:0;
403  }
404  */
405 
417  public function fetchAll(User $user, $activeOnly = 0, $sortfield = 's.rowid', $sortorder = 'ASC', $limit = 100, $page = 0)
418  {
419  global $langs;
420 
421  $obj_ret = array();
422 
423  $sql = "SELECT s.rowid";
424  $sql .= " FROM ".MAIN_DB_PREFIX."emailcollector_emailcollector as s";
425  $sql .= ' WHERE s.entity IN ('.getEntity('emailcollector').')';
426  if ($activeOnly) {
427  $sql .= " AND s.status = 1";
428  }
429  $sql .= $this->db->order($sortfield, $sortorder);
430  if ($limit) {
431  if ($page < 0) {
432  $page = 0;
433  }
434  $offset = $limit * $page;
435 
436  $sql .= $this->db->plimit($limit + 1, $offset);
437  }
438 
439  $result = $this->db->query($sql);
440  if ($result) {
441  $num = $this->db->num_rows($result);
442  $i = 0;
443  while ($i < $num) {
444  $obj = $this->db->fetch_object($result);
445  $emailcollector_static = new EmailCollector($this->db);
446  if ($emailcollector_static->fetch($obj->rowid)) {
447  $obj_ret[] = $emailcollector_static;
448  }
449  $i++;
450  }
451  } else {
452  $this->errors[] = 'EmailCollector::fetchAll Error when retrieve emailcollector list';
453  dol_syslog('EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
454  $ret = -1;
455  }
456  if (!count($obj_ret)) {
457  dol_syslog('EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
458  }
459 
460  return $obj_ret;
461  }
462 
470  public function update(User $user, $notrigger = false)
471  {
472  global $langs;
473 
474  // Check parameters
475  if ($this->host && preg_match('/^http:/i', trim($this->host))) {
476  $langs->load("errors");
477  $this->error = $langs->trans("ErrorHostMustNotStartWithHttp", $this->host);
478  return -1;
479  }
480 
481  return $this->updateCommon($user, $notrigger);
482  }
483 
491  public function delete(User $user, $notrigger = false)
492  {
493  return $this->deleteCommon($user, $notrigger, 1);
494  }
495 
506  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
507  {
508  global $conf, $langs, $action, $hookmanager;
509 
510  if (!empty($conf->dol_no_mouse_hover)) {
511  $notooltip = 1; // Force disable tooltips
512  }
513 
514  $result = '';
515 
516  $label = '<u>'.$langs->trans("EmailCollector").'</u>';
517  $label .= '<br>';
518  $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
519 
520  $url = DOL_URL_ROOT.'/admin/emailcollector_card.php?id='.$this->id;
521 
522  if ($option != 'nolink') {
523  // Add param to save lastsearch_values or not
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;
527  }
528  if ($add_save_lastsearch_values) {
529  $url .= '&save_lastsearch_values=1';
530  }
531  }
532 
533  $linkclose = '';
534  if (empty($notooltip)) {
535  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
536  $label = $langs->trans("ShowEmailCollector");
537  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
538  }
539  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
540  $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
541  } else {
542  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
543  }
544 
545  $linkstart = '<a href="'.$url.'"';
546  $linkstart .= $linkclose.'>';
547  $linkend = '</a>';
548 
549  $result .= $linkstart;
550  if ($withpicto) {
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);
552  }
553  if ($withpicto != 2) {
554  $result .= $this->ref;
555  }
556  $result .= $linkend;
557  //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
558 
559  $hookmanager->initHooks(array('emailcollectordao'));
560  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
561  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
562  if ($reshook > 0) {
563  $result = $hookmanager->resPrint;
564  } else {
565  $result .= $hookmanager->resPrint;
566  }
567 
568  return $result;
569  }
570 
577  public function getLibStatut($mode = 0)
578  {
579  return $this->LibStatut($this->status, $mode);
580  }
581 
582  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
590  public function LibStatut($status, $mode = 0)
591  {
592  // phpcs:enable
593  if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
594  global $langs;
595  //$langs->load("mymodule");
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');
600  }
601 
602  $statusType = 'status5';
603  if ($status == self::STATUS_ENABLED) {
604  $statusType = 'status4';
605  }
606 
607  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
608  }
609 
616  public function info($id)
617  {
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);
623  if ($result) {
624  if ($this->db->num_rows($result)) {
625  $obj = $this->db->fetch_object($result);
626  $this->id = $obj->rowid;
627 
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);
632  }
633 
634  $this->db->free($result);
635  } else {
636  dol_print_error($this->db);
637  }
638  }
639 
646  public function initAsSpecimen()
647  {
648  $this->host = 'localhost';
649  $this->login = 'alogin';
650 
651  $this->initAsSpecimenCommon();
652  }
653 
660  public function fetchFilters()
661  {
662  $this->filters = array();
663 
664  $sql = 'SELECT rowid, type, rulevalue, status';
665  $sql .= ' FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectorfilter';
666  $sql .= ' WHERE fk_emailcollector = '.((int) $this->id);
667  //$sql.= ' ORDER BY position';
668 
669  $resql = $this->db->query($sql);
670  if ($resql) {
671  $num = $this->db->num_rows($resql);
672  $i = 0;
673  while ($i < $num) {
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);
676  $i++;
677  }
678  $this->db->free($resql);
679  } else {
680  dol_print_error($this->db);
681  }
682 
683  return 1;
684  }
685 
692  public function fetchActions()
693  {
694  $this->actions = array();
695 
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';
700 
701  $resql = $this->db->query($sql);
702  if ($resql) {
703  $num = $this->db->num_rows($resql);
704  $i = 0;
705  while ($i < $num) {
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);
708  $i++;
709  }
710  $this->db->free($resql);
711  } else {
712  dol_print_error($this->db);
713  }
714  }
715 
716 
724  public function getConnectStringIMAP($ssl = 1, $norsh = 0)
725  {
726  global $conf;
727 
728  // Connect to IMAP
729  $flags = '/service=imap'; // IMAP
730  if (!empty($conf->global->IMAP_FORCE_TLS)) {
731  $flags .= '/tls';
732  } elseif (empty($conf->global->IMAP_FORCE_NOSSL)) {
733  if ($ssl) {
734  $flags .= '/ssl';
735  }
736  }
737  $flags .= '/novalidate-cert';
738  //$flags.='/readonly';
739  //$flags.='/debug';
740  if ($norsh || !empty($conf->global->IMAP_FORCE_NORSH)) {
741  $flags .= '/norsh';
742  }
743  //Used in shared mailbox from Office365
744  if (strpos($this->login, '/') != false) {
745  $partofauth = explode('/', $this->login);
746  $flags .= '/authuser='.$partofauth[0].'/user='.$partofauth[1];
747  }
748 
749  $connectstringserver = '{'.$this->host.':993'.$flags.'}';
750 
751  return $connectstringserver;
752  }
753 
760  public function getEncodedUtf7($str)
761  {
762  if (function_exists('mb_convert_encoding')) {
763  // change spaces by entropy because mb_convert fail with spaces
764  $str = preg_replace("/ /", "xyxy", $str);
765  // if mb_convert work
766  if ($str = mb_convert_encoding($str, "UTF-7")) {
767  // change characters
768  $str = preg_replace("/\+A/", "&A", $str);
769  // change to spaces again
770  $str = preg_replace("/xyxy/", " ", $str);
771  return $str;
772  } else {
773  // print error and return false
774  $this->error = "error: is not possible to encode this string '".$str."'";
775  return false;
776  }
777  } else {
778  return $str;
779  }
780  }
781 
788  public function doCollect()
789  {
790  global $user;
791 
792  $nberror = 0;
793 
794  $arrayofcollectors = $this->fetchAll($user, 1);
795 
796  // Loop on each collector
797  foreach ($arrayofcollectors as $emailcollector) {
798  $result = $emailcollector->doCollectOneCollector();
799  dol_syslog("doCollect result = ".$result." for emailcollector->id = ".$emailcollector->id);
800 
801  $this->error .= 'EmailCollector ID '.$emailcollector->id.':'.$emailcollector->error.'<br>';
802  if (!empty($emailcollector->errors)) {
803  $this->error .= join('<br>', $emailcollector->errors);
804  }
805  $this->output .= 'EmailCollector ID '.$emailcollector->id.': '.$emailcollector->lastresult.'<br>';
806  }
807 
808  return $nberror;
809  }
810 
821  private function overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject, $header)
822  {
823  $errorforthisaction = 0;
824 
825  // Overwrite values with values extracted from source email
826  // $this->actionparam = 'opportunity_status=123;abc=EXTRACT:BODY:....'
827  $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '=');
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];
834  } else {
835  $tmpproperty = $tmparray[0];
836  }
837  if ($tmpclass && ($tmpclass != $object->element)) {
838  continue; // Property is for another type of object
839  }
840 
841  //if (property_exists($object, $tmpproperty) || preg_match('/^options_/', $tmpproperty))
842  if ($tmpproperty) {
843  $sourcestring = '';
844  $sourcefield = '';
845  $regexstring = '';
846  //$transformationstring='';
847  $regforregex = array();
848  if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
849  $sourcefield = $regforregex[1];
850  $regexstring = $regforregex[2];
851  //$transofrmationstring=$regforregex[3];
852  } elseif (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
853  $sourcefield = $regforregex[1];
854  $regexstring = $regforregex[2];
855  }
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;
863  }
864 
865  if ($sourcestring) {
866  $regforval = array();
867  $regexoptions = '';
868  if (strtolower($sourcefield) == 'body') {
869  $regexoptions = 'ms'; // The m means ^ and $ char is valid at each new line. The s means the char '.' is valid for new lines char too
870  }
871  if (strtolower($sourcefield) == 'header') {
872  $regexoptions = 'm'; // The m means ^ and $ char is valid at each new line.
873  }
874 
875  //var_dump($tmpproperty.' - '.$regexstring.' - '.$regexoptions.' - '.$sourcestring);
876  if (preg_match('/'.$regexstring.'/'.$regexoptions, $sourcestring, $regforval)) {
877  //var_dump($regforval[count($regforval)-1]);exit;
878  // Overwrite param $tmpproperty
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);
883  } else {
884  $object->$tmpproperty = $this->decodeSMTPSubject($valueextracted);
885  }
886  } else {
887  if (preg_match('/^options_/', $tmpproperty)) {
888  $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $this->decodeSMTPSubject($valueextracted);
889  } else {
890  $object->$tmpproperty = $this->decodeSMTPSubject($valueextracted);
891  }
892  }
893  } else {
894  // Regex not found
895  $object->$tmpproperty = null;
896  }
897  } else {
898  // Nothing can be done for this param
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;
902  }
903  } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
904  $valuecurrent = '';
905  if (preg_match('/^options_/', $tmpproperty)) {
906  $valuecurrent = $object->array_options[preg_replace('/^options_/', '', $tmpproperty)];
907  } else {
908  $valuecurrent = $object->$tmpproperty;
909  }
910 
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);
916  //var_dump($tmpproperty.' - '.$object->$tmpproperty.' - '.$valuetouse); var_dump($matcharray);
917  if (is_array($matcharray[1])) { // $matcharray[1] is array with list of substitution key found without the __
918  foreach ($matcharray[1] as $keytoreplace) {
919  if ($keytoreplace && isset($object->$keytoreplace)) {
920  $substitutionarray['__'.$keytoreplace.'__'] = $object->$keytoreplace;
921  }
922  }
923  }
924  //var_dump($substitutionarray);
925  dol_syslog(var_export($substitutionarray, true));
926  //var_dump($substitutionarray);
927  $valuetouse = make_substitutions($valuetouse, $substitutionarray);
928  if (preg_match('/^options_/', $tmpproperty)) {
929  $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $valuetouse;
930  } else {
931  $object->$tmpproperty = $valuetouse;
932  }
933  }
934  } else {
935  $errorforthisaction++;
936  $this->error = 'Bad syntax for description of action parameters: '.$actionparam;
937  $this->errors[] = $this->error;
938  }
939  }
940  }
941 
942  return $errorforthisaction;
943  }
944 
950  public function doCollectOneCollector()
951  {
952  global $conf, $langs, $user;
953  global $hookmanager;
954 
955  //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
956 
957  require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
958 
959  dol_syslog("EmailCollector::doCollectOneCollector start for id=".$this->id." - ".$this->ref, LOG_DEBUG);
960 
961  $langs->loadLangs(array("project", "companies", "mails", "errors", "ticket", "agenda", "commercial"));
962 
963  $error = 0;
964  $this->output = '';
965  $this->error = '';
966 
967  $now = dol_now();
968 
969  if (empty($this->host)) {
970  $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMailHost'));
971  return -1;
972  }
973  if (empty($this->login)) {
974  $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Login'));
975  return -1;
976  }
977  if (empty($this->source_directory)) {
978  $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('MailboxSourceDirectory'));
979  return -1;
980  }
981  if (!function_exists('imap_open')) {
982  $this->error = 'IMAP function not enabled on your PHP';
983  return -2;
984  }
985 
986  $this->fetchFilters();
987  $this->fetchActions();
988 
989  $sourcedir = $this->source_directory;
990  $targetdir = ($this->target_directory ? $this->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag'
991 
992  $connectstringserver = $this->getConnectStringIMAP();
993  $connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
994  $connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
995 
996  $connection = imap_open($connectstringsource, $this->login, $this->password);
997  if (!$connection) {
998  $this->error = 'Failed to open IMAP connection '.$connectstringsource;
999  return -3;
1000  }
1001  imap_errors(); // Clear stack of errors.
1002 
1003  $host = dol_getprefix('email');
1004  //$host = '123456';
1005 
1006  // Define the IMAP search string
1007  // See https://tools.ietf.org/html/rfc3501#section-6.4.4 for IMAPv4 (PHP not yet compatible)
1008  // See https://tools.ietf.org/html/rfc1064 page 13 for IMAPv2
1009  //$search='ALL';
1010  $search = 'UNDELETED'; // Seems not supported by some servers
1011  $searchhead = '';
1012  $searchfilterdoltrackid = 0;
1013  $searchfilternodoltrackid = 0;
1014  $searchfilterisanswer = 0;
1015  $searchfilterisnotanswer = 0;
1016  foreach ($this->filters as $rule) {
1017  if (empty($rule['status'])) {
1018  continue;
1019  }
1020 
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).'"';
1026  }
1027  } else {
1028  $search .= ($search ? ' ' : '').'TO "'.str_replace('"', '', $rule['rulevalue']).'"';
1029  }
1030  }
1031  if ($rule['type'] == 'bcc') {
1032  $search .= ($search ? ' ' : '').'BCC';
1033  }
1034  if ($rule['type'] == 'cc') {
1035  $search .= ($search ? ' ' : '').'CC';
1036  }
1037  if ($rule['type'] == 'from') {
1038  $search .= ($search ? ' ' : '').'FROM "'.str_replace('"', '', $rule['rulevalue']).'"';
1039  }
1040  if ($rule['type'] == 'subject') {
1041  $search .= ($search ? ' ' : '').'SUBJECT "'.str_replace('"', '', $rule['rulevalue']).'"';
1042  }
1043  if ($rule['type'] == 'body') {
1044  $search .= ($search ? ' ' : '').'BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
1045  }
1046  if ($rule['type'] == 'header') {
1047  $search .= ($search ? ' ' : '').'HEADER '.$rule['rulevalue'];
1048  }
1049 
1050  if ($rule['type'] == 'notinsubject') {
1051  $search .= ($search ? ' ' : '').'SUBJECT NOT "'.str_replace('"', '', $rule['rulevalue']).'"';
1052  }
1053  if ($rule['type'] == 'notinbody') {
1054  $search .= ($search ? ' ' : '').'BODY NOT "'.str_replace('"', '', $rule['rulevalue']).'"';
1055  }
1056 
1057  if ($rule['type'] == 'seen') {
1058  $search .= ($search ? ' ' : '').'SEEN';
1059  }
1060  if ($rule['type'] == 'unseen') {
1061  $search .= ($search ? ' ' : '').'UNSEEN';
1062  }
1063  if ($rule['type'] == 'unanswered') {
1064  $search .= ($search ? ' ' : '').'UNANSWERED';
1065  }
1066  if ($rule['type'] == 'answered') {
1067  $search .= ($search ? ' ' : '').'ANSWERED';
1068  }
1069  if ($rule['type'] == 'smaller') {
1070  $search .= ($search ? ' ' : '').'SMALLER "'.str_replace('"', '', $rule['rulevalue']).'"';
1071  }
1072  if ($rule['type'] == 'larger') {
1073  $search .= ($search ? ' ' : '').'LARGER "'.str_replace('"', '', $rule['rulevalue']).'"';
1074  }
1075 
1076  if ($rule['type'] == 'withtrackingidinmsgid') {
1077  $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
1078  }
1079  if ($rule['type'] == 'withouttrackingidinmsgid') {
1080  $searchfilterdoltrackid++; $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
1081  }
1082  if ($rule['type'] == 'withtrackingid') {
1083  $searchfilterdoltrackid++; $searchhead .= '/References.*@'.preg_quote($host, '/').'/';
1084  }
1085  if ($rule['type'] == 'withouttrackingid') {
1086  $searchfilternodoltrackid++; $searchhead .= '! /References.*@'.preg_quote($host, '/').'/';
1087  }
1088 
1089  if ($rule['type'] == 'isanswer') {
1090  $searchfilterisanswer++; $searchhead .= '/References.*@.*/';
1091  }
1092  if ($rule['type'] == 'isnotanswer') {
1093  $searchfilterisnotanswer++; $searchhead .= '! /References.*@.*/';
1094  }
1095  }
1096 
1097  if (empty($targetdir)) { // Use last date as filter if there is no targetdir defined.
1098  $fromdate = 0;
1099  if ($this->datelastok) {
1100  $fromdate = $this->datelastok;
1101  }
1102  if ($fromdate > 0) {
1103  $search .= ($search ? ' ' : '').'SINCE '.date('j-M-Y', $fromdate - 1); // SENTSINCE not supported. Date must be X-Abc-9999 (X on 1 digit if < 10)
1104  }
1105  //$search.=($search?' ':'').'SINCE 8-Apr-2018';
1106  }
1107  dol_syslog("IMAP search string = ".$search);
1108  //var_dump($search);
1109 
1110  $nbemailprocessed = 0;
1111  $nbemailok = 0;
1112  $nbactiondone = 0;
1113  $charset = ($this->hostcharset ? $this->hostcharset : "UTF-8");
1114 
1115  // Scan IMAP inbox
1116  $arrayofemail = imap_search($connection, $search, null, $charset);
1117  if ($arrayofemail === false) {
1118  // Nothing found or search string not understood
1119  $mapoferrrors = imap_errors();
1120  if ($mapoferrrors !== false) {
1121  $error++;
1122  $this->error = "Search string not understood - ".join(',', $mapoferrrors);
1123  $this->errors[] = $this->error;
1124  }
1125  }
1126 
1127  // Loop on each email found
1128  if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
1129  // Loop to get part html and plain
1130  /*
1131  0 multipart/mixed
1132  1 multipart/alternative
1133  1.1 text/plain
1134  1.2 text/html
1135  2 message/rfc822
1136  2 multipart/mixed
1137  2.1 multipart/alternative
1138  2.1.1 text/plain
1139  2.1.2 text/html
1140  2.2 message/rfc822
1141  2.2 multipart/alternative
1142  2.2.1 text/plain
1143  2.2.2 text/html
1144  */
1152  /*function createPartArray($structure, $prefix = "")
1153  {
1154  //print_r($structure);
1155  $part_array=array();
1156  if (count($structure->parts) > 0) { // There some sub parts
1157  foreach ($structure->parts as $count => $part) {
1158  addPartToArray($part, $prefix.($count+1), $part_array);
1159  }
1160  }else{ // Email does not have a seperate mime attachment for text
1161  $part_array[] = array('part_number' => $prefix.'1', 'part_object' => $structure);
1162  }
1163  return $part_array;
1164  }*/
1165 
1174  /*function addPartToArray($obj, $partno, &$part_array)
1175  {
1176  $part_array[] = array('part_number' => $partno, 'part_object' => $obj);
1177  if ($obj->type == 2) { // Check to see if the part is an attached email message, as in the RFC-822 type
1178  //print_r($obj);
1179  if (array_key_exists('parts', $obj)) { // Check to see if the email has parts
1180  foreach ($obj->parts as $count => $part) {
1181  // Iterate here again to compensate for the broken way that imap_fetchbody() handles attachments
1182  if (count($part->parts) > 0) {
1183  foreach ($part->parts as $count2 => $part2) {
1184  addPartToArray($part2, $partno.".".($count2+1), $part_array);
1185  }
1186  }else{ // Attached email does not have a seperate mime attachment for text
1187  $part_array[] = array('part_number' => $partno.'.'.($count+1), 'part_object' => $obj);
1188  }
1189  }
1190  }else{ // Not sure if this is possible
1191  $part_array[] = array('part_number' => $partno.'.1', 'part_object' => $obj);
1192  }
1193  }else{ // If there are more sub-parts, expand them out.
1194  if (array_key_exists('parts', $obj)) {
1195  foreach ($obj->parts as $count => $p) {
1196  addPartToArray($p, $partno.".".($count+1), $part_array);
1197  }
1198  }
1199  }
1200  }*/
1201 
1202  dol_syslog("Start of loop on email", LOG_INFO, 1);
1203 
1204  $iforemailloop = 0;
1205  foreach ($arrayofemail as $imapemail) {
1206  if ($nbemailprocessed > 1000) {
1207  break; // Do not process more than 1000 email per launch (this is a different protection than maxnbcollectedpercollect)
1208  }
1209 
1210  $iforemailloop++;
1211 
1212  // GET header and overview datas
1213 
1214  $header = imap_fetchheader($connection, $imapemail, 0);
1215  $overview = imap_fetch_overview($connection, $imapemail, 0);
1216 
1217  // print $header;
1218  // var_dump($overview);
1219 
1220  // Process $header of email
1221  $header = preg_replace('/\r\n\s+/m', ' ', $header); // When a header line is on several lines, merge lines
1222 
1223  $matches = array();
1224  preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)\r\n/m', $header, $matches);
1225  $headers = array_combine($matches[1], $matches[2]);
1226 
1227  if (!empty($headers['in-reply-to']) && empty($headers['In-Reply-To'])) {
1228  $headers['In-Reply-To'] = $headers['in-reply-to'];
1229  }
1230  if (!empty($headers['references']) && empty($headers['References'])) {
1231  $headers['References'] = $headers['references'];
1232  }
1233  if (!empty($headers['message-id']) && empty($headers['Message-ID'])) {
1234  $headers['Message-ID'] = $headers['message-id'];
1235  }
1236 
1237  $headers['Subject'] = $this->decodeSMTPSubject($headers['Subject']);
1238 
1239  $emailto = $this->decodeSMTPSubject($overview[0]->to);
1240 
1241 
1242  dol_syslog("** Process email ".$iforemailloop." References: ".$headers['References']." Subject: ".$headers['Subject']);
1243  //print "Process mail ".$iforemailloop." Subject: ".dol_escape_htmltag($headers['Subject'])." References: ".dol_escape_htmltag($headers['References'])." In-Reply-To: ".dol_escape_htmltag($headers['In-Reply-To'])."<br>\n";
1244 
1245  $trackidfoundintorecipienttype = '';
1246  $trackidfoundintorecipientid = 0;
1247  $reg = array();
1248  // See also later list of all supported tags...
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)) { // Can be 'emailing-test' or 'emailing-IdMailing-IdRecipient'
1253  $trackidfoundintorecipienttype = 'emailing';
1254  $trackidfoundintorecipientid = $reg[1];
1255  }
1256 
1257  // If there is a filter on trackid
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");
1263  continue; // Exclude email
1264  }
1265  }
1266  }
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");
1271  continue; // Exclude email
1272  }
1273  }
1274 
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)");
1279  continue; // Exclude email
1280  }
1281  // Note: we can have
1282  // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer or NOT (a transfer rewriten)
1283  $isanswer = 0;
1284  if (preg_match('/Re\s*:\s+/i', $headers['Subject'])) {
1285  $isanswer = 1;
1286  }
1287  //if ($headers['In-Reply-To'] != $headers['Message-ID'] && empty($headers['References'])) $isanswer = 1; // If in-reply-to differs of message-id, this is a reply
1288  //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1;
1289 
1290  if (!$isanswer) {
1291  $nbemailprocessed++;
1292  dol_syslog(" Discarded - Email is not an answer (no RE prefix in subject)");
1293  continue; // Exclude email
1294  }
1295  }
1296  if ($searchfilterisnotanswer > 0) {
1297  if (!empty($headers['In-Reply-To'])) {
1298  // Note: we can have
1299  // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer or NOT (a transfer rewriten)
1300  $isanswer = 0;
1301  if (preg_match('/Re\s*:\s+/i', $headers['Subject'])) {
1302  $isanswer = 1;
1303  }
1304  //if ($headers['In-Reply-To'] != $headers['Message-ID'] && empty($headers['References'])) $isanswer = 1; // If in-reply-to differs of message-id, this is a reply
1305  //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1;
1306  if ($isanswer) {
1307  $nbemailprocessed++;
1308  dol_syslog(" Discarded - Email is an answer");
1309  continue; // Exclude email
1310  }
1311  }
1312  }
1313 
1314  //print "Process mail ".$iforemailloop." Subject: ".dol_escape_htmltag($headers['Subject'])." selected<br>\n";
1315 
1316  $thirdpartystatic = new Societe($this->db);
1317  $contactstatic = new Contact($this->db);
1318  $projectstatic = new Project($this->db);
1319 
1320  $nbactiondoneforemail = 0;
1321  $errorforemail = 0;
1322  $errorforactions = 0;
1323  $thirdpartyfoundby = '';
1324  $contactfoundby = '';
1325  $projectfoundby = '';
1326  $ticketfoundby = '';
1327  $candidaturefoundby = '';
1328 
1329  $this->db->begin();
1330 
1331 
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);
1333 
1334  $overview[0]->subject = $this->decodeSMTPSubject($overview[0]->subject);
1335 
1336  $overview[0]->from = $this->decodeSMTPSubject($overview[0]->from);
1337 
1338  // Removed emojis
1339  $overview[0]->subject = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $overview[0]->subject);
1340 
1341  // GET IMAP email structure/content
1342 
1343  global $htmlmsg, $plainmsg, $charset, $attachments;
1344 
1345  $this->getmsg($connection, $imapemail);
1346 
1347  //print $plainmsg;
1348  //var_dump($plainmsg); exit;
1349 
1350  //$htmlmsg,$plainmsg,$charset,$attachments
1351  $messagetext = $plainmsg ? $plainmsg : dol_string_nohtmltag($htmlmsg, 0);
1352  // Removed emojis
1353  $messagetext = preg_replace('/[\x{10000}-\x{10FFFF}]/u', "\xEF\xBF\xBD", $messagetext);
1354 
1355  //var_dump($plainmsg);
1356  //var_dump($htmlmsg);
1357  //var_dump($messagetext);
1358  //var_dump($charset);
1359  //var_dump($attachments);
1360  //exit;
1361 
1362  // Parse IMAP email structure
1363  /*
1364  $structure = imap_fetchstructure($connection, $imapemail, 0);
1365 
1366  $partplain = $parthtml = -1;
1367  $encodingplain = $encodinghtml = '';
1368 
1369  $result = createPartArray($structure, '');
1370 
1371  foreach($result as $part)
1372  {
1373  // $part['part_object']->type seems 0 for content
1374  // $part['part_object']->type seems 5 for attachment
1375  if (empty($part['part_object'])) continue;
1376  if ($part['part_object']->subtype == 'HTML')
1377  {
1378  $parthtml=$part['part_number'];
1379  if ($part['part_object']->encoding == 4)
1380  {
1381  $encodinghtml = 'aaa';
1382  }
1383  }
1384  if ($part['part_object']->subtype == 'PLAIN')
1385  {
1386  $partplain=$part['part_number'];
1387  if ($part['part_object']->encoding == 4)
1388  {
1389  $encodingplain = 'rr';
1390  }
1391  }
1392  }
1393  //var_dump($result);
1394  //var_dump($partplain);
1395  //var_dump($parthtml);
1396 
1397  //var_dump($structure);
1398  //var_dump($parthtml);
1399  //var_dump($partplain);
1400 
1401  $messagetext = imap_fetchbody($connection, $imapemail, ($parthtml != '-1' ? $parthtml : ($partplain != '-1' ? $partplain : 1)), FT_PEEK);
1402  */
1403 
1404  //var_dump($messagetext);
1405  //var_dump($structure->parts[0]->parts);
1406  //print $header;
1407  //print $messagetext;
1408  //exit;
1409 
1410  $fromstring = $overview[0]->from;
1411 
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;
1419  //var_dump($msgid);exit;
1420 
1421  $reg = array();
1422  if (preg_match('/^(.*)<(.*)>$/', $fromstring, $reg)) {
1423  $from = $reg[2];
1424  $fromtext = $reg[1];
1425  } else {
1426  $from = $fromstring;
1427  $fromtext = '';
1428  }
1429  $fk_element_id = 0; $fk_element_type = '';
1430 
1431 
1432  $contactid = 0; $thirdpartyid = 0; $projectid = 0; $ticketid = 0;
1433 
1434  // Analyze TrackId in field References. For example:
1435  // References: <1542377954.SMTPs-dolibarr-thi649@8f6014fde11ec6cdec9a822234fc557e>
1436  // References: <1542377954.SMTPs-dolibarr-tic649@8f6014fde11ec6cdec9a822234fc557e>
1437  // References: <1542377954.SMTPs-dolibarr-abc649@8f6014fde11ec6cdec9a822234fc557e>
1438  $trackid = '';
1439  $objectid = 0;
1440  $objectemail = null;
1441 
1442  $reg = array();
1443  if (!empty($headers['References'])) {
1444  $arrayofreferences = preg_split('/(,|\s+)/', $headers['References']);
1445  // var_dump($headers['References']);
1446  // var_dump($arrayofreferences);
1447 
1448  foreach ($arrayofreferences as $reference) {
1449  //print "Process mail ".$iforemailloop." email_msgid ".$msgid.", date ".dol_print_date($date, 'dayhour').", subject ".$subject.", reference ".dol_escape_htmltag($reference)."<br>\n";
1450  if (!empty($trackidfoundintorecipienttype)) {
1451  $resultsearchtrackid = -1;
1452  $reg[1] = $trackidfoundintorecipienttype;
1453  $reg[2] = $trackidfoundintorecipientid;
1454  } else {
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);
1458  }
1459  }
1460 
1461  if (!empty($resultsearchtrackid)) {
1462  // We found a tracker (in recipient email or into a Reference matching the Dolibarr server)
1463  $trackid = $reg[1].$reg[2];
1464 
1465  $objectid = $reg[2];
1466  // See also list into interface_50_modAgenda_ActionsAuto
1467  if ($reg[1] == 'thi') {
1468  $objectemail = new Societe($this->db);
1469  }
1470  if ($reg[1] == 'ctc') {
1471  $objectemail = new Contact($this->db);
1472  }
1473  if ($reg[1] == 'inv') { // customer invoices
1474  $objectemail = new Facture($this->db);
1475  }
1476  if ($reg[1] == 'sinv') { // supplier invoices
1477  $objectemail = new FactureFournisseur($this->db);
1478  }
1479  if ($reg[1] == 'pro') { // customer proposals
1480  $objectemail = new Propal($this->db);
1481  }
1482  if ($reg[1] == 'ord') { // customer orders
1483  $objectemail = new Commande($this->db);
1484  }
1485  if ($reg[1] == 'shi') { // shipments
1486  $objectemail = new Expedition($this->db);
1487  }
1488  if ($reg[1] == 'spro') { // supplier proposal
1489  $objectemail = new SupplierProposal($this->db);
1490  }
1491  if ($reg[1] == 'sord') { // supplier order
1492  $objectemail = new CommandeFournisseur($this->db);
1493  }
1494  if ($reg[1] == 'rec') { // Reception
1495  $objectemail = new Reception($this->db);
1496  }
1497  if ($reg[1] == 'proj') {
1498  $objectemail = new Project($this->db);
1499  }
1500  if ($reg[1] == 'tas') {
1501  $objectemail = new Task($this->db);
1502  }
1503  if ($reg[1] == 'con') {
1504  $objectemail = new Contact($this->db);
1505  }
1506  if ($reg[1] == 'use') {
1507  $objectemail = new User($this->db);
1508  }
1509  if ($reg[1] == 'tic') {
1510  $objectemail = new Ticket($this->db);
1511  }
1512  if ($reg[1] == 'recruitmentcandidature') {
1513  $objectemail = new RecruitmentCandidature($this->db);
1514  }
1515  if ($reg[1] == 'mem') {
1516  $objectemail = new Adherent($this->db);
1517  }
1518  /*if ($reg[1] == 'leav') {
1519  $objectemail = new Holiday($db);
1520  }
1521  if ($reg[1] == 'exp') {
1522  $objectemail = new ExpenseReport($db);
1523  }*/
1524  } elseif (preg_match('/<(.*@.*)>/', $reference, $reg)) {
1525  // This is an external reference, we check if we have it in our database
1526  if (!is_object($objectemail)) {
1527  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."ticket where email_msgid = '".$this->db->escape($reg[1])."'";
1528  $resql = $this->db->query($sql);
1529  if ($resql) {
1530  $obj = $this->db->fetch_object($resql);
1531  if ($obj) {
1532  $objectid = $obj->rowid;
1533  $objectemail = new Ticket($this->db);
1534  $ticketfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
1535  }
1536  } else {
1537  $errorforemail++;
1538  }
1539  }
1540 
1541  if (!is_object($objectemail)) {
1542  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."projet where email_msgid = '".$this->db->escape($reg[1])."'";
1543  $resql = $this->db->query($sql);
1544  if ($resql) {
1545  $obj = $this->db->fetch_object($resql);
1546  if ($obj) {
1547  $objectid = $obj->rowid;
1548  $objectemail = new Project($this->db);
1549  $projectfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
1550  }
1551  } else {
1552  $errorforemail++;
1553  }
1554  }
1555 
1556  if (!is_object($objectemail)) {
1557  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1])."'";
1558  $resql = $this->db->query($sql);
1559  if ($resql) {
1560  $obj = $this->db->fetch_object($resql);
1561  if ($obj) {
1562  $objectid = $obj->rowid;
1563  $objectemail = new RecruitmentCandidature($this->db);
1564  $candidaturefoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
1565  }
1566  } else {
1567  $errorforemail++;
1568  }
1569  }
1570  }
1571 
1572  // Load object linked to email
1573  if (is_object($objectemail)) {
1574  $result = $objectemail->fetch($objectid);
1575  if ($result > 0) {
1576  $fk_element_id = $objectemail->id;
1577  $fk_element_type = $objectemail->element;
1578  // Fix fk_element_type
1579  if ($fk_element_type == 'facture') {
1580  $fk_element_type = 'invoice';
1581  }
1582 
1583  if (get_class($objectemail) != 'Societe') {
1584  $thirdpartyid = $objectemail->fk_soc;
1585  } else {
1586  $thirdpartyid = $objectemail->id;
1587  }
1588 
1589  if (get_class($objectemail) != 'Contact') {
1590  $contactid = $objectemail->fk_socpeople;
1591  } else {
1592  $contactid = $objectemail->id;
1593  }
1594 
1595  if (get_class($objectemail) != 'Project') {
1596  $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
1597  } else {
1598  $projectid = $objectemail->id;
1599  }
1600  }
1601  }
1602 
1603  // Project
1604  if ($projectid > 0) {
1605  $result = $projectstatic->fetch($projectid);
1606  if ($result <= 0) {
1607  $projectstatic->id = 0;
1608  } else {
1609  $projectid = $projectstatic->id;
1610  if ($trackid) {
1611  $projectfoundby = 'trackid ('.$trackid.')';
1612  }
1613  if (empty($contactid)) {
1614  $contactid = $projectstatic->fk_contact;
1615  }
1616  if (empty($thirdpartyid)) {
1617  $thirdpartyid = $projectstatic->fk_soc;
1618  }
1619  }
1620  }
1621  // Contact
1622  if ($contactid > 0) {
1623  $result = $contactstatic->fetch($contactid);
1624  if ($result <= 0) {
1625  $contactstatic->id = 0;
1626  } else {
1627  $contactid = $contactstatic->id;
1628  if ($trackid) {
1629  $contactfoundby = 'trackid ('.$trackid.')';
1630  }
1631  if (empty($thirdpartyid)) {
1632  $thirdpartyid = $contactstatic->fk_soc;
1633  }
1634  }
1635  }
1636  // Thirdparty
1637  if ($thirdpartyid > 0) {
1638  $result = $thirdpartystatic->fetch($thirdpartyid);
1639  if ($result <= 0) {
1640  $thirdpartystatic->id = 0;
1641  } else {
1642  $thirdpartyid = $thirdpartystatic->id;
1643  if ($trackid) {
1644  $thirdpartyfoundby = 'trackid ('.$trackid.')';
1645  }
1646  }
1647  }
1648 
1649  if (is_object($objectemail)) {
1650  break; // Exit loop of references. We already found an accurate reference
1651  }
1652  }
1653  }
1654 
1655  if (empty($contactid)) { // Try to find contact using email
1656  $result = $contactstatic->fetch(0, null, '', $from);
1657 
1658  if ($result > 0) {
1659  $contactid = $contactstatic->id;
1660  $contactfoundby = 'email of contact ('.$from.')';
1661  if (empty($thirdpartyid) && $contactstatic->socid > 0) {
1662  $result = $thirdpartystatic->fetch($contactstatic->socid);
1663  if ($result > 0) {
1664  $thirdpartyid = $thirdpartystatic->id;
1665  $thirdpartyfoundby = 'email of contact ('.$from.')';
1666  }
1667  }
1668  }
1669  }
1670 
1671  if (empty($thirdpartyid)) { // Try to find thirdparty using email
1672  $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $from);
1673  if ($result > 0) {
1674  $thirdpartyfoundby = 'email ('.$from.')';
1675  }
1676  }
1677 
1678  // Do operations
1679  foreach ($this->actions as $operation) {
1680  $errorforthisaction = 0;
1681 
1682  if ($errorforactions) {
1683  break;
1684  }
1685  if (empty($operation['status'])) {
1686  continue;
1687  }
1688 
1689  // Make Operation
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); // If a Dolibarr tracker id is found, we should now the id of object
1692 
1693  $actioncode = 'EMAIL_IN';
1694  // If we scan the Sent box, we use the code for out email
1695  if ($this->source_directory == 'Sent') {
1696  $actioncode = 'EMAIL_OUT';
1697  }
1698 
1699  $description = $descriptiontitle = $descriptionmeta = $descriptionfull = '';
1700 
1701  $descriptiontitle = $langs->trans("RecordCreatedByEmailCollector", $this->ref, $msgid);
1702 
1703  $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTopic").' : '.dol_escape_htmltag($subject));
1704  $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailFrom").($langs->trans("MailFrom") != 'From' ? ' (From)' : '').' : '.dol_escape_htmltag($fromstring));
1705  if ($sender) {
1706  $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("Sender").($langs->trans("Sender") != 'Sender' ? ' (Sender)' : '').' : '.dol_escape_htmltag($sender));
1707  }
1708  $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTo").($langs->trans("MailTo") != 'To' ? ' (To)' : '').' : '.dol_escape_htmltag($to));
1709  if ($sendtocc) {
1710  $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailCC").($langs->trans("MailCC") != 'CC' ? ' (CC)' : '').' : '.dol_escape_htmltag($sendtocc));
1711  }
1712 
1713  // Search and create thirdparty
1714  if ($operation['type'] == 'loadthirdparty' || $operation['type'] == 'loadandcreatethirdparty') {
1715  if (empty($operation['actionparam'])) {
1716  $errorforactions++;
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;
1719  } else {
1720  $actionparam = $operation['actionparam'];
1721  $idtouseforthirdparty = '';
1722  $nametouseforthirdparty = '';
1723  $emailtouseforthirdparty = '';
1724 
1725  // $actionparam = 'param=SET:aaa' or 'param=EXTRACT:BODY:....'
1726  $arrayvaluetouse = dolExplodeIntoArray($actionparam, ';', '=');
1727  foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
1728  $sourcestring = '';
1729  $sourcefield = '';
1730  $regexstring = '';
1731  $regforregex = array();
1732 
1733  if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
1734  $sourcefield = $regforregex[1];
1735  $regexstring = $regforregex[2];
1736  }
1737 
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;
1745  }
1746 
1747  if ($sourcestring) {
1748  $regforval = array();
1749  //var_dump($regexstring);var_dump($sourcestring);
1750  if (preg_match('/'.$regexstring.'/ms', $sourcestring, $regforval)) {
1751  //var_dump($regforval[count($regforval)-1]);exit;
1752  // Overwrite param $tmpproperty
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;
1757  } else {
1758  $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
1759  }
1760  } else {
1761  // Regex not found
1762  $idtouseforthirdparty = null;
1763  $nametouseforthirdparty = null;
1764  $emailtouseforthirdparty = null;
1765  }
1766  //var_dump($object->$tmpproperty);exit;
1767  } else {
1768  // Nothing can be done for this param
1769  $errorforactions++;
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;
1772  }
1773  } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
1774  //if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $reg[1];
1775  //else $object->$tmpproperty = $reg[1];
1776  if ($propertytooverwrite == 'id') {
1777  $idtouseforthirdparty = $reg[2];
1778  } elseif ($propertytooverwrite == 'email') {
1779  $emailtouseforthirdparty = $reg[2];
1780  } else {
1781  $nametouseforthirdparty = $reg[2];
1782  }
1783  } else {
1784  $errorforactions++;
1785  $this->error = 'Bad syntax for description of action parameters: '.$actionparam;
1786  $this->errors[] = $this->error;
1787  break;
1788  }
1789  }
1790 
1791  if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty)) {
1792  $result = $thirdpartystatic->fetch($idtouseforthirdparty, $nametouseforthirdparty, '', '', '', '', '', '', '', '', $emailtouseforthirdparty);
1793  if ($result < 0) {
1794  $errorforactions++;
1795  $this->error = 'Error when getting thirdparty with name '.$nametouseforthirdparty.' (may be 2 record exists with same name ?)';
1796  $this->errors[] = $this->error;
1797  break;
1798  } elseif ($result == 0) {
1799  if ($operation['type'] == 'loadthirdparty') {
1800  dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." was not found");
1801 
1802  $errorforactions++;
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.");
1807 
1808  // Create thirdparty
1809  $thirdpartystatic->name = $nametouseforthirdparty;
1810  if ($fromtext != $nametouseforthirdparty) {
1811  $thirdpartystatic->name_alias = $fromtext;
1812  }
1813  $thirdpartystatic->email = ($emailtouseforthirdparty ? $emailtouseforthirdparty : $from);
1814 
1815  // Overwrite values with values extracted from source email
1816  $errorforthisaction = $this->overwritePropertiesOfObject($thirdpartystatic, $operation['actionparam'], $messagetext, $subject, $header);
1817 
1818  if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
1819  $thirdpartystatic->code_client = 'auto';
1820  }
1821  if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
1822  $thirdpartystatic->code_fournisseur = 'auto';
1823  }
1824 
1825  if ($errorforthisaction) {
1826  $errorforactions++;
1827  } else {
1828  $result = $thirdpartystatic->create($user);
1829  if ($result <= 0) {
1830  $errorforactions++;
1831  $this->error = $thirdpartystatic->error;
1832  $this->errors = $thirdpartystatic->errors;
1833  }
1834  }
1835  }
1836  }
1837  }
1838  }
1839  } elseif ($operation['type'] == 'recordevent') {
1840  // Create event
1841  $actioncomm = new ActionComm($this->db);
1842 
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);
1848  }
1849  }
1850  if ($thirdpartystatic->id > 0) {
1851  if ($thirdpartyfoundby) {
1852  $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
1853  }
1854  }
1855  if ($contactstatic->id > 0) {
1856  if ($contactfoundby) {
1857  $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
1858  }
1859  }
1860 
1861  $description = $descriptiontitle;
1862  $description = dol_concatdesc($description, "-----");
1863  $description = dol_concatdesc($description, $descriptionmeta);
1864  $description = dol_concatdesc($description, "-----");
1865  $description = dol_concatdesc($description, $messagetext);
1866 
1867  $descriptionfull = $description;
1868  if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
1869  $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
1870  $descriptionfull = dol_concatdesc($descriptionfull, $header);
1871  }
1872 
1873  // Insert record of emails sent
1874  $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
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; // Not applicable
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; // User saving action
1886  $actioncomm->userownerid = $user->id; // Owner of action
1887  // Fields when action is an email (content should be added into note)
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 = '';
1896 
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;
1903  }
1904  }
1905 
1906  //$actioncomm->extraparams = $extraparams;
1907 
1908  // Overwrite values with values extracted from source email
1909  $errorforthisaction = $this->overwritePropertiesOfObject($actioncomm, $operation['actionparam'], $messagetext, $subject, $header);
1910 
1911  //var_dump($fk_element_id);
1912  //var_dump($fk_element_type);
1913  //var_dump($alreadycreated);
1914  //var_dump($operation['type']);
1915  //var_dump($actioncomm);
1916  //exit;
1917 
1918  if ($errorforthisaction) {
1919  $errorforactions++;
1920  } else {
1921  $result = $actioncomm->create($user);
1922  if ($result <= 0) {
1923  $errorforactions++;
1924  $this->errors = $actioncomm->errors;
1925  }
1926  }
1927  }
1928  } elseif ($operation['type'] == 'recordjoinpiece') {
1929  $pj = getAttachments($imapemail, $connection);
1930  foreach ($pj as $key => $val) {
1931  $data[$val['filename']] = getFileData($imapemail, $val['pos'], $val['type'], $connection);
1932  }
1933  if (count($pj) > 0) {
1934  $sql = "SELECT rowid as id FROM " . MAIN_DB_PREFIX . "user WHERE email LIKE '%" . $from . "%'";
1935  $resql = $this->db->query($sql);
1936  if ($this->db->num_rows($resql) == 0) {
1937  $this->errors[] = 'User Not allowed to add documents';
1938  }
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',
2027  'object' => 'BOM'),
2028  'mrp' => array('table' => 'mrp_mo',
2029  'fields' => array('ref'),
2030  'class' => 'mrp/class/mo.class.php',
2031  'object' => 'Mo'),
2032  );
2033 
2034  if (!is_object($hookmanager)) {
2035  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
2036  $hookmanager = new HookManager($this->db);
2037  }
2038  $hookmanager->initHooks(array('emailcolector'));
2039  $parameters = array('arrayobject' => $arrayobject);
2040  $reshook = $hookmanager->executeHooks('addmoduletoeamailcollectorjoinpiece', $parameters); // Note that $action and $object may have been modified by some hooks
2041  if ($reshook > 0) {
2042  $arrayobject = $hookmanager->resArray;
2043  }
2044 
2045  $resultobj = array();
2046 
2047  foreach ($arrayobject as $key => $objectdesc) {
2048  $sql = 'SELECT DISTINCT t.rowid ';
2049  $sql .= ' FROM ' . MAIN_DB_PREFIX . $objectdesc['table'] . ' AS t';
2050  $sql .= ' WHERE ';
2051  foreach ($objectdesc['fields'] as $field) {
2052  $sql .= "'" .$this->db->escape($subject) . "' LIKE CONCAT('%', t." . $field . ", '%') OR ";
2053  }
2054  $sql = substr($sql, 0, -4);
2055 
2056  $ressqlobj = $this->db->query($sql);
2057  if ($ressqlobj) {
2058  while ($obj = $this->db->fetch_object($ressqlobj)) {
2059  $resultobj[$key][] = $obj->rowid;
2060  }
2061  }
2062  }
2063  $dirs = array();
2064  foreach ($resultobj as $mod => $ids) {
2065  $moddesc = $arrayobject[$mod];
2066  $elementpath = $mod;
2067  dol_include_once($moddesc['class']);
2068  $objectmanaged = new $moddesc['object']($this->db);
2069  foreach ($ids as $val) {
2070  $res = $objectmanaged->fetch($val);
2071  if ($res) {
2072  $path = ($objectmanaged->entity > 1 ? "/" . $objectmanaged->entity : '');
2073  $dirs[] = DOL_DATA_ROOT . $path . "/" . $elementpath . '/' . dol_sanitizeFileName($objectmanaged->ref) . '/';
2074  } else {
2075  $this->errors[] = 'object not found';
2076  }
2077  }
2078  }
2079  foreach ($dirs as $target) {
2080  foreach ($data as $filename => $content) {
2081  $prefix = $this->actions[$this->id]['actionparam'];
2082 
2083  $resr = saveAttachment($target, $prefix . '_' . $filename, $content);
2084  if ($resr == -1) {
2085  $this->errors[] = 'Doc not saved';
2086  }
2087  }
2088  }
2089  } else {
2090  $this->errors[] = 'no joined piece';
2091  }
2092  } elseif ($operation['type'] == 'project') {
2093  // Create project / lead
2094  $projecttocreate = new Project($this->db);
2095 
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);
2102  }
2103  }
2104  if ($contactstatic->id > 0) {
2105  $projecttocreate->contact_id = $contactstatic->id;
2106  if ($contactfoundby) {
2107  $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
2108  }
2109  }
2110 
2111  $description = $descriptiontitle;
2112  $description = dol_concatdesc($description, "-----");
2113  $description = dol_concatdesc($description, $descriptionmeta);
2114  $description = dol_concatdesc($description, "-----");
2115  $description = dol_concatdesc($description, $messagetext);
2116 
2117  $descriptionfull = $description;
2118  if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2119  $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
2120  $descriptionfull = dol_concatdesc($descriptionfull, $header);
2121  }
2122 
2123  $id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid');
2124  $percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent');
2125 
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;
2131  $projecttocreate->description = dol_concatdesc(dolGetFirstLineOfText(dol_string_nohtmltag($description, 2), 10), '...'.$langs->transnoentities("SeePrivateNote").'...');
2132  $projecttocreate->note_private = $descriptionfull;
2133  $projecttocreate->entity = $conf->entity;
2134  $projecttocreate->email_msgid = $msgid;
2135 
2136  $savesocid = $projecttocreate->socid;
2137 
2138  // Overwrite values with values extracted from source email.
2139  // This may overwrite any $projecttocreate->xxx properties.
2140  $errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject, $header);
2141 
2142  // Set project ref if not yet defined
2143  if (empty($projecttocreate->ref)) {
2144  // Get next Ref
2145  $defaultref = '';
2146  $modele = empty($conf->global->PROJECT_ADDON) ? 'mod_project_simple' : $conf->global->PROJECT_ADDON;
2147 
2148  // Search template files
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)) {
2154  $filefound = 1;
2155  $classname = $modele;
2156  break;
2157  }
2158  }
2159 
2160  if ($filefound) {
2161  if ($savesocid > 0) {
2162  if ($savesocid != $projecttocreate->socid) {
2163  $errorforactions++;
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');
2165  }
2166  } else {
2167  if ($projecttocreate->socid > 0) {
2168  $thirdpartystatic->fetch($projecttocreate->socid);
2169  }
2170  }
2171 
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);
2175  }
2176  $projecttocreate->ref = $defaultref;
2177  }
2178 
2179  if ($errorforthisaction) {
2180  $errorforactions++;
2181  } else {
2182  if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
2183  $errorforactions++;
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;
2185  } else {
2186  // Create project
2187  $result = $projecttocreate->create($user);
2188  if ($result <= 0) {
2189  $errorforactions++;
2190  $this->error = 'Failed to create project: '.$langs->trans($projecttocreate->error);
2191  $this->errors = $projecttocreate->errors;
2192  }
2193  }
2194  }
2195  }
2196  } elseif ($operation['type'] == 'ticket') {
2197  // Create ticket
2198  $tickettocreate = new Ticket($this->db);
2199 
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);
2207  }
2208  }
2209  if ($contactstatic->id > 0) {
2210  $tickettocreate->contact_id = $contactstatic->id;
2211  if ($contactfoundby) {
2212  $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
2213  }
2214  }
2215 
2216  $description = $descriptiontitle;
2217  $description = dol_concatdesc($description, "-----");
2218  $description = dol_concatdesc($description, $descriptionmeta);
2219  $description = dol_concatdesc($description, "-----");
2220  $description = dol_concatdesc($description, $messagetext);
2221 
2222  $descriptionfull = $description;
2223  if (empty($conf->global->MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER)) {
2224  $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
2225  $descriptionfull = dol_concatdesc($descriptionfull, $header);
2226  }
2227 
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;
2241  //$tickettocreate->fk_contact = $contactstatic->id;
2242 
2243  $savesocid = $tickettocreate->socid;
2244 
2245  // Overwrite values with values extracted from source email.
2246  // This may overwrite any $projecttocreate->xxx properties.
2247  $errorforthisaction = $this->overwritePropertiesOfObject($tickettocreate, $operation['actionparam'], $messagetext, $subject, $header);
2248 
2249  // Set ticket ref if not yet defined
2250  if (empty($tickettocreate->ref)) {
2251  // Get next Ref
2252  $defaultref = '';
2253  $modele = empty($conf->global->TICKET_ADDON) ? 'mod_ticket_simple' : $conf->global->TICKET_ADDON;
2254 
2255  // Search template files
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)) {
2261  $filefound = 1;
2262  $classname = $modele;
2263  break;
2264  }
2265  }
2266 
2267  if ($filefound) {
2268  if ($savesocid > 0) {
2269  if ($savesocid != $tickettocreate->socid) {
2270  $errorforactions++;
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');
2272  }
2273  } else {
2274  if ($tickettocreate->socid > 0) {
2275  $thirdpartystatic->fetch($tickettocreate->socid);
2276  }
2277  }
2278 
2279  $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
2280  $modModuleToUseForNextValue = new $classname;
2281  $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
2282  }
2283  $tickettocreate->ref = $defaultref;
2284  }
2285 
2286  if ($errorforthisaction) {
2287  $errorforactions++;
2288  } else {
2289  if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
2290  $errorforactions++;
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;
2292  } else {
2293  // Create project
2294  $result = $tickettocreate->create($user);
2295  if ($result <= 0) {
2296  $errorforactions++;
2297  $this->error = 'Failed to create ticket: '.$langs->trans($tickettocreate->error);
2298  $this->errors = $tickettocreate->errors;
2299  } else {
2300  if ($attachments) {
2301  $destdir = $conf->ticket->dir_output.'/'.$tickettocreate->ref;
2302  if (!dol_is_dir($destdir)) {
2303  dol_mkdir($destdir);
2304  $this->getmsg($connection, $imapemail, $destdir);
2305  }
2306  }
2307  }
2308  }
2309  }
2310  }
2311  } elseif ($operation['type'] == 'candidature') {
2312  // Create candidature
2313  $candidaturetocreate = new RecruitmentCandidature($this->db);
2314 
2315  $alreadycreated = $candidaturetocreate->fetch(0, '', $msgid);
2316  if ($alreadycreated == 0) {
2317  $description = $descriptiontitle;
2318  $description = dol_concatdesc($description, "-----");
2319  $description = dol_concatdesc($description, $descriptionmeta);
2320  $description = dol_concatdesc($description, "-----");
2321  $description = dol_concatdesc($description, $messagetext);
2322 
2323  $descriptionfull = $description;
2324  $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
2325  $descriptionfull = dol_concatdesc($descriptionfull, $header);
2326 
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;
2333  //$candidaturetocreate->lastname = $langs->trans("Anonymous").' - '.$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;
2342  //$candidaturetocreate->fk_contact = $contactstatic->id;
2343 
2344  // Overwrite values with values extracted from source email.
2345  // This may overwrite any $projecttocreate->xxx properties.
2346  $errorforthisaction = $this->overwritePropertiesOfObject($candidaturetocreate, $operation['actionparam'], $messagetext, $subject, $header);
2347 
2348  // Set candidature ref if not yet defined
2349  /*if (empty($candidaturetocreate->ref)) We do not need this because we create object in draft status
2350  {
2351  // Get next Ref
2352  $defaultref = '';
2353  $modele = empty($conf->global->CANDIDATURE_ADDON) ? 'mod_candidature_simple' : $conf->global->CANDIDATURE_ADDON;
2354 
2355  // Search template files
2356  $file = ''; $classname = ''; $filefound = 0; $reldir = '';
2357  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
2358  foreach ($dirmodels as $reldir)
2359  {
2360  $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
2361  if (file_exists($file)) {
2362  $filefound = 1;
2363  $classname = $modele;
2364  break;
2365  }
2366  }
2367 
2368  if ($filefound) {
2369  if ($savesocid > 0) {
2370  if ($savesocid != $candidaturetocreate->socid) {
2371  $errorforactions++;
2372  setEventMessages('You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$candidaturetocreate->socid.') by setting socid in operation with a different value', null, 'errors');
2373  }
2374  } else {
2375  if ($candidaturetocreate->socid > 0)
2376  {
2377  $thirdpartystatic->fetch($candidaturetocreate->socid);
2378  }
2379  }
2380 
2381  $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
2382  $modModuleToUseForNextValue = new $classname;
2383  $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
2384  }
2385  $candidaturetocreate->ref = $defaultref;
2386  }*/
2387 
2388  if ($errorforthisaction) {
2389  $errorforactions++;
2390  } else {
2391  // Create project
2392  $result = $candidaturetocreate->create($user);
2393  if ($result <= 0) {
2394  $errorforactions++;
2395  $this->error = 'Failed to create ticket: '.join(', ', $candidaturetocreate->errors);
2396  $this->errors = $candidaturetocreate->errors;
2397  }
2398  }
2399  }
2400  } elseif (substr($operation['type'], 0, 4) == 'hook') {
2401  // Create event specific on hook
2402  // this code action is hook..... for support this call
2403  if (!is_object($hookmanager)) {
2404  include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
2405  $hookmanager = new HookManager($this->db);
2406  }
2407 
2408  $parameters = array(
2409  'connection'=> $connection,
2410  'imapemail'=>$imapemail,
2411  'overview'=>$overview,
2412 
2413  'from' => $from,
2414  'fromtext' => $fromtext,
2415 
2416  'actionparam'=> $operation['actionparam'],
2417 
2418  'thirdpartyid' => $thirdpartyid,
2419  'objectid'=> $objectid,
2420  'objectemail'=> $objectemail,
2421 
2422  'messagetext'=>$messagetext,
2423  'subject'=>$subject,
2424  'header'=>$header,
2425  'attachments'=>$attachments,
2426  );
2427  $reshook = $hookmanager->executeHooks('doCollectOneCollector', $parameters, $this, $operation['type']);
2428 
2429  if ($reshook < 0) {
2430  $errorforthisaction++;
2431  $this->error = $hookmanager->resPrint;
2432  }
2433  if ($errorforthisaction) {
2434  $errorforactions++;
2435  }
2436  }
2437 
2438  if (!$errorforactions) {
2439  $nbactiondoneforemail++;
2440  }
2441  }
2442 
2443  // Error for email or not ?
2444  if (!$errorforactions) {
2445  if ($targetdir) {
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) {
2449  $errorforemail++;
2450  $this->error = imap_last_error();
2451  $this->errors[] = $this->error;
2452  dol_syslog(imap_last_error());
2453  }
2454  } else {
2455  dol_syslog("EmailCollector::doCollectOneCollector message ".$imapemail." to ".$connectstringtarget." was set to read", LOG_DEBUG);
2456  }
2457  } else {
2458  $errorforemail++;
2459  }
2460 
2461  unset($objectemail);
2462  unset($projectstatic);
2463  unset($thirdpartystatic);
2464  unset($contactstatic);
2465 
2466  $nbemailprocessed++;
2467 
2468  if (!$errorforemail) {
2469  $nbactiondone += $nbactiondoneforemail;
2470  $nbemailok++;
2471 
2472  $this->db->commit();
2473 
2474  // Stop the loop to process email if we reach maximum collected per collect
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.");
2477  break;
2478  }
2479  } else {
2480  $error++;
2481 
2482  $this->db->rollback();
2483  }
2484  }
2485 
2486  $output = $langs->trans('XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
2487 
2488  dol_syslog("End of loop on emails", LOG_INFO, -1);
2489  } else {
2490  $output = $langs->trans('NoNewEmailToProcess');
2491  }
2492 
2493  imap_expunge($connection); // To validate any move
2494 
2495  imap_close($connection);
2496 
2497  $this->datelastresult = $now;
2498  $this->lastresult = $output;
2499  $this->debuginfo = 'IMAP search string used : '.$search;
2500  if ($searchhead) {
2501  $this->debuginfo .= '<br>Then search string into email header : '.$searchhead;
2502  }
2503 
2504  if (!$error) {
2505  $this->datelastok = $now;
2506  }
2507 
2508  if (!empty($this->errors)) {
2509  $this->lastresult .= " - ".join(" - ", $this->errors);
2510  }
2511  $this->codelastresult = ($error ? 'KO' : 'OK');
2512  $this->update($user);
2513 
2514  dol_syslog("EmailCollector::doCollectOneCollector end", LOG_DEBUG);
2515 
2516  return $error ?-1 : 1;
2517  }
2518 
2519 
2520 
2521  // Loop to get part html and plain. Code found on PHP imap_fetchstructure documentation
2522 
2531  private function getmsg($mbox, $mid, $destdir = '')
2532  {
2533  // input $mbox = IMAP stream, $mid = message id
2534  // output all the following:
2535  global $charset, $htmlmsg, $plainmsg, $attachments;
2536  $htmlmsg = $plainmsg = $charset = '';
2537  $attachments = array();
2538 
2539  // HEADER
2540  //$h = imap_header($mbox,$mid);
2541  // add code here to get date, from, to, cc, subject...
2542 
2543  // BODY
2544  $s = imap_fetchstructure($mbox, $mid);
2545 
2546  if (!$s->parts) {
2547  // simple
2548  $this->getpart($mbox, $mid, $s, 0); // pass 0 as part-number
2549  } else {
2550  // multipart: cycle through each part
2551  foreach ($s->parts as $partno0 => $p) {
2552  $this->getpart($mbox, $mid, $p, $partno0 + 1, $destdir);
2553  }
2554  }
2555  }
2556 
2557  /* partno string
2558  0 multipart/mixed
2559  1 multipart/alternative
2560  1.1 text/plain
2561  1.2 text/html
2562  2 message/rfc822
2563  2 multipart/mixed
2564  2.1 multipart/alternative
2565  2.1.1 text/plain
2566  2.1.2 text/html
2567  2.2 message/rfc822
2568  2.2 multipart/alternative
2569  2.2.1 text/plain
2570  2.2.2 text/html
2571  */
2582  private function getpart($mbox, $mid, $p, $partno, $destdir = '')
2583  {
2584  // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
2585  global $htmlmsg, $plainmsg, $charset, $attachments;
2586 
2587  // DECODE DATA
2588  $data = ($partno) ?
2589  imap_fetchbody($mbox, $mid, $partno) : // multipart
2590  imap_body($mbox, $mid); // simple
2591  // Any part may be encoded, even plain text messages, so check everything.
2592  if ($p->encoding == 4) {
2593  $data = quoted_printable_decode($data);
2594  } elseif ($p->encoding == 3) {
2595  $data = base64_decode($data);
2596  }
2597 
2598  // PARAMETERS
2599  // get all parameters, like charset, filenames of attachments, etc.
2600  $params = array();
2601  if ($p->parameters) {
2602  foreach ($p->parameters as $x) {
2603  $params[strtolower($x->attribute)] = $x->value;
2604  }
2605  }
2606  if ($p->dparameters) {
2607  foreach ($p->dparameters as $x) {
2608  $params[strtolower($x->attribute)] = $x->value;
2609  }
2610  }
2611 
2612  // ATTACHMENT
2613  // Any part with a filename is an attachment,
2614  // so an attached text file (type 0) is not mistaken as the message.
2615  if ($params['filename'] || $params['name']) {
2616  // filename may be given as 'Filename' or 'Name' or both
2617  $filename = ($params['filename']) ? $params['filename'] : $params['name'];
2618  // filename may be encoded, so see imap_mime_header_decode()
2619  $attachments[$filename] = $data; // this is a problem if two files have same name
2620 
2621  // Get file name (with extension)
2622  $file_name_complete = $params['filename'];
2623 
2624 
2625  $destination = $destdir.'/'.$file_name_complete;
2626 
2627  // Extract file extension
2628  $extension = pathinfo($file_name_complete, PATHINFO_EXTENSION);
2629 
2630  // Extract file name without extension
2631  $file_name = pathinfo($file_name_complete, PATHINFO_FILENAME);
2632 
2633  // Save an original file name variable to track while renaming if file already exists
2634  $file_name_original = $file_name;
2635 
2636  // Increment file name by 1
2637  $num = 1;
2638 
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;
2647  $num++;
2648  }
2649 
2650 
2651  file_put_contents($destination, $data);
2652  }
2653 
2654  // TEXT
2655  if ($p->type == 0 && $data) {
2656  if (!empty($params['charset'])) {
2657  $data = $this->convertStringEncoding($data, $params['charset']);
2658  }
2659  // Messages may be split in different parts because of inline attachments,
2660  // so append parts together with blank row.
2661  if (strtolower($p->subtype) == 'plain') {
2662  $plainmsg .= trim($data)."\n\n";
2663  } else {
2664  $htmlmsg .= $data."<br><br>";
2665  }
2666  $charset = $params['charset']; // assume all parts are same charset
2667  } elseif ($p->type == 2 && $data) {
2668  // EMBEDDED MESSAGE
2669  // Many bounce notifications embed the original message as type 2,
2670  // but AOL uses type 1 (multipart), which is not handled here.
2671  // There are no PHP functions to parse embedded messages,
2672  // so this just appends the raw source to the main message.
2673  if (!empty($params['charset'])) {
2674  $data = $this->convertStringEncoding($data, $params['charset']);
2675  }
2676  $plainmsg .= $data."\n\n";
2677  }
2678 
2679  // SUBPART RECURSION
2680  if ($p->parts) {
2681  foreach ($p->parts as $partno0 => $p2) {
2682  $this->getpart($mbox, $mid, $p2, $partno.'.'.($partno0 + 1)); // 1.2, 1.2.1, etc.
2683  }
2684  }
2685  }
2686 
2696  protected function convertStringEncoding($string, $fromEncoding, $toEncoding = 'UTF-8')
2697  {
2698  if (!$string || $fromEncoding == $toEncoding) {
2699  return $string;
2700  }
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);
2704  }
2705  if (!$convertedString) {
2706  throw new Exception('Mime string encoding conversion failed');
2707  }
2708  return $convertedString;
2709  }
2710 
2721  protected function decodeSMTPSubject($subject)
2722  {
2723  // Decode $overview[0]->subject according to RFC2047
2724  // Can use also imap_mime_header_decode($str)
2725  // Can use also mb_decode_mimeheader($str)
2726  // Can use also iconv_mime_decode($str, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8')
2727  if (function_exists('imap_mime_header_decode') && function_exists('iconv_mime_decode')) {
2728  $elements = imap_mime_header_decode($subject);
2729  $newstring = '';
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;
2735  }
2736  $subject = $newstring;
2737  }
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');
2742  }
2743 
2744  return $subject;
2745  }
2746 }
make_substitutions
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
Definition: functions.lib.php:7824
CommonObject\deleteCommon
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
Definition: commonobject.class.php:9388
Societe
Class to manage third parties objects (customers, suppliers, prospects...)
Definition: societe.class.php:48
EmailCollector\convertStringEncoding
convertStringEncoding($string, $fromEncoding, $toEncoding='UTF-8')
Converts a string from one encoding to another.
Definition: emailcollector.class.php:2696
db
$conf db
API class for accounts.
Definition: inc.php:41
dol_escape_htmltag
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
Definition: functions.lib.php:1454
CommonObject\fetchCommon
fetchCommon($id, $ref=null, $morewhere='')
Load object in memory from the database.
Definition: commonobject.class.php:9184
Reception
Class to manage receptions.
Definition: reception.class.php:49
EmailCollector\info
info($id)
Charge les informations d'ordre info dans l'objet commande.
Definition: emailcollector.class.php:616
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1212
Expedition
Class to manage shipments.
Definition: expedition.class.php:52
Project
Class to manage projects.
Definition: project.class.php:35
ActionComm
Class to manage agenda events (actions)
Definition: actioncomm.class.php:38
EmailCollector\getConnectStringIMAP
getConnectStringIMAP($ssl=1, $norsh=0)
Return the connectstring to use with IMAP connection function.
Definition: emailcollector.class.php:724
EmailCollector\fetchAll
fetchAll(User $user, $activeOnly=0, $sortfield='s.rowid', $sortorder='ASC', $limit=100, $page=0)
Load object lines in memory from the database.
Definition: emailcollector.class.php:417
EmailCollector\overwritePropertiesOfObject
overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject, $header)
overwitePropertiesOfObject
Definition: emailcollector.class.php:821
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
EmailCollectorAction
Class for EmailCollectorAction.
Definition: emailcollectoraction.class.php:33
FactureFournisseur
Class to manage suppliers invoices.
Definition: fournisseur.facture.class.php:53
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4830
EmailCollector\getpart
getpart($mbox, $mid, $p, $partno, $destdir='')
Sub function for getpart().
Definition: emailcollector.class.php:2582
getAttachments
getAttachments($jk, $mbox)
Get attachments of a given mail.
Definition: emailcollector.lib.php:118
dol_include_once
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
Definition: functions.lib.php:1033
dol_buildpath
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Definition: functions.lib.php:1062
EmailCollector\doCollectOneCollector
doCollectOneCollector()
Execute collect for current collector loaded previously with fetch.
Definition: emailcollector.class.php:950
EmailCollector\fetch
fetch($id, $ref=null)
Load object in memory from the database.
Definition: emailcollector.class.php:383
EmailCollectorFilter
Class for EmailCollectorFilter.
Definition: emailcollectorfilter.class.php:33
Task
Class to manage tasks.
Definition: task.class.php:37
ref
$object ref
Definition: info.php:77
EmailCollector\initAsSpecimen
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
Definition: emailcollector.class.php:646
CommonObject\initAsSpecimenCommon
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
Definition: commonobject.class.php:9715
EmailCollector\fetchFilters
fetchFilters()
Fetch filters.
Definition: emailcollector.class.php:660
Facture
Class to manage invoices.
Definition: facture.class.php:60
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:44
EmailCollector\LibStatut
LibStatut($status, $mode=0)
Return the status.
Definition: emailcollector.class.php:590
EmailCollector\getNomUrl
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionaly the picto)
Definition: emailcollector.class.php:506
EmailCollector\createFromClone
createFromClone(User $user, $fromid)
Clone and object into another one.
Definition: emailcollector.class.php:314
dol_print_date
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
Definition: functions.lib.php:2500
dolExplodeIntoArray
dolExplodeIntoArray($string, $delimiter=';', $kv='=')
Split a string with 2 keys into key array.
Definition: functions.lib.php:9340
dol_concatdesc
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...
Definition: functions.lib.php:7234
CommonObject\createCommon
createCommon(User $user, $notrigger=false)
Create object into database.
Definition: commonobject.class.php:9017
Exception
EmailCollector\getLibStatut
getLibStatut($mode=0)
Return label of the status.
Definition: emailcollector.class.php:577
dol_getIdFromCode
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='')
Return an id or code from a code or id.
Definition: functions.lib.php:8521
EmailCollector\doCollect
doCollect()
Action executed by scheduler CAN BE A CRON TASK.
Definition: emailcollector.class.php:788
Commande
Class to manage customers orders.
Definition: commande.class.php:46
EmailCollector\getmsg
getmsg($mbox, $mid, $destdir='')
getmsg
Definition: emailcollector.class.php:2531
getFileData
getFileData($jk, $fpos, $type, $mbox)
Get content of a joined file from its position into a given email.
Definition: emailcollector.lib.php:154
RecruitmentCandidature
Class for RecruitmentCandidature.
Definition: recruitmentcandidature.class.php:32
dol_string_nohtmltag
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
Definition: functions.lib.php:6680
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1589
Contact
Class to manage contact/addresses.
Definition: contact.class.php:40
EmailCollector\__construct
__construct(DoliDB $db)
Constructor.
Definition: emailcollector.class.php:227
EmailCollector\decodeSMTPSubject
decodeSMTPSubject($subject)
Decode a subject string according to RFC2047 Example: '=?Windows-1252?Q?RE=A0:_ABC?...
Definition: emailcollector.class.php:2721
Adherent
Class to manage members of a foundation.
Definition: adherent.class.php:46
CommonObject\updateCommon
updateCommon(User $user, $notrigger=false)
Update object into database.
Definition: commonobject.class.php:9290
getDolGlobalString
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:80
CommandeFournisseur
Class to manage predefined suppliers products.
Definition: fournisseur.commande.class.php:47
User
Class to manage Dolibarr users.
Definition: user.class.php:44
EmailCollector
Class for EmailCollector.
Definition: emailcollector.class.php:49
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10324
EmailCollector\update
update(User $user, $notrigger=false)
Update object into database.
Definition: emailcollector.class.php:470
saveAttachment
saveAttachment($path, $filename, $data)
Save joined file into a directory with a given name.
Definition: emailcollector.lib.php:170
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4197
EmailCollector\create
create(User $user, $notrigger=false)
Create object into database.
Definition: emailcollector.class.php:264
EmailCollector\fetchActions
fetchActions()
Fetch actions.
Definition: emailcollector.class.php:692
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2831
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
EmailCollector\getEncodedUtf7
getEncodedUtf7($str)
Convert str to UTF-7 imap default mailbox names.
Definition: emailcollector.class.php:760
Ticket
Class to generate the form for creating a new ticket.
Definition: html.formticket.class.php:31
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8123
dol_is_dir
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:447
dolGetFirstLineOfText
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
Definition: functions.lib.php:6893
Propal
Class to manage proposals.
Definition: propal.class.php:52
dol_mkdir
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
Definition: functions.lib.php:6589
SupplierProposal
Class to manage price ask supplier.
Definition: supplier_proposal.class.php:50
HookManager
Class to manage hooks.
Definition: hookmanager.class.php:30