1<?php
2/* Copyright (C) 2003      Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2017 Laurent Destailleur  <eldy@users.sourceforge.net>
4 * Copyright (C) 2010-2014 Juanjo Menent		<jmenent@2byte.es>
5 * Copyright (C) 2015      Marcos García        <marcosgdf@gmail.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21/**
22 *	    \file       htdocs/societe/notify/card.php
23 *      \ingroup    societe notification
24 *		\brief      Tab for notifications of third party
25 */
26
27require '../../main.inc.php';
28require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
29require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
30require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
31require_once DOL_DOCUMENT_ROOT.'/core/triggers/interface_50_modNotification_Notification.class.php';
32
33$langs->loadLangs(array("companies", "mails", "admin", "other", "errors"));
34
35$socid     = GETPOST("socid", 'int');
36$action    = GETPOST('action', 'aZ09');
37$contactid = GETPOST('contactid', 'alpha'); // May be an int or 'thirdparty'
38$actionid  = GETPOST('actionid', 'int');
39$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
40
41// Security check
42if ($user->socid) {
43	$socid = $user->socid;
44}
45$result = restrictedArea($user, 'societe', '', '');
46
47$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
48$sortfield = GETPOST("sortfield", 'alpha');
49$sortorder = GETPOST("sortorder", 'alpha');
50$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
51if (!$sortorder) {
52	$sortorder = "DESC";
53}
54if (!$sortfield) {
55	$sortfield = "n.daten";
56}
57if (empty($page) || $page == -1) {
58	$page = 0;
59}
60$offset = $limit * $page;
61$pageprev = $page - 1;
62$pagenext = $page + 1;
63
64$now = dol_now();
65
66$object = new Societe($db);
67
68// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
69$hookmanager->initHooks(array('thirdpartynotification', 'globalcard'));
70
71
72
73/*
74 * Actions
75 */
76
77$parameters = array('id'=>$socid);
78$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
79if ($reshook < 0) {
80	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
81}
82
83if (empty($reshook)) {
84	$error = 0;
85
86	// Add a notification
87	if ($action == 'add') {
88		if (empty($contactid)) {
89			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Contact")), null, 'errors');
90			$error++;
91		}
92		if ($actionid <= 0) {
93			setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Action")), null, 'errors');
94			$error++;
95		}
96
97		if (!$error) {
98			$db->begin();
99
100			$sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def";
101			$sql .= " WHERE fk_soc=".((int) $socid)." AND fk_contact=".((int) $contactid)." AND fk_action=".((int) $actionid);
102			if ($db->query($sql)) {
103				$sql = "INSERT INTO ".MAIN_DB_PREFIX."notify_def (datec,fk_soc, fk_contact, fk_action)";
104				$sql .= " VALUES ('".$db->idate($now)."',".((int) $socid).",".((int) $contactid).",".((int) $actionid).")";
105
106				if (!$db->query($sql)) {
107					$error++;
108					dol_print_error($db);
109				}
110			} else {
111				dol_print_error($db);
112			}
113
114			if (!$error) {
115				$db->commit();
116			} else {
117				$db->rollback();
118			}
119		}
120	}
121
122	// Remove a notification
123	if ($action == 'delete') {
124		$sql = "DELETE FROM ".MAIN_DB_PREFIX."notify_def where rowid=".GETPOST('actid', 'int');
125		$db->query($sql);
126	}
127}
128
129
130
131/*
132 *	View
133 */
134
135$form = new Form($db);
136
137$object = new Societe($db);
138$result = $object->fetch($socid);
139
140$title = $langs->trans("ThirdParty").' - '.$langs->trans("Notification");
141if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) {
142	$title = $object->name.' - '.$langs->trans("Notification");
143}
144$help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas';
145
146llxHeader('', $title, $help_url);
147
148
149if ($result > 0) {
150	$langs->load("other");
151
152	$head = societe_prepare_head($object);
153
154	print dol_get_fiche_head($head, 'notify', $langs->trans("ThirdParty"), -1, 'company');
155
156	$linkback = '<a href="'.DOL_URL_ROOT.'/societe/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
157
158	dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom');
159
160	print '<div class="fichecenter">';
161
162	print '<div class="underbanner clearboth"></div>';
163	print '<table class="border centpercent tableforfield">';
164
165	// Type Prospect/Customer/Supplier
166	print '<tr><td class="titlefield">'.$langs->trans('NatureOfThirdParty').'</td><td>';
167	print $object->getTypeUrl(1);
168	print '</td></tr>';
169
170	// Prefix
171	if (!empty($conf->global->SOCIETE_USEPREFIX)) {  // Old not used prefix field
172		print '<tr><td class="titlefield">'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>';
173	}
174
175	if ($object->client) {
176		print '<tr><td class="titlefield">';
177		print $langs->trans('CustomerCode').'</td><td colspan="3">';
178		print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_client));
179		$tmpcheck = $object->check_codeclient();
180		if ($tmpcheck != 0 && $tmpcheck != -5) {
181			print ' <font class="error">('.$langs->trans("WrongCustomerCode").')</font>';
182		}
183		print '</td></tr>';
184	}
185
186	if (((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) {
187		print '<tr><td class="titlefield">';
188		print $langs->trans('SupplierCode').'</td><td colspan="3">';
189		print showValueWithClipboardCPButton(dol_escape_htmltag($object->code_fournisseur));
190		$tmpcheck = $object->check_codefournisseur();
191		if ($tmpcheck != 0 && $tmpcheck != -5) {
192			print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>';
193		}
194		print '</td></tr>';
195	}
196
197	/*print '<tr><td class="titlefield">'.$langs->trans("NbOfActiveNotifications").'</td>';   // Notification for this thirdparty
198	print '<td colspan="3">';
199	$nbofrecipientemails=0;
200	$notify=new Notify($db);
201	$tmparray = $notify->getNotificationsArray('', $object->id, null, 0, array('thirdparty'));
202	foreach($tmparray as $tmpkey => $tmpval)
203	{
204		if (! empty($tmpkey)) $nbofrecipientemails++;
205	}
206	print $nbofrecipientemails;
207	print '</td></tr>';*/
208
209	print '</table>';
210
211	print '</div>';
212
213	print dol_get_fiche_end();
214
215	print "\n";
216
217	// Help
218	print '<div class="opacitymedium hideonsmartphone">';
219	print $langs->trans("NotificationsDesc");
220	print '<br>'.$langs->trans("NotificationsDescUser");
221	print '<br>'.$langs->trans("NotificationsDescContact");
222	print '<br>'.$langs->trans("NotificationsDescGlobal");
223	print '<br>';
224	print '</div>';
225
226	print '<br>'."\n";
227
228
229	// List of notifications enabled for contacts
230	$sql = "SELECT n.rowid, n.type,";
231	$sql .= " a.code, a.label,";
232	$sql .= " c.rowid as contactid, c.lastname, c.firstname, c.email";
233	$sql .= " FROM ".MAIN_DB_PREFIX."c_action_trigger as a,";
234	$sql .= " ".MAIN_DB_PREFIX."notify_def as n,";
235	$sql .= " ".MAIN_DB_PREFIX."socpeople c";
236	$sql .= " WHERE a.rowid = n.fk_action";
237	$sql .= " AND c.rowid = n.fk_contact";
238	$sql .= " AND c.fk_soc = ".((int) $object->id);
239
240	$resql = $db->query($sql);
241	if ($resql) {
242		$num = $db->num_rows($resql);
243	} else {
244		dol_print_error($db);
245	}
246
247
248	// Add notification form
249	print load_fiche_titre($langs->trans("ListOfActiveNotifications").' <span class="opacitymedium colorblack paddingleft">('.$num.')</span>', '', '');
250
251	print '<form action="'.$_SERVER["PHP_SELF"].'?socid='.$socid.'" method="post">';
252	print '<input type="hidden" name="token" value="'.newToken().'">';
253	print '<input type="hidden" name="action" value="add">';
254
255	$param = "&socid=".$socid;
256
257	// Line with titles
258	print '<div class="div-table-responsive-no-min">';
259	print '<table class="centpercent noborder">';
260	print '<tr class="liste_titre">';
261	print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, 'width="45%"', $sortfield, $sortorder);
262	print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, 'width="35%"', $sortfield, $sortorder);
263	print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, 'width="10%"', $sortfield, $sortorder);
264	print_liste_field_titre('');
265	print "</tr>\n";
266
267	// Line to add a new subscription
268	$listofemails = $object->thirdparty_and_contact_email_array();
269	if (count($listofemails) > 0) {
270		$actions = array();
271
272		// Load array of available notifications
273		$notificationtrigger = new InterfaceNotification($db);
274		$listofmanagedeventfornotification = $notificationtrigger->getListOfManagedEvents();
275
276		foreach ($listofmanagedeventfornotification as $managedeventfornotification) {
277			$label = ($langs->trans("Notify_".$managedeventfornotification['code']) != "Notify_".$managedeventfornotification['code'] ? $langs->trans("Notify_".$managedeventfornotification['code']) : $managedeventfornotification['label']);
278			$actions[$managedeventfornotification['rowid']] = $label;
279		}
280		print '<tr class="oddeven nohover">';
281		print '<td class="nowraponall">';
282		print img_picto('', 'contact', '', false, 0, 0, '', 'paddingright').$form->selectarray("contactid", $listofemails, '', 1, 0, 0, '', 0, 0, 0, '', 'minwidth100imp maxwidthonsmartphone');
283		print '</td>';
284		print '<td class="nowraponall">';
285		print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$form->selectarray("actionid", $actions, '', 1, 0, 0, '', 0, 0, 0, '', 'minwidth100imp maxwidthonsmartphone');
286		print '</td>';
287		print '<td>';
288		$type = array('email'=>$langs->trans("EMail"));
289		print $form->selectarray("typeid", $type, '', 0, 0, 0, '', 0, 0, 0, '', 'minwidth75imp');
290		print '</td>';
291		print '<td class="right"><input type="submit" class="button" value="'.$langs->trans("Add").'"></td>';
292		print '</tr>';
293	} else {
294		print '<tr class="oddeven"><td colspan="4" class="opacitymedium">';
295		print $langs->trans("YouMustCreateContactFirst");
296		print '</td></tr>';
297	}
298
299
300	if ($num) {
301		$i = 0;
302
303		$contactstatic = new Contact($db);
304
305		while ($i < $num) {
306			$obj = $db->fetch_object($resql);
307
308			$contactstatic->id = $obj->contact_id;
309			$contactstatic->lastname = $obj->lastname;
310			$contactstatic->firstname = $obj->firstname;
311
312			print '<tr class="oddeven">';
313			print '<td>'.$contactstatic->getNomUrl(1);
314			if ($obj->type == 'email') {
315				if (isValidEmail($obj->email)) {
316					print ' &lt;'.$obj->email.'&gt;';
317				} else {
318					$langs->load("errors");
319					print ' '.img_warning().' <span class="warning">'.$langs->trans("ErrorBadEMail", $obj->email).'</span>';
320				}
321			}
322			print '</td>';
323			print '<td class="tdoverflowmax200" title="'.dol_escape_htmltag($label).'">';
324			$label = ($langs->trans("Notify_".$obj->code) != "Notify_".$obj->code ? $langs->trans("Notify_".$obj->code) : $obj->label);
325			print img_picto('', 'object_action', '', false, 0, 0, '', 'paddingright').$label;
326			print '</td>';
327			print '<td>';
328			if ($obj->type == 'email') {
329				print $langs->trans("Email");
330			}
331			if ($obj->type == 'sms') {
332				print $langs->trans("SMS");
333			}
334			print '</td>';
335			print '<td class="right"><a href="card.php?socid='.$socid.'&action=delete&token='.newToken().'&actid='.$obj->rowid.'">'.img_delete().'</a></td>';
336			print '</tr>';
337			$i++;
338		}
339		$db->free($resql);
340	}
341
342	// List of notifications enabled for fixed email
343	/*
344	foreach($conf->global as $key => $val)
345	{
346		if (! preg_match('/^NOTIFICATION_FIXEDEMAIL_(.*)/', $key, $reg)) continue;
347		print '<tr class="oddeven"><td>';
348		$listtmp=explode(',',$val);
349		$first=1;
350		foreach($listtmp as $keyemail => $valemail)
351		{
352			if (! $first) print ', ';
353			$first=0;
354			$valemail=trim($valemail);
355			//print $keyemail.' - '.$valemail.' - '.$reg[1].'<br>';
356			if (isValidEmail($valemail, 1))
357			{
358				if ($valemail == '__SUPERVISOREMAIL__') print $valemail;
359				else print ' &lt;'.$valemail.'&gt;';
360			}
361			else
362			{
363				$langs->load("errors");
364				print ' '.img_warning().' <span class="warning">'.$langs->trans("ErrorBadEMail",$valemail).'</span>;
365			}
366		}
367		print '</td>';
368		print '<td>';
369		$notifcode=preg_replace('/_THRESHOLD_.*$/','',$reg[1]);
370		$notifcodecond=preg_replace('/^.*_(THRESHOLD_)/','$1',$reg[1]);
371		$label=($langs->trans("Notify_".$notifcode)!="Notify_".$notifcode?$langs->trans("Notify_".$notifcode):$notifcode);
372		print $label;
373		if (preg_match('/^THRESHOLD_HIGHER_(.*)$/',$notifcodecond,$regcond) && ($regcond[1] > 0))
374		{
375			print ' - '.$langs->trans("IfAmountHigherThan",$regcond[1]);
376		}
377		print '</td>';
378		print '<td>';
379		print $langs->trans("Email");
380		print '</td>';
381		print '<td class="right">'.$langs->trans("SeeModuleSetup", $langs->transnoentitiesnoconv("Module600Name")).'</td>';
382		print '</tr>';
383	}*/
384
385	/*if ($user->admin)
386	{
387		print '<tr class="oddeven"><td colspan="4">';
388		print '+ <a href="'.DOL_URL_ROOT.'/admin/notification.php">'.$langs->trans("SeeModuleSetup", $langs->transnoentitiesnoconv("Module600Name")).'</a>';
389		print '</td></tr>';
390	}*/
391
392	print '</table>';
393	print '</div>';
394	print '</form>';
395
396	print '<br><br>'."\n";
397
398
399	// List
400	$sql = "SELECT n.rowid, n.daten, n.email, n.objet_type as object_type, n.objet_id as object_id, n.type,";
401	$sql .= " c.rowid as id, c.lastname, c.firstname, c.email as contactemail,";
402	$sql .= " a.code, a.label";
403	$sql .= " FROM ".MAIN_DB_PREFIX."c_action_trigger as a,";
404	$sql .= " ".MAIN_DB_PREFIX."notify as n ";
405	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as c ON n.fk_contact = c.rowid";
406	$sql .= " WHERE a.rowid = n.fk_action";
407	$sql .= " AND n.fk_soc = ".((int) $object->id);
408	$sql .= $db->order($sortfield, $sortorder);
409
410	// Count total nb of records
411	$nbtotalofrecords = '';
412	if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
413		$result = $db->query($sql);
414		$nbtotalofrecords = $db->num_rows($result);
415		if (($page * $limit) > $nbtotalofrecords) {	// if total resultset is smaller then paging size (filtering), goto and load page 0
416			$page = 0;
417			$offset = 0;
418		}
419	}
420
421	$sql .= $db->plimit($limit + 1, $offset);
422
423	$resql = $db->query($sql);
424	if ($resql) {
425		$num = $db->num_rows($resql);
426	} else {
427		dol_print_error($db);
428	}
429
430	$param = '&socid='.$object->id;
431	if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
432		$param .= '&contextpage='.$contextpage;
433	}
434	if ($limit > 0 && $limit != $conf->liste_limit) {
435		$param .= '&limit='.$limit;
436	}
437
438	print '<form method="post" action="'.$_SERVER["PHP_SELF"].'" name="formfilter">';
439	if ($optioncss != '') {
440		print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
441	}
442	print '<input type="hidden" name="token" value="'.newToken().'">';
443	print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
444	print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
445	print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
446	print '<input type="hidden" name="page" value="'.$page.'">';
447	print '<input type="hidden" name="socid" value="'.$object->id.'">';
448
449	// List of active notifications
450	print_barre_liste($langs->trans("ListOfNotificationsDone"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit);
451
452	// Line with titles
453	print '<div class="div-table-responsive-no-min">';
454	print '<table class="centpercent noborder">';
455	print '<tr class="liste_titre">';
456	print_liste_field_titre("Target", $_SERVER["PHP_SELF"], "c.lastname,c.firstname", '', $param, '', $sortfield, $sortorder);
457	print_liste_field_titre("Action", $_SERVER["PHP_SELF"], "", '', $param, '', $sortfield, $sortorder);
458	print_liste_field_titre("Type", $_SERVER["PHP_SELF"], "n.type", '', $param, '', $sortfield, $sortorder);
459	//print_liste_field_titre("Object",$_SERVER["PHP_SELF"],"",'',$param,'"',$sortfield,$sortorder);
460	print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "n.daten", '', $param, '', $sortfield, $sortorder, 'right ');
461	print '</tr>';
462
463	if ($num > 0) {
464		$i = 0;
465
466		$contactstatic = new Contact($db);
467
468		while ($i < $num) {
469			$obj = $db->fetch_object($resql);
470
471			print '<tr class="oddeven"><td>';
472			if ($obj->id > 0) {
473				$contactstatic->id = $obj->id;
474				$contactstatic->lastname = $obj->lastname;
475				$contactstatic->firstname = $obj->firstname;
476				print $contactstatic->getNomUrl(1);
477				print $obj->email ? ' &lt;'.$obj->email.'&gt;' : $langs->trans("NoMail");
478			} else {
479				print $obj->email;
480			}
481			print '</td>';
482			print '<td>';
483			$label = ($langs->trans("Notify_".$obj->code) != "Notify_".$obj->code ? $langs->trans("Notify_".$obj->code) : $obj->label);
484			print $label;
485			print '</td>';
486			print '<td>';
487			if ($obj->type == 'email') {
488				print $langs->trans("Email");
489			}
490			if ($obj->type == 'sms') {
491				print $langs->trans("Sms");
492			}
493			print '</td>';
494			// TODO Add link to object here for other types
495			/*print '<td>';
496			if ($obj->object_type == 'order')
497			{
498				$orderstatic->id=$obj->object_id;
499				$orderstatic->ref=...
500				print $orderstatic->getNomUrl(1);
501			}
502			   print '</td>';*/
503			// print
504			print'<td class="right">'.dol_print_date($db->jdate($obj->daten), 'dayhour').'</td>';
505			print '</tr>';
506			$i++;
507		}
508		$db->free($resql);
509	} else {
510		print '<tr><td colspan="4"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
511	}
512
513	print '</table>';
514	print '</div>';
515
516	print '</form>';
517} else {
518	dol_print_error('', 'RecordNotFound');
519}
520
521// End of page
522llxFooter();
523$db->close();
524