Merge branch 'MDL-32693' of git://github.com/danpoltawski/moodle
[moodle.git] / calendar / lib.php
blob7280f14c7a85d1124017b383cfd2ffed0954b39d
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 $summary = get_string('tabledata', 'access', $summary);
246 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
247 $content .= '<tr class="weekdays">'; // Header row: day names
249 // Print out the names of the weekdays
250 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
251 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
252 // This uses the % operator to get the correct weekday no matter what shift we have
253 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
254 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
255 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
258 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
260 // For the table display. $week is the row; $dayweek is the column.
261 $dayweek = $startwday;
263 // Paddding (the first week may have blank days in the beginning)
264 for($i = $display->minwday; $i < $startwday; ++$i) {
265 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
268 $weekend = CALENDAR_DEFAULT_WEEKEND;
269 if (isset($CFG->calendar_weekend)) {
270 $weekend = intval($CFG->calendar_weekend);
273 // Now display all the calendar
274 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
275 if($dayweek > $display->maxwday) {
276 // We need to change week (table row)
277 $content .= '</tr><tr>';
278 $dayweek = $display->minwday;
281 // Reset vars
282 $cell = '';
283 if ($weekend & (1 << ($dayweek % 7))) {
284 // Weekend. This is true no matter what the exact range is.
285 $class = 'weekend day';
286 } else {
287 // Normal working day.
288 $class = 'day';
291 // Special visual fx if an event is defined
292 if(isset($eventsbyday[$day])) {
293 $class .= ' hasevent';
294 $hrefparams['view'] = 'day';
295 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $hrefparams), $day, $m, $y);
297 $popupcontent = '';
298 foreach($eventsbyday[$day] as $eventid) {
299 if (!isset($events[$eventid])) {
300 continue;
302 $event = $events[$eventid];
303 $popupalt = '';
304 $component = 'moodle';
305 if(!empty($event->modulename)) {
306 $popupicon = 'icon';
307 $popupalt = $event->modulename;
308 $component = $event->modulename;
309 } else if ($event->courseid == SITEID) { // Site event
310 $popupicon = 'c/site';
311 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
312 $popupicon = 'c/course';
313 } else if ($event->groupid) { // Group event
314 $popupicon = 'c/group';
315 } else if ($event->userid) { // User event
316 $popupicon = 'c/user';
319 $dayhref->set_anchor('event_'.$event->id);
321 $popupcontent .= html_writer::start_tag('div');
322 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
323 $popupcontent .= html_writer::link($dayhref, format_string($event->name, true));
324 $popupcontent .= html_writer::end_tag('div');
327 //Accessibility: functionality moved to calendar_get_popup.
328 if($display->thismonth && $day == $d) {
329 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
330 } else {
331 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
334 // Class and cell content
335 if(isset($typesbyday[$day]['startglobal'])) {
336 $class .= ' calendar_event_global';
337 } else if(isset($typesbyday[$day]['startcourse'])) {
338 $class .= ' calendar_event_course';
339 } else if(isset($typesbyday[$day]['startgroup'])) {
340 $class .= ' calendar_event_group';
341 } else if(isset($typesbyday[$day]['startuser'])) {
342 $class .= ' calendar_event_user';
344 $cell = '<a href="'.(string)$dayhref.'" '.$popup.'>'.$day.'</a>';
345 } else {
346 $cell = $day;
349 $durationclass = false;
350 if (isset($typesbyday[$day]['durationglobal'])) {
351 $durationclass = ' duration_global';
352 } else if(isset($typesbyday[$day]['durationcourse'])) {
353 $durationclass = ' duration_course';
354 } else if(isset($typesbyday[$day]['durationgroup'])) {
355 $durationclass = ' duration_group';
356 } else if(isset($typesbyday[$day]['durationuser'])) {
357 $durationclass = ' duration_user';
359 if ($durationclass) {
360 $class .= ' duration '.$durationclass;
363 // If event has a class set then add it to the table day <td> tag
364 // Note: only one colour for minicalendar
365 if(isset($eventsbyday[$day])) {
366 foreach($eventsbyday[$day] as $eventid) {
367 if (!isset($events[$eventid])) {
368 continue;
370 $event = $events[$eventid];
371 if (!empty($event->class)) {
372 $class .= ' '.$event->class;
374 break;
378 // Special visual fx for today
379 //Accessibility: hidden text for today, and popup.
380 if($display->thismonth && $day == $d) {
381 $class .= ' today';
382 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
384 if(! isset($eventsbyday[$day])) {
385 $class .= ' eventnone';
386 $popup = calendar_get_popup(true, false);
387 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
389 $cell = get_accesshide($today.' ').$cell;
392 // Just display it
393 if(!empty($class)) {
394 $class = ' class="'.$class.'"';
396 $content .= '<td'.$class.'>'.$cell."</td>\n";
399 // Paddding (the last week may have blank days at the end)
400 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
401 $content .= '<td class="dayblank">&nbsp;</td>';
403 $content .= '</tr>'; // Last row ends
405 $content .= '</table>'; // Tabular display of days ends
407 return $content;
411 * Gets the calendar popup
413 * It called at multiple points in from calendar_get_mini.
414 * Copied and modified from calendar_get_mini.
416 * @param bool $is_today false except when called on the current day.
417 * @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
418 * @param string $popupcontent content for the popup window/layout
419 * @return string of eventid for the calendar_tooltip popup window/layout
421 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
422 global $PAGE;
423 static $popupcount;
424 if ($popupcount === null) {
425 $popupcount = 1;
427 $popupcaption = '';
428 if($is_today) {
429 $popupcaption = get_string('today', 'calendar').' ';
431 if (false === $event_timestart) {
432 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
433 $popupcontent = get_string('eventnone', 'calendar');
435 } else {
436 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
438 $id = 'calendar_tooltip_'.$popupcount;
439 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
441 $popupcount++;
442 return 'id="'.$id.'"';
446 * Gets the calendar upcoming event
448 * @param array $courses array of courses
449 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
450 * @param array|int|bool $users array of users, user id or boolean for all/no user events
451 * @param int $daysinfuture number of days in the future we 'll look
452 * @param int $maxevents maximum number of events
453 * @param int $fromtime start time
454 * @return array $output array of upcoming events
456 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
457 global $CFG, $COURSE, $DB;
459 $display = new stdClass;
460 $display->range = $daysinfuture; // How many days in the future we 'll look
461 $display->maxevents = $maxevents;
463 $output = array();
465 // Prepare "course caching", since it may save us a lot of queries
466 $coursecache = array();
468 $processed = 0;
469 $now = time(); // We 'll need this later
470 $usermidnighttoday = usergetmidnight($now);
472 if ($fromtime) {
473 $display->tstart = $fromtime;
474 } else {
475 $display->tstart = $usermidnighttoday;
478 // This works correctly with respect to the user's DST, but it is accurate
479 // only because $fromtime is always the exact midnight of some day!
480 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
482 // Get the events matching our criteria
483 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
485 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
486 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
487 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
488 // arguments to this function.
490 $hrefparams = array();
491 if(!empty($courses)) {
492 $courses = array_diff($courses, array(SITEID));
493 if(count($courses) == 1) {
494 $hrefparams['course'] = reset($courses);
498 if ($events !== false) {
500 $modinfo = get_fast_modinfo($COURSE);
502 foreach($events as $event) {
505 if (!empty($event->modulename)) {
506 if ($event->courseid == $COURSE->id) {
507 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
508 $cm = $modinfo->instances[$event->modulename][$event->instance];
509 if (!$cm->uservisible) {
510 continue;
513 } else {
514 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
515 continue;
517 if (!coursemodule_visible_for_user($cm)) {
518 continue;
521 if ($event->modulename == 'assignment'){
522 // create calendar_event to test edit_event capability
523 // this new event will also prevent double creation of calendar_event object
524 $checkevent = new calendar_event($event);
525 // TODO: rewrite this hack somehow
526 if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
527 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
528 // print_error("invalidid", 'assignment');
529 continue;
531 // assign assignment to assignment object to use hidden_is_hidden method
532 require_once($CFG->dirroot.'/mod/assignment/lib.php');
534 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
535 continue;
537 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
539 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
540 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
542 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
543 $event->description = get_string('notavailableyet', 'assignment');
549 if ($processed >= $display->maxevents) {
550 break;
553 $event->time = calendar_format_event_time($event, $now, $hrefparams);
554 $output[] = $event;
555 ++$processed;
558 return $output;
562 * Add calendar event metadata
564 * @param stdClass $event event info
565 * @return stdClass $event metadata
567 function calendar_add_event_metadata($event) {
568 global $CFG, $OUTPUT;
570 //Support multilang in event->name
571 $event->name = format_string($event->name,true);
573 if(!empty($event->modulename)) { // Activity event
574 // The module name is set. I will assume that it has to be displayed, and
575 // also that it is an automatically-generated event. And of course that the
576 // fields for get_coursemodule_from_instance are set correctly.
577 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
579 if ($module === false) {
580 return;
583 $modulename = get_string('modulename', $event->modulename);
584 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
585 // will be used as alt text if the event icon
586 $eventtype = get_string($event->eventtype, $event->modulename);
587 } else {
588 $eventtype = '';
590 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
592 $context = get_context_instance(CONTEXT_COURSE, $module->course);
593 $fullname = format_string($coursecache[$module->course]->fullname, true, array('context' => $context));
595 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
596 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
597 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$fullname.'</a>';
598 $event->cmid = $module->id;
601 } else if($event->courseid == SITEID) { // Site event
602 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
603 $event->cssclass = 'calendar_event_global';
604 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
605 calendar_get_course_cached($coursecache, $event->courseid);
607 $context = get_context_instance(CONTEXT_COURSE, $event->courseid);
608 $fullname = format_string($coursecache[$event->courseid]->fullname, true, array('context' => $context));
610 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
611 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$fullname.'</a>';
612 $event->cssclass = 'calendar_event_course';
613 } else if ($event->groupid) { // Group event
614 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
615 $event->cssclass = 'calendar_event_group';
616 } else if($event->userid) { // User event
617 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
618 $event->cssclass = 'calendar_event_user';
620 return $event;
624 * Prints a calendar event
626 * @deprecated Moodle 2.0 - MDL-22887 please do not use this function any more.
627 * @todo MDL-31133 - will be removed in Moodle 2.3
628 * @see core_calendar_renderer event function
630 function calendar_print_event($event, $showactions=true) {
631 global $CFG, $USER, $OUTPUT, $PAGE;
632 debugging('calendar_print_event is deprecated please update your code', DEBUG_DEVELOPER);
633 $renderer = $PAGE->get_renderer('core_calendar');
634 if (!($event instanceof calendar_event)) {
635 $event = new calendar_event($event);
637 echo $renderer->event($event);
641 * Get calendar events
643 * @param int $tstart Start time of time range for events
644 * @param int $tend End time of time range for events
645 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
646 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
647 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
648 * @param boolean $withduration whether only events starting within time range selected
649 * or events in progress/already started selected as well
650 * @param boolean $ignorehidden whether to select only visible events or all events
651 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
653 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
654 global $DB;
656 $whereclause = '';
657 // Quick test
658 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
659 return array();
662 if(is_array($users) && !empty($users)) {
663 // Events from a number of users
664 if(!empty($whereclause)) $whereclause .= ' OR';
665 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
666 } else if(is_numeric($users)) {
667 // Events from one user
668 if(!empty($whereclause)) $whereclause .= ' OR';
669 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
670 } else if($users === true) {
671 // Events from ALL users
672 if(!empty($whereclause)) $whereclause .= ' OR';
673 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
674 } else if($users === false) {
675 // No user at all, do nothing
678 if(is_array($groups) && !empty($groups)) {
679 // Events from a number of groups
680 if(!empty($whereclause)) $whereclause .= ' OR';
681 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
682 } else if(is_numeric($groups)) {
683 // Events from one group
684 if(!empty($whereclause)) $whereclause .= ' OR ';
685 $whereclause .= ' groupid = '.$groups;
686 } else if($groups === true) {
687 // Events from ALL groups
688 if(!empty($whereclause)) $whereclause .= ' OR ';
689 $whereclause .= ' groupid != 0';
691 // boolean false (no groups at all): we don't need to do anything
693 if(is_array($courses) && !empty($courses)) {
694 if(!empty($whereclause)) {
695 $whereclause .= ' OR';
697 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
698 } else if(is_numeric($courses)) {
699 // One course
700 if(!empty($whereclause)) $whereclause .= ' OR';
701 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
702 } else if ($courses === true) {
703 // Events from ALL courses
704 if(!empty($whereclause)) $whereclause .= ' OR';
705 $whereclause .= ' (groupid = 0 AND courseid != 0)';
708 // Security check: if, by now, we have NOTHING in $whereclause, then it means
709 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
710 // events no matter what. Allowing the code to proceed might return a completely
711 // valid query with only time constraints, thus selecting ALL events in that time frame!
712 if(empty($whereclause)) {
713 return array();
716 if($withduration) {
717 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
719 else {
720 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
722 if(!empty($whereclause)) {
723 // We have additional constraints
724 $whereclause = $timeclause.' AND ('.$whereclause.')';
726 else {
727 // Just basic time filtering
728 $whereclause = $timeclause;
731 if ($ignorehidden) {
732 $whereclause .= ' AND visible = 1';
735 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
736 if ($events === false) {
737 $events = array();
739 return $events;
743 * Get control options for Calendar
745 * @param string $type of calendar
746 * @param array $data calendar information
747 * @return string $content return available control for the calender in html
749 function calendar_top_controls($type, $data) {
750 global $CFG;
751 $content = '';
752 if(!isset($data['d'])) {
753 $data['d'] = 1;
756 // Ensure course id passed if relevant
757 // Required due to changes in view/lib.php mainly (calendar_session_vars())
758 $courseid = '';
759 if (!empty($data['id'])) {
760 $courseid = '&amp;course='.$data['id'];
763 if(!checkdate($data['m'], $data['d'], $data['y'])) {
764 $time = time();
766 else {
767 $time = make_timestamp($data['y'], $data['m'], $data['d']);
769 $date = usergetdate($time);
771 $data['m'] = $date['mon'];
772 $data['y'] = $date['year'];
774 //Accessibility: calendar block controls, replaced <table> with <div>.
775 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
776 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
778 switch($type) {
779 case 'frontpage':
780 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
781 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
782 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
783 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
785 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
786 if (!empty($data['id'])) {
787 $calendarlink->param('course', $data['id']);
790 if (right_to_left()) {
791 $left = $nextlink;
792 $right = $prevlink;
793 } else {
794 $left = $prevlink;
795 $right = $nextlink;
798 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
799 $content .= $left.'<span class="hide"> | </span>';
800 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
801 $content .= '<span class="hide"> | </span>'. $right;
802 $content .= "<span class=\"clearer\"><!-- --></span>\n";
803 $content .= html_writer::end_tag('div');
805 break;
806 case 'course':
807 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
808 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
809 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
810 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);
812 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
813 if (!empty($data['id'])) {
814 $calendarlink->param('course', $data['id']);
817 if (right_to_left()) {
818 $left = $nextlink;
819 $right = $prevlink;
820 } else {
821 $left = $prevlink;
822 $right = $nextlink;
825 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
826 $content .= $left.'<span class="hide"> | </span>';
827 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
828 $content .= '<span class="hide"> | </span>'. $right;
829 $content .= "<span class=\"clearer\"><!-- --></span>";
830 $content .= html_writer::end_tag('div');
831 break;
832 case 'upcoming':
833 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
834 if (!empty($data['id'])) {
835 $calendarlink->param('course', $data['id']);
837 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
838 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
839 break;
840 case 'display':
841 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
842 if (!empty($data['id'])) {
843 $calendarlink->param('course', $data['id']);
845 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
846 $content .= html_writer::tag('h3', $calendarlink);
847 break;
848 case 'month':
849 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
850 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
851 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
852 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
853 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
854 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
856 if (right_to_left()) {
857 $left = $nextlink;
858 $right = $prevlink;
859 } else {
860 $left = $prevlink;
861 $right = $nextlink;
864 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
865 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
866 $content .= '<span class="hide"> | </span>' . $right;
867 $content .= '<span class="clearer"><!-- --></span>';
868 $content .= html_writer::end_tag('div')."\n";
869 break;
870 case 'day':
871 $days = calendar_get_days();
872 $data['d'] = $date['mday']; // Just for convenience
873 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
874 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
875 $prevname = calendar_wday_name($days[$prevdate['wday']]);
876 $nextname = calendar_wday_name($days[$nextdate['wday']]);
877 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
878 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
880 if (right_to_left()) {
881 $left = $nextlink;
882 $right = $prevlink;
883 } else {
884 $left = $prevlink;
885 $right = $nextlink;
888 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
889 $content .= $left;
890 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
891 $content .= '<span class="hide"> | </span>'. $right;
892 $content .= "<span class=\"clearer\"><!-- --></span>";
893 $content .= html_writer::end_tag('div')."\n";
895 break;
897 return $content;
901 * Get the controls filter for calendar.
903 * Filter is used to hide calendar info from the display page
905 * @param moodle_url $returnurl return-url for filter controls
906 * @return string $content return filter controls in html
908 function calendar_filter_controls(moodle_url $returnurl) {
909 global $CFG, $USER, $OUTPUT;
911 $groupevents = true;
913 $id = optional_param( 'id',0,PARAM_INT );
915 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));
917 $content = '<table>';
918 $content .= '<tr>';
920 $seturl->param('var', 'showglobal');
921 if (calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
922 $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>';
923 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
924 } else {
925 $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>';
926 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
929 $seturl->param('var', 'showcourses');
930 if (calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
931 $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>';
932 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
933 } else {
934 $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>';
935 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
938 if (isloggedin() && !isguestuser()) {
939 $content .= "</tr>\n<tr>";
941 if ($groupevents) {
942 // This course MIGHT have group events defined, so show the filter
943 $seturl->param('var', 'showgroups');
944 if (calendar_show_event_type(CALENDAR_EVENT_GROUP)) {
945 $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>';
946 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
947 } else {
948 $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>';
949 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
951 } else {
952 // This course CANNOT have group events, so lose the filter
953 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
956 $seturl->param('var', 'showuser');
957 if (calendar_show_event_type(CALENDAR_EVENT_USER)) {
958 $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>';
959 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
960 } else {
961 $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>';
962 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
965 $content .= "</tr>\n</table>\n";
967 return $content;
971 * Return the representation day
973 * @param int $tstamp Timestamp in GMT
974 * @param int $now current Unix timestamp
975 * @param bool $usecommonwords
976 * @return string the formatted date/time
978 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
980 static $shortformat;
981 if(empty($shortformat)) {
982 $shortformat = get_string('strftimedayshort');
985 if($now === false) {
986 $now = time();
989 // To have it in one place, if a change is needed
990 $formal = userdate($tstamp, $shortformat);
992 $datestamp = usergetdate($tstamp);
993 $datenow = usergetdate($now);
995 if($usecommonwords == false) {
996 // We don't want words, just a date
997 return $formal;
999 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1000 // Today
1001 return get_string('today', 'calendar');
1003 else if(
1004 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1005 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
1007 // Yesterday
1008 return get_string('yesterday', 'calendar');
1010 else if(
1011 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1012 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
1014 // Tomorrow
1015 return get_string('tomorrow', 'calendar');
1017 else {
1018 return $formal;
1023 * return the formatted representation time
1025 * @param int $time the timestamp in UTC, as obtained from the database
1026 * @return string the formatted date/time
1028 function calendar_time_representation($time) {
1029 static $langtimeformat = NULL;
1030 if($langtimeformat === NULL) {
1031 $langtimeformat = get_string('strftimetime');
1033 $timeformat = get_user_preferences('calendar_timeformat');
1034 if(empty($timeformat)){
1035 $timeformat = get_config(NULL,'calendar_site_timeformat');
1037 // The ? is needed because the preference might be present, but empty
1038 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1042 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1044 * @param string|moodle_url $linkbase
1045 * @param int $d The number of the day.
1046 * @param int $m The number of the month.
1047 * @param int $y The number of the year.
1048 * @return moodle_url|null $linkbase
1050 function calendar_get_link_href($linkbase, $d, $m, $y) {
1051 if (empty($linkbase)) {
1052 return '';
1054 if (!($linkbase instanceof moodle_url)) {
1055 $linkbase = new moodle_url();
1057 if (!empty($d)) {
1058 $linkbase->param('cal_d', $d);
1060 if (!empty($m)) {
1061 $linkbase->param('cal_m', $m);
1063 if (!empty($y)) {
1064 $linkbase->param('cal_y', $y);
1066 return $linkbase;
1070 * This function has been deprecated as of Moodle 2.0... DO NOT USE!!!!!
1072 * @deprecated Moodle 2.0 - MDL-24284 please do not use this function any more.
1073 * @todo MDL-31134 - will be removed in Moodle 2.3
1074 * @see calendar_get_link_href()
1076 * @param string $text
1077 * @param string|moodle_url $linkbase
1078 * @param int|null $d The number of the day.
1079 * @param int|null $m The number of the month.
1080 * @param int|null $y The number of the year.
1081 * @return string HTML link
1083 function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
1084 $url = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1085 if (empty($url)) {
1086 return $text;
1088 return html_writer::link($url, $text);
1092 * Build and return a previous month HTML link, with an arrow.
1094 * @param string $text The text label.
1095 * @param string|moodle_url $linkbase The URL stub.
1096 * @param int $d The number of the date.
1097 * @param int $m The number of the month.
1098 * @param int $y year The number of the year.
1099 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1100 * @return string HTML string.
1102 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
1103 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1104 if (empty($href)) {
1105 return $text;
1107 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1111 * Build and return a next month HTML link, with an arrow.
1113 * @param string $text The text label.
1114 * @param string|moodle_url $linkbase The URL stub.
1115 * @param int $d the number of the Day
1116 * @param int $m The number of the month.
1117 * @param int $y The number of the year.
1118 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1119 * @return string HTML string.
1121 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
1122 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1123 if (empty($href)) {
1124 return $text;
1126 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1130 * Return the name of the weekday
1132 * @param string $englishname
1133 * @return string of the weekeday
1135 function calendar_wday_name($englishname) {
1136 return get_string(strtolower($englishname), 'calendar');
1140 * Return the number of days in month
1142 * @param int $month the number of the month.
1143 * @param int $year the number of the year
1144 * @return int
1146 function calendar_days_in_month($month, $year) {
1147 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1151 * Get the upcoming event block
1153 * @param array $events list of events
1154 * @param moodle_url|string $linkhref link to event referer
1155 * @return string|null $content html block content
1157 function calendar_get_block_upcoming($events, $linkhref = NULL) {
1158 $content = '';
1159 $lines = count($events);
1160 if (!$lines) {
1161 return $content;
1164 for ($i = 0; $i < $lines; ++$i) {
1165 if (!isset($events[$i]->time)) { // Just for robustness
1166 continue;
1168 $events[$i] = calendar_add_event_metadata($events[$i]);
1169 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
1170 if (!empty($events[$i]->referer)) {
1171 // That's an activity event, so let's provide the hyperlink
1172 $content .= $events[$i]->referer;
1173 } else {
1174 if(!empty($linkhref)) {
1175 $ed = usergetdate($events[$i]->timestart);
1176 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1177 $href->set_anchor('event_'.$events[$i]->id);
1178 $content .= html_writer::link($href, $events[$i]->name);
1180 else {
1181 $content .= $events[$i]->name;
1184 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1185 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1186 if ($i < $lines - 1) $content .= '<hr />';
1189 return $content;
1193 * Get the next following month
1195 * If the current month is December, it will get the first month of the following year.
1198 * @param int $month the number of the month.
1199 * @param int $year the number of the year.
1200 * @return array the following month
1202 function calendar_add_month($month, $year) {
1203 if($month == 12) {
1204 return array(1, $year + 1);
1206 else {
1207 return array($month + 1, $year);
1212 * Get the previous month
1214 * If the current month is January, it will get the last month of the previous year.
1216 * @param int $month the number of the month.
1217 * @param int $year the number of the year.
1218 * @return array previous month
1220 function calendar_sub_month($month, $year) {
1221 if($month == 1) {
1222 return array(12, $year - 1);
1224 else {
1225 return array($month - 1, $year);
1230 * Get per-day basis events
1232 * @param array $events list of events
1233 * @param int $month the number of the month
1234 * @param int $year the number of the year
1235 * @param array $eventsbyday event on specific day
1236 * @param array $durationbyday duration of the event in days
1237 * @param array $typesbyday event type (eg: global, course, user, or group)
1238 * @param array $courses list of courses
1239 * @return void
1241 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1242 $eventsbyday = array();
1243 $typesbyday = array();
1244 $durationbyday = array();
1246 if($events === false) {
1247 return;
1250 foreach($events as $event) {
1252 $startdate = usergetdate($event->timestart);
1253 // Set end date = start date if no duration
1254 if ($event->timeduration) {
1255 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1256 } else {
1257 $enddate = $startdate;
1260 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1261 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1262 // Out of bounds
1263 continue;
1266 $eventdaystart = intval($startdate['mday']);
1268 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1269 // Give the event to its day
1270 $eventsbyday[$eventdaystart][] = $event->id;
1272 // Mark the day as having such an event
1273 if($event->courseid == SITEID && $event->groupid == 0) {
1274 $typesbyday[$eventdaystart]['startglobal'] = true;
1275 // Set event class for global event
1276 $events[$event->id]->class = 'calendar_event_global';
1278 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1279 $typesbyday[$eventdaystart]['startcourse'] = true;
1280 // Set event class for course event
1281 $events[$event->id]->class = 'calendar_event_course';
1283 else if($event->groupid) {
1284 $typesbyday[$eventdaystart]['startgroup'] = true;
1285 // Set event class for group event
1286 $events[$event->id]->class = 'calendar_event_group';
1288 else if($event->userid) {
1289 $typesbyday[$eventdaystart]['startuser'] = true;
1290 // Set event class for user event
1291 $events[$event->id]->class = 'calendar_event_user';
1295 if($event->timeduration == 0) {
1296 // Proceed with the next
1297 continue;
1300 // The event starts on $month $year or before. So...
1301 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1303 // Also, it ends on $month $year or later...
1304 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1306 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1307 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1308 $durationbyday[$i][] = $event->id;
1309 if($event->courseid == SITEID && $event->groupid == 0) {
1310 $typesbyday[$i]['durationglobal'] = true;
1312 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1313 $typesbyday[$i]['durationcourse'] = true;
1315 else if($event->groupid) {
1316 $typesbyday[$i]['durationgroup'] = true;
1318 else if($event->userid) {
1319 $typesbyday[$i]['durationuser'] = true;
1324 return;
1328 * Get current module cache
1330 * @param array $coursecache list of course cache
1331 * @param string $modulename name of the module
1332 * @param int $instance module instance number
1333 * @return stdClass|bool $module information
1335 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1336 $module = get_coursemodule_from_instance($modulename, $instance);
1338 if($module === false) return false;
1339 if(!calendar_get_course_cached($coursecache, $module->course)) {
1340 return false;
1342 return $module;
1346 * Get current course cache
1348 * @param array $coursecache list of course cache
1349 * @param int $courseid id of the course
1350 * @return stdClass $coursecache[$courseid] return the specific course cache
1352 function calendar_get_course_cached(&$coursecache, $courseid) {
1353 global $COURSE, $DB;
1355 if (!isset($coursecache[$courseid])) {
1356 if ($courseid == $COURSE->id) {
1357 $coursecache[$courseid] = $COURSE;
1358 } else {
1359 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
1362 return $coursecache[$courseid];
1366 * Returns the courses to load events for, the
1368 * @param array $courseeventsfrom An array of courses to load calendar events for
1369 * @param bool $ignorefilters specify the use of filters, false is set as default
1370 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1372 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1373 global $USER, $CFG, $DB;
1375 // For backwards compatability we have to check whether the courses array contains
1376 // just id's in which case we need to load course objects.
1377 $coursestoload = array();
1378 foreach ($courseeventsfrom as $id => $something) {
1379 if (!is_object($something)) {
1380 $coursestoload[] = $id;
1381 unset($courseeventsfrom[$id]);
1384 if (!empty($coursestoload)) {
1385 // TODO remove this in 2.2
1386 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
1387 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1390 $courses = array();
1391 $user = false;
1392 $group = false;
1394 $isloggedin = isloggedin();
1396 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1397 $courses = array_keys($courseeventsfrom);
1399 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1400 $courses[] = SITEID;
1402 $courses = array_unique($courses);
1403 sort($courses);
1405 if (!empty($courses) && in_array(SITEID, $courses)) {
1406 // Sort courses for consistent colour highlighting
1407 // Effectively ignoring SITEID as setting as last course id
1408 $key = array_search(SITEID, $courses);
1409 unset($courses[$key]);
1410 $courses[] = SITEID;
1413 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1414 $user = $USER->id;
1417 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1419 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', get_system_context())) {
1420 $group = true;
1421 } else if ($isloggedin) {
1422 $groupids = array();
1424 // We already have the courses to examine in $courses
1425 // For each course...
1426 foreach ($courseeventsfrom as $courseid => $course) {
1427 // If the user is an editing teacher in there,
1428 if (!empty($USER->groupmember[$course->id])) {
1429 // We've already cached the users groups for this course so we can just use that
1430 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1431 } else if (($course->groupmode != NOGROUPS || !$course->groupmodeforce) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $course->id))) {
1432 // If this course has groups, show events from all of them
1433 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1434 $groupids = array_merge($groupids, $coursegroups['0']);
1437 if (!empty($groupids)) {
1438 $group = $groupids;
1442 if (empty($courses)) {
1443 $courses = false;
1446 return array($courses, $group, $user);
1450 * Return the capability for editing calendar event
1452 * @param calendar_event $event event object
1453 * @return bool capability to edit event
1455 function calendar_edit_event_allowed($event) {
1456 global $USER, $DB;
1458 // Must be logged in
1459 if (!isloggedin()) {
1460 return false;
1463 // can not be using guest account
1464 if (isguestuser()) {
1465 return false;
1468 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1469 // if user has manageentries at site level, return true
1470 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1471 return true;
1474 // if groupid is set, it's definitely a group event
1475 if (!empty($event->groupid)) {
1476 // Allow users to add/edit group events if:
1477 // 1) They have manageentries (= entries for whole course)
1478 // 2) They have managegroupentries AND are in the group
1479 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1480 return $group && (
1481 has_capability('moodle/calendar:manageentries', $event->context) ||
1482 (has_capability('moodle/calendar:managegroupentries', $event->context)
1483 && groups_is_member($event->groupid)));
1484 } else if (!empty($event->courseid)) {
1485 // if groupid is not set, but course is set,
1486 // it's definiely a course event
1487 return has_capability('moodle/calendar:manageentries', $event->context);
1488 } else if (!empty($event->userid) && $event->userid == $USER->id) {
1489 // if course is not set, but userid id set, it's a user event
1490 return (has_capability('moodle/calendar:manageownentries', $event->context));
1491 } else if (!empty($event->userid)) {
1492 return (has_capability('moodle/calendar:manageentries', $event->context));
1494 return false;
1498 * Returns the default courses to display on the calendar when there isn't a specific
1499 * course to display.
1501 * @return array $courses Array of courses to display
1503 function calendar_get_default_courses() {
1504 global $CFG, $DB;
1506 if (!isloggedin()) {
1507 return array();
1510 $courses = array();
1511 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
1512 list ($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1513 $sql = "SELECT DISTINCT c.* $select
1514 FROM {course} c
1515 JOIN {event} e ON e.courseid = c.id
1516 $join";
1517 $courses = $DB->get_records_sql($sql, null, 0, 20);
1518 foreach ($courses as $course) {
1519 context_instance_preload($course);
1521 return $courses;
1524 $courses = enrol_get_my_courses();
1526 return $courses;
1530 * Display calendar preference button
1532 * @param stdClass $course course object
1533 * @return string return preference button in html
1535 function calendar_preferences_button(stdClass $course) {
1536 global $OUTPUT;
1538 // Guests have no preferences
1539 if (!isloggedin() || isguestuser()) {
1540 return '';
1543 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
1547 * Get event format time
1549 * @param calendar_event $event event object
1550 * @param int $now current time in gmt
1551 * @param array $linkparams list of params for event link
1552 * @param bool $usecommonwords the words as formatted date/time.
1553 * @param int $showtime determine the show time GMT timestamp
1554 * @return string $eventtime link/string for event time
1556 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
1557 $startdate = usergetdate($event->timestart);
1558 $enddate = usergetdate($event->timestart + $event->timeduration);
1559 $usermidnightstart = usergetmidnight($event->timestart);
1561 if($event->timeduration) {
1562 // To avoid doing the math if one IF is enough :)
1563 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1565 else {
1566 $usermidnightend = $usermidnightstart;
1569 if (empty($linkparams) || !is_array($linkparams)) {
1570 $linkparams = array();
1572 $linkparams['view'] = 'day';
1574 // OK, now to get a meaningful display...
1575 // First of all we have to construct a human-readable date/time representation
1577 if($event->timeduration) {
1578 // It has a duration
1579 if($usermidnightstart == $usermidnightend ||
1580 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1581 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
1582 // But it's all on the same day
1583 $timestart = calendar_time_representation($event->timestart);
1584 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1585 $time = $timestart.' <strong>&raquo;</strong> '.$timeend;
1587 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1588 $time = get_string('allday', 'calendar');
1591 // Set printable representation
1592 if (!$showtime) {
1593 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1594 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1595 $eventtime = html_writer::link($url, $day).', '.$time;
1596 } else {
1597 $eventtime = $time;
1599 } else {
1600 // It spans two or more days
1601 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1602 if ($showtime == $usermidnightstart) {
1603 $daystart = '';
1605 $timestart = calendar_time_representation($event->timestart);
1606 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1607 if ($showtime == $usermidnightend) {
1608 $dayend = '';
1610 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1612 // Set printable representation
1613 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
1614 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1615 $eventtime = $timestart.' <strong>&raquo;</strong> '.html_writer::link($url, $dayend).$timeend;
1616 } else {
1617 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1618 $eventtime = html_writer::link($url, $daystart).$timestart.' <strong>&raquo;</strong> ';
1620 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1621 $eventtime .= html_writer::link($url, $dayend).$timeend;
1624 } else {
1625 $time = calendar_time_representation($event->timestart);
1627 // Set printable representation
1628 if (!$showtime) {
1629 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1630 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1631 $eventtime = html_writer::link($url, $day).', '.trim($time);
1632 } else {
1633 $eventtime = $time;
1637 if($event->timestart + $event->timeduration < $now) {
1638 // It has expired
1639 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1642 return $eventtime;
1646 * Display month selector options
1648 * @param string $name for the select element
1649 * @param string|array $selected options for select elements
1651 function calendar_print_month_selector($name, $selected) {
1652 $months = array();
1653 for ($i=1; $i<=12; $i++) {
1654 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1656 echo html_writer::select($months, $name, $selected, false);
1660 * Checks to see if the requested type of event should be shown for the given user.
1662 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1663 * The type to check the display for (default is to display all)
1664 * @param stdClass|int|null $user The user to check for - by default the current user
1665 * @return bool True if the tyep should be displayed false otherwise
1667 function calendar_show_event_type($type, $user = null) {
1668 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1669 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1670 global $SESSION;
1671 if (!isset($SESSION->calendarshoweventtype)) {
1672 $SESSION->calendarshoweventtype = $default;
1674 return $SESSION->calendarshoweventtype & $type;
1675 } else {
1676 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1681 * Sets the display of the event type given $display.
1683 * If $display = true the event type will be shown.
1684 * If $display = false the event type will NOT be shown.
1685 * If $display = null the current value will be toggled and saved.
1687 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1688 * @param bool $display option to display event type
1689 * @param stdClass|int $user moodle user object or id, null means current user
1691 function calendar_set_event_type_display($type, $display = null, $user = null) {
1692 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1693 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1694 if ($persist === 0) {
1695 global $SESSION;
1696 if (!isset($SESSION->calendarshoweventtype)) {
1697 $SESSION->calendarshoweventtype = $default;
1699 $preference = $SESSION->calendarshoweventtype;
1700 } else {
1701 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1703 $current = $preference & $type;
1704 if ($display === null) {
1705 $display = !$current;
1707 if ($display && !$current) {
1708 $preference += $type;
1709 } else if (!$display && $current) {
1710 $preference -= $type;
1712 if ($persist === 0) {
1713 $SESSION->calendarshoweventtype = $preference;
1714 } else {
1715 if ($preference == $default) {
1716 unset_user_preference('calendar_savedflt', $user);
1717 } else {
1718 set_user_preference('calendar_savedflt', $preference, $user);
1724 * Get calendar's allowed types
1726 * @param stdClass $allowed list of allowed edit for event type
1727 * @param stdClass|int $course object of a course or course id
1729 function calendar_get_allowed_types(&$allowed, $course = null) {
1730 global $USER, $CFG, $DB;
1731 $allowed = new stdClass();
1732 $allowed->user = has_capability('moodle/calendar:manageownentries', get_system_context());
1733 $allowed->groups = false; // This may change just below
1734 $allowed->courses = false; // This may change just below
1735 $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1737 if (!empty($course)) {
1738 if (!is_object($course)) {
1739 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
1741 if ($course->id != SITEID) {
1742 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1744 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1745 $allowed->courses = array($course->id => 1);
1747 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1748 $allowed->groups = groups_get_all_groups($course->id);
1750 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1751 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1752 $allowed->groups = groups_get_all_groups($course->id);
1760 * See if user can add calendar entries at all
1761 * used to print the "New Event" button
1763 * @param stdClass $course object of a course or course id
1764 * @return bool has the capability to add at least one event type
1766 function calendar_user_can_add_event($course) {
1767 if (!isloggedin() || isguestuser()) {
1768 return false;
1770 calendar_get_allowed_types($allowed, $course);
1771 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1775 * Check wether the current user is permitted to add events
1777 * @param stdClass $event object of event
1778 * @return bool has the capability to add event
1780 function calendar_add_event_allowed($event) {
1781 global $USER, $DB;
1783 // can not be using guest account
1784 if (!isloggedin() or isguestuser()) {
1785 return false;
1788 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1789 // if user has manageentries at site level, always return true
1790 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1791 return true;
1794 switch ($event->eventtype) {
1795 case 'course':
1796 return has_capability('moodle/calendar:manageentries', $event->context);
1798 case 'group':
1799 // Allow users to add/edit group events if:
1800 // 1) They have manageentries (= entries for whole course)
1801 // 2) They have managegroupentries AND are in the group
1802 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1803 return $group && (
1804 has_capability('moodle/calendar:manageentries', $event->context) ||
1805 (has_capability('moodle/calendar:managegroupentries', $event->context)
1806 && groups_is_member($event->groupid)));
1808 case 'user':
1809 if ($event->userid == $USER->id) {
1810 return (has_capability('moodle/calendar:manageownentries', $event->context));
1812 //there is no 'break;' intentionally
1814 case 'site':
1815 return has_capability('moodle/calendar:manageentries', $event->context);
1817 default:
1818 return has_capability('moodle/calendar:manageentries', $event->context);
1823 * Manage calendar events
1825 * This class provides the required functionality in order to manage calendar events.
1826 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1827 * better framework for dealing with calendar events in particular regard to file
1828 * handling through the new file API
1830 * @package core_calendar
1831 * @category calendar
1832 * @copyright 2009 Sam Hemelryk
1833 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1835 * @property int $id The id within the event table
1836 * @property string $name The name of the event
1837 * @property string $description The description of the event
1838 * @property int $format The format of the description FORMAT_?
1839 * @property int $courseid The course the event is associated with (0 if none)
1840 * @property int $groupid The group the event is associated with (0 if none)
1841 * @property int $userid The user the event is associated with (0 if none)
1842 * @property int $repeatid If this is a repeated event this will be set to the
1843 * id of the original
1844 * @property string $modulename If added by a module this will be the module name
1845 * @property int $instance If added by a module this will be the module instance
1846 * @property string $eventtype The event type
1847 * @property int $timestart The start time as a timestamp
1848 * @property int $timeduration The duration of the event in seconds
1849 * @property int $visible 1 if the event is visible
1850 * @property int $uuid ?
1851 * @property int $sequence ?
1852 * @property int $timemodified The time last modified as a timestamp
1854 class calendar_event {
1856 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
1857 protected $properties = null;
1860 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
1861 protected $_description = null;
1863 /** @var array The options to use with this description editor */
1864 protected $editoroptions = array(
1865 'subdirs'=>false,
1866 'forcehttps'=>false,
1867 'maxfiles'=>-1,
1868 'maxbytes'=>null,
1869 'trusttext'=>false);
1871 /** @var object The context to use with the description editor */
1872 protected $editorcontext = null;
1875 * Instantiates a new event and optionally populates its properties with the
1876 * data provided
1878 * @param stdClass $data Optional. An object containing the properties to for
1879 * an event
1881 public function __construct($data=null) {
1882 global $CFG, $USER;
1884 // First convert to object if it is not already (should either be object or assoc array)
1885 if (!is_object($data)) {
1886 $data = (object)$data;
1889 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1891 $data->eventrepeats = 0;
1893 if (empty($data->id)) {
1894 $data->id = null;
1897 // Default to a user event
1898 if (empty($data->eventtype)) {
1899 $data->eventtype = 'user';
1902 // Default to the current user
1903 if (empty($data->userid)) {
1904 $data->userid = $USER->id;
1907 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1908 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1910 if (!empty($data->description) && is_array($data->description)) {
1911 $data->format = $data->description['format'];
1912 $data->description = $data->description['text'];
1913 } else if (empty($data->description)) {
1914 $data->description = '';
1915 $data->format = editors_get_preferred_format();
1917 // Ensure form is defaulted correctly
1918 if (empty($data->format)) {
1919 $data->format = editors_get_preferred_format();
1922 if (empty($data->context)) {
1923 $data->context = $this->calculate_context($data);
1925 $this->properties = $data;
1929 * Magic property method
1931 * Attempts to call a set_$key method if one exists otherwise falls back
1932 * to simply set the property
1934 * @param string $key property name
1935 * @param mixed $value value of the property
1937 public function __set($key, $value) {
1938 if (method_exists($this, 'set_'.$key)) {
1939 $this->{'set_'.$key}($value);
1941 $this->properties->{$key} = $value;
1945 * Magic get method
1947 * Attempts to call a get_$key method to return the property and ralls over
1948 * to return the raw property
1950 * @param string $key property name
1951 * @return mixed property value
1953 public function __get($key) {
1954 if (method_exists($this, 'get_'.$key)) {
1955 return $this->{'get_'.$key}();
1957 if (!isset($this->properties->{$key})) {
1958 throw new coding_exception('Undefined property requested');
1960 return $this->properties->{$key};
1964 * Stupid PHP needs an isset magic method if you use the get magic method and
1965 * still want empty calls to work.... blah ~!
1967 * @param string $key $key property name
1968 * @return bool|mixed property value, false if property is not exist
1970 public function __isset($key) {
1971 return !empty($this->properties->{$key});
1975 * Calculate the context value needed for calendar_event.
1976 * Event's type can be determine by the available value store in $data
1977 * It is important to check for the existence of course/courseid to determine
1978 * the course event.
1979 * Default value is set to CONTEXT_USER
1981 * @param stdClass $data information about event
1982 * @return stdClass The context object.
1984 protected function calculate_context(stdClass $data) {
1985 global $USER, $DB;
1987 $context = null;
1988 if (isset($data->courseid) && $data->courseid > 0) {
1989 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
1990 } else if (isset($data->course) && $data->course > 0) {
1991 $context = get_context_instance(CONTEXT_COURSE, $data->course);
1992 } else if (isset($data->groupid) && $data->groupid > 0) {
1993 $group = $DB->get_record('groups', array('id'=>$data->groupid));
1994 $context = get_context_instance(CONTEXT_COURSE, $group->courseid);
1995 } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
1996 $context = get_context_instance(CONTEXT_USER, $data->userid);
1997 } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
1998 isset($data->instance) && $data->instance > 0) {
1999 $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
2000 $context = get_context_instance(CONTEXT_COURSE, $cm->course);
2001 } else {
2002 $context = get_context_instance(CONTEXT_USER);
2005 return $context;
2009 * Returns an array of editoroptions for this event: Called by __get
2010 * Please use $blah = $event->editoroptions;
2012 * @return array event editor options
2014 protected function get_editoroptions() {
2015 return $this->editoroptions;
2019 * Returns an event description: Called by __get
2020 * Please use $blah = $event->description;
2022 * @return string event description
2024 protected function get_description() {
2025 global $CFG;
2027 require_once($CFG->libdir . '/filelib.php');
2029 if ($this->_description === null) {
2030 // Check if we have already resolved the context for this event
2031 if ($this->editorcontext === null) {
2032 // Switch on the event type to decide upon the appropriate context
2033 // to use for this event
2034 $this->editorcontext = $this->properties->context;
2035 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
2036 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
2037 return clean_text($this->properties->description, $this->properties->format);
2041 // Work out the item id for the editor, if this is a repeated event then the files will
2042 // be associated with the original
2043 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2044 $itemid = $this->properties->repeatid;
2045 } else {
2046 $itemid = $this->properties->id;
2049 // Convert file paths in the description so that things display correctly
2050 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
2051 // Clean the text so no nasties get through
2052 $this->_description = clean_text($this->_description, $this->properties->format);
2054 // Finally return the description
2055 return $this->_description;
2059 * Return the number of repeat events there are in this events series
2061 * @return int number of event repeated
2063 public function count_repeats() {
2064 global $DB;
2065 if (!empty($this->properties->repeatid)) {
2066 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
2067 // We don't want to count ourselves
2068 $this->properties->eventrepeats--;
2070 return $this->properties->eventrepeats;
2074 * Update or create an event within the database
2076 * Pass in a object containing the event properties and this function will
2077 * insert it into the database and deal with any associated files
2079 * @see add_event()
2080 * @see update_event()
2082 * @param stdClass $data object of event
2083 * @param bool $checkcapability if moodle should check calendar managing capability or not
2084 * @return bool event updated
2086 public function update($data, $checkcapability=true) {
2087 global $CFG, $DB, $USER;
2089 foreach ($data as $key=>$value) {
2090 $this->properties->$key = $value;
2093 $this->properties->timemodified = time();
2094 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
2096 if (empty($this->properties->id) || $this->properties->id < 1) {
2098 if ($checkcapability) {
2099 if (!calendar_add_event_allowed($this->properties)) {
2100 print_error('nopermissiontoupdatecalendar');
2104 if ($usingeditor) {
2105 switch ($this->properties->eventtype) {
2106 case 'user':
2107 $this->editorcontext = $this->properties->context;
2108 $this->properties->courseid = 0;
2109 $this->properties->groupid = 0;
2110 $this->properties->userid = $USER->id;
2111 break;
2112 case 'site':
2113 $this->editorcontext = $this->properties->context;
2114 $this->properties->courseid = SITEID;
2115 $this->properties->groupid = 0;
2116 $this->properties->userid = $USER->id;
2117 break;
2118 case 'course':
2119 $this->editorcontext = $this->properties->context;
2120 $this->properties->groupid = 0;
2121 $this->properties->userid = $USER->id;
2122 break;
2123 case 'group':
2124 $this->editorcontext = $this->properties->context;
2125 $this->properties->userid = $USER->id;
2126 break;
2127 default:
2128 // Ewww we should NEVER get here, but just incase we do lets
2129 // fail gracefully
2130 $usingeditor = false;
2131 break;
2134 $editor = $this->properties->description;
2135 $this->properties->format = $this->properties->description['format'];
2136 $this->properties->description = $this->properties->description['text'];
2139 // Insert the event into the database
2140 $this->properties->id = $DB->insert_record('event', $this->properties);
2142 if ($usingeditor) {
2143 $this->properties->description = file_save_draft_area_files(
2144 $editor['itemid'],
2145 $this->editorcontext->id,
2146 'calendar',
2147 'event_description',
2148 $this->properties->id,
2149 $this->editoroptions,
2150 $editor['text'],
2151 $this->editoroptions['forcehttps']);
2153 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2156 // Log the event entry.
2157 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2159 $repeatedids = array();
2161 if (!empty($this->properties->repeat)) {
2162 $this->properties->repeatid = $this->properties->id;
2163 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
2165 $eventcopy = clone($this->properties);
2166 unset($eventcopy->id);
2168 for($i = 1; $i < $eventcopy->repeats; $i++) {
2170 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
2172 // Get the event id for the log record.
2173 $eventcopyid = $DB->insert_record('event', $eventcopy);
2175 // If the context has been set delete all associated files
2176 if ($usingeditor) {
2177 $fs = get_file_storage();
2178 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2179 foreach ($files as $file) {
2180 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2184 $repeatedids[] = $eventcopyid;
2185 // Log the event entry.
2186 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
2190 // Hook for tracking added events
2191 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2192 return true;
2193 } else {
2195 if ($checkcapability) {
2196 if(!calendar_edit_event_allowed($this->properties)) {
2197 print_error('nopermissiontoupdatecalendar');
2201 if ($usingeditor) {
2202 if ($this->editorcontext !== null) {
2203 $this->properties->description = file_save_draft_area_files(
2204 $this->properties->description['itemid'],
2205 $this->editorcontext->id,
2206 'calendar',
2207 'event_description',
2208 $this->properties->id,
2209 $this->editoroptions,
2210 $this->properties->description['text'],
2211 $this->editoroptions['forcehttps']);
2212 } else {
2213 $this->properties->format = $this->properties->description['format'];
2214 $this->properties->description = $this->properties->description['text'];
2218 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2220 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2222 if ($updaterepeated) {
2223 // Update all
2224 if ($this->properties->timestart != $event->timestart) {
2225 $timestartoffset = $this->properties->timestart - $event->timestart;
2226 $sql = "UPDATE {event}
2227 SET name = ?,
2228 description = ?,
2229 timestart = timestart + ?,
2230 timeduration = ?,
2231 timemodified = ?
2232 WHERE repeatid = ?";
2233 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2234 } else {
2235 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2236 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2238 $DB->execute($sql, $params);
2240 // Log the event update.
2241 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2242 } else {
2243 $DB->update_record('event', $this->properties);
2244 $event = calendar_event::load($this->properties->id);
2245 $this->properties = $event->properties();
2246 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2249 // Hook for tracking event updates
2250 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2251 return true;
2256 * Deletes an event and if selected an repeated events in the same series
2258 * This function deletes an event, any associated events if $deleterepeated=true,
2259 * and cleans up any files associated with the events.
2261 * @see delete_event()
2263 * @param bool $deleterepeated delete event repeatedly
2264 * @return bool succession of deleting event
2266 public function delete($deleterepeated=false) {
2267 global $DB;
2269 // If $this->properties->id is not set then something is wrong
2270 if (empty($this->properties->id)) {
2271 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2272 return false;
2275 // Delete the event
2276 $DB->delete_records('event', array('id'=>$this->properties->id));
2278 // If the editor context hasn't already been set then set it now
2279 if ($this->editorcontext === null) {
2280 $this->editorcontext = $this->properties->context;
2283 // If the context has been set delete all associated files
2284 if ($this->editorcontext !== null) {
2285 $fs = get_file_storage();
2286 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2287 foreach ($files as $file) {
2288 $file->delete();
2292 // Fire the event deleted hook
2293 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2295 // If we need to delete repeated events then we will fetch them all and delete one by one
2296 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2297 // Get all records where the repeatid is the same as the event being removed
2298 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2299 // For each of the returned events populate a calendar_event object and call delete
2300 // make sure the arg passed is false as we are already deleting all repeats
2301 foreach ($events as $event) {
2302 $event = new calendar_event($event);
2303 $event->delete(false);
2307 return true;
2311 * Fetch all event properties
2313 * This function returns all of the events properties as an object and optionally
2314 * can prepare an editor for the description field at the same time. This is
2315 * designed to work when the properties are going to be used to set the default
2316 * values of a moodle forms form.
2318 * @param bool $prepareeditor If set to true a editor is prepared for use with
2319 * the mforms editor element. (for description)
2320 * @return stdClass Object containing event properties
2322 public function properties($prepareeditor=false) {
2323 global $USER, $CFG, $DB;
2325 // First take a copy of the properties. We don't want to actually change the
2326 // properties or we'd forever be converting back and forwards between an
2327 // editor formatted description and not
2328 $properties = clone($this->properties);
2329 // Clean the description here
2330 $properties->description = clean_text($properties->description, $properties->format);
2332 // If set to true we need to prepare the properties for use with an editor
2333 // and prepare the file area
2334 if ($prepareeditor) {
2336 // We may or may not have a property id. If we do then we need to work
2337 // out the context so we can copy the existing files to the draft area
2338 if (!empty($properties->id)) {
2340 if ($properties->eventtype === 'site') {
2341 // Site context
2342 $this->editorcontext = $this->properties->context;
2343 } else if ($properties->eventtype === 'user') {
2344 // User context
2345 $this->editorcontext = $this->properties->context;
2346 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2347 // First check the course is valid
2348 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2349 if (!$course) {
2350 print_error('invalidcourse');
2352 // Course context
2353 $this->editorcontext = $this->properties->context;
2354 // We have a course and are within the course context so we had
2355 // better use the courses max bytes value
2356 $this->editoroptions['maxbytes'] = $course->maxbytes;
2357 } else {
2358 // If we get here we have a custom event type as used by some
2359 // modules. In this case the event will have been added by
2360 // code and we won't need the editor
2361 $this->editoroptions['maxbytes'] = 0;
2362 $this->editoroptions['maxfiles'] = 0;
2365 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2366 $contextid = false;
2367 } else {
2368 // Get the context id that is what we really want
2369 $contextid = $this->editorcontext->id;
2371 } else {
2373 // If we get here then this is a new event in which case we don't need a
2374 // context as there is no existing files to copy to the draft area.
2375 $contextid = null;
2378 // If the contextid === false we don't support files so no preparing
2379 // a draft area
2380 if ($contextid !== false) {
2381 // Just encase it has already been submitted
2382 $draftiddescription = file_get_submitted_draft_itemid('description');
2383 // Prepare the draft area, this copies existing files to the draft area as well
2384 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
2385 } else {
2386 $draftiddescription = 0;
2389 // Structure the description field as the editor requires
2390 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2393 // Finally return the properties
2394 return $properties;
2398 * Toggles the visibility of an event
2400 * @param null|bool $force If it is left null the events visibility is flipped,
2401 * If it is false the event is made hidden, if it is true it
2402 * is made visible.
2403 * @return bool if event is successfully updated, toggle will be visible
2405 public function toggle_visibility($force=null) {
2406 global $CFG, $DB;
2408 // Set visible to the default if it is not already set
2409 if (empty($this->properties->visible)) {
2410 $this->properties->visible = 1;
2413 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2414 // Make this event visible
2415 $this->properties->visible = 1;
2416 // Fire the hook
2417 self::calendar_event_hook('show_event', array($this->properties));
2418 } else {
2419 // Make this event hidden
2420 $this->properties->visible = 0;
2421 // Fire the hook
2422 self::calendar_event_hook('hide_event', array($this->properties));
2425 // Update the database to reflect this change
2426 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2430 * Attempts to call the hook for the specified action should a calendar type
2431 * by set $CFG->calendar, and the appopriate function defined
2433 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2434 * @param array $args The args to pass to the hook, usually the event is the first element
2435 * @return bool attempts to call event hook
2437 public static function calendar_event_hook($action, array $args) {
2438 global $CFG;
2439 static $extcalendarinc;
2440 if ($extcalendarinc === null) {
2441 if (!empty($CFG->calendar) && file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2442 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2443 $extcalendarinc = true;
2444 } else {
2445 $extcalendarinc = false;
2448 if($extcalendarinc === false) {
2449 return false;
2451 $hook = $CFG->calendar .'_'.$action;
2452 if (function_exists($hook)) {
2453 call_user_func_array($hook, $args);
2454 return true;
2456 return false;
2460 * Returns a calendar_event object when provided with an event id
2462 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2463 * it will result in an exception being thrown
2465 * @param int|object $param event object or event id
2466 * @return calendar_event|false status for loading calendar_event
2468 public static function load($param) {
2469 global $DB;
2470 if (is_object($param)) {
2471 $event = new calendar_event($param);
2472 } else {
2473 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2474 $event = new calendar_event($event);
2476 return $event;
2480 * Creates a new event and returns a calendar_event object
2482 * @param object|array $properties An object containing event properties
2483 * @return calendar_event|false The event object or false if it failed
2485 public static function create($properties) {
2486 if (is_array($properties)) {
2487 $properties = (object)$properties;
2489 if (!is_object($properties)) {
2490 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2492 $event = new calendar_event($properties);
2493 if ($event->update($properties)) {
2494 return $event;
2495 } else {
2496 return false;
2502 * Calendar information class
2504 * This class is used simply to organise the information pertaining to a calendar
2505 * and is used primarily to make information easily available.
2507 * @package core_calendar
2508 * @category calendar
2509 * @copyright 2010 Sam Hemelryk
2510 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2512 class calendar_information {
2513 /** @var int The day */
2514 public $day;
2516 /** @var int The month */
2517 public $month;
2519 /** @var int The year */
2520 public $year;
2522 /** @var int A course id */
2523 public $courseid = null;
2525 /** @var array An array of courses */
2526 public $courses = array();
2528 /** @var array An array of groups */
2529 public $groups = array();
2531 /** @var array An array of users */
2532 public $users = array();
2535 * Creates a new instance
2537 * @param int $day the number of the day
2538 * @param int $month the number of the month
2539 * @param int $year the number of the year
2541 public function __construct($day=0, $month=0, $year=0) {
2543 $date = usergetdate(time());
2545 if (empty($day)) {
2546 $day = $date['mday'];
2549 if (empty($month)) {
2550 $month = $date['mon'];
2553 if (empty($year)) {
2554 $year = $date['year'];
2557 $this->day = $day;
2558 $this->month = $month;
2559 $this->year = $year;
2563 * Initialize calendar information
2565 * @param stdClass $course object
2566 * @param array $coursestoload An array of courses [$course->id => $course]
2567 * @param bool $ignorefilters options to use filter
2569 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
2570 $this->courseid = $course->id;
2571 $this->course = $course;
2572 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2573 $this->courses = $courses;
2574 $this->groups = $group;
2575 $this->users = $user;
2579 * Ensures the date for the calendar is correct and either sets it to now
2580 * or throws a moodle_exception if not
2582 * @param bool $defaultonow use current time
2583 * @throws moodle_exception
2584 * @return bool validation of checkdate
2586 public function checkdate($defaultonow = true) {
2587 if (!checkdate($this->month, $this->day, $this->year)) {
2588 if ($defaultonow) {
2589 $now = usergetdate(time());
2590 $this->day = intval($now['mday']);
2591 $this->month = intval($now['mon']);
2592 $this->year = intval($now['year']);
2593 return true;
2594 } else {
2595 throw new moodle_exception('invaliddate');
2598 return true;
2601 * Gets todays timestamp for the calendar
2603 * @return int today timestamp
2605 public function timestamp_today() {
2606 return make_timestamp($this->year, $this->month, $this->day);
2609 * Gets tomorrows timestamp for the calendar
2611 * @return int tomorrow timestamp
2613 public function timestamp_tomorrow() {
2614 return make_timestamp($this->year, $this->month, $this->day+1);
2617 * Adds the pretend blocks for teh calendar
2619 * @param core_calendar_renderer $renderer
2620 * @param bool $showfilters display filters, false is set as default
2621 * @param string|null $view preference view options (eg: day, month, upcoming)
2623 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2624 if ($showfilters) {
2625 $filters = new block_contents();
2626 $filters->content = $renderer->fake_block_filters($this->courseid, $this->day, $this->month, $this->year, $view, $this->courses);
2627 $filters->footer = '';
2628 $filters->title = get_string('eventskey', 'calendar');
2629 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2631 $block = new block_contents;
2632 $block->content = $renderer->fake_block_threemonths($this);
2633 $block->footer = '';
2634 $block->title = get_string('monthlyview', 'calendar');
2635 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);