Moodle release 3.10.1
[moodle.git] / calendar / export_execute.php
blob5a53e7edfe76d78383ce37cda0c2bc882b3ed607
1 <?php
3 require_once('../config.php');
4 //require_once($CFG->dirroot.'/course/lib.php');
5 require_once($CFG->dirroot.'/calendar/lib.php');
6 require_once($CFG->libdir.'/bennu/bennu.inc.php');
8 $userid = optional_param('userid', 0, PARAM_INT);
9 $username = optional_param('username', '', PARAM_TEXT);
10 $authtoken = required_param('authtoken', PARAM_ALPHANUM);
11 $generateurl = optional_param('generateurl', '', PARAM_TEXT);
13 if (empty($CFG->enablecalendarexport)) {
14 die('no export');
17 //Fetch user information
18 $checkuserid = !empty($userid) && $user = $DB->get_record('user', array('id' => $userid), 'id,password');
19 //allowing for fallback check of old url - MDL-27542
20 $checkusername = !empty($username) && $user = $DB->get_record('user', array('username' => $username), 'id,password');
21 if ((!$checkuserid && !$checkusername) || !$user) {
22 //No such user
23 die('Invalid authentication');
26 //Check authentication token
27 $authuserid = !empty($userid) && $authtoken == calendar_get_export_token($user);
28 //allowing for fallback check of old url - MDL-27542
29 $authusername = !empty($username) && $authtoken == sha1($username . $user->password . $CFG->calendar_exportsalt);
30 if (!$authuserid && !$authusername) {
31 die('Invalid authentication');
34 // Get the calendar type we are using.
35 $calendartype = \core_calendar\type_factory::get_calendar_instance();
37 $what = optional_param('preset_what', 'all', PARAM_ALPHA);
38 $time = optional_param('preset_time', 'weeknow', PARAM_ALPHA);
40 $now = $calendartype->timestamp_to_date_array(time());
42 // Let's see if we have sufficient and correct data
43 $allowedwhat = ['all', 'user', 'groups', 'courses', 'categories'];
44 $allowedtime = ['weeknow', 'weeknext', 'monthnow', 'monthnext', 'recentupcoming', 'custom'];
46 if (!empty($generateurl)) {
47 $authtoken = calendar_get_export_token($user);
48 $params = array();
49 $params['preset_what'] = $what;
50 $params['preset_time'] = $time;
51 $params['userid'] = $userid;
52 $params['authtoken'] = $authtoken;
53 $params['generateurl'] = true;
55 $link = new moodle_url('/calendar/export.php', $params);
56 redirect($link->out());
57 die;
59 $paramcategory = false;
60 if(!empty($what) && !empty($time)) {
61 if(in_array($what, $allowedwhat) && in_array($time, $allowedtime)) {
62 $courses = enrol_get_users_courses($user->id, true, 'id, visible, shortname');
63 // Array of courses that we will pass to calendar_get_legacy_events() which
64 // is initially set to the list of the user's courses.
65 $paramcourses = $courses;
66 if ($what == 'all' || $what == 'groups') {
67 $groups = array();
68 foreach ($courses as $course) {
69 $course_groups = groups_get_all_groups($course->id, $user->id);
70 $groups = array_merge($groups, array_keys($course_groups));
72 if (empty($groups)) {
73 $groups = false;
76 if ($what == 'all') {
77 $users = $user->id;
78 $courses[SITEID] = new stdClass;
79 $courses[SITEID]->shortname = get_string('siteevents', 'calendar');
80 $paramcourses[SITEID] = $courses[SITEID];
81 $paramcategory = true;
82 } else if ($what == 'groups') {
83 $users = false;
84 $paramcourses = array();
85 } else if ($what == 'user') {
86 $users = $user->id;
87 $groups = false;
88 $paramcourses = array();
89 } else if ($what == 'categories') {
90 $users = $user->id;
91 $groups = false;
92 $paramcourses = array();
93 $paramcategory = true;
94 } else {
95 $users = false;
96 $groups = false;
99 // Store the number of days in the week.
100 $numberofdaysinweek = $calendartype->get_num_weekdays();
102 switch($time) {
103 case 'weeknow':
104 $startweekday = calendar_get_starting_weekday();
105 $startmonthday = find_day_in_month($now['mday'] - ($numberofdaysinweek - 1), $startweekday, $now['mon'], $now['year']);
106 $startmonth = $now['mon'];
107 $startyear = $now['year'];
108 if ($startmonthday > calendar_days_in_month($startmonth, $startyear)) {
109 list($startmonth, $startyear) = calendar_add_month($startmonth, $startyear);
110 $startmonthday = find_day_in_month(1, $startweekday, $startmonth, $startyear);
112 $gregoriandate = $calendartype->convert_to_gregorian($startyear, $startmonth, $startmonthday);
113 $timestart = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
114 $gregoriandate['hour'], $gregoriandate['minute']);
116 $endmonthday = $startmonthday + $numberofdaysinweek;
117 $endmonth = $startmonth;
118 $endyear = $startyear;
119 if ($endmonthday > calendar_days_in_month($endmonth, $endyear)) {
120 list($endmonth, $endyear) = calendar_add_month($endmonth, $endyear);
121 $endmonthday = find_day_in_month(1, $startweekday, $endmonth, $endyear);
123 $gregoriandate = $calendartype->convert_to_gregorian($endyear, $endmonth, $endmonthday);
124 $timeend = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
125 $gregoriandate['hour'], $gregoriandate['minute']);
126 break;
127 case 'weeknext':
128 $startweekday = calendar_get_starting_weekday();
129 $startmonthday = find_day_in_month($now['mday'] + 1, $startweekday, $now['mon'], $now['year']);
130 $startmonth = $now['mon'];
131 $startyear = $now['year'];
132 if ($startmonthday > calendar_days_in_month($startmonth, $startyear)) {
133 list($startmonth, $startyear) = calendar_add_month($startmonth, $startyear);
134 $startmonthday = find_day_in_month(1, $startweekday, $startmonth, $startyear);
136 $gregoriandate = $calendartype->convert_to_gregorian($startyear, $startmonth, $startmonthday);
137 $timestart = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
138 $gregoriandate['hour'], $gregoriandate['minute']);
140 $endmonthday = $startmonthday + $numberofdaysinweek;
141 $endmonth = $startmonth;
142 $endyear = $startyear;
143 if ($endmonthday > calendar_days_in_month($endmonth, $endyear)) {
144 list($endmonth, $endyear) = calendar_add_month($endmonth, $endyear);
145 $endmonthday = find_day_in_month(1, $startweekday, $endmonth, $endyear);
147 $gregoriandate = $calendartype->convert_to_gregorian($endyear, $endmonth, $endmonthday);
148 $timeend = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
149 $gregoriandate['hour'], $gregoriandate['minute']);
150 break;
151 case 'monthnow':
152 // Convert to gregorian.
153 $gregoriandate = $calendartype->convert_to_gregorian($now['year'], $now['mon'], 1);
155 $timestart = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
156 $gregoriandate['hour'], $gregoriandate['minute']);
157 $timeend = $timestart + (calendar_days_in_month($now['mon'], $now['year']) * DAYSECS);
158 break;
159 case 'monthnext':
160 // Get the next month for this calendar.
161 list($nextmonth, $nextyear) = calendar_add_month($now['mon'], $now['year']);
163 // Convert to gregorian.
164 $gregoriandate = $calendartype->convert_to_gregorian($nextyear, $nextmonth, 1);
166 // Create the timestamps.
167 $timestart = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
168 $gregoriandate['hour'], $gregoriandate['minute']);
169 $timeend = $timestart + (calendar_days_in_month($nextmonth, $nextyear) * DAYSECS);
170 break;
171 case 'recentupcoming':
172 //Events in the last 5 or next 60 days
173 $timestart = time() - 432000;
174 $timeend = time() + 5184000;
175 break;
176 case 'custom':
177 // Events based on custom date range.
178 $timestart = time() - $CFG->calendar_exportlookback * DAYSECS;
179 $timeend = time() + $CFG->calendar_exportlookahead * DAYSECS;
180 break;
183 else {
184 // Parameters given but incorrect, redirect back to export page
185 redirect($CFG->wwwroot.'/calendar/export.php');
186 die();
189 $limitnum = 0;
190 $events = calendar_get_legacy_events($timestart, $timeend, $users, $groups, array_keys($paramcourses), false, true,
191 $paramcategory, $limitnum);
193 $ical = new iCalendar;
194 $ical->add_property('method', 'PUBLISH');
195 $ical->add_property('prodid', '-//Moodle Pty Ltd//NONSGML Moodle Version ' . $CFG->version . '//EN');
196 foreach($events as $event) {
197 if (!empty($event->modulename)) {
198 $instances = get_fast_modinfo($event->courseid, $userid)->get_instances_of($event->modulename);
199 if (empty($instances[$event->instance]->uservisible)) {
200 continue;
203 $hostaddress = str_replace('http://', '', $CFG->wwwroot);
204 $hostaddress = str_replace('https://', '', $hostaddress);
206 $me = new calendar_event($event); // To use moodle calendar event services.
207 $ev = new iCalendar_event; // To export in ical format.
208 $ev->add_property('uid', $event->id.'@'.$hostaddress);
210 // Set iCal event summary from event name.
211 $ev->add_property('summary', format_string($event->name, true, ['context' => $me->context]));
213 // Format the description text.
214 $description = format_text($me->description, $me->format, ['context' => $me->context]);
215 // Then convert it to plain text, since it's the only format allowed for the event description property.
216 // We use html_to_text in order to convert <br> and <p> tags to new line characters for descriptions in HTML format.
217 $description = html_to_text($description, 0);
218 $ev->add_property('description', $description);
220 $ev->add_property('class', 'PUBLIC'); // PUBLIC / PRIVATE / CONFIDENTIAL
221 $ev->add_property('last-modified', Bennu::timestamp_to_datetime($event->timemodified));
223 if (!empty($event->location)) {
224 $ev->add_property('location', $event->location);
227 $ev->add_property('dtstamp', Bennu::timestamp_to_datetime()); // now
228 if ($event->timeduration > 0) {
229 //dtend is better than duration, because it works in Microsoft Outlook and works better in Korganizer
230 $ev->add_property('dtstart', Bennu::timestamp_to_datetime($event->timestart)); // when event starts.
231 $ev->add_property('dtend', Bennu::timestamp_to_datetime($event->timestart + $event->timeduration));
232 } else if ($event->timeduration == 0) {
233 // When no duration is present, the event is instantaneous event, ex - Due date of a module.
234 // Moodle doesn't support all day events yet. See MDL-56227.
235 $ev->add_property('dtstart', Bennu::timestamp_to_datetime($event->timestart));
236 $ev->add_property('dtend', Bennu::timestamp_to_datetime($event->timestart));
237 } else {
238 // This can be used to represent all day events in future.
239 throw new coding_exception("Negative duration is not supported yet.");
241 if ($event->courseid != 0) {
242 $coursecontext = context_course::instance($event->courseid);
243 $ev->add_property('categories', format_string($courses[$event->courseid]->shortname, true, array('context' => $coursecontext)));
245 $ical->add_component($ev);
248 $serialized = $ical->serialize();
249 if(empty($serialized)) {
250 // TODO
251 die('bad serialization');
254 $filename = 'icalexport.ics';
256 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
257 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
258 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .'GMT');
259 header('Pragma: no-cache');
260 header('Accept-Ranges: none'); // Comment out if PDFs do not work...
261 header('Content-disposition: attachment; filename='.$filename);
262 header('Content-length: '.strlen($serialized));
263 header('Content-type: text/calendar; charset=utf-8');
265 echo $serialized;