MDL-16660: WIP - fixes as per review
[moodle.git] / calendar / lib.php
CommitLineData
93c91ee4 1<?php
08b4a4e1
RW
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
7423f116 16
08b4a4e1
RW
17/**
18 * Calendar extension
19 *
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
22 * Avgoustos Tsinakos
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
4c349ad7 26require_once($CFG->libdir.'/bennu/bennu.inc.php');
b5a52acd 27
08b4a4e1
RW
28/**
29 * These are read by the administration component to provide default values
30 */
31
32/**
33 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
34 */
bb4a2e85 35define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
08b4a4e1
RW
36
37/**
38 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
39 */
bb4a2e85 40define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
08b4a4e1
RW
41
42/**
43 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
44 */
45define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
46
bb4a2e85 47// This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
48// Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
08b4a4e1
RW
49
50/**
51 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
52 */
53define('CALENDAR_DEFAULT_WEEKEND', 65);
54
55/**
56 * CALENDAR_URL - path to calendar's folder
57 */
76d9df3f 58define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
08b4a4e1
RW
59
60/**
61 * CALENDAR_TF_24 - Calendar time in 24 hours format
62 */
76d9df3f 63define('CALENDAR_TF_24', '%H:%M');
08b4a4e1
RW
64
65/**
66 * CALENDAR_TF_12 - Calendar time in 12 hours format
67 */
76d9df3f 68define('CALENDAR_TF_12', '%I:%M %p');
bb4a2e85 69
08b4a4e1
RW
70/**
71 * CALENDAR_EVENT_GLOBAL - Global calendar event types
72 */
797cedc7 73define('CALENDAR_EVENT_GLOBAL', 1);
08b4a4e1
RW
74
75/**
76 * CALENDAR_EVENT_COURSE - Course calendar event types
77 */
797cedc7 78define('CALENDAR_EVENT_COURSE', 2);
08b4a4e1
RW
79
80/**
81 * CALENDAR_EVENT_GROUP - group calendar event types
82 */
797cedc7 83define('CALENDAR_EVENT_GROUP', 4);
08b4a4e1
RW
84
85/**
86 * CALENDAR_EVENT_USER - user calendar event types
87 */
797cedc7
SH
88define('CALENDAR_EVENT_USER', 8);
89
7423f116 90
b5a52acd
JH
91/**
92 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
93 */
94define('CALENDAR_IMPORT_FROM_FILE', 0);
95
96/**
97 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
98 */
99define('CALENDAR_IMPORT_FROM_URL', 1);
100
101/**
102 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
103 */
104define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
105
106/**
107 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
108 */
109define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
110
797cedc7
SH
111/**
112 * Return the days of the week
113 *
08b4a4e1 114 * @return array array of days
797cedc7
SH
115 */
116function calendar_get_days() {
117 return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
118}
f2bffd9e 119
76d9df3f
SH
120/**
121 * Gets the first day of the week
122 *
123 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
124 *
125 * @return int
126 */
127function calendar_get_starting_weekday() {
128 global $CFG;
37d87d11 129
76d9df3f
SH
130 if (isset($CFG->calendar_startwday)) {
131 $firstday = $CFG->calendar_startwday;
132 } else {
0a933ae6 133 $firstday = get_string('firstdayofweek', 'langconfig');
76d9df3f
SH
134 }
135
136 if(!is_numeric($firstday)) {
137 return CALENDAR_DEFAULT_STARTING_WEEKDAY;
138 } else {
139 return intval($firstday) % 7;
140 }
141}
bd119567 142
0f927f1e 143/**
14236cbd 144 * Generates the HTML for a miniature calendar
0f927f1e 145 *
08b4a4e1
RW
146 * @param array $courses list of course
147 * @param array $groups list of group
148 * @param array $users user's info
149 * @param int $cal_month calendar month in numeric, default is set to false
150 * @param int $cal_year calendar month in numeric, default is set to false
151 * @return string $content return html table for mini calendar
0f927f1e 152 */
7423f116 153function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
6b608f8f 154 global $CFG, $USER, $OUTPUT;
7423f116 155
dd97c328 156 $display = new stdClass;
76d9df3f 157 $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
7423f116 158 $display->maxwday = $display->minwday + 6;
159
160 $content = '';
161
162 if(!empty($cal_month) && !empty($cal_year)) {
163 $thisdate = usergetdate(time()); // Date and time the user sees at his location
164 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
165 // Navigated to this month
166 $date = $thisdate;
167 $display->thismonth = true;
36dc3b71 168 } else {
7423f116 169 // Navigated to other month, let's do a nice trick and save us a lot of work...
170 if(!checkdate($cal_month, 1, $cal_year)) {
171 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
172 $display->thismonth = true;
36dc3b71 173 } else {
7423f116 174 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
175 $display->thismonth = false;
176 }
177 }
36dc3b71 178 } else {
7423f116 179 $date = usergetdate(time()); // Date and time the user sees at his location
180 $display->thismonth = true;
181 }
182
183 // Fill in the variables we 're going to use, nice and tidy
184 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
185 $display->maxdays = calendar_days_in_month($m, $y);
186
d6198903 187 if (get_user_timezone_offset() < 99) {
188 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
61240489 189 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
190 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
d6198903 191 } else {
192 // no timezone info specified
61240489 193 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
194 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
d6198903 195 }
7423f116 196
69244b91 197 $startwday = dayofweek(1, $m, $y);
7423f116 198
199 // Align the starting weekday to fall in our display range
200 // This is simple, not foolproof.
201 if($startwday < $display->minwday) {
202 $startwday += 7;
203 }
204
c0b507d1 205 // TODO: THIS IS TEMPORARY CODE!
206 // [pj] I was just reading through this and realized that I when writing this code I was probably
207 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
208 // make_timestamp would accomplish the same thing. So here goes a test:
1747ee05 209 //$test_start = make_timestamp($y, $m, 1);
210 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
211 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
212 //notify('Failed assertion in calendar/lib.php line 126; display->tstart = '.$display->tstart.', dst_offset = '.dst_offset_on($display->tstart).', usertime = '.usertime($display->tstart).', make_t = '.$test_start);
213 //}
214 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
215 //notify('Failed assertion in calendar/lib.php line 130; display->tend = '.$display->tend.', dst_offset = '.dst_offset_on($display->tend).', usertime = '.usertime($display->tend).', make_t = '.$test_end);
216 //}
c0b507d1 217
218
7423f116 219 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
8263f802 220 $events = calendar_get_events(
d3555a2f 221 usertime($display->tstart) - dst_offset_on($display->tstart),
222 usertime($display->tend) - dst_offset_on($display->tend),
223 $users, $groups, $courses);
7423f116 224
b4892fa2 225 // Set event course class for course events
226 if (!empty($events)) {
13534ef7 227 foreach ($events as $eventid => $event) {
13534ef7
ML
228 if (!empty($event->modulename)) {
229 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
230 if (!groups_course_module_visible($cm)) {
231 unset($events[$eventid]);
232 }
233 }
b4892fa2 234 }
235 }
6619eba4 236
c635dcda 237 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 238 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 239 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
240 // arguments to this function.
241
0f927f1e 242 $hrefparams = array();
7bd1677c 243 if(!empty($courses)) {
e749554e 244 $courses = array_diff($courses, array(SITEID));
7bd1677c 245 if(count($courses) == 1) {
0f927f1e 246 $hrefparams['course'] = reset($courses);
7bd1677c 247 }
c635dcda 248 }
249
7423f116 250 // We want to have easy access by day, since the display is on a per-day basis.
251 // Arguments passed by reference.
7b38bfa6 252 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
7c50db30 253 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
7423f116 254
f20c4d02 255 //Accessibility: added summary and <abbr> elements.
797cedc7 256 $days_title = calendar_get_days();
f20c4d02 257
2a06efcc 258 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
90723839 259 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
f136e4c5 260 $content .= '<tr class="weekdays">'; // Header row: day names
7423f116 261
262 // Print out the names of the weekdays
263 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
264 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
265 // This uses the % operator to get the correct weekday no matter what shift we have
266 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
f20c4d02 267 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
268 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
7423f116 269 }
270
f136e4c5 271 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
7423f116 272
273 // For the table display. $week is the row; $dayweek is the column.
7423f116 274 $dayweek = $startwday;
275
276 // Paddding (the first week may have blank days in the beginning)
277 for($i = $display->minwday; $i < $startwday; ++$i) {
3bfd8bc8 278 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
7423f116 279 }
280
797cedc7
SH
281 $weekend = CALENDAR_DEFAULT_WEEKEND;
282 if (isset($CFG->calendar_weekend)) {
283 $weekend = intval($CFG->calendar_weekend);
284 }
285
7423f116 286 // Now display all the calendar
287 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
288 if($dayweek > $display->maxwday) {
289 // We need to change week (table row)
d56d4e23 290 $content .= '</tr><tr>';
7423f116 291 $dayweek = $display->minwday;
7423f116 292 }
92668ad2 293
7423f116 294 // Reset vars
7423f116 295 $cell = '';
797cedc7 296 if ($weekend & (1 << ($dayweek % 7))) {
7423f116 297 // Weekend. This is true no matter what the exact range is.
e2aa618b 298 $class = 'weekend day';
90723839 299 } else {
7423f116 300 // Normal working day.
e2aa618b 301 $class = 'day';
7423f116 302 }
303
304 // Special visual fx if an event is defined
305 if(isset($eventsbyday[$day])) {
90723839 306 $class .= ' hasevent';
0f927f1e
SH
307 $hrefparams['view'] = 'day';
308 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $hrefparams), $day, $m, $y);
f434283f 309
7423f116 310 $popupcontent = '';
311 foreach($eventsbyday[$day] as $eventid) {
41d30a8e 312 if (!isset($events[$eventid])) {
313 continue;
4e17c6f3 314 }
41d30a8e 315 $event = $events[$eventid];
0f927f1e
SH
316 $popupalt = '';
317 $component = 'moodle';
41d30a8e 318 if(!empty($event->modulename)) {
0f927f1e 319 $popupicon = 'icon';
41d30a8e 320 $popupalt = $event->modulename;
0f927f1e 321 $component = $event->modulename;
9064751b 322 } else if ($event->courseid == SITEID) { // Site event
0f927f1e 323 $popupicon = 'c/site';
c3d3b6d4 324 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
0f927f1e 325 $popupicon = 'c/course';
41d30a8e 326 } else if ($event->groupid) { // Group event
0f927f1e 327 $popupicon = 'c/group';
41d30a8e 328 } else if ($event->userid) { // User event
0f927f1e 329 $popupicon = 'c/user';
4e17c6f3 330 }
1d5bd3d2 331
0f927f1e 332 $dayhref->set_anchor('event_'.$event->id);
1d5bd3d2 333
0f927f1e 334 $popupcontent .= html_writer::start_tag('div');
adc3cfc7 335 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
0f927f1e
SH
336 $popupcontent .= html_writer::link($dayhref, format_string($event->name, true));
337 $popupcontent .= html_writer::end_tag('div');
7423f116 338 }
e295df44 339
b5c42e70 340 //Accessibility: functionality moved to calendar_get_popup.
341 if($display->thismonth && $day == $d) {
7df3ea15 342 $popupid = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
b5c42e70 343 } else {
7df3ea15 344 $popupid = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
e295df44 345 }
f20c4d02 346
7423f116 347 // Class and cell content
348 if(isset($typesbyday[$day]['startglobal'])) {
90723839
SH
349 $class .= ' calendar_event_global';
350 } else if(isset($typesbyday[$day]['startcourse'])) {
351 $class .= ' calendar_event_course';
352 } else if(isset($typesbyday[$day]['startgroup'])) {
353 $class .= ' calendar_event_group';
354 } else if(isset($typesbyday[$day]['startuser'])) {
355 $class .= ' calendar_event_user';
7423f116 356 }
7df3ea15 357 $cell = html_writer::link((string)$dayhref, $day, array('aria-controls' => $popupid.'_panel', 'id' => $popupid));
90723839 358 } else {
05fcc5fd 359 $cell = $day;
7423f116 360 }
361
90723839
SH
362 $durationclass = false;
363 if (isset($typesbyday[$day]['durationglobal'])) {
364 $durationclass = ' duration_global';
365 } else if(isset($typesbyday[$day]['durationcourse'])) {
366 $durationclass = ' duration_course';
367 } else if(isset($typesbyday[$day]['durationgroup'])) {
368 $durationclass = ' duration_group';
369 } else if(isset($typesbyday[$day]['durationuser'])) {
370 $durationclass = ' duration_user';
7423f116 371 }
90723839
SH
372 if ($durationclass) {
373 $class .= ' duration '.$durationclass;
7423f116 374 }
375
b4892fa2 376 // If event has a class set then add it to the table day <td> tag
377 // Note: only one colour for minicalendar
378 if(isset($eventsbyday[$day])) {
379 foreach($eventsbyday[$day] as $eventid) {
380 if (!isset($events[$eventid])) {
381 continue;
382 }
383 $event = $events[$eventid];
384 if (!empty($event->class)) {
385 $class .= ' '.$event->class;
386 }
387 break;
388 }
389 }
390
7423f116 391 // Special visual fx for today
450a0a7d 392 //Accessibility: hidden text for today, and popup.
7423f116 393 if($display->thismonth && $day == $d) {
edbe6c1b 394 $class .= ' today';
b5c42e70 395 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
e295df44 396
b5c42e70 397 if(! isset($eventsbyday[$day])) {
450a0a7d 398 $class .= ' eventnone';
7df3ea15
AA
399 $popupid = calendar_get_popup(true, false);
400 $cell = html_writer::link('#', $day, array('aria-controls' => $popupid.'_panel', 'id' => $popupid));;
b5c42e70 401 }
f79f2494 402 $cell = get_accesshide($today.' ').$cell;
7423f116 403 }
404
405 // Just display it
92668ad2 406 if(!empty($class)) {
d56d4e23 407 $class = ' class="'.$class.'"';
92668ad2 408 }
409 $content .= '<td'.$class.'>'.$cell."</td>\n";
7423f116 410 }
411
412 // Paddding (the last week may have blank days at the end)
413 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
3bfd8bc8 414 $content .= '<td class="dayblank">&nbsp;</td>';
7423f116 415 }
416 $content .= '</tr>'; // Last row ends
417
f136e4c5 418 $content .= '</table>'; // Tabular display of days ends
7423f116 419
420 return $content;
421}
422
b5c42e70 423/**
08b4a4e1
RW
424 * Gets the calendar popup
425 *
426 * It called at multiple points in from calendar_get_mini.
427 * Copied and modified from calendar_get_mini.
428 *
429 * @param bool $is_today false except when called on the current day.
430 * @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
7df3ea15
AA
431 * @param string $popupcontent content for the popup window/layout.
432 * @return string eventid for the calendar_tooltip popup window/layout.
b5c42e70 433 */
434function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
458eb0d1 435 global $PAGE;
436 static $popupcount;
437 if ($popupcount === null) {
438 $popupcount = 1;
439 }
b5c42e70 440 $popupcaption = '';
441 if($is_today) {
442 $popupcaption = get_string('today', 'calendar').' ';
443 }
444 if (false === $event_timestart) {
445 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
446 $popupcontent = get_string('eventnone', 'calendar');
450a0a7d 447
b5c42e70 448 } else {
449 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
450 }
458eb0d1 451 $id = 'calendar_tooltip_'.$popupcount;
33e48a1a 452 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
bdbae764 453
458eb0d1 454 $popupcount++;
7df3ea15 455 return $id;
b5c42e70 456}
457
08b4a4e1
RW
458/**
459 * Gets the calendar upcoming event
460 *
461 * @param array $courses array of courses
462 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
463 * @param array|int|bool $users array of users, user id or boolean for all/no user events
464 * @param int $daysinfuture number of days in the future we 'll look
465 * @param int $maxevents maximum number of events
466 * @param int $fromtime start time
467 * @return array $output array of upcoming events
468 */
9958a08c 469function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
62d11d77 470 global $CFG, $COURSE, $DB;
7423f116 471
dd97c328 472 $display = new stdClass;
7423f116 473 $display->range = $daysinfuture; // How many days in the future we 'll look
474 $display->maxevents = $maxevents;
475
476 $output = array();
477
478 // Prepare "course caching", since it may save us a lot of queries
479 $coursecache = array();
480
481 $processed = 0;
482 $now = time(); // We 'll need this later
9d567178 483 $usermidnighttoday = usergetmidnight($now);
7423f116 484
9958a08c 485 if ($fromtime) {
486 $display->tstart = $fromtime;
487 } else {
9d567178 488 $display->tstart = $usermidnighttoday;
9958a08c 489 }
7423f116 490
1f473774 491 // This works correctly with respect to the user's DST, but it is accurate
492 // only because $fromtime is always the exact midnight of some day!
493 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
7423f116 494
495 // Get the events matching our criteria
8263f802 496 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
7423f116 497
c635dcda 498 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 499 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 500 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
501 // arguments to this function.
502
0f927f1e 503 $hrefparams = array();
7bd1677c 504 if(!empty($courses)) {
e749554e 505 $courses = array_diff($courses, array(SITEID));
7bd1677c 506 if(count($courses) == 1) {
0f927f1e 507 $hrefparams['course'] = reset($courses);
7bd1677c 508 }
c635dcda 509 }
510
dd97c328 511 if ($events !== false) {
512
f20edd52 513 $modinfo = get_fast_modinfo($COURSE);
fa22fd5f 514
7423f116 515 foreach($events as $event) {
dc6cb74e 516
dd97c328 517
518 if (!empty($event->modulename)) {
519 if ($event->courseid == $COURSE->id) {
520 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
521 $cm = $modinfo->instances[$event->modulename][$event->instance];
522 if (!$cm->uservisible) {
523 continue;
524 }
525 }
526 } else {
527 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
dc6cb74e 528 continue;
529 }
dd97c328 530 if (!coursemodule_visible_for_user($cm)) {
dc6cb74e 531 continue;
532 }
dd97c328 533 }
534 if ($event->modulename == 'assignment'){
f4700b91
RW
535 // create calendar_event to test edit_event capability
536 // this new event will also prevent double creation of calendar_event object
537 $checkevent = new calendar_event($event);
dd97c328 538 // TODO: rewrite this hack somehow
f4700b91 539 if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
62d11d77 540 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
f581f8d6 541 // print_error("invalidid", 'assignment');
dd97c328 542 continue;
543 }
544 // assign assignment to assignment object to use hidden_is_hidden method
545 require_once($CFG->dirroot.'/mod/assignment/lib.php');
546
547 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
548 continue;
549 }
550 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
551
552 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
553 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
554
555 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
556 $event->description = get_string('notavailableyet', 'assignment');
557 }
dc6cb74e 558 }
559 }
560 }
9d567178 561
dd97c328 562 if ($processed >= $display->maxevents) {
9d567178 563 break;
564 }
7423f116 565
0f927f1e 566 $event->time = calendar_format_event_time($event, $now, $hrefparams);
3c134875 567 $output[] = $event;
568 ++$processed;
569 }
570 }
571 return $output;
572}
7423f116 573
08b4a4e1
RW
574/**
575 * Add calendar event metadata
576 *
577 * @param stdClass $event event info
578 * @return stdClass $event metadata
579 */
9df8ff44 580function calendar_add_event_metadata($event) {
6b608f8f 581 global $CFG, $OUTPUT;
fb73f3b3 582
e295df44 583 //Support multilang in event->name
fb73f3b3 584 $event->name = format_string($event->name,true);
e295df44 585
3c134875 586 if(!empty($event->modulename)) { // Activity event
587 // The module name is set. I will assume that it has to be displayed, and
588 // also that it is an automatically-generated event. And of course that the
589 // fields for get_coursemodule_from_instance are set correctly.
590 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
7423f116 591
3c134875 592 if ($module === false) {
593 return;
594 }
9958a08c 595
3c134875 596 $modulename = get_string('modulename', $event->modulename);
a48bf079
DM
597 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
598 // will be used as alt text if the event icon
599 $eventtype = get_string($event->eventtype, $event->modulename);
600 } else {
601 $eventtype = '';
602 }
b5d0cafc 603 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
9958a08c 604
6ca657a7 605 $context = context_course::instance($module->course);
91d284c1
SH
606 $fullname = format_string($coursecache[$module->course]->fullname, true, array('context' => $context));
607
10daca92 608 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
fb73f3b3 609 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
91d284c1 610 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$fullname.'</a>';
3c134875 611 $event->cmid = $module->id;
9958a08c 612
9958a08c 613
3c134875 614 } else if($event->courseid == SITEID) { // Site event
b5d0cafc 615 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
90723839 616 $event->cssclass = 'calendar_event_global';
3c134875 617 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
618 calendar_get_course_cached($coursecache, $event->courseid);
91d284c1 619
6ca657a7 620 $context = context_course::instance($event->courseid);
91d284c1
SH
621 $fullname = format_string($coursecache[$event->courseid]->fullname, true, array('context' => $context));
622
b5d0cafc 623 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
91d284c1 624 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$fullname.'</a>';
90723839 625 $event->cssclass = 'calendar_event_course';
3c134875 626 } else if ($event->groupid) { // Group event
b5d0cafc 627 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
90723839 628 $event->cssclass = 'calendar_event_group';
3c134875 629 } else if($event->userid) { // User event
b5d0cafc 630 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
90723839 631 $event->cssclass = 'calendar_event_user';
3c134875 632 }
9df8ff44 633 return $event;
e295df44 634}
9df8ff44 635
8263f802 636/**
637 * Get calendar events
08b4a4e1 638 *
8263f802 639 * @param int $tstart Start time of time range for events
08b4a4e1
RW
640 * @param int $tend End time of time range for events
641 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
642 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
643 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
8263f802 644 * @param boolean $withduration whether only events starting within time range selected
645 * or events in progress/already started selected as well
646 * @param boolean $ignorehidden whether to select only visible events or all events
08b4a4e1 647 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
8263f802 648 */
649function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
62d11d77 650 global $DB;
651
7423f116 652 $whereclause = '';
653 // Quick test
654 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
8263f802 655 return array();
7423f116 656 }
482dbe0c 657
7423f116 658 if(is_array($users) && !empty($users)) {
659 // Events from a number of users
660 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 661 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
36dc3b71 662 } else if(is_numeric($users)) {
7423f116 663 // Events from one user
664 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 665 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
36dc3b71 666 } else if($users === true) {
7423f116 667 // Events from ALL users
668 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 669 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
36dc3b71 670 } else if($users === false) {
6e957c41 671 // No user at all, do nothing
f52f7413 672 }
482dbe0c 673
7423f116 674 if(is_array($groups) && !empty($groups)) {
675 // Events from a number of groups
676 if(!empty($whereclause)) $whereclause .= ' OR';
677 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
36dc3b71 678 } else if(is_numeric($groups)) {
7423f116 679 // Events from one group
680 if(!empty($whereclause)) $whereclause .= ' OR ';
681 $whereclause .= ' groupid = '.$groups;
36dc3b71 682 } else if($groups === true) {
7423f116 683 // Events from ALL groups
684 if(!empty($whereclause)) $whereclause .= ' OR ';
685 $whereclause .= ' groupid != 0';
686 }
482dbe0c 687 // boolean false (no groups at all): we don't need to do anything
688
36dc3b71
SH
689 if(is_array($courses) && !empty($courses)) {
690 if(!empty($whereclause)) {
691 $whereclause .= ' OR';
f52f7413 692 }
36dc3b71
SH
693 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
694 } else if(is_numeric($courses)) {
7423f116 695 // One course
696 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 697 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
36dc3b71 698 } else if ($courses === true) {
7423f116 699 // Events from ALL courses
700 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 701 $whereclause .= ' (groupid = 0 AND courseid != 0)';
7423f116 702 }
8c165fe9 703
482dbe0c 704 // Security check: if, by now, we have NOTHING in $whereclause, then it means
705 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
706 // events no matter what. Allowing the code to proceed might return a completely
707 // valid query with only time constraints, thus selecting ALL events in that time frame!
708 if(empty($whereclause)) {
8263f802 709 return array();
482dbe0c 710 }
711
7423f116 712 if($withduration) {
b4892fa2 713 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
7423f116 714 }
715 else {
716 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
717 }
718 if(!empty($whereclause)) {
719 // We have additional constraints
720 $whereclause = $timeclause.' AND ('.$whereclause.')';
721 }
722 else {
723 // Just basic time filtering
724 $whereclause = $timeclause;
725 }
f52f7413 726
0ad072de 727 if ($ignorehidden) {
728 $whereclause .= ' AND visible = 1';
729 }
730
62d11d77 731 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
8263f802 732 if ($events === false) {
733 $events = array();
734 }
735 return $events;
7423f116 736}
737
08b4a4e1
RW
738/**
739 * Get control options for Calendar
740 *
741 * @param string $type of calendar
742 * @param array $data calendar information
743 * @return string $content return available control for the calender in html
744 */
7423f116 745function calendar_top_controls($type, $data) {
797cedc7 746 global $CFG;
7423f116 747 $content = '';
748 if(!isset($data['d'])) {
749 $data['d'] = 1;
750 }
5147ad48 751
f21ed0f3 752 // Ensure course id passed if relevant
753 // Required due to changes in view/lib.php mainly (calendar_session_vars())
754 $courseid = '';
755 if (!empty($data['id'])) {
756 $courseid = '&amp;course='.$data['id'];
757 }
758
5147ad48 759 if(!checkdate($data['m'], $data['d'], $data['y'])) {
760 $time = time();
761 }
762 else {
763 $time = make_timestamp($data['y'], $data['m'], $data['d']);
764 }
765 $date = usergetdate($time);
e295df44 766
7423f116 767 $data['m'] = $date['mon'];
768 $data['y'] = $date['year'];
7423f116 769
2a06efcc 770 //Accessibility: calendar block controls, replaced <table> with <div>.
a84dea2c 771 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
772 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
2a06efcc 773
7423f116 774 switch($type) {
775 case 'frontpage':
776 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
777 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
a84dea2c 778 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
779 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
ae53bd1d 780
0f927f1e
SH
781 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
782 if (!empty($data['id'])) {
783 $calendarlink->param('course', $data['id']);
784 }
785
43c90b9b 786 if (right_to_left()) {
0f927f1e
SH
787 $left = $nextlink;
788 $right = $prevlink;
43c90b9b 789 } else {
0f927f1e
SH
790 $left = $prevlink;
791 $right = $nextlink;
43c90b9b 792 }
ae53bd1d 793
0f927f1e
SH
794 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
795 $content .= $left.'<span class="hide"> | </span>';
e71e340d 796 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
0f927f1e 797 $content .= '<span class="hide"> | </span>'. $right;
6694ff84 798 $content .= "<span class=\"clearer\"><!-- --></span>\n";
0f927f1e
SH
799 $content .= html_writer::end_tag('div');
800
801 break;
7423f116 802 case 'course':
803 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
804 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
a84dea2c 805 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
806 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);
0f927f1e
SH
807
808 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
809 if (!empty($data['id'])) {
810 $calendarlink->param('course', $data['id']);
811 }
812
813 if (right_to_left()) {
814 $left = $nextlink;
815 $right = $prevlink;
816 } else {
817 $left = $prevlink;
818 $right = $nextlink;
819 }
820
821 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
822 $content .= $left.'<span class="hide"> | </span>';
e71e340d 823 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
0f927f1e
SH
824 $content .= '<span class="hide"> | </span>'. $right;
825 $content .= "<span class=\"clearer\"><!-- --></span>";
826 $content .= html_writer::end_tag('div');
827 break;
7423f116 828 case 'upcoming':
0f927f1e
SH
829 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
830 if (!empty($data['id'])) {
831 $calendarlink->param('course', $data['id']);
832 }
833 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
834 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
835 break;
7423f116 836 case 'display':
0f927f1e
SH
837 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
838 if (!empty($data['id'])) {
839 $calendarlink->param('course', $data['id']);
840 }
841 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
842 $content .= html_writer::tag('h3', $calendarlink);
843 break;
7423f116 844 case 'month':
845 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
846 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
5147ad48 847 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
848 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
0f927f1e
SH
849 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
850 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
851
852 if (right_to_left()) {
853 $left = $nextlink;
854 $right = $prevlink;
855 } else {
856 $left = $prevlink;
857 $right = $nextlink;
858 }
859
860 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
861 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
862 $content .= '<span class="hide"> | </span>' . $right;
863 $content .= '<span class="clearer"><!-- --></span>';
864 $content .= html_writer::end_tag('div')."\n";
865 break;
7423f116 866 case 'day':
797cedc7 867 $days = calendar_get_days();
7423f116 868 $data['d'] = $date['mday']; // Just for convenience
5147ad48 869 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
870 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
797cedc7
SH
871 $prevname = calendar_wday_name($days[$prevdate['wday']]);
872 $nextname = calendar_wday_name($days[$nextdate['wday']]);
0f927f1e
SH
873 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
874 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
875
876 if (right_to_left()) {
877 $left = $nextlink;
878 $right = $prevlink;
879 } else {
880 $left = $prevlink;
881 $right = $nextlink;
882 }
883
884 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
885 $content .= $left;
886 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
887 $content .= '<span class="hide"> | </span>'. $right;
888 $content .= "<span class=\"clearer\"><!-- --></span>";
889 $content .= html_writer::end_tag('div')."\n";
890
891 break;
7423f116 892 }
893 return $content;
894}
895
ef21ad21
FM
896/**
897 * Formats a filter control element.
898 *
899 * @param moodle_url $url of the filter
900 * @param int $type constant defining the type filter
901 * @return string html content of the element
902 */
903function calendar_filter_controls_element(moodle_url $url, $type) {
904 global $OUTPUT;
905 switch ($type) {
906 case CALENDAR_EVENT_GLOBAL:
907 $typeforhumans = 'global';
908 $class = 'calendar_event_global';
909 break;
910 case CALENDAR_EVENT_COURSE:
911 $typeforhumans = 'course';
912 $class = 'calendar_event_course';
913 break;
914 case CALENDAR_EVENT_GROUP:
915 $typeforhumans = 'groups';
916 $class = 'calendar_event_group';
917 break;
918 case CALENDAR_EVENT_USER:
919 $typeforhumans = 'user';
920 $class = 'calendar_event_user';
921 break;
922 }
923 if (calendar_show_event_type($type)) {
924 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
925 $str = get_string('hide'.$typeforhumans.'events', 'calendar');
926 } else {
927 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
928 $str = get_string('show'.$typeforhumans.'events', 'calendar');
929 }
930 $content = html_writer::start_tag('li', array('class' => 'calendar_event'));
931 $content .= html_writer::start_tag('a', array('href' => $url));
932 $content .= html_writer::tag('span', $icon, array('class' => $class));
933 $content .= html_writer::tag('span', $str, array('class' => 'eventname'));
934 $content .= html_writer::end_tag('a');
935 $content .= html_writer::end_tag('li');
936 return $content;
937}
938
08b4a4e1
RW
939/**
940 * Get the controls filter for calendar.
941 *
942 * Filter is used to hide calendar info from the display page
943 *
944 * @param moodle_url $returnurl return-url for filter controls
945 * @return string $content return filter controls in html
946 */
797cedc7
SH
947function calendar_filter_controls(moodle_url $returnurl) {
948 global $CFG, $USER, $OUTPUT;
7423f116 949
48f508ab 950 $groupevents = true;
7f4d18fc 951 $id = optional_param( 'id',0,PARAM_INT );
eb59a448 952 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));
ef21ad21 953 $content = html_writer::start_tag('ul');
797cedc7
SH
954
955 $seturl->param('var', 'showglobal');
ef21ad21 956 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL);
aa6c1ced 957
797cedc7 958 $seturl->param('var', 'showcourses');
ef21ad21 959 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE);
48f508ab 960
4f0c2d00 961 if (isloggedin() && !isguestuser()) {
797cedc7 962 if ($groupevents) {
43c3ffbe 963 // This course MIGHT have group events defined, so show the filter
797cedc7 964 $seturl->param('var', 'showgroups');
ef21ad21 965 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP);
e3bb6401 966 } else {
43c3ffbe 967 // This course CANNOT have group events, so lose the filter
fdbffa54 968 }
797cedc7 969 $seturl->param('var', 'showuser');
ef21ad21 970 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER);
48f508ab 971 }
ef21ad21 972 $content .= html_writer::end_tag('ul');
48f508ab 973
7423f116 974 return $content;
975}
976
08b4a4e1
RW
977/**
978 * Return the representation day
979 *
980 * @param int $tstamp Timestamp in GMT
981 * @param int $now current Unix timestamp
982 * @param bool $usecommonwords
983 * @return string the formatted date/time
984 */
7423f116 985function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
986
0ef7c973 987 static $shortformat;
988 if(empty($shortformat)) {
e70fdac0 989 $shortformat = get_string('strftimedayshort');
0ef7c973 990 }
991
7423f116 992 if($now === false) {
993 $now = time();
994 }
995
996 // To have it in one place, if a change is needed
e70fdac0 997 $formal = userdate($tstamp, $shortformat);
7423f116 998
7b38bfa6 999 $datestamp = usergetdate($tstamp);
1000 $datenow = usergetdate($now);
7423f116 1001
1002 if($usecommonwords == false) {
1003 // We don't want words, just a date
1004 return $formal;
1005 }
7b38bfa6 1006 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
7423f116 1007 // Today
1008 return get_string('today', 'calendar');
1009 }
7b38bfa6 1010 else if(
1011 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1012 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
1013 ) {
7423f116 1014 // Yesterday
1015 return get_string('yesterday', 'calendar');
1016 }
7b38bfa6 1017 else if(
1018 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1019 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
1020 ) {
7423f116 1021 // Tomorrow
1022 return get_string('tomorrow', 'calendar');
1023 }
1024 else {
1025 return $formal;
1026 }
1027}
1028
08b4a4e1
RW
1029/**
1030 * return the formatted representation time
1031 *
1032 * @param int $time the timestamp in UTC, as obtained from the database
1033 * @return string the formatted date/time
1034 */
7423f116 1035function calendar_time_representation($time) {
1b0ebe79 1036 static $langtimeformat = NULL;
1037 if($langtimeformat === NULL) {
1038 $langtimeformat = get_string('strftimetime');
1039 }
1040 $timeformat = get_user_preferences('calendar_timeformat');
c7dd2550 1041 if(empty($timeformat)){
1042 $timeformat = get_config(NULL,'calendar_site_timeformat');
1043 }
1b0ebe79 1044 // The ? is needed because the preference might be present, but empty
1045 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
7423f116 1046}
1047
e295df44 1048/**
14236cbd
SH
1049 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1050 *
1051 * @param string|moodle_url $linkbase
08b4a4e1
RW
1052 * @param int $d The number of the day.
1053 * @param int $m The number of the month.
1054 * @param int $y The number of the year.
1055 * @return moodle_url|null $linkbase
e295df44 1056 */
7423f116 1057function calendar_get_link_href($linkbase, $d, $m, $y) {
0f927f1e
SH
1058 if (empty($linkbase)) {
1059 return '';
1060 }
1061 if (!($linkbase instanceof moodle_url)) {
1062 $linkbase = new moodle_url();
1063 }
1064 if (!empty($d)) {
1065 $linkbase->param('cal_d', $d);
1066 }
1067 if (!empty($m)) {
1068 $linkbase->param('cal_m', $m);
1069 }
1070 if (!empty($y)) {
1071 $linkbase->param('cal_y', $y);
1072 }
1073 return $linkbase;
7423f116 1074}
1075
a84dea2c 1076/**
1077 * Build and return a previous month HTML link, with an arrow.
14236cbd 1078 *
a84dea2c 1079 * @param string $text The text label.
14236cbd 1080 * @param string|moodle_url $linkbase The URL stub.
08b4a4e1
RW
1081 * @param int $d The number of the date.
1082 * @param int $m The number of the month.
1083 * @param int $y year The number of the year.
a84dea2c 1084 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1085 * @return string HTML string.
1086 */
1087function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
0f927f1e
SH
1088 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1089 if (empty($href)) {
1090 return $text;
1091 }
1092 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
a84dea2c 1093}
1094
1095/**
1096 * Build and return a next month HTML link, with an arrow.
1d5bd3d2 1097 *
a84dea2c 1098 * @param string $text The text label.
14236cbd 1099 * @param string|moodle_url $linkbase The URL stub.
08b4a4e1
RW
1100 * @param int $d the number of the Day
1101 * @param int $m The number of the month.
1102 * @param int $y The number of the year.
a84dea2c 1103 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1104 * @return string HTML string.
1105 */
1106function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
0f927f1e
SH
1107 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1108 if (empty($href)) {
1109 return $text;
1110 }
1111 return link_arrow_right($text, (string)$href, $accesshide, 'next');
a84dea2c 1112}
1113
08b4a4e1
RW
1114/**
1115 * Return the name of the weekday
1116 *
1117 * @param string $englishname
1118 * @return string of the weekeday
1119 */
7423f116 1120function calendar_wday_name($englishname) {
1121 return get_string(strtolower($englishname), 'calendar');
1122}
1123
08b4a4e1
RW
1124/**
1125 * Return the number of days in month
1126 *
1127 * @param int $month the number of the month.
1128 * @param int $year the number of the year
1129 * @return int
1130 */
7423f116 1131function calendar_days_in_month($month, $year) {
7b38bfa6 1132 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
7423f116 1133}
1134
08b4a4e1
RW
1135/**
1136 * Get the upcoming event block
1137 *
1138 * @param array $events list of events
1139 * @param moodle_url|string $linkhref link to event referer
1140 * @return string|null $content html block content
1141 */
6605ff8c 1142function calendar_get_block_upcoming($events, $linkhref = NULL) {
7423f116 1143 $content = '';
1144 $lines = count($events);
396b61f0 1145 if (!$lines) {
1146 return $content;
1147 }
7423f116 1148
396b61f0 1149 for ($i = 0; $i < $lines; ++$i) {
b0ac9180 1150 if (!isset($events[$i]->time)) { // Just for robustness
1151 continue;
1152 }
9df8ff44 1153 $events[$i] = calendar_add_event_metadata($events[$i]);
ea21c1f4 1154 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
43c3ffbe 1155 if (!empty($events[$i]->referer)) {
7423f116 1156 // That's an activity event, so let's provide the hyperlink
396b61f0 1157 $content .= $events[$i]->referer;
1158 } else {
e749554e 1159 if(!empty($linkhref)) {
1160 $ed = usergetdate($events[$i]->timestart);
0f927f1e
SH
1161 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1162 $href->set_anchor('event_'.$events[$i]->id);
1163 $content .= html_writer::link($href, $events[$i]->name);
e749554e 1164 }
1165 else {
1166 $content .= $events[$i]->name;
1167 }
7423f116 1168 }
9ecf051d 1169 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1170 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
396b61f0 1171 if ($i < $lines - 1) $content .= '<hr />';
7423f116 1172 }
1173
1174 return $content;
7423f116 1175}
1176
08b4a4e1
RW
1177/**
1178 * Get the next following month
1179 *
1180 * If the current month is December, it will get the first month of the following year.
1181 *
1182 *
1183 * @param int $month the number of the month.
1184 * @param int $year the number of the year.
1185 * @return array the following month
1186 */
7423f116 1187function calendar_add_month($month, $year) {
1188 if($month == 12) {
1189 return array(1, $year + 1);
1190 }
1191 else {
1192 return array($month + 1, $year);
1193 }
1194}
1195
08b4a4e1
RW
1196/**
1197 * Get the previous month
1198 *
1199 * If the current month is January, it will get the last month of the previous year.
1200 *
1201 * @param int $month the number of the month.
1202 * @param int $year the number of the year.
1203 * @return array previous month
1204 */
7423f116 1205function calendar_sub_month($month, $year) {
1206 if($month == 1) {
1207 return array(12, $year - 1);
1208 }
1209 else {
1210 return array($month - 1, $year);
1211 }
1212}
1213
08b4a4e1
RW
1214/**
1215 * Get per-day basis events
1216 *
1217 * @param array $events list of events
1218 * @param int $month the number of the month
1219 * @param int $year the number of the year
1220 * @param array $eventsbyday event on specific day
1221 * @param array $durationbyday duration of the event in days
1222 * @param array $typesbyday event type (eg: global, course, user, or group)
1223 * @param array $courses list of courses
1224 * @return void
1225 */
7c50db30 1226function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
7423f116 1227 $eventsbyday = array();
1228 $typesbyday = array();
1229 $durationbyday = array();
1230
1231 if($events === false) {
1232 return;
1233 }
1234
7423f116 1235 foreach($events as $event) {
7423f116 1236
7b38bfa6 1237 $startdate = usergetdate($event->timestart);
b4892fa2 1238 // Set end date = start date if no duration
1239 if ($event->timeduration) {
1240 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1241 } else {
1242 $enddate = $startdate;
1243 }
7423f116 1244
7b38bfa6 1245 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
ef618501 1246 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
7b38bfa6 1247 // Out of bounds
1248 continue;
7423f116 1249 }
1250
7b38bfa6 1251 $eventdaystart = intval($startdate['mday']);
7423f116 1252
7b38bfa6 1253 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1254 // Give the event to its day
1255 $eventsbyday[$eventdaystart][] = $event->id;
7423f116 1256
7b38bfa6 1257 // Mark the day as having such an event
9064751b 1258 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 1259 $typesbyday[$eventdaystart]['startglobal'] = true;
b4892fa2 1260 // Set event class for global event
90723839 1261 $events[$event->id]->class = 'calendar_event_global';
7b38bfa6 1262 }
c3d3b6d4 1263 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 1264 $typesbyday[$eventdaystart]['startcourse'] = true;
b4892fa2 1265 // Set event class for course event
90723839 1266 $events[$event->id]->class = 'calendar_event_course';
7b38bfa6 1267 }
1268 else if($event->groupid) {
1269 $typesbyday[$eventdaystart]['startgroup'] = true;
b4892fa2 1270 // Set event class for group event
90723839 1271 $events[$event->id]->class = 'calendar_event_group';
7b38bfa6 1272 }
1273 else if($event->userid) {
1274 $typesbyday[$eventdaystart]['startuser'] = true;
b4892fa2 1275 // Set event class for user event
90723839 1276 $events[$event->id]->class = 'calendar_event_user';
7b38bfa6 1277 }
1278 }
7423f116 1279
7b38bfa6 1280 if($event->timeduration == 0) {
1281 // Proceed with the next
1282 continue;
1283 }
7423f116 1284
7b38bfa6 1285 // The event starts on $month $year or before. So...
ef618501 1286 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
7b38bfa6 1287
1288 // Also, it ends on $month $year or later...
1289 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1290
1291 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1292 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1293 $durationbyday[$i][] = $event->id;
9064751b 1294 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 1295 $typesbyday[$i]['durationglobal'] = true;
1296 }
c3d3b6d4 1297 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 1298 $typesbyday[$i]['durationcourse'] = true;
1299 }
1300 else if($event->groupid) {
1301 $typesbyday[$i]['durationgroup'] = true;
1302 }
1303 else if($event->userid) {
1304 $typesbyday[$i]['durationuser'] = true;
7423f116 1305 }
1306 }
7b38bfa6 1307
7423f116 1308 }
1309 return;
1310}
1311
08b4a4e1
RW
1312/**
1313 * Get current module cache
1314 *
1315 * @param array $coursecache list of course cache
1316 * @param string $modulename name of the module
1317 * @param int $instance module instance number
1318 * @return stdClass|bool $module information
1319 */
b63c0ee5 1320function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1321 $module = get_coursemodule_from_instance($modulename, $instance);
7423f116 1322
1323 if($module === false) return false;
b63c0ee5 1324 if(!calendar_get_course_cached($coursecache, $module->course)) {
7423f116 1325 return false;
1326 }
1327 return $module;
1328}
1329
08b4a4e1
RW
1330/**
1331 * Get current course cache
1332 *
1333 * @param array $coursecache list of course cache
1334 * @param int $courseid id of the course
1335 * @return stdClass $coursecache[$courseid] return the specific course cache
1336 */
7423f116 1337function calendar_get_course_cached(&$coursecache, $courseid) {
62d11d77 1338 global $COURSE, $DB;
1339
b571c6b3 1340 if (!isset($coursecache[$courseid])) {
1341 if ($courseid == $COURSE->id) {
1342 $coursecache[$courseid] = $COURSE;
1343 } else {
62d11d77 1344 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
b571c6b3 1345 }
7423f116 1346 }
1347 return $coursecache[$courseid];
1348}
1349
797cedc7
SH
1350/**
1351 * Returns the courses to load events for, the
1352 *
797cedc7 1353 * @param array $courseeventsfrom An array of courses to load calendar events for
08b4a4e1 1354 * @param bool $ignorefilters specify the use of filters, false is set as default
797cedc7
SH
1355 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1356 */
1357function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1358 global $USER, $CFG, $DB;
7423f116 1359
797cedc7
SH
1360 // For backwards compatability we have to check whether the courses array contains
1361 // just id's in which case we need to load course objects.
1362 $coursestoload = array();
1363 foreach ($courseeventsfrom as $id => $something) {
1364 if (!is_object($something)) {
1365 $coursestoload[] = $id;
1366 unset($courseeventsfrom[$id]);
753b799d 1367 }
dd97c328 1368 }
797cedc7
SH
1369 if (!empty($coursestoload)) {
1370 // TODO remove this in 2.2
1371 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
1372 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
89adb174 1373 }
7423f116 1374
797cedc7
SH
1375 $courses = array();
1376 $user = false;
1377 $group = false;
7423f116 1378
7fd5786e
HB
1379 // capabilities that allow seeing group events from all groups
1380 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1381 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1382
797cedc7 1383 $isloggedin = isloggedin();
d12e3ff2 1384
797cedc7
SH
1385 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1386 $courses = array_keys($courseeventsfrom);
7423f116 1387 }
797cedc7
SH
1388 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1389 $courses[] = SITEID;
7423f116 1390 }
797cedc7
SH
1391 $courses = array_unique($courses);
1392 sort($courses);
7c50db30 1393
797cedc7 1394 if (!empty($courses) && in_array(SITEID, $courses)) {
7c50db30 1395 // Sort courses for consistent colour highlighting
1396 // Effectively ignoring SITEID as setting as last course id
1397 $key = array_search(SITEID, $courses);
797cedc7
SH
1398 unset($courses[$key]);
1399 $courses[] = SITEID;
0e6a8f4b 1400 }
7423f116 1401
797cedc7
SH
1402 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1403 $user = $USER->id;
7423f116 1404 }
257e3f4c 1405
797cedc7
SH
1406 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1407
7fd5786e
HB
1408 if (count($courseeventsfrom)==1) {
1409 $course = reset($courseeventsfrom);
6ca657a7 1410 if (has_any_capability($allgroupscaps, context_course::instance($course->id))) {
7fd5786e
HB
1411 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
1412 $group = array_keys($coursegroups);
7423f116 1413 }
7fd5786e
HB
1414 }
1415 if ($group === false) {
1416 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, get_system_context())) {
1417 $group = true;
1418 } else if ($isloggedin) {
1419 $groupids = array();
c46da759 1420
7fd5786e
HB
1421 // We already have the courses to examine in $courses
1422 // For each course...
1423 foreach ($courseeventsfrom as $courseid => $course) {
1424 // If the user is an editing teacher in there,
1425 if (!empty($USER->groupmember[$course->id])) {
1426 // We've already cached the users groups for this course so we can just use that
1427 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1428 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1429 // If this course has groups, show events from all of those related to the current user
1430 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1431 $groupids = array_merge($groupids, $coursegroups['0']);
1432 }
1433 }
1434 if (!empty($groupids)) {
1435 $group = $groupids;
1436 }
6c9584d1 1437 }
7423f116 1438 }
7423f116 1439 }
797cedc7
SH
1440 if (empty($courses)) {
1441 $courses = false;
7423f116 1442 }
797cedc7
SH
1443
1444 return array($courses, $group, $user);
7423f116 1445}
1446
08b4a4e1
RW
1447/**
1448 * Return the capability for editing calendar event
1449 *
1450 * @param calendar_event $event event object
1451 * @return bool capability to edit event
1452 */
7423f116 1453function calendar_edit_event_allowed($event) {
62d11d77 1454 global $USER, $DB;
7423f116 1455
2ac8da76 1456 // Must be logged in
1457 if (!isloggedin()) {
1458 return false;
1459 }
1460
89491dbd 1461 // can not be using guest account
2396a414 1462 if (isguestuser()) {
e295df44 1463 return false;
89491dbd 1464 }
e295df44 1465
6ca657a7 1466 $sitecontext = context_system::instance();
89491dbd 1467 // if user has manageentries at site level, return true
28ee98c5 1468 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
89491dbd 1469 return true;
f52f7413 1470 }
e295df44 1471
c0a2c361 1472 // if groupid is set, it's definitely a group event
438e4add 1473 if (!empty($event->groupid)) {
f63d2922 1474 // Allow users to add/edit group events if:
1475 // 1) They have manageentries (= entries for whole course)
1476 // 2) They have managegroupentries AND are in the group
62d11d77 1477 $group = $DB->get_record('groups', array('id'=>$event->groupid));
f63d2922 1478 return $group && (
f4700b91
RW
1479 has_capability('moodle/calendar:manageentries', $event->context) ||
1480 (has_capability('moodle/calendar:managegroupentries', $event->context)
f63d2922 1481 && groups_is_member($event->groupid)));
438e4add 1482 } else if (!empty($event->courseid)) {
c0a2c361 1483 // if groupid is not set, but course is set,
1484 // it's definiely a course event
f4700b91 1485 return has_capability('moodle/calendar:manageentries', $event->context);
438e4add 1486 } else if (!empty($event->userid) && $event->userid == $USER->id) {
c0a2c361 1487 // if course is not set, but userid id set, it's a user event
f4700b91
RW
1488 return (has_capability('moodle/calendar:manageownentries', $event->context));
1489 } else if (!empty($event->userid)) {
1490 return (has_capability('moodle/calendar:manageentries', $event->context));
e295df44 1491 }
7423f116 1492 return false;
1493}
1494
797cedc7
SH
1495/**
1496 * Returns the default courses to display on the calendar when there isn't a specific
1497 * course to display.
1498 *
08b4a4e1 1499 * @return array $courses Array of courses to display
797cedc7
SH
1500 */
1501function calendar_get_default_courses() {
1502 global $CFG, $DB;
7423f116 1503
4f0c2d00 1504 if (!isloggedin()) {
2ef75eee 1505 return array();
1506 }
1507
7423f116 1508 $courses = array();
d083084a 1509 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
797cedc7 1510 list ($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
d083084a 1511 $sql = "SELECT c.* $select
797cedc7 1512 FROM {course} c
d083084a
ARN
1513 $join
1514 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1515 ";
797cedc7
SH
1516 $courses = $DB->get_records_sql($sql, null, 0, 20);
1517 foreach ($courses as $course) {
d083084a 1518 context_helper::preload_from_record($course);
86f092d2 1519 }
797cedc7 1520 return $courses;
95a89225 1521 }
e295df44 1522
df997f84 1523 $courses = enrol_get_my_courses();
37d87d11 1524
1525 return $courses;
7423f116 1526}
1527
08b4a4e1
RW
1528/**
1529 * Display calendar preference button
1530 *
1531 * @param stdClass $course course object
1532 * @return string return preference button in html
1533 */
797cedc7
SH
1534function calendar_preferences_button(stdClass $course) {
1535 global $OUTPUT;
7423f116 1536
1537 // Guests have no preferences
4f0c2d00 1538 if (!isloggedin() || isguestuser()) {
7423f116 1539 return '';
1540 }
1541
797cedc7 1542 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
7423f116 1543}
1544
08b4a4e1
RW
1545/**
1546 * Get event format time
1547 *
1548 * @param calendar_event $event event object
1549 * @param int $now current time in gmt
1550 * @param array $linkparams list of params for event link
1551 * @param bool $usecommonwords the words as formatted date/time.
1552 * @param int $showtime determine the show time GMT timestamp
1553 * @return string $eventtime link/string for event time
1554 */
0f927f1e 1555function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
8f896582 1556 $startdate = usergetdate($event->timestart);
1557 $enddate = usergetdate($event->timestart + $event->timeduration);
1558 $usermidnightstart = usergetmidnight($event->timestart);
1559
1560 if($event->timeduration) {
1561 // To avoid doing the math if one IF is enough :)
1562 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1563 }
1564 else {
1565 $usermidnightend = $usermidnightstart;
1566 }
1567
0f927f1e
SH
1568 if (empty($linkparams) || !is_array($linkparams)) {
1569 $linkparams = array();
1570 }
1571 $linkparams['view'] = 'day';
1572
8f896582 1573 // OK, now to get a meaningful display...
1574 // First of all we have to construct a human-readable date/time representation
1575
b4892fa2 1576 if($event->timeduration) {
8f896582 1577 // It has a duration
b4892fa2 1578 if($usermidnightstart == $usermidnightend ||
1579 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1580 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
8f896582 1581 // But it's all on the same day
8f896582 1582 $timestart = calendar_time_representation($event->timestart);
1583 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
b4892fa2 1584 $time = $timestart.' <strong>&raquo;</strong> '.$timeend;
1585
1586 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1587 $time = get_string('allday', 'calendar');
1588 }
8f896582 1589
1590 // Set printable representation
b4892fa2 1591 if (!$showtime) {
1592 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
0f927f1e
SH
1593 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1594 $eventtime = html_writer::link($url, $day).', '.$time;
b4892fa2 1595 } else {
1596 $eventtime = $time;
1597 }
1598 } else {
8f896582 1599 // It spans two or more days
b4892fa2 1600 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1601 if ($showtime == $usermidnightstart) {
1602 $daystart = '';
1603 }
8f896582 1604 $timestart = calendar_time_representation($event->timestart);
b4892fa2 1605 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1606 if ($showtime == $usermidnightend) {
1607 $dayend = '';
1608 }
8f896582 1609 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1610
1611 // Set printable representation
b4892fa2 1612 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
0f927f1e
SH
1613 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1614 $eventtime = $timestart.' <strong>&raquo;</strong> '.html_writer::link($url, $dayend).$timeend;
b4892fa2 1615 } else {
0f927f1e
SH
1616 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1617 $eventtime = html_writer::link($url, $daystart).$timestart.' <strong>&raquo;</strong> ';
1d5bd3d2 1618
0f927f1e
SH
1619 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1620 $eventtime .= html_writer::link($url, $dayend).$timeend;
b4892fa2 1621 }
8f896582 1622 }
b4892fa2 1623 } else {
2af268a1 1624 $time = calendar_time_representation($event->timestart);
8f896582 1625
1626 // Set printable representation
b4892fa2 1627 if (!$showtime) {
1628 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
0f927f1e 1629 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
2af268a1 1630 $eventtime = html_writer::link($url, $day).', '.trim($time);
b4892fa2 1631 } else {
1632 $eventtime = $time;
1633 }
1634 }
1635
1636 if($event->timestart + $event->timeduration < $now) {
1637 // It has expired
1638 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
8f896582 1639 }
09d36284 1640
8f896582 1641 return $eventtime;
1642}
054193be 1643
08b4a4e1
RW
1644/**
1645 * Display month selector options
1646 *
1647 * @param string $name for the select element
1648 * @param string|array $selected options for select elements
1649 */
86f092d2 1650function calendar_print_month_selector($name, $selected) {
86f092d2 1651 $months = array();
86f092d2 1652 for ($i=1; $i<=12; $i++) {
76ab1c33 1653 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
86f092d2 1654 }
5c576552 1655 echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
d776d59e 1656 echo html_writer::select($months, $name, $selected, false);
86f092d2 1657}
1658
797cedc7
SH
1659/**
1660 * Checks to see if the requested type of event should be shown for the given user.
1661 *
1662 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1663 * The type to check the display for (default is to display all)
1664 * @param stdClass|int|null $user The user to check for - by default the current user
1665 * @return bool True if the tyep should be displayed false otherwise
1666 */
1667function calendar_show_event_type($type, $user = null) {
1668 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1669 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1670 global $SESSION;
1671 if (!isset($SESSION->calendarshoweventtype)) {
1672 $SESSION->calendarshoweventtype = $default;
1673 }
1674 return $SESSION->calendarshoweventtype & $type;
1675 } else {
1676 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
054193be 1677 }
797cedc7
SH
1678}
1679
1680/**
1681 * Sets the display of the event type given $display.
08b4a4e1 1682 *
797cedc7
SH
1683 * If $display = true the event type will be shown.
1684 * If $display = false the event type will NOT be shown.
1685 * If $display = null the current value will be toggled and saved.
1686 *
08b4a4e1
RW
1687 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1688 * @param bool $display option to display event type
1689 * @param stdClass|int $user moodle user object or id, null means current user
797cedc7
SH
1690 */
1691function calendar_set_event_type_display($type, $display = null, $user = null) {
1692 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1693 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1694 if ($persist === 0) {
1695 global $SESSION;
1696 if (!isset($SESSION->calendarshoweventtype)) {
1697 $SESSION->calendarshoweventtype = $default;
1698 }
1699 $preference = $SESSION->calendarshoweventtype;
1700 } else {
1701 $preference = get_user_preferences('calendar_savedflt', $default, $user);
054193be 1702 }
797cedc7
SH
1703 $current = $preference & $type;
1704 if ($display === null) {
1705 $display = !$current;
054193be 1706 }
797cedc7
SH
1707 if ($display && !$current) {
1708 $preference += $type;
1709 } else if (!$display && $current) {
1710 $preference -= $type;
054193be 1711 }
797cedc7
SH
1712 if ($persist === 0) {
1713 $SESSION->calendarshoweventtype = $preference;
1714 } else {
1715 if ($preference == $default) {
1716 unset_user_preference('calendar_savedflt', $user);
1717 } else {
1718 set_user_preference('calendar_savedflt', $preference, $user);
1719 }
054193be 1720 }
054193be 1721}
1722
08b4a4e1
RW
1723/**
1724 * Get calendar's allowed types
1725 *
1726 * @param stdClass $allowed list of allowed edit for event type
1727 * @param stdClass|int $course object of a course or course id
1728 */
797cedc7
SH
1729function calendar_get_allowed_types(&$allowed, $course = null) {
1730 global $USER, $CFG, $DB;
b85b25eb 1731 $allowed = new stdClass();
797cedc7 1732 $allowed->user = has_capability('moodle/calendar:manageownentries', get_system_context());
86ac8b24 1733 $allowed->groups = false; // This may change just below
1734 $allowed->courses = false; // This may change just below
6ca657a7 1735 $allowed->site = has_capability('moodle/calendar:manageentries', context_course::instance(SITEID));
86ac8b24 1736
797cedc7
SH
1737 if (!empty($course)) {
1738 if (!is_object($course)) {
1739 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
1740 }
1741 if ($course->id != SITEID) {
6ca657a7 1742 $coursecontext = context_course::instance($course->id);
3c0ea9b2 1743 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
86ac8b24 1744
797cedc7
SH
1745 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1746 $allowed->courses = array($course->id => 1);
aa6c1ced 1747
797cedc7
SH
1748 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1749 $allowed->groups = groups_get_all_groups($course->id);
1750 }
1751 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1752 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1753 $allowed->groups = groups_get_all_groups($course->id);
1754 }
f63d2922 1755 }
86ac8b24 1756 }
1757 }
1758}
1759
1760/**
08b4a4e1 1761 * See if user can add calendar entries at all
86ac8b24 1762 * used to print the "New Event" button
08b4a4e1
RW
1763 *
1764 * @param stdClass $course object of a course or course id
1765 * @return bool has the capability to add at least one event type
86ac8b24 1766 */
797cedc7
SH
1767function calendar_user_can_add_event($course) {
1768 if (!isloggedin() || isguestuser()) {
1769 return false;
1770 }
1771 calendar_get_allowed_types($allowed, $course);
e295df44 1772 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
86ac8b24 1773}
76d9df3f
SH
1774
1775/**
1776 * Check wether the current user is permitted to add events
1777 *
08b4a4e1
RW
1778 * @param stdClass $event object of event
1779 * @return bool has the capability to add event
76d9df3f
SH
1780 */
1781function calendar_add_event_allowed($event) {
1782 global $USER, $DB;
1783
1784 // can not be using guest account
4f0c2d00 1785 if (!isloggedin() or isguestuser()) {
76d9df3f
SH
1786 return false;
1787 }
1788
6ca657a7 1789 $sitecontext = context_system::instance();
76d9df3f
SH
1790 // if user has manageentries at site level, always return true
1791 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1792 return true;
1793 }
1794
1795 switch ($event->eventtype) {
1796 case 'course':
f4700b91 1797 return has_capability('moodle/calendar:manageentries', $event->context);
76d9df3f
SH
1798
1799 case 'group':
1800 // Allow users to add/edit group events if:
1801 // 1) They have manageentries (= entries for whole course)
1802 // 2) They have managegroupentries AND are in the group
1803 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1804 return $group && (
f4700b91
RW
1805 has_capability('moodle/calendar:manageentries', $event->context) ||
1806 (has_capability('moodle/calendar:managegroupentries', $event->context)
76d9df3f
SH
1807 && groups_is_member($event->groupid)));
1808
1809 case 'user':
1810 if ($event->userid == $USER->id) {
f4700b91 1811 return (has_capability('moodle/calendar:manageownentries', $event->context));
76d9df3f
SH
1812 }
1813 //there is no 'break;' intentionally
1814
1815 case 'site':
f4700b91 1816 return has_capability('moodle/calendar:manageentries', $event->context);
76d9df3f
SH
1817
1818 default:
f4700b91 1819 return has_capability('moodle/calendar:manageentries', $event->context);
76d9df3f
SH
1820 }
1821}
1822
1823/**
08b4a4e1 1824 * Manage calendar events
76d9df3f
SH
1825 *
1826 * This class provides the required functionality in order to manage calendar events.
1827 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1828 * better framework for dealing with calendar events in particular regard to file
1829 * handling through the new file API
1830 *
08b4a4e1
RW
1831 * @package core_calendar
1832 * @category calendar
1833 * @copyright 2009 Sam Hemelryk
1834 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1835 *
76d9df3f
SH
1836 * @property int $id The id within the event table
1837 * @property string $name The name of the event
1838 * @property string $description The description of the event
1839 * @property int $format The format of the description FORMAT_?
1840 * @property int $courseid The course the event is associated with (0 if none)
1841 * @property int $groupid The group the event is associated with (0 if none)
1842 * @property int $userid The user the event is associated with (0 if none)
1843 * @property int $repeatid If this is a repeated event this will be set to the
1844 * id of the original
1845 * @property string $modulename If added by a module this will be the module name
1846 * @property int $instance If added by a module this will be the module instance
1847 * @property string $eventtype The event type
1848 * @property int $timestart The start time as a timestamp
1849 * @property int $timeduration The duration of the event in seconds
1850 * @property int $visible 1 if the event is visible
1851 * @property int $uuid ?
1852 * @property int $sequence ?
1853 * @property int $timemodified The time last modified as a timestamp
1854 */
1855class calendar_event {
1856
08b4a4e1 1857 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
76d9df3f 1858 protected $properties = null;
08b4a4e1 1859
76d9df3f 1860 /**
08b4a4e1 1861 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
76d9df3f 1862 protected $_description = null;
08b4a4e1
RW
1863
1864 /** @var array The options to use with this description editor */
76d9df3f
SH
1865 protected $editoroptions = array(
1866 'subdirs'=>false,
1867 'forcehttps'=>false,
2b35ed1a 1868 'maxfiles'=>-1,
76d9df3f
SH
1869 'maxbytes'=>null,
1870 'trusttext'=>false);
08b4a4e1
RW
1871
1872 /** @var object The context to use with the description editor */
76d9df3f
SH
1873 protected $editorcontext = null;
1874
1875 /**
1876 * Instantiates a new event and optionally populates its properties with the
1877 * data provided
1878 *
1879 * @param stdClass $data Optional. An object containing the properties to for
1880 * an event
1881 */
1882 public function __construct($data=null) {
c203a277 1883 global $CFG, $USER;
76d9df3f
SH
1884
1885 // First convert to object if it is not already (should either be object or assoc array)
1886 if (!is_object($data)) {
1887 $data = (object)$data;
1888 }
1889
1890 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1891
1892 $data->eventrepeats = 0;
1893
1894 if (empty($data->id)) {
1895 $data->id = null;
1896 }
1897
c203a277
SH
1898 // Default to a user event
1899 if (empty($data->eventtype)) {
1900 $data->eventtype = 'user';
1901 }
1902
1903 // Default to the current user
1904 if (empty($data->userid)) {
1905 $data->userid = $USER->id;
1906 }
1907
76d9df3f
SH
1908 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1909 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1910 }
1911 if (!empty($data->description) && is_array($data->description)) {
1912 $data->format = $data->description['format'];
1913 $data->description = $data->description['text'];
1914 } else if (empty($data->description)) {
1915 $data->description = '';
20e5da7d 1916 $data->format = editors_get_preferred_format();
76d9df3f 1917 }
c203a277
SH
1918 // Ensure form is defaulted correctly
1919 if (empty($data->format)) {
1920 $data->format = editors_get_preferred_format();
1921 }
76d9df3f 1922
f4700b91
RW
1923 if (empty($data->context)) {
1924 $data->context = $this->calculate_context($data);
1925 }
76d9df3f
SH
1926 $this->properties = $data;
1927 }
1928
1929 /**
1930 * Magic property method
1931 *
1932 * Attempts to call a set_$key method if one exists otherwise falls back
1933 * to simply set the property
1934 *
08b4a4e1
RW
1935 * @param string $key property name
1936 * @param mixed $value value of the property
76d9df3f
SH
1937 */
1938 public function __set($key, $value) {
1939 if (method_exists($this, 'set_'.$key)) {
1940 $this->{'set_'.$key}($value);
1941 }
1942 $this->properties->{$key} = $value;
1943 }
1944
1945 /**
1946 * Magic get method
1947 *
1948 * Attempts to call a get_$key method to return the property and ralls over
1949 * to return the raw property
1950 *
08b4a4e1
RW
1951 * @param string $key property name
1952 * @return mixed property value
76d9df3f
SH
1953 */
1954 public function __get($key) {
1955 if (method_exists($this, 'get_'.$key)) {
1956 return $this->{'get_'.$key}();
1957 }
c203a277
SH
1958 if (!isset($this->properties->{$key})) {
1959 throw new coding_exception('Undefined property requested');
1960 }
76d9df3f
SH
1961 return $this->properties->{$key};
1962 }
1963
1964 /**
1965 * Stupid PHP needs an isset magic method if you use the get magic method and
1966 * still want empty calls to work.... blah ~!
1967 *
08b4a4e1
RW
1968 * @param string $key $key property name
1969 * @return bool|mixed property value, false if property is not exist
76d9df3f
SH
1970 */
1971 public function __isset($key) {
1972 return !empty($this->properties->{$key});
1973 }
1974
f4700b91
RW
1975 /**
1976 * Calculate the context value needed for calendar_event.
1977 * Event's type can be determine by the available value store in $data
1978 * It is important to check for the existence of course/courseid to determine
1979 * the course event.
1980 * Default value is set to CONTEXT_USER
1981 *
08b4a4e1
RW
1982 * @param stdClass $data information about event
1983 * @return stdClass The context object.
f4700b91
RW
1984 */
1985 protected function calculate_context(stdClass $data) {
025d82e0 1986 global $USER, $DB;
f4700b91 1987
f4700b91
RW
1988 $context = null;
1989 if (isset($data->courseid) && $data->courseid > 0) {
6ca657a7 1990 $context = context_course::instance($data->courseid);
f4700b91 1991 } else if (isset($data->course) && $data->course > 0) {
6ca657a7 1992 $context = context_course::instance($data->course);
f4700b91
RW
1993 } else if (isset($data->groupid) && $data->groupid > 0) {
1994 $group = $DB->get_record('groups', array('id'=>$data->groupid));
6ca657a7 1995 $context = context_course::instance($group->courseid);
f4700b91 1996 } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
6ca657a7 1997 $context = context_user::instance($data->userid);
f4700b91
RW
1998 } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
1999 isset($data->instance) && $data->instance > 0) {
18d63ffb 2000 $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
6ca657a7 2001 $context = context_course::instance($cm->course);
f4700b91 2002 } else {
6ca657a7 2003 $context = context_user::instance();
f4700b91
RW
2004 }
2005
2006 return $context;
2007 }
2008
76d9df3f
SH
2009 /**
2010 * Returns an array of editoroptions for this event: Called by __get
2011 * Please use $blah = $event->editoroptions;
08b4a4e1
RW
2012 *
2013 * @return array event editor options
76d9df3f
SH
2014 */
2015 protected function get_editoroptions() {
2016 return $this->editoroptions;
2017 }
2018
2019 /**
2020 * Returns an event description: Called by __get
2021 * Please use $blah = $event->description;
2022 *
08b4a4e1 2023 * @return string event description
76d9df3f
SH
2024 */
2025 protected function get_description() {
f4700b91 2026 global $CFG;
99d19c13
PS
2027
2028 require_once($CFG->libdir . '/filelib.php');
2029
76d9df3f
SH
2030 if ($this->_description === null) {
2031 // Check if we have already resolved the context for this event
2032 if ($this->editorcontext === null) {
2033 // Switch on the event type to decide upon the appropriate context
2034 // to use for this event
f4700b91
RW
2035 $this->editorcontext = $this->properties->context;
2036 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
2037 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
2038 return clean_text($this->properties->description, $this->properties->format);
76d9df3f
SH
2039 }
2040 }
2041
2042 // Work out the item id for the editor, if this is a repeated event then the files will
2043 // be associated with the original
2044 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2045 $itemid = $this->properties->repeatid;
2046 } else {
2047 $itemid = $this->properties->id;
2048 }
2049
2050 // Convert file paths in the description so that things display correctly
64f93798 2051 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
76d9df3f
SH
2052 // Clean the text so no nasties get through
2053 $this->_description = clean_text($this->_description, $this->properties->format);
2054 }
2055 // Finally return the description
2056 return $this->_description;
2057 }
2058
2059 /**
2060 * Return the number of repeat events there are in this events series
aa6c1ced 2061 *
08b4a4e1 2062 * @return int number of event repeated
76d9df3f
SH
2063 */
2064 public function count_repeats() {
2065 global $DB;
2066 if (!empty($this->properties->repeatid)) {
2067 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
2068 // We don't want to count ourselves
2069 $this->properties->eventrepeats--;
2070 }
2071 return $this->properties->eventrepeats;
2072 }
2073
2074 /**
2075 * Update or create an event within the database
2076 *
2077 * Pass in a object containing the event properties and this function will
2078 * insert it into the database and deal with any associated files
2079 *
2080 * @see add_event()
2081 * @see update_event()
2082 *
08b4a4e1
RW
2083 * @param stdClass $data object of event
2084 * @param bool $checkcapability if moodle should check calendar managing capability or not
2085 * @return bool event updated
76d9df3f 2086 */
1d5bd3d2 2087 public function update($data, $checkcapability=true) {
76d9df3f
SH
2088 global $CFG, $DB, $USER;
2089
438e4add
SH
2090 foreach ($data as $key=>$value) {
2091 $this->properties->$key = $value;
2092 }
2093
76d9df3f
SH
2094 $this->properties->timemodified = time();
2095 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
2096
2097 if (empty($this->properties->id) || $this->properties->id < 1) {
2098
1d5bd3d2
DC
2099 if ($checkcapability) {
2100 if (!calendar_add_event_allowed($this->properties)) {
2101 print_error('nopermissiontoupdatecalendar');
2102 }
76d9df3f
SH
2103 }
2104
2105 if ($usingeditor) {
2106 switch ($this->properties->eventtype) {
2107 case 'user':
f4700b91 2108 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2109 $this->properties->courseid = 0;
2110 $this->properties->groupid = 0;
2111 $this->properties->userid = $USER->id;
2112 break;
2113 case 'site':
f4700b91 2114 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2115 $this->properties->courseid = SITEID;
2116 $this->properties->groupid = 0;
2117 $this->properties->userid = $USER->id;
2118 break;
2119 case 'course':
f4700b91 2120 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2121 $this->properties->groupid = 0;
2122 $this->properties->userid = $USER->id;
2123 break;
2124 case 'group':
f4700b91 2125 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2126 $this->properties->userid = $USER->id;
2127 break;
2128 default:
2129 // Ewww we should NEVER get here, but just incase we do lets
2130 // fail gracefully
2131 $usingeditor = false;
2132 break;
2133 }
2134
2135 $editor = $this->properties->description;
2136 $this->properties->format = $this->properties->description['format'];
2137 $this->properties->description = $this->properties->description['text'];
2138 }
2139
2140 // Insert the event into the database
2141 $this->properties->id = $DB->insert_record('event', $this->properties);
2142
2143 if ($usingeditor) {
2144 $this->properties->description = file_save_draft_area_files(
2145 $editor['itemid'],
2146 $this->editorcontext->id,
64f93798
PS
2147 'calendar',
2148 'event_description',
76d9df3f
SH
2149 $this->properties->id,
2150 $this->editoroptions,
2151 $editor['text'],
2152 $this->editoroptions['forcehttps']);
2153
2154 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2155 }
aa6c1ced 2156
76d9df3f
SH
2157 // Log the event entry.
2158 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2159
2160 $repeatedids = array();
2161
2162 if (!empty($this->properties->repeat)) {
2163 $this->properties->repeatid = $this->properties->id;
2164 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
2165
2166 $eventcopy = clone($this->properties);
2167 unset($eventcopy->id);
2168
2169 for($i = 1; $i < $eventcopy->repeats; $i++) {
2170
2171 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
2172
2173 // Get the event id for the log record.
2174 $eventcopyid = $DB->insert_record('event', $eventcopy);
2175
2176 // If the context has been set delete all associated files
2177 if ($usingeditor) {
2178 $fs = get_file_storage();
64f93798 2179 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
76d9df3f
SH
2180 foreach ($files as $file) {
2181 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2182 }
2183 }
2184
2185 $repeatedids[] = $eventcopyid;
2186 // Log the event entry.
2187 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
2188 }
2189 }
2190
2191 // Hook for tracking added events
2192 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2193 return true;
2194 } else {
2195
1d5bd3d2
DC
2196 if ($checkcapability) {
2197 if(!calendar_edit_event_allowed($this->properties)) {
2198 print_error('nopermissiontoupdatecalendar');
2199 }
76d9df3f
SH
2200 }
2201
2202 if ($usingeditor) {
2203 if ($this->editorcontext !== null) {
2204 $this->properties->description = file_save_draft_area_files(
2205 $this->properties->description['itemid'],
2206 $this->editorcontext->id,
64f93798
PS
2207 'calendar',
2208 'event_description',
76d9df3f
SH
2209 $this->properties->id,
2210 $this->editoroptions,
2211 $this->properties->description['text'],
2212 $this->editoroptions['forcehttps']);
2213 } else {
2214 $this->properties->format = $this->properties->description['format'];
2215 $this->properties->description = $this->properties->description['text'];
2216 }
2217 }
2218
2219 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2220
2221 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2222
2223 if ($updaterepeated) {
2224 // Update all
2225 if ($this->properties->timestart != $event->timestart) {
2226 $timestartoffset = $this->properties->timestart - $event->timestart;
2227 $sql = "UPDATE {event}
2228 SET name = ?,
2229 description = ?,
2230 timestart = timestart + ?,
2231 timeduration = ?,
2232 timemodified = ?
2233 WHERE repeatid = ?";
2234 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2235 } else {
2236 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2237 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2238 }
2239 $DB->execute($sql, $params);
2240
2241 // Log the event update.
2242 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2243 } else {
2244 $DB->update_record('event', $this->properties);
ddaff608
SH
2245 $event = calendar_event::load($this->properties->id);
2246 $this->properties = $event->properties();
76d9df3f
SH
2247 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2248 }
2249
2250 // Hook for tracking event updates
2251 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2252 return true;
2253 }
2254 }
2255
2256 /**
2257 * Deletes an event and if selected an repeated events in the same series
2258 *
2259 * This function deletes an event, any associated events if $deleterepeated=true,
2260 * and cleans up any files associated with the events.
2261 *
2262 * @see delete_event()
2263 *
08b4a4e1
RW
2264 * @param bool $deleterepeated delete event repeatedly
2265 * @return bool succession of deleting event
76d9df3f
SH
2266 */
2267 public function delete($deleterepeated=false) {
f4700b91 2268 global $DB;
76d9df3f
SH
2269
2270 // If $this->properties->id is not set then something is wrong
2271 if (empty($this->properties->id)) {
2272 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2273 return false;
2274 }
2275
2276 // Delete the event
2277 $DB->delete_records('event', array('id'=>$this->properties->id));
2278
ff284fac
AA
2279 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2280 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
2281 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties->id), IGNORE_MULTIPLE);
2282 if (!empty($newparent)) {
2283 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties->id));
5ff114ad
AA
2284 // Get all records where the repeatid is the same as the event being removed
2285 $events = $DB->get_records('event', array('repeatid' => $newparent));
2286 // For each of the returned events trigger the event_update hook.
2287 foreach ($events as $event) {
2288 self::calendar_event_hook('update_event', array($event, false));
2289 }
ff284fac
AA
2290 }
2291 }
2292
76d9df3f
SH
2293 // If the editor context hasn't already been set then set it now
2294 if ($this->editorcontext === null) {
f4700b91 2295 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2296 }
2297
2298 // If the context has been set delete all associated files
2299 if ($this->editorcontext !== null) {
2300 $fs = get_file_storage();
64f93798 2301 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
76d9df3f
SH
2302 foreach ($files as $file) {
2303 $file->delete();
2304 }
2305 }
2306
2307 // Fire the event deleted hook
2308 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2309
2310 // If we need to delete repeated events then we will fetch them all and delete one by one
2311 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2312 // Get all records where the repeatid is the same as the event being removed
2313 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2314 // For each of the returned events populate a calendar_event object and call delete
2315 // make sure the arg passed is false as we are already deleting all repeats
2316 foreach ($events as $event) {
2317 $event = new calendar_event($event);
2318 $event->delete(false);
2319 }
2320 }
2321
2322 return true;
2323 }
2324
2325 /**
2326 * Fetch all event properties
2327 *
2328 * This function returns all of the events properties as an object and optionally
2329 * can prepare an editor for the description field at the same time. This is
2330 * designed to work when the properties are going to be used to set the default
2331 * values of a moodle forms form.
2332 *
2333 * @param bool $prepareeditor If set to true a editor is prepared for use with
2334 * the mforms editor element. (for description)
2335 * @return stdClass Object containing event properties
2336 */
2337 public function properties($prepareeditor=false) {
2338 global $USER, $CFG, $DB;
2339
2340 // First take a copy of the properties. We don't want to actually change the
2341 // properties or we'd forever be converting back and forwards between an
2342 // editor formatted description and not
2343 $properties = clone($this->properties);
2344 // Clean the description here
2345 $properties->description = clean_text($properties->description, $properties->format);
2346
2347 // If set to true we need to prepare the properties for use with an editor
2348 // and prepare the file area
2349 if ($prepareeditor) {
2350
2351 // We may or may not have a property id. If we do then we need to work
2352 // out the context so we can copy the existing files to the draft area
2353 if (!empty($properties->id)) {
2354
2355 if ($properties->eventtype === 'site') {
2356 // Site context
f4700b91 2357 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2358 } else if ($properties->eventtype === 'user') {
2359 // User context
f4700b91 2360 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2361 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2362 // First check the course is valid
2363 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2364 if (!$course) {
2365 print_error('invalidcourse');
2366 }
2367 // Course context
f4700b91 2368 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2369 // We have a course and are within the course context so we had
2370 // better use the courses max bytes value
2371 $this->editoroptions['maxbytes'] = $course->maxbytes;
2372 } else {
2373 // If we get here we have a custom event type as used by some
2374 // modules. In this case the event will have been added by
2375 // code and we won't need the editor
2376 $this->editoroptions['maxbytes'] = 0;
2377 $this->editoroptions['maxfiles'] = 0;
2378 }
2379
2380 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2381 $contextid = false;
2382 } else {
2383 // Get the context id that is what we really want
2384 $contextid = $this->editorcontext->id;
2385 }
2386 } else {
2387
2388 // If we get here then this is a new event in which case we don't need a
2389 // context as there is no existing files to copy to the draft area.
2390 $contextid = null;
2391 }
2392
2393 // If the contextid === false we don't support files so no preparing
2394 // a draft area
2395 if ($contextid !== false) {
2396 // Just encase it has already been submitted
2397 $draftiddescription = file_get_submitted_draft_itemid('description');
2398 // Prepare the draft area, this copies existing files to the draft area as well
64f93798 2399 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
76d9df3f
SH
2400 } else {
2401 $draftiddescription = 0;
2402 }
aa6c1ced 2403
76d9df3f
SH
2404 // Structure the description field as the editor requires
2405 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2406 }
2407
2408 // Finally return the properties
2409 return $properties;
2410 }
2411
2412 /**
2413 * Toggles the visibility of an event
2414 *
2415 * @param null|bool $force If it is left null the events visibility is flipped,
2416 * If it is false the event is made hidden, if it is true it
2417 * is made visible.
08b4a4e1 2418 * @return bool if event is successfully updated, toggle will be visible
76d9df3f
SH
2419 */
2420 public function toggle_visibility($force=null) {
2421 global $CFG, $DB;
2422
2423 // Set visible to the default if it is not already set
2424 if (empty($this->properties->visible)) {
2425 $this->properties->visible = 1;
2426 }
2427
2428 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2429 // Make this event visible
2430 $this->properties->visible = 1;
2431 // Fire the hook
2432 self::calendar_event_hook('show_event', array($this->properties));
2433 } else {
2434 // Make this event hidden
2435 $this->properties->visible = 0;
2436 // Fire the hook
2437 self::calendar_event_hook('hide_event', array($this->properties));
2438 }
2439
2440 // Update the database to reflect this change
2441 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2442 }
2443
2444 /**
2445 * Attempts to call the hook for the specified action should a calendar type
2446 * by set $CFG->calendar, and the appopriate function defined
2447 *
76d9df3f
SH
2448 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2449 * @param array $args The args to pass to the hook, usually the event is the first element
08b4a4e1 2450 * @return bool attempts to call event hook
76d9df3f
SH
2451 */
2452 public static function calendar_event_hook($action, array $args) {
2453 global $CFG;
2454 static $extcalendarinc;
2455 if ($extcalendarinc === null) {
d2b46849
BJ
2456 if (!empty($CFG->calendar)) {
2457 if (is_readable($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2458 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2459 $extcalendarinc = true;
2460 } else {
2461 debugging("Calendar lib file missing or not readable at /calendar/{$CFG->calendar}/lib.php.",
2462 DEBUG_DEVELOPER);
2463 $extcalendarinc = false;
2464 }
76d9df3f
SH
2465 } else {
2466 $extcalendarinc = false;
2467 }
2468 }
2469 if($extcalendarinc === false) {
2470 return false;
2471 }
438e4add 2472 $hook = $CFG->calendar .'_'.$action;
76d9df3f
SH
2473 if (function_exists($hook)) {
2474 call_user_func_array($hook, $args);
2475 return true;
2476 }
2477 return false;
2478 }
2479
2480 /**
2481 * Returns a calendar_event object when provided with an event id
2482 *
2483 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2484 * it will result in an exception being thrown
2485 *
08b4a4e1
RW
2486 * @param int|object $param event object or event id
2487 * @return calendar_event|false status for loading calendar_event
76d9df3f 2488 */
fd699564 2489 public static function load($param) {
76d9df3f 2490 global $DB;
fd699564
SH
2491 if (is_object($param)) {
2492 $event = new calendar_event($param);
2493 } else {
2494 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2495 $event = new calendar_event($event);
2496 }
76d9df3f
SH
2497 return $event;
2498 }
2499
2500 /**
2501 * Creates a new event and returns a calendar_event object
2502 *
2503 * @param object|array $properties An object containing event properties
2504 * @return calendar_event|false The event object or false if it failed
2505 */
2506 public static function create($properties) {
2507 if (is_array($properties)) {
2508 $properties = (object)$properties;
2509 }
2510 if (!is_object($properties)) {
2511 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2512 }
f4700b91 2513 $event = new calendar_event($properties);
76d9df3f
SH
2514 if ($event->update($properties)) {
2515 return $event;
2516 } else {
2517 return false;
2518 }
2519 }
2520}
36dc3b71
SH
2521
2522/**
2523 * Calendar information class
2524 *
2525 * This class is used simply to organise the information pertaining to a calendar
2526 * and is used primarily to make information easily available.
08b4a4e1
RW
2527 *
2528 * @package core_calendar
2529 * @category calendar
2530 * @copyright 2010 Sam Hemelryk
2531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36dc3b71
SH
2532 */
2533class calendar_information {
08b4a4e1 2534 /** @var int The day */
36dc3b71 2535 public $day;
08b4a4e1
RW
2536
2537 /** @var int The month */
36dc3b71 2538 public $month;
08b4a4e1
RW
2539
2540 /** @var int The year */
36dc3b71
SH
2541 public $year;
2542
08b4a4e1 2543 /** @var int A course id */
36dc3b71 2544 public $courseid = null;
08b4a4e1
RW
2545
2546 /** @var array An array of courses */
36dc3b71 2547 public $courses = array();
08b4a4e1
RW
2548
2549 /** @var array An array of groups */
36dc3b71 2550 public $groups = array();
08b4a4e1
RW
2551
2552 /** @var array An array of users */
36dc3b71
SH
2553 public $users = array();
2554
2555 /**
2556 * Creates a new instance
2557 *
08b4a4e1
RW
2558 * @param int $day the number of the day
2559 * @param int $month the number of the month
2560 * @param int $year the number of the year
36dc3b71 2561 */
d8d8bdd9
SH
2562 public function __construct($day=0, $month=0, $year=0) {
2563
2564 $date = usergetdate(time());
2565
2566 if (empty($day)) {
2567 $day = $date['mday'];
2568 }
2569
2570 if (empty($month)) {
2571 $month = $date['mon'];
2572 }
2573
2574 if (empty($year)) {
2575 $year = $date['year'];
2576 }
2577
36dc3b71
SH
2578 $this->day = $day;
2579 $this->month = $month;
2580 $this->year = $year;
2581 }
2582
797cedc7 2583 /**
08b4a4e1 2584 * Initialize calendar information
797cedc7 2585 *
08b4a4e1 2586 * @param stdClass $course object
797cedc7 2587 * @param array $coursestoload An array of courses [$course->id => $course]
08b4a4e1 2588 * @param bool $ignorefilters options to use filter
797cedc7
SH
2589 */
2590 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
2591 $this->courseid = $course->id;
2592 $this->course = $course;
2593 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2594 $this->courses = $courses;
2595 $this->groups = $group;
2596 $this->users = $user;
2597 }
2598
36dc3b71
SH
2599 /**
2600 * Ensures the date for the calendar is correct and either sets it to now
2601 * or throws a moodle_exception if not
2602 *
08b4a4e1
RW
2603 * @param bool $defaultonow use current time
2604 * @throws moodle_exception
2605 * @return bool validation of checkdate
36dc3b71
SH
2606 */
2607 public function checkdate($defaultonow = true) {
2608 if (!checkdate($this->month, $this->day, $this->year)) {
2609 if ($defaultonow) {
2610 $now = usergetdate(time());
2611 $this->day = intval($now['mday']);
2612 $this->month = intval($now['mon']);
2613 $this->year = intval($now['year']);
2614 return true;
2615 } else {
2616 throw new moodle_exception('invaliddate');
2617 }
2618 }
2619 return true;
2620 }
2621 /**
2622 * Gets todays timestamp for the calendar
08b4a4e1
RW
2623 *
2624 * @return int today timestamp
36dc3b71
SH
2625 */
2626 public function timestamp_today() {
2627 return make_timestamp($this->year, $this->month, $this->day);
2628 }
2629 /**
2630 * Gets tomorrows timestamp for the calendar
08b4a4e1
RW
2631 *
2632 * @return int tomorrow timestamp
36dc3b71
SH
2633 */
2634 public function timestamp_tomorrow() {
2635 return make_timestamp($this->year, $this->month, $this->day+1);
2636 }
2637 /**
2638 * Adds the pretend blocks for teh calendar
2639 *
2640 * @param core_calendar_renderer $renderer
08b4a4e1
RW
2641 * @param bool $showfilters display filters, false is set as default
2642 * @param string|null $view preference view options (eg: day, month, upcoming)
36dc3b71
SH
2643 */
2644 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2645 if ($showfilters) {
2646 $filters = new block_contents();
2647 $filters->content = $renderer->fake_block_filters($this->courseid, $this->day, $this->month, $this->year, $view, $this->courses);
2648 $filters->footer = '';
2649 $filters->title = get_string('eventskey', 'calendar');
2650 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2651 }
2652 $block = new block_contents;
2653 $block->content = $renderer->fake_block_threemonths($this);
2654 $block->footer = '';
2655 $block->title = get_string('monthlyview', 'calendar');
2656 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
2657 }
1d5bd3d2 2658}
b5a52acd
JH
2659
2660/**
2661 * Returns option list for the pollinterval setting.
4c349ad7 2662 * @return array option list
b5a52acd
JH
2663 */
2664function calendar_get_pollinterval_choices() {
2665 return array(
2666 '0' => get_string('never', 'calendar'),
2667 '3600' => get_string('hourly', 'calendar'),
2668 '86400' => get_string('daily', 'calendar'),
2669 '604800' => get_string('weekly', 'calendar'),
2670 '2628000' => get_string('monthly', 'calendar'),
2671 '31536000' => get_string('annually', 'calendar'),
2672 );
2673}
2674
2675/**
4c349ad7
JH
2676 * Returns option list of available options for the calendar event type, given
2677 * the current user and course.
2678 * @param int $courseid The id of the course
2679 * @return array option list
b5a52acd
JH
2680 */
2681function calendar_get_eventtype_choices($courseid) {
2682 $choices = array();
2683 $allowed = new stdClass;
2684 calendar_get_allowed_types($allowed, $courseid);
2685
2686 if ($allowed->user) {
2687 $choices[0] = get_string('userevents', 'calendar');
2688 }
2689 if ($allowed->site) {
4c349ad7 2690 $choices[SITEID] = get_string('globalevents', 'calendar');
b5a52acd
JH
2691 }
2692 if (!empty($allowed->courses)) {
2693 $choices[$courseid] = get_string('courseevents', 'calendar');
2694 }
2695 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2696 $choices['group'] = get_string('group');
2697 }
2698
2699 return array($choices, $allowed->groups);
2700}
2701
2702/**
2703 * Form for adding a subscription to a Moodle course calendar.
2704 */
2705class calendar_addsubscription_form extends moodleform {
2706
2707 function definition() {
2708 $mform =& $this->_form;
2709 $courseid = optional_param('course', 0, PARAM_INT);
2710
2711 // code to show/hide the form from the heading
2712 $mform->addElement('html', '<script type="text/javascript"><!--
2713 function showhide_subform() {
2714 divs = document.getElementById("addsubscriptionform").getElementsByTagName("div");
2715 for (var i = 0; i < divs.length; ++i) {
2716 if (divs[i].style.display=="none") {
2717 divs[i].style.display = "block";
2718 } else {
2719 divs[i].style.display = "none";
2720 }
2721 }
2722 }
2723 //--></script>');
4c349ad7 2724 $mform->addElement('header', 'addsubscriptionform', '<a name="targetsubcriptionform" onclick="showhide_subform()">'.get_string('importcalendarheading', 'calendar').'</a>');
b5a52acd
JH
2725
2726 $mform->addElement('text', 'name', get_string('subscriptionname', 'calendar'), 'maxlength="255" size="40"');
2727 $mform->addRule('name', get_string('required'), 'required');
2728
4c349ad7 2729 $mform->addElement('html', get_string('importfrominstructions', 'calendar'));
b5a52acd
JH
2730 $choices = array(CALENDAR_IMPORT_FROM_FILE => get_string('importfromfile', 'calendar'),
2731 CALENDAR_IMPORT_FROM_URL => get_string('importfromurl', 'calendar'));
2732 $mform->addElement('select', 'importfrom', get_string('importcalendarfrom', 'calendar'), $choices);
2733 $mform->setDefault('importfrom', CALENDAR_IMPORT_FROM_URL);
2734
2735 $mform->addElement('text', 'url', get_string('importfromurl', 'calendar'), 'maxlength="255" size="50"');
2736 $mform->addElement('filepicker', 'importfile', get_string('importfromfile', 'calendar'));
2737
2738 $mform->disabledIf('url', 'importfrom', 'eq', CALENDAR_IMPORT_FROM_FILE);
2739 $mform->disabledIf('importfile', 'importfrom', 'eq', CALENDAR_IMPORT_FROM_URL);
2740
2741 $choices = calendar_get_pollinterval_choices();
2742 $mform->addElement('select', 'pollinterval', get_string('pollinterval', 'calendar'), $choices);
2743
2744 $mform->setDefault('pollinterval', 604800);
2745 $mform->addHelpButton('pollinterval', 'pollinterval', 'calendar');
2746
2747 // eventtype: 0 = user, 1 = global, anything else = course ID
2748 list($choices, $groups) = calendar_get_eventtype_choices($courseid);
2749 $mform->addElement('select', 'eventtype', get_string('eventkind', 'calendar'), $choices);
2750 $mform->addRule('eventtype', get_string('required'), 'required');
2751
2752 if (!empty($groups) and is_array($groups)) {
2753 $groupoptions = array();
2754 foreach ($groups as $group) {
2755 $groupoptions[$group->id] = $group->name;
2756 }
2757 $mform->addElement('select', 'groupid', get_string('typegroup', 'calendar'), $groupoptions);
2758 $mform->disabledIf('groupid', 'eventtype', 'noteq', 'group');
2759 }
2760
2761 $mform->addElement('hidden', 'course', optional_param('course', 0, PARAM_INT));
2762 $mform->addElement('hidden', 'view', optional_param('view', 'upcoming', PARAM_ALPHA));
2763 $mform->addElement('hidden', 'cal_d', optional_param('cal_d', 0, PARAM_INT));
2764 $mform->addElement('hidden', 'cal_m', optional_param('cal_m', 0, PARAM_INT));
2765 $mform->addElement('hidden', 'cal_y', optional_param('cal_y', 0, PARAM_INT));
2766 $mform->addElement('hidden', 'id', optional_param('id', 0, PARAM_INT));
2767
2768 $mform->addElement('submit', 'add', get_string('add'));
2769
2770 // *sigh* folding up the form breaks the filepicker control
2771 // $mform->addElement('html', '<script type="text/javascript">showhide_subform()</script>');
2772 }
2773
2774 function get_ical_data() {
2775 $formdata = $this->get_data();
2776 switch ($formdata->importfrom) {
2777 case CALENDAR_IMPORT_FROM_FILE:
2778 $calendar = $this->get_file_content('importfile');
2779 break;
2780 case CALENDAR_IMPORT_FROM_URL:
4c349ad7 2781 $calendar = download_file_content($formdata->importurl);
b5a52acd
JH
2782 break;
2783 }
2784 return $calendar;
2785 }
2786}
2787
2788/**
2789 * Add an iCalendar subscription to the database.
2790 * @param object $sub The subscription object (e.g. from the form)
2791 * @return int The insert ID, if any.
2792 */
2793function calendar_add_subscription($sub) {
2794 global $DB, $USER;
2795 $sub->courseid = $sub->eventtype;
2796 if ($sub->eventtype == 'group') {
2797 $sub->courseid = $sub->course;
2798 }
2799 $sub->userid = $USER->id;
2800
2801 // file subscriptions never update.
2802 if (empty($sub->url)) {
2803 $sub->pollinterval = 0;
2804 }
2805
2806 if (!empty($sub->name)) {
2807 if (empty($sub->id)) {
2808 $id = $DB->insert_record('event_subscriptions', $sub);
2809 return $id;
2810 } else {
2811 $DB->update_record('event_subscriptions', $sub);
2812 return $sub->id;
2813 }
2814 } else {
2815 print_error('errorbadsubscription', 'importcalendar');
2816 }
2817}
2818
2819/**
2820 * Add an iCalendar event to the Moodle calendar.
2821 * @param object $event The RFC-2445 iCalendar event
2822 * @param int $courseid The course ID
2823 * @param int $subscriptionid The iCalendar subscription ID
2824 * @return int Code: 1=updated, 2=inserted, 0=error
2825 */
2826function calendar_add_icalendar_event($event, $courseid, $subscriptionid=null) {
2827 global $DB, $USER;
2828
2829 $eventrecord = new stdClass;
2830
2831 // probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2832 if (empty($event->properties['SUMMARY'])) {
2833 return 0;
2834 }
2835
2836 $name = $event->properties['SUMMARY'][0]->value;
2837 $name = str_replace('\n', '<br />', $name);
2838 $name = str_replace('\\', '', $name);
2839 $name = preg_replace('/\s+/', ' ', $name);
4c349ad7 2840 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
b5a52acd
JH
2841
2842 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2843 $description = '';
2844 } else {
2845 $description = $event->properties['DESCRIPTION'][0]->value;
2846 $description = str_replace('\n', '<br />', $description);
2847 $description = str_replace('\\', '', $description);
2848 $description = preg_replace('/\s+/', ' ', $description);
2849 }
4c349ad7 2850 $eventrecord->description = clean_param($description, PARAM_NOTAGS);
b5a52acd
JH
2851
2852 // probably a repeating event with RRULE etc. TODO: skip for now
2853 if (empty($event->properties['DTSTART'][0]->value)) {
2854 return 0;
2855 }
2856
2857 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value);
2858 if (empty($event->properties['DTEND'])) {
2859 $eventrecord->timeduration = 3600; // one hour if no end time specified
2860 } else {
2861 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value) - $eventrecord->timestart;
2862 }
2863 $eventrecord->uuid = $event->properties['UID'][0]->value;
2864 $eventrecord->timemodified = time();
2865
2866 // Add the iCal subscription details if required
2867 if ($sub = $DB->get_record('event_subscriptions', array('id' => $subscriptionid))) {
2868 $eventrecord->subscriptionid = $subscriptionid;
2869 $eventrecord->userid = $sub->userid;
2870 $eventrecord->groupid = $sub->groupid;
2871 $eventrecord->courseid = $sub->courseid;
2872 } else {
2873 $eventrecord->userid = $USER->id;
2874 $eventrecord->groupid = 0; // TODO: ???
2875 $eventrecord->courseid = $courseid;
2876 }
2877
2878 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid))) {
2879 $eventrecord->id = $updaterecord->id;
2880 if ($DB->update_record('event', $eventrecord)) {
2881 return CALENDAR_IMPORT_EVENT_UPDATED;
2882 } else {
2883 return 0;
2884 }
2885 } else {
2886 if ($DB->insert_record('event', $eventrecord)) {
2887 return CALENDAR_IMPORT_EVENT_INSERTED;
2888 } else {
2889 return 0;
2890 }
2891 }
2892}
2893
2894/**
2895 * Create the list of iCalendar subscriptions for a course calendar.
2896 * @param int $courseid The course ID
2897 * @return string The table output.
2898 */
2899function calendar_show_subscriptions($courseid, $importresults='') {
2900 global $DB, $OUTPUT, $CFG, $USER;
2901
2902 $view = optional_param('view', '', PARAM_ALPHA);
2903 $sesskey = sesskey();
2904 $out = '';
2905
4c349ad7 2906 $str = new object();
b5a52acd
JH
2907 $str->update = get_string('update');
2908 $str->remove = get_string('remove');
2909 $str->add = get_string('add');
4c349ad7
JH
2910 $str->colcalendar = get_string('colcalendar', 'calendar');
2911 $str->collastupdated = get_string('collastupdated', 'calendar');
2912 $str->colpoll = get_string('colpoll', 'calendar');
2913 $str->colactions = get_string('colactions', 'calendar');
2914 $str->nocalendarsubscriptions = get_string('nocalendarsubscriptions', 'calendar');
b5a52acd
JH
2915
2916 $out .= $OUTPUT->box_start('generalbox calendarsubs');
2917 $out .= $importresults;
2918
2919 $table = new html_table();
4c349ad7 2920 $table->head = array($str->colcalendar, $str->collastupdated, $str->colpoll, $str->colactions);
b5a52acd
JH
2921 $table->align = array('left', 'left', 'left', 'center');
2922 $table->width = '100%';
2923 $table->data = array();
2924
2925 $subs = $DB->get_records_sql('select * from {event_subscriptions}
2926 where courseid = :courseid
2927 or (courseid = 0 and userid = :userid)',
2928 array('courseid' => $courseid, 'userid' => $USER->id));
2929 if (empty($subs)) {
4c349ad7 2930 $c = new html_table_cell($str->nocalendarsubscriptions);
b5a52acd
JH
2931 $c->colspan = 4;
2932 $table->data[] = new html_table_row(array($c));
2933 }
2934 foreach ($subs as $id => $sub) {
2935 $label = empty($sub->url) ? $sub->name : "<a href=\"{$sub->url}\">{$sub->name}</a>";
4c349ad7 2936 $cellurl = new html_table_cell($label);
b5a52acd
JH
2937 $lastupdated = empty($sub->lastupdated)
2938 ? get_string('never', 'calendar')
4c349ad7
JH
2939 : userdate($sub->lastupdated, get_string('strftimedatetimeshort', 'langconfig'));
2940 $cellupdated = new html_table_cell($lastupdated);
b5a52acd
JH
2941
2942 if (empty($sub->url)) {
2943 // don't update an iCal file, which has no URL.
2944 $pollinterval = '<input type="hidden" name="pollinterval" value="0" />';
2945 } else {
2946 // assemble pollinterval control
2947 $pollinterval = "<div style=\"float:left\">
2948 <select name=\"pollinterval\">\n";
2949 foreach (calendar_get_pollinterval_choices() as $k => $v) {
2950 $selected = ($k == $sub->pollinterval) ? ' selected' : '';
2951 $pollinterval .= "<option value=\"{$k}\"{$selected}>{$v}</option>\n";
2952 }
2953 $pollinterval .= "</select></div>";
2954 }
2955
2956 // assemble form for the subscription row
2957 $rowform = "
2958 <form action=\"{$CFG->wwwroot}/calendar/view.php\" method=\"post\">
2959 {$pollinterval}
2960 <div style=\"float:right\">
2961 <input type=\"hidden\" name=\"sesskey\" value=\"{$sesskey}\" />
2962 <input type=\"hidden\" name=\"view\" value=\"{$view}\" />
2963 <input type=\"hidden\" name=\"course\" value=\"{$courseid}\" />
2964 <input type=\"hidden\" name=\"id\" value=\"{$sub->id}\" />
2965 " . (empty($sub->url)
2966 ? ''
2967 : "<input type=\"submit\" name=\"action\" value=\"{$str->update}\" />") . "
2968 <input type=\"submit\" name=\"action\" value=\"{$str->remove}\" />
2969 </div>
2970 </form>";
4c349ad7
JH
2971 $cellform = new html_table_cell($rowform);
2972 $cellform->colspan = 2;
2973 $table->data[] = new html_table_row(array($cellurl, $cellupdated, $cellform));
b5a52acd
JH
2974 }
2975 $out .= html_writer::table($table);
2976
2977 // form for adding a new subscription
2978 $form = new calendar_addsubscription_form();
2979 $formdata = $form->get_data();
2980 if (empty($formdata)) {
2981 $formdata = new stdClass;
2982 $formdata->course = $courseid;
2983 $form->set_data($formdata);
2984 }
2985
2986 // *sigh* there appears to be no function that returns Moodle Form HTML.
2987 ob_start();
2988 $form->display();
2989 $buffer = ob_get_contents();
2990 $out .= $buffer;
2991 ob_end_clean();
2992
2993 $out .= $OUTPUT->box_end();
2994 return $out;
2995}
2996
2997/**
2998 * Add a subscription from the form data and add its events to the calendar.
2999 * The form data will be either from the new subscription form, or from a form
3000 * on one of the rows in the existing subscriptions table.
3001 * @param int $courseid The course ID
3002 * @return string A log of the import progress, including errors
3003 */
3004function calendar_process_subscription_form($courseid) {
3005 global $DB;
3006
3007 $form = new calendar_addsubscription_form();
3008 $formdata = $form->get_data();
3009 if (!empty($formdata)) {
3010 if (empty($formdata->url) and empty($formdata->importfile)) {
3011 print_error('errorrequiredurlorfile', 'calendar');
3012 }
3013 if ($formdata->importfrom == CALENDAR_IMPORT_FROM_FILE) {
3014 // blank the URL if it's a file import
3015 $formdata->url = '';
3016 $subscriptionid = calendar_add_subscription($formdata);
3017 $calendar = $form->get_ical_data();
3018 $ical = new iCalendar();
3019 $ical->unserialize($calendar);
3020 return calendar_import_icalendar_events($ical, $courseid, $subscriptionid);
3021 } else {
3022 $subscriptionid = calendar_add_subscription($formdata);
3023 return calendar_update_subscription_events($subscriptionid);
3024 }
3025 } else {
3026 // process any subscription row form data
3027 return calendar_process_subscription_row();
3028 }
3029}
3030
3031/**
3032 * Update a subscription from the form data in one of the rows in the existing
3033 * subscriptions table.
3034 * @return string A log of the import progress, including errors
3035 */
3036function calendar_process_subscription_row() {
3037 global $DB;
3038
3039 $id = optional_param('id', 0, PARAM_INT);
3040 $courseid = optional_param('course', 0, PARAM_INT);
3041 $pollinterval = optional_param('pollinterval', 0, PARAM_INT);
3042 $action = optional_param('action', '', PARAM_ALPHA);
3043
3044 if (empty($id)) {
3045 return '';
3046 }
3047
3048 $str->update = get_string('update');
3049 $str->remove = get_string('remove');
3050
3051 // update or remove the subscription, based on action.
3052 $sub = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
3053 switch ($action) {
3054 case $str->update:
3055 // skip updating file subscriptions
3056 if (empty($sub->url)) {
3057 break;
3058 }
3059 $sub->pollinterval = $pollinterval;
3060 $DB->update_record('event_subscriptions', $sub);
3061
3062 // update the events
3063 return "<p>Calendar subscription '{$sub->name}' updated.</p>" . calendar_update_subscription_events($id);
3064 break;
3065
3066 case $str->remove:
3067 $sesskey = required_param('sesskey', PARAM_ALPHANUM);
3068 $DB->delete_records('event', array('subscriptionid' => $id));
3069 $DB->delete_records('event_subscriptions', array('id' => $id));
3070 return "Calendar subscription '{$sub->name}' removed.";
3071 break;
3072
3073 default:
3074 break;
3075 }
3076 return '';
3077}
3078
3079/**
3080 * From a URL, fetch the calendar and return an iCalendar object.
3081 * @param string $url The iCalendar URL
3082 * @return object The iCalendar object
3083 */
3084function calendar_get_icalendar($url) {
3085 $calendar = file_get_contents($url);
3086 $ical = new iCalendar();
3087 $ical->unserialize($calendar);
3088 return $ical;
3089}
3090
3091/**
3092 * Import events from an iCalendar object into a course calendar.
3093 * @param object $ical The iCalendar object
3094 * @param integer $courseid The course ID for the calendar
3095 * @param integer $subscriptionid The subscription ID
3096 * @return string A log of the import progress, including
3097 * errors
3098 */
3099function calendar_import_icalendar_events($ical, $courseid, $subscriptionid=null) {
3100 global $DB;
3101 $return = '';
3102 $eventcount = 0;
3103 $updatecount = 0;
3104
3105 // large calendars take a while...
3106 ini_set('max_execution_time', 300);
3107
3108 // mark all events in a subscription with a zero timestamp
3109 if (!empty($subscriptionid)) {
3110 $sql = "update {event} set timemodified = :time where subscriptionid = :id";
3111 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3112 }
4c349ad7 3113 foreach ($ical->components['VEVENT'] as $event) {
b5a52acd
JH
3114 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid);
3115 switch ($res) {
3116 case CALENDAR_IMPORT_EVENT_UPDATED:
3117 $updatecount++;
3118 break;
3119 case CALENDAR_IMPORT_EVENT_INSERTED:
3120 $eventcount++;
3121 break;
3122 case 0:
4c349ad7 3123 $return .= '<p>'.get_string('erroraddingevent', 'calendar').': '.(empty($event->properties['SUMMARY'])?'('.get_string('notitle', 'calendar').')':$event->properties['SUMMARY'][0]->value)." </p>\n";
b5a52acd
JH
3124 break;
3125 }
3126 }
4c349ad7
JH
3127 $return .= "<p> ".get_string('eventsimported', 'calendar').": {$eventcount} </p>\n";
3128 $return .= "<p> ".get_string('eventsupdated', 'calendar').": {$updatecount} </p>\n";
b5a52acd
JH
3129
3130 // delete remaining zero-marked events since they're not in remote calendar
3131 if (!empty($subscriptionid)) {
3132 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3133 if (!empty($deletecount)) {
3134 $sql = "delete from {event} where timemodified = :time and subscriptionid = :id";
3135 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
4c349ad7 3136 $return .= "<p> ".get_string('eventsdeleted', 'calendar').": {$deletecount} </p>\n";
b5a52acd
JH
3137 }
3138 }
3139
3140 return $return;
3141}
3142
3143/**
3144 * Fetch a calendar subscription and update the events in the calendar.
3145 * @param integer $subscriptionid The course ID for the calendar
3146 * @return string A log of the import progress, including
3147 * errors
3148 */
3149function calendar_update_subscription_events($subscriptionid) {
3150 global $DB;
3151 $return = '';
3152
3153 $sub = $DB->get_record('event_subscriptions', array('id' => $subscriptionid));
3154 if (empty($sub)) {
3155 print_error('errorbadsubscription', 'calendar');
3156 }
3157 // Don't update a file subscription. TODO: Update from a new uploaded file?
3158 if (empty($sub->url)) {
3159 return 'File subscription not updated.';
3160 }
3161 $ical = calendar_get_icalendar($sub->url);
3162 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
3163 $sub->lastupdated = time();
3164 $DB->update_record('event_subscriptions', $sub);
3165 return $return;
3166}
3167
3168/**
3169 * Update calendar subscriptions.
3170 */
3171function calendar_cron() {
3172 global $DB;
4c349ad7 3173 mtrace(get_string('cronupdate', 'calendar'));
b5a52acd 3174 $time = time();
4c349ad7
JH
3175 $subscriptions = $DB->get_records_sql('select * from {event_subscriptions} where pollinterval > 0 and lastupdated + pollinterval < ?', array($time));
3176 foreach ($subscriptions as $sub) {
3177 mtrace(get_string('cronupdatesub', 'calendar', $sub));
b5a52acd
JH
3178 $log = calendar_update_subscription_events($sub->id);
3179 mtrace(trim(strip_tags($log)));
3180 }
4c349ad7 3181 mtrace(get_string('cronupdatefinished', 'calendar'));
b5a52acd
JH
3182 return true;
3183}
3184