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