Merge branch 'MDL-51969-master' of https://github.com/dmitriim/moodle
[moodle.git] / calendar / export_execute.php
blob53bd01d4add5d55210a4a6158d11fc5752f16fa5
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) {
22 //No such user
23 die('Invalid authentication');
26 //Check authentication token
27 $authuserid = !empty($userid) && $authtoken == sha1($userid . $user->password . $CFG->calendar_exportsalt);
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 $allowed_what = array('all', 'user', 'groups', 'courses');
44 $allowed_time = array('weeknow', 'weeknext', 'monthnow', 'monthnext', 'recentupcoming', 'custom');
46 if (!empty($generateurl)) {
47 $authtoken = sha1($user->id . $user->password . $CFG->calendar_exportsalt);
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;
60 if(!empty($what) && !empty($time)) {
61 if(in_array($what, $allowed_what) && in_array($time, $allowed_time)) {
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('globalevents', 'calendar');
80 $paramcourses[SITEID] = $courses[SITEID];
81 } else if ($what == 'groups') {
82 $users = false;
83 $paramcourses = array();
84 } else if ($what == 'user') {
85 $users = $user->id;
86 $groups = false;
87 $paramcourses = array();
88 } else {
89 $users = false;
90 $groups = false;
93 // Store the number of days in the week.
94 $numberofdaysinweek = $calendartype->get_num_weekdays();
96 switch($time) {
97 case 'weeknow':
98 $startweekday = calendar_get_starting_weekday();
99 $startmonthday = find_day_in_month($now['mday'] - ($numberofdaysinweek - 1), $startweekday, $now['mon'], $now['year']);
100 $startmonth = $now['mon'];
101 $startyear = $now['year'];
102 if ($startmonthday > calendar_days_in_month($startmonth, $startyear)) {
103 list($startmonth, $startyear) = calendar_add_month($startmonth, $startyear);
104 $startmonthday = find_day_in_month(1, $startweekday, $startmonth, $startyear);
106 $gregoriandate = $calendartype->convert_to_gregorian($startyear, $startmonth, $startmonthday);
107 $timestart = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
108 $gregoriandate['hour'], $gregoriandate['minute']);
110 $endmonthday = $startmonthday + $numberofdaysinweek;
111 $endmonth = $startmonth;
112 $endyear = $startyear;
113 if ($endmonthday > calendar_days_in_month($endmonth, $endyear)) {
114 list($endmonth, $endyear) = calendar_add_month($endmonth, $endyear);
115 $endmonthday = find_day_in_month(1, $startweekday, $endmonth, $endyear);
117 $gregoriandate = $calendartype->convert_to_gregorian($endyear, $endmonth, $endmonthday);
118 $timeend = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
119 $gregoriandate['hour'], $gregoriandate['minute']);
120 break;
121 case 'weeknext':
122 $startweekday = calendar_get_starting_weekday();
123 $startmonthday = find_day_in_month($now['mday'] + 1, $startweekday, $now['mon'], $now['year']);
124 $startmonth = $now['mon'];
125 $startyear = $now['year'];
126 if ($startmonthday > calendar_days_in_month($startmonth, $startyear)) {
127 list($startmonth, $startyear) = calendar_add_month($startmonth, $startyear);
128 $startmonthday = find_day_in_month(1, $startweekday, $startmonth, $startyear);
130 $gregoriandate = $calendartype->convert_to_gregorian($startyear, $startmonth, $startmonthday);
131 $timestart = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
132 $gregoriandate['hour'], $gregoriandate['minute']);
134 $endmonthday = $startmonthday + $numberofdaysinweek;
135 $endmonth = $startmonth;
136 $endyear = $startyear;
137 if ($endmonthday > calendar_days_in_month($endmonth, $endyear)) {
138 list($endmonth, $endyear) = calendar_add_month($endmonth, $endyear);
139 $endmonthday = find_day_in_month(1, $startweekday, $endmonth, $endyear);
141 $gregoriandate = $calendartype->convert_to_gregorian($endyear, $endmonth, $endmonthday);
142 $timeend = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
143 $gregoriandate['hour'], $gregoriandate['minute']);
144 break;
145 case 'monthnow':
146 // Convert to gregorian.
147 $gregoriandate = $calendartype->convert_to_gregorian($now['year'], $now['mon'], 1);
149 $timestart = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
150 $gregoriandate['hour'], $gregoriandate['minute']);
151 $timeend = $timestart + (calendar_days_in_month($now['mon'], $now['year']) * DAYSECS);
152 break;
153 case 'monthnext':
154 // Get the next month for this calendar.
155 list($nextmonth, $nextyear) = calendar_add_month($now['mon'], $now['year']);
157 // Convert to gregorian.
158 $gregoriandate = $calendartype->convert_to_gregorian($nextyear, $nextmonth, 1);
160 // Create the timestamps.
161 $timestart = make_timestamp($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
162 $gregoriandate['hour'], $gregoriandate['minute']);
163 $timeend = $timestart + (calendar_days_in_month($nextmonth, $nextyear) * DAYSECS);
164 break;
165 case 'recentupcoming':
166 //Events in the last 5 or next 60 days
167 $timestart = time() - 432000;
168 $timeend = time() + 5184000;
169 break;
170 case 'custom':
171 // Events based on custom date range.
172 $timestart = time() - $CFG->calendar_exportlookback * DAYSECS;
173 $timeend = time() + $CFG->calendar_exportlookahead * DAYSECS;
174 break;
177 else {
178 // Parameters given but incorrect, redirect back to export page
179 redirect($CFG->wwwroot.'/calendar/export.php');
180 die();
183 $events = calendar_get_legacy_events($timestart, $timeend, $users, $groups, array_keys($paramcourses), false);
185 $ical = new iCalendar;
186 $ical->add_property('method', 'PUBLISH');
187 $ical->add_property('prodid', '-//Moodle Pty Ltd//NONSGML Moodle Version ' . $CFG->version . '//EN');
188 foreach($events as $event) {
189 if (!empty($event->modulename)) {
190 $instances = get_fast_modinfo($event->courseid, $userid)->get_instances_of($event->modulename);
191 if (empty($instances[$event->instance]->uservisible)) {
192 continue;
195 $hostaddress = str_replace('http://', '', $CFG->wwwroot);
196 $hostaddress = str_replace('https://', '', $hostaddress);
198 $me = new calendar_event($event); // To use moodle calendar event services.
199 $ev = new iCalendar_event; // To export in ical format.
200 $ev->add_property('uid', $event->id.'@'.$hostaddress);
202 // Set iCal event summary from event name.
203 $ev->add_property('summary', format_string($event->name, true, ['context' => $me->context]));
205 // Format the description text.
206 $description = format_text($me->description, $me->format, ['context' => $me->context]);
207 // Then convert it to plain text, since it's the only format allowed for the event description property.
208 // We use html_to_text in order to convert <br> and <p> tags to new line characters for descriptions in HTML format.
209 $description = html_to_text($description, 0);
210 $ev->add_property('description', $description);
212 $ev->add_property('class', 'PUBLIC'); // PUBLIC / PRIVATE / CONFIDENTIAL
213 $ev->add_property('last-modified', Bennu::timestamp_to_datetime($event->timemodified));
215 if (!empty($event->location)) {
216 $ev->add_property('location', $event->location);
219 $ev->add_property('dtstamp', Bennu::timestamp_to_datetime()); // now
220 if ($event->timeduration > 0) {
221 //dtend is better than duration, because it works in Microsoft Outlook and works better in Korganizer
222 $ev->add_property('dtstart', Bennu::timestamp_to_datetime($event->timestart)); // when event starts.
223 $ev->add_property('dtend', Bennu::timestamp_to_datetime($event->timestart + $event->timeduration));
224 } else if ($event->timeduration == 0) {
225 // When no duration is present, the event is instantaneous event, ex - Due date of a module.
226 // Moodle doesn't support all day events yet. See MDL-56227.
227 $ev->add_property('dtstart', Bennu::timestamp_to_datetime($event->timestart));
228 $ev->add_property('dtend', Bennu::timestamp_to_datetime($event->timestart));
229 } else {
230 // This can be used to represent all day events in future.
231 throw new coding_exception("Negative duration is not supported yet.");
233 if ($event->courseid != 0) {
234 $coursecontext = context_course::instance($event->courseid);
235 $ev->add_property('categories', format_string($courses[$event->courseid]->shortname, true, array('context' => $coursecontext)));
237 $ical->add_component($ev);
240 $serialized = $ical->serialize();
241 if(empty($serialized)) {
242 // TODO
243 die('bad serialization');
246 $filename = 'icalexport.ics';
248 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
249 header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
250 header('Expires: '. gmdate('D, d M Y H:i:s', 0) .'GMT');
251 header('Pragma: no-cache');
252 header('Accept-Ranges: none'); // Comment out if PDFs do not work...
253 header('Content-disposition: attachment; filename='.$filename);
254 header('Content-length: '.strlen($serialized));
255 header('Content-type: text/calendar; charset=utf-8');
257 echo $serialized;