dolibarr 24.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.
63header('Cache-Control: max-age=10800, public, must-revalidate');
64
65
66print "jQuery(document).ready(function () {\n";
67
68//print " console.log('referrer=".dol_escape_js($_SERVER['HTTP_REFERER'])."');\n";
69
70print 'var nowtime = Date.now();'."\n";
71print 'var time_auto_update = '.max(1, getDolGlobalInt('MAIN_BROWSER_NOTIFICATION_FREQUENCY')).';'."\n"; // Always defined
72print 'var time_js_next_test;'."\n";
73print 'var dolnotif_nb_test_for_page = 0;'."\n";
74print 'var dolnotif_idinterval = null;'."\n";
75?>
76
77var methodfornotification = '<?php print getDolUserString('AGENDA_NOTIFICATION_METHOD', getDolGlobalString('AGENDA_NOTIFICATION_METHOD', 'jnotify')); ?>';
78
79/* For old method notification system, check if Notification is supported */
80if (methodfornotification == "jsnotification") {
81 if ("Notification" in window) {
82 /* Check if permission ok */
83 if (Notification.permission !== "granted") {
84 console.log("Ask Notification.permission");
85 Notification.requestPermission(function(result) {
86 console.log("result for Notification.requestPermission is "+result);
87 });
88 }
89 } else {
90 console.log("This browser in this context does not support Notification.");
91 }
92}
93
94/* Launch timer for notifications */
95if (methodfornotification == "jnotify" || (methodfornotification == "jsnotification" && "Notification" in window)) {
96 // We set a delay before launching first test so next check will arrive after the time_auto_update compared to previous one.
97 //var time_first_execution = (time_auto_update + (time_js_next_test - nowtime)) * 1000; //need milliseconds
98 var time_first_execution = <?php echo max(3, getDolGlobalInt('MAIN_BROWSER_NOTIFICATION_CHECK_FIRST_EXECUTION', 0)); ?>;
99
100 setTimeout(first_execution, time_first_execution * 1000); // Launch the function first_execution() after a time_first_execution delay
101 time_js_next_test = nowtime + time_first_execution;
102 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);
103}
104
105/* The method called after time_first_execution on each page */
106function first_execution() {
107 console.log("Call first_execution of check_events()");
108 result = check_events(); //one check before setting the new time for other checks
109 if (result > 0) {
110 console.log("check_events() is scheduled as a repeated task with a time_auto_update = MAIN_BROWSER_NOTIFICATION_FREQUENCY = "+time_auto_update+"s");
111 dolnotif_idinterval = setInterval(check_events, time_auto_update * 1000); // Set new time to run next check events. time_auto_update=nb of seconds
112 }
113}
114
115/* The method call frequently every time_auto_update */
116function check_events() {
117 var result = 0;
118 dolnotif_nb_test_for_page += 1;
119 var methodfornotification = '<?php print getDolUserString('AGENDA_NOTIFICATION_METHOD', getDolGlobalString('AGENDA_NOTIFICATION_METHOD', 'jnotify')); ?>';
120
121 permissionok = 0;
122 if (methodfornotification == "jsnotification" && Notification.permission == "granted") {
123 permissionok = 1;
124 }
125 if (methodfornotification == "jnotify") {
126 permissionok = 1;
127 }
128
129 if (permissionok == 1) {
130 var currentToken = 'notrequired';
131 const allMeta = document.getElementsByTagName("meta");
132 for (let i = 0; i < allMeta.length; i++) {
133 if (allMeta[i].getAttribute("name") == 'anti-csrf-currenttoken') {
134 currentToken = allMeta[i].getAttribute('content');
135 console.log("currentToken in page = "+currentToken);
136 }
137 }
138 time_js_next_test += time_auto_update;
139
140 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);
141
142 $.ajax("<?php print DOL_URL_ROOT.'/core/ajax/check_notifications.php'; ?>", {
143 type: "POST", // Usually post or get
144 async: true,
145 data: { time_js_next_test: time_js_next_test, forcechecknow: 1, token: currentToken, dolnotif_nb_test_for_page: dolnotif_nb_test_for_page },
146 dataType: "json",
147 success: function (result) {
148 //console.log(result);
149 var arrayofpastreminders = Object.values(result.pastreminders);
150 if (arrayofpastreminders && arrayofpastreminders.length > 0) {
151 console.log("Retrieved "+arrayofpastreminders.length+" reminders to do.");
152 var audio = null;
153 <?php
154 if (getDolUserString('AGENDA_REMINDER_BROWSER_SOUND', getDolGlobalString('AGENDA_REMINDER_BROWSER_SOUND'))) {
155 print 'audio = new Audio(\''.DOL_URL_ROOT.'/theme/common/sound/notification_agenda.wav\');';
156 }
157 ?>
158 var icon = '<?php print DOL_URL_ROOT.'/public/theme/common/bell.svg'; ?>';
159 var listofreminderids = '';
160 var noti = []
161
162 $.each(arrayofpastreminders, function (index, value) {
163 console.log(value);
164 var url = "notdefined";
165 var title = "Not defined";
166 var body = "";
167
168 if (value.type == 'agenda')
169 {
170 url = '<?php print DOL_URL_ROOT.'/comm/action/card.php?id='; ?>' + value.id_agenda;
171 title = '<?php print dol_escape_js($langs->transnoentities('EventReminder')) ?>';
172 }
173
174 if (methodfornotification == "jsnotification") {
175 body = value.label;
176 if (value.type == 'agenda' && value.location != null && value.location != '') {
177 body += '\n' + value.location;
178 }
179
180 if (value.type == 'agenda' && (value.event_date_start_formated != null || value.event_date_start_formated['event_date_start'] != '')) {
181 body += '\n' + value.event_date_start_formated;
182 }
183 } else {
184 if (title != "Not defined") {
185 body = title+'<br><br>';
186 }
187 body += '<img src="'+icon+'">';
188 if (value.type == 'agenda' && (value.event_date_start_formated != null || value.event_date_start_formated['event_date_start'] != '')) {
189 body += ' '+value.event_date_start_formated;
190 }
191 body += ' - <a href="'+url+'"><?php echo img_picto("", "url", 'class="pictofixedwidth"').dol_escape_js($langs->trans("ShowDetails")); ?></a>';
192 body += '<br>'+value.label;
193 if (value.type == 'agenda' && value.location != null && value.location != '') {
194 body += '<br>' + value.location;
195 }
196 }
197
198 // We release the notify
199 console.log("Send notification on browser url="+url+" using method="+methodfornotification);
200
201 // Using the js browser Notification() popup
202 if (methodfornotification == 'jsnotification') {
203 var extra = {
204 icon: icon,
205 body: body,
206 lang: '<?php print dol_escape_js($langs->getDefaultLang(1)); ?>',
207 tag: value.id_agenda,
208 requireInteraction: true /* wait that the user click or close the notification */
209 /* "actions:" parameter is only supported for persistent notification shown using ServiceWorkerRegistration.showNotification() so disabled */
210 /* actions: [{ action: 'action1', title: 'New Button Label' }, { action: 'action2', title: 'Another Button' }] */
211 };
212
213 noti[index] = new Notification(title, extra);
214 if (index==0 && audio)
215 {
216 audio.play();
217 }
218
219 if (noti[index]) {
220 noti[index].onclick = function (event) {
221 /* If the user has clicked on button Activate */
222 console.log("A click on notification on browser has been done for url="+url);
223 event.preventDefault(); // prevent the browser from focusing the Notification's tab
224 window.focus();
225 window.open(url, '_blank');
226 noti[index].close();
227 };
228
229 listofreminderids = (listofreminderids == '' ? '' : listofreminderids + ',') + value.id_reminder
230 }
231 }
232
233 // Using jNotify popup
234 if (methodfornotification == 'jnotify') {
235 // Output a message with level "warning"
236 $.jnotify(body, 'warning', true, { remove: function (){} } );
237
238 listofreminderids = (listofreminderids == '' ? '' : listofreminderids + ',') + value.id_reminder
239 }
240 });
241
242 // Update status of all notifications we sent on browser (listofreminderids)
243 if (listofreminderids != '') {
244 console.log("Flag notification as done for listofreminderids="+listofreminderids);
245 $.ajax("<?php print DOL_URL_ROOT.'/core/ajax/check_notifications.php?action=stopreminder&listofreminderids='; ?>"+listofreminderids, {
246 type: "POST",
247 async: true,
248 data: { time_js_next_test: time_js_next_test, token: currentToken }
249 });
250 }
251 } else {
252 console.log("No remind to do found, next search at "+time_js_next_test);
253 }
254 }
255 });
256
257 result = 1;
258 } else {
259 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).");
260
261 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)
262 }
263
264 if (dolnotif_nb_test_for_page >= 5) {
265 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);
266 clearInterval(dolnotif_idinterval);
267 }
268
269 return result;
270}
271<?php
272
273print "\n";
274print '})'."\n";
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'))
Abort invoice creation with a given error message.
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|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition repair.php:130