1<?php
2/* Copyright (C) 2004      Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2005-2015 Laurent Destailleur  <eldy@users.sourceforge.org>
4 * Copyright (C) 2013      Juanjo Menent		    <jmenent@2byte.es>
5 * Copyright (C) 2015      Bahfir Abbes         <contact@dolibarrpar.org>
6 * Copyright (C) 2020      Thibault FOUCART     <suport@ptibogxiv.net>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22/**
23 *	    \file       htdocs/admin/notification.php
24 *		\ingroup    notification
25 *		\brief      Page to setup notification module
26 */
27
28require '../main.inc.php';
29require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
31require_once DOL_DOCUMENT_ROOT.'/core/triggers/interface_50_modNotification_Notification.class.php';
32
33// Load translation files required by the page
34$langs->loadLangs(array('admin', 'other', 'orders', 'propal', 'bills', 'errors', 'mails'));
35
36// Security check
37if (!$user->admin) {
38	accessforbidden();
39}
40
41$action = GETPOST('action', 'aZ09');
42$error = 0;
43
44
45/*
46 * Actions
47 */
48
49// Action to update or add a constant
50if ($action == 'settemplates')
51{
52	$db->begin();
53
54	if (!$error && is_array($_POST))
55	{
56		$reg = array();
57		foreach ($_POST as $key => $val)
58		{
59			if (!preg_match('/^constvalue_(.*)_TEMPLATE/', $key, $reg)) continue;
60
61			$triggername = $reg[1];
62			$constvalue = GETPOST($key, 'alpha');
63			$consttype = 'emailtemplate:xxx';
64			$tmparray = explode(':', $constvalue);
65			if (!empty($tmparray[0]) && !empty($tmparray[1])) {
66				$constvalue = $tmparray[0];
67				$consttype = 'emailtemplate:'.$tmparray[1];
68				//var_dump($constvalue);
69				//var_dump($consttype);
70				$res = dolibarr_set_const($db, $triggername.'_TEMPLATE', $constvalue, $consttype, 0, '', $conf->entity);
71				if ($res < 0) {
72					$error++;
73					break;
74				}
75			} else {
76				$res = dolibarr_del_const($db, $triggername.'_TEMPLATE', $conf->entity);
77			}
78		}
79	}
80
81
82	if (!$error)
83	{
84		$db->commit();
85
86		setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
87	} else {
88		$db->rollback();
89
90		setEventMessages($langs->trans("Error"), null, 'errors');
91	}
92}
93
94if ($action == 'setvalue' && $user->admin)
95{
96	$db->begin();
97
98	$result = dolibarr_set_const($db, "NOTIFICATION_EMAIL_FROM", GETPOST("email_from", "restricthtml"), 'chaine', 0, '', $conf->entity);
99	if ($result < 0) $error++;
100
101
102	if (!$error)
103	{
104		$db->commit();
105
106		setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
107	} else {
108		$db->rollback();
109
110		setEventMessages($langs->trans("Error"), null, 'errors');
111	}
112}
113
114
115if ($action == 'setfixednotif' && $user->admin)
116{
117	$db->begin();
118
119	if (!$error && is_array($_POST))
120	{
121		$reg = array();
122		foreach ($_POST as $key => $val)
123		{
124			if (!preg_match('/^NOTIF_(.*)_key$/', $key, $reg)) continue;
125
126			$newval = '';
127			$newkey = '';
128
129			$shortkey = preg_replace('/_key$/', '', $key);
130			//print $shortkey.'<br>';
131
132			if (preg_match('/^NOTIF_(.*)_old_(.*)_key/', $key, $reg))
133			{
134				dolibarr_del_const($db, 'NOTIFICATION_FIXEDEMAIL_'.$reg[1].'_THRESHOLD_HIGHER_'.$reg[2], $conf->entity);
135
136				$newkey = 'NOTIFICATION_FIXEDEMAIL_'.$reg[1].'_THRESHOLD_HIGHER_'.((int) GETPOST($shortkey.'_amount'));
137				$newval = GETPOST($shortkey.'_key');
138				//print $newkey.' - '.$newval.'<br>';
139			} elseif (preg_match('/^NOTIF_(.*)_new_key/', $key, $reg))
140			{
141				// Add a new entry
142				$newkey = 'NOTIFICATION_FIXEDEMAIL_'.$reg[1].'_THRESHOLD_HIGHER_'.((int) GETPOST($shortkey.'_amount'));
143				$newval = GETPOST($shortkey.'_key');
144			}
145
146			if ($newkey && $newval)
147			{
148				$result = dolibarr_set_const($db, $newkey, $newval, 'chaine', 0, '', $conf->entity);
149			}
150		}
151	}
152
153  	if (!$error)
154	{
155		$db->commit();
156
157		setEventMessages($langs->trans("SetupSaved"), null, 'mesgs');
158	} else {
159		$db->rollback();
160
161		setEventMessages($langs->trans("Error"), null, 'errors');
162	}
163}
164
165
166
167/*
168 *	View
169 */
170
171$form = new Form($db);
172$notify = new Notify($db);
173
174llxHeader('', $langs->trans("NotificationSetup"));
175
176$linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php?restore_lastsearch_values=1">'.$langs->trans("BackToModuleList").'</a>';
177print load_fiche_titre($langs->trans("NotificationSetup"), $linkback, 'title_setup');
178
179print '<span class="opacitymedium">';
180print $langs->trans("NotificationsDesc").'<br>';
181print $langs->trans("NotificationsDescUser").'<br>';
182if (!empty($conf->societe->enabled)) print $langs->trans("NotificationsDescContact").'<br>';
183print $langs->trans("NotificationsDescGlobal").'<br>';
184print '</span>';
185print '<br>';
186
187print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
188print '<input type="hidden" name="token" value="'.newToken().'">';
189print '<input type="hidden" name="action" value="setvalue">';
190
191print '<table class="noborder centpercent">';
192print '<tr class="liste_titre">';
193print '<td>'.$langs->trans("Parameter").'</td>';
194print '<td>'.$langs->trans("Value").'</td>';
195print "</tr>\n";
196
197print '<tr class="oddeven"><td>';
198print $langs->trans("NotificationEMailFrom").'</td>';
199print '<td>';
200print '<input size="32" type="email" name="email_from" value="'.$conf->global->NOTIFICATION_EMAIL_FROM.'">';
201if (!empty($conf->global->NOTIFICATION_EMAIL_FROM) && !isValidEmail($conf->global->NOTIFICATION_EMAIL_FROM)) print ' '.img_warning($langs->trans("ErrorBadEMail"));
202print '</td>';
203print '</tr>';
204print '</table>';
205
206print '<div class="center"><input type="submit" class="button button-save" value="'.$langs->trans("Save").'"></div>';
207
208print '</form>';
209
210
211print '<br><br>';
212
213
214print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
215print '<input type="hidden" name="token" value="'.newToken().'">';
216print '<input type="hidden" name="action" value="settemplates">';
217
218// Notification per contacts
219$title = $langs->trans("ListOfNotificationsPerUser");
220if (!empty($conf->societe->enabled)) $title = $langs->trans("ListOfNotificationsPerUserOrContact");
221print load_fiche_titre($title, '', '');
222
223// Load array of available notifications
224$notificationtrigger = new InterfaceNotification($db);
225$listofnotifiedevents = $notificationtrigger->getListOfManagedEvents();
226
227
228if ($conf->global->MAIN_FEATURES_LEVEL >= 2) {
229	// Editing global variables not related to a specific theme
230	$constantes = array();
231	foreach ($listofnotifiedevents as $notifiedevent)
232	{
233		$label = $langs->trans("Notify_".$notifiedevent['code']); //!=$langs->trans("Notify_".$notifiedevent['code'])?$langs->trans("Notify_".$notifiedevent['code']):$notifiedevent['label'];
234		$elementLabel = $langs->trans(ucfirst($notifiedevent['elementtype']));
235
236		if ($notifiedevent['elementtype'] == 'order_supplier') $elementLabel = $langs->trans('SupplierOrder');
237		elseif ($notifiedevent['elementtype'] == 'propal') $elementLabel = $langs->trans('Proposal');
238		elseif ($notifiedevent['elementtype'] == 'facture') $elementLabel = $langs->trans('Bill');
239		elseif ($notifiedevent['elementtype'] == 'commande') $elementLabel = $langs->trans('Order');
240		elseif ($notifiedevent['elementtype'] == 'ficheinter') $elementLabel = $langs->trans('Intervention');
241		elseif ($notifiedevent['elementtype'] == 'shipping') $elementLabel = $langs->trans('Shipping');
242		elseif ($notifiedevent['elementtype'] == 'expensereport') $elementLabel = $langs->trans('ExpenseReport');
243
244		if ($notifiedevent['elementtype'] == 'propal')              $model = 'propal_send';
245		elseif ($notifiedevent['elementtype'] == 'commande')        $model = 'order_send';
246		elseif ($notifiedevent['elementtype'] == 'facture')         $model = 'facture_send';
247		elseif ($notifiedevent['elementtype'] == 'shipping')        $model = 'shipping_send';
248		elseif ($notifiedevent['elementtype'] == 'ficheinter')      $model = 'fichinter_send';
249		elseif ($notifiedevent['elementtype'] == 'expensereport')   $model = 'expensereport_send';
250		elseif ($notifiedevent['elementtype'] == 'order_supplier')	$model = 'order_supplier_send';
251		//elseif ($notifiedevent['elementtype'] == 'invoice_supplier') $model = 'invoice_supplier_send';
252		elseif ($notifiedevent['elementtype'] == 'member')          $model = 'member';
253
254		$constantes[$notifiedevent['code'].'_TEMPLATE'] = array('type'=>'emailtemplate:'.$model, 'label'=>$label);
255	}
256
257	$helptext = '';
258	form_constantes($constantes, 2, $helptext);
259} else {
260	print '<table class="noborder centpercent">';
261	print '<tr class="liste_titre">';
262	print '<td>'.$langs->trans("Label").'</td>';
263	/*print '<td>'.$langs->trans("Code").'</td>';
264	print '<td>'.$langs->trans("Label").'</td>';*/
265	//print '<td class="right">'.$langs->trans("NbOfTargetedContacts").'</td>';
266	print "</tr>\n";
267
268	print '<tr class="oddeven">';
269	print '<td>';
270
271	$i = 0;
272	foreach ($listofnotifiedevents as $notifiedevent)
273	{
274		$label = $langs->trans("Notify_".$notifiedevent['code']); //!=$langs->trans("Notify_".$notifiedevent['code'])?$langs->trans("Notify_".$notifiedevent['code']):$notifiedevent['label'];
275		$elementLabel = $langs->trans(ucfirst($notifiedevent['elementtype']));
276
277		if ($notifiedevent['elementtype'] == 'order_supplier') $elementLabel = $langs->trans('SupplierOrder');
278		elseif ($notifiedevent['elementtype'] == 'propal') $elementLabel = $langs->trans('Proposal');
279		elseif ($notifiedevent['elementtype'] == 'facture') $elementLabel = $langs->trans('Bill');
280		elseif ($notifiedevent['elementtype'] == 'commande') $elementLabel = $langs->trans('Order');
281		elseif ($notifiedevent['elementtype'] == 'ficheinter') $elementLabel = $langs->trans('Intervention');
282		elseif ($notifiedevent['elementtype'] == 'shipping') $elementLabel = $langs->trans('Shipping');
283		elseif ($notifiedevent['elementtype'] == 'expensereport') $elementLabel = $langs->trans('ExpenseReport');
284
285		if ($i) print ', ';
286		print $label;
287
288		$i++;
289	}
290
291	print '</td></tr>';
292	print '</table>';
293}
294
295print '<div class="center"><input type="submit" class="button button-save" value="'.$langs->trans("Save").'"></div>';
296
297print '</form>';
298
299
300print '<br><br>';
301
302
303print '<form method="post" action="'.$_SERVER["PHP_SELF"].'">';
304print '<input type="hidden" name="token" value="'.newToken().'">';
305print '<input type="hidden" name="action" value="setfixednotif">';
306
307print load_fiche_titre($langs->trans("ListOfFixedNotifications"), '', '');
308
309print '<table class="noborder centpercent">';
310print '<tr class="liste_titre">';
311print '<td>'.$langs->trans("Module").'</td>';
312print '<td>'.$langs->trans("Code").'</td>';
313print '<td>'.$langs->trans("Label").'</td>';
314print '<td>'.$langs->trans("FixedEmailTarget").'</td>';
315print '<td>'.$langs->trans("Threshold").'</td>';
316print '<td></td>';
317print "</tr>\n";
318
319foreach ($listofnotifiedevents as $notifiedevent)
320{
321	$label = $langs->trans("Notify_".$notifiedevent['code']); //!=$langs->trans("Notify_".$notifiedevent['code'])?$langs->trans("Notify_".$notifiedevent['code']):$notifiedevent['label'];
322
323	$elementLabel = $langs->trans(ucfirst($notifiedevent['elementtype']));
324	// Special cases
325	if ($notifiedevent['elementtype'] == 'order_supplier') $elementLabel = $langs->trans('SupplierOrder');
326	elseif ($notifiedevent['elementtype'] == 'propal') $elementLabel = $langs->trans('Proposal');
327	elseif ($notifiedevent['elementtype'] == 'facture') $elementLabel = $langs->trans('Bill');
328	elseif ($notifiedevent['elementtype'] == 'commande') $elementLabel = $langs->trans('Order');
329	elseif ($notifiedevent['elementtype'] == 'ficheinter') $elementLabel = $langs->trans('Intervention');
330	elseif ($notifiedevent['elementtype'] == 'shipping') $elementLabel = $langs->trans('Shipping');
331	elseif ($notifiedevent['elementtype'] == 'expensereport') $elementLabel = $langs->trans('ExpenseReport');
332
333	print '<tr class="oddeven">';
334	print '<td>'.$elementLabel.'</td>';
335	print '<td>'.$notifiedevent['code'].'</td>';
336	print '<td>'.$label.'</td>';
337	print '<td>';
338	// Notification with threshold
339	foreach ($conf->global as $key => $val)
340	{
341		if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifiedevent['code'].'_THRESHOLD_HIGHER_(.*)/', $key, $reg)) continue;
342
343		$param = 'NOTIFICATION_FIXEDEMAIL_'.$notifiedevent['code'].'_THRESHOLD_HIGHER_'.$reg[1];
344		$value = GETPOST('NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_key') ?GETPOST('NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_key', 'alpha') : $conf->global->$param;
345
346		$s = '<input type="text" size="32" name="NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_key" value="'.dol_escape_htmltag($value).'">'; // Do not use type="email" here, we must be able to enter a list of email with , separator.
347		$arrayemail = explode(',', $value);
348		$showwarning = 0;
349		foreach ($arrayemail as $keydet => $valuedet)
350		{
351			$valuedet = trim($valuedet);
352			if (!empty($valuedet) && !isValidEmail($valuedet, 1)) $showwarning++;
353		}
354		if ((!empty($conf->global->$param)) && $showwarning) $s .= ' '.img_warning($langs->trans("ErrorBadEMail"));
355		print $form->textwithpicto($s, $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients").'<br>'.$langs->trans("YouCanAlsoUseSupervisorKeyword"), 1, 'help', '', 0, 2);
356		print '<br>';
357	}
358	// New entry input fields
359	$s = '<input type="text" size="32" name="NOTIF_'.$notifiedevent['code'].'_new_key" value="">'; // Do not use type="email" here, we must be able to enter a list of email with , separator.
360	print $form->textwithpicto($s, $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients").'<br>'.$langs->trans("YouCanAlsoUseSupervisorKeyword"), 1, 'help', '', 0, 2);
361	print '</td>';
362
363	print '<td>';
364	// Notification with threshold
365	foreach ($conf->global as $key => $val)
366	{
367		if ($val == '' || !preg_match('/^NOTIFICATION_FIXEDEMAIL_'.$notifiedevent['code'].'_THRESHOLD_HIGHER_(.*)/', $key, $reg)) continue;
368
369		print $langs->trans("AmountHT").' >= <input type="text" size="4" name="NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_amount" value="'.dol_escape_htmltag($reg[1]).'">';
370		print '<br>';
371	}
372	// New entry input fields
373	print $langs->trans("AmountHT").' >= <input type="text" size="4" name="NOTIF_'.$notifiedevent['code'].'_new_amount" value="">';
374	print '</td>';
375
376	print '<td>';
377	// TODO Add link to show message content
378
379	print '</td>';
380	print '</tr>';
381}
382print '</table>';
383
384print '<div class="opacitymedium">';
385print '* '.$langs->trans("GoOntoUserCardToAddMore").'<br>';
386if (!empty($conf->societe->enabled)) print '** '.$langs->trans("GoOntoContactCardToAddMore").'<br>';
387
388print '</div>';
389
390print '<br>';
391
392print '<div class="center"><input type="submit" class="button button-save" value="'.$langs->trans("Save").'"></div>';
393
394print '</form>';
395
396// End of page
397llxFooter();
398$db->close();
399