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