MDL-32279 filters: add documentation to upgrade.txt
[moodle.git] / calendar / lib.php
blob815299001b5d36ebe9eb31e6b640d2a7db5fa8be
1 <?php
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.
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/>.
17 /**
18 * Calendar extension
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
26 /**
27 * These are read by the administration component to provide default values
30 /**
31 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
33 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
35 /**
36 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
38 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
40 /**
41 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
43 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
45 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
46 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
48 /**
49 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
51 define('CALENDAR_DEFAULT_WEEKEND', 65);
53 /**
54 * CALENDAR_URL - path to calendar's folder
56 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
58 /**
59 * CALENDAR_TF_24 - Calendar time in 24 hours format
61 define('CALENDAR_TF_24', '%H:%M');
63 /**
64 * CALENDAR_TF_12 - Calendar time in 12 hours format
66 define('CALENDAR_TF_12', '%I:%M %p');
68 /**
69 * CALENDAR_EVENT_GLOBAL - Global calendar event types
71 define('CALENDAR_EVENT_GLOBAL', 1);
73 /**
74 * CALENDAR_EVENT_COURSE - Course calendar event types
76 define('CALENDAR_EVENT_COURSE', 2);
78 /**
79 * CALENDAR_EVENT_GROUP - group calendar event types
81 define('CALENDAR_EVENT_GROUP', 4);
83 /**
84 * CALENDAR_EVENT_USER - user calendar event types
86 define('CALENDAR_EVENT_USER', 8);
88 /**
89 * CALENDAR_STARTING_WEEKDAY - has since been deprecated please call calendar_get_starting_weekday() instead
91 * @deprecated Moodle 2.0 MDL-24284- please do not use this function any more.
92 * @todo MDL-31132 This will be deleted in Moodle 2.3.
93 * @see calendar_get_starting_weekday()
95 define('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);
97 /**
98 * Return the days of the week
100 * @return array array of days
102 function calendar_get_days() {
103 return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
107 * Gets the first day of the week
109 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
111 * @return int
113 function calendar_get_starting_weekday() {
114 global $CFG;
116 if (isset($CFG->calendar_startwday)) {
117 $firstday = $CFG->calendar_startwday;
118 } else {
119 $firstday = get_string('firstdayofweek', 'langconfig');
122 if(!is_numeric($firstday)) {
123 return CALENDAR_DEFAULT_STARTING_WEEKDAY;
124 } else {
125 return intval($firstday) % 7;
130 * Generates the HTML for a miniature calendar
132 * @param array $courses list of course
133 * @param array $groups list of group
134 * @param array $users user's info
135 * @param int $cal_month calendar month in numeric, default is set to false
136 * @param int $cal_year calendar month in numeric, default is set to false
137 * @return string $content return html table for mini calendar
139 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
140 global $CFG, $USER, $OUTPUT;
142 $display = new stdClass;
143 $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
144 $display->maxwday = $display->minwday + 6;
146 $content = '';
148 if(!empty($cal_month) && !empty($cal_year)) {
149 $thisdate = usergetdate(time()); // Date and time the user sees at his location
150 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
151 // Navigated to this month
152 $date = $thisdate;
153 $display->thismonth = true;
154 } else {
155 // Navigated to other month, let's do a nice trick and save us a lot of work...
156 if(!checkdate($cal_month, 1, $cal_year)) {
157 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
158 $display->thismonth = true;
159 } else {
160 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
161 $display->thismonth = false;
164 } else {
165 $date = usergetdate(time()); // Date and time the user sees at his location
166 $display->thismonth = true;
169 // Fill in the variables we 're going to use, nice and tidy
170 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
171 $display->maxdays = calendar_days_in_month($m, $y);
173 if (get_user_timezone_offset() < 99) {
174 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
175 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
176 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
177 } else {
178 // no timezone info specified
179 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
180 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
183 $startwday = dayofweek(1, $m, $y);
185 // Align the starting weekday to fall in our display range
186 // This is simple, not foolproof.
187 if($startwday < $display->minwday) {
188 $startwday += 7;
191 // TODO: THIS IS TEMPORARY CODE!
192 // [pj] I was just reading through this and realized that I when writing this code I was probably
193 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
194 // make_timestamp would accomplish the same thing. So here goes a test:
195 //$test_start = make_timestamp($y, $m, 1);
196 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
197 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
198 //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);
200 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
201 //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);
205 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
206 $events = calendar_get_events(
207 usertime($display->tstart) - dst_offset_on($display->tstart),
208 usertime($display->tend) - dst_offset_on($display->tend),
209 $users, $groups, $courses);
211 // Set event course class for course events
212 if (!empty($events)) {
213 foreach ($events as $eventid => $event) {
214 if (!empty($event->modulename)) {
215 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
216 if (!groups_course_module_visible($cm)) {
217 unset($events[$eventid]);
223 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
224 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
225 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
226 // arguments to this function.
228 $hrefparams = array();
229 if(!empty($courses)) {
230 $courses = array_diff($courses, array(SITEID));
231 if(count($courses) == 1) {
232 $hrefparams['course'] = reset($courses);
236 // We want to have easy access by day, since the display is on a per-day basis.
237 // Arguments passed by reference.
238 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
239 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
241 //Accessibility: added summary and <abbr> elements.
242 $days_title = calendar_get_days();
244 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
245 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
246 $content .= '<tr class="weekdays">'; // Header row: day names
248 // Print out the names of the weekdays
249 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
250 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
251 // This uses the % operator to get the correct weekday no matter what shift we have
252 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
253 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
254 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
257 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
259 // For the table display. $week is the row; $dayweek is the column.
260 $dayweek = $startwday;
262 // Paddding (the first week may have blank days in the beginning)
263 for($i = $display->minwday; $i < $startwday; ++$i) {
264 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
267 $weekend = CALENDAR_DEFAULT_WEEKEND;
268 if (isset($CFG->calendar_weekend)) {
269 $weekend = intval($CFG->calendar_weekend);
272 // Now display all the calendar
273 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
274 if($dayweek > $display->maxwday) {
275 // We need to change week (table row)
276 $content .= '</tr><tr>';
277 $dayweek = $display->minwday;
280 // Reset vars
281 $cell = '';
282 if ($weekend & (1 << ($dayweek % 7))) {
283 // Weekend. This is true no matter what the exact range is.
284 $class = 'weekend day';
285 } else {
286 // Normal working day.
287 $class = 'day';
290 // Special visual fx if an event is defined
291 if(isset($eventsbyday[$day])) {
292 $class .= ' hasevent';
293 $hrefparams['view'] = 'day';
294 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $hrefparams), $day, $m, $y);
296 $popupcontent = '';
297 foreach($eventsbyday[$day] as $eventid) {
298 if (!isset($events[$eventid])) {
299 continue;
301 $event = $events[$eventid];
302 $popupalt = '';
303 $component = 'moodle';
304 if(!empty($event->modulename)) {
305 $popupicon = 'icon';
306 $popupalt = $event->modulename;
307 $component = $event->modulename;
308 } else if ($event->courseid == SITEID) { // Site event
309 $popupicon = 'c/site';
310 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
311 $popupicon = 'c/course';
312 } else if ($event->groupid) { // Group event
313 $popupicon = 'c/group';
314 } else if ($event->userid) { // User event
315 $popupicon = 'c/user';
318 $dayhref->set_anchor('event_'.$event->id);
320 $popupcontent .= html_writer::start_tag('div');
321 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
322 $popupcontent .= html_writer::link($dayhref, format_string($event->name, true));
323 $popupcontent .= html_writer::end_tag('div');
326 //Accessibility: functionality moved to calendar_get_popup.
327 if($display->thismonth && $day == $d) {
328 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
329 } else {
330 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
333 // Class and cell content
334 if(isset($typesbyday[$day]['startglobal'])) {
335 $class .= ' calendar_event_global';
336 } else if(isset($typesbyday[$day]['startcourse'])) {
337 $class .= ' calendar_event_course';
338 } else if(isset($typesbyday[$day]['startgroup'])) {
339 $class .= ' calendar_event_group';
340 } else if(isset($typesbyday[$day]['startuser'])) {
341 $class .= ' calendar_event_user';
343 $cell = '<a href="'.(string)$dayhref.'" '.$popup.'>'.$day.'</a>';
344 } else {
345 $cell = $day;
348 $durationclass = false;
349 if (isset($typesbyday[$day]['durationglobal'])) {
350 $durationclass = ' duration_global';
351 } else if(isset($typesbyday[$day]['durationcourse'])) {
352 $durationclass = ' duration_course';
353 } else if(isset($typesbyday[$day]['durationgroup'])) {
354 $durationclass = ' duration_group';
355 } else if(isset($typesbyday[$day]['durationuser'])) {
356 $durationclass = ' duration_user';
358 if ($durationclass) {
359 $class .= ' duration '.$durationclass;
362 // If event has a class set then add it to the table day <td> tag
363 // Note: only one colour for minicalendar
364 if(isset($eventsbyday[$day])) {
365 foreach($eventsbyday[$day] as $eventid) {
366 if (!isset($events[$eventid])) {
367 continue;
369 $event = $events[$eventid];
370 if (!empty($event->class)) {
371 $class .= ' '.$event->class;
373 break;
377 // Special visual fx for today
378 //Accessibility: hidden text for today, and popup.
379 if($display->thismonth && $day == $d) {
380 $class .= ' today';
381 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
383 if(! isset($eventsbyday[$day])) {
384 $class .= ' eventnone';
385 $popup = calendar_get_popup(true, false);
386 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
388 $cell = get_accesshide($today.' ').$cell;
391 // Just display it
392 if(!empty($class)) {
393 $class = ' class="'.$class.'"';
395 $content .= '<td'.$class.'>'.$cell."</td>\n";
398 // Paddding (the last week may have blank days at the end)
399 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
400 $content .= '<td class="dayblank">&nbsp;</td>';
402 $content .= '</tr>'; // Last row ends
404 $content .= '</table>'; // Tabular display of days ends
406 return $content;
410 * Gets the calendar popup
412 * It called at multiple points in from calendar_get_mini.
413 * Copied and modified from calendar_get_mini.
415 * @param bool $is_today false except when called on the current day.
416 * @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
417 * @param string $popupcontent content for the popup window/layout
418 * @return string of eventid for the calendar_tooltip popup window/layout
420 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
421 global $PAGE;
422 static $popupcount;
423 if ($popupcount === null) {
424 $popupcount = 1;
426 $popupcaption = '';
427 if($is_today) {
428 $popupcaption = get_string('today', 'calendar').' ';
430 if (false === $event_timestart) {
431 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
432 $popupcontent = get_string('eventnone', 'calendar');
434 } else {
435 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
437 $id = 'calendar_tooltip_'.$popupcount;
438 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
440 $popupcount++;
441 return 'id="'.$id.'"';
445 * Gets the calendar upcoming event
447 * @param array $courses array of courses
448 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
449 * @param array|int|bool $users array of users, user id or boolean for all/no user events
450 * @param int $daysinfuture number of days in the future we 'll look
451 * @param int $maxevents maximum number of events
452 * @param int $fromtime start time
453 * @return array $output array of upcoming events
455 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
456 global $CFG, $COURSE, $DB;
458 $display = new stdClass;
459 $display->range = $daysinfuture; // How many days in the future we 'll look
460 $display->maxevents = $maxevents;
462 $output = array();
464 // Prepare "course caching", since it may save us a lot of queries
465 $coursecache = array();
467 $processed = 0;
468 $now = time(); // We 'll need this later
469 $usermidnighttoday = usergetmidnight($now);
471 if ($fromtime) {
472 $display->tstart = $fromtime;
473 } else {
474 $display->tstart = $usermidnighttoday;
477 // This works correctly with respect to the user's DST, but it is accurate
478 // only because $fromtime is always the exact midnight of some day!
479 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
481 // Get the events matching our criteria
482 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
484 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
485 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
486 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
487 // arguments to this function.
489 $hrefparams = array();
490 if(!empty($courses)) {
491 $courses = array_diff($courses, array(SITEID));
492 if(count($courses) == 1) {
493 $hrefparams['course'] = reset($courses);
497 if ($events !== false) {
499 $modinfo = get_fast_modinfo($COURSE);
501 foreach($events as $event) {
504 if (!empty($event->modulename)) {
505 if ($event->courseid == $COURSE->id) {
506 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
507 $cm = $modinfo->instances[$event->modulename][$event->instance];
508 if (!$cm->uservisible) {
509 continue;
512 } else {
513 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
514 continue;
516 if (!coursemodule_visible_for_user($cm)) {
517 continue;
520 if ($event->modulename == 'assignment'){
521 // create calendar_event to test edit_event capability
522 // this new event will also prevent double creation of calendar_event object
523 $checkevent = new calendar_event($event);
524 // TODO: rewrite this hack somehow
525 if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
526 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
527 // print_error("invalidid", 'assignment');
528 continue;
530 // assign assignment to assignment object to use hidden_is_hidden method
531 require_once($CFG->dirroot.'/mod/assignment/lib.php');
533 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
534 continue;
536 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
538 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
539 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
541 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
542 $event->description = get_string('notavailableyet', 'assignment');
548 if ($processed >= $display->maxevents) {
549 break;
552 $event->time = calendar_format_event_time($event, $now, $hrefparams);
553 $output[] = $event;
554 ++$processed;
557 return $output;
561 * Add calendar event metadata
563 * @param stdClass $event event info
564 * @return stdClass $event metadata
566 function calendar_add_event_metadata($event) {
567 global $CFG, $OUTPUT;
569 //Support multilang in event->name
570 $event->name = format_string($event->name,true);
572 if(!empty($event->modulename)) { // Activity event
573 // The module name is set. I will assume that it has to be displayed, and
574 // also that it is an automatically-generated event. And of course that the
575 // fields for get_coursemodule_from_instance are set correctly.
576 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
578 if ($module === false) {
579 return;
582 $modulename = get_string('modulename', $event->modulename);
583 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
584 // will be used as alt text if the event icon
585 $eventtype = get_string($event->eventtype, $event->modulename);
586 } else {
587 $eventtype = '';
589 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
591 $context = get_context_instance(CONTEXT_COURSE, $module->course);
592 $fullname = format_string($coursecache[$module->course]->fullname, true, array('context' => $context));
594 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
595 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
596 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$fullname.'</a>';
597 $event->cmid = $module->id;
600 } else if($event->courseid == SITEID) { // Site event
601 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
602 $event->cssclass = 'calendar_event_global';
603 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
604 calendar_get_course_cached($coursecache, $event->courseid);
606 $context = get_context_instance(CONTEXT_COURSE, $event->courseid);
607 $fullname = format_string($coursecache[$event->courseid]->fullname, true, array('context' => $context));
609 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
610 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$fullname.'</a>';
611 $event->cssclass = 'calendar_event_course';
612 } else if ($event->groupid) { // Group event
613 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
614 $event->cssclass = 'calendar_event_group';
615 } else if($event->userid) { // User event
616 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
617 $event->cssclass = 'calendar_event_user';
619 return $event;
623 * Get calendar events
625 * @param int $tstart Start time of time range for events
626 * @param int $tend End time of time range for events
627 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
628 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
629 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
630 * @param boolean $withduration whether only events starting within time range selected
631 * or events in progress/already started selected as well
632 * @param boolean $ignorehidden whether to select only visible events or all events
633 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
635 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
636 global $DB;
638 $whereclause = '';
639 // Quick test
640 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
641 return array();
644 if(is_array($users) && !empty($users)) {
645 // Events from a number of users
646 if(!empty($whereclause)) $whereclause .= ' OR';
647 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
648 } else if(is_numeric($users)) {
649 // Events from one user
650 if(!empty($whereclause)) $whereclause .= ' OR';
651 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
652 } else if($users === true) {
653 // Events from ALL users
654 if(!empty($whereclause)) $whereclause .= ' OR';
655 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
656 } else if($users === false) {
657 // No user at all, do nothing
660 if(is_array($groups) && !empty($groups)) {
661 // Events from a number of groups
662 if(!empty($whereclause)) $whereclause .= ' OR';
663 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
664 } else if(is_numeric($groups)) {
665 // Events from one group
666 if(!empty($whereclause)) $whereclause .= ' OR ';
667 $whereclause .= ' groupid = '.$groups;
668 } else if($groups === true) {
669 // Events from ALL groups
670 if(!empty($whereclause)) $whereclause .= ' OR ';
671 $whereclause .= ' groupid != 0';
673 // boolean false (no groups at all): we don't need to do anything
675 if(is_array($courses) && !empty($courses)) {
676 if(!empty($whereclause)) {
677 $whereclause .= ' OR';
679 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
680 } else if(is_numeric($courses)) {
681 // One course
682 if(!empty($whereclause)) $whereclause .= ' OR';
683 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
684 } else if ($courses === true) {
685 // Events from ALL courses
686 if(!empty($whereclause)) $whereclause .= ' OR';
687 $whereclause .= ' (groupid = 0 AND courseid != 0)';
690 // Security check: if, by now, we have NOTHING in $whereclause, then it means
691 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
692 // events no matter what. Allowing the code to proceed might return a completely
693 // valid query with only time constraints, thus selecting ALL events in that time frame!
694 if(empty($whereclause)) {
695 return array();
698 if($withduration) {
699 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
701 else {
702 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
704 if(!empty($whereclause)) {
705 // We have additional constraints
706 $whereclause = $timeclause.' AND ('.$whereclause.')';
708 else {
709 // Just basic time filtering
710 $whereclause = $timeclause;
713 if ($ignorehidden) {
714 $whereclause .= ' AND visible = 1';
717 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
718 if ($events === false) {
719 $events = array();
721 return $events;
725 * Get control options for Calendar
727 * @param string $type of calendar
728 * @param array $data calendar information
729 * @return string $content return available control for the calender in html
731 function calendar_top_controls($type, $data) {
732 global $CFG;
733 $content = '';
734 if(!isset($data['d'])) {
735 $data['d'] = 1;
738 // Ensure course id passed if relevant
739 // Required due to changes in view/lib.php mainly (calendar_session_vars())
740 $courseid = '';
741 if (!empty($data['id'])) {
742 $courseid = '&amp;course='.$data['id'];
745 if(!checkdate($data['m'], $data['d'], $data['y'])) {
746 $time = time();
748 else {
749 $time = make_timestamp($data['y'], $data['m'], $data['d']);
751 $date = usergetdate($time);
753 $data['m'] = $date['mon'];
754 $data['y'] = $date['year'];
756 //Accessibility: calendar block controls, replaced <table> with <div>.
757 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
758 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
760 switch($type) {
761 case 'frontpage':
762 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
763 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
764 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
765 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
767 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
768 if (!empty($data['id'])) {
769 $calendarlink->param('course', $data['id']);
772 if (right_to_left()) {
773 $left = $nextlink;
774 $right = $prevlink;
775 } else {
776 $left = $prevlink;
777 $right = $nextlink;
780 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
781 $content .= $left.'<span class="hide"> | </span>';
782 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
783 $content .= '<span class="hide"> | </span>'. $right;
784 $content .= "<span class=\"clearer\"><!-- --></span>\n";
785 $content .= html_writer::end_tag('div');
787 break;
788 case 'course':
789 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
790 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
791 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
792 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);
794 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
795 if (!empty($data['id'])) {
796 $calendarlink->param('course', $data['id']);
799 if (right_to_left()) {
800 $left = $nextlink;
801 $right = $prevlink;
802 } else {
803 $left = $prevlink;
804 $right = $nextlink;
807 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
808 $content .= $left.'<span class="hide"> | </span>';
809 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
810 $content .= '<span class="hide"> | </span>'. $right;
811 $content .= "<span class=\"clearer\"><!-- --></span>";
812 $content .= html_writer::end_tag('div');
813 break;
814 case 'upcoming':
815 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
816 if (!empty($data['id'])) {
817 $calendarlink->param('course', $data['id']);
819 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
820 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
821 break;
822 case 'display':
823 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
824 if (!empty($data['id'])) {
825 $calendarlink->param('course', $data['id']);
827 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
828 $content .= html_writer::tag('h3', $calendarlink);
829 break;
830 case 'month':
831 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
832 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
833 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
834 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
835 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
836 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
838 if (right_to_left()) {
839 $left = $nextlink;
840 $right = $prevlink;
841 } else {
842 $left = $prevlink;
843 $right = $nextlink;
846 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
847 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
848 $content .= '<span class="hide"> | </span>' . $right;
849 $content .= '<span class="clearer"><!-- --></span>';
850 $content .= html_writer::end_tag('div')."\n";
851 break;
852 case 'day':
853 $days = calendar_get_days();
854 $data['d'] = $date['mday']; // Just for convenience
855 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
856 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
857 $prevname = calendar_wday_name($days[$prevdate['wday']]);
858 $nextname = calendar_wday_name($days[$nextdate['wday']]);
859 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
860 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
862 if (right_to_left()) {
863 $left = $nextlink;
864 $right = $prevlink;
865 } else {
866 $left = $prevlink;
867 $right = $nextlink;
870 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
871 $content .= $left;
872 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
873 $content .= '<span class="hide"> | </span>'. $right;
874 $content .= "<span class=\"clearer\"><!-- --></span>";
875 $content .= html_writer::end_tag('div')."\n";
877 break;
879 return $content;
883 * Get the controls filter for calendar.
885 * Filter is used to hide calendar info from the display page
887 * @param moodle_url $returnurl return-url for filter controls
888 * @return string $content return filter controls in html
890 function calendar_filter_controls(moodle_url $returnurl) {
891 global $CFG, $USER, $OUTPUT;
893 $groupevents = true;
895 $id = optional_param( 'id',0,PARAM_INT );
897 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));
899 $content = '<table>';
900 $content .= '<tr>';
902 $seturl->param('var', 'showglobal');
903 if (calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
904 $content .= '<td class="eventskey calendar_event_global" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
905 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
906 } else {
907 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
908 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
911 $seturl->param('var', 'showcourses');
912 if (calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
913 $content .= '<td class="eventskey calendar_event_course" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidecourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
914 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
915 } else {
916 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_showcourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
917 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
920 if (isloggedin() && !isguestuser()) {
921 $content .= "</tr>\n<tr>";
923 if ($groupevents) {
924 // This course MIGHT have group events defined, so show the filter
925 $seturl->param('var', 'showgroups');
926 if (calendar_show_event_type(CALENDAR_EVENT_GROUP)) {
927 $content .= '<td class="eventskey calendar_event_group" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidegroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
928 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
929 } else {
930 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showgroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
931 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
933 } else {
934 // This course CANNOT have group events, so lose the filter
935 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
938 $seturl->param('var', 'showuser');
939 if (calendar_show_event_type(CALENDAR_EVENT_USER)) {
940 $content .= '<td class="eventskey calendar_event_user" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
941 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
942 } else {
943 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
944 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
947 $content .= "</tr>\n</table>\n";
949 return $content;
953 * Return the representation day
955 * @param int $tstamp Timestamp in GMT
956 * @param int $now current Unix timestamp
957 * @param bool $usecommonwords
958 * @return string the formatted date/time
960 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
962 static $shortformat;
963 if(empty($shortformat)) {
964 $shortformat = get_string('strftimedayshort');
967 if($now === false) {
968 $now = time();
971 // To have it in one place, if a change is needed
972 $formal = userdate($tstamp, $shortformat);
974 $datestamp = usergetdate($tstamp);
975 $datenow = usergetdate($now);
977 if($usecommonwords == false) {
978 // We don't want words, just a date
979 return $formal;
981 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
982 // Today
983 return get_string('today', 'calendar');
985 else if(
986 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
987 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
989 // Yesterday
990 return get_string('yesterday', 'calendar');
992 else if(
993 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
994 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
996 // Tomorrow
997 return get_string('tomorrow', 'calendar');
999 else {
1000 return $formal;
1005 * return the formatted representation time
1007 * @param int $time the timestamp in UTC, as obtained from the database
1008 * @return string the formatted date/time
1010 function calendar_time_representation($time) {
1011 static $langtimeformat = NULL;
1012 if($langtimeformat === NULL) {
1013 $langtimeformat = get_string('strftimetime');
1015 $timeformat = get_user_preferences('calendar_timeformat');
1016 if(empty($timeformat)){
1017 $timeformat = get_config(NULL,'calendar_site_timeformat');
1019 // The ? is needed because the preference might be present, but empty
1020 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1024 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1026 * @param string|moodle_url $linkbase
1027 * @param int $d The number of the day.
1028 * @param int $m The number of the month.
1029 * @param int $y The number of the year.
1030 * @return moodle_url|null $linkbase
1032 function calendar_get_link_href($linkbase, $d, $m, $y) {
1033 if (empty($linkbase)) {
1034 return '';
1036 if (!($linkbase instanceof moodle_url)) {
1037 $linkbase = new moodle_url();
1039 if (!empty($d)) {
1040 $linkbase->param('cal_d', $d);
1042 if (!empty($m)) {
1043 $linkbase->param('cal_m', $m);
1045 if (!empty($y)) {
1046 $linkbase->param('cal_y', $y);
1048 return $linkbase;
1052 * Build and return a previous month HTML link, with an arrow.
1054 * @param string $text The text label.
1055 * @param string|moodle_url $linkbase The URL stub.
1056 * @param int $d The number of the date.
1057 * @param int $m The number of the month.
1058 * @param int $y year The number of the year.
1059 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1060 * @return string HTML string.
1062 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
1063 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1064 if (empty($href)) {
1065 return $text;
1067 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1071 * Build and return a next month HTML link, with an arrow.
1073 * @param string $text The text label.
1074 * @param string|moodle_url $linkbase The URL stub.
1075 * @param int $d the number of the Day
1076 * @param int $m The number of the month.
1077 * @param int $y The number of the year.
1078 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1079 * @return string HTML string.
1081 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
1082 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1083 if (empty($href)) {
1084 return $text;
1086 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1090 * Return the name of the weekday
1092 * @param string $englishname
1093 * @return string of the weekeday
1095 function calendar_wday_name($englishname) {
1096 return get_string(strtolower($englishname), 'calendar');
1100 * Return the number of days in month
1102 * @param int $month the number of the month.
1103 * @param int $year the number of the year
1104 * @return int
1106 function calendar_days_in_month($month, $year) {
1107 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1111 * Get the upcoming event block
1113 * @param array $events list of events
1114 * @param moodle_url|string $linkhref link to event referer
1115 * @return string|null $content html block content
1117 function calendar_get_block_upcoming($events, $linkhref = NULL) {
1118 $content = '';
1119 $lines = count($events);
1120 if (!$lines) {
1121 return $content;
1124 for ($i = 0; $i < $lines; ++$i) {
1125 if (!isset($events[$i]->time)) { // Just for robustness
1126 continue;
1128 $events[$i] = calendar_add_event_metadata($events[$i]);
1129 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
1130 if (!empty($events[$i]->referer)) {
1131 // That's an activity event, so let's provide the hyperlink
1132 $content .= $events[$i]->referer;
1133 } else {
1134 if(!empty($linkhref)) {
1135 $ed = usergetdate($events[$i]->timestart);
1136 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1137 $href->set_anchor('event_'.$events[$i]->id);
1138 $content .= html_writer::link($href, $events[$i]->name);
1140 else {
1141 $content .= $events[$i]->name;
1144 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1145 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1146 if ($i < $lines - 1) $content .= '<hr />';
1149 return $content;
1153 * Get the next following month
1155 * If the current month is December, it will get the first month of the following year.
1158 * @param int $month the number of the month.
1159 * @param int $year the number of the year.
1160 * @return array the following month
1162 function calendar_add_month($month, $year) {
1163 if($month == 12) {
1164 return array(1, $year + 1);
1166 else {
1167 return array($month + 1, $year);
1172 * Get the previous month
1174 * If the current month is January, it will get the last month of the previous year.
1176 * @param int $month the number of the month.
1177 * @param int $year the number of the year.
1178 * @return array previous month
1180 function calendar_sub_month($month, $year) {
1181 if($month == 1) {
1182 return array(12, $year - 1);
1184 else {
1185 return array($month - 1, $year);
1190 * Get per-day basis events
1192 * @param array $events list of events
1193 * @param int $month the number of the month
1194 * @param int $year the number of the year
1195 * @param array $eventsbyday event on specific day
1196 * @param array $durationbyday duration of the event in days
1197 * @param array $typesbyday event type (eg: global, course, user, or group)
1198 * @param array $courses list of courses
1199 * @return void
1201 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1202 $eventsbyday = array();
1203 $typesbyday = array();
1204 $durationbyday = array();
1206 if($events === false) {
1207 return;
1210 foreach($events as $event) {
1212 $startdate = usergetdate($event->timestart);
1213 // Set end date = start date if no duration
1214 if ($event->timeduration) {
1215 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1216 } else {
1217 $enddate = $startdate;
1220 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1221 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1222 // Out of bounds
1223 continue;
1226 $eventdaystart = intval($startdate['mday']);
1228 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1229 // Give the event to its day
1230 $eventsbyday[$eventdaystart][] = $event->id;
1232 // Mark the day as having such an event
1233 if($event->courseid == SITEID && $event->groupid == 0) {
1234 $typesbyday[$eventdaystart]['startglobal'] = true;
1235 // Set event class for global event
1236 $events[$event->id]->class = 'calendar_event_global';
1238 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1239 $typesbyday[$eventdaystart]['startcourse'] = true;
1240 // Set event class for course event
1241 $events[$event->id]->class = 'calendar_event_course';
1243 else if($event->groupid) {
1244 $typesbyday[$eventdaystart]['startgroup'] = true;
1245 // Set event class for group event
1246 $events[$event->id]->class = 'calendar_event_group';
1248 else if($event->userid) {
1249 $typesbyday[$eventdaystart]['startuser'] = true;
1250 // Set event class for user event
1251 $events[$event->id]->class = 'calendar_event_user';
1255 if($event->timeduration == 0) {
1256 // Proceed with the next
1257 continue;
1260 // The event starts on $month $year or before. So...
1261 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1263 // Also, it ends on $month $year or later...
1264 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1266 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1267 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1268 $durationbyday[$i][] = $event->id;
1269 if($event->courseid == SITEID && $event->groupid == 0) {
1270 $typesbyday[$i]['durationglobal'] = true;
1272 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1273 $typesbyday[$i]['durationcourse'] = true;
1275 else if($event->groupid) {
1276 $typesbyday[$i]['durationgroup'] = true;
1278 else if($event->userid) {
1279 $typesbyday[$i]['durationuser'] = true;
1284 return;
1288 * Get current module cache
1290 * @param array $coursecache list of course cache
1291 * @param string $modulename name of the module
1292 * @param int $instance module instance number
1293 * @return stdClass|bool $module information
1295 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1296 $module = get_coursemodule_from_instance($modulename, $instance);
1298 if($module === false) return false;
1299 if(!calendar_get_course_cached($coursecache, $module->course)) {
1300 return false;
1302 return $module;
1306 * Get current course cache
1308 * @param array $coursecache list of course cache
1309 * @param int $courseid id of the course
1310 * @return stdClass $coursecache[$courseid] return the specific course cache
1312 function calendar_get_course_cached(&$coursecache, $courseid) {
1313 global $COURSE, $DB;
1315 if (!isset($coursecache[$courseid])) {
1316 if ($courseid == $COURSE->id) {
1317 $coursecache[$courseid] = $COURSE;
1318 } else {
1319 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
1322 return $coursecache[$courseid];
1326 * Returns the courses to load events for, the
1328 * @param array $courseeventsfrom An array of courses to load calendar events for
1329 * @param bool $ignorefilters specify the use of filters, false is set as default
1330 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1332 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1333 global $USER, $CFG, $DB;
1335 // For backwards compatability we have to check whether the courses array contains
1336 // just id's in which case we need to load course objects.
1337 $coursestoload = array();
1338 foreach ($courseeventsfrom as $id => $something) {
1339 if (!is_object($something)) {
1340 $coursestoload[] = $id;
1341 unset($courseeventsfrom[$id]);
1344 if (!empty($coursestoload)) {
1345 // TODO remove this in 2.2
1346 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
1347 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1350 $courses = array();
1351 $user = false;
1352 $group = false;
1354 // capabilities that allow seeing group events from all groups
1355 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1356 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1358 $isloggedin = isloggedin();
1360 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1361 $courses = array_keys($courseeventsfrom);
1363 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1364 $courses[] = SITEID;
1366 $courses = array_unique($courses);
1367 sort($courses);
1369 if (!empty($courses) && in_array(SITEID, $courses)) {
1370 // Sort courses for consistent colour highlighting
1371 // Effectively ignoring SITEID as setting as last course id
1372 $key = array_search(SITEID, $courses);
1373 unset($courses[$key]);
1374 $courses[] = SITEID;
1377 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1378 $user = $USER->id;
1381 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1383 if (count($courseeventsfrom)==1) {
1384 $course = reset($courseeventsfrom);
1385 if (has_any_capability($allgroupscaps, get_context_instance(CONTEXT_COURSE, $course->id))) {
1386 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
1387 $group = array_keys($coursegroups);
1390 if ($group === false) {
1391 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, get_system_context())) {
1392 $group = true;
1393 } else if ($isloggedin) {
1394 $groupids = array();
1396 // We already have the courses to examine in $courses
1397 // For each course...
1398 foreach ($courseeventsfrom as $courseid => $course) {
1399 // If the user is an editing teacher in there,
1400 if (!empty($USER->groupmember[$course->id])) {
1401 // We've already cached the users groups for this course so we can just use that
1402 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1403 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1404 // If this course has groups, show events from all of those related to the current user
1405 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1406 $groupids = array_merge($groupids, $coursegroups['0']);
1409 if (!empty($groupids)) {
1410 $group = $groupids;
1415 if (empty($courses)) {
1416 $courses = false;
1419 return array($courses, $group, $user);
1423 * Return the capability for editing calendar event
1425 * @param calendar_event $event event object
1426 * @return bool capability to edit event
1428 function calendar_edit_event_allowed($event) {
1429 global $USER, $DB;
1431 // Must be logged in
1432 if (!isloggedin()) {
1433 return false;
1436 // can not be using guest account
1437 if (isguestuser()) {
1438 return false;
1441 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1442 // if user has manageentries at site level, return true
1443 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1444 return true;
1447 // if groupid is set, it's definitely a group event
1448 if (!empty($event->groupid)) {
1449 // Allow users to add/edit group events if:
1450 // 1) They have manageentries (= entries for whole course)
1451 // 2) They have managegroupentries AND are in the group
1452 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1453 return $group && (
1454 has_capability('moodle/calendar:manageentries', $event->context) ||
1455 (has_capability('moodle/calendar:managegroupentries', $event->context)
1456 && groups_is_member($event->groupid)));
1457 } else if (!empty($event->courseid)) {
1458 // if groupid is not set, but course is set,
1459 // it's definiely a course event
1460 return has_capability('moodle/calendar:manageentries', $event->context);
1461 } else if (!empty($event->userid) && $event->userid == $USER->id) {
1462 // if course is not set, but userid id set, it's a user event
1463 return (has_capability('moodle/calendar:manageownentries', $event->context));
1464 } else if (!empty($event->userid)) {
1465 return (has_capability('moodle/calendar:manageentries', $event->context));
1467 return false;
1471 * Returns the default courses to display on the calendar when there isn't a specific
1472 * course to display.
1474 * @return array $courses Array of courses to display
1476 function calendar_get_default_courses() {
1477 global $CFG, $DB;
1479 if (!isloggedin()) {
1480 return array();
1483 $courses = array();
1484 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
1485 list ($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1486 $sql = "SELECT c.* $select
1487 FROM {course} c
1488 $join
1489 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1491 $courses = $DB->get_records_sql($sql, null, 0, 20);
1492 foreach ($courses as $course) {
1493 context_helper::preload_from_record($course);
1495 return $courses;
1498 $courses = enrol_get_my_courses();
1500 return $courses;
1504 * Display calendar preference button
1506 * @param stdClass $course course object
1507 * @return string return preference button in html
1509 function calendar_preferences_button(stdClass $course) {
1510 global $OUTPUT;
1512 // Guests have no preferences
1513 if (!isloggedin() || isguestuser()) {
1514 return '';
1517 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
1521 * Get event format time
1523 * @param calendar_event $event event object
1524 * @param int $now current time in gmt
1525 * @param array $linkparams list of params for event link
1526 * @param bool $usecommonwords the words as formatted date/time.
1527 * @param int $showtime determine the show time GMT timestamp
1528 * @return string $eventtime link/string for event time
1530 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
1531 $startdate = usergetdate($event->timestart);
1532 $enddate = usergetdate($event->timestart + $event->timeduration);
1533 $usermidnightstart = usergetmidnight($event->timestart);
1535 if($event->timeduration) {
1536 // To avoid doing the math if one IF is enough :)
1537 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1539 else {
1540 $usermidnightend = $usermidnightstart;
1543 if (empty($linkparams) || !is_array($linkparams)) {
1544 $linkparams = array();
1546 $linkparams['view'] = 'day';
1548 // OK, now to get a meaningful display...
1549 // First of all we have to construct a human-readable date/time representation
1551 if($event->timeduration) {
1552 // It has a duration
1553 if($usermidnightstart == $usermidnightend ||
1554 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1555 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
1556 // But it's all on the same day
1557 $timestart = calendar_time_representation($event->timestart);
1558 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1559 $time = $timestart.' <strong>&raquo;</strong> '.$timeend;
1561 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1562 $time = get_string('allday', 'calendar');
1565 // Set printable representation
1566 if (!$showtime) {
1567 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1568 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1569 $eventtime = html_writer::link($url, $day).', '.$time;
1570 } else {
1571 $eventtime = $time;
1573 } else {
1574 // It spans two or more days
1575 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1576 if ($showtime == $usermidnightstart) {
1577 $daystart = '';
1579 $timestart = calendar_time_representation($event->timestart);
1580 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1581 if ($showtime == $usermidnightend) {
1582 $dayend = '';
1584 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1586 // Set printable representation
1587 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
1588 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1589 $eventtime = $timestart.' <strong>&raquo;</strong> '.html_writer::link($url, $dayend).$timeend;
1590 } else {
1591 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1592 $eventtime = html_writer::link($url, $daystart).$timestart.' <strong>&raquo;</strong> ';
1594 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1595 $eventtime .= html_writer::link($url, $dayend).$timeend;
1598 } else {
1599 $time = calendar_time_representation($event->timestart);
1601 // Set printable representation
1602 if (!$showtime) {
1603 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1604 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1605 $eventtime = html_writer::link($url, $day).', '.trim($time);
1606 } else {
1607 $eventtime = $time;
1611 if($event->timestart + $event->timeduration < $now) {
1612 // It has expired
1613 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1616 return $eventtime;
1620 * Display month selector options
1622 * @param string $name for the select element
1623 * @param string|array $selected options for select elements
1625 function calendar_print_month_selector($name, $selected) {
1626 $months = array();
1627 for ($i=1; $i<=12; $i++) {
1628 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1630 echo html_writer::select($months, $name, $selected, false);
1634 * Checks to see if the requested type of event should be shown for the given user.
1636 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1637 * The type to check the display for (default is to display all)
1638 * @param stdClass|int|null $user The user to check for - by default the current user
1639 * @return bool True if the tyep should be displayed false otherwise
1641 function calendar_show_event_type($type, $user = null) {
1642 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1643 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1644 global $SESSION;
1645 if (!isset($SESSION->calendarshoweventtype)) {
1646 $SESSION->calendarshoweventtype = $default;
1648 return $SESSION->calendarshoweventtype & $type;
1649 } else {
1650 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1655 * Sets the display of the event type given $display.
1657 * If $display = true the event type will be shown.
1658 * If $display = false the event type will NOT be shown.
1659 * If $display = null the current value will be toggled and saved.
1661 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1662 * @param bool $display option to display event type
1663 * @param stdClass|int $user moodle user object or id, null means current user
1665 function calendar_set_event_type_display($type, $display = null, $user = null) {
1666 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1667 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1668 if ($persist === 0) {
1669 global $SESSION;
1670 if (!isset($SESSION->calendarshoweventtype)) {
1671 $SESSION->calendarshoweventtype = $default;
1673 $preference = $SESSION->calendarshoweventtype;
1674 } else {
1675 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1677 $current = $preference & $type;
1678 if ($display === null) {
1679 $display = !$current;
1681 if ($display && !$current) {
1682 $preference += $type;
1683 } else if (!$display && $current) {
1684 $preference -= $type;
1686 if ($persist === 0) {
1687 $SESSION->calendarshoweventtype = $preference;
1688 } else {
1689 if ($preference == $default) {
1690 unset_user_preference('calendar_savedflt', $user);
1691 } else {
1692 set_user_preference('calendar_savedflt', $preference, $user);
1698 * Get calendar's allowed types
1700 * @param stdClass $allowed list of allowed edit for event type
1701 * @param stdClass|int $course object of a course or course id
1703 function calendar_get_allowed_types(&$allowed, $course = null) {
1704 global $USER, $CFG, $DB;
1705 $allowed = new stdClass();
1706 $allowed->user = has_capability('moodle/calendar:manageownentries', get_system_context());
1707 $allowed->groups = false; // This may change just below
1708 $allowed->courses = false; // This may change just below
1709 $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1711 if (!empty($course)) {
1712 if (!is_object($course)) {
1713 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
1715 if ($course->id != SITEID) {
1716 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1717 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
1719 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1720 $allowed->courses = array($course->id => 1);
1722 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1723 $allowed->groups = groups_get_all_groups($course->id);
1725 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1726 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1727 $allowed->groups = groups_get_all_groups($course->id);
1735 * See if user can add calendar entries at all
1736 * used to print the "New Event" button
1738 * @param stdClass $course object of a course or course id
1739 * @return bool has the capability to add at least one event type
1741 function calendar_user_can_add_event($course) {
1742 if (!isloggedin() || isguestuser()) {
1743 return false;
1745 calendar_get_allowed_types($allowed, $course);
1746 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1750 * Check wether the current user is permitted to add events
1752 * @param stdClass $event object of event
1753 * @return bool has the capability to add event
1755 function calendar_add_event_allowed($event) {
1756 global $USER, $DB;
1758 // can not be using guest account
1759 if (!isloggedin() or isguestuser()) {
1760 return false;
1763 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1764 // if user has manageentries at site level, always return true
1765 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1766 return true;
1769 switch ($event->eventtype) {
1770 case 'course':
1771 return has_capability('moodle/calendar:manageentries', $event->context);
1773 case 'group':
1774 // Allow users to add/edit group events if:
1775 // 1) They have manageentries (= entries for whole course)
1776 // 2) They have managegroupentries AND are in the group
1777 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1778 return $group && (
1779 has_capability('moodle/calendar:manageentries', $event->context) ||
1780 (has_capability('moodle/calendar:managegroupentries', $event->context)
1781 && groups_is_member($event->groupid)));
1783 case 'user':
1784 if ($event->userid == $USER->id) {
1785 return (has_capability('moodle/calendar:manageownentries', $event->context));
1787 //there is no 'break;' intentionally
1789 case 'site':
1790 return has_capability('moodle/calendar:manageentries', $event->context);
1792 default:
1793 return has_capability('moodle/calendar:manageentries', $event->context);
1798 * Manage calendar events
1800 * This class provides the required functionality in order to manage calendar events.
1801 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1802 * better framework for dealing with calendar events in particular regard to file
1803 * handling through the new file API
1805 * @package core_calendar
1806 * @category calendar
1807 * @copyright 2009 Sam Hemelryk
1808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1810 * @property int $id The id within the event table
1811 * @property string $name The name of the event
1812 * @property string $description The description of the event
1813 * @property int $format The format of the description FORMAT_?
1814 * @property int $courseid The course the event is associated with (0 if none)
1815 * @property int $groupid The group the event is associated with (0 if none)
1816 * @property int $userid The user the event is associated with (0 if none)
1817 * @property int $repeatid If this is a repeated event this will be set to the
1818 * id of the original
1819 * @property string $modulename If added by a module this will be the module name
1820 * @property int $instance If added by a module this will be the module instance
1821 * @property string $eventtype The event type
1822 * @property int $timestart The start time as a timestamp
1823 * @property int $timeduration The duration of the event in seconds
1824 * @property int $visible 1 if the event is visible
1825 * @property int $uuid ?
1826 * @property int $sequence ?
1827 * @property int $timemodified The time last modified as a timestamp
1829 class calendar_event {
1831 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
1832 protected $properties = null;
1835 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
1836 protected $_description = null;
1838 /** @var array The options to use with this description editor */
1839 protected $editoroptions = array(
1840 'subdirs'=>false,
1841 'forcehttps'=>false,
1842 'maxfiles'=>-1,
1843 'maxbytes'=>null,
1844 'trusttext'=>false);
1846 /** @var object The context to use with the description editor */
1847 protected $editorcontext = null;
1850 * Instantiates a new event and optionally populates its properties with the
1851 * data provided
1853 * @param stdClass $data Optional. An object containing the properties to for
1854 * an event
1856 public function __construct($data=null) {
1857 global $CFG, $USER;
1859 // First convert to object if it is not already (should either be object or assoc array)
1860 if (!is_object($data)) {
1861 $data = (object)$data;
1864 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1866 $data->eventrepeats = 0;
1868 if (empty($data->id)) {
1869 $data->id = null;
1872 // Default to a user event
1873 if (empty($data->eventtype)) {
1874 $data->eventtype = 'user';
1877 // Default to the current user
1878 if (empty($data->userid)) {
1879 $data->userid = $USER->id;
1882 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1883 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1885 if (!empty($data->description) && is_array($data->description)) {
1886 $data->format = $data->description['format'];
1887 $data->description = $data->description['text'];
1888 } else if (empty($data->description)) {
1889 $data->description = '';
1890 $data->format = editors_get_preferred_format();
1892 // Ensure form is defaulted correctly
1893 if (empty($data->format)) {
1894 $data->format = editors_get_preferred_format();
1897 if (empty($data->context)) {
1898 $data->context = $this->calculate_context($data);
1900 $this->properties = $data;
1904 * Magic property method
1906 * Attempts to call a set_$key method if one exists otherwise falls back
1907 * to simply set the property
1909 * @param string $key property name
1910 * @param mixed $value value of the property
1912 public function __set($key, $value) {
1913 if (method_exists($this, 'set_'.$key)) {
1914 $this->{'set_'.$key}($value);
1916 $this->properties->{$key} = $value;
1920 * Magic get method
1922 * Attempts to call a get_$key method to return the property and ralls over
1923 * to return the raw property
1925 * @param string $key property name
1926 * @return mixed property value
1928 public function __get($key) {
1929 if (method_exists($this, 'get_'.$key)) {
1930 return $this->{'get_'.$key}();
1932 if (!isset($this->properties->{$key})) {
1933 throw new coding_exception('Undefined property requested');
1935 return $this->properties->{$key};
1939 * Stupid PHP needs an isset magic method if you use the get magic method and
1940 * still want empty calls to work.... blah ~!
1942 * @param string $key $key property name
1943 * @return bool|mixed property value, false if property is not exist
1945 public function __isset($key) {
1946 return !empty($this->properties->{$key});
1950 * Calculate the context value needed for calendar_event.
1951 * Event's type can be determine by the available value store in $data
1952 * It is important to check for the existence of course/courseid to determine
1953 * the course event.
1954 * Default value is set to CONTEXT_USER
1956 * @param stdClass $data information about event
1957 * @return stdClass The context object.
1959 protected function calculate_context(stdClass $data) {
1960 global $USER, $DB;
1962 $context = null;
1963 if (isset($data->courseid) && $data->courseid > 0) {
1964 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
1965 } else if (isset($data->course) && $data->course > 0) {
1966 $context = get_context_instance(CONTEXT_COURSE, $data->course);
1967 } else if (isset($data->groupid) && $data->groupid > 0) {
1968 $group = $DB->get_record('groups', array('id'=>$data->groupid));
1969 $context = get_context_instance(CONTEXT_COURSE, $group->courseid);
1970 } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
1971 $context = get_context_instance(CONTEXT_USER, $data->userid);
1972 } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
1973 isset($data->instance) && $data->instance > 0) {
1974 $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
1975 $context = get_context_instance(CONTEXT_COURSE, $cm->course);
1976 } else {
1977 $context = get_context_instance(CONTEXT_USER);
1980 return $context;
1984 * Returns an array of editoroptions for this event: Called by __get
1985 * Please use $blah = $event->editoroptions;
1987 * @return array event editor options
1989 protected function get_editoroptions() {
1990 return $this->editoroptions;
1994 * Returns an event description: Called by __get
1995 * Please use $blah = $event->description;
1997 * @return string event description
1999 protected function get_description() {
2000 global $CFG;
2002 require_once($CFG->libdir . '/filelib.php');
2004 if ($this->_description === null) {
2005 // Check if we have already resolved the context for this event
2006 if ($this->editorcontext === null) {
2007 // Switch on the event type to decide upon the appropriate context
2008 // to use for this event
2009 $this->editorcontext = $this->properties->context;
2010 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
2011 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
2012 return clean_text($this->properties->description, $this->properties->format);
2016 // Work out the item id for the editor, if this is a repeated event then the files will
2017 // be associated with the original
2018 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2019 $itemid = $this->properties->repeatid;
2020 } else {
2021 $itemid = $this->properties->id;
2024 // Convert file paths in the description so that things display correctly
2025 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
2026 // Clean the text so no nasties get through
2027 $this->_description = clean_text($this->_description, $this->properties->format);
2029 // Finally return the description
2030 return $this->_description;
2034 * Return the number of repeat events there are in this events series
2036 * @return int number of event repeated
2038 public function count_repeats() {
2039 global $DB;
2040 if (!empty($this->properties->repeatid)) {
2041 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
2042 // We don't want to count ourselves
2043 $this->properties->eventrepeats--;
2045 return $this->properties->eventrepeats;
2049 * Update or create an event within the database
2051 * Pass in a object containing the event properties and this function will
2052 * insert it into the database and deal with any associated files
2054 * @see add_event()
2055 * @see update_event()
2057 * @param stdClass $data object of event
2058 * @param bool $checkcapability if moodle should check calendar managing capability or not
2059 * @return bool event updated
2061 public function update($data, $checkcapability=true) {
2062 global $CFG, $DB, $USER;
2064 foreach ($data as $key=>$value) {
2065 $this->properties->$key = $value;
2068 $this->properties->timemodified = time();
2069 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
2071 if (empty($this->properties->id) || $this->properties->id < 1) {
2073 if ($checkcapability) {
2074 if (!calendar_add_event_allowed($this->properties)) {
2075 print_error('nopermissiontoupdatecalendar');
2079 if ($usingeditor) {
2080 switch ($this->properties->eventtype) {
2081 case 'user':
2082 $this->editorcontext = $this->properties->context;
2083 $this->properties->courseid = 0;
2084 $this->properties->groupid = 0;
2085 $this->properties->userid = $USER->id;
2086 break;
2087 case 'site':
2088 $this->editorcontext = $this->properties->context;
2089 $this->properties->courseid = SITEID;
2090 $this->properties->groupid = 0;
2091 $this->properties->userid = $USER->id;
2092 break;
2093 case 'course':
2094 $this->editorcontext = $this->properties->context;
2095 $this->properties->groupid = 0;
2096 $this->properties->userid = $USER->id;
2097 break;
2098 case 'group':
2099 $this->editorcontext = $this->properties->context;
2100 $this->properties->userid = $USER->id;
2101 break;
2102 default:
2103 // Ewww we should NEVER get here, but just incase we do lets
2104 // fail gracefully
2105 $usingeditor = false;
2106 break;
2109 $editor = $this->properties->description;
2110 $this->properties->format = $this->properties->description['format'];
2111 $this->properties->description = $this->properties->description['text'];
2114 // Insert the event into the database
2115 $this->properties->id = $DB->insert_record('event', $this->properties);
2117 if ($usingeditor) {
2118 $this->properties->description = file_save_draft_area_files(
2119 $editor['itemid'],
2120 $this->editorcontext->id,
2121 'calendar',
2122 'event_description',
2123 $this->properties->id,
2124 $this->editoroptions,
2125 $editor['text'],
2126 $this->editoroptions['forcehttps']);
2128 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2131 // Log the event entry.
2132 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2134 $repeatedids = array();
2136 if (!empty($this->properties->repeat)) {
2137 $this->properties->repeatid = $this->properties->id;
2138 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
2140 $eventcopy = clone($this->properties);
2141 unset($eventcopy->id);
2143 for($i = 1; $i < $eventcopy->repeats; $i++) {
2145 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
2147 // Get the event id for the log record.
2148 $eventcopyid = $DB->insert_record('event', $eventcopy);
2150 // If the context has been set delete all associated files
2151 if ($usingeditor) {
2152 $fs = get_file_storage();
2153 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2154 foreach ($files as $file) {
2155 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2159 $repeatedids[] = $eventcopyid;
2160 // Log the event entry.
2161 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
2165 // Hook for tracking added events
2166 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2167 return true;
2168 } else {
2170 if ($checkcapability) {
2171 if(!calendar_edit_event_allowed($this->properties)) {
2172 print_error('nopermissiontoupdatecalendar');
2176 if ($usingeditor) {
2177 if ($this->editorcontext !== null) {
2178 $this->properties->description = file_save_draft_area_files(
2179 $this->properties->description['itemid'],
2180 $this->editorcontext->id,
2181 'calendar',
2182 'event_description',
2183 $this->properties->id,
2184 $this->editoroptions,
2185 $this->properties->description['text'],
2186 $this->editoroptions['forcehttps']);
2187 } else {
2188 $this->properties->format = $this->properties->description['format'];
2189 $this->properties->description = $this->properties->description['text'];
2193 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2195 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2197 if ($updaterepeated) {
2198 // Update all
2199 if ($this->properties->timestart != $event->timestart) {
2200 $timestartoffset = $this->properties->timestart - $event->timestart;
2201 $sql = "UPDATE {event}
2202 SET name = ?,
2203 description = ?,
2204 timestart = timestart + ?,
2205 timeduration = ?,
2206 timemodified = ?
2207 WHERE repeatid = ?";
2208 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2209 } else {
2210 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2211 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2213 $DB->execute($sql, $params);
2215 // Log the event update.
2216 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2217 } else {
2218 $DB->update_record('event', $this->properties);
2219 $event = calendar_event::load($this->properties->id);
2220 $this->properties = $event->properties();
2221 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2224 // Hook for tracking event updates
2225 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2226 return true;
2231 * Deletes an event and if selected an repeated events in the same series
2233 * This function deletes an event, any associated events if $deleterepeated=true,
2234 * and cleans up any files associated with the events.
2236 * @see delete_event()
2238 * @param bool $deleterepeated delete event repeatedly
2239 * @return bool succession of deleting event
2241 public function delete($deleterepeated=false) {
2242 global $DB;
2244 // If $this->properties->id is not set then something is wrong
2245 if (empty($this->properties->id)) {
2246 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2247 return false;
2250 // Delete the event
2251 $DB->delete_records('event', array('id'=>$this->properties->id));
2253 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2254 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
2255 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties->id), IGNORE_MULTIPLE);
2256 if (!empty($newparent)) {
2257 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties->id));
2258 // Get all records where the repeatid is the same as the event being removed
2259 $events = $DB->get_records('event', array('repeatid' => $newparent));
2260 // For each of the returned events trigger the event_update hook.
2261 foreach ($events as $event) {
2262 self::calendar_event_hook('update_event', array($event, false));
2267 // If the editor context hasn't already been set then set it now
2268 if ($this->editorcontext === null) {
2269 $this->editorcontext = $this->properties->context;
2272 // If the context has been set delete all associated files
2273 if ($this->editorcontext !== null) {
2274 $fs = get_file_storage();
2275 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2276 foreach ($files as $file) {
2277 $file->delete();
2281 // Fire the event deleted hook
2282 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2284 // If we need to delete repeated events then we will fetch them all and delete one by one
2285 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2286 // Get all records where the repeatid is the same as the event being removed
2287 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2288 // For each of the returned events populate a calendar_event object and call delete
2289 // make sure the arg passed is false as we are already deleting all repeats
2290 foreach ($events as $event) {
2291 $event = new calendar_event($event);
2292 $event->delete(false);
2296 return true;
2300 * Fetch all event properties
2302 * This function returns all of the events properties as an object and optionally
2303 * can prepare an editor for the description field at the same time. This is
2304 * designed to work when the properties are going to be used to set the default
2305 * values of a moodle forms form.
2307 * @param bool $prepareeditor If set to true a editor is prepared for use with
2308 * the mforms editor element. (for description)
2309 * @return stdClass Object containing event properties
2311 public function properties($prepareeditor=false) {
2312 global $USER, $CFG, $DB;
2314 // First take a copy of the properties. We don't want to actually change the
2315 // properties or we'd forever be converting back and forwards between an
2316 // editor formatted description and not
2317 $properties = clone($this->properties);
2318 // Clean the description here
2319 $properties->description = clean_text($properties->description, $properties->format);
2321 // If set to true we need to prepare the properties for use with an editor
2322 // and prepare the file area
2323 if ($prepareeditor) {
2325 // We may or may not have a property id. If we do then we need to work
2326 // out the context so we can copy the existing files to the draft area
2327 if (!empty($properties->id)) {
2329 if ($properties->eventtype === 'site') {
2330 // Site context
2331 $this->editorcontext = $this->properties->context;
2332 } else if ($properties->eventtype === 'user') {
2333 // User context
2334 $this->editorcontext = $this->properties->context;
2335 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2336 // First check the course is valid
2337 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2338 if (!$course) {
2339 print_error('invalidcourse');
2341 // Course context
2342 $this->editorcontext = $this->properties->context;
2343 // We have a course and are within the course context so we had
2344 // better use the courses max bytes value
2345 $this->editoroptions['maxbytes'] = $course->maxbytes;
2346 } else {
2347 // If we get here we have a custom event type as used by some
2348 // modules. In this case the event will have been added by
2349 // code and we won't need the editor
2350 $this->editoroptions['maxbytes'] = 0;
2351 $this->editoroptions['maxfiles'] = 0;
2354 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2355 $contextid = false;
2356 } else {
2357 // Get the context id that is what we really want
2358 $contextid = $this->editorcontext->id;
2360 } else {
2362 // If we get here then this is a new event in which case we don't need a
2363 // context as there is no existing files to copy to the draft area.
2364 $contextid = null;
2367 // If the contextid === false we don't support files so no preparing
2368 // a draft area
2369 if ($contextid !== false) {
2370 // Just encase it has already been submitted
2371 $draftiddescription = file_get_submitted_draft_itemid('description');
2372 // Prepare the draft area, this copies existing files to the draft area as well
2373 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
2374 } else {
2375 $draftiddescription = 0;
2378 // Structure the description field as the editor requires
2379 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2382 // Finally return the properties
2383 return $properties;
2387 * Toggles the visibility of an event
2389 * @param null|bool $force If it is left null the events visibility is flipped,
2390 * If it is false the event is made hidden, if it is true it
2391 * is made visible.
2392 * @return bool if event is successfully updated, toggle will be visible
2394 public function toggle_visibility($force=null) {
2395 global $CFG, $DB;
2397 // Set visible to the default if it is not already set
2398 if (empty($this->properties->visible)) {
2399 $this->properties->visible = 1;
2402 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2403 // Make this event visible
2404 $this->properties->visible = 1;
2405 // Fire the hook
2406 self::calendar_event_hook('show_event', array($this->properties));
2407 } else {
2408 // Make this event hidden
2409 $this->properties->visible = 0;
2410 // Fire the hook
2411 self::calendar_event_hook('hide_event', array($this->properties));
2414 // Update the database to reflect this change
2415 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2419 * Attempts to call the hook for the specified action should a calendar type
2420 * by set $CFG->calendar, and the appopriate function defined
2422 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2423 * @param array $args The args to pass to the hook, usually the event is the first element
2424 * @return bool attempts to call event hook
2426 public static function calendar_event_hook($action, array $args) {
2427 global $CFG;
2428 static $extcalendarinc;
2429 if ($extcalendarinc === null) {
2430 if (!empty($CFG->calendar) && file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2431 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2432 $extcalendarinc = true;
2433 } else {
2434 $extcalendarinc = false;
2437 if($extcalendarinc === false) {
2438 return false;
2440 $hook = $CFG->calendar .'_'.$action;
2441 if (function_exists($hook)) {
2442 call_user_func_array($hook, $args);
2443 return true;
2445 return false;
2449 * Returns a calendar_event object when provided with an event id
2451 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2452 * it will result in an exception being thrown
2454 * @param int|object $param event object or event id
2455 * @return calendar_event|false status for loading calendar_event
2457 public static function load($param) {
2458 global $DB;
2459 if (is_object($param)) {
2460 $event = new calendar_event($param);
2461 } else {
2462 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2463 $event = new calendar_event($event);
2465 return $event;
2469 * Creates a new event and returns a calendar_event object
2471 * @param object|array $properties An object containing event properties
2472 * @return calendar_event|false The event object or false if it failed
2474 public static function create($properties) {
2475 if (is_array($properties)) {
2476 $properties = (object)$properties;
2478 if (!is_object($properties)) {
2479 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2481 $event = new calendar_event($properties);
2482 if ($event->update($properties)) {
2483 return $event;
2484 } else {
2485 return false;
2491 * Calendar information class
2493 * This class is used simply to organise the information pertaining to a calendar
2494 * and is used primarily to make information easily available.
2496 * @package core_calendar
2497 * @category calendar
2498 * @copyright 2010 Sam Hemelryk
2499 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2501 class calendar_information {
2502 /** @var int The day */
2503 public $day;
2505 /** @var int The month */
2506 public $month;
2508 /** @var int The year */
2509 public $year;
2511 /** @var int A course id */
2512 public $courseid = null;
2514 /** @var array An array of courses */
2515 public $courses = array();
2517 /** @var array An array of groups */
2518 public $groups = array();
2520 /** @var array An array of users */
2521 public $users = array();
2524 * Creates a new instance
2526 * @param int $day the number of the day
2527 * @param int $month the number of the month
2528 * @param int $year the number of the year
2530 public function __construct($day=0, $month=0, $year=0) {
2532 $date = usergetdate(time());
2534 if (empty($day)) {
2535 $day = $date['mday'];
2538 if (empty($month)) {
2539 $month = $date['mon'];
2542 if (empty($year)) {
2543 $year = $date['year'];
2546 $this->day = $day;
2547 $this->month = $month;
2548 $this->year = $year;
2552 * Initialize calendar information
2554 * @param stdClass $course object
2555 * @param array $coursestoload An array of courses [$course->id => $course]
2556 * @param bool $ignorefilters options to use filter
2558 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
2559 $this->courseid = $course->id;
2560 $this->course = $course;
2561 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2562 $this->courses = $courses;
2563 $this->groups = $group;
2564 $this->users = $user;
2568 * Ensures the date for the calendar is correct and either sets it to now
2569 * or throws a moodle_exception if not
2571 * @param bool $defaultonow use current time
2572 * @throws moodle_exception
2573 * @return bool validation of checkdate
2575 public function checkdate($defaultonow = true) {
2576 if (!checkdate($this->month, $this->day, $this->year)) {
2577 if ($defaultonow) {
2578 $now = usergetdate(time());
2579 $this->day = intval($now['mday']);
2580 $this->month = intval($now['mon']);
2581 $this->year = intval($now['year']);
2582 return true;
2583 } else {
2584 throw new moodle_exception('invaliddate');
2587 return true;
2590 * Gets todays timestamp for the calendar
2592 * @return int today timestamp
2594 public function timestamp_today() {
2595 return make_timestamp($this->year, $this->month, $this->day);
2598 * Gets tomorrows timestamp for the calendar
2600 * @return int tomorrow timestamp
2602 public function timestamp_tomorrow() {
2603 return make_timestamp($this->year, $this->month, $this->day+1);
2606 * Adds the pretend blocks for teh calendar
2608 * @param core_calendar_renderer $renderer
2609 * @param bool $showfilters display filters, false is set as default
2610 * @param string|null $view preference view options (eg: day, month, upcoming)
2612 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2613 if ($showfilters) {
2614 $filters = new block_contents();
2615 $filters->content = $renderer->fake_block_filters($this->courseid, $this->day, $this->month, $this->year, $view, $this->courses);
2616 $filters->footer = '';
2617 $filters->title = get_string('eventskey', 'calendar');
2618 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2620 $block = new block_contents;
2621 $block->content = $renderer->fake_block_threemonths($this);
2622 $block->footer = '';
2623 $block->title = get_string('monthlyview', 'calendar');
2624 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);