dolibarr  18.0.0-alpha
emailcollector_card.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2018 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <https://www.gnu.org/licenses/>.
17  */
18 
25 // Load Dolibarr environment
26 require '../main.inc.php';
27 require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
28 require_once DOL_DOCUMENT_ROOT.'/core/lib/agenda.lib.php';
29 require_once DOL_DOCUMENT_ROOT.'/core/class/events.class.php';
30 
31 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php';
32 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
33 include_once DOL_DOCUMENT_ROOT.'/emailcollector/class/emailcollector.class.php';
34 include_once DOL_DOCUMENT_ROOT.'/emailcollector/class/emailcollectorfilter.class.php';
35 include_once DOL_DOCUMENT_ROOT.'/emailcollector/class/emailcollectoraction.class.php';
36 include_once DOL_DOCUMENT_ROOT.'/emailcollector/lib/emailcollector.lib.php';
37 
38 // use Webklex\PHPIMAP;
39 require DOL_DOCUMENT_ROOT.'/includes/webklex/php-imap/vendor/autoload.php';
40 use Webklex\PHPIMAP\ClientManager;
41 use Webklex\PHPIMAP\Exceptions\ConnectionFailedException;
42 use Webklex\PHPIMAP\Exceptions\InvalidWhereQueryCriteriaException;
43 
44 
45 use OAuth\Common\Storage\DoliStorage;
46 use OAuth\Common\Consumer\Credentials;
47 
48 if (!$user->admin) {
50 }
51 if (!isModEnabled('emailcollector')) {
53 }
54 
55 // Load traductions files required by page
56 $langs->loadLangs(array("admin", "mails", "other"));
57 
58 // Get parameters
59 $id = GETPOST('id', 'int');
60 $ref = GETPOST('ref', 'alpha');
61 $action = GETPOST('action', 'aZ09');
62 $confirm = GETPOST('confirm', 'alpha');
63 $cancel = GETPOST('cancel', 'aZ09');
64 $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'emailcollectorcard'; // To manage different context of search
65 $backtopage = GETPOST('backtopage', 'alpha');
66 
67 $operationid = GETPOST('operationid', 'int');
68 
69 // Initialize technical objects
70 $object = new EmailCollector($db);
71 $extrafields = new ExtraFields($db);
72 $diroutputmassaction = $conf->emailcollector->dir_output.'/temp/massgeneration/'.$user->id;
73 $hookmanager->initHooks(array('emailcollectorcard')); // Note that conf->hooks_modules contains array
74 
75 // Fetch optionals attributes and labels
76 $extrafields->fetch_name_optionals_label($object->table_element);
77 
78 $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
79 
80 // Initialize array of search criterias
81 $search_all = GETPOST("search_all", 'alpha');
82 $search = array();
83 foreach ($object->fields as $key => $val) {
84  if (GETPOST('search_'.$key, 'alpha')) {
85  $search[$key] = GETPOST('search_'.$key, 'alpha');
86  }
87 }
88 
89 if (GETPOST('saveoperation2')) {
90  $action = 'updateoperation';
91 }
92 if (empty($action) && empty($id) && empty($ref)) {
93  $action = 'view';
94 }
95 
96 // Load object
97 include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
98 
99 // Security check - Protection if external user
100 //if ($user->socid > 0) accessforbidden();
101 //if ($user->socid > 0) $socid = $user->socid;
102 //$isdraft = (($object->statut == MyObject::STATUS_DRAFT) ? 1 : 0);
103 //$result = restrictedArea($user, 'mymodule', $object->id, '', '', 'fk_soc', 'rowid', $isdraft);
104 
105 $permissionnote = $user->admin; // Used by the include of actions_setnotes.inc.php
106 $permissiondellink = $user->admin; // Used by the include of actions_dellink.inc.php
107 $permissiontoadd = $user->admin; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
108 
109 $debuginfo = '';
110 $error = 0;
111 
112 
113 /*
114  * Actions
115  */
116 
117 $parameters = array();
118 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
119 
120 if ($reshook < 0) {
121  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
122 }
123 
124 if (empty($reshook)) {
125  $permissiontoadd = 1;
126  $permissiontodelete = 1;
127  if (empty($backtopage)) {
128  $backtopage = DOL_URL_ROOT.'/admin/emailcollector_card.php?id='.($id > 0 ? $id : '__ID__');
129  }
130  $backurlforlist = DOL_URL_ROOT.'/admin/emailcollector_list.php';
131 
132  // Actions cancel, add, update, delete or clone
133  include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
134 
135  // Actions when linking object each other
136  include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
137 
138  // Actions when printing a doc from card
139  include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
140 }
141 
142 if (GETPOST('addfilter', 'alpha')) {
143  $emailcollectorfilter = new EmailCollectorFilter($db);
144  $emailcollectorfilter->type = GETPOST('filtertype', 'aZ09');
145  $emailcollectorfilter->rulevalue = GETPOST('rulevalue', 'alpha');
146  $emailcollectorfilter->fk_emailcollector = $object->id;
147  $emailcollectorfilter->status = 1;
148 
149  $result = $emailcollectorfilter->create($user);
150 
151  if ($result > 0) {
152  $object->fetchFilters();
153  } else {
154  setEventMessages($emailcollectorfilter->errors, $emailcollectorfilter->error, 'errors');
155  }
156 }
157 
158 if ($action == 'deletefilter') {
159  $emailcollectorfilter = new EmailCollectorFilter($db);
160  $emailcollectorfilter->fetch(GETPOST('filterid', 'int'));
161  if ($emailcollectorfilter->id > 0) {
162  $result = $emailcollectorfilter->delete($user);
163  if ($result > 0) {
164  $object->fetchFilters();
165  } else {
166  setEventMessages($emailcollectorfilter->errors, $emailcollectorfilter->error, 'errors');
167  }
168  }
169 }
170 
171 if (GETPOST('addoperation', 'alpha')) {
172  $emailcollectoroperation = new EmailCollectorAction($db);
173  $emailcollectoroperation->type = GETPOST('operationtype', 'aZ09');
174  $emailcollectoroperation->actionparam = GETPOST('operationparam', 'restricthtml');
175  $emailcollectoroperation->fk_emailcollector = $object->id;
176  $emailcollectoroperation->status = 1;
177  $emailcollectoroperation->position = 50;
178 
179  if ($emailcollectoroperation->type == '-1') {
180  $error++;
181  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Operation")), null, 'errors');
182  }
183 
184  if (in_array($emailcollectoroperation->type, array('loadthirdparty', 'loadandcreatethirdparty'))
185  && empty($emailcollectoroperation->actionparam)) {
186  $error++;
187  setEventMessages($langs->trans("ErrorAParameterIsRequiredForThisOperation"), null, 'errors');
188  }
189 
190  if (!$error) {
191  $result = $emailcollectoroperation->create($user);
192 
193  if ($result > 0) {
194  $object->fetchActions();
195  } else {
196  $error++;
197  setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors');
198  }
199  }
200 }
201 
202 if ($action == 'updateoperation') {
203  $emailcollectoroperation = new EmailCollectorAction($db);
204  $emailcollectoroperation->fetch(GETPOST('rowidoperation2', 'int'));
205 
206  $emailcollectoroperation->actionparam = GETPOST('operationparam2', 'alphawithlgt');
207 
208  if (in_array($emailcollectoroperation->type, array('loadthirdparty', 'loadandcreatethirdparty'))
209  && empty($emailcollectoroperation->actionparam)) {
210  $error++;
211  setEventMessages($langs->trans("ErrorAParameterIsRequiredForThisOperation"), null, 'errors');
212  }
213 
214  if (!$error) {
215  $result = $emailcollectoroperation->update($user);
216 
217  if ($result > 0) {
218  $object->fetchActions();
219  } else {
220  $error++;
221  setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors');
222  }
223  }
224 }
225 if ($action == 'deleteoperation') {
226  $emailcollectoroperation = new EmailCollectorAction($db);
227  $emailcollectoroperation->fetch(GETPOST('operationid', 'int'));
228  if ($emailcollectoroperation->id > 0) {
229  $result = $emailcollectoroperation->delete($user);
230  if ($result > 0) {
231  $object->fetchActions();
232  } else {
233  setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors');
234  }
235  }
236 }
237 
238 if ($action == 'collecttest') {
239  dol_include_once('/emailcollector/class/emailcollector.class.php');
240 
241  $res = $object->doCollectOneCollector(1);
242  if ($res > 0) {
243  $debuginfo = $object->debuginfo;
244  setEventMessages($object->lastresult, null, 'mesgs');
245  } else {
246  $debuginfo = $object->debuginfo;
247  setEventMessages($object->error, null, 'errors');
248  }
249 
250  $action = '';
251 }
252 
253 if ($action == 'confirm_collect') {
254  dol_include_once('/emailcollector/class/emailcollector.class.php');
255 
256  $res = $object->doCollectOneCollector(0);
257  if ($res > 0) {
258  $debuginfo = $object->debuginfo;
259  setEventMessages($object->lastresult, null, 'mesgs');
260  } else {
261  $debuginfo = $object->debuginfo;
262  setEventMessages($object->error, null, 'errors');
263  }
264 
265  $action = '';
266 }
267 
268 
269 
270 /*
271  * View
272  */
273 
274 $form = new Form($db);
275 $formfile = new FormFile($db);
276 
277 $help_url = "EN:Module_EMail_Collector|FR:Module_Collecteur_de_courrier_électronique|ES:Module_EMail_Collector";
278 
279 llxHeader('', 'EmailCollector', $help_url);
280 
281 // Part to create
282 if ($action == 'create') {
283  print load_fiche_titre($langs->trans("NewEmailCollector", $langs->transnoentitiesnoconv("EmailCollector")));
284 
285  print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
286  print '<input type="hidden" name="token" value="'.newToken().'">';
287  print '<input type="hidden" name="action" value="add">';
288  print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
289 
290  print dol_get_fiche_head(array(), '');
291 
292  print '<table class="border centpercent tableforfield">'."\n";
293 
294  //unset($fields[]);
295 
296  // Common attributes
297  include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php';
298 
299  // Other attributes
300  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
301 
302  print '</table>'."\n";
303 
304  print dol_get_fiche_end();
305 
306  print $form->buttonsSaveCancel("Create");
307 
308  print '</form>';
309 }
310 
311 // Part to edit record
312 if (($id || $ref) && $action == 'edit') {
313  print load_fiche_titre($langs->trans("EmailCollector"));
314 
315  print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
316  print '<input type="hidden" name="token" value="'.newToken().'">';
317  print '<input type="hidden" name="action" value="update">';
318  print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
319  print '<input type="hidden" name="id" value="'.$object->id.'">';
320 
321  print dol_get_fiche_head();
322 
323  print '<table class="border centpercent tableforfield">'."\n";
324 
325  // Common attributes
326  include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php';
327 
328  // Other attributes
329  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php';
330 
331  print '</table>';
332 
333  print dol_get_fiche_end();
334 
335  print $form->buttonsSaveCancel();
336 
337  print '</form>';
338 }
339 
340 // Part to show record
341 if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
342  $res = $object->fetch_optionals();
343 
344  $object->fetchFilters();
345  $object->fetchActions();
346 
347  $head = emailcollectorPrepareHead($object);
348  print dol_get_fiche_head($head, 'card', $langs->trans("EmailCollector"), -1, 'email');
349 
350  $formconfirm = '';
351 
352  // Confirmation to delete
353  if ($action == 'delete') {
354  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteEmailCollector'), $langs->trans('ConfirmDeleteEmailCollector'), 'confirm_delete', '', 0, 1);
355  }
356 
357  // Clone confirmation
358  if ($action == 'clone') {
359  // Create an array for form
360  $formquestion = array();
361  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneEmailCollector', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
362  }
363 
364  // Confirmation of action process
365  if ($action == 'collect') {
366  $formquestion = array();
367  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('EmailCollectorConfirmCollectTitle'), $langs->trans('EmailCollectorConfirmCollect'), 'confirm_collect', $formquestion, 0, 1, 220);
368  }
369 
370  // Call Hook formConfirm
371  $parameters = array('formConfirm' => $formconfirm);
372  $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
373  if (empty($reshook)) {
374  $formconfirm .= $hookmanager->resPrint;
375  } elseif ($reshook > 0) {
376  $formconfirm = $hookmanager->resPrint;
377  }
378 
379  // Print form confirm
380  print $formconfirm;
381 
382  // Object card
383  // ------------------------------------------------------------
384  $linkback = '<a href="'.DOL_URL_ROOT.'/admin/emailcollector_list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
385 
386  $morehtmlref = '<div class="refidno">';
387  $morehtmlref .= '</div>';
388 
389  $morehtml = '';
390 
391  $sourcedir = $object->source_directory;
392  $targetdir = ($object->target_directory ? $object->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag'
393 
394  $connection = null;
395  $connectstringserver = '';
396  $connectstringsource = '';
397  $connectstringtarget = '';
398 
399  // Note: $object->host has been loaded by the fetch
400  $usessl = 1;
401 
402  $connectstringserver = $object->getConnectStringIMAP($usessl);
403 
404  if ($action == 'scan') {
405  if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
406  if ($object->acces_type == 1) {
407  // Mode OAUth2 with PHP-IMAP
408  require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // define $supportedoauth2array
409  $keyforsupportedoauth2array = $object->oauth_service;
410  if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
411  $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
412  } else {
413  $keyforprovider = '';
414  }
415  $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
416  $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
417 
418  $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array]['name']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['name'].($keyforprovider ? '-'.$keyforprovider : ''));
419 
420  require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
421  //$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;
422  //dol_syslog($debugtext);
423 
424  $token = '';
425 
426  $storage = new DoliStorage($db, $conf, $keyforprovider);
427 
428  try {
429  $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
430 
431  $expire = true;
432  // Is token expired or will token expire in the next 30 seconds
433  // if (is_object($tokenobj)) {
434  // $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
435  // }
436  // Token expired so we refresh it
437  if (is_object($tokenobj) && $expire) {
438  $credentials = new Credentials(
439  getDolGlobalString('OAUTH_'.$object->oauth_service.'_ID'),
440  getDolGlobalString('OAUTH_'.$object->oauth_service.'_SECRET'),
441  getDolGlobalString('OAUTH_'.$object->oauth_service.'_URLAUTHORIZE')
442  );
443  $serviceFactory = new \OAuth\ServiceFactory();
444  $oauthname = explode('-', $OAUTH_SERVICENAME);
445 
446  // ex service is Google-Emails we need only the first part Google
447  $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
448 
449  // We have to save the token because Google give it only once
450  $refreshtoken = $tokenobj->getRefreshToken();
451  //var_dump($tokenobj);
452  $tokenobj = $apiService->refreshAccessToken($tokenobj);
453 
454  $tokenobj->setRefreshToken($refreshtoken);
455  $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
456  }
457  $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
458  if (is_object($tokenobj)) {
459  $token = $tokenobj->getAccessToken();
460  } else {
461  $error++;
462  $morehtml .= "Token not found";
463  }
464  } catch (Exception $e) {
465  $error++;
466  $morehtml .= $e->getMessage();
467  }
468 
469  if (empty($object->login)) {
470  $error++;
471  $morehtml .= 'Error: Login is empty. Must be email owner when using MAIN_IMAP_USE_PHPIMAP and OAuth.';
472  }
473 
474  $cm = new ClientManager();
475  $client = $cm->make([
476  'host' => $object->host,
477  'port' => $object->port,
478  'encryption' => 'ssl',
479  'validate_cert' => true,
480  'protocol' => 'imap',
481  'username' => $object->login,
482  'password' => $token,
483  'authentication' => "oauth",
484  ]);
485  } else {
486  // Mode login/pass with PHP-IMAP
487  $cm = new ClientManager();
488  $client = $cm->make([
489  'host' => $object->host,
490  'port' => $object->port,
491  'encryption' => 'ssl',
492  'validate_cert' => true,
493  'protocol' => 'imap',
494  'username' => $object->login,
495  'password' => $object->password,
496  'authentication' => "login",
497  ]);
498  }
499  if (!$error) {
500  try {
501  // To emulate the command connect, you can run
502  // openssl s_client -crlf -connect outlook.office365.com:993
503  // TAG1 AUTHENTICATE XOAUTH2 dXN...
504  // TO Get debug log, you can set protected $debug = true; in Protocol.php file
505  //
506  // A MS bug make this not working !
507  // See https://github.com/MicrosoftDocs/office-developer-exchange-docs/issues/100
508  // See github.com/MicrosoftDocs/office-developer-exchange-docs/issues/87
509  // See github.com/Webklex/php-imap/issues/81
510  $client->connect();
511 
512  $f = $client->getFolders(false, $object->source_directory);
513  $nbemail = $f[0]->examine()["exists"];
514  $morehtml .= $nbemail;
515  } catch (ConnectionFailedException $e) {
516  $morehtml .= 'ConnectionFailedException '.$e->getMessage();
517  }
518  }
519  } else {
520  if (function_exists('imap_open')) {
521  try {
522  if ($sourcedir) {
523  //$connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
524  $connectstringsource = $connectstringserver.$object->getEncodedUtf7($sourcedir);
525  }
526  if ($targetdir) {
527  //$connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
528  $connectstringtarget = $connectstringserver.$object->getEncodedUtf7($targetdir);
529  }
530 
531  $timeoutconnect = empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 5 : $conf->global->MAIN_USE_CONNECT_TIMEOUT;
532  $timeoutread = empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 20 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT;
533 
534  dol_syslog("imap_open connectstring=".$connectstringsource." login=".$object->login." password=".$object->password." timeoutconnect=".$timeoutconnect." timeoutread=".$timeoutread);
535 
536  $result1 = imap_timeout(IMAP_OPENTIMEOUT, $timeoutconnect); // timeout seems ignored with ssl connect
537  $result2 = imap_timeout(IMAP_READTIMEOUT, $timeoutread);
538  $result3 = imap_timeout(IMAP_WRITETIMEOUT, 5);
539  $result4 = imap_timeout(IMAP_CLOSETIMEOUT, 5);
540 
541  dol_syslog("result1=".$result1." result2=".$result2." result3=".$result3." result4=".$result4);
542 
543  $connection = imap_open($connectstringsource, $object->login, $object->password);
544 
545  //dol_syslog("end imap_open connection=".var_export($connection, true));
546  } catch (Exception $e) {
547  $morehtml .= $e->getMessage();
548  }
549 
550  if (!$connection) {
551  $morehtml .= 'Failed to open IMAP connection '.$connectstringsource;
552  if (function_exists('imap_last_error')) {
553  $morehtml .= '<br>'.imap_last_error();
554  }
555  dol_syslog("Error ".$morehtml, LOG_WARNING);
556  //var_dump(imap_errors())
557  } else {
558  dol_syslog("Imap connected. Now we call imap_num_msg()");
559  $morehtml .= imap_num_msg($connection);
560  }
561 
562  if ($connection) {
563  dol_syslog("Imap close");
564  imap_close($connection);
565  }
566  } else {
567  $morehtml .= 'IMAP functions not available on your PHP. ';
568  }
569  }
570  }
571 
572  $morehtml = $form->textwithpicto($langs->trans("NbOfEmailsInInbox"), 'connect string '.$connectstringserver).': '.($morehtml ? $morehtml : '?');
573  $morehtml .= '<a class="flat paddingleft marginleftonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=scan&token='.newToken().'">'.img_picto('', 'refresh', 'class="paddingrightonly"').$langs->trans("Refresh").'</a>';
574 
575  dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref.'<div class="refidno">'.$morehtml.'</div>', '', 0, '', '', 0, '');
576 
577  print '<div class="fichecenter">';
578  print '<div class="fichehalfleft">';
579  print '<div class="underbanner clearboth"></div>';
580  print '<table class="border centpercent tableforfield">'."\n";
581 
582  // Common attributes
583  //$keyforbreak='fieldkeytoswithonsecondcolumn';
584  include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
585 
586  // Other attributes
587  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
588 
589  print '</table>';
590 
591 
592  print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
593  print '<input type="hidden" name="token" value="'.newToken().'">';
594  print '<input type="hidden" name="action" value="updatefiltersactions">';
595  print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
596  print '<input type="hidden" name="id" value="'.$object->id.'">';
597 
598  // Filters
599  print '<div class="div-table-responsive-no-min">';
600  print '<table id="tablelineoffilters" class="noborder margintable noshadow">';
601  print '<tr class="liste_titre nodrag nodrop">';
602  print '<td>'.img_picto('', 'filter', 'class="pictofixedwidth opacitymedium"').$form->textwithpicto($langs->trans("Filters"), $langs->trans("EmailCollectorFilterDesc")).'</td><td></td><td></td>';
603  print '</tr>';
604  // Add filter
605  print '<tr class="oddeven nodrag nodrop">';
606  print '<td>';
607  $arrayoftypes = array(
608  'from'=>array('label'=>'MailFrom', 'data-placeholder'=>$langs->trans('SearchString')),
609  'to'=>array('label'=>'MailTo', 'data-placeholder'=>$langs->trans('SearchString')),
610  'cc'=>array('label'=>'Cc', 'data-placeholder'=>$langs->trans('SearchString')),
611  'bcc'=>array('label'=>'Bcc', 'data-placeholder'=>$langs->trans('SearchString')),
612  'subject'=>array('label'=>'Subject', 'data-placeholder'=>$langs->trans('SearchString')),
613  'body'=>array('label'=>'Body', 'data-placeholder'=>$langs->trans('SearchString')),
614  // disabled because PHP imap_search is not compatible IMAPv4, only IMAPv2
615  //'header'=>array('label'=>'Header', 'data-placeholder'=>'HeaderKey SearchString'), // HEADER key value
616  //'X1'=>'---',
617  //'notinsubject'=>array('label'=>'SubjectNotIn', 'data-placeholder'=>'SearchString'),
618  //'notinbody'=>array('label'=>'BodyNotIn', 'data-placeholder'=>'SearchString'),
619  'X2'=>'---',
620  'seen'=>array('label'=>'AlreadyRead', 'data-noparam'=>1),
621  'unseen'=>array('label'=>'NotRead', 'data-noparam'=>1),
622  'unanswered'=>array('label'=>'Unanswered', 'data-noparam'=>1),
623  'answered'=>array('label'=>'Answered', 'data-noparam'=>1),
624  'smaller'=>array('label'=>'SmallerThan', 'data-placeholder'=>$langs->trans('NumberOfBytes')),
625  'larger'=>array('label'=>'LargerThan', 'data-placeholder'=>$langs->trans('NumberOfBytes')),
626  'X3'=>'---',
627  'withtrackingid'=>array('label'=>'WithDolTrackingID', 'data-noparam'=>1),
628  'withouttrackingid'=>array('label'=>'WithoutDolTrackingID', 'data-noparam'=>1),
629  'withtrackingidinmsgid'=>array('label'=>'WithDolTrackingIDInMsgId', 'data-noparam'=>1),
630  'withouttrackingidinmsgid'=>array('label'=>'WithoutDolTrackingIDInMsgId', 'data-noparam'=>1),
631  'X4'=>'---',
632  'isnotanswer'=>array('label'=>'IsNotAnAnswer', 'data-noparam'=>1),
633  'isanswer'=>array('label'=>'IsAnAnswer', 'data-noparam'=>1)
634  );
635  print $form->selectarray('filtertype', $arrayoftypes, '', 1, 0, 0, '', 1, 0, 0, '', 'maxwidth300', 1, '', 2);
636 
637  print "\n";
638  print '<script>';
639  print 'jQuery("#filtertype").change(function() {
640  console.log("We change a filter");
641  if (jQuery("#filtertype option:selected").attr("data-noparam")) {
642  jQuery("#rulevalue").attr("placeholder", "");
643  jQuery("#rulevalue").text(""); jQuery("#rulevalue").prop("disabled", true);
644  }
645  else { jQuery("#rulevalue").prop("disabled", false); }
646  jQuery("#rulevalue").attr("placeholder", (jQuery("#filtertype option:selected").attr("data-placeholder")));
647  ';
648  /*$noparam = array();
649  foreach ($arrayoftypes as $key => $value)
650  {
651  if ($value['noparam']) $noparam[] = $key;
652  }*/
653  print '})';
654  print '</script>'."\n";
655 
656  print '</td><td>';
657  print '<input type="text" name="rulevalue" id="rulevalue">';
658  print '</td>';
659  print '<td class="right"><input type="submit" name="addfilter" id="addfilter" class="flat button small" value="'.$langs->trans("Add").'"></td>';
660  print '</tr>';
661  // List filters
662  foreach ($object->filters as $rulefilter) {
663  $rulefilterobj = new EmailCollectorFilter($db);
664  $rulefilterobj->fetch($rulefilter['id']);
665 
666  print '<tr class="oddeven">';
667  print '<td title="'.dol_escape_htmltag($langs->trans("Filter").': '.$rulefilter['type']).'">';
668  print $langs->trans($arrayoftypes[$rulefilter['type']]['label']);
669  print '</td>';
670  print '<td>'.$rulefilter['rulevalue'].'</td>';
671  print '<td class="right">';
672  print ' <a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletefilter&token='.urlencode(newToken()).'&filterid='.$rulefilter['id'].'">'.img_delete().'</a>';
673  print '</td>';
674  print '</tr>';
675  }
676 
677  print '</tr>';
678  print '</table>';
679  print '</div>';
680 
681  print '<div class="clearboth"></div><br>';
682 
683  // Operations
684  print '<div class="div-table-responsive">';
685  print '<table id="tablelines" class="noborder margintable noshadow">';
686  print '<tr class="liste_titre nodrag nodrop">';
687  print '<td>'.img_picto('', 'technic', 'class="pictofixedwidth"').$form->textwithpicto($langs->trans("EmailcollectorOperations"), $langs->trans("EmailcollectorOperationsDesc")).'</td><td></td><td></td><td></td>';
688  print '</tr>';
689 
690  $arrayoftypes = array(
691  'loadthirdparty' => $langs->trans('LoadThirdPartyFromName', $langs->transnoentities("ThirdPartyName")),
692  'loadandcreatethirdparty' => $langs->trans('LoadThirdPartyFromNameOrCreate', $langs->transnoentities("ThirdPartyName")),
693  'recordjoinpiece' => 'AttachJoinedDocumentsToObject',
694  'recordevent' => 'RecordEvent'
695  );
696  $arrayoftypesnocondition = $arrayoftypes;
697  if (isModEnabled('project')) {
698  $arrayoftypes['project'] = 'CreateLeadAndThirdParty';
699  }
700  $arrayoftypesnocondition['project'] = 'CreateLeadAndThirdParty';
701  if (isModEnabled('ticket')) {
702  $arrayoftypes['ticket'] = 'CreateTicketAndThirdParty';
703  }
704  $arrayoftypesnocondition['ticket'] = 'CreateTicketAndThirdParty';
705  if (isModEnabled('recruitment')) {
706  $arrayoftypes['candidature'] = 'CreateCandidature';
707  }
708  $arrayoftypesnocondition['candidature'] = 'CreateCandidature';
709 
710  // support hook for add action
711  $parameters = array('arrayoftypes' => $arrayoftypes);
712  $res = $hookmanager->executeHooks('addMoreActionsEmailCollector', $parameters, $object, $action);
713 
714  if ($res) {
715  $arrayoftypes = $hookmanager->resArray;
716  } else {
717  foreach ($hookmanager->resArray as $k => $desc) {
718  $arrayoftypes[$k] = $desc;
719  }
720  }
721 
722  // Add operation
723  print '<tr class="oddeven nodrag nodrop">';
724  print '<td>';
725  print $form->selectarray('operationtype', $arrayoftypes, '', 1, 0, 0, '', 1, 0, 0, '', 'minwidth150 maxwidth300', 1);
726  print '</td><td>';
727  //print '<input type="text" name="operationparam">';
728  $htmltext = $langs->transnoentitiesnoconv("OperationParamDesc");
729  print $form->textwithpicto('<input type="text" name="operationparam">', $htmltext, 1, 'help', '', 0, 2, 'operationparamtt');
730  print '</td>';
731  print '<td>';
732  print '</td>';
733  print '<td class="right"><input type="submit" name="addoperation" id="addoperation" class="flat button small" value="'.$langs->trans("Add").'"></td>';
734  print '</tr>';
735  // List operations
736  $nboflines = count($object->actions);
737  $table_element_line = 'emailcollector_emailcollectoraction';
738  $fk_element = 'position';
739  $i = 0;
740  foreach ($object->actions as $ruleaction) {
741  $ruleactionobj = new EmailcollectorAction($db);
742  $ruleactionobj->fetch($ruleaction['id']);
743 
744  print '<tr class="drag drop oddeven" id="row-'.$ruleaction['id'].'">';
745  print '<td title="'.dol_escape_htmltag($langs->trans("Operation").': '.$ruleaction['type']).'">';
746  print '<!-- type of action: '.$ruleaction['type'].' -->';
747  if (array_key_exists($ruleaction['type'], $arrayoftypes)) {
748  print $langs->trans($arrayoftypes[$ruleaction['type']]);
749  } else {
750  if (array_key_exists($ruleaction['type'], $arrayoftypesnocondition)) {
751  print '<span class="opacitymedium">'.$langs->trans($arrayoftypesnocondition[$ruleaction['type']]).' - '.$langs->trans("Disabled").'</span>';
752  }
753  }
754 
755  if (in_array($ruleaction['type'], array('recordevent'))) {
756  print $form->textwithpicto('', $langs->transnoentitiesnoconv('IfTrackingIDFoundEventWillBeLinked'));
757  } elseif (in_array($ruleaction['type'], array('loadthirdparty', 'loadandcreatethirdparty'))) {
758  print $form->textwithpicto('', $langs->transnoentitiesnoconv('EmailCollectorLoadThirdPartyHelp'));
759  }
760  print '</td>';
761  print '<td class="wordbreak minwidth300 small">';
762  if ($action == 'editoperation' && $ruleaction['id'] == $operationid) {
763  print '<input type="text" class="quatrevingtquinzepercent" name="operationparam2" value="'.dol_escape_htmltag($ruleaction['actionparam']).'"><br>';
764  print '<input type="hidden" name="rowidoperation2" value="'.$ruleaction['id'].'">';
765  print '<input type="submit" class="button small button-save" name="saveoperation2" value="'.$langs->trans("Save").'">';
766  print '<input type="submit" class="button small button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
767  } else {
768  print dol_escape_htmltag($ruleaction['actionparam']);
769  }
770  print '</td>';
771  // Move up/down
772  print '<td class="center linecolmove tdlineupdown">';
773  if ($i > 0) {
774  print '<a class="lineupdown" href="'.$_SERVER['PHP_SELF'].'?action=up&amp;rowid='.$ruleaction['id'].'">'.img_up('default', 0, 'imgupforline').'</a>';
775  }
776  if ($i < count($object->actions) - 1) {
777  print '<a class="lineupdown" href="'.$_SERVER['PHP_SELF'].'?action=down&amp;rowid='.$ruleaction['id'].'">'.img_down('default', 0, 'imgdownforline').'</a>';
778  }
779  print '</td>';
780  // Delete
781  print '<td class="right nowraponall">';
782  print '<a class="editfielda marginrightonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=editoperation&token='.newToken().'&operationid='.$ruleaction['id'].'">'.img_edit().'</a>';
783  print ' <a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deleteoperation&token='.newToken().'&operationid='.$ruleaction['id'].'">'.img_delete().'</a>';
784  print '</td>';
785  print '</tr>';
786  $i++;
787  }
788 
789  print '</tr>';
790  print '</table>';
791  print '</div>';
792 
793  if (!empty($conf->use_javascript_ajax)) {
794  $urltorefreshaftermove = DOL_URL_ROOT.'/admin/emailcollector_card.php?id='.$id;
795  include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
796  }
797 
798  print '</form>';
799 
800  print '</div>';
801  print '</div>'; // End <div class="fichecenter">
802 
803 
804  print '<div class="clearboth"></div><br>';
805 
806  print dol_get_fiche_end();
807 
808  // Buttons for actions
809  if ($action != 'presend' && $action != 'editline') {
810  print '<div class="tabsAction">'."\n";
811  $parameters = array();
812  $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
813  if ($reshook < 0) {
814  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
815  }
816 
817  if (empty($reshook)) {
818  // Edit
819  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&token='.newToken().'">'.$langs->trans("Edit").'</a></div>';
820 
821  // Clone
822  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=clone&token='.newToken().'&object=order">'.$langs->trans("ToClone").'</a></div>';
823 
824  // Collect now
825  print '<div class="inline-block divButAction"><a class="butAction reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=collecttest&token='.newToken().'">'.$langs->trans("TestCollectNow").'</a></div>';
826 
827  if (count($object->actions) > 0) {
828  print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=collect&token='.newToken().'">'.$langs->trans("CollectNow").'</a></div>';
829  } else {
830  print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("NoOperations")).'">'.$langs->trans("CollectNow").'</a></div>';
831  }
832 
833  print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.urlencode(newToken()).'">'.$langs->trans('Delete').'</a></div>';
834  }
835  print '</div>'."\n";
836  }
837 
838  if (!empty($debuginfo)) {
839  print info_admin($debuginfo);
840  }
841 }
842 
843 // End of page
844 llxFooter();
845 $db->close();
dol_escape_htmltag
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
Definition: functions.lib.php:1504
llxFooter
llxFooter()
Empty footer.
Definition: wrapper.php:70
EmailCollectorAction
Class for EmailCollectorAction.
Definition: emailcollectoraction.class.php:31
load_fiche_titre
load_fiche_titre($titre, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
Definition: functions.lib.php:5363
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:530
dol_include_once
if(!function_exists('dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
Definition: functions.lib.php:1043
EmailCollectorFilter
Class for EmailCollectorFilter.
Definition: emailcollectorfilter.class.php:33
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:143
img_edit
img_edit($titlealt='default', $float=0, $other='')
Show logo editer/modifier fiche.
Definition: functions.lib.php:4539
dol_banner_tab
dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlstatus='', $onlybanner=0, $morehtmlright='')
Show tab footer of a card.
Definition: functions.lib.php:2097
$help_url
if(GETPOST('button_removefilter_x', 'alpha')||GETPOST('button_removefilter.x', 'alpha')||GETPOST('button_removefilter', 'alpha')) if(GETPOST('button_search_x', 'alpha')||GETPOST('button_search.x', 'alpha')||GETPOST('button_search', 'alpha')) if($action=="save" &&empty($cancel)) $help_url
View.
Definition: agenda.php:118
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:4025
llxHeader
if(!defined('NOREQUIRESOC')) if(!defined('NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined('NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined('NOREQUIREAJAX')) llxHeader()
Empty header.
Definition: wrapper.php:56
img_up
img_up($titlealt='default', $selected=0, $moreclass='')
Show top arrow logo.
Definition: functions.lib.php:4765
Exception
img_delete
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
Definition: functions.lib.php:4579
$formconfirm
$formconfirm
if ($action == 'delbookkeepingyear') {
Definition: listbyaccount.php:634
FormFile
Class to offer components to list and upload files.
Definition: html.formfile.class.php:36
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1639
img_down
img_down($titlealt='default', $selected=0, $moreclass='')
Show down arrow logo.
Definition: functions.lib.php:4746
dol_get_fiche_head
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='')
Show tabs of a record.
Definition: functions.lib.php:1873
getDolGlobalString
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
Definition: functions.lib.php:82
info_admin
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='')
Show information for admin users or standard users.
Definition: functions.lib.php:4950
newToken
newToken()
Return the value of token currently saved into session with name 'newtoken'.
Definition: functions.lib.php:11317
dol_get_fiche_end
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition: functions.lib.php:2069
isModEnabled
isModEnabled($module)
Is Dolibarr module enabled.
Definition: functions.lib.php:147
EmailCollector
Class for EmailCollector.
Definition: emailcollector.class.php:62
ExtraFields
Class to manage standard extra fields.
Definition: extrafields.class.php:39
Form
Class to manage generation of HTML components Only common components must be here.
Definition: html.form.class.php:52
emailcollectorPrepareHead
emailcollectorPrepareHead($object)
Prepare array of tabs for EmailCollector.
Definition: emailcollector.lib.php:31
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8509
accessforbidden
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.
Definition: security.lib.php:1106