dolibarr 25.0.0-alpha
emailcollector.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2026 Vincent de Grandpré <vincent@de-grandpre.quebec>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
27// Put here all includes required by your class file
28include_once DOL_DOCUMENT_ROOT .'/emailcollector/lib/emailcollector.lib.php';
29
30require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
31require_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
32require_once DOL_DOCUMENT_ROOT .'/core/lib/functions2.lib.php';
33
34require_once DOL_DOCUMENT_ROOT .'/comm/propal/class/propal.class.php'; // Customer Proposal
35require_once DOL_DOCUMENT_ROOT .'/commande/class/commande.class.php'; // Sale Order
36require_once DOL_DOCUMENT_ROOT .'/compta/facture/class/facture.class.php'; // Customer Invoice
37require_once DOL_DOCUMENT_ROOT .'/contact/class/contact.class.php'; // Contact / Address
38require_once DOL_DOCUMENT_ROOT .'/expedition/class/expedition.class.php'; // Shipping / Delivery
39require_once DOL_DOCUMENT_ROOT .'/fourn/class/fournisseur.commande.class.php'; // Purchase Order
40require_once DOL_DOCUMENT_ROOT .'/fourn/class/fournisseur.facture.class.php'; // Purchase Invoice
41require_once DOL_DOCUMENT_ROOT .'/projet/class/project.class.php'; // Project
42require_once DOL_DOCUMENT_ROOT .'/reception/class/reception.class.php'; // Reception
43require_once DOL_DOCUMENT_ROOT .'/recruitment/class/recruitmentcandidature.class.php'; // Recruiting
44require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php'; // Third-Party
45require_once DOL_DOCUMENT_ROOT .'/supplier_proposal/class/supplier_proposal.class.php'; // Supplier Proposal
46require_once DOL_DOCUMENT_ROOT .'/ticket/class/ticket.class.php'; // Ticket
47require_once DOL_DOCUMENT_ROOT .'/adherents/class/adherent.class.php'; // Member/Adherent
48//require_once DOL_DOCUMENT_ROOT .'/expensereport/class/expensereport.class.php'; // Expense Report
49//require_once DOL_DOCUMENT_ROOT .'/holiday/class/holiday.class.php'; // Holidays (leave request)
50
51
52use Webklex\PHPIMAP\ClientManager;
53use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
54use Webklex\PHPIMAP\Exceptions\InvalidWhereQueryCriteriaException;
55use OAuth\Common\Storage\DoliStorage;
56use OAuth\Common\Consumer\Credentials;
57
62{
66 public $element = 'emailcollector';
67
71 public $table_element = 'emailcollector_emailcollector';
72
76 public $picto = 'email';
77
81 public $fk_element = 'fk_emailcollector';
82
86 protected $childtables = array();
87
91 protected $childtablesoncascade = array('emailcollector_emailcollectorfilter', 'emailcollector_emailcollectoraction');
92
93
113 // BEGIN MODULEBUILDER PROPERTIES
117 public $fields = array(
118 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'visible' => -2, 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'index' => 1),
119 'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'default' => '1', 'notnull' => 1, 'index' => 1, 'position' => 20),
120 'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'showoncombobox' => 1, 'index' => 1, 'position' => 10, 'searchall' => 1, 'help' => 'Example: MyCollector1', 'csslist' => 'tdoverflowmax200'),
121 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'visible' => 1, 'enabled' => 1, 'position' => 30, 'notnull' => -1, 'searchall' => 1, 'help' => 'Example: My Email collector', 'csslist' => 'tdoverflowmax150 small', 'tdcss' => 'titlefieldmiddle'),
122 'description' => array('type' => 'text', 'label' => 'Description', 'visible' => -1, 'enabled' => 1, 'position' => 60, 'notnull' => -1, 'cssview' => 'small', 'csslist' => 'small tdoverflowmax200'),
123 'host' => array('type' => 'varchar(255)', 'label' => 'EMailHost', 'visible' => 1, 'enabled' => 1, 'position' => 90, 'notnull' => 1, 'searchall' => 1, 'comment' => "IMAP server", 'help' => 'Example: imap.gmail.com', 'csslist' => 'tdoverflowmax125'),
124 'port' => array('type' => 'varchar(10)', 'label' => 'EMailHostPort', 'visible' => 1, 'enabled' => 1, 'position' => 91, 'notnull' => 1, 'searchall' => 0, 'comment' => "IMAP server port", 'help' => 'Example: 993', 'csslist' => 'tdoverflowmax50', 'default' => '993'),
125 'imap_encryption' => array('type' => 'varchar(16)', 'label' => 'ImapEncryption', 'visible' => -1, 'enabled' => 1, 'position' => 92, 'searchall' => 0, 'comment' => "IMAP encryption", 'help' => 'ImapEncryptionHelp', 'arrayofkeyval' => array('ssl' => 'SSL', 'tls' => 'TLS', 'notls' => 'NOTLS'), 'default' => 'ssl'),
126 'hostcharset' => array('type' => 'varchar(16)', 'label' => 'HostCharset', 'visible' => -1, 'enabled' => 1, 'position' => 93, 'notnull' => 0, 'searchall' => 0, 'comment' => "IMAP server charset", 'help' => 'Example: "UTF-8" (May be "US-ASCII" with some Office365)', 'default' => 'UTF-8'),
127 'norsh' => array('type' => 'integer', 'label' => 'NoRSH', 'visible' => -1, 'enabled' => "!getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')", 'position' => 94, 'searchall' => 0, 'help' => 'NoRSHHelp', 'arrayofkeyval' => array(0 => 'No', 1 => 'Yes'), 'default' => '0'),
128 'acces_type' => array('type' => 'integer', 'label' => 'AuthenticationMethod', 'visible' => -1, 'enabled' => "getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')", 'position' => 101, 'notnull' => 1, 'index' => 1, 'comment' => "IMAP login type", 'arrayofkeyval' => array(0 => 'loginPassword', 1 => 'oauthToken'), 'default' => '0', 'help' => ''),
129 'login' => array('type' => 'varchar(128)', 'label' => 'Login', 'visible' => -1, 'enabled' => 1, 'position' => 102, 'notnull' => -1, 'index' => 1, 'comment' => "IMAP login", 'help' => 'Example: myaccount@gmail.com'),
130 'password' => array('type' => 'password', 'label' => 'Password', 'visible' => -1, 'enabled' => "1", 'position' => 103, 'notnull' => -1, 'comment' => "IMAP password", 'help' => 'WithGMailYouCanCreateADedicatedPassword'),
131 'oauth_service' => array('type' => 'varchar(128)', 'label' => 'oauthService', 'visible' => -1, 'enabled' => "getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')", 'position' => 104, 'notnull' => 0, 'index' => 1, 'comment' => "IMAP login oauthService", 'arrayofkeyval' => array(), 'help' => 'TokenMustHaveBeenCreated'),
132 'source_directory' => array('type' => 'varchar(255)', 'label' => 'MailboxSourceDirectory', 'visible' => -1, 'enabled' => 1, 'position' => 109, 'notnull' => 1, 'default' => 'Inbox', 'csslist' => 'tdoverflowmax100', 'help' => 'Example: INBOX, [Gmail]/Spam, [Gmail]/Draft, [Gmail]/Brouillons, [Gmail]/Sent Mail, [Gmail]/Messages envoyés, ...'),
133 'target_directory' => array('type' => 'varchar(255)', 'label' => 'MailboxTargetDirectory', 'visible' => 1, 'enabled' => 1, 'position' => 110, 'notnull' => 0, 'csslist' => 'tdoverflowmax100', 'help' => "EmailCollectorTargetDir"),
134 'maxemailpercollect' => array('type' => 'integer', 'label' => 'MaxEmailCollectPerCollect', 'visible' => -1, 'enabled' => 1, 'position' => 111, 'default' => '50'),
135 'datelastresult' => array('type' => 'datetime', 'label' => 'DateLastCollectResult', 'visible' => 1, 'enabled' => '$action != "create" && $action != "edit"', 'position' => 121, 'notnull' => -1, 'csslist' => 'nowraponall'),
136 'codelastresult' => array('type' => 'varchar(16)', 'label' => 'CodeLastResult', 'visible' => 1, 'enabled' => '$action != "create" && $action != "edit"', 'position' => 122, 'notnull' => -1,),
137 'lastresult' => array('type' => 'varchar(255)', 'label' => 'LastResult', 'visible' => 1, 'enabled' => '$action != "create" && $action != "edit"', 'position' => 123, 'notnull' => -1, 'cssview' => 'small', 'csslist' => 'maxwidth250imp'),
138 'datelastok' => array('type' => 'datetime', 'label' => 'DateLastcollectResultOk', 'visible' => 1, 'enabled' => '$action != "create"', 'position' => 125, 'notnull' => -1, 'csslist' => 'nowraponall'),
139 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'visible' => 0, 'enabled' => 1, 'position' => 61, 'notnull' => -1,),
140 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'visible' => 0, 'enabled' => 1, 'position' => 62, 'notnull' => -1,),
141 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'visible' => -2, 'enabled' => 1, 'position' => 500, 'notnull' => 1,),
142 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'visible' => -2, 'enabled' => 1, 'position' => 501, 'notnull' => 1,),
143 //'date_validation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
144 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'visible' => -2, 'enabled' => 1, 'position' => 510, 'notnull' => 1,),
145 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'visible' => -2, 'enabled' => 1, 'position' => 511, 'notnull' => -1,),
146 //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
147 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'visible' => -2, 'enabled' => 1, 'position' => 1000, 'notnull' => -1,),
148 'status' => array('type' => 'integer', 'label' => 'Status', 'visible' => 1, 'enabled' => 1, 'position' => 1000, 'notnull' => 1, 'default' => '0', 'index' => 1, 'arrayofkeyval' => array(0 => 'Inactive', 1 => 'Active'))
149 );
150
151
155 public $rowid;
156
160 public $ref;
161
165 public $label;
166
170 public $description;
171
175 public $status;
176
180 public $fk_user_creat;
181
185 public $fk_user_modif;
186
190 public $import_key;
191
195 public $host;
199 public $port;
203 public $hostcharset;
207 public $login;
211 public $password;
215 public $acces_type;
219 public $oauth_service;
223 public $imap_encryption;
227 public $norsh;
231 public $source_directory;
235 public $target_directory;
239 public $maxemailpercollect;
240
244 public $datelastresult;
245
249 public $codelastresult;
253 public $lastresult;
257 public $datelastok;
258 // END MODULEBUILDER PROPERTIES
259
263 public $filters;
267 public $actions;
268
272 public $debuginfo;
273
274 const STATUS_DISABLED = 0;
275 const STATUS_ENABLED = 1;
276
277
283 public function __construct(DoliDB $db)
284 {
285 global $conf, $langs;
286
287 $this->db = $db;
288
289 $this->ismultientitymanaged = 1;
290 $this->isextrafieldmanaged = 0;
291
292 /*if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
293 $this->fields['rowid']['visible'] = 0;
294 }*/
295 if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
296 $this->fields['entity']['enabled'] = 0;
297 }
298
299 // List of oauth services
300 $oauthservices = array();
301
302 foreach ($conf->global as $key => $val) {
303 if (!empty($val) && preg_match('/^OAUTH_.*_ID$/', $key)) {
304 $key = preg_replace('/^OAUTH_/', '', $key);
305 $key = preg_replace('/_ID$/', '', $key);
306 if (preg_match('/^.*-/', $key)) {
307 $name = preg_replace('/^.*-/', '', $key);
308 } else {
309 $name = $langs->trans("NoName");
310 }
311 $provider = preg_replace('/-.*$/', '', $key);
312 $provider = ucfirst(strtolower($provider));
313
314 $oauthservices[$key] = $name." (".$provider.")";
315 }
316 }
317
318 $this->fields['oauth_service']['arrayofkeyval'] = $oauthservices;
319
320 // Unset fields that are disabled
321 foreach ($this->fields as $key => $val) {
322 if (isset($val['enabled']) && empty($val['enabled'])) {
323 unset($this->fields[$key]);
324 }
325 }
326
327 // Translate some data of arrayofkeyval
328 if (is_object($langs)) {
329 foreach ($this->fields as $key => $val) {
330 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
331 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
332 $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
333 }
334 }
335 }
336 }
337 }
338
346 public function create(User $user, $notrigger = 0)
347 {
348 global $langs;
349
350 // Check parameters
351 if ($this->host && preg_match('/^http:/i', trim($this->host))) {
352 $langs->load("errors");
353 $this->error = $langs->trans("ErrorHostMustNotStartWithHttp", $this->host);
354 return -1;
355 }
356
357 include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
358 $this->password = dolEncrypt($this->password);
359
360 $id = $this->createCommon($user, $notrigger);
361
362 $this->password = dolDecrypt($this->password);
363
364 if (is_array($this->filters) && count($this->filters)) {
365 $emailcollectorfilter = new EmailCollectorFilter($this->db);
366
367 foreach ($this->filters as $filter) {
368 $emailcollectorfilter->type = $filter['type'];
369 $emailcollectorfilter->rulevalue = $filter['rulevalue'];
370 $emailcollectorfilter->fk_emailcollector = $this->id;
371 $emailcollectorfilter->status = $filter['status'];
372
373 $emailcollectorfilter->create($user);
374 }
375 }
376
377 if (is_array($this->actions) && count($this->actions)) {
378 $emailcollectoroperation = new EmailCollectorAction($this->db);
379
380 foreach ($this->actions as $operation) {
381 $emailcollectoroperation->type = $operation['type'];
382 $emailcollectoroperation->actionparam = $operation['actionparam'];
383 $emailcollectoroperation->fk_emailcollector = $this->id;
384 $emailcollectoroperation->status = $operation['status'];
385 $emailcollectoroperation->position = $operation['position'];
386
387 $emailcollectoroperation->create($user);
388 }
389 }
390
391 return $id;
392 }
393
401 public function createFromClone(User $user, $fromid)
402 {
403 global $langs, $extrafields;
404 $error = 0;
405
406 dol_syslog(__METHOD__, LOG_DEBUG);
407
408 $object = new self($this->db);
409
410 $this->db->begin();
411
412 // Load source object
413 $object->fetchCommon($fromid);
414
415 $object->fetchFilters(); // Rules
416 $object->fetchActions(); // Operations
417
418 // Reset some properties
419 unset($object->id);
420 unset($object->fk_user_creat);
421 unset($object->import_key);
422 unset($object->password);
423 unset($object->lastresult);
424 unset($object->codelastresult);
425 unset($object->datelastresult);
426 unset($object->datelastok);
427 unset($object->debuginfo);
428
429 // Clear fields
430 $object->ref = "copy_of_".$object->ref;
431 $object->label = $langs->trans("CopyOf")." ".$object->label;
432 if (empty($object->host)) {
433 $object->host = 'imap.example.com';
434 }
435 // Clear extrafields that are unique
436 if (is_array($object->array_options) && count($object->array_options) > 0) {
437 $extrafields->fetch_name_optionals_label($this->table_element);
438 foreach ($object->array_options as $key => $option) {
439 $shortkey = preg_replace('/options_/', '', $key);
440 if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
441 unset($object->array_options[$key]);
442 }
443 }
444 }
445
446 // Create clone
447 $object->context['createfromclone'] = 'createfromclone';
448 $result = $object->create($user);
449 if ($result < 0) {
450 $error++;
452 }
453
454 unset($object->context['createfromclone']);
455
456 // End
457 if (!$error) {
458 $this->db->commit();
459 return $object;
460 } else {
461 $this->db->rollback();
462 return -1;
463 }
464 }
465
473 public function fetch($id, $ref = null)
474 {
475 $result = $this->fetchCommon($id, $ref);
476
477 include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
478 $this->password = dolDecrypt($this->password);
479
480 //if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
481 return $result;
482 }
483
489 /*
490 public function fetchLines()
491 {
492 $this->lines=array();
493
494 // Load lines with object EmailCollectorLine
495
496 return count($this->lines)?1:0;
497 }
498 */
499
511 public function fetchAll(User $user, $activeOnly = 0, $sortfield = 's.rowid', $sortorder = 'ASC', $limit = 100, $page = 0)
512 {
513 $obj_ret = array();
514
515 $sql = "SELECT s.rowid";
516 $sql .= " FROM ".MAIN_DB_PREFIX."emailcollector_emailcollector as s";
517 $sql .= ' WHERE s.entity IN ('.getEntity('emailcollector').')';
518 if ($activeOnly) {
519 $sql .= " AND s.status = 1";
520 }
521 $sql .= $this->db->order($sortfield, $sortorder);
522 if ($limit) {
523 if ($page < 0) {
524 $page = 0;
525 }
526 $offset = $limit * $page;
527
528 $sql .= $this->db->plimit($limit + 1, $offset);
529 }
530
531 $result = $this->db->query($sql);
532 if ($result) {
533 $num = $this->db->num_rows($result);
534 $i = 0;
535 while ($i < $num) {
536 $obj = $this->db->fetch_object($result);
537 $emailcollector_static = new EmailCollector($this->db);
538 if ($emailcollector_static->fetch($obj->rowid)) {
539 $obj_ret[] = $emailcollector_static;
540 }
541 $i++;
542 }
543 } else {
544 $this->errors[] = 'EmailCollector::fetchAll Error when retrieve emailcollector list';
545 dol_syslog('EmailCollector::fetchAll Error when retrieve emailcollector list', LOG_ERR);
546 }
547 if (!count($obj_ret)) {
548 dol_syslog('EmailCollector::fetchAll No emailcollector found', LOG_DEBUG);
549 }
550
551 return $obj_ret;
552 }
553
561 public function update(User $user, $notrigger = 0)
562 {
563 global $langs;
564
565 // Check parameters
566 if ($this->host && preg_match('/^http:/i', trim($this->host))) {
567 $langs->load("errors");
568 $this->error = $langs->trans("ErrorHostMustNotStartWithHttp", $this->host);
569 return -1;
570 }
571
572 include_once DOL_DOCUMENT_ROOT.'/core/lib/security.lib.php';
573 $this->password = dolEncrypt($this->password);
574
575 $result = $this->updateCommon($user, $notrigger);
576
577 $this->password = dolDecrypt($this->password);
578
579 return $result;
580 }
581
589 public function delete(User $user, $notrigger = 0)
590 {
591 return $this->deleteCommon($user, $notrigger, 1);
592 }
593
604 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
605 {
606 global $conf, $langs, $action, $hookmanager;
607
608 if (!empty($conf->dol_no_mouse_hover)) {
609 $notooltip = 1; // Force disable tooltips
610 }
611
612 $result = '';
613
614 $label = '<u>'.$langs->trans("EmailCollector").'</u>';
615 $label .= '<br>';
616 $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
617
618 $url = DOL_URL_ROOT.'/admin/emailcollector_card.php?id='.$this->id;
619
620 if ($option != 'nolink') {
621 // Add param to save lastsearch_values or not
622 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
623 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
624 $add_save_lastsearch_values = 1;
625 }
626 if ($add_save_lastsearch_values) {
627 $url .= '&save_lastsearch_values=1';
628 }
629 }
630
631 $linkclose = '';
632 if (empty($notooltip)) {
633 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
634 $label = $langs->trans("ShowEmailCollector");
635 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
636 }
637 $linkclose .= ' title="'.dolPrintHTMLForAttribute($label).'"';
638 $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
639 } else {
640 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
641 }
642
643 $linkstart = '<a href="'.$url.'"';
644 $linkstart .= $linkclose.'>';
645 $linkend = '</a>';
646
647 $result .= $linkstart;
648 if ($withpicto) {
649 $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);
650 }
651 if ($withpicto != 2) {
652 $result .= $this->ref;
653 }
654 $result .= $linkend;
655 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
656
657 $hookmanager->initHooks(array('emailcollectordao'));
658 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
659 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
660 if ($reshook > 0) {
661 $result = $hookmanager->resPrint;
662 } else {
663 $result .= $hookmanager->resPrint;
664 }
665
666 return $result;
667 }
668
675 public function getLibStatut($mode = 0)
676 {
677 return $this->LibStatut($this->status, $mode);
678 }
679
680 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
688 public function LibStatut($status, $mode = 0)
689 {
690 // phpcs:enable
691 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
692 global $langs;
693 //$langs->load("mymodule");
694 $this->labelStatus[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
695 $this->labelStatus[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
696 $this->labelStatusShort[self::STATUS_ENABLED] = $langs->transnoentitiesnoconv('Enabled');
697 $this->labelStatusShort[self::STATUS_DISABLED] = $langs->transnoentitiesnoconv('Disabled');
698 }
699
700 $statusType = 'status5';
701 if ($status == self::STATUS_ENABLED) {
702 $statusType = 'status4';
703 }
704
705 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
706 }
707
714 public function info($id)
715 {
716 $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
717 $sql .= ' fk_user_creat, fk_user_modif';
718 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
719 $sql .= ' WHERE t.rowid = '.((int) $id);
720 $result = $this->db->query($sql);
721 if ($result) {
722 if ($this->db->num_rows($result)) {
723 $obj = $this->db->fetch_object($result);
724
725 $this->id = $obj->rowid;
726
727 $this->user_creation_id = $obj->fk_user_creat;
728 $this->user_modification_id = $obj->fk_user_modif;
729 $this->date_creation = $this->db->jdate($obj->datec);
730 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
731 }
732
733 $this->db->free($result);
734 } else {
735 dol_print_error($this->db);
736 }
737 }
738
745 public function initAsSpecimen()
746 {
747 $this->host = 'localhost';
748 $this->login = 'alogin';
749
750 return $this->initAsSpecimenCommon();
751 }
752
759 public function fetchFilters()
760 {
761 $this->filters = array();
762
763 $sql = 'SELECT rowid, type, rulevalue, status';
764 $sql .= ' FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectorfilter';
765 $sql .= ' WHERE fk_emailcollector = '.((int) $this->id);
766 //$sql.= ' ORDER BY position';
767
768 $resql = $this->db->query($sql);
769 if ($resql) {
770 $num = $this->db->num_rows($resql);
771 $i = 0;
772 while ($i < $num) {
773 $obj = $this->db->fetch_object($resql);
774 $this->filters[$obj->rowid] = array('id' => $obj->rowid, 'type' => $obj->type, 'rulevalue' => $obj->rulevalue, 'status' => $obj->status);
775 $i++;
776 }
777 $this->db->free($resql);
778 } else {
779 dol_print_error($this->db);
780 }
781
782 return 1;
783 }
784
791 public function fetchActions()
792 {
793 $this->actions = array();
794
795 $sql = 'SELECT rowid, type, actionparam, status';
796 $sql .= ' FROM '.MAIN_DB_PREFIX.'emailcollector_emailcollectoraction';
797 $sql .= ' WHERE fk_emailcollector = '.((int) $this->id);
798 $sql .= ' ORDER BY position';
799
800 $resql = $this->db->query($sql);
801 if ($resql) {
802 $num = $this->db->num_rows($resql);
803 $i = 0;
804 while ($i < $num) {
805 $obj = $this->db->fetch_object($resql);
806 $this->actions[$obj->rowid] = array('id' => $obj->rowid, 'type' => $obj->type, 'actionparam' => $obj->actionparam, 'status' => $obj->status);
807 $i++;
808 }
809 $this->db->free($resql);
810
811 return 1;
812 } else {
813 dol_print_error($this->db);
814
815 return -1;
816 }
817 }
818
819
825 public function getConnectStringIMAP()
826 {
827 // Connect to IMAP
828 $flags = '/service=imap'; // IMAP
829 if (getDolGlobalString('IMAP_FORCE_TLS')) {
830 $flags .= '/tls';
831 } elseif (empty($this->imap_encryption) || ($this->imap_encryption == 'ssl' && getDolGlobalString('IMAP_FORCE_NOSSL'))) {
832 $flags .= '';
833 } else {
834 $flags .= '/' . $this->imap_encryption;
835 }
836
837 $flags .= '/novalidate-cert';
838 //$flags.='/readonly';
839 //$flags.='/debug';
840 if (!empty($this->norsh) || getDolGlobalString('IMAP_FORCE_NORSH')) {
841 $flags .= '/norsh';
842 }
843 //Used in shared mailbox from Office365
844 if (!empty($this->login) && strpos($this->login, '/') != false) {
845 $partofauth = explode('/', $this->login);
846 $flags .= '/authuser='.$partofauth[0].'/user='.$partofauth[1];
847 }
848
849 $connectstringserver = '{'.$this->host.':'.$this->port.$flags.'}';
850
851 return $connectstringserver;
852 }
853
860 public function getEncodedUtf7($str)
861 {
862 if (function_exists('mb_convert_encoding')) {
863 // change spaces by entropy because mb_convert fail with spaces
864 $str = preg_replace("/ /", "xxxSPACExxx", $str); // the replacement string must be valid in utf7 so _ can't be used
865 $str = preg_replace("/_/", "xxxUNDERSCORExxx", $str); // encode underscore to avoid encoding issues with mb_convert
866 $str = preg_replace("/\[Gmail\]/", "xxxGMAILxxx", $str); // the replacement string must be valid in utf7 so _ can't be used
867 // if mb_convert work
868 if ($str = mb_convert_encoding($str, "UTF-7")) {
869 // change characters
870 $str = preg_replace("/\+A/", "&A", $str);
871 $str = preg_replace("/xxxUNDERSCORExxx/", "_", $str);
872 // change to spaces again
873 $str = preg_replace("/xxxSPACExxx/", " ", $str);
874 // change to [Gmail] again
875 $str = preg_replace("/xxxGMAILxxx/", "[Gmail]", $str);
876 return $str;
877 } else {
878 // print error and return false
879 $this->error = "error: is not possible to encode this string '".$str."'";
880 return false;
881 }
882 } else {
883 return $str;
884 }
885 }
886
893 public function doCollect()
894 {
895 global $user;
896
897 $nbErrors = 0;
898
899 $arrayofcollectors = $this->fetchAll($user, 1);
900 // Loop on each collector
901 foreach ($arrayofcollectors as $emailcollector) {
902 $result = $emailcollector->doCollectOneCollector(0);
903
904 dol_syslog("doCollect result = ".$result." for emailcollector->id = ".$emailcollector->id);
905
906 $this->error .= 'EmailCollector ID '.$emailcollector->id.':'.$emailcollector->error.'<br>';
907 if (!empty($emailcollector->errors)) {
908 $this->error .= implode('<br>', $emailcollector->errors);
909 $nbErrors++;
910 }
911 $this->output .= 'EmailCollector ID '.$emailcollector->id.': '.$emailcollector->lastresult.'<br>';
912
913 if ($result < 0) {
914 $nbErrors++;
915 }
916 }
917
918 return $nbErrors;
919 }
920
932 private function overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject, $header, &$operationslog)
933 {
934 global $conf, $langs;
935
936 $errorforthisaction = 0;
937
938 // set output lang
939 $outputlangs = $langs;
940 $newlang = '';
941 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
942 $newlang = GETPOST('lang_id', 'aZ09');
943 }
944 if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
945 $newlang = !empty($object->thirdparty->default_lang) ? $object->thirdparty->default_lang : $newlang;
946 }
947 if (!empty($newlang)) {
948 $outputlangs = new Translate('', $conf);
949 $outputlangs->setDefaultLang($newlang);
950 }
951
952 // Overwrite values with values extracted from source email
953 // $this->actionparam = 'opportunity_status=123;abc=EXTRACT:BODY:....'
954 $arrayvaluetouse = dolExplodeIntoArray($actionparam, '(\n\r|\r|\n|;)', '=');
955
956 $tmp = array();
957
958 // Loop on each property set into actionparam
959 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
960 $tmpclass = '';
961 $tmpproperty = '';
962 $tmparray = explode('.', $propertytooverwrite);
963 if (count($tmparray) == 2) {
964 $tmpclass = $tmparray[0];
965 $tmpproperty = $tmparray[1];
966 } else {
967 $tmpproperty = $tmparray[0];
968 }
969 if ($tmpclass && ($tmpclass != $object->element)) {
970 continue; // Property is for another type of object
971 }
972
973 //if (property_exists($object, $tmpproperty) || preg_match('/^options_/', $tmpproperty))
974 if ($tmpproperty) {
975 $sourcestring = '';
976 $sourcefield = '';
977 $regexstring = '';
978 //$transformationstring='';
979 $regforregex = array();
980 if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*):([^:])$/', $valueforproperty, $regforregex)) {
981 $sourcefield = $regforregex[1];
982 $regexstring = $regforregex[2];
983 //$transofrmationstring=$regforregex[3];
984 } elseif (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
985 $sourcefield = $regforregex[1];
986 $regexstring = $regforregex[2];
987 }
988
989 if (!empty($sourcefield) && !empty($regexstring)) {
990 if (strtolower($sourcefield) == 'body') {
991 $sourcestring = $messagetext;
992 } elseif (strtolower($sourcefield) == 'subject') {
993 $sourcestring = $subject;
994 } elseif (strtolower($sourcefield) == 'header') {
995 $sourcestring = $header;
996 }
997
998 if ($sourcestring) {
999 $regforval = array();
1000 $regexoptions = '';
1001 if (strtolower($sourcefield) == 'body') {
1002 $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
1003 }
1004 if (strtolower($sourcefield) == 'header') {
1005 $regexoptions = 'm'; // The m means ^ and $ char is valid at each new line.
1006 }
1007
1008 if (preg_match('/'.$regexstring.'/'.$regexoptions, $sourcestring, $regforval)) {
1009 // Overwrite param $tmpproperty
1010 $valueextracted = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : '';
1011 $valuetoset = (strtolower($sourcefield) == 'body') ? $valueextracted : $this->decodeSMTPSubject($valueextracted);
1012 if (preg_match('/^options_/', $tmpproperty)) {
1013 $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $valuetoset;
1014 } else {
1015 if (property_exists($object, $tmpproperty)) {
1016 $object->$tmpproperty = $valuetoset;
1017 } else {
1018 $tmp[$tmpproperty] = $valuetoset;
1019 }
1020 }
1021
1022 if (preg_match('/^options_/', $tmpproperty)) {
1023 $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/'.dol_escape_htmltag($regexoptions).' into '.strtolower($sourcefield).' -> extract '.dol_escape_htmltag(dol_trunc($object->array_options[preg_replace('/^options_/', '', $tmpproperty)], 128)).' so object extrafield '.dol_escape_htmltag($tmpproperty).' is set.';
1024 } else {
1025 if (property_exists($object, $tmpproperty)) {
1026 $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/'.dol_escape_htmltag($regexoptions).' into '.strtolower($sourcefield).' -> extract '.dol_escape_htmltag(dol_trunc($object->$tmpproperty, 128)).' so object property '.dol_escape_htmltag($tmpproperty).' is set.';
1027 } else {
1028 $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/'.dol_escape_htmltag($regexoptions).' into '.strtolower($sourcefield).' -> extract '.dol_escape_htmltag(dol_trunc($tmp[$tmpproperty], 128)).' so var '.dol_escape_htmltag($tmpproperty).' is set.';
1029 }
1030 }
1031 } else {
1032 // Regex not found
1033 if (property_exists($object, $tmpproperty)) {
1034 $object->$tmpproperty = null;
1035 $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/'.dol_escape_htmltag($regexoptions).' into '.strtolower($sourcefield).' -> not found, so object property '.dol_escape_htmltag($tmpproperty).' is set to null.';
1036 } else {
1037 $tmp[$tmpproperty] = null;
1038 $operationslog .= '<br>Regex /'.dol_escape_htmltag($regexstring).'/'.dol_escape_htmltag($regexoptions).' into '.strtolower($sourcefield).' -> not found, so var '.dol_escape_htmltag($tmpproperty).' is set to null.';
1039 }
1040 }
1041 } else {
1042 // Nothing can be done for this param
1043 $errorforthisaction++;
1044 $this->error = 'The extract rule to use to overwrite properties has on an unknown source (must be HEADER, SUBJECT or BODY)';
1045 $this->errors[] = $this->error;
1046
1047 $operationslog .= '<br>'.$this->error;
1048 }
1049 } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $regforregex)) {
1050 $valuecurrent = '';
1051 if (preg_match('/^options_/', $tmpproperty)) {
1052 $valuecurrent = $object->array_options[preg_replace('/^options_/', '', $tmpproperty)];
1053 } else {
1054 if (property_exists($object, $tmpproperty)) {
1055 $valuecurrent = $object->$tmpproperty;
1056 } else {
1057 // False positive @phan-suppress-next-line PhanTypeInvalidDimOffset
1058 $valuecurrent = $tmp[$tmpproperty];
1059 }
1060 }
1061
1062 if ($regforregex[1] == 'SET' || empty($valuecurrent)) {
1063 $valuetouse = $regforregex[2];
1064 $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
1065 complete_substitutions_array($substitutionarray, $outputlangs, $object);
1066 $matcharray = array();
1067 preg_match_all('/__([a-z0-9]+(?:_[a-z0-9]+)?)__/i', $valuetouse, $matcharray);
1068 if (is_array($matcharray[1])) { // $matcharray[1] is an array with the list of all substitution keys found with the __X__ syntax into the SET entry.
1069 foreach ($matcharray[1] as $keytoreplace) {
1070 if ($keytoreplace) {
1071 if (preg_match('/^options_/', $keytoreplace)) {
1072 $substitutionarray['__'.$keytoreplace.'__'] = $object->array_options[preg_replace('/^options_/', '', $keytoreplace)];
1073 } else {
1074 if (property_exists($object, $keytoreplace)) {
1075 $substitutionarray['__'.$keytoreplace.'__'] = $object->$keytoreplace;
1076 } else {
1077 // False positive @phan-suppress-next-line PhanTypeInvalidDimOffset
1078 $substitutionarray['__'.$keytoreplace.'__'] = $tmp[$keytoreplace];
1079 }
1080 }
1081 }
1082 }
1083 }
1084 // dol_syslog('substitutionarray='.var_export($substitutionarray, true));
1085
1086 $valuetouse = make_substitutions($valuetouse, $substitutionarray);
1087 if (preg_match('/^options_/', $tmpproperty)) {
1088 $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $valuetouse;
1089
1090 $operationslog .= '<br>Set value '.dol_escape_htmltag($valuetouse).' into object->array_options['.dol_escape_htmltag(preg_replace('/^options_/', '', $tmpproperty)).']';
1091 } else {
1092 if (property_exists($object, $tmpproperty)) {
1093 $object->$tmpproperty = $valuetouse;
1094 } else {
1095 $tmp[$tmpproperty] = $valuetouse;
1096 }
1097
1098 $operationslog .= '<br>Set value '.dol_escape_htmltag($valuetouse).' into object->'.dol_escape_htmltag($tmpproperty);
1099 }
1100 }
1101 } else {
1102 $errorforthisaction++;
1103 $this->error = 'Bad syntax for description of action parameters: '.$actionparam;
1104 $this->errors[] = $this->error;
1105 }
1106 }
1107 }
1108
1109 return $errorforthisaction;
1110 }
1111
1118 public function doCollectOneCollector($mode = 0)
1119 {
1120 global $db, $conf, $langs, $user;
1121 global $hookmanager;
1122
1123 //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1124
1125 require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
1126 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
1127 require_once DOL_DOCUMENT_ROOT.'/includes/webklex/php-imap/vendor/autoload.php';
1128 }
1129
1130 dol_syslog("EmailCollector::doCollectOneCollector start for id=".$this->id." - ".$this->ref, LOG_INFO);
1131
1132 $langs->loadLangs(array("project", "companies", "mails", "errors", "ticket", "agenda", "commercial"));
1133
1134 $error = 0;
1135 $this->output = '';
1136 $this->error = '';
1137 $this->debuginfo = '';
1138
1139 $search = '';
1140 $searchhead = '';
1141 $searchfilterdoltrackid = 0;
1142 $searchfilternodoltrackid = 0;
1143 $searchfilterisanswer = 0;
1144 $searchfilterisnotanswer = 0;
1145 $searchfilterreplyto = 0;
1146 $searchfilterexcludebodyarray = array();
1147 $searchfilterexcludesubjectarray = array();
1148 $searchfilterexcludeemailarray = array();
1149 $searchfilterexcludedomainarray = array();
1150 $searchfilterexcludeemailmap = array();
1151 $operationslog = '';
1152 $rulesreplyto = array();
1153 $connectstringsource = '';
1154 $connectstringtarget = '';
1155 $connection = false;
1156 $arrayofemail = array();
1157
1158 $now = dol_now();
1159 $datelastok = $now;
1160
1161 if (empty($this->host)) {
1162 $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('EMailHost'));
1163 return -1;
1164 }
1165 if (empty($this->login)) {
1166 $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Login'));
1167 return -1;
1168 }
1169 if (empty($this->source_directory)) {
1170 $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('MailboxSourceDirectory'));
1171 return -1;
1172 }
1173
1174 $client = null;
1175
1176 $sourcedir = $this->source_directory;
1177 $targetdir = ($this->target_directory ? $this->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag'
1178
1179 $this->fetchFilters();
1180 $this->fetchActions();
1181
1182 $sourcedir = $this->source_directory;
1183 $targetdir = ($this->target_directory ? $this->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag'
1184
1185 // Avoid long blocks on IMAP operations (applies to native IMAP and Webklex/php-imap).
1186 $timeoutconnect = (int) getDolGlobalInt('MAIN_USE_CONNECT_TIMEOUT', 5);
1187 if ($timeoutconnect <= 0) {
1188 $timeoutconnect = 5;
1189 }
1190 $timeoutread = (int) getDolGlobalInt('MAIN_USE_RESPONSE_TIMEOUT', 20);
1191 if ($timeoutread <= 0) {
1192 $timeoutread = 20;
1193 }
1194 if (function_exists('imap_timeout')) {
1195 imap_timeout(IMAP_OPENTIMEOUT, $timeoutconnect); // timeout seems ignored with ssl connect
1196 imap_timeout(IMAP_READTIMEOUT, $timeoutread);
1197 imap_timeout(IMAP_WRITETIMEOUT, 5);
1198 imap_timeout(IMAP_CLOSETIMEOUT, 5);
1199 $this->debuginfo .= 'IMAP timeouts: connect='.$timeoutconnect.'s, read='.$timeoutread.'s<br>';
1200 }
1201
1202 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
1203 if ($this->acces_type == 1) {
1204 // Mode OAUth2 (access_type == 1) with PHP-IMAP
1205 $this->debuginfo .= 'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=1 (OAUTH2)<br>';
1206
1207 require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php';
1208
1209 $supportedoauth2array = getSupportedOauth2Array();
1210
1211 $keyforsupportedoauth2array = $this->oauth_service;
1212 if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
1213 $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
1214 } else {
1215 $keyforprovider = '';
1216 }
1217 $keyforsupportedoauth2array = preg_replace('/-.*$/', '', strtoupper($keyforsupportedoauth2array));
1218 $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
1219
1220 if (!empty($supportedoauth2array)) {
1221 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']));
1222 $nameofservice .= ($keyforprovider ? '-'.$keyforprovider : '');
1223 $OAUTH_SERVICENAME = $nameofservice;
1224 } else {
1225 $OAUTH_SERVICENAME = 'Unknown';
1226 }
1227
1228 $keyforparamtenant = 'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']).($keyforprovider ? '-'.$keyforprovider : '').'_TENANT';
1229
1230 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
1231 //$debugtext = "Host: ".$this->host."<br>Port: ".$this->port."<br>Login: ".$this->login."<br>Password: ".$this->password."<br>access type: ".$this->acces_type."<br>oauth service: ".$this->oauth_service."<br>Max email per collect: ".$this->maxemailpercollect;
1232 //dol_syslog($debugtext);
1233
1234 $token = '';
1235
1236 $storage = new DoliStorage($db, $conf, $keyforprovider, getDolGlobalString($keyforparamtenant));
1237
1238 try {
1239 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1240
1241 $expire = false;
1242 if (is_object($tokenobj) && method_exists($tokenobj, 'getEndOfLife')) {
1243 $endOfLife = $tokenobj->getEndOfLife();
1244 // time() is used internally in token @phan-suppress-next-line DolibarrForbiddenFunctionPlugin
1245 if ($endOfLife !== -9002 && $endOfLife !== -9001 && time() > ($endOfLife - 30)) {
1246 $expire = true;
1247 }
1248 }
1249
1250 // Token expired so we refresh it
1251 if (is_object($tokenobj) && $expire) {
1252 $this->debuginfo .= 'Refresh token '.$OAUTH_SERVICENAME.'<br>';
1253 $credentials = new Credentials(
1254 getDolGlobalString('OAUTH_'.$this->oauth_service.'_ID'),
1255 getDolGlobalString('OAUTH_'.$this->oauth_service.'_SECRET'),
1256 getDolGlobalString('OAUTH_'.$this->oauth_service.'_URLCALLBACK')
1257 );
1258 $serviceFactory = new \OAuth\ServiceFactory();
1259 $oauthname = explode('-', $OAUTH_SERVICENAME);
1260 // ex service is Google-Emails we need only the first part Google
1261
1262 $scopes = array();
1263 if (preg_match('/^Microsoft/', $OAUTH_SERVICENAME)) {
1264 //$extraparams = $tokenobj->getExtraParams();
1265 $tmp = explode('-', $OAUTH_SERVICENAME);
1266 $scopes = explode(',', getDolGlobalString('OAUTH_'.strtoupper($tmp[0]).(empty($tmp[1]) ? '' : '-'.$tmp[1]).'_SCOPE'));
1267 }
1268
1269 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $scopes);
1270
1271 '@phan-var-force OAuth\OAuth2\Service\AbstractService|OAuth\OAuth1\Service\AbstractService $apiService'; // createService is only ServiceInterface
1272
1273 $refreshtoken = $tokenobj->getRefreshToken();
1274 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1275
1276 // We have to save the token because answer give it only once
1277 $tokenobj->setRefreshToken($refreshtoken);
1278 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1279 }
1280 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1281 if (is_object($tokenobj)) {
1282 $token = $tokenobj->getAccessToken();
1283 } else {
1284 $this->error = "Token not found";
1285 return -1;
1286 }
1287 } catch (Exception $e) {
1288 // Return an error if token not found
1289 $this->error = $e->getMessage();
1290 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1291 return -1;
1292 }
1293
1294 $cm = new ClientManager();
1295 $client = $cm->make([
1296 'host' => $this->host,
1297 'port' => $this->port,
1298 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1299 'validate_cert' => true,
1300 'protocol' => 'imap',
1301 'username' => $this->login,
1302 'password' => $token,
1303 'authentication' => "oauth",
1304 ]);
1305 } else {
1306 // Mode LOGIN (login/pass) with PHP-IMAP
1307 $this->debuginfo .= 'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=1, access_type=0 (LOGIN)<br>';
1308
1309 $cm = new ClientManager();
1310 $client = $cm->make([
1311 'host' => $this->host,
1312 'port' => $this->port,
1313 'encryption' => !empty($this->imap_encryption) ? $this->imap_encryption : false,
1314 'validate_cert' => true,
1315 'protocol' => 'imap',
1316 'username' => $this->login,
1317 'password' => $this->password,
1318 'authentication' => "login",
1319 ]);
1320 }
1321
1322 try {
1323 $client->connect();
1324
1325 $connection = true;
1326 } catch (ConnectionFailedException $e) {
1327 $this->error = $e->getMessage();
1328 $this->errors[] = $this->error;
1329 dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1330 return -1;
1331 }
1332
1333 $host = dol_getprefix('email');
1334 } else {
1335 // Use native IMAP functions
1336 $this->debuginfo .= 'doCollectOneCollector is using method MAIN_IMAP_USE_PHPIMAP=0 (native PHP imap, LOGIN)<br>';
1337
1338 if (!function_exists('imap_open')) {
1339 $this->error = 'IMAP function not enabled on your PHP';
1340 return -2;
1341 }
1342
1343 $connectstringserver = $this->getConnectStringIMAP();
1344 if (!getDolGlobalString('MAIL_DISABLE_UTF7_ENCODE_OF_DIR')) {
1345 $connectstringsource = $connectstringserver.$this->getEncodedUtf7($sourcedir);
1346 $connectstringtarget = $connectstringserver.$this->getEncodedUtf7($targetdir);
1347 } else {
1348 $connectstringsource = $connectstringserver.$sourcedir;
1349 $connectstringtarget = $connectstringserver.$targetdir;
1350 }
1351
1352 $this->debuginfo .= 'connectstringsource = '.$connectstringsource.', $connectstringtarget='.$connectstringtarget.'<br>';
1353
1354 $connection = imap_open($connectstringsource, $this->login, $this->password);
1355 if ($connection === false) {
1356 $this->error = 'Failed to open IMAP connection '.$connectstringsource.' '.imap_last_error();
1357 return -3;
1358 }
1359 '@phan-var-force resource|IMAP\Connection $connection';
1360 imap_errors(); // Clear stack of errors.
1361
1362 $host = dol_getprefix('email');
1363 //$host = '123456';
1364
1365 // Define the IMAP search string
1366 // See https://tools.ietf.org/html/rfc3501#section-6.4.4 for IMAPv4 (PHP not yet compatible)
1367 // See https://tools.ietf.org/html/rfc1064 page 13 for IMAPv2
1368 //$search='ALL';
1369 }
1370
1371 $criteria = array();
1372 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
1373 // Use PHPIMAP external library
1374 $criteria = array(array('UNDELETED')); // Seems not supported by some servers
1375 foreach ($this->filters as $rule) {
1376 if (empty($rule['status'])) {
1377 continue;
1378 }
1379
1380 $not = '';
1381 if (strpos($rule['rulevalue'], '!') === 0) {
1382 // The value start with !, so we exclude the criteria
1383 $not = 'NOT ';
1384 // Then remove the ! from the string for next filters
1385 $rule['rulevalue'] = substr($rule['rulevalue'], 1);
1386 }
1387
1388 if ($rule['type'] == 'excludeemail') {
1389 $tmpvalues = preg_split('/[\\r\\n,;]+/', (string) $rule['rulevalue']);
1390 if (is_array($tmpvalues)) {
1391 foreach ($tmpvalues as $tmpvalue) {
1392 $tmpvalue = trim((string) $tmpvalue);
1393 if ($tmpvalue === '') {
1394 continue;
1395 }
1396
1397 if (preg_match_all('/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpvalue, $tmpmatches)) {
1398 foreach ($tmpmatches[0] as $tmpemail) {
1399 $tmpemail = strtolower(trim($tmpemail));
1400 if ($tmpemail !== '') {
1401 $searchfilterexcludeemailarray[] = $tmpemail;
1402 }
1403 }
1404 }
1405 }
1406 }
1407 continue;
1408 }
1409 if ($rule['type'] == 'excludedomain') {
1410 $tmpvalues = preg_split('/[\\r\\n,;]+/', (string) $rule['rulevalue']);
1411 if (is_array($tmpvalues)) {
1412 foreach ($tmpvalues as $tmpvalue) {
1413 $tmpvalue = trim((string) $tmpvalue);
1414 if ($tmpvalue === '') {
1415 continue;
1416 }
1417
1418 if (preg_match_all('/[a-z0-9._%+\\-]+@([a-z0-9.\\-]+\\.[a-z]{2,})/i', $tmpvalue, $tmpmatches)) {
1419 foreach ($tmpmatches[1] as $tmpdomain) {
1420 $tmpdomain = strtolower(trim($tmpdomain));
1421 $tmpdomain = trim($tmpdomain, ". \t\n\r\0\x0B");
1422 if ($tmpdomain !== '') {
1423 $searchfilterexcludedomainarray[] = $tmpdomain;
1424 }
1425 }
1426 continue;
1427 }
1428
1429 $tmpdomain = strtolower($tmpvalue);
1430 $tmpdomain = preg_replace('/^mailto:/i', '', $tmpdomain);
1431 $tmpdomain = trim($tmpdomain);
1432 $tmpdomain = trim($tmpdomain, "<> \t\n\r\0\x0B.,;");
1433 if (strpos($tmpdomain, '@') === 0) {
1434 $tmpdomain = substr($tmpdomain, 1);
1435 }
1436 $posat = strrpos($tmpdomain, '@');
1437 if ($posat !== false) {
1438 $tmpdomain = substr($tmpdomain, $posat + 1);
1439 }
1440 $tmpdomain = trim($tmpdomain, ". \t\n\r\0\x0B");
1441 if ($tmpdomain !== '') {
1442 $searchfilterexcludedomainarray[] = $tmpdomain;
1443 }
1444 }
1445 }
1446 continue;
1447 }
1448
1449 if ($rule['type'] == 'from') {
1450 $tmprulevaluearray = explode('*', $rule['rulevalue']);
1451 if (count($tmprulevaluearray) >= 2) {
1452 foreach ($tmprulevaluearray as $tmprulevalue) {
1453 array_push($criteria, array($not."FROM" => $tmprulevalue));
1454 }
1455 } else {
1456 array_push($criteria, array($not."FROM" => $rule['rulevalue']));
1457 }
1458 }
1459 if ($rule['type'] == 'to') {
1460 $tmprulevaluearray = explode('*', $rule['rulevalue']);
1461 if (count($tmprulevaluearray) >= 2) {
1462 foreach ($tmprulevaluearray as $tmprulevalue) {
1463 array_push($criteria, array($not."TO" => $tmprulevalue));
1464 }
1465 } else {
1466 array_push($criteria, array($not."TO" => $rule['rulevalue']));
1467 }
1468 }
1469 if ($rule['type'] == 'bcc') {
1470 array_push($criteria, array($not."BCC" => $rule['rulevalue']));
1471 }
1472 if ($rule['type'] == 'cc') {
1473 array_push($criteria, array($not."CC" => $rule['rulevalue']));
1474 }
1475 if ($rule['type'] == 'subject') {
1476 if ($not) {
1477 //array_push($criteria, array("NOT SUBJECT" => $rule['rulevalue']));
1478 $searchfilterexcludesubjectarray[] = $rule['rulevalue'];
1479 } else {
1480 array_push($criteria, array("SUBJECT" => $rule['rulevalue']));
1481 }
1482 }
1483 if ($rule['type'] == 'body') {
1484 if ($not) {
1485 //array_push($criteria, array("NOT BODY" => $rule['rulevalue']));
1486 $searchfilterexcludebodyarray[] = $rule['rulevalue'];
1487 } else {
1488 array_push($criteria, array("BODY" => $rule['rulevalue']));
1489 }
1490 }
1491 if ($rule['type'] == 'header') {
1492 array_push($criteria, array($not."HEADER" => $rule['rulevalue']));
1493 }
1494
1495 /* seems not used */
1496 /*
1497 if ($rule['type'] == 'notinsubject') {
1498 array_push($criteria, array($not."SUBJECT NOT" => $rule['rulevalue']));
1499 }
1500 if ($rule['type'] == 'notinbody') {
1501 array_push($criteria, array($not."BODY NOT" => $rule['rulevalue']));
1502 }*/
1503
1504 if ($rule['type'] == 'seen') {
1505 array_push($criteria, array($not."SEEN"));
1506 }
1507 if ($rule['type'] == 'unseen') {
1508 array_push($criteria, array($not."UNSEEN"));
1509 }
1510 if ($rule['type'] == 'unanswered') {
1511 array_push($criteria, array($not."UNANSWERED"));
1512 }
1513 if ($rule['type'] == 'answered') {
1514 array_push($criteria, array($not."ANSWERED"));
1515 }
1516 if ($rule['type'] == 'smaller') {
1517 array_push($criteria, array($not."SMALLER"));
1518 }
1519 if ($rule['type'] == 'larger') {
1520 array_push($criteria, array($not."LARGER"));
1521 }
1522
1523 // Rules to filter after the search imap
1524 if ($rule['type'] == 'withtrackingidinmsgid') {
1525 $searchfilterdoltrackid++;
1526 $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
1527 }
1528 if ($rule['type'] == 'withouttrackingidinmsgid') {
1529 $searchfilterdoltrackid++;
1530 $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
1531 }
1532 if ($rule['type'] == 'withtrackingid') {
1533 $searchfilterdoltrackid++;
1534 $searchhead .= '/References.*@'.preg_quote($host, '/').'/';
1535 }
1536 if ($rule['type'] == 'withouttrackingid') {
1537 $searchfilternodoltrackid++;
1538 $searchhead .= '! /References.*@'.preg_quote($host, '/').'/';
1539 }
1540
1541 if ($rule['type'] == 'isanswer') {
1542 $searchfilterisanswer++;
1543 $searchhead .= '/References.*@.*/';
1544 }
1545 if ($rule['type'] == 'isnotanswer') {
1546 $searchfilterisnotanswer++;
1547 $searchhead .= '! /References.*@.*/';
1548 }
1549
1550 if ($rule['type'] == 'replyto') {
1551 $searchfilterreplyto++;
1552 $rulesreplyto[] = $rule['rulevalue'];
1553 $searchhead .= '/Reply-To.*'.preg_quote($rule['rulevalue'], '/').'/';
1554 }
1555 }
1556
1557 if (empty($targetdir) || !getDolGlobalString('EMAILCOLLECTOR_NO_FILTER_ON_DATE_IF_THERE_IS_A_TARGETDIR')) { // Use the last date of successful check as a filter if there is no targetdir defined.
1558 $fromdate = 0;
1559 if ($this->datelastok) {
1560 $fromdate = $this->datelastok;
1561 }
1562 if ($fromdate > 0) {
1563 // IMAP SINCE works by day; keep a 1-day overlap so we don't miss emails left unprocessed (e.g. discarded by filters).
1564 array_push($criteria, array("SINCE" => date('j-M-Y', $fromdate - 86400)));
1565 }
1566 //$search.=($search?' ':'').'SINCE 8-Apr-2022';
1567 }
1568
1569 dol_syslog("IMAP search string = ".formatLogObject($criteria));
1570 $search = var_export($criteria, true);
1571 } else {
1572 // Use native IMAP functions
1573 $search = 'UNDELETED'; // Seems not supported by some servers
1574 foreach ($this->filters as $rule) {
1575 if (empty($rule['status'])) {
1576 continue;
1577 }
1578
1579 // Forge the IMAP search string.
1580 // See https://www.rfc-editor.org/rfc/rfc3501
1581
1582 $not = '';
1583 if (!empty($rule['rulevalue']) && strpos($rule['rulevalue'], '!') === 0) {
1584 // The value start with !, so we exclude the criteria
1585 $not = 'NOT ';
1586 // Then remove the ! from the string for next filters
1587 $rule['rulevalue'] = substr($rule['rulevalue'], 1);
1588 }
1589
1590 if ($rule['type'] == 'excludeemail') {
1591 $tmpvalues = preg_split('/[\\r\\n,;]+/', (string) $rule['rulevalue']);
1592 if (is_array($tmpvalues)) {
1593 foreach ($tmpvalues as $tmpvalue) {
1594 $tmpvalue = trim((string) $tmpvalue);
1595 if ($tmpvalue === '') {
1596 continue;
1597 }
1598
1599 if (preg_match_all('/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpvalue, $tmpmatches)) {
1600 foreach ($tmpmatches[0] as $tmpemail) {
1601 $tmpemail = strtolower(trim($tmpemail));
1602 if ($tmpemail !== '') {
1603 $searchfilterexcludeemailarray[] = $tmpemail;
1604 }
1605 }
1606 }
1607 }
1608 }
1609 continue;
1610 }
1611 if ($rule['type'] == 'excludedomain') {
1612 $tmpvalues = preg_split('/[\\r\\n,;]+/', (string) $rule['rulevalue']);
1613 if (is_array($tmpvalues)) {
1614 foreach ($tmpvalues as $tmpvalue) {
1615 $tmpvalue = trim((string) $tmpvalue);
1616 if ($tmpvalue === '') {
1617 continue;
1618 }
1619
1620 if (preg_match_all('/[a-z0-9._%+\\-]+@([a-z0-9.\\-]+\\.[a-z]{2,})/i', $tmpvalue, $tmpmatches)) {
1621 foreach ($tmpmatches[1] as $tmpdomain) {
1622 $tmpdomain = strtolower(trim($tmpdomain));
1623 $tmpdomain = trim($tmpdomain, ". \t\n\r\0\x0B");
1624 if ($tmpdomain !== '') {
1625 $searchfilterexcludedomainarray[] = $tmpdomain;
1626 }
1627 }
1628 continue;
1629 }
1630
1631 $tmpdomain = strtolower($tmpvalue);
1632 $tmpdomain = preg_replace('/^mailto:/i', '', $tmpdomain);
1633 $tmpdomain = trim($tmpdomain);
1634 $tmpdomain = trim($tmpdomain, "<> \t\n\r\0\x0B.,;");
1635 if (strpos($tmpdomain, '@') === 0) {
1636 $tmpdomain = substr($tmpdomain, 1);
1637 }
1638 $posat = strrpos($tmpdomain, '@');
1639 if ($posat !== false) {
1640 $tmpdomain = substr($tmpdomain, $posat + 1);
1641 }
1642 $tmpdomain = trim($tmpdomain, ". \t\n\r\0\x0B");
1643 if ($tmpdomain !== '') {
1644 $searchfilterexcludedomainarray[] = $tmpdomain;
1645 }
1646 }
1647 }
1648 continue;
1649 }
1650
1651 if ($rule['type'] == 'from') {
1652 $tmprulevaluearray = explode('*', $rule['rulevalue']); // Search on abc*def means searching on 'abc' and on 'def'
1653 if (count($tmprulevaluearray) >= 2) {
1654 foreach ($tmprulevaluearray as $tmprulevalue) {
1655 $search .= ' '.$not.'FROM "'.str_replace('"', '', $tmprulevalue).'"';
1656 }
1657 } else {
1658 $search .= ' '.$not.'FROM "'.str_replace('"', '', $rule['rulevalue']).'"';
1659 }
1660 }
1661 if ($rule['type'] == 'to') {
1662 $tmprulevaluearray = explode('*', $rule['rulevalue']); // Search on abc*def means searching on 'abc' and on 'def'
1663 if (count($tmprulevaluearray) >= 2) {
1664 foreach ($tmprulevaluearray as $tmprulevalue) {
1665 $search .= ' '.$not.'TO "'.str_replace('"', '', $tmprulevalue).'"';
1666 }
1667 } else {
1668 $search .= ' '.$not.'TO "'.str_replace('"', '', $rule['rulevalue']).'"';
1669 }
1670 }
1671 if ($rule['type'] == 'bcc') {
1672 $search .= ' '.$not.'BCC';
1673 }
1674 if ($rule['type'] == 'cc') {
1675 $search .= ' '.$not.'CC';
1676 }
1677 if ($rule['type'] == 'subject') {
1678 if ($not) {
1679 //$search .= ($search ? ' ' : '').'NOT BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
1680 $searchfilterexcludesubjectarray[] = $rule['rulevalue'];
1681 } else {
1682 $search .= ' SUBJECT "'.str_replace('"', '', $rule['rulevalue']).'"';
1683 }
1684 }
1685 if ($rule['type'] == 'body') {
1686 if ($not) {
1687 //$search .= ($search ? ' ' : '').'NOT BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
1688 $searchfilterexcludebodyarray[] = $rule['rulevalue'];
1689 } else {
1690 // Warning: Google doesn't implement IMAP properly, and only matches whole words,
1691 $search .= ' BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
1692 }
1693 }
1694 if ($rule['type'] == 'header') {
1695 $search .= ' '.$not.'HEADER '.$rule['rulevalue'];
1696 }
1697
1698 /* seems not used */
1699 /*
1700 if ($rule['type'] == 'notinsubject') {
1701 $search .= ($search ? ' ' : '').'NOT SUBJECT "'.str_replace('"', '', $rule['rulevalue']).'"';
1702 }
1703 if ($rule['type'] == 'notinbody') {
1704 $search .= ($search ? ' ' : '').'NOT BODY "'.str_replace('"', '', $rule['rulevalue']).'"';
1705 }*/
1706
1707 if ($rule['type'] == 'seen') {
1708 $search .= ' '.$not.'SEEN';
1709 }
1710 if ($rule['type'] == 'unseen') {
1711 $search .= ' '.$not.'UNSEEN';
1712 }
1713 if ($rule['type'] == 'unanswered') {
1714 $search .= ' '.$not.'UNANSWERED';
1715 }
1716 if ($rule['type'] == 'answered') {
1717 $search .= ' '.$not.'ANSWERED';
1718 }
1719 if ($rule['type'] == 'smaller') {
1720 $search .= ' '.$not.'SMALLER "'.str_replace('"', '', $rule['rulevalue']).'"';
1721 }
1722 if ($rule['type'] == 'larger') {
1723 $search .= ' '.$not.'LARGER "'.str_replace('"', '', $rule['rulevalue']).'"';
1724 }
1725
1726 // Rules to filter after the search imap
1727 if ($rule['type'] == 'withtrackingidinmsgid') {
1728 $searchfilterdoltrackid++;
1729 $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
1730 }
1731 if ($rule['type'] == 'withouttrackingidinmsgid') {
1732 $searchfilterdoltrackid++;
1733 $searchhead .= '/Message-ID.*@'.preg_quote($host, '/').'/';
1734 }
1735 if ($rule['type'] == 'withtrackingid') {
1736 $searchfilterdoltrackid++;
1737 $searchhead .= '/References.*@'.preg_quote($host, '/').'/';
1738 }
1739 if ($rule['type'] == 'withouttrackingid') {
1740 $searchfilternodoltrackid++;
1741 $searchhead .= '! /References.*@'.preg_quote($host, '/').'/';
1742 }
1743
1744 if ($rule['type'] == 'isanswer') {
1745 $searchfilterisanswer++;
1746 $searchhead .= '/References.*@.*/';
1747 }
1748 if ($rule['type'] == 'isnotanswer') {
1749 $searchfilterisnotanswer++;
1750 $searchhead .= '! /References.*@.*/';
1751 }
1752
1753 if ($rule['type'] == 'replyto') {
1754 $searchfilterreplyto++;
1755 $rulesreplyto[] = $rule['rulevalue'];
1756 $searchhead .= '/Reply-To.*'.preg_quote($rule['rulevalue'], '/').'/';
1757 }
1758 }
1759
1760 if (empty($targetdir)) { // Use last date as filter if there is no targetdir defined.
1761 $fromdate = 0;
1762 if ($this->datelastok) {
1763 $fromdate = $this->datelastok;
1764 }
1765 if ($fromdate > 0) {
1766 // IMAP SINCE works by day; keep a 1-day overlap so we don't miss emails left unprocessed (e.g. discarded by filters).
1767 $search .= ' SINCE '.date('j-M-Y', $fromdate - 86400); // SENTSINCE not supported. Date must be X-Abc-9999 (X on 1 digit if < 10)
1768 }
1769 //$search.=($search?' ':'').'SINCE 8-Apr-2018';
1770 }
1771
1772 dol_syslog("IMAP search string = ".$search);
1773 }
1774
1775 if (!empty($searchfilterexcludeemailarray)) {
1776 $searchfilterexcludeemailarray = array_values(array_filter(array_unique($searchfilterexcludeemailarray)));
1777 $searchfilterexcludeemailmap = array_fill_keys($searchfilterexcludeemailarray, true);
1778 }
1779 if (!empty($searchfilterexcludedomainarray)) {
1780 $searchfilterexcludedomainarray = array_values(array_filter(array_unique($searchfilterexcludedomainarray)));
1781 }
1782
1783 $nbemailprocessed = 0;
1784 $nbemailok = 0;
1785 $nbactiondone = 0;
1786 $charset = ($this->hostcharset ? $this->hostcharset : "UTF-8");
1787 $arrayofemail = array();
1788
1789 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP') && is_object($client)) {
1790 $Query = null;
1791
1792 try {
1793 // Uncomment this to output debug info
1794 //$client->getConnection()->enableDebug();
1795
1796 $tmpsourcedir = $sourcedir;
1797 if (!getDolGlobalString('MAIL_DISABLE_UTF7_ENCODE_OF_DIR')) {
1798 $tmpsourcedir = $this->getEncodedUtf7($sourcedir);
1799 }
1800
1801 $f = $client->getFolders(false, $tmpsourcedir); // Note the search of directory do a search on sourcedir*
1802 if ($f) {
1803 // getFolders does a sourcedir* match so INBOX also returns INBOX.Traites
1804 // etc. Pick the folder whose full_name matches the requested source
1805 // before falling back to the first result, otherwise polling can land
1806 // on an empty subfolder instead of INBOX (#37357).
1807 $folder = $f[0];
1808 foreach ($f as $candidate) {
1809 if ($candidate instanceof Webklex\PHPIMAP\Folder && $candidate->full_name === $tmpsourcedir) {
1810 $folder = $candidate;
1811 break;
1812 }
1813 }
1814 if ($folder instanceof Webklex\PHPIMAP\Folder) {
1815 $Query = $folder->messages()->where($criteria); // @phan-suppress-current-line PhanPluginUnknownObjectMethodCall
1816 }
1817 } else {
1818 $error++;
1819 $this->error = "Failed to execute getfolders";
1820 $this->errors[] = $this->error;
1821 dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1822 return -1;
1823 }
1824 } catch (InvalidWhereQueryCriteriaException $e) {
1825 $this->error = $e->getMessage();
1826 $this->errors[] = $this->error;
1827 dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1828 return -1;
1829 } catch (Exception $e) {
1830 $this->error = $e->getMessage();
1831 $this->errors[] = $this->error;
1832 dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1833 return -1;
1834 }
1835
1836 // @phpstan-ignore-line
1837 if (empty($Query)) {
1838 $error++;
1839 $this->error = "Source directory ".$sourcedir." not found";
1840 $this->errors[] = $this->error;
1841 dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_WARNING);
1842 return -1;
1843 }
1844
1845 '@phan-var-force Webklex\PHPIMAP\Query\Query $Query';
1846 try {
1847 if ($mode > 0) {
1848 $Query->leaveUnread();
1849 }
1850 $arrayofemail = $Query->limit($this->maxemailpercollect)->setFetchOrder("asc")->get();
1851 dol_syslog("EmailCollector::doCollectOneCollector nb arrayofemail ".(is_array($arrayofemail) ? count($arrayofemail) : 'Not array')); // @phpstan-ignore-line
1852 } catch (Exception $e) {
1853 $this->error = $e->getMessage();
1854 $this->errors[] = $this->error;
1855 dol_syslog("EmailCollector::doCollectOneCollector ".$this->error, LOG_ERR);
1856 return -1;
1857 }
1858 } elseif ($connection !== false) {
1859 // Scan IMAP dir (for native IMAP, the source dir is inside the $connection variable)
1860 $arrayofemail = imap_search($connection, $search, SE_UID, $charset);
1861
1862 if ($arrayofemail === false) {
1863 // Nothing found or search string not understood
1864 $mapoferrrors = imap_errors();
1865 if ($mapoferrrors !== false) {
1866 $error++;
1867 $this->error = "Search string not understood - ".implode(',', $mapoferrrors);
1868 $this->errors[] = $this->error;
1869 }
1870 }
1871 }
1872
1873 $arrayofemailtodelete = array(); // Track email to delete to make the deletion at end.
1874
1875 // Loop on each email found
1876 if (!$error && !empty($arrayofemail) && count($arrayofemail) > 0) {
1877 // Loop to get part html and plain
1878 /*
1879 0 multipart/mixed
1880 1 multipart/alternative
1881 1.1 text/plain
1882 1.2 text/html
1883 2 message/rfc822
1884 2 multipart/mixed
1885 2.1 multipart/alternative
1886 2.1.1 text/plain
1887 2.1.2 text/html
1888 2.2 message/rfc822
1889 2.2 multipart/alternative
1890 2.2.1 text/plain
1891 2.2.2 text/html
1892 */
1893 dol_syslog("Start of loop on email", LOG_INFO, 1);
1894
1895 $richarrayofemail = array();
1896
1897 foreach ($arrayofemail as $imapemail) {
1898 // GET header and overview datas
1899 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
1900 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1901 $header = $imapemail->getHeader()->raw; // @phan-suppress-current-line PhanPluginUnknownObjectMethodCall // @phan-suppress-current-line PhanPluginUnknownObjectMethodCall
1902 $overview = $imapemail->getAttributes();
1903 } else {
1904 $header = imap_fetchheader($connection, $imapemail, FT_UID);
1905 $overview = imap_fetch_overview($connection, $imapemail, FT_UID);
1906 }
1907
1908 $header = preg_replace('/\r\n\s+/m', ' ', $header); // When a header line is on several lines, merge lines
1909
1910 $matches = array();
1911 preg_match_all('/([^: ]+): (.+?(?:\r\n\s(?:.+?))*)(\r\n|\s$)/m', $header, $matches);
1912 $headers = array_combine($matches[1], $matches[2]);
1913
1914
1915 $richarrayofemail[] = array('imapemail' => $imapemail, 'header' => $header, 'headers' => $headers, 'overview' => $overview, 'date' => empty($headers['Date']) ? false : strtotime($headers['Date']));
1916 }
1917
1918
1919 // Sort email found by ascending date
1920 $richarrayofemail = dol_sort_array($richarrayofemail, 'date', 'asc');
1921
1922
1923 $iforemailloop = 0;
1924 foreach ($richarrayofemail as $tmpval) {
1925 if ($nbemailprocessed > 1000) {
1926 break; // Do not process more than 1000 email per launch (this is a different protection than maxnbcollectedpercollect)
1927 }
1928
1929 $iforemailloop++;
1930
1931 $imapemail = $tmpval['imapemail'];
1932 $header = $tmpval['header'];
1933 $overview = $tmpval['overview'];
1934 $headers = $tmpval['headers'];
1935
1936 if (!empty($headers['in-reply-to']) && empty($headers['In-Reply-To'])) {
1937 $headers['In-Reply-To'] = $headers['in-reply-to'];
1938 }
1939 if (!empty($headers['references']) && empty($headers['References'])) {
1940 $headers['References'] = $headers['references'];
1941 }
1942 if (!empty($headers['message-id']) && empty($headers['Message-ID'])) {
1943 $headers['Message-ID'] = $headers['message-id'];
1944 }
1945 if (!empty($headers['subject']) && empty($headers['Subject'])) {
1946 $headers['Subject'] = $headers['subject'];
1947 }
1948
1949 $headers['Subject'] = $this->decodeSMTPSubject($headers['Subject']);
1950
1951 if (getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')) {
1952 $emailto = (string) $overview['to'];
1953 } else {
1954 $emailto = $this->decodeSMTPSubject($overview[0]->to);
1955 }
1956
1957 $operationslog .= '<br>** Process email #'.dol_escape_htmltag((string) $iforemailloop);
1958
1959 if (getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')) {
1961 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
1962 // $operationslog .= " - ".dol_escape_htmltag((string) $imapemail);
1963 $msgid = str_replace(array('<', '>'), '', $overview['message_id']);
1964 } else {
1965 $operationslog .= " - ".dol_escape_htmltag((string) $imapemail);
1966 $msgid = str_replace(array('<', '>'), '', $overview[0]->message_id);
1967 }
1968 $operationslog .= " - MsgId: ".$msgid;
1969 $operationslog .= " - Date: ".($headers['Date'] ?? $langs->transnoentitiesnoconv("NotFound"));
1970 $operationslog .= " - References: ".dol_escape_htmltag($headers['References'] ?? $langs->transnoentitiesnoconv("NotFound"))." - Subject: ".dol_escape_htmltag($headers['Subject']);
1971
1972 dol_syslog("-- Process email #".$iforemailloop.", MsgId: ".$msgid.", Date: ".($headers['Date'] ?? '').", References: ".($headers['References'] ?? '').", Subject: ".$headers['Subject']);
1973
1974
1975 $trackidfoundintorecipienttype = '';
1976 $trackidfoundintorecipientid = 0;
1977 $reg = array();
1978 // See also later list of all supported tags...
1979 // Note: "th[i]" to avoid matching a codespell suggestion to convert to "this".
1980 // TODO Add host after the @'.preg_quote($host, '/')
1981 if (preg_match('/\+(th[i]|ctc|use|mem|sub|proj|tas|con|tic|pro|ord|inv|spro|sor|sin|leav|stockinv|job|surv|salary)([0-9]+)@/', $emailto, $reg)) {
1982 $trackidfoundintorecipienttype = $reg[1];
1983 $trackidfoundintorecipientid = $reg[2];
1984 } elseif (preg_match('/\+emailing-(\w+)@/', $emailto, $reg)) { // Can be 'emailing-test' or 'emailing-IdMailing-IdRecipient'
1985 $trackidfoundintorecipienttype = 'emailing';
1986 $trackidfoundintorecipientid = $reg[1];
1987 }
1988
1989 $trackidfoundintomsgidtype = '';
1990 $trackidfoundintomsgidid = 0;
1991 $reg = array();
1992 // See also later list of all supported tags...
1993 // Note: "th[i]" to avoid matching a codespell suggestion to convert to "this".
1994 // TODO Add host after the @
1995 if (preg_match('/(?:[\+\-])(th[i]|ctc|use|mem|sub|proj|tas|con|tic|pro|ord|inv|spro|sor|sin|leav|stockinv|job|surv|salary)([0-9]+)@/', $msgid, $reg)) {
1996 $trackidfoundintomsgidtype = $reg[1];
1997 $trackidfoundintomsgidid = $reg[2];
1998 } elseif (preg_match('/(?:[\+\-])emailing-(\w+)@/', $msgid, $reg)) { // Can be 'emailing-test' or 'emailing-IdMailing-IdRecipient'
1999 $trackidfoundintomsgidtype = 'emailing';
2000 $trackidfoundintomsgidid = $reg[1];
2001 }
2002
2003 // Now apply some filters.
2004
2005 // If there is an emailcollector filter on trackid
2006 if ($searchfilterdoltrackid > 0) {
2007 $referencesForFilter = $headers['References'] ?? '';
2008 if (!empty($headers['References']) && !empty($headers['In-Reply-To'])) {
2009 $referencesForFilter .= ' ';
2010 }
2011 $referencesForFilter .= ($headers['In-Reply-To'] ?? '');
2012
2013 if (empty($trackidfoundintorecipienttype) && empty($trackidfoundintomsgidtype)) {
2014 if (empty($referencesForFilter) || !preg_match('/@'.preg_quote($host, '/').'/', $referencesForFilter)) {
2015 $nbemailprocessed++;
2016 dol_syslog(" Discarded - No suffix in email recipient, and no Header 'References/In-Reply-To' found matching the signature of the application, so with a trackid coming from the application");
2017 continue; // Exclude email
2018 }
2019 }
2020 }
2021 // If we DON'T want email if there is a trackid
2022 if ($searchfilternodoltrackid > 0) {
2023 $referencesForFilter = $headers['References'] ?? '';
2024 if (!empty($headers['References']) && !empty($headers['In-Reply-To'])) {
2025 $referencesForFilter .= ' ';
2026 }
2027 $referencesForFilter .= ($headers['In-Reply-To'] ?? '');
2028
2029 if (!empty($trackidfoundintorecipienttype) || !empty($trackidfoundintomsgidtype) || (!empty($referencesForFilter) && preg_match('/@'.preg_quote($host, '/').'/', $referencesForFilter))) {
2030 $nbemailprocessed++;
2031 dol_syslog(" Discarded - Suffix found into email recipient, or Header 'References/In-Reply-To' found and matching signature of application so with a trackid");
2032 continue; // Exclude email
2033 }
2034 }
2035
2036 if ($searchfilterisanswer > 0) {
2037 $referencesforanswer = '';
2038 if (!empty($headers['References'])) {
2039 $referencesforanswer .= $headers['References'].' ';
2040 }
2041 if (!empty($headers['In-Reply-To'])) {
2042 $referencesforanswer .= $headers['In-Reply-To'];
2043 }
2044
2045 $hasdolibarrreference = 0;
2046 if (!empty($referencesforanswer)) {
2047 if (preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host, '/').'/', $referencesforanswer)) {
2048 $hasdolibarrreference = 1;
2049 } elseif (getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2050 if (preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE'), '/').'/', $referencesforanswer)) {
2051 $hasdolibarrreference = 1;
2052 }
2053 }
2054 }
2055
2056 $isanswer = 0;
2057 if (preg_match('/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers['Subject'])) {
2058 $isanswer = 1;
2059 }
2060 if (getDolGlobalString('EMAILCOLLECTOR_USE_IN_REPLY_TO_TO_DETECT_ANSWERS')) {
2061 // Note: "In-Reply-To" to detect if mail is an answer of another mail is not reliable because we can have:
2062 // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer but may be NOT (for example a transfer of an email rewritten)
2063 if (!empty($headers['In-Reply-To'])) {
2064 $isanswer = 1;
2065 }
2066 }
2067 if ($hasdolibarrreference) {
2068 $isanswer = 1;
2069 }
2070 //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
2071 //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1;
2072
2073 if (!$isanswer) {
2074 $nbemailprocessed++;
2075 dol_syslog(" Discarded - Email is not an answer (no reply marker detected, and test on In-Reply-To not requested because not reliable, or test on In-Reply-To requested but not found)");
2076 continue; // Exclude email
2077 }
2078 }
2079 if ($searchfilterisnotanswer > 0) {
2080 // Note: "In-Reply-To" to detect if mail is an answer is not reliable because we can have:
2081 // Message-ID=A, In-Reply-To=B, References=B and message can BE an answer or NOT (for example a transfer rewritten)
2082 $isanswer = 0;
2083 if (preg_match('/^(回复|回覆|SV|Antw|VS|RE|Re|AW|Aw|ΑΠ|השב| תשובה | הועבר|Vá|R|RIF|BLS|Atb|RES|Odp|பதில்|YNT|ATB)\s*:\s+/i', $headers['Subject'])) {
2084 $isanswer = 1;
2085 }
2086 // By default, ignore generic non-empty References to avoid false positives from
2087 // automated platform notifications. This option restores legacy behavior.
2088 if (!$isanswer && getDolGlobalInt('EMAILCOLLECTOR_ISNOTANSWER_USE_REFERENCES') && !empty($headers['References'])) {
2089 $isanswer = 1;
2090 }
2091 if (!$isanswer && getDolGlobalString('EMAILCOLLECTOR_USE_IN_REPLY_TO_TO_DETECT_ANSWERS')) {
2092 if (!empty($headers['In-Reply-To'])) {
2093 $isanswer = 1;
2094 }
2095 }
2096 //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
2097 //if ($headers['In-Reply-To'] != $headers['Message-ID'] && !empty($headers['References']) && strpos($headers['References'], $headers['Message-ID']) !== false) $isanswer = 1;
2098 if ($isanswer) {
2099 $nbemailprocessed++;
2100 dol_syslog(" Discarded - Email is an answer");
2101 continue; // Exclude email
2102 }
2103 }
2104 if ($searchfilterreplyto > 0) {
2105 if (!empty($headers['Reply-To'])) {
2106 $isreplytook = 0;
2107 foreach ($rulesreplyto as $key => $rulereplyto) {
2108 if (preg_match('/'.preg_quote($rulereplyto, '/').'/', $headers['Reply-To'])) {
2109 $isreplytook++;
2110 }
2111 }
2112
2113 if (!$isreplytook || $isreplytook != count($rulesreplyto)) {
2114 $nbemailprocessed++;
2115 dol_syslog(" Discarded - Reply-to does not match");
2116 continue; // Exclude email
2117 }
2118 }
2119 }
2120
2121 //print "Process mail ".$iforemailloop." Subject: ".dol_escape_htmltag($headers['Subject'])." selected<br>\n";
2122
2123 $thirdpartystatic = new Societe($this->db);
2124 $contactstatic = new Contact($this->db);
2125 $projectstatic = new Project($this->db);
2126
2127 $nbactiondoneforemail = 0;
2128 $errorforemail = 0;
2129 $errorforactions = 0;
2130 $thirdpartyfoundby = '';
2131 $contactfoundby = '';
2132 $projectfoundby = '';
2133 $ticketfoundby = '';
2134 $candidaturefoundby = '';
2135
2136
2137 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
2138 $dateformated = dol_print_date($overview['date'], 'dayrfc', 'gmt'); // May generate a warning "dol_print_date($overview['date'], 'dayrfc', 'gmt')" in log
2139 dol_syslog("msgid=".$overview['message_id']." date=".$dateformated." from=".$overview['from']." to=".$overview['to']." subject=".$overview['subject']);
2140
2141 // Removed emojis
2142 $overview['subject'] = removeEmoji($overview['subject'], getDolGlobalInt('MAIN_EMAIL_COLLECTOR_ACCEPT_EMOJIS', 1));
2143 } else {
2144 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);
2145
2146 $overview[0]->subject = $this->decodeSMTPSubject($overview[0]->subject);
2147
2148 $overview[0]->from = $this->decodeSMTPSubject($overview[0]->from);
2149
2150 // Removed emojis
2151 $overview[0]->subject = removeEmoji($overview[0]->subject, getDolGlobalInt('MAIN_EMAIL_COLLECTOR_ACCEPT_EMOJIS', 1));
2152 }
2153 // GET IMAP email structure/content
2154 global $htmlmsg, $plainmsg, $charset, $attachments;
2155
2156 if (getDolGlobalInt('MAIN_IMAP_USE_PHPIMAP')) {
2158 '@phan-var-force Webklex\PHPIMAP\Message $imapemail';
2159 // Reset message body globals to prevent carryover from previous email in loop
2160 // Note: $charset is NOT reset as PHPIMAP handles charset internally
2161 $htmlmsg = $plainmsg = '';
2162 $attachments = array();
2163
2164 if ($imapemail->hasHTMLBody()) {
2165 $htmlmsg = $imapemail->getHTMLBody();
2166 }
2167 if ($imapemail->hasTextBody() && $imapemail->getTextBody() != "\n") {
2168 $plainmsg = $imapemail->getTextBody();
2169 }
2170 if ($imapemail->hasAttachments()) {
2171 $attachments = $imapemail->getAttachments()->all();
2172 } else {
2173 $attachments = array();
2174 }
2175 } else {
2176 $getMsg = $this->getmsg($connection, $imapemail); // This set global var $charset, $htmlmsg, $plainmsg, $attachments
2177 if ($getMsg < 0) {
2178 $this->errors = array_merge($this->errors, [$this->error]);
2179 return $getMsg;
2180 }
2181 }
2182 '@phan-var-force Webklex\PHPIMAP\Attachment[] $attachments';
2185 //$htmlmsg,$plainmsg,$charset,$attachments
2186 $messagetext = $plainmsg ? $plainmsg : dol_string_nohtmltag((string) $htmlmsg, 0);
2187 // Removed emojis
2188
2189 if (utf8_valid($messagetext)) {
2190 $messagetext = removeEmoji($messagetext, getDolGlobalInt('MAIN_EMAIL_COLLECTOR_ACCEPT_EMOJIS', 1));
2191 } else {
2192 $operationslog .= '<br>Discarded - Email body is not valid utf8';
2193 dol_syslog(" Discarded - Email body is not valid utf8");
2194 continue; // Exclude email
2195 }
2196
2197 if (!empty($searchfilterexcludebodyarray)) {
2198 foreach ($searchfilterexcludebodyarray as $searchfilterexcludebody) {
2199 if (preg_match('/'.preg_quote($searchfilterexcludebody, '/').'/ms', $messagetext)) {
2200 $nbemailprocessed++;
2201 $operationslog .= '<br>Discarded - Email body contains string '.$searchfilterexcludebody;
2202 dol_syslog(" Discarded - Email body contains string ".$searchfilterexcludebody);
2203 continue 2; // Exclude email
2204 }
2205 }
2206 }
2207
2208 // Parse IMAP email structure
2209 /*
2210 $structure = imap_fetchstructure($connection, $imapemail, FT_UID);
2211
2212 $partplain = $parthtml = -1;
2213 $encodingplain = $encodinghtml = '';
2214
2215 $result = createPartArray($structure, '');
2216
2217 foreach($result as $part)
2218 {
2219 // $part['part_object']->type seems 0 for content
2220 // $part['part_object']->type seems 5 for attachment
2221 if (empty($part['part_object'])) continue;
2222 if ($part['part_object']->subtype == 'HTML')
2223 {
2224 $parthtml=$part['part_number'];
2225 if ($part['part_object']->encoding == 4)
2226 {
2227 $encodinghtml = 'aaa';
2228 }
2229 }
2230 if ($part['part_object']->subtype == 'PLAIN')
2231 {
2232 $partplain=$part['part_number'];
2233 if ($part['part_object']->encoding == 4)
2234 {
2235 $encodingplain = 'rr';
2236 }
2237 }
2238 }
2239
2240 $messagetext = imap_fetchbody($connection, $imapemail, ($parthtml != '-1' ? $parthtml : ($partplain != '-1' ? $partplain : 1)), FT_PEEK|FTP_UID);
2241 */
2242
2243 $fromstring = '';
2244 $replytostring = '';
2245
2246 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
2247 $fromstring = $this->decodeSMTPSubject((string) ($overview['from'] ?? ''));
2248 $replytostring = !empty($headers['Reply-To']) ? $this->decodeSMTPSubject($headers['Reply-To']) : '';
2249
2250 $sender = $this->decodeSMTPSubject((string) ($overview['sender'] ?? ''));
2251 $to = $this->decodeSMTPSubject((string) ($overview['to'] ?? ''));
2252 $sendtocc = $this->decodeSMTPSubject((string) ($overview['cc'] ?? ''));
2253 $sendtobcc = $this->decodeSMTPSubject((string) ($overview['bcc'] ?? ''));
2254
2255 $tmpdate = $overview['date']->toDate(); // @phan-suppress-current-line PhanPluginUnknownObjectMethodCall
2256 $tmptimezone = $tmpdate->getTimezone()->getName(); // @phan-suppress-current-line PhanPluginUnknownObjectMethodCall
2257
2258 $dateemail = dol_stringtotime((string) $overview['date'], 'gmt'); // if $overview['timezone'] is "+00:00"
2259 if (preg_match('/^([+\-])(\d\d):(\d\d)/', $tmptimezone, $reg)) {
2260 if ($reg[1] == '+' && ($reg[2] != '00' || $reg[3] != '00')) {
2261 $dateemail -= (3600 * (int) $reg[2]);
2262 $dateemail -= (60 * (int) $reg[3]);
2263 }
2264 if ($reg[1] == '-' && ($reg[2] != '00' || $reg[3] != '00')) {
2265 $dateemail += (3600 * (int) $reg[2]);
2266 $dateemail += (60 * (int) $reg[3]);
2267 }
2268 }
2269 $subject = $this->decodeSMTPSubject((string) ($overview['subject'] ?? ''));
2270 } else {
2271 $fromstring = (string) $overview[0]->from;
2272 $replytostring = (!empty($overview['in_reply-to']) ? $overview['in_reply-to'] : (!empty($headers['Reply-To']) ? $headers['Reply-To'] : "")) ;
2273
2274 $sender = !empty($overview[0]->sender) ? $overview[0]->sender : '';
2275 $to = $overview[0]->to;
2276 $sendtocc = !empty($overview[0]->cc) ? $overview[0]->cc : '';
2277 $sendtobcc = !empty($overview[0]->bcc) ? $overview[0]->bcc : '';
2278 $dateemail = dol_stringtotime((string) $overview[0]->udate, 'gmt');
2279 $subject = (string) $overview[0]->subject;
2280 }
2281
2282 if (!empty($searchfilterexcludesubjectarray)) {
2283 foreach ($searchfilterexcludesubjectarray as $searchfilterexcludesubject) {
2284 if (preg_match('/'.preg_quote($searchfilterexcludesubject, '/').'/ms', $subject)) {
2285 $nbemailprocessed++;
2286 $operationslog .= '<br>Discarded - Email subject contains string '.$searchfilterexcludesubject;
2287 dol_syslog(" Discarded - Email subject contains string ".$searchfilterexcludesubject);
2288 continue 2; // Exclude email
2289 }
2290 }
2291 }
2292
2293 $reg = array();
2294 if (preg_match('/^(.*)<(.*)>$/', $fromstring, $reg)) {
2295 $email_from = $reg[2];
2296 $fromtext = $reg[1];
2297 } else {
2298 $email_from = $fromstring;
2299 $fromtext = '';
2300 }
2301 if (preg_match('/^(.*)<(.*)>$/', $replytostring, $reg)) {
2302 $replyto = $reg[2];
2303 $replytotext = $reg[1];
2304 } else {
2305 $replyto = $replytostring;
2306 $replytotext = '';
2307 }
2308
2309 if (!empty($searchfilterexcludeemailmap) || !empty($searchfilterexcludedomainarray)) {
2310 $emailsToCheck = array();
2311 $tmpaddressblob = trim($fromstring.' '.$replytostring);
2312 if ($tmpaddressblob !== '' && preg_match_all('/[a-z0-9._%+\\-]+@[a-z0-9.\\-]+\\.[a-z]{2,}/i', $tmpaddressblob, $tmpmatches)) {
2313 foreach ($tmpmatches[0] as $tmpEmail) {
2314 $tmpEmail = strtolower(trim($tmpEmail));
2315 if ($tmpEmail !== '') {
2316 $emailsToCheck[$tmpEmail] = true;
2317 }
2318 }
2319 }
2320
2321 if (empty($emailsToCheck)) {
2322 foreach (array($email_from, $replyto) as $tmpEmail) {
2323 $tmpEmail = strtolower(trim((string) $tmpEmail));
2324 if ($tmpEmail !== '' && strpos($tmpEmail, '@') !== false) {
2325 $emailsToCheck[$tmpEmail] = true;
2326 }
2327 }
2328 }
2329
2330 $discardEmail = '';
2331 $discardDomain = '';
2332 $matchedDomainRule = '';
2333
2334 foreach (array_keys($emailsToCheck) as $tmpEmail) {
2335 if (!empty($searchfilterexcludeemailmap[$tmpEmail])) {
2336 $discardEmail = $tmpEmail;
2337 break;
2338 }
2339
2340 if (!empty($searchfilterexcludedomainarray)) {
2341 $posat = strrpos($tmpEmail, '@');
2342 if ($posat === false) {
2343 continue;
2344 }
2345 $tmpDomain = strtolower(substr($tmpEmail, $posat + 1));
2346 foreach ($searchfilterexcludedomainarray as $excludedDomain) {
2347 if ($excludedDomain === '') {
2348 continue;
2349 }
2350 if ($tmpDomain === $excludedDomain || substr($tmpDomain, -strlen('.'.$excludedDomain)) === '.'.$excludedDomain) {
2351 $discardDomain = $tmpDomain;
2352 $matchedDomainRule = $excludedDomain;
2353 break 2;
2354 }
2355 }
2356 }
2357 }
2358
2359 if ($discardEmail !== '' || $discardDomain !== '') {
2360 $nbemailprocessed++;
2361 if ($discardEmail !== '') {
2362 $operationslog .= '<br>Discarded - Sender email excluded: '.$discardEmail;
2363 dol_syslog(" Discarded - Sender email excluded: ".$discardEmail);
2364 } else {
2365 $operationslog .= '<br>Discarded - Sender domain excluded: '.$discardDomain.($matchedDomainRule !== '' && $matchedDomainRule !== $discardDomain ? ' (matched '.$matchedDomainRule.')' : '');
2366 dol_syslog(" Discarded - Sender domain excluded: ".$discardDomain.($matchedDomainRule !== '' && $matchedDomainRule !== $discardDomain ? " (matched ".$matchedDomainRule.")" : ""));
2367 }
2368 continue;
2369 }
2370 }
2371
2372 $fk_element_id = 0;
2373 $fk_element_type = '';
2374
2375
2376 $this->db->begin();
2377
2378 $contactid = 0;
2379 $thirdpartyid = 0;
2380 $projectid = 0;
2381 $ticketid = 0;
2382
2383 // Analyze TrackId in field References (already analyzed previously into the "To:" and "Message-Id").
2384 // For example:
2385 // References: <1542377954.SMTPs-dolibarr-thi649@8f6014fde11ec6cdec9a822234fc557e>
2386 // References: <1542377954.SMTPs-dolibarr-tic649@8f6014fde11ec6cdec9a822234fc557e>
2387 // References: <1542377954.SMTPs-dolibarr-abc649@8f6014fde11ec6cdec9a822234fc557e>
2388 $trackid = '';
2389 $objectid = 0;
2390 $objectemail = null;
2391
2392 $reg = array();
2393 $arrayofreferences = array();
2394 if (!empty($headers['References'])) {
2395 $arrayofreferences = preg_split('/(,|\s+)/', $headers['References']);
2396 }
2397 if (!in_array('<'.$msgid.'>', $arrayofreferences)) {
2398 $arrayofreferences = array_merge($arrayofreferences, array('<'.$msgid.'>'));
2399 }
2400
2401 // We loop on References, but as soon as we found one that allow us to find an existing object,
2402 // we do a break (See line with comment "Exit loop of references").
2403 foreach ($arrayofreferences as $reference) {
2404 //print "Process mail ".$iforemailloop." email_msgid ".$msgid.", date ".dol_print_date($dateemail, 'dayhour', 'gmt').", subject ".$subject.", reference ".dol_escape_htmltag($reference)."<br>\n";
2405 if (!empty($trackidfoundintorecipienttype)) {
2406 $resultsearchtrackid = -1; // trackid found
2407 $reg[1] = $trackidfoundintorecipienttype;
2408 $reg[2] = $trackidfoundintorecipientid;
2409 } elseif (!empty($trackidfoundintomsgidtype)) {
2410 $resultsearchtrackid = -1; // trackid found
2411 $reg[1] = $trackidfoundintomsgidtype;
2412 $reg[2] = $trackidfoundintomsgidid;
2413 } else {
2414 $resultsearchtrackid = preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote($host, '/').'/', $reference, $reg); // trackid found or not
2415 if (empty($resultsearchtrackid) && getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE')) {
2416 $resultsearchtrackid = preg_match('/dolibarr-([a-z]+)([0-9]+)@'.preg_quote(getDolGlobalString('EMAIL_ALTERNATIVE_HOST_SIGNATURE'), '/').'/', $reference, $reg); // trackid found
2417 }
2418 }
2419
2420 if (!empty($resultsearchtrackid)) {
2421 // We found a tracker (in recipient email or msgid or into a Reference matching the Dolibarr server)
2422 $trackid = $reg[1].$reg[2];
2423
2424 $objectid = $reg[2];
2425 // See also list into interface_50_modAgenda_ActionsAuto
2426 if ($reg[1] == 'thi') { // Third-party
2427 $objectemail = new Societe($this->db);
2428 }
2429 if ($reg[1] == 'ctc') { // Contact
2430 $objectemail = new Contact($this->db);
2431 }
2432 if ($reg[1] == 'inv') { // Customer Invoice
2433 $objectemail = new Facture($this->db);
2434 }
2435 if ($reg[1] == 'sinv') { // Supplier Invoice
2436 $objectemail = new FactureFournisseur($this->db);
2437 }
2438 if ($reg[1] == 'pro') { // Customer Proposal
2439 $objectemail = new Propal($this->db);
2440 }
2441 if ($reg[1] == 'ord') { // Sale Order
2442 $objectemail = new Commande($this->db);
2443 }
2444 if ($reg[1] == 'shi') { // Shipment
2445 $objectemail = new Expedition($this->db);
2446 }
2447 if ($reg[1] == 'spro') { // Supplier Proposal
2448 $objectemail = new SupplierProposal($this->db);
2449 }
2450 if ($reg[1] == 'sord') { // Supplier Order
2451 $objectemail = new CommandeFournisseur($this->db);
2452 }
2453 if ($reg[1] == 'rec') { // Reception
2454 $objectemail = new Reception($this->db);
2455 }
2456 if ($reg[1] == 'proj') { // Project
2457 $objectemail = new Project($this->db);
2458 $projectfoundby = 'TrackID dolibarr-'.$trackid.'@...';
2459 }
2460 if ($reg[1] == 'tas') { // Task
2461 $objectemail = new Task($this->db);
2462 }
2463 if ($reg[1] == 'con') { // Contact
2464 $objectemail = new Contact($this->db);
2465 }
2466 if ($reg[1] == 'use') { // User
2467 $objectemail = new User($this->db);
2468 }
2469 if ($reg[1] == 'tic') { // Ticket
2470 $objectemail = new Ticket($this->db);
2471 $ticketfoundby = 'TrackID dolibarr-'.$trackid.'@...';
2472 }
2473 if ($reg[1] == 'recruitmentcandidature') { // Recruiting Candidate
2474 $objectemail = new RecruitmentCandidature($this->db);
2475 $candidaturefoundby = 'TrackID dolibarr-'.$trackid.'@...';
2476 }
2477 if ($reg[1] == 'mem') { // Member
2478 $objectemail = new Adherent($this->db);
2479 }
2480 /*if ($reg[1] == 'leav') { // Leave / Holiday
2481 $objectemail = new Holiday($db);
2482 }
2483 if ($reg[1] == 'exp') { // ExpenseReport
2484 $objectemail = new ExpenseReport($db);
2485 }*/
2486 } elseif (preg_match('/<(.*@.*)>/', $reference, $reg)) {
2487 // This is an external reference, we check if we have it in our database
2488 if (is_null($objectemail) && isModEnabled('ticket')) {
2489 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."ticket";
2490 $sql .= " WHERE email_msgid = '".$this->db->escape($reg[1])."' OR origin_references LIKE '%".$this->db->escape($this->db->escapeforlike($reg[1]))."%'";
2491 $resql = $this->db->query($sql);
2492 if ($resql) {
2493 $obj = $this->db->fetch_object($resql);
2494 if ($obj) {
2495 $objectid = $obj->rowid;
2496 $objectemail = new Ticket($this->db);
2497 $ticketfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
2498 }
2499 } else {
2500 $errorforemail++;
2501 }
2502 }
2503
2504 if (!is_object($objectemail) && isModEnabled('project')) {
2505 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."projet where email_msgid = '".$this->db->escape($reg[1])."'";
2506 $resql = $this->db->query($sql);
2507 if ($resql) {
2508 $obj = $this->db->fetch_object($resql);
2509 if ($obj) {
2510 $objectid = $obj->rowid;
2511 $objectemail = new Project($this->db);
2512 $projectfoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
2513 }
2514 } else {
2515 $errorforemail++;
2516 }
2517 }
2518
2519 if (!is_object($objectemail) && isModEnabled('recruitment')) {
2520 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."recruitment_recruitmentcandidature where email_msgid = '".$this->db->escape($reg[1])."'";
2521 $resql = $this->db->query($sql);
2522 if ($resql) {
2523 $obj = $this->db->fetch_object($resql);
2524 if ($obj) {
2525 $objectid = $obj->rowid;
2526 $objectemail = new RecruitmentCandidature($this->db);
2527 $candidaturefoundby = $langs->transnoentitiesnoconv("EmailMsgID").' ('.$reg[1].')';
2528 }
2529 } else {
2530 $errorforemail++;
2531 }
2532 }
2533 }
2534
2535 // Load object linked to email
2536 if (is_object($objectemail)) {
2537 $result = $objectemail->fetch($objectid);
2538 if ($result > 0) {
2539 $fk_element_id = $objectemail->id;
2540 $fk_element_type = $objectemail->element;
2541 // Fix fk_element_type
2542 if ($fk_element_type == 'facture') {
2543 $fk_element_type = 'invoice';
2544 }
2545
2546 if (get_class($objectemail) != 'Societe') {
2547 $thirdpartyid = $objectemail->fk_soc ?? $objectemail->socid;
2548 } else {
2549 $thirdpartyid = $objectemail->id;
2550 }
2551
2552 if (get_class($objectemail) != 'Contact') {
2553 $contactid = $objectemail->fk_socpeople;
2554 } else {
2555 $contactid = $objectemail->id;
2556 }
2557
2558 if (get_class($objectemail) != 'Project') {
2559 $projectid = isset($objectemail->fk_project) ? $objectemail->fk_project : $objectemail->fk_projet;
2560 } else {
2561 $projectid = $objectemail->id;
2562 }
2563
2564 if ($objectemail instanceof Ticket) { // For tickets, we have a column to store all met references, so we complete it if we need to.
2565 $ticketid = $objectemail->id;
2566
2567 $changeonticket_references = false;
2568 if (empty($trackid)) {
2569 $trackid = $objectemail->track_id;
2570 }
2571 if (empty($objectemail->origin_references)) {
2572 $objectemail->origin_references = !empty($headers['References']) ? $headers['References'] : null;
2573 $changeonticket_references = true;
2574 } else {
2575 foreach ($arrayofreferences as $key => $referencetmp) {
2576 if (!str_contains($objectemail->origin_references, $referencetmp)) {
2577 $objectemail->origin_references .= " ".$referencetmp;
2578 $changeonticket_references = true;
2579 }
2580 }
2581 }
2582 if ($changeonticket_references) {
2583 $operationslog .= '<br>We complete ticket ID='.$ticketid.' with property origin_references='.$objectemail->origin_references;
2584 $objectemail->update($user, 1); // We complete the references field with all references mentioned into this email. This field is for technical tracking purpose, not a user field, so no need to execute triggers
2585 }
2586 }
2587 }
2588 }
2589
2590 // Project
2591 if ($projectid > 0) {
2592 $result = $projectstatic->fetch($projectid);
2593 if ($result <= 0) {
2594 $projectstatic->id = 0;
2595 } else {
2596 $projectid = $projectstatic->id;
2597 if ($trackid) {
2598 $projectfoundby = 'trackid ('.$trackid.')';
2599 }
2600 /* if (empty($contactid)) {
2601 $contactid = $projectstatic->fk_contact;
2602 } */
2603 if (empty($thirdpartyid)) {
2604 $thirdpartyid = $projectstatic->socid;
2605 }
2606 }
2607 }
2608 // Contact
2609 if ($contactid > 0) {
2610 $result = $contactstatic->fetch($contactid);
2611 if ($result <= 0) {
2612 $contactstatic->id = 0;
2613 } else {
2614 $contactid = $contactstatic->id;
2615 if ($trackid) {
2616 $contactfoundby = 'trackid ('.$trackid.')';
2617 }
2618 if (empty($thirdpartyid)) {
2619 $thirdpartyid = $contactstatic->fk_soc;
2620 }
2621 }
2622 }
2623 // Thirdparty
2624 if ($thirdpartyid > 0) {
2625 $result = $thirdpartystatic->fetch($thirdpartyid);
2626 if ($result <= 0) {
2627 $thirdpartystatic->id = 0;
2628 } else {
2629 $thirdpartyid = $thirdpartystatic->id;
2630 if ($trackid) {
2631 $thirdpartyfoundby = 'trackid ('.$trackid.')';
2632 }
2633 }
2634 }
2635
2636 if (is_object($objectemail)) {
2637 break; // Exit loop of references. We already found an accurate reference
2638 }
2639 }
2640
2641 if (empty($contactid)) { // Try to find contact using email
2642 $result = $contactstatic->fetch(0, null, '', $email_from);
2643
2644 if ($result > 0) {
2645 dol_syslog("We found a contact with the email ".$email_from);
2646 $contactid = $contactstatic->id;
2647 $contactfoundby = 'email of contact ('.$email_from.')';
2648 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2649 $result = $thirdpartystatic->fetch($contactstatic->socid);
2650 if ($result > 0) {
2651 $thirdpartyid = $thirdpartystatic->id;
2652 $thirdpartyfoundby = 'email of contact ('.$email_from.')';
2653 }
2654 }
2655 }
2656 }
2657
2658 if (empty($thirdpartyid)) { // Try to find thirdparty using email
2659 $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $email_from);
2660 if ($result > 0) {
2661 dol_syslog("We found a thirdparty with the email ".$email_from);
2662 $thirdpartyid = $thirdpartystatic->id;
2663 $thirdpartyfoundby = 'email ('.$email_from.')';
2664 }
2665 }
2666
2667 /*
2668 if ($replyto) {
2669 if (empty($contactid)) { // Try to find contact using email
2670 $result = $contactstatic->fetch(0, null, '', $replyto);
2671
2672 if ($result > 0) {
2673 dol_syslog("We found a contact with the email ".$replyto);
2674 $contactid = $contactstatic->id;
2675 $contactfoundby = 'email of contact ('.$replyto.')';
2676 if (empty($thirdpartyid) && $contactstatic->socid > 0) {
2677 $result = $thirdpartystatic->fetch($contactstatic->socid);
2678 if ($result > 0) {
2679 $thirdpartyid = $thirdpartystatic->id;
2680 $thirdpartyfoundby = 'email of contact ('.$replyto.')';
2681 }
2682 }
2683 }
2684 }
2685
2686 if (empty($thirdpartyid)) { // Try to find thirdparty using email
2687 $result = $thirdpartystatic->fetch(0, '', '', '', '', '', '', '', '', '', $replyto);
2688 if ($result > 0) {
2689 dol_syslog("We found a thirdparty with the email ".$replyto);
2690 $thirdpartyid = $thirdpartystatic->id;
2691 $thirdpartyfoundby = 'email ('.$replyto.')';
2692 }
2693 }
2694 }
2695 */
2696
2697 // Persist attachments for some linked objects (so hooks can rely on files on disk).
2698 $savedattachments = array();
2699 $savedattachmentsdir = '';
2700 $savedattachmentsnote = '';
2701 if (empty($mode) && !empty($attachments) && $fk_element_id > 0 && $fk_element_type === 'order_supplier' && $objectemail instanceof CommandeFournisseur) {
2702 $orderref = isset($objectemail->ref) ? (string) $objectemail->ref : '';
2703 if ($orderref !== '' && !empty($conf->fournisseur->commande)) {
2704 $entityforobject = isset($objectemail->entity) ? (int) $objectemail->entity : (int) $conf->entity;
2705 $basedir = (!empty($conf->fournisseur->commande->multidir_output[$entityforobject]) ? $conf->fournisseur->commande->multidir_output[$entityforobject] : $conf->fournisseur->commande->dir_output);
2706 $savedattachmentsdir = rtrim($basedir, '/').'/'.dol_sanitizeFileName($orderref);
2707 $savedattachments = $this->saveEmailCollectorAttachmentsToDir($savedattachmentsdir, $attachments);
2708 if (!empty($savedattachments)) {
2709 $operationslog .= '<br>Saved '.count($savedattachments).' attachment(s) into '.dol_escape_htmltag($savedattachmentsdir);
2710 }
2711 }
2712 }
2713 if (!empty($savedattachments)) {
2714 $names = array();
2715 foreach ($savedattachments as $attmeta) {
2716 if (!is_array($attmeta) || empty($attmeta['name'])) {
2717 continue;
2718 }
2719 $names[] = (string) $attmeta['name'];
2720 }
2721 if (!empty($names)) {
2722 $savedattachmentsnote = $langs->trans("NbOfAttachedFiles").' : '.count($names);
2723 $savedattachmentsnote .= ' ('.implode(', ', array_slice($names, 0, 10)).(count($names) > 10 ? '...' : '').')';
2724 }
2725 }
2726
2727
2728 // Now do all operations for the email (extract variables and creating data)
2729 if ($mode < 2) { // 0=Mode production, 1=Mode test (read IMAP and try SQL update then rollback), 2=Mode test with no SQL updates
2730 foreach ($this->actions as $operation) {
2731 $errorforthisaction = 0;
2732 $ticketalreadyexists = 0;
2733 if ($errorforactions) {
2734 break;
2735 }
2736 if (empty($operation['status'])) {
2737 continue;
2738 }
2739
2740 $operationslog .= '<br>* Process operation '.$operation['type'];
2741
2742 // Make Operation
2743 dol_syslog("Execute action ".$operation['type']." actionparam=".$operation['actionparam'].' thirdpartystatic->id='.$thirdpartystatic->id.' contactstatic->id='.$contactstatic->id.' projectstatic->id='.$projectstatic->id);
2744 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
2745
2746 // Try to guess if this is an email in or out.
2747 $actioncode = 'EMAIL_IN';
2748 // If we scan the Sent box, we use the code for out email
2749 if (preg_match('/Sent$/', $sourcedir) || preg_match('/envoyés$/i', $sourcedir)) {
2750 $actioncode = 'EMAIL';
2751 }
2752 // If sender is in the list MAIL_FROM_EMAILS_TO_CONSIDER_SENDING
2753 $arrayofemailtoconsidersender = array_filter(array_map('trim', explode(',', getDolGlobalString('MAIL_FROM_EMAILS_TO_CONSIDER_SENDING'))));
2754 foreach ($arrayofemailtoconsidersender as $emailtoconsidersender) {
2755 if ($emailtoconsidersender === '') {
2756 continue;
2757 }
2758 if (preg_match('/'.preg_quote($emailtoconsidersender, '/').'/', $fromstring)) {
2759 $actioncode = 'EMAIL';
2760 }
2761 }
2762 $operationslog .= '<br>Email will have actioncode='.$actioncode;
2763
2764 $description = $descriptiontitle = $descriptionmeta = $descriptionfull = '';
2765
2766 $descriptiontitle = $langs->transnoentitiesnoconv("RecordCreatedByEmailCollector", $this->ref);
2767
2768 $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("EmailMsgID").' : '.dol_escape_htmltag($msgid));
2769 $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTopic").' : '.dol_escape_htmltag($subject));
2770 $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailDate").($langs->trans("MailDate") != 'Date' ? ' (Date)' : '').' : '.dol_escape_htmltag(dol_print_date($dateemail, "dayhourtext", "gmt")));
2771 $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailFrom").($langs->trans("MailFrom") != 'From' ? ' (From)' : '').' : '.dol_escape_htmltag($fromstring));
2772 if ($sender) {
2773 $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("Sender").($langs->trans("Sender") != 'Sender' ? ' (Sender)' : '').' : '.dol_escape_htmltag($sender));
2774 }
2775 $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailTo").($langs->trans("MailTo") != 'To' ? ' (To)' : '').' : '.dol_escape_htmltag($to));
2776 if ($replyto) {
2777 $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailReply").($langs->trans("MailReply") != 'Reply to' ? ' (Reply to)' : '').' : '.dol_escape_htmltag($replyto));
2778 }
2779 if ($sendtocc) {
2780 $descriptionmeta = dol_concatdesc($descriptionmeta, $langs->trans("MailCC").($langs->trans("MailCC") != 'CC' ? ' (CC)' : '').' : '.dol_escape_htmltag($sendtocc));
2781 }
2782 if ($savedattachmentsnote) {
2783 $descriptionmeta = dol_concatdesc($descriptionmeta, $savedattachmentsnote);
2784 }
2785
2786 if ($operation['type'] == 'ticket') {
2787 // Verify if ticket already exists to fall back on the right operation
2788 $tickettocreate = new Ticket($this->db);
2789 $errorfetchticket = 0;
2790 $alreadycreated = 0;
2791 if (!empty($objectid) && $objectemail instanceof Ticket) {
2792 $alreadycreated = $tickettocreate->fetch((int) $objectid);
2793 }
2794 if ($alreadycreated == 0 && $ticketid > 0) { // objectemail was on a ticket it ticketid set
2795 $alreadycreated = $tickettocreate->fetch($ticketid);
2796 }
2797 if ($alreadycreated == 0 && !empty($trackid)) { // objectemail was on a ticket if trackid is set
2798 $alreadycreated = $tickettocreate->fetch(0, '', $trackid);
2799 }
2800 if ($alreadycreated == 0 && !empty($msgid)) { // objectemail was on a ticket if msgid is set
2801 $alreadycreated = $tickettocreate->fetch(0, '', '', $msgid);
2802 }
2803 if ($alreadycreated < 0) {
2804 $errorfetchticket++;
2805 }
2806 if (empty($errorfetchticket)) {
2807 if ($alreadycreated == 0) {
2808 $operationslog .= '<br>Ticket not found using trackid='.$trackid.' or msgid='.$msgid;
2809 $ticketalreadyexists = 0;
2810 } else {
2811 $operationslog .= '<br>Ticket already found using trackid='.$trackid.' or msgid='.$msgid.", we replace operation 'ticket' with 'recordevent' to add a new message"; // We change the operation type to do
2812 $ticketalreadyexists = 1;
2813 $operation['type'] = 'recordevent';
2814 }
2815 } else {
2816 $ticketalreadyexists = -1;
2817 }
2818 }
2819
2820 // Process now the operation according to its type
2821
2822 // Search and create thirdparty
2823 if ($operation['type'] == 'loadthirdparty' || $operation['type'] == 'loadandcreatethirdparty') {
2824 if ($thirdpartyid > 0) {
2825 // We already have found the thirdparty id to load, so we bypass the action loadthirdparty
2826 $idtouseforthirdparty = $thirdpartyid;
2827 $operationslog .= '<br>We already have found a related thirdparty id, so we bypass the action loadthirdparty and use idtouseforthirdparty='.$idtouseforthirdparty;
2828 } elseif (empty($operation['actionparam'])) {
2829 $errorforactions++;
2830 $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;";
2831 $this->errors[] = $this->error;
2832 } else {
2833 $actionparam = $operation['actionparam'];
2834 $idtouseforthirdparty = '';
2835 $nametouseforthirdparty = '';
2836 $emailtouseforthirdparty = '';
2837 $namealiastouseforthirdparty = '';
2838
2839 $operationslog .= '<br>Loop on each property to set into actionparam';
2840
2841 // $actionparam = 'param=SET:aaa' or 'param=EXTRACT:BODY:....'
2842 $arrayvaluetouse = dolExplodeIntoArray($actionparam, '(\n\r|\r|\n|;)', '=');
2843 foreach ($arrayvaluetouse as $propertytooverwrite => $valueforproperty) {
2844 $sourcestring = '';
2845 $sourcefield = '';
2846 $regexstring = '';
2847 $regforregex = array();
2848
2849 if (preg_match('/^EXTRACT:([a-zA-Z0-9_]+):(.*)$/', $valueforproperty, $regforregex)) {
2850 $sourcefield = $regforregex[1];
2851 $regexstring = $regforregex[2];
2852 }
2853
2854 if (!empty($sourcefield) && !empty($regexstring)) {
2855 if (strtolower($sourcefield) == 'body') {
2856 $sourcestring = $messagetext;
2857 } elseif (strtolower($sourcefield) == 'subject') {
2858 $sourcestring = $subject;
2859 } elseif (strtolower($sourcefield) == 'header') {
2860 $sourcestring = $header;
2861 }
2862
2863 if ($sourcestring) {
2864 $regforval = array();
2865 if (preg_match('/'.$regexstring.'/ms', $sourcestring, $regforval)) {
2866 // Overwrite param $tmpproperty
2867 if ($propertytooverwrite == 'id') {
2868 $idtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2869
2870 $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found idtouseforthirdparty='.dol_escape_htmltag($idtouseforthirdparty);
2871 } elseif ($propertytooverwrite == 'email') {
2872 $emailtouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2873
2874 $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found emailtouseforthirdparty='.dol_escape_htmltag($emailtouseforthirdparty);
2875 } elseif ($propertytooverwrite == 'name') {
2876 $nametouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2877
2878 $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found nametouseforthirdparty='.dol_escape_htmltag($nametouseforthirdparty);
2879 } elseif ($propertytooverwrite == 'name_alias') {
2880 $namealiastouseforthirdparty = isset($regforval[count($regforval) - 1]) ? trim($regforval[count($regforval) - 1]) : null;
2881
2882 $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Found namealiastouseforthirdparty='.dol_escape_htmltag($namealiastouseforthirdparty);
2883 } else {
2884 $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> We discard this, not a field used to search an existing thirdparty';
2885 }
2886 } else {
2887 // Regex not found
2888 if (in_array($propertytooverwrite, array('id', 'email', 'name', 'name_alias'))) {
2889 $idtouseforthirdparty = null;
2890 $nametouseforthirdparty = null;
2891 $emailtouseforthirdparty = null;
2892 $namealiastouseforthirdparty = null;
2893
2894 $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Not found. Property searched is critical so we cancel the search.';
2895 } else {
2896 $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' Regex /'.dol_escape_htmltag($regexstring).'/ms into '.strtoupper($sourcefield).' -> Not found';
2897 }
2898 }
2899 } else {
2900 // Nothing can be done for this param
2901 $errorforactions++;
2902 $this->error = 'The extract rule to use to load thirdparty for email '.$msgid.' has an unknown source (must be HEADER, SUBJECT or BODY)';
2903 $this->errors[] = $this->error;
2904
2905 $operationslog .= '<br>'.$this->error;
2906 }
2907 } elseif (preg_match('/^(SET|SETIFEMPTY):(.*)$/', $valueforproperty, $reg)) {
2908 //if (preg_match('/^options_/', $tmpproperty)) $object->array_options[preg_replace('/^options_/', '', $tmpproperty)] = $reg[1];
2909 //else $object->$tmpproperty = $reg[1];
2910 // Example: id=SETIFEMPTY:123
2911 if ($propertytooverwrite == 'id') {
2912 $idtouseforthirdparty = $reg[2];
2913
2914 $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property idtouseforthrdparty='.dol_escape_htmltag($idtouseforthirdparty);
2915 } elseif ($propertytooverwrite == 'email') {
2916 $emailtouseforthirdparty = $reg[2];
2917
2918 $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property emailtouseforthrdparty='.dol_escape_htmltag($emailtouseforthirdparty);
2919 } elseif ($propertytooverwrite == 'name') {
2920 $nametouseforthirdparty = $reg[2];
2921
2922 $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property nametouseforthirdparty='.dol_escape_htmltag($nametouseforthirdparty);
2923 } elseif ($propertytooverwrite == 'name_alias') {
2924 $namealiastouseforthirdparty = $reg[2];
2925
2926 $operationslog .= '<br>propertytooverwrite='.$propertytooverwrite.' We set property namealiastouseforthirdparty='.dol_escape_htmltag($namealiastouseforthirdparty);
2927 }
2928 } else {
2929 $errorforactions++;
2930 $this->error = 'Bad syntax for description of action parameters: '.$actionparam;
2931 $this->errors[] = $this->error;
2932 break;
2933 }
2934 }
2935
2936 if (!$errorforactions && ($idtouseforthirdparty || $emailtouseforthirdparty || $nametouseforthirdparty || $namealiastouseforthirdparty)) {
2937 // We make another search on thirdparty
2938 $operationslog .= '<br>We have this initial main data to search thirdparty: id='.$idtouseforthirdparty.', email='.$emailtouseforthirdparty.', name='.$nametouseforthirdparty.', name_alias='.$namealiastouseforthirdparty.'.';
2939
2940 $tmpobject = new stdClass();
2941 $tmpobject->element = 'generic';
2942 $tmpobject->id = $idtouseforthirdparty;
2943 $tmpobject->name = $nametouseforthirdparty;
2944 $tmpobject->name_alias = $namealiastouseforthirdparty;
2945 $tmpobject->email = $emailtouseforthirdparty;
2946
2947 $this->overwritePropertiesOfObject($tmpobject, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
2948
2949 $idtouseforthirdparty = $tmpobject->id;
2950 $nametouseforthirdparty = $tmpobject->name;
2951 $namealiastouseforthirdparty = $tmpobject->name_alias;
2952 $emailtouseforthirdparty = $tmpobject->email;
2953
2954 $operationslog .= '<br>We try to search existing thirdparty with idtouseforthirdparty='.$idtouseforthirdparty.' emailtouseforthirdparty='.$emailtouseforthirdparty.' nametouseforthirdparty='.$nametouseforthirdparty.' namealiastouseforthirdparty='.$namealiastouseforthirdparty;
2955
2956 // Try to find the thirdparty that match the most the information we have
2957 $result = $thirdpartystatic->findNearest((int) $idtouseforthirdparty, (string) $nametouseforthirdparty, '', '', '', '', '', '', '', '', (string) $emailtouseforthirdparty, (string) $namealiastouseforthirdparty);
2958
2959 if ($result < 0) {
2960 if (getDolGlobalInt('EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE') && $result == -2) { // If 2 thirdparty found, we will use a generic one defined by EMAILCOLLECTOR_USE_THIS_THIRDPARTYID_IF_DUPLICATE
2961 $idtouseforthirdparty = getDolGlobalInt('EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE');
2962
2963 $thirdpartystatic->fetch($idtouseforthirdparty);
2964
2965 dol_syslog('Thirdparty found twice (or more) so, according to option EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE, we will use the generic one with id = '.dol_escape_htmltag((string) $thirdpartystatic->id)." and name ".dol_escape_htmltag($thirdpartystatic->name));
2966
2967 $operationslog .= '<br>Thirdparty found twice (or more) so, according to option EMAILCOLLECTOR_USE_THIS_THIRDPARTY_ID_IF_DUPLICATE, we will use the generic one with id = '.dol_escape_htmltag((string) $thirdpartystatic->id)." and name ".dol_escape_htmltag($thirdpartystatic->name);
2968 } else {
2969 $errorforactions++;
2970 $this->error = 'Error when getting thirdparty with name '.((string) $nametouseforthirdparty).', alternative name '.((string) $namealiastouseforthirdparty).' and email '.$emailtouseforthirdparty.' (may be 2 record exists with same name ?)';
2971 $this->errors[] = $this->error;
2972 break;
2973 }
2974 }
2975 if ($result == 0) { // No thirdparty found
2976 if ($operation['type'] == 'loadthirdparty') {
2977 dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." name_alias=".$namealiastouseforthirdparty." was not found");
2978
2979 // Search into contacts of thirdparties to try to guess the thirdparty to use
2980 $resultContact = $contactstatic->findNearest(0, '', '', '', (string) $emailtouseforthirdparty, '', 0);
2981 if ($resultContact > 0) {
2982 $contactstatic->fetch($resultContact);
2983 $idtouseforthirdparty = $contactstatic->socid;
2984 $result = $thirdpartystatic->fetch($idtouseforthirdparty);
2985 if ($result > 0) {
2986 dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." name_alias=".$namealiastouseforthirdparty." was found thanks to linked contact search");
2987 } else {
2988 $errorforactions++;
2989 $langs->load("errors");
2990 $this->error = $langs->trans('ErrorFailedToLoadThirdParty', (string) $idtouseforthirdparty, (string) $emailtouseforthirdparty, (string) $nametouseforthirdparty, (string) $namealiastouseforthirdparty);
2991 $this->errors[] = $this->error;
2992 }
2993 } else {
2994 $errorforactions++;
2995 $langs->load("errors");
2996 $this->error = $langs->trans('ErrorFailedToLoadThirdParty', (string) $idtouseforthirdparty, (string) $emailtouseforthirdparty, (string) $nametouseforthirdparty, (string) $namealiastouseforthirdparty);
2997 $this->errors[] = $this->error;
2998 }
2999 } elseif ($operation['type'] == 'loadandcreatethirdparty') {
3000 dol_syslog("Third party with id=".$idtouseforthirdparty." email=".$emailtouseforthirdparty." name=".$nametouseforthirdparty." name_alias=".$namealiastouseforthirdparty." was not found. We try to create it.");
3001
3002 // Create thirdparty
3003 $thirdpartystatic = new Societe($db);
3004 $thirdpartystatic->name = (string) $nametouseforthirdparty;
3005 if (!empty($namealiastouseforthirdparty)) {
3006 if ($namealiastouseforthirdparty != $nametouseforthirdparty) {
3007 $thirdpartystatic->name_alias = $namealiastouseforthirdparty;
3008 }
3009 } else {
3010 $thirdpartystatic->name_alias = (empty($replytostring) ? (empty($fromtext) ? '' : $fromtext) : $replytostring);
3011 }
3012 $thirdpartystatic->email = (empty($emailtouseforthirdparty) ? (empty($replyto) ? (empty($email_from) ? '' : $email_from) : $replyto) : $emailtouseforthirdparty);
3013
3014 // Overwrite values with values extracted from source email
3015 $errorforthisaction = $this->overwritePropertiesOfObject($thirdpartystatic, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
3016
3017 if ($thirdpartystatic->client && empty($thirdpartystatic->code_client)) {
3018 $thirdpartystatic->code_client = 'auto';
3019 }
3020 if ($thirdpartystatic->fournisseur && empty($thirdpartystatic->code_fournisseur)) {
3021 $thirdpartystatic->code_fournisseur = 'auto';
3022 }
3023
3024 if ($errorforthisaction) {
3025 $errorforactions++;
3026 } else {
3027 $result = $thirdpartystatic->create($user);
3028 if ($result <= 0) {
3029 $errorforactions++;
3030 $this->error = $thirdpartystatic->error;
3031 $this->errors = $thirdpartystatic->errors;
3032 } else {
3033 $operationslog .= '<br>Thirdparty created -> id = '.dol_escape_htmltag((string) $thirdpartystatic->id);
3034 }
3035 }
3036 }
3037 } elseif ($result > 0) { // if $result > 0, it is ID of thirdparty
3038 dol_syslog("One and only one existing third party has been found");
3039
3040 $thirdpartystatic->fetch($result);
3041
3042 $operationslog .= '<br>Thirdparty already exists with id = '.dol_escape_htmltag((string) $thirdpartystatic->id)." and name ".dol_escape_htmltag($thirdpartystatic->name);
3043 }
3044 }
3045 }
3046 } elseif ($operation['type'] == 'loadandcreatecontact') { // Search and create contact
3047 if (empty($operation['actionparam'])) {
3048 $errorforactions++;
3049 $this->error = "Action loadandcreatecontact has empty parameter. Must be 'SET:xxx' or 'EXTRACT:(body|subject):regex' to define how to extract data";
3050 $this->errors[] = $this->error;
3051 } else {
3052 $contact_static = new Contact($this->db);
3053 // Overwrite values with values extracted from source email
3054 $errorforthisaction = $this->overwritePropertiesOfObject($contact_static, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
3055 if ($errorforthisaction) {
3056 $errorforactions++;
3057 } else {
3058 if (!empty($contact_static->email) && $contact_static->email != $email_from) {
3059 $email_from = $contact_static->email;
3060 }
3061 $email_from = (string) $email_from;
3062
3063 $email_from = (string) $email_from;
3064
3065 $result = $contactstatic->fetch(0, null, '', $email_from);
3066 if ($result < 0) {
3067 $errorforactions++;
3068 $this->error = 'Error when getting contact with email ' . $email_from;
3069 $this->errors[] = $this->error;
3070 break;
3071 } elseif ($result == 0) {
3072 dol_syslog("Contact with email " . $email_from . " was not found. We try to create it.");
3073 $contactstatic = new Contact($this->db);
3074
3075 // Create contact
3076 $contactstatic->email = $email_from;
3077 $operationslog .= '<br>We set property email='.dol_escape_htmltag($email_from);
3078
3079 // Overwrite values with values extracted from source email
3080 $errorforthisaction = $this->overwritePropertiesOfObject($contactstatic, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
3081
3082 if ($errorforthisaction) {
3083 $errorforactions++;
3084 } else {
3085 // Search country by name or code
3086 if (!empty($contactstatic->country)) {
3087 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
3088 $result = getCountry('', '3', $this->db, null, 1, $contactstatic->country);
3089 if ($result == 'NotDefined') {
3090 $errorforactions++;
3091 $this->error = "Error country not found by this name '" . $contactstatic->country . "'";
3092 } elseif (!($result > 0)) {
3093 $errorforactions++;
3094 $this->error = "Error when search country by this name '" . $contactstatic->country . "'";
3095 $this->errors[] = $this->db->lasterror();
3096 } else {
3097 $contactstatic->country_id = $result;
3098 $operationslog .= '<br>We set property country_id='.dol_escape_htmltag($result);
3099 }
3100 } elseif (!empty($contactstatic->country_code)) {
3101 require_once DOL_DOCUMENT_ROOT . '/core/lib/company.lib.php';
3102 $result = getCountry($contactstatic->country_code, '3', $this->db);
3103 if ($result == 'NotDefined') {
3104 $errorforactions++;
3105 $this->error = "Error country not found by this code '" . $contactstatic->country_code . "'";
3106 } elseif (!($result > 0)) {
3107 $errorforactions++;
3108 $this->error = "Error when search country by this code '" . $contactstatic->country_code . "'";
3109 $this->errors[] = $this->db->lasterror();
3110 } else {
3111 $contactstatic->country_id = $result;
3112 $operationslog .= '<br>We set property country_id='.dol_escape_htmltag($result);
3113 }
3114 }
3115
3116 if (!$errorforactions) {
3117 // Search state by name or code (for country if defined)
3118 if (!empty($contactstatic->state)) {
3119 $result = dol_getIdFromCode($this->db, $contactstatic->state, 'c_departements', 'nom', 'rowid');
3120 if (empty($result)) {
3121 $errorforactions++;
3122 $this->error = "Error state not found by this name '" . $contactstatic->state . "'";
3123 } elseif (!($result > 0)) {
3124 $errorforactions++;
3125 $this->error = "Error when search state by this name '" . $contactstatic->state . "'";
3126 $this->errors[] = $this->db->lasterror();
3127 } else {
3128 $contactstatic->state_id = $result;
3129 $operationslog .= '<br>We set property state_id='.dol_escape_htmltag($result);
3130 }
3131 } elseif (!empty($contactstatic->state_code)) {
3132 $result = dol_getIdFromCode($this->db, $contactstatic->state_code, 'c_departements', 'code_departement', 'rowid');
3133 if (empty($result)) {
3134 $errorforactions++;
3135 $this->error = "Error state not found by this code '" . $contactstatic->state_code . "'";
3136 } elseif (!($result > 0)) {
3137 $errorforactions++;
3138 $this->error = "Error when search state by this code '" . $contactstatic->state_code . "'";
3139 $this->errors[] = $this->db->lasterror();
3140 } else {
3141 $contactstatic->state_id = $result;
3142 $operationslog .= '<br>We set property state_id='.dol_escape_htmltag($result);
3143 }
3144 }
3145 }
3146
3147 if (!$errorforactions) {
3148 $result = $contactstatic->create($user);
3149 if ($result <= 0) {
3150 $errorforactions++;
3151 $this->error = $contactstatic->error;
3152 $this->errors = $contactstatic->errors;
3153 } else {
3154 $operationslog .= '<br>Contact created -> id = '.dol_escape_htmltag((string) $contactstatic->id);
3155 }
3156 }
3157 }
3158 }
3159 }
3160 }
3161 } elseif ($operation['type'] == 'recordevent') {
3162 // Create event
3163 $actioncomm = new ActionComm($this->db);
3164
3165 $alreadycreated = $actioncomm->fetch(0, '', '', $msgid);
3166 if ($alreadycreated == 0) {
3167 $operationslog .= '<br>We did not find existing actioncomm with msgid='.$msgid;
3168
3169 if ($projectstatic->id > 0) {
3170 if ($projectfoundby) {
3171 $descriptionmeta = dol_concatdesc($descriptionmeta, 'Project found from '.$projectfoundby);
3172 }
3173 }
3174 if ($thirdpartystatic->id > 0) {
3175 if ($thirdpartyfoundby) {
3176 $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
3177 }
3178 }
3179 if ($contactstatic->id > 0) {
3180 if ($contactfoundby) {
3181 $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
3182 }
3183 }
3184
3185 $description = $descriptiontitle;
3186
3187 $description = dol_concatdesc($description, $descriptionmeta);
3188 $description = dol_concatdesc($description, "-----");
3189 $description = dol_concatdesc($description, $messagetext);
3190
3191 $descriptionfull = $description;
3192 if (!getDolGlobalString('MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER')) {
3193 $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
3194 $descriptionfull = dol_concatdesc($descriptionfull, $header);
3195 }
3196
3197 // Insert record of emails sent
3198 $actioncomm->type_code = 'AC_OTH_AUTO'; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
3199 $actioncomm->code = 'AC_'.$actioncode;
3200 $actioncomm->label = $langs->trans("ActionAC_".$actioncode).' - '.$langs->trans("MailFrom").' '.$email_from;
3201 $actioncomm->note_private = $descriptionfull;
3202 $actioncomm->fk_project = $projectstatic->id;
3203 $actioncomm->datep = $dateemail; // date of email
3204 $actioncomm->datef = $dateemail; // date of email
3205 $actioncomm->percentage = -1; // Not applicable
3206 $actioncomm->socid = $thirdpartystatic->id;
3207 $actioncomm->contact_id = $contactstatic->id;
3208 $actioncomm->socpeopleassigned = (!empty($contactstatic->id) ? array($contactstatic->id) : array());
3209 $actioncomm->authorid = $user->id; // User saving action
3210 $actioncomm->userownerid = $user->id; // Owner of action
3211 // Fields when action is an email (content should be added into note)
3212 $actioncomm->email_msgid = $msgid;
3213 $actioncomm->email_from = $fromstring;
3214 $actioncomm->email_sender = $sender;
3215 $actioncomm->email_to = $to;
3216 $actioncomm->email_tocc = $sendtocc;
3217 $actioncomm->email_tobcc = $sendtobcc;
3218 $actioncomm->email_subject = $subject;
3219 $actioncomm->errors_to = '';
3220
3221 if (!in_array($fk_element_type, array('societe', 'contact', 'project', 'user'))) {
3222 $actioncomm->fk_element = $fk_element_id;
3223 $actioncomm->elementid = $fk_element_id;
3224 $actioncomm->elementtype = $fk_element_type;
3225 if (is_object($objectemail) && $objectemail->module) {
3226 $actioncomm->elementtype .= '@'.$objectemail->module;
3227 }
3228 }
3229
3230 //$actioncomm->extraparams = $extraparams;
3231
3232 // Overwrite values with values extracted from source email
3233 $errorforthisaction = $this->overwritePropertiesOfObject($actioncomm, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
3234
3235 if ($errorforthisaction) {
3236 $errorforactions++;
3237 } else {
3238 $result = $actioncomm->create($user);
3239 if ($result <= 0) {
3240 $errorforactions++;
3241 $this->errors = $actioncomm->errors;
3242 } else {
3243 if ($fk_element_type == "ticket" && is_object($objectemail)) {
3244 if ($objectemail->status == Ticket::STATUS_CLOSED || $objectemail->status == Ticket::STATUS_CANCELED || $objectemail->status == Ticket::STATUS_NEED_MORE_INFO || $objectemail->status == Ticket::STATUS_WAITING) {
3245 if ($objectemail->fk_user_assign != null) {
3246 $res = $objectemail->setStatut(Ticket::STATUS_ASSIGNED);
3247 } else {
3248 $res = $objectemail->setStatut(Ticket::STATUS_NOT_READ);
3249 }
3250
3251 if ($res) {
3252 $operationslog .= '<br>Ticket Re-Opened successfully -> ref='.$objectemail->ref;
3253 } else {
3254 $errorforactions++;
3255 $this->error = 'Error while changing the ticket status -> ref='.$objectemail->ref;
3256 $this->errors[] = $this->error;
3257 }
3258 }
3259 if (!empty($attachments)) {
3260 // There is an attachment for the ticket -> store attachment
3261 $ticket = new Ticket($this->db);
3262 $ticket->fetch($fk_element_id);
3263 $destdir = $conf->ticket->dir_output.'/'.$ticket->ref;
3264 if (!dol_is_dir($destdir)) {
3265 dol_mkdir($destdir);
3266 }
3267 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
3268 $skippedatt = 0;
3269 foreach ($attachments as $attachment) {
3270 try {
3271 $filename = (string) $attachment->getName();
3272 } catch (Throwable $e) {
3273 $filename = '';
3274 }
3275 if (!$this->isAllowedAttachmentFilename($filename)) {
3276 $skippedatt++;
3277 continue;
3278 }
3279 $this->saveAttachment($destdir, $filename, (string) $attachment->getContent());
3280 }
3281 if ($skippedatt > 0) {
3282 $operationslog .= '<br>Skipped '.$skippedatt.' attachment(s) due to allowed extensions filter';
3283 }
3284 } else {
3285 $this->getmsg($connection, $imapemail, $destdir);
3286 }
3287 }
3288 }
3289
3290 $operationslog .= '<br>Event created -> id='.dol_escape_htmltag((string) $actioncomm->id);
3291 }
3292 }
3293 } else {
3294 $operationslog .= '<br>An event in actioncomm table already exists for the msgid = '.$msgid.' so we bypass this action.';
3295 }
3296 } elseif ($operation['type'] == 'recordjoinpiece') {
3297 $data = [];
3298 $skippedatt = 0;
3299 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
3300 foreach ($attachments as $attachment) {
3301 try {
3302 $filename = (string) $attachment->getName();
3303 } catch (Throwable $e) {
3304 $filename = '';
3305 }
3306 if (!$this->isAllowedAttachmentFilename($filename)) {
3307 $skippedatt++;
3308 continue;
3309 }
3310 $data[$filename] = $attachment->getContent();
3311 }
3312 } else {
3313 $pj = getAttachments($imapemail, $connection);
3314 foreach ($pj as $key => $val) {
3315 if (!$this->isAllowedAttachmentFilename((string) $val['filename'])) {
3316 $skippedatt++;
3317 continue;
3318 }
3319 $data[$val['filename']] = getFileData($imapemail, (string) $val['pos'], $val['type'], $connection);
3320 }
3321 }
3322 if ($skippedatt > 0) {
3323 $operationslog .= '<br>Skipped '.$skippedatt.' attachment(s) due to allowed extensions filter';
3324 }
3325 if (count($data) > 0) {
3326 $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."user WHERE email LIKE '%".$this->db->escape($email_from)."%'";
3327 $resql = $this->db->query($sql);
3328 if ($this->db->num_rows($resql) == 0) {
3329 $this->errors[] = "User Not allowed to add documents ({$email_from})";
3330 }
3331 $arrayobject = array(
3332 'propale' => array('table' => 'propal',
3333 'fields' => array('ref'),
3334 'class' => 'comm/propal/class/propal.class.php',
3335 'object' => 'Propal'),
3336 'holiday' => array('table' => 'holiday',
3337 'fields' => array('ref'),
3338 'class' => 'holiday/class/holiday.class.php',
3339 'object' => 'Holiday'),
3340 'expensereport' => array('table' => 'expensereport',
3341 'fields' => array('ref'),
3342 'class' => 'expensereport/class/expensereport.class.php',
3343 'object' => 'ExpenseReport'),
3344 'recruitment/recruitmentjobposition' => array('table' => 'recruitment_recruitmentjobposition',
3345 'fields' => array('ref'),
3346 'class' => 'recruitment/class/recruitmentjobposition.class.php',
3347 'object' => 'RecruitmentJobPosition'),
3348 'recruitment/recruitmentcandidature' => array('table' => 'recruitment_recruitmentcandidature',
3349 'fields' => array('ref'),
3350 'class' => 'recruitment/class/recruitmentcandidature.class.php',
3351 'object' => 'RecruitmentCandidature'),
3352 'societe' => array('table' => 'societe',
3353 'fields' => array('code_client', 'code_fournisseur'),
3354 'class' => 'societe/class/societe.class.php',
3355 'object' => 'Societe'),
3356 'commande' => array('table' => 'commande',
3357 'fields' => array('ref'),
3358 'class' => 'commande/class/commande.class.php',
3359 'object' => 'Commande'),
3360 'expedition' => array('table' => 'expedition',
3361 'fields' => array('ref'),
3362 'class' => 'expedition/class/expedition.class.php',
3363 'object' => 'Expedition'),
3364 'contract' => array('table' => 'contrat',
3365 'fields' => array('ref'),
3366 'class' => 'contrat/class/contrat.class.php',
3367 'object' => 'Contrat'),
3368 'fichinter' => array('table' => 'fichinter',
3369 'fields' => array('ref'),
3370 'class' => 'fichinter/class/fichinter.class.php',
3371 'object' => 'Fichinter'),
3372 'ticket' => array('table' => 'ticket',
3373 'fields' => array('ref'),
3374 'class' => 'ticket/class/ticket.class.php',
3375 'object' => 'Ticket'),
3376 'knowledgemanagement' => array('table' => 'knowledgemanagement_knowledgerecord',
3377 'fields' => array('ref'),
3378 'class' => 'knowledgemanagement/class/knowledgemanagement.class.php',
3379 'object' => 'KnowledgeRecord'),
3380 'supplier_proposal' => array('table' => 'supplier_proposal',
3381 'fields' => array('ref'),
3382 'class' => 'supplier_proposal/class/supplier_proposal.class.php',
3383 'object' => 'SupplierProposal'),
3384 'fournisseur/commande' => array('table' => 'commande_fournisseur',
3385 'fields' => array('ref', 'ref_supplier'),
3386 'class' => 'fourn/class/fournisseur.commande.class.php',
3387 'object' => 'SupplierProposal'),
3388 'facture' => array('table' => 'facture',
3389 'fields' => array('ref'),
3390 'class' => 'compta/facture/class/facture.class.php',
3391 'object' => 'Facture'),
3392 'fournisseur/facture' => array('table' => 'facture_fourn',
3393 'fields' => array('ref', 'ref_client'),
3394 'class' => 'fourn/class/fournisseur.facture.class.php',
3395 'object' => 'FactureFournisseur'),
3396 'produit' => array('table' => 'product',
3397 'fields' => array('ref'),
3398 'class' => 'product/class/product.class.php',
3399 'object' => 'Product'),
3400 'productlot' => array('table' => 'product_lot',
3401 'fields' => array('batch'),
3402 'class' => 'product/stock/class/productlot.class.php',
3403 'object' => 'Productlot'),
3404 'projet' => array('table' => 'projet',
3405 'fields' => array('ref'),
3406 'class' => 'projet/class/projet.class.php',
3407 'object' => 'Project'),
3408 'projet_task' => array('table' => 'projet_task',
3409 'fields' => array('ref'),
3410 'class' => 'projet/class/task.class.php',
3411 'object' => 'Task'),
3412 'ressource' => array('table' => 'resource',
3413 'fields' => array('ref'),
3414 'class' => 'ressource/class/dolressource.class.php',
3415 'object' => 'Dolresource'),
3416 'bom' => array('table' => 'bom_bom',
3417 'fields' => array('ref'),
3418 'class' => 'bom/class/bom.class.php',
3419 'object' => 'BOM'),
3420 'mrp' => array('table' => 'mrp_mo',
3421 'fields' => array('ref'),
3422 'class' => 'mrp/class/mo.class.php',
3423 'object' => 'Mo'),
3424 );
3425
3426 if (!is_object($hookmanager)) {
3427 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
3428 $hookmanager = new HookManager($this->db);
3429 }
3430 $hookmanager->initHooks(array('emailcolector', 'emailcollector'));
3431 $parameters = array('arrayobject' => $arrayobject);
3432 $reshook = $hookmanager->executeHooks('addmoduletoeamailcollectorjoinpiece', $parameters); // Note that $action and $object may have been modified by some hooks
3433 if ($reshook > 0) {
3434 $arrayobject = $hookmanager->resArray;
3435 }
3436
3437 $resultobj = array();
3438
3439 foreach ($arrayobject as $key => $objectdesc) {
3440 $sql = 'SELECT DISTINCT t.rowid ';
3441 $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->db->sanitize($objectdesc['table']) . ' AS t';
3442 $sql .= ' WHERE ';
3443 foreach ($objectdesc['fields'] as $field) {
3444 $sql .= "('" .$this->db->escape($subject) . "' LIKE CONCAT('%', t." . $this->db->sanitize($field) . ", '%') AND t." . $this->db->sanitize($field) . " <> '') OR ";
3445 }
3446 $sql = substr($sql, 0, -4);
3447
3448 $ressqlobj = $this->db->query($sql);
3449 if ($ressqlobj) {
3450 while ($obj = $this->db->fetch_object($ressqlobj)) {
3451 $resultobj[$key][] = $obj->rowid;
3452 }
3453 }
3454 }
3455 $dirs = array();
3456 foreach ($resultobj as $mod => $ids) {
3457 $moddesc = $arrayobject[$mod];
3458 $elementpath = $mod;
3459 dol_include_once($moddesc['class']);
3460 $objectmanaged = new $moddesc['object']($this->db);
3461 '@phan-var-force CommonObject $objectmanaged';
3462 foreach ($ids as $val) {
3463 $res = $objectmanaged->fetch($val);
3464 if ($res) {
3465 $path = ($objectmanaged->entity > 1 ? "/" . $objectmanaged->entity : '');
3466 $dirs[] = DOL_DATA_ROOT . $path . "/" . $elementpath . '/' . dol_sanitizeFileName($objectmanaged->ref) . '/';
3467 } else {
3468 $this->errors[] = 'object not found';
3469 }
3470 }
3471 }
3472 foreach ($dirs as $target) {
3473 $prefix = $this->actions[$this->id]['actionparam'];
3474 foreach ($data as $filename => $content) {
3475 $resr = $this->saveAttachment($target, $prefix . '_' . $filename, $content);
3476 if ($resr == -1) {
3477 $this->errors[] = 'Doc not saved';
3478 }
3479 }
3480 }
3481
3482 $operationslog .= '<br>Save attachment files on disk';
3483 } else {
3484 $this->errors[] = 'no joined piece';
3485
3486 $operationslog .= '<br>No joinded files';
3487 }
3488 } elseif ($operation['type'] == 'project') {
3489 // Create project / lead
3490 $projecttocreate = new Project($this->db);
3491 $alreadycreated = $projecttocreate->fetch(0, '', '', $msgid);
3492 if ($alreadycreated == 0) {
3493 if ($thirdpartystatic->id > 0) {
3494 $projecttocreate->socid = $thirdpartystatic->id;
3495 if ($thirdpartyfoundby) {
3496 $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
3497 }
3498 }
3499 if ($contactstatic->id > 0) {
3500 $projecttocreate->contact_id = $contactstatic->id;
3501 if ($contactfoundby) {
3502 $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
3503 }
3504 }
3505
3506 $description = $descriptiontitle;
3507
3508 $description = dol_concatdesc($description, $descriptionmeta);
3509 $description = dol_concatdesc($description, "-----");
3510 $description = dol_concatdesc($description, $messagetext);
3511
3512 $descriptionfull = $description;
3513 if (!getDolGlobalString('MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER')) {
3514 $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
3515 $descriptionfull = dol_concatdesc($descriptionfull, $header);
3516 }
3517
3518 $id_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'rowid');
3519 $percent_opp_status = dol_getIdFromCode($this->db, 'PROSP', 'c_lead_status', 'code', 'percent');
3520
3521 $projecttocreate->title = $subject;
3522 $projecttocreate->date_start = $dateemail; // date of email
3523 $projecttocreate->date_end = 0;
3524 $projecttocreate->opp_status = $id_opp_status;
3525 $projecttocreate->opp_percent = $percent_opp_status;
3526 $projecttocreate->description = dol_concatdesc(dolGetFirstLineOfText(dol_string_nohtmltag($description, 2), 10), '...'.$langs->transnoentities("SeePrivateNote").'...');
3527 $projecttocreate->note_private = $descriptionfull;
3528 $projecttocreate->entity = $conf->entity;
3529 // Fields when action is an email (content should be added into agenda event)
3530 $projecttocreate->email_date = $dateemail;
3531 $projecttocreate->email_msgid = $msgid;
3532 $projecttocreate->email_from = $fromstring;
3533 $projecttocreate->email_sender = $sender;
3534 $projecttocreate->email_to = $to;
3535 $projecttocreate->email_tocc = $sendtocc;
3536 $projecttocreate->email_tobcc = $sendtobcc;
3537 $projecttocreate->email_subject = $subject;
3538 $projecttocreate->errors_to = '';
3539
3540 $savesocid = $projecttocreate->socid;
3541
3542 // Overwrite values with values extracted from source email.
3543 // This may overwrite any $projecttocreate->xxx properties.
3544 $errorforthisaction = $this->overwritePropertiesOfObject($projecttocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
3545 $modele = null;
3546
3547 // Set project ref if not yet defined
3548 if (empty($projecttocreate->ref)) {
3549 // Get next Ref
3550 $defaultref = '';
3551 $modele = getDolGlobalString('PROJECT_ADDON', 'mod_project_simple');
3552
3553 // Search template files
3554 $file = '';
3555 $classname = '';
3556 $reldir = '';
3557 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
3558 foreach ($dirmodels as $reldir) {
3559 $file = dol_buildpath($reldir."core/modules/project/".$modele.'.php', 0);
3560 if (file_exists($file)) {
3561 $classname = $modele;
3562 break;
3563 }
3564 }
3565
3566 if ($classname !== '') {
3567 if ($savesocid > 0) {
3568 if ($savesocid != $projecttocreate->socid) {
3569 $errorforactions++;
3570 $this->error = 'You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$projecttocreate->socid.') by setting socid in operation with a different value';
3571 $this->errors[] = $this->error;
3572 }
3573 } else {
3574 if ($projecttocreate->socid > 0) {
3575 $thirdpartystatic->fetch($projecttocreate->socid);
3576 }
3577 }
3578
3579 $result = dol_include_once($reldir."core/modules/project/".$modele.'.php');
3580 $modModuleToUseForNextValue = new $classname();
3581 '@phan-var-force ModeleNumRefProjects $modModuleToUseForNextValue';
3582 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $projecttocreate);
3583 }
3584 $projecttocreate->ref = $defaultref;
3585 }
3586
3587
3588 if ($errorforthisaction) {
3589 $errorforactions++;
3590 } else {
3591 if (empty($projecttocreate->ref) || (is_numeric($projecttocreate->ref) && $projecttocreate->ref <= 0)) {
3592 $errorforactions++;
3593 $this->error = 'Failed to create project: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id;
3594
3595 $operationslog .= '<br>'.$this->error;
3596 } else {
3597 // Create project
3598 $result = $projecttocreate->create($user);
3599 if ($result <= 0) {
3600 $errorforactions++;
3601 $this->error = 'Failed to create project: '.$langs->trans($projecttocreate->error);
3602 $this->errors = $projecttocreate->errors;
3603
3604 $operationslog .= '<br>'.$this->error;
3605 } else {
3606 if ($attachments) {
3607 $destdir = $conf->project->dir_output.'/'.$projecttocreate->ref;
3608 if (!dol_is_dir($destdir)) {
3609 dol_mkdir($destdir);
3610 }
3611 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
3612 $skippedatt = 0;
3613 foreach ($attachments as $attachment) {
3614 // $attachment->save($destdir.'/');
3615 $filename = $attachment->getFilename();
3616 if (!$this->isAllowedAttachmentFilename((string) $filename)) {
3617 $skippedatt++;
3618 continue;
3619 }
3620 $content = $attachment->getContent();
3621 $this->saveAttachment($destdir, $filename, $content);
3622 }
3623 if ($skippedatt > 0) {
3624 $operationslog .= '<br>Skipped '.$skippedatt.' attachment(s) due to allowed extensions filter';
3625 }
3626 } else {
3627 $getMsg = $this->getmsg($connection, $imapemail, $destdir);
3628 if ($getMsg < 0) {
3629 $this->errors = array_merge($this->errors, [$this->error]);
3630 return $getMsg;
3631 }
3632 }
3633
3634 $operationslog .= '<br>Project created with attachments -> id='.dol_escape_htmltag((string) $projecttocreate->id);
3635 } else {
3636 $operationslog .= '<br>Project created without attachments -> id='.dol_escape_htmltag((string) $projecttocreate->id);
3637 }
3638 }
3639 }
3640 }
3641 } else {
3642 dol_syslog("Project already exists for msgid = ".dol_escape_htmltag($msgid).", so we do not recreate it.");
3643
3644 $operationslog .= '<br>Project already exists for msgid ='.dol_escape_htmltag($msgid);
3645 }
3646 } elseif ($operation['type'] == 'ticket') {
3647 // Create ticket
3648 $tickettocreate = new Ticket($this->db);
3649 if ($ticketalreadyexists == 0) {
3650 if ($thirdpartystatic->id > 0) {
3651 $tickettocreate->socid = $thirdpartystatic->id;
3652 $tickettocreate->fk_soc = $thirdpartystatic->id;
3653 if ($thirdpartyfoundby) {
3654 $descriptionmeta = dol_concatdesc($descriptionmeta, 'Third party found from '.$thirdpartyfoundby);
3655 }
3656 }
3657 if ($contactstatic->id > 0) {
3658 $tickettocreate->contact_id = $contactstatic->id;
3659 if ($contactfoundby) {
3660 $descriptionmeta = dol_concatdesc($descriptionmeta, 'Contact/address found from '.$contactfoundby);
3661 }
3662 }
3663
3664 $description = $descriptiontitle;
3665
3666 $description = dol_concatdesc($description, $descriptionmeta);
3667 $description = dol_concatdesc($description, "-----");
3668 $description = dol_concatdesc($description, $messagetext);
3669
3670 $descriptionfull = $description;
3671 if (!getDolGlobalString('MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER')) {
3672 $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
3673 $descriptionfull = dol_concatdesc($descriptionfull, $header);
3674 }
3675
3676 $tickettocreate->subject = $subject;
3677 $tickettocreate->message = $description;
3678 $tickettocreate->type_code = (getDolGlobalString('MAIN_EMAILCOLLECTOR_TICKET_TYPE_CODE', dol_getIdFromCode($this->db, 1, 'c_ticket_type', 'use_default', 'code', 1)));
3679 $tickettocreate->category_code = (getDolGlobalString('MAIN_EMAILCOLLECTOR_TICKET_CATEGORY_CODE', dol_getIdFromCode($this->db, 1, 'c_ticket_category', 'use_default', 'code', 1)));
3680 $tickettocreate->severity_code = (getDolGlobalString('MAIN_EMAILCOLLECTOR_TICKET_SEVERITY_CODE', dol_getIdFromCode($this->db, 1, 'c_ticket_severity', 'use_default', 'code', 1)));
3681 $tickettocreate->origin_email = $email_from;
3682 $tickettocreate->origin_replyto = (!empty($replyto) ? $replyto : null);
3683 $tickettocreate->origin_references = (!empty($headers['References']) ? $headers['References'] : null);
3684 $tickettocreate->fk_user_create = $user->id;
3685 $tickettocreate->datec = dol_now();
3686 $tickettocreate->fk_project = $projectstatic->id;
3687 $tickettocreate->notify_tiers_at_create = getDolGlobalInt('TICKET_CHECK_NOTIFY_THIRDPARTY_AT_CREATION');
3688 $tickettocreate->note_private = $descriptionfull;
3689 $tickettocreate->entity = $conf->entity;
3690 // Fields when action is an email (content should be added into agenda event)
3691 $tickettocreate->email_date = $dateemail;
3692 $tickettocreate->email_msgid = $msgid;
3693 $tickettocreate->email_from = $fromstring;
3694 $tickettocreate->email_sender = $sender;
3695 $tickettocreate->email_to = $to;
3696 $tickettocreate->email_tocc = $sendtocc;
3697 $tickettocreate->email_tobcc = $sendtobcc;
3698 $tickettocreate->email_subject = $subject;
3699 $tickettocreate->errors_to = '';
3700
3701 //$tickettocreate->fk_contact = $contactstatic->id;
3702
3703 $savesocid = $tickettocreate->socid;
3704
3705 // Overwrite values with values extracted from source email.
3706 // This may overwrite any $projecttocreate->xxx properties.
3707 $errorforthisaction = $this->overwritePropertiesOfObject($tickettocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
3708
3709 $modele = 'UNDEFINED';
3710 // Set ticket ref if not yet defined
3711 if (empty($tickettocreate->ref)) {
3712 // Get next Ref
3713 $defaultref = '';
3714 $modele = getDolGlobalString('TICKET_ADDON', 'mod_ticket_simple');
3715
3716 // Search template files
3717 $file = '';
3718 $classname = '';
3719 $reldir = '';
3720 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
3721 foreach ($dirmodels as $reldir) {
3722 $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
3723 if (file_exists($file)) {
3724 $classname = $modele;
3725 break;
3726 }
3727 }
3728
3729 if ($classname !== '') {
3730 if ($savesocid > 0) {
3731 if ($savesocid != $tickettocreate->socid) {
3732 $errorforactions++;
3733 $this->error = 'You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$tickettocreate->socid.') by setting socid in operation with a different value';
3734 $this->errors[] = $this->error;
3735 }
3736 } else {
3737 if ($tickettocreate->socid > 0) {
3738 $thirdpartystatic->fetch($tickettocreate->socid);
3739 }
3740 }
3741
3742 $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
3743 $modModuleToUseForNextValue = new $classname();
3744 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3745 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3746 }
3747 $tickettocreate->ref = $defaultref;
3748 }
3749
3750 if ($errorforthisaction) {
3751 $errorforactions++;
3752 } else {
3753 if (is_numeric($tickettocreate->ref) && $tickettocreate->ref <= 0) {
3754 $errorforactions++;
3755 $this->error = 'Failed to create ticket: Can\'t get a valid value for the field ref with numbering template = '.$modele.', thirdparty id = '.$thirdpartystatic->id;
3756 } else {
3757 // Create ticket
3758 $tickettocreate->context['actionmsg2'] = $langs->trans("ActionAC_EMAIL_IN").' - '.$langs->trans("TICKET_CREATEInDolibarr");
3759 $tickettocreate->context['actionmsg'] = $langs->trans("ActionAC_EMAIL_IN").' - '.$langs->trans("TICKET_CREATEInDolibarr");
3760 //$tickettocreate->email_fields_no_propagate_in_actioncomm = 0;
3761
3762 // Add sender to context array to make sure that confirmation e-mail can be sent by trigger script
3763 $sender_contact = new Contact($this->db);
3764 $sender_contact->fetch(0, null, '', $email_from);
3765 if (!empty($sender_contact->id)) {
3766 $tickettocreate->context['contact_id'] = $sender_contact->id;
3767 }
3768
3769 $result = $tickettocreate->create($user);
3770 if ($result <= 0) {
3771 $errorforactions++;
3772 $this->error = 'Failed to create ticket: '.$langs->trans($tickettocreate->error);
3773 $this->errors = $tickettocreate->errors;
3774 } else {
3775 if ($attachments) {
3776 $destdir = $conf->ticket->dir_output.'/'.$tickettocreate->ref;
3777 if (!dol_is_dir($destdir)) {
3778 dol_mkdir($destdir);
3779 }
3780 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
3781 $skippedatt = 0;
3782 foreach ($attachments as $attachment) {
3783 // $attachment->save($destdir.'/');
3784 $filename = $attachment->getName();
3785 if (!$this->isAllowedAttachmentFilename((string) $filename)) {
3786 $skippedatt++;
3787 continue;
3788 }
3789 $content = $attachment->getContent();
3790 $this->saveAttachment($destdir, $filename, $content);
3791 }
3792 if ($skippedatt > 0) {
3793 $operationslog .= '<br>Skipped '.$skippedatt.' attachment(s) due to allowed extensions filter';
3794 }
3795 } else {
3796 $getMsg = $this->getmsg($connection, $imapemail, $destdir);
3797 if ($getMsg < 0) {
3798 $this->errors = array_merge($this->errors, [$this->error]);
3799 return $getMsg;
3800 }
3801 }
3802
3803 $operationslog .= '<br>Ticket created with attachments -> id='.dol_escape_htmltag((string) $tickettocreate->id);
3804 } else {
3805 $operationslog .= '<br>Ticket created without attachments -> id='.dol_escape_htmltag((string) $tickettocreate->id);
3806 }
3807 }
3808 }
3809 }
3810 } else {
3811 // Do nothing in action ticket if ticket already exists.
3812 // Note that if we want to add a new event to a ticket, we should have a collector with action "Record event in agenda" or hope the type of action 'ticket' was
3813 // already replaced automatically by operation "recordevent".
3814 $operationslog .= '<br>Ticket already exists, so we bypass action "ticket"';
3815 }
3816 } elseif ($operation['type'] == 'candidature') {
3817 // Create candidature
3818 $candidaturetocreate = new RecruitmentCandidature($this->db);
3819
3820 $alreadycreated = $candidaturetocreate->fetch(0, '', $msgid);
3821 if ($alreadycreated == 0) {
3822 $description = $descriptiontitle;
3823 $description = dol_concatdesc($description, "-----");
3824 $description = dol_concatdesc($description, $descriptionmeta);
3825 $description = dol_concatdesc($description, "-----");
3826 $description = dol_concatdesc($description, $messagetext);
3827
3828 $descriptionfull = $description;
3829 if (!getDolGlobalString('MAIN_EMAILCOLLECTOR_MAIL_WITHOUT_HEADER')) {
3830 $descriptionfull = dol_concatdesc($descriptionfull, "----- Header");
3831 $descriptionfull = dol_concatdesc($descriptionfull, $header);
3832 }
3833
3834 $candidaturetocreate->subject = $subject;
3835 $candidaturetocreate->message = $description;
3836 $candidaturetocreate->type_code = 0;
3837 $candidaturetocreate->category_code = null;
3838 $candidaturetocreate->severity_code = null;
3839 $candidaturetocreate->email = $email_from;
3840 //$candidaturetocreate->lastname = $langs->trans("Anonymous").' - '.$email_from;
3841 $candidaturetocreate->fk_user_creat = $user->id;
3842 $candidaturetocreate->date_creation = dol_now();
3843 $candidaturetocreate->fk_project = $projectstatic->id;
3844 $candidaturetocreate->description = $description;
3845 $candidaturetocreate->note_private = $descriptionfull;
3846 $candidaturetocreate->entity = $conf->entity;
3847 $candidaturetocreate->email_msgid = $msgid;
3848 $candidaturetocreate->email_date = $dateemail; // date of email
3849 $candidaturetocreate->status = $candidaturetocreate::STATUS_DRAFT;
3850 //$candidaturetocreate->fk_contact = $contactstatic->id;
3851
3852 // Overwrite values with values extracted from source email.
3853 // This may overwrite any $projecttocreate->xxx properties.
3854 $errorforthisaction = $this->overwritePropertiesOfObject($candidaturetocreate, $operation['actionparam'], $messagetext, $subject, $header, $operationslog);
3855
3856 // Set candidature ref if not yet defined
3857 /*if (empty($candidaturetocreate->ref)) We do not need this because we create object in draft status
3858 {
3859 // Get next Ref
3860 $defaultref = '';
3861 $modele = empty($conf->global->CANDIDATURE_ADDON) ? 'mod_candidature_simple' : $conf->global->CANDIDATURE_ADDON;
3862
3863 // Search template files
3864 $file = ''; $classname = ''; $filefound = 0; $reldir = '';
3865 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
3866 foreach ($dirmodels as $reldir)
3867 {
3868 $file = dol_buildpath($reldir."core/modules/ticket/".$modele.'.php', 0);
3869 if (file_exists($file)) {
3870 $filefound = 1;
3871 $classname = $modele;
3872 break;
3873 }
3874 }
3875
3876 if ($filefound) {
3877 if ($savesocid > 0) {
3878 if ($savesocid != $candidaturetocreate->socid) {
3879 $errorforactions++;
3880 $this->error = 'You loaded a thirdparty (id='.$savesocid.') and you force another thirdparty id (id='.$candidaturetocreate->socid.') by setting socid in operation with a different value';
3881 $this->errors[] = $this->error;
3882 }
3883 } else {
3884 if ($candidaturetocreate->socid > 0)
3885 {
3886 $thirdpartystatic->fetch($candidaturetocreate->socid);
3887 }
3888 }
3889
3890 $result = dol_include_once($reldir."core/modules/ticket/".$modele.'.php');
3891 $modModuleToUseForNextValue = new $classname;
3892 '@phan-var-force ModeleNumRefTicket $modModuleToUseForNextValue';
3893 $defaultref = $modModuleToUseForNextValue->getNextValue(($thirdpartystatic->id > 0 ? $thirdpartystatic : null), $tickettocreate);
3894 }
3895 $candidaturetocreate->ref = $defaultref;
3896 }*/
3897
3898 if ($errorforthisaction) {
3899 $errorforactions++;
3900 } else {
3901 // Create project
3902 $result = $candidaturetocreate->create($user);
3903 if ($result <= 0) {
3904 $errorforactions++;
3905 $this->error = 'Failed to create candidature: '.implode(', ', $candidaturetocreate->errors);
3906 $this->errors = $candidaturetocreate->errors;
3907 }
3908
3909 $operationslog .= '<br>Candidature created without attachments -> id='.dol_escape_htmltag((string) $candidaturetocreate->id);
3910 }
3911 }
3912 } elseif (substr($operation['type'], 0, 4) == 'hook') {
3913 // Create event specific on hook
3914 // this code action is hook..... for support this call
3915 if (!is_object($hookmanager)) {
3916 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
3917 $hookmanager = new HookManager($this->db);
3918 }
3919 $hookmanager->initHooks(array('emailcolector', 'emailcollector'));
3920
3921 $parameters = array(
3922 'connection' => $connection,
3923 'imapemail' => $imapemail,
3924 'overview' => $overview,
3925
3926 'from' => $email_from,
3927 'fromtext' => $fromtext,
3928
3929 'actionparam' => $operation['actionparam'],
3930
3931 'thirdpartyid' => ($thirdpartyid ? $thirdpartyid : $thirdpartystatic->id),
3932 'objectid' => $objectid,
3933 'objectemail' => $objectemail,
3934
3935 'messagetext' => $messagetext,
3936 'subject' => $subject,
3937 'header' => $header,
3938 'attachments' => $attachments,
3939 'savedattachments' => $savedattachments,
3940 'savedattachmentsdir' => $savedattachmentsdir,
3941 );
3942 $reshook = $hookmanager->executeHooks('doCollectImapOneCollector', $parameters, $this, $operation['type']);
3943
3944 if ($reshook < 0) {
3945 $errorforthisaction++;
3946 $this->error = $hookmanager->resPrint;
3947 if (!empty($hookmanager->resPrint)) {
3948 $operationslog .= '<br>Hook error: '.dol_escape_htmltag($hookmanager->resPrint);
3949 }
3950 }
3951 if ($errorforthisaction) {
3952 $errorforactions++;
3953 $operationslog .= '<br>Hook doCollectImapOneCollector executed with error';
3954 } else {
3955 $operationslog .= '<br>Hook doCollectImapOneCollector executed without error';
3956 }
3957 }
3958
3959 if (!$errorforactions) {
3960 $nbactiondoneforemail++;
3961 }
3962 }
3963 }
3964
3965 // Error for email or not ?
3966 if (!$errorforactions) {
3967 if (!empty($targetdir)) {
3968 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
3969 // Move mail using PHP-IMAP
3970 dol_syslog("EmailCollector::doCollectOneCollector move message ".($imapemail->getHeader()->get('subject'))." to ".$targetdir, LOG_DEBUG);
3971 $operationslog .= '<br>Move mail '.($this->uidAsString($imapemail)).' - '.$msgid.' - '.$imapemail->getHeader()->get('subject').' to '.$targetdir;
3972
3973 $arrayofemailtodelete[$this->uidAsString($imapemail)] = $imapemail;
3974 // Note: Real move is done later using $arrayofemailtodelete
3975 } else {
3976 dol_syslog("EmailCollector::doCollectOneCollector move message ".($this->uidAsString($imapemail))." to ".$connectstringtarget, LOG_DEBUG);
3977 $operationslog .= '<br>Move mail '.($this->uidAsString($imapemail)).' - '.$msgid;
3978
3979 $arrayofemailtodelete[$imapemail] = $msgid;
3980 // Note: Real move is done later using $arrayofemailtodelete
3981 }
3982 } else {
3983 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
3984 dol_syslog("EmailCollector::doCollectOneCollector message ".($this->uidAsString($imapemail))." '".($imapemail->getHeader()->get('subject'))."' using this->host=".$this->host.", this->access_type=".$this->acces_type." was set to read", LOG_DEBUG);
3985 } else {
3986 dol_syslog("EmailCollector::doCollectOneCollector message ".($this->uidAsString($imapemail))." to ".$connectstringtarget." was set to read", LOG_DEBUG);
3987 }
3988 }
3989 } else {
3990 $errorforemail++;
3991 }
3992
3993
3994 unset($objectemail);
3995 unset($projectstatic);
3996 unset($thirdpartystatic);
3997 unset($contactstatic);
3998
3999 $nbemailprocessed++;
4000
4001 if (!$errorforemail) {
4002 $nbactiondone += $nbactiondoneforemail;
4003 $nbemailok++;
4004
4005 if (empty($mode)) {
4006 $this->db->commit();
4007 } else {
4008 $this->db->rollback();
4009 }
4010
4011 // Stop the loop to process email if we reach maximum collected per collect
4012 if ($this->maxemailpercollect > 0 && $nbemailok >= $this->maxemailpercollect) {
4013 dol_syslog("EmailCollect::doCollectOneCollector We reach maximum of ".$nbemailok." collected with success, so we stop this collector now.");
4014 $datelastok = strtotime($headers['Date']); // Set datetime
4015 break;
4016 }
4017 } else {
4018 $error++;
4019
4020 $this->db->rollback();
4021 }
4022 }
4023
4024 $output = $langs->trans('XEmailsDoneYActionsDone', $nbemailprocessed, $nbemailok, $nbactiondone);
4025
4026 dol_syslog("End of loop on emails", LOG_INFO, -1);
4027 } else {
4028 $langs->load("admin");
4029 $output = $langs->trans('NoNewEmailToProcess');
4030 $output .= ' (defaultlang='.$langs->defaultlang.')';
4031 }
4032
4033 // Disconnect
4034 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
4035 // We sort to move/delete array with the more recent first (with higher number) so renumbering does not affect number of others to delete
4036 krsort($arrayofemailtodelete, SORT_NUMERIC);
4037
4038 foreach ($arrayofemailtodelete as $imapemailnum => $imapemail) {
4039 dol_syslog("EmailCollect::doCollectOneCollector delete email ".$imapemailnum);
4040
4041 $operationslog .= "<br> move email ".$imapemailnum.($mode > 0 ? ' (test)' : '');
4042
4043 if (empty($mode) && empty($error)) {
4044 $tmptargetdir = $targetdir;
4045 if (!getDolGlobalString('MAIL_DISABLE_UTF7_ENCODE_OF_DIR')) {
4046 $tmptargetdir = $this->getEncodedUtf7($targetdir);
4047 }
4048
4049 $result = 0;
4050 try {
4051 $result = $imapemail->move($tmptargetdir, false);
4052 } catch (Exception $e) {
4053 // Nothing to do. $result will remain 0
4054 $operationslog .= '<br>Exception !!!! '.$e->getMessage();
4055 }
4056 if (empty($result)) {
4057 dol_syslog("Failed to move email into target directory ".$targetdir);
4058 $operationslog .= '<br>Failed to move email into target directory '.$targetdir;
4059 $error++;
4060 }
4061 }
4062 }
4063
4064 if (empty($mode) && empty($error)) {
4065 dol_syslog("Expunge", LOG_DEBUG);
4066 $operationslog .= "<br>Expunge";
4067
4068 $client->expunge(); // To validate all moves
4069 }
4070
4071 $client->disconnect();
4072 } else {
4073 foreach ($arrayofemailtodelete as $imapemail => $msgid) {
4074 dol_syslog("EmailCollect::doCollectOneCollector delete email ".$imapemail." ".$msgid);
4075
4076 $operationslog .= "<br> delete email ".$imapemail." ".$msgid.($mode > 0 ? ' (test)' : '');
4077
4078 if (empty($mode) && empty($error)) {
4079 $res = imap_mail_move($connection, $imapemail, $targetdir, CP_UID);
4080 if (!$res) {
4081 // $errorforemail++; // Not in loop, not needed, not initialised
4082 $this->error = imap_last_error();
4083 $this->errors[] = $this->error;
4084
4085 $operationslog .= '<br>Error in move '.$this->error;
4086
4087 dol_syslog(imap_last_error());
4088 }
4089 }
4090 }
4091
4092 if (empty($mode) && empty($error)) {
4093 dol_syslog("Expunge", LOG_DEBUG);
4094 $operationslog .= "<br>Expunge";
4095
4096 imap_expunge($connection); // To validate all moves
4097 }
4098 imap_close($connection);
4099 }
4100
4101 $this->datelastresult = $now;
4102 $this->lastresult = $output;
4103 if (getDolGlobalString('MAIN_IMAP_USE_PHPIMAP')) {
4104 $this->debuginfo .= 'IMAP search array used : '.$search;
4105 } else {
4106 $this->debuginfo .= 'IMAP search string used : '.$search;
4107 }
4108 if ($searchhead) {
4109 $this->debuginfo .= '<br>Then search string into email header : '.dol_escape_htmltag($searchhead);
4110 }
4111 if ($operationslog) {
4112 $this->debuginfo .= $operationslog;
4113 }
4114
4115 if (empty($error) && empty($mode)) {
4116 $this->datelastok = $datelastok;
4117 }
4118
4119 if (!empty($this->errors)) {
4120 $this->lastresult .= "<br>".implode("<br>", $this->errors);
4121 }
4122 $this->codelastresult = ($error ? 'KO' : 'OK');
4123
4124 if (empty($mode)) {
4125 $this->update($user);
4126 }
4127
4128 dol_syslog("EmailCollector::doCollectOneCollector end error=".$error, LOG_INFO);
4129
4130 return $error ? -1 : 1;
4131 }
4132
4133
4134
4135 // Loop to get part html and plain. Code found on PHP imap_fetchstructure documentation
4136
4145 private function getmsg($mbox, $mid, $destdir = ''): int
4146 {
4147 // input $mbox = IMAP stream, $mid = message id
4148 // output all the following:
4149 global $charset, $htmlmsg, $plainmsg, $attachments;
4150 $htmlmsg = $plainmsg = $charset = '';
4151 $attachments = array();
4152
4153 // HEADER
4154 //$h = imap_header($mbox,$mid);
4155 // add code here to get date, from, to, cc, subject...
4156
4157 // BODY
4158 $s = imap_fetchstructure($mbox, $mid, FT_UID);
4159 if ($s === false) {
4160 $this->errors = array_merge($this->errors, [imap_last_error()]);
4161 return -1;
4162 }
4163
4164 if (empty($s->parts)) {
4165 // simple
4166 $this->getpart($mbox, $mid, $s, '0'); // pass '0' as part-number
4167 } else {
4168 // multipart: cycle through each part
4169 foreach ($s->parts as $partno0 => $p) {
4170 $this->getpart($mbox, $mid, $p, (string) ($partno0 + 1), $destdir);
4171 }
4172 }
4173
4174 return 1;
4175 }
4176
4177 /* partno string
4178 0 multipart/mixed
4179 1 multipart/alternative
4180 1.1 text/plain
4181 1.2 text/html
4182 2 message/rfc822
4183 2 multipart/mixed
4184 2.1 multipart/alternative
4185 2.1.1 text/plain
4186 2.1.2 text/html
4187 2.2 message/rfc822
4188 2.2 multipart/alternative
4189 2.2.1 text/plain
4190 2.2.2 text/html
4191 */
4192
4203 private function getpart($mbox, $mid, $p, $partno, $destdir = '')
4204 {
4205 // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
4206 global $htmlmsg, $plainmsg, $charset, $attachments;
4207
4208 // DECODE DATA
4209 $data = ($partno) ?
4210 imap_fetchbody($mbox, $mid, $partno, FT_UID) : // multipart
4211 imap_body($mbox, $mid, FT_UID); // simple
4212 // Any part may be encoded, even plain text messages, so check everything.
4213 if ($p->encoding == 4) {
4214 $data = quoted_printable_decode($data);
4215 } elseif ($p->encoding == 3) {
4216 $data = base64_decode($data);
4217 }
4218
4219 // PARAMETERS
4220 // get all parameters, like charset, filenames of attachments, etc.
4221 $params = array();
4222 if ($p->parameters) {
4223 foreach ($p->parameters as $x) {
4224 $params[strtolower($x->attribute)] = $x->value;
4225 }
4226 }
4227 if (!empty($p->dparameters)) {
4228 foreach ($p->dparameters as $x) {
4229 $params[strtolower($x->attribute)] = $x->value;
4230 }
4231 }
4232 '@phan-var-force array{filename?:string,name?:string,charset?:string} $params';
4233
4234 // ATTACHMENT
4235 // Any part with a filename is an attachment,
4236 // so an attached text file (type 0) is not mistaken as the message.
4237 if ((!empty($params['filename']) || !empty($params['name'])) && $this->isAllowedAttachmentFilename((string) ($params['filename'] ?? $params['name']))) {
4238 // filename may be given as 'Filename' or 'Name' or both
4239 $filename = $params['filename'] ?? $params['name'];
4240 // filename may be encoded, so see imap_mime_header_decode()
4241 $attachments[$filename] = $data; // this is a problem if two files have same name
4242
4243 if (strlen($destdir)) {
4244 // Same name sanitization and same rules as for an uploaded file (see saveAttachment())
4245 $this->saveAttachment($destdir, $filename, $data);
4246 }
4247 }
4248
4249 // TEXT
4250 if ($p->type == 0 && $data) {
4251 if (!empty($params['charset'])) {
4252 $data = $this->convertStringEncoding($data, $params['charset']);
4253 }
4254 // Messages may be split in different parts because of inline attachments,
4255 // so append parts together with blank row.
4256 if (strtolower($p->subtype) == 'plain') {
4257 $plainmsg .= trim($data)."\n\n";
4258 } else {
4259 $htmlmsg .= $data."<br><br>";
4260 }
4261 $charset = $params['charset']; // assume all parts are same charset
4262 } elseif ($p->type == 2 && $data) {
4263 // EMBEDDED MESSAGE
4264 // Many bounce notifications embed the original message as type 2,
4265 // but AOL uses type 1 (multipart), which is not handled here.
4266 // There are no PHP functions to parse embedded messages,
4267 // so this just appends the raw source to the main message.
4268 if (!empty($params['charset'])) {
4269 $data = $this->convertStringEncoding($data, $params['charset']);
4270 }
4271 $plainmsg .= $data."\n\n";
4272 }
4273
4274 // SUBPART RECURSION
4275 if (!empty($p->parts)) {
4276 foreach ($p->parts as $partno0 => $p2) {
4277 $this->getpart($mbox, $mid, $p2, $partno.'.'.($partno0 + 1), $destdir); // 1.2, 1.2.1, etc.
4278 }
4279 }
4280 }
4281
4291 protected function convertStringEncoding($string, $fromEncoding, $toEncoding = 'UTF-8')
4292 {
4293 if (!$string || $fromEncoding == $toEncoding) {
4294 return $string;
4295 }
4296 $convertedString = function_exists('iconv') ? @iconv($fromEncoding, $toEncoding.'//IGNORE', $string) : null;
4297 if (!$convertedString && extension_loaded('mbstring')) {
4298 $convertedString = @mb_convert_encoding($string, $toEncoding, $fromEncoding);
4299 }
4300 if (!$convertedString) {
4301 throw new Exception('Mime string encoding conversion failed');
4302 }
4303 return $convertedString;
4304 }
4305
4316 protected function decodeSMTPSubject($subject)
4317 {
4318 // Decode $overview[0]->subject according to RFC2047
4319 // Can use also imap_mime_header_decode($str)
4320 // Can use also mb_decode_mimeheader($str)
4321 // Can use also iconv_mime_decode($str, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8')
4322 if (function_exists('imap_mime_header_decode') && function_exists('iconv_mime_decode')) {
4323 $elements = imap_mime_header_decode($subject);
4324 $newstring = '';
4325 if (!empty($elements)) {
4326 $num = count($elements);
4327 for ($i = 0; $i < $num; $i++) {
4328 $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));
4329 $newstring .= $stringinutf8;
4330 }
4331 $subject = $newstring;
4332 }
4333 } elseif (!function_exists('mb_decode_mimeheader')) {
4334 $subject = mb_decode_mimeheader($subject);
4335 } elseif (function_exists('iconv_mime_decode')) {
4336 $subject = iconv_mime_decode($subject, ICONV_MIME_DECODE_CONTINUE_ON_ERROR, 'UTF-8');
4337 }
4338
4339 return (string) $subject;
4340 }
4341
4349 private function saveEmailCollectorAttachmentsToDir($destdir, $attachments)
4350 {
4351 $destdir = rtrim((string) $destdir, '/');
4352 if ($destdir === '' || empty($attachments) || !is_array($attachments)) {
4353 return array();
4354 }
4355
4356 if (!dol_is_dir($destdir)) {
4357 if (dol_mkdir($destdir) < 0) {
4358 return array();
4359 }
4360 }
4361
4362 $stored = array();
4363 $seenHashes = array();
4364
4365 // Build a hash map of existing files to avoid storing duplicates.
4366 $filelist = dol_dir_list($destdir, 'files', 0, '', '(\\.meta|_preview.*.*\\.png)$', 'date', SORT_DESC, 0, 1);
4367 foreach ($filelist as $fileinfo) {
4368 if (empty($fileinfo['fullname']) || !is_file($fileinfo['fullname']) || !is_readable($fileinfo['fullname'])) {
4369 continue;
4370 }
4371 $hash = hash_file('sha256', $fileinfo['fullname']);
4372 if ($hash !== false && empty($seenHashes[$hash])) {
4373 $seenHashes[$hash] = $fileinfo['name'];
4374 }
4375 }
4376
4377 // Compute path relative to DOL_DATA_ROOT (used by hooks to reopen attachments later).
4378 $relativeDir = '';
4379 if (defined('DOL_DATA_ROOT')) {
4380 $root = rtrim((string) DOL_DATA_ROOT, '/').'/';
4381 $destdirwithslash = $destdir.'/';
4382 if (strpos($destdirwithslash, $root) === 0) {
4383 $relativeDir = rtrim(substr($destdirwithslash, strlen($root)), '/');
4384 }
4385 }
4386
4387 $index = 0;
4388 foreach ($attachments as $key => $attachment) {
4389 $index++;
4390 $origName = '';
4391 $content = '';
4392 $mime = null;
4393
4394 // PHP-IMAP (Webklex): array of Attachment objects.
4395 if (is_object($attachment)) {
4396 '@phan-var-force Webklex\PHPIMAP\Attachment $attachment';
4398 try {
4399 $origName = (string) $attachment->getName(); // Webklex Attachment uses magic __call
4400 } catch (Throwable $e) {
4401 $origName = '';
4402 }
4403 try {
4404 $content = (string) $attachment->getContent(); // Webklex Attachment uses magic __call
4405 } catch (Throwable $e) {
4406 $content = '';
4407 }
4408 try {
4409 $tmpmime = (string) $attachment->getContentType(); // Webklex Attachment uses magic __call
4410 $mime = ($tmpmime !== '' ? $tmpmime : null);
4411 } catch (Throwable $e) {
4412 $mime = null;
4413 }
4414 } else {
4415 // Native IMAP: array(filename => raw_data).
4416 $origName = (string) $key;
4417 $content = (string) $attachment;
4418 }
4419
4420 if ($origName === '' || $origName === 'undefined') {
4421 $origName = 'attachment-'.$index;
4422 }
4423 if (!$this->isAllowedAttachmentFilename($origName)) {
4424 continue;
4425 }
4426 if ($content === '') {
4427 continue;
4428 }
4429
4430 $safeName = dol_sanitizeFileName($origName, '_', 1, 0);
4431 if ($safeName === '') {
4432 $safeName = 'attachment-'.$index;
4433 }
4434
4435 $contentHash = hash('sha256', $content);
4436 $finalName = $safeName;
4437 $useExisting = false;
4438 if (!empty($seenHashes[$contentHash])) {
4439 $finalName = $seenHashes[$contentHash];
4440 if (file_exists($destdir.'/'.$finalName)) {
4441 $useExisting = true;
4442 }
4443 }
4444
4445 if (!$useExisting) {
4446 $n = 1;
4447 while (file_exists($destdir.'/'.$finalName)) {
4448 $finalName = preg_replace('/(\\.[A-Za-z0-9]{1,10})$/', '', $safeName).'-'.$n;
4449 if (preg_match('/\\.[A-Za-z0-9]{1,10}$/', $safeName, $m)) {
4450 $finalName .= $m[0];
4451 }
4452 $n++;
4453 }
4454
4455 $resultsave = $this->saveAttachment($destdir, $finalName, $content);
4456 if (!is_string($resultsave)) {
4457 continue; // Not saved (refused by the antivirus or error)
4458 }
4459 $finalName = basename($resultsave); // The name may have been changed (suffix .noexe, no dot at the beginning...)
4460 $seenHashes[$contentHash] = $finalName;
4461 }
4462
4463 $fullPath = $destdir.'/'.$finalName;
4464 $size = (file_exists($fullPath) ? filesize($fullPath) : null);
4465 $sizevalue = ($size === false ? null : $size);
4466 $sha256 = $contentHash;
4467
4468 $stored[] = array(
4469 'name' => $finalName,
4470 'original_name' => $origName,
4471 'relative_path' => ($relativeDir !== '' ? $relativeDir.'/'.$finalName : ''),
4472 'content_type' => $mime,
4473 'size' => ($sizevalue !== null ? (int) $sizevalue : null),
4474 'sha256' => $sha256,
4475 );
4476 }
4477
4478 return $stored;
4479 }
4480
4490 private function isAllowedAttachmentFilename($filename)
4491 {
4492 static $allowedExtRaw = null;
4493 static $allowedExtMap = null;
4494
4495 $raw = trim(getDolGlobalString('EMAILCOLLECTOR_ALLOWED_ATTACHMENT_EXTENSIONS'));
4496 if ($raw === '') {
4497 return true;
4498 }
4499
4500 if ($allowedExtRaw !== $raw) {
4501 $allowedExtRaw = $raw;
4502 $allowedExtMap = array();
4503 $tokens = preg_split('/[\s,;]+/', strtolower($raw));
4504 if (is_array($tokens)) {
4505 foreach ($tokens as $token) {
4506 $token = (string) preg_replace('/[^a-z0-9]+/', '', ltrim(trim($token), '.'));
4507 if ($token !== '') {
4508 $allowedExtMap[$token] = true;
4509 }
4510 }
4511 }
4512 }
4513
4514 // Ignore an invalid configuration instead of blocking every attachment.
4515 if (empty($allowedExtMap)) {
4516 return true;
4517 }
4518
4519 $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
4520 return $extension !== '' && !empty($allowedExtMap[$extension]);
4521 }
4522
4531 private function saveAttachment($destdir, $filename, $content)
4532 {
4533 global $conf;
4534
4535 require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';
4536
4537 $destdir = dol_sanitizePathName($destdir, '_', 0); // The directory is not built from the email, so we keep its accents
4538 $filename = dol_sanitizeFileName($filename);
4539 // Same rules as for an uploaded file: no control character, no dot or space at the end (removed by some OS, so the
4540 // extension tested would not be the real one), no dot at the beginning (hidden or setup file like .htaccess)
4541 $filename = preg_replace('/[\x00-\x1F\x7F]/', '', $filename);
4542 $filename = preg_replace('/^\.+/', '', rtrim($filename, '. '));
4543 if ($filename === '') {
4544 $filename = 'attachment';
4545 }
4546
4547 if (!file_exists($destdir)) {
4548 if (dol_mkdir($destdir) < 0) {
4549 return -1;
4550 }
4551 }
4552
4553 $tmp = explode('.', $filename);
4554 $ext = (count($tmp) > 1 ? '.' . array_pop($tmp) : ''); // A file name with no dot has no extension
4555 $filename = implode('.', $tmp);
4556
4557 // Same rule as for an uploaded file (see dol_move_uploaded_file()): a file with an executable content gets the suffix .noexe,
4558 // so it can't be run on demand if the documents directory is inside the web root
4559 if (isAFileWithExecutableContent($filename . $ext) && !getDolGlobalString('MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED')) {
4560 $ext .= '.noexe';
4561 }
4562
4563 $i = 1;
4564 $filepath = $destdir . (preg_match('/\/$/', $destdir) ? '' : '/') . $filename . $ext;
4565
4566 while (file_exists($filepath)) {
4567 $filepath = $destdir . (preg_match('/\/$/', $destdir) ? '' : '/') . $filename . '(' . $i . ')' . $ext;
4568 $i++;
4569 }
4570
4571 // Same rule as for an uploaded file: the antivirus checks the content before it is moved into the documents. It is
4572 // written first into a temporary file with a neutral name, as the name of the attachment comes from the email.
4573 $tmpdir = $conf->admin->dir_temp;
4574 if (!dol_is_dir($tmpdir)) {
4575 dol_mkdir($tmpdir);
4576 }
4577 $tmpfile = $tmpdir.'/emailcollector_attachment_'.dol_hash(uniqid((string) mt_rand(), true), 'md5');
4578 if (file_put_contents($tmpfile, $content) === false) {
4579 return -1; // Nothing saved, so nothing to index
4580 }
4581 $checkvirusarray = dolCheckVirus($tmpfile, $filepath);
4582 if (count($checkvirusarray)) {
4583 dol_syslog('EmailCollector::saveAttachment File "'.$filepath.'" KO with antivirus: errors='.implode(',', $checkvirusarray), LOG_WARNING);
4584 dol_delete_file($tmpfile, 0, 0, 0, null, false, 0);
4585 return -1;
4586 }
4587 if (!dol_move($tmpfile, $filepath, '0', 0, 0, 0)) {
4588 dol_delete_file($tmpfile, 0, 0, 0, null, false, 0);
4589 return -1; // Nothing saved, so nothing to index
4590 }
4591
4592 dolChmod($filepath);
4593
4594 // The name of the file saved, with its extension and the suffix added if a file with the same name already exists
4595 $filename = basename($filepath);
4596
4597 if (image_format_supported($filename) == 1) {
4598 $tmparraysize = getDefaultImageSizes();
4599 $maxwidthsmall = $tmparraysize['maxwidthsmall'];
4600 $maxheightsmall = $tmparraysize['maxheightsmall'];
4601 $maxwidthmini = $tmparraysize['maxwidthmini'];
4602 $maxheightmini = $tmparraysize['maxheightmini'];
4603 $quality = $tmparraysize['quality'];
4604
4605 // Create thumbs
4606 vignette($filepath, $maxwidthsmall, $maxheightsmall, '_small', $quality, "thumbs");
4607 // Create mini thumbs for image (Ratio is near 16/9)
4608 vignette($filepath, $maxwidthmini, $maxheightmini, '_mini', $quality, "thumbs");
4609 }
4610
4611 addFileIntoDatabaseIndex($destdir, $filename);
4612
4613 return $filepath;
4614 }
4615
4622 protected function uidAsString($imapemail)
4623 {
4624 if (is_object($imapemail)) {
4625 return $imapemail->getAttributes()["uid"];
4626 } else {
4627 return (string) $imapemail;
4628 }
4629 }
4630}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage agenda events (actions)
Class to manage members of a foundation.
Class to manage predefined suppliers products.
Class to manage customers orders.
setErrorsFromObject($object)
setErrorsFromObject
createCommon(User $user, $notrigger=0)
Create object in the database.
updateCommon(User $user, $notrigger=0)
Update object into database.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
Class to manage contact/addresses.
Class to manage Dolibarr database access.
Class for EmailCollectorAction.
Class for EmailCollectorFilter.
Class for EmailCollector.
fetch($id, $ref=null)
Load object in memory from the database.
createFromClone(User $user, $fromid)
Clone and object into another one.
convertStringEncoding($string, $fromEncoding, $toEncoding='UTF-8')
Converts a string from one encoding to another.
overwritePropertiesOfObject(&$object, $actionparam, $messagetext, $subject, $header, &$operationslog)
overwitePropertiesOfObject
__construct(DoliDB $db)
Constructor.
getpart($mbox, $mid, $p, $partno, $destdir='')
Sub function for getpart().
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
getEncodedUtf7($str)
Convert str to UTF-7 imap.
getConnectStringIMAP()
Return the connectstring to use with IMAP connection function.
decodeSMTPSubject($subject)
Decode a subject string according to RFC2047 Example: '=?Windows-1252?Q?RE=A0:_ABC?...
fetchFilters()
Fetch filters.
uidAsString($imapemail)
Get UID of message as a string.
LibStatut($status, $mode=0)
Return the status.
isAllowedAttachmentFilename($filename)
Check if an attachment filename is allowed by configuration.
fetchActions()
Fetch actions.
update(User $user, $notrigger=0)
Update object into database.
saveAttachment($destdir, $filename, $content)
saveAttachment
fetchAll(User $user, $activeOnly=0, $sortfield='s.rowid', $sortorder='ASC', $limit=100, $page=0)
Load object lines in memory from the database.
info($id)
Charge les information d'ordre info dans l'objet commande.
getmsg($mbox, $mid, $destdir='')
getmsg
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionally the picto)
create(User $user, $notrigger=0)
Create object into database.
doCollect()
Action executed by scheduler CAN BE A CRON TASK.
getLibStatut($mode=0)
Return label of the status.
Class to manage suppliers invoices.
Class to manage invoices.
Class to manage hooks.
Class to manage projects.
Class to manage proposals.
Class to manage receptions.
Class for RecruitmentCandidature.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage price ask supplier.
Class to manage tasks.
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
getCountry($searchkey, $withcode='', $dbtouse=null, $outputlangs=null, $entconv=1, $searchlabel='')
Return country label, code or id from an id, code or label.
dol_stringtotime($string, $gm=1, $processnotimeasnoon=0)
Convert a string date into a GM Timestamps date Warning: YYYY-MM-DDTHH:MM:SS+02:00 (RFC3339) is not s...
Definition date.lib.php:452
getFileData($jk, $fpos, $type, $mbox)
Get content of a joined file from its position into a given email.
getAttachments($jk, $mbox)
Get attachments of a given mail.
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
addFileIntoDatabaseIndex($dir, $file, $fullpathorig='', $mode='uploaded', $setsharekey=0, $object=null, $forceFullTextIndexation='')
Add a file into database index.
dolCheckVirus($src_file, $dest_file='')
Check virus into a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_is_dir($folder)
Test if filename is a directory.
removeEmoji($text, $allowedemoji=1)
Remove EMoji from email content.
dol_now($mode='gmt')
Return date for now.
dol_getIdFromCode($db, $key, $tablename, $fieldkey='code', $fieldid='id', $entityfilter=0, $filters='', $useCache=true)
Return an id or code from a code or id.
dolExplodeIntoArray($string, $delimiter=';', $kv='=')
Split a string with 2 keys into key array.
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
utf8_valid($str)
Check if a string is in UTF8.
dolChmod($filepath, $newmask='')
Change mod of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_sort_array(&$array, $index, $order='asc', $natsort=0, $case_sensitive=0, $keepindex=0)
Advanced sort array by the value of a given key, which produces ascending (default) or descending out...
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_concatdesc($text1, $text2, $forxml=false, $invert=false)
Concat 2 descriptions with a new line between them (second operand after first one with appropriate n...
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) formatLogObject($data)
Return a string serialized to be output on log with dol_syslog() An option allow to output log in one...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
isAFileWithExecutableContent($filename)
Return if a file can contains executable content.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
vignette($file, $maxWidth=160, $maxHeight=120, $extName='_small', $quality=50, $outdir='thumbs', $targetformat=0)
Create a thumbnail from an image file (Supported extensions are gif, jpg, png and bmp).
if(!defined( 'IMAGETYPE_WEBP')) getDefaultImageSizes()
Return default values for image sizes.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Class to generate the form for creating a new ticket.
getSupportedOauth2Array()
Return array of tabs to use on pages to setup cron module.
print $langs trans('Date')." left Ref Label right Qty right Price right TotalHT right TotalTTC right right right right right right right right right centpercent right TotalHT right n right VAT right n right TotalVAT right n No sujeto a RE IRPF right TotalLT1 right n right TotalLT2 right n right TotalTTC right n takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency takeposcustomercurrency right TotalTTC takeposcustomercurrency right takeposcustomercurrency n right Paid right PaymentTypeShortLIQ right SELECT p pos_change as p datep as date
Definition receipt.php:492
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.
dolDecrypt($chain, $key='', $patterntotest='')
Decode a string with a symmetric encryption.
dolEncrypt($chain, $key='', $ciphering='', $forceseed='', $obfuscationmode='dolcrypt')
Encode a string with a symmetric encryption.