1<?php
2/* Copyright (C) 2016	   Sergio Sanchis		<sergiosanchis@hotmail.com>
3 * Copyright (C) 2017	   Juanjo Menent		<jmenent@2byte.es>
4 * Copyright (C) 2019      Frédéric France      <frederic.france@netlogic.fr>
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
20if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1');
21if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
22if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
23if (!defined('NOREQUIREHTML'))  define('NOREQUIREHTML', '1');
24if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
25if (!defined('NOREQUIRESOC'))   define('NOREQUIRESOC', '1');
26if (!defined('NOREQUIRETRAN'))  define('NOREQUIRETRAN', '1');
27
28//if (! defined('NOREQUIREUSER'))            define('NOREQUIREUSER', '1');					// Do not load object $user
29//if (! defined('NOREQUIRESOC'))             define('NOREQUIRESOC', '1');					// Do not load object $mysoc
30//if (! defined('NOREQUIRETRAN'))            define('NOREQUIRETRAN', '1');					// Do not load object $langs
31//if (! defined('NOSCANGETFORINJECTION'))    define('NOSCANGETFORINJECTION', '1');			// Do not check injection attack on GET parameters
32//if (! defined('NOSCANPOSTFORINJECTION'))   define('NOSCANPOSTFORINJECTION', '1');			// Do not check injection attack on POST parameters
33//if (! defined('NOCSRFCHECK'))              define('NOCSRFCHECK', '1');					// Do not check CSRF attack (test on referer + on token if option MAIN_SECURITY_CSRF_WITH_TOKEN is on).
34//if (! defined('NOTOKENRENEWAL'))           define('NOTOKENRENEWAL', '1');					// Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on)
35//if (! defined('NOSTYLECHECK'))             define('NOSTYLECHECK', '1');					// Do not check style html tag into posted data
36//if (! defined('NOIPCHECK'))                define('NOIPCHECK', '1');						// Do not check IP defined into conf $dolibarr_main_restrict_ip
37//if (! defined('NOREQUIREMENU'))            define('NOREQUIREMENU', '1');					// If there is no need to load and show top and left menu
38//if (! defined('NOREQUIREHTML'))            define('NOREQUIREHTML', '1');					// If we don't need to load the html.form.class.php
39//if (! defined('NOREQUIREAJAX'))            define('NOREQUIREAJAX', '1');       		  	// Do not load ajax.lib.php library
40//if (! defined("NOLOGIN"))                  define("NOLOGIN", '1');						// If this page is public (can be called outside logged session)
41//if (! defined("MAIN_LANG_DEFAULT"))        define('MAIN_LANG_DEFAULT', 'auto');			// Force lang to a particular value
42//if (! defined("MAIN_AUTHENTICATION_MODE")) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule');		// Force authentication handler
43//if (! defined("NOREDIRECTBYMAINTOLOGIN"))  define('NOREDIRECTBYMAINTOLOGIN', '1');		// The main.inc.php does not make a redirect if not logged, instead show simple error message
44//if (! defined("XFRAMEOPTIONS_ALLOWALL"))   define('XFRAMEOPTIONS_ALLOWALL', '1');			// Do not add the HTTP header 'X-Frame-Options: SAMEORIGIN' but 'X-Frame-Options: ALLOWALL'
45
46
47require '../../main.inc.php';
48
49//$time = (int) GETPOST('time', 'int'); // Use the time parameter that is always increased by time_update, even if call is late
50$time = dol_now();
51$action = GETPOST('action', 'aZ09');
52$listofreminderids = GETPOST('listofreminderids', 'aZ09');
53
54
55/*
56 * Actions
57 */
58
59if ($action == 'stopreminder') {
60	dol_syslog("Clear notification for listofreminderids=".$listofreminderids);
61	$listofreminderid = GETPOST('listofreminderids', 'intcomma');
62
63	// Set the reminder as done
64	//foreach ($listofreminderidsarray as $listofreminderid) {
65	//	if (empty($listofreminderid)) continue;
66	//$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'action_reminder WHERE rowid = '.$listofreminderid.' AND fk_user = '.$user->id;
67	$sql = 'UPDATE '.MAIN_DB_PREFIX.'actioncomm_reminder SET status = 1';
68	$sql .= ' WHERE status = 0 AND rowid IN ('.$db->sanitize($db->escape($listofreminderid)).')';
69	$sql .= ' AND fk_user = '.$user->id.' AND entity = '.$conf->entity;
70	$resql = $db->query($sql);
71	if (!$resql) {
72		dol_print_error($db);
73	}
74	//}
75
76	include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
77
78	// Clean database
79	$sql = 'DELETE FROM '.MAIN_DB_PREFIX.'actioncomm_reminder';
80	$sql .= " WHERE dateremind < '".$db->idate(dol_time_plus_duree(dol_now(), -1, 'm'))."'";
81	$resql = $db->query($sql);
82	if (!$resql) {
83		dol_print_error($db);
84	}
85
86	exit;
87}
88
89
90/*
91 * View
92 */
93
94top_httphead('application/json');
95
96global $user, $db, $langs, $conf;
97
98$eventfound = array();
99//Uncomment this to force a test
100//$eventfound[]=array('type'=>'agenda', 'id'=>1, 'tipo'=>'eee', 'location'=>'aaa');
101
102//dol_syslog('time='.$time.' $_SESSION[auto_ck_events_not_before]='.$_SESSION['auto_check_events_not_before']);
103
104// TODO Try to make a solution with only a javascript timer that is easier. Difficulty is to avoid notification twice when several tabs are opened.
105// This need to extend period to be sure to not miss and save in session what we notified to avoid duplicate.
106if (empty($_SESSION['auto_check_events_not_before']) || $time >= $_SESSION['auto_check_events_not_before'] || GETPOST('forcechecknow', 'int'))
107{
108	/*$time_update = (int) $conf->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY; // Always defined
109    if (!empty($_SESSION['auto_check_events_not_before']))
110    {
111        // We start scan from the not before so if two tabs were opend at differents seconds and we close one (so the js timer),
112        // then we are not losing periods
113        $starttime = $_SESSION['auto_check_events_not_before'];
114        // Protection to avoid too long sessions
115        if ($starttime < ($time - (int) $conf->global->MAIN_SESSION_TIMEOUT))
116        {
117            dol_syslog("We ask to check browser notification on a too large period. We fix this with current date.");
118            $starttime = $time;
119        }
120    } else {
121        $starttime = $time;
122    }
123
124    $_SESSION['auto_check_events_not_before'] = $time + $time_update;
125	*/
126
127	// Force save of the session change we did.
128	// WARNING: Any change in sessions after that will not be saved !
129	session_write_close();
130
131	require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
132
133
134	dol_syslog('NEW $_SESSION[auto_check_events_not_before]='.(empty($_SESSION['auto_check_events_not_before']) ? '' : $_SESSION['auto_check_events_not_before']));
135
136	$sql = 'SELECT a.id as id_agenda, a.code, a.datep, a.label, a.location, ar.rowid as id_reminder, ar.dateremind, ar.fk_user as id_user_reminder';
137	$sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a';
138	if (!empty($user->conf->MAIN_USER_WANT_ALL_EVENTS_NOTIFICATIONS)) {
139		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'actioncomm_reminder as ar ON a.id = ar.fk_actioncomm AND ar.fk_user = '.$user->id;
140		$sql .= ' WHERE a.code <> "AC_OTH_AUTO"';
141		$sql .= ' AND (';
142		$sql .= " (ar.typeremind = 'browser' AND ar.dateremind < '".$db->idate(dol_now())."' AND ar.status = 0 AND ar.entity = ".$conf->entity;
143		$sql .= ' )';
144	} else {
145		$sql .= ' JOIN '.MAIN_DB_PREFIX.'actioncomm_reminder as ar ON a.id = ar.fk_actioncomm AND ar.fk_user = '.$user->id;
146		$sql .= " AND ar.typeremind = 'browser' AND ar.dateremind < '".$db->idate(dol_now())."' AND ar.status = 0 AND ar.entity = ".$conf->entity;
147	}
148	$sql .= $db->order('datep', 'ASC');
149	$sql .= ' LIMIT 10'; // Avoid too many notification at once
150
151	$resql = $db->query($sql);
152	if ($resql) {
153		while ($obj = $db->fetch_object($resql))
154		{
155			// Message must be formated and translated to be used with javascript directly
156			$event = array();
157			$event['type'] = 'agenda';
158			$event['id_reminder'] = $obj->id_reminder;
159			$event['id_agenda'] = $obj->id_agenda;
160			$event['id_user'] = $obj->id_user_reminder;
161			$event['code'] = $obj->code;
162			$event['label'] = $obj->label;
163			$event['location'] = $obj->location;
164			$event['reminder_date_formated'] = dol_print_date($db->jdate($obj->dateremind), 'standard');
165			$event['event_date_start_formated'] = dol_print_date($db->jdate($obj->datep), 'standard');
166
167			$eventfound[$obj->id_agenda] = $event;
168		}
169	} else {
170		dol_syslog("Error sql = ".$db->lasterror(), LOG_ERR);
171	}
172}
173
174print json_encode(array('pastreminders'=>$eventfound, 'nextreminder'=>''));
175