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