weekly release 2.2.7+
[moodle.git] / calendar / lib.php
bloba584c54591fb8c8b5748e7ba345d2686ed3bcf26
1 <?php
3 /////////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Calendar extension //
8 // //
9 // Copyright (C) 2003-2004 Greek School Network www.sch.gr //
10 // //
11 // Designed by: //
12 // Avgoustos Tsinakos (tsinakos@teikav.edu.gr) //
13 // Jon Papaioannou (pj@moodle.org) //
14 // //
15 // Programming and development: //
16 // Jon Papaioannou (pj@moodle.org) //
17 // //
18 // For bugs, suggestions, etc contact: //
19 // Jon Papaioannou (pj@moodle.org) //
20 // //
21 // The current module was developed at the University of Macedonia //
22 // (www.uom.gr) under the funding of the Greek School Network (www.sch.gr) //
23 // The aim of this project is to provide additional and improved //
24 // functionality to the Asynchronous Distance Education service that the //
25 // Greek School Network deploys. //
26 // //
27 // This program is free software; you can redistribute it and/or modify //
28 // it under the terms of the GNU General Public License as published by //
29 // the Free Software Foundation; either version 2 of the License, or //
30 // (at your option) any later version. //
31 // //
32 // This program is distributed in the hope that it will be useful, //
33 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
34 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
35 // GNU General Public License for more details: //
36 // //
37 // http://www.gnu.org/copyleft/gpl.html //
38 // //
39 /////////////////////////////////////////////////////////////////////////////
41 // These are read by the administration component to provide default values
42 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
43 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44 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
47 define('CALENDAR_DEFAULT_WEEKEND', 65);
48 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
49 define('CALENDAR_TF_24', '%H:%M');
50 define('CALENDAR_TF_12', '%I:%M %p');
52 define('CALENDAR_EVENT_GLOBAL', 1);
53 define('CALENDAR_EVENT_COURSE', 2);
54 define('CALENDAR_EVENT_GROUP', 4);
55 define('CALENDAR_EVENT_USER', 8);
57 /**
58 * CALENDAR_STARTING_WEEKDAY has since been deprecated please call calendar_get_starting_weekday() instead
59 * @deprecated
61 define('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);
63 /**
64 * Return the days of the week
66 * @return array
68 function calendar_get_days() {
69 return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
72 /**
73 * Gets the first day of the week
75 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
77 * @return int
79 function calendar_get_starting_weekday() {
80 global $CFG;
82 if (isset($CFG->calendar_startwday)) {
83 $firstday = $CFG->calendar_startwday;
84 } else {
85 $firstday = get_string('firstdayofweek', 'langconfig');
88 if(!is_numeric($firstday)) {
89 return CALENDAR_DEFAULT_STARTING_WEEKDAY;
90 } else {
91 return intval($firstday) % 7;
95 /**
96 * Generates the HTML for a miniature calendar
98 * @global core_renderer $OUTPUT
99 * @param array $courses
100 * @param array $groups
101 * @param array $users
102 * @param int $cal_month
103 * @param int $cal_year
104 * @return string
106 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
107 global $CFG, $USER, $OUTPUT;
109 $display = new stdClass;
110 $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
111 $display->maxwday = $display->minwday + 6;
113 $content = '';
115 if(!empty($cal_month) && !empty($cal_year)) {
116 $thisdate = usergetdate(time()); // Date and time the user sees at his location
117 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
118 // Navigated to this month
119 $date = $thisdate;
120 $display->thismonth = true;
121 } else {
122 // Navigated to other month, let's do a nice trick and save us a lot of work...
123 if(!checkdate($cal_month, 1, $cal_year)) {
124 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
125 $display->thismonth = true;
126 } else {
127 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
128 $display->thismonth = false;
131 } else {
132 $date = usergetdate(time()); // Date and time the user sees at his location
133 $display->thismonth = true;
136 // Fill in the variables we 're going to use, nice and tidy
137 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
138 $display->maxdays = calendar_days_in_month($m, $y);
140 if (get_user_timezone_offset() < 99) {
141 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
142 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
143 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
144 } else {
145 // no timezone info specified
146 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
147 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
150 $startwday = dayofweek(1, $m, $y);
152 // Align the starting weekday to fall in our display range
153 // This is simple, not foolproof.
154 if($startwday < $display->minwday) {
155 $startwday += 7;
158 // TODO: THIS IS TEMPORARY CODE!
159 // [pj] I was just reading through this and realized that I when writing this code I was probably
160 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
161 // make_timestamp would accomplish the same thing. So here goes a test:
162 //$test_start = make_timestamp($y, $m, 1);
163 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
164 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
165 //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);
167 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
168 //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);
172 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
173 $events = calendar_get_events(
174 usertime($display->tstart) - dst_offset_on($display->tstart),
175 usertime($display->tend) - dst_offset_on($display->tend),
176 $users, $groups, $courses);
178 // Set event course class for course events
179 if (!empty($events)) {
180 foreach ($events as $eventid => $event) {
181 if (!empty($event->modulename)) {
182 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
183 if (!groups_course_module_visible($cm)) {
184 unset($events[$eventid]);
190 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
191 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
192 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
193 // arguments to this function.
195 $hrefparams = array();
196 if(!empty($courses)) {
197 $courses = array_diff($courses, array(SITEID));
198 if(count($courses) == 1) {
199 $hrefparams['course'] = reset($courses);
203 // We want to have easy access by day, since the display is on a per-day basis.
204 // Arguments passed by reference.
205 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
206 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
208 //Accessibility: added summary and <abbr> elements.
209 $days_title = calendar_get_days();
211 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
212 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
213 $content .= '<tr class="weekdays">'; // Header row: day names
215 // Print out the names of the weekdays
216 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
217 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
218 // This uses the % operator to get the correct weekday no matter what shift we have
219 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
220 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
221 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
224 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
226 // For the table display. $week is the row; $dayweek is the column.
227 $dayweek = $startwday;
229 // Paddding (the first week may have blank days in the beginning)
230 for($i = $display->minwday; $i < $startwday; ++$i) {
231 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
234 $weekend = CALENDAR_DEFAULT_WEEKEND;
235 if (isset($CFG->calendar_weekend)) {
236 $weekend = intval($CFG->calendar_weekend);
239 // Now display all the calendar
240 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
241 if($dayweek > $display->maxwday) {
242 // We need to change week (table row)
243 $content .= '</tr><tr>';
244 $dayweek = $display->minwday;
247 // Reset vars
248 $cell = '';
249 if ($weekend & (1 << ($dayweek % 7))) {
250 // Weekend. This is true no matter what the exact range is.
251 $class = 'weekend day';
252 } else {
253 // Normal working day.
254 $class = 'day';
257 // Special visual fx if an event is defined
258 if(isset($eventsbyday[$day])) {
259 $class .= ' hasevent';
260 $hrefparams['view'] = 'day';
261 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $hrefparams), $day, $m, $y);
263 $popupcontent = '';
264 foreach($eventsbyday[$day] as $eventid) {
265 if (!isset($events[$eventid])) {
266 continue;
268 $event = $events[$eventid];
269 $popupalt = '';
270 $component = 'moodle';
271 if(!empty($event->modulename)) {
272 $popupicon = 'icon';
273 $popupalt = $event->modulename;
274 $component = $event->modulename;
275 } else if ($event->courseid == SITEID) { // Site event
276 $popupicon = 'c/site';
277 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
278 $popupicon = 'c/course';
279 } else if ($event->groupid) { // Group event
280 $popupicon = 'c/group';
281 } else if ($event->userid) { // User event
282 $popupicon = 'c/user';
285 $dayhref->set_anchor('event_'.$event->id);
287 $popupcontent .= html_writer::start_tag('div');
288 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
289 $popupcontent .= html_writer::link($dayhref, format_string($event->name, true));
290 $popupcontent .= html_writer::end_tag('div');
293 //Accessibility: functionality moved to calendar_get_popup.
294 if($display->thismonth && $day == $d) {
295 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
296 } else {
297 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
300 // Class and cell content
301 if(isset($typesbyday[$day]['startglobal'])) {
302 $class .= ' calendar_event_global';
303 } else if(isset($typesbyday[$day]['startcourse'])) {
304 $class .= ' calendar_event_course';
305 } else if(isset($typesbyday[$day]['startgroup'])) {
306 $class .= ' calendar_event_group';
307 } else if(isset($typesbyday[$day]['startuser'])) {
308 $class .= ' calendar_event_user';
310 $cell = '<a href="'.(string)$dayhref.'" '.$popup.'>'.$day.'</a>';
311 } else {
312 $cell = $day;
315 $durationclass = false;
316 if (isset($typesbyday[$day]['durationglobal'])) {
317 $durationclass = ' duration_global';
318 } else if(isset($typesbyday[$day]['durationcourse'])) {
319 $durationclass = ' duration_course';
320 } else if(isset($typesbyday[$day]['durationgroup'])) {
321 $durationclass = ' duration_group';
322 } else if(isset($typesbyday[$day]['durationuser'])) {
323 $durationclass = ' duration_user';
325 if ($durationclass) {
326 $class .= ' duration '.$durationclass;
329 // If event has a class set then add it to the table day <td> tag
330 // Note: only one colour for minicalendar
331 if(isset($eventsbyday[$day])) {
332 foreach($eventsbyday[$day] as $eventid) {
333 if (!isset($events[$eventid])) {
334 continue;
336 $event = $events[$eventid];
337 if (!empty($event->class)) {
338 $class .= ' '.$event->class;
340 break;
344 // Special visual fx for today
345 //Accessibility: hidden text for today, and popup.
346 if($display->thismonth && $day == $d) {
347 $class .= ' today';
348 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
350 if(! isset($eventsbyday[$day])) {
351 $class .= ' eventnone';
352 $popup = calendar_get_popup(true, false);
353 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
355 $cell = get_accesshide($today.' ').$cell;
358 // Just display it
359 if(!empty($class)) {
360 $class = ' class="'.$class.'"';
362 $content .= '<td'.$class.'>'.$cell."</td>\n";
365 // Paddding (the last week may have blank days at the end)
366 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
367 $content .= '<td class="dayblank">&nbsp;</td>';
369 $content .= '</tr>'; // Last row ends
371 $content .= '</table>'; // Tabular display of days ends
373 return $content;
377 * calendar_get_popup, called at multiple points in from calendar_get_mini.
378 * Copied and modified from calendar_get_mini.
379 * @global moodle_page $PAGE
380 * @param $is_today bool, false except when called on the current day.
381 * @param $event_timestart mixed, $events[$eventid]->timestart, OR false if there are no events.
382 * @param $popupcontent string.
383 * @return $popup string, contains onmousover and onmouseout events.
385 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
386 global $PAGE;
387 static $popupcount;
388 if ($popupcount === null) {
389 $popupcount = 1;
391 $popupcaption = '';
392 if($is_today) {
393 $popupcaption = get_string('today', 'calendar').' ';
395 if (false === $event_timestart) {
396 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
397 $popupcontent = get_string('eventnone', 'calendar');
399 } else {
400 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
402 $id = 'calendar_tooltip_'.$popupcount;
403 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
405 $popupcount++;
406 return 'id="'.$id.'"';
409 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
410 global $CFG, $COURSE, $DB;
412 $display = new stdClass;
413 $display->range = $daysinfuture; // How many days in the future we 'll look
414 $display->maxevents = $maxevents;
416 $output = array();
418 // Prepare "course caching", since it may save us a lot of queries
419 $coursecache = array();
421 $processed = 0;
422 $now = time(); // We 'll need this later
423 $usermidnighttoday = usergetmidnight($now);
425 if ($fromtime) {
426 $display->tstart = $fromtime;
427 } else {
428 $display->tstart = $usermidnighttoday;
431 // This works correctly with respect to the user's DST, but it is accurate
432 // only because $fromtime is always the exact midnight of some day!
433 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
435 // Get the events matching our criteria
436 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
438 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
439 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
440 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
441 // arguments to this function.
443 $hrefparams = array();
444 if(!empty($courses)) {
445 $courses = array_diff($courses, array(SITEID));
446 if(count($courses) == 1) {
447 $hrefparams['course'] = reset($courses);
451 if ($events !== false) {
453 $modinfo =& get_fast_modinfo($COURSE);
455 foreach($events as $event) {
458 if (!empty($event->modulename)) {
459 if ($event->courseid == $COURSE->id) {
460 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
461 $cm = $modinfo->instances[$event->modulename][$event->instance];
462 if (!$cm->uservisible) {
463 continue;
466 } else {
467 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
468 continue;
470 if (!coursemodule_visible_for_user($cm)) {
471 continue;
474 if ($event->modulename == 'assignment'){
475 // create calendar_event to test edit_event capability
476 // this new event will also prevent double creation of calendar_event object
477 $checkevent = new calendar_event($event);
478 // TODO: rewrite this hack somehow
479 if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
480 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
481 // print_error("invalidid", 'assignment');
482 continue;
484 // assign assignment to assignment object to use hidden_is_hidden method
485 require_once($CFG->dirroot.'/mod/assignment/lib.php');
487 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
488 continue;
490 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
492 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
493 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
495 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
496 $event->description = get_string('notavailableyet', 'assignment');
502 if ($processed >= $display->maxevents) {
503 break;
506 $event->time = calendar_format_event_time($event, $now, $hrefparams);
507 $output[] = $event;
508 ++$processed;
511 return $output;
514 function calendar_add_event_metadata($event) {
515 global $CFG, $OUTPUT;
517 //Support multilang in event->name
518 $event->name = format_string($event->name,true);
520 if(!empty($event->modulename)) { // Activity event
521 // The module name is set. I will assume that it has to be displayed, and
522 // also that it is an automatically-generated event. And of course that the
523 // fields for get_coursemodule_from_instance are set correctly.
524 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
526 if ($module === false) {
527 return;
530 $modulename = get_string('modulename', $event->modulename);
531 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
532 // will be used as alt text if the event icon
533 $eventtype = get_string($event->eventtype, $event->modulename);
534 } else {
535 $eventtype = '';
537 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
539 $context = get_context_instance(CONTEXT_COURSE, $module->course);
540 $fullname = format_string($coursecache[$module->course]->fullname, true, array('context' => $context));
542 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
543 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
544 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$fullname.'</a>';
545 $event->cmid = $module->id;
548 } else if($event->courseid == SITEID) { // Site event
549 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
550 $event->cssclass = 'calendar_event_global';
551 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
552 calendar_get_course_cached($coursecache, $event->courseid);
554 $context = get_context_instance(CONTEXT_COURSE, $event->courseid);
555 $fullname = format_string($coursecache[$event->courseid]->fullname, true, array('context' => $context));
557 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
558 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$fullname.'</a>';
559 $event->cssclass = 'calendar_event_course';
560 } else if ($event->groupid) { // Group event
561 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
562 $event->cssclass = 'calendar_event_group';
563 } else if($event->userid) { // User event
564 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
565 $event->cssclass = 'calendar_event_user';
567 return $event;
571 * Prints a calendar event
573 * @deprecated 2.0
575 function calendar_print_event($event, $showactions=true) {
576 global $CFG, $USER, $OUTPUT, $PAGE;
577 debugging('calendar_print_event is deprecated please update your code', DEBUG_DEVELOPER);
578 $renderer = $PAGE->get_renderer('core_calendar');
579 if (!($event instanceof calendar_event)) {
580 $event = new calendar_event($event);
582 echo $renderer->event($event);
586 * Get calendar events
587 * @param int $tstart Start time of time range for events
588 * @param int $tend End time of time range for events
589 * @param array/int/boolean $users array of users, user id or boolean for all/no user events
590 * @param array/int/boolean $groups array of groups, group id or boolean for all/no group events
591 * @param array/int/boolean $courses array of courses, course id or boolean for all/no course events
592 * @param boolean $withduration whether only events starting within time range selected
593 * or events in progress/already started selected as well
594 * @param boolean $ignorehidden whether to select only visible events or all events
595 * @return array of selected events or an empty array if there aren't any (or there was an error)
597 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
598 global $DB;
600 $whereclause = '';
601 // Quick test
602 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
603 return array();
606 if(is_array($users) && !empty($users)) {
607 // Events from a number of users
608 if(!empty($whereclause)) $whereclause .= ' OR';
609 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
610 } else if(is_numeric($users)) {
611 // Events from one user
612 if(!empty($whereclause)) $whereclause .= ' OR';
613 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
614 } else if($users === true) {
615 // Events from ALL users
616 if(!empty($whereclause)) $whereclause .= ' OR';
617 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
618 } else if($users === false) {
619 // No user at all, do nothing
622 if(is_array($groups) && !empty($groups)) {
623 // Events from a number of groups
624 if(!empty($whereclause)) $whereclause .= ' OR';
625 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
626 } else if(is_numeric($groups)) {
627 // Events from one group
628 if(!empty($whereclause)) $whereclause .= ' OR ';
629 $whereclause .= ' groupid = '.$groups;
630 } else if($groups === true) {
631 // Events from ALL groups
632 if(!empty($whereclause)) $whereclause .= ' OR ';
633 $whereclause .= ' groupid != 0';
635 // boolean false (no groups at all): we don't need to do anything
637 if(is_array($courses) && !empty($courses)) {
638 if(!empty($whereclause)) {
639 $whereclause .= ' OR';
641 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
642 } else if(is_numeric($courses)) {
643 // One course
644 if(!empty($whereclause)) $whereclause .= ' OR';
645 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
646 } else if ($courses === true) {
647 // Events from ALL courses
648 if(!empty($whereclause)) $whereclause .= ' OR';
649 $whereclause .= ' (groupid = 0 AND courseid != 0)';
652 // Security check: if, by now, we have NOTHING in $whereclause, then it means
653 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
654 // events no matter what. Allowing the code to proceed might return a completely
655 // valid query with only time constraints, thus selecting ALL events in that time frame!
656 if(empty($whereclause)) {
657 return array();
660 if($withduration) {
661 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
663 else {
664 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
666 if(!empty($whereclause)) {
667 // We have additional constraints
668 $whereclause = $timeclause.' AND ('.$whereclause.')';
670 else {
671 // Just basic time filtering
672 $whereclause = $timeclause;
675 if ($ignorehidden) {
676 $whereclause .= ' AND visible = 1';
679 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
680 if ($events === false) {
681 $events = array();
683 return $events;
686 function calendar_top_controls($type, $data) {
687 global $CFG;
688 $content = '';
689 if(!isset($data['d'])) {
690 $data['d'] = 1;
693 // Ensure course id passed if relevant
694 // Required due to changes in view/lib.php mainly (calendar_session_vars())
695 $courseid = '';
696 if (!empty($data['id'])) {
697 $courseid = '&amp;course='.$data['id'];
700 if(!checkdate($data['m'], $data['d'], $data['y'])) {
701 $time = time();
703 else {
704 $time = make_timestamp($data['y'], $data['m'], $data['d']);
706 $date = usergetdate($time);
708 $data['m'] = $date['mon'];
709 $data['y'] = $date['year'];
711 //Accessibility: calendar block controls, replaced <table> with <div>.
712 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
713 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
715 switch($type) {
716 case 'frontpage':
717 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
718 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
719 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
720 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
722 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
723 if (!empty($data['id'])) {
724 $calendarlink->param('course', $data['id']);
727 if (right_to_left()) {
728 $left = $nextlink;
729 $right = $prevlink;
730 } else {
731 $left = $prevlink;
732 $right = $nextlink;
735 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
736 $content .= $left.'<span class="hide"> | </span>';
737 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
738 $content .= '<span class="hide"> | </span>'. $right;
739 $content .= "<span class=\"clearer\"><!-- --></span>\n";
740 $content .= html_writer::end_tag('div');
742 break;
743 case 'course':
744 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
745 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
746 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
747 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);
749 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
750 if (!empty($data['id'])) {
751 $calendarlink->param('course', $data['id']);
754 if (right_to_left()) {
755 $left = $nextlink;
756 $right = $prevlink;
757 } else {
758 $left = $prevlink;
759 $right = $nextlink;
762 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
763 $content .= $left.'<span class="hide"> | </span>';
764 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
765 $content .= '<span class="hide"> | </span>'. $right;
766 $content .= "<span class=\"clearer\"><!-- --></span>";
767 $content .= html_writer::end_tag('div');
768 break;
769 case 'upcoming':
770 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
771 if (!empty($data['id'])) {
772 $calendarlink->param('course', $data['id']);
774 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
775 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
776 break;
777 case 'display':
778 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
779 if (!empty($data['id'])) {
780 $calendarlink->param('course', $data['id']);
782 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
783 $content .= html_writer::tag('h3', $calendarlink);
784 break;
785 case 'month':
786 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
787 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
788 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
789 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
790 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
791 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
793 if (right_to_left()) {
794 $left = $nextlink;
795 $right = $prevlink;
796 } else {
797 $left = $prevlink;
798 $right = $nextlink;
801 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
802 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
803 $content .= '<span class="hide"> | </span>' . $right;
804 $content .= '<span class="clearer"><!-- --></span>';
805 $content .= html_writer::end_tag('div')."\n";
806 break;
807 case 'day':
808 $days = calendar_get_days();
809 $data['d'] = $date['mday']; // Just for convenience
810 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
811 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
812 $prevname = calendar_wday_name($days[$prevdate['wday']]);
813 $nextname = calendar_wday_name($days[$nextdate['wday']]);
814 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
815 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
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;
827 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
828 $content .= '<span class="hide"> | </span>'. $right;
829 $content .= "<span class=\"clearer\"><!-- --></span>";
830 $content .= html_writer::end_tag('div')."\n";
832 break;
834 return $content;
837 function calendar_filter_controls(moodle_url $returnurl) {
838 global $CFG, $USER, $OUTPUT;
840 $groupevents = true;
842 $id = optional_param( 'id',0,PARAM_INT );
844 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));
846 $content = '<table>';
847 $content .= '<tr>';
849 $seturl->param('var', 'showglobal');
850 if (calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
851 $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>';
852 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
853 } else {
854 $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>';
855 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
858 $seturl->param('var', 'showcourses');
859 if (calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
860 $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>';
861 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
862 } else {
863 $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>';
864 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
867 if (isloggedin() && !isguestuser()) {
868 $content .= "</tr>\n<tr>";
870 if ($groupevents) {
871 // This course MIGHT have group events defined, so show the filter
872 $seturl->param('var', 'showgroups');
873 if (calendar_show_event_type(CALENDAR_EVENT_GROUP)) {
874 $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>';
875 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
876 } else {
877 $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>';
878 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
880 } else {
881 // This course CANNOT have group events, so lose the filter
882 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
885 $seturl->param('var', 'showuser');
886 if (calendar_show_event_type(CALENDAR_EVENT_USER)) {
887 $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>';
888 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
889 } else {
890 $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>';
891 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
894 $content .= "</tr>\n</table>\n";
896 return $content;
899 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
901 static $shortformat;
902 if(empty($shortformat)) {
903 $shortformat = get_string('strftimedayshort');
906 if($now === false) {
907 $now = time();
910 // To have it in one place, if a change is needed
911 $formal = userdate($tstamp, $shortformat);
913 $datestamp = usergetdate($tstamp);
914 $datenow = usergetdate($now);
916 if($usecommonwords == false) {
917 // We don't want words, just a date
918 return $formal;
920 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
921 // Today
922 return get_string('today', 'calendar');
924 else if(
925 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
926 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
928 // Yesterday
929 return get_string('yesterday', 'calendar');
931 else if(
932 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
933 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
935 // Tomorrow
936 return get_string('tomorrow', 'calendar');
938 else {
939 return $formal;
943 function calendar_time_representation($time) {
944 static $langtimeformat = NULL;
945 if($langtimeformat === NULL) {
946 $langtimeformat = get_string('strftimetime');
948 $timeformat = get_user_preferences('calendar_timeformat');
949 if(empty($timeformat)){
950 $timeformat = get_config(NULL,'calendar_site_timeformat');
952 // The ? is needed because the preference might be present, but empty
953 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
957 * Adds day, month, year arguments to a URL and returns a moodle_url object.
959 * @param string|moodle_url $linkbase
960 * @param int $d
961 * @param int $m
962 * @param int $y
963 * @return moodle_url
965 function calendar_get_link_href($linkbase, $d, $m, $y) {
966 if (empty($linkbase)) {
967 return '';
969 if (!($linkbase instanceof moodle_url)) {
970 $linkbase = new moodle_url();
972 if (!empty($d)) {
973 $linkbase->param('cal_d', $d);
975 if (!empty($m)) {
976 $linkbase->param('cal_m', $m);
978 if (!empty($y)) {
979 $linkbase->param('cal_y', $y);
981 return $linkbase;
985 * This function has been deprecated as of Moodle 2.0... DO NOT USE!!!!!
987 * @deprecated
988 * @since 2.0
990 * @param string $text
991 * @param string|moodle_url $linkbase
992 * @param int|null $d
993 * @param int|null $m
994 * @param int|null $y
995 * @return string HTML link
997 function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
998 $url = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
999 if (empty($url)) {
1000 return $text;
1002 return html_writer::link($url, $text);
1006 * Build and return a previous month HTML link, with an arrow.
1008 * @param string $text The text label.
1009 * @param string|moodle_url $linkbase The URL stub.
1010 * @param int $d $m $y Day of month, month and year numbers.
1011 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1012 * @return string HTML string.
1014 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
1015 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1016 if (empty($href)) {
1017 return $text;
1019 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1023 * Build and return a next month HTML link, with an arrow.
1025 * @param string $text The text label.
1026 * @param string|moodle_url $linkbase The URL stub.
1027 * @param int $d $m $y Day of month, month and year numbers.
1028 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1029 * @return string HTML string.
1031 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
1032 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1033 if (empty($href)) {
1034 return $text;
1036 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1039 function calendar_wday_name($englishname) {
1040 return get_string(strtolower($englishname), 'calendar');
1043 function calendar_days_in_month($month, $year) {
1044 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1047 function calendar_get_block_upcoming($events, $linkhref = NULL) {
1048 $content = '';
1049 $lines = count($events);
1050 if (!$lines) {
1051 return $content;
1054 for ($i = 0; $i < $lines; ++$i) {
1055 if (!isset($events[$i]->time)) { // Just for robustness
1056 continue;
1058 $events[$i] = calendar_add_event_metadata($events[$i]);
1059 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
1060 if (!empty($events[$i]->referer)) {
1061 // That's an activity event, so let's provide the hyperlink
1062 $content .= $events[$i]->referer;
1063 } else {
1064 if(!empty($linkhref)) {
1065 $ed = usergetdate($events[$i]->timestart);
1066 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1067 $href->set_anchor('event_'.$events[$i]->id);
1068 $content .= html_writer::link($href, $events[$i]->name);
1070 else {
1071 $content .= $events[$i]->name;
1074 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1075 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1076 if ($i < $lines - 1) $content .= '<hr />';
1079 return $content;
1082 function calendar_add_month($month, $year) {
1083 if($month == 12) {
1084 return array(1, $year + 1);
1086 else {
1087 return array($month + 1, $year);
1091 function calendar_sub_month($month, $year) {
1092 if($month == 1) {
1093 return array(12, $year - 1);
1095 else {
1096 return array($month - 1, $year);
1100 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1101 $eventsbyday = array();
1102 $typesbyday = array();
1103 $durationbyday = array();
1105 if($events === false) {
1106 return;
1109 foreach($events as $event) {
1111 $startdate = usergetdate($event->timestart);
1112 // Set end date = start date if no duration
1113 if ($event->timeduration) {
1114 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1115 } else {
1116 $enddate = $startdate;
1119 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1120 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1121 // Out of bounds
1122 continue;
1125 $eventdaystart = intval($startdate['mday']);
1127 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1128 // Give the event to its day
1129 $eventsbyday[$eventdaystart][] = $event->id;
1131 // Mark the day as having such an event
1132 if($event->courseid == SITEID && $event->groupid == 0) {
1133 $typesbyday[$eventdaystart]['startglobal'] = true;
1134 // Set event class for global event
1135 $events[$event->id]->class = 'calendar_event_global';
1137 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1138 $typesbyday[$eventdaystart]['startcourse'] = true;
1139 // Set event class for course event
1140 $events[$event->id]->class = 'calendar_event_course';
1142 else if($event->groupid) {
1143 $typesbyday[$eventdaystart]['startgroup'] = true;
1144 // Set event class for group event
1145 $events[$event->id]->class = 'calendar_event_group';
1147 else if($event->userid) {
1148 $typesbyday[$eventdaystart]['startuser'] = true;
1149 // Set event class for user event
1150 $events[$event->id]->class = 'calendar_event_user';
1154 if($event->timeduration == 0) {
1155 // Proceed with the next
1156 continue;
1159 // The event starts on $month $year or before. So...
1160 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1162 // Also, it ends on $month $year or later...
1163 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1165 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1166 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1167 $durationbyday[$i][] = $event->id;
1168 if($event->courseid == SITEID && $event->groupid == 0) {
1169 $typesbyday[$i]['durationglobal'] = true;
1171 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1172 $typesbyday[$i]['durationcourse'] = true;
1174 else if($event->groupid) {
1175 $typesbyday[$i]['durationgroup'] = true;
1177 else if($event->userid) {
1178 $typesbyday[$i]['durationuser'] = true;
1183 return;
1186 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1187 $module = get_coursemodule_from_instance($modulename, $instance);
1189 if($module === false) return false;
1190 if(!calendar_get_course_cached($coursecache, $module->course)) {
1191 return false;
1193 return $module;
1196 function calendar_get_course_cached(&$coursecache, $courseid) {
1197 global $COURSE, $DB;
1199 if (!isset($coursecache[$courseid])) {
1200 if ($courseid == $COURSE->id) {
1201 $coursecache[$courseid] = $COURSE;
1202 } else {
1203 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
1206 return $coursecache[$courseid];
1210 * Returns the courses to load events for, the
1212 * @global moodle_database $DB
1213 * @param array $courseeventsfrom An array of courses to load calendar events for
1214 * @param bool $ignorefilters
1215 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1217 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1218 global $USER, $CFG, $DB;
1220 // For backwards compatability we have to check whether the courses array contains
1221 // just id's in which case we need to load course objects.
1222 $coursestoload = array();
1223 foreach ($courseeventsfrom as $id => $something) {
1224 if (!is_object($something)) {
1225 $coursestoload[] = $id;
1226 unset($courseeventsfrom[$id]);
1229 if (!empty($coursestoload)) {
1230 // TODO remove this in 2.2
1231 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
1232 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1235 $courses = array();
1236 $user = false;
1237 $group = false;
1239 // capabilities that allow seeing group events from all groups
1240 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1241 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1243 $isloggedin = isloggedin();
1245 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1246 $courses = array_keys($courseeventsfrom);
1248 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1249 $courses[] = SITEID;
1251 $courses = array_unique($courses);
1252 sort($courses);
1254 if (!empty($courses) && in_array(SITEID, $courses)) {
1255 // Sort courses for consistent colour highlighting
1256 // Effectively ignoring SITEID as setting as last course id
1257 $key = array_search(SITEID, $courses);
1258 unset($courses[$key]);
1259 $courses[] = SITEID;
1262 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1263 $user = $USER->id;
1266 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1268 if (count($courseeventsfrom)==1) {
1269 $course = reset($courseeventsfrom);
1270 if (has_any_capability($allgroupscaps, get_context_instance(CONTEXT_COURSE, $course->id))) {
1271 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
1272 $group = array_keys($coursegroups);
1275 if ($group === false) {
1276 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, get_system_context())) {
1277 $group = true;
1278 } else if ($isloggedin) {
1279 $groupids = array();
1281 // We already have the courses to examine in $courses
1282 // For each course...
1283 foreach ($courseeventsfrom as $courseid => $course) {
1284 // If the user is an editing teacher in there,
1285 if (!empty($USER->groupmember[$course->id])) {
1286 // We've already cached the users groups for this course so we can just use that
1287 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1288 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1289 // If this course has groups, show events from all of those related to the current user
1290 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1291 $groupids = array_merge($groupids, $coursegroups['0']);
1294 if (!empty($groupids)) {
1295 $group = $groupids;
1300 if (empty($courses)) {
1301 $courses = false;
1304 return array($courses, $group, $user);
1307 function calendar_edit_event_allowed($event) {
1308 global $USER, $DB;
1310 // Must be logged in
1311 if (!isloggedin()) {
1312 return false;
1315 // can not be using guest account
1316 if (isguestuser()) {
1317 return false;
1320 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1321 // if user has manageentries at site level, return true
1322 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1323 return true;
1326 // if groupid is set, it's definitely a group event
1327 if (!empty($event->groupid)) {
1328 // Allow users to add/edit group events if:
1329 // 1) They have manageentries (= entries for whole course)
1330 // 2) They have managegroupentries AND are in the group
1331 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1332 return $group && (
1333 has_capability('moodle/calendar:manageentries', $event->context) ||
1334 (has_capability('moodle/calendar:managegroupentries', $event->context)
1335 && groups_is_member($event->groupid)));
1336 } else if (!empty($event->courseid)) {
1337 // if groupid is not set, but course is set,
1338 // it's definiely a course event
1339 return has_capability('moodle/calendar:manageentries', $event->context);
1340 } else if (!empty($event->userid) && $event->userid == $USER->id) {
1341 // if course is not set, but userid id set, it's a user event
1342 return (has_capability('moodle/calendar:manageownentries', $event->context));
1343 } else if (!empty($event->userid)) {
1344 return (has_capability('moodle/calendar:manageentries', $event->context));
1346 return false;
1350 * Returns the default courses to display on the calendar when there isn't a specific
1351 * course to display.
1353 * @global moodle_database $DB
1354 * @return array Array of courses to display
1356 function calendar_get_default_courses() {
1357 global $CFG, $DB;
1359 if (!isloggedin()) {
1360 return array();
1363 $courses = array();
1364 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
1365 list ($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1366 $sql = "SELECT c.* $select
1367 FROM {course} c
1368 $join
1369 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1371 $courses = $DB->get_records_sql($sql, null, 0, 20);
1372 foreach ($courses as $course) {
1373 context_helper::preload_from_record($course);
1375 return $courses;
1378 $courses = enrol_get_my_courses();
1380 return $courses;
1383 function calendar_preferences_button(stdClass $course) {
1384 global $OUTPUT;
1386 // Guests have no preferences
1387 if (!isloggedin() || isguestuser()) {
1388 return '';
1391 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
1394 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
1395 $startdate = usergetdate($event->timestart);
1396 $enddate = usergetdate($event->timestart + $event->timeduration);
1397 $usermidnightstart = usergetmidnight($event->timestart);
1399 if($event->timeduration) {
1400 // To avoid doing the math if one IF is enough :)
1401 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1403 else {
1404 $usermidnightend = $usermidnightstart;
1407 if (empty($linkparams) || !is_array($linkparams)) {
1408 $linkparams = array();
1410 $linkparams['view'] = 'day';
1412 // OK, now to get a meaningful display...
1413 // First of all we have to construct a human-readable date/time representation
1415 if($event->timeduration) {
1416 // It has a duration
1417 if($usermidnightstart == $usermidnightend ||
1418 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1419 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
1420 // But it's all on the same day
1421 $timestart = calendar_time_representation($event->timestart);
1422 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1423 $time = $timestart.' <strong>&raquo;</strong> '.$timeend;
1425 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1426 $time = get_string('allday', 'calendar');
1429 // Set printable representation
1430 if (!$showtime) {
1431 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1432 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1433 $eventtime = html_writer::link($url, $day).', '.$time;
1434 } else {
1435 $eventtime = $time;
1437 } else {
1438 // It spans two or more days
1439 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1440 if ($showtime == $usermidnightstart) {
1441 $daystart = '';
1443 $timestart = calendar_time_representation($event->timestart);
1444 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1445 if ($showtime == $usermidnightend) {
1446 $dayend = '';
1448 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1450 // Set printable representation
1451 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
1452 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1453 $eventtime = $timestart.' <strong>&raquo;</strong> '.html_writer::link($url, $dayend).$timeend;
1454 } else {
1455 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1456 $eventtime = html_writer::link($url, $daystart).$timestart.' <strong>&raquo;</strong> ';
1458 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1459 $eventtime .= html_writer::link($url, $dayend).$timeend;
1462 } else {
1463 $time = calendar_time_representation($event->timestart);
1465 // Set printable representation
1466 if (!$showtime) {
1467 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1468 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1469 $eventtime = html_writer::link($url, $day).', '.trim($time);
1470 } else {
1471 $eventtime = $time;
1475 if($event->timestart + $event->timeduration < $now) {
1476 // It has expired
1477 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1480 return $eventtime;
1483 function calendar_print_month_selector($name, $selected) {
1484 $months = array();
1485 for ($i=1; $i<=12; $i++) {
1486 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1488 echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
1489 echo html_writer::select($months, $name, $selected, false);
1493 * Checks to see if the requested type of event should be shown for the given user.
1495 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1496 * The type to check the display for (default is to display all)
1497 * @param stdClass|int|null $user The user to check for - by default the current user
1498 * @return bool True if the tyep should be displayed false otherwise
1500 function calendar_show_event_type($type, $user = null) {
1501 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1502 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1503 global $SESSION;
1504 if (!isset($SESSION->calendarshoweventtype)) {
1505 $SESSION->calendarshoweventtype = $default;
1507 return $SESSION->calendarshoweventtype & $type;
1508 } else {
1509 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1514 * Sets the display of the event type given $display.
1515 * If $display = true the event type will be shown.
1516 * If $display = false the event type will NOT be shown.
1517 * If $display = null the current value will be toggled and saved.
1519 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1520 * @param true|false|null $display
1521 * @param stdClass|int|null $user
1523 function calendar_set_event_type_display($type, $display = null, $user = null) {
1524 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1525 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1526 if ($persist === 0) {
1527 global $SESSION;
1528 if (!isset($SESSION->calendarshoweventtype)) {
1529 $SESSION->calendarshoweventtype = $default;
1531 $preference = $SESSION->calendarshoweventtype;
1532 } else {
1533 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1535 $current = $preference & $type;
1536 if ($display === null) {
1537 $display = !$current;
1539 if ($display && !$current) {
1540 $preference += $type;
1541 } else if (!$display && $current) {
1542 $preference -= $type;
1544 if ($persist === 0) {
1545 $SESSION->calendarshoweventtype = $preference;
1546 } else {
1547 if ($preference == $default) {
1548 unset_user_preference('calendar_savedflt', $user);
1549 } else {
1550 set_user_preference('calendar_savedflt', $preference, $user);
1555 function calendar_get_allowed_types(&$allowed, $course = null) {
1556 global $USER, $CFG, $DB;
1557 $allowed = new stdClass();
1558 $allowed->user = has_capability('moodle/calendar:manageownentries', get_system_context());
1559 $allowed->groups = false; // This may change just below
1560 $allowed->courses = false; // This may change just below
1561 $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1563 if (!empty($course)) {
1564 if (!is_object($course)) {
1565 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
1567 if ($course->id != SITEID) {
1568 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1569 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
1571 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1572 $allowed->courses = array($course->id => 1);
1574 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1575 $allowed->groups = groups_get_all_groups($course->id);
1577 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1578 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1579 $allowed->groups = groups_get_all_groups($course->id);
1587 * see if user can add calendar entries at all
1588 * used to print the "New Event" button
1589 * @return bool
1591 function calendar_user_can_add_event($course) {
1592 if (!isloggedin() || isguestuser()) {
1593 return false;
1595 calendar_get_allowed_types($allowed, $course);
1596 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1600 * Check wether the current user is permitted to add events
1602 * @param object $event
1603 * @return bool
1605 function calendar_add_event_allowed($event) {
1606 global $USER, $DB;
1608 // can not be using guest account
1609 if (!isloggedin() or isguestuser()) {
1610 return false;
1613 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1614 // if user has manageentries at site level, always return true
1615 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1616 return true;
1619 switch ($event->eventtype) {
1620 case 'course':
1621 return has_capability('moodle/calendar:manageentries', $event->context);
1623 case 'group':
1624 // Allow users to add/edit group events if:
1625 // 1) They have manageentries (= entries for whole course)
1626 // 2) They have managegroupentries AND are in the group
1627 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1628 return $group && (
1629 has_capability('moodle/calendar:manageentries', $event->context) ||
1630 (has_capability('moodle/calendar:managegroupentries', $event->context)
1631 && groups_is_member($event->groupid)));
1633 case 'user':
1634 if ($event->userid == $USER->id) {
1635 return (has_capability('moodle/calendar:manageownentries', $event->context));
1637 //there is no 'break;' intentionally
1639 case 'site':
1640 return has_capability('moodle/calendar:manageentries', $event->context);
1642 default:
1643 return has_capability('moodle/calendar:manageentries', $event->context);
1648 * A class to manage calendar events
1650 * This class provides the required functionality in order to manage calendar events.
1651 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1652 * better framework for dealing with calendar events in particular regard to file
1653 * handling through the new file API
1655 * @property int $id The id within the event table
1656 * @property string $name The name of the event
1657 * @property string $description The description of the event
1658 * @property int $format The format of the description FORMAT_?
1659 * @property int $courseid The course the event is associated with (0 if none)
1660 * @property int $groupid The group the event is associated with (0 if none)
1661 * @property int $userid The user the event is associated with (0 if none)
1662 * @property int $repeatid If this is a repeated event this will be set to the
1663 * id of the original
1664 * @property string $modulename If added by a module this will be the module name
1665 * @property int $instance If added by a module this will be the module instance
1666 * @property string $eventtype The event type
1667 * @property int $timestart The start time as a timestamp
1668 * @property int $timeduration The duration of the event in seconds
1669 * @property int $visible 1 if the event is visible
1670 * @property int $uuid ?
1671 * @property int $sequence ?
1672 * @property int $timemodified The time last modified as a timestamp
1674 class calendar_event {
1677 * An object containing the event properties can be accessed via the
1678 * magic __get/set methods
1679 * @var array
1681 protected $properties = null;
1683 * The converted event discription with file paths resolved
1684 * This gets populated when someone requests description for the first time
1685 * @var string
1687 protected $_description = null;
1689 * The options to use with this description editor
1690 * @var array
1692 protected $editoroptions = array(
1693 'subdirs'=>false,
1694 'forcehttps'=>false,
1695 'maxfiles'=>-1,
1696 'maxbytes'=>null,
1697 'trusttext'=>false);
1699 * The context to use with the description editor
1700 * @var object
1702 protected $editorcontext = null;
1705 * Instantiates a new event and optionally populates its properties with the
1706 * data provided
1708 * @param stdClass $data Optional. An object containing the properties to for
1709 * an event
1711 public function __construct($data=null) {
1712 global $CFG, $USER;
1714 // First convert to object if it is not already (should either be object or assoc array)
1715 if (!is_object($data)) {
1716 $data = (object)$data;
1719 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1721 $data->eventrepeats = 0;
1723 if (empty($data->id)) {
1724 $data->id = null;
1727 // Default to a user event
1728 if (empty($data->eventtype)) {
1729 $data->eventtype = 'user';
1732 // Default to the current user
1733 if (empty($data->userid)) {
1734 $data->userid = $USER->id;
1737 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1738 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1740 if (!empty($data->description) && is_array($data->description)) {
1741 $data->format = $data->description['format'];
1742 $data->description = $data->description['text'];
1743 } else if (empty($data->description)) {
1744 $data->description = '';
1745 $data->format = editors_get_preferred_format();
1747 // Ensure form is defaulted correctly
1748 if (empty($data->format)) {
1749 $data->format = editors_get_preferred_format();
1752 if (empty($data->context)) {
1753 $data->context = $this->calculate_context($data);
1755 $this->properties = $data;
1759 * Magic property method
1761 * Attempts to call a set_$key method if one exists otherwise falls back
1762 * to simply set the property
1764 * @param string $key
1765 * @param mixed $value
1767 public function __set($key, $value) {
1768 if (method_exists($this, 'set_'.$key)) {
1769 $this->{'set_'.$key}($value);
1771 $this->properties->{$key} = $value;
1775 * Magic get method
1777 * Attempts to call a get_$key method to return the property and ralls over
1778 * to return the raw property
1780 * @param str $key
1781 * @return mixed
1783 public function __get($key) {
1784 if (method_exists($this, 'get_'.$key)) {
1785 return $this->{'get_'.$key}();
1787 if (!isset($this->properties->{$key})) {
1788 throw new coding_exception('Undefined property requested');
1790 return $this->properties->{$key};
1794 * Stupid PHP needs an isset magic method if you use the get magic method and
1795 * still want empty calls to work.... blah ~!
1797 * @param string $key
1798 * @return bool
1800 public function __isset($key) {
1801 return !empty($this->properties->{$key});
1805 * Calculate the context value needed for calendar_event.
1806 * Event's type can be determine by the available value store in $data
1807 * It is important to check for the existence of course/courseid to determine
1808 * the course event.
1809 * Default value is set to CONTEXT_USER
1811 * @return stdClass
1813 protected function calculate_context(stdClass $data) {
1814 global $USER, $DB;
1816 $context = null;
1817 if (isset($data->courseid) && $data->courseid > 0) {
1818 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
1819 } else if (isset($data->course) && $data->course > 0) {
1820 $context = get_context_instance(CONTEXT_COURSE, $data->course);
1821 } else if (isset($data->groupid) && $data->groupid > 0) {
1822 $group = $DB->get_record('groups', array('id'=>$data->groupid));
1823 $context = get_context_instance(CONTEXT_COURSE, $group->courseid);
1824 } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
1825 $context = get_context_instance(CONTEXT_USER, $data->userid);
1826 } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
1827 isset($data->instance) && $data->instance > 0) {
1828 $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
1829 $context = get_context_instance(CONTEXT_COURSE, $cm->course);
1830 } else {
1831 $context = get_context_instance(CONTEXT_USER);
1834 return $context;
1838 * Returns an array of editoroptions for this event: Called by __get
1839 * Please use $blah = $event->editoroptions;
1840 * @return array
1842 protected function get_editoroptions() {
1843 return $this->editoroptions;
1847 * Returns an event description: Called by __get
1848 * Please use $blah = $event->description;
1850 * @return string
1852 protected function get_description() {
1853 global $CFG;
1855 require_once($CFG->libdir . '/filelib.php');
1857 if ($this->_description === null) {
1858 // Check if we have already resolved the context for this event
1859 if ($this->editorcontext === null) {
1860 // Switch on the event type to decide upon the appropriate context
1861 // to use for this event
1862 $this->editorcontext = $this->properties->context;
1863 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
1864 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
1865 return clean_text($this->properties->description, $this->properties->format);
1869 // Work out the item id for the editor, if this is a repeated event then the files will
1870 // be associated with the original
1871 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
1872 $itemid = $this->properties->repeatid;
1873 } else {
1874 $itemid = $this->properties->id;
1877 // Convert file paths in the description so that things display correctly
1878 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
1879 // Clean the text so no nasties get through
1880 $this->_description = clean_text($this->_description, $this->properties->format);
1882 // Finally return the description
1883 return $this->_description;
1887 * Return the number of repeat events there are in this events series
1889 * @return int
1891 public function count_repeats() {
1892 global $DB;
1893 if (!empty($this->properties->repeatid)) {
1894 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
1895 // We don't want to count ourselves
1896 $this->properties->eventrepeats--;
1898 return $this->properties->eventrepeats;
1902 * Update or create an event within the database
1904 * Pass in a object containing the event properties and this function will
1905 * insert it into the database and deal with any associated files
1907 * @see add_event()
1908 * @see update_event()
1910 * @param stdClass $data
1911 * @param boolean $checkcapability if moodle should check calendar managing capability or not
1913 public function update($data, $checkcapability=true) {
1914 global $CFG, $DB, $USER;
1916 foreach ($data as $key=>$value) {
1917 $this->properties->$key = $value;
1920 $this->properties->timemodified = time();
1921 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
1923 if (empty($this->properties->id) || $this->properties->id < 1) {
1925 if ($checkcapability) {
1926 if (!calendar_add_event_allowed($this->properties)) {
1927 print_error('nopermissiontoupdatecalendar');
1931 if ($usingeditor) {
1932 switch ($this->properties->eventtype) {
1933 case 'user':
1934 $this->properties->courseid = 0;
1935 $this->properties->course = 0;
1936 $this->properties->groupid = 0;
1937 $this->properties->userid = $USER->id;
1938 break;
1939 case 'site':
1940 $this->properties->courseid = SITEID;
1941 $this->properties->course = SITEID;
1942 $this->properties->groupid = 0;
1943 $this->properties->userid = $USER->id;
1944 break;
1945 case 'course':
1946 $this->properties->groupid = 0;
1947 $this->properties->userid = $USER->id;
1948 break;
1949 case 'group':
1950 $this->properties->userid = $USER->id;
1951 break;
1952 default:
1953 // Ewww we should NEVER get here, but just incase we do lets
1954 // fail gracefully
1955 $usingeditor = false;
1956 break;
1959 // If we are actually using the editor, we recalculate the context because some default values
1960 // were set when calculate_context() was called from the constructor.
1961 if ($usingeditor) {
1962 $this->properties->context = $this->calculate_context($this->properties);
1963 $this->editorcontext = $this->properties->context;
1966 $editor = $this->properties->description;
1967 $this->properties->format = $this->properties->description['format'];
1968 $this->properties->description = $this->properties->description['text'];
1971 // Insert the event into the database
1972 $this->properties->id = $DB->insert_record('event', $this->properties);
1974 if ($usingeditor) {
1975 $this->properties->description = file_save_draft_area_files(
1976 $editor['itemid'],
1977 $this->editorcontext->id,
1978 'calendar',
1979 'event_description',
1980 $this->properties->id,
1981 $this->editoroptions,
1982 $editor['text'],
1983 $this->editoroptions['forcehttps']);
1984 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
1987 // Log the event entry.
1988 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
1990 $repeatedids = array();
1992 if (!empty($this->properties->repeat)) {
1993 $this->properties->repeatid = $this->properties->id;
1994 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
1996 $eventcopy = clone($this->properties);
1997 unset($eventcopy->id);
1999 for($i = 1; $i < $eventcopy->repeats; $i++) {
2001 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
2003 // Get the event id for the log record.
2004 $eventcopyid = $DB->insert_record('event', $eventcopy);
2006 // If the context has been set delete all associated files
2007 if ($usingeditor) {
2008 $fs = get_file_storage();
2009 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2010 foreach ($files as $file) {
2011 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2015 $repeatedids[] = $eventcopyid;
2016 // Log the event entry.
2017 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
2021 // Hook for tracking added events
2022 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2023 return true;
2024 } else {
2026 if ($checkcapability) {
2027 if(!calendar_edit_event_allowed($this->properties)) {
2028 print_error('nopermissiontoupdatecalendar');
2032 if ($usingeditor) {
2033 if ($this->editorcontext !== null) {
2034 $this->properties->description = file_save_draft_area_files(
2035 $this->properties->description['itemid'],
2036 $this->editorcontext->id,
2037 'calendar',
2038 'event_description',
2039 $this->properties->id,
2040 $this->editoroptions,
2041 $this->properties->description['text'],
2042 $this->editoroptions['forcehttps']);
2043 } else {
2044 $this->properties->format = $this->properties->description['format'];
2045 $this->properties->description = $this->properties->description['text'];
2049 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2051 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2053 if ($updaterepeated) {
2054 // Update all
2055 if ($this->properties->timestart != $event->timestart) {
2056 $timestartoffset = $this->properties->timestart - $event->timestart;
2057 $sql = "UPDATE {event}
2058 SET name = ?,
2059 description = ?,
2060 timestart = timestart + ?,
2061 timeduration = ?,
2062 timemodified = ?
2063 WHERE repeatid = ?";
2064 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2065 } else {
2066 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2067 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2069 $DB->execute($sql, $params);
2071 // Log the event update.
2072 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2073 } else {
2074 $DB->update_record('event', $this->properties);
2075 $event = calendar_event::load($this->properties->id);
2076 $this->properties = $event->properties();
2077 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2080 // Hook for tracking event updates
2081 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2082 return true;
2087 * Deletes an event and if selected an repeated events in the same series
2089 * This function deletes an event, any associated events if $deleterepeated=true,
2090 * and cleans up any files associated with the events.
2092 * @see delete_event()
2094 * @param bool $deleterepeated
2095 * @return bool
2097 public function delete($deleterepeated=false) {
2098 global $DB;
2100 // If $this->properties->id is not set then something is wrong
2101 if (empty($this->properties->id)) {
2102 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2103 return false;
2106 // Delete the event
2107 $DB->delete_records('event', array('id'=>$this->properties->id));
2109 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2110 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
2111 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties->id), IGNORE_MULTIPLE);
2112 if (!empty($newparent)) {
2113 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties->id));
2114 // Get all records where the repeatid is the same as the event being removed
2115 $events = $DB->get_records('event', array('repeatid' => $newparent));
2116 // For each of the returned events trigger the event_update hook.
2117 foreach ($events as $event) {
2118 self::calendar_event_hook('update_event', array($event, false));
2123 // If the editor context hasn't already been set then set it now
2124 if ($this->editorcontext === null) {
2125 $this->editorcontext = $this->properties->context;
2128 // If the context has been set delete all associated files
2129 if ($this->editorcontext !== null) {
2130 $fs = get_file_storage();
2131 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2132 foreach ($files as $file) {
2133 $file->delete();
2137 // Fire the event deleted hook
2138 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2140 // If we need to delete repeated events then we will fetch them all and delete one by one
2141 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2142 // Get all records where the repeatid is the same as the event being removed
2143 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2144 // For each of the returned events populate a calendar_event object and call delete
2145 // make sure the arg passed is false as we are already deleting all repeats
2146 foreach ($events as $event) {
2147 $event = new calendar_event($event);
2148 $event->delete(false);
2152 return true;
2156 * Fetch all event properties
2158 * This function returns all of the events properties as an object and optionally
2159 * can prepare an editor for the description field at the same time. This is
2160 * designed to work when the properties are going to be used to set the default
2161 * values of a moodle forms form.
2163 * @param bool $prepareeditor If set to true a editor is prepared for use with
2164 * the mforms editor element. (for description)
2165 * @return stdClass Object containing event properties
2167 public function properties($prepareeditor=false) {
2168 global $USER, $CFG, $DB;
2170 // First take a copy of the properties. We don't want to actually change the
2171 // properties or we'd forever be converting back and forwards between an
2172 // editor formatted description and not
2173 $properties = clone($this->properties);
2174 // Clean the description here
2175 $properties->description = clean_text($properties->description, $properties->format);
2177 // If set to true we need to prepare the properties for use with an editor
2178 // and prepare the file area
2179 if ($prepareeditor) {
2181 // We may or may not have a property id. If we do then we need to work
2182 // out the context so we can copy the existing files to the draft area
2183 if (!empty($properties->id)) {
2185 if ($properties->eventtype === 'site') {
2186 // Site context
2187 $this->editorcontext = $this->properties->context;
2188 } else if ($properties->eventtype === 'user') {
2189 // User context
2190 $this->editorcontext = $this->properties->context;
2191 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2192 // First check the course is valid
2193 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2194 if (!$course) {
2195 print_error('invalidcourse');
2197 // Course context
2198 $this->editorcontext = $this->properties->context;
2199 // We have a course and are within the course context so we had
2200 // better use the courses max bytes value
2201 $this->editoroptions['maxbytes'] = $course->maxbytes;
2202 } else {
2203 // If we get here we have a custom event type as used by some
2204 // modules. In this case the event will have been added by
2205 // code and we won't need the editor
2206 $this->editoroptions['maxbytes'] = 0;
2207 $this->editoroptions['maxfiles'] = 0;
2210 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2211 $contextid = false;
2212 } else {
2213 // Get the context id that is what we really want
2214 $contextid = $this->editorcontext->id;
2216 } else {
2218 // If we get here then this is a new event in which case we don't need a
2219 // context as there is no existing files to copy to the draft area.
2220 $contextid = null;
2223 // If the contextid === false we don't support files so no preparing
2224 // a draft area
2225 if ($contextid !== false) {
2226 // Just encase it has already been submitted
2227 $draftiddescription = file_get_submitted_draft_itemid('description');
2228 // Prepare the draft area, this copies existing files to the draft area as well
2229 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
2230 } else {
2231 $draftiddescription = 0;
2234 // Structure the description field as the editor requires
2235 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2238 // Finally return the properties
2239 return $properties;
2243 * Toggles the visibility of an event
2245 * @param null|bool $force If it is left null the events visibility is flipped,
2246 * If it is false the event is made hidden, if it is true it
2247 * is made visible.
2249 public function toggle_visibility($force=null) {
2250 global $CFG, $DB;
2252 // Set visible to the default if it is not already set
2253 if (empty($this->properties->visible)) {
2254 $this->properties->visible = 1;
2257 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2258 // Make this event visible
2259 $this->properties->visible = 1;
2260 // Fire the hook
2261 self::calendar_event_hook('show_event', array($this->properties));
2262 } else {
2263 // Make this event hidden
2264 $this->properties->visible = 0;
2265 // Fire the hook
2266 self::calendar_event_hook('hide_event', array($this->properties));
2269 // Update the database to reflect this change
2270 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2274 * Attempts to call the hook for the specified action should a calendar type
2275 * by set $CFG->calendar, and the appopriate function defined
2277 * @static
2278 * @staticvar bool $extcalendarinc Used to track the inclusion of the calendar lib
2279 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2280 * @param array $args The args to pass to the hook, usually the event is the first element
2281 * @return bool
2283 public static function calendar_event_hook($action, array $args) {
2284 global $CFG;
2285 static $extcalendarinc;
2286 if ($extcalendarinc === null) {
2287 if (!empty($CFG->calendar) && file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2288 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2289 $extcalendarinc = true;
2290 } else {
2291 $extcalendarinc = false;
2294 if($extcalendarinc === false) {
2295 return false;
2297 $hook = $CFG->calendar .'_'.$action;
2298 if (function_exists($hook)) {
2299 call_user_func_array($hook, $args);
2300 return true;
2302 return false;
2306 * Returns a calendar_event object when provided with an event id
2308 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2309 * it will result in an exception being thrown
2311 * @param int|object $param
2312 * @return calendar_event|false
2314 public static function load($param) {
2315 global $DB;
2316 if (is_object($param)) {
2317 $event = new calendar_event($param);
2318 } else {
2319 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2320 $event = new calendar_event($event);
2322 return $event;
2326 * Creates a new event and returns a calendar_event object
2328 * @param object|array $properties An object containing event properties
2329 * @return calendar_event|false The event object or false if it failed
2331 public static function create($properties) {
2332 if (is_array($properties)) {
2333 $properties = (object)$properties;
2335 if (!is_object($properties)) {
2336 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2338 $event = new calendar_event($properties);
2339 if ($event->update($properties)) {
2340 return $event;
2341 } else {
2342 return false;
2348 * Calendar information class
2350 * This class is used simply to organise the information pertaining to a calendar
2351 * and is used primarily to make information easily available.
2353 class calendar_information {
2355 * The day
2356 * @var int
2358 public $day;
2360 * The month
2361 * @var int
2363 public $month;
2365 * The year
2366 * @var int
2368 public $year;
2371 * A course id
2372 * @var int
2374 public $courseid = null;
2376 * An array of courses
2377 * @var array
2379 public $courses = array();
2381 * An array of groups
2382 * @var array
2384 public $groups = array();
2386 * An array of users
2387 * @var array
2389 public $users = array();
2392 * Creates a new instance
2394 * @param int $day
2395 * @param int $month
2396 * @param int $year
2398 public function __construct($day=0, $month=0, $year=0) {
2400 $date = usergetdate(time());
2402 if (empty($day)) {
2403 $day = $date['mday'];
2406 if (empty($month)) {
2407 $month = $date['mon'];
2410 if (empty($year)) {
2411 $year = $date['year'];
2414 $this->day = $day;
2415 $this->month = $month;
2416 $this->year = $year;
2421 * @param stdClass $course
2422 * @param array $coursestoload An array of courses [$course->id => $course]
2423 * @param type $ignorefilters
2425 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
2426 $this->courseid = $course->id;
2427 $this->course = $course;
2428 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2429 $this->courses = $courses;
2430 $this->groups = $group;
2431 $this->users = $user;
2435 * Ensures the date for the calendar is correct and either sets it to now
2436 * or throws a moodle_exception if not
2438 * @param bool $defaultonow
2439 * @return bool
2441 public function checkdate($defaultonow = true) {
2442 if (!checkdate($this->month, $this->day, $this->year)) {
2443 if ($defaultonow) {
2444 $now = usergetdate(time());
2445 $this->day = intval($now['mday']);
2446 $this->month = intval($now['mon']);
2447 $this->year = intval($now['year']);
2448 return true;
2449 } else {
2450 throw new moodle_exception('invaliddate');
2453 return true;
2456 * Gets todays timestamp for the calendar
2457 * @return int
2459 public function timestamp_today() {
2460 return make_timestamp($this->year, $this->month, $this->day);
2463 * Gets tomorrows timestamp for the calendar
2464 * @return int
2466 public function timestamp_tomorrow() {
2467 return make_timestamp($this->year, $this->month, $this->day+1);
2470 * Adds the pretend blocks for teh calendar
2472 * @param core_calendar_renderer $renderer
2473 * @param bool $showfilters
2474 * @param string|null $view
2476 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2477 if ($showfilters) {
2478 $filters = new block_contents();
2479 $filters->content = $renderer->fake_block_filters($this->courseid, $this->day, $this->month, $this->year, $view, $this->courses);
2480 $filters->footer = '';
2481 $filters->title = get_string('eventskey', 'calendar');
2482 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2484 $block = new block_contents;
2485 $block->content = $renderer->fake_block_threemonths($this);
2486 $block->footer = '';
2487 $block->title = get_string('monthlyview', 'calendar');
2488 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);