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