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