dolibarr  x.y.z
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 
111 
112 /*
113  * Actions
114  */
115 
116 $parameters = array();
117 $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
118 
119 if ($reshook < 0) {
120  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
121 }
122 
123 if (empty($reshook)) {
124  $error = 0;
125 
126  $permissiontoadd = 1;
127  $permissiontodelete = 1;
128  if (empty($backtopage)) {
129  $backtopage = DOL_URL_ROOT.'/admin/emailcollector_card.php?id='.($id > 0 ? $id : '__ID__');
130  }
131  $backurlforlist = DOL_URL_ROOT.'/admin/emailcollector_list.php';
132 
133  // Actions cancel, add, update, delete or clone
134  include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
135 
136  // Actions when linking object each other
137  include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php';
138 
139  // Actions when printing a doc from card
140  include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php';
141 }
142 
143 if (GETPOST('addfilter', 'alpha')) {
144  $emailcollectorfilter = new EmailCollectorFilter($db);
145  $emailcollectorfilter->type = GETPOST('filtertype', 'aZ09');
146  $emailcollectorfilter->rulevalue = GETPOST('rulevalue', 'alpha');
147  $emailcollectorfilter->fk_emailcollector = $object->id;
148  $emailcollectorfilter->status = 1;
149 
150  $result = $emailcollectorfilter->create($user);
151 
152  if ($result > 0) {
153  $object->fetchFilters();
154  } else {
155  setEventMessages($emailcollectorfilter->errors, $emailcollectorfilter->error, 'errors');
156  }
157 }
158 
159 if ($action == 'deletefilter') {
160  $emailcollectorfilter = new EmailCollectorFilter($db);
161  $emailcollectorfilter->fetch(GETPOST('filterid', 'int'));
162  if ($emailcollectorfilter->id > 0) {
163  $result = $emailcollectorfilter->delete($user);
164  if ($result > 0) {
165  $object->fetchFilters();
166  } else {
167  setEventMessages($emailcollectorfilter->errors, $emailcollectorfilter->error, 'errors');
168  }
169  }
170 }
171 
172 if (GETPOST('addoperation', 'alpha')) {
173  $emailcollectoroperation = new EmailCollectorAction($db);
174  $emailcollectoroperation->type = GETPOST('operationtype', 'aZ09');
175  $emailcollectoroperation->actionparam = GETPOST('operationparam', 'restricthtml');
176  $emailcollectoroperation->fk_emailcollector = $object->id;
177  $emailcollectoroperation->status = 1;
178  $emailcollectoroperation->position = 50;
179 
180  if ($emailcollectoroperation->type == '-1') {
181  $error++;
182  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Operation")), null, 'errors');
183  }
184 
185  if (in_array($emailcollectoroperation->type, array('loadthirdparty', 'loadandcreatethirdparty'))
186  && empty($emailcollectoroperation->actionparam)) {
187  $error++;
188  setEventMessages($langs->trans("ErrorAParameterIsRequiredForThisOperation"), null, 'errors');
189  }
190 
191  if (!$error) {
192  $result = $emailcollectoroperation->create($user);
193 
194  if ($result > 0) {
195  $object->fetchActions();
196  } else {
197  $error++;
198  setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors');
199  }
200  }
201 }
202 
203 if ($action == 'updateoperation') {
204  $emailcollectoroperation = new EmailCollectorAction($db);
205  $emailcollectoroperation->fetch(GETPOST('rowidoperation2', 'int'));
206 
207  $emailcollectoroperation->actionparam = GETPOST('operationparam2', 'alphawithlgt');
208 
209  if (in_array($emailcollectoroperation->type, array('loadthirdparty', 'loadandcreatethirdparty'))
210  && empty($emailcollectoroperation->actionparam)) {
211  $error++;
212  setEventMessages($langs->trans("ErrorAParameterIsRequiredForThisOperation"), null, 'errors');
213  }
214 
215  if (!$error) {
216  $result = $emailcollectoroperation->update($user);
217 
218  if ($result > 0) {
219  $object->fetchActions();
220  } else {
221  $error++;
222  setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors');
223  }
224  }
225 }
226 if ($action == 'deleteoperation') {
227  $emailcollectoroperation = new EmailCollectorAction($db);
228  $emailcollectoroperation->fetch(GETPOST('operationid', 'int'));
229  if ($emailcollectoroperation->id > 0) {
230  $result = $emailcollectoroperation->delete($user);
231  if ($result > 0) {
232  $object->fetchActions();
233  } else {
234  setEventMessages($emailcollectoroperation->errors, $emailcollectoroperation->error, 'errors');
235  }
236  }
237 }
238 
239 if ($action == 'collecttest') {
240  dol_include_once('/emailcollector/class/emailcollector.class.php');
241 
242  $res = $object->doCollectOneCollector(1);
243  if ($res > 0) {
244  $debuginfo = $object->debuginfo;
245  setEventMessages($object->lastresult, null, 'mesgs');
246  } else {
247  $debuginfo = $object->debuginfo;
248  setEventMessages($object->error, null, 'errors');
249  }
250 
251  $action = '';
252 }
253 
254 if ($action == 'confirm_collect') {
255  dol_include_once('/emailcollector/class/emailcollector.class.php');
256 
257  $res = $object->doCollectOneCollector(0);
258  if ($res > 0) {
259  $debuginfo = $object->debuginfo;
260  setEventMessages($object->lastresult, null, 'mesgs');
261  } else {
262  $debuginfo = $object->debuginfo;
263  setEventMessages($object->error, null, 'errors');
264  }
265 
266  $action = '';
267 }
268 
269 
270 
271 /*
272  * View
273  */
274 
275 $form = new Form($db);
276 $formfile = new FormFile($db);
277 
278 $help_url = "EN:Module_EMail_Collector|FR:Module_Collecteur_de_courrier_électronique|ES:Module_EMail_Collector";
279 
280 llxHeader('', 'EmailCollector', $help_url);
281 
282 // Part to create
283 if ($action == 'create') {
284  print load_fiche_titre($langs->trans("NewEmailCollector", $langs->transnoentitiesnoconv("EmailCollector")));
285 
286  print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
287  print '<input type="hidden" name="token" value="'.newToken().'">';
288  print '<input type="hidden" name="action" value="add">';
289  print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
290 
291  print dol_get_fiche_head(array(), '');
292 
293  print '<table class="border centpercent tableforfield">'."\n";
294 
295  //unset($fields[]);
296 
297  // Common attributes
298  include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php';
299 
300  // Other attributes
301  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php';
302 
303  print '</table>'."\n";
304 
305  print dol_get_fiche_end();
306 
307  print $form->buttonsSaveCancel("Create");
308 
309  print '</form>';
310 }
311 
312 // Part to edit record
313 if (($id || $ref) && $action == 'edit') {
314  print load_fiche_titre($langs->trans("EmailCollector"));
315 
316  print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
317  print '<input type="hidden" name="token" value="'.newToken().'">';
318  print '<input type="hidden" name="action" value="update">';
319  print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
320  print '<input type="hidden" name="id" value="'.$object->id.'">';
321 
322  print dol_get_fiche_head();
323 
324  print '<table class="border centpercent tableforfield">'."\n";
325 
326  // Common attributes
327  include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php';
328 
329  // Other attributes
330  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php';
331 
332  print '</table>';
333 
334  print dol_get_fiche_end();
335 
336  print $form->buttonsSaveCancel();
337 
338  print '</form>';
339 }
340 
341 // Part to show record
342 if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
343  $res = $object->fetch_optionals();
344 
345  $object->fetchFilters();
346  $object->fetchActions();
347 
348  $head = emailcollectorPrepareHead($object);
349  print dol_get_fiche_head($head, 'card', $langs->trans("EmailCollector"), -1, 'email');
350 
351  $formconfirm = '';
352 
353  // Confirmation to delete
354  if ($action == 'delete') {
355  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteEmailCollector'), $langs->trans('ConfirmDeleteEmailCollector'), 'confirm_delete', '', 0, 1);
356  }
357 
358  // Clone confirmation
359  if ($action == 'clone') {
360  // Create an array for form
361  $formquestion = array();
362  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneEmailCollector', $object->ref), 'confirm_clone', $formquestion, 'yes', 1);
363  }
364 
365  // Confirmation of action process
366  if ($action == 'collect') {
367  $formquestion = array();
368  $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('EmailCollectorConfirmCollectTitle'), $langs->trans('EmailCollectorConfirmCollect'), 'confirm_collect', $formquestion, 0, 1, 220);
369  }
370 
371  // Call Hook formConfirm
372  $parameters = array('formConfirm' => $formconfirm);
373  $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
374  if (empty($reshook)) {
375  $formconfirm .= $hookmanager->resPrint;
376  } elseif ($reshook > 0) {
377  $formconfirm = $hookmanager->resPrint;
378  }
379 
380  // Print form confirm
381  print $formconfirm;
382 
383  // Object card
384  // ------------------------------------------------------------
385  $linkback = '<a href="'.DOL_URL_ROOT.'/admin/emailcollector_list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
386 
387  $morehtmlref = '<div class="refidno">';
388  $morehtmlref .= '</div>';
389 
390  $morehtml = $langs->trans("NbOfEmailsInInbox").' : ';
391 
392  $sourcedir = $object->source_directory;
393  $targetdir = ($object->target_directory ? $object->target_directory : ''); // Can be '[Gmail]/Trash' or 'mytag'
394 
395  $connection = null;
396  $connectstringserver = '';
397  $connectstringsource = '';
398  $connectstringtarget = '';
399 
400  if (function_exists('imap_open')) {
401  // Note: $object->host has been loaded by the fetch
402  $usessl = 1;
403 
404  $connectstringserver = $object->getConnectStringIMAP($usessl);
405 
406  if ($action == 'scan') {
407  if (!empty($conf->global->MAIN_IMAP_USE_PHPIMAP)) {
408  if ($object->acces_type == 1) {
409  // Mode OAUth2 with PHP-IMAP
410  require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // define $supportedoauth2array
411  $keyforsupportedoauth2array = $object->oauth_service;
412  if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
413  $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
414  } else {
415  $keyforprovider = '';
416  }
417  $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
418  $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
419 
420  $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array]['name']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['name'].($keyforprovider ? '-'.$keyforprovider : ''));
421 
422  require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
423  //$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;
424  //dol_syslog($debugtext);
425 
426  $storage = new DoliStorage($db, $conf);
427 
428  try {
429  $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
430  $expire = true;
431  // Is token expired or will token expire in the next 30 seconds
432  // if (is_object($tokenobj)) {
433  // $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
434  // }
435  // Token expired so we refresh it
436  if (is_object($tokenobj) && $expire) {
437  $credentials = new Credentials(
438  getDolGlobalString('OAUTH_'.$object->oauth_service.'_ID'),
439  getDolGlobalString('OAUTH_'.$object->oauth_service.'_SECRET'),
440  getDolGlobalString('OAUTH_'.$object->oauth_service.'_URLAUTHORIZE')
441  );
442  $serviceFactory = new \OAuth\ServiceFactory();
443  $oauthname = explode('-', $OAUTH_SERVICENAME);
444  // ex service is Google-Emails we need only the first part Google
445  $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
446  // We have to save the token because Google give it only once
447  $refreshtoken = $tokenobj->getRefreshToken();
448  $tokenobj = $apiService->refreshAccessToken($tokenobj);
449  $tokenobj->setRefreshToken($refreshtoken);
450  $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
451  }
452  $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
453  if (is_object($tokenobj)) {
454  $token = $tokenobj->getAccessToken();
455  } else {
456  $object->error = "Token not found";
457  return -1;
458  }
459  } catch (Exception $e) {
460  print $e->getMessage();
461  }
462 
463  $cm = new ClientManager();
464  $client = $cm->make([
465  'host' => $object->host,
466  'port' => $object->port,
467  'encryption' => 'ssl',
468  'validate_cert' => true,
469  'protocol' => 'imap',
470  'username' => $object->login,
471  'password' => $token,
472  'authentication' => "oauth",
473  ]);
474  } else {
475  // Mode login/pass with PHP-IMAP
476  $cm = new ClientManager();
477  $client = $cm->make([
478  'host' => $object->host,
479  'port' => $object->port,
480  'encryption' => 'ssl',
481  'validate_cert' => true,
482  'protocol' => 'imap',
483  'username' => $object->login,
484  'password' => $object->password,
485  'authentication' => "login",
486  ]);
487  }
488  try {
489  $client->connect();
490  } catch (ConnectionFailedException $e) {
491  print $e->getMessage();
492  }
493 
494  $f = $client->getFolders(false, $object->source_directory);
495  $nbemail = $f[0]->examine()["exists"];
496  $morehtml .= $nbemail;
497  } else {
498  try {
499  if ($sourcedir) {
500  //$connectstringsource = $connectstringserver.imap_utf7_encode($sourcedir);
501  $connectstringsource = $connectstringserver.$object->getEncodedUtf7($sourcedir);
502  }
503  if ($targetdir) {
504  //$connectstringtarget = $connectstringserver.imap_utf7_encode($targetdir);
505  $connectstringtarget = $connectstringserver.$object->getEncodedUtf7($targetdir);
506  }
507 
508  $timeoutconnect = empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 5 : $conf->global->MAIN_USE_CONNECT_TIMEOUT;
509  $timeoutread = empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 20 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT;
510 
511  dol_syslog("imap_open connectstring=".$connectstringsource." login=".$object->login." password=".$object->password." timeoutconnect=".$timeoutconnect." timeoutread=".$timeoutread);
512 
513  $result1 = imap_timeout(IMAP_OPENTIMEOUT, $timeoutconnect); // timeout seems ignored with ssl connect
514  $result2 = imap_timeout(IMAP_READTIMEOUT, $timeoutread);
515  $result3 = imap_timeout(IMAP_WRITETIMEOUT, 5);
516  $result4 = imap_timeout(IMAP_CLOSETIMEOUT, 5);
517 
518  dol_syslog("result1=".$result1." result2=".$result2." result3=".$result3." result4=".$result4);
519 
520  $connection = imap_open($connectstringsource, $object->login, $object->password);
521 
522  //dol_syslog("end imap_open connection=".var_export($connection, true));
523  } catch (Exception $e) {
524  print $e->getMessage();
525  }
526 
527  if (!$connection) {
528  $morehtml .= 'Failed to open IMAP connection '.$connectstringsource;
529  if (function_exists('imap_last_error')) {
530  $morehtml .= '<br>'.imap_last_error();
531  }
532  dol_syslog("Error ".$morehtml, LOG_WARNING);
533  //var_dump(imap_errors())
534  } else {
535  dol_syslog("Imap connected. Now we call imap_num_msg()");
536  $morehtml .= imap_num_msg($connection);
537  }
538 
539  if ($connection) {
540  dol_syslog("Imap close");
541  imap_close($connection);
542  }
543  }
544  } else {
545  $morehtml .= '<a class="flat" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=scan&token='.newToken().'">'.img_picto('', 'refresh', 'class="paddingrightonly"').$langs->trans("Refresh").'</a>';
546  }
547 
548  $morehtml .= $form->textwithpicto('', 'connect string '.$connectstringserver);
549  } else {
550  $morehtml .= 'IMAP functions not available on your PHP. ';
551  }
552 
553  dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref.'<div class="refidno">'.$morehtml.'</div>', '', 0, '', '', 0, '');
554 
555  print '<div class="fichecenter">';
556  print '<div class="fichehalfleft">';
557  print '<div class="underbanner clearboth"></div>';
558  print '<table class="border centpercent tableforfield">'."\n";
559 
560  // Common attributes
561  //$keyforbreak='fieldkeytoswithonsecondcolumn';
562  include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
563 
564  // Other attributes
565  include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
566 
567  print '</table>';
568 
569 
570  print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
571  print '<input type="hidden" name="token" value="'.newToken().'">';
572  print '<input type="hidden" name="action" value="updatefiltersactions">';
573  print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
574  print '<input type="hidden" name="id" value="'.$object->id.'">';
575 
576  // Filters
577  print '<div class="div-table-responsive-no-min">';
578  print '<table id="tablelineoffilters" class="noborder margintable noshadow">';
579  print '<tr class="liste_titre nodrag nodrop">';
580  print '<td>'.img_picto('', 'filter', 'class="pictofixedwidth opacitymedium"').$form->textwithpicto($langs->trans("Filters"), $langs->trans("EmailCollectorFilterDesc")).'</td><td></td><td></td>';
581  print '</tr>';
582  // Add filter
583  print '<tr class="oddeven nodrag nodrop">';
584  print '<td>';
585  $arrayoftypes = array(
586  'from'=>array('label'=>'MailFrom', 'data-placeholder'=>$langs->trans('SearchString')),
587  'to'=>array('label'=>'MailTo', 'data-placeholder'=>$langs->trans('SearchString')),
588  'cc'=>array('label'=>'Cc', 'data-placeholder'=>$langs->trans('SearchString')),
589  'bcc'=>array('label'=>'Bcc', 'data-placeholder'=>$langs->trans('SearchString')),
590  'subject'=>array('label'=>'Subject', 'data-placeholder'=>$langs->trans('SearchString')),
591  'body'=>array('label'=>'Body', 'data-placeholder'=>$langs->trans('SearchString')),
592  // disabled because PHP imap_search is not compatible IMAPv4, only IMAPv2
593  //'header'=>array('label'=>'Header', 'data-placeholder'=>'HeaderKey SearchString'), // HEADER key value
594  //'X1'=>'---',
595  //'notinsubject'=>array('label'=>'SubjectNotIn', 'data-placeholder'=>'SearchString'),
596  //'notinbody'=>array('label'=>'BodyNotIn', 'data-placeholder'=>'SearchString'),
597  'X2'=>'---',
598  'seen'=>array('label'=>'AlreadyRead', 'data-noparam'=>1),
599  'unseen'=>array('label'=>'NotRead', 'data-noparam'=>1),
600  'unanswered'=>array('label'=>'Unanswered', 'data-noparam'=>1),
601  'answered'=>array('label'=>'Answered', 'data-noparam'=>1),
602  'smaller'=>array('label'=>'SmallerThan', 'data-placeholder'=>$langs->trans('NumberOfBytes')),
603  'larger'=>array('label'=>'LargerThan', 'data-placeholder'=>$langs->trans('NumberOfBytes')),
604  'X3'=>'---',
605  'withtrackingid'=>array('label'=>'WithDolTrackingID', 'data-noparam'=>1),
606  'withouttrackingid'=>array('label'=>'WithoutDolTrackingID', 'data-noparam'=>1),
607  'withtrackingidinmsgid'=>array('label'=>'WithDolTrackingIDInMsgId', 'data-noparam'=>1),
608  'withouttrackingidinmsgid'=>array('label'=>'WithoutDolTrackingIDInMsgId', 'data-noparam'=>1),
609  'X4'=>'---',
610  'isnotanswer'=>array('label'=>'IsNotAnAnswer', 'data-noparam'=>1),
611  'isanswer'=>array('label'=>'IsAnAnswer', 'data-noparam'=>1)
612  );
613  print $form->selectarray('filtertype', $arrayoftypes, '', 1, 0, 0, '', 1, 0, 0, '', 'maxwidth300', 1, '', 2);
614 
615  print "\n";
616  print '<script>';
617  print 'jQuery("#filtertype").change(function() {
618  console.log("We change a filter");
619  if (jQuery("#filtertype option:selected").attr("data-noparam")) {
620  jQuery("#rulevalue").attr("placeholder", "");
621  jQuery("#rulevalue").text(""); jQuery("#rulevalue").prop("disabled", true);
622  }
623  else { jQuery("#rulevalue").prop("disabled", false); }
624  jQuery("#rulevalue").attr("placeholder", (jQuery("#filtertype option:selected").attr("data-placeholder")));
625  ';
626  /*$noparam = array();
627  foreach ($arrayoftypes as $key => $value)
628  {
629  if ($value['noparam']) $noparam[] = $key;
630  }*/
631  print '})';
632  print '</script>'."\n";
633 
634  print '</td><td>';
635  print '<input type="text" name="rulevalue" id="rulevalue">';
636  print '</td>';
637  print '<td class="right"><input type="submit" name="addfilter" id="addfilter" class="flat button small" value="'.$langs->trans("Add").'"></td>';
638  print '</tr>';
639  // List filters
640  foreach ($object->filters as $rulefilter) {
641  $rulefilterobj = new EmailCollectorFilter($db);
642  $rulefilterobj->fetch($rulefilter['id']);
643 
644  print '<tr class="oddeven">';
645  print '<td title="'.dol_escape_htmltag($langs->trans("Filter").': '.$rulefilter['type']).'">';
646  print $langs->trans($arrayoftypes[$rulefilter['type']]['label']);
647  print '</td>';
648  print '<td>'.$rulefilter['rulevalue'].'</td>';
649  print '<td class="right">';
650  print ' <a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletefilter&token='.urlencode(newToken()).'&filterid='.$rulefilter['id'].'">'.img_delete().'</a>';
651  print '</td>';
652  print '</tr>';
653  }
654 
655  print '</tr>';
656  print '</table>';
657  print '</div>';
658 
659  print '<div class="clearboth"></div><br>';
660 
661  // Operations
662  print '<div class="div-table-responsive">';
663  print '<table id="tablelines" class="noborder margintable noshadow">';
664  print '<tr class="liste_titre nodrag nodrop">';
665  print '<td>'.img_picto('', 'technic', 'class="pictofixedwidth"').$form->textwithpicto($langs->trans("EmailcollectorOperations"), $langs->trans("EmailcollectorOperationsDesc")).'</td><td></td><td></td><td></td>';
666  print '</tr>';
667 
668  $arrayoftypes = array(
669  'loadthirdparty' => $langs->trans('LoadThirdPartyFromName', $langs->transnoentities("ThirdPartyName")),
670  'loadandcreatethirdparty' => $langs->trans('LoadThirdPartyFromNameOrCreate', $langs->transnoentities("ThirdPartyName")),
671  'recordjoinpiece' => 'AttachJoinedDocumentsToObject',
672  'recordevent' => 'RecordEvent'
673  );
674  $arrayoftypesnocondition = $arrayoftypes;
675  if (isModEnabled('project')) {
676  $arrayoftypes['project'] = 'CreateLeadAndThirdParty';
677  }
678  $arrayoftypesnocondition['project'] = 'CreateLeadAndThirdParty';
679  if (isModEnabled('ticket')) {
680  $arrayoftypes['ticket'] = 'CreateTicketAndThirdParty';
681  }
682  $arrayoftypesnocondition['ticket'] = 'CreateTicketAndThirdParty';
683  if (isModEnabled('recruitment')) {
684  $arrayoftypes['candidature'] = 'CreateCandidature';
685  }
686  $arrayoftypesnocondition['candidature'] = 'CreateCandidature';
687 
688  // support hook for add action
689  $parameters = array('arrayoftypes' => $arrayoftypes);
690  $res = $hookmanager->executeHooks('addMoreActionsEmailCollector', $parameters, $object, $action);
691 
692  if ($res) {
693  $arrayoftypes = $hookmanager->resArray;
694  } else {
695  foreach ($hookmanager->resArray as $k => $desc) {
696  $arrayoftypes[$k] = $desc;
697  }
698  }
699 
700  // Add operation
701  print '<tr class="oddeven nodrag nodrop">';
702  print '<td>';
703  print $form->selectarray('operationtype', $arrayoftypes, '', 1, 0, 0, '', 1, 0, 0, '', 'maxwidth300', 1);
704  print '</td><td>';
705  //print '<input type="text" name="operationparam">';
706  $htmltext = $langs->transnoentitiesnoconv("OperationParamDesc");
707  print $form->textwithpicto('<input type="text" name="operationparam">', $htmltext, 1, 'help', '', 0, 2, 'operationparamtt');
708  print '</td>';
709  print '<td>';
710  print '</td>';
711  print '<td class="right"><input type="submit" name="addoperation" id="addoperation" class="flat button small" value="'.$langs->trans("Add").'"></td>';
712  print '</tr>';
713  // List operations
714  $nboflines = count($object->actions);
715  $table_element_line = 'emailcollector_emailcollectoraction';
716  $fk_element = 'position';
717  $i = 0;
718  foreach ($object->actions as $ruleaction) {
719  $ruleactionobj = new EmailcollectorAction($db);
720  $ruleactionobj->fetch($ruleaction['id']);
721 
722  print '<tr class="drag drop oddeven" id="row-'.$ruleaction['id'].'">';
723  print '<td title="'.dol_escape_htmltag($langs->trans("Operation").': '.$ruleaction['type']).'">';
724  print '<!-- type of action: '.$ruleaction['type'].' -->';
725  if (array_key_exists($ruleaction['type'], $arrayoftypes)) {
726  print $langs->trans($arrayoftypes[$ruleaction['type']]);
727  } else {
728  if (array_key_exists($ruleaction['type'], $arrayoftypesnocondition)) {
729  print '<span class="opacitymedium">'.$langs->trans($arrayoftypesnocondition[$ruleaction['type']]).' - '.$langs->trans("Disabled").'</span>';
730  }
731  }
732 
733  if (in_array($ruleaction['type'], array('recordevent'))) {
734  print $form->textwithpicto('', $langs->transnoentitiesnoconv('IfTrackingIDFoundEventWillBeLinked'));
735  } elseif (in_array($ruleaction['type'], array('loadthirdparty', 'loadandcreatethirdparty'))) {
736  print $form->textwithpicto('', $langs->transnoentitiesnoconv('EmailCollectorLoadThirdPartyHelp'));
737  }
738  print '</td>';
739  print '<td class="wordbreak minwidth300 small">';
740  if ($action == 'editoperation' && $ruleaction['id'] == $operationid) {
741  print '<input type="text" class="quatrevingtquinzepercent" name="operationparam2" value="'.dol_escape_htmltag($ruleaction['actionparam']).'"><br>';
742  print '<input type="hidden" name="rowidoperation2" value="'.$ruleaction['id'].'">';
743  print '<input type="submit" class="button small button-save" name="saveoperation2" value="'.$langs->trans("Save").'">';
744  print '<input type="submit" class="button small button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
745  } else {
746  print dol_escape_htmltag($ruleaction['actionparam']);
747  }
748  print '</td>';
749  // Move up/down
750  print '<td class="center linecolmove tdlineupdown">';
751  if ($i > 0) {
752  print '<a class="lineupdown" href="'.$_SERVER['PHP_SELF'].'?action=up&amp;rowid='.$ruleaction['id'].'">'.img_up('default', 0, 'imgupforline').'</a>';
753  }
754  if ($i < count($object->actions) - 1) {
755  print '<a class="lineupdown" href="'.$_SERVER['PHP_SELF'].'?action=down&amp;rowid='.$ruleaction['id'].'">'.img_down('default', 0, 'imgdownforline').'</a>';
756  }
757  print '</td>';
758  // Delete
759  print '<td class="right nowraponall">';
760  print '<a class="editfielda marginrightonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=editoperation&token='.newToken().'&operationid='.$ruleaction['id'].'">'.img_edit().'</a>';
761  print ' <a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deleteoperation&token='.newToken().'&operationid='.$ruleaction['id'].'">'.img_delete().'</a>';
762  print '</td>';
763  print '</tr>';
764  $i++;
765  }
766 
767  print '</tr>';
768  print '</table>';
769  print '</div>';
770 
771  if (!empty($conf->use_javascript_ajax)) {
772  $urltorefreshaftermove = DOL_URL_ROOT.'/admin/emailcollector_card.php?id='.$id;
773  include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
774  }
775 
776  print '</form>';
777 
778  print '</div>';
779  print '</div>'; // End <div class="fichecenter">
780 
781 
782  print '<div class="clearboth"></div><br>';
783 
784  print dol_get_fiche_end();
785 
786  // Buttons for actions
787  if ($action != 'presend' && $action != 'editline') {
788  print '<div class="tabsAction">'."\n";
789  $parameters = array();
790  $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
791  if ($reshook < 0) {
792  setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
793  }
794 
795  if (empty($reshook)) {
796  // Edit
797  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>';
798 
799  // Clone
800  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>';
801 
802  // Collect now
803  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>';
804 
805  if (count($object->actions) > 0) {
806  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>';
807  } else {
808  print '<div class="inline-block divButAction"><a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->trans("NoOperations")).'">'.$langs->trans("CollectNow").'</a></div>';
809  }
810 
811  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>';
812  }
813  print '</div>'."\n";
814  }
815 
816  if (!empty($debuginfo)) {
817  print info_admin($debuginfo);
818  }
819 }
820 
821 // End of page
822 llxFooter();
823 $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.
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.