lib_notification.js.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. <?php
  2. /* Copyright (C) 2016 Sergio Sanchis <sergiosanchis@hotmail.com>
  3. * Copyright (C) 2017 Juanjo Menent <jmenent@2byte.es>
  4. * Copyright (C) 2020 Destailleur Laurent <eldy@users.sourceforge.net>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. *
  19. * Library javascript to enable Browser notifications
  20. */
  21. if (!defined('NOREQUIREUSER')) {
  22. define('NOREQUIREUSER', '1');
  23. }
  24. if (!defined('NOREQUIRESOC')) {
  25. define('NOREQUIRESOC', '1');
  26. }
  27. if (!defined('NOCSRFCHECK')) {
  28. define('NOCSRFCHECK', 1);
  29. }
  30. if (!defined('NOTOKENRENEWAL')) {
  31. define('NOTOKENRENEWAL', 1);
  32. }
  33. if (!defined('NOLOGIN')) {
  34. define('NOLOGIN', 1);
  35. }
  36. if (!defined('NOREQUIREMENU')) {
  37. define('NOREQUIREMENU', 1);
  38. }
  39. if (!defined('NOREQUIREHTML')) {
  40. define('NOREQUIREHTML', 1);
  41. }
  42. session_cache_limiter('public');
  43. require_once '../../main.inc.php';
  44. /*
  45. * View
  46. */
  47. top_httphead('text/javascript; charset=UTF-8');
  48. // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
  49. if (empty($dolibarr_nocache)) {
  50. header('Cache-Control: max-age=10800, public, must-revalidate');
  51. } else {
  52. header('Cache-Control: no-cache');
  53. }
  54. print "jQuery(document).ready(function () {\n";
  55. //print " console.log('referrer=".dol_escape_js($_SERVER['HTTP_REFERER'])."');\n";
  56. print ' var nowtime = Date.now();';
  57. print ' var time_auto_update = '.max(1, getDolGlobalInt('MAIN_BROWSER_NOTIFICATION_FREQUENCY')).';'."\n"; // Always defined
  58. print ' var time_js_next_test;'."\n";
  59. print ' var dolnotif_nb_test_for_page = 0;'."\n";
  60. print ' var dolnotif_idinterval = null;'."\n";
  61. ?>
  62. /* Check if Notification is supported */
  63. if ("Notification" in window) {
  64. /* Check if permission ok */
  65. if (Notification.permission !== "granted") {
  66. console.log("Ask Notification.permission");
  67. Notification.requestPermission()
  68. }
  69. /* Launch timer */
  70. // We set a delay before launching first test so next check will arrive after the time_auto_update compared to previous one.
  71. //var time_first_execution = (time_auto_update + (time_js_next_test - nowtime)) * 1000; //need milliseconds
  72. var time_first_execution = <?php echo max(3, empty($conf->global->MAIN_BROWSER_NOTIFICATION_CHECK_FIRST_EXECUTION) ? 0 : $conf->global->MAIN_BROWSER_NOTIFICATION_CHECK_FIRST_EXECUTION); ?>;
  73. setTimeout(first_execution, time_first_execution * 1000); // Launch a first execution after a time_first_execution delay
  74. time_js_next_test = nowtime + time_first_execution;
  75. 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);
  76. } else {
  77. console.log("This browser in this context does not support Notification.");
  78. }
  79. function first_execution() {
  80. console.log("Call first_execution of check_events()");
  81. result = check_events(); //one check before setting the new time for other checks
  82. if (result > 0) {
  83. console.log("check_events() is scheduled as a repeated task with a time_auto_update = MAIN_BROWSER_NOTIFICATION_FREQUENCY = "+time_auto_update+"s");
  84. dolnotif_idinterval = setInterval(check_events, time_auto_update * 1000); // Set new time to run next check events. time_auto_update=nb of seconds
  85. }
  86. }
  87. function check_events() {
  88. var result = 0;
  89. dolnotif_nb_test_for_page += 1;
  90. if (Notification.permission === "granted") {
  91. var currentToken = 'notrequired';
  92. const allMeta = document.getElementsByTagName("meta");
  93. for (let i = 0; i < allMeta.length; i++) {
  94. if (allMeta[i].getAttribute("name") == 'anti-csrf-currenttoken') {
  95. currentToken = allMeta[i].getAttribute('content');
  96. console.log("currentToken in page = "+currentToken);
  97. }
  98. }
  99. time_js_next_test += time_auto_update;
  100. 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);
  101. $.ajax("<?php print DOL_URL_ROOT.'/core/ajax/check_notifications.php'; ?>", {
  102. type: "post", // Usually post or get
  103. async: true,
  104. data: { time_js_next_test: time_js_next_test, forcechecknow: 1, token: currentToken },
  105. dataType: "json",
  106. success: function (result) {
  107. //console.log(result);
  108. var arrayofpastreminders = Object.values(result.pastreminders);
  109. if (arrayofpastreminders && arrayofpastreminders.length > 0) {
  110. console.log("Retrieved "+arrayofpastreminders.length+" reminders to do.");
  111. var audio = null;
  112. <?php
  113. if (!empty($conf->global->AGENDA_REMINDER_BROWSER_SOUND)) {
  114. print 'audio = new Audio(\''.DOL_URL_ROOT.'/theme/common/sound/notification_agenda.wav\');';
  115. }
  116. ?>
  117. var listofreminderids = '';
  118. var noti = []
  119. $.each(arrayofpastreminders, function (index, value) {
  120. console.log(value);
  121. var url = "notdefined";
  122. var title = "Not defined";
  123. var body = value.label;
  124. if (value.type == 'agenda' && value.location != null && value.location != '') {
  125. body += '\n' + value.location;
  126. }
  127. if (value.type == 'agenda' && (value.event_date_start_formated != null || value.event_date_start_formated['event_date_start'] != '')) {
  128. body += '\n' + value.event_date_start_formated;
  129. }
  130. if (value.type == 'agenda')
  131. {
  132. url = '<?php print DOL_URL_ROOT.'/comm/action/card.php?id='; ?>' + value.id_agenda;
  133. title = '<?php print dol_escape_js($langs->transnoentities('EventReminder')) ?>';
  134. }
  135. var extra = {
  136. icon: '<?php print DOL_URL_ROOT.'/theme/common/bell.png'; ?>',
  137. //image: '<?php print DOL_URL_ROOT.'/theme/common/bell.png'; ?>',
  138. body: body,
  139. tag: value.id_agenda,
  140. requireInteraction: true
  141. };
  142. // We release the notify
  143. console.log("Send notification on browser");
  144. noti[index] = new Notification(title, extra);
  145. if (index==0 && audio)
  146. {
  147. audio.play();
  148. }
  149. if (noti[index]) {
  150. noti[index].onclick = function (event) {
  151. console.log("A click on notification on browser has been done");
  152. event.preventDefault(); // prevent the browser from focusing the Notification's tab
  153. window.focus();
  154. window.open(url, '_blank');
  155. noti[index].close();
  156. };
  157. listofreminderids = (listofreminderids == '' ? '' : listofreminderids + ',') + value.id_reminder
  158. }
  159. });
  160. // Update status of all notifications we sent on browser (listofreminderids)
  161. console.log("Flag notification as done for listofreminderids="+listofreminderids);
  162. $.ajax("<?php print DOL_URL_ROOT.'/core/ajax/check_notifications.php?action=stopreminder&listofreminderids='; ?>"+listofreminderids, {
  163. type: "POST", // Usually post or get
  164. async: true,
  165. data: { time_js_next_test: time_js_next_test, token: currentToken }
  166. });
  167. } else {
  168. console.log("No remind to do found, next search at "+time_js_next_test);
  169. }
  170. }
  171. });
  172. result = 1;
  173. } else {
  174. console.log("Cancel check_events() with dolnotif_nb_test_for_page="+dolnotif_nb_test_for_page+". Check is useless because javascript Notification.permission is "+Notification.permission+" (blocked manualy or web site is not https).");
  175. result = 2; // We return a positive so the repeated check will done even if authroization is not yet allowed may be after this check)
  176. }
  177. if (dolnotif_nb_test_for_page >= 5) {
  178. 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);
  179. clearInterval(dolnotif_idinterval);
  180. }
  181. return result;
  182. }
  183. <?php
  184. print "\n";
  185. print '})'."\n";