dolibarr 21.0.0-beta
lib_notification.js.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2016 Sergio Sanchis <sergiosanchis@hotmail.com>
3 * Copyright (C) 2017 Juanjo Menent <jmenent@2byte.es>
4 * Copyright (C) 2020-2023 Destailleur Laurent <eldy@users.sourceforge.net>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
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 * Library javascript to enable Browser notifications
21 */
22
28if (!defined('NOREQUIREUSER')) {
29 define('NOREQUIREUSER', '1');
30}
31if (!defined('NOREQUIRESOC')) {
32 define('NOREQUIRESOC', '1');
33}
34if (!defined('NOCSRFCHECK')) {
35 define('NOCSRFCHECK', 1);
36}
37if (!defined('NOTOKENRENEWAL')) {
38 define('NOTOKENRENEWAL', 1);
39}
40if (!defined('NOLOGIN')) {
41 define('NOLOGIN', 1);
42}
43if (!defined('NOREQUIREMENU')) {
44 define('NOREQUIREMENU', 1);
45}
46if (!defined('NOREQUIREHTML')) {
47 define('NOREQUIREHTML', 1);
48}
49
50session_cache_limiter('public');
51
52require_once '../../main.inc.php';
57/*
58 * View
59 */
60
61top_httphead('text/javascript; charset=UTF-8');
62// Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
63if (empty($dolibarr_nocache)) {
64 header('Cache-Control: max-age=10800, public, must-revalidate');
65} else {
66 header('Cache-Control: no-cache');
67}
68
69
70print "jQuery(document).ready(function () {\n";
71
72//print " console.log('referrer=".dol_escape_js($_SERVER['HTTP_REFERER'])."');\n";
73
74print ' var nowtime = Date.now();';
75print ' var time_auto_update = '.max(1, getDolGlobalInt('MAIN_BROWSER_NOTIFICATION_FREQUENCY')).';'."\n"; // Always defined
76print ' var time_js_next_test;'."\n";
77print ' var dolnotif_nb_test_for_page = 0;'."\n";
78print ' var dolnotif_idinterval = null;'."\n";
79?>
80
81/* Check if Notification is supported */
82if ("Notification" in window) {
83 /* Check if permission ok */
84 if (Notification.permission !== "granted") {
85 console.log("Ask Notification.permission");
86 Notification.requestPermission(function(result) {
87 console.log("result for Notification.requestPermission is "+result);
88 });
89 }
90
91 /* Launch timer */
92
93 // We set a delay before launching first test so next check will arrive after the time_auto_update compared to previous one.
94 //var time_first_execution = (time_auto_update + (time_js_next_test - nowtime)) * 1000; //need milliseconds
95 var time_first_execution = <?php echo max(3, getDolGlobalInt('MAIN_BROWSER_NOTIFICATION_CHECK_FIRST_EXECUTION', 0)); ?>;
96
97 setTimeout(first_execution, time_first_execution * 1000); // Launch a first execution after a time_first_execution delay
98 time_js_next_test = nowtime + time_first_execution;
99 console.log("Launch browser notif check: setTimeout is set to launch 'first_execution' function after a wait of time_first_execution="+time_first_execution+". nowtime (time php page generation) = "+nowtime+" time_js_next_check = "+time_js_next_test);
100} else {
101 console.log("This browser in this context does not support Notification.");
102}
103
104/* The method called after time_first_execution on each page */
105function first_execution() {
106 console.log("Call first_execution of check_events()");
107 result = check_events(); //one check before setting the new time for other checks
108 if (result > 0) {
109 console.log("check_events() is scheduled as a repeated task with a time_auto_update = MAIN_BROWSER_NOTIFICATION_FREQUENCY = "+time_auto_update+"s");
110 dolnotif_idinterval = setInterval(check_events, time_auto_update * 1000); // Set new time to run next check events. time_auto_update=nb of seconds
111 }
112}
113
114/* the method call frequently every time_auto_update */
115function check_events() {
116 var result = 0;
117 dolnotif_nb_test_for_page += 1;
118 var methodfornotification = '<?php print getDolUserString('AGENDA_NOTIFICATION_METHOD', getDolGlobalString('AGENDA_NOTIFICATION_METHOD', 'jnotify')); ?>';
119
120 permissionok = 0;
121 if (methodfornotification == "jsnotification" && Notification.permission == "granted") {
122 permissionok = 1;
123 }
124 if (methodfornotification == "jnotify") {
125 permissionok = 1;
126 }
127
128 if (permissionok == 1) {
129 var currentToken = 'notrequired';
130 const allMeta = document.getElementsByTagName("meta");
131 for (let i = 0; i < allMeta.length; i++) {
132 if (allMeta[i].getAttribute("name") == 'anti-csrf-currenttoken') {
133 currentToken = allMeta[i].getAttribute('content');
134 console.log("currentToken in page = "+currentToken);
135 }
136 }
137 time_js_next_test += time_auto_update;
138
139 console.log("Call ajax to check events with time_js_next_test = "+time_js_next_test+" dolnotif_nb_test_for_page="+dolnotif_nb_test_for_page);
140
141 $.ajax("<?php print DOL_URL_ROOT.'/core/ajax/check_notifications.php'; ?>", {
142 type: "POST", // Usually post or get
143 async: true,
144 data: { time_js_next_test: time_js_next_test, forcechecknow: 1, token: currentToken, dolnotif_nb_test_for_page: dolnotif_nb_test_for_page },
145 dataType: "json",
146 success: function (result) {
147 //console.log(result);
148 var arrayofpastreminders = Object.values(result.pastreminders);
149 if (arrayofpastreminders && arrayofpastreminders.length > 0) {
150 console.log("Retrieved "+arrayofpastreminders.length+" reminders to do.");
151 var audio = null;
152 <?php
153 if (getDolUserString('AGENDA_REMINDER_BROWSER_SOUND', getDolGlobalString('AGENDA_REMINDER_BROWSER_SOUND'))) {
154 print 'audio = new Audio(\''.DOL_URL_ROOT.'/theme/common/sound/notification_agenda.wav\');';
155 }
156 ?>
157 var icon = '<?php print DOL_URL_ROOT.'/theme/common/octicons/build/svg/bell.svg'; ?>';
158 var listofreminderids = '';
159 var noti = []
160
161 $.each(arrayofpastreminders, function (index, value) {
162 console.log(value);
163 var url = "notdefined";
164 var title = "Not defined";
165 var body = "";
166
167 if (value.type == 'agenda')
168 {
169 url = '<?php print DOL_URL_ROOT.'/comm/action/card.php?id='; ?>' + value.id_agenda;
170 title = '<?php print dol_escape_js($langs->transnoentities('EventReminder')) ?>';
171 }
172
173 if (methodfornotification == "jsnotification") {
174 body = value.label;
175 if (value.type == 'agenda' && value.location != null && value.location != '') {
176 body += '\n' + value.location;
177 }
178
179 if (value.type == 'agenda' && (value.event_date_start_formated != null || value.event_date_start_formated['event_date_start'] != '')) {
180 body += '\n' + value.event_date_start_formated;
181 }
182 } else {
183 if (title != "Not defined") {
184 body = title+'<br><br>';
185 }
186 body += '<img src="'+icon+'">';
187 if (value.type == 'agenda' && (value.event_date_start_formated != null || value.event_date_start_formated['event_date_start'] != '')) {
188 body += ' '+value.event_date_start_formated;
189 }
190 body += ' - <a href="'+url+'"><?php echo img_picto("", "url", 'class="pictofixedwidth"').dol_escape_js($langs->trans("ShowDetails")); ?></a>';
191 body += '<br>'+value.label;
192 if (value.type == 'agenda' && value.location != null && value.location != '') {
193 body += '<br>' + value.location;
194 }
195 }
196
197 // We release the notify
198 console.log("Send notification on browser url="+url+" using method="+methodfornotification);
199
200 // Using the js browser Notification() popup
201 if (methodfornotification == 'jsnotification') {
202 var extra = {
203 icon: icon,
204 body: body,
205 lang: '<?php print dol_escape_js($langs->getDefaultLang(1)); ?>',
206 tag: value.id_agenda,
207 requireInteraction: true /* wait that the user click or close the notification */
208 /* "actions:" parameter is only supported for persistent notification shown using ServiceWorkerRegistration.showNotification() so disabled */
209 /* actions: [{ action: 'action1', title: 'New Button Label' }, { action: 'action2', title: 'Another Button' }] */
210 };
211
212 noti[index] = new Notification(title, extra);
213 if (index==0 && audio)
214 {
215 audio.play();
216 }
217
218 if (noti[index]) {
219 noti[index].onclick = function (event) {
220 /* If the user has clicked on button Activate */
221 console.log("A click on notification on browser has been done for url="+url);
222 event.preventDefault(); // prevent the browser from focusing the Notification's tab
223 window.focus();
224 window.open(url, '_blank');
225 noti[index].close();
226 };
227
228 listofreminderids = (listofreminderids == '' ? '' : listofreminderids + ',') + value.id_reminder
229 }
230 }
231
232 // Using jNotify popup
233 if (methodfornotification == 'jnotify') {
234 // Output a message with level "warning"
235 $.jnotify(body, 'warning', true, { remove: function (){} } );
236
237 listofreminderids = (listofreminderids == '' ? '' : listofreminderids + ',') + value.id_reminder
238 }
239 });
240
241 // Update status of all notifications we sent on browser (listofreminderids)
242 if (listofreminderids != '') {
243 console.log("Flag notification as done for listofreminderids="+listofreminderids);
244 $.ajax("<?php print DOL_URL_ROOT.'/core/ajax/check_notifications.php?action=stopreminder&listofreminderids='; ?>"+listofreminderids, {
245 type: "POST",
246 async: true,
247 data: { time_js_next_test: time_js_next_test, token: currentToken }
248 });
249 }
250 } else {
251 console.log("No remind to do found, next search at "+time_js_next_test);
252 }
253 }
254 });
255
256 result = 1;
257 } else {
258 console.log("Cancel check_events() with dolnotif_nb_test_for_page="+dolnotif_nb_test_for_page+". Check is useless because permission is off. Javascript Notification.permission is "+Notification.permission+" (blocked manually or web site is not https or browser is in Private mode).");
259
260 result = 2; // We return a positive so the repeated check will be done even if authorization is not yet allowed may be after this check)
261 }
262
263 if (dolnotif_nb_test_for_page >= 5) {
264 console.log("We did "+dolnotif_nb_test_for_page+" consecutive test on this page. We stop checking now from here by clearing dolnotif_idinterval="+dolnotif_idinterval);
265 clearInterval(dolnotif_idinterval);
266 }
267
268 return result;
269}
270<?php
271
272print "\n";
273print '})'."\n";
currentToken()
Return the value of token currently saved into session with name 'token'.
getDolUserString($key, $default='', $tmpuser=null)
Return Dolibarr user constant string value.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:149